From 088bae693f8d3ed56446f1f8be73a6cff5a93c3d Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:40:16 -0800 Subject: [PATCH 01/10] 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 3e4e4b715ed78ef03baf9fd138e9abdead17bde5 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:40:17 -0800 Subject: [PATCH 02/10] 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 ba809fb147ec00566dd736bc92217ffdb5eb7b98 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:09:08 -0800 Subject: [PATCH 03/10] 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 7b7b0a775a..bbbf58fd25 100644 --- a/tests/support/README.md +++ b/tests/support/README.md @@ -25,8 +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_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 ed62c23eb6..0d9cbc2af3 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 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 403ef9cf8401df2702833e4825f0d0f91e795c0c Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:09:14 -0800 Subject: [PATCH 04/10] ci(e2e): run the provider refresh suite 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 c84837c976..185755c6c9 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -116,6 +116,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":"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 5b187ffc133e39f7e354bb800202a8778812e8b0 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:22:50 -0800 Subject: [PATCH 05/10] 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 1200c171f5..26001d589f 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -2878,6 +2878,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 = "pulldown-cmark" version = "0.13.6" diff --git a/tests/suites/features/Cargo.toml b/tests/suites/features/Cargo.toml index 07f5f08a45..84c5ffd3c4 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", "provider-refresh", "provider-rotation", "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 0de57be365dee4ea2bd7a1290dc4559ed3f43ee7 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:26:38 -0800 Subject: [PATCH 06/10] 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 185755c6c9..e863396cf8 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -118,6 +118,8 @@ jobs: {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"connect-ssh-supervision","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"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 e7e5a8667862f3711bf2ba972ced4692745649bc Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:32:34 -0800 Subject: [PATCH 07/10] test(e2e): remove gateway configuration tests ported to testkit suites Signed-off-by: Matthew Grossman --- CI.md | 5 +- e2e/rust/Cargo.toml | 10 - e2e/rust/tests/provider_readiness.rs | 1591 ----------------- e2e/rust/tests/provider_refresh_handles.rs | 16 - .../tests/stable_external_placeholders.rs | 1354 -------------- 5 files changed, 1 insertion(+), 2975 deletions(-) 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/stable_external_placeholders.rs diff --git a/CI.md b/CI.md index 8255385c34..78ac0e2c2d 100644 --- a/CI.md +++ b/CI.md @@ -265,10 +265,7 @@ issuer and authenticated HTTPS API/Git fixture. It checks both clients across replacement handle. No live GitHub app or installation is required. It needs the wrapper-managed gateway so it can temporarily trust the fixture CA; the original gateway configuration is restored afterward. The OAuth counterpart -remains separately selectable as `provider_refresh_handles`. It uses an HTTP -fixture and the standard workload image, and supports both wrapper-managed -gateways and existing gateways selected with `OPENSHELL_GATEWAY_ENDPOINT`. -It does not install CA trust or restart the gateway. +is the `features/provider-refresh` testkit suite. ## Informational security reports diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 6b0f5d5d1e..4ef1f3540b 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" 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/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("; ")) - } -} From 195fa5caddd042a2640ceff4bbff3dcad3c7b4c6 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 11:45:11 -0800 Subject: [PATCH 08/10] 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/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 ++++ 5 files changed, 29 insertions(+), 2 deletions(-) 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. From 86d183e37afec105fcbfe6cef7f910607e8c2c49 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 22:03:55 -0800 Subject: [PATCH 09/10] 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 +- 5 files changed, 125 insertions(+), 84 deletions(-) diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index 26001d589f..37d673afeb 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -2873,8 +2873,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(), From ad1c906a9fad1834ecc6898c56a82159f62ec834 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 22:04:18 -0800 Subject: [PATCH 10/10] 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 e863396cf8..bbc9b2315a 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -118,6 +118,7 @@ jobs: {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"connect-ssh-supervision","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"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"},