From 5ba8a5748e074235b2c66a311ba546ae4e34ef86 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:40:16 -0800 Subject: [PATCH 01/22] test(testkit): add provider refresh commands to the test context Signed-off-by: Matthew Grossman --- tests/testkit/README.md | 3 +- tests/testkit/testkit/src/lib.rs | 2 + tests/testkit/testkit/src/provider_refresh.rs | 87 +++++++++++++++++++ 3 files changed, 91 insertions(+), 1 deletion(-) create mode 100644 tests/testkit/testkit/src/provider_refresh.rs diff --git a/tests/testkit/README.md b/tests/testkit/README.md index def3f82421..b276465428 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -139,7 +139,8 @@ fails. A killed test process skips cleanup, so names are unique to the run. to set provider config. Build the profile with `testkit::Profile` and `testkit::Credential`, whose setters are named after the profile YAML fields; `policy::Endpoint` configures its endpoints. `profile.to_yaml()` - renders it for these calls. + renders it for these calls. `cx.provider_refresh(provider, key)` runs + `provider refresh configure`, `rotate` and `status` for one credential. - `testkit::YamlFile` for YAML a CLI command reads from a file. - `cx.client()` for SDK calls testkit does not wrap. - In `tests/support`: `host-server` starts servers on the machine that runs diff --git a/tests/testkit/testkit/src/lib.rs b/tests/testkit/testkit/src/lib.rs index d7e39746a6..d081d82bce 100644 --- a/tests/testkit/testkit/src/lib.rs +++ b/tests/testkit/testkit/src/lib.rs @@ -41,6 +41,7 @@ mod poll; pub mod profile; pub mod program; mod provider; +mod provider_refresh; mod ready; mod registry; mod run; @@ -63,6 +64,7 @@ pub use poll::{Poll, poll_until, with_deadline}; pub use profile::{Credential, Profile}; pub use program::main; pub use provider::ProviderBuilder; +pub use provider_refresh::ProviderRefresh; pub use ready::check as check_ready; pub use registry::Test; pub use run::{TestInfo, run}; diff --git a/tests/testkit/testkit/src/provider_refresh.rs b/tests/testkit/testkit/src/provider_refresh.rs new file mode 100644 index 0000000000..ec40308994 --- /dev/null +++ b/tests/testkit/testkit/src/provider_refresh.rs @@ -0,0 +1,87 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use crate::cli::{Cli, CliOutput}; +use crate::context::Context; +use crate::error::Result; + +impl Context { + /// The `provider refresh` commands for the credential `key` of + /// `provider`. + pub fn provider_refresh(&self, provider: &str, key: &str) -> ProviderRefresh { + ProviderRefresh { + cli: self.cli_handle(), + provider: provider.to_string(), + key: key.to_string(), + } + } +} + +/// The `provider refresh` commands for one provider credential, from +/// [`Context::provider_refresh`]. Each returns the CLI output whatever the +/// exit code; check it with [`CliOutput::success`] or +/// [`CliOutput::failure`]. +#[derive(Clone, Debug)] +pub struct ProviderRefresh { + cli: Cli, + provider: String, + key: String, +} + +impl ProviderRefresh { + /// `provider refresh configure` with `strategy`, such as + /// `oauth2-client-credentials`, the plain `material` pairs and the + /// `secret_material` pairs. The CLI reads each secret from its + /// environment, so the values aren't in the reported command. + pub async fn configure( + &self, + strategy: &str, + material: &[(&str, &str)], + secret_material: &[(&str, &str)], + ) -> Result { + let mut args = self.args("configure"); + args.extend(["--strategy".to_string(), strategy.to_string()]); + for (name, value) in material { + args.extend(["--material".to_string(), format!("{name}={value}")]); + } + let env_vars: Vec = secret_material + .iter() + .map(|(name, _)| format!("TESTKIT_REFRESH_{}", name.to_ascii_uppercase())) + .collect(); + for ((name, _), env_var) in secret_material.iter().zip(&env_vars) { + args.extend([ + "--secret-material-env".to_string(), + format!("{name}={env_var}"), + ]); + } + let env: Vec<(&str, &str)> = env_vars + .iter() + .zip(secret_material) + .map(|(env_var, (_, value))| (env_var.as_str(), *value)) + .collect(); + self.cli.run_with_env(None, &env, args).await + } + + /// `provider refresh rotate`, which refreshes the credential now. + pub async fn rotate(&self) -> Result { + self.cli.run(self.args("rotate")).await + } + + /// `provider refresh status`. + pub async fn status(&self) -> Result { + self.cli.run(self.args("status")).await + } + + fn args(&self, verb: &str) -> Vec { + [ + "provider", + "refresh", + verb, + &self.provider, + "--credential-key", + &self.key, + ] + .map(str::to_string) + .to_vec() + } +} From 5dbbfcadd8140f6d1557a8010459844fbba38c00 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:40:17 -0800 Subject: [PATCH 02/22] test(features): port the provider refresh handle test Signed-off-by: Matthew Grossman --- tests/suites/features/Cargo.lock | 9 + tests/suites/features/Cargo.toml | 2 +- .../features/provider-refresh/Cargo.toml | 17 ++ .../provider-refresh/tests/refresh_handles.rs | 259 ++++++++++++++++++ 4 files changed, 286 insertions(+), 1 deletion(-) create mode 100644 tests/suites/features/provider-refresh/Cargo.toml create mode 100644 tests/suites/features/provider-refresh/tests/refresh_handles.rs diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index 04592b09f0..1200c171f5 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -2869,6 +2869,15 @@ version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" +[[package]] +name = "provider-refresh" +version = "0.0.0" +dependencies = [ + "host-server-support", + "openshell-testkit", + "serde_json", +] + [[package]] name = "pulldown-cmark" version = "0.13.6" diff --git a/tests/suites/features/Cargo.toml b/tests/suites/features/Cargo.toml index 7c7fe40ae7..07f5f08a45 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", "oci-image", "provider-refresh", "routable-host-ip"] diff --git a/tests/suites/features/provider-refresh/Cargo.toml b/tests/suites/features/provider-refresh/Cargo.toml new file mode 100644 index 0000000000..c6b2b394be --- /dev/null +++ b/tests/suites/features/provider-refresh/Cargo.toml @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "provider-refresh" +description = "Features suite: provider credential refresh against a token issuer the gateway reaches on the test host" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/NVIDIA/OpenShell" +publish = false + +[dependencies] +host-server-support = { path = "../../../support/host-server" } +openshell-testkit = { path = "../../../testkit/testkit" } +serde_json = "1" diff --git a/tests/suites/features/provider-refresh/tests/refresh_handles.rs b/tests/suites/features/provider-refresh/tests/refresh_handles.rs new file mode 100644 index 0000000000..1c5ecea062 --- /dev/null +++ b/tests/suites/features/provider-refresh/tests/refresh_handles.rs @@ -0,0 +1,259 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Refresh-managed workload credential handles. +//! +//! The test serves a token issuer and a resource from one host server. The +//! gateway calls the issuer on `127.0.0.1`, so the gateway must run on the +//! machine that runs the tests; the sandbox reaches the resource through +//! `host.openshell.internal`. + +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use host_server_support::{HttpRecorder, Request, Response, TEST_HOST}; +use serde_json::json; +use testkit::{Context, PYTHON_BINARIES, Poll, Result, Sandbox, policy, poll_until}; + +const TOKEN_ENV: &str = "REFRESH_E2E_ACCESS_TOKEN"; +const BOOTSTRAP_TOKEN: &str = "bootstrap-token"; +const ROTATIONS: usize = 12; +const PROBE_TIMEOUT: Duration = Duration::from_secs(45); + +/// The main process keeps the environment it started with. It checks that +/// its credential is a stable handle, then runs the probe in [`probe`] +/// whenever `/sandbox/probe-trigger` appears and writes `ok` or `failed` +/// to `/sandbox/probe-result`. +fn main_process(resource_url: &str) -> String { + format!( + r#"case "${TOKEN_ENV}" in + openshell:resolve:env:s*_{TOKEN_ENV}) ;; + *) exit 64 ;; +esac +while true; do + if [ -f /sandbox/probe-trigger ]; then + rm -f /sandbox/probe-trigger + if {probe}; then + echo ok > /sandbox/probe-result + else + echo failed > /sandbox/probe-result + fi + fi + sleep 0.1 +done"#, + probe = probe(resource_url) + ) +} + +/// A shell command that requests `resource_url` with the credential from the +/// environment as a bearer token, and fails unless the resource accepts it. +fn probe(resource_url: &str) -> String { + format!( + r#"python3 -c 'import os, urllib.request; urllib.request.urlopen(urllib.request.Request("{resource_url}", headers={{"Authorization": "Bearer " + os.environ["{TOKEN_ENV}"]}}), timeout=5).read()'"# + ) +} + +/// One long-running process keeps its original environment while the +/// gateway rotates the credential 12 times, each rotation invalidating the +/// last token. The process still reaches the resource with the newest token. +/// Reconfiguring the refresh revokes the process's handle, and a new process +/// gets a working one. +#[testkit::test] +async fn long_running_process_survives_rotations_and_reconfigure_revokes( + cx: &mut Context, +) -> testkit::Result { + let issuer = Issuer::start().await?; + let provider = cx.name("refresh"); + let profile = profile(&provider, issuer.port()); + let provider_type = cx.import_profile(&profile).await?; + cx.create_provider(&provider, &provider_type, &[(TOKEN_ENV, BOOTSTRAP_TOKEN)]) + .await?; + let refresh = cx.provider_refresh(&provider, TOKEN_ENV); + let configure = async || { + refresh + .configure( + "oauth2-client-credentials", + &[("client_id", "e2e-client")], + &[("client_secret", "e2e-client-secret")], + ) + .await? + .success() + }; + configure().await?; + + let resource_url = format!("http://{TEST_HOST}:{}/probe", issuer.port()); + let sandbox = cx + .sandbox("rfh") + .image(testkit::python_image()) + .providers([provider.as_str()]) + .policy(probe_policy(issuer.port())?) + .command(["sh", "-c", &main_process(&resource_url)]) + .create_ready() + .await?; + + let first = trigger_probe(&sandbox).await?; + testkit::ensure!( + first == "ok", + "the first probe from the long-running process returned {first:?}; issuer saw {}", + issuer.summary() + ); + + for _ in 0..ROTATIONS { + refresh.rotate().await?.success()?; + } + wait_for_probe( + &sandbox, + "ok", + "the long-running process to use the latest rotated token", + ) + .await + .map_err(|error| error.context(format!("issuer saw {}", issuer.summary())))?; + + configure().await?; + wait_for_probe( + &sandbox, + "failed", + "reconfiguring the refresh to revoke the long-running process's handle", + ) + .await?; + + sandbox + .exec(["sh", "-c", &probe(&resource_url)]) + .await? + .success()?; + Ok(()) +} + +/// Ask the main process to run its probe, and return what it wrote. +async fn trigger_probe(sandbox: &Sandbox) -> Result { + let output = sandbox + .exec([ + "sh", + "-c", + "rm -f /sandbox/probe-result; touch /sandbox/probe-trigger; \ + for _ in $(seq 100); do \ + if [ -f /sandbox/probe-result ]; then cat /sandbox/probe-result; exit 0; fi; \ + sleep 0.1; \ + done; exit 1", + ]) + .await? + .success()?; + Ok(output.stdout.trim().to_string()) +} + +async fn wait_for_probe(sandbox: &Sandbox, expected: &str, what: &str) -> Result { + poll_until( + what, + PROBE_TIMEOUT, + Duration::from_millis(500), + async || { + let result = trigger_probe(sandbox).await?; + Ok(if result == expected { + Poll::Ready(()) + } else { + Poll::Pending(format!("the probe returned {result:?}")) + }) + }, + ) + .await +} + +/// An OAuth issuer and the resource it guards. Each `POST /token` issues a +/// new token and invalidates the last. `GET /probe` answers `204` to the +/// current token and `401` to anything else. +struct Issuer { + server: HttpRecorder, +} + +impl Issuer { + async fn start() -> Result { + let state = Arc::new(Mutex::new((0_u32, BOOTSTRAP_TOKEN.to_string()))); + let server = HttpRecorder::serve(move |request: &Request| { + let mut state = state.lock().unwrap_or_else(PoisonError::into_inner); + match (request.method(), request.path()) { + ("POST", "/token") => { + state.0 += 1; + state.1 = format!("access-token-{}", state.0); + Response::json(&json!({ + "access_token": state.1, + "expires_in": 300, + "token_type": "Bearer", + })) + } + ("GET", "/probe") + if request.header("authorization").as_deref() + == Some(&format!("Bearer {}", state.1)) => + { + Response::new(204) + } + _ => Response::new(401), + } + }) + .await?; + Ok(Self { server }) + } + + fn port(&self) -> u16 { + self.server.port + } + + /// The requests so far, without their headers, for a failure report. + fn summary(&self) -> String { + let requests: Vec = self + .server + .requests() + .iter() + .map(|request| format!("{} {}", request.method(), request.path())) + .collect(); + format!("{requests:?}") + } +} + +/// A profile whose credential refreshes with OAuth client credentials from +/// the issuer on `port`, and is bound to the resource on the same port. +fn profile(id: &str, port: u16) -> String { + let binaries = PYTHON_BINARIES + .iter() + .map(|binary| format!("\"{binary}\"")) + .collect::>() + .join(", "); + format!( + "id: {id} +display_name: Provider refresh handle test +category: other +credentials: + - name: access_token + env_vars: [{TOKEN_ENV}] + required: true + auth_style: bearer + header_name: authorization + refresh: + strategy: oauth2_client_credentials + token_url: http://127.0.0.1:{port}/token + refresh_before_seconds: 30 + max_lifetime_seconds: 300 + material: + - name: client_id + required: true + - name: client_secret + required: true + secret: true +endpoints: + - {{host: {TEST_HOST}, port: {port}, path: /probe, protocol: rest, access: full, enforcement: enforce}} +binaries: [{binaries}] +" + ) +} + +fn probe_policy(port: u16) -> Result { + policy::base_with(&format!( + "network_policies: + refresh_probe: + name: refresh_probe + endpoints: + - {{host: {TEST_HOST}, port: {port}, path: /probe, protocol: rest, access: full, enforcement: enforce}} + binaries: {binaries} +", + binaries = policy::binaries_yaml(PYTHON_BINARIES), + )) +} From 7b93cae03070014b2c07199efd27f11f0c671012 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:49:49 -0800 Subject: [PATCH 03/22] test(tmachine): add an OTLP feature environment that points the gateway at a test collector Signed-off-by: Matthew Grossman --- tests/tmachine/ansible/playbooks/otlp.yaml | 41 ++++++++++++++++++++++ tests/tmachine/config.nix | 6 ++++ 2 files changed, 47 insertions(+) create mode 100644 tests/tmachine/ansible/playbooks/otlp.yaml diff --git a/tests/tmachine/ansible/playbooks/otlp.yaml b/tests/tmachine/ansible/playbooks/otlp.yaml new file mode 100644 index 0000000000..6d4ba1d460 --- /dev/null +++ b/tests/tmachine/ansible/playbooks/otlp.yaml @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Point the gateway's OTLP export and agent trace relay at a collector the +# tests run, and publish where the tests listen. +# +# Nothing listens on the port until a test starts its collector. Supervisors +# connect lazily, so sandboxes created before then only fail their exports. +# Supervisors in Podman containers reach the test VM as +# host.containers.internal. The OTLP fixture (tests/support/otlp) reads the +# variables published below. +--- +- name: OTLP collector for tests + hosts: all + gather_facts: false + vars: + otlp_port: 4317 + otlp_endpoint: "http://host.containers.internal:{{ otlp_port }}" + tasks: + - name: Wait for SSH + ansible.builtin.wait_for_connection: + + - name: Export traces and relay agent traces to the test collector + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: otlp + gateway_overrides_content: | + [openshell.gateway.otlp] + endpoint = "{{ otlp_endpoint }}" + + [openshell.gateway.otlp.agent] + enabled = true + + - name: Publish OTLP test variables + ansible.builtin.include_tasks: test-env.yaml + vars: + test_env_name: otlp + test_env_vars: + OPENSHELL_TEST_OTLP_LISTEN: "0.0.0.0:{{ otlp_port }}" + OPENSHELL_TEST_OTLP_ENDPOINT: "{{ otlp_endpoint }}" diff --git a/tests/tmachine/config.nix b/tests/tmachine/config.nix index ed62c23eb6..dd51a3c6ca 100644 --- a/tests/tmachine/config.nix +++ b/tests/tmachine/config.nix @@ -114,6 +114,12 @@ let bases = dockerBases ++ podmanBases; setup.playbooks = [ "ansible/playbooks/cdi.yaml" ]; }; + # A test-run OTLP collector for the gateway and the agent trace relay, for + # the otlp-relay suite. Its endpoint names Podman's host alias. + otlp = { + bases = podmanBases; + setup.playbooks = [ "ansible/playbooks/otlp.yaml" ]; + }; }; featureEnvironments = pkgs.lib.concatMap ( feature: map (base: withSetup base feature features.${feature}.setup) features.${feature}.bases From 1c0a83ec6df5d0b87528fcb9066d198c13900861 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:49:50 -0800 Subject: [PATCH 04/22] test(support): add an OTLP collector fixture on the environment's address Signed-off-by: Matthew Grossman --- tests/support/Cargo.lock | 326 ++++++++++++++++++++++++++++++++++ tests/support/Cargo.toml | 2 +- tests/support/README.md | 2 + tests/support/otlp/Cargo.toml | 16 ++ tests/support/otlp/src/lib.rs | 131 ++++++++++++++ 5 files changed, 476 insertions(+), 1 deletion(-) create mode 100644 tests/support/otlp/Cargo.toml create mode 100644 tests/support/otlp/src/lib.rs diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 4de10e2dd6..58a78625ba 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -599,6 +599,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" @@ -948,6 +957,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" @@ -2019,6 +2038,15 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + [[package]] name = "matchit" version = "0.8.4" @@ -2041,6 +2069,16 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "metrics" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5312e9ba3771cfa961b585728215e3d972c950a3eed9252aa093d6301277e8" +dependencies = [ + "ahash", + "portable-atomic", +] + [[package]] name = "miette" version = "7.6.0" @@ -2090,6 +2128,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", + "simd-adler32", ] [[package]] @@ -2167,6 +2206,15 @@ dependencies = [ "smallvec", ] +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -2355,6 +2403,73 @@ dependencies = [ "tower", ] +[[package]] +name = "openshell-ocsf" +version = "0.0.0" +dependencies = [ + "chrono", + "serde", + "serde_json", + "serde_repr", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "openshell-otel" +version = "0.0.0" +dependencies = [ + "async-trait", + "bytes", + "futures", + "http", + "http-body-util", + "hyper-rustls", + "hyper-util", + "metrics", + "openshell-crypto", + "openshell-ocsf", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-otlp", + "opentelemetry_sdk", + "rustls", + "rustls-native-certs", + "serde_json", + "thiserror 2.0.20", + "tokio", + "tonic", + "tower-http 0.6.8", + "tracing", + "tracing-opentelemetry", + "tracing-subscriber", + "zeroize", +] + +[[package]] +name = "openshell-otel-test-support" +version = "0.0.0" +dependencies = [ + "bytes", + "http", + "http-body-util", + "hyper", + "hyper-util", + "openshell-crypto", + "openshell-otel", + "opentelemetry-proto", + "prost", + "rcgen", + "rustls", + "tokio", + "tokio-rustls", + "tokio-stream", + "tonic", + "tracing", + "tracing-subscriber", +] + [[package]] name = "openshell-policy" version = "0.0.0" @@ -2473,6 +2588,83 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "opentelemetry" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c1f1a6ac9c875a4941e4c7c085b61e8f4daa326de03b4701768c3491a6ad9ee" +dependencies = [ + "futures-core", + "futures-sink", + "js-sys", + "pin-project-lite", + "thiserror 2.0.20", + "tracing", +] + +[[package]] +name = "opentelemetry-http" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302249bd8ee804789faaa7b5b2cbf79bc61cb864714079c644e3828af5b7e811" +dependencies = [ + "async-trait", + "bytes", + "http", + "opentelemetry", +] + +[[package]] +name = "opentelemetry-otlp" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0756af24841e367128ef31c831999937b8b5c5197d47914590d8f4e2e88c2e1a" +dependencies = [ + "flate2", + "http", + "httpdate", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-proto", + "opentelemetry_sdk", + "prost", + "thiserror 2.0.20", + "tokio", + "tonic", + "tonic-types", +] + +[[package]] +name = "opentelemetry-proto" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d576f5dddc3299341bcd85a04be17b2564844c0c9563214f02d85f2524d1afae" +dependencies = [ + "opentelemetry", + "opentelemetry_sdk", + "prost", + "tonic", + "tonic-prost", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "372a912db2974d1990207006fd0e3aa0ef3fd4ad3be43c65cfaadf2206866061" +dependencies = [ + "futures-channel", + "futures-executor", + "futures-util", + "opentelemetry", + "percent-encoding", + "portable-atomic", + "rand 0.9.4", + "thiserror 2.0.20", + "tokio", + "tokio-stream", +] + [[package]] name = "ordered-float" version = "2.10.1" @@ -2482,6 +2674,14 @@ dependencies = [ "num-traits", ] +[[package]] +name = "otlp-support" +version = "0.0.0" +dependencies = [ + "openshell-otel-test-support", + "openshell-testkit", +] + [[package]] name = "owo-colors" version = "4.3.0" @@ -3397,6 +3597,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_repr" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -3453,6 +3664,15 @@ dependencies = [ "digest 0.11.2", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "1.3.0" @@ -3478,6 +3698,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" @@ -3886,6 +4112,15 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + [[package]] name = "time" version = "0.3.47" @@ -4032,6 +4267,7 @@ dependencies = [ "axum", "base64 0.22.1", "bytes", + "flate2", "h2", "http", "http-body", @@ -4138,6 +4374,8 @@ dependencies = [ "tower", "tower-layer", "tower-service", + "tracing", + "uuid", ] [[package]] @@ -4202,6 +4440,64 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-opentelemetry" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a904802a1b902f43638b677ff2a650847e3b4404101b6c586d648e8c1e3e8fe" +dependencies = [ + "js-sys", + "opentelemetry", + "tracing", + "tracing-core", + "tracing-log", + "tracing-subscriber", + "web-time", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", ] [[package]] @@ -4352,6 +4648,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "vcpkg" version = "0.2.15" @@ -4515,6 +4817,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-root-certs" version = "1.0.10" @@ -4892,6 +5204,20 @@ name = "zeroize" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] name = "zerotrie" diff --git a/tests/support/Cargo.toml b/tests/support/Cargo.toml index e3dae4234d..ecb651ad07 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", "otlp", "podman", "sandbox-clients"] diff --git a/tests/support/README.md b/tests/support/README.md index 7b7b0a775a..e7aea2ac85 100644 --- a/tests/support/README.md +++ b/tests/support/README.md @@ -25,6 +25,8 @@ never skips it. Add a row when you add a variable. The runner also sets | `OPENSHELL_TEST_KEYCLOAK_CLIENT_ID` | `-keycloak` | `keycloak-support` | A client in that realm that allows password grants. | | `OPENSHELL_TEST_KEYCLOAK_USERNAME` | `-keycloak` | `keycloak-support` | The realm user that tests sign in as. | | `OPENSHELL_TEST_KEYCLOAK_PASSWORD` | `-keycloak` | `keycloak-support` | That user's password. | +| `OPENSHELL_TEST_OTLP_LISTEN` | `-otlp` (`playbooks/otlp.yaml`) | `otlp-support` | The address the test's OTLP/gRPC collector listens on, such as `0.0.0.0:4317`. | +| `OPENSHELL_TEST_OTLP_ENDPOINT` | `-otlp` | `otlp-support` | The collector endpoint in the gateway's `[openshell.gateway.otlp]`, which also enables the agent trace relay. Tests check that sandboxes never see it. | | `OPENSHELL_TEST_ADDITIONAL_CA_CERT` | The additional-CA environment, which sets `openshell.supervisor.network.additional_ca_bundle` (added by #5729) | `host-server-support` (`TestCa::from_env`) | The path of the CA certificate, in PEM, that the supervisor trusts for sandbox egress. | | `OPENSHELL_TEST_ADDITIONAL_CA_KEY` | The additional-CA environment | `host-server-support` (`TestCa::from_env`) | The path of that CA's private key, in PEM, readable by the test user. Tests sign server certificates with it. | | `OPENSHELL_TEST_BASE_IMAGE` | Optional; you, for example to use a mirror | `testkit::base_image()` | The default sandbox image. Unset, it is `nvcr.io/nvidia/base/ubuntu:24.04`. | diff --git a/tests/support/otlp/Cargo.toml b/tests/support/otlp/Cargo.toml new file mode 100644 index 0000000000..4d994f2032 --- /dev/null +++ b/tests/support/otlp/Cargo.toml @@ -0,0 +1,16 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "otlp-support" +description = "OTLP collector fixture for test suites whose gateway exports to a collector the test runs" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/NVIDIA/OpenShell" +publish = false + +[dependencies] +openshell-otel-test-support = { path = "../../../crates/openshell-otel-test-support" } +openshell-testkit = { path = "../../testkit/testkit" } diff --git a/tests/support/otlp/src/lib.rs b/tests/support/otlp/src/lib.rs new file mode 100644 index 0000000000..13463dce9a --- /dev/null +++ b/tests/support/otlp/src/lib.rs @@ -0,0 +1,131 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! An OTLP collector for suites whose gateway exports to a collector the +//! test runs. +//! +//! The environment configures the gateway's `[openshell.gateway.otlp]` +//! endpoint and publishes it, with the address the test must listen on, in +//! `OPENSHELL_TEST_OTLP_*` variables. Under `openshell-test-runner`, the +//! tmachine `-otlp` environments do that +//! (`tests/tmachine/ansible/playbooks/otlp.yaml`); against your own +//! deployment, set them yourself: +//! +//! | Variable | Example | +//! |---|---| +//! | `OPENSHELL_TEST_OTLP_LISTEN` | `0.0.0.0:4317` | +//! | `OPENSHELL_TEST_OTLP_ENDPOINT` | `http://host.containers.internal:4317` | +//! +//! A missing variable fails the test; it never skips it. Tests that start a +//! collector can't run at the same time, since they bind the same address. + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::time::Duration; + +use openshell_otel_test_support::OtlpTestServer; +use testkit::{Error, Poll, Result, ResultExt as _, poll_until}; + +pub use openshell_otel_test_support::ReceivedTraces; +pub use openshell_otel_test_support::relay::{ + SANDBOX_ID_KEY, SOURCE_KEY, SOURCE_VALUE, encoded_trace_request, +}; + +pub const LISTEN_ENV: &str = "OPENSHELL_TEST_OTLP_LISTEN"; +pub const ENDPOINT_ENV: &str = "OPENSHELL_TEST_OTLP_ENDPOINT"; + +/// String resource attributes, keyed by name. +pub type Attributes = HashMap; + +/// An OTLP/gRPC collector on the address the environment chose. It records +/// what arrives and stops when dropped. +pub struct Collector { + server: OtlpTestServer, + endpoint: String, +} + +impl Collector { + /// Listen on [`LISTEN_ENV`]. + pub async fn start() -> Result { + let listen = required(LISTEN_ENV)?; + let endpoint = required(ENDPOINT_ENV)?; + let addr: SocketAddr = listen + .parse() + .map_err(|error| Error::msg(format!("{LISTEN_ENV}={listen}: {error}")))?; + let server = OtlpTestServer::try_start_on(addr) + .await + .context(format!("start the OTLP collector on {addr}"))?; + Ok(Self { server, endpoint }) + } + + /// The endpoint the gateway exports to, such as + /// `http://host.containers.internal:4317`. + pub fn endpoint(&self) -> &str { + &self.endpoint + } + + /// The `host:port` of [`Self::endpoint`]. + pub fn host_port(&self) -> &str { + let authority = self + .endpoint + .split_once("://") + .map_or(self.endpoint.as_str(), |(_, rest)| rest); + authority.split('/').next().unwrap_or(authority) + } + + /// Everything received so far. + pub fn received(&self) -> ReceivedTraces { + self.server.received() + } + + /// Wait up to `within` until every span in `names` has arrived. Returns + /// the resource attributes of the batch each span arrived in, keyed by + /// span name. + pub async fn wait_for_spans( + &self, + names: &[&str], + within: Duration, + ) -> Result> { + poll_until( + &format!("the collector to receive spans {names:?}"), + within, + Duration::from_millis(250), + async || { + let received = self.received(); + let arrived: Vec<&str> = received + .spans + .iter() + .map(|span| span.name.as_str()) + .collect(); + if !names.iter().all(|name| arrived.contains(name)) { + return Ok(Poll::Pending(format!("received spans {arrived:?}"))); + } + Ok(Poll::Ready( + received + .spans + .iter() + .zip(&received.span_resources) + .map(|(span, attributes)| (span.name.clone(), attributes.clone())) + .collect(), + )) + }, + ) + .await + } + + /// Stop listening, so the next test can bind the address. + pub async fn shutdown(self) { + drop(self.server.shutdown().await); + } +} + +fn required(name: &str) -> Result { + std::env::var(name) + .ok() + .filter(|value| !value.is_empty()) + .ok_or_else(|| { + Error::msg(format!( + "{name} is not set; this suite needs a gateway that exports to a test collector (see the otlp-support crate docs)" + )) + }) +} From 919fc9608823a1430ddac32e733020f58be038d6 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:50:09 -0800 Subject: [PATCH 05/22] test(features): port the OTLP agent trace relay tests Signed-off-by: Matthew Grossman --- tests/suites/features/Cargo.lock | 335 ++++++++++++++++++ tests/suites/features/Cargo.toml | 2 +- tests/suites/features/otlp-relay/Cargo.toml | 17 + .../features/otlp-relay/tests/otlp_relay.rs | 249 +++++++++++++ 4 files changed, 602 insertions(+), 1 deletion(-) create mode 100644 tests/suites/features/otlp-relay/Cargo.toml create mode 100644 tests/suites/features/otlp-relay/tests/otlp_relay.rs diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index 1200c171f5..5e9d6fc0d3 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" @@ -2063,6 +2082,15 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + [[package]] name = "matchit" version = "0.8.4" @@ -2085,6 +2113,16 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "metrics" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5312e9ba3771cfa961b585728215e3d972c950a3eed9252aa093d6301277e8" +dependencies = [ + "ahash", + "portable-atomic", +] + [[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]] @@ -2211,6 +2250,15 @@ dependencies = [ "smallvec", ] +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -2408,6 +2456,73 @@ dependencies = [ "tower", ] +[[package]] +name = "openshell-ocsf" +version = "0.0.0" +dependencies = [ + "chrono", + "serde", + "serde_json", + "serde_repr", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "openshell-otel" +version = "0.0.0" +dependencies = [ + "async-trait", + "bytes", + "futures", + "http", + "http-body-util", + "hyper-rustls", + "hyper-util", + "metrics", + "openshell-crypto", + "openshell-ocsf", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-otlp", + "opentelemetry_sdk", + "rustls", + "rustls-native-certs", + "serde_json", + "thiserror 2.0.20", + "tokio", + "tonic", + "tower-http 0.6.8", + "tracing", + "tracing-opentelemetry", + "tracing-subscriber", + "zeroize", +] + +[[package]] +name = "openshell-otel-test-support" +version = "0.0.0" +dependencies = [ + "bytes", + "http", + "http-body-util", + "hyper", + "hyper-util", + "openshell-crypto", + "openshell-otel", + "opentelemetry-proto", + "prost", + "rcgen", + "rustls", + "tokio", + "tokio-rustls", + "tokio-stream", + "tonic", + "tracing", + "tracing-subscriber", +] + [[package]] name = "openshell-policy" version = "0.0.0" @@ -2538,6 +2653,83 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "opentelemetry" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c1f1a6ac9c875a4941e4c7c085b61e8f4daa326de03b4701768c3491a6ad9ee" +dependencies = [ + "futures-core", + "futures-sink", + "js-sys", + "pin-project-lite", + "thiserror 2.0.20", + "tracing", +] + +[[package]] +name = "opentelemetry-http" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302249bd8ee804789faaa7b5b2cbf79bc61cb864714079c644e3828af5b7e811" +dependencies = [ + "async-trait", + "bytes", + "http", + "opentelemetry", +] + +[[package]] +name = "opentelemetry-otlp" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0756af24841e367128ef31c831999937b8b5c5197d47914590d8f4e2e88c2e1a" +dependencies = [ + "flate2", + "http", + "httpdate", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-proto", + "opentelemetry_sdk", + "prost", + "thiserror 2.0.20", + "tokio", + "tonic", + "tonic-types", +] + +[[package]] +name = "opentelemetry-proto" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d576f5dddc3299341bcd85a04be17b2564844c0c9563214f02d85f2524d1afae" +dependencies = [ + "opentelemetry", + "opentelemetry_sdk", + "prost", + "tonic", + "tonic-prost", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "372a912db2974d1990207006fd0e3aa0ef3fd4ad3be43c65cfaadf2206866061" +dependencies = [ + "futures-channel", + "futures-executor", + "futures-util", + "opentelemetry", + "percent-encoding", + "portable-atomic", + "rand 0.9.4", + "thiserror 2.0.20", + "tokio", + "tokio-stream", +] + [[package]] name = "ordered-float" version = "2.10.1" @@ -2547,6 +2739,23 @@ dependencies = [ "num-traits", ] +[[package]] +name = "otlp-relay" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "openshell-testkit", + "otlp-support", +] + +[[package]] +name = "otlp-support" +version = "0.0.0" +dependencies = [ + "openshell-otel-test-support", + "openshell-testkit", +] + [[package]] name = "owo-colors" version = "4.3.0" @@ -3472,6 +3681,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_repr" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -3528,6 +3748,15 @@ dependencies = [ "digest 0.11.2", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "1.3.0" @@ -3553,6 +3782,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" @@ -3961,6 +4196,15 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + [[package]] name = "time" version = "0.3.47" @@ -4107,6 +4351,7 @@ dependencies = [ "axum", "base64 0.22.1", "bytes", + "flate2", "h2", "http", "http-body", @@ -4213,6 +4458,8 @@ dependencies = [ "tower", "tower-layer", "tower-service", + "tracing", + "uuid", ] [[package]] @@ -4277,6 +4524,64 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-opentelemetry" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a904802a1b902f43638b677ff2a650847e3b4404101b6c586d648e8c1e3e8fe" +dependencies = [ + "js-sys", + "opentelemetry", + "tracing", + "tracing-core", + "tracing-log", + "tracing-subscriber", + "web-time", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", ] [[package]] @@ -4427,6 +4732,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "vcpkg" version = "0.2.15" @@ -4590,6 +4901,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-root-certs" version = "1.0.10" @@ -4967,6 +5288,20 @@ name = "zeroize" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] name = "zerotrie" diff --git a/tests/suites/features/Cargo.toml b/tests/suites/features/Cargo.toml index 07f5f08a45..5f1d30c4f6 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", "provider-refresh", "routable-host-ip"] +members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "oci-image", "otlp-relay", "provider-refresh", "routable-host-ip"] diff --git a/tests/suites/features/otlp-relay/Cargo.toml b/tests/suites/features/otlp-relay/Cargo.toml new file mode 100644 index 0000000000..f66c8aa2e3 --- /dev/null +++ b/tests/suites/features/otlp-relay/Cargo.toml @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "otlp-relay" +description = "Features suite: the supervisor's agent trace relay, with and without a collector" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/NVIDIA/OpenShell" +publish = false + +[dependencies] +base64 = "0.22" +openshell-testkit = { path = "../../../testkit/testkit" } +otlp-support = { path = "../../../support/otlp" } diff --git a/tests/suites/features/otlp-relay/tests/otlp_relay.rs b/tests/suites/features/otlp-relay/tests/otlp_relay.rs new file mode 100644 index 0000000000..6c9f3db2ed --- /dev/null +++ b/tests/suites/features/otlp-relay/tests/otlp_relay.rs @@ -0,0 +1,249 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The supervisor's agent trace relay. +//! +//! The collector tests need a gateway whose OTLP export and agent trace relay +//! point at a collector the test runs ([`otlp_support`]). The inert test +//! needs a gateway without either, so no environment runs all three: select +//! them with a filter. + +use std::collections::HashMap; +use std::time::Duration; + +use base64::Engine as _; +use otlp_support::{Attributes, Collector, SANDBOX_ID_KEY, SOURCE_KEY, SOURCE_VALUE}; +use testkit::sdk::SandboxPhase; +use testkit::{Context, Error, Result, ResultExt as _}; + +const ENV_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_ENDPOINT"; +const ENV_PROTOCOL: &str = "OTEL_EXPORTER_OTLP_PROTOCOL"; +const ENV_COLLECTOR: &str = "OPENSHELL_OTLP_ENDPOINT"; +const RELAY_ENDPOINT: &str = "http://192.0.0.8:4318"; + +/// Posts the base64 body from `OTLP_BODY_B64` to the relay and prints the +/// status plus the complete environment, one `ENV key=value` line each, so +/// the test can check values and prove the collector address is nowhere. +const EXPORT_SCRIPT: &str = r#" +import base64, os, requests +body = base64.b64decode(os.environ["OTLP_BODY_B64"]) +url = os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] + "/v1/traces" +response = requests.post(url, data=body, headers={"Content-Type": "application/x-protobuf"}, timeout=10) +print("STATUS", response.status_code) +for key, value in sorted(os.environ.items()): + if key != "OTLP_BODY_B64": + print("ENV " + key + "=" + value) +"#; + +/// Reports whether an endpoint was injected, then posts to the relay address +/// directly and reports the failure class instead of raising. +const INERT_SCRIPT: &str = r#" +import os, requests +print("ENDPOINT", os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "unset")) +url = "http://192.0.0.8:4318/v1/traces" +try: + response = requests.post(url, data=b"", headers={"Content-Type": "application/x-protobuf"}, timeout=3) + print("STATUS", response.status_code) +except Exception as error: + print("ERROR", type(error).__name__) +"#; + +/// A main process that posts one span with the payload embedded, and exits +/// as soon as the POST returns: 0 if the relay accepted it. +fn exit_script(body_b64: &str) -> String { + format!( + r#" +import base64, os, requests +body = base64.b64decode("{body_b64}") +url = os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] + "/v1/traces" +response = requests.post(url, data=body, headers={{"Content-Type": "application/x-protobuf"}}, timeout=10) +raise SystemExit(0 if response.status_code == 200 else 1) +"# + ) +} + +/// A span exported from a sandbox reaches the collector within 5 seconds, +/// with the supervisor's attribution in place of the agent's spoofed values. +/// The workload gets the relay endpoint and protocol, and never the +/// collector's address. +#[testkit::test] +async fn agent_span_reaches_collector_with_attribution(cx: &mut Context) -> testkit::Result { + let collector = Collector::start().await?; + let body = format!("OTLP_BODY_B64={}", encoded_request("e2e-span")); + let builder = cx + .cli_sandbox("otlp") + .image(testkit::python_image()) + .args(["--env", &body, "--no-auto-providers"]) + .command(["python3", "-c", EXPORT_SCRIPT]); + let name = builder.name().to_string(); + let run = builder.run().await?.success()?; + let output = format!("{}{}", run.stdout, run.stderr); + + testkit::ensure!( + output.contains("STATUS 200"), + "the relay did not accept the export:\n{output}" + ); + for expected in [ + format!("ENV {ENV_ENDPOINT}={RELAY_ENDPOINT}"), + format!("ENV {ENV_PROTOCOL}=http/protobuf"), + ] { + testkit::ensure!( + output.contains(&expected), + "the workload environment lacks {expected}:\n{output}" + ); + } + testkit::ensure!( + !output.contains(ENV_COLLECTOR), + "{ENV_COLLECTOR} is visible inside the sandbox:\n{output}" + ); + let host_port = collector.host_port(); + testkit::ensure!( + !output.contains(host_port), + "the collector address {host_port} appears in the sandbox environment:\n{output}" + ); + + let sandbox = cx.adopt(&name).await?; + let spans = collector + .wait_for_spans(&["e2e-span"], Duration::from_secs(5)) + .await?; + expect_no_duplicate_resource_keys(&collector)?; + expect_attribution(&spans["e2e-span"], sandbox.id())?; + collector.shutdown().await; + Ok(()) +} + +/// A main process that exports a span and exits at once still delivers it: +/// the supervisor flushes before it reports the exit, so the span is at the +/// collector by the time the sandbox is Completed. Five sandboxes in a row. +#[testkit::test] +async fn span_emitted_before_exit_is_delivered(cx: &mut Context) -> testkit::Result { + let collector = Collector::start().await?; + let names: Vec = (1..=5).map(|i| format!("exit-span-{i}")).collect(); + let mut ids = HashMap::new(); + for (index, name) in names.iter().enumerate() { + let sandbox = cx + .cli_sandbox(&format!("otlpx{index}")) + .image(testkit::python_image()) + .command(["python3", "-c", &exit_script(&encoded_request(name))]) + .create() + .await?; + let finished = sandbox.wait_finished().await?; + if finished.phase != SandboxPhase::Completed || finished.exit_code != Some(0) { + let logs = sandbox.logs().await?; + return Err(Error::msg(format!( + "sandbox {} finished in {:?} with exit code {:?}; expected Completed with 0. Supervisor logs:\n{logs}", + sandbox.name(), + finished.phase, + finished.exit_code + ))); + } + let arrived: Vec = collector + .received() + .spans + .into_iter() + .map(|span| span.name) + .collect(); + testkit::ensure!( + arrived.contains(name), + "{name} had not reached the collector when the exit was reported; it holds {arrived:?}" + ); + ids.insert(name.clone(), sandbox.id().to_string()); + sandbox.delete().await?; + sandbox + .wait_absent(Duration::from_secs(60)) + .await + .context("let the sandbox's teardown finish before the next create")?; + } + + let name_refs: Vec<&str> = names.iter().map(String::as_str).collect(); + let spans = collector + .wait_for_spans(&name_refs, Duration::from_secs(15)) + .await?; + expect_no_duplicate_resource_keys(&collector)?; + for name in &names { + expect_attribution(&spans[name], &ids[name])?; + } + collector.shutdown().await; + Ok(()) +} + +/// Without a collector, the supervisor injects no relay endpoint, nothing +/// listens on the relay address, and the supervisor logs that the relay is +/// inactive. +#[testkit::test] +async fn relay_is_inert_without_collector(cx: &mut Context) -> testkit::Result { + let builder = cx + .cli_sandbox("otlpi") + .image(testkit::python_image()) + .args(["--no-auto-providers"]) + .command(["python3", "-c", INERT_SCRIPT]); + let name = builder.name().to_string(); + let run = builder.run().await?.success()?; + let output = format!("{}{}", run.stdout, run.stderr); + testkit::ensure!( + output.contains("ENDPOINT unset"), + "a relay endpoint was injected while the relay is inactive:\n{output}" + ); + testkit::ensure!( + output.contains("ERROR ConnectionError"), + "the export did not fail with a connection error:\n{output}" + ); + + let sandbox = cx.adopt(&name).await?; + let logs = sandbox + .logs_until("that the OTLP agent trace relay is inactive", |logs| { + logs.contains("OTLP agent trace relay inactive") + }) + .await?; + testkit::ensure!( + !logs.contains("OTLP agent trace relay enabled"), + "the supervisor also reported the relay enabled:\n{logs}" + ); + Ok(()) +} + +/// One span with the agent's own service name and spoofed values for both +/// attribution keys, base64-encoded. +fn encoded_request(span_name: &str) -> String { + let request = otlp_support::encoded_trace_request( + span_name, + &[ + ("service.name", "e2e-agent"), + (SANDBOX_ID_KEY, "spoofed"), + (SOURCE_KEY, "infrastructure"), + ], + ); + base64::engine::general_purpose::STANDARD.encode(request) +} + +/// The received attributes keep the last value of a key, so a spoofed +/// attribute that was appended to rather than replaced shows only as a +/// duplicate. +fn expect_no_duplicate_resource_keys(collector: &Collector) -> Result { + let duplicates = collector.received().duplicate_resource_keys; + testkit::ensure!( + duplicates.is_empty(), + "attribution keys were appended, not replaced: {duplicates:?}" + ); + Ok(()) +} + +fn expect_attribution(attributes: &Attributes, sandbox_id: &str) -> Result { + testkit::ensure!( + !attributes + .values() + .any(|value| value == "spoofed" || value == "infrastructure"), + "the agent's attribution values were kept: {attributes:?}" + ); + for (key, expected) in [ + ("service.name", "e2e-agent"), + (SOURCE_KEY, SOURCE_VALUE), + (SANDBOX_ID_KEY, sandbox_id), + ] { + testkit::ensure!( + attributes.get(key).map(String::as_str) == Some(expected), + "resource attribute {key} is not {expected}: {attributes:?}" + ); + } + Ok(()) +} From 820adaf9addf3870b9d4218d701be3a1a693c191 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:50:09 -0800 Subject: [PATCH 06/22] ci(e2e): select tests per row with a filter and run otlp-relay Signed-off-by: Matthew Grossman --- .github/workflows/e2e-suites.yml | 12 ++++++++++-- TESTING.md | 4 +++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index c84837c976..611a11c16f 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -4,8 +4,9 @@ # Runs testkit suites in tmachine environments on CI. Each row of `ROWS` below # names a tmachine environment and installer, the family (the path of a # workspace under tests/suites/, such as conformance or drivers/podman) and, -# optionally, the package in it, the gateway name the installer registers, and -# the runner label for the environment's architecture. `openshell-test-runner` +# optionally, the package in it, a nextest filterset (`filter`) for a package +# whose tests need different environments, the gateway name the installer +# registers, and the runner label for the environment's architecture. `openshell-test-runner` # builds the tests, boots the environment, runs them inside it and checks the # results. With `prebuilt`, the rows run what the caller built once for the # run instead: conformance rows the static `openshell-conformance`, the other @@ -116,6 +117,8 @@ 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":"fedora-podman-rootless-otlp","installer":"rpm","family":"features","package":"otlp-relay","filter":"not test(relay_is_inert_without_collector)","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"otlp-relay","filter":"test(relay_is_inert_without_collector)","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"}, @@ -135,6 +138,7 @@ jobs: | select((.external_driver // false) == false or $external == "true") | select((.upgrade_source // false) == false or $upgrade == "true") | .package //= "" + | .filter //= "" | .disruption //= "" | .suite = ([.family, .package, .disruption] | map(select(. != "")) | join("/")) | .artifact = ([.suite, .environment, .installer] | join("-") | gsub("/"; "-")) @@ -254,6 +258,7 @@ jobs: INSTALLER: ${{ matrix.installer }} FAMILY: ${{ matrix.family }} PACKAGE: ${{ matrix.package }} + FILTER: ${{ matrix.filter }} GATEWAY: ${{ matrix.gateway }} DISRUPTION: ${{ matrix.disruption }} TEST_THREADS: ${{ matrix.test_threads }} @@ -286,6 +291,9 @@ jobs: if [ -n "${PACKAGE}" ]; then selection+=(--package "${PACKAGE}") fi + if [ -n "${FILTER}" ]; then + selection+=(--filter "${FILTER}") + fi fi if [ -n "${TEST_THREADS}" ]; then selection+=(--test-threads "${TEST_THREADS}") diff --git a/TESTING.md b/TESTING.md index 42c4321aa4..854e92f536 100644 --- a/TESTING.md +++ b/TESTING.md @@ -281,7 +281,9 @@ out of every environment until it's fixed. an explicit matrix and runs the runner once per row. Branch E2E calls it once per family when the `test:e2e` label is set, and a failure fails the Core E2E result. Release Dev and Release Qualification run the conformance and feature -families. To run a suite in another environment on CI, add a row. +families. To run a suite in another environment on CI, add a row. A row's +`filter`, a nextest filterset, runs only some of the package's tests, for a +package whose tests need different environments. ### Adding a feature suite From d96188757549507d19cfbbe86a27900e817e62f2 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:04:13 -0800 Subject: [PATCH 07/22] test(tmachine): add SPIFFE Workload API environments Signed-off-by: Matthew Grossman --- tests/tmachine/ansible/playbooks/spiffe.yaml | 77 ++++++++++++++++++++ tests/tmachine/config.nix | 7 ++ 2 files changed, 84 insertions(+) create mode 100644 tests/tmachine/ansible/playbooks/spiffe.yaml diff --git a/tests/tmachine/ansible/playbooks/spiffe.yaml b/tests/tmachine/ansible/playbooks/spiffe.yaml new file mode 100644 index 0000000000..7c510a55c3 --- /dev/null +++ b/tests/tmachine/ansible/playbooks/spiffe.yaml @@ -0,0 +1,77 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Point the gateway and the supervisors at SPIFFE Workload APIs the tests run, +# and publish where the tests listen. +# +# The gateway reads its Workload API socket only from +# OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET. The packaged gateway is a +# systemd user service whose installer rewrites gateway.env, so a user-unit +# drop-in sets the variable. Supervisors use the driver's +# provider_spiffe_workload_api_socket. Podman supervisors share the test VM's +# network, so they reach the test's listener over loopback. Nothing listens +# until a test starts its Workload API. The SPIFFE fixture +# (tests/support/spiffe) reads the variables published below. +--- +- name: SPIFFE Workload APIs for tests + hosts: all + gather_facts: false + vars: + spiffe_directory: /var/lib/openshell-test/spiffe + spiffe_gateway_socket: "{{ spiffe_directory }}/gateway.sock" + spiffe_supervisor_port: 17690 + tasks: + - name: Wait for SSH + ansible.builtin.wait_for_connection: + + - name: Require the environment's driver + ansible.builtin.assert: + that: [environment_driver is defined] + fail_msg: environment_driver names the gateway driver and comes from the environment's base in config.nix + + # The test binds the socket as tmachine. A root gateway connects anyway. + - name: Create the gateway Workload API socket directory + become: true + ansible.builtin.file: + path: "{{ spiffe_directory }}" + state: directory + owner: tmachine + group: tmachine + mode: "0755" + + - name: Create the gateway user-unit drop-in directory + become: true + ansible.builtin.file: + path: /etc/systemd/user/openshell-gateway.service.d + state: directory + owner: root + group: root + mode: "0755" + + - name: Point the gateway at the test's Workload API + become: true + ansible.builtin.copy: + dest: /etc/systemd/user/openshell-gateway.service.d/spiffe.conf + owner: root + group: root + mode: "0644" + content: | + [Service] + Environment=OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET={{ spiffe_gateway_socket }} + + - name: Point supervisors at the test's Workload API + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: spiffe + gateway_overrides_content: | + [openshell.drivers.{{ environment_driver }}] + provider_spiffe_workload_api_socket = "tcp:127.0.0.1:{{ spiffe_supervisor_port }}" + + - name: Publish SPIFFE test variables + ansible.builtin.include_tasks: test-env.yaml + vars: + test_env_name: spiffe + test_env_vars: + OPENSHELL_TEST_SPIFFE_GATEWAY_LISTEN: "{{ spiffe_gateway_socket }}" + OPENSHELL_TEST_SPIFFE_SUPERVISOR_LISTEN: "0.0.0.0:{{ spiffe_supervisor_port }}" diff --git a/tests/tmachine/config.nix b/tests/tmachine/config.nix index dd51a3c6ca..4f953cab7c 100644 --- a/tests/tmachine/config.nix +++ b/tests/tmachine/config.nix @@ -120,6 +120,13 @@ let bases = podmanBases; setup.playbooks = [ "ansible/playbooks/otlp.yaml" ]; }; + # Test-run SPIFFE Workload APIs for the gateway and supervisors, for the + # provider-token-exchange suite. Supervisors reach theirs over loopback, + # which needs Podman's host-network supervisors. + spiffe = { + bases = podmanBases; + setup.playbooks = [ "ansible/playbooks/spiffe.yaml" ]; + }; }; featureEnvironments = pkgs.lib.concatMap ( feature: map (base: withSetup base feature features.${feature}.setup) features.${feature}.bases From 1362872b81487cd3f68b059d40ae16133e202f87 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:04:13 -0800 Subject: [PATCH 08/22] test(support): add SPIFFE Workload API fixture Signed-off-by: Matthew Grossman --- tests/support/Cargo.lock | 19 ++ tests/support/Cargo.toml | 2 +- tests/support/README.md | 2 + tests/support/spiffe/Cargo.toml | 27 ++ tests/support/spiffe/src/lib.rs | 460 ++++++++++++++++++++++++++++++++ 5 files changed, 509 insertions(+), 1 deletion(-) create mode 100644 tests/support/spiffe/Cargo.toml create mode 100644 tests/support/spiffe/src/lib.rs diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 58a78625ba..25cfcf2c4f 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -3757,6 +3757,25 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spiffe-support" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "futures-util", + "hex", + "jsonwebtoken", + "openshell-crypto", + "openshell-testkit", + "prost", + "serde_json", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", + "tower", +] + [[package]] name = "spin" version = "0.9.9" diff --git a/tests/support/Cargo.toml b/tests/support/Cargo.toml index ecb651ad07..e47dbc2d8a 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", "otlp", "podman", "sandbox-clients"] +members = ["container-engine", "host-server", "keycloak", "otlp", "podman", "sandbox-clients", "spiffe"] diff --git a/tests/support/README.md b/tests/support/README.md index e7aea2ac85..72a7924ceb 100644 --- a/tests/support/README.md +++ b/tests/support/README.md @@ -27,6 +27,8 @@ never skips it. Add a row when you add a variable. The runner also sets | `OPENSHELL_TEST_KEYCLOAK_PASSWORD` | `-keycloak` | `keycloak-support` | That user's password. | | `OPENSHELL_TEST_OTLP_LISTEN` | `-otlp` (`playbooks/otlp.yaml`) | `otlp-support` | The address the test's OTLP/gRPC collector listens on, such as `0.0.0.0:4317`. | | `OPENSHELL_TEST_OTLP_ENDPOINT` | `-otlp` | `otlp-support` | The collector endpoint in the gateway's `[openshell.gateway.otlp]`, which also enables the agent trace relay. Tests check that sandboxes never see it. | +| `OPENSHELL_TEST_SPIFFE_GATEWAY_LISTEN` | `-spiffe` (`playbooks/spiffe.yaml`) | `spiffe-support` | The Unix socket the test's gateway Workload API listens on. The gateway's `OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET` names it. | +| `OPENSHELL_TEST_SPIFFE_SUPERVISOR_LISTEN` | `-spiffe` | `spiffe-support` | The TCP address the test's supervisor Workload API listens on, such as `0.0.0.0:17690`. The driver's `provider_spiffe_workload_api_socket` reaches it as `tcp:127.0.0.1:`. | | `OPENSHELL_TEST_ADDITIONAL_CA_CERT` | The additional-CA environment, which sets `openshell.supervisor.network.additional_ca_bundle` (added by #5729) | `host-server-support` (`TestCa::from_env`) | The path of the CA certificate, in PEM, that the supervisor trusts for sandbox egress. | | `OPENSHELL_TEST_ADDITIONAL_CA_KEY` | The additional-CA environment | `host-server-support` (`TestCa::from_env`) | The path of that CA's private key, in PEM, readable by the test user. Tests sign server certificates with it. | | `OPENSHELL_TEST_BASE_IMAGE` | Optional; you, for example to use a mirror | `testkit::base_image()` | The default sandbox image. Unset, it is `nvcr.io/nvidia/base/ubuntu:24.04`. | diff --git a/tests/support/spiffe/Cargo.toml b/tests/support/spiffe/Cargo.toml new file mode 100644 index 0000000000..438461fead --- /dev/null +++ b/tests/support/spiffe/Cargo.toml @@ -0,0 +1,27 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "spiffe-support" +description = "SPIFFE Workload API fixtures for test suites whose gateway and supervisors use Workload APIs the test runs" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/NVIDIA/OpenShell" +publish = false + +[dependencies] +base64 = "0.22" +futures-util = "0.3" +hex = "0.4" +jsonwebtoken = { version = "10", default-features = false, features = ["use_pem"] } +openshell-crypto = { path = "../../../crates/openshell-crypto" } +openshell-testkit = { path = "../../testkit/testkit" } +prost = "0.14" +serde_json = "1" +tokio = { version = "1.43", features = ["net", "rt", "sync"] } +tokio-stream = { version = "0.1", features = ["net"] } +tonic = { version = "0.14", default-features = false, features = ["codegen", "router", "server"] } +tonic-prost = "0.14" +tower = "0.5" diff --git a/tests/support/spiffe/src/lib.rs b/tests/support/spiffe/src/lib.rs new file mode 100644 index 0000000000..e222ef03b6 --- /dev/null +++ b/tests/support/spiffe/src/lib.rs @@ -0,0 +1,460 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! SPIFFE Workload APIs for suites whose gateway and supervisors fetch +//! JWT-SVIDs from Workload APIs the test runs. +//! +//! The environment points the gateway's Workload API socket and the driver's +//! `provider_spiffe_workload_api_socket` at addresses the test listens on, and +//! publishes them in `OPENSHELL_TEST_SPIFFE_*` variables. Under +//! `openshell-test-runner`, the tmachine `-spiffe` environments +//! do that (`tests/tmachine/ansible/playbooks/spiffe.yaml`); against your own +//! deployment, set them yourself: +//! +//! | Variable | Example | +//! |---|---| +//! | `OPENSHELL_TEST_SPIFFE_GATEWAY_LISTEN` | `/var/lib/openshell-test/spiffe/gateway.sock` | +//! | `OPENSHELL_TEST_SPIFFE_SUPERVISOR_LISTEN` | `0.0.0.0:17690` | +//! +//! Both Workload APIs sign with one fixture key and serve its bundle for +//! [`TRUST_DOMAIN`]. Every supervisor gets [`SUPERVISOR_SUBJECT`]: suites +//! test credential isolation with distinct providers and audiences, not +//! SPIRE attestation. A missing variable fails the test; it never skips it. +//! Tests that start the Workload APIs can't run at the same time, since they +//! bind the same addresses. + +use std::collections::HashMap; +use std::convert::Infallible; +use std::net::SocketAddr; +use std::os::unix::fs::PermissionsExt as _; +use std::path::PathBuf; +use std::sync::Arc; +use std::task::{Context, Poll}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use base64::Engine as _; +use futures_util::future::BoxFuture; +use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation}; +use serde_json::json; +use testkit::{Error, Result, ResultExt as _}; +use tokio::net::{TcpListener, UnixListener}; +use tokio_stream::wrappers::{ReceiverStream, TcpListenerStream, UnixListenerStream}; +use tonic::body::Body as TonicBody; +use tonic::codegen::{Body, http}; +use tonic::{Request, Response, Status}; + +pub const GATEWAY_LISTEN_ENV: &str = "OPENSHELL_TEST_SPIFFE_GATEWAY_LISTEN"; +pub const SUPERVISOR_LISTEN_ENV: &str = "OPENSHELL_TEST_SPIFFE_SUPERVISOR_LISTEN"; + +pub const TRUST_DOMAIN: &str = "openshell-e2e.test"; +/// The `iss` of every JWT-SVID. +pub const ISSUER: &str = "https://spiffe.openshell-e2e.test"; +/// The SPIFFE ID the gateway's Workload API issues. +pub const GATEWAY_SUBJECT: &str = "spiffe://openshell-e2e.test/openshell/gateway"; +/// The SPIFFE ID the supervisors' Workload API issues. +pub const SUPERVISOR_SUBJECT: &str = "spiffe://openshell-e2e.test/openshell/sandbox/e2e"; +const KEY_ID: &str = "openshell-e2e-test-key"; + +const TEST_RSA_PRIVATE_KEY: &str = r"-----BEGIN PRIVATE KEY----- +MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCvCoZ0mVHpCHsF +zeeqw2caNIe/eb4BQUccFPhZfRnF7sCfyB84zTBmuwG2umRBdjFnVsfIIZRp2HcD +OESrRYYiE1RGfjBXImGVg2Wtza0HYhL1sLyX1eaEefylxoilmApAgWDh9p36h8J2 +s5YHwyXPTttx4DpdWDnxju1iNmwoIB8uVE/5amWgbNvlETMBOcB1RxDHtnVy+xJz +jjjrzK4Qz9WsUTHAvngdi4Yyxvci+yKpjYTg5+UWxmAN6iW522TpLe32MDb5Ug1d +trBvvepWmdQ6CBwPhBHCt/sMoSJAYSO4RKeBnBjeLQBXFTxaOv5iTGIsRTX3K471 +epHp3cT5AgMBAAECggEASQlRv/4nZN5SgsH/K8v7zb3kdHsmUly8AJYpaCGgauvr +uN/mUyueyga2uNl+MqhQBef6VWHZjO6y/gdw86v/Q2GgVQebQQhKAnpAp2w+Ceoc +siKMFqi8VkOWLU+xPbM6d97kH3TpRxt1g1T8wYFmWeF0BEiE4eUJzGaQW14M9BJ+ +G0QxmP/zjX9cNpVeApKTjBWKiH4CXG3DuI3pJ93VOMpUlOsrdLXvKGTze0e01itr +MX/MHHTE+VXB4FB+/zKSA4c36egi676OSXrGC/GDmM8ntJ4CUGeD5uZsMSADiAUn +iccv5iGRWVMIKxUS5Q4k0jy8uWuK+QVP4Y6cQWYArwKBgQDhuSNORBNpIGRfsKGN +iJo/h+qinz6pEIpa3D3oVl7rpkyvgIyaTwfXvC1vfdS9V5VIel2gV2Cx0OrI8yrr +nQu1JuNV/rLmtvqX321fgBLRdoiqF3pAy1gbmdUz1elerAIYL578gXQ6jg1bbdic +kJpn0MsoDUJGwvJnXcgLqG7q3wKBgQDGhRIa4oJsj1vqICc8zt8YsCAcot3vjWLH +588X7JdBGOWJdWxfdmGXQRn5Zw9UhMQnYa3uyTBPeVcXopThlPotYeuFhLSU856T +IJzfpzCJzC4zIQayoyvJFrKe7N70iUQ986dewYy9oxQhHvFKd/qe4ylbzZJXpthX +eWEuuBSjJwKBgGkqXt6qLPj/1IQYwUw15tfOtW0LEKCoSi3HCzjidNsJ4hSqqdeD +Fr5WuDyHvcRxt+XKzTBVRYHTOnBhiw+3XasK8UQxpJyFh/+WY1jpTNs2hLnqslTZ +6LUDWSgLc+1d6qPmHAa9Ma/OWz7L0O4xGR9hUiXY95YMYe/y668yzGq1AoGBAJyU +Gsqfu7U6gYmxoKEine6QBFPx1dD7GF2KJdq93jMXGvyHZFoLOkAdtgnz0rCcI0bY +kWKUxwj4MMxQjNM8OPMQl75xBCmz2XA8Od9htDQLmqjzNKAzePabc3lMZTJFDlE6 +29kuGf79IIRbLn/JECDAFT/2baW60Ep2T0OVJ5njAoGAfaCaQ4aVgjI027q7Y5qP +KfNSI8uuA8PLqmUY30I9KFWzN6VDLu00eKa90F4w3CeWRRQWXW1+007tTz3V1mNw +20A24Fi3HGQmXc7NyuLDODTJsWBICuOemCnRkvcxIlxb+ec7jp+XRmzDwKkzSnVN +pM2zFU8SeVkvHKlEuoHaP0s= +-----END PRIVATE KEY-----"; //notsecret + +const TEST_RSA_MODULUS_HEX: &str = concat!( + "af0a86749951e9087b05cde7aac3671a3487bf79be0141471c14f8597d19c5eec09fc81f38cd3066bb01b6ba", + "644176316756c7c8219469d877033844ab4586221354467e30572261958365adcdad076212f5b0bc97d5e684", + "79fca5c688a5980a408160e1f69dfa87c276b39607c325cf4edb71e03a5d5839f18eed62366c28201f2e54", + "4ff96a65a06cdbe511330139c0754710c7b67572fb12738e38ebccae10cfd5ac5131c0be781d8b8632c6", + "f722fb22a98d84e0e7e516c6600dea25b9db64e92dedf63036f9520d5db6b06fbdea5699d43a081c0f84", + "11c2b7fb0ca122406123b844a7819c18de2d0057153c5a3afe624c622c4535f72b8ef57a91e9ddc4f9" +); + +/// The gateway's and the supervisors' Workload APIs. They stop when dropped. +pub struct WorkloadApis { + gateway: Server, + supervisor: Server, +} + +impl WorkloadApis { + /// Serve the gateway's Workload API on the Unix socket + /// [`GATEWAY_LISTEN_ENV`] names, and the supervisors' on the TCP address + /// [`SUPERVISOR_LISTEN_ENV`] names. + pub async fn start() -> Result { + let socket = PathBuf::from(required(GATEWAY_LISTEN_ENV)?); + let listen = required(SUPERVISOR_LISTEN_ENV)?; + let addr: SocketAddr = listen + .parse() + .map_err(|error| Error::msg(format!("{SUPERVISOR_LISTEN_ENV}={listen}: {error}")))?; + + // A socket a stopped test left behind would make the bind fail. + match std::fs::remove_file(&socket) { + Err(error) if error.kind() != std::io::ErrorKind::NotFound => { + return Err(error).context(format!("remove {}", socket.display())); + } + _ => {} + } + let unix = UnixListener::bind(&socket).context(format!( + "bind the gateway Workload API on {}", + socket.display() + ))?; + // The gateway may run as another user. + std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o777)).context( + format!("make {} reachable to the gateway", socket.display()), + )?; + let gateway = Server::spawn( + WorkloadApi::new(GATEWAY_SUBJECT)?, + UnixListenerStream::new(unix), + Some(socket), + ); + + let tcp = TcpListener::bind(addr) + .await + .context(format!("bind the supervisors' Workload API on {addr}"))?; + let supervisor = Server::spawn( + WorkloadApi::new(SUPERVISOR_SUBJECT)?, + TcpListenerStream::new(tcp), + None, + ); + Ok(Self { + gateway, + supervisor, + }) + } + + /// Stop listening, so the next test can bind the addresses. + pub async fn shutdown(self) { + let Self { + gateway, + supervisor, + } = self; + gateway.shutdown().await; + supervisor.shutdown().await; + } +} + +/// Whether `token` is a JWT-SVID these Workload APIs issued to a supervisor +/// for `audience`, with a valid signature and lifetime. +pub fn verify_supervisor_svid(token: &str, audience: &str) -> bool { + let Ok(key) = decoding_key() else { + return false; + }; + let mut validation = Validation::new(Algorithm::RS256); + validation.set_issuer(&[ISSUER]); + validation.set_audience(&[audience]); + validation.sub = Some(SUPERVISOR_SUBJECT.to_string()); + validation.set_required_spec_claims(&["exp", "iat", "iss", "sub", "aud"]); + openshell_crypto::jwt::decode::(token, &key, &validation) + .is_ok_and(|verified| verified.header.kid.as_deref() == Some(KEY_ID)) +} + +/// Whether `value` contains a JWT-SVID these Workload APIs could have issued, +/// judged by its issuer and without checking the signature. Use it to prove +/// that no SVID reached a place it must not. +pub fn contains_svid(value: &str) -> bool { + value + .split(|c: char| !(c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))) + .filter_map(|word| { + let mut parts = word.split('.'); + match (parts.next(), parts.next(), parts.next(), parts.next()) { + (Some(_), Some(payload), Some(_), None) => Some(payload), + _ => None, + } + }) + .filter_map(|payload| { + base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(payload.trim_end_matches('=')) + .ok() + }) + .filter_map(|claims| serde_json::from_slice::(&claims).ok()) + .any(|claims| claims["iss"] == ISSUER) +} + +fn required(name: &str) -> Result { + std::env::var(name) + .ok() + .filter(|value| !value.is_empty()) + .ok_or_else(|| { + Error::msg(format!( + "{name} is not set; this suite needs a gateway and supervisors that use the test's SPIFFE Workload APIs (see the spiffe-support crate docs)" + )) + }) +} + +fn modulus() -> Result> { + hex::decode(TEST_RSA_MODULUS_HEX) + .map_err(|error| Error::msg(format!("decode the fixture RSA modulus: {error}"))) +} + +fn decoding_key() -> Result { + let n = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(modulus()?); + DecodingKey::from_rsa_components(&n, "AQAB") + .map_err(|error| Error::msg(format!("read the fixture verification key: {error}"))) +} + +fn jwks() -> Result> { + let n = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(modulus()?); + serde_json::to_vec(&json!({ + "keys": [{"kty": "RSA", "kid": KEY_ID, "use": "sig", "alg": "RS256", "n": n, "e": "AQAB"}] + })) + .context("serialize the fixture JWKS") +} + +fn unix_timestamp() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |elapsed| { + elapsed.as_secs().try_into().unwrap_or(i64::MAX) + }) +} + +struct Server { + task: tokio::task::JoinHandle<()>, + socket: Option, +} + +impl Server { + fn spawn(api: WorkloadApi, incoming: S, socket: Option) -> Self + where + S: tokio_stream::Stream> + Send + 'static, + IO: tokio::io::AsyncRead + + tokio::io::AsyncWrite + + tonic::transport::server::Connected + + Unpin + + Send + + 'static, + E: Into>, + { + let task = tokio::spawn(async move { + if let Err(error) = tonic::transport::Server::builder() + .add_service(WorkloadApiServer(Arc::new(api))) + .serve_with_incoming(incoming) + .await + { + eprintln!("SPIFFE Workload API fixture failed: {error}"); + } + }); + Self { task, socket } + } + + async fn shutdown(mut self) { + self.task.abort(); + let _ = (&mut self.task).await; + } +} + +impl Drop for Server { + fn drop(&mut self) { + self.task.abort(); + if let Some(socket) = &self.socket { + let _ = std::fs::remove_file(socket); + } + } +} + +#[derive(Clone, PartialEq, prost::Message)] +struct JwtsvidRequest { + #[prost(string, repeated, tag = "1")] + audience: Vec, + #[prost(string, tag = "2")] + spiffe_id: String, +} + +#[derive(Clone, PartialEq, prost::Message)] +struct JwtsvidResponse { + #[prost(message, repeated, tag = "1")] + svids: Vec, +} + +#[derive(Clone, PartialEq, prost::Message)] +struct Jwtsvid { + #[prost(string, tag = "1")] + spiffe_id: String, + #[prost(string, tag = "2")] + svid: String, + #[prost(string, tag = "3")] + hint: String, +} + +#[derive(Clone, PartialEq, prost::Message)] +struct JwtBundlesRequest {} + +#[derive(Clone, PartialEq, prost::Message)] +struct JwtBundlesResponse { + #[prost(map = "string, bytes", tag = "1")] + bundles: HashMap>, +} + +/// A Workload API that issues RS256 JWT-SVIDs for one subject and serves the +/// bundle that verifies them. +struct WorkloadApi { + subject: &'static str, + jwks: Vec, + encoding_key: EncodingKey, +} + +impl WorkloadApi { + fn new(subject: &'static str) -> Result { + Ok(Self { + subject, + jwks: jwks()?, + encoding_key: EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY.as_bytes()) + .map_err(|error| Error::msg(format!("read the fixture signing key: {error}")))?, + }) + } + + fn jwt_svid(&self, audience: &[String]) -> std::result::Result { + let now = unix_timestamp(); + let mut header = Header::new(Algorithm::RS256); + header.kid = Some(KEY_ID.to_string()); + let claims = json!({ + "iss": ISSUER, + "sub": self.subject, + "aud": audience, + "iat": now, + "exp": now + 3600, + }); + openshell_crypto::jwt::encode(&header, &claims, &self.encoding_key) + .map_err(|error| Status::internal(format!("sign JWT-SVID: {error}"))) + } +} + +#[derive(Clone)] +struct WorkloadApiServer(Arc); + +impl tonic::server::NamedService for WorkloadApiServer { + const NAME: &'static str = "SpiffeWorkloadAPI"; +} + +#[derive(Clone)] +struct FetchJwtsvid(Arc); + +impl tonic::server::UnaryService for FetchJwtsvid { + type Response = JwtsvidResponse; + type Future = BoxFuture<'static, std::result::Result, Status>>; + + fn call(&mut self, request: Request) -> Self::Future { + let api = Arc::clone(&self.0); + Box::pin(async move { + let svid = api.jwt_svid(&request.into_inner().audience)?; + Ok(Response::new(JwtsvidResponse { + svids: vec![Jwtsvid { + spiffe_id: api.subject.to_string(), + svid, + hint: String::new(), + }], + })) + }) + } +} + +#[derive(Clone)] +struct FetchJwtBundles(Arc); + +impl tonic::server::ServerStreamingService for FetchJwtBundles { + type Response = JwtBundlesResponse; + type ResponseStream = ReceiverStream>; + type Future = BoxFuture<'static, std::result::Result, Status>>; + + fn call(&mut self, _request: Request) -> Self::Future { + let api = Arc::clone(&self.0); + Box::pin(async move { + let bundles = HashMap::from([(TRUST_DOMAIN.to_string(), api.jwks.clone())]); + let (tx, rx) = tokio::sync::mpsc::channel(1); + tx.send(Ok(JwtBundlesResponse { bundles })) + .await + .map_err(|error| Status::internal(format!("send bundle: {error}")))?; + Ok(Response::new(ReceiverStream::new(rx))) + }) + } +} + +impl tower::Service> for WorkloadApiServer +where + B: Body + Send + 'static, + B::Error: Into> + Send + 'static, +{ + type Response = http::Response; + type Error = Infallible; + type Future = BoxFuture<'static, std::result::Result>; + + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, request: http::Request) -> Self::Future { + let api = Arc::clone(&self.0); + match request.uri().path() { + "/SpiffeWorkloadAPI/FetchJWTSVID" => Box::pin(async move { + let mut grpc = tonic::server::Grpc::new(tonic_prost::ProstCodec::default()); + Ok(grpc.unary(FetchJwtsvid(api), request).await) + }), + "/SpiffeWorkloadAPI/FetchJWTBundles" => Box::pin(async move { + let mut grpc = tonic::server::Grpc::new(tonic_prost::ProstCodec::default()); + Ok(grpc.server_streaming(FetchJwtBundles(api), request).await) + }), + _ => Box::pin(async move { + let mut response = http::Response::new(TonicBody::empty()); + response.headers_mut().insert( + tonic::Status::GRPC_STATUS, + (tonic::Code::Unimplemented as i32).into(), + ); + response.headers_mut().insert( + http::header::CONTENT_TYPE, + tonic::metadata::GRPC_CONTENT_TYPE, + ); + Ok(response) + }), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn supervisor_svids_verify_for_their_audience_only() { + let supervisor = WorkloadApi::new(SUPERVISOR_SUBJECT).unwrap(); + let svid = supervisor.jwt_svid(&["aud-a".to_string()]).unwrap(); + assert!(verify_supervisor_svid(&svid, "aud-a")); + assert!(!verify_supervisor_svid(&svid, "aud-b")); + + let gateway = WorkloadApi::new(GATEWAY_SUBJECT).unwrap(); + let svid = gateway.jwt_svid(&["aud-a".to_string()]).unwrap(); + assert!(!verify_supervisor_svid(&svid, "aud-a")); + } + + #[test] + fn finds_svids_in_text() { + let svid = WorkloadApi::new(SUPERVISOR_SUBJECT) + .unwrap() + .jwt_svid(&["aud".to_string()]) + .unwrap(); + assert!(contains_svid(&format!("X-Workload-Jwt: {svid}\r\n"))); + assert!(!contains_svid("a.b.c and no token")); + } +} From ed4f6cc1c820142b4a687a2bc78b84679d38d128 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:04:31 -0800 Subject: [PATCH 09/22] test(features): port provider token exchange tests to testkit Signed-off-by: Matthew Grossman --- tests/suites/features/Cargo.lock | 30 + tests/suites/features/Cargo.toml | 2 +- .../provider-token-exchange/Cargo.toml | 19 + .../tests/token_exchange.rs | 1034 +++++++++++++++++ 4 files changed, 1084 insertions(+), 1 deletion(-) create mode 100644 tests/suites/features/provider-token-exchange/Cargo.toml create mode 100644 tests/suites/features/provider-token-exchange/tests/token_exchange.rs diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index 5e9d6fc0d3..746309ca36 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -3087,6 +3087,17 @@ dependencies = [ "serde_json", ] +[[package]] +name = "provider-token-exchange" +version = "0.0.0" +dependencies = [ + "openshell-testkit", + "serde_json", + "spiffe-support", + "tokio", + "url", +] + [[package]] name = "pulldown-cmark" version = "0.13.6" @@ -3841,6 +3852,25 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spiffe-support" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "futures-util", + "hex", + "jsonwebtoken", + "openshell-crypto", + "openshell-testkit", + "prost", + "serde_json", + "tokio", + "tokio-stream", + "tonic", + "tonic-prost", + "tower", +] + [[package]] name = "spin" version = "0.9.9" diff --git a/tests/suites/features/Cargo.toml b/tests/suites/features/Cargo.toml index 5f1d30c4f6..24a024035d 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", "otlp-relay", "provider-refresh", "routable-host-ip"] +members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "oci-image", "otlp-relay", "provider-refresh", "provider-token-exchange", "routable-host-ip"] diff --git a/tests/suites/features/provider-token-exchange/Cargo.toml b/tests/suites/features/provider-token-exchange/Cargo.toml new file mode 100644 index 0000000000..76efa9b842 --- /dev/null +++ b/tests/suites/features/provider-token-exchange/Cargo.toml @@ -0,0 +1,19 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "provider-token-exchange" +description = "Features suite: provider token grants that exchange SPIFFE JWT-SVIDs at token endpoints the test runs" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/NVIDIA/OpenShell" +publish = false + +[dependencies] +openshell-testkit = { path = "../../../testkit/testkit" } +serde_json = "1" +spiffe-support = { path = "../../../support/spiffe" } +tokio = { version = "1.43", features = ["io-util", "macros", "net", "rt", "sync", "time"] } +url = "2" diff --git a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs new file mode 100644 index 0000000000..d84d4e20c0 --- /dev/null +++ b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs @@ -0,0 +1,1034 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Provider token grants: the gateway and the supervisor exchange SPIFFE +//! JWT-SVIDs at token endpoints the test runs, and the supervisor injects the +//! results into requests to a protected target. +//! +//! The gateway and supervisors fetch JWT-SVIDs from Workload APIs the test +//! runs ([`spiffe_support`]). The token endpoints listen on loopback, which +//! both the gateway and Podman's host-network supervisors reach and which the +//! token endpoint transport policy allows over plain HTTP. The targets listen +//! on every address, for sandboxes to reach through `host.openshell.internal`. +//! Tests never print the fixture tokens, though none are real. + +use std::collections::HashMap; +use std::future::Future; +use std::net::{Ipv4Addr, SocketAddr}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use serde_json::json; +use spiffe_support::{ISSUER, SUPERVISOR_SUBJECT, WorkloadApis, verify_supervisor_svid}; +use testkit::{Context, Error, Poll, Result, ResultExt as _, Sandbox, poll_until}; +use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; +use tokio::net::{TcpListener, TcpStream}; + +const TEST_HOST: &str = "host.openshell.internal"; +const USER_SUBJECT_TOKEN: &str = "stored-user-token"; +const INTERMEDIATE_TOKEN: &str = "intermediate-token"; +const FINAL_ACCESS_TOKEN: &str = "final-access-token"; +const TOKEN_TYPE_ACCESS_TOKEN: &str = "urn:ietf:params:oauth:token-type:access_token"; +const CLIENT_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe"; +const IDENTITY_AUDIENCE: &str = "identity-proxy"; +const IDENTITY_JWT_AUDIENCE: &str = "https://identity.openshell-e2e.test"; +const IDENTITY_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; +const SUBJECT_TOKEN_ENV: &str = "subject_token"; + +/// Two sandboxes, each with its own provider, request the same host and +/// port at the same time. Each request carries its provider's bearer token, +/// from a two-stage token exchange, and its own signed JWT-SVID, from a +/// client-credentials grant; the target checks both. Repeat requests use the +/// cached credentials. A failed grant returns 502 and sends the target no +/// bytes, and the other credential stays cached. No credential reaches the +/// workload. +#[testkit::test] +async fn independent_grants_across_sandboxes(cx: &mut Context) -> testkit::Result { + let apis = WorkloadApis::start().await?; + let observations = Arc::new(GrantObservations::default()); + let (token_listener, token_port) = listen(Ipv4Addr::LOCALHOST).await?; + let (identity_listener, identity_port) = listen(Ipv4Addr::LOCALHOST).await?; + let (target_listener, target_port) = listen(Ipv4Addr::UNSPECIFIED).await?; + let _token = serve(token_listener, { + let observations = Arc::clone(&observations); + move |stream| exchange_token(stream, Arc::clone(&observations)) + }); + let _identity = serve(identity_listener, { + let observations = Arc::clone(&observations); + move |stream| issue_identity(stream, Arc::clone(&observations)) + }); + let _target = serve(target_listener, { + let observations = Arc::clone(&observations); + move |stream| protected_target(stream, Arc::clone(&observations)) + }); + + let mut sandboxes = Vec::new(); + for instance in ["a", "b"] { + let provider = cx.name(&format!("grants-{instance}")); + let profile_type = cx + .import_profile(&grants_profile( + &provider, + token_port, + identity_port, + target_port, + instance, + )) + .await?; + let subject = format!("{USER_SUBJECT_TOKEN}-{instance}"); + cx.create_provider(&provider, &profile_type, &[(SUBJECT_TOKEN_ENV, &subject)]) + .await?; + sandboxes.push( + cx.sandbox(&format!("pte{instance}")) + .image(testkit::python_image()) + .providers([provider.as_str()]) + .create_ready() + .await?, + ); + } + let [a, b] = &sandboxes[..] else { + unreachable!("two sandboxes") + }; + + for round in ["first", "cached"] { + let (from_a, from_b) = tokio::join!( + probe(a, target_port, "/resource/a", false), + probe(b, target_port, "/resource/b", false), + ); + from_a.context(format!("the {round} request from sandbox A"))?; + from_b.context(format!("the {round} request from sandbox B"))?; + if round == "first" { + let issued = observations.issued(); + testkit::ensure!( + issued + .iter() + .all(|(service, identity)| *service > 0 && *identity > 0), + "each provider did not acquire both credentials: {issued:?}" + ); + } + } + let issued = observations.issued(); + testkit::ensure!( + observations.target_rejected.load(Ordering::SeqCst) == 0, + "the target rejected a request with mismatched or untrusted credentials, even if a retry then passed" + ); + // The first round's check passed, so any difference is the second round. + testkit::ensure!( + observations.issued() == issued, + "repeat requests acquired credentials again instead of using the caches" + ); + + let target_requests = observations.target_requests.load(Ordering::SeqCst); + // An audience override forces acquisition of only the failing credential; + // the other stays cached from the successful requests. + let (from_a, from_b) = tokio::join!( + probe(a, target_port, "/deny-service/a", true), + probe(b, target_port, "/deny-identity/b", true), + ); + from_a.context("the request from sandbox A whose service grant fails")?; + from_b.context("the request from sandbox B whose identity grant fails")?; + testkit::ensure!( + observations.service_denied.load(Ordering::SeqCst) > 0, + "the token endpoint saw no request for the denied service audience" + ); + testkit::ensure!( + observations.identity_denied.load(Ordering::SeqCst) > 0, + "the identity endpoint saw no request for the denied identity audience" + ); + testkit::ensure!( + observations.target_requests.load(Ordering::SeqCst) == target_requests, + "a failed grant forwarded request bytes to the target" + ); + apis.shutdown().await; + Ok(()) +} + +/// A sandbox with two providers, each bound to its own path, reaches one +/// target. A transient grant failure on B returns 502 with a request ID the +/// token endpoint also saw, closes the tunnel, and shows in the sandbox's +/// status as a retryable failure. Then requests to A, B and A on one client +/// connection each carry only their own route's token, over one upstream +/// connection, and the success clears the reported failure. The failed +/// grant sends the target nothing. +#[testkit::test] +async fn routes_recover_and_select_a_b_a_on_one_connection(cx: &mut Context) -> testkit::Result { + let apis = WorkloadApis::start().await?; + let grants = Arc::new(RouteGrantState::default()); + let observed = Arc::new(Mutex::new(Vec::new())); + let observed_bytes = Arc::new(AtomicUsize::new(0)); + let (token_listener, token_port) = listen(Ipv4Addr::LOCALHOST).await?; + let (target_listener, target_port) = listen(Ipv4Addr::UNSPECIFIED).await?; + let _token = serve(token_listener, { + let grants = Arc::clone(&grants); + move |stream| route_token(stream, Arc::clone(&grants)) + }); + let target = RouteTarget::start( + target_listener, + Arc::clone(&observed), + Arc::clone(&observed_bytes), + ); + + let mut providers = Vec::new(); + for route in ["a", "b"] { + let provider = cx.name(&format!("route-{route}")); + let profile_type = cx + .import_profile(&route_profile(&provider, token_port, target_port, route)) + .await?; + cx.create_provider( + &provider, + &profile_type, + &[(SUBJECT_TOKEN_ENV, &format!("stored-{route}"))], + ) + .await?; + providers.push(provider); + } + let sandbox = cx + .sandbox("pter") + .image(testkit::python_image()) + .providers(providers.iter().map(String::as_str)) + .create_ready() + .await?; + + grants.fail_next_b.store(true, Ordering::SeqCst); + // The supervisor mediates direct workload connections as CONNECT. + // HTTPConnection keeps one client socket for the A/B/A run. + let failure_script = format!( + r#"import http.client, uuid +first = http.client.HTTPConnection({TEST_HOST:?}, {target_port}, timeout=10) +first.request('GET', '/b/failure', headers={{'Authorization': 'Bearer stale-value'}}) +failed = first.getresponse() +failed.read() +assert failed.status == 502, 'the controlled grant failure must return 502' +request_id = failed.getheader('x-openshell-request-id', '') +assert str(uuid.UUID(request_id)) == request_id, 'the refusal must carry a canonical request ID' +print('failed-request-id=' + request_id) +assert failed.will_close, 'the failed tunnel must close' +first.close() +"# + ); + let recovery_script = format!( + r#"import http.client +recovered = http.client.HTTPConnection({TEST_HOST:?}, {target_port}, timeout=10) +connection = None +for path in ['/a/first', '/b/second', '/a/third']: + recovered.request('GET', path, headers={{'Authorization': 'Bearer stale-value'}}) + if connection is None: + connection = recovered.sock + assert recovered.sock is connection, 'client connection was replaced' + response = recovered.getresponse() + response.read() + assert response.status == 200, 'upstream rejected the selected credential' + assert recovered.sock is connection and connection.fileno() >= 0, 'keepalive connection closed' +recovered.close() +print('route-recovery-a-b-a-ok') +"# + ); + + let failed = sandbox.run_python(&failure_script, &[]).await?; + let request_id = failed + .stdout + .lines() + .find_map(|line| line.strip_prefix("failed-request-id=")) + .ok_or_else(|| Error::msg("the workload did not print the refusal's request ID"))? + .to_string(); + // An authorized reader sees the cause of the refused grant. + let reported = wait_for_grant_failure(&sandbox, true).await?; + let recovered = sandbox.run_python(&recovery_script, &[]).await?; + testkit::ensure!( + recovered.stdout.contains("route-recovery-a-b-a-ok"), + "the A/B/A requests did not finish: {}", + recovered.stdout + ); + // The matching grant's later success clears it. + wait_for_grant_failure(&sandbox, false).await?; + sandbox.delete().await?; + sandbox.wait_absent(Duration::from_secs(60)).await?; + target + .drain() + .await + .context("the route target saw EOF on every accepted connection")?; + apis.shutdown().await; + + testkit::ensure!( + grants.failed_request_id.lock().expect("lock").as_deref() == Some(request_id.as_str()), + "the token endpoint and the refused response named different exchanges" + ); + let expected_failure = [ + ("request_id", json!(request_id)), + ("code", json!("unavailable")), + ("recovery_action", json!("retry")), + ("stage", json!("token_endpoint")), + ("upstream_http_status", json!(503)), + ("provider", json!(providers[1])), + ("credential_key", json!("access_token")), + ]; + testkit::ensure!( + reported["destination_port"] == json!(target_port), + "the reported failure names destination port {}, not {target_port}", + reported["destination_port"] + ); + for (key, expected) in expected_failure { + testkit::ensure!( + reported["failure"][key] == expected, + "the reported failure's {key} is {}, not {expected}", + reported["failure"][key] + ); + } + + let requests = observed.lock().expect("lock"); + let summary: Vec<(usize, &str)> = requests + .iter() + .map(|request| (request.connection, request.path.as_str())) + .collect(); + testkit::ensure!( + requests.len() == 3, + "the target saw {summary:?}; the failed grant must not reach it" + ); + testkit::ensure!( + observed_bytes.load(Ordering::Relaxed) + == requests.iter().map(|request| request.bytes).sum::(), + "part of the failed request reached the target" + ); + for ((request, path), token) in requests + .iter() + .zip(["/a/first", "/b/second", "/a/third"]) + .zip(["Bearer final-a", "Bearer final-b", "Bearer final-a"]) + { + testkit::ensure!( + request.path == path && request.connection == requests[0].connection, + "the target saw {summary:?}; expected the A/B/A paths on one upstream connection" + ); + testkit::ensure!( + request.authorization.len() == 1 && request.authorization[0] == token, + "{path} did not carry exactly its own route's token" + ); + } + let exchanges = grants.supervisor_requests.lock().expect("lock").clone(); + testkit::ensure!( + exchanges == ["b", "a", "b"], + "the supervisor exchanged tokens for routes {exchanges:?}; expected B (failed), A, B and A from its cache" + ); + Ok(()) +} + +#[derive(Default)] +struct GrantObservations { + service_issued: [AtomicUsize; 2], + identity_issued: [AtomicUsize; 2], + service_denied: AtomicUsize, + identity_denied: AtomicUsize, + target_requests: AtomicUsize, + target_rejected: AtomicUsize, +} + +impl GrantObservations { + fn issued(&self) -> [(usize, usize); 2] { + std::array::from_fn(|index| { + ( + self.service_issued[index].load(Ordering::SeqCst), + self.identity_issued[index].load(Ordering::SeqCst), + ) + }) + } +} + +/// The gateway's and the supervisor's token exchanges. The gateway trades +/// the stored subject token for an intermediate token addressed to the +/// supervisor's SPIFFE ID; the supervisor trades that for the final token. +async fn exchange_token(mut stream: TcpStream, observations: Arc) { + let Some(request) = read_http_request(&mut stream).await else { + return; + }; + let form = token_form(&request); + let field = |name: &str| form.get(name).map_or("", String::as_str); + let valid = request.starts_with("POST /token ") + && field("grant_type") == "urn:ietf:params:oauth:grant-type:token-exchange" + && field("client_assertion_type") == CLIENT_ASSERTION_TYPE + && field("subject_token_type") == TOKEN_TYPE_ACCESS_TOKEN + && field("requested_token_type") == TOKEN_TYPE_ACCESS_TOKEN + && !field("client_assertion").is_empty(); + let mut access_token = None; + for (index, instance) in ["a", "b"].into_iter().enumerate() { + if !valid { + break; + } + if field("subject_token") == format!("{USER_SUBJECT_TOKEN}-{instance}") + && field("audience") == SUPERVISOR_SUBJECT + && field("scope").is_empty() + { + access_token = Some(format!("{INTERMEDIATE_TOKEN}-{instance}")); + } else if field("subject_token") == format!("{INTERMEDIATE_TOKEN}-{instance}") + && field("scope") == "service.read" + { + if field("audience") == format!("service-{instance}") { + observations.service_issued[index].fetch_add(1, Ordering::SeqCst); + access_token = Some(format!("{FINAL_ACCESS_TOKEN}-{instance}")); + } else if field("audience") == format!("denied-service-{instance}") { + observations.service_denied.fetch_add(1, Ordering::SeqCst); + } + } + } + write_token_response(&mut stream, access_token.as_deref(), 600).await; +} + +/// A client-credentials grant that checks the supervisor's JWT-SVID and +/// returns it as the access token. No new grant type or sandbox-visible +/// credential is needed to exercise custom-header injection. +async fn issue_identity(mut stream: TcpStream, observations: Arc) { + let Some(request) = read_http_request(&mut stream).await else { + return; + }; + let form = token_form(&request); + let field = |name: &str| form.get(name).map_or("", String::as_str); + let mut access_token = None; + for (index, instance) in ["a", "b"].into_iter().enumerate() { + let valid = request.starts_with("POST /identity-token ") + && field("grant_type") == "client_credentials" + && field("client_assertion_type") == IDENTITY_ASSERTION_TYPE + && field("scope") == "identity.read" + && verify_supervisor_svid(field("client_assertion"), &identity_jwt_audience(instance)); + if valid && field("audience") == format!("{IDENTITY_AUDIENCE}-{instance}") { + observations.identity_issued[index].fetch_add(1, Ordering::SeqCst); + access_token = Some(field("client_assertion")); + } else if valid && field("audience") == format!("denied-identity-{instance}") { + observations.identity_denied.fetch_add(1, Ordering::SeqCst); + } + } + write_token_response(&mut stream, access_token, 900).await; +} + +/// Accepts `GET /resource/` only with exactly one bearer token and +/// one JWT-SVID, both for that instance. +async fn protected_target(mut stream: TcpStream, observations: Arc) { + // Count any request bytes, including an incomplete header. A failed + // grant may open a TCP stream but must send no request. + let mut byte = [0_u8; 1]; + if !matches!( + tokio::time::timeout(Duration::from_secs(5), stream.peek(&mut byte)).await, + Ok(Ok(1)) + ) { + return; + } + observations.target_requests.fetch_add(1, Ordering::SeqCst); + let Some(request) = read_http_request(&mut stream).await else { + return; + }; + let headers = request.split("\r\n\r\n").next().unwrap_or_default(); + let header_values = |name: &str| { + headers + .lines() + .filter_map(|line| line.split_once(':')) + .filter(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.trim()) + .collect::>() + }; + let bearer = header_values("authorization"); + let identity = header_values("x-workload-jwt"); + let ok = ["a", "b"].into_iter().any(|instance| { + request.starts_with(&format!("GET /resource/{instance} ")) + && bearer.len() == 1 + && bearer[0] == format!("Bearer {FINAL_ACCESS_TOKEN}-{instance}") + && identity.len() == 1 + && verify_supervisor_svid(identity[0], &identity_jwt_audience(instance)) + }); + let (status, body) = if ok { + ("HTTP/1.1 200 OK", "independent-grants-ok") + } else { + // Keep the rejection even if the workload retries and a later + // request gets the right credentials. + observations.target_rejected.fetch_add(1, Ordering::SeqCst); + ( + "HTTP/1.1 401 Unauthorized", + "credential-verification-failed", + ) + }; + let response = format!( + "{status}\r\ncontent-type: text/plain\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); + let _ = stream.write_all(response.as_bytes()).await; +} + +fn identity_jwt_audience(instance: &str) -> String { + format!("{IDENTITY_JWT_AUDIENCE}/{instance}") +} + +/// Request `path` from the target with agent-supplied credentials the +/// supervisor must replace, and fail if any credential reaches the workload. +/// `expect_denied` expects the supervisor's 502 refusal with a request ID. +/// Retries while the exec fails, as when a grant is still settling. +async fn probe(sandbox: &Sandbox, target_port: u16, path: &str, expect_denied: bool) -> Result { + let url = format!("http://{TEST_HOST}:{target_port}{path}"); + let expect_denied_python = if expect_denied { "True" } else { "False" }; + let expected = if expect_denied { + "grant-denied" + } else { + "independent-grants-ok" + }; + // The script prints fixed markers only, so its output never holds a + // credential. + let script = format!( + r#"import base64, json, os, re, urllib.error, urllib.request, uuid + +def contains_credential(value): + if any(marker in value for marker in ( + "stored-user-token", "intermediate-token", "final-access-token", "openshell:resolve:" + )): + return True + for token in re.findall(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", value): + try: + payload = token.split(".")[1] + claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + if claims.get("iss") == "{ISSUER}": + return True + except (ValueError, UnicodeError, AttributeError): + pass + return False + +if any(contains_credential(value) for value in os.environ.values()): + raise SystemExit("provider credential material reached the workload environment") +request = urllib.request.Request({url:?}, headers={{ + "Authorization": "Bearer agent-supplied", + "X-Workload-Jwt": "agent-supplied", +}}) +try: + with urllib.request.urlopen(request, timeout=10) as response: + body = response.read().decode() + if contains_credential(body): + raise SystemExit("provider credential material reached the workload response") + if {expect_denied_python}: + raise SystemExit("failed grant unexpectedly reached the target") + print(body) +except urllib.error.HTTPError as error: + body = error.read().decode() + if contains_credential(body): + raise SystemExit("provider credential material reached the workload error") + if not {expect_denied_python} or error.code != 502: + raise SystemExit("unexpected HTTP status " + str(error.code)) + # The refusal names the exchange with an opaque ID and nothing else. + request_id = error.headers.get("x-openshell-request-id", "") + if str(uuid.UUID(request_id)) != request_id: + raise SystemExit("refusal did not carry a canonical request ID") + print("grant-denied") +"# + ); + let output = sandbox + .poll_exec( + &format!("{path} to answer from sandbox {}", sandbox.name()), + Duration::from_secs(20), + ["python3", "-c", &script], + |output| output.exit_code == 0, + ) + .await?; + testkit::ensure!( + output.stdout.trim() == expected, + "{path} from sandbox {} printed {:?}, not {expected}", + sandbox.name(), + output.stdout.trim() + ); + Ok(()) +} + +/// A profile with two grants for one request: a token-exchange bearer token +/// and a client-credentials JWT-SVID header. Each has a path whose audience +/// the token endpoints deny. +fn grants_profile( + profile_type: &str, + token_port: u16, + identity_port: u16, + target_port: u16, + instance: &str, +) -> String { + let token_endpoint = format!("http://127.0.0.1:{token_port}/token"); + let identity_jwt_audience = identity_jwt_audience(instance); + format!( + r"id: {profile_type} +display_name: Token exchange test +description: Independent bearer and JWT-SVID grants for one request +category: other +credentials: + - name: subject_token + description: Stored user subject token + required: true + - name: access_token + description: Access token obtained through token exchange + required: false + auth_style: bearer + header_name: Authorization + token_grant: + grant_type: token_exchange + token_endpoint: {token_endpoint} + audience: service-{instance} + scopes: [service.read] + jwt_svid_audience: {token_endpoint} + client_assertion_type: {CLIENT_ASSERTION_TYPE} + requested_token_type: {TOKEN_TYPE_ACCESS_TOKEN} + cache_ttl_seconds: 300 + audience_overrides: + - path: /deny-service/{instance} + audience: denied-service-{instance} + subject_token: + source: provider_credential + credential: subject_token + subject_token_type: {TOKEN_TYPE_ACCESS_TOKEN} + - name: workload_identity + description: Signed workload identity for the identity proxy + required: false + auth_style: header + header_name: X-Workload-Jwt + token_grant: + grant_type: client_credentials + token_endpoint: http://127.0.0.1:{identity_port}/identity-token + audience: {IDENTITY_AUDIENCE}-{instance} + scopes: [identity.read] + jwt_svid_audience: {identity_jwt_audience} + client_assertion_type: {IDENTITY_ASSERTION_TYPE} + cache_ttl_seconds: 600 + audience_overrides: + - path: /deny-identity/{instance} + audience: denied-identity-{instance} +{}", + endpoints(target_port, "/**") + ) +} + +/// A profile with one token-exchange bearer grant bound to `//**`. +/// Each route has its own audience, so the token endpoint can tell which +/// endpoint's grant the supervisor selected. +fn route_profile(profile_type: &str, token_port: u16, target_port: u16, route: &str) -> String { + let token_endpoint = format!("http://127.0.0.1:{token_port}/token"); + format!( + r"id: {profile_type} +display_name: Token exchange route test +description: Route-bound bearer grant +category: other +credentials: + - name: subject_token + description: Stored user subject token + required: true + - name: access_token + description: Access token obtained through token exchange + required: false + auth_style: bearer + header_name: Authorization + token_grant: + grant_type: token_exchange + token_endpoint: {token_endpoint} + audience: audience-{route} + jwt_svid_audience: {token_endpoint} + client_assertion_type: {CLIENT_ASSERTION_TYPE} + requested_token_type: {TOKEN_TYPE_ACCESS_TOKEN} + cache_ttl_seconds: 300 + subject_token: + source: provider_credential + credential: subject_token + subject_token_type: {TOKEN_TYPE_ACCESS_TOKEN} +{}", + endpoints(target_port, &format!("/{route}/**")) + ) +} + +fn endpoints(target_port: u16, path: &str) -> String { + format!( + r"endpoints: + - host: {TEST_HOST} + port: {target_port} + path: {path} + protocol: rest + access: read-write + enforcement: enforce + allowed_ips: + - 10.0.0.0/8 + - 169.254.0.0/16 + - 172.0.0.0/8 + - 192.168.0.0/16 +binaries: + - /** +" + ) +} + +/// Poll the sandbox's status until its last token-grant failure is present +/// or absent, and return it. +async fn wait_for_grant_failure(sandbox: &Sandbox, present: bool) -> Result { + let what = if present { + "to report a token-grant failure" + } else { + "to clear its token-grant failure" + }; + poll_until( + &format!("sandbox {} {what}", sandbox.name()), + Duration::from_secs(30), + Duration::from_secs(1), + async || { + let failure = sandbox.get_json().await?["last_token_grant_failure"].clone(); + Ok(if failure.is_null() == present { + Poll::Pending(format!("last_token_grant_failure is {failure}")) + } else { + Poll::Ready(failure) + }) + }, + ) + .await +} + +#[derive(Default)] +struct RouteGrantState { + fail_next_b: AtomicBool, + supervisor_requests: Mutex>, + failed_request_id: Mutex>, +} + +/// The route grants' token endpoint. It records each supervisor exchange's +/// route, and fails the next one for B with a 503 when `fail_next_b` is set. +async fn route_token(mut stream: TcpStream, state: Arc) { + let Ok(Some(request)) = read_route_request(&mut stream, None).await else { + return; + }; + let form = token_form(&request); + let field = |name: &str| form.get(name).map_or("", String::as_str); + let subject = field("subject_token"); + let route = match subject { + "stored-a" | "intermediate-a" => "a", + "stored-b" | "intermediate-b" => "b", + _ => "", + }; + let supervisor = subject.starts_with("intermediate-"); + // The gateway's exchange targets the supervisor's SPIFFE ID; the + // supervisor's targets the route's audience. + let valid = !route.is_empty() + && request.starts_with("POST /token ") + && !field("client_assertion").is_empty() + && !field("audience").is_empty() + && (!supervisor || field("audience") == format!("audience-{route}")); + let fail = if valid && supervisor { + state + .supervisor_requests + .lock() + .expect("lock") + .push(route.to_owned()); + route == "b" && state.fail_next_b.swap(false, Ordering::SeqCst) + } else { + false + }; + let (status, body) = if fail { + let request_id = request + .split_once("\r\n\r\n") + .map(|(headers, _)| headers) + .unwrap_or_default() + .lines() + .filter_map(|line| line.split_once(':')) + .find(|(name, _)| name.eq_ignore_ascii_case("x-openshell-request-id")) + .map(|(_, value)| value.trim().to_owned()); + *state.failed_request_id.lock().expect("lock") = request_id; + ( + "HTTP/1.1 503 Service Unavailable", + json!({"error": "temporary_failure"}).to_string(), + ) + } else if valid { + let stage = if supervisor { "final" } else { "intermediate" }; + ( + "HTTP/1.1 200 OK", + json!({"access_token": format!("{stage}-{route}"), "token_type": "Bearer", "expires_in": 300}) + .to_string(), + ) + } else { + ( + "HTTP/1.1 400 Bad Request", + json!({"error": "unexpected_route_exchange"}).to_string(), + ) + }; + let response = format!( + "{status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + let _ = tokio::time::timeout( + Duration::from_secs(5), + stream.write_all(response.as_bytes()), + ) + .await; +} + +struct RouteTargetRequest { + connection: usize, + path: String, + authorization: Vec, + bytes: usize, +} + +/// The route grants' target. It keeps each connection open across requests +/// and records every byte it reads, so draining it proves that nothing else +/// arrived. +struct RouteTarget { + stop: Option>, + task: tokio::task::JoinHandle>, +} + +impl RouteTarget { + fn start( + listener: TcpListener, + observed: Arc>>, + observed_bytes: Arc, + ) -> Self { + let (stop, mut stopped) = tokio::sync::oneshot::channel(); + let task = tokio::spawn(async move { + let next_connection = AtomicUsize::new(1); + let mut connections = tokio::task::JoinSet::new(); + let mut completed = Vec::new(); + loop { + tokio::select! { + // Once the workload has closed, accept queued connections + // before stopping so their buffered bytes are observed too. + biased; + accepted = listener.accept() => { + let (stream, _) = accepted + .map_err(|error| format!("route target accept failed: {error}"))?; + let connection = next_connection.fetch_add(1, Ordering::Relaxed); + connections.spawn(route_connection( + stream, + connection, + Arc::clone(&observed), + Arc::clone(&observed_bytes), + )); + } + _ = &mut stopped => break, + Some(result) = connections.join_next(), if !connections.is_empty() => { + completed.push(result); + } + } + } + drop(listener); + // Only EOF proves that the byte count includes everything sent on + // each accepted connection, so wait for every reader. + while let Some(result) = connections.join_next().await { + completed.push(result); + } + for result in completed { + result.map_err(|error| format!("route target reader task failed: {error}"))??; + } + Ok(()) + }); + Self { + stop: Some(stop), + task, + } + } + + /// Stop accepting, then wait for every connection to reach EOF. + async fn drain(mut self) -> Result { + if let Some(stop) = self.stop.take() { + // A closed receiver means the task already stopped; joining still + // reports its error. + let _ = stop.send(()); + } + tokio::time::timeout(Duration::from_secs(35), &mut self.task) + .await + .map_err(|_| Error::msg("the route target did not drain its connections"))? + .map_err(|error| Error::msg(format!("the route target task failed: {error}")))? + .map_err(Error::msg) + } +} + +impl Drop for RouteTarget { + fn drop(&mut self) { + self.task.abort(); + } +} + +async fn route_connection( + mut stream: TcpStream, + connection: usize, + observed: Arc>>, + observed_bytes: Arc, +) -> std::result::Result<(), String> { + while let Some(request) = read_route_request(&mut stream, Some(&observed_bytes)).await? { + let path = request + .lines() + .next() + .and_then(|line| line.split_whitespace().nth(1)) + .unwrap_or_default() + .to_owned(); + let authorization = request + .lines() + .filter_map(|line| line.split_once(':')) + .filter(|(name, _)| name.eq_ignore_ascii_case("authorization")) + .map(|(_, value)| value.trim().to_owned()) + .collect::>(); + let expected = if path.starts_with("/a/") { + "Bearer final-a" + } else { + "Bearer final-b" + }; + let valid = authorization.len() == 1 && authorization[0] == expected; + observed.lock().expect("lock").push(RouteTargetRequest { + connection, + path, + authorization, + bytes: request.len(), + }); + let status = if valid { + "HTTP/1.1 200 OK" + } else { + "HTTP/1.1 401 Unauthorized" + }; + let response = format!("{status}\r\nContent-Length: 0\r\n\r\n"); + tokio::time::timeout( + Duration::from_secs(5), + stream.write_all(response.as_bytes()), + ) + .await + .map_err(|_| "route target response write timed out".to_owned())? + .map_err(|error| format!("route target response write failed: {error}"))?; + } + Ok(()) +} + +async fn listen(ip: Ipv4Addr) -> Result<(TcpListener, u16)> { + let listener = TcpListener::bind(SocketAddr::from((ip, 0))) + .await + .context(format!("listen on {ip}"))?; + let port = listener + .local_addr() + .context("read the listener's port")? + .port(); + Ok((listener, port)) +} + +/// Handle each connection `listener` accepts with `handle`, until dropped. +struct Served(tokio::task::JoinHandle<()>); + +impl Drop for Served { + fn drop(&mut self) { + self.0.abort(); + } +} + +fn serve(listener: TcpListener, handle: F) -> Served +where + F: Fn(TcpStream) -> Fut + Send + 'static, + Fut: Future + Send + 'static, +{ + Served(tokio::spawn(async move { + while let Ok((stream, _)) = listener.accept().await { + let _ = stream.set_nodelay(true); + tokio::spawn(handle(stream)); + } + })) +} + +/// Read one bounded request framed by Content-Length. Forms and JWT headers +/// can span TCP reads. +async fn read_http_request(stream: &mut TcpStream) -> Option { + tokio::time::timeout(Duration::from_secs(5), async { + let mut request = Vec::new(); + let mut buffer = [0_u8; 4096]; + loop { + let length = stream.read(&mut buffer).await.ok()?; + if length == 0 || request.len() + length > 32 * 1024 { + return None; + } + request.extend_from_slice(&buffer[..length]); + if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") { + let headers = std::str::from_utf8(&request[..end]).ok()?; + let content_length = headers + .lines() + .filter_map(|line| line.split_once(':')) + .find(|(name, _)| name.eq_ignore_ascii_case("content-length")) + .map_or(Some(0), |(_, value)| value.trim().parse::().ok())?; + if request.len() >= end.checked_add(4)?.checked_add(content_length)? { + return String::from_utf8(request).ok(); + } + } + } + }) + .await + .ok() + .flatten() +} + +/// Read one whole request without consuming the next one on a keepalive +/// connection, counting the bytes read in `observed_bytes`. `None` is a +/// clean EOF. +async fn read_route_request( + stream: &mut TcpStream, + observed_bytes: Option<&AtomicUsize>, +) -> std::result::Result, String> { + tokio::time::timeout(Duration::from_secs(30), async { + let mut bytes = Vec::new(); + while !bytes.ends_with(b"\r\n\r\n") { + let mut byte = [0]; + if stream + .read(&mut byte) + .await + .map_err(|error| error.to_string())? + == 0 + { + return if bytes.is_empty() { + Ok(None) + } else { + Err("partial fixture header".into()) + }; + } + bytes.push(byte[0]); + if let Some(observed) = observed_bytes { + observed.fetch_add(1, Ordering::Relaxed); + } + if bytes.len() > 16 * 1024 { + return Err("fixture header exceeds limit".into()); + } + } + let header = std::str::from_utf8(&bytes).map_err(|error| error.to_string())?; + let length = header + .lines() + .filter_map(|line| line.split_once(':')) + .find(|(name, _)| name.eq_ignore_ascii_case("content-length")) + .map(|(_, value)| value.trim().parse::()) + .transpose() + .map_err(|error| error.to_string())? + .unwrap_or(0); + if length > 64 * 1024 { + return Err("fixture body exceeds limit".into()); + } + let header_len = bytes.len(); + bytes.resize(header_len + length, 0); + stream + .read_exact(&mut bytes[header_len..]) + .await + .map_err(|error| error.to_string())?; + if let Some(observed) = observed_bytes { + observed.fetch_add(length, Ordering::Relaxed); + } + String::from_utf8(bytes) + .map(Some) + .map_err(|error| error.to_string()) + }) + .await + .map_err(|_| "fixture request timed out".to_owned())? +} + +fn token_form(request: &str) -> HashMap { + let (_, body) = request.split_once("\r\n\r\n").unwrap_or_default(); + url::form_urlencoded::parse(body.as_bytes()) + .into_owned() + .collect() +} + +async fn write_token_response(stream: &mut TcpStream, access_token: Option<&str>, ttl: u64) { + let (status, body) = if let Some(access_token) = access_token { + ( + "HTTP/1.1 200 OK", + json!({"access_token": access_token, "token_type": "Bearer", "expires_in": ttl}) + .to_string(), + ) + } else { + ( + "HTTP/1.1 400 Bad Request", + json!({"error": "invalid_grant"}).to_string(), + ) + }; + let response = format!( + "{status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", + body.len() + ); + let _ = stream.write_all(response.as_bytes()).await; +} From 1147ce8cf1a204702ef34f5d26dcba9df62c9efc Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:09:08 -0800 Subject: [PATCH 10/22] test(tmachine): add an additional destination CA environment Signed-off-by: Matthew Grossman --- tests/support/README.md | 4 +- .../ansible/playbooks/additional-ca.yaml | 90 +++++++++++++++++++ tests/tmachine/config.nix | 6 ++ 3 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 tests/tmachine/ansible/playbooks/additional-ca.yaml diff --git a/tests/support/README.md b/tests/support/README.md index 72a7924ceb..7493ce83fb 100644 --- a/tests/support/README.md +++ b/tests/support/README.md @@ -29,8 +29,8 @@ never skips it. Add a row when you add a variable. The runner also sets | `OPENSHELL_TEST_OTLP_ENDPOINT` | `-otlp` | `otlp-support` | The collector endpoint in the gateway's `[openshell.gateway.otlp]`, which also enables the agent trace relay. Tests check that sandboxes never see it. | | `OPENSHELL_TEST_SPIFFE_GATEWAY_LISTEN` | `-spiffe` (`playbooks/spiffe.yaml`) | `spiffe-support` | The Unix socket the test's gateway Workload API listens on. The gateway's `OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET` names it. | | `OPENSHELL_TEST_SPIFFE_SUPERVISOR_LISTEN` | `-spiffe` | `spiffe-support` | The TCP address the test's supervisor Workload API listens on, such as `0.0.0.0:17690`. The driver's `provider_spiffe_workload_api_socket` reaches it as `tcp:127.0.0.1:`. | -| `OPENSHELL_TEST_ADDITIONAL_CA_CERT` | The additional-CA environment, which sets `openshell.supervisor.network.additional_ca_bundle` (added by #5729) | `host-server-support` (`TestCa::from_env`) | The path of the CA certificate, in PEM, that the supervisor trusts for sandbox egress. | -| `OPENSHELL_TEST_ADDITIONAL_CA_KEY` | The additional-CA environment | `host-server-support` (`TestCa::from_env`) | The path of that CA's private key, in PEM, readable by the test user. Tests sign server certificates with it. | +| `OPENSHELL_TEST_ADDITIONAL_CA_CERT` | `-additional-ca` (`playbooks/additional-ca.yaml`), which sets `openshell.supervisor.network.additional_ca_bundle` | `host-server-support` (`TestCa::from_env`) | The path of the CA certificate, in PEM, that the supervisor trusts for sandbox egress. | +| `OPENSHELL_TEST_ADDITIONAL_CA_KEY` | `-additional-ca` | `host-server-support` (`TestCa::from_env`) | The path of that CA's private key, in PEM, readable by the test user. Tests sign server certificates with it. | | `OPENSHELL_TEST_BASE_IMAGE` | Optional; you, for example to use a mirror | `testkit::base_image()` | The default sandbox image. Unset, it is `nvcr.io/nvidia/base/ubuntu:24.04`. | | `OPENSHELL_TEST_PYTHON_IMAGE` | Optional; `e2e/rust/e2e-kubernetes.sh` and `e2e-vm.sh` set a pullable image | `testkit::python_image()` | The workload image for tests that run `python3`, curl, git or openssl. Unset, it is `openshell/e2e-python:dev`, which the tmachine installers load. | | `OPENSHELL_TEST_UNSUPPORTED` | CI and `e2e/support/conformance.sh` derive it from `tests/suites/unsupported.yaml` with `tasks/scripts/suite-unsupported.sh` | testkit programs | Tests the environment can't pass yet, as `=` entries. See [Unsupported tests](../testkit/README.md#unsupported-tests). | diff --git a/tests/tmachine/ansible/playbooks/additional-ca.yaml b/tests/tmachine/ansible/playbooks/additional-ca.yaml new file mode 100644 index 0000000000..e884157845 --- /dev/null +++ b/tests/tmachine/ansible/playbooks/additional-ca.yaml @@ -0,0 +1,90 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Make a CA that sandboxes trust for egress (`additional_ca_bundle`), and +# publish its certificate and key so tests can sign certificates for the TLS +# servers they run. The key stays on the test VM; only tests read it. The +# host-server fixture (TestCa::from_env in tests/support/host-server) reads +# the variables published below. +--- +- name: Additional destination CA for tests + hosts: all + gather_facts: false + vars: + additional_ca_directory: /var/lib/openshell-test/additional-ca + additional_ca_cert: "{{ additional_ca_directory }}/ca.pem" + additional_ca_key: "{{ additional_ca_directory }}/ca.key" + tasks: + - name: Wait for SSH + ansible.builtin.wait_for_connection: + + - name: Create the additional CA directory + become: true + ansible.builtin.file: + path: "{{ additional_ca_directory }}" + state: directory + owner: tmachine + group: tmachine + mode: "0755" + + # The gateway reads the certificate as its own user, which may be root + # or tmachine. Only tmachine, which runs the tests, reads the key. + - name: Generate the additional CA + become: true + become_user: tmachine + ansible.builtin.command: + argv: + - openssl + - req + - -x509 + - -newkey + - ec + - -pkeyopt + - ec_paramgen_curve:P-256 + - -nodes + - -days + - "7" + - -subj + - /CN=openshell-test-additional-ca + - -addext + - basicConstraints=critical,CA:TRUE + - -addext + - keyUsage=critical,keyCertSign,cRLSign + - -keyout + - "{{ additional_ca_key }}" + - -out + - "{{ additional_ca_cert }}" + creates: "{{ additional_ca_cert }}" + + - name: Restrict the additional CA key to the test user + become: true + ansible.builtin.file: + path: "{{ additional_ca_key }}" + owner: tmachine + group: tmachine + mode: "0600" + + - name: Let the gateway read the additional CA certificate + become: true + ansible.builtin.file: + path: "{{ additional_ca_cert }}" + owner: tmachine + group: tmachine + mode: "0644" + + - name: Trust the additional CA for sandbox egress + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: additional-ca + gateway_overrides_content: | + [openshell.supervisor.network] + additional_ca_bundle = "{{ additional_ca_cert }}" + + - name: Publish additional CA test variables + ansible.builtin.include_tasks: test-env.yaml + vars: + test_env_name: additional-ca + test_env_vars: + OPENSHELL_TEST_ADDITIONAL_CA_CERT: "{{ additional_ca_cert }}" + OPENSHELL_TEST_ADDITIONAL_CA_KEY: "{{ additional_ca_key }}" diff --git a/tests/tmachine/config.nix b/tests/tmachine/config.nix index 4f953cab7c..40a178566b 100644 --- a/tests/tmachine/config.nix +++ b/tests/tmachine/config.nix @@ -127,6 +127,12 @@ let bases = podmanBases; setup.playbooks = [ "ansible/playbooks/spiffe.yaml" ]; }; + # A CA that sandboxes trust for egress, whose key tests use to sign their + # TLS servers' certificates. + additional-ca = { + bases = dockerBases ++ podmanBases; + setup.playbooks = [ "ansible/playbooks/additional-ca.yaml" ]; + }; }; featureEnvironments = pkgs.lib.concatMap ( feature: map (base: withSetup base feature features.${feature}.setup) features.${feature}.bases From 4aad092661273a23e682950be814ff7096a4924b Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:09:14 -0800 Subject: [PATCH 11/22] ci(e2e): run provider refresh and token exchange suites Signed-off-by: Matthew Grossman --- .github/workflows/e2e-suites.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index 611a11c16f..b4e83c11c4 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -119,6 +119,9 @@ jobs: {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"connect-ssh-supervision","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootless-otlp","installer":"rpm","family":"features","package":"otlp-relay","filter":"not test(relay_is_inert_without_collector)","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"otlp-relay","filter":"test(relay_is_inert_without_collector)","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"fedora-podman-rootless-spiffe","installer":"rpm","family":"features","package":"provider-token-exchange","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"provider-refresh","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"}, From c84976c51f18e8f1b33ed95b38dac80c66bf5486 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:14:18 -0800 Subject: [PATCH 12/22] test(features): keep OTLP exit-span sandbox names within the limit Signed-off-by: Matthew Grossman --- tests/suites/features/otlp-relay/tests/otlp_relay.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/suites/features/otlp-relay/tests/otlp_relay.rs b/tests/suites/features/otlp-relay/tests/otlp_relay.rs index 6c9f3db2ed..23eeb1e4d2 100644 --- a/tests/suites/features/otlp-relay/tests/otlp_relay.rs +++ b/tests/suites/features/otlp-relay/tests/otlp_relay.rs @@ -122,7 +122,7 @@ async fn span_emitted_before_exit_is_delivered(cx: &mut Context) -> testkit::Res let mut ids = HashMap::new(); for (index, name) in names.iter().enumerate() { let sandbox = cx - .cli_sandbox(&format!("otlpx{index}")) + .cli_sandbox(&format!("otlp{index}")) .image(testkit::python_image()) .command(["python3", "-c", &exit_script(&encoded_request(name))]) .create() From fb3901587eaadd454684955ebb8a2ede363b73c8 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:22:50 -0800 Subject: [PATCH 13/22] test(features): port provider readiness and stable placeholder tests Signed-off-by: Matthew Grossman --- tests/suites/features/Cargo.lock | 10 + tests/suites/features/Cargo.toml | 2 +- .../features/provider-rotation/Cargo.toml | 18 + .../features/provider-rotation/src/lib.rs | 425 ++++++++++++++ .../provider-rotation/tests/readiness.rs | 531 ++++++++++++++++++ .../tests/stable_placeholders.rs | 438 +++++++++++++++ 6 files changed, 1423 insertions(+), 1 deletion(-) create mode 100644 tests/suites/features/provider-rotation/Cargo.toml create mode 100644 tests/suites/features/provider-rotation/src/lib.rs create mode 100644 tests/suites/features/provider-rotation/tests/readiness.rs create mode 100644 tests/suites/features/provider-rotation/tests/stable_placeholders.rs diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index 746309ca36..e378203e76 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -3087,6 +3087,16 @@ dependencies = [ "serde_json", ] +[[package]] +name = "provider-rotation" +version = "0.0.0" +dependencies = [ + "host-server-support", + "openshell-testkit", + "rand 0.9.4", + "serde_json", +] + [[package]] name = "provider-token-exchange" version = "0.0.0" diff --git a/tests/suites/features/Cargo.toml b/tests/suites/features/Cargo.toml index 24a024035d..5282b43b9d 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", "otlp-relay", "provider-refresh", "provider-token-exchange", "routable-host-ip"] +members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "oci-image", "otlp-relay", "provider-refresh", "provider-rotation", "provider-token-exchange", "routable-host-ip"] diff --git a/tests/suites/features/provider-rotation/Cargo.toml b/tests/suites/features/provider-rotation/Cargo.toml new file mode 100644 index 0000000000..f43f75b90f --- /dev/null +++ b/tests/suites/features/provider-rotation/Cargo.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "provider-rotation" +description = "Features suite: provider credential changes reaching sandbox HTTPS requests to TLS servers the additional destination CA signs" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/NVIDIA/OpenShell" +publish = false + +[dependencies] +host-server-support = { path = "../../../support/host-server" } +openshell-testkit = { path = "../../../testkit/testkit" } +rand = "0.9" +serde_json = "1" diff --git a/tests/suites/features/provider-rotation/src/lib.rs b/tests/suites/features/provider-rotation/src/lib.rs new file mode 100644 index 0000000000..c0a13922cc --- /dev/null +++ b/tests/suites/features/provider-rotation/src/lib.rs @@ -0,0 +1,425 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Support for the provider rotation tests: two TLS servers that check the +//! credential a sandbox sends, and the probes that drive a long-running +//! client in the sandbox. +//! +//! The servers run on the test host with a certificate signed by the +//! environment's additional CA ([`TestCa::from_env`]), so supervisors trust +//! them only through `additional_ca_bundle`. Sandboxes reach them by +//! [`TEST_HOST`], and by the host's primary IPv4 address for the wrong-host +//! checks. That address differs from the one [`TEST_HOST`] leads to: Docker's +//! bridge gateway, or the supervisor's loopback with Podman. +//! +//! Only the servers and the provider CLI see the keys. A client reports +//! status fields only, and the helpers here fail without echoing any output +//! that contains a key, an issued reference, or a bearer header. + +use std::net::{IpAddr, Ipv4Addr, UdpSocket}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use host_server_support::{HttpRecorder, Request, Response, TEST_HOST, TestCa}; +use serde_json::{Value, json}; +use testkit::sdk::raw::proto::SandboxPolicy; +use testkit::{Context, Error, PYTHON_BINARIES, Poll, Result, Sandbox, policy, poll_until}; + +/// The provider credential's environment variable. +pub const TOKEN_ENV: &str = "PROVIDER_ROTATION_TOKEN"; +/// The header the external caller assertion travels in. +pub const ASSERTION_HEADER: &str = "x-openshell-sandbox-assertion"; +/// How long `--wait` waits for a provider change to be acknowledged. +pub const READINESS_TIMEOUT_SECONDS: &str = "90"; +/// How long a client has to answer a probe once it is running. +const PROBE_TIMEOUT: Duration = Duration::from_secs(20); + +/// Two random keys: the provider's first credential and its replacement. +pub fn keys() -> [String; 2] { + [ + format!("test-{:032x}", rand::random::()), + format!("test-{:032x}", rand::random::()), + ] +} + +/// Fail, without echoing `text`, if it contains a key, an issued reference, +/// or a bearer header. +pub fn ensure_no_credentials(text: &str, keys: &[String; 2], what: &str) -> Result { + if keys.iter().any(|key| text.contains(key.as_str())) + || text.contains("openshell:resolve:") + || text.contains("Bearer ") + { + return Err(Error::msg(format!( + "{what} contained credential material; output withheld" + ))); + } + Ok(()) +} + +/// Run the CLI with `env` and `args` and parse its JSON output. Fails if the +/// command fails or its output contains credential material, and reports the +/// output only when it contains none. +pub async fn cli_json( + cx: &Context, + env: &[(&str, &str)], + args: &[&str], + keys: &[String; 2], +) -> Result { + let output = cx.cli_with_env(env, args).await?; + let what = format!("`{}`", output.command); + if output.exit_code != 0 { + let report = format!("{}\n{}", output.stdout, output.stderr); + ensure_no_credentials(&report, keys, &what)?; + return Err(Error::msg(format!( + "{what} exited {}: {report}", + output.exit_code + ))); + } + ensure_no_credentials(&output.stdout, keys, &what)?; + serde_json::from_str(&output.stdout) + .map_err(|_| Error::msg(format!("{what} printed invalid JSON"))) +} + +/// How the servers read the credential from a request. +#[derive(Clone, Copy, Debug)] +pub enum Credential { + /// `Authorization: Bearer `, for any POST. + Bearer, + /// [`ASSERTION_HEADER`] with the key, for a JSON-RPC `tools/call` of + /// `local_hello` that [`tool_call`] describes. + Assertion, +} + +/// The JSON-RPC request an assertion client sends. +pub fn tool_call() -> Value { + json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": "local_hello", "arguments": {"name": "rotation-proof"}}}) +} + +/// What the servers have seen, across both. They hold no header or key. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Counts { + /// The key the servers accept: 0 until [`Backends::rotate`], then 1. + pub phase: usize, + pub total: u64, + /// Accepted requests by the phase they arrived in. + pub accepted: [u64; 2], + pub rejected: u64, + /// Requests carrying the first or the replacement key. + pub received: [u64; 2], + /// Requests carrying no credential. + pub missing: u64, + /// Requests carrying something other than a key. + pub unknown: u64, + /// Requests whose body wasn't the expected tool call. + pub invalid_tool_calls: u64, +} + +/// Two TLS servers on the test host that accept the current key and count +/// what they see. [`Backends::port`] is the provider's endpoint, and +/// [`Backends::other_port`] and [`Backends::other_host`] are the wrong-port +/// and wrong-host checks. +pub struct Backends { + servers: [HttpRecorder; 2], + counts: Arc>, + other_host: String, +} + +impl Backends { + pub async fn start(credential: Credential, keys: &[String; 2]) -> Result { + let other_host = primary_ipv4()?; + let identity = TestCa::from_env()?.leaf(&[TEST_HOST, &other_host])?; + let counts = Arc::new(Mutex::new(Counts::default())); + let keys = Arc::new(keys.clone()); + let server = async || { + let counts = Arc::clone(&counts); + let keys = Arc::clone(&keys); + HttpRecorder::serve_tls(&identity, move |request| { + respond(credential, &keys, &counts, request) + }) + .await + }; + let servers = [server().await?, server().await?]; + Ok(Self { + servers, + counts, + other_host, + }) + } + + pub fn port(&self) -> u16 { + self.servers[0].port + } + + pub fn other_port(&self) -> u16 { + self.servers[1].port + } + + /// The test host's primary IPv4 address. + pub fn other_host(&self) -> &str { + &self.other_host + } + + /// Accept only the replacement key from now on. + pub fn rotate(&self) { + self.counts + .lock() + .unwrap_or_else(PoisonError::into_inner) + .phase = 1; + } + + pub fn counts(&self) -> Counts { + self.counts + .lock() + .unwrap_or_else(PoisonError::into_inner) + .clone() + } + + /// Fail unless the requests so far reached the servers on an address + /// other than [`Backends::other_host`], so the wrong-host checks really + /// name a different host. Call it before any wrong-host request. + pub fn ensure_distinct_hosts(&self) -> Result { + let arrivals: Vec = self + .servers + .iter() + .flat_map(HttpRecorder::requests) + .filter_map(|request| request.local_addr.map(|address| address.ip())) + .collect(); + testkit::ensure!( + !arrivals.is_empty(), + "no request to {TEST_HOST} reached the servers" + ); + testkit::ensure!( + arrivals + .iter() + .all(|address| address.to_string() != self.other_host), + "requests to {TEST_HOST} arrived on {arrivals:?}, which includes the wrong-host \ + address {}", + self.other_host + ); + Ok(()) + } + + /// A policy that lets Python reach the provider's endpoint and the + /// wrong-host and wrong-port addresses, so only the credential binding + /// keeps a credential from them. Other binaries, such as curl, can't + /// connect. + pub fn policy(&self) -> Result { + let endpoints: String = [ + (TEST_HOST, self.port()), + (TEST_HOST, self.other_port()), + (self.other_host.as_str(), self.port()), + ] + .iter() + .map(|(host, port)| { + format!( + " - {{host: \"{host}\", port: {port}, path: \"/**\", protocol: rest, access: full, enforcement: enforce}}\n" + ) + }) + .collect(); + policy::base_with(&format!( + "network_policies: + rotation_backends: + name: rotation_backends + endpoints: +{endpoints} binaries: {binaries} +", + binaries = policy::binaries_yaml(PYTHON_BINARIES), + )) + } +} + +fn respond( + credential: Credential, + keys: &[String; 2], + counts: &Mutex, + request: &Request, +) -> Response { + let body: Value = serde_json::from_str(&request.body).unwrap_or(Value::Null); + let (presented, is_tool_call) = match credential { + Credential::Bearer => ( + request + .header("authorization") + .and_then(|value| value.strip_prefix("Bearer ").map(str::to_string)), + true, + ), + Credential::Assertion => ( + request.header(ASSERTION_HEADER), + body["jsonrpc"] == "2.0" + && body["method"] == "tools/call" + && body["params"] == tool_call()["params"], + ), + }; + let generation = presented + .as_deref() + .map(|value| keys.iter().position(|key| key == value)); + let mut counts = counts.lock().unwrap_or_else(PoisonError::into_inner); + let phase = counts.phase; + let generation = match generation { + None => { + counts.missing += 1; + "missing" + } + Some(None) => { + counts.unknown += 1; + "unknown" + } + Some(Some(index)) => { + counts.received[index] += 1; + if index == 0 { "A" } else { "B" } + } + }; + if !is_tool_call { + counts.invalid_tool_calls += 1; + } + let valid = is_tool_call && presented.as_deref() == Some(keys[phase].as_str()); + counts.total += 1; + if valid { + counts.accepted[phase] += 1; + } else { + counts.rejected += 1; + } + drop(counts); + let reply = match credential { + Credential::Bearer => json!({"authorized": valid, "phase": phase}), + Credential::Assertion => { + let mut reply = json!({"jsonrpc": "2.0", "id": body["id"], + "fixture": {"authorized": valid, "phase": phase, + "credential_generation": generation, "tool_call": is_tool_call}}); + if valid { + reply["result"] = + json!({"content": [{"type": "text", "text": "Hello rotation-proof"}]}); + } else { + reply["error"] = json!({"code": -32001, "message": "Unauthorized"}); + } + reply + } + }; + Response::json(&reply).status(if valid { 200 } else { 401 }) +} + +/// The address this host sends from on its default route. +fn primary_ipv4() -> Result { + let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))?; + // Connecting a UDP socket sends nothing; it only picks the route. + socket.connect((Ipv4Addr::new(192, 0, 2, 1), 9))?; + let address = socket.local_addr()?.ip(); + testkit::ensure!( + matches!(address, IpAddr::V4(v4) if v4.is_private()), + "the test host's primary address {address} isn't a private IPv4 address" + ); + Ok(address.to_string()) +} + +/// Ask the client called `client` in `sandbox` to run `phase` and return its +/// result. A client watches `/sandbox/rotation-probe-` and writes its +/// result to `/sandbox/rotation-result-`. Allow `timeout` for a +/// client that may still be starting, [`PROBE_TIMEOUT`] otherwise. +pub async fn probe( + sandbox: &Sandbox, + client: &str, + phase: &str, + timeout: Option, +) -> Result { + let control = format!("/sandbox/rotation-probe-{client}"); + let result = format!("/sandbox/rotation-result-{client}"); + // The client takes the control file as soon as it appears, so write it + // whole and rename it into place. + sandbox + .exec([ + "sh".to_string(), + "-c".to_string(), + format!( + "rm -f {result} && printf '%s' '{phase}' > {control}.tmp && mv {control}.tmp {control}" + ), + ]) + .await? + .success()?; + let response = poll_until( + &format!("client {client} to answer {phase}"), + timeout.unwrap_or(PROBE_TIMEOUT), + Duration::from_millis(100), + async || { + let output = sandbox.exec(["cat", result.as_str()]).await?; + if output.exit_code != 0 || output.stdout.trim().is_empty() { + return Ok(Poll::Pending("no result yet".to_string())); + } + serde_json::from_str::(output.stdout.trim()) + .map(Poll::Ready) + .map_err(|_| Error::msg(format!("client {client} wrote an invalid result"))) + }, + ) + .await?; + testkit::ensure!( + response["phase"] == phase && response["same_reference"] == true, + "client {client} answered {phase} with phase {} and same_reference {}", + response["phase"], + response["same_reference"] + ); + Ok(response) +} + +/// Fail unless `response` came from the process `pid` and its request +/// succeeded exactly when `success` says. With `backend_phase`, the server +/// must also have accepted it in that phase. +pub fn check(response: &Value, pid: u64, success: bool, backend_phase: Option) -> Result { + // Report typed status fields only, never error text, which can carry + // headers. + testkit::ensure!( + response["pid"].as_u64() == Some(pid) && response["ok"].as_bool() == Some(success), + "probe {} failed: pid_matches={}, expected_ok={success}, actual_ok={:?}, status={:?}, \ + error_kind={:?}, reason_kind={:?}", + response["phase"], + response["pid"].as_u64() == Some(pid), + response["ok"].as_bool(), + response["status"].as_u64(), + response["error_kind"].as_str(), + response["reason_kind"].as_str(), + ); + if let Some(phase) = backend_phase { + testkit::ensure!( + response["backend_phase"].as_u64() == Some(phase) && response["status"] == 200, + "probe {} was not accepted with key {phase}: backend_phase={}, status={}", + response["phase"], + response["backend_phase"], + response["status"] + ); + } + Ok(()) +} + +/// Send the credential from curl, which the policy doesn't allow, with +/// `header` (such as `Authorization: Bearer `) before it and `data` as the +/// body. Fails unless the request is denied. +/// +/// curl runs as a sibling of the clients, so no allowed ancestor authorizes +/// it, and it reads the header from a pipe, so the credential isn't in its +/// arguments. +pub async fn probe_disallowed_binary( + sandbox: &Sandbox, + header: &str, + url: &str, + data: &str, +) -> Result { + let script = format!( + r#"token=$(printenv {TOKEN_ENV}) || exit 64 +command -v curl >/dev/null 2>&1 || exit 65 +if printf '%s%s\n' "$1" "$token" | \ + curl --silent --fail --max-time 5 --output /dev/null --header @- --data "$2" "$3" 2>/dev/null +then + printf unexpected-success +else + printf denied +fi"# + ); + let output = sandbox + .exec(["sh", "-c", &script, "binary-probe", header, data, url]) + .await?; + testkit::ensure!( + output.exit_code == 0 && output.stdout.trim() == "denied", + "curl's request to {url} wasn't denied: exit {}, stdout {:?}", + output.exit_code, + output.stdout.trim() + ); + Ok(()) +} diff --git a/tests/suites/features/provider-rotation/tests/readiness.rs b/tests/suites/features/provider-rotation/tests/readiness.rs new file mode 100644 index 0000000000..c302645e0a --- /dev/null +++ b/tests/suites/features/provider-rotation/tests/readiness.rs @@ -0,0 +1,531 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Provider changes acknowledged through a sandbox HTTPS request path. +//! +//! Attach, update, and detach wait for confirmation of their exact saved +//! changes. Clients launched after attach and update keep their own static +//! references. The first request from the client launched after the update +//! uses the new credential, and detach revokes both retained references and +//! removes the credential from later launches. +//! +//! Ported from the `provider_readiness` e2e test, which ran the servers in +//! containers on the e2e network and swapped the supervisor image to trust +//! their CA. Here they run on the test host and the environment's additional +//! CA signs them. + +use std::time::Duration; + +use host_server_support::TEST_HOST; +use provider_rotation::{ + Backends, Counts, Credential, READINESS_TIMEOUT_SECONDS, TOKEN_ENV, check, cli_json, keys, + probe, probe_disallowed_binary, +}; +use serde_json::{Value, json}; +use testkit::{CliChild, Context, Error, PYTHON_BINARIES, Result, Sandbox}; + +const READY: &str = "rotation-client-ready"; +const START_TIMEOUT: Duration = Duration::from_secs(60); + +/// A client that checks it got an issued reference, prints [`READY`], and +/// then answers probes (see [`probe`]). Its source holds no key. +const CLIENT: &str = r" +import json, os, pathlib, re, ssl, sys, time, urllib.error, urllib.request + +config = json.loads(sys.argv[1]) +key = config['key'] +token = os.environ.get(key, '') +if not re.fullmatch(r'openshell:resolve:env:v[1-9][0-9]*_' + key, token): + print('client did not receive a revision-scoped reference', flush=True) + sys.exit(64) +client = sys.argv[2] +pid = os.getpid() +control = pathlib.Path('/sandbox/rotation-probe-' + client) +result = pathlib.Path('/sandbox/rotation-result-' + client) + +def probe(phase): + host, port, path = config['host'], config['port'], '/v1/chat/completions' + target = phase[:-8] if phase.endswith('_control') else phase + if target == 'wrong_host': + host = config['other_host'] + elif target == 'wrong_port': + port = config['other_port'] + elif target == 'wrong_path': + path = '/outside' + url = 'https://%s:%s%s' % (host, port, path) + response = {'phase': phase, 'pid': pid, 'same_reference': os.environ.get(key) == token, + 'ok': False, 'status': 0, 'backend_phase': -1} + try: + context = ssl.create_default_context() + if phase == 'untrusted_ca': + # An empty trust store proves this client does verify TLS. + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + headers = {'Content-Type': 'application/json'} + if not phase.endswith('_control'): + headers['Authorization'] = 'Bearer ' + token + request = urllib.request.Request(url, data=b'{}', headers=headers) + try: + reply = urllib.request.urlopen(request, context=context, timeout=5) + except urllib.error.HTTPError as error: + # The server's 401 body proves the endpoint is reachable. + reply = error + with reply: + body = json.loads(reply.read(1024)) + response['ok'] = body.get('authorized') is True + response['status'] = reply.status + response['backend_phase'] = body.get('phase', -1) + except Exception as error: + # HTTP and TLS errors can embed headers; report only type names. + response['error_kind'] = type(error).__name__ + response['reason_kind'] = type(getattr(error, 'reason', None)).__name__ + return response + +print('rotation-client-ready', flush=True) +deadline = time.monotonic() + 600 +while time.monotonic() < deadline: + if control.exists(): + phase = control.read_text().strip() + control.unlink() + temporary = result.with_suffix('.tmp') + temporary.write_text(json.dumps(probe(phase))) + temporary.replace(result) + time.sleep(0.05) +"; + +/// Attach, a single update, and detach each wait for acknowledgment. Two +/// clients, launched after attach and after the update, keep running +/// throughout, and detach revokes both of their references. +#[testkit::test] +async fn acknowledged_changes_reach_fresh_clients_and_detach_revokes_retained_references( + cx: &mut Context, +) -> testkit::Result { + let keys = keys(); + let backends = Backends::start(Credential::Bearer, &keys).await?; + let provider = cx.name("ready"); + let provider_type = cx + .import_profile(&profile(&provider, backends.port())) + .await?; + cx.create_provider(&provider, &provider_type, &[(TOKEN_ENV, &keys[0])]) + .await?; + let sandbox = cx + .sandbox("ready") + .image(testkit::python_image()) + .policy(backends.policy()?) + .command(["sleep", "infinity"]) + .create_ready() + .await?; + let config = json!({"key": TOKEN_ENV, "host": TEST_HOST, "other_host": backends.other_host(), + "port": backends.port(), "other_port": backends.other_port()}) + .to_string(); + future_environment(&sandbox, false).await?; + + let output = cli_json( + cx, + &[], + &[ + "sandbox", + "provider", + "attach", + sandbox.name(), + &provider, + "-o", + "json", + ], + &keys, + ) + .await?; + let attach = Receipt::capture(&output, &sandbox, &provider, "attach")?; + attach.wait(cx, &sandbox, &provider, "ready", &keys).await?; + future_environment(&sandbox, true).await?; + // Client A starts only after the launch environment is acknowledged, + // and keeps that reference until the sandbox is deleted. + let _client_a = start_client(cx, &sandbox, &config, "a").await?; + let initial = probe(&sandbox, "a", "initial", None).await?; + let pid_a = pid(&initial)?; + check(&initial, pid_a, true, Some(0))?; + backends.ensure_distinct_hosts()?; + let before = backends.counts(); + testkit::ensure!( + before.total == 1 && before.accepted[0] == 1, + "the first request wasn't the only one accepted: {before:?}" + ); + for phase in [ + "wrong_host_control", + "wrong_port_control", + "wrong_path_control", + ] { + let control = probe(&sandbox, "a", phase, None).await?; + check(&control, pid_a, false, None)?; + testkit::ensure!( + control["status"] == 401 && control["backend_phase"] == 0, + "{phase} without a credential didn't reach the server: {control}" + ); + } + let before = backends.counts(); + testkit::ensure!( + before.total == 4 && before.rejected == 3 && before.accepted == [1, 0], + "the requests without a credential weren't counted as rejected: {before:?}" + ); + for phase in ["wrong_host", "wrong_port", "wrong_path", "untrusted_ca"] { + check( + &probe(&sandbox, "a", phase, None).await?, + pid_a, + false, + None, + )?; + expect_counts(&backends, &before, phase)?; + } + probe_disallowed_binary( + &sandbox, + "Authorization: Bearer ", + &format!( + "https://{TEST_HOST}:{}/v1/chat/completions", + backends.port() + ), + "{}", + ) + .await?; + expect_counts(&backends, &before, "the request from curl")?; + + backends.rotate(); + let output = cli_json( + cx, + &[(TOKEN_ENV, &keys[1])], + &[ + "provider", + "update", + &provider, + "--credential", + TOKEN_ENV, + "-o", + "json", + ], + &keys, + ) + .await?; + let update = Receipt::capture(&output, &sandbox, &provider, "update")?; + update.follows(&attach)?; + // No requests happen while waiting. Client B starts after the update is + // acknowledged, and its first request must use the new key. + update.wait(cx, &sandbox, &provider, "ready", &keys).await?; + future_environment(&sandbox, true).await?; + let _client_b = start_client(cx, &sandbox, &config, "b").await?; + let rotated_request = probe(&sandbox, "b", "rotated", None).await?; + let pid_b = pid(&rotated_request)?; + testkit::ensure!(pid_b != pid_a, "client B is the same process as client A"); + check(&rotated_request, pid_b, true, Some(1))?; + let rotated = backends.counts(); + testkit::ensure!( + rotated.total == 5 && rotated.accepted == [1, 1] && rotated.rejected == 3, + "the servers didn't see exactly one request with the new key: {rotated:?}" + ); + + let output = cli_json( + cx, + &[], + &[ + "sandbox", + "provider", + "detach", + sandbox.name(), + &provider, + "-o", + "json", + ], + &keys, + ) + .await?; + let detach = Receipt::capture(&output, &sandbox, &provider, "detach")?; + detach.follows(&update)?; + detach + .wait(cx, &sandbox, &provider, "revoked", &keys) + .await?; + future_environment(&sandbox, false).await?; + // The route stays allowed after detach, so a denial below is the + // revoked reference, not a network failure. + let control = probe(&sandbox, "b", "detached_control", None).await?; + check(&control, pid_b, false, None)?; + testkit::ensure!( + control["status"] == 401 && control["backend_phase"] == 1, + "the endpoint wasn't reachable without a credential after detach: {control}" + ); + let detached = backends.counts(); + testkit::ensure!( + detached + == Counts { + total: 6, + accepted: [1, 1], + rejected: 4, + phase: 1, + ..detached.clone() + }, + "the request without a credential after detach wasn't counted as rejected: {detached:?}" + ); + for (client, pid) in [("a", pid_a), ("b", pid_b)] { + check( + &probe(&sandbox, client, "detached", None).await?, + pid, + false, + None, + )?; + expect_counts( + &backends, + &detached, + &format!("client {client}'s request after detach"), + )?; + } + Ok(()) +} + +/// A profile with one bearer credential bound to the server on `port`. +fn profile(id: &str, port: u16) -> String { + json!({ + "id": id, "display_name": "Provider readiness test", "category": "other", + "credentials": [{"name": "synthetic", "env_vars": [TOKEN_ENV], "required": true, + "auth_style": "bearer", "header_name": "authorization"}], + "endpoints": [{"host": TEST_HOST, "port": port, "path": "/v1/**", "protocol": "rest", + "access": "full", "enforcement": "enforce"}], + "binaries": PYTHON_BINARIES, + }) + .to_string() +} + +fn pid(response: &Value) -> Result { + response["pid"] + .as_u64() + .ok_or_else(|| Error::msg(format!("probe {} reported no PID", response["phase"]))) +} + +fn expect_counts(backends: &Backends, expected: &Counts, what: &str) -> Result { + let counts = backends.counts(); + testkit::ensure!( + &counts == expected, + "{what} reached the servers: {counts:?}, expected {expected:?}" + ); + Ok(()) +} + +/// Start the client called `client` with `sandbox exec`, and wait until it +/// is ready. It runs until the returned handle is dropped. +async fn start_client( + cx: &Context, + sandbox: &Sandbox, + config: &str, + client: &str, +) -> Result { + let mut child = cx.cli_spawn([ + "sandbox", + "exec", + "--name", + sandbox.name(), + "--no-tty", + "--", + "python3", + "-u", + "-c", + CLIENT, + config, + client, + ])?; + child + .stdout_until(START_TIMEOUT, |line| line == READY) + .await + .map_err(|error| error.context(format!("start client {client}")))?; + Ok(child) +} + +/// Fail unless a new process in `sandbox` gets an issued reference exactly +/// when `present` says. It reports booleans only. +async fn future_environment(sandbox: &Sandbox, present: bool) -> Result { + let script = format!( + "import json,os,re; key='{TOKEN_ENV}'; value=os.environ.get(key,''); \ + print(json.dumps({{'present':key in os.environ,\ + 'reference':bool(re.fullmatch(r'openshell:resolve:env:v[1-9][0-9]*_'+key,value))}}))" + ); + let result = sandbox.run_python(&script, &[]).await?.last_json()?; + testkit::ensure!( + result["present"] == present && result["reference"] == present, + "a new process's credential reference didn't match the acknowledged provider state \ + (expected present={present}): {result}" + ); + Ok(()) +} + +/// The receipt a provider mutation printed. +struct Receipt { + mutation_id: String, + receipt: Value, +} + +fn single_target(body: &Value) -> Result<&Value> { + // The provider is unique and has one attachment, so a mutation that + // selects another sandbox or none can't pass. + match body["targets"].as_array().map(Vec::as_slice) { + Some([target]) => Ok(target), + _ => Err(Error::msg( + "the provider readiness output didn't name exactly one sandbox", + )), + } +} + +fn nonempty<'a>(object: &'a Value, field: &str) -> Result<&'a str> { + object[field] + .as_str() + .filter(|value| !value.is_empty()) + .ok_or_else(|| Error::msg(format!("provider readiness field {field} is missing"))) +} + +impl Receipt { + fn capture(body: &Value, sandbox: &Sandbox, provider: &str, kind: &str) -> Result { + let status = single_target(body)?; + let receipt = &status["receipt"]; + let desired = &receipt["desired"]; + let mutation_id = nonempty(body, "mutation_id")?; + testkit::ensure!( + receipt["mutation_id"] == mutation_id + && receipt["provider"] == provider + && receipt["kind"] == kind + && desired["sandbox"] == sandbox.name() + && status["state"] == "persisted" + && status["wait_outcome"] == "not_requested", + "the {kind} receipt doesn't describe the persisted change: {status}" + ); + nonempty(receipt, "receipt_id")?; + for field in [ + "sandbox_id", + "attachment_epoch", + "provider_resource_version", + "provider_env_revision", + "config_revision", + "policy_hash", + ] { + nonempty(desired, field)?; + } + if kind == "detach" { + testkit::ensure!( + desired["provider_id"] == "" && desired["provider_resource_version"] == "0", + "the detach receipt kept the provider: {desired}" + ); + } else { + nonempty(desired, "provider_id")?; + } + nonempty(receipt, "persisted_time")?; + Ok(Self { + mutation_id: mutation_id.to_string(), + receipt: receipt.clone(), + }) + } + + /// Fail unless this receipt is a new change to the same target as + /// `previous`. + fn follows(&self, previous: &Self) -> Result { + let desired = &self.receipt["desired"]; + let preceding = &previous.receipt["desired"]; + testkit::ensure!( + self.mutation_id != previous.mutation_id + && self.receipt["receipt_id"] != previous.receipt["receipt_id"] + && self.receipt["provider"] == previous.receipt["provider"] + && self.receipt["workspace"] == previous.receipt["workspace"] + && desired["sandbox_id"] == preceding["sandbox_id"] + && desired["sandbox"] == preceding["sandbox"] + && desired["provider_env_revision"] != preceding["provider_env_revision"], + "the {} receipt isn't a distinct change to the same target: {desired} after {preceding}", + self.receipt["kind"] + ); + // Revisions are opaque, so only equality means anything. + if self.receipt["kind"] == "update" { + testkit::ensure!( + desired["provider_id"] == preceding["provider_id"] + && desired["provider_resource_version"] + != preceding["provider_resource_version"] + && desired["attachment_epoch"] == preceding["attachment_epoch"], + "the update didn't keep its attachment: {desired} after {preceding}" + ); + } + if self.receipt["kind"] == "detach" { + testkit::ensure!( + desired["attachment_epoch"] != preceding["attachment_epoch"], + "the detach didn't replace the attachment epoch: {desired}" + ); + } + Ok(()) + } + + /// Wait for the receipt to complete in `expected_state`, and check the + /// sandbox installed exactly what it asked for. + async fn wait( + &self, + cx: &Context, + sandbox: &Sandbox, + provider: &str, + expected_state: &str, + keys: &[String; 2], + ) -> Result { + let body = cli_json( + cx, + &[], + &[ + "sandbox", + "provider", + "status", + sandbox.name(), + provider, + "--receipt", + nonempty(&self.receipt, "receipt_id")?, + "--wait", + "--timeout", + READINESS_TIMEOUT_SECONDS, + "-o", + "json", + ], + keys, + ) + .await?; + let status = single_target(&body)?; + testkit::ensure!( + body["mutation_id"] == self.mutation_id.as_str() + && status["receipt"] == self.receipt + && status["state"] == expected_state + && status["reason"] == "unspecified" + && status["wait_outcome"] == "complete", + "the {} receipt didn't complete as {expected_state}: {status}", + self.receipt["kind"] + ); + let desired = &self.receipt["desired"]; + let observed = &status["observed"]; + for field in [ + "attachment_epoch", + "provider_env_revision", + "config_revision", + "policy_hash", + ] { + testkit::ensure!( + observed[field] == desired[field], + "the sandbox installed {field} {}, not {}", + observed[field], + desired[field] + ); + } + for field in [ + "credentials_installed", + "policy_active", + "launch_environment_installed", + ] { + testkit::ensure!( + observed[field] == true, + "the receipt completed without {field}: {observed}" + ); + } + for field in ["session_id", "sequence", "process_instance_id"] { + nonempty(observed, field)?; + } + nonempty(status, "network_instance_id")?; + nonempty(status, "observed_time")?; + nonempty(status, "evaluated_time")?; + testkit::ensure!( + observed["reason"] == "unspecified", + "the installation wasn't acknowledged successfully: {observed}" + ); + Ok(()) + } +} diff --git a/tests/suites/features/provider-rotation/tests/stable_placeholders.rs b/tests/suites/features/provider-rotation/tests/stable_placeholders.rs new file mode 100644 index 0000000000..ad6e2f2919 --- /dev/null +++ b/tests/suites/features/provider-rotation/tests/stable_placeholders.rs @@ -0,0 +1,438 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! External caller assertion rotation through a sandbox HTTPS request path. +//! +//! The sandbox's main process keeps one supervisor-issued reference and sends +//! a `tools/call` request with it whenever the test asks. After one provider +//! update, a stable placeholder resolves to the new assertion, while an +//! ordinary reference keeps the revoked one. This exercises credential +//! substitution, not an MCP session. +//! +//! Ported from the `stable_external_placeholders` e2e test, which ran the +//! servers in containers on the e2e network and swapped the supervisor image +//! to trust their CA. Here they run on the test host and the environment's +//! additional CA signs them. + +use std::time::Duration; + +use host_server_support::TEST_HOST; +use provider_rotation::{ + ASSERTION_HEADER, Backends, Counts, Credential, READINESS_TIMEOUT_SECONDS, TOKEN_ENV, check, + cli_json, keys, probe, probe_disallowed_binary, tool_call, +}; +use serde_json::{Value, json}; +use testkit::{Context, Error, PYTHON_BINARIES, Result, Sandbox}; + +/// The main process's client name in [`probe`]. +const CLIENT_NAME: &str = "main"; +/// How long the main process has to start before it answers the first probe. +const START_TIMEOUT: Duration = Duration::from_secs(60); + +/// A client that checks it got the expected kind of issued reference and +/// answers probes (see [`probe`]), or with `--once`, sends one request and +/// prints the result. Its source holds no key. +const CLIENT: &str = r" +import json, os, pathlib, re, ssl, sys, time, urllib.error, urllib.request + +config = json.loads(sys.argv[1]) +key = config['key'] +token = os.environ.get(key, '') +pattern = r's[0-9a-f]{64}' if config['stable'] else r'v[1-9][0-9]*' +if not re.fullmatch(r'openshell:resolve:env:' + pattern + '_' + key, token): + print('client did not receive the expected issued reference', flush=True) + sys.exit(64) +pid = os.getpid() +control = pathlib.Path('/sandbox/rotation-probe-main') +result = pathlib.Path('/sandbox/rotation-result-main') + +def probe(phase): + host, port, path = config['host'], config['port'], '/mcp/local-hello' + authorization = token + target = phase[:-8] if phase.endswith('_control') else phase + if target == 'wrong_host': + host = config['other_host'] + elif target == 'wrong_port': + port = config['other_port'] + elif target == 'wrong_path': + path = '/outside' + elif phase == 'canonical_alias': + authorization = 'openshell:resolve:env:' + key + url = 'https://%s:%s%s' % (host, port, path) + response = {'phase': phase, 'pid': pid, 'same_reference': os.environ.get(key) == token, + 'ok': False, 'status': 0, 'backend_phase': -1, + 'credential_generation': 'unobserved', 'tool_call': False} + try: + context = ssl.create_default_context() + if phase == 'untrusted_ca': + # An empty trust store proves this client does verify TLS. + context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) + headers = {'Content-Type': 'application/json'} + if not phase.endswith('_control'): + headers[config['header']] = authorization + request = urllib.request.Request(url, data=json.dumps(config['payload']).encode(), + headers=headers) + try: + reply = urllib.request.urlopen(request, context=context, timeout=5) + except urllib.error.HTTPError as error: + # The server's 401 body proves the endpoint is reachable. + reply = error + with reply: + body = json.loads(reply.read(1024)) + attestation = body.get('fixture', {}) + response['ok'] = (attestation.get('authorized') is True + and body.get('result', {}).get('content') == + [{'type': 'text', 'text': 'Hello rotation-proof'}]) + response['status'] = reply.status + response['backend_phase'] = attestation.get('phase', -1) + response['credential_generation'] = attestation.get('credential_generation', 'unobserved') + response['tool_call'] = attestation.get('tool_call') is True + except Exception as error: + # HTTP and TLS errors can embed headers; report only type names. + response['error_kind'] = type(error).__name__ + response['reason_kind'] = type(getattr(error, 'reason', None)).__name__ + return response + +if len(sys.argv) > 2 and sys.argv[2] == '--once': + print(json.dumps(probe('fresh')), flush=True) + sys.exit(0) + +deadline = time.monotonic() + 600 +while time.monotonic() < deadline: + if control.exists(): + phase = control.read_text().strip() + control.unlink() + temporary = result.with_suffix('.tmp') + temporary.write_text(json.dumps(probe(phase))) + temporary.replace(result) + time.sleep(0.05) +"; + +/// With `stable_placeholder`, the main process's retained reference resolves +/// to the new assertion after one update, and detach revokes it. +#[testkit::test] +async fn stable_placeholder_follows_rotation_and_detach_revokes( + cx: &mut Context, +) -> testkit::Result { + assertion_rotation(cx, true).await +} + +/// Without `stable_placeholder`, the main process's retained reference keeps +/// sending the revoked assertion after an update, while a new process sends +/// the new one. +#[testkit::test] +async fn ordinary_reference_keeps_revoked_assertion_after_rotation( + cx: &mut Context, +) -> testkit::Result { + assertion_rotation(cx, false).await +} + +// One lifecycle, so no phase can replace the retained client. +#[allow(clippy::too_many_lines)] +async fn assertion_rotation(cx: &Context, stable: bool) -> Result { + let keys = keys(); + let backends = Backends::start(Credential::Assertion, &keys).await?; + let suffix = if stable { "stbl" } else { "ordn" }; + let provider = cx.name(suffix); + let provider_type = cx + .import_profile(&profile(&provider, backends.port(), stable)) + .await?; + cx.create_provider(&provider, &provider_type, &[(TOKEN_ENV, &keys[0])]) + .await?; + let config = json!({"key": TOKEN_ENV, "header": ASSERTION_HEADER, "payload": tool_call(), + "host": TEST_HOST, "other_host": backends.other_host(), "port": backends.port(), + "other_port": backends.other_port(), "stable": stable}) + .to_string(); + let sandbox = cx + .sandbox(suffix) + .image(testkit::python_image()) + .providers([provider.as_str()]) + .policy(backends.policy()?) + .command(["python3", "-u", "-c", CLIENT, &config]) + .create_ready() + .await?; + + let initial = probe(&sandbox, CLIENT_NAME, "initial", Some(START_TIMEOUT)).await?; + let pid = pid(&initial)?; + check_generation(&initial, pid, true, Some(0))?; + backends.ensure_distinct_hosts()?; + let before = backends.counts(); + testkit::ensure!( + before.total == 1 && before.accepted[0] == 1, + "the first request wasn't the only one accepted: {before:?}" + ); + for phase in [ + "wrong_host_control", + "wrong_port_control", + "wrong_path_control", + ] { + let control = probe(&sandbox, CLIENT_NAME, phase, None).await?; + check(&control, pid, false, None)?; + testkit::ensure!( + control["status"] == 401 && control["backend_phase"] == 0, + "{phase} without a credential didn't reach the server: {control}" + ); + } + let before = backends.counts(); + testkit::ensure!( + before.total == 4 && before.rejected == 3 && before.accepted == [1, 0], + "the requests without a credential weren't counted as rejected: {before:?}" + ); + for phase in [ + "wrong_host", + "wrong_port", + "wrong_path", + "canonical_alias", + "untrusted_ca", + ] { + check( + &probe(&sandbox, CLIENT_NAME, phase, None).await?, + pid, + false, + None, + )?; + expect_counts(&backends, &before, phase)?; + } + probe_disallowed_binary( + &sandbox, + &format!("{ASSERTION_HEADER}: "), + &format!("https://{TEST_HOST}:{}/mcp/local-hello", backends.port()), + &tool_call().to_string(), + ) + .await?; + expect_counts(&backends, &before, "the request from curl")?; + + backends.rotate(); + // The only update. --wait acknowledges the saved revision before the + // client sends its next request. + acknowledged_mutation( + cx, + &[(TOKEN_ENV, &keys[1])], + &["provider", "update", &provider, "--credential", TOKEN_ENV], + &sandbox, + &provider, + "update", + &keys, + ) + .await?; + // The next request must send B with the opt-in; the ordinary reference + // still resolves to A. + let retained = probe(&sandbox, CLIENT_NAME, "rotated", None).await?; + check_generation(&retained, pid, stable, stable.then_some(1))?; + if !stable { + testkit::ensure!( + retained["status"] == 401 + && retained["backend_phase"] == 1 + && retained["credential_generation"] == "A" + && retained["tool_call"] == true, + "the ordinary retained reference didn't send the revoked assertion A: {retained}" + ); + } + let rejected = if stable { 3 } else { 4 }; + let rotated = backends.counts(); + let expected = Counts { + phase: 1, + total: 5, + accepted: if stable { [1, 1] } else { [1, 0] }, + rejected, + received: if stable { [1, 1] } else { [2, 0] }, + missing: 3, + unknown: 0, + invalid_tool_calls: 0, + }; + testkit::ensure!( + rotated == expected, + "after the update the servers saw {rotated:?}, expected {expected:?}" + ); + + // A new process uses B in both modes. It leaves the main process alone. + let fresh = sandbox + .run_python(CLIENT, &[&config, "--once"]) + .await? + .last_json()?; + let fresh_pid = self::pid(&fresh)?; + testkit::ensure!( + fresh_pid != pid && fresh["same_reference"] == true, + "the new process isn't separate from the main process: {fresh}" + ); + check_generation(&fresh, fresh_pid, true, Some(1))?; + let refreshed = backends.counts(); + let expected = Counts { + total: 6, + accepted: if stable { [1, 2] } else { [1, 1] }, + received: if stable { [1, 2] } else { [2, 1] }, + ..expected + }; + testkit::ensure!( + refreshed == expected, + "the new process's request didn't send assertion B: the servers saw {refreshed:?}, \ + expected {expected:?}" + ); + + acknowledged_mutation( + cx, + &[], + &["sandbox", "provider", "detach", sandbox.name(), &provider], + &sandbox, + &provider, + "detach", + &keys, + ) + .await?; + // The route stays allowed after detach, so a denial below is the + // revoked reference, not a network failure. + let control = probe(&sandbox, CLIENT_NAME, "detached_control", None).await?; + check(&control, pid, false, None)?; + testkit::ensure!( + control["status"] == 401 && control["backend_phase"] == 1, + "the endpoint wasn't reachable without a credential after detach: {control}" + ); + let detached = backends.counts(); + let expected = Counts { + total: 7, + rejected: rejected + 1, + missing: 4, + ..expected + }; + testkit::ensure!( + detached == expected, + "after detach the servers saw {detached:?}, expected {expected:?}" + ); + check( + &probe(&sandbox, CLIENT_NAME, "detached", None).await?, + pid, + false, + None, + )?; + expect_counts(&backends, &detached, "the request after detach") +} + +/// A profile with one header credential bound to the server on `port`, +/// opting in to a stable placeholder when `stable` says. Without the +/// opt-in, it behaves as an existing static credential profile. +fn profile(id: &str, port: u16, stable: bool) -> String { + let mut credential = json!({"name": "synthetic_assertion", "env_vars": [TOKEN_ENV], + "required": true, "auth_style": "header", "header_name": ASSERTION_HEADER}); + if stable { + credential["stable_placeholder"] = json!(true); + } + json!({ + "id": id, "display_name": "External caller assertion test", "category": "other", + "credentials": [credential], + "endpoints": [{"host": TEST_HOST, "port": port, "path": "/mcp/**", "protocol": "rest", + "access": "full", "enforcement": "enforce"}], + "binaries": PYTHON_BINARIES, + }) + .to_string() +} + +fn pid(response: &Value) -> Result { + response["pid"] + .as_u64() + .ok_or_else(|| Error::msg(format!("probe {} reported no PID", response["phase"]))) +} + +/// [`check`], and with `backend_phase`, the server also saw that phase's +/// assertion in a valid tool call. +fn check_generation( + response: &Value, + pid: u64, + success: bool, + backend_phase: Option, +) -> Result { + check(response, pid, success, backend_phase)?; + if let Some(phase) = backend_phase { + let generation = if phase == 0 { "A" } else { "B" }; + testkit::ensure!( + response["credential_generation"] == generation && response["tool_call"] == true, + "probe {} didn't send assertion {generation} in a tool call: credential_generation={}, \ + tool_call={}", + response["phase"], + response["credential_generation"], + response["tool_call"] + ); + } + Ok(()) +} + +fn expect_counts(backends: &Backends, expected: &Counts, what: &str) -> Result { + let counts = backends.counts(); + testkit::ensure!( + &counts == expected, + "{what} reached the servers: {counts:?}, expected {expected:?}" + ); + Ok(()) +} + +/// Run a provider mutation with `--wait` and check it was acknowledged for +/// `sandbox` with exactly what it asked for. +async fn acknowledged_mutation( + cx: &Context, + env: &[(&str, &str)], + args: &[&str], + sandbox: &Sandbox, + provider: &str, + kind: &str, + keys: &[String; 2], +) -> Result { + let mut args = args.to_vec(); + args.extend([ + "--wait", + "--timeout", + READINESS_TIMEOUT_SECONDS, + "-o", + "json", + ]); + let body = cli_json(cx, env, &args, keys).await?; + let Some([status]) = body["targets"].as_array().map(Vec::as_slice) else { + return Err(Error::msg(format!( + "the {kind} wasn't acknowledged for exactly one sandbox: {body}" + ))); + }; + let receipt = &status["receipt"]; + let desired = &receipt["desired"]; + let observed = &status["observed"]; + let expected = if kind == "detach" { "revoked" } else { "ready" }; + testkit::ensure!( + body["mutation_id"] + .as_str() + .is_some_and(|id| !id.is_empty()) + && receipt["mutation_id"] == body["mutation_id"] + && receipt["provider"] == provider + && receipt["kind"] == kind + && desired["sandbox"] == sandbox.name() + && status["state"] == expected + && status["wait_outcome"] == "complete" + && status["reason"] == "unspecified" + && observed["reason"] == "unspecified", + "the {kind} wasn't acknowledged as {expected} for {}: {status}", + sandbox.name() + ); + for field in [ + "attachment_epoch", + "provider_env_revision", + "config_revision", + "policy_hash", + ] { + testkit::ensure!( + desired[field] + .as_str() + .is_some_and(|value| !value.is_empty()) + && observed[field] == desired[field], + "the sandbox installed {field} {}, not {}", + observed[field], + desired[field] + ); + } + for field in [ + "credentials_installed", + "policy_active", + "launch_environment_installed", + ] { + testkit::ensure!( + observed[field] == true, + "the {kind} was acknowledged without {field}: {observed}" + ); + } + Ok(()) +} From 556ca6a32280e93e18b4c0a2ad04a9ea14499470 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:26:38 -0800 Subject: [PATCH 14/22] ci(e2e): run provider rotation suite on additional-CA environments Signed-off-by: Matthew Grossman --- .github/workflows/e2e-suites.yml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index b4e83c11c4..626cc115b2 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -122,6 +122,8 @@ jobs: {"environment":"fedora-podman-rootless-spiffe","installer":"rpm","family":"features","package":"provider-token-exchange","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"ubuntu-docker-rootful-additional-ca","installer":"deb","family":"features","package":"provider-rotation","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"fedora-podman-rootful-additional-ca","installer":"rpm","family":"features","package":"provider-rotation","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"}, From 63e523e62fd757e9f31b0fe49502c57e85a79916 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:32:34 -0800 Subject: [PATCH 15/22] test(e2e): remove gateway configuration tests ported to testkit suites Signed-off-by: Matthew Grossman --- e2e/rust/Cargo.lock | 396 +--- e2e/rust/Cargo.toml | 22 - e2e/rust/e2e-podman.sh | 17 - e2e/rust/tests/otlp_relay.rs | 420 ----- e2e/rust/tests/provider_readiness.rs | 1591 ----------------- e2e/rust/tests/provider_refresh_handles.rs | 16 - e2e/rust/tests/provider_token_exchange.rs | 1466 --------------- .../tests/stable_external_placeholders.rs | 1354 -------------- e2e/support/podman-gateway-config.sh | 22 +- e2e/with-docker-gateway.sh | 12 - e2e/with-podman-gateway.sh | 13 - tasks/scripts/test-gateway-config.sh | 5 +- 12 files changed, 6 insertions(+), 5328 deletions(-) delete mode 100644 e2e/rust/tests/otlp_relay.rs delete mode 100644 e2e/rust/tests/provider_readiness.rs delete mode 100644 e2e/rust/tests/provider_refresh_handles.rs delete mode 100644 e2e/rust/tests/provider_token_exchange.rs delete mode 100644 e2e/rust/tests/stable_external_placeholders.rs diff --git a/e2e/rust/Cargo.lock b/e2e/rust/Cargo.lock index d4afe2b166..b5f42d20de 100644 --- a/e2e/rust/Cargo.lock +++ b/e2e/rust/Cargo.lock @@ -46,15 +46,6 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - [[package]] name = "annotate-snippets" version = "0.12.18" @@ -468,20 +459,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - [[package]] name = "cmake" version = "0.1.58" @@ -1008,7 +985,6 @@ checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218" dependencies = [ "futures-channel", "futures-core", - "futures-executor", "futures-io", "futures-sink", "futures-task", @@ -1436,30 +1412,6 @@ dependencies = [ "tower-service", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.4.0" @@ -1925,7 +1877,7 @@ dependencies = [ "tokio", "tokio-util", "tower", - "tower-http 0.7.1", + "tower-http", "tracing", ] @@ -2054,15 +2006,6 @@ version = "0.4.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" -[[package]] -name = "matchers" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" -dependencies = [ - "regex-automata", -] - [[package]] name = "matchit" version = "0.8.4" @@ -2085,16 +2028,6 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" -[[package]] -name = "metrics" -version = "0.24.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89550ee9f79e88fef3119de263694973a8adb26c21d75322164fb8c493039fe2" -dependencies = [ - "portable-atomic", - "rapidhash", -] - [[package]] name = "micromap" version = "0.3.0" @@ -2219,15 +2152,6 @@ dependencies = [ "smallvec", ] -[[package]] -name = "nu-ansi-term" -version = "0.50.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "num" version = "0.4.3" @@ -2426,8 +2350,6 @@ dependencies = [ "openshell-core", "openshell-crypto", "openshell-ocsf-validate", - "openshell-otel-test-support", - "opentelemetry-proto", "prost", "rand 0.9.5", "rustls", @@ -2458,19 +2380,6 @@ dependencies = [ "tower", ] -[[package]] -name = "openshell-ocsf" -version = "0.0.0" -dependencies = [ - "chrono", - "serde", - "serde_json", - "serde_repr", - "tracing", - "tracing-subscriber", - "uuid", -] - [[package]] name = "openshell-ocsf-validate" version = "0.0.0" @@ -2480,60 +2389,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "openshell-otel" -version = "0.0.0" -dependencies = [ - "async-trait", - "bytes", - "futures", - "http", - "http-body-util", - "hyper-rustls", - "hyper-util", - "metrics", - "openshell-crypto", - "openshell-ocsf", - "opentelemetry", - "opentelemetry-http", - "opentelemetry-otlp", - "opentelemetry_sdk", - "rustls", - "rustls-native-certs", - "serde_json", - "thiserror", - "tokio", - "tonic", - "tower-http 0.6.11", - "tracing", - "tracing-opentelemetry", - "tracing-subscriber", - "zeroize", -] - -[[package]] -name = "openshell-otel-test-support" -version = "0.0.0" -dependencies = [ - "bytes", - "http", - "http-body-util", - "hyper", - "hyper-util", - "openshell-crypto", - "openshell-otel", - "opentelemetry-proto", - "prost", - "rcgen", - "rustls", - "tokio", - "tokio-rustls", - "tokio-stream", - "tonic", - "tracing", - "tracing-subscriber", -] - [[package]] name = "openshell-policy-schema" version = "0.0.0" @@ -2563,83 +2418,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" -[[package]] -name = "opentelemetry" -version = "0.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c1f1a6ac9c875a4941e4c7c085b61e8f4daa326de03b4701768c3491a6ad9ee" -dependencies = [ - "futures-core", - "futures-sink", - "js-sys", - "pin-project-lite", - "thiserror", - "tracing", -] - -[[package]] -name = "opentelemetry-http" -version = "0.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "302249bd8ee804789faaa7b5b2cbf79bc61cb864714079c644e3828af5b7e811" -dependencies = [ - "async-trait", - "bytes", - "http", - "opentelemetry", -] - -[[package]] -name = "opentelemetry-otlp" -version = "0.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0756af24841e367128ef31c831999937b8b5c5197d47914590d8f4e2e88c2e1a" -dependencies = [ - "flate2", - "http", - "httpdate", - "opentelemetry", - "opentelemetry-http", - "opentelemetry-proto", - "opentelemetry_sdk", - "prost", - "thiserror", - "tokio", - "tonic", - "tonic-types", -] - -[[package]] -name = "opentelemetry-proto" -version = "0.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d576f5dddc3299341bcd85a04be17b2564844c0c9563214f02d85f2524d1afae" -dependencies = [ - "opentelemetry", - "opentelemetry_sdk", - "prost", - "tonic", - "tonic-prost", -] - -[[package]] -name = "opentelemetry_sdk" -version = "0.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "372a912db2974d1990207006fd0e3aa0ef3fd4ad3be43c65cfaadf2206866061" -dependencies = [ - "futures-channel", - "futures-executor", - "futures-util", - "opentelemetry", - "percent-encoding", - "portable-atomic", - "rand 0.9.5", - "thiserror", - "tokio", - "tokio-stream", -] - [[package]] name = "ordered-float" version = "2.10.1" @@ -3074,15 +2852,6 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" -[[package]] -name = "rapidhash" -version = "4.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e" -dependencies = [ - "rustversion", -] - [[package]] name = "rcgen" version = "0.14.10" @@ -3587,15 +3356,6 @@ dependencies = [ "digest 0.11.3", ] -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - [[package]] name = "shlex" version = "2.0.1" @@ -4035,15 +3795,6 @@ dependencies = [ "syn 3.0.3", ] -[[package]] -name = "thread_local" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" -dependencies = [ - "cfg-if", -] - [[package]] name = "time" version = "0.3.54" @@ -4165,7 +3916,6 @@ dependencies = [ "axum", "base64 0.22.1", "bytes", - "flate2", "h2", "http", "http-body", @@ -4256,23 +4006,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "tower-http" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" -dependencies = [ - "bitflags 2.13.1", - "bytes", - "http", - "http-body", - "pin-project-lite", - "tower-layer", - "tower-service", - "tracing", - "uuid", -] - [[package]] name = "tower-http" version = "0.7.1" @@ -4335,64 +4068,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - -[[package]] -name = "tracing-opentelemetry" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a904802a1b902f43638b677ff2a650847e3b4404101b6c586d648e8c1e3e8fe" -dependencies = [ - "js-sys", - "opentelemetry", - "tracing", - "tracing-core", - "tracing-log", - "tracing-subscriber", - "web-time", -] - -[[package]] -name = "tracing-serde" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" -dependencies = [ - "serde", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" -dependencies = [ - "matchers", - "nu-ansi-term", - "once_cell", - "regex-automata", - "serde", - "serde_json", - "sharded-slab", - "smallvec", - "thread_local", - "tracing", - "tracing-core", - "tracing-log", - "tracing-serde", ] [[package]] @@ -4515,12 +4190,6 @@ dependencies = [ "vsimd", ] -[[package]] -name = "valuable" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" - [[package]] name = "vcpkg" version = "0.2.15" @@ -4628,16 +4297,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - [[package]] name = "webpki-root-certs" version = "1.0.12" @@ -4699,65 +4358,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - [[package]] name = "windows-sys" version = "0.52.0" diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 6b0f5d5d1e..2213644db9 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -148,21 +148,11 @@ name = "podman_resource_limits" path = "tests/podman_resource_limits.rs" required-features = ["e2e-podman"] -[[test]] -name = "provider_refresh_handles" -path = "tests/provider_refresh_handles.rs" -required-features = ["e2e-podman"] - [[test]] name = "provider_github_app" path = "tests/provider_github_app.rs" required-features = ["e2e-podman"] -[[test]] -name = "provider_readiness" -path = "tests/provider_readiness.rs" -required-features = ["e2e-docker"] - [[test]] name = "vm_gateway_start" path = "tests/vm_gateway_start.rs" @@ -173,11 +163,6 @@ name = "vm_corporate_proxy" path = "tests/vm_corporate_proxy.rs" required-features = ["e2e-vm"] -[[test]] -name = "provider_token_exchange" -path = "tests/provider_token_exchange.rs" -required-features = ["e2e-podman"] - [[test]] name = "kubernetes_ha_rebalancing" path = "tests/kubernetes_ha_rebalancing.rs" @@ -233,16 +218,9 @@ name = "gpu" path = "tests/gpu.rs" required-features = ["e2e-gpu"] -[[test]] -name = "otlp_relay" -path = "tests/otlp_relay.rs" -required-features = ["e2e-local-container-driver"] - [dependencies] openshell-core = { path = "../../crates/openshell-core", default-features = false, features = ["jwt"], optional = true } openshell-crypto = { path = "../../crates/openshell-crypto" } -openshell-otel-test-support = { path = "../../crates/openshell-otel-test-support" } -opentelemetry-proto = { version = "0.33", default-features = false, features = ["gen-tonic", "trace"] } base64 = "0.22" bollard = "0.20" bytes = "1" diff --git a/e2e/rust/e2e-podman.sh b/e2e/rust/e2e-podman.sh index db4c26dbe8..78afd1f7f2 100755 --- a/e2e/rust/e2e-podman.sh +++ b/e2e/rust/e2e-podman.sh @@ -28,12 +28,10 @@ PODMAN_CI_TESTS=( host_gateway_alias local_driver_token_restart ocsf_jsonl_conformance - otlp_relay podman_corporate_proxy podman_gateway_start podman_host_gateway provider_github_app - provider_token_exchange sandbox_compat_signals_sched ) @@ -87,21 +85,6 @@ if [ "${1:-}" = "${RUN_WITH_GATEWAY_COMMAND}" ]; then exit 0 fi -# An empty selector runs the full Podman suite, including provider_token_exchange. -if [ "${#SELECTED_TESTS[@]}" -eq 0 ] || [[ " ${SELECTED_TESTS[*]} " == *" provider_token_exchange "* ]]; then - export OPENSHELL_E2E_SPIFFE_FIXTURE="${OPENSHELL_E2E_SPIFFE_FIXTURE:-1}" -fi - -# When the selection includes otlp_relay, enable OTLP export in the generated -# gateway config so the test can bind a collector stub on this port. All -# selected tests share the gateway, so they run with the relay enabled too. -# Containers reach the host through host.containers.internal. Set the -# variable to an empty string to disable export and run the relay's inert -# case instead. -if [ "${#SELECTED_TESTS[@]}" -eq 0 ] || [[ " ${SELECTED_TESTS[*]} " == *" otlp_relay "* ]]; then - export OPENSHELL_E2E_OTLP_ENDPOINT="${OPENSHELL_E2E_OTLP_ENDPOINT-http://host.containers.internal:4317}" -fi - if [ -n "${OPENSHELL_GATEWAY_ENDPOINT:-}" ] && [ -z "${OPENSHELL_BIN:-}" ]; then cargo build -p openshell-cli export OPENSHELL_BIN="${ROOT}/target/debug/openshell" diff --git a/e2e/rust/tests/otlp_relay.rs b/e2e/rust/tests/otlp_relay.rs deleted file mode 100644 index fe53630044..0000000000 --- a/e2e/rust/tests/otlp_relay.rs +++ /dev/null @@ -1,420 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Supervisor-direct OTLP trace relay. -//! -//! The gateway wrapper writes `[openshell.gateway.otlp].endpoint` from -//! `OPENSHELL_E2E_OTLP_ENDPOINT` and enables `[openshell.gateway.otlp.agent]` -//! unless `OPENSHELL_E2E_OTLP_AGENT=0`. These tests bind a collector stub on -//! that endpoint's port and prove that a span exported from inside a sandbox -//! arrives with the supervisor's attribution. With the variable unset or -//! empty, or with the relay disabled, the inert case runs instead. - -#![cfg(feature = "e2e-local-container-driver")] - -use std::collections::HashMap; -use std::net::SocketAddr; -use std::time::Duration; - -use base64::Engine as _; -use openshell_e2e::harness::cli; -use openshell_e2e::harness::sandbox::SandboxGuard; -use openshell_otel_test_support::OtlpTestServer; -use openshell_otel_test_support::relay::{ - SANDBOX_ID_KEY, SOURCE_KEY, SOURCE_VALUE, encoded_trace_request, -}; -use serial_test::serial; - -const ENV_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_ENDPOINT"; -const ENV_PROTOCOL: &str = "OTEL_EXPORTER_OTLP_PROTOCOL"; -const ENV_COLLECTOR: &str = "OPENSHELL_OTLP_ENDPOINT"; - -/// Posts the base64 body from `OTLP_BODY_B64` to the relay and prints the -/// status plus the complete environment, one `ENV key=value` line each, so -/// the test can check values and prove the collector address is nowhere. -const EXPORT_SCRIPT: &str = r#" -import base64, os, requests -body = base64.b64decode(os.environ["OTLP_BODY_B64"]) -url = os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] + "/v1/traces" -response = requests.post(url, data=body, headers={"Content-Type": "application/x-protobuf"}, timeout=10) -print("STATUS", response.status_code) -for key, value in sorted(os.environ.items()): - if key != "OTLP_BODY_B64": - print("ENV " + key + "=" + value) -"#; - -/// Main-process variant: the payload is embedded so no `--env` is needed, -/// and the process exits the moment the POST returns. -fn exit_script(body_b64: &str) -> String { - format!( - r#" -import base64, os, requests -body = base64.b64decode("{body_b64}") -url = os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] + "/v1/traces" -response = requests.post(url, data=body, headers={{"Content-Type": "application/x-protobuf"}}, timeout=10) -raise SystemExit(0 if response.status_code == 200 else 1) -"# - ) -} - -/// For the inert case: reports whether an endpoint was injected, then posts -/// to the relay address directly and reports the failure class instead of -/// raising. -const INERT_SCRIPT: &str = r#" -import os, requests -print("ENDPOINT", os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "unset")) -url = "http://192.0.0.8:4318/v1/traces" -try: - response = requests.post(url, data=b"", headers={"Content-Type": "application/x-protobuf"}, timeout=3) - print("STATUS", response.status_code) -except Exception as error: - print("ERROR", type(error).__name__) -"#; - -/// The collector the relay forwards to, when the harness enabled both OTLP -/// export and the agent trace relay. -fn collector_endpoint() -> Option { - let relay_enabled = std::env::var("OPENSHELL_E2E_OTLP_AGENT").as_deref() != Ok("0"); - std::env::var("OPENSHELL_E2E_OTLP_ENDPOINT") - .ok() - .filter(|value| !value.is_empty() && relay_enabled) -} - -fn collector_bind_addr(endpoint: &str) -> SocketAddr { - let url = url::Url::parse(endpoint).expect("OPENSHELL_E2E_OTLP_ENDPOINT is a URL"); - let port = url - .port_or_known_default() - .expect("OPENSHELL_E2E_OTLP_ENDPOINT names a port"); - // Containers reach the host through its bridge address, not loopback. - SocketAddr::from(([0, 0, 0, 0], port)) -} - -/// `host:port` of the collector as the gateway configures it, the string -/// that must not appear anywhere in the sandbox environment. -fn collector_host_port(endpoint: &str) -> String { - let url = url::Url::parse(endpoint).expect("OPENSHELL_E2E_OTLP_ENDPOINT is a URL"); - format!( - "{}:{}", - url.host_str().expect("collector host"), - url.port_or_known_default().expect("collector port") - ) -} - -/// One span with the agent's own service name and spoofed values for both -/// attribution keys, base64-encoded for the workload's environment. -fn encoded_request(span_name: &str) -> String { - let request = encoded_trace_request( - span_name, - &[ - ("service.name", "e2e-agent"), - (SANDBOX_ID_KEY, "spoofed"), - (SOURCE_KEY, "infrastructure"), - ], - ); - base64::engine::general_purpose::STANDARD.encode(request) -} - -/// The harness CLI runner with a `Result` for the failure path. -async fn run_cli(args: &[&str]) -> Result { - let (output, code) = cli::run_cli(args).await; - if code != 0 { - return Err(format!( - "openshell {} failed (exit {code}):\n{output}", - args.join(" ") - )); - } - Ok(output) -} - -async fn sandbox_id(name: &str) -> Result { - let details = run_cli(&["sandbox", "get", name, "--output", "json"]).await?; - let details: serde_json::Value = - serde_json::from_str(&details).map_err(|e| format!("parse sandbox JSON: {e}"))?; - details["id"] - .as_str() - .map(str::to_string) - .ok_or_else(|| format!("sandbox has no id: {details}")) -} - -/// Polls `sandbox get` until the gateway no longer knows the sandbox, so -/// the next create does not overlap the previous teardown. -async fn wait_for_sandbox_gone(name: &str) { - let deadline = tokio::time::Instant::now() + Duration::from_secs(60); - while run_cli(&["sandbox", "get", name]).await.is_ok() { - if tokio::time::Instant::now() >= deadline { - eprintln!("sandbox {name} still listed after delete; continuing"); - return; - } - tokio::time::sleep(Duration::from_millis(250)).await; - } -} - -/// Waits for the sandbox to reach `phase` through the harness, then returns -/// its details for further assertions. -async fn wait_for_sandbox_phase(name: &str, phase: &str) -> Result { - cli::wait_for_sandbox_phase(name, phase, Duration::from_secs(60)).await?; - run_cli(&["sandbox", "get", name]).await -} - -async fn wait_for_sandbox_logs( - sandbox_name: &str, - expected: impl Fn(&str) -> bool, -) -> Result { - let deadline = tokio::time::Instant::now() + Duration::from_secs(15); - loop { - let logs = run_cli(&[ - "logs", - sandbox_name, - "-n", - "500", - "--since", - "5m", - "--source", - "sandbox", - ]) - .await?; - if expected(&logs) { - return Ok(logs); - } - if tokio::time::Instant::now() >= deadline { - return Err(format!( - "timed out waiting for expected sandbox logs:\n{logs}" - )); - } - tokio::time::sleep(Duration::from_millis(250)).await; - } -} - -/// Waits up to `within` until the collector holds every span in `names`, -/// returning the resource attributes keyed by span name. -async fn wait_for_spans( - collector: &OtlpTestServer, - names: &[&str], - within: Duration, -) -> Result>, String> { - let deadline = tokio::time::Instant::now() + within; - loop { - let received = collector.received(); - let received_names: Vec<&str> = received - .spans - .iter() - .map(|span| span.name.as_str()) - .collect(); - if names.iter().all(|name| received_names.contains(name)) { - // Supervisor batches share the collector; `span_resources` pairs - // every span with the resource of the batch it arrived in. - let by_name = received - .spans - .iter() - .zip(received.span_resources.iter()) - .map(|(span, attributes)| (span.name.clone(), attributes.clone())) - .collect(); - return Ok(by_name); - } - if tokio::time::Instant::now() >= deadline { - return Err(format!( - "collector received {received_names:?}, expected all of {names:?}" - )); - } - tokio::time::sleep(Duration::from_millis(250)).await; - } -} - -/// The collector keeps the last value per key, so a spoofed attribute that -/// was appended to rather than replaced is only visible as a duplicate. -fn assert_no_duplicate_resource_keys(collector: &OtlpTestServer) { - let duplicates = collector.received().duplicate_resource_keys; - assert!( - duplicates.is_empty(), - "attribution keys were appended, not replaced: {duplicates:?}" - ); -} - -fn assert_attribution(attributes: &HashMap, sandbox_id: &str) { - assert!( - !attributes - .values() - .any(|value| value == "spoofed" || value == "infrastructure"), - "agent-supplied attribution values must be discarded: {attributes:?}" - ); - assert_eq!( - attributes.get("service.name").map(String::as_str), - Some("e2e-agent"), - "agent service name is preserved: {attributes:?}" - ); - assert_eq!( - attributes.get(SOURCE_KEY).map(String::as_str), - Some(SOURCE_VALUE), - "{attributes:?}" - ); - assert_eq!( - attributes.get(SANDBOX_ID_KEY).map(String::as_str), - Some(sandbox_id), - "spoofed sandbox id is replaced: {attributes:?}" - ); -} - -#[tokio::test] -#[serial] -async fn agent_span_reaches_collector_with_attribution() { - let Some(endpoint) = collector_endpoint() else { - eprintln!("OPENSHELL_E2E_OTLP_ENDPOINT is unset; skipping the collector case"); - return; - }; - let collector = OtlpTestServer::start_on(collector_bind_addr(&endpoint)).await; - - let body = format!("OTLP_BODY_B64={}", encoded_request("e2e-span")); - let mut sandbox = SandboxGuard::create(&[ - "--env", - &body, - "--no-auto-providers", - "--", - "python3", - "-c", - EXPORT_SCRIPT, - ]) - .await - .expect("sandbox exports one span to the relay"); - let output = sandbox.create_output.clone(); - assert!( - output.contains("STATUS 200"), - "relay must accept the export:\n{output}" - ); - // US1-S3: the exact values a standard SDK needs. - assert!( - output.contains(&format!("ENV {ENV_ENDPOINT}=http://192.0.0.8:4318")), - "the relay endpoint is set for the workload:\n{output}" - ); - assert!( - output.contains(&format!("ENV {ENV_PROTOCOL}=http/protobuf")), - "the exporter protocol is set for the workload:\n{output}" - ); - // US1-S4: neither the variable nor the address itself is present anywhere. - assert!( - !output.contains(ENV_COLLECTOR), - "the collector variable must not be visible inside the sandbox:\n{output}" - ); - let host_port = collector_host_port(&endpoint); - assert!( - !output.contains(&host_port), - "the collector address {host_port} must not appear in the sandbox environment:\n{output}" - ); - - let id = sandbox_id(&sandbox.name).await.expect("sandbox id"); - // US1-S1: within 5 seconds. - let spans = wait_for_spans(&collector, &["e2e-span"], Duration::from_secs(5)) - .await - .expect("span reaches the collector stub within 5 s"); - assert_no_duplicate_resource_keys(&collector); - assert_attribution(&spans["e2e-span"], &id); - - sandbox.cleanup().await; - drop(collector.shutdown().await); -} - -#[tokio::test] -#[serial] -async fn relay_is_inert_without_collector() { - if collector_endpoint().is_some() { - eprintln!("the agent trace relay is enabled; skipping the inert case"); - return; - } - - let mut sandbox = - SandboxGuard::create(&["--no-auto-providers", "--", "python3", "-c", INERT_SCRIPT]) - .await - .expect("sandbox attempts an export without a collector"); - let output = sandbox.create_output.clone(); - assert!( - output.contains("ENDPOINT unset"), - "no relay endpoint is injected while the relay is inactive:\n{output}" - ); - assert!( - output.contains("ERROR ConnectionError"), - "the export must fail with a connection error, not a timeout:\n{output}" - ); - - let logs = wait_for_sandbox_logs(&sandbox.name, |logs| { - logs.contains("OTLP agent trace relay inactive") - }) - .await - .expect("supervisor reports the relay as inactive"); - assert!(!logs.contains("OTLP agent trace relay enabled"), "{logs}"); - - sandbox.cleanup().await; -} - -#[tokio::test] -#[serial] -async fn span_emitted_before_exit_is_delivered() { - let Some(endpoint) = collector_endpoint() else { - eprintln!("OPENSHELL_E2E_OTLP_ENDPOINT is unset; skipping the flush case"); - return; - }; - let collector = OtlpTestServer::start_on(collector_bind_addr(&endpoint)).await; - - // The main process posts and exits at once; the supervisor must flush - // the batch before it reports the exit. Five cycles stand in for SC-005. - let names: Vec = (1..=5).map(|i| format!("exit-span-{i}")).collect(); - let mut ids = HashMap::new(); - for name in &names { - let script = exit_script(&encoded_request(name)); - let mut sandbox = SandboxGuard::create_detached_main(&["python3", "-c", &script]) - .await - .expect("sandbox whose main process exports one span and exits"); - let details = match wait_for_sandbox_phase(&sandbox.name, "Completed").await { - Ok(details) => details, - Err(error) => { - let logs = run_cli(&[ - "logs", - &sandbox.name, - "-n", - "500", - "--since", - "5m", - "--source", - "sandbox", - ]) - .await - .unwrap_or_else(|e| format!("(logs unavailable: {e})")); - sandbox.cleanup().await; - panic!( - "main process did not exit after the export: {error}\nsupervisor logs:\n{logs}" - ); - } - }; - assert!( - !details.contains("Exit Code: 1"), - "relay must accept the export:\n{details}" - ); - // US4-S1: the gateway marks the sandbox Completed only after the - // supervisor's exit report, and the supervisor flushes before that - // report, so the span must already be at the collector now. - let snapshot = collector.received(); - assert!( - snapshot.spans.iter().any(|span| &span.name == name), - "{name} must reach the collector before the exit is reported; collector holds {:?}", - snapshot - .spans - .iter() - .map(|span| span.name.as_str()) - .collect::>() - ); - ids.insert( - name.clone(), - sandbox_id(&sandbox.name).await.expect("sandbox id"), - ); - sandbox.cleanup().await; - wait_for_sandbox_gone(&sandbox.name).await; - } - - let name_refs: Vec<&str> = names.iter().map(String::as_str).collect(); - let spans = wait_for_spans(&collector, &name_refs, Duration::from_secs(15)) - .await - .expect("every span emitted right before exit reaches the collector"); - assert_no_duplicate_resource_keys(&collector); - for name in &names { - assert_attribution(&spans[name], &ids[name]); - } - drop(collector.shutdown().await); -} diff --git a/e2e/rust/tests/provider_readiness.rs b/e2e/rust/tests/provider_readiness.rs deleted file mode 100644 index b7d1256641..0000000000 --- a/e2e/rust/tests/provider_readiness.rs +++ /dev/null @@ -1,1591 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e-docker")] - -//! Provider changes acknowledged through a real sandbox HTTPS request path. -//! -//! Attach, update, and detach wait for confirmation of their exact saved changes. -//! Clients launched after attach and update keep their own static references. -//! The first request from the updated launch uses the acknowledged credential; -//! detach revokes both retained references and removes them from future launches. -//! Only the synthetic backends and privileged provider CLI receive keys; -//! workload files, responses, and diagnostics contain status information only. - -use std::net::Ipv4Addr; -use std::path::{Path, PathBuf}; -use std::process::Stdio; -use std::time::Duration; - -use openshell_e2e::harness::binary::openshell_cmd; -use openshell_e2e::harness::container::{ContainerEngine, e2e_network_name}; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::sandbox::{E2E_WORKLOAD_IMAGE, SandboxGuard}; -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; -use tempfile::TempDir; -use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines}; -use tokio::process::{Child, ChildStdin, ChildStdout, Command}; -use tokio::time::{Instant, sleep, timeout}; - -const TOKEN_ENV: &str = "PROVIDER_READINESS_E2E_TOKEN"; -const BACKEND_PORT: u16 = 8443; -const OTHER_BACKEND_PORT: u16 = 8444; -const READY: &str = "provider-readiness-client-ready"; -const CONTROL: &str = "/sandbox/provider-readiness-probe"; -const RESULT: &str = "/sandbox/provider-readiness-result"; -const COMMAND_TIMEOUT: Duration = Duration::from_secs(60); -const IMAGE_BUILD_TIMEOUT: Duration = Duration::from_secs(300); -const READINESS_TIMEOUT_SECONDS: &str = "90"; -const READINESS_COMMAND_TIMEOUT: Duration = Duration::from_secs(105); -const GATEWAY_READY_TIMEOUT: Duration = Duration::from_secs(120); - -// Keys arrive on a private stdin pipe after process creation. Neither the -// command line nor any file contains them, and HTTP/server errors are silent. -const BACKEND: &str = r" -import http.server, json, ssl, sys, threading - -config = json.loads(sys.stdin.readline()) -keys = config.pop('keys') -lock = threading.Lock() -state = {'phase': 0, 'total': 0, 'accepted': [0, 0], 'rejected': 0} - -class Server(http.server.ThreadingHTTPServer): - daemon_threads = True - def handle_error(self, request, client_address): - pass - -class Handler(http.server.BaseHTTPRequestHandler): - def log_message(self, *args): - pass - def do_POST(self): - with lock: - phase = state['phase'] - valid = self.headers.get('Authorization') == 'Bearer ' + keys[phase] - state['total'] += 1 - if valid: - state['accepted'][phase] += 1 - else: - state['rejected'] += 1 - body = json.dumps({'authorized': valid, 'phase': phase}).encode() - self.send_response(200 if valid else 401) - self.send_header('Content-Type', 'application/json') - self.send_header('Content-Length', str(len(body))) - self.send_header('Connection', 'close') - self.end_headers() - self.wfile.write(body) - -context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) -context.minimum_version = ssl.TLSVersion.TLSv1_2 -context.load_cert_chain(config['certificate'], config['private_key']) -servers = [] -for port in config['ports']: - server = Server(('0.0.0.0', port), Handler) - server.socket = context.wrap_socket(server.socket, server_side=True) - threading.Thread(target=server.serve_forever, daemon=True).start() - servers.append(server) -print(json.dumps({'ready': True}), flush=True) - -for line in sys.stdin: - request = json.loads(line) - with lock: - if request['command'] == 'rotate': - state['phase'] = 1 - print(json.dumps(state), flush=True) -for server in servers: - server.shutdown() - server.server_close() -"; - -// This source is safe to place in the workload image: it contains environment -// key names and endpoint coordinates, but never a key value or issued handle. -const CLIENT: &str = r" -import json, os, pathlib, re, ssl, sys, time, urllib.error, urllib.request - -config = json.loads(sys.argv[1]) -key = 'PROVIDER_READINESS_E2E_TOKEN' -token = os.environ.get(key, '') -if not re.fullmatch(r'openshell:resolve:env:v[1-9][0-9]*_' + key, token): - print('client did not receive a revision-scoped reference', flush=True) - sys.exit(64) -client = sys.argv[2] -if client not in ('a', 'b'): - sys.exit(64) -pid = os.getpid() -control = pathlib.Path('/sandbox/provider-readiness-probe-' + client) -result = pathlib.Path('/sandbox/provider-readiness-result-' + client) - -def probe(phase): - host, port, path = config['host'], config['port'], '/v1/chat/completions' - target = phase[:-8] if phase.endswith('_control') else phase - if target == 'wrong_host': - host = config['other_host'] - elif target == 'wrong_port': - port = config['other_port'] - elif target == 'wrong_path': - path = '/outside' - url = 'https://%s:%s%s' % (host, port, path) - response = {'phase': phase, 'pid': pid, 'same_reference': os.environ.get(key) == token, - 'ok': False, 'status': 0, 'backend_phase': -1} - try: - context = ssl.create_default_context() - if phase == 'untrusted_ca': - # An empty trust store proves this client does verify TLS. - context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) - headers = {'Content-Type': 'application/json'} - if not phase.endswith('_control'): - headers['Authorization'] = 'Bearer ' + token - request = urllib.request.Request(url, data=b'{}', headers=headers) - try: - reply = urllib.request.urlopen(request, context=context, timeout=5) - except urllib.error.HTTPError as error: - # The backend's safe 401 body proves the negative endpoint is - # reachable before a credential-bearing request is denied. - reply = error - with reply: - body = json.loads(reply.read(1024)) - response['ok'] = body.get('authorized') is True - response['status'] = reply.status - response['backend_phase'] = body.get('phase', -1) - except Exception as error: - # HTTP/TLS exceptions can embed headers; expose only fixed type names. - response['error_kind'] = type(error).__name__ - response['reason_kind'] = type(getattr(error, 'reason', None)).__name__ - return response - -print('provider-readiness-client-ready', flush=True) -deadline = time.monotonic() + 600 -while time.monotonic() < deadline: - if control.exists(): - phase = control.read_text().strip() - control.unlink() - temporary = result.with_suffix('.tmp') - temporary.write_text(json.dumps(probe(phase))) - temporary.replace(result) - time.sleep(0.05) -"; - -struct FixtureImage { - engine: ContainerEngine, - tag: String, -} - -impl FixtureImage { - fn new() -> Result { - Ok(Self { - engine: ContainerEngine::from_env()?, - tag: format!( - "localhost/openshell-e2e-readiness-{}-{:016x}:latest", - std::process::id(), - rand::random::(), - ), - }) - } - - fn tag(&self) -> &str { - &self.tag - } - - async fn build(&self, dockerfile: &Path, context: &Path, label: &str) -> Result<(), String> { - let mut command = Command::from(self.engine.command()); - command - .args(["build", "--file"]) - .arg(dockerfile) - .args(["--tag", &self.tag]) - .arg(context); - checked_command_with_timeout(&mut command, label, IMAGE_BUILD_TIMEOUT) - .await - .map(|_| ()) - } - - async fn remove(&self) -> Result<(), String> { - let mut command = Command::from(self.engine.command()); - command.args(["image", "rm", "--force", &self.tag]); - // Teardown is explicit and bounded. This type has no Drop subprocess - // that could block the test runtime after the removal deadline expires. - checked_command(&mut command, "remove fixture image") - .await - .map(|_| ()) - } -} - -// This fixture owns the only test in its binary. The wrapper's gateway is -// private to this run, so replacing its supervisor image cannot affect another -// test while the public fixture CA is installed in the supervisor trust store. -struct GatewayTrustFixture { - directory: PathBuf, - supervisor_image: String, - health_port: u16, - restore_required: bool, -} - -impl GatewayTrustFixture { - fn load() -> Result { - if std::env::var_os("OPENSHELL_GATEWAY_ENDPOINT").is_some() - || std::env::var_os("OPENSHELL_E2E_GATEWAY_BIN").is_none() - || std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("docker") - || std::env::var("OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER") - .is_ok_and(|value| value != "0") - { - return Err("provider readiness fixture requires a wrapper-owned gateway with the bundled Docker driver".to_string()); - } - let args_file = std::env::var_os("OPENSHELL_E2E_GATEWAY_ARGS_FILE") - .ok_or("managed gateway argument metadata is missing")?; - let directory = Path::new(&args_file) - .parent() - .ok_or("managed gateway arguments have no parent directory")? - .to_path_buf(); - let raw = - std::fs::read(args_file).map_err(|_| "could not read managed gateway arguments")?; - let args = raw - .split(|byte| *byte == 0) - .filter(|arg| !arg.is_empty()) - .map(std::str::from_utf8) - .collect::, _>>() - .map_err(|_| "managed gateway arguments were not UTF-8")?; - let argument = |name| { - let mut values = args.windows(2).filter(|pair| pair[0] == name); - let value = values.next().ok_or("managed gateway argument is missing")?[1]; - if values.next().is_some() { - return Err("managed gateway argument is duplicated"); - } - Ok(value) - }; - let health_port = argument("--health-port")? - .parse::() - .map_err(|_| "managed gateway health port is invalid")?; - let supervisor_image = std::env::var("OPENSHELL_SUPERVISOR_IMAGE") - .map_err(|_| "managed supervisor image is missing")?; - Ok(Self { - directory, - supervisor_image, - health_port, - restore_required: false, - }) - } - - async fn apply(&mut self, image: &str) -> Result<(), String> { - self.restore_required = true; - restart_fixture_gateway(self.health_port, Some(image)).await - } - - async fn restore(&mut self) -> Result<(), String> { - if !self.restore_required { - return Ok(()); - } - restart_fixture_gateway(self.health_port, None) - .await - .map_err(|_| "could not restore original gateway runtime")?; - self.restore_required = false; - Ok(()) - } -} - -async fn restart_fixture_gateway( - health_port: u16, - supervisor_image: Option<&str>, -) -> Result<(), String> { - let mut gateway = ManagedGateway::from_env() - .map_err(|_| "could not load managed gateway restart metadata")? - .ok_or("managed gateway restart metadata disappeared")?; - if let Some(image) = supervisor_image { - gateway.set_supervisor_image(image); - } - gateway - .stop() - .map_err(|_| "could not stop fixture gateway")?; - gateway - .start() - .map_err(|_| "could not restart fixture gateway")?; - let url = format!("http://127.0.0.1:{health_port}/healthz"); - let deadline = Instant::now() + GATEWAY_READY_TIMEOUT; - loop { - if checked_command( - Command::new("curl").args(["--silent", "--fail", "--max-time", "2", &url]), - "check fixture gateway health", - ) - .await - .is_ok() - { - return Ok(()); - } - if Instant::now() >= deadline { - return Err("fixture gateway did not become healthy".to_string()); - } - sleep(Duration::from_millis(250)).await; - } -} - -struct Backend { - engine: ContainerEngine, - name: String, - network: String, - namespace: String, - child: Option, - input: Option, - output: Option>>, - launch_attempted: bool, -} - -struct PersistentClient { - child: Child, - // Keep the stream open after reading the marker so the CLI can continue - // relaying the same remote process until explicit sandbox teardown. - _output: Lines>, -} - -impl PersistentClient { - async fn start( - sandbox: &SandboxGuard, - python: &str, - config: &str, - client: &str, - ) -> Result { - let mut command = sandbox_command( - sandbox, - &[ - python, - "-u", - "/opt/provider-readiness-client.py", - config, - client, - ], - ); - let mut child = command - .stdin(Stdio::null()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .kill_on_drop(true) - .spawn() - .map_err(|_| "persistent workload exec could not start")?; - let output = child - .stdout - .take() - .ok_or("workload stdout was unavailable")?; - let mut output = BufReader::new(output).lines(); - timeout(COMMAND_TIMEOUT, async { - while let Some(line) = output - .next_line() - .await - .map_err(|_| "workload marker could not be read")? - { - if line.trim() == READY { - return Ok(()); - } - // A CLI or workload error can contain environment material. - // Ignore every unrecognized line without including it in errors. - } - Err("persistent workload closed before its ready marker") - }) - .await - .map_err(|_| "persistent workload ready marker timed out")??; - Ok(Self { - child, - _output: output, - }) - } - - async fn stop(&mut self) -> Result<(), String> { - // Sandbox deletion ends the remote workload; reap the retained relay - // even if the remote deletion or normal stream shutdown fails. - timeout(COMMAND_TIMEOUT, self.child.kill()) - .await - .map_err(|_| "persistent client cleanup timed out")? - .map_err(|_| "persistent client cleanup failed".to_string()) - } -} - -impl Backend { - fn new(name: String) -> Result { - Ok(Self { - engine: ContainerEngine::from_env()?, - name, - network: e2e_network_name().ok_or("fixture requires the managed Docker network")?, - namespace: std::env::var("OPENSHELL_E2E_SANDBOX_NAMESPACE") - .map_err(|_| "fixture requires the managed Docker namespace")?, - child: None, - input: None, - output: None, - launch_attempted: false, - }) - } - - async fn spawn(&mut self, base: &str, tls_directory: &Path) -> Result { - let tls_directory = tls_directory - .to_str() - .filter(|path| !path.contains([':', '\n', '\r'])) - .ok_or("fixture TLS mount path is invalid")?; - // Docker's structured `--mount` syntax cannot request SELinux - // relabeling. Both fixture backends mount this ephemeral directory, so - // use the shared `z` label rather than the single-container `Z` label. - let mount = format!("{tls_directory}:/fixture-tls:ro,z"); - let namespace_label = format!("openshell.ai/sandbox-namespace={}", self.namespace); - let mut command = Command::from(self.engine.command()); - command - .args([ - "run", - "--rm", - "--interactive", - "--pull=never", - "--name", - &self.name, - "--network", - &self.network, - "--label", - "openshell.ai/managed-by=openshell", - "--label", - &namespace_label, - "--label", - "openshell.ai/isolation-role=fixture", - "--read-only", - "--cap-drop=ALL", - "--security-opt=no-new-privileges:true", - "--volume", - &mount, - "--entrypoint", - "/usr/bin/python3", - base, - "-u", - "-c", - BACKEND, - ]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .kill_on_drop(true); - // Record the unique container name before creation. Every Result exit - // removes it, including a failed readiness exchange after Docker starts. - // Wrapper-scoped labels also let wrapper teardown reap an interrupted run. - self.launch_attempted = true; - let child = command - .spawn() - .map_err(|_| "could not start synthetic HTTPS backend".to_string())?; - self.child = Some(child); - let child = self.child.as_mut().ok_or("backend child was absent")?; - self.input = Some( - child - .stdin - .take() - .ok_or("backend stdin was not available")?, - ); - let output = child - .stdout - .take() - .ok_or("backend stdout was not available")?; - self.output = Some(BufReader::new(output).lines()); - // Python waits for its private stdin configuration before reading TLS - // files. Discover the actual address first so its certificate can name - // that exact endpoint without DNS or an unverified TLS connection. - self.address().await - } - - async fn address(&mut self) -> Result { - let deadline = Instant::now() + COMMAND_TIMEOUT; - loop { - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - return Err("backend bridge address did not become available".to_string()); - } - let mut inspect = Command::from(self.engine.command()); - inspect.args([ - "inspect", - "--format", - "{{json .NetworkSettings.Networks}}", - &self.name, - ]); - if let Ok(output) = checked_command_with_timeout( - &mut inspect, - "inspect backend bridge address", - remaining.min(Duration::from_secs(2)), - ) - .await - { - let networks: Value = serde_json::from_str(&output) - .map_err(|_| "backend network metadata was invalid")?; - if let Some(address) = networks[&self.network]["IPAddress"] - .as_str() - .filter(|address| !address.is_empty()) - { - let address = address - .parse::() - .map_err(|_| "backend network address was not IPv4")?; - if !address.is_private() { - return Err("fixture backend requires a private bridge address".to_string()); - } - return Ok(address.to_string()); - } - } - if self - .child - .as_mut() - .ok_or("backend child was absent")? - .try_wait() - .map_err(|_| "could not inspect backend client status")? - .is_some() - { - return Err("backend exited before its bridge address was available".to_string()); - } - sleep(Duration::from_millis(100)).await; - } - } - - async fn initialize(&mut self, config: &Value) -> Result<(), String> { - if self.exchange(config).await?["ready"] != true { - return Err("synthetic HTTPS backend did not become ready".to_string()); - } - Ok(()) - } - - async fn exchange(&mut self, request: &Value) -> Result { - let mut bytes = - serde_json::to_vec(request).map_err(|_| "backend request encoding failed")?; - bytes.push(b'\n'); - let input = self.input.as_mut().ok_or("backend stdin was absent")?; - let output = self.output.as_mut().ok_or("backend stdout was absent")?; - timeout(COMMAND_TIMEOUT, async { - input - .write_all(&bytes) - .await - .map_err(|_| "backend control write failed")?; - let line = output - .next_line() - .await - .map_err(|_| "backend control read failed")? - .ok_or("backend closed its control stream")?; - serde_json::from_str(&line).map_err(|_| "backend status was not valid JSON") - }) - .await - .map_err(|_| "backend control operation timed out".to_string())? - .map_err(str::to_string) - } - - async fn stop(&mut self) -> Result<(), String> { - // Closing stdin lets Python shut down normally. Removing the named - // container also covers a stalled startup or disconnected Docker client; - // killing the attached client alone cannot prove the container stopped. - drop(self.input.take()); - let mut reap_result = Ok(()); - if let Some(child) = self.child.as_mut() { - reap_result = timeout(COMMAND_TIMEOUT, child.kill()) - .await - .map_err(|_| "backend client teardown timed out".to_string()) - .and_then(|result| { - result.map_err(|_| "backend client teardown failed".to_string()) - }); - } - if !self.launch_attempted { - return reap_result; - } - remove_fixture_container(&self.engine, &self.name).await?; - reap_result - } -} - -/// Counters deliberately contain no authorization headers or secret values. -#[derive(Deserialize, Serialize)] -struct BackendCounts { - phase: u8, - total: u64, - accepted: [u64; 2], - rejected: u64, -} - -// A second endpoint supplies a reachable wrong-host control. Each container -// retains its own counters; their sum proves denied traffic reaches neither. -struct BackendPair { - backends: [Backend; 2], -} - -impl BackendPair { - fn new(name: &str) -> Result { - Ok(Self { - backends: [ - Backend::new(format!("{name}-backend"))?, - Backend::new(format!("{name}-other-backend"))?, - ], - }) - } - - async fn spawn(&mut self, base: &str, tls_directory: &Path) -> Result<[String; 2], String> { - let host = self.backends[0].spawn(base, tls_directory).await?; - let other_host = self.backends[1].spawn(base, tls_directory).await?; - if host == other_host { - return Err("wrong-host control requires a distinct backend address".to_string()); - } - Ok([host, other_host]) - } - - async fn initialize(&mut self, config: &Value) -> Result<(), String> { - for backend in &mut self.backends { - backend.initialize(config).await?; - } - Ok(()) - } - - async fn rotate(&mut self) -> Result<(), String> { - for backend in &mut self.backends { - if backend.exchange(&json!({"command": "rotate"})).await?["phase"] != 1 { - return Err("backend did not switch to the replacement key".to_string()); - } - } - Ok(()) - } - - async fn counts(&mut self) -> Result { - let mut combined: Option = None; - for backend in &mut self.backends { - let response = backend.exchange(&json!({"command": "snapshot"})).await?; - let counters: BackendCounts = - serde_json::from_value(response).map_err(|_| "backend counters were invalid")?; - if let Some(total) = combined.as_mut() { - if total.phase != counters.phase { - return Err("fixture backends disagree on the active key".to_string()); - } - let add = |left: u64, right: u64| { - left.checked_add(right).ok_or("backend counters overflowed") - }; - total.total = add(total.total, counters.total)?; - total.rejected = add(total.rejected, counters.rejected)?; - for (left, right) in total.accepted.iter_mut().zip(counters.accepted) { - *left = add(*left, right)?; - } - } else { - combined = Some(counters); - } - } - serde_json::to_value(combined.ok_or("backend counters were absent")?) - .map_err(|_| "backend counters could not be encoded".to_string()) - } - - async fn stop(&mut self) -> Result<(), String> { - let mut failures = Vec::new(); - for backend in &mut self.backends { - if let Err(error) = backend.stop().await { - failures.push(error); - } - } - if failures.is_empty() { - Ok(()) - } else { - Err(failures.join("; ")) - } - } -} - -async fn checked_command(command: &mut Command, label: &str) -> Result { - checked_command_with_timeout(command, label, COMMAND_TIMEOUT).await -} - -async fn checked_command_with_timeout( - command: &mut Command, - label: &str, - max_wait: Duration, -) -> Result { - command - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .kill_on_drop(true); - let output = timeout(max_wait, command.output()) - .await - .map_err(|_| format!("{label} timed out"))? - .map_err(|_| format!("{label} could not start"))?; - if !output.status.success() { - // CLI arguments, captured output, and subprocess errors can contain - // credential material. Error messages expose only the safe operation. - return Err(format!("{label} failed; subprocess output withheld")); - } - String::from_utf8(output.stdout).map_err(|_| format!("{label} returned invalid UTF-8")) -} - -async fn cli(label: &str, args: &[&str], credential: Option<&str>) -> Result { - let mut command = openshell_cmd(); - command.args(args); - if let Some(credential) = credential { - command.env(TOKEN_ENV, credential); - } - checked_command(&mut command, label).await -} - -fn sandbox_command(sandbox: &SandboxGuard, argv: &[&str]) -> Command { - let mut command = openshell_cmd(); - command - .args(["sandbox", "exec", "--name", &sandbox.name, "--no-tty", "--"]) - .args(argv); - command -} - -async fn generate_certificates( - directory: &Path, - host: &str, - other_host: &str, -) -> Result<(PathBuf, PathBuf), String> { - let ca_key = directory.join("ca.key.fixture"); - let ca = directory.join("ca.crt"); - let key = directory.join("backend.key.fixture"); - let csr = directory.join("backend.csr"); - let certificate = directory.join("backend.crt"); - let extensions = directory.join("backend.ext"); - std::fs::write( - &extensions, - format!( - "basicConstraints=critical,CA:FALSE\nsubjectAltName=IP:{host},IP:{other_host}\nextendedKeyUsage=serverAuth\n" - ), - ) - .map_err(|_| "could not write public TLS certificate extensions")?; - checked_command( - Command::new("openssl") - .args([ - "req", - "-x509", - "-newkey", - "rsa:2048", - "-nodes", - "-days", - "1", - "-subj", - "/CN=provider-readiness-e2e-ca", - "-keyout", - ]) - .arg(&ca_key) - .arg("-out") - .arg(&ca), - "generate fixture CA", - ) - .await?; - checked_command( - Command::new("openssl") - .args([ - "req", - "-newkey", - "rsa:2048", - "-nodes", - "-subj", - &format!("/CN={host}"), - "-keyout", - ]) - .arg(&key) - .arg("-out") - .arg(&csr), - "generate fixture TLS key", - ) - .await?; - checked_command( - Command::new("openssl") - .args(["x509", "-req", "-days", "1", "-in"]) - .arg(&csr) - .arg("-CA") - .arg(&ca) - .arg("-CAkey") - .arg(&ca_key) - .arg("-CAcreateserial") - .arg("-extfile") - .arg(&extensions) - .arg("-out") - .arg(&certificate), - "sign fixture TLS certificate", - ) - .await?; - Ok((certificate, key)) -} - -async fn base_binaries(base: &str) -> Result { - let engine = ContainerEngine::from_env()?; - let name = format!( - "e2e-readiness-binaries-{}-{:016x}", - std::process::id(), - rand::random::() - ); - let namespace = std::env::var("OPENSHELL_E2E_SANDBOX_NAMESPACE") - .map_err(|_| "binary probe requires the managed Docker namespace")?; - let namespace_label = format!("openshell.ai/sandbox-namespace={namespace}"); - let mut command = Command::from(engine.command()); - command.args([ - "run", "--rm", "--name", &name, "--network", "none", - "--label", "openshell.ai/managed-by=openshell", - "--label", &namespace_label, - "--label", "openshell.ai/isolation-role=fixture", - "--entrypoint", "/usr/bin/python3", base, - "-c", "import json,os,shutil,sys; print(json.dumps({'python':os.path.realpath(sys.executable),'curl':shutil.which('curl')}))", - ]); - // A timeout terminates the attached CLI, which does not prove its container - // stopped. Always remove the known name; labels also let wrapper teardown - // recover it if the entire test is cancelled before explicit cleanup. - let result = async { - let output = checked_command(&mut command, "inspect fixture image binaries").await?; - let binaries: Value = - serde_json::from_str(&output).map_err(|_| "image binary probe was invalid")?; - for field in ["python", "curl"] { - if !binaries[field] - .as_str() - .is_some_and(|path| Path::new(path).is_absolute()) - { - return Err(format!("fixture image has no absolute {field} executable")); - } - } - Ok(binaries) - } - .await; - let cleanup = remove_fixture_container(&engine, &name).await; - match (result, cleanup) { - (Ok(binaries), Ok(())) => Ok(binaries), - (Err(error), Ok(())) | (Ok(_), Err(error)) => Err(error), - (Err(error), Err(cleanup)) => Err(format!("{error}; {cleanup}")), - } -} - -async fn remove_fixture_container(engine: &ContainerEngine, name: &str) -> Result<(), String> { - let mut remove = Command::from(engine.command()); - remove.args(["rm", "--force", name]); - let removed = checked_command(&mut remove, "remove fixture container").await; - // --rm may have already removed a normally exited fixture. Only a - // successful exact-name listing can establish absence after rm fails. - if removed.is_err() { - let mut list = Command::from(engine.command()); - let filter = format!("name=^/{name}$"); - list.args(["ps", "--all", "--quiet", "--filter", &filter]); - if !checked_command(&mut list, "verify fixture container removal") - .await? - .trim() - .is_empty() - { - return Err("fixture container remained after teardown".to_string()); - } - } - Ok(()) -} - -fn write_profile( - path: &Path, - name: &str, - host: &str, - port: u16, - python: &str, -) -> Result<(), String> { - let document = json!({ - "id": name, "display_name": "Provider readiness E2E", "category": "other", - "credentials": [{"name": "synthetic", "env_vars": [TOKEN_ENV], "required": true, - "auth_style": "bearer", "header_name": "authorization"}], - "endpoints": [{"host": host, "port": port, "path": "/v1/**", "protocol": "rest", - "access": "full", "enforcement": "enforce", - "allowed_ips": [host]}], - "binaries": [python], - }); - std::fs::write(path, document.to_string()) - .map_err(|_| "could not write synthetic profile".to_string()) -} - -fn write_policy( - path: &Path, - host: &str, - other_host: &str, - port: u16, - other_port: u16, - python: &str, -) -> Result<(), String> { - // Permit the negative endpoint probes at the network layer so the - // credential binding itself must prevent them from reaching the backend. - // The exact binary allowlist independently denies curl at the valid endpoint. - let endpoints = [(host, port), (host, other_port), (other_host, port)] - .into_iter() - .map(|(host, port)| { - json!({"host": host, "port": port, "path": "/**", "protocol": "rest", - "access": "full", "enforcement": "enforce", - "allowed_ips": [host]}) - }) - .collect::>(); - let document = json!({ - "version": 1, - "filesystem_policy": {"include_workdir": false, - "read_only": ["/usr", "/lib", "/proc", "/dev/urandom", "/etc", "/opt", "/var/log"], - "read_write": ["/sandbox", "/tmp", "/dev/null"]}, - "landlock": {"compatibility": "best_effort"}, - "process": {"run_as_user": "sandbox", "run_as_group": "sandbox"}, - "network_policies": {"synthetic_backend": {"name": "synthetic_backend", - "endpoints": endpoints, "binaries": [{"path": python}]}}, - }); - std::fs::write(path, document.to_string()) - .map_err(|_| "could not write synthetic policy".to_string()) -} - -struct MutationReceipt { - mutation_id: String, - receipt: Value, -} - -fn readiness_output(output: &str, keys: &[String; 2]) -> Result { - // Never echo a malformed response: both a key leak and a leaked issued - // reference must fail with the same fixed diagnostic. - if keys.iter().any(|key| output.contains(key)) - || output.contains("openshell:resolve:") - || output.contains("Bearer ") - { - return Err("provider readiness output contained credential material".to_string()); - } - serde_json::from_str(output) - .map_err(|_| "provider readiness output was invalid JSON".to_string()) -} - -fn single_target(body: &Value) -> Result<&Value, String> { - let targets = body["targets"] - .as_array() - .ok_or("provider readiness targets were absent")?; - // This provider is unique and has exactly one attachment. A mutation that - // selects a different sandbox or omits this sandbox cannot satisfy the test. - if targets.len() != 1 { - return Err("provider readiness did not identify exactly one sandbox".to_string()); - } - Ok(&targets[0]) -} - -fn nonempty_string<'a>(object: &'a Value, field: &str) -> Result<&'a str, String> { - object[field] - .as_str() - .filter(|value| !value.is_empty()) - .ok_or_else(|| format!("provider readiness identity field {field} was absent")) -} - -impl MutationReceipt { - fn capture( - output: &str, - sandbox: &SandboxGuard, - provider: &str, - kind: &str, - keys: &[String; 2], - ) -> Result { - let body = readiness_output(output, keys)?; - let status = single_target(&body)?; - let receipt = &status["receipt"]; - let desired = &receipt["desired"]; - let mutation_id = nonempty_string(&body, "mutation_id")?; - if receipt["mutation_id"] != mutation_id - || receipt["provider"] != provider - || receipt["kind"] != kind - || desired["sandbox"] != sandbox.name - || status["state"] != "persisted" - || status["wait_outcome"] != "not_requested" - { - return Err( - "provider mutation receipt did not match persisted target intent".to_string(), - ); - } - nonempty_string(receipt, "receipt_id")?; - for field in [ - "sandbox_id", - "attachment_epoch", - "provider_resource_version", - "provider_env_revision", - "config_revision", - "policy_hash", - ] { - nonempty_string(desired, field)?; - } - if kind == "detach" { - if desired["provider_id"] != "" || desired["provider_resource_version"] != "0" { - return Err("detach receipt retained provider authority".to_string()); - } - } else { - nonempty_string(desired, "provider_id")?; - } - nonempty_string(receipt, "persisted_time")?; - Ok(Self { - mutation_id: mutation_id.to_string(), - receipt: receipt.clone(), - }) - } - - fn follows(&self, previous: &Self) -> Result<(), String> { - let desired = &self.receipt["desired"]; - let preceding = &previous.receipt["desired"]; - if self.mutation_id == previous.mutation_id - || self.receipt["receipt_id"] == previous.receipt["receipt_id"] - || self.receipt["provider"] != previous.receipt["provider"] - || self.receipt["workspace"] != previous.receipt["workspace"] - || desired["sandbox_id"] != preceding["sandbox_id"] - || desired["sandbox"] != preceding["sandbox"] - || desired["provider_env_revision"] == preceding["provider_env_revision"] - { - return Err( - "provider mutation did not identify distinct authority for the same target" - .to_string(), - ); - } - // Revisions are opaque strings. Only identity equality is meaningful; - // a numerically lower fingerprint is still a different installation. - if self.receipt["kind"] == "update" - && (desired["provider_id"] != preceding["provider_id"] - || desired["provider_resource_version"] == preceding["provider_resource_version"] - || desired["attachment_epoch"] != preceding["attachment_epoch"]) - { - return Err("provider update did not preserve its attachment identity".to_string()); - } - if self.receipt["kind"] == "detach" - && desired["attachment_epoch"] == preceding["attachment_epoch"] - { - return Err("provider detach did not replace its attachment epoch".to_string()); - } - Ok(()) - } - - async fn wait( - &self, - sandbox: &SandboxGuard, - provider: &str, - expected_state: &str, - keys: &[String; 2], - ) -> Result { - let mut command = openshell_cmd(); - command.args([ - "sandbox", - "provider", - "status", - &sandbox.name, - provider, - "--receipt", - nonempty_string(&self.receipt, "receipt_id")?, - "--wait", - "--timeout", - READINESS_TIMEOUT_SECONDS, - "-o", - "json", - ]); - let output = checked_command_with_timeout( - &mut command, - "wait for original provider mutation receipt", - READINESS_COMMAND_TIMEOUT, - ) - .await?; - let body = readiness_output(&output, keys)?; - let status = single_target(&body)?; - if body["mutation_id"] != self.mutation_id - || status["receipt"] != self.receipt - || status["state"] != expected_state - || status["reason"] != "unspecified" - || status["wait_outcome"] != "complete" - { - return Err( - "original provider receipt did not complete against its exact desired authority" - .to_string(), - ); - } - let desired = &self.receipt["desired"]; - let observed = &status["observed"]; - for field in [ - "attachment_epoch", - "provider_env_revision", - "config_revision", - "policy_hash", - ] { - if observed[field] != desired[field] { - return Err(format!( - "provider installation did not match desired {field}" - )); - } - } - for field in [ - "credentials_installed", - "policy_active", - "launch_environment_installed", - ] { - if observed[field] != true { - return Err(format!("provider receipt completed without {field}")); - } - } - for field in ["session_id", "sequence", "process_instance_id"] { - nonempty_string(observed, field)?; - } - nonempty_string(status, "network_instance_id")?; - nonempty_string(status, "observed_time")?; - nonempty_string(status, "evaluated_time")?; - if observed["reason"] != "unspecified" { - return Err( - "provider installation observation lacked a successful timestamped acknowledgment" - .to_string(), - ); - } - Ok(status.clone()) - } -} - -async fn future_environment( - sandbox: &SandboxGuard, - python: &str, - expected_present: bool, -) -> Result<(), String> { - // A new exec consumes the process supervisor's current launch snapshot. - // Only booleans leave the process, never the reference or its length. - let script = "import json,os,re; key='PROVIDER_READINESS_E2E_TOKEN'; value=os.environ.get(key,''); print(json.dumps({'present':key in os.environ,'reference':bool(re.fullmatch(r'openshell:resolve:env:v[1-9][0-9]*_'+key,value))}))"; - let output = checked_command( - &mut sandbox_command(sandbox, &[python, "-c", script]), - "probe future process provider environment", - ) - .await?; - let result: Value = - serde_json::from_str(output.trim()).map_err(|_| "future environment probe was invalid")?; - if result["present"] != expected_present || result["reference"] != expected_present { - return Err( - "future process environment did not match acknowledged provider authority".to_string(), - ); - } - Ok(()) -} - -async fn probe(sandbox: &SandboxGuard, client: &str, phase: &str) -> Result { - // Each retained process owns a separate mailbox so both old and current - // references can be checked after detach without a client consuming the - // other client's command. Labels and phases are fixed fixture constants. - let control = format!("{CONTROL}-{client}"); - let result = format!("{RESULT}-{client}"); - // The client consumes the control file as soon as it appears. Publish a - // complete phase atomically so polling cannot observe an empty write. - let command = format!( - "rm -f {result} && printf '%s' '{phase}' > {control}.tmp && mv {control}.tmp {control}" - ); - checked_command( - &mut sandbox_command(sandbox, &["sh", "-c", &command]), - "trigger persistent client phase", - ) - .await?; - let deadline = Instant::now() + Duration::from_secs(20); - loop { - if let Ok(output) = checked_command_with_timeout( - &mut sandbox_command(sandbox, &["cat", &result]), - "read persistent client phase", - Duration::from_secs(10), - ) - .await - { - let response: Value = - serde_json::from_str(output.trim()).map_err(|_| "client result was invalid")?; - if response["phase"] != phase || response["same_reference"] != true { - return Err( - "persistent client changed its retained environment reference".to_string(), - ); - } - return Ok(response); - } - if Instant::now() >= deadline { - return Err(format!("client phase {phase} did not finish")); - } - sleep(Duration::from_millis(100)).await; - } -} - -async fn probe_disallowed_binary( - sandbox: &SandboxGuard, - curl: &str, - host: &str, - port: u16, -) -> Result<(), String> { - // Binary authorization includes allowed ancestors. Launch curl as a - // sibling of the retained Python client, so Python cannot authorize it. - // The shell builtin sends the reference only through curl's stdin pipe. - let script = r#" -test -n "$PROVIDER_READINESS_E2E_TOKEN" || exit 64 -"$1" --version >/dev/null 2>&1 || exit 65 -if printf 'Authorization: Bearer %s\n' "$PROVIDER_READINESS_E2E_TOKEN" | \ - "$1" --silent --fail --max-time 5 --output /dev/null --header @- --data '{}' "$2" 2>/dev/null -then - printf 'unexpected-success' -else - printf 'denied' -fi -"#; - let url = format!("https://{host}:{port}/v1/chat/completions"); - let output = checked_command( - &mut sandbox_command(sandbox, &["sh", "-c", script, "binary-probe", curl, &url]), - "probe independent disallowed binary", - ) - .await?; - if output.trim() != "denied" { - return Err("independent disallowed binary reached the endpoint".to_string()); - } - Ok(()) -} - -fn check( - response: &Value, - pid: u64, - success: bool, - backend_phase: Option, -) -> Result<(), String> { - if response["pid"].as_u64() != Some(pid) || response["ok"].as_bool() != Some(success) { - // Report only typed status fields; never include HTTP error text or - // a serialized response that might later grow a credential field. - return Err(format!( - "client probe failed: pid_matches={}, expected_ok={success}, actual_ok={:?}, status={:?}, error_kind={:?}, reason_kind={:?}", - response["pid"].as_u64() == Some(pid), - response["ok"].as_bool(), - response["status"].as_u64(), - response["error_kind"].as_str(), - response["reason_kind"].as_str(), - )); - } - if let Some(phase) = backend_phase - && (response["backend_phase"].as_u64() != Some(phase) || response["status"] != 200) - { - return Err("backend did not attest the expected credential generation".to_string()); - } - Ok(()) -} - -#[tokio::test] -// Both clients remain alive through detach so their own retained references -// prove revocation across the attach and update launch boundaries. -#[allow(clippy::too_many_lines)] -async fn acknowledged_provider_changes_apply_to_fresh_clients_and_revoke_retained_references() --> Result<(), String> { - let mut gateway_fixture = GatewayTrustFixture::load()?; - // Sandbox names are limited to 19 characters. Retain all 64 random bits - // within that limit so concurrent fixtures still own distinct resources. - let name = format!("e2e{:016x}", rand::random::()); - let mut backend = BackendPair::new(&name)?; - // The wrapper's directory is shared with the host Docker daemon in CI; - // a job-container-local temporary path cannot back the TLS bind mount. - let directory = TempDir::new_in(&gateway_fixture.directory) - .map_err(|_| "could not allocate fixture directory")?; - let context = directory.path().join("image"); - std::fs::create_dir(&context).map_err(|_| "could not allocate public image context")?; - let backend_tls = directory.path().join("backend-tls"); - std::fs::create_dir(&backend_tls).map_err(|_| "could not allocate backend TLS directory")?; - let image = FixtureImage::new()?; - let supervisor_image = FixtureImage::new()?; - // Each backend has its own network namespace, so fixed internal ports need - // no host reservation or publication and remain independent across runs. - let port = BACKEND_PORT; - let other_port = OTHER_BACKEND_PORT; - let keys = [ - format!("e2e-{:032x}", rand::random::()), - format!("e2e-{:032x}", rand::random::()), - ]; - let mut sandbox = None; - let mut sandbox_attempted = false; - let mut clients = Vec::with_capacity(2); - let result = async { - // Begin container mutation inside this scope so certificate, image, - // and enrollment failures still reach explicit bounded teardown. - std::fs::write(context.join("client.py"), CLIENT) - .map_err(|_| "could not write client source")?; - let dockerfile = context.join("Dockerfile"); - std::fs::write( - &dockerfile, - format!( - "FROM {E2E_WORKLOAD_IMAGE}\nCOPY client.py /opt/provider-readiness-client.py\nUSER 1000:1000\n", - ), - ) - .map_err(|_| "could not write fixture Dockerfile")?; - image - .build(&dockerfile, &context, "build workload fixture image") - .await?; - let binaries = base_binaries(image.tag()).await?; - let python = binaries["python"] - .as_str() - .ok_or("Python executable was absent")?; - let curl = binaries["curl"] - .as_str() - .ok_or("curl executable was absent")?; - - let [host, other_host] = backend.spawn(image.tag(), &backend_tls).await?; - let (certificate, private_key) = - generate_certificates(directory.path(), &host, &other_host).await?; - std::fs::copy(&certificate, backend_tls.join("backend.crt")) - .map_err(|_| "could not stage backend certificate")?; - let backend_tls_key = backend_tls.join("backend.key.fixture"); - std::fs::copy(&private_key, &backend_tls_key) - .map_err(|_| "could not stage backend TLS key")?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - // The backends inherit the image's unprivileged user. Only their - // mounted leaf key is readable there; the host TempDir is private - // and the CA signing key never enters a container or image context. - std::fs::set_permissions(&backend_tls_key, std::fs::Permissions::from_mode(0o444)) - .map_err(|_| "could not set backend TLS key permissions")?; - } - backend.initialize(&json!({"keys": keys, "ports": [port, other_port], - "certificate": "/fixture-tls/backend.crt", "private_key": "/fixture-tls/backend.key.fixture"})) - .await?; - std::fs::copy(directory.path().join("ca.crt"), context.join("fixture-ca.crt")) - .map_err(|_| "could not copy public fixture CA")?; - let supervisor_dockerfile = context.join("Dockerfile.supervisor"); - // Outbound TLS belongs to the separate supervisor. Assemble its combined - // public trust bundle in the shell-capable workload image because the - // final supervisor image is intentionally distroless. Preserve the final - // image's user setting: Docker's archive upload applies an explicit image - // user to the supervisor's private bootstrap files. - std::fs::write(&supervisor_dockerfile, format!( - "FROM {} AS supervisor\nFROM {} AS trust-bundle\nUSER 0\nCOPY --from=supervisor /etc/ssl/certs/ca-certificates.crt /tmp/ca-certificates.crt\nCOPY fixture-ca.crt /tmp/readiness-fixture-ca.crt\nRUN [\"/usr/bin/python3\", \"-c\", \"from pathlib import Path; bundle = Path('/tmp/ca-certificates.crt'); bundle.write_bytes(bundle.read_bytes() + Path('/tmp/readiness-fixture-ca.crt').read_bytes())\"]\nFROM {}\nCOPY --from=trust-bundle /tmp/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt\n", - gateway_fixture.supervisor_image, - image.tag(), - gateway_fixture.supervisor_image, - )).map_err(|_| "could not write fixture supervisor Dockerfile")?; - supervisor_image - .build( - &supervisor_dockerfile, - &context, - "build supervisor fixture image", - ) - .await?; - gateway_fixture.apply(supervisor_image.tag()).await?; - let profile = directory.path().join("profile.json"); - let policy = directory.path().join("policy.json"); - write_profile(&profile, &name, &host, port, python)?; - write_policy(&policy, &host, &other_host, port, other_port, python)?; - let profile_path = profile.to_str().ok_or("profile path was not UTF-8")?; - let policy_path = policy.to_str().ok_or("policy path was not UTF-8")?; - let configuration = json!({"host": host, "other_host": other_host, "port": port, - "other_port": other_port}).to_string(); - cli( - "import synthetic provider profile", - &["provider", "profile", "import", "--file", profile_path], - None, - ) - .await?; - cli( - "create synthetic provider", - &[ - "provider", - "create", - "--name", - &name, - "--type", - &name, - "--credential", - TOKEN_ENV, - ], - Some(&keys[0]), - ) - .await?; - // Retain a known name even when creation times out after persistence, - // so teardown can still remove the partially created sandbox. - sandbox_attempted = true; - sandbox = Some( - SandboxGuard::create(&[ - "--name", - &name, - "--from", - image.tag(), - "--policy", - policy_path, - "--no-auto-providers", - ]) - .await - .map_err(|_| "scratch sandbox could not start")?, - ); - let running = sandbox - .as_ref() - .ok_or("sandbox was absent after creation")?; - future_environment(running, python, false).await?; - let output = cli( - "attach synthetic provider", - &[ - "sandbox", - "provider", - "attach", - &running.name, - &name, - "-o", - "json", - ], - None, - ) - .await?; - let attach = MutationReceipt::capture(&output, running, &name, "attach", &keys)?; - let attached = attach.wait(running, &name, "ready", &keys).await?; - future_environment(running, python, true).await?; - // Start A only after the actual launch environment acknowledgment. - // It retains this static reference until teardown; updates need not - // change the credential selected by an already-running process. - clients.push(PersistentClient::start(running, python, &configuration, "a").await?); - let initial = probe(running, "a", "initial").await?; - let pid_a = initial["pid"].as_u64().ok_or("client A PID was absent")?; - check(&initial, pid_a, true, Some(0))?; - let before = backend.counts().await?; - if before["total"] != 1 || before["accepted"][0] != 1 { - return Err("initial backend request count was incorrect".to_string()); - } - for phase in [ - "wrong_host_control", - "wrong_port_control", - "wrong_path_control", - ] { - let control = probe(running, "a", phase).await?; - check(&control, pid_a, false, None)?; - if control["status"] != 401 || control["backend_phase"] != 0 { - return Err(format!( - "negative endpoint {phase} was not reachable without a credential" - )); - } - } - let before = backend.counts().await?; - if before["total"] != 4 || before["rejected"] != 3 || before["accepted"] != json!([1, 0]) { - return Err("uncredentialed endpoint control assertions failed".to_string()); - } - for phase in [ - "wrong_host", - "wrong_port", - "wrong_path", - "untrusted_ca", - ] { - check(&probe(running, "a", phase).await?, pid_a, false, None)?; - if backend.counts().await? != before { - return Err(format!("denied phase {phase} reached the backend")); - } - } - probe_disallowed_binary(running, curl, &host, port).await?; - if backend.counts().await? != before { - return Err("disallowed binary reached the backend".to_string()); - } - - backend.rotate().await?; - let output = cli( - "update synthetic provider once", - &[ - "provider", - "update", - &name, - "--credential", - TOKEN_ENV, - "-o", - "json", - ], - Some(&keys[1]), - ) - .await?; - let update = MutationReceipt::capture(&output, running, &name, "update", &keys)?; - update.follows(&attach)?; - // No workload requests occur while waiting. Launch B through the - // acknowledged environment boundary; its first request must use the - // new credential without warming requests or success retries. - let updated = update.wait(running, &name, "ready", &keys).await?; - future_environment(running, python, true).await?; - clients.push(PersistentClient::start(running, python, &configuration, "b").await?); - let rotated_request = probe(running, "b", "rotated").await?; - let pid_b = rotated_request["pid"].as_u64().ok_or("client B PID was absent")?; - if pid_b == pid_a { - return Err("provider update reused the original client process".to_string()); - } - check(&rotated_request, pid_b, true, Some(1))?; - let rotated = backend.counts().await?; - if rotated["total"] != 5 || rotated["accepted"] != json!([1, 1]) || rotated["rejected"] != 3 - { - return Err("single-update backend assertions failed".to_string()); - } - - let output = cli( - "detach synthetic provider", - &[ - "sandbox", - "provider", - "detach", - &running.name, - &name, - "-o", - "json", - ], - None, - ) - .await?; - let detach = MutationReceipt::capture(&output, running, &name, "detach", &keys)?; - detach.follows(&update)?; - let revoked = detach.wait(running, &name, "revoked", &keys).await?; - future_environment(running, python, false).await?; - // Detach must revoke the reference while leaving the independently - // authorized route usable; a network outage cannot satisfy this proof. - let control = probe(running, "b", "detached_control").await?; - check(&control, pid_b, false, None)?; - if control["status"] != 401 || control["backend_phase"] != 1 { - return Err("detached endpoint was not reachable without a credential".to_string()); - } - let detached = backend.counts().await?; - if detached["total"] != 6 - || detached["accepted"] != json!([1, 1]) - || detached["rejected"] != 4 - || detached["phase"] != 1 - { - return Err("detached endpoint control assertions failed".to_string()); - } - for (client, pid) in [("a", pid_a), ("b", pid_b)] { - check(&probe(running, client, "detached").await?, pid, false, None)?; - if backend.counts().await? != detached { - return Err(format!("detached client {client} credential reached the backend")); - } - } - println!( - "{}", - json!({"phase": "complete", "client_a_pid": pid_a, "client_b_pid": pid_b, - "clients_retained_own_references": true, "fresh_client_first_request_rotated": true, - "endpoint_denials": true, "binary_denial": true, - "tls_verified": true, "both_client_references_revoked": true, - "future_environment_installed": true, "future_environment_removed": true, - "attach": attached, "update": updated, "detach": revoked}) - ); - Ok(()) - } - .await; - - // Resource names are unique to this run. Always attempt cleanup, including - // failures during enrollment, and keep failures visible without exposing - // captured provider output. The generic guard suppresses delete errors, so - // first issue an explicit checked delete before disarming its fallback. - let mut cleanup_results = Vec::new(); - if sandbox_attempted { - cleanup_results.push( - cli( - "delete fixture sandbox", - &["sandbox", "delete", &name], - None, - ) - .await - .map(|_| ()), - ); - } - if let Some(mut sandbox) = sandbox { - cleanup_results.push( - timeout(COMMAND_TIMEOUT, sandbox.cleanup()) - .await - .map_err(|_| "sandbox guard cleanup timed out".to_string()), - ); - } - for mut client in clients { - cleanup_results.push(client.stop().await); - } - cleanup_results.push( - cli( - "delete synthetic provider", - &["provider", "delete", &name], - None, - ) - .await - .map(|_| ()), - ); - cleanup_results.push( - cli( - "delete synthetic profile", - &["provider", "profile", "delete", &name], - None, - ) - .await - .map(|_| ()), - ); - cleanup_results.push(backend.stop().await); - // Restore the original runtime before removing its replacement. Retain the - // derived supervisor image if restoration fails, and report that failure - // even when a lifecycle assertion already failed. - let gateway_restore = gateway_fixture.restore().await; - let supervisor_cleanup = if gateway_restore.is_ok() { - supervisor_image.remove().await - } else { - Ok(()) - }; - let image_cleanup = image.remove().await; - let failures = [result, gateway_restore, supervisor_cleanup, image_cleanup] - .into_iter() - .chain(cleanup_results) - .filter_map(Result::err) - .collect::>(); - if failures.is_empty() { - Ok(()) - } else { - Err(failures.join("; ")) - } -} diff --git a/e2e/rust/tests/provider_refresh_handles.rs b/e2e/rust/tests/provider_refresh_handles.rs deleted file mode 100644 index a1ce70132a..0000000000 --- a/e2e/rust/tests/provider_refresh_handles.rs +++ /dev/null @@ -1,16 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e-podman")] - -#[path = "support/provider_refresh_handles.rs"] -mod support; - -const PROVIDER_NAME: &str = "e2e-oauth-refresh-handle"; -const PROFILE_ID: &str = "e2e-oauth-refresh-handle"; -const TOKEN_ENV: &str = "REFRESH_E2E_ACCESS_TOKEN"; - -#[tokio::test] -async fn long_running_process_survives_rotations_and_reconfigure_revokes() -> Result<(), String> { - support::exercise_refresh_handles(None).await -} diff --git a/e2e/rust/tests/provider_token_exchange.rs b/e2e/rust/tests/provider_token_exchange.rs deleted file mode 100644 index 9105be98bc..0000000000 --- a/e2e/rust/tests/provider_token_exchange.rs +++ /dev/null @@ -1,1466 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e-podman")] - -use std::collections::HashMap; -use std::convert::Infallible; -use std::fs; -use std::io::Write as _; -use std::net::{Ipv4Addr, SocketAddr}; -use std::os::unix::fs::PermissionsExt as _; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; -use std::task::{Context, Poll}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use base64::Engine as _; -use futures_util::future::BoxFuture; -use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation}; -use openshell_e2e::harness::binary::openshell_cmd; -use openshell_e2e::harness::port::find_free_port; -use openshell_e2e::harness::sandbox::SandboxGuard; -use serde_json::json; -use tempfile::NamedTempFile; -use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; -use tokio::net::{TcpListener, TcpStream, UnixListener}; -use tokio_stream::wrappers::{ReceiverStream, TcpListenerStream, UnixListenerStream}; -use tonic::body::Body as TonicBody; -use tonic::codegen::{Body, http}; -use tonic::{Request, Response, Status}; - -const TRUST_DOMAIN: &str = "openshell-e2e.test"; -const ISSUER: &str = "https://spiffe.openshell-e2e.test"; -const KEY_ID: &str = "openshell-e2e-test-key"; -const USER_SUBJECT_TOKEN: &str = "stored-user-token"; -const INTERMEDIATE_TOKEN: &str = "intermediate-token"; -const FINAL_ACCESS_TOKEN: &str = "final-access-token"; -const TOKEN_TYPE_ACCESS_TOKEN: &str = "urn:ietf:params:oauth:token-type:access_token"; -const CLIENT_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe"; -const IDENTITY_AUDIENCE: &str = "identity-proxy"; -const IDENTITY_JWT_AUDIENCE: &str = "https://identity.openshell-e2e.test"; -const IDENTITY_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; - -// The harness gives this test binary one pair of SPIFFE listener endpoints. -// Serialize their ownership even when the Rust test runner uses many threads. -static SPIFFE_FIXTURE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); - -#[derive(Default)] -struct GrantObservations { - service_issued: [AtomicUsize; 2], - identity_issued: [AtomicUsize; 2], - service_denied: AtomicUsize, - identity_denied: AtomicUsize, - target_requests: AtomicUsize, - target_rejected: AtomicUsize, -} - -impl GrantObservations { - fn issued(&self) -> [(usize, usize); 2] { - std::array::from_fn(|index| { - ( - self.service_issued[index].load(Ordering::SeqCst), - self.identity_issued[index].load(Ordering::SeqCst), - ) - }) - } -} - -const TEST_RSA_PRIVATE_KEY: &str = r"-----BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCvCoZ0mVHpCHsF -zeeqw2caNIe/eb4BQUccFPhZfRnF7sCfyB84zTBmuwG2umRBdjFnVsfIIZRp2HcD -OESrRYYiE1RGfjBXImGVg2Wtza0HYhL1sLyX1eaEefylxoilmApAgWDh9p36h8J2 -s5YHwyXPTttx4DpdWDnxju1iNmwoIB8uVE/5amWgbNvlETMBOcB1RxDHtnVy+xJz -jjjrzK4Qz9WsUTHAvngdi4Yyxvci+yKpjYTg5+UWxmAN6iW522TpLe32MDb5Ug1d -trBvvepWmdQ6CBwPhBHCt/sMoSJAYSO4RKeBnBjeLQBXFTxaOv5iTGIsRTX3K471 -epHp3cT5AgMBAAECggEASQlRv/4nZN5SgsH/K8v7zb3kdHsmUly8AJYpaCGgauvr -uN/mUyueyga2uNl+MqhQBef6VWHZjO6y/gdw86v/Q2GgVQebQQhKAnpAp2w+Ceoc -siKMFqi8VkOWLU+xPbM6d97kH3TpRxt1g1T8wYFmWeF0BEiE4eUJzGaQW14M9BJ+ -G0QxmP/zjX9cNpVeApKTjBWKiH4CXG3DuI3pJ93VOMpUlOsrdLXvKGTze0e01itr -MX/MHHTE+VXB4FB+/zKSA4c36egi676OSXrGC/GDmM8ntJ4CUGeD5uZsMSADiAUn -iccv5iGRWVMIKxUS5Q4k0jy8uWuK+QVP4Y6cQWYArwKBgQDhuSNORBNpIGRfsKGN -iJo/h+qinz6pEIpa3D3oVl7rpkyvgIyaTwfXvC1vfdS9V5VIel2gV2Cx0OrI8yrr -nQu1JuNV/rLmtvqX321fgBLRdoiqF3pAy1gbmdUz1elerAIYL578gXQ6jg1bbdic -kJpn0MsoDUJGwvJnXcgLqG7q3wKBgQDGhRIa4oJsj1vqICc8zt8YsCAcot3vjWLH -588X7JdBGOWJdWxfdmGXQRn5Zw9UhMQnYa3uyTBPeVcXopThlPotYeuFhLSU856T -IJzfpzCJzC4zIQayoyvJFrKe7N70iUQ986dewYy9oxQhHvFKd/qe4ylbzZJXpthX -eWEuuBSjJwKBgGkqXt6qLPj/1IQYwUw15tfOtW0LEKCoSi3HCzjidNsJ4hSqqdeD -Fr5WuDyHvcRxt+XKzTBVRYHTOnBhiw+3XasK8UQxpJyFh/+WY1jpTNs2hLnqslTZ -6LUDWSgLc+1d6qPmHAa9Ma/OWz7L0O4xGR9hUiXY95YMYe/y668yzGq1AoGBAJyU -Gsqfu7U6gYmxoKEine6QBFPx1dD7GF2KJdq93jMXGvyHZFoLOkAdtgnz0rCcI0bY -kWKUxwj4MMxQjNM8OPMQl75xBCmz2XA8Od9htDQLmqjzNKAzePabc3lMZTJFDlE6 -29kuGf79IIRbLn/JECDAFT/2baW60Ep2T0OVJ5njAoGAfaCaQ4aVgjI027q7Y5qP -KfNSI8uuA8PLqmUY30I9KFWzN6VDLu00eKa90F4w3CeWRRQWXW1+007tTz3V1mNw -20A24Fi3HGQmXc7NyuLDODTJsWBICuOemCnRkvcxIlxb+ec7jp+XRmzDwKkzSnVN -pM2zFU8SeVkvHKlEuoHaP0s= ------END PRIVATE KEY-----"; //notsecret - -const TEST_RSA_MODULUS_HEX: &str = concat!( - "af0a86749951e9087b05cde7aac3671a3487bf79be0141471c14f8597d19c5eec09fc81f38cd3066bb01b6ba", - "644176316756c7c8219469d877033844ab4586221354467e30572261958365adcdad076212f5b0bc97d5e684", - "79fca5c688a5980a408160e1f69dfa87c276b39607c325cf4edb71e03a5d5839f18eed62366c28201f2e54", - "4ff96a65a06cdbe511330139c0754710c7b67572fb12738e38ebccae10cfd5ac5131c0be781d8b8632c6", - "f722fb22a98d84e0e7e516c6600dea25b9db64e92dedf63036f9520d5db6b06fbdea5699d43a081c0f84", - "11c2b7fb0ca122406123b844a7819c18de2d0057153c5a3afe624c622c4535f72b8ef57a91e9ddc4f9" -); - -#[derive(Clone, PartialEq, prost::Message)] -struct JwtsvidRequest { - #[prost(string, repeated, tag = "1")] - audience: Vec, - #[prost(string, tag = "2")] - spiffe_id: String, -} - -#[derive(Clone, PartialEq, prost::Message)] -struct JwtsvidResponse { - #[prost(message, repeated, tag = "1")] - svids: Vec, -} - -#[derive(Clone, PartialEq, prost::Message)] -struct Jwtsvid { - #[prost(string, tag = "1")] - spiffe_id: String, - #[prost(string, tag = "2")] - svid: String, - #[prost(string, tag = "3")] - hint: String, -} - -#[derive(Clone, PartialEq, prost::Message)] -struct JwtBundlesRequest {} - -#[derive(Clone, PartialEq, prost::Message)] -struct JwtBundlesResponse { - #[prost(map = "string, bytes", tag = "1")] - bundles: HashMap>, -} - -#[derive(Clone)] -struct SpiffeWorkloadApi { - subject: Arc, - jwks: Arc>, - encoding_key: Arc, -} - -impl SpiffeWorkloadApi { - fn jwt_svid(&self, audience: &[String]) -> Result { - let now = unix_timestamp(); - let mut header = Header::new(Algorithm::RS256); - header.kid = Some(KEY_ID.to_string()); - let claims = json!({ - "iss": ISSUER, - "sub": self.subject.as_ref(), - "aud": audience, - "iat": now, - "exp": now + 3600, - }); - openshell_crypto::jwt::encode(&header, &claims, &self.encoding_key) - .map_err(|err| Status::internal(format!("sign JWT-SVID: {err}"))) - } -} - -#[derive(Clone)] -struct SpiffeWorkloadApiServer { - inner: Arc, -} - -impl SpiffeWorkloadApiServer { - fn new(inner: SpiffeWorkloadApi) -> Self { - Self { - inner: Arc::new(inner), - } - } -} - -impl tower::Service> for SpiffeWorkloadApiServer -where - B: Body + Send + 'static, - B::Error: Into> + Send + 'static, -{ - type Response = http::Response; - type Error = Infallible; - type Future = BoxFuture<'static, Result>; - - fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { - Poll::Ready(Ok(())) - } - - fn call(&mut self, req: http::Request) -> Self::Future { - match req.uri().path() { - "/SpiffeWorkloadAPI/FetchJWTSVID" => { - #[derive(Clone)] - struct FetchJwtsvidSvc(Arc); - impl tonic::server::UnaryService for FetchJwtsvidSvc { - type Response = JwtsvidResponse; - type Future = BoxFuture<'static, Result, Status>>; - - fn call(&mut self, request: Request) -> Self::Future { - let inner = Arc::clone(&self.0); - Box::pin(async move { - let request = request.into_inner(); - let svid = inner.jwt_svid(&request.audience)?; - Ok(Response::new(JwtsvidResponse { - svids: vec![Jwtsvid { - spiffe_id: inner.subject.to_string(), - svid, - hint: String::new(), - }], - })) - }) - } - } - - let inner = Arc::clone(&self.inner); - Box::pin(async move { - let codec = tonic_prost::ProstCodec::default(); - let mut grpc = tonic::server::Grpc::new(codec); - Ok(grpc.unary(FetchJwtsvidSvc(inner), req).await) - }) - } - "/SpiffeWorkloadAPI/FetchJWTBundles" => { - #[derive(Clone)] - struct FetchJwtBundlesSvc(Arc); - impl tonic::server::ServerStreamingService for FetchJwtBundlesSvc { - type Response = JwtBundlesResponse; - type ResponseStream = ReceiverStream>; - type Future = - BoxFuture<'static, Result, Status>>; - - fn call(&mut self, _request: Request) -> Self::Future { - let inner = Arc::clone(&self.0); - Box::pin(async move { - let mut bundles = HashMap::new(); - bundles.insert(TRUST_DOMAIN.to_string(), inner.jwks.as_ref().clone()); - let (tx, rx) = tokio::sync::mpsc::channel(1); - tx.send(Ok(JwtBundlesResponse { bundles })) - .await - .map_err(|err| Status::internal(format!("send bundle: {err}")))?; - Ok(Response::new(ReceiverStream::new(rx))) - }) - } - } - - let inner = Arc::clone(&self.inner); - Box::pin(async move { - let codec = tonic_prost::ProstCodec::default(); - let mut grpc = tonic::server::Grpc::new(codec); - Ok(grpc.server_streaming(FetchJwtBundlesSvc(inner), req).await) - }) - } - _ => Box::pin(async move { - let mut response = http::Response::new(TonicBody::empty()); - response.headers_mut().insert( - tonic::Status::GRPC_STATUS, - (tonic::Code::Unimplemented as i32).into(), - ); - response.headers_mut().insert( - http::header::CONTENT_TYPE, - tonic::metadata::GRPC_CONTENT_TYPE, - ); - Ok(response) - }), - } - } -} - -impl tonic::server::NamedService for SpiffeWorkloadApiServer { - const NAME: &'static str = "SpiffeWorkloadAPI"; -} - -struct FixtureHandle { - task: tokio::task::JoinHandle<()>, -} - -impl FixtureHandle { - async fn shutdown(mut self) { - self.task.abort(); - let _ = (&mut self.task).await; - } -} - -impl Drop for FixtureHandle { - fn drop(&mut self) { - self.task.abort(); - } -} - -fn unix_timestamp() -> i64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("system time should be after unix epoch") - .as_secs() - .try_into() - .expect("timestamp should fit i64") -} - -fn jwks() -> Vec { - let modulus = hex::decode(TEST_RSA_MODULUS_HEX).expect("valid test RSA modulus hex"); - let n = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(modulus); - let e = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([0x01, 0x00, 0x01]); - serde_json::to_vec(&json!({ - "keys": [{ - "kty": "RSA", - "kid": KEY_ID, - "use": "sig", - "alg": "RS256", - "n": n, - "e": e, - }] - })) - .expect("JWKS should serialize") -} - -async fn start_spiffe_workload_api(path: &Path, subject: &str) -> FixtureHandle { - let api = SpiffeWorkloadApi { - subject: Arc::::from(subject), - jwks: Arc::new(jwks()), - encoding_key: Arc::new( - EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY.as_bytes()) - .expect("test RSA key should parse"), - ), - }; - let endpoint = path.to_string_lossy(); - if endpoint.starts_with("tcp:") { - let listen = std::env::var("OPENSHELL_E2E_PROVIDER_SPIFFE_LISTEN") - .expect("OPENSHELL_E2E_PROVIDER_SPIFFE_LISTEN must be set for TCP SPIFFE fixture"); - let listener = TcpListener::bind(&listen) - .await - .expect("bind TCP SPIFFE Workload API fixture"); - let incoming = TcpListenerStream::new(listener); - let task = tokio::spawn(async move { - let result = tonic::transport::Server::builder() - .add_service(SpiffeWorkloadApiServer::new(api)) - .serve_with_incoming(incoming) - .await; - if let Err(err) = result { - eprintln!("SPIFFE Workload API fixture failed: {err}"); - } - }); - return FixtureHandle { task }; - } - let _ = fs::remove_file(path); - let listener = UnixListener::bind(path).expect("bind SPIFFE Workload API socket"); - let mut permissions = fs::metadata(path) - .expect("stat SPIFFE Workload API socket") - .permissions(); - permissions.set_mode(0o777); - fs::set_permissions(path, permissions).expect("chmod SPIFFE Workload API socket"); - let incoming = UnixListenerStream::new(listener); - let task = tokio::spawn(async move { - let result = tonic::transport::Server::builder() - .add_service(SpiffeWorkloadApiServer::new(api)) - .serve_with_incoming(incoming) - .await; - if let Err(err) = result { - eprintln!("SPIFFE Workload API fixture failed: {err}"); - } - }); - FixtureHandle { task } -} - -// Forms and JWT headers can span TCP reads. Read the bounded, Content-Length -// framed request completely so packet boundaries cannot change fixture results. -async fn read_http_request(stream: &mut TcpStream) -> Option { - tokio::time::timeout(Duration::from_secs(5), async { - let mut request = Vec::new(); - let mut buffer = [0_u8; 4096]; - loop { - let length = stream.read(&mut buffer).await.ok()?; - if length == 0 || request.len() + length > 32 * 1024 { - return None; - } - request.extend_from_slice(&buffer[..length]); - if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") { - let headers = std::str::from_utf8(&request[..end]).ok()?; - let content_length = headers - .lines() - .filter_map(|line| line.split_once(':')) - .find(|(name, _)| name.eq_ignore_ascii_case("content-length")) - .map_or(Some(0), |(_, value)| value.trim().parse::().ok())?; - if request.len() >= end.checked_add(4)?.checked_add(content_length)? { - return String::from_utf8(request).ok(); - } - } - } - }) - .await - .ok() - .flatten() -} - -fn verifies_jwt_svid(token: &str, instance: &str) -> bool { - let keys: jsonwebtoken::jwk::JwkSet = - serde_json::from_slice(&jwks()).expect("fixture JWKS should parse"); - let key = DecodingKey::from_jwk(keys.find(KEY_ID).expect("fixture signing key exists")) - .expect("fixture verification key should parse"); - let mut validation = Validation::new(Algorithm::RS256); - validation.set_issuer(&[ISSUER]); - validation.set_audience(&[format!("{IDENTITY_JWT_AUDIENCE}/{instance}")]); - validation.sub = Some(format!("spiffe://{TRUST_DOMAIN}/openshell/sandbox/e2e")); - validation.set_required_spec_claims(&["exp", "iat", "iss", "sub", "aud"]); - jsonwebtoken::decode::(token, &key, &validation) - .is_ok_and(|verified| verified.header.kid.as_deref() == Some(KEY_ID)) -} - -fn token_form(request: &str) -> HashMap { - let (_, body) = request.split_once("\r\n\r\n").unwrap_or_default(); - url::form_urlencoded::parse(body.as_bytes()) - .into_owned() - .collect() -} - -async fn write_token_response(stream: &mut TcpStream, access_token: Option<&str>, ttl: u64) { - let (status, body) = if let Some(access_token) = access_token { - ( - "HTTP/1.1 200 OK", - json!({"access_token": access_token, "token_type": "Bearer", "expires_in": ttl}) - .to_string(), - ) - } else { - ( - "HTTP/1.1 400 Bad Request", - json!({"error": "invalid_grant"}).to_string(), - ) - }; - let response = format!( - "{status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", - body.len() - ); - let _ = stream.write_all(response.as_bytes()).await; -} - -async fn start_gateway_token_endpoint( - port: u16, - observations: Arc, -) -> FixtureHandle { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) - .await - .expect("bind gateway token endpoint"); - let task = tokio::spawn(async move { - loop { - let Ok((mut stream, _peer)) = listener.accept().await else { - break; - }; - let observations = Arc::clone(&observations); - tokio::spawn(async move { - let Some(request) = read_http_request(&mut stream).await else { - return; - }; - let form = token_form(&request); - let field = |name: &str| form.get(name).map_or("", String::as_str); - let valid = request.starts_with("POST /token ") - && field("grant_type") == "urn:ietf:params:oauth:grant-type:token-exchange" - && field("client_assertion_type") == CLIENT_ASSERTION_TYPE - && field("subject_token_type") == TOKEN_TYPE_ACCESS_TOKEN - && field("requested_token_type") == TOKEN_TYPE_ACCESS_TOKEN - && !field("client_assertion").is_empty(); - let mut access_token = None; - for (index, instance) in ["a", "b"].into_iter().enumerate() { - if valid - && field("subject_token") == format!("{USER_SUBJECT_TOKEN}-{instance}") - && field("audience") - == format!("spiffe://{TRUST_DOMAIN}/openshell/sandbox/e2e") - && field("scope").is_empty() - { - access_token = Some(format!("{INTERMEDIATE_TOKEN}-{instance}")); - } else if valid - && field("subject_token") == format!("{INTERMEDIATE_TOKEN}-{instance}") - && field("scope") == "service.read" - { - if field("audience") == format!("service-{instance}") { - observations.service_issued[index].fetch_add(1, Ordering::SeqCst); - access_token = Some(format!("{FINAL_ACCESS_TOKEN}-{instance}")); - } else if field("audience") == format!("denied-service-{instance}") { - observations.service_denied.fetch_add(1, Ordering::SeqCst); - } - } - } - write_token_response(&mut stream, access_token.as_deref(), 600).await; - }); - } - }); - FixtureHandle { task } -} - -// This issuer returns the actual Workload API JWT-SVID after checking its -// signature and audience. No new production grant type or sandbox-visible -// credential is needed to exercise custom-header injection. -async fn start_identity_token_endpoint( - port: u16, - observations: Arc, -) -> FixtureHandle { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) - .await - .expect("bind identity token endpoint"); - let task = tokio::spawn(async move { - loop { - let Ok((mut stream, _peer)) = listener.accept().await else { - break; - }; - let observations = Arc::clone(&observations); - tokio::spawn(async move { - let Some(request) = read_http_request(&mut stream).await else { - return; - }; - let form = token_form(&request); - let field = |name: &str| form.get(name).map_or("", String::as_str); - let mut access_token = None; - for (index, instance) in ["a", "b"].into_iter().enumerate() { - let valid = request.starts_with("POST /identity-token ") - && field("grant_type") == "client_credentials" - && field("client_assertion_type") == IDENTITY_ASSERTION_TYPE - && field("scope") == "identity.read" - && verifies_jwt_svid(field("client_assertion"), instance); - if valid && field("audience") == format!("{IDENTITY_AUDIENCE}-{instance}") { - observations.identity_issued[index].fetch_add(1, Ordering::SeqCst); - access_token = Some(field("client_assertion")); - } else if valid && field("audience") == format!("denied-identity-{instance}") { - observations.identity_denied.fetch_add(1, Ordering::SeqCst); - } - } - write_token_response(&mut stream, access_token, 900).await; - }); - } - }); - FixtureHandle { task } -} - -async fn start_protected_target(port: u16, observations: Arc) -> FixtureHandle { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, port))) - .await - .expect("bind protected target"); - let task = tokio::spawn(async move { - loop { - let Ok((mut stream, _peer)) = listener.accept().await else { - break; - }; - let observations = Arc::clone(&observations); - tokio::spawn(async move { - // Count any request bytes, including an incomplete header. A - // failed grant may open a TCP stream but must send no request. - let mut byte = [0_u8; 1]; - if !matches!( - tokio::time::timeout(Duration::from_secs(5), stream.peek(&mut byte)).await, - Ok(Ok(1)) - ) { - return; - } - observations.target_requests.fetch_add(1, Ordering::SeqCst); - let Some(request) = read_http_request(&mut stream).await else { - return; - }; - let headers = request.split("\r\n\r\n").next().unwrap_or_default(); - let header_values = |name: &str| { - headers - .lines() - .filter_map(|line| line.split_once(':')) - .filter(|(key, _)| key.eq_ignore_ascii_case(name)) - .map(|(_, value)| value.trim()) - .collect::>() - }; - let bearer = header_values("authorization"); - let identity = header_values("x-workload-jwt"); - let ok = ["a", "b"].into_iter().any(|instance| { - request.starts_with(&format!("GET /resource/{instance} ")) - && bearer.len() == 1 - && bearer[0] == format!("Bearer {FINAL_ACCESS_TOKEN}-{instance}") - && identity.len() == 1 - && verifies_jwt_svid(identity[0], instance) - }); - let (status, body) = if ok { - ("HTTP/1.1 200 OK", "independent-grants-ok") - } else { - // Keep rejection evidence even if the workload retries and - // a later request happens to receive the correct credentials. - observations.target_rejected.fetch_add(1, Ordering::SeqCst); - ( - "HTTP/1.1 401 Unauthorized", - "credential-verification-failed", - ) - }; - let response = format!( - "{status}\r\ncontent-type: text/plain\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", - body.len() - ); - let _ = stream.write_all(response.as_bytes()).await; - }); - } - }); - FixtureHandle { task } -} - -async fn run_cli(args: &[&str]) -> Result<(), String> { - let output = openshell_cmd() - .args(args) - .output() - .await - .map_err(|_| "could not spawn openshell CLI".to_string())?; - if output.status.success() { - Ok(()) - } else { - // Provider creation arguments contain the stored subject token. - // Keep command arguments and raw diagnostics out of test failures. - Err(format!( - "openshell command failed; exit={:?}", - output.status.code() - )) - } -} - -async fn run_cli_ignore_error(args: &[&str]) { - let _ = openshell_cmd().args(args).output().await; -} - -fn write_profile( - profile_type: &str, - token_port: u16, - identity_port: u16, - target_port: u16, - instance: &str, -) -> NamedTempFile { - let token_endpoint = format!("http://127.0.0.1:{token_port}/token"); - let mut file = tempfile::Builder::new() - .suffix(".yaml") - .tempfile() - .expect("create provider profile temp file"); - let profile = format!( - r"id: {profile_type} -display_name: Podman token exchange e2e -description: Independent bearer and JWT-SVID grants for one request -category: other -credentials: - - name: subject_token - description: Stored user subject token - required: true - - name: access_token - description: Access token obtained through token exchange - required: false - auth_style: bearer - header_name: Authorization - token_grant: - grant_type: token_exchange - token_endpoint: {token_endpoint} - audience: service-{instance} - scopes: [service.read] - jwt_svid_audience: {token_endpoint} - client_assertion_type: {CLIENT_ASSERTION_TYPE} - requested_token_type: {TOKEN_TYPE_ACCESS_TOKEN} - cache_ttl_seconds: 300 - audience_overrides: - - path: /deny-service/{instance} - audience: denied-service-{instance} - subject_token: - source: provider_credential - credential: subject_token - subject_token_type: {TOKEN_TYPE_ACCESS_TOKEN} - - name: workload_identity - description: Signed workload identity for the identity proxy - required: false - auth_style: header - header_name: X-Workload-Jwt - token_grant: - grant_type: client_credentials - token_endpoint: http://127.0.0.1:{identity_port}/identity-token - audience: {IDENTITY_AUDIENCE}-{instance} - scopes: [identity.read] - jwt_svid_audience: {IDENTITY_JWT_AUDIENCE}/{instance} - client_assertion_type: {IDENTITY_ASSERTION_TYPE} - cache_ttl_seconds: 600 - audience_overrides: - - path: /deny-identity/{instance} - audience: denied-identity-{instance} -endpoints: - - host: host.openshell.internal - port: {target_port} - path: /** - protocol: rest - access: read-write - enforcement: enforce - allowed_ips: - - 10.0.0.0/8 - - 169.254.0.0/16 - - 172.0.0.0/8 - - 192.168.0.0/16 -binaries: - - /** -" - ); - file.write_all(profile.as_bytes()) - .expect("write provider profile"); - file.flush().expect("flush provider profile"); - file -} - -/// Writes a profile with one bearer token-exchange grant bound to `/{route}/**`. -/// Each route carries its own audience so the token endpoint can tell which -/// endpoint's grant the supervisor selected. -fn write_route_profile( - profile_type: &str, - token_port: u16, - target_port: u16, - route: &str, -) -> NamedTempFile { - let token_endpoint = format!("http://127.0.0.1:{token_port}/token"); - let mut file = tempfile::Builder::new() - .suffix(".yaml") - .tempfile() - .expect("create provider profile temp file"); - let profile = format!( - r"id: {profile_type} -display_name: Podman token exchange route e2e -description: Route-bound bearer grant -category: other -credentials: - - name: subject_token - description: Stored user subject token - required: true - - name: access_token - description: Access token obtained through token exchange - required: false - auth_style: bearer - header_name: Authorization - token_grant: - grant_type: token_exchange - token_endpoint: {token_endpoint} - audience: audience-{route} - jwt_svid_audience: {token_endpoint} - client_assertion_type: {CLIENT_ASSERTION_TYPE} - requested_token_type: {TOKEN_TYPE_ACCESS_TOKEN} - cache_ttl_seconds: 300 - subject_token: - source: provider_credential - credential: subject_token - subject_token_type: {TOKEN_TYPE_ACCESS_TOKEN} -endpoints: - - host: host.openshell.internal - port: {target_port} - path: /{route}/** - protocol: rest - access: read-write - enforcement: enforce - allowed_ips: - - 10.0.0.0/8 - - 169.254.0.0/16 - - 172.0.0.0/8 - - 192.168.0.0/16 -binaries: - - /** -" - ); - file.write_all(profile.as_bytes()) - .expect("write provider profile"); - file.flush().expect("flush provider profile"); - file -} - -fn sandbox_script() -> String { - r"set -eu -echo token-server-ready -while true; do sleep 60; done -" - .to_string() -} - -async fn sandbox_exec_http( - sandbox_name: &str, - target_port: u16, - path: &str, - expect_denied: bool, -) -> Result { - let url = format!("http://host.openshell.internal:{target_port}{path}"); - let expect_denied_python = if expect_denied { "True" } else { "False" }; - let script = format!( - r#"import base64, json, os, re, urllib.error, urllib.request, uuid - -def contains_credential(value): - if any(marker in value for marker in ( - "stored-user-token", "intermediate-token", "final-access-token", "openshell:resolve:" - )): - return True - for token in re.findall(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", value): - try: - payload = token.split(".")[1] - claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) - if claims.get("iss") == "{ISSUER}": - return True - except (ValueError, UnicodeError): - pass - return False - -if any(contains_credential(value) for value in os.environ.values()): - raise RuntimeError("provider credential material reached the workload environment") -request = urllib.request.Request({url:?}, headers={{ - "Authorization": "Bearer agent-supplied", - "X-Workload-Jwt": "agent-supplied", -}}) -try: - with urllib.request.urlopen(request, timeout=10) as response: - body = response.read().decode() - if contains_credential(body): - raise RuntimeError("provider credential material reached the workload response") - if {expect_denied_python}: - raise RuntimeError("failed grant unexpectedly reached the target") - print(body) -except urllib.error.HTTPError as error: - body = error.read().decode() - if contains_credential(body): - raise RuntimeError("provider credential material reached the workload error") - if not {expect_denied_python} or error.code != 502: - raise RuntimeError("unexpected HTTP response") from None - # The refusal names the exchange with an opaque ID and nothing else. - request_id = error.headers.get("x-openshell-request-id", "") - if str(uuid.UUID(request_id)) != request_id: - raise RuntimeError("refusal did not carry a canonical request ID") - print("grant-denied") -"# - ); - let mut last_status = None; - for _ in 0..20 { - let output = openshell_cmd() - .args([ - "sandbox", - "exec", - "--name", - sandbox_name, - "--no-tty", - "--", - "python3", - "-c", - &script, - ]) - .output() - .await - .map_err(|_| "could not spawn sandbox HTTP probe".to_string())?; - if output.status.success() { - // The child emits fixed markers only. Never return raw stderr: - // runtime failures can include request or credential diagnostics. - let stdout = String::from_utf8_lossy(&output.stdout); - let expected = if expect_denied { - "grant-denied" - } else { - "independent-grants-ok" - }; - if stdout.trim() == expected { - return Ok(expected.to_string()); - } - return Err("sandbox probe returned unexpected output".to_string()); - } - last_status = output.status.code(); - tokio::time::sleep(Duration::from_millis(500)).await; - } - Err(format!("sandbox HTTP probe failed; exit={last_status:?}")) -} - -async fn create_provider_instance( - token_port: u16, - identity_port: u16, - target_port: u16, - instance: &str, -) -> String { - let name = format!("podman-grants-{instance}-{}", std::process::id()); - run_cli_ignore_error(&["provider", "delete", &name, "--yes"]).await; - run_cli_ignore_error(&["profile", "delete", &name, "--yes"]).await; - let profile = write_profile(&name, token_port, identity_port, target_port, instance); - let profile_path = profile - .path() - .to_str() - .expect("profile path should be UTF-8"); - run_cli(&["profile", "import", "-f", profile_path]) - .await - .expect("import independent-grant profile"); - run_cli(&[ - "provider", - "create", - "--name", - &name, - "--type", - &name, - "--credential", - &format!("subject_token={USER_SUBJECT_TOKEN}-{instance}"), - ]) - .await - .expect("create provider instance"); - name -} - -#[tokio::test] -async fn podman_provider_token_exchange_injects_independent_grants_across_sandboxes() { - let _fixture_guard = SPIFFE_FIXTURE_LOCK.lock().await; - let gateway_socket = PathBuf::from( - std::env::var("OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET") - .expect("OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET must be set by e2e-podman.sh"), - ); - let provider_socket = PathBuf::from( - std::env::var("OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET") - .expect("OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET must be set by e2e-podman.sh"), - ); - let token_port = find_free_port(); - let identity_port = find_free_port(); - let target_port = find_free_port(); - let gateway_subject = format!("spiffe://{TRUST_DOMAIN}/openshell/gateway"); - // The mock shares a workload subject. Distinct providers and JWT audiences - // test cross-sandbox credential isolation, not production SPIRE attestation. - let supervisor_subject = format!("spiffe://{TRUST_DOMAIN}/openshell/sandbox/e2e"); - let observations = Arc::new(GrantObservations::default()); - let _gateway_spiffe = start_spiffe_workload_api(&gateway_socket, &gateway_subject).await; - let _provider_spiffe = start_spiffe_workload_api(&provider_socket, &supervisor_subject).await; - let _gateway_token = start_gateway_token_endpoint(token_port, Arc::clone(&observations)).await; - let _identity_token = - start_identity_token_endpoint(identity_port, Arc::clone(&observations)).await; - let _target = start_protected_target(target_port, Arc::clone(&observations)).await; - - let mut provider_names = Vec::new(); - for instance in ["a", "b"] { - provider_names - .push(create_provider_instance(token_port, identity_port, target_port, instance).await); - } - - let script = sandbox_script(); - let mut sandbox_a = SandboxGuard::create_keep_with_args( - &["--provider", &provider_names[0]], - &["sh", "-lc", &script], - "token-server-ready", - ) - .await - .expect("create sandbox A"); - let mut sandbox_b = SandboxGuard::create_keep_with_args( - &["--provider", &provider_names[1]], - &["sh", "-lc", &script], - "token-server-ready", - ) - .await - .expect("create sandbox B"); - - // Both supervisors request the same host/port concurrently. The target - // verifies each path's distinct bearer and signed JWT audience together. - let initial = tokio::join!( - sandbox_exec_http(&sandbox_a.name, target_port, "/resource/a", false), - sandbox_exec_http(&sandbox_b.name, target_port, "/resource/b", false), - ); - let before_cache = observations.issued(); - let cached = tokio::join!( - sandbox_exec_http(&sandbox_a.name, target_port, "/resource/a", false), - sandbox_exec_http(&sandbox_b.name, target_port, "/resource/b", false), - ); - let after_cache = observations.issued(); - let target_requests = observations.target_requests.load(Ordering::SeqCst); - // An audience override forces acquisition of only the failing credential; - // the other credential remains cached from the successful request. - let denied = tokio::join!( - sandbox_exec_http(&sandbox_a.name, target_port, "/deny-service/a", true), - sandbox_exec_http(&sandbox_b.name, target_port, "/deny-identity/b", true), - ); - - sandbox_a.cleanup().await; - sandbox_b.cleanup().await; - for name in &provider_names { - run_cli_ignore_error(&["provider", "delete", name, "--yes"]).await; - run_cli_ignore_error(&["profile", "delete", name, "--yes"]).await; - } - // Release the shared SPIFFE endpoints before the next test binds them. - _target.shutdown().await; - _identity_token.shutdown().await; - _gateway_token.shutdown().await; - _provider_spiffe.shutdown().await; - _gateway_spiffe.shutdown().await; - - for outcome in [initial.0, initial.1, cached.0, cached.1] { - assert_eq!( - outcome.expect("independent grant request should succeed"), - "independent-grants-ok" - ); - } - assert_eq!( - observations.target_rejected.load(Ordering::SeqCst), - 0, - "no request may present mismatched or untrusted credentials, even before a retry" - ); - assert!( - before_cache - .iter() - .all(|(service, identity)| *service > 0 && *identity > 0), - "each provider instance must acquire both credentials" - ); - assert_eq!( - after_cache, before_cache, - "repeat requests should use both caches" - ); - for outcome in [denied.0, denied.1] { - assert_eq!( - outcome.expect("failed grant should return 502"), - "grant-denied" - ); - } - assert!(observations.service_denied.load(Ordering::SeqCst) > 0); - assert!(observations.identity_denied.load(Ordering::SeqCst) > 0); - assert_eq!( - observations.target_requests.load(Ordering::SeqCst), - target_requests, - "neither failed grant may forward any request bytes" - ); -} - -// Read one whole fixture request without consuming the following keepalive -// request. OAuth forms can arrive separately from their headers. -async fn read_route_fixture_request( - stream: &mut TcpStream, - observed_bytes: Option<&AtomicUsize>, -) -> Result, String> { - tokio::time::timeout(Duration::from_secs(30), async { - let mut bytes = Vec::new(); - while !bytes.ends_with(b"\r\n\r\n") { - let mut byte = [0]; - if stream - .read(&mut byte) - .await - .map_err(|err| err.to_string())? - == 0 - { - return if bytes.is_empty() { - Ok(None) - } else { - Err("partial fixture header".into()) - }; - } - bytes.push(byte[0]); - if let Some(observed) = observed_bytes { - observed.fetch_add(1, Ordering::Relaxed); - } - if bytes.len() > 16 * 1024 { - return Err("fixture header exceeds limit".into()); - } - } - let header = std::str::from_utf8(&bytes).map_err(|err| err.to_string())?; - let length = header - .lines() - .filter_map(|line| line.split_once(':')) - .find(|(name, _)| name.eq_ignore_ascii_case("content-length")) - .map(|(_, value)| value.trim().parse::()) - .transpose() - .map_err(|err| err.to_string())? - .unwrap_or(0); - if length > 64 * 1024 { - return Err("fixture body exceeds limit".into()); - } - let header_len = bytes.len(); - bytes.resize(header_len + length, 0); - stream - .read_exact(&mut bytes[header_len..]) - .await - .map_err(|err| err.to_string())?; - if let Some(observed) = observed_bytes { - observed.fetch_add(length, Ordering::Relaxed); - } - String::from_utf8(bytes) - .map(Some) - .map_err(|err| err.to_string()) - }) - .await - .map_err(|_| "fixture request timed out".to_owned())? -} - -#[derive(Default)] -struct RouteGrantState { - fail_next_b: AtomicBool, - supervisor_requests: Mutex>, - failed_request_id: Mutex>, -} - -async fn start_route_token_endpoint(port: u16, state: Arc) -> FixtureHandle { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) - .await - .expect("bind route token endpoint"); - let task = tokio::spawn(async move { - let mut requests = tokio::task::JoinSet::new(); - loop { - tokio::select! { - accepted = listener.accept() => { - let Ok((mut stream, _)) = accepted else { break; }; - let state = state.clone(); - requests.spawn(async move { - let Ok(Some(request)) = read_route_fixture_request(&mut stream, None).await else { return; }; - let form = request.split_once("\r\n\r\n").map_or("", |(_, body)| body); - let fields = form.split('&').filter_map(|part| part.split_once('=')).collect::>(); - let subject = fields.get("subject_token").copied().unwrap_or_default(); - let route = match subject { - "stored-a" | "intermediate-a" => "a", - "stored-b" | "intermediate-b" => "b", - _ => "", - }; - let supervisor = subject.starts_with("intermediate-"); - let valid = !route.is_empty() && request.starts_with("POST /token ") - && fields.get("client_assertion").is_some_and(|value| !value.is_empty()) - // Gateway exchange targets the supervisor's SPIFFE - // subject; final exchange targets the route audience. - && fields.get("audience").is_some_and(|value| !value.is_empty() - && (!supervisor || *value == format!("audience-{route}"))); - let fail = if valid && supervisor { - state.supervisor_requests.lock().expect("route grant requests lock").push(route.to_owned()); - route == "b" && state.fail_next_b.swap(false, Ordering::SeqCst) - } else { false }; - let (status, body) = if fail { - let request_id = request.split_once("\r\n\r\n") - .map(|(headers, _)| headers) - .unwrap_or_default() - .lines() - .filter_map(|line| line.split_once(':')) - .find(|(name, _)| name.eq_ignore_ascii_case("x-openshell-request-id")) - .map(|(_, value)| value.trim().to_owned()); - *state.failed_request_id.lock().expect("failed grant request ID lock") = request_id; - ("HTTP/1.1 503 Service Unavailable", json!({"error": "temporary_failure"}).to_string()) - } else if valid { - let stage = if supervisor { "final" } else { "intermediate" }; - ("HTTP/1.1 200 OK", json!({ - "access_token": format!("{stage}-{route}"), "token_type": "Bearer", "expires_in": 300 - }).to_string()) - } else { - ("HTTP/1.1 400 Bad Request", json!({"error": "unexpected_route_exchange"}).to_string()) - }; - let response = format!("{status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); - let _ = tokio::time::timeout(Duration::from_secs(5), stream.write_all(response.as_bytes())).await; - }); - } - _ = requests.join_next(), if !requests.is_empty() => {} - } - } - }); - FixtureHandle { task } -} - -struct RouteTargetRequest { - connection: usize, - path: String, - authorization: Vec, - bytes: usize, -} - -struct RouteTargetHandle { - stop: Option>, - task: tokio::task::JoinHandle>, -} - -impl RouteTargetHandle { - async fn drain(mut self) -> Result<(), String> { - if let Some(stop) = self.stop.take() { - // A closed receiver means the task already stopped; joining still - // reports its error rather than hiding it behind the stop signal. - let _ = stop.send(()); - } - tokio::time::timeout(Duration::from_secs(35), &mut self.task) - .await - .map_err(|_| "route target did not drain accepted connections".to_owned())? - .map_err(|err| format!("route target task failed: {err}"))? - } -} - -impl Drop for RouteTargetHandle { - fn drop(&mut self) { - // Failure and timeout cleanup must also cancel the owned JoinSet. - self.task.abort(); - } -} - -async fn start_route_target( - port: u16, - observed: Arc>>, - observed_bytes: Arc, -) -> RouteTargetHandle { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, port))) - .await - .expect("bind route target"); - let (stop, mut stopped) = tokio::sync::oneshot::channel(); - let task = tokio::spawn(async move { - let next_connection = AtomicUsize::new(1); - let mut connections = tokio::task::JoinSet::new(); - let mut completed = Vec::new(); - let mut accept_error = None; - loop { - tokio::select! { - // Once the workload has closed, accept queued connections - // before stopping so their buffered bytes are also observed. - biased; - accepted = listener.accept() => { - let (mut stream, _) = match accepted { - Ok(accepted) => accepted, - Err(err) => { - accept_error = Some(format!("route target accept failed: {err}")); - break; - } - }; - let connection = next_connection.fetch_add(1, Ordering::Relaxed); - let observed = observed.clone(); - let observed_bytes = observed_bytes.clone(); - connections.spawn(async move { - loop { - let Some(request) = read_route_fixture_request(&mut stream, Some(&observed_bytes)).await? else { return Ok::<(), String>(()); }; - let path = request.lines().next().and_then(|line| line.split_whitespace().nth(1)).unwrap_or_default().to_owned(); - let authorization = request.lines().filter_map(|line| line.split_once(':')) - .filter(|(name, _)| name.eq_ignore_ascii_case("authorization")) - .map(|(_, value)| value.trim().to_owned()).collect::>(); - let expected = if path.starts_with("/a/") { "Bearer final-a" } else { "Bearer final-b" }; - let valid = authorization.len() == 1 && authorization[0] == expected; - observed.lock().expect("route target observations lock").push(RouteTargetRequest { connection, path, authorization, bytes: request.len() }); - let status = if valid { "HTTP/1.1 200 OK" } else { "HTTP/1.1 401 Unauthorized" }; - let response = format!("{status}\r\nContent-Length: 0\r\n\r\n"); - tokio::time::timeout(Duration::from_secs(5), stream.write_all(response.as_bytes())).await - .map_err(|_| "route target response write timed out".to_owned())? - .map_err(|err| format!("route target response write failed: {err}"))?; - } - }); - } - _ = &mut stopped => break, - Some(result) = connections.join_next(), if !connections.is_empty() => completed.push(result), - } - } - drop(listener); - // Only EOF proves that the byte counter includes everything sent on - // each accepted connection. Do not abort pending readers on success. - while let Some(result) = connections.join_next().await { - completed.push(result); - } - if let Some(error) = accept_error { - return Err(error); - } - for result in completed { - result.map_err(|err| format!("route target reader task failed: {err}"))??; - } - Ok(()) - }); - RouteTargetHandle { - stop: Some(stop), - task, - } -} - -async fn exec_within(sandbox: &SandboxGuard, script: &str) -> Result { - tokio::time::timeout( - Duration::from_secs(60), - sandbox.exec(&["python3", "-c", script]), - ) - .await - .map_err(|_| "route workload timed out".to_owned())? -} - -/// Poll `sandbox get` until the last token-grant failure is present or absent. -async fn wait_for_token_grant_failure( - name: &str, - present: bool, -) -> Result { - for _ in 0..30 { - let output = openshell_cmd() - .args(["sandbox", "get", name, "--output", "json"]) - .output() - .await - .map_err(|_| "could not spawn openshell CLI".to_owned())?; - if output.status.success() - && let Ok(sandbox) = serde_json::from_slice::(&output.stdout) - && sandbox["last_token_grant_failure"].is_null() != present - { - return Ok(sandbox["last_token_grant_failure"].clone()); - } - tokio::time::sleep(Duration::from_secs(1)).await; - } - Err(format!( - "last token-grant failure present={present} not observed" - )) -} - -#[tokio::test] -async fn podman_provider_routes_recover_and_select_a_b_a_on_one_connection() { - let _fixture_guard = SPIFFE_FIXTURE_LOCK.lock().await; - let gateway_socket = PathBuf::from( - std::env::var("OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET") - .expect("gateway SPIFFE fixture endpoint"), - ); - let provider_socket = PathBuf::from( - std::env::var("OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET") - .expect("provider SPIFFE fixture endpoint"), - ); - // A remote Podman VM can forward this fixed loopback port to the test - // process. Keep the issuer URL on loopback so the fixture obeys the - // production token endpoint transport policy on both sides of the tunnel. - let token_port = std::env::var("OPENSHELL_E2E_TOKEN_PORT").map_or_else( - |_| find_free_port(), - |port| { - let port = port - .parse::() - .expect("OPENSHELL_E2E_TOKEN_PORT must be a valid TCP port"); - assert_ne!(port, 0, "OPENSHELL_E2E_TOKEN_PORT must be nonzero"); - port - }, - ); - let target_port = find_free_port(); - let grants = Arc::new(RouteGrantState::default()); - let observed = Arc::new(Mutex::new(Vec::new())); - let observed_bytes = Arc::new(AtomicUsize::new(0)); - let _gateway_spiffe = start_spiffe_workload_api( - &gateway_socket, - &format!("spiffe://{TRUST_DOMAIN}/openshell/gateway"), - ) - .await; - let _provider_spiffe = start_spiffe_workload_api( - &provider_socket, - &format!("spiffe://{TRUST_DOMAIN}/openshell/sandbox/e2e"), - ) - .await; - let _token_endpoint = start_route_token_endpoint(token_port, grants.clone()).await; - let _target = start_route_target(target_port, observed.clone(), observed_bytes.clone()).await; - let names = ["a", "b"].map(|route| format!("podman-route-{route}-{}", std::process::id())); - for name in &names { - run_cli_ignore_error(&["provider", "delete", name, "--yes"]).await; - run_cli_ignore_error(&["profile", "delete", name, "--yes"]).await; - } - let result: Result = async { - for (route, name) in ["a", "b"].iter().zip(&names) { - let profile = write_route_profile(name, token_port, target_port, route); - run_cli(&[ - "profile", - "import", - "-f", - profile.path().to_str().expect("UTF-8 profile path"), - ]) - .await?; - run_cli(&[ - "provider", - "create", - "--name", - name, - "--type", - name, - "--credential", - &format!("subject_token=stored-{route}"), - ]) - .await?; - } - let mut sandbox = SandboxGuard::create_keep_with_args( - &["--provider", &names[0], "--provider", &names[1]], - &["sh", "-lc", &sandbox_script()], - "token-server-ready", - ) - .await?; - grants.fail_next_b.store(true, Ordering::SeqCst); - // The supervisor mediates direct workload connections as CONNECT. - // HTTPConnection keeps one client socket for the successful A/B/A run. - let failure_script = format!( - r#"import http.client, uuid -first = http.client.HTTPConnection('host.openshell.internal', {target_port}, timeout=10) -first.request('GET', '/b/failure', headers={{'Authorization': 'Bearer stale-value'}}) -failed = first.getresponse() -failed.read() -assert failed.status == 502, 'the controlled grant failure must return 502' -request_id = failed.getheader('x-openshell-request-id', '') -assert str(uuid.UUID(request_id)) == request_id, 'the refusal must carry a canonical request ID' -print('failed-request-id=' + request_id) -assert failed.will_close, 'the failed tunnel must close' -first.close() -"# - ); - let recovery_script = format!( - r#"import http.client -host = 'host.openshell.internal' -port = {target_port} -recovered = http.client.HTTPConnection(host, port, timeout=10) -connection = None -for path in ['/a/first', '/b/second', '/a/third']: - recovered.request('GET', path, headers={{'Authorization': 'Bearer stale-value'}}) - if connection is None: - connection = recovered.sock - assert recovered.sock is connection, 'client connection was replaced' - response = recovered.getresponse() - response.read() - assert response.status == 200, 'upstream rejected the selected credential' - assert recovered.sock is connection and connection.fileno() >= 0, 'keepalive connection closed' -recovered.close() -print('route-recovery-a-b-a-ok') -"# - ); - let output = async { - let mut output = exec_within(&sandbox, &failure_script).await?; - // An authorized reader sees the cause of the refused grant. - let failure = wait_for_token_grant_failure(&sandbox.name, true).await?; - output.push_str(&format!("reported-failure={failure}\n")); - output.push_str(&exec_within(&sandbox, &recovery_script).await?); - // The matching grant's later success clears it. - wait_for_token_grant_failure(&sandbox.name, false).await?; - Ok::<_, String>(output) - } - .await; - sandbox.cleanup().await; - output - } - .await; - for name in &names { - run_cli_ignore_error(&["provider", "delete", name, "--yes"]).await; - run_cli_ignore_error(&["profile", "delete", name, "--yes"]).await; - } - let target_result = _target.drain().await; - _token_endpoint.shutdown().await; - _provider_spiffe.shutdown().await; - _gateway_spiffe.shutdown().await; - let output = result.expect("gateway-configured route workload succeeds"); - target_result.expect("route target observes EOF on every accepted connection"); - assert!(output.contains("route-recovery-a-b-a-ok")); - let response_request_id = output - .lines() - .find_map(|line| line.strip_prefix("failed-request-id=")) - .expect("workload prints the refused response's request ID"); - assert_eq!( - grants.failed_request_id.lock().unwrap().as_deref(), - Some(response_request_id), - "the token service and refused response must identify the same exchange" - ); - let reported: serde_json::Value = serde_json::from_str( - output - .lines() - .find_map(|line| line.strip_prefix("reported-failure=")) - .expect("the refused grant reached sandbox status"), - ) - .expect("reported failure is JSON"); - assert_eq!(reported["destination_port"], u64::from(target_port)); - let failure = &reported["failure"]; - assert_eq!(failure["request_id"], response_request_id); - assert_eq!(failure["code"], "unavailable"); - assert_eq!(failure["recovery_action"], "retry"); - assert_eq!(failure["stage"], "token_endpoint"); - assert_eq!(failure["upstream_http_status"], 503); - assert_eq!(failure["provider"], names[1].as_str()); - assert_eq!(failure["credential_key"], "access_token"); - let requests = observed.lock().expect("route target observations lock"); - assert_eq!(requests.len(), 3, "failed grant must not reach the target"); - assert_eq!( - observed_bytes.load(Ordering::Relaxed), - requests.iter().map(|request| request.bytes).sum::(), - "no partial failed request reached the target" - ); - for ((request, path), token) in requests - .iter() - .zip(["/a/first", "/b/second", "/a/third"]) - .zip(["Bearer final-a", "Bearer final-b", "Bearer final-a"]) - { - assert_eq!(request.path, path); - assert_eq!( - request.connection, requests[0].connection, - "upstream connection reused" - ); - assert_eq!( - request.authorization.len(), - 1, - "one Authorization replacement" - ); - assert!( - request.authorization[0] == token, - "the admitted path owns the injected token" - ); - } - assert_eq!( - *grants - .supervisor_requests - .lock() - .expect("route grant requests lock"), - ["b", "a", "b"], - "failed grant retries; repeated A uses its own cached token" - ); -} diff --git a/e2e/rust/tests/stable_external_placeholders.rs b/e2e/rust/tests/stable_external_placeholders.rs deleted file mode 100644 index 16002c21c2..0000000000 --- a/e2e/rust/tests/stable_external_placeholders.rs +++ /dev/null @@ -1,1354 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e-docker")] - -//! External caller assertion rotation through a real sandbox HTTPS request path. -//! -//! The workload sends a synthetic `tools/call` request using one retained -//! supervisor-issued reference in one Python process. The fixture exercises -//! credential substitution, not a complete MCP session or an agent runtime. -//! Only the isolated backend and privileged provider CLI receive synthetic keys; -//! workload files, responses, and diagnostics contain status information only. - -use std::net::Ipv4Addr; -use std::path::{Path, PathBuf}; -use std::process::Stdio; -use std::time::Duration; - -use openshell_e2e::harness::binary::openshell_cmd; -use openshell_e2e::harness::container::{ContainerEngine, e2e_network_name}; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::sandbox::{E2E_WORKLOAD_IMAGE, SandboxGuard}; -use serde::{Deserialize, Serialize}; -use serde_json::{Value, json}; -use tempfile::TempDir; -use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines}; -use tokio::process::{Child, ChildStdin, ChildStdout, Command}; -use tokio::time::{Instant, sleep, timeout}; - -const TOKEN_ENV: &str = "STABLE_EXTERNAL_E2E_TOKEN"; -const BACKEND_PORT: u16 = 8443; -const OTHER_BACKEND_PORT: u16 = 8444; -const READY: &str = "stable-placeholder-client-ready"; -const CONTROL: &str = "/sandbox/stable-placeholder-probe"; -const RESULT: &str = "/sandbox/stable-placeholder-result"; -const COMMAND_TIMEOUT: Duration = Duration::from_secs(60); -const IMAGE_BUILD_TIMEOUT: Duration = Duration::from_secs(300); -const READINESS_TIMEOUT_SECONDS: &str = "90"; -const READINESS_COMMAND_TIMEOUT: Duration = Duration::from_secs(105); -const GATEWAY_READY_TIMEOUT: Duration = Duration::from_secs(120); - -// Keys arrive on a private stdin pipe after process creation. Neither the -// command line nor any file contains them, and HTTP/server errors are silent. -const BACKEND: &str = r" -import http.server, json, ssl, sys, threading - -sys.excepthook = lambda *_: None -config = json.loads(sys.stdin.readline()) -keys = config.pop('keys') -lock = threading.Lock() -state = {'phase': 0, 'total': 0, 'accepted': [0, 0], 'rejected': 0, - 'received': [0, 0], 'missing': 0, 'unknown': 0, 'invalid_tool_calls': 0} - -class Server(http.server.ThreadingHTTPServer): - daemon_threads = True - def handle_error(self, request, client_address): - pass - -class Handler(http.server.BaseHTTPRequestHandler): - def log_message(self, *args): - pass - def do_POST(self): - request = json.loads(self.rfile.read(int(self.headers.get('Content-Length', '0')))) - tool_call = (request.get('jsonrpc') == '2.0' and request.get('method') == 'tools/call' - and request.get('params') == {'name': 'local_hello', - 'arguments': {'name': 'rotation-proof'}}) - with lock: - phase = state['phase'] - assertion = self.headers.get('x-openshell-sandbox-assertion') - generation = 'missing' if assertion is None else 'unknown' - for index, key in enumerate(keys): - if assertion == key: - generation = 'A' if index == 0 else 'B' - state['received'][index] += 1 - if generation in ('missing', 'unknown'): - state[generation] += 1 - if not tool_call: - state['invalid_tool_calls'] += 1 - valid = assertion == keys[phase] and tool_call - state['total'] += 1 - if valid: - state['accepted'][phase] += 1 - else: - state['rejected'] += 1 - response = {'jsonrpc': '2.0', 'id': request.get('id'), - 'fixture': {'authorized': valid, 'phase': phase, - 'credential_generation': generation, 'tool_call': tool_call}} - if valid: - response['result'] = {'content': [{'type': 'text', 'text': 'Hello rotation-proof'}]} - else: - response['error'] = {'code': -32001, 'message': 'Unauthorized'} - body = json.dumps(response).encode() - self.send_response(200 if valid else 401) - self.send_header('Content-Type', 'application/json') - self.send_header('Content-Length', str(len(body))) - self.send_header('Connection', 'close') - self.end_headers() - self.wfile.write(body) - -context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) -context.minimum_version = ssl.TLSVersion.TLSv1_2 -context.load_cert_chain(config['certificate'], config['private_key']) -servers = [] -for port in config['ports']: - server = Server(('0.0.0.0', port), Handler) - server.socket = context.wrap_socket(server.socket, server_side=True) - threading.Thread(target=server.serve_forever, daemon=True).start() - servers.append(server) -print(json.dumps({'ready': True}), flush=True) - -for line in sys.stdin: - request = json.loads(line) - with lock: - if request['command'] == 'rotate': - state['phase'] = 1 - print(json.dumps(state), flush=True) -for server in servers: - server.shutdown() - server.server_close() -"; - -// This source is safe to place in the workload image: it contains environment -// key names and endpoint coordinates, but never a key value or issued handle. -const CLIENT: &str = r" -import json, os, pathlib, re, ssl, sys, time, urllib.error, urllib.request - -config = json.loads(sys.argv[1]) -key = 'STABLE_EXTERNAL_E2E_TOKEN' -token = os.environ.get(key, '') -pattern = r's[0-9a-f]{64}' if config['stable'] else r'v[1-9][0-9]*' -if not re.fullmatch(r'openshell:resolve:env:' + pattern + '_' + key, token): - print('client did not receive the expected issued reference', flush=True) - sys.exit(64) -pid = os.getpid() -control = pathlib.Path('/sandbox/stable-placeholder-probe') -result = pathlib.Path('/sandbox/stable-placeholder-result') - -def probe(phase): - host, port, path = config['host'], config['port'], '/mcp/local-hello' - authorization = token - target = phase[:-8] if phase.endswith('_control') else phase - if target == 'wrong_host': - host = config['other_host'] - elif target == 'wrong_port': - port = config['other_port'] - elif target == 'wrong_path': - path = '/outside' - elif phase == 'canonical_alias': - authorization = 'openshell:resolve:env:' + key - url = 'https://%s:%s%s' % (host, port, path) - response = {'phase': phase, 'pid': pid, 'same_reference': os.environ.get(key) == token, - 'ok': False, 'status': 0, 'backend_phase': -1, - 'credential_generation': 'unobserved', 'tool_call': False} - try: - context = ssl.create_default_context() - if phase == 'untrusted_ca': - # An empty trust store proves this client does verify TLS. - context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) - headers = {'Content-Type': 'application/json'} - if not phase.endswith('_control'): - headers['x-openshell-sandbox-assertion'] = authorization - payload = {'jsonrpc': '2.0', 'id': 1, 'method': 'tools/call', - 'params': {'name': 'local_hello', 'arguments': {'name': 'rotation-proof'}}} - request = urllib.request.Request(url, data=json.dumps(payload).encode(), headers=headers) - try: - reply = urllib.request.urlopen(request, context=context, timeout=5) - except urllib.error.HTTPError as error: - # The backend's safe 401 body proves the negative endpoint is - # reachable before a credential-bearing request is denied. - reply = error - with reply: - body = json.loads(reply.read(1024)) - attestation = body.get('fixture', {}) - response['ok'] = (attestation.get('authorized') is True - and body.get('result', {}).get('content') == - [{'type': 'text', 'text': 'Hello rotation-proof'}]) - response['status'] = reply.status - response['backend_phase'] = attestation.get('phase', -1) - response['credential_generation'] = attestation.get('credential_generation', 'unobserved') - response['tool_call'] = attestation.get('tool_call') is True - except Exception as error: - # HTTP/TLS exception text can embed headers. Type names expose the - # failure layer without retaining messages, headers, or credentials. - response['error_kind'] = type(error).__name__ - response['reason_kind'] = type(getattr(error, 'reason', None)).__name__ - return response - -if len(sys.argv) > 2 and sys.argv[2] == '--once': - print(json.dumps(probe('fresh')), flush=True) - sys.exit(0) - -print('stable-placeholder-client-ready', flush=True) -deadline = time.monotonic() + 600 -while time.monotonic() < deadline: - if control.exists(): - phase = control.read_text().strip() - control.unlink() - temporary = result.with_suffix('.tmp') - temporary.write_text(json.dumps(probe(phase))) - temporary.replace(result) - time.sleep(0.05) -"; - -struct FixtureImage { - engine: ContainerEngine, - tag: String, -} - -impl FixtureImage { - fn new() -> Result { - Ok(Self { - engine: ContainerEngine::from_env()?, - tag: format!( - "localhost/openshell-e2e-stable-{}-{:016x}:latest", - std::process::id(), - rand::random::(), - ), - }) - } - - fn tag(&self) -> &str { - &self.tag - } - - async fn build(&self, dockerfile: &Path, context: &Path) -> Result<(), String> { - let mut command = Command::from(self.engine.command()); - command - .args(["build", "--file"]) - .arg(dockerfile) - .args(["--tag", &self.tag]) - .arg(context); - checked_command_with_timeout(&mut command, "build fixture image", IMAGE_BUILD_TIMEOUT) - .await - .map(|_| ()) - } - - async fn remove(&self) -> Result<(), String> { - let mut command = Command::from(self.engine.command()); - command.args(["image", "rm", "--force", &self.tag]); - // Teardown is explicit and bounded. This type has no Drop subprocess - // that could block the test runtime after the removal deadline expires. - checked_command(&mut command, "remove fixture image") - .await - .map(|_| ()) - } -} - -// These tests run serially against a wrapper-owned gateway. The public fixture -// CA must be removed and the original supervisor restored before the next case. -struct GatewayTrustFixture { - directory: PathBuf, - supervisor_image: String, - health_port: u16, - restore_required: bool, -} - -impl GatewayTrustFixture { - fn load() -> Result { - if std::env::var_os("OPENSHELL_GATEWAY_ENDPOINT").is_some() - || std::env::var_os("OPENSHELL_E2E_GATEWAY_BIN").is_none() - || std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("docker") - || std::env::var("OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER") - .is_ok_and(|value| value != "0") - { - return Err("stable placeholder fixture requires a wrapper-owned gateway with the bundled Docker driver".to_string()); - } - let args_file = std::env::var_os("OPENSHELL_E2E_GATEWAY_ARGS_FILE") - .ok_or("managed gateway argument metadata is missing")?; - let directory = Path::new(&args_file) - .parent() - .ok_or("managed gateway arguments have no parent directory")? - .to_path_buf(); - let raw = - std::fs::read(args_file).map_err(|_| "could not read managed gateway arguments")?; - let args = raw - .split(|byte| *byte == 0) - .filter(|arg| !arg.is_empty()) - .map(std::str::from_utf8) - .collect::, _>>() - .map_err(|_| "managed gateway arguments were not UTF-8")?; - let argument = |name| { - let mut values = args.windows(2).filter(|pair| pair[0] == name); - let value = values.next().ok_or("managed gateway argument is missing")?[1]; - if values.next().is_some() { - return Err("managed gateway argument is duplicated"); - } - Ok(value) - }; - let health_port = argument("--health-port")? - .parse::() - .map_err(|_| "managed gateway health port is invalid")?; - let supervisor_image = std::env::var("OPENSHELL_SUPERVISOR_IMAGE") - .map_err(|_| "managed supervisor image is missing")?; - Ok(Self { - directory, - supervisor_image, - health_port, - restore_required: false, - }) - } - - async fn apply(&mut self, image: &str) -> Result<(), String> { - self.restore_required = true; - restart_fixture_gateway(self.health_port, Some(image)).await - } - - async fn restore(&mut self) -> Result<(), String> { - if !self.restore_required { - return Ok(()); - } - restart_fixture_gateway(self.health_port, None) - .await - .map_err(|_| "could not restore original gateway runtime")?; - self.restore_required = false; - Ok(()) - } -} - -async fn restart_fixture_gateway( - health_port: u16, - supervisor_image: Option<&str>, -) -> Result<(), String> { - let mut gateway = ManagedGateway::from_env() - .map_err(|_| "could not load managed gateway restart metadata")? - .ok_or("managed gateway restart metadata disappeared")?; - if let Some(image) = supervisor_image { - gateway.set_supervisor_image(image); - } - gateway - .stop() - .map_err(|_| "could not stop fixture gateway")?; - gateway - .start() - .map_err(|_| "could not restart fixture gateway")?; - let url = format!("http://127.0.0.1:{health_port}/healthz"); - let deadline = Instant::now() + GATEWAY_READY_TIMEOUT; - loop { - if checked_command( - Command::new("curl").args(["--silent", "--fail", "--max-time", "2", &url]), - "check fixture gateway health", - ) - .await - .is_ok() - { - return Ok(()); - } - if Instant::now() >= deadline { - return Err("fixture gateway did not become healthy".to_string()); - } - sleep(Duration::from_millis(250)).await; - } -} - -struct Backend { - engine: ContainerEngine, - name: String, - network: String, - namespace: String, - child: Option, - input: Option, - output: Option>>, - launch_attempted: bool, -} - -impl Backend { - fn new(name: String) -> Result { - Ok(Self { - engine: ContainerEngine::from_env()?, - name, - network: e2e_network_name().ok_or("fixture requires the managed Docker network")?, - namespace: std::env::var("OPENSHELL_E2E_SANDBOX_NAMESPACE") - .map_err(|_| "fixture requires the managed Docker namespace")?, - child: None, - input: None, - output: None, - launch_attempted: false, - }) - } - - async fn spawn(&mut self, base: &str, tls_directory: &Path) -> Result { - let tls_directory = tls_directory - .to_str() - .filter(|path| !path.contains([',', '\n', '\r'])) - .ok_or("fixture TLS mount path is invalid")?; - let mount = format!("type=bind,src={tls_directory},dst=/fixture-tls,readonly"); - let namespace_label = format!("openshell.ai/sandbox-namespace={}", self.namespace); - let mut command = Command::from(self.engine.command()); - command - .args([ - "run", - "--rm", - "--interactive", - "--pull=never", - "--name", - &self.name, - "--network", - &self.network, - "--label", - "openshell.ai/managed-by=openshell", - "--label", - &namespace_label, - "--label", - "openshell.ai/isolation-role=fixture", - "--read-only", - "--cap-drop=ALL", - "--security-opt=no-new-privileges:true", - "--mount", - &mount, - "--entrypoint", - "/usr/bin/python3", - base, - "-u", - "-c", - BACKEND, - ]) - .stdin(Stdio::piped()) - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .kill_on_drop(true); - // Record the unique container name before creation. Every Result exit - // removes it, including a failed readiness exchange after Docker starts. - // Wrapper-scoped labels also let wrapper teardown reap an interrupted run. - self.launch_attempted = true; - let child = command - .spawn() - .map_err(|_| "could not start synthetic HTTPS backend".to_string())?; - self.child = Some(child); - let child = self.child.as_mut().ok_or("backend child was absent")?; - self.input = Some( - child - .stdin - .take() - .ok_or("backend stdin was not available")?, - ); - let output = child - .stdout - .take() - .ok_or("backend stdout was not available")?; - self.output = Some(BufReader::new(output).lines()); - // The host-networked supervisor cannot resolve Docker bridge aliases. - // Python waits for configuration on stdin while we inspect its bridge - // address and generate a certificate for that exact IP. - self.address().await - } - - async fn address(&mut self) -> Result { - let deadline = Instant::now() + COMMAND_TIMEOUT; - loop { - let remaining = deadline.saturating_duration_since(Instant::now()); - if remaining.is_zero() { - return Err("backend bridge address did not become available".to_string()); - } - let mut inspect = Command::from(self.engine.command()); - inspect.args([ - "inspect", - "--format", - "{{json .NetworkSettings.Networks}}", - &self.name, - ]); - if let Ok(output) = checked_command_with_timeout( - &mut inspect, - "inspect backend bridge address", - remaining.min(Duration::from_secs(2)), - ) - .await - { - let networks: Value = serde_json::from_str(&output) - .map_err(|_| "backend network metadata was invalid")?; - if let Some(address) = networks[&self.network]["IPAddress"] - .as_str() - .filter(|address| !address.is_empty()) - { - let address = address - .parse::() - .map_err(|_| "backend network address was not IPv4")?; - if !address.is_private() { - return Err("fixture backend requires a private bridge address".to_string()); - } - return Ok(address.to_string()); - } - } - if self - .child - .as_mut() - .ok_or("backend child was absent")? - .try_wait() - .map_err(|_| "could not inspect backend client status")? - .is_some() - { - return Err("backend exited before its bridge address was available".to_string()); - } - sleep(Duration::from_millis(100)).await; - } - } - - async fn initialize(&mut self, config: &Value) -> Result<(), String> { - if self.exchange(config).await?["ready"] != true { - return Err("synthetic HTTPS backend did not become ready".to_string()); - } - Ok(()) - } - - async fn exchange(&mut self, request: &Value) -> Result { - let mut bytes = - serde_json::to_vec(request).map_err(|_| "backend request encoding failed")?; - bytes.push(b'\n'); - let input = self.input.as_mut().ok_or("backend stdin was absent")?; - let output = self.output.as_mut().ok_or("backend stdout was absent")?; - timeout(COMMAND_TIMEOUT, async { - input - .write_all(&bytes) - .await - .map_err(|_| "backend control write failed")?; - let line = output - .next_line() - .await - .map_err(|_| "backend control read failed")? - .ok_or("backend closed its control stream")?; - serde_json::from_str(&line).map_err(|_| "backend status was not valid JSON") - }) - .await - .map_err(|_| "backend control operation timed out".to_string())? - .map_err(str::to_string) - } - - async fn stop(&mut self) -> Result<(), String> { - // Closing stdin lets Python shut down normally. Removing the named - // container also covers a stalled startup or disconnected Docker client; - // killing the attached client alone cannot prove the container stopped. - drop(self.input.take()); - let mut reap_result = Ok(()); - if let Some(child) = self.child.as_mut() { - reap_result = timeout(COMMAND_TIMEOUT, child.kill()) - .await - .map_err(|_| "backend client teardown timed out".to_string()) - .and_then(|result| { - result.map_err(|_| "backend client teardown failed".to_string()) - }); - } - if !self.launch_attempted { - return reap_result; - } - let mut remove = Command::from(self.engine.command()); - remove.args(["rm", "--force", &self.name]); - let removed = checked_command(&mut remove, "remove synthetic backend container").await; - // --rm may have already removed a normally exited backend. Only a - // successful exact-name listing can establish absence after rm fails. - if removed.is_err() { - let mut list = Command::from(self.engine.command()); - let filter = format!("name=^/{}$", self.name); - list.args(["ps", "--all", "--quiet", "--filter", &filter]); - if !checked_command(&mut list, "verify synthetic backend removal") - .await? - .trim() - .is_empty() - { - return Err("synthetic backend container remained after teardown".to_string()); - } - } - reap_result - } -} - -// Counters attest generations without retaining headers or credential values. -#[derive(Deserialize, Serialize)] -struct BackendCounts { - phase: u8, - total: u64, - accepted: [u64; 2], - rejected: u64, - received: [u64; 2], - missing: u64, - unknown: u64, - invalid_tool_calls: u64, -} - -// Distinct bridge addresses provide independent authorized and wrong-host -// endpoints. Summed counters prove denied traffic reaches neither container. -struct BackendPair { - backends: [Backend; 2], -} - -impl BackendPair { - fn new(name: &str) -> Result { - Ok(Self { - backends: [ - Backend::new(format!("{name}-backend"))?, - Backend::new(format!("{name}-other-backend"))?, - ], - }) - } - - async fn spawn(&mut self, base: &str, tls_directory: &Path) -> Result<[String; 2], String> { - let host = self.backends[0].spawn(base, tls_directory).await?; - let other_host = self.backends[1].spawn(base, tls_directory).await?; - if host == other_host { - return Err("wrong-host control requires a distinct backend address".to_string()); - } - Ok([host, other_host]) - } - - async fn initialize(&mut self, config: &Value) -> Result<(), String> { - for backend in &mut self.backends { - backend.initialize(config).await?; - } - Ok(()) - } - - async fn rotate(&mut self) -> Result<(), String> { - for backend in &mut self.backends { - if backend.exchange(&json!({"command": "rotate"})).await?["phase"] != 1 { - return Err("backend did not switch to the replacement assertion".to_string()); - } - } - Ok(()) - } - - async fn counts(&mut self) -> Result { - let mut combined: Option = None; - for backend in &mut self.backends { - let response = backend.exchange(&json!({"command": "snapshot"})).await?; - let counters: BackendCounts = - serde_json::from_value(response).map_err(|_| "backend counters were invalid")?; - if let Some(total) = combined.as_mut() { - if total.phase != counters.phase { - return Err("fixture backends disagree on the active assertion".to_string()); - } - let add = |left: u64, right: u64| { - left.checked_add(right).ok_or("backend counters overflowed") - }; - total.total = add(total.total, counters.total)?; - total.rejected = add(total.rejected, counters.rejected)?; - total.missing = add(total.missing, counters.missing)?; - total.unknown = add(total.unknown, counters.unknown)?; - total.invalid_tool_calls = - add(total.invalid_tool_calls, counters.invalid_tool_calls)?; - for (left, right) in total.accepted.iter_mut().zip(counters.accepted) { - *left = add(*left, right)?; - } - for (left, right) in total.received.iter_mut().zip(counters.received) { - *left = add(*left, right)?; - } - } else { - combined = Some(counters); - } - } - serde_json::to_value(combined.ok_or("backend counters were absent")?) - .map_err(|_| "backend counters could not be encoded".to_string()) - } - - async fn stop(&mut self) -> Result<(), String> { - let mut failures = Vec::new(); - for backend in &mut self.backends { - if let Err(error) = backend.stop().await { - failures.push(error); - } - } - if failures.is_empty() { - Ok(()) - } else { - Err(failures.join("; ")) - } - } -} - -async fn checked_command(command: &mut Command, label: &str) -> Result { - checked_command_with_timeout(command, label, COMMAND_TIMEOUT).await -} - -async fn checked_command_with_timeout( - command: &mut Command, - label: &str, - max_wait: Duration, -) -> Result { - command - .stdout(Stdio::piped()) - .stderr(Stdio::null()) - .kill_on_drop(true); - let output = timeout(max_wait, command.output()) - .await - .map_err(|_| format!("{label} timed out"))? - .map_err(|_| format!("{label} could not start"))?; - if !output.status.success() { - // CLI arguments, captured output, and subprocess errors can contain - // credential material. Error messages expose only the safe operation. - return Err(format!("{label} failed; subprocess output withheld")); - } - String::from_utf8(output.stdout).map_err(|_| format!("{label} returned invalid UTF-8")) -} - -async fn cli(label: &str, args: &[&str], credential: Option<&str>) -> Result { - let mut command = openshell_cmd(); - command.args(args); - if let Some(credential) = credential { - command.env(TOKEN_ENV, credential); - } - checked_command(&mut command, label).await -} - -async fn generate_certificates( - directory: &Path, - host: &str, - other_host: &str, -) -> Result<(PathBuf, PathBuf), String> { - let ca_key = directory.join("ca.key.fixture"); - let ca = directory.join("ca.crt"); - let key = directory.join("backend.key.fixture"); - let csr = directory.join("backend.csr"); - let certificate = directory.join("backend.crt"); - let extensions = directory.join("backend.ext"); - std::fs::write( - &extensions, - format!( - "basicConstraints=critical,CA:FALSE\nsubjectAltName=IP:{host},IP:{other_host}\nextendedKeyUsage=serverAuth\n" - ), - ) - .map_err(|_| "could not write public TLS certificate extensions")?; - checked_command( - Command::new("openssl") - .args([ - "req", - "-x509", - "-newkey", - "rsa:2048", - "-nodes", - "-days", - "1", - "-subj", - "/CN=stable-placeholder-e2e-ca", - "-keyout", - ]) - .arg(&ca_key) - .arg("-out") - .arg(&ca), - "generate fixture CA", - ) - .await?; - checked_command( - Command::new("openssl") - .args([ - "req", - "-newkey", - "rsa:2048", - "-nodes", - "-subj", - &format!("/CN={host}"), - "-keyout", - ]) - .arg(&key) - .arg("-out") - .arg(&csr), - "generate fixture TLS key", - ) - .await?; - checked_command( - Command::new("openssl") - .args(["x509", "-req", "-days", "1", "-in"]) - .arg(&csr) - .arg("-CA") - .arg(&ca) - .arg("-CAkey") - .arg(&ca_key) - .arg("-CAcreateserial") - .arg("-extfile") - .arg(&extensions) - .arg("-out") - .arg(&certificate), - "sign fixture TLS certificate", - ) - .await?; - Ok((certificate, key)) -} - -async fn base_binaries(base: &str) -> Result { - let engine = ContainerEngine::from_env()?; - let mut command = Command::from(engine.command()); - command.args([ - "run", "--rm", "--network", "none", "--entrypoint", "/usr/bin/python3", base, - "-c", "import json,os,shutil,sys; print(json.dumps({'python':os.path.realpath(sys.executable),'curl':shutil.which('curl')}))", - ]); - let output = checked_command(&mut command, "inspect fixture image binaries").await?; - let binaries: Value = - serde_json::from_str(&output).map_err(|_| "image binary probe was invalid")?; - for field in ["python", "curl"] { - if !binaries[field] - .as_str() - .is_some_and(|path| Path::new(path).is_absolute()) - { - return Err(format!("fixture image has no absolute {field} executable")); - } - } - Ok(binaries) -} - -fn write_profile( - path: &Path, - name: &str, - host: &str, - port: u16, - python: &str, - stable: bool, -) -> Result<(), String> { - // Omitting the opt-in reproduces the behavior of an existing static - // credential profile on both the upstream gateway and the candidate. - let mut credential = json!({"name": "synthetic_assertion", "env_vars": [TOKEN_ENV], - "required": true, "auth_style": "header", "header_name": "x-openshell-sandbox-assertion"}); - if stable { - credential["stable_placeholder"] = json!(true); - } - let document = json!({ - "id": name, "display_name": "External caller assertion E2E", "category": "other", - "credentials": [credential], - "endpoints": [{"host": host, "port": port, "path": "/mcp/**", "protocol": "rest", - "access": "full", "enforcement": "enforce", - "allowed_ips": ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]}], - "binaries": [python], - }); - std::fs::write(path, document.to_string()) - .map_err(|_| "could not write synthetic profile".to_string()) -} - -fn write_policy( - path: &Path, - host: &str, - other_host: &str, - port: u16, - other_port: u16, - python: &str, -) -> Result<(), String> { - // Permit the negative endpoint probes at the network layer so the - // credential binding itself must prevent them from reaching the backend. - // The exact binary allowlist independently denies curl at the valid endpoint. - let endpoints = [(host, port), (host, other_port), (other_host, port)] - .into_iter() - .map(|(host, port)| { - json!({"host": host, "port": port, "path": "/**", "protocol": "rest", - "access": "full", "enforcement": "enforce", - "allowed_ips": ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]}) - }) - .collect::>(); - let document = json!({ - "version": 1, - "filesystem_policy": {"include_workdir": false, - "read_only": ["/usr", "/lib", "/proc", "/dev/urandom", "/etc", "/opt", "/var/log"], - "read_write": ["/sandbox", "/tmp", "/dev/null"]}, - "landlock": {"compatibility": "best_effort"}, - "process": {"run_as_user": "sandbox", "run_as_group": "sandbox"}, - "network_policies": {"synthetic_backend": {"name": "synthetic_backend", - "endpoints": endpoints, "binaries": [{"path": python}]}}, - }); - std::fs::write(path, document.to_string()) - .map_err(|_| "could not write synthetic policy".to_string()) -} - -async fn acknowledged_mutation( - args: &[&str], - credential: Option<&str>, - sandbox: &SandboxGuard, - provider: &str, - kind: &str, - keys: &[String; 2], -) -> Result<(), String> { - let mut command = openshell_cmd(); - command.args(args).args([ - "--wait", - "--timeout", - READINESS_TIMEOUT_SECONDS, - "-o", - "json", - ]); - if let Some(credential) = credential { - command.env(TOKEN_ENV, credential); - } - let output = checked_command_with_timeout( - &mut command, - "apply and acknowledge provider mutation", - READINESS_COMMAND_TIMEOUT, - ) - .await?; - if keys.iter().any(|key| output.contains(key)) || output.contains("openshell:resolve:") { - return Err("provider readiness output contained credential material".to_string()); - } - let body: Value = - serde_json::from_str(&output).map_err(|_| "provider readiness output was invalid JSON")?; - let targets = body["targets"] - .as_array() - .ok_or("provider readiness targets were absent")?; - let [status] = targets.as_slice() else { - return Err("provider mutation did not acknowledge exactly one sandbox".to_string()); - }; - let receipt = &status["receipt"]; - let desired = &receipt["desired"]; - let observed = &status["observed"]; - let expected = if kind == "detach" { "revoked" } else { "ready" }; - if body["mutation_id"].as_str().is_none_or(str::is_empty) - || receipt["mutation_id"] != body["mutation_id"] - || receipt["provider"] != provider - || receipt["kind"] != kind - || desired["sandbox"] != sandbox.name - || status["state"] != expected - || status["wait_outcome"] != "complete" - || status["reason"] != "unspecified" - || observed["reason"] != "unspecified" - { - return Err("provider mutation was not acknowledged for the intended sandbox".to_string()); - } - for field in [ - "attachment_epoch", - "provider_env_revision", - "config_revision", - "policy_hash", - ] { - if desired[field].as_str().is_none_or(str::is_empty) || observed[field] != desired[field] { - return Err(format!( - "provider acknowledgment did not match desired {field}" - )); - } - } - for field in [ - "credentials_installed", - "policy_active", - "launch_environment_installed", - ] { - if observed[field] != true { - return Err(format!("provider acknowledgment omitted {field}")); - } - } - Ok(()) -} - -async fn probe(sandbox: &SandboxGuard, phase: &str) -> Result { - // The client consumes the control file as soon as it appears. Publish a - // complete phase atomically so polling cannot observe an empty write. - let command = format!( - "rm -f {RESULT} && printf '%s' '{phase}' > {CONTROL}.tmp && mv {CONTROL}.tmp {CONTROL}" - ); - timeout(COMMAND_TIMEOUT, sandbox.exec(&["sh", "-c", &command])) - .await - .map_err(|_| "client trigger timed out")? - .map_err(|_| "client trigger failed")?; - let deadline = Instant::now() + Duration::from_secs(20); - loop { - if let Ok(Ok(output)) = - timeout(Duration::from_secs(10), sandbox.exec(&["cat", RESULT])).await - { - let response: Value = - serde_json::from_str(output.trim()).map_err(|_| "client result was invalid")?; - if response["phase"] != phase || response["same_reference"] != true { - return Err( - "persistent client changed its retained environment reference".to_string(), - ); - } - return Ok(response); - } - if Instant::now() >= deadline { - return Err(format!("client phase {phase} did not finish")); - } - sleep(Duration::from_millis(100)).await; - } -} - -async fn probe_disallowed_binary( - sandbox: &SandboxGuard, - curl: &str, - host: &str, - port: u16, -) -> Result<(), String> { - // Binary authorization includes allowed ancestors. Launch curl as a - // sibling of the retained Python client, so Python cannot authorize it. - // The shell builtin sends the reference only through curl's stdin pipe. - let script = r#" -test -n "$STABLE_EXTERNAL_E2E_TOKEN" || exit 64 -"$1" --version >/dev/null 2>&1 || exit 65 -if printf 'x-openshell-sandbox-assertion: %s\n' "$STABLE_EXTERNAL_E2E_TOKEN" | \ - "$1" --silent --fail --max-time 5 --output /dev/null --header @- \ - --data '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"local_hello","arguments":{"name":"rotation-proof"}}}' "$2" 2>/dev/null -then - printf 'unexpected-success' -else - printf 'denied' -fi -"#; - let url = format!("https://{host}:{port}/mcp/local-hello"); - let output = timeout( - COMMAND_TIMEOUT, - sandbox.exec(&["sh", "-c", script, "binary-probe", curl, &url]), - ) - .await - .map_err(|_| "independent binary probe timed out")? - .map_err(|_| "independent binary probe failed to execute")?; - if output.trim() != "denied" { - return Err("independent disallowed binary reached the endpoint".to_string()); - } - Ok(()) -} - -fn check( - response: &Value, - pid: u64, - success: bool, - backend_phase: Option, -) -> Result<(), String> { - if response["pid"].as_u64() != Some(pid) || response["ok"].as_bool() != Some(success) { - // Report only typed status fields; never include HTTP error text or - // a serialized response that might later grow a credential field. - return Err(format!( - "client probe failed: pid_matches={}, expected_ok={success}, actual_ok={:?}, status={:?}, error_kind={:?}, reason_kind={:?}", - response["pid"].as_u64() == Some(pid), - response["ok"].as_bool(), - response["status"].as_u64(), - response["error_kind"].as_str(), - response["reason_kind"].as_str(), - )); - } - if let Some(phase) = backend_phase - && (response["backend_phase"].as_u64() != Some(phase) - || response["status"] != 200 - || response["credential_generation"] != if phase == 0 { "A" } else { "B" } - || response["tool_call"] != true) - { - return Err("backend did not attest the expected credential generation".to_string()); - } - Ok(()) -} - -#[tokio::test] -#[serial_test::serial] -async fn persistent_external_placeholder_rotation_and_revocation() -> Result<(), String> { - external_caller_assertion_rotation(true).await -} - -#[tokio::test] -#[serial_test::serial] -async fn ordinary_external_placeholder_keeps_revoked_assertion_after_rotation() -> Result<(), String> -{ - external_caller_assertion_rotation(false).await -} - -// Keep each lifecycle together so no phase can replace the retained client. -#[allow(clippy::too_many_lines)] -async fn external_caller_assertion_rotation(stable: bool) -> Result<(), String> { - let mut gateway_fixture = GatewayTrustFixture::load()?; - let name = format!("e2e{:016x}", rand::random::()); - let mut backend = BackendPair::new(&name)?; - // The wrapper's directory is shared with the host Docker daemon in CI; - // a job-container-local temporary path cannot back the TLS bind mount. - let directory = TempDir::new_in(&gateway_fixture.directory) - .map_err(|_| "could not allocate fixture directory")?; - let context = directory.path().join("image"); - std::fs::create_dir(&context).map_err(|_| "could not allocate public image context")?; - let backend_tls = directory.path().join("backend-tls"); - std::fs::create_dir(&backend_tls).map_err(|_| "could not allocate backend TLS directory")?; - std::fs::write(context.join("client.py"), CLIENT) - .map_err(|_| "could not write client source")?; - let base = std::env::var("OPENSHELL_E2E_DOCKER_SANDBOX_IMAGE") - .unwrap_or_else(|_| E2E_WORKLOAD_IMAGE.to_string()); - if base.chars().any(char::is_whitespace) { - return Err("fixture image reference contains whitespace".to_string()); - } - let binaries = base_binaries(&base).await?; - let python = binaries["python"] - .as_str() - .ok_or("Python executable was absent")?; - let dockerfile = context.join("Dockerfile"); - std::fs::write( - &dockerfile, - format!("FROM {base}\nCOPY client.py /opt/stable-placeholder-client.py\nUSER 1000:1000\n"), - ) - .map_err(|_| "could not write fixture Dockerfile")?; - let supervisor_dockerfile = context.join("Dockerfile.supervisor"); - // Build the combined trust bundle in the workload image: the supervisor is - // distroless and has no shell. The final stage preserves the supervisor's - // default user and its original public trust roots. - std::fs::write(&supervisor_dockerfile, format!( - "FROM {} AS supervisor\nFROM {base} AS trust-bundle\nUSER 0\nCOPY --from=supervisor /etc/ssl/certs/ca-certificates.crt /tmp/ca-certificates.crt\nCOPY fixture-ca.crt /tmp/stable-fixture-ca.crt\nRUN [\"/usr/bin/python3\", \"-c\", \"from pathlib import Path; bundle = Path('/tmp/ca-certificates.crt'); bundle.write_bytes(bundle.read_bytes() + Path('/tmp/stable-fixture-ca.crt').read_bytes())\"]\nFROM {}\nCOPY --from=trust-bundle /tmp/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt\n", - gateway_fixture.supervisor_image, - gateway_fixture.supervisor_image - )).map_err(|_| "could not write fixture supervisor Dockerfile")?; - let image = FixtureImage::new()?; - let supervisor_image = FixtureImage::new()?; - // Each backend has its own network namespace, so fixed internal ports need - // no host reservation or publication and remain independent across runs. - let port = BACKEND_PORT; - let other_port = OTHER_BACKEND_PORT; - let keys = [ - format!("e2e-{:032x}", rand::random::()), - format!("e2e-{:032x}", rand::random::()), - ]; - let profile = directory.path().join("profile.json"); - let policy = directory.path().join("policy.json"); - let profile_path = profile.to_str().ok_or("profile path was not UTF-8")?; - let policy_path = policy.to_str().ok_or("policy path was not UTF-8")?; - let curl = binaries["curl"] - .as_str() - .ok_or("curl executable was absent")?; - let mut sandbox = None; - let result = async { - // Begin container mutation inside this scope so address, certificate, - // image and enrollment failures all reach explicit bounded teardown. - image.build(&dockerfile, &context).await?; - let [host, other_host] = backend.spawn(&base, &backend_tls).await?; - let (certificate, private_key) = - generate_certificates(directory.path(), &host, &other_host).await?; - std::fs::copy(&certificate, backend_tls.join("backend.crt")) - .map_err(|_| "could not stage backend certificate")?; - let backend_tls_key = backend_tls.join("backend.key.fixture"); - std::fs::copy(&private_key, &backend_tls_key) - .map_err(|_| "could not stage backend TLS key")?; - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt as _; - // The backends inherit the image's unprivileged user. Only their - // mounted leaf key is readable; the private CA key stays outside - // the shared mount and both image build contexts. - std::fs::set_permissions(&backend_tls_key, std::fs::Permissions::from_mode(0o444)) - .map_err(|_| "could not set backend TLS key permissions")?; - } - backend.initialize(&json!({"keys": keys, "ports": [port, other_port], - "certificate": "/fixture-tls/backend.crt", "private_key": "/fixture-tls/backend.key.fixture"})) - .await?; - std::fs::copy(directory.path().join("ca.crt"), context.join("fixture-ca.crt")) - .map_err(|_| "could not copy public fixture CA")?; - supervisor_image - .build(&supervisor_dockerfile, &context) - .await?; - gateway_fixture.apply(supervisor_image.tag()).await?; - write_profile(&profile, &name, &host, port, python, stable)?; - write_policy(&policy, &host, &other_host, port, other_port, python)?; - let configuration = json!({"host": host, "other_host": other_host, "port": port, - "other_port": other_port, "stable": stable}).to_string(); - cli( - "import synthetic provider profile", - &["provider", "profile", "import", "--file", profile_path], - None, - ) - .await?; - cli( - "create synthetic provider", - &[ - "provider", - "create", - "--name", - &name, - "--type", - &name, - "--credential", - TOKEN_ENV, - ], - Some(&keys[0]), - ) - .await?; - sandbox = Some( - SandboxGuard::create_keep_with_args( - &[ - "--from", - image.tag(), - "--provider", - &name, - "--policy", - policy_path, - "--no-auto-providers", - ], - &[ - "/usr/bin/python3", - "-u", - "/opt/stable-placeholder-client.py", - &configuration, - ], - READY, - ) - .await - .map_err(|_| "persistent sandbox client could not start")?, - ); - let running = sandbox - .as_ref() - .ok_or("sandbox was absent after creation")?; - let initial = probe(running, "initial").await?; - let pid = initial["pid"].as_u64().ok_or("client PID was absent")?; - check(&initial, pid, true, Some(0))?; - let before = backend.counts().await?; - if before["total"] != 1 || before["accepted"][0] != 1 { - return Err("initial backend request count was incorrect".to_string()); - } - for phase in [ - "wrong_host_control", - "wrong_port_control", - "wrong_path_control", - ] { - let control = probe(running, phase).await?; - check(&control, pid, false, None)?; - if control["status"] != 401 || control["backend_phase"] != 0 { - return Err(format!( - "negative endpoint {phase} was not reachable without a credential" - )); - } - } - let before = backend.counts().await?; - if before["total"] != 4 || before["rejected"] != 3 || before["accepted"] != json!([1, 0]) { - return Err("uncredentialed endpoint control assertions failed".to_string()); - } - for phase in [ - "wrong_host", - "wrong_port", - "wrong_path", - "canonical_alias", - "untrusted_ca", - ] { - check(&probe(running, phase).await?, pid, false, None)?; - if backend.counts().await? != before { - return Err(format!("denied phase {phase} reached the backend")); - } - } - probe_disallowed_binary(running, curl, &host, port).await?; - if backend.counts().await? != before { - return Err("disallowed binary reached the backend".to_string()); - } - - backend.rotate().await?; - // This is the only provider update. --wait acknowledges the exact - // saved revision before either client sends its next tool request. - acknowledged_mutation( - &["provider", "update", &name, "--credential", TOKEN_ENV], - Some(&keys[1]), - running, &name, "update", &keys, - ) - .await?; - // No workload requests occur while waiting. The first next request - // must use B with the opt-in; the ordinary profile still resolves A. - let retained = probe(running, "rotated").await?; - check(&retained, pid, stable, stable.then_some(1))?; - if !stable && (retained["status"] != 401 || retained["backend_phase"] != 1 - || retained["credential_generation"] != "A" || retained["tool_call"] != true) - { - return Err("ordinary retained reference did not send the revoked assertion A".to_string()); - } - let rotated = backend.counts().await?; - let accepted_after_rotation = if stable { json!([1, 1]) } else { json!([1, 0]) }; - let received_after_rotation = if stable { json!([1, 1]) } else { json!([2, 0]) }; - let rejected_after_rotation = if stable { 3 } else { 4 }; - if rotated["total"] != 5 || rotated["accepted"] != accepted_after_rotation - || rotated["received"] != received_after_rotation - || rotated["rejected"] != rejected_after_rotation - || rotated["missing"] != 3 || rotated["unknown"] != 0 || rotated["invalid_tool_calls"] != 0 - { - return Err("single-update backend assertions failed".to_string()); - } - - // A fresh process proves the installed provider revision can use B in - // both modes. It does not replace or modify the original client. - let fresh_output = timeout(COMMAND_TIMEOUT, running.exec(&[ - "/usr/bin/python3", "-u", "/opt/stable-placeholder-client.py", &configuration, "--once", - ])).await.map_err(|_| "fresh client timed out")? - .map_err(|_| "fresh client failed")?; - let fresh: Value = serde_json::from_str(fresh_output.trim()) - .map_err(|_| "fresh client returned invalid status")?; - let fresh_pid = fresh["pid"].as_u64().ok_or("fresh client PID was absent")?; - if fresh_pid == pid || fresh["same_reference"] != true { - return Err("fresh process control did not retain its own issued reference".to_string()); - } - check(&fresh, fresh_pid, true, Some(1))?; - let refreshed = backend.counts().await?; - let final_accepted = if stable { json!([1, 2]) } else { json!([1, 1]) }; - let final_received = if stable { json!([1, 2]) } else { json!([2, 1]) }; - if refreshed["total"] != 6 || refreshed["accepted"] != final_accepted - || refreshed["received"] != final_received || refreshed["rejected"] != rejected_after_rotation - || refreshed["missing"] != 3 || refreshed["unknown"] != 0 || refreshed["invalid_tool_calls"] != 0 - { - return Err("fresh process did not prove installed assertion B".to_string()); - } - - acknowledged_mutation( - &["sandbox", "provider", "detach", &running.name, &name], - None, - running, &name, "detach", &keys, - ) - .await?; - // Detach must revoke the reference while leaving the independently - // authorized route usable; a network outage cannot satisfy this proof. - let control = probe(running, "detached_control").await?; - check(&control, pid, false, None)?; - if control["status"] != 401 || control["backend_phase"] != 1 { - return Err("detached endpoint was not reachable without a credential".to_string()); - } - let detached = backend.counts().await?; - if detached["total"] != 7 - || detached["accepted"] != final_accepted - || detached["received"] != final_received - || detached["rejected"] != rejected_after_rotation + 1 - || detached["missing"] != 4 || detached["unknown"] != 0 || detached["invalid_tool_calls"] != 0 - || detached["phase"] != 1 - { - return Err("detached endpoint control assertions failed".to_string()); - } - check(&probe(running, "detached").await?, pid, false, None)?; - if backend.counts().await? != detached { - return Err("detached credential reached the backend".to_string()); - } - println!( - "{}", - json!({"phase": "complete", "pid": pid, "same_reference": true, - "stable_placeholder": stable, "provider_updates": 1, - "retained_assertion": if stable { "B" } else { "A" }, - "retained_request_accepted": stable, "fresh_process_assertion": "B", - "tool": "local_hello", "endpoint_denials": true, "binary_denial": true, - "canonical_alias_denial": true, "tls_verified": true, "detached": true}) - ); - Ok(()) - } - .await; - - // Resource names are unique to this run. Always attempt cleanup, including - // failures during enrollment, without exposing captured provider output. - if let Some(mut sandbox) = sandbox { - let _ = timeout(COMMAND_TIMEOUT, sandbox.cleanup()).await; - } - let _ = cli( - "delete synthetic provider", - &["provider", "delete", &name], - None, - ) - .await; - let _ = cli( - "delete synthetic profile", - &["provider", "profile", "delete", &name], - None, - ) - .await; - let backend_cleanup = backend.stop().await; - // Restore the original runtime before removing its replacement. Retain the - // derived supervisor image if restoration fails, and report that failure - // even when a lifecycle assertion already failed. - let gateway_restore = gateway_fixture.restore().await; - let supervisor_cleanup = if gateway_restore.is_ok() { - supervisor_image.remove().await - } else { - Ok(()) - }; - let image_cleanup = image.remove().await; - let failures = [ - result, - backend_cleanup, - gateway_restore, - supervisor_cleanup, - image_cleanup, - ] - .into_iter() - .filter_map(Result::err) - .collect::>(); - if failures.is_empty() { - Ok(()) - } else { - Err(failures.join("; ")) - } -} diff --git a/e2e/support/podman-gateway-config.sh b/e2e/support/podman-gateway-config.sh index 580ad0673d..0be7ab7576 100755 --- a/e2e/support/podman-gateway-config.sh +++ b/e2e/support/podman-gateway-config.sh @@ -30,10 +30,9 @@ e2e_write_podman_gateway_config() { local stop_timeout_secs=${11} local supervisor_image=${12} local sandbox_runtime_image=${13} - local provider_spiffe_socket=${14} - local podman_socket=${15} - local oidc_mode=${16} - local oidc_issuer=${17} + local podman_socket=${14} + local oidc_mode=${15} + local oidc_issuer=${16} local configured_with_tls cp "${root}/deploy/rpm/gateway.toml.default" "${output}" @@ -67,9 +66,6 @@ e2e_write_podman_gateway_config() { printf 'supervisor_image = %s\n' "$(e2e_podman_toml_string "${supervisor_image}")" printf 'sandbox_runtime_image = %s\n' "$(e2e_podman_toml_string "${sandbox_runtime_image}")" printf 'enable_bind_mounts = true\n' - if [ -n "${provider_spiffe_socket}" ]; then - printf 'provider_spiffe_workload_api_socket = %s\n' "$(e2e_podman_toml_string "${provider_spiffe_socket}")" - fi if [ -n "${podman_socket}" ]; then printf 'socket_path = %s\n' "$(e2e_podman_toml_string "${podman_socket}")" fi @@ -83,17 +79,5 @@ e2e_write_podman_gateway_config() { e2e_write_gateway_oidc_config "${oidc_issuer}" fi fi - # Opt-in OTLP export so the otlp_relay e2e can bind a collector stub on - # the referenced port. Supervisors connect lazily, so the gateway may - # start before the stub exists. - if [ -n "${OPENSHELL_E2E_OTLP_ENDPOINT:-}" ]; then - printf '\n[openshell.gateway.otlp]\n' - printf 'endpoint = %s\n' "$(e2e_podman_toml_string "${OPENSHELL_E2E_OTLP_ENDPOINT}")" - # The agent trace relay is opt-in; OPENSHELL_E2E_OTLP_AGENT=0 runs the - # relay's inert case with trace export still on. - if [ "${OPENSHELL_E2E_OTLP_AGENT:-1}" != "0" ]; then - printf '\n[openshell.gateway.otlp.agent]\nenabled = true\n' - fi - fi } >>"${output}" } diff --git a/e2e/with-docker-gateway.sh b/e2e/with-docker-gateway.sh index 8f62245c9c..90dc957745 100755 --- a/e2e/with-docker-gateway.sh +++ b/e2e/with-docker-gateway.sh @@ -645,18 +645,6 @@ GATEWAY_CONFIG="${STATE_DIR}/gateway.toml" printf 'additional_ca_bundle = %s\n\n' \ "$(toml_string "${ADDITIONAL_CA_DIR}/ca.crt")" fi - # Opt-in OTLP export so the otlp_relay e2e can bind a collector stub on - # the referenced port. Supervisors connect lazily, so the gateway may - # start before the stub exists. - if [ -n "${OPENSHELL_E2E_OTLP_ENDPOINT:-}" ]; then - printf '[openshell.gateway.otlp]\n' - printf 'endpoint = %s\n\n' "$(toml_string "${OPENSHELL_E2E_OTLP_ENDPOINT}")" - # The agent trace relay is opt-in; OPENSHELL_E2E_OTLP_AGENT=0 runs the - # relay's inert case with trace export still on. - if [ "${OPENSHELL_E2E_OTLP_AGENT:-1}" != "0" ]; then - printf '[openshell.gateway.otlp.agent]\nenabled = true\n\n' - fi - fi printf '[openshell.drivers.docker]\n' if [ -n "${SUPERVISOR_NETWORK_MODE}" ]; then printf 'supervisor_network_mode = %s\n' "$(toml_string "${SUPERVISOR_NETWORK_MODE}")" diff --git a/e2e/with-podman-gateway.sh b/e2e/with-podman-gateway.sh index 96b2091380..62841d9665 100755 --- a/e2e/with-podman-gateway.sh +++ b/e2e/with-podman-gateway.sh @@ -97,18 +97,6 @@ podman_cmd() { WORKDIR_PARENT="${TMPDIR:-/tmp}" WORKDIR_PARENT="${WORKDIR_PARENT%/}" WORKDIR="$(mktemp -d "${WORKDIR_PARENT}/openshell-e2e-podman.XXXXXX")" -if [ "${OPENSHELL_E2E_SPIFFE_FIXTURE:-0}" = "1" ]; then - mkdir -p "${WORKDIR}/spiffe" - export OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET="${OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET:-${WORKDIR}/spiffe/gateway.sock}" - export OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET="${OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET}" - if [ -z "${OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET:-}" ]; then - OPENSHELL_E2E_PROVIDER_SPIFFE_PORT="$(e2e_pick_port)" - export OPENSHELL_E2E_PROVIDER_SPIFFE_LISTEN="0.0.0.0:${OPENSHELL_E2E_PROVIDER_SPIFFE_PORT}" - # Podman supervisors run with host networking, so reach the host-side - # Workload API fixture over loopback rather than the workload bridge. - export OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET="tcp:127.0.0.1:${OPENSHELL_E2E_PROVIDER_SPIFFE_PORT}" - fi -fi GATEWAY_BIN="" CLI_BIN="" GATEWAY_PID="" @@ -583,7 +571,6 @@ e2e_write_podman_gateway_config \ "${PODMAN_STOP_TIMEOUT_SECS}" \ "${SUPERVISOR_IMAGE}" \ "${SANDBOX_BOUNDARY_IMAGE}" \ - "${OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET:-}" \ "${OPENSHELL_PODMAN_SOCKET:-}" \ "${OIDC_MODE}" \ "${OPENSHELL_OIDC_ISSUER:-}" diff --git a/tasks/scripts/test-gateway-config.sh b/tasks/scripts/test-gateway-config.sh index bc36c9c55c..109fed8a76 100755 --- a/tasks/scripts/test-gateway-config.sh +++ b/tasks/scripts/test-gateway-config.sh @@ -43,12 +43,12 @@ mkdir -p "${WORK}/pki/client" "${WORK}/jwt" e2e_write_podman_gateway_config \ "${WORK}/podman.toml" "${ROOT}" "${WORK}/pki" "${WORK}/jwt" \ test-gateway 0 "${WORK}/driver.sock" test-network 18181 \ - workload:test 15 supervisor:test sandbox:test "${WORK}/spiffe.sock" \ + workload:test 15 supervisor:test sandbox:test \ "${WORK}/podman.sock" 0 "" e2e_write_podman_gateway_config \ "${WORK}/podman-external.toml" "${ROOT}" "${WORK}/pki" "${WORK}/jwt" \ test-gateway 1 "${WORK}/driver.sock" test-network 18181 \ - workload:test 15 supervisor:test sandbox:test "${WORK}/spiffe.sock" \ + workload:test 15 supervisor:test sandbox:test \ "${WORK}/podman.sock" 0 "" printf '%s\n' \ @@ -65,7 +65,6 @@ printf '%s\n' \ 'assert driver["image_pull_policy"] == "if_not_present"' \ 'assert driver["supervisor_image"] == "supervisor:test"' \ 'assert driver["sandbox_runtime_image"] == "sandbox:test"' \ - 'assert driver["provider_spiffe_workload_api_socket"].endswith("/spiffe.sock")' \ 'assert driver["socket_path"].endswith("/podman.sock")' \ 'assert driver["resource_admission"] == {"enabled": False}' \ 'external_driver = external["openshell"]["drivers"]["podman"]' \ From 752a7f0abb57749e3a13e535068ac9067b1e414e Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 22:04:37 -0800 Subject: [PATCH 16/22] test(support): name the OTLP and SPIFFE environment ports _PORT Signed-off-by: Matthew Grossman --- tests/support/README.md | 6 ++--- tests/support/otlp/src/lib.rs | 23 ++++++++-------- tests/support/spiffe/src/lib.rs | 28 +++++++++++--------- tests/tmachine/ansible/playbooks/otlp.yaml | 2 +- tests/tmachine/ansible/playbooks/spiffe.yaml | 4 +-- 5 files changed, 33 insertions(+), 30 deletions(-) diff --git a/tests/support/README.md b/tests/support/README.md index 7493ce83fb..764c901e56 100644 --- a/tests/support/README.md +++ b/tests/support/README.md @@ -25,10 +25,10 @@ never skips it. Add a row when you add a variable. The runner also sets | `OPENSHELL_TEST_KEYCLOAK_CLIENT_ID` | `-keycloak` | `keycloak-support` | A client in that realm that allows password grants. | | `OPENSHELL_TEST_KEYCLOAK_USERNAME` | `-keycloak` | `keycloak-support` | The realm user that tests sign in as. | | `OPENSHELL_TEST_KEYCLOAK_PASSWORD` | `-keycloak` | `keycloak-support` | That user's password. | -| `OPENSHELL_TEST_OTLP_LISTEN` | `-otlp` (`playbooks/otlp.yaml`) | `otlp-support` | The address the test's OTLP/gRPC collector listens on, such as `0.0.0.0:4317`. | +| `OPENSHELL_TEST_OTLP_PORT` | `-otlp` (`playbooks/otlp.yaml`) | `otlp-support` | The port the test's OTLP/gRPC collector listens on, such as `4317`. | | `OPENSHELL_TEST_OTLP_ENDPOINT` | `-otlp` | `otlp-support` | The collector endpoint in the gateway's `[openshell.gateway.otlp]`, which also enables the agent trace relay. Tests check that sandboxes never see it. | -| `OPENSHELL_TEST_SPIFFE_GATEWAY_LISTEN` | `-spiffe` (`playbooks/spiffe.yaml`) | `spiffe-support` | The Unix socket the test's gateway Workload API listens on. The gateway's `OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET` names it. | -| `OPENSHELL_TEST_SPIFFE_SUPERVISOR_LISTEN` | `-spiffe` | `spiffe-support` | The TCP address the test's supervisor Workload API listens on, such as `0.0.0.0:17690`. The driver's `provider_spiffe_workload_api_socket` reaches it as `tcp:127.0.0.1:`. | +| `OPENSHELL_TEST_SPIFFE_GATEWAY_SOCKET` | `-spiffe` (`playbooks/spiffe.yaml`) | `spiffe-support` | The Unix socket the test's gateway Workload API listens on. The gateway's `OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET` names it. | +| `OPENSHELL_TEST_SPIFFE_SUPERVISOR_PORT` | `-spiffe` | `spiffe-support` | The TCP port the test's supervisor Workload API listens on, such as `17690`. The driver's `provider_spiffe_workload_api_socket` reaches it as `tcp:127.0.0.1:`. | | `OPENSHELL_TEST_ADDITIONAL_CA_CERT` | `-additional-ca` (`playbooks/additional-ca.yaml`), which sets `openshell.supervisor.network.additional_ca_bundle` | `host-server-support` (`TestCa::from_env`) | The path of the CA certificate, in PEM, that the supervisor trusts for sandbox egress. | | `OPENSHELL_TEST_ADDITIONAL_CA_KEY` | `-additional-ca` | `host-server-support` (`TestCa::from_env`) | The path of that CA's private key, in PEM, readable by the test user. Tests sign server certificates with it. | | `OPENSHELL_TEST_BASE_IMAGE` | Optional; you, for example to use a mirror | `testkit::base_image()` | The default sandbox image. Unset, it is `nvcr.io/nvidia/base/ubuntu:24.04`. | diff --git a/tests/support/otlp/src/lib.rs b/tests/support/otlp/src/lib.rs index 13463dce9a..c33757f36e 100644 --- a/tests/support/otlp/src/lib.rs +++ b/tests/support/otlp/src/lib.rs @@ -5,7 +5,7 @@ //! test runs. //! //! The environment configures the gateway's `[openshell.gateway.otlp]` -//! endpoint and publishes it, with the address the test must listen on, in +//! endpoint and publishes it, with the port the test must listen on, in //! `OPENSHELL_TEST_OTLP_*` variables. Under `openshell-test-runner`, the //! tmachine `-otlp` environments do that //! (`tests/tmachine/ansible/playbooks/otlp.yaml`); against your own @@ -13,14 +13,14 @@ //! //! | Variable | Example | //! |---|---| -//! | `OPENSHELL_TEST_OTLP_LISTEN` | `0.0.0.0:4317` | +//! | `OPENSHELL_TEST_OTLP_PORT` | `4317` | //! | `OPENSHELL_TEST_OTLP_ENDPOINT` | `http://host.containers.internal:4317` | //! //! A missing variable fails the test; it never skips it. Tests that start a -//! collector can't run at the same time, since they bind the same address. +//! collector can't run at the same time, since they bind the same port. use std::collections::HashMap; -use std::net::SocketAddr; +use std::net::{Ipv4Addr, SocketAddr}; use std::time::Duration; use openshell_otel_test_support::OtlpTestServer; @@ -31,13 +31,13 @@ pub use openshell_otel_test_support::relay::{ SANDBOX_ID_KEY, SOURCE_KEY, SOURCE_VALUE, encoded_trace_request, }; -pub const LISTEN_ENV: &str = "OPENSHELL_TEST_OTLP_LISTEN"; +pub const PORT_ENV: &str = "OPENSHELL_TEST_OTLP_PORT"; pub const ENDPOINT_ENV: &str = "OPENSHELL_TEST_OTLP_ENDPOINT"; /// String resource attributes, keyed by name. pub type Attributes = HashMap; -/// An OTLP/gRPC collector on the address the environment chose. It records +/// An OTLP/gRPC collector on the port the environment chose. It records /// what arrives and stops when dropped. pub struct Collector { server: OtlpTestServer, @@ -45,13 +45,14 @@ pub struct Collector { } impl Collector { - /// Listen on [`LISTEN_ENV`]. + /// Listen on [`PORT_ENV`] on every host address. pub async fn start() -> Result { - let listen = required(LISTEN_ENV)?; + let port = required(PORT_ENV)?; let endpoint = required(ENDPOINT_ENV)?; - let addr: SocketAddr = listen + let port: u16 = port .parse() - .map_err(|error| Error::msg(format!("{LISTEN_ENV}={listen}: {error}")))?; + .map_err(|error| Error::msg(format!("{PORT_ENV}={port}: {error}")))?; + let addr = SocketAddr::from((Ipv4Addr::UNSPECIFIED, port)); let server = OtlpTestServer::try_start_on(addr) .await .context(format!("start the OTLP collector on {addr}"))?; @@ -113,7 +114,7 @@ impl Collector { .await } - /// Stop listening, so the next test can bind the address. + /// Stop listening, so the next test can bind the port. pub async fn shutdown(self) { drop(self.server.shutdown().await); } diff --git a/tests/support/spiffe/src/lib.rs b/tests/support/spiffe/src/lib.rs index e222ef03b6..194b4a4036 100644 --- a/tests/support/spiffe/src/lib.rs +++ b/tests/support/spiffe/src/lib.rs @@ -5,7 +5,8 @@ //! JWT-SVIDs from Workload APIs the test runs. //! //! The environment points the gateway's Workload API socket and the driver's -//! `provider_spiffe_workload_api_socket` at addresses the test listens on, and +//! `provider_spiffe_workload_api_socket` at a socket and a port the test +//! listens on, and //! publishes them in `OPENSHELL_TEST_SPIFFE_*` variables. Under //! `openshell-test-runner`, the tmachine `-spiffe` environments //! do that (`tests/tmachine/ansible/playbooks/spiffe.yaml`); against your own @@ -13,19 +14,19 @@ //! //! | Variable | Example | //! |---|---| -//! | `OPENSHELL_TEST_SPIFFE_GATEWAY_LISTEN` | `/var/lib/openshell-test/spiffe/gateway.sock` | -//! | `OPENSHELL_TEST_SPIFFE_SUPERVISOR_LISTEN` | `0.0.0.0:17690` | +//! | `OPENSHELL_TEST_SPIFFE_GATEWAY_SOCKET` | `/var/lib/openshell-test/spiffe/gateway.sock` | +//! | `OPENSHELL_TEST_SPIFFE_SUPERVISOR_PORT` | `17690` | //! //! Both Workload APIs sign with one fixture key and serve its bundle for //! [`TRUST_DOMAIN`]. Every supervisor gets [`SUPERVISOR_SUBJECT`]: suites //! test credential isolation with distinct providers and audiences, not //! SPIRE attestation. A missing variable fails the test; it never skips it. //! Tests that start the Workload APIs can't run at the same time, since they -//! bind the same addresses. +//! bind the same socket and port. use std::collections::HashMap; use std::convert::Infallible; -use std::net::SocketAddr; +use std::net::{Ipv4Addr, SocketAddr}; use std::os::unix::fs::PermissionsExt as _; use std::path::PathBuf; use std::sync::Arc; @@ -43,8 +44,8 @@ use tonic::body::Body as TonicBody; use tonic::codegen::{Body, http}; use tonic::{Request, Response, Status}; -pub const GATEWAY_LISTEN_ENV: &str = "OPENSHELL_TEST_SPIFFE_GATEWAY_LISTEN"; -pub const SUPERVISOR_LISTEN_ENV: &str = "OPENSHELL_TEST_SPIFFE_SUPERVISOR_LISTEN"; +pub const GATEWAY_SOCKET_ENV: &str = "OPENSHELL_TEST_SPIFFE_GATEWAY_SOCKET"; +pub const SUPERVISOR_PORT_ENV: &str = "OPENSHELL_TEST_SPIFFE_SUPERVISOR_PORT"; pub const TRUST_DOMAIN: &str = "openshell-e2e.test"; /// The `iss` of every JWT-SVID. @@ -101,14 +102,15 @@ pub struct WorkloadApis { impl WorkloadApis { /// Serve the gateway's Workload API on the Unix socket - /// [`GATEWAY_LISTEN_ENV`] names, and the supervisors' on the TCP address - /// [`SUPERVISOR_LISTEN_ENV`] names. + /// [`GATEWAY_SOCKET_ENV`] names, and the supervisors' on the TCP port + /// [`SUPERVISOR_PORT_ENV`] names, on every host address. pub async fn start() -> Result { - let socket = PathBuf::from(required(GATEWAY_LISTEN_ENV)?); - let listen = required(SUPERVISOR_LISTEN_ENV)?; - let addr: SocketAddr = listen + let socket = PathBuf::from(required(GATEWAY_SOCKET_ENV)?); + let port = required(SUPERVISOR_PORT_ENV)?; + let port: u16 = port .parse() - .map_err(|error| Error::msg(format!("{SUPERVISOR_LISTEN_ENV}={listen}: {error}")))?; + .map_err(|error| Error::msg(format!("{SUPERVISOR_PORT_ENV}={port}: {error}")))?; + let addr = SocketAddr::from((Ipv4Addr::UNSPECIFIED, port)); // A socket a stopped test left behind would make the bind fail. match std::fs::remove_file(&socket) { diff --git a/tests/tmachine/ansible/playbooks/otlp.yaml b/tests/tmachine/ansible/playbooks/otlp.yaml index 6d4ba1d460..a1375cfc67 100644 --- a/tests/tmachine/ansible/playbooks/otlp.yaml +++ b/tests/tmachine/ansible/playbooks/otlp.yaml @@ -37,5 +37,5 @@ vars: test_env_name: otlp test_env_vars: - OPENSHELL_TEST_OTLP_LISTEN: "0.0.0.0:{{ otlp_port }}" + OPENSHELL_TEST_OTLP_PORT: "{{ otlp_port }}" OPENSHELL_TEST_OTLP_ENDPOINT: "{{ otlp_endpoint }}" diff --git a/tests/tmachine/ansible/playbooks/spiffe.yaml b/tests/tmachine/ansible/playbooks/spiffe.yaml index 7c510a55c3..149de03ef9 100644 --- a/tests/tmachine/ansible/playbooks/spiffe.yaml +++ b/tests/tmachine/ansible/playbooks/spiffe.yaml @@ -73,5 +73,5 @@ vars: test_env_name: spiffe test_env_vars: - OPENSHELL_TEST_SPIFFE_GATEWAY_LISTEN: "{{ spiffe_gateway_socket }}" - OPENSHELL_TEST_SPIFFE_SUPERVISOR_LISTEN: "0.0.0.0:{{ spiffe_supervisor_port }}" + OPENSHELL_TEST_SPIFFE_GATEWAY_SOCKET: "{{ spiffe_gateway_socket }}" + OPENSHELL_TEST_SPIFFE_SUPERVISOR_PORT: "{{ spiffe_supervisor_port }}" From a29ffe03ac88c84e69e957b14b23743561fc317a Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 22:56:12 -0800 Subject: [PATCH 17/22] test(tmachine): drop the removed provider_token_exchange binary from the Podman archive filter Signed-off-by: Matthew Grossman --- tests/tmachine/artifacts.nix | 2 -- 1 file changed, 2 deletions(-) diff --git a/tests/tmachine/artifacts.nix b/tests/tmachine/artifacts.nix index d8b743b803..e25d04d03e 100644 --- a/tests/tmachine/artifacts.nix +++ b/tests/tmachine/artifacts.nix @@ -100,8 +100,6 @@ let # Its move to conformance is deferred until the isolation work in #4120; see # #4246. "provider_auto_create" - # Needs the SPIFFE fixtures that the wrapper sets up. Wrapper lane. - "provider_token_exchange" # Holds only the on-failure restart test until #5507; the rest moved to # testkit. Nextest archive filters cannot select individual tests, so keep # the complete binary in the follow-up bucket. From 333a05fd6c8f2cc789a50507233b9ac05105f707 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 11:45:11 -0800 Subject: [PATCH 18/22] test(features): run the gateway-config suites under testkit's harness Each test target now has a unique name, harness = false and a testkit main, so tests/suites/unsupported.yaml can skip a test per environment. The manifests also point at the ai-openshell repository. Signed-off-by: Matthew Grossman --- tests/suites/features/otlp-relay/Cargo.toml | 7 ++++++- tests/suites/features/otlp-relay/tests/otlp_relay.rs | 4 ++++ tests/suites/features/provider-refresh/Cargo.toml | 7 ++++++- .../provider-refresh/tests/refresh_handles.rs | 4 ++++ tests/suites/features/provider-rotation/Cargo.toml | 12 +++++++++++- .../features/provider-rotation/tests/readiness.rs | 4 ++++ .../provider-rotation/tests/stable_placeholders.rs | 4 ++++ .../features/provider-token-exchange/Cargo.toml | 7 ++++++- .../provider-token-exchange/tests/token_exchange.rs | 4 ++++ tests/support/otlp/Cargo.toml | 2 +- tests/support/spiffe/Cargo.toml | 2 +- 11 files changed, 51 insertions(+), 6 deletions(-) diff --git a/tests/suites/features/otlp-relay/Cargo.toml b/tests/suites/features/otlp-relay/Cargo.toml index f66c8aa2e3..0acf07c087 100644 --- a/tests/suites/features/otlp-relay/Cargo.toml +++ b/tests/suites/features/otlp-relay/Cargo.toml @@ -8,9 +8,14 @@ version = "0.0.0" edition = "2024" rust-version = "1.94" license = "Apache-2.0" -repository = "https://github.com/NVIDIA/OpenShell" +repository = "https://github.com/ai-openshell/openshell" publish = false +[[test]] +name = "otlp-relay" +path = "tests/otlp_relay.rs" +harness = false + [dependencies] base64 = "0.22" openshell-testkit = { path = "../../../testkit/testkit" } diff --git a/tests/suites/features/otlp-relay/tests/otlp_relay.rs b/tests/suites/features/otlp-relay/tests/otlp_relay.rs index 23eeb1e4d2..98de4c5a95 100644 --- a/tests/suites/features/otlp-relay/tests/otlp_relay.rs +++ b/tests/suites/features/otlp-relay/tests/otlp_relay.rs @@ -16,6 +16,10 @@ use otlp_support::{Attributes, Collector, SANDBOX_ID_KEY, SOURCE_KEY, SOURCE_VAL use testkit::sdk::SandboxPhase; use testkit::{Context, Error, Result, ResultExt as _}; +fn main() -> std::process::ExitCode { + testkit::main() +} + const ENV_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_ENDPOINT"; const ENV_PROTOCOL: &str = "OTEL_EXPORTER_OTLP_PROTOCOL"; const ENV_COLLECTOR: &str = "OPENSHELL_OTLP_ENDPOINT"; diff --git a/tests/suites/features/provider-refresh/Cargo.toml b/tests/suites/features/provider-refresh/Cargo.toml index c6b2b394be..bc736eeb0a 100644 --- a/tests/suites/features/provider-refresh/Cargo.toml +++ b/tests/suites/features/provider-refresh/Cargo.toml @@ -8,9 +8,14 @@ version = "0.0.0" edition = "2024" rust-version = "1.94" license = "Apache-2.0" -repository = "https://github.com/NVIDIA/OpenShell" +repository = "https://github.com/ai-openshell/openshell" publish = false +[[test]] +name = "provider-refresh" +path = "tests/refresh_handles.rs" +harness = false + [dependencies] host-server-support = { path = "../../../support/host-server" } openshell-testkit = { path = "../../../testkit/testkit" } diff --git a/tests/suites/features/provider-refresh/tests/refresh_handles.rs b/tests/suites/features/provider-refresh/tests/refresh_handles.rs index 1c5ecea062..4f09506bca 100644 --- a/tests/suites/features/provider-refresh/tests/refresh_handles.rs +++ b/tests/suites/features/provider-refresh/tests/refresh_handles.rs @@ -15,6 +15,10 @@ use host_server_support::{HttpRecorder, Request, Response, TEST_HOST}; use serde_json::json; use testkit::{Context, PYTHON_BINARIES, Poll, Result, Sandbox, policy, poll_until}; +fn main() -> std::process::ExitCode { + testkit::main() +} + const TOKEN_ENV: &str = "REFRESH_E2E_ACCESS_TOKEN"; const BOOTSTRAP_TOKEN: &str = "bootstrap-token"; const ROTATIONS: usize = 12; diff --git a/tests/suites/features/provider-rotation/Cargo.toml b/tests/suites/features/provider-rotation/Cargo.toml index f43f75b90f..06b93de4f2 100644 --- a/tests/suites/features/provider-rotation/Cargo.toml +++ b/tests/suites/features/provider-rotation/Cargo.toml @@ -8,9 +8,19 @@ version = "0.0.0" edition = "2024" rust-version = "1.94" license = "Apache-2.0" -repository = "https://github.com/NVIDIA/OpenShell" +repository = "https://github.com/ai-openshell/openshell" publish = false +[[test]] +name = "provider-rotation-readiness" +path = "tests/readiness.rs" +harness = false + +[[test]] +name = "provider-rotation-stable-placeholders" +path = "tests/stable_placeholders.rs" +harness = false + [dependencies] host-server-support = { path = "../../../support/host-server" } openshell-testkit = { path = "../../../testkit/testkit" } diff --git a/tests/suites/features/provider-rotation/tests/readiness.rs b/tests/suites/features/provider-rotation/tests/readiness.rs index c302645e0a..f6c6955391 100644 --- a/tests/suites/features/provider-rotation/tests/readiness.rs +++ b/tests/suites/features/provider-rotation/tests/readiness.rs @@ -24,6 +24,10 @@ use provider_rotation::{ use serde_json::{Value, json}; use testkit::{CliChild, Context, Error, PYTHON_BINARIES, Result, Sandbox}; +fn main() -> std::process::ExitCode { + testkit::main() +} + const READY: &str = "rotation-client-ready"; const START_TIMEOUT: Duration = Duration::from_secs(60); diff --git a/tests/suites/features/provider-rotation/tests/stable_placeholders.rs b/tests/suites/features/provider-rotation/tests/stable_placeholders.rs index ad6e2f2919..93fda93290 100644 --- a/tests/suites/features/provider-rotation/tests/stable_placeholders.rs +++ b/tests/suites/features/provider-rotation/tests/stable_placeholders.rs @@ -24,6 +24,10 @@ use provider_rotation::{ use serde_json::{Value, json}; use testkit::{Context, Error, PYTHON_BINARIES, Result, Sandbox}; +fn main() -> std::process::ExitCode { + testkit::main() +} + /// The main process's client name in [`probe`]. const CLIENT_NAME: &str = "main"; /// How long the main process has to start before it answers the first probe. diff --git a/tests/suites/features/provider-token-exchange/Cargo.toml b/tests/suites/features/provider-token-exchange/Cargo.toml index 76efa9b842..ebcc310eb7 100644 --- a/tests/suites/features/provider-token-exchange/Cargo.toml +++ b/tests/suites/features/provider-token-exchange/Cargo.toml @@ -8,9 +8,14 @@ version = "0.0.0" edition = "2024" rust-version = "1.94" license = "Apache-2.0" -repository = "https://github.com/NVIDIA/OpenShell" +repository = "https://github.com/ai-openshell/openshell" publish = false +[[test]] +name = "provider-token-exchange" +path = "tests/token_exchange.rs" +harness = false + [dependencies] openshell-testkit = { path = "../../../testkit/testkit" } serde_json = "1" diff --git a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs index d84d4e20c0..3a8d197213 100644 --- a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs +++ b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs @@ -25,6 +25,10 @@ use testkit::{Context, Error, Poll, Result, ResultExt as _, Sandbox, poll_until} use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; use tokio::net::{TcpListener, TcpStream}; +fn main() -> std::process::ExitCode { + testkit::main() +} + const TEST_HOST: &str = "host.openshell.internal"; const USER_SUBJECT_TOKEN: &str = "stored-user-token"; const INTERMEDIATE_TOKEN: &str = "intermediate-token"; diff --git a/tests/support/otlp/Cargo.toml b/tests/support/otlp/Cargo.toml index 4d994f2032..5bc1eda8e3 100644 --- a/tests/support/otlp/Cargo.toml +++ b/tests/support/otlp/Cargo.toml @@ -8,7 +8,7 @@ version = "0.0.0" edition = "2024" rust-version = "1.94" license = "Apache-2.0" -repository = "https://github.com/NVIDIA/OpenShell" +repository = "https://github.com/ai-openshell/openshell" publish = false [dependencies] diff --git a/tests/support/spiffe/Cargo.toml b/tests/support/spiffe/Cargo.toml index 438461fead..ec29c6c55b 100644 --- a/tests/support/spiffe/Cargo.toml +++ b/tests/support/spiffe/Cargo.toml @@ -8,7 +8,7 @@ version = "0.0.0" edition = "2024" rust-version = "1.94" license = "Apache-2.0" -repository = "https://github.com/NVIDIA/OpenShell" +repository = "https://github.com/ai-openshell/openshell" publish = false [dependencies] From 3e471b9b976d74cec1fab7ba8e681314f503ea8b Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 22:03:55 -0800 Subject: [PATCH 19/22] test(features): use testkit's typed profiles and match the stronger refresh test Build the refresh-handle and readiness profiles with testkit::Profile and the probe policy with policy::allow, and create every provider with install_provider. The stable-placeholder and token-exchange profiles stay YAML because Profile has no stable_placeholder or token_grant setter. The legacy refresh-handle test now waits for the probe after each rotation, sends the token as Bearer and as Basic x-access-token, and after reconfiguring rotates again, waits for a new process to succeed and checks the old handle stays revoked. Do the same here. Signed-off-by: Matthew Grossman --- tests/suites/features/Cargo.lock | 2 + .../features/provider-refresh/Cargo.toml | 2 + .../provider-refresh/tests/refresh_handles.rs | 165 +++++++++++------- .../provider-rotation/tests/readiness.rs | 34 ++-- .../tests/stable_placeholders.rs | 6 +- .../tests/token_exchange.rs | 23 +-- 6 files changed, 130 insertions(+), 102 deletions(-) diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index e378203e76..414c863000 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -3082,8 +3082,10 @@ checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" name = "provider-refresh" version = "0.0.0" dependencies = [ + "base64 0.22.1", "host-server-support", "openshell-testkit", + "prost-types", "serde_json", ] diff --git a/tests/suites/features/provider-refresh/Cargo.toml b/tests/suites/features/provider-refresh/Cargo.toml index bc736eeb0a..62da81d0fa 100644 --- a/tests/suites/features/provider-refresh/Cargo.toml +++ b/tests/suites/features/provider-refresh/Cargo.toml @@ -17,6 +17,8 @@ path = "tests/refresh_handles.rs" harness = false [dependencies] +base64 = "0.22" host-server-support = { path = "../../../support/host-server" } openshell-testkit = { path = "../../../testkit/testkit" } +prost-types = "0.14" serde_json = "1" diff --git a/tests/suites/features/provider-refresh/tests/refresh_handles.rs b/tests/suites/features/provider-refresh/tests/refresh_handles.rs index 4f09506bca..6ab50ffd41 100644 --- a/tests/suites/features/provider-refresh/tests/refresh_handles.rs +++ b/tests/suites/features/provider-refresh/tests/refresh_handles.rs @@ -11,9 +11,13 @@ use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; +use base64::Engine as _; +use base64::engine::general_purpose::STANDARD as BASE64; use host_server_support::{HttpRecorder, Request, Response, TEST_HOST}; use serde_json::json; -use testkit::{Context, PYTHON_BINARIES, Poll, Result, Sandbox, policy, poll_until}; +use testkit::policy::{self, Access, Endpoint as _}; +use testkit::sdk::raw::proto; +use testkit::{Context, Credential, PYTHON_BINARIES, Poll, Profile, Result, Sandbox, poll_until}; fn main() -> std::process::ExitCode { testkit::main() @@ -49,11 +53,12 @@ done"#, ) } -/// A shell command that requests `resource_url` with the credential from the -/// environment as a bearer token, and fails unless the resource accepts it. +/// A shell command that requests `resource_url` twice with the credential +/// from the environment, as a bearer token and as the password of HTTP Basic +/// `x-access-token`, and fails unless the resource accepts both. fn probe(resource_url: &str) -> String { format!( - r#"python3 -c 'import os, urllib.request; urllib.request.urlopen(urllib.request.Request("{resource_url}", headers={{"Authorization": "Bearer " + os.environ["{TOKEN_ENV}"]}}), timeout=5).read()'"# + r#"python3 -c 'import os, base64, urllib.request; token = os.environ["{TOKEN_ENV}"]; auths = ["Bearer " + token, "Basic " + base64.b64encode(("x-access-token:" + token).encode()).decode()]; [urllib.request.urlopen(urllib.request.Request("{resource_url}", headers={{"Authorization": auth}}), timeout=5).read() for auth in auths]'"# ) } @@ -68,9 +73,8 @@ async fn long_running_process_survives_rotations_and_reconfigure_revokes( ) -> testkit::Result { let issuer = Issuer::start().await?; let provider = cx.name("refresh"); - let profile = profile(&provider, issuer.port()); - let provider_type = cx.import_profile(&profile).await?; - cx.create_provider(&provider, &provider_type, &[(TOKEN_ENV, BOOTSTRAP_TOKEN)]) + let profile = profile(&provider, issuer.port()).to_yaml()?; + cx.install_provider(&provider, &profile, &[(TOKEN_ENV, BOOTSTRAP_TOKEN)]) .await?; let refresh = cx.provider_refresh(&provider, TOKEN_ENV); let configure = async || { @@ -90,7 +94,7 @@ async fn long_running_process_survives_rotations_and_reconfigure_revokes( .sandbox("rfh") .image(testkit::python_image()) .providers([provider.as_str()]) - .policy(probe_policy(issuer.port())?) + .policy(probe_policy(issuer.port())) .command(["sh", "-c", &main_process(&resource_url)]) .create_ready() .await?; @@ -104,14 +108,14 @@ async fn long_running_process_survives_rotations_and_reconfigure_revokes( for _ in 0..ROTATIONS { refresh.rotate().await?.success()?; + wait_for_probe( + &sandbox, + "ok", + "the long-running process to use the latest rotated token", + ) + .await + .map_err(|error| error.context(format!("issuer saw {}", issuer.summary())))?; } - wait_for_probe( - &sandbox, - "ok", - "the long-running process to use the latest rotated token", - ) - .await - .map_err(|error| error.context(format!("issuer saw {}", issuer.summary())))?; configure().await?; wait_for_probe( @@ -121,10 +125,31 @@ async fn long_running_process_survives_rotations_and_reconfigure_revokes( ) .await?; - sandbox - .exec(["sh", "-c", &probe(&resource_url)]) - .await? - .success()?; + refresh.rotate().await?.success()?; + poll_until( + "a new process to reach the resource after reconfiguring", + PROBE_TIMEOUT, + Duration::from_millis(500), + async || { + let fresh = sandbox.exec(["sh", "-c", &probe(&resource_url)]).await?; + Ok(if fresh.exit_code == 0 { + Poll::Ready(()) + } else { + Poll::Pending(format!( + "the probe exited {}: {}", + fresh.exit_code, + fresh.stderr.trim() + )) + }) + }, + ) + .await + .map_err(|error| error.context(format!("issuer saw {}", issuer.summary())))?; + let old = trigger_probe(&sandbox).await?; + testkit::ensure!( + old == "failed", + "the long-running process's revoked handle worked again after a new token was issued: {old:?}" + ); Ok(()) } @@ -164,7 +189,8 @@ async fn wait_for_probe(sandbox: &Sandbox, expected: &str, what: &str) -> Result /// An OAuth issuer and the resource it guards. Each `POST /token` issues a /// new token and invalidates the last. `GET /probe` answers `204` to the -/// current token and `401` to anything else. +/// current token, as a bearer token or as the password of HTTP Basic +/// `x-access-token`, and `401` to anything else. struct Issuer { server: HttpRecorder, } @@ -185,8 +211,14 @@ impl Issuer { })) } ("GET", "/probe") - if request.header("authorization").as_deref() - == Some(&format!("Bearer {}", state.1)) => + if request.header("authorization").is_some_and(|auth| { + auth == format!("Bearer {}", state.1) + || auth + == format!( + "Basic {}", + BASE64.encode(format!("x-access-token:{}", state.1)) + ) + }) => { Response::new(204) } @@ -215,49 +247,52 @@ impl Issuer { /// A profile whose credential refreshes with OAuth client credentials from /// the issuer on `port`, and is bound to the resource on the same port. -fn profile(id: &str, port: u16) -> String { - let binaries = PYTHON_BINARIES - .iter() - .map(|binary| format!("\"{binary}\"")) - .collect::>() - .join(", "); - format!( - "id: {id} -display_name: Provider refresh handle test -category: other -credentials: - - name: access_token - env_vars: [{TOKEN_ENV}] - required: true - auth_style: bearer - header_name: authorization - refresh: - strategy: oauth2_client_credentials - token_url: http://127.0.0.1:{port}/token - refresh_before_seconds: 30 - max_lifetime_seconds: 300 - material: - - name: client_id - required: true - - name: client_secret - required: true - secret: true -endpoints: - - {{host: {TEST_HOST}, port: {port}, path: /probe, protocol: rest, access: full, enforcement: enforce}} -binaries: [{binaries}] -" - ) +fn profile(id: &str, port: u16) -> Profile { + let material = |name: &str, secret: bool| proto::ProviderCredentialRefreshMaterial { + name: name.to_string(), + required: true, + secret, + ..proto::ProviderCredentialRefreshMaterial::default() + }; + let seconds = |seconds| Some(prost_types::Duration { seconds, nanos: 0 }); + Profile::new(id) + .display_name("Provider refresh handle test") + .credential( + Credential::new("access_token") + .env_var(TOKEN_ENV) + .required() + .auth_style("bearer") + .header_name("authorization") + .refresh(proto::ProviderCredentialRefresh { + strategy: proto::ProviderCredentialRefreshStrategy::Oauth2ClientCredentials + as i32, + token_url: format!("http://127.0.0.1:{port}/token"), + refresh_before: seconds(30), + max_lifetime: seconds(300), + material: vec![ + material("client_id", false), + material("client_secret", true), + ], + ..proto::ProviderCredentialRefresh::default() + }), + ) + .endpoint(TEST_HOST, port, |ep| { + ep.rest(Access::Full).enforce().path("/probe"); + }) + .binaries(PYTHON_BINARIES.iter().copied()) } -fn probe_policy(port: u16) -> Result { - policy::base_with(&format!( - "network_policies: - refresh_probe: - name: refresh_probe - endpoints: - - {{host: {TEST_HOST}, port: {port}, path: /probe, protocol: rest, access: full, enforcement: enforce}} - binaries: {binaries} -", - binaries = policy::binaries_yaml(PYTHON_BINARIES), - )) +fn probe_policy(port: u16) -> proto::SandboxPolicy { + let mut policy = policy::base(); + policy::allow( + &mut policy, + "refresh_probe", + TEST_HOST, + port, + PYTHON_BINARIES, + ) + .rest(Access::Full) + .enforce() + .path("/probe"); + policy } diff --git a/tests/suites/features/provider-rotation/tests/readiness.rs b/tests/suites/features/provider-rotation/tests/readiness.rs index f6c6955391..5ea223ceb2 100644 --- a/tests/suites/features/provider-rotation/tests/readiness.rs +++ b/tests/suites/features/provider-rotation/tests/readiness.rs @@ -22,7 +22,8 @@ use provider_rotation::{ probe, probe_disallowed_binary, }; use serde_json::{Value, json}; -use testkit::{CliChild, Context, Error, PYTHON_BINARIES, Result, Sandbox}; +use testkit::policy::{Access, Endpoint as _}; +use testkit::{CliChild, Context, Error, PYTHON_BINARIES, Profile, Result, Sandbox}; fn main() -> std::process::ExitCode { testkit::main() @@ -106,10 +107,8 @@ async fn acknowledged_changes_reach_fresh_clients_and_detach_revokes_retained_re let keys = keys(); let backends = Backends::start(Credential::Bearer, &keys).await?; let provider = cx.name("ready"); - let provider_type = cx - .import_profile(&profile(&provider, backends.port())) - .await?; - cx.create_provider(&provider, &provider_type, &[(TOKEN_ENV, &keys[0])]) + let profile = profile(&provider, backends.port())?; + cx.install_provider(&provider, &profile, &[(TOKEN_ENV, &keys[0])]) .await?; let sandbox = cx .sandbox("ready") @@ -282,16 +281,21 @@ async fn acknowledged_changes_reach_fresh_clients_and_detach_revokes_retained_re } /// A profile with one bearer credential bound to the server on `port`. -fn profile(id: &str, port: u16) -> String { - json!({ - "id": id, "display_name": "Provider readiness test", "category": "other", - "credentials": [{"name": "synthetic", "env_vars": [TOKEN_ENV], "required": true, - "auth_style": "bearer", "header_name": "authorization"}], - "endpoints": [{"host": TEST_HOST, "port": port, "path": "/v1/**", "protocol": "rest", - "access": "full", "enforcement": "enforce"}], - "binaries": PYTHON_BINARIES, - }) - .to_string() +fn profile(id: &str, port: u16) -> Result { + Profile::new(id) + .display_name("Provider readiness test") + .credential( + testkit::Credential::new("synthetic") + .env_var(TOKEN_ENV) + .required() + .auth_style("bearer") + .header_name("authorization"), + ) + .endpoint(TEST_HOST, port, |ep| { + ep.rest(Access::Full).enforce().path("/v1/**"); + }) + .binaries(PYTHON_BINARIES.iter().copied()) + .to_yaml() } fn pid(response: &Value) -> Result { diff --git a/tests/suites/features/provider-rotation/tests/stable_placeholders.rs b/tests/suites/features/provider-rotation/tests/stable_placeholders.rs index 93fda93290..2b6cf2388d 100644 --- a/tests/suites/features/provider-rotation/tests/stable_placeholders.rs +++ b/tests/suites/features/provider-rotation/tests/stable_placeholders.rs @@ -138,10 +138,8 @@ async fn assertion_rotation(cx: &Context, stable: bool) -> Result { let backends = Backends::start(Credential::Assertion, &keys).await?; let suffix = if stable { "stbl" } else { "ordn" }; let provider = cx.name(suffix); - let provider_type = cx - .import_profile(&profile(&provider, backends.port(), stable)) - .await?; - cx.create_provider(&provider, &provider_type, &[(TOKEN_ENV, &keys[0])]) + let profile = profile(&provider, backends.port(), stable); + cx.install_provider(&provider, &profile, &[(TOKEN_ENV, &keys[0])]) .await?; let config = json!({"key": TOKEN_ENV, "header": ASSERTION_HEADER, "payload": tool_call(), "host": TEST_HOST, "other_host": backends.other_host(), "port": backends.port(), diff --git a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs index 3a8d197213..b2e6e50a47 100644 --- a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs +++ b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs @@ -70,17 +70,9 @@ async fn independent_grants_across_sandboxes(cx: &mut Context) -> testkit::Resul let mut sandboxes = Vec::new(); for instance in ["a", "b"] { let provider = cx.name(&format!("grants-{instance}")); - let profile_type = cx - .import_profile(&grants_profile( - &provider, - token_port, - identity_port, - target_port, - instance, - )) - .await?; + let profile = grants_profile(&provider, token_port, identity_port, target_port, instance); let subject = format!("{USER_SUBJECT_TOKEN}-{instance}"); - cx.create_provider(&provider, &profile_type, &[(SUBJECT_TOKEN_ENV, &subject)]) + cx.install_provider(&provider, &profile, &[(SUBJECT_TOKEN_ENV, &subject)]) .await?; sandboxes.push( cx.sandbox(&format!("pte{instance}")) @@ -175,15 +167,10 @@ async fn routes_recover_and_select_a_b_a_on_one_connection(cx: &mut Context) -> let mut providers = Vec::new(); for route in ["a", "b"] { let provider = cx.name(&format!("route-{route}")); - let profile_type = cx - .import_profile(&route_profile(&provider, token_port, target_port, route)) + let profile = route_profile(&provider, token_port, target_port, route); + let stored = format!("stored-{route}"); + cx.install_provider(&provider, &profile, &[(SUBJECT_TOKEN_ENV, &stored)]) .await?; - cx.create_provider( - &provider, - &profile_type, - &[(SUBJECT_TOKEN_ENV, &format!("stored-{route}"))], - ) - .await?; providers.push(provider); } let sandbox = cx From 56cda261dc1b598f7e807be0a557c675c80cfda8 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 22:04:18 -0800 Subject: [PATCH 20/22] ci(e2e): run provider-refresh on fedora-podman-rootless Signed-off-by: Matthew Grossman --- .github/workflows/e2e-suites.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index 626cc115b2..006be066f7 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -122,6 +122,7 @@ jobs: {"environment":"fedora-podman-rootless-spiffe","installer":"rpm","family":"features","package":"provider-token-exchange","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"fedora-podman-rootless","installer":"rpm","family":"features","package":"provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful-additional-ca","installer":"deb","family":"features","package":"provider-rotation","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-additional-ca","installer":"rpm","family":"features","package":"provider-rotation","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"}, From d05c29d11328bbc1a95c62320544d0ee279fb2a3 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Tue, 24 Nov 2026 13:36:58 -0800 Subject: [PATCH 21/22] test(features): compare cached token-exchange grants with the first round The cache check compared the issued counts with themselves, so it could not fail. Save the counts after the first round and compare the cached round with them. Signed-off-by: Matthew Grossman --- .../provider-token-exchange/tests/token_exchange.rs | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs index b2e6e50a47..684e402956 100644 --- a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs +++ b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs @@ -86,6 +86,7 @@ async fn independent_grants_across_sandboxes(cx: &mut Context) -> testkit::Resul unreachable!("two sandboxes") }; + let mut after_first = None; for round in ["first", "cached"] { let (from_a, from_b) = tokio::join!( probe(a, target_port, "/resource/a", false), @@ -101,17 +102,17 @@ async fn independent_grants_across_sandboxes(cx: &mut Context) -> testkit::Resul .all(|(service, identity)| *service > 0 && *identity > 0), "each provider did not acquire both credentials: {issued:?}" ); + after_first = Some(issued); } } - let issued = observations.issued(); testkit::ensure!( observations.target_rejected.load(Ordering::SeqCst) == 0, "the target rejected a request with mismatched or untrusted credentials, even if a retry then passed" ); - // The first round's check passed, so any difference is the second round. + let issued = observations.issued(); testkit::ensure!( - observations.issued() == issued, - "repeat requests acquired credentials again instead of using the caches" + Some(issued) == after_first, + "repeat requests acquired credentials again instead of using the caches: {after_first:?} after the first round, {issued:?} after the cached round" ); let target_requests = observations.target_requests.load(Ordering::SeqCst); From 0446dcee99ffe452f60f20be082ca99a03693fcf Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Tue, 24 Nov 2026 13:36:58 -0800 Subject: [PATCH 22/22] test(tmachine): set the SPIFFE gateway socket for the binaries installer too The binaries installer runs the gateway as a system unit, which ignores user-unit drop-ins. Write the drop-in for both units. Signed-off-by: Matthew Grossman --- tests/tmachine/ansible/playbooks/spiffe.yaml | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/tests/tmachine/ansible/playbooks/spiffe.yaml b/tests/tmachine/ansible/playbooks/spiffe.yaml index 149de03ef9..606f9d2f63 100644 --- a/tests/tmachine/ansible/playbooks/spiffe.yaml +++ b/tests/tmachine/ansible/playbooks/spiffe.yaml @@ -6,8 +6,9 @@ # # The gateway reads its Workload API socket only from # OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET. The packaged gateway is a -# systemd user service whose installer rewrites gateway.env, so a user-unit -# drop-in sets the variable. Supervisors use the driver's +# systemd user service whose installer rewrites gateway.env, and the binaries +# installer runs a system service, so a drop-in for each unit sets the +# variable. Supervisors use the driver's # provider_spiffe_workload_api_socket. Podman supervisors share the test VM's # network, so they reach the test's listener over loopback. Nothing listens # until a test starts its Workload API. The SPIFFE fixture @@ -39,25 +40,27 @@ group: tmachine mode: "0755" - - name: Create the gateway user-unit drop-in directory + - name: Create the gateway unit drop-in directories become: true ansible.builtin.file: - path: /etc/systemd/user/openshell-gateway.service.d + path: "{{ item }}/openshell-gateway.service.d" state: directory owner: root group: root mode: "0755" + loop: [/etc/systemd/user, /etc/systemd/system] - name: Point the gateway at the test's Workload API become: true ansible.builtin.copy: - dest: /etc/systemd/user/openshell-gateway.service.d/spiffe.conf + dest: "{{ item }}/openshell-gateway.service.d/spiffe.conf" owner: root group: root mode: "0644" content: | [Service] Environment=OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET={{ spiffe_gateway_socket }} + loop: [/etc/systemd/user, /etc/systemd/system] - name: Point supervisors at the test's Workload API ansible.builtin.include_role: