From 527bd7080673a29acf1a80029115f28e67957d18 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 3 Dec 2026 17:19:23 -0800 Subject: [PATCH 01/10] test(e2e): port additional CA trust and delivery checks to testkit suites Move the trust checks to tests/suites/features/additional-ca and the Docker and Podman supervisor delivery checks to the driver suites. tmachine environments configure the gateway with a CA through gateway overrides and publish its certificate and key. The VM lane runs the new feature suite in its additional-CA mode. e2e/rust/tests/additional_ca.rs keeps only the Kubernetes and VM paths. Signed-off-by: Matthew Grossman --- .github/workflows/branch-e2e.yml | 17 -- .github/workflows/e2e-docker-test.yml | 2 +- .github/workflows/e2e-suites.yml | 5 +- e2e/rust/e2e-docker.sh | 5 - e2e/rust/e2e-podman.sh | 5 - e2e/rust/e2e-vm.sh | 13 + e2e/rust/tests/additional_ca.rs | 225 +----------------- e2e/support/gateway-common.sh | 2 +- e2e/with-docker-gateway.sh | 33 --- e2e/with-podman-gateway.sh | 46 ---- tests/suites/drivers/docker/Cargo.lock | 1 + tests/suites/drivers/docker/Cargo.toml | 6 + .../drivers/docker/tests/additional_ca.rs | 94 ++++++++ tests/suites/drivers/podman/Cargo.toml | 5 + .../drivers/podman/tests/additional_ca.rs | 107 +++++++++ tests/suites/features/Cargo.lock | 9 + .../suites/features/additional-ca/Cargo.toml | 21 ++ .../additional-ca/tests/additional_ca.rs | 133 +++++++++++ tests/support/host-server/src/tls.rs | 3 + .../ansible/playbooks/additional-ca.yaml | 67 ++++++ tests/tmachine/config.nix | 9 +- tests/tmachine/features/additional-ca.nix | 9 + 22 files changed, 491 insertions(+), 326 deletions(-) create mode 100644 tests/suites/drivers/docker/tests/additional_ca.rs create mode 100644 tests/suites/drivers/podman/tests/additional_ca.rs create mode 100644 tests/suites/features/additional-ca/Cargo.toml create mode 100644 tests/suites/features/additional-ca/tests/additional_ca.rs create mode 100644 tests/tmachine/ansible/playbooks/additional-ca.yaml create mode 100644 tests/tmachine/features/additional-ca.nix diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index 87d9a38db7..f81c903557 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -572,22 +572,6 @@ jobs: suite-matrix: >- [{"suite":"ci","runner":"ubuntu-26.04","podman_major":"5","podman_package_version":"5.7.0+ds2-3build1","conmon_package_version":"2.1.13+ds1-2","cmd":"mise run --no-deps --skip-deps e2e:podman:ci"}] - podman-additional-ca-e2e: - needs: [pr_metadata, build-binaries-linux, build-conformance, build-images] - if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_core_e2e == 'true' - permissions: - actions: read - contents: read - packages: read - uses: ./.github/workflows/e2e-podman-test.yml - with: - checkout-ref: ${{ needs.pr_metadata.outputs.sha }} - prebuilt-conformance: true - image-tag: ${{ needs.pr_metadata.outputs.sha }} - external-driver-binary: openshell-driver-podman - suite-matrix: >- - [{"suite":"additional-ca","runner":"ubuntu-26.04","podman_major":"5","podman_package_version":"5.7.0+ds2-3build1","conmon_package_version":"2.1.13+ds1-2","cmd":"OPENSHELL_E2E_PODMAN_TEST=additional_ca mise run --no-deps --skip-deps e2e:podman"}] - vm-e2e: needs: [pr_metadata, build-binaries-linux, build-conformance, build-vm-driver-linux] if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_core_e2e == 'true' @@ -826,7 +810,6 @@ jobs: - podman-e2e-integration - docker-e2e - podman-e2e - - podman-additional-ca-e2e - vm-e2e - vm-additional-ca-e2e - podman-external-driver-e2e diff --git a/.github/workflows/e2e-docker-test.yml b/.github/workflows/e2e-docker-test.yml index d7ba6761d3..b3e2291e25 100644 --- a/.github/workflows/e2e-docker-test.yml +++ b/.github/workflows/e2e-docker-test.yml @@ -33,7 +33,7 @@ on: required: false type: string default: >- - [{"suite":"oidc-pkce-docker","cmd":"mise run --no-deps --skip-deps e2e:oidc-pkce:docker","apt_packages":"openssh-client","mcp":false},{"suite":"rust-docker","cmd":"mise run --no-deps --skip-deps e2e:rust","apt_packages":"openssh-client","mcp":false},{"suite":"oci-image","cmd":"mise run --no-deps --skip-deps e2e:oci-image","apt_packages":"openssh-client","mcp":false},{"suite":"additional-ca","cmd":"OPENSHELL_E2E_DOCKER_TEST=additional_ca mise run --no-deps --skip-deps e2e:docker","apt_packages":"openssh-client","mcp":false},{"suite":"mcp","cmd":"mise run --no-deps --skip-deps e2e:mcp","apt_packages":"","mcp":true}] + [{"suite":"oidc-pkce-docker","cmd":"mise run --no-deps --skip-deps e2e:oidc-pkce:docker","apt_packages":"openssh-client","mcp":false},{"suite":"rust-docker","cmd":"mise run --no-deps --skip-deps e2e:rust","apt_packages":"openssh-client","mcp":false},{"suite":"oci-image","cmd":"mise run --no-deps --skip-deps e2e:oci-image","apt_packages":"openssh-client","mcp":false},{"suite":"mcp","cmd":"mise run --no-deps --skip-deps e2e:mcp","apt_packages":"","mcp":true}] permissions: actions: read diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index 3de3608656..05f0e640bd 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -110,6 +110,9 @@ jobs: {"environment":"ubuntu-docker-rootful-corporate-proxy","installer":"deb","family":"features","package":"corporate-proxy","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-corporate-proxy","installer":"rpm","family":"features","package":"corporate-proxy","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootless-corporate-proxy","installer":"rpm","family":"features","package":"corporate-proxy","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"ubuntu-docker-rootful-additional-ca","installer":"deb","family":"features","package":"additional-ca","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"fedora-podman-rootful-additional-ca","installer":"rpm","family":"features","package":"additional-ca","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"fedora-podman-rootless-additional-ca","installer":"rpm","family":"features","package":"additional-ca","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful-keycloak","installer":"deb","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"gateway-mtls","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful-oidc","installer":"deb","family":"features","package":"oidc-auth","gateway":"openshell","runner":"ubuntu-24.04"}, @@ -145,7 +148,7 @@ jobs: {"environment":"fedora-podman-rootless","installer":"rpm","family":"features","package":"service-exposure","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":"ubuntu-docker-rootful","installer":"deb","family":"drivers/docker","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"ubuntu-docker-rootful-additional-ca","installer":"deb","family":"drivers/docker","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-userns-default","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-userns-auto","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-userns-keep-id","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, diff --git a/e2e/rust/e2e-docker.sh b/e2e/rust/e2e-docker.sh index 68d48e7370..79f4a534fd 100755 --- a/e2e/rust/e2e-docker.sh +++ b/e2e/rust/e2e-docker.sh @@ -18,11 +18,6 @@ RUN_WITH_GATEWAY_COMMAND="__openshell_run_docker_e2e" # shellcheck source=e2e/support/conformance.sh source "${ROOT}/e2e/support/conformance.sh" -if [ "${E2E_TEST}" = "additional_ca" ]; then - export OPENSHELL_E2E_ADDITIONAL_CA=1 - E2E_FEATURES="${E2E_FEATURES},e2e-additional-ca" -fi - run_e2e() { e2e_run_openshell_conformance "Docker" diff --git a/e2e/rust/e2e-podman.sh b/e2e/rust/e2e-podman.sh index d47c0f365b..bff337644b 100755 --- a/e2e/rust/e2e-podman.sh +++ b/e2e/rust/e2e-podman.sh @@ -50,11 +50,6 @@ if [ -n "${E2E_TEST}" ]; then SELECTED_TESTS=("${E2E_TEST}") fi -if [ "${E2E_TEST}" = "additional_ca" ]; then - export OPENSHELL_E2E_ADDITIONAL_CA=1 - E2E_FEATURES="${E2E_FEATURES},e2e-additional-ca" -fi - if [ "${E2E_TEST}" = "gpu" ] && [ -z "${OPENSHELL_E2E_WORKLOAD_MANIFEST:-}" ] && [ ! -f "${DEFAULT_WORKLOAD_MANIFEST}" ]; then echo "note: running Podman GPU e2e without a workload manifest; workload validation will log an explicit skip. Build one with 'CONTAINER_ENGINE=podman mise run e2e:workloads:build' or set OPENSHELL_E2E_WORKLOAD_MANIFEST." fi diff --git a/e2e/rust/e2e-vm.sh b/e2e/rust/e2e-vm.sh index eaef034e0f..36a4b274e4 100755 --- a/e2e/rust/e2e-vm.sh +++ b/e2e/rust/e2e-vm.sh @@ -465,6 +465,19 @@ export OPENSHELL_PROVISION_TIMEOUT="${SANDBOX_PROVISION_TIMEOUT}" OPENSHELL_TEST_PYTHON_IMAGE="${OPENSHELL_TEST_PYTHON_IMAGE:-${E2E_PULLABLE_PYTHON_IMAGE}}" \ e2e_run_openshell_conformance "VM" +if [ "${ADDITIONAL_CA_MODE}" = "1" ]; then + # The additional-ca feature suite signs its server's certificate with the + # fixture's CA, which the gateway trusts. + echo "==> Running the additional-ca feature suite" + OPENSHELL_TEST_PYTHON_IMAGE="${OPENSHELL_TEST_PYTHON_IMAGE:-${E2E_PULLABLE_PYTHON_IMAGE}}" \ + OPENSHELL_TEST_ADDITIONAL_CA_CERT="${ADDITIONAL_CA_DIR}/ca.crt" \ + OPENSHELL_TEST_ADDITIONAL_CA_KEY="${ADDITIONAL_CA_DIR}/ca.key" \ + cargo-nextest nextest run --locked \ + --manifest-path "${ROOT}/tests/suites/features/Cargo.toml" \ + --package additional-ca \ + --config-file "${ROOT}/tests/runner/src/program-nextest.toml" \ + --profile openshell --no-tests fail +fi if [ "${E2E_FEATURES}" = "e2e-conformance-only" ]; then echo "::notice::Skipping Rust e2e tests (e2e-conformance-only)" exit 0 diff --git a/e2e/rust/tests/additional_ca.rs b/e2e/rust/tests/additional_ca.rs index 99599b37d0..e33d01f30f 100644 --- a/e2e/rust/tests/additional_ca.rs +++ b/e2e/rust/tests/additional_ca.rs @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Driver-backed e2e coverage for the global network-supervisor additional CA. +//! Kubernetes and VM e2e coverage for the global network-supervisor +//! additional CA. The trust checks and the Docker and Podman delivery checks +//! moved to `tests/suites/features/additional-ca` and `tests/suites/drivers`. use std::io::Write; use std::net::TcpListener; @@ -15,12 +17,7 @@ use serde_json::Value; use sha2::Digest as _; use tempfile::NamedTempFile; -#[cfg(any(feature = "e2e-docker", feature = "e2e-podman"))] -use openshell_e2e::harness::container::ContainerEngine; - const ADDITIONAL_CA_MOUNT_PATH: &str = "/etc/openshell/tls/additional/ca-bundle.pem"; -#[cfg(any(feature = "e2e-docker", feature = "e2e-podman"))] -const GATEWAY_CA_PATH: &str = "/etc/openshell/tls/client/ca.crt"; const READY_MARKER: &str = "additional-ca-e2e-ready"; const LIFECYCLE_READY_MARKER: &str = "additional-ca-lifecycle-ready"; const LIFECYCLE_DURABLE_MARKER: &str = "additional-ca-lifecycle-durable"; @@ -40,8 +37,6 @@ impl Drop for PortForwardGuard { fn driver() -> Result<&'static str, String> { match std::env::var("OPENSHELL_E2E_DRIVER").as_deref() { - Ok("docker") => Ok("docker"), - Ok("podman") => Ok("podman"), Ok("kubernetes") => Ok("kubernetes"), Ok("vm") => Ok("vm"), Ok(other) => Err(format!("unsupported additional CA e2e driver: {other}")), @@ -124,149 +119,6 @@ fn run_json(mut command: Command, description: &str) -> Result { .map_err(|error| format!("parse {description} JSON: {error}; output={stdout}")) } -#[cfg(any(feature = "e2e-docker", feature = "e2e-podman"))] -fn engine_command(container_engine: &ContainerEngine) -> Command { - let mut command = container_engine.command(); - if container_engine.name() == "podman" - && let Ok(socket) = std::env::var("OPENSHELL_PODMAN_SOCKET") - { - command.arg("--url").arg(format!("unix://{socket}")); - } - command -} - -#[cfg(any(feature = "e2e-docker", feature = "e2e-podman"))] -fn inspect_local_container(driver: &str, sandbox_name: &str) -> Result<(), String> { - let container_engine = ContainerEngine::from_env().map_err(|error| error.clone())?; - // The supervisor container owns the additional CA mount and command. It is - // host-networked (or attached to a runtime bridge), so it cannot be - // located through e2e network membership; select it by managed labels. - // The sandbox namespace label is not used because the Podman driver - // labels containers with the gateway-elided request namespace. - let output = engine_command(&container_engine) - .args([ - "ps", - "-aq", - "--filter", - "label=openshell.ai/isolation-role=supervisor", - "--filter", - ]) - .arg(format!("label=openshell.ai/sandbox-name={sandbox_name}")) - .output() - .map_err(|error| format!("run {driver} ps: {error}"))?; - if !output.status.success() { - return Err(format!( - "{driver} ps failed: {}", - String::from_utf8_lossy(&output.stderr) - )); - } - let ids = String::from_utf8_lossy(&output.stdout) - .lines() - .map(str::trim) - .filter(|line| !line.is_empty()) - .map(ToString::to_string) - .collect::>(); - let [container_id] = ids.as_slice() else { - return Err(format!( - "expected one {driver} supervisor container for {sandbox_name}, found {ids:?}" - )); - }; - - let mut mounts_command = engine_command(&container_engine); - mounts_command.args(["inspect", "--format", "{{json .Mounts}}", container_id]); - let mounts = run_json(mounts_command, &format!("{driver} mount inspection"))?; - let mounts = mounts.as_array().ok_or("mounts must be an array")?; - let destination_mounts = mounts - .iter() - .filter(|mount| mount["Destination"] == ADDITIONAL_CA_MOUNT_PATH) - .collect::>(); - if destination_mounts.len() != 1 || destination_mounts[0]["RW"] != false { - return Err(format!("unexpected destination CA mounts: {mounts:#?}")); - } - // Podman bind-mounts the gateway mTLS CA only when user namespaces are - // not remapping UIDs; otherwise it is delivered as a container secret - // (`openshell-tls-ca-*`), which does not appear in `.Mounts`. Docker never - // bind-mounts it: the gateway CA is staged inside the read-only supervisor - // state volume as `tls/ca.pem` and the supervisor is pointed at it through - // the `OPENSHELL_TLS_CA` environment variable. - let gateway_ca_mount = mounts - .iter() - .find(|mount| mount["Destination"] == GATEWAY_CA_PATH); - let gateway_ca_secret = gateway_ca_mount.is_none() - && driver == "podman" - && podman_gateway_ca_secret(&container_engine, driver, container_id)?; - let gateway_ca_staged = gateway_ca_mount.is_none() - && driver == "docker" - && docker_gateway_ca_staged(&container_engine, container_id, mounts)?; - if gateway_ca_mount.is_none() && !gateway_ca_secret && !gateway_ca_staged { - return Err("gateway mTLS CA delivery must remain present".to_string()); - } - let gateway_ca_source = gateway_ca_mount.map(|mount| mount["Source"].clone()); - if let Some(gateway_ca_source) = gateway_ca_source - && destination_mounts[0]["Source"] == gateway_ca_source - { - return Err("destination and gateway CA mounts must be distinct".to_string()); - } - - let mut command_inspect = engine_command(&container_engine); - command_inspect.args(["inspect", "--format", "{{json .Config.Cmd}}", container_id]); - let command = run_json(command_inspect, &format!("{driver} command inspection"))?; - assert_network_ca_command(command.as_array().ok_or("command must be an array")?) -} - -/// Check whether the supervisor received the gateway mTLS CA as a Podman -/// container secret (the delivery path used when user namespaces remap UIDs). -#[cfg(any(feature = "e2e-docker", feature = "e2e-podman"))] -fn podman_gateway_ca_secret( - container_engine: &ContainerEngine, - driver: &str, - container_id: &str, -) -> Result { - let mut secrets_command = engine_command(container_engine); - secrets_command.args([ - "inspect", - "--format", - "{{json .Config.Secrets}}", - container_id, - ]); - let secrets = run_json(secrets_command, &format!("{driver} secret inspection"))?; - let secrets = secrets - .as_array() - .ok_or("supervisor secrets must be an array")?; - Ok(secrets.iter().any(|secret| { - secret["Name"] - .as_str() - .is_some_and(|name| name.starts_with("openshell-tls-ca-")) - })) -} - -/// Check whether the Docker supervisor received the gateway mTLS CA through -/// its staged delivery path: the read-only supervisor state volume plus the -/// `OPENSHELL_TLS_CA` environment pointer. -#[cfg(any(feature = "e2e-docker", feature = "e2e-podman"))] -fn docker_gateway_ca_staged( - container_engine: &ContainerEngine, - container_id: &str, - mounts: &[Value], -) -> Result { - const SUPERVISOR_STATE_MOUNT_PATH: &str = "/.openshell/supervisor"; - let supervisor_volume = mounts - .iter() - .find(|mount| mount["Destination"] == SUPERVISOR_STATE_MOUNT_PATH); - if supervisor_volume.is_none_or(|mount| mount["RW"] != false) { - return Ok(false); - } - let mut env_command = engine_command(container_engine); - env_command.args(["inspect", "--format", "{{json .Config.Env}}", container_id]); - let envs = run_json(env_command, "docker environment inspection")?; - let envs = envs - .as_array() - .ok_or("supervisor environment must be an array")?; - Ok(envs - .iter() - .any(|env| env.as_str() == Some("OPENSHELL_TLS_CA=/.openshell/supervisor/tls/ca.pem"))) -} - fn assert_additional_ca_command(command: &[Value]) -> Result<(), String> { let bundle_pairs = command .windows(2) @@ -280,11 +132,6 @@ fn assert_additional_ca_command(command: &[Value]) -> Result<(), String> { Ok(()) } -#[cfg(any(feature = "e2e-docker", feature = "e2e-podman"))] -fn assert_network_ca_command(command: &[Value]) -> Result<(), String> { - assert_additional_ca_command(command) -} - fn kubectl_json(args: &[&str]) -> Result { let context = std::env::var("OPENSHELL_E2E_KUBE_CONTEXT_ACTIVE") .map_err(|error| format!("active Kubernetes context missing: {error}"))?; @@ -681,43 +528,6 @@ async fn assert_kubernetes_invalid_staged_material_fails_closed( Ok(()) } -async fn assert_invalid_staged_material_fails_closed(policy_path: &str) { - let startup_error = match SandboxGuard::create(&["--policy", policy_path, "--", "true"]).await { - Ok(mut unexpected) => { - unexpected.cleanup().await; - panic!("a new sandbox accepted invalid staged destination trust"); - } - Err(error) => error, - }; - assert!( - startup_error.contains("error phase") || startup_error.contains("failed"), - "invalid staged trust did not fail sandbox startup: {startup_error}" - ); - // Miette wraps long CLI diagnostics and prefixes continuation lines with a - // box-drawing marker. Normalize that presentation before matching the - // driver's stable error text. - let normalized_startup_error = startup_error - .lines() - .map(|line| line.trim().trim_start_matches('│').trim()) - .collect::>() - .join(" "); - assert!( - normalized_startup_error.contains("--additional-ca-bundle") - || normalized_startup_error.contains("additional destination CA bundle") - || normalized_startup_error.contains("invalid staged destination CA bundle") - || normalized_startup_error - .contains("network additional CA artifact verification failed") - || normalized_startup_error - .contains("does not match the gateway startup trust generation"), - "invalid staged trust lacked stable supervisor additional-CA validation evidence: {startup_error}" - ); - assert!( - !startup_error.contains("-----BEGIN CERTIFICATE-----") - && !startup_error.contains("-----BEGIN PRIVATE KEY-----"), - "invalid staged trust failure disclosed certificate or key material" - ); -} - fn remove_additional_ca_section(config: &str) -> Result { const SECTION: &str = "[openshell.supervisor.network]"; let mut found = false; @@ -962,14 +772,10 @@ fn python_fetch_argv(driver: &str, url: &str) -> Vec { ] } -fn python_binary_for_driver(driver: &str) -> &'static str { - match driver { - // The container-engine lanes run the Noble fixture image. - "docker" | "podman" => "/usr/bin/python3", - // The Kubernetes and VM lanes run the uv-based workload image, where - // python3 lives under /usr/local/bin and curl is not present. - _ => "/usr/local/bin/python3", - } +// The Kubernetes and VM lanes run the uv-based workload image, where python3 +// lives under /usr/local/bin and curl is not present. +fn python_binary_for_driver(_driver: &str) -> &'static str { + "/usr/local/bin/python3" } fn hostname_validation_script(matching_host: &str, port: u16) -> String { @@ -1064,21 +870,12 @@ async fn additional_ca_trusts_matching_and_public_hosts_and_rejects_mismatch() { panic!("VM driver feature missing"); } } else { - #[cfg(any(feature = "e2e-docker", feature = "e2e-podman"))] - { - inspect_local_container(driver, &sandbox.name) - .expect("inspect local container delivery"); - None - } - #[cfg(not(any(feature = "e2e-docker", feature = "e2e-podman")))] - { - panic!("local-container driver feature missing"); - } + panic!("unsupported additional CA e2e driver: {driver}"); }; replace_staged_material(driver, kubernetes_identity.as_deref()) .expect("replace staged destination trust with invalid material"); - if driver == "kubernetes" || driver == "vm" { + { let fetch_argv = python_fetch_argv(driver, &matching_url); let fetch_argv = fetch_argv.iter().map(String::as_str).collect::>(); let output = sandbox @@ -1095,7 +892,7 @@ async fn additional_ca_trusts_matching_and_public_hosts_and_rejects_mismatch() { assert_kubernetes_invalid_staged_material_fails_closed(&sandbox.name) .await .expect("stopped Kubernetes sandbox rejects invalid staged trust on start"); - } else if driver == "vm" { + } else { let mut retained_snapshot_sandbox = SandboxGuard::create_keep_with_args( &["--policy", policy_path], &[python_binary_for_driver(driver), "-c", script.as_str()], @@ -1109,8 +906,6 @@ async fn additional_ca_trusts_matching_and_public_hosts_and_rejects_mismatch() { .contains("matching-host-trusted") ); retained_snapshot_sandbox.cleanup().await; - } else { - assert_invalid_staged_material_fails_closed(policy_path).await; } // Remove the sandbox whose startup trust and staged material were mutated diff --git a/e2e/support/gateway-common.sh b/e2e/support/gateway-common.sh index f69518f0bc..b23c183012 100644 --- a/e2e/support/gateway-common.sh +++ b/e2e/support/gateway-common.sh @@ -138,7 +138,7 @@ e2e_start_additional_ca_fixture() { mkdir -p "${fixture_dir}" ( umask 077 - openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 \ + openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 \ -out "${fixture_dir}/ca.key" >/dev/null 2>&1 openssl req -x509 -new -key "${fixture_dir}/ca.key" \ -out "${fixture_dir}/ca.crt" -days 1 \ diff --git a/e2e/with-docker-gateway.sh b/e2e/with-docker-gateway.sh index 57d49632f4..e6176444a5 100755 --- a/e2e/with-docker-gateway.sh +++ b/e2e/with-docker-gateway.sh @@ -121,11 +121,6 @@ DOCKER_NETWORK_MANAGED=0 GPU_MODE="${OPENSHELL_E2E_DOCKER_GPU:-0}" OIDC_MODE="${OPENSHELL_E2E_OIDC_GATEWAY:-0}" OIDC_ISSUER="${OPENSHELL_E2E_OIDC_ISSUER:-}" -ADDITIONAL_CA_MODE="${OPENSHELL_E2E_ADDITIONAL_CA:-0}" -ADDITIONAL_CA_SERVER_PID="" -ADDITIONAL_CA_SERVER_LOG="${WORKDIR}/additional-ca-server.log" -ADDITIONAL_CA_DIR="${WORKDIR}/additional-ca" -ADDITIONAL_CA_PORT="" IMAGE_UPDATES_MODE="${OPENSHELL_E2E_DOCKER_IMAGE_UPDATES:-0}" SUPERVISOR_NETWORK_MODE="${OPENSHELL_E2E_DOCKER_SUPERVISOR_NETWORK_MODE:-}" case "${SUPERVISOR_NETWORK_MODE}" in @@ -155,7 +150,6 @@ cleanup() { local exit_code=$? e2e_stop_gateway "${GATEWAY_PID}" "${GATEWAY_PID_FILE}" - e2e_stop_process "${ADDITIONAL_CA_SERVER_PID}" "additional CA HTTPS fixture" if [ "${exit_code}" -ne 0 ] \ && [ -n "${E2E_NAMESPACE}" ] \ @@ -204,11 +198,6 @@ cleanup() { fi e2e_print_gateway_log_on_failure "${exit_code}" "${GATEWAY_LOG}" - if [ "${exit_code}" -ne 0 ] && [ -f "${ADDITIONAL_CA_SERVER_LOG}" ]; then - echo "=== additional CA HTTPS fixture log ===" - cat "${ADDITIONAL_CA_SERVER_LOG}" || true - echo "=== end additional CA HTTPS fixture log ===" - fi rm -rf "${WORKDIR}" 2>/dev/null || true } @@ -279,10 +268,6 @@ connect_current_container_to_docker_network() { } if [ -n "${OPENSHELL_GATEWAY_ENDPOINT:-}" ]; then - if [ "${ADDITIONAL_CA_MODE}" = "1" ]; then - echo "ERROR: additional CA e2e requires the wrapper-managed Docker gateway." >&2 - exit 2 - fi case "${OPENSHELL_GATEWAY_ENDPOINT}" in http://*) ;; https://*) @@ -559,15 +544,6 @@ if ! ensure_sandbox_image_available "${SANDBOX_IMAGE}"; then exit 2 fi -start_additional_ca_fixture() { - e2e_start_additional_ca_fixture \ - "${ADDITIONAL_CA_DIR}" "${ADDITIONAL_CA_SERVER_LOG}" \ - ADDITIONAL_CA_SERVER_PID ADDITIONAL_CA_PORT -} -if [ "${ADDITIONAL_CA_MODE}" = "1" ]; then - start_additional_ca_fixture -fi - HOST_PORT=$(e2e_pick_port) HEALTH_PORT=$(e2e_pick_port) STATE_DIR="${XDG_STATE_HOME}" @@ -585,10 +561,6 @@ export OPENSHELL_E2E_DOCKER_NETWORK_NAME="${DOCKER_NETWORK_NAME}" export OPENSHELL_E2E_NETWORK_NAME="${DOCKER_NETWORK_NAME}" export OPENSHELL_E2E_SANDBOX_NAMESPACE="${E2E_NAMESPACE}" export OPENSHELL_E2E_DRIVER="docker" -if [ "${ADDITIONAL_CA_MODE}" = "1" ]; then - export OPENSHELL_E2E_ADDITIONAL_CA_ARTIFACT="${XDG_STATE_HOME}/openshell/network-supervisor" - export OPENSHELL_E2E_GATEWAY_CONFIG="${STATE_DIR}/gateway.toml" -fi if connect_current_container_to_docker_network "${DOCKER_NETWORK_NAME}"; then echo "Connected CI job container to Docker network ${DOCKER_NETWORK_NAME} (${GATEWAY_HOST_ALIAS_IP})." # Container jobs use the host Docker daemon. The host-networked supervisor @@ -645,11 +617,6 @@ GATEWAY_CONFIG="${STATE_DIR}/gateway.toml" e2e_write_gateway_oidc_config "${OPENSHELL_OIDC_ISSUER}" fi fi - if [ "${ADDITIONAL_CA_MODE}" = "1" ]; then - printf '[openshell.supervisor.network]\n' - printf 'additional_ca_bundle = %s\n\n' \ - "$(toml_string "${ADDITIONAL_CA_DIR}/ca.crt")" - fi printf '[openshell.drivers.docker]\n' if [ -n "${SUPERVISOR_NETWORK_MODE}" ]; then printf 'supervisor_network_mode = %s\n' "$(toml_string "${SUPERVISOR_NETWORK_MODE}")" diff --git a/e2e/with-podman-gateway.sh b/e2e/with-podman-gateway.sh index c489fb678e..9f7a32250f 100755 --- a/e2e/with-podman-gateway.sh +++ b/e2e/with-podman-gateway.sh @@ -119,11 +119,6 @@ PODMAN_SOCKET="" GPU_MODE="${OPENSHELL_E2E_PODMAN_GPU:-0}" OIDC_MODE="${OPENSHELL_E2E_OIDC_GATEWAY:-0}" OIDC_ISSUER="${OPENSHELL_E2E_OIDC_ISSUER:-}" -ADDITIONAL_CA_MODE="${OPENSHELL_E2E_ADDITIONAL_CA:-0}" -ADDITIONAL_CA_SERVER_PID="" -ADDITIONAL_CA_SERVER_LOG="${WORKDIR}/additional-ca-server.log" -ADDITIONAL_CA_DIR="${WORKDIR}/additional-ca" -ADDITIONAL_CA_PORT="" if [ "${OIDC_MODE}" = "1" ] && [ -z "${OIDC_ISSUER}" ]; then echo "ERROR: OPENSHELL_E2E_OIDC_ISSUER is required when OPENSHELL_E2E_OIDC_GATEWAY=1" >&2 @@ -138,7 +133,6 @@ cleanup() { e2e_stop_gateway "${GATEWAY_PID}" "${GATEWAY_PID_FILE}" e2e_stop_process "${DRIVER_PID}" "external Podman compute driver" - e2e_stop_process "${ADDITIONAL_CA_SERVER_PID}" "additional CA HTTPS fixture" local sandbox_ids="" if command -v podman >/dev/null 2>&1; then @@ -209,11 +203,6 @@ cleanup() { cat "${PODMAN_SERVICE_LOG}" || true echo "=== end podman service log ===" fi - if [ "${exit_code}" -ne 0 ] && [ -f "${ADDITIONAL_CA_SERVER_LOG}" ]; then - echo "=== additional CA HTTPS fixture log ===" - cat "${ADDITIONAL_CA_SERVER_LOG}" || true - echo "=== end additional CA HTTPS fixture log ===" - fi if [ -n "${PODMAN_SERVICE_PID}" ]; then kill "${PODMAN_SERVICE_PID}" >/dev/null 2>&1 || true @@ -440,10 +429,6 @@ ensure_podman_sandbox_runtime_image() { } if [ -n "${OPENSHELL_GATEWAY_ENDPOINT:-}" ]; then - if [ "${ADDITIONAL_CA_MODE}" = "1" ]; then - echo "ERROR: additional CA e2e requires the wrapper-managed Podman gateway." >&2 - exit 2 - fi case "${OPENSHELL_GATEWAY_ENDPOINT}" in http://*) ;; https://*) @@ -518,19 +503,6 @@ PKI_DIR="${WORKDIR}/pki" e2e_generate_pki "${GATEWAY_BIN}" "${PKI_DIR}" "host.containers.internal" export OPENSHELL_E2E_GATEWAY_CA_CERT="${PKI_DIR}/ca.crt" -start_additional_ca_fixture() { - e2e_start_additional_ca_fixture \ - "${ADDITIONAL_CA_DIR}" "${ADDITIONAL_CA_SERVER_LOG}" \ - ADDITIONAL_CA_SERVER_PID ADDITIONAL_CA_PORT -} -if [ "${ADDITIONAL_CA_MODE}" = "1" ]; then - if [ "${OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER:-0}" = "1" ]; then - echo "ERROR: additional CA e2e requires the in-process Podman driver." >&2 - exit 2 - fi - start_additional_ca_fixture -fi - HOST_PORT=$(e2e_pick_port) HEALTH_PORT=$(e2e_pick_port) PRIMARY_BIND_IP="127.0.0.1" @@ -548,10 +520,6 @@ ensure_e2e_podman_network "${PODMAN_NETWORK_NAME}" export OPENSHELL_E2E_DRIVER="podman" export OPENSHELL_E2E_NETWORK_NAME="${PODMAN_NETWORK_NAME}" export OPENSHELL_E2E_SANDBOX_NAMESPACE="${E2E_NAMESPACE}" -if [ "${ADDITIONAL_CA_MODE}" = "1" ]; then - export OPENSHELL_E2E_ADDITIONAL_CA_ARTIFACT="${XDG_STATE_HOME}/openshell/network-supervisor" - export OPENSHELL_E2E_GATEWAY_CONFIG="${STATE_DIR}/gateway.toml" -fi echo "Starting openshell-gateway on port ${HOST_PORT} (namespace: ${E2E_NAMESPACE})..." e2e_generate_gateway_jwt "${JWT_DIR}" @@ -574,20 +542,6 @@ e2e_write_podman_gateway_config \ "${OPENSHELL_PODMAN_SOCKET:-}" \ "${OIDC_MODE}" \ "${OPENSHELL_OIDC_ISSUER:-}" -if [ "${ADDITIONAL_CA_MODE}" = "1" ]; then - CONFIG_WITH_ADDITIONAL_CA="${GATEWAY_CONFIG}.additional-ca" - awk -v ca_path="$(e2e_podman_toml_string "${ADDITIONAL_CA_DIR}/ca.crt")" ' - !inserted && $0 == "[openshell.drivers.podman]" { - print "[openshell.supervisor.network]" - print "additional_ca_bundle = " ca_path - print "" - inserted = 1 - } - { print } - END { if (!inserted) exit 42 } - ' "${GATEWAY_CONFIG}" >"${CONFIG_WITH_ADDITIONAL_CA}" - mv "${CONFIG_WITH_ADDITIONAL_CA}" "${GATEWAY_CONFIG}" -fi if [ "${OPENSHELL_E2E_EXTERNAL_COMPUTE_DRIVER:-0}" != "1" ]; then # The gateway launches the Podman driver from this directory. CONFIG_WITH_DRIVER_DIR="${GATEWAY_CONFIG}.driver-dir" diff --git a/tests/suites/drivers/docker/Cargo.lock b/tests/suites/drivers/docker/Cargo.lock index c9e06d3753..fea9fbe014 100644 --- a/tests/suites/drivers/docker/Cargo.lock +++ b/tests/suites/drivers/docker/Cargo.lock @@ -792,6 +792,7 @@ version = "0.0.0" dependencies = [ "container-engine-support", "openshell-testkit", + "serde_json", ] [[package]] diff --git a/tests/suites/drivers/docker/Cargo.toml b/tests/suites/drivers/docker/Cargo.toml index 418983946f..3e2c9bb258 100644 --- a/tests/suites/drivers/docker/Cargo.toml +++ b/tests/suites/drivers/docker/Cargo.toml @@ -12,6 +12,11 @@ license = "Apache-2.0" repository = "https://github.com/ai-openshell/openshell" publish = false +[[test]] +name = "docker-additional-ca" +path = "tests/additional_ca.rs" +harness = false + [[test]] name = "docker-lifecycle" path = "tests/lifecycle.rs" @@ -20,5 +25,6 @@ harness = false [dependencies] container-engine-support = { path = "../../../support/container-engine" } openshell-testkit = { path = "../../../testkit/testkit" } +serde_json = "1" [workspace] diff --git a/tests/suites/drivers/docker/tests/additional_ca.rs b/tests/suites/drivers/docker/tests/additional_ca.rs new file mode 100644 index 0000000000..94f46171ae --- /dev/null +++ b/tests/suites/drivers/docker/tests/additional_ca.rs @@ -0,0 +1,94 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! How the Docker driver delivers the gateway's additional destination CA to +//! a sandbox's supervisor. +//! +//! The environment configures the gateway with an additional CA +//! (`openshell.supervisor.network.additional_ca_bundle`). The +//! `features/additional-ca` suite checks that sandbox egress trusts it. +//! +//! Ported from `e2e/rust/tests/additional_ca.rs`. + +use container_engine_support::Engine; +use serde_json::Value; +use testkit::{Context, Error, ResultExt as _}; + +fn main() -> std::process::ExitCode { + testkit::main() +} + +/// Where the supervisor reads the additional CA. +const ADDITIONAL_CA_PATH: &str = "/etc/openshell/tls/additional/ca-bundle.pem"; +/// The read-only supervisor state volume, which holds the gateway's mTLS CA. +const SUPERVISOR_STATE_PATH: &str = "/.openshell/supervisor"; +const GATEWAY_CA_ENV: &str = "OPENSHELL_TLS_CA=/.openshell/supervisor/tls/ca.pem"; + +/// The supervisor gets the additional CA in a read-only mount of its own and +/// is told where it is, and still gets the gateway's mTLS CA from its state +/// volume. +#[testkit::test] +async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> testkit::Result { + cx.expect_compute_driver("docker").await?; + let engine = Engine::from_env()?; + let sandbox = cx + .sandbox("aca") + .command(["sleep", "infinity"]) + .create_ready() + .await?; + let supervisor = engine + .container_for_role(sandbox.name(), "supervisor") + .await?; + + let mounts = inspect_json(&engine, &supervisor, "{{json .Mounts}}").await?; + let mounts = mounts.as_array().cloned().unwrap_or_default(); + let read_only_at = |path: &str| { + mounts + .iter() + .filter(|mount| mount["Destination"] == path && mount["RW"] == false) + .count() + }; + testkit::ensure!( + read_only_at(ADDITIONAL_CA_PATH) == 1, + "the supervisor should have one read-only mount at {ADDITIONAL_CA_PATH}: {mounts:#?}" + ); + testkit::ensure!( + read_only_at(SUPERVISOR_STATE_PATH) == 1, + "the supervisor should have its state volume read-only at {SUPERVISOR_STATE_PATH}: \ + {mounts:#?}" + ); + + let env = inspect_json(&engine, &supervisor, "{{json .Config.Env}}").await?; + testkit::ensure!( + env.as_array() + .is_some_and(|env| env.iter().any(|var| var == GATEWAY_CA_ENV)), + "the supervisor should read the gateway's mTLS CA from its state volume ({GATEWAY_CA_ENV}): \ + {env}" + ); + + let command = inspect_json(&engine, &supervisor, "{{json .Config.Cmd}}").await?; + expect_additional_ca_argument(&command) +} + +async fn inspect_json(engine: &Engine, container: &str, format: &str) -> testkit::Result { + let output = engine.inspect_container(container, format).await?; + serde_json::from_str(output.trim()).context(format!("parse {format} of {container}")) +} + +/// Fail unless `command` passes `--additional-ca-bundle` once, with +/// [`ADDITIONAL_CA_PATH`]. +fn expect_additional_ca_argument(command: &Value) -> testkit::Result { + let args = command + .as_array() + .ok_or_else(|| Error::msg(format!("the supervisor command is not a list: {command}")))?; + let values: Vec<&Value> = args + .windows(2) + .filter(|pair| pair[0] == "--additional-ca-bundle") + .map(|pair| &pair[1]) + .collect(); + testkit::ensure!( + values == [ADDITIONAL_CA_PATH], + "the supervisor command should pass --additional-ca-bundle {ADDITIONAL_CA_PATH} once: \ + {command}" + ); + Ok(()) +} diff --git a/tests/suites/drivers/podman/Cargo.toml b/tests/suites/drivers/podman/Cargo.toml index f45178df31..3fd499d43b 100644 --- a/tests/suites/drivers/podman/Cargo.toml +++ b/tests/suites/drivers/podman/Cargo.toml @@ -12,6 +12,11 @@ license = "Apache-2.0" repository = "https://github.com/ai-openshell/openshell" publish = false +[[test]] +name = "podman-additional-ca" +path = "tests/additional_ca.rs" +harness = false + [[test]] name = "podman-lifecycle" path = "tests/lifecycle.rs" diff --git a/tests/suites/drivers/podman/tests/additional_ca.rs b/tests/suites/drivers/podman/tests/additional_ca.rs new file mode 100644 index 0000000000..81670f1b4f --- /dev/null +++ b/tests/suites/drivers/podman/tests/additional_ca.rs @@ -0,0 +1,107 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! How the Podman driver delivers the gateway's additional destination CA to +//! a sandbox's supervisor. +//! +//! The environment configures the gateway with an additional CA +//! (`openshell.supervisor.network.additional_ca_bundle`). The +//! `features/additional-ca` suite checks that sandbox egress trusts it. +//! +//! Ported from `e2e/rust/tests/additional_ca.rs`. + +use container_engine_support::Engine; +use serde_json::Value; +use testkit::{Context, Error, ResultExt as _}; + +fn main() -> std::process::ExitCode { + testkit::main() +} + +/// Where the supervisor reads the additional CA. +const ADDITIONAL_CA_PATH: &str = "/etc/openshell/tls/additional/ca-bundle.pem"; +/// Where the supervisor reads the gateway's mTLS CA when it is bind-mounted. +const GATEWAY_CA_PATH: &str = "/etc/openshell/tls/client/ca.crt"; +/// The prefix of the secret that carries the gateway's mTLS CA when user +/// namespaces remap UIDs. +const GATEWAY_CA_SECRET_PREFIX: &str = "openshell-tls-ca-"; + +/// The supervisor gets the additional CA in a read-only mount of its own and +/// is told where it is, and still gets the gateway's mTLS CA, as a separate +/// mount or a secret depending on the user-namespace mode. +#[testkit::test] +async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> testkit::Result { + cx.expect_compute_driver("podman").await?; + let engine = Engine::from_env()?; + let sandbox = cx + .sandbox("aca") + .command(["sleep", "infinity"]) + .create_ready() + .await?; + let supervisor = engine + .container_for_role(sandbox.name(), "supervisor") + .await?; + + let mounts = inspect_json(&engine, &supervisor, "{{json .Mounts}}").await?; + let mounts = mounts.as_array().cloned().unwrap_or_default(); + let additional: Vec<&Value> = mounts + .iter() + .filter(|mount| mount["Destination"] == ADDITIONAL_CA_PATH) + .collect(); + testkit::ensure!( + matches!(additional.as_slice(), [mount] if mount["RW"] == false), + "the supervisor should have one read-only mount at {ADDITIONAL_CA_PATH}: {mounts:#?}" + ); + + match mounts + .iter() + .find(|mount| mount["Destination"] == GATEWAY_CA_PATH) + { + Some(gateway) => testkit::ensure!( + gateway["Source"] != additional[0]["Source"], + "the gateway's mTLS CA and the additional CA should come from different files: \ + {mounts:#?}" + ), + None => { + let secrets = inspect_json(&engine, &supervisor, "{{json .Config.Secrets}}").await?; + let has_secret = secrets.as_array().is_some_and(|secrets| { + secrets.iter().any(|secret| { + secret["Name"] + .as_str() + .is_some_and(|name| name.starts_with(GATEWAY_CA_SECRET_PREFIX)) + }) + }); + testkit::ensure!( + has_secret, + "the supervisor should get the gateway's mTLS CA at {GATEWAY_CA_PATH} or in a \ + {GATEWAY_CA_SECRET_PREFIX}* secret; mounts: {mounts:#?}; secrets: {secrets}" + ); + } + } + + let command = inspect_json(&engine, &supervisor, "{{json .Config.Cmd}}").await?; + expect_additional_ca_argument(&command) +} + +async fn inspect_json(engine: &Engine, container: &str, format: &str) -> testkit::Result { + let output = engine.inspect_container(container, format).await?; + serde_json::from_str(output.trim()).context(format!("parse {format} of {container}")) +} + +/// Fail unless `command` passes `--additional-ca-bundle` once, with +/// [`ADDITIONAL_CA_PATH`]. +fn expect_additional_ca_argument(command: &Value) -> testkit::Result { + let args = command + .as_array() + .ok_or_else(|| Error::msg(format!("the supervisor command is not a list: {command}")))?; + let values: Vec<&Value> = args + .windows(2) + .filter(|pair| pair[0] == "--additional-ca-bundle") + .map(|pair| &pair[1]) + .collect(); + testkit::ensure!( + values == [ADDITIONAL_CA_PATH], + "the supervisor command should pass --additional-ca-bundle {ADDITIONAL_CA_PATH} once: \ + {command}" + ); + Ok(()) +} diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index d7f4f342a4..b0f5953788 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "additional-ca" +version = "0.0.0" +dependencies = [ + "host-server-support", + "openshell-testkit", + "serde_json", +] + [[package]] name = "addr2line" version = "0.25.1" diff --git a/tests/suites/features/additional-ca/Cargo.toml b/tests/suites/features/additional-ca/Cargo.toml new file mode 100644 index 0000000000..61ec74a950 --- /dev/null +++ b/tests/suites/features/additional-ca/Cargo.toml @@ -0,0 +1,21 @@ +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "additional-ca" +description = "Features suite: sandbox egress trusts the gateway's additional destination CA" +version = "0.0.0" +edition = "2024" +rust-version = "1.95" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[[test]] +name = "additional-ca" +path = "tests/additional_ca.rs" +harness = false + +[dependencies] +host-server-support = { path = "../../../support/host-server" } +openshell-testkit = { path = "../../../testkit/testkit" } +serde_json = "1" diff --git a/tests/suites/features/additional-ca/tests/additional_ca.rs b/tests/suites/features/additional-ca/tests/additional_ca.rs new file mode 100644 index 0000000000..2028801eb3 --- /dev/null +++ b/tests/suites/features/additional-ca/tests/additional_ca.rs @@ -0,0 +1,133 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Sandbox egress trusts the gateway's additional destination CA +//! (`openshell.supervisor.network.additional_ca_bundle`). +//! +//! The environment configures the gateway with a CA and publishes its +//! certificate and key (see `TestCa::from_env` in `host-server-support`). The +//! test signs a certificate for its own TLS server with it. +//! +//! Ported from `e2e/rust/tests/additional_ca.rs`. The checks that tamper with +//! the gateway's staged CA or remove it and restart the gateway were dropped +//! (#5917). The driver suites check how the CA reaches the supervisor. + +use host_server_support::{HttpRecorder, TEST_HOST, TestCa}; +use testkit::policy::{self, Access, Endpoint as _}; +use testkit::{Context, PYTHON_BINARIES, ResultExt as _}; + +fn main() -> std::process::ExitCode { + testkit::main() +} + +/// A name the server's certificate doesn't cover. +const MISMATCH_HOST: &str = "mismatch.openshell.internal"; +/// A public host whose certificate chains to a system root. +const PUBLIC_HOST: &str = "example.com"; +const BODY: &str = r#"{"additional_ca":"trusted"}"#; + +/// The address ranges a sandbox may reach `host.openshell.internal` at, +/// across drivers. +const HOST_RANGES: &[&str] = &["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]; + +/// With the workload's default trust, prints one JSON object with: +/// +/// - `matching`: the body of `https://:/`, or the error. +/// - `mismatch`: the error from a TLS handshake with the same server that +/// presents `argv[2]` as the server name, or `null` if it succeeded. +/// - `public`: the status of `https:///`, or the error. +/// +/// A failed request is retried, since a policy reload while the sandbox +/// starts can deny it once. +const CLIENT: &str = r#" +import json, socket, ssl, sys, time, urllib.request + +host, mismatch_host, port, public_host = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4] + +def retry(attempt): + result = None + for n in range(6): + if n: + time.sleep(1) + try: + return attempt() + except Exception as error: + result = {"error": f"{type(error).__name__}: {error}"} + return result + +def matching(): + with urllib.request.urlopen(f"https://{host}:{port}/", timeout=30) as response: + return {"body": response.read().decode()} + +def mismatch(): + address = socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP)[0][4] + with socket.create_connection(address, timeout=15) as sock: + try: + ssl.create_default_context().wrap_socket(sock, server_hostname=mismatch_host).close() + except ssl.SSLCertVerificationError as error: + return {"rejected": str(error)} + return {"rejected": None} + +def public(): + with urllib.request.urlopen(f"https://{public_host}/", timeout=30) as response: + return {"status": response.status} + +results = {"matching": retry(matching), "mismatch": mismatch(), "public": retry(public)} +print(json.dumps(results)) +"#; + +/// The workload trusts a server whose certificate the additional CA signed, +/// still rejects that server under a name its certificate doesn't cover, and +/// still trusts public hosts through the system roots. +#[testkit::test] +async fn additional_ca_trusts_matching_and_public_hosts_and_rejects_mismatch( + cx: &mut Context, +) -> testkit::Result { + let identity = TestCa::from_env()?.leaf(&[TEST_HOST])?; + let server = HttpRecorder::start_tls(&identity, BODY).await?; + + let mut policy = policy::base(); + for host in [TEST_HOST, MISMATCH_HOST] { + let endpoint = policy::allow( + &mut policy, + "additional_ca", + host, + server.port, + PYTHON_BINARIES, + ); + endpoint.rest(Access::Full).enforce().path("/**"); + endpoint.allowed_ips = HOST_RANGES.iter().map(ToString::to_string).collect(); + } + policy::allow(&mut policy, "public", PUBLIC_HOST, 443, PYTHON_BINARIES) + .rest(Access::Full) + .enforce() + .path("/**"); + + let sandbox = cx.python_sandbox("aca", policy).create_ready().await?; + let port = server.port.to_string(); + let results = sandbox + .run_python(CLIENT, &[TEST_HOST, MISMATCH_HOST, &port, PUBLIC_HOST]) + .await? + .last_json() + .context("run the TLS client")?; + + testkit::ensure!( + results["matching"]["body"] == BODY, + "the workload should trust {TEST_HOST}, whose certificate the additional CA signed: {}", + results["matching"] + ); + let rejected = results["mismatch"]["rejected"].as_str().unwrap_or_default(); + testkit::ensure!( + ["mismatch", "doesn't match"] + .iter() + .any(|reason| rejected.to_lowercase().contains(reason)), + "a handshake with {TEST_HOST}'s server as {MISMATCH_HOST} should fail the hostname \ + check: {}", + results["mismatch"] + ); + testkit::ensure!( + results["public"]["status"] == 200, + "the workload should still trust {PUBLIC_HOST} through the system roots: {}", + results["public"] + ); + Ok(()) +} diff --git a/tests/support/host-server/src/tls.rs b/tests/support/host-server/src/tls.rs index 71df5e7c8b..13d5f9a7f1 100644 --- a/tests/support/host-server/src/tls.rs +++ b/tests/support/host-server/src/tls.rs @@ -13,6 +13,9 @@ //! (`openshell.supervisor.network.additional_ca_bundle`). The environment //! publishes the paths of its PEM certificate and key in //! `OPENSHELL_TEST_ADDITIONAL_CA_CERT` and `OPENSHELL_TEST_ADDITIONAL_CA_KEY`. +//! tmachine environments do that +//! (`tests/tmachine/ansible/playbooks/additional-ca.yaml`), and so does +//! `e2e/rust/e2e-vm.sh` in its additional-CA mode. use std::path::Path; use std::sync::Arc; diff --git a/tests/tmachine/ansible/playbooks/additional-ca.yaml b/tests/tmachine/ansible/playbooks/additional-ca.yaml new file mode 100644 index 0000000000..7866e8d147 --- /dev/null +++ b/tests/tmachine/ansible/playbooks/additional-ca.yaml @@ -0,0 +1,67 @@ +# SPDX-License-Identifier: Apache-2.0 + +# Create a CA, configure the gateway to trust it for sandbox egress +# (`additional_ca_bundle`) and publish its certificate and key. Tests sign +# certificates for the servers they start with it (TestCa::from_env in +# tests/support/host-server). The settings go to the gateway overrides (the +# gateway_overrides role), which the binaries, deb and rpm installers apply. +--- +- name: Additional destination CA for tests + hosts: all + gather_facts: false + vars: + additional_ca_dir: /etc/openshell-test/additional-ca + tasks: + - name: Wait for SSH + ansible.builtin.wait_for_connection: + + - name: Install OpenSSL + become: true + ansible.builtin.package: + name: [openssl] + state: present + + - name: Create the additional CA directory + become: true + ansible.builtin.file: + path: "{{ additional_ca_dir }}" + state: directory + owner: root + group: root + mode: "0755" + + # The gateway reads the certificate. Only the tests, which run as the + # tmachine user, read the key. + - name: Create the additional CA + become: true + ansible.builtin.shell: + cmd: | + set -eu + dir={{ additional_ca_dir }} + work=$(mktemp -d) + trap 'rm -rf "$work"' EXIT + openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$work/ca-key.pem" + openssl req -x509 -new -key "$work/ca-key.pem" -out "$work/ca.pem" -days 3650 \ + -subj '/CN=OpenShell test additional CA' \ + -addext 'basicConstraints=critical,CA:TRUE' \ + -addext 'keyUsage=critical,keyCertSign,cRLSign' + install -m 0600 -o tmachine -g tmachine "$work/ca-key.pem" "$dir/ca-key.pem" + install -m 0644 "$work/ca.pem" "$dir/ca.pem" + creates: "{{ additional_ca_dir }}/ca.pem" + + - name: Configure the gateway with the additional CA + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: additional-ca + gateway_overrides_content: | + [openshell.supervisor.network] + additional_ca_bundle = "{{ additional_ca_dir }}/ca.pem" + + - 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_dir }}/ca.pem" + OPENSHELL_TEST_ADDITIONAL_CA_KEY: "{{ additional_ca_dir }}/ca-key.pem" diff --git a/tests/tmachine/config.nix b/tests/tmachine/config.nix index 02d563d366..1d5124417b 100644 --- a/tests/tmachine/config.nix +++ b/tests/tmachine/config.nix @@ -174,13 +174,18 @@ let ) (builtins.attrNames features); # -userns-{default,auto,keep-id,private} configure the Podman # gateway's user-namespace mode, for the Podman driver suite. Every installer - # applies the mode through /etc/openshell-test/gateway-overrides.toml. + # applies the mode through /etc/openshell-test/gateway-overrides.toml. They + # also configure an additional destination CA, whose delivery the suite + # checks in each mode. podmanUsernsEnvironments = pkgs.lib.concatMap ( base: map ( userns: withSetup base "userns-${userns}" { - playbooks = [ "ansible/playbooks/drivers/podman/userns.yaml" ]; + playbooks = [ + "ansible/playbooks/drivers/podman/userns.yaml" + "ansible/playbooks/additional-ca.yaml" + ]; inputs.podman_userns_mode = userns; } ) podmanUsernsModes diff --git a/tests/tmachine/features/additional-ca.nix b/tests/tmachine/features/additional-ca.nix new file mode 100644 index 0000000000..045421acf1 --- /dev/null +++ b/tests/tmachine/features/additional-ca.nix @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: Apache-2.0 + +# A gateway trusting an additional destination CA whose key the tests read, +# for the additional-ca suite and the Docker driver suite. +{ dockerBases, podmanBases, ... }: +{ + bases = dockerBases ++ podmanBases; + setup.playbooks = [ "ansible/playbooks/additional-ca.yaml" ]; +} From 53f9006543c8a349067e24a208c835812803e5b3 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 4 Dec 2026 10:33:34 -0800 Subject: [PATCH 02/10] test(drivers): require exactly one read-only Docker additional CA mount Count every supervisor mount at the destination before checking that it is read-only, as the Podman test does. Add a TESTING.md example for running the Docker driver suite in its CI environment. Signed-off-by: Matthew Grossman --- TESTING.md | 4 ++++ tests/suites/drivers/docker/tests/additional_ca.rs | 14 ++++++++------ 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/TESTING.md b/TESTING.md index 5cf0592fd0..42c2520be7 100644 --- a/TESTING.md +++ b/TESTING.md @@ -70,6 +70,10 @@ nix run .#openshell-test-runner -- run \ nix run .#openshell-test-runner -- run \ --environment fedora-podman-rootful-userns-default --installer rpm \ --family drivers/podman + +nix run .#openshell-test-runner -- run \ + --environment ubuntu-docker-rootful-additional-ca --installer deb \ + --family drivers/docker ``` Results and logs go to `artifacts/test-results/` by default. See diff --git a/tests/suites/drivers/docker/tests/additional_ca.rs b/tests/suites/drivers/docker/tests/additional_ca.rs index 94f46171ae..a73e985b34 100644 --- a/tests/suites/drivers/docker/tests/additional_ca.rs +++ b/tests/suites/drivers/docker/tests/additional_ca.rs @@ -41,18 +41,20 @@ async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> te let mounts = inspect_json(&engine, &supervisor, "{{json .Mounts}}").await?; let mounts = mounts.as_array().cloned().unwrap_or_default(); - let read_only_at = |path: &str| { - mounts + // Exactly one mount at the path, and it is read-only. + let one_read_only_at = |path: &str| { + let at: Vec<_> = mounts .iter() - .filter(|mount| mount["Destination"] == path && mount["RW"] == false) - .count() + .filter(|mount| mount["Destination"] == path) + .collect(); + matches!(at.as_slice(), [mount] if mount["RW"] == false) }; testkit::ensure!( - read_only_at(ADDITIONAL_CA_PATH) == 1, + one_read_only_at(ADDITIONAL_CA_PATH), "the supervisor should have one read-only mount at {ADDITIONAL_CA_PATH}: {mounts:#?}" ); testkit::ensure!( - read_only_at(SUPERVISOR_STATE_PATH) == 1, + one_read_only_at(SUPERVISOR_STATE_PATH), "the supervisor should have its state volume read-only at {SUPERVISOR_STATE_PATH}: \ {mounts:#?}" ); From 5c08cf8caf863713db995eb989df77d2e457c5d9 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 4 Dec 2026 11:30:30 -0800 Subject: [PATCH 03/10] test(support): share container inspect JSON and flag parsing Move the JSON inspect and command-flag helpers that the Docker and Podman additional CA tests each defined into container-engine-support. Signed-off-by: Matthew Grossman --- tests/suites/drivers/docker/Cargo.lock | 2 +- tests/suites/drivers/docker/Cargo.toml | 1 - .../drivers/docker/tests/additional_ca.rs | 36 ++++++------------- tests/suites/drivers/podman/Cargo.lock | 1 + .../drivers/podman/tests/additional_ca.rs | 35 ++++++------------ tests/suites/features/Cargo.lock | 1 + tests/support/Cargo.lock | 1 + tests/support/container-engine/Cargo.toml | 1 + tests/support/container-engine/src/lib.rs | 20 +++++++++++ 9 files changed, 45 insertions(+), 53 deletions(-) diff --git a/tests/suites/drivers/docker/Cargo.lock b/tests/suites/drivers/docker/Cargo.lock index fea9fbe014..1bc442af24 100644 --- a/tests/suites/drivers/docker/Cargo.lock +++ b/tests/suites/drivers/docker/Cargo.lock @@ -531,6 +531,7 @@ name = "container-engine-support" version = "0.0.0" dependencies = [ "openshell-testkit", + "serde_json", "tempfile", "tokio", ] @@ -792,7 +793,6 @@ version = "0.0.0" dependencies = [ "container-engine-support", "openshell-testkit", - "serde_json", ] [[package]] diff --git a/tests/suites/drivers/docker/Cargo.toml b/tests/suites/drivers/docker/Cargo.toml index 3e2c9bb258..0a6225e739 100644 --- a/tests/suites/drivers/docker/Cargo.toml +++ b/tests/suites/drivers/docker/Cargo.toml @@ -25,6 +25,5 @@ harness = false [dependencies] container-engine-support = { path = "../../../support/container-engine" } openshell-testkit = { path = "../../../testkit/testkit" } -serde_json = "1" [workspace] diff --git a/tests/suites/drivers/docker/tests/additional_ca.rs b/tests/suites/drivers/docker/tests/additional_ca.rs index a73e985b34..8ca10935ce 100644 --- a/tests/suites/drivers/docker/tests/additional_ca.rs +++ b/tests/suites/drivers/docker/tests/additional_ca.rs @@ -9,9 +9,8 @@ //! //! Ported from `e2e/rust/tests/additional_ca.rs`. -use container_engine_support::Engine; -use serde_json::Value; -use testkit::{Context, Error, ResultExt as _}; +use container_engine_support::{Engine, flag_values}; +use testkit::Context; fn main() -> std::process::ExitCode { testkit::main() @@ -39,7 +38,7 @@ async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> te .container_for_role(sandbox.name(), "supervisor") .await?; - let mounts = inspect_json(&engine, &supervisor, "{{json .Mounts}}").await?; + let mounts = engine.inspect_json(&supervisor, "{{json .Mounts}}").await?; let mounts = mounts.as_array().cloned().unwrap_or_default(); // Exactly one mount at the path, and it is read-only. let one_read_only_at = |path: &str| { @@ -59,7 +58,9 @@ async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> te {mounts:#?}" ); - let env = inspect_json(&engine, &supervisor, "{{json .Config.Env}}").await?; + let env = engine + .inspect_json(&supervisor, "{{json .Config.Env}}") + .await?; testkit::ensure!( env.as_array() .is_some_and(|env| env.iter().any(|var| var == GATEWAY_CA_ENV)), @@ -67,28 +68,11 @@ async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> te {env}" ); - let command = inspect_json(&engine, &supervisor, "{{json .Config.Cmd}}").await?; - expect_additional_ca_argument(&command) -} - -async fn inspect_json(engine: &Engine, container: &str, format: &str) -> testkit::Result { - let output = engine.inspect_container(container, format).await?; - serde_json::from_str(output.trim()).context(format!("parse {format} of {container}")) -} - -/// Fail unless `command` passes `--additional-ca-bundle` once, with -/// [`ADDITIONAL_CA_PATH`]. -fn expect_additional_ca_argument(command: &Value) -> testkit::Result { - let args = command - .as_array() - .ok_or_else(|| Error::msg(format!("the supervisor command is not a list: {command}")))?; - let values: Vec<&Value> = args - .windows(2) - .filter(|pair| pair[0] == "--additional-ca-bundle") - .map(|pair| &pair[1]) - .collect(); + let command = engine + .inspect_json(&supervisor, "{{json .Config.Cmd}}") + .await?; testkit::ensure!( - values == [ADDITIONAL_CA_PATH], + flag_values(&command, "--additional-ca-bundle")? == [ADDITIONAL_CA_PATH], "the supervisor command should pass --additional-ca-bundle {ADDITIONAL_CA_PATH} once: \ {command}" ); diff --git a/tests/suites/drivers/podman/Cargo.lock b/tests/suites/drivers/podman/Cargo.lock index 1187155f9c..776518a3a5 100644 --- a/tests/suites/drivers/podman/Cargo.lock +++ b/tests/suites/drivers/podman/Cargo.lock @@ -531,6 +531,7 @@ name = "container-engine-support" version = "0.0.0" dependencies = [ "openshell-testkit", + "serde_json", "tempfile", "tokio", ] diff --git a/tests/suites/drivers/podman/tests/additional_ca.rs b/tests/suites/drivers/podman/tests/additional_ca.rs index 81670f1b4f..34827e22c8 100644 --- a/tests/suites/drivers/podman/tests/additional_ca.rs +++ b/tests/suites/drivers/podman/tests/additional_ca.rs @@ -9,9 +9,9 @@ //! //! Ported from `e2e/rust/tests/additional_ca.rs`. -use container_engine_support::Engine; +use container_engine_support::{Engine, flag_values}; use serde_json::Value; -use testkit::{Context, Error, ResultExt as _}; +use testkit::Context; fn main() -> std::process::ExitCode { testkit::main() @@ -41,7 +41,7 @@ async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> te .container_for_role(sandbox.name(), "supervisor") .await?; - let mounts = inspect_json(&engine, &supervisor, "{{json .Mounts}}").await?; + let mounts = engine.inspect_json(&supervisor, "{{json .Mounts}}").await?; let mounts = mounts.as_array().cloned().unwrap_or_default(); let additional: Vec<&Value> = mounts .iter() @@ -62,7 +62,9 @@ async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> te {mounts:#?}" ), None => { - let secrets = inspect_json(&engine, &supervisor, "{{json .Config.Secrets}}").await?; + let secrets = engine + .inspect_json(&supervisor, "{{json .Config.Secrets}}") + .await?; let has_secret = secrets.as_array().is_some_and(|secrets| { secrets.iter().any(|secret| { secret["Name"] @@ -78,28 +80,11 @@ async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> te } } - let command = inspect_json(&engine, &supervisor, "{{json .Config.Cmd}}").await?; - expect_additional_ca_argument(&command) -} - -async fn inspect_json(engine: &Engine, container: &str, format: &str) -> testkit::Result { - let output = engine.inspect_container(container, format).await?; - serde_json::from_str(output.trim()).context(format!("parse {format} of {container}")) -} - -/// Fail unless `command` passes `--additional-ca-bundle` once, with -/// [`ADDITIONAL_CA_PATH`]. -fn expect_additional_ca_argument(command: &Value) -> testkit::Result { - let args = command - .as_array() - .ok_or_else(|| Error::msg(format!("the supervisor command is not a list: {command}")))?; - let values: Vec<&Value> = args - .windows(2) - .filter(|pair| pair[0] == "--additional-ca-bundle") - .map(|pair| &pair[1]) - .collect(); + let command = engine + .inspect_json(&supervisor, "{{json .Config.Cmd}}") + .await?; testkit::ensure!( - values == [ADDITIONAL_CA_PATH], + flag_values(&command, "--additional-ca-bundle")? == [ADDITIONAL_CA_PATH], "the supervisor command should pass --additional-ca-bundle {ADDITIONAL_CA_PATH} once: \ {command}" ); diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index b0f5953788..1e0e2dbb2a 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -585,6 +585,7 @@ name = "container-engine-support" version = "0.0.0" dependencies = [ "openshell-testkit", + "serde_json", "tempfile", "tokio", ] diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 83e25ef4da..49f0bc8fcb 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -531,6 +531,7 @@ name = "container-engine-support" version = "0.0.0" dependencies = [ "openshell-testkit", + "serde_json", "tempfile", "tokio", ] diff --git a/tests/support/container-engine/Cargo.toml b/tests/support/container-engine/Cargo.toml index b3ef69395c..4f76ba92f7 100644 --- a/tests/support/container-engine/Cargo.toml +++ b/tests/support/container-engine/Cargo.toml @@ -13,5 +13,6 @@ publish = false [dependencies] openshell-testkit = { path = "../../testkit/testkit" } +serde_json = "1" tempfile = "3" tokio = { version = "1.43", features = ["process", "time"] } diff --git a/tests/support/container-engine/src/lib.rs b/tests/support/container-engine/src/lib.rs index f80def0eb2..f7bb9c8f29 100644 --- a/tests/support/container-engine/src/lib.rs +++ b/tests/support/container-engine/src/lib.rs @@ -153,6 +153,13 @@ impl Engine { .await } + /// `container inspect --format format` for one container, where `format` + /// prints JSON, such as `{{json .Mounts}}`. + pub async fn inspect_json(&self, id: &str, format: &str) -> Result { + let output = self.inspect_container(id, format).await?; + serde_json::from_str(output.trim()).context(format!("parse {format} of {id}")) + } + /// The IDs of every container, running or not, that the driver labeled /// with sandbox ID `sandbox_id`. Sandbox IDs are unique, so this finds /// only the containers of the sandbox the test created. @@ -311,3 +318,16 @@ fn utf8(path: &Path) -> Result<&str> { path.to_str() .ok_or_else(|| Error::msg(format!("{} is not UTF-8", path.display()))) } + +/// The values `command`, a container's `.Config.Cmd` as JSON, passes for +/// `flag` (` `), in order. +pub fn flag_values<'a>(command: &'a serde_json::Value, flag: &str) -> Result> { + let args = command + .as_array() + .ok_or_else(|| Error::msg(format!("the command is not a list: {command}")))?; + Ok(args + .windows(2) + .filter(|pair| pair[0] == flag) + .filter_map(|pair| pair[1].as_str()) + .collect()) +} From 8732e5cc589ec93e508fc57f46e31782ec018e2d Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 3 Dec 2026 16:01:02 -0800 Subject: [PATCH 04/10] test(e2e): port gateway restart tests to the continuity suite Merge gateway_start, podman_gateway_start, vm_gateway_start and the VM token check from local_driver_token_restart into a sandbox_intent continuity scenario. The runner's gateway-restart and upgrade disruptions run it on Docker and Podman; e2e-vm.sh runs seed, restarts its gateway and runs verify until tmachine has a VM row (#5918). Part of #6214 Part of #5297 Signed-off-by: Matthew Grossman --- TESTING.md | 8 +- e2e/rust/Cargo.toml | 20 -- e2e/rust/e2e-podman.sh | 1 - e2e/rust/e2e-vm.sh | 65 +++-- e2e/rust/tests/gateway_start.rs | 230 ------------------ e2e/rust/tests/local_driver_token_restart.rs | 175 ------------- e2e/rust/tests/podman_gateway_start.rs | 205 ---------------- e2e/rust/tests/vm_gateway_start.rs | 165 ------------- e2e/support/continuity.sh | 27 ++ tests/suites/continuity/Cargo.lock | 12 + tests/suites/continuity/Cargo.toml | 1 + tests/suites/continuity/src/lib.rs | 1 + tests/suites/continuity/src/sandbox_intent.rs | 201 +++++++++++++++ .../continuity/src/sandbox_workspace.rs | 31 +-- tests/suites/continuity/src/scenario.rs | 36 ++- tests/support/Cargo.lock | 11 + tests/support/vm/Cargo.toml | 18 ++ tests/support/vm/src/lib.rs | 102 ++++++++ tests/tmachine/artifacts.nix | 14 +- 19 files changed, 462 insertions(+), 861 deletions(-) delete mode 100644 e2e/rust/tests/gateway_start.rs delete mode 100644 e2e/rust/tests/local_driver_token_restart.rs delete mode 100644 e2e/rust/tests/podman_gateway_start.rs delete mode 100644 e2e/rust/tests/vm_gateway_start.rs create mode 100644 e2e/support/continuity.sh create mode 100644 tests/suites/continuity/src/sandbox_intent.rs create mode 100644 tests/support/vm/Cargo.toml create mode 100644 tests/support/vm/src/lib.rs diff --git a/TESTING.md b/TESTING.md index 42c2520be7..33a8936b84 100644 --- a/TESTING.md +++ b/TESTING.md @@ -463,6 +463,10 @@ nix run .#openshell-test-runner -- run \ --family continuity --disruption gateway-restart ``` +tmachine doesn't run the VM driver yet (#5918), so `mise run e2e:vm` runs the +`seed` tests, restarts its gateway, and runs the `verify` tests itself. It sets +`OPENSHELL_TEST_VM_STATE_DIR` for checks on the VM driver's state. + The `upgrade` disruption installs the candidate over a released package. Use the `deb-upgrade-source` installer, or `rpm-upgrade-source` on `fedora-podman-rootless` or `fedora-podman-rootful`, which installs the latest release as the baseline. @@ -567,7 +571,7 @@ Suites: - Driver suites (`--features e2e-docker`, `e2e-podman`, `e2e-kubernetes`, or `e2e-vm`) - conformance plus the common and driver-specific coverage for the selected deployment. -- Docker suite (`--features e2e-docker`) - includes Docker-only coverage such as Dockerfile image builds, Docker preflight checks, and managed Docker gateway start. +- Docker suite (`--features e2e-docker`) - includes Docker-only coverage such as Dockerfile image builds and Docker preflight checks. - Docker GPU suite (`--features e2e-docker-gpu`) - Docker suite plus GPU sandbox smoke coverage. - VM suite (`--features e2e-vm`) - runs e2e tests on a VM. - Kubernetes credential-driver suite (`--features e2e-kubernetes-credential-drivers`) - targeted Kubernetes Secrets and Vault provider credential storage coverage. @@ -1014,7 +1018,7 @@ cargo test --manifest-path e2e/rust/Cargo.toml --features e2e --test sync Run a single Docker-only test directly with cargo: ```shell -cargo test --manifest-path e2e/rust/Cargo.toml --features e2e-docker --test gateway_start +cargo test --manifest-path e2e/rust/Cargo.toml --features e2e-docker --test provider_readiness ``` The harness (`e2e/rust/src/harness/`) provides: diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 33464ed903..12c2b52bb9 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -81,26 +81,11 @@ name = "additional_ca" path = "tests/additional_ca.rs" required-features = ["e2e-additional-ca"] -[[test]] -name = "gateway_start" -path = "tests/gateway_start.rs" -required-features = ["e2e-docker"] - -[[test]] -name = "local_driver_token_restart" -path = "tests/local_driver_token_restart.rs" -required-features = ["e2e"] - [[test]] name = "ephemeral_cleanup" path = "tests/ephemeral_cleanup.rs" required-features = ["e2e"] -[[test]] -name = "podman_gateway_start" -path = "tests/podman_gateway_start.rs" -required-features = ["e2e-podman"] - [[test]] name = "provider_refresh_handles" path = "tests/provider_refresh_handles.rs" @@ -116,11 +101,6 @@ name = "provider_readiness" path = "tests/provider_readiness.rs" required-features = ["e2e-docker"] -[[test]] -name = "vm_gateway_start" -path = "tests/vm_gateway_start.rs" -required-features = ["e2e-vm"] - [[test]] name = "vm_corporate_proxy" path = "tests/vm_corporate_proxy.rs" diff --git a/e2e/rust/e2e-podman.sh b/e2e/rust/e2e-podman.sh index bff337644b..986738c224 100755 --- a/e2e/rust/e2e-podman.sh +++ b/e2e/rust/e2e-podman.sh @@ -24,7 +24,6 @@ source "${ROOT}/e2e/support/conformance.sh" PODMAN_CI_TESTS=( ephemeral_cleanup edge_tunnel_e2e - podman_gateway_start provider_github_app ) diff --git a/e2e/rust/e2e-vm.sh b/e2e/rust/e2e-vm.sh index 36a4b274e4..a66ec85c42 100755 --- a/e2e/rust/e2e-vm.sh +++ b/e2e/rust/e2e-vm.sh @@ -44,6 +44,8 @@ ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" source "${ROOT}/e2e/support/gateway-common.sh" # shellcheck source=e2e/support/conformance.sh source "${ROOT}/e2e/support/conformance.sh" +# shellcheck source=e2e/support/continuity.sh +source "${ROOT}/e2e/support/continuity.sh" COMPRESSED_DIR="${ROOT}/target/vm-runtime-compressed" GATEWAY_BIN="${OPENSHELL_GATEWAY_BIN:-${ROOT}/target/debug/openshell-gateway}" @@ -371,10 +373,13 @@ GATEWAY_ARGS=( ) e2e_write_gateway_args_file "${GATEWAY_ARGS_FILE}" "${GATEWAY_ARGS[@]}" -"${GATEWAY_BIN}" "${GATEWAY_ARGS[@]}" \ - >"${GATEWAY_LOG}" 2>&1 & -GATEWAY_PID=$! -printf '%s\n' "${GATEWAY_PID}" >"${GATEWAY_PID_FILE}" +start_gateway() { + "${GATEWAY_BIN}" "${GATEWAY_ARGS[@]}" \ + >>"${GATEWAY_LOG}" 2>&1 & + GATEWAY_PID=$! + printf '%s\n' "${GATEWAY_PID}" >"${GATEWAY_PID_FILE}" +} +start_gateway # Register the gateway before polling so readiness exercises the same mTLS # client path as the smoke tests. @@ -393,25 +398,25 @@ export OPENSHELL_GATEWAY_ENDPOINT="${CLI_GATEWAY_ENDPOINT}" # particular gateway log message. The VM driver is spawned eagerly, while # sandboxes are created on demand. -echo "==> Waiting for gateway readiness (timeout ${GATEWAY_READY_TIMEOUT}s)" -elapsed=0 -last_status_output="" -while [ "${elapsed}" -lt "${GATEWAY_READY_TIMEOUT}" ]; do - if ! kill -0 "${GATEWAY_PID}" 2>/dev/null; then - echo "ERROR: openshell-gateway exited before becoming ready" - exit 1 - fi - if last_status_output="$("${CLI_BIN}" status --output json 2>&1)" && - printf '%s\n' "${last_status_output}" | - grep -Eq '"status"[[:space:]]*:[[:space:]]*"connected"'; then - echo "==> Gateway ready after ${elapsed}s" - break - fi - sleep 2 - elapsed=$((elapsed + 2)) -done +wait_for_gateway() { + echo "==> Waiting for gateway readiness (timeout ${GATEWAY_READY_TIMEOUT}s)" + local elapsed=0 + local last_status_output="" + while [ "${elapsed}" -lt "${GATEWAY_READY_TIMEOUT}" ]; do + if ! kill -0 "${GATEWAY_PID}" 2>/dev/null; then + echo "ERROR: openshell-gateway exited before becoming ready" + exit 1 + fi + if last_status_output="$("${CLI_BIN}" status --output json 2>&1)" && + printf '%s\n' "${last_status_output}" | + grep -Eq '"status"[[:space:]]*:[[:space:]]*"connected"'; then + echo "==> Gateway ready after ${elapsed}s" + return + fi + sleep 2 + elapsed=$((elapsed + 2)) + done -if [ "${elapsed}" -ge "${GATEWAY_READY_TIMEOUT}" ]; then echo "ERROR: openshell-gateway did not become ready after ${GATEWAY_READY_TIMEOUT}s" echo "=== last openshell status output ===" if [ -n "${last_status_output}" ]; then @@ -421,7 +426,8 @@ if [ "${elapsed}" -ge "${GATEWAY_READY_TIMEOUT}" ]; then fi echo "=== end openshell status output ===" exit 1 -fi +} +wait_for_gateway # ── Run the smoke test ─────────────────────────────────────────────── # @@ -509,6 +515,17 @@ else run_e2e_test ephemeral_cleanup run_e2e_test vm_overlay run_e2e_test vm_bind_mount - run_e2e_test vm_gateway_start run_e2e_test vm_corporate_proxy + + # The continuity suite's seed and verify tests, with a gateway restart + # between them, as tmachine's gateway-restart disruption does (#5918). + CONTINUITY_RUN_ID="$(printf '%x' "$(date +%s)")" + export CONTINUITY_RUN_ID + export OPENSHELL_TEST_VM_STATE_DIR="${RUN_STATE_DIR}" + e2e_run_continuity_phase seed + echo "==> Restarting openshell-gateway" + e2e_stop_gateway "${GATEWAY_PID}" "${GATEWAY_PID_FILE}" + start_gateway + wait_for_gateway + e2e_run_continuity_phase verify fi diff --git a/e2e/rust/tests/gateway_start.rs b/e2e/rust/tests/gateway_start.rs deleted file mode 100644 index 2bd9c0c738..0000000000 --- a/e2e/rust/tests/gateway_start.rs +++ /dev/null @@ -1,230 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e")] - -//! E2E coverage for reconciling Docker sandboxes after a standalone gateway restart. -//! -//! This intentionally targets the Docker-driver gateway started by -//! `e2e/with-docker-gateway.sh`. Existing-endpoint E2E runs do not own the -//! gateway process, so they skip this restart-only coverage. - -use std::process::{Command, Stdio}; -use std::time::Duration; - -use openshell_e2e::harness::cli::{ - run_cli, sandbox_names, wait_for_healthy, wait_for_sandbox_exec_contains, - wait_for_sandbox_phase, -}; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::sandbox::SandboxGuard; -use tokio::time::sleep; - -const MANAGED_BY_LABEL_FILTER: &str = "label=openshell.ai/managed-by=openshell"; -const READY_MARKER: &str = "gateway-start-ready"; -const STOPPED_READY_MARKER: &str = "gateway-start-stopped-ready"; -const START_FILE: &str = "/sandbox/gateway-start-state"; -const SANDBOX_NAMESPACE_LABEL: &str = "openshell.ai/sandbox-namespace"; -const SANDBOX_NAME_LABEL: &str = "openshell.ai/sandbox-name"; -const SANDBOX_ROLE_LABEL_FILTER: &str = "label=openshell.ai/isolation-role=sandbox"; - -fn sandbox_container_id(namespace: &str, sandbox_name: &str) -> Result { - let namespace_filter = format!("label={SANDBOX_NAMESPACE_LABEL}={namespace}"); - let sandbox_name_filter = format!("label={SANDBOX_NAME_LABEL}={sandbox_name}"); - let output = Command::new("docker") - .args([ - "ps", - "-aq", - "--filter", - MANAGED_BY_LABEL_FILTER, - "--filter", - SANDBOX_ROLE_LABEL_FILTER, - "--filter", - ]) - .arg(namespace_filter) - .args(["--filter"]) - .arg(sandbox_name_filter) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .map_err(|err| format!("failed to run docker ps: {err}"))?; - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - let combined = format!("{stdout}{stderr}"); - if !output.status.success() { - return Err(format!( - "docker ps failed (exit {:?}):\n{combined}", - output.status.code() - )); - } - - let ids = stdout - .lines() - .map(str::trim) - .filter(|line| !line.is_empty()) - .collect::>(); - match ids.as_slice() { - [id] => Ok((*id).to_string()), - [] => Err(format!( - "no Docker container found for sandbox '{sandbox_name}' in namespace '{namespace}'" - )), - _ => Err(format!( - "multiple Docker containers found for sandbox '{sandbox_name}' in namespace '{namespace}': {ids:?}" - )), - } -} - -fn sandbox_container_running(namespace: &str, sandbox_name: &str) -> Result { - let container_id = sandbox_container_id(namespace, sandbox_name)?; - let output = Command::new("docker") - .args(["inspect", "-f", "{{.State.Running}}", &container_id]) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .map_err(|err| format!("failed to run docker inspect: {err}"))?; - let stdout = String::from_utf8_lossy(&output.stdout); - let stderr = String::from_utf8_lossy(&output.stderr); - let combined = format!("{stdout}{stderr}"); - if !output.status.success() { - return Err(format!( - "docker inspect failed (exit {:?}):\n{combined}", - output.status.code() - )); - } - - match stdout.trim() { - "true" => Ok(true), - "false" => Ok(false), - other => Err(format!( - "unexpected Docker running state for container {container_id}: {other}" - )), - } -} - -async fn wait_for_container_running( - namespace: &str, - sandbox_name: &str, - expected: bool, - timeout: Duration, -) -> Result<(), String> { - let start = std::time::Instant::now(); - let mut last_state: String; - - loop { - match sandbox_container_running(namespace, sandbox_name) { - Ok(running) if running == expected => return Ok(()), - Ok(running) => last_state = format!("running={running}"), - Err(err) => last_state = err, - } - - if start.elapsed() > timeout { - return Err(format!( - "sandbox container '{sandbox_name}' did not reach running={expected} within {}s. Last state: {last_state}", - timeout.as_secs() - )); - } - sleep(Duration::from_secs(1)).await; - } -} - -#[tokio::test] -async fn docker_gateway_restart_preserves_running_and_stopped_intent() { - let Some(gateway) = ManagedGateway::from_env().expect("load managed e2e gateway metadata") - else { - eprintln!("Skipping gateway start test: e2e gateway is not managed by this test run"); - return; - }; - let Some(namespace) = std::env::var("OPENSHELL_E2E_DOCKER_NETWORK_NAME") - .ok() - .filter(|value| !value.trim().is_empty()) - else { - eprintln!("Skipping gateway start test: Docker e2e namespace is unavailable"); - return; - }; - - wait_for_healthy(Duration::from_secs(30)) - .await - .expect("gateway should start healthy"); - - let script = format!( - "echo before-restart > {START_FILE}; echo {READY_MARKER}; while true; do sleep 1; done" - ); - let mut sandbox = SandboxGuard::create_keep(&["sh", "-lc", &script], READY_MARKER) - .await - .expect("create long-running sandbox"); - - let before_restart = sandbox - .exec(&["cat", START_FILE]) - .await - .expect("read sandbox state before restart"); - assert!( - before_restart.contains("before-restart"), - "sandbox state was not written before restart:\n{before_restart}" - ); - - wait_for_container_running(&namespace, &sandbox.name, true, Duration::from_mins(1)) - .await - .expect("sandbox container should be running before gateway restart"); - - let stopped_script = format!("echo {STOPPED_READY_MARKER}; while true; do sleep 1; done"); - let mut stopped_sandbox = - SandboxGuard::create_keep(&["sh", "-lc", &stopped_script], STOPPED_READY_MARKER) - .await - .expect("create Docker sandbox that will remain stopped"); - let (stop_output, stop_code) = run_cli(&["sandbox", "stop", &stopped_sandbox.name]).await; - assert_eq!(stop_code, 0, "sandbox stop should succeed:\n{stop_output}"); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_secs(30)) - .await - .expect("sandbox should be stopped before gateway restart"); - wait_for_container_running( - &namespace, - &stopped_sandbox.name, - false, - Duration::from_secs(30), - ) - .await - .expect("stopped Docker sandbox container should not be running"); - - gateway.stop().expect("stop e2e gateway"); - wait_for_container_running(&namespace, &sandbox.name, false, Duration::from_secs(30)) - .await - .expect("gateway shutdown should stop a running-intent Docker sandbox"); - - gateway.start().expect("restart e2e gateway"); - wait_for_healthy(Duration::from_mins(2)) - .await - .expect("gateway should become healthy after restart"); - wait_for_container_running(&namespace, &sandbox.name, true, Duration::from_mins(2)) - .await - .expect("gateway startup should restart the running-intent Docker sandbox container"); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_mins(2)) - .await - .expect("explicitly stopped Docker sandbox should remain stopped after restart"); - wait_for_container_running( - &namespace, - &stopped_sandbox.name, - false, - Duration::from_secs(30), - ) - .await - .expect("gateway startup should not start an explicitly stopped Docker sandbox"); - - let names = sandbox_names().await.expect("list sandboxes after restart"); - assert!( - names.contains(&sandbox.name), - "sandbox '{}' should still be listed after gateway restart. Names: {names:?}", - sandbox.name - ); - - wait_for_sandbox_exec_contains( - &sandbox.name, - &["cat", START_FILE], - "before-restart", - Duration::from_mins(4), - ) - .await - .expect("sandbox should become ready again with its state preserved"); - - sandbox.cleanup().await; - stopped_sandbox.cleanup().await; -} diff --git a/e2e/rust/tests/local_driver_token_restart.rs b/e2e/rust/tests/local_driver_token_restart.rs deleted file mode 100644 index 976bd217fd..0000000000 --- a/e2e/rust/tests/local_driver_token_restart.rs +++ /dev/null @@ -1,175 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e")] - -//! VM-driver E2E regression for sandbox bootstrap JWT material. Launch-scoped -//! bootstrap tokens must remain valid long enough for driver recovery, so -//! restarting the VM gateway reconnects the running sandbox. The Docker and -//! Podman stop-is-terminal checks live in `tests/suites/drivers`. - -use std::fs; -use std::path::PathBuf; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use base64::Engine as _; -use openshell_e2e::harness::cli::{wait_for_healthy, wait_for_sandbox_exec_contains}; -use openshell_e2e::harness::container::e2e_driver; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::sandbox::SandboxGuard; -use prost::Message; - -const READY_MARKER: &str = "local-driver-token-restart-ready"; -const VM_STATE_DIR_ENV: &str = "OPENSHELL_E2E_VM_STATE_DIR"; - -#[derive(Clone, PartialEq, Message)] -struct PersistedDriverSandbox { - #[prost(string, tag = "2")] - name: String, - #[prost(message, optional, tag = "4")] - spec: Option, -} - -#[derive(Clone, PartialEq, Message)] -struct PersistedDriverSandboxSpec { - #[prost(string, tag = "11")] - sandbox_token: String, -} - -fn read_vm_bootstrap_token(sandbox_name: &str) -> Result { - let state_dir = std::env::var_os(VM_STATE_DIR_ENV) - .map(PathBuf::from) - .ok_or_else(|| format!("{VM_STATE_DIR_ENV} must be set for VM restart coverage"))?; - let sandboxes_dir = state_dir.join("sandboxes"); - let entries = fs::read_dir(&sandboxes_dir) - .map_err(|err| format!("read VM sandboxes dir '{}': {err}", sandboxes_dir.display()))?; - - let mut decoded_names = Vec::new(); - for entry in entries { - let entry = entry.map_err(|err| { - format!( - "read VM sandbox dir entry under '{}': {err}", - sandboxes_dir.display() - ) - })?; - let request_path = entry.path().join("sandbox.pb"); - let bytes = match fs::read(&request_path) { - Ok(bytes) => bytes, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue, - Err(err) => { - return Err(format!( - "read VM sandbox request '{}': {err}", - request_path.display() - )); - } - }; - - let sandbox = PersistedDriverSandbox::decode(bytes.as_slice()).map_err(|err| { - format!( - "decode VM sandbox request '{}': {err}", - request_path.display() - ) - })?; - decoded_names.push(sandbox.name.clone()); - if sandbox.name != sandbox_name { - continue; - } - - let spec = sandbox - .spec - .ok_or_else(|| format!("VM sandbox '{sandbox_name}' is missing driver spec"))?; - if spec.sandbox_token.trim().is_empty() { - return Err(format!( - "VM sandbox '{sandbox_name}' persisted driver spec has no sandbox token" - )); - } - return Ok(spec.sandbox_token); - } - - Err(format!( - "no VM sandbox request found for '{sandbox_name}' under '{}'. Decoded sandbox names: {decoded_names:?}", - sandboxes_dir.display() - )) -} - -fn token_exp_claim(token: &str) -> Result { - let payload_b64 = token - .trim() - .split('.') - .nth(1) - .ok_or_else(|| "sandbox JWT has no payload segment".to_string())?; - let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD - .decode(payload_b64) - .map_err(|err| format!("failed to decode sandbox JWT payload: {err}"))?; - let claims: serde_json::Value = serde_json::from_slice(&payload) - .map_err(|err| format!("failed to parse sandbox JWT claims: {err}"))?; - claims - .get("exp") - .and_then(serde_json::Value::as_i64) - .ok_or_else(|| format!("sandbox JWT missing integer exp claim: {claims}")) -} - -fn require_unexpired_token(token: &str, context: &str) -> Result<(), String> { - let exp = token_exp_claim(token)?; - let now = i64::try_from( - SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(|err| format!("system clock is before Unix epoch: {err}"))? - .as_secs(), - ) - .map_err(|_| "current Unix timestamp does not fit in i64".to_string())?; - // Sandbox session tokens use exp=0 when no TTL is configured. - if exp != 0 && exp <= now { - return Err(format!( - "{context} should expire in the future, got exp={exp}, now={now}" - )); - } - Ok(()) -} - -async fn restart_vm_sandbox(gateway: &ManagedGateway, sandbox_name: &str) -> Result<(), String> { - let token = read_vm_bootstrap_token(sandbox_name)?; - require_unexpired_token(&token, "VM bootstrap JWT")?; - - gateway.stop()?; - gateway.start()?; - wait_for_healthy(Duration::from_mins(2)).await -} - -#[tokio::test] -async fn vm_gateway_restart_reconnects_sandbox() { - if e2e_driver().as_deref() != Some("vm") { - eprintln!("Skipping VM driver restart test: e2e driver is not VM"); - return; - } - let Some(gateway) = ManagedGateway::from_env().expect("load managed e2e gateway metadata") - else { - eprintln!( - "Skipping VM driver restart test: VM e2e gateway is not managed by this test run" - ); - return; - }; - - wait_for_healthy(Duration::from_secs(30)) - .await - .expect("gateway should start healthy"); - - let script = format!("echo {READY_MARKER}; while true; do sleep 1; done"); - let mut sandbox = SandboxGuard::create_keep(&["sh", "-lc", &script], READY_MARKER) - .await - .expect("create long-running VM sandbox"); - - restart_vm_sandbox(&gateway, &sandbox.name) - .await - .expect("restart e2e VM gateway"); - wait_for_sandbox_exec_contains( - &sandbox.name, - &["echo", "vm-reconnect-ok"], - "vm-reconnect-ok", - Duration::from_mins(4), - ) - .await - .expect("sandbox supervisor should reconnect after VM driver restart"); - - sandbox.cleanup().await; -} diff --git a/e2e/rust/tests/podman_gateway_start.rs b/e2e/rust/tests/podman_gateway_start.rs deleted file mode 100644 index 907f9c71b4..0000000000 --- a/e2e/rust/tests/podman_gateway_start.rs +++ /dev/null @@ -1,205 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e-podman")] - -//! Podman-specific E2E coverage for stopping and starting sandboxes across a -//! standalone gateway restart. - -use std::process::{Command, Stdio}; -use std::time::Duration; - -use openshell_e2e::harness::cli::{ - run_cli, sandbox_names, wait_for_healthy, wait_for_sandbox_exec_contains, - wait_for_sandbox_phase, -}; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::sandbox::SandboxGuard; -use tokio::time::sleep; - -const READY_MARKER: &str = "podman-gateway-start-ready"; -const STOPPED_READY_MARKER: &str = "podman-gateway-start-stopped-ready"; -const START_FILE: &str = "/sandbox/podman-gateway-start-state"; -const MANAGED_BY_LABEL_FILTER: &str = "label=openshell.managed=true"; -const SANDBOX_NAME_LABEL: &str = "openshell.ai/sandbox-name"; - -/// Build a `podman` command that targets the same API socket the gateway uses. -/// -/// The e2e harness (`e2e/with-podman-gateway.sh`) exports -/// `OPENSHELL_PODMAN_SOCKET` (discovered via `podman machine inspect` on macOS, -/// or the rootless socket on Linux) and also clobbers `XDG_CONFIG_HOME` with an -/// empty directory to isolate CLI/SDK gateway metadata. On macOS the podman -/// client resolves its VM connection through `XDG_CONFIG_HOME`, so a bare -/// `podman ps` here falls back to a nonexistent native rootless socket and -/// fails. Pinning `--url` to the exported socket bypasses connection-config -/// resolution entirely and mirrors the shell's `podman_cmd` helper. -/// -/// When `OPENSHELL_PODMAN_SOCKET` is unset (e.g. running this test outside the -/// harness), fall back to plain `podman`, leaving Linux behavior unchanged. -fn podman_command() -> Command { - let mut command = Command::new("podman"); - if let Ok(socket) = std::env::var("OPENSHELL_PODMAN_SOCKET") - && !socket.is_empty() - { - command.arg("--url").arg(format!("unix://{socket}")); - } - command -} - -fn sandbox_container_running(sandbox_name: &str) -> Result { - let sandbox_name_filter = format!("label={SANDBOX_NAME_LABEL}={sandbox_name}"); - let output = podman_command() - .args([ - "ps", - "-aq", - "--filter", - MANAGED_BY_LABEL_FILTER, - "--filter", - "label=openshell.ai/isolation-role=sandbox", - "--filter", - ]) - .arg(sandbox_name_filter) - .stdout(Stdio::piped()) - .stderr(Stdio::piped()) - .output() - .map_err(|err| format!("failed to run podman ps: {err}"))?; - if !output.status.success() { - return Err(format!( - "podman ps failed: {}{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )); - } - let ids = String::from_utf8_lossy(&output.stdout) - .lines() - .map(str::trim) - .filter(|line| !line.is_empty()) - .map(str::to_string) - .collect::>(); - let [container_id] = ids.as_slice() else { - return Err(format!( - "expected one Podman container for sandbox '{sandbox_name}', found {ids:?}" - )); - }; - let output = podman_command() - .args(["inspect", "-f", "{{.State.Running}}", container_id]) - .output() - .map_err(|err| format!("failed to run podman inspect: {err}"))?; - if !output.status.success() { - return Err(format!( - "podman inspect failed: {}{}", - String::from_utf8_lossy(&output.stdout), - String::from_utf8_lossy(&output.stderr) - )); - } - match String::from_utf8_lossy(&output.stdout).trim() { - "true" => Ok(true), - "false" => Ok(false), - state => Err(format!("unexpected Podman running state: {state}")), - } -} - -async fn wait_for_container_running( - sandbox_name: &str, - expected: bool, - timeout: Duration, -) -> Result<(), String> { - let start = std::time::Instant::now(); - let mut last_state; - loop { - match sandbox_container_running(sandbox_name) { - Ok(running) if running == expected => return Ok(()), - Ok(running) => last_state = format!("running={running}"), - Err(err) => last_state = err, - } - if start.elapsed() > timeout { - return Err(format!( - "Podman container for '{sandbox_name}' did not reach running={expected}: {last_state}" - )); - } - sleep(Duration::from_secs(1)).await; - } -} - -#[tokio::test] -async fn podman_gateway_restart_preserves_running_and_stopped_intent() { - if std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("podman") { - eprintln!("Skipping Podman gateway start test: e2e driver is not podman"); - return; - } - let Some(gateway) = ManagedGateway::from_env().expect("load managed e2e gateway metadata") - else { - eprintln!( - "Skipping Podman gateway start test: e2e gateway is not managed by this test run" - ); - return; - }; - - wait_for_healthy(Duration::from_secs(30)) - .await - .expect("gateway should start healthy"); - - let script = format!( - "echo before-restart > {START_FILE}; echo {READY_MARKER}; while true; do sleep 1; done" - ); - let mut sandbox = SandboxGuard::create_keep(&["sh", "-lc", &script], READY_MARKER) - .await - .expect("create long-running Podman sandbox"); - wait_for_container_running(&sandbox.name, true, Duration::from_mins(1)) - .await - .expect("Podman sandbox container should initially be running"); - - let before_restart = sandbox - .exec(&["cat", START_FILE]) - .await - .expect("read Podman sandbox state before restart"); - assert!( - before_restart.contains("before-restart"), - "sandbox state was not written before restart:\n{before_restart}" - ); - - let stopped_script = format!("echo {STOPPED_READY_MARKER}; while true; do sleep 1; done"); - let mut stopped_sandbox = - SandboxGuard::create_keep(&["sh", "-lc", &stopped_script], STOPPED_READY_MARKER) - .await - .expect("create Podman sandbox that will remain stopped"); - let (stop_output, stop_code) = run_cli(&["sandbox", "stop", &stopped_sandbox.name]).await; - assert_eq!(stop_code, 0, "sandbox stop should succeed:\n{stop_output}"); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_mins(2)) - .await - .expect("Podman sandbox should be stopped before gateway restart"); - - gateway.stop().expect("stop e2e gateway"); - wait_for_container_running(&sandbox.name, false, Duration::from_mins(1)) - .await - .expect("gateway shutdown should stop the running-intent Podman sandbox"); - gateway.start().expect("restart e2e gateway"); - wait_for_healthy(Duration::from_mins(2)) - .await - .expect("gateway should become healthy after restart"); - wait_for_container_running(&sandbox.name, true, Duration::from_mins(2)) - .await - .expect("gateway startup should restart the running-intent Podman sandbox"); - - let names = sandbox_names().await.expect("list sandboxes after restart"); - assert!( - names.contains(&sandbox.name), - "sandbox '{}' should still be listed after gateway restart. Names: {names:?}", - sandbox.name - ); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_mins(2)) - .await - .expect("explicitly stopped Podman sandbox should remain stopped after restart"); - - wait_for_sandbox_exec_contains( - &sandbox.name, - &["cat", START_FILE], - "before-restart", - Duration::from_mins(4), - ) - .await - .expect("Podman sandbox should become ready again with its state preserved"); - - sandbox.cleanup().await; - stopped_sandbox.cleanup().await; -} diff --git a/e2e/rust/tests/vm_gateway_start.rs b/e2e/rust/tests/vm_gateway_start.rs deleted file mode 100644 index 9c785a46cb..0000000000 --- a/e2e/rust/tests/vm_gateway_start.rs +++ /dev/null @@ -1,165 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e-vm")] - -//! VM-specific E2E coverage for starting sandboxes after a standalone gateway -//! restart. -//! -//! This test is gated behind the `e2e-vm` feature because it requires the VM -//! driver runtime prepared by `e2e/rust/e2e-vm.sh`. - -use std::fs; -use std::path::PathBuf; -use std::time::Duration; - -use openshell_e2e::harness::cli::{ - run_cli, sandbox_names, wait_for_healthy, wait_for_sandbox_exec_contains, - wait_for_sandbox_phase, -}; -use openshell_e2e::harness::gateway::ManagedGateway; -use openshell_e2e::harness::sandbox::SandboxGuard; -use prost::Message; -use tokio::time::sleep; - -const READY_MARKER: &str = "vm-gateway-start-ready"; -const STOPPED_READY_MARKER: &str = "vm-gateway-start-stopped-ready"; -const START_FILE: &str = "/sandbox/vm-gateway-start-state"; -const VM_STATE_DIR_ENV: &str = "OPENSHELL_E2E_VM_STATE_DIR"; - -#[derive(Clone, PartialEq, Message)] -struct PersistedDriverSandbox { - #[prost(string, tag = "2")] - name: String, -} - -fn vm_sandbox_stopped(sandbox_name: &str) -> Result { - let state_dir = std::env::var_os(VM_STATE_DIR_ENV) - .map(PathBuf::from) - .ok_or_else(|| format!("{VM_STATE_DIR_ENV} must be set"))?; - let sandboxes_dir = state_dir.join("sandboxes"); - for entry in fs::read_dir(&sandboxes_dir) - .map_err(|err| format!("read '{}': {err}", sandboxes_dir.display()))? - { - let path = entry - .map_err(|err| format!("read VM sandbox entry: {err}"))? - .path(); - let request_path = path.join("sandbox.pb"); - let bytes = match fs::read(&request_path) { - Ok(bytes) => bytes, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue, - Err(err) => return Err(format!("read '{}': {err}", request_path.display())), - }; - let sandbox = PersistedDriverSandbox::decode(bytes.as_slice()) - .map_err(|err| format!("decode '{}': {err}", request_path.display()))?; - if sandbox.name == sandbox_name { - return Ok(path.join("stopped").exists()); - } - } - Err(format!( - "VM state for sandbox '{sandbox_name}' was not found" - )) -} - -async fn wait_for_vm_stopped_marker( - sandbox_name: &str, - expected: bool, - timeout: Duration, -) -> Result<(), String> { - let start = std::time::Instant::now(); - let mut last_state; - loop { - match vm_sandbox_stopped(sandbox_name) { - Ok(stopped) if stopped == expected => return Ok(()), - Ok(stopped) => last_state = format!("stopped={stopped}"), - Err(err) => last_state = err, - } - if start.elapsed() > timeout { - return Err(format!( - "VM '{sandbox_name}' did not reach stopped={expected}: {last_state}" - )); - } - sleep(Duration::from_secs(1)).await; - } -} - -#[tokio::test] -async fn vm_gateway_restart_preserves_running_and_stopped_intent() { - if std::env::var("OPENSHELL_E2E_DRIVER").as_deref() != Ok("vm") { - eprintln!("Skipping VM gateway start test: e2e driver is not vm"); - return; - } - let Some(gateway) = ManagedGateway::from_env().expect("load managed e2e gateway metadata") - else { - eprintln!("Skipping VM gateway start test: e2e gateway is not managed by this test run"); - return; - }; - - wait_for_healthy(Duration::from_secs(30)) - .await - .expect("gateway should start healthy"); - - // The gateway restart terminates the VM process before re-adopting its - // overlay. Flush the marker before reporting readiness so the assertion - // verifies durable overlay state rather than guest page-cache timing. - let script = format!( - "echo before-restart > {START_FILE}; sync; echo {READY_MARKER}; while true; do sleep 1; done" - ); - let mut sandbox = SandboxGuard::create_keep(&["sh", "-lc", &script], READY_MARKER) - .await - .expect("create long-running VM sandbox"); - - let before_restart = sandbox - .exec(&["cat", START_FILE]) - .await - .expect("read VM sandbox state before restart"); - assert!( - before_restart.contains("before-restart"), - "VM sandbox state was not written before restart:\n{before_restart}" - ); - - let stopped_script = format!("echo {STOPPED_READY_MARKER}; while true; do sleep 1; done"); - let mut stopped_sandbox = - SandboxGuard::create_keep(&["sh", "-lc", &stopped_script], STOPPED_READY_MARKER) - .await - .expect("create VM sandbox that will remain stopped"); - let (stop_output, stop_code) = run_cli(&["sandbox", "stop", &stopped_sandbox.name]).await; - assert_eq!(stop_code, 0, "sandbox stop should succeed:\n{stop_output}"); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_mins(2)) - .await - .expect("VM sandbox should be stopped before gateway restart"); - - gateway.stop().expect("stop e2e gateway"); - wait_for_vm_stopped_marker(&sandbox.name, true, Duration::from_mins(1)) - .await - .expect("gateway shutdown should stop the running-intent VM through its driver"); - gateway.start().expect("restart e2e gateway"); - wait_for_healthy(Duration::from_mins(2)) - .await - .expect("gateway should become healthy after restart"); - wait_for_vm_stopped_marker(&sandbox.name, false, Duration::from_mins(2)) - .await - .expect("gateway startup should restart the running-intent VM"); - - let names = sandbox_names().await.expect("list sandboxes after restart"); - assert!( - names.contains(&sandbox.name), - "sandbox '{}' should still be listed after gateway restart. Names: {names:?}", - sandbox.name - ); - wait_for_sandbox_phase(&stopped_sandbox.name, "Stopped", Duration::from_mins(2)) - .await - .expect("explicitly stopped VM sandbox should remain stopped after restart"); - - wait_for_sandbox_exec_contains( - &sandbox.name, - &["cat", START_FILE], - "before-restart", - Duration::from_mins(4), - ) - .await - .expect("VM sandbox should become ready again with its overlay state preserved"); - - sandbox.cleanup().await; - stopped_sandbox.cleanup().await; -} diff --git a/e2e/support/continuity.sh b/e2e/support/continuity.sh new file mode 100644 index 0000000000..bae757f9ba --- /dev/null +++ b/e2e/support/continuity.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 + +# Run one phase of the continuity suite (tests/suites/continuity) against an +# already configured e2e gateway, for host lanes that restart their own +# gateway between the phases. The caller sets CONTINUITY_RUN_ID to the same +# value for both phases. + +# Run every scenario's `seed` or `verify` test with nextest. +e2e_run_continuity_phase() ( + local phase=$1 + local root + root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)" + + e2e_require_openshell_bin || return + if [ -z "${CONTINUITY_RUN_ID:-}" ]; then + echo "ERROR: CONTINUITY_RUN_ID must be set for both continuity phases" >&2 + return 2 + fi + + echo "==> Running continuity ${phase} tests (run ${CONTINUITY_RUN_ID})" + cargo-nextest nextest run --locked \ + --manifest-path "${root}/tests/suites/continuity/Cargo.toml" \ + --config-file "${root}/tests/runner/src/program-nextest.toml" \ + --profile openshell --no-tests fail \ + -E "test(/::${phase}\$/)" +) diff --git a/tests/suites/continuity/Cargo.lock b/tests/suites/continuity/Cargo.lock index f031bc1b57..603422f057 100644 --- a/tests/suites/continuity/Cargo.lock +++ b/tests/suites/continuity/Cargo.lock @@ -532,6 +532,7 @@ version = "0.0.0" dependencies = [ "openshell-testkit", "tokio", + "vm-support", ] [[package]] @@ -4395,6 +4396,17 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vm-support" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "openshell-core", + "openshell-testkit", + "prost", + "serde_json", +] + [[package]] name = "vte" version = "0.14.1" diff --git a/tests/suites/continuity/Cargo.toml b/tests/suites/continuity/Cargo.toml index 785102ad6f..60d45f5a2c 100644 --- a/tests/suites/continuity/Cargo.toml +++ b/tests/suites/continuity/Cargo.toml @@ -15,5 +15,6 @@ publish = false [dependencies] openshell-testkit = { path = "../../testkit/testkit" } tokio = { version = "1", features = ["time"] } +vm-support = { path = "../../support/vm" } [workspace] diff --git a/tests/suites/continuity/src/lib.rs b/tests/suites/continuity/src/lib.rs index 678290eaf2..46bd3e0dbc 100644 --- a/tests/suites/continuity/src/lib.rs +++ b/tests/suites/continuity/src/lib.rs @@ -15,6 +15,7 @@ //! through the CLI, which testkit doesn't track, and `verify` adopts them so //! its own cleanup removes them. +mod sandbox_intent; mod sandbox_workspace; mod scenario; diff --git a/tests/suites/continuity/src/sandbox_intent.rs b/tests/suites/continuity/src/sandbox_intent.rs new file mode 100644 index 0000000000..40a478c885 --- /dev/null +++ b/tests/suites/continuity/src/sandbox_intent.rs @@ -0,0 +1,201 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! A disruption keeps each sandbox's running or stopped intent. +//! +//! Every disruption restarts the gateway, and a gateway that shuts down stops +//! the sandboxes it runs. When it comes back, it starts the running sandbox +//! again, so that sandbox's processes start after `seed`, with the same SSH +//! host key. It leaves the stopped sandbox stopped. + +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use testkit::sdk::SandboxPhase; +use testkit::{Context, Poll, ResultExt as _}; + +use crate::scenario::{create_and_run, name}; + +/// The time `seed` ran, in seconds since the epoch on the sandbox's clock, +/// and the sandbox's SSH host key fingerprint, one per line. +const MARKER: &str = "/sandbox/.continuity-intent"; +const STOP_TIMEOUT: Duration = Duration::from_secs(120); + +/// Creates a running sandbox that records when `seed` ran and its host key, +/// and a sandbox that is stopped. +#[testkit::test] +async fn seed(cx: &mut Context) -> testkit::Result { + let (running, stopped) = (name("run")?, name("stop")?); + create_and_run(cx, &stopped, "true").await?; + cx.cli(["sandbox", "stop", &stopped]) + .await? + .success() + .context("stop the sandbox")?; + testkit::poll_until( + &format!("sandbox {stopped} to be Stopped"), + STOP_TIMEOUT, + Duration::from_secs(2), + async || { + let phase = cx.client().get_sandbox(&stopped).await?.phase; + Ok(if phase == SandboxPhase::Stopped { + Poll::Ready(()) + } else { + Poll::Pending(format!("phase {phase:?}")) + }) + }, + ) + .await?; + + create_and_run(cx, &running, "true").await?; + let fingerprint = host_key(cx, &running).await?; + let record = + format!("printf '%s\\n%s\\n' \"$(date +%s)\" '{fingerprint}' > '{MARKER}' && sync"); + cx.cli([ + "sandbox", "exec", "--name", &running, "--no-tty", "--", "sh", "-c", &record, + ]) + .await? + .success() + .context("record the seed time and host key")?; + Ok(()) +} + +/// The running sandbox's processes started after `seed`, it kept its host +/// key, and the stopped sandbox is still stopped. +#[testkit::test] +async fn verify(cx: &mut Context) -> testkit::Result { + // Adopting tracks the sandboxes, so cleanup deletes them after this test. + let running = cx + .adopt(&name("run")?) + .await + .context("find the running sandbox")?; + let stopped = cx + .adopt(&name("stop")?) + .await + .context("find the stopped sandbox")?; + running.wait_ready().await?; + + // The marker, the kernel's boot time, the clock tick rate, and the stat + // line of the sandbox's first process. + let script = format!( + "cat '{MARKER}' && grep '^btime ' /proc/stat \ + && (getconf CLK_TCK 2>/dev/null || echo 100) && cat /proc/1/stat" + ); + let probe = running.exec(["sh", "-c", &script]).await?.success()?; + let observed = + Probe::parse(&probe.stdout).context(format!("read the probe output {:?}", probe.stdout))?; + testkit::ensure!( + observed.started > observed.seeded, + "sandbox {} has run since {}, before seed recorded {}: the disruption didn't restart it", + running.name(), + observed.started, + observed.seeded + ); + let fingerprint = host_key(cx, running.name()).await?; + testkit::ensure!( + fingerprint == observed.fingerprint, + "sandbox {}'s host key changed from {} to {fingerprint}", + running.name(), + observed.fingerprint + ); + + // The running sandbox is ready, so the gateway has reconciled both. + let phase = stopped.get().await?.phase; + testkit::ensure!( + phase == SandboxPhase::Stopped, + "sandbox {} was stopped before the disruption and is {phase:?} after it", + stopped.name() + ); + + if cx.compute_driver().await? == "vm" { + let state = vm_support::StateDir::from_env()?; + let expiry = vm_support::token_expiry(&state.sandbox_token(running.name())?)?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|err| testkit::Error::msg(format!("read the clock: {err}")))? + .as_secs(); + // A token without a lifetime has exp 0. + testkit::ensure!( + expiry == 0 || expiry > now, + "the VM driver relaunched sandbox {} with a token that expired at {expiry}; now is {now}", + running.name() + ); + } + Ok(()) +} + +/// The sandbox's SSH host key fingerprint. +async fn host_key(cx: &Context, sandbox: &str) -> testkit::Result { + cx.client() + .get_sandbox(sandbox) + .await + .context(format!("get sandbox {sandbox}"))? + .host_key_fingerprint + .ok_or_else(|| { + testkit::Error::msg(format!("sandbox {sandbox} has no host key fingerprint")) + }) +} + +/// What `verify`'s probe printed, with times in seconds since the epoch. +#[derive(Debug, PartialEq)] +struct Probe { + seeded: u64, + fingerprint: String, + /// When the sandbox's first process started. + started: u64, +} + +impl Probe { + fn parse(output: &str) -> testkit::Result { + let mut lines = output.lines(); + let mut next = |what: &str| { + lines + .next() + .ok_or_else(|| testkit::Error::msg(format!("no {what} line"))) + }; + let seeded = number(next("seed time")?)?; + let fingerprint = next("fingerprint")?.to_string(); + let boot = number( + next("btime")? + .strip_prefix("btime ") + .ok_or_else(|| testkit::Error::msg("the btime line has no btime prefix"))?, + )?; + let ticks_per_second = number(next("clock tick")?)?; + testkit::ensure!(ticks_per_second > 0, "the clock tick rate is 0"); + // The command name in field 2 may hold spaces, so count fields after + // its closing parenthesis. The start time is field 22. + let stat = next("stat")?; + let start_ticks = stat + .rsplit_once(')') + .and_then(|(_, rest)| rest.split_whitespace().nth(19)) + .ok_or_else(|| testkit::Error::msg(format!("no start time in {stat:?}")))?; + let started = boot + number(start_ticks)? / ticks_per_second; + Ok(Self { + seeded, + fingerprint, + started, + }) + } +} + +fn number(text: &str) -> testkit::Result { + text.trim() + .parse() + .map_err(|err| testkit::Error::msg(format!("{text:?} is not a number: {err}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_when_the_first_process_started() { + let output = "1700000000\nSHA256:abc\nbtime 1699990000\n100\n\ + 1 (openshell sandbox) S 0 1 1 0 -1 4194560 0 0 0 0 0 0 0 0 20 0 1 0 1500000 0 0\n"; + assert_eq!( + Probe::parse(output).unwrap(), + Probe { + seeded: 1_700_000_000, + fingerprint: "SHA256:abc".to_string(), + started: 1_700_005_000, + } + ); + } +} diff --git a/tests/suites/continuity/src/sandbox_workspace.rs b/tests/suites/continuity/src/sandbox_workspace.rs index f05827670f..302b4d5583 100644 --- a/tests/suites/continuity/src/sandbox_workspace.rs +++ b/tests/suites/continuity/src/sandbox_workspace.rs @@ -3,46 +3,19 @@ //! A sandbox and its workspace survive a disruption. -use std::time::Duration; - use testkit::{Context, ResultExt as _}; -use crate::scenario::{id, name}; +use crate::scenario::{create_and_run, id, name}; const MARKER: &str = "/sandbox/.continuity-marker"; -const READY_TIMEOUT: Duration = Duration::from_secs(120); /// Creates a sandbox, waits until it runs commands, and writes the run id to a /// file in its workspace. #[testkit::test] async fn seed(cx: &mut Context) -> testkit::Result { let (sandbox, id) = (name("ws")?, id()?); - // Created through the CLI, which testkit doesn't track, so it outlives - // this test. - cx.cli([ - "sandbox", "create", "--name", &sandbox, "--detach", "--", "sleep", "infinity", - ]) - .await? - .success() - .context("create the sandbox")?; - let write = format!("printf '%s\\n' '{id}' > '{MARKER}' && sync"); - let deadline = tokio::time::Instant::now() + READY_TIMEOUT; - loop { - let out = cx - .cli([ - "sandbox", "exec", "--name", &sandbox, "--no-tty", "--", "sh", "-c", &write, - ]) - .await?; - if out.success().is_ok() { - return Ok(()); - } - testkit::ensure!( - tokio::time::Instant::now() < deadline, - "sandbox {sandbox} did not run a command within {READY_TIMEOUT:?}" - ); - tokio::time::sleep(Duration::from_secs(2)).await; - } + create_and_run(cx, &sandbox, &write).await } /// The sandbox is still listed and ready, its file is intact, and a sandbox diff --git a/tests/suites/continuity/src/scenario.rs b/tests/suites/continuity/src/scenario.rs index c9705124cf..71ac016f0c 100644 --- a/tests/suites/continuity/src/scenario.rs +++ b/tests/suites/continuity/src/scenario.rs @@ -3,12 +3,17 @@ //! What a scenario's `seed` and `verify` share. -use testkit::Result; +use std::time::Duration; + +use testkit::{Context, Result, ResultExt as _}; /// The variable the runner sets to the id shared by one run's `seed` and /// `verify` tests. pub const ID_ENV: &str = "CONTINUITY_RUN_ID"; +/// How long a sandbox `seed` creates may take to run a command. +const READY_TIMEOUT: Duration = Duration::from_secs(120); + /// The id of this run. Fails when the tests were not started by the runner's /// `--disruption` mode, because a `seed` without a `verify` proves nothing. pub fn id() -> Result { @@ -26,3 +31,32 @@ pub fn id() -> Result { pub fn name(suffix: &str) -> Result { Ok(format!("cont-{}-{suffix}", id()?)) } + +/// Create a long-running sandbox through the CLI, which testkit doesn't +/// track, so it outlives `seed`, and run `script` in it once it runs +/// commands. +pub async fn create_and_run(cx: &Context, sandbox: &str, script: &str) -> Result { + cx.cli([ + "sandbox", "create", "--name", sandbox, "--detach", "--", "sleep", "infinity", + ]) + .await? + .success() + .context(format!("create sandbox {sandbox}"))?; + + let deadline = tokio::time::Instant::now() + READY_TIMEOUT; + loop { + let out = cx + .cli([ + "sandbox", "exec", "--name", sandbox, "--no-tty", "--", "sh", "-c", script, + ]) + .await?; + if out.success().is_ok() { + return Ok(()); + } + testkit::ensure!( + tokio::time::Instant::now() < deadline, + "sandbox {sandbox} did not run a command within {READY_TIMEOUT:?}" + ); + tokio::time::sleep(Duration::from_secs(2)).await; + } +} diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 49f0bc8fcb..5d4092dc5a 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -4766,6 +4766,17 @@ version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" +[[package]] +name = "vm-support" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "openshell-core", + "openshell-testkit", + "prost", + "serde_json", +] + [[package]] name = "vte" version = "0.14.1" diff --git a/tests/support/vm/Cargo.toml b/tests/support/vm/Cargo.toml new file mode 100644 index 0000000000..c6599d50fe --- /dev/null +++ b/tests/support/vm/Cargo.toml @@ -0,0 +1,18 @@ +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "vm-support" +description = "Access to the VM driver's sandbox state, for test suites" +version = "0.0.0" +edition = "2024" +rust-version = "1.95" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[dependencies] +base64 = "0.22" +openshell-core = { path = "../../../crates/openshell-core", default-features = false } +openshell-testkit = { path = "../../testkit/testkit" } +prost = "0.14" +serde_json = "1" diff --git a/tests/support/vm/src/lib.rs b/tests/support/vm/src/lib.rs new file mode 100644 index 0000000000..f208d4d988 --- /dev/null +++ b/tests/support/vm/src/lib.rs @@ -0,0 +1,102 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! The VM driver's sandbox state, for checks the gateway API can't make. +//! +//! The VM driver keeps each sandbox's request under +//! `/sandboxes//sandbox.pb`. The environment names the state +//! directory in `OPENSHELL_TEST_VM_STATE_DIR`, and the test must run as the +//! user that owns it. `e2e/rust/e2e-vm.sh` sets it. A missing variable fails +//! the test; it never skips it. + +use std::path::PathBuf; + +use base64::Engine as _; +use openshell_core::proto::compute::v1::DriverSandbox; +use prost::Message as _; +use testkit::{Error, Result, ResultExt as _}; + +pub const STATE_DIR_ENV: &str = "OPENSHELL_TEST_VM_STATE_DIR"; + +/// The VM driver's state directory. +#[derive(Clone, Debug)] +pub struct StateDir(PathBuf); + +impl StateDir { + /// Read [`STATE_DIR_ENV`]. + pub fn from_env() -> Result { + testkit::required_env(STATE_DIR_ENV, "the VM driver's state directory") + .map(|dir| Self(dir.into())) + } + + /// The request the driver keeps for sandbox `name`. + pub fn sandbox(&self, name: &str) -> Result { + let dir = self.0.join("sandboxes"); + let entries = std::fs::read_dir(&dir).context(format!("read {}", dir.display()))?; + let mut names = Vec::new(); + for entry in entries { + let path = entry + .context(format!("read {}", dir.display()))? + .path() + .join("sandbox.pb"); + let bytes = match std::fs::read(&path) { + Ok(bytes) => bytes, + Err(err) if err.kind() == std::io::ErrorKind::NotFound => continue, + Err(err) => return Err(Error::msg(format!("read {}: {err}", path.display()))), + }; + let sandbox = DriverSandbox::decode(bytes.as_slice()) + .map_err(|err| Error::msg(format!("decode {}: {err}", path.display())))?; + if sandbox.name == name { + return Ok(sandbox); + } + names.push(sandbox.name); + } + Err(Error::msg(format!( + "no VM sandbox {name} under {}; found {names:?}", + dir.display() + ))) + } + + /// The bootstrap token the driver launches sandbox `name` with. + pub fn sandbox_token(&self, name: &str) -> Result { + let token = self + .sandbox(name)? + .spec + .map(|spec| spec.sandbox_token) + .unwrap_or_default(); + testkit::ensure!( + !token.trim().is_empty(), + "VM sandbox {name} has no sandbox token" + ); + Ok(token) + } +} + +/// The `exp` claim of JWT `token`, unverified. A token without a lifetime has +/// 0. +pub fn token_expiry(token: &str) -> Result { + let payload = token + .trim() + .split('.') + .nth(1) + .ok_or_else(|| Error::msg("the token has no payload"))?; + let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD + .decode(payload) + .map_err(|err| Error::msg(format!("decode the token payload: {err}")))?; + let claims: serde_json::Value = + serde_json::from_slice(&payload).context("parse the token claims")?; + claims["exp"] + .as_u64() + .ok_or_else(|| Error::msg(format!("the token has no numeric exp claim: {claims}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_the_expiry_claim() { + let payload = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(br#"{"exp":42}"#); + assert_eq!(token_expiry(&format!("h.{payload}.s")).unwrap(), 42); + assert!(token_expiry("no-payload").is_err()); + } +} diff --git a/tests/tmachine/artifacts.nix b/tests/tmachine/artifacts.nix index 9f09e539ad..385fc32582 100644 --- a/tests/tmachine/artifacts.nix +++ b/tests/tmachine/artifacts.nix @@ -86,19 +86,15 @@ let # entry says what it needs. Entries marked "wrapper lane" still run in the # wrapper-based Podman lane (`mise run e2e:podman:ci`), so they are covered # there until tmachine provides what they need. - podmanE2eFollowUpBinaries = [ - # Holds only the VM gateway restart test, which skips on Podman. - "local_driver_token_restart" - # Self-skips without wrapper-owned gateway metadata (restart and - # configuration control), so exclude it rather than report false passes. - # Wrapper lane. - "podman_gateway_start" - ]; + podmanE2eFollowUpBinaries = [ ]; podmanE2eArchiveFilter = let excludedBinaries = map (binary: "binary(=${binary})") podmanE2eFollowUpBinaries; in - "kind(test) and not (${pkgs.lib.concatStringsSep " or " excludedBinaries})"; + if excludedBinaries == [ ] then + "kind(test)" + else + "kind(test) and not (${pkgs.lib.concatStringsSep " or " excludedBinaries})"; podmanE2eCiTests = pkgs.writeShellApplication { name = "generate-podman-e2e-ci-tests"; From 6637f32e7ed8bf1874516e9304d1b3ea5fddff40 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 4 Dec 2026 09:28:59 -0800 Subject: [PATCH 05/10] test(continuity): fix VM driver detection and honor unsupported entries The VM driver reports its name as openshell-driver-vm, so sandbox_intent::verify checks the configured driver name directly. Continuity tests now honor OPENSHELL_TEST_UNSUPPORTED, and sandbox_intent::verify is unsupported on fedora-podman-rootless/rpm-upgrade-source until #6242 is fixed. Signed-off-by: Matthew Grossman --- tasks/scripts/check-conformance-program.sh | 3 ++- tests/suites/continuity/src/sandbox_intent.rs | 10 +++++++++- tests/suites/unsupported.yaml | 11 ++++++++++- tests/testkit/README.md | 15 +++++++++------ tests/testkit/testkit-macros/src/lib.rs | 9 ++++++++- tests/testkit/testkit/src/lib.rs | 1 + tests/testkit/testkit/src/program/mod.rs | 4 +++- tests/testkit/testkit/src/program/unsupported.rs | 13 +++++++++++++ 8 files changed, 55 insertions(+), 11 deletions(-) diff --git a/tasks/scripts/check-conformance-program.sh b/tasks/scripts/check-conformance-program.sh index ca8edaa8f6..a7acc9ea77 100755 --- a/tasks/scripts/check-conformance-program.sh +++ b/tasks/scripts/check-conformance-program.sh @@ -20,7 +20,8 @@ trap 'rm -rf "${work}"' EXIT # Cargo metadata includes auto-discovered integration targets, but not their # harness settings. Check the manifest for the explicit opt-out. # The conformance binary registers tests from its library, not its own crate. -printf '%s\n' conformance > "${work}/crates" +# Libtest runs the continuity crate's tests. +printf '%s\n' conformance continuity > "${work}/crates" for manifest in "${manifests[@]}"; do # shellcheck disable=SC2016 # $manifest inside the yq expression is a yq variable. cargo metadata --locked --no-deps --format-version 1 --manifest-path "${manifest}" \ diff --git a/tests/suites/continuity/src/sandbox_intent.rs b/tests/suites/continuity/src/sandbox_intent.rs index 40a478c885..c3000860a7 100644 --- a/tests/suites/continuity/src/sandbox_intent.rs +++ b/tests/suites/continuity/src/sandbox_intent.rs @@ -104,7 +104,15 @@ async fn verify(cx: &mut Context) -> testkit::Result { stopped.name() ); - if cx.compute_driver().await? == "vm" { + // The VM driver reports its driver name as `openshell-driver-vm`, so + // `compute_driver` doesn't recognize it. + let vm = cx + .gateway_info() + .await? + .compute_drivers + .iter() + .any(|driver| driver.name == "vm"); + if vm { let state = vm_support::StateDir::from_env()?; let expiry = vm_support::token_expiry(&state.sandbox_token(running.name())?)?; let now = SystemTime::now() diff --git a/tests/suites/unsupported.yaml b/tests/suites/unsupported.yaml index 360d783dea..0022023b6e 100644 --- a/tests/suites/unsupported.yaml +++ b/tests/suites/unsupported.yaml @@ -1,7 +1,8 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# Conformance, features and drivers tests an environment can't pass yet. +# Conformance, continuity, features and drivers tests an environment can't pass +# yet. # CI turns the entries for each environment into OPENSHELL_TEST_UNSUPPORTED. # # Each entry is one issue and the environments it breaks the test in: @@ -35,6 +36,14 @@ environments: - vm +# Cleanup deletes the stopped sandbox while the restarted gateway is still in +# its startup sweep, before it watches driver events, so the delete never +# completes (#6242). +- test: continuity::sandbox_intent::verify + issue: https://github.com/ai-openshell/openshell/issues/6242 + environments: + - fedora-podman-rootless/rpm-upgrade-source + # Rootless Podman can't relabel the root-owned proxy CA that the driver # bind-mounts, so sandbox creation fails (#5795). - test: corporate_proxy::approved_egress_uses_authenticated_proxy diff --git a/tests/testkit/README.md b/tests/testkit/README.md index 5195b87262..97ac83b6df 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -313,8 +313,9 @@ the first directory under the last `suites` directory in the crate's path: ### Unsupported tests -When a conformance, features or drivers test can't pass in one CI environment, -keep it in the row and skip it there instead of using `#[ignore]` everywhere: +When a conformance, continuity, features or drivers test can't pass in one CI +environment, keep it in the row and skip it there instead of using `#[ignore]` +everywhere: 1. File an issue for the bug. 2. Add the test, issue URL and affected environments to the shared @@ -332,14 +333,16 @@ entries separated by commas or whitespace: export OPENSHELL_TEST_UNSUPPORTED="cdi::read_only_file=https://github.com/ai-openshell/openshell/issues/1234" ``` -`` is the crate name (`conformance` for conformance, the `[[test]]` target +`` is the crate name (`conformance` or `continuity`, the `[[test]]` target name for features and drivers, with `_` for `-`), then `::` and the name listed by nextest. Features and drivers integration targets need a unique `[[test]]` name, `harness = false`, and a `main` that returns `testkit::main()`. -`cargo test` and nextest treat unsupported tests as ignored. Testkit's `list` -marks them `[unsupported: ]`, and its `run` prints the entries and -includes them in its summary and JUnit report. +`cargo test` and nextest treat unsupported tests as ignored, except in the +continuity crate, which libtest runs: there an unsupported test passes without +running and prints its issue. Testkit's `list` marks them +`[unsupported: ]`, and its `run` prints the entries and includes them in +its summary and JUnit report. A program applies only the entries for crates it links, so one value can serve several programs. Branch Checks rejects unknown crates. A bad entry for a diff --git a/tests/testkit/testkit-macros/src/lib.rs b/tests/testkit/testkit-macros/src/lib.rs index b8a614f3c6..a6747e65a1 100644 --- a/tests/testkit/testkit-macros/src/lib.rs +++ b/tests/testkit/testkit-macros/src/lib.rs @@ -19,7 +19,8 @@ //! `testkit::run`, with the original function nested in it; //! - under `#[cfg(test)]`, a `#[tokio::test]` wrapper with the same name that //! calls it, so `cargo test` and nextest run the test like any other and the -//! test name is the function name; +//! test name is the function name. It returns without running the test +//! when `OPENSHELL_TEST_UNSUPPORTED` lists it; //! - an entry in `testkit`'s test registry, with the test's family, name, //! description, and `#[ignore]`, which `testkit::main()` runs. //! @@ -160,6 +161,12 @@ fn expand( #[cfg(test)] #[::testkit::__private::tokio::test(crate = "::testkit::__private::tokio")] #vis async fn #name() { + if let ::core::option::Option::Some(issue) = + ::testkit::__private::unsupported_issue(::core::module_path!(), #name_str) + { + ::std::eprintln!("[{}] skipped, unsupported: {}", #name_str, issue); + return; + } #entry().await; } diff --git a/tests/testkit/testkit/src/lib.rs b/tests/testkit/testkit/src/lib.rs index 5d5b1c0ae4..4627433519 100644 --- a/tests/testkit/testkit/src/lib.rs +++ b/tests/testkit/testkit/src/lib.rs @@ -78,6 +78,7 @@ pub use yaml_file::YamlFile; #[doc(hidden)] pub mod __private { + pub use crate::program::libtest_issue as unsupported_issue; pub use crate::registry::TESTS; pub use linkme; pub use tokio; diff --git a/tests/testkit/testkit/src/program/mod.rs b/tests/testkit/testkit/src/program/mod.rs index dedd5d2e12..d87c689846 100644 --- a/tests/testkit/testkit/src/program/mod.rs +++ b/tests/testkit/testkit/src/program/mod.rs @@ -29,7 +29,8 @@ //! //! `OPENSHELL_TEST_UNSUPPORTED` lists tests an environment does not support //! yet (see `unsupported.rs`). They are reported as ignored under every -//! interface, and a forced run of one fails. +//! interface, and a forced run of one fails. A test that libtest runs, outside +//! a program, passes without running and prints the issue. #[cfg(unix)] mod capture; @@ -43,6 +44,7 @@ mod supervisor; mod unsupported; pub(crate) use unsupported::Unsupported; +pub use unsupported::libtest_issue; use std::ffi::OsString; use std::path::PathBuf; diff --git a/tests/testkit/testkit/src/program/unsupported.rs b/tests/testkit/testkit/src/program/unsupported.rs index 8d4889afae..3912eac287 100644 --- a/tests/testkit/testkit/src/program/unsupported.rs +++ b/tests/testkit/testkit/src/program/unsupported.rs @@ -93,6 +93,19 @@ impl Unsupported { } } +/// The issue [`ENV`] lists for the test `name` in `module_path`, for a test +/// that libtest runs instead of a program, such as a continuity scenario. +/// Libtest can't ignore a test at run time, so the caller skips it. Panics on +/// a bad value, which fails the test. +pub fn libtest_issue(module_path: &str, name: &str) -> Option { + let unsupported = + Unsupported::from_env(&crate::registry::TESTS).unwrap_or_else(|error| panic!("{error}")); + unsupported + .0 + .get(&format!("{module_path}::{name}")) + .cloned() +} + #[cfg(test)] mod tests { use super::Unsupported; From 4303b8cc021645bbda59d4c827d29dc72f105a8c Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 4 Dec 2026 11:34:15 -0800 Subject: [PATCH 06/10] test(continuity): run the suite as a testkit program Build continuity like conformance, as a harness=false program over its library, so unsupported tests are reported as ignored. This replaces the libtest wrapper skip. testkit's compute_driver now accepts the VM driver's reported name, so sandbox_intent::verify uses it. Signed-off-by: Matthew Grossman --- tasks/scripts/check-conformance-program.sh | 4 +- tests/suites/continuity/Cargo.toml | 10 +++ tests/suites/continuity/src/lib.rs | 1 + tests/suites/continuity/src/main.rs | 16 ++++ tests/suites/continuity/src/probe.rs | 53 +++++++++++++ tests/suites/continuity/src/sandbox_intent.rs | 78 +------------------ tests/suites/continuity/tests/probe.rs | 17 ++++ tests/testkit/README.md | 8 +- tests/testkit/testkit-macros/src/lib.rs | 9 +-- tests/testkit/testkit/src/context.rs | 17 +++- tests/testkit/testkit/src/lib.rs | 1 - tests/testkit/testkit/src/program/mod.rs | 4 +- .../testkit/src/program/unsupported.rs | 13 ---- 13 files changed, 121 insertions(+), 110 deletions(-) create mode 100644 tests/suites/continuity/src/main.rs create mode 100644 tests/suites/continuity/src/probe.rs create mode 100644 tests/suites/continuity/tests/probe.rs diff --git a/tasks/scripts/check-conformance-program.sh b/tasks/scripts/check-conformance-program.sh index a7acc9ea77..27b1ecdc09 100755 --- a/tasks/scripts/check-conformance-program.sh +++ b/tasks/scripts/check-conformance-program.sh @@ -19,8 +19,8 @@ trap 'rm -rf "${work}"' EXIT # Cargo metadata includes auto-discovered integration targets, but not their # harness settings. Check the manifest for the explicit opt-out. -# The conformance binary registers tests from its library, not its own crate. -# Libtest runs the continuity crate's tests. +# The conformance and continuity binaries register tests from their +# libraries, not their own crates. printf '%s\n' conformance continuity > "${work}/crates" for manifest in "${manifests[@]}"; do # shellcheck disable=SC2016 # $manifest inside the yq expression is a yq variable. diff --git a/tests/suites/continuity/Cargo.toml b/tests/suites/continuity/Cargo.toml index 60d45f5a2c..428c490e01 100644 --- a/tests/suites/continuity/Cargo.toml +++ b/tests/suites/continuity/Cargo.toml @@ -12,6 +12,16 @@ license = "Apache-2.0" repository = "https://github.com/ai-openshell/openshell" publish = false +# `openshell-continuity` is the test target, with testkit's libtest interface +# as its harness, so it applies OPENSHELL_TEST_UNSUPPORTED like conformance. +[lib] +test = false + +[[bin]] +name = "openshell-continuity" +path = "src/main.rs" +harness = false + [dependencies] openshell-testkit = { path = "../../testkit/testkit" } tokio = { version = "1", features = ["time"] } diff --git a/tests/suites/continuity/src/lib.rs b/tests/suites/continuity/src/lib.rs index 46bd3e0dbc..2df09f432b 100644 --- a/tests/suites/continuity/src/lib.rs +++ b/tests/suites/continuity/src/lib.rs @@ -15,6 +15,7 @@ //! through the CLI, which testkit doesn't track, and `verify` adopts them so //! its own cleanup removes them. +pub mod probe; mod sandbox_intent; mod sandbox_workspace; mod scenario; diff --git a/tests/suites/continuity/src/main.rs b/tests/suites/continuity/src/main.rs new file mode 100644 index 0000000000..e9954ab11a --- /dev/null +++ b/tests/suites/continuity/src/main.rs @@ -0,0 +1,16 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! `openshell-continuity`: the continuity suite as one program. +//! +//! The tests are registered by `#[testkit::test]` in this crate's library; +//! see `testkit::program` for the commands. + +use std::process::ExitCode; + +// A dependency that is never named is not linked, and its tests would be +// missing. +use continuity as _; + +fn main() -> ExitCode { + testkit::program::main_for(env!("CARGO_PKG_NAME"), env!("CARGO_BIN_NAME")) +} diff --git a/tests/suites/continuity/src/probe.rs b/tests/suites/continuity/src/probe.rs new file mode 100644 index 0000000000..ce96bedd92 --- /dev/null +++ b/tests/suites/continuity/src/probe.rs @@ -0,0 +1,53 @@ +// SPDX-License-Identifier: Apache-2.0 + +//! Reading `sandbox_intent::verify`'s probe of the running sandbox. + +/// What `verify`'s probe printed, with times in seconds since the epoch. +#[derive(Debug, PartialEq)] +pub struct Probe { + pub seeded: u64, + pub fingerprint: String, + /// When the sandbox's first process started. + pub started: u64, +} + +impl Probe { + /// Parse the probe's output: the marker's two lines, the `btime` line + /// of `/proc/stat`, the clock tick rate, and `/proc/1/stat`. + pub fn parse(output: &str) -> testkit::Result { + let mut lines = output.lines(); + let mut next = |what: &str| { + lines + .next() + .ok_or_else(|| testkit::Error::msg(format!("no {what} line"))) + }; + let seeded = number(next("seed time")?)?; + let fingerprint = next("fingerprint")?.to_string(); + let boot = number( + next("btime")? + .strip_prefix("btime ") + .ok_or_else(|| testkit::Error::msg("the btime line has no btime prefix"))?, + )?; + let ticks_per_second = number(next("clock tick")?)?; + testkit::ensure!(ticks_per_second > 0, "the clock tick rate is 0"); + // The command name in field 2 may hold spaces, so count fields after + // its closing parenthesis. The start time is field 22. + let stat = next("stat")?; + let start_ticks = stat + .rsplit_once(')') + .and_then(|(_, rest)| rest.split_whitespace().nth(19)) + .ok_or_else(|| testkit::Error::msg(format!("no start time in {stat:?}")))?; + let started = boot + number(start_ticks)? / ticks_per_second; + Ok(Self { + seeded, + fingerprint, + started, + }) + } +} + +fn number(text: &str) -> testkit::Result { + text.trim() + .parse() + .map_err(|err| testkit::Error::msg(format!("{text:?} is not a number: {err}"))) +} diff --git a/tests/suites/continuity/src/sandbox_intent.rs b/tests/suites/continuity/src/sandbox_intent.rs index c3000860a7..ebe0384bc0 100644 --- a/tests/suites/continuity/src/sandbox_intent.rs +++ b/tests/suites/continuity/src/sandbox_intent.rs @@ -12,6 +12,7 @@ use std::time::{Duration, SystemTime, UNIX_EPOCH}; use testkit::sdk::SandboxPhase; use testkit::{Context, Poll, ResultExt as _}; +use crate::probe::Probe; use crate::scenario::{create_and_run, name}; /// The time `seed` ran, in seconds since the epoch on the sandbox's clock, @@ -104,15 +105,7 @@ async fn verify(cx: &mut Context) -> testkit::Result { stopped.name() ); - // The VM driver reports its driver name as `openshell-driver-vm`, so - // `compute_driver` doesn't recognize it. - let vm = cx - .gateway_info() - .await? - .compute_drivers - .iter() - .any(|driver| driver.name == "vm"); - if vm { + if cx.compute_driver().await? == "vm" { let state = vm_support::StateDir::from_env()?; let expiry = vm_support::token_expiry(&state.sandbox_token(running.name())?)?; let now = SystemTime::now() @@ -140,70 +133,3 @@ async fn host_key(cx: &Context, sandbox: &str) -> testkit::Result { testkit::Error::msg(format!("sandbox {sandbox} has no host key fingerprint")) }) } - -/// What `verify`'s probe printed, with times in seconds since the epoch. -#[derive(Debug, PartialEq)] -struct Probe { - seeded: u64, - fingerprint: String, - /// When the sandbox's first process started. - started: u64, -} - -impl Probe { - fn parse(output: &str) -> testkit::Result { - let mut lines = output.lines(); - let mut next = |what: &str| { - lines - .next() - .ok_or_else(|| testkit::Error::msg(format!("no {what} line"))) - }; - let seeded = number(next("seed time")?)?; - let fingerprint = next("fingerprint")?.to_string(); - let boot = number( - next("btime")? - .strip_prefix("btime ") - .ok_or_else(|| testkit::Error::msg("the btime line has no btime prefix"))?, - )?; - let ticks_per_second = number(next("clock tick")?)?; - testkit::ensure!(ticks_per_second > 0, "the clock tick rate is 0"); - // The command name in field 2 may hold spaces, so count fields after - // its closing parenthesis. The start time is field 22. - let stat = next("stat")?; - let start_ticks = stat - .rsplit_once(')') - .and_then(|(_, rest)| rest.split_whitespace().nth(19)) - .ok_or_else(|| testkit::Error::msg(format!("no start time in {stat:?}")))?; - let started = boot + number(start_ticks)? / ticks_per_second; - Ok(Self { - seeded, - fingerprint, - started, - }) - } -} - -fn number(text: &str) -> testkit::Result { - text.trim() - .parse() - .map_err(|err| testkit::Error::msg(format!("{text:?} is not a number: {err}"))) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn reads_when_the_first_process_started() { - let output = "1700000000\nSHA256:abc\nbtime 1699990000\n100\n\ - 1 (openshell sandbox) S 0 1 1 0 -1 4194560 0 0 0 0 0 0 0 0 20 0 1 0 1500000 0 0\n"; - assert_eq!( - Probe::parse(output).unwrap(), - Probe { - seeded: 1_700_000_000, - fingerprint: "SHA256:abc".to_string(), - started: 1_700_005_000, - } - ); - } -} diff --git a/tests/suites/continuity/tests/probe.rs b/tests/suites/continuity/tests/probe.rs new file mode 100644 index 0000000000..46a359d491 --- /dev/null +++ b/tests/suites/continuity/tests/probe.rs @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: Apache-2.0 + +use continuity::probe::Probe; + +#[test] +fn reads_when_the_first_process_started() { + let output = "1700000000\nSHA256:abc\nbtime 1699990000\n100\n\ + 1 (openshell sandbox) S 0 1 1 0 -1 4194560 0 0 0 0 0 0 0 0 20 0 1 0 1500000 0 0\n"; + assert_eq!( + Probe::parse(output).unwrap(), + Probe { + seeded: 1_700_000_000, + fingerprint: "SHA256:abc".to_string(), + started: 1_700_005_000, + } + ); +} diff --git a/tests/testkit/README.md b/tests/testkit/README.md index 97ac83b6df..32a0f5e5ce 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -338,11 +338,9 @@ name for features and drivers, with `_` for `-`), then `::` and the name listed by nextest. Features and drivers integration targets need a unique `[[test]]` name, `harness = false`, and a `main` that returns `testkit::main()`. -`cargo test` and nextest treat unsupported tests as ignored, except in the -continuity crate, which libtest runs: there an unsupported test passes without -running and prints its issue. Testkit's `list` marks them -`[unsupported: ]`, and its `run` prints the entries and includes them in -its summary and JUnit report. +`cargo test` and nextest treat unsupported tests as ignored. Testkit's `list` +marks them `[unsupported: ]`, and its `run` prints the entries and +includes them in its summary and JUnit report. A program applies only the entries for crates it links, so one value can serve several programs. Branch Checks rejects unknown crates. A bad entry for a diff --git a/tests/testkit/testkit-macros/src/lib.rs b/tests/testkit/testkit-macros/src/lib.rs index a6747e65a1..b8a614f3c6 100644 --- a/tests/testkit/testkit-macros/src/lib.rs +++ b/tests/testkit/testkit-macros/src/lib.rs @@ -19,8 +19,7 @@ //! `testkit::run`, with the original function nested in it; //! - under `#[cfg(test)]`, a `#[tokio::test]` wrapper with the same name that //! calls it, so `cargo test` and nextest run the test like any other and the -//! test name is the function name. It returns without running the test -//! when `OPENSHELL_TEST_UNSUPPORTED` lists it; +//! test name is the function name; //! - an entry in `testkit`'s test registry, with the test's family, name, //! description, and `#[ignore]`, which `testkit::main()` runs. //! @@ -161,12 +160,6 @@ fn expand( #[cfg(test)] #[::testkit::__private::tokio::test(crate = "::testkit::__private::tokio")] #vis async fn #name() { - if let ::core::option::Option::Some(issue) = - ::testkit::__private::unsupported_issue(::core::module_path!(), #name_str) - { - ::std::eprintln!("[{}] skipped, unsupported: {}", #name_str, issue); - return; - } #entry().await; } diff --git a/tests/testkit/testkit/src/context.rs b/tests/testkit/testkit/src/context.rs index 9f0b05f460..53e124fabd 100644 --- a/tests/testkit/testkit/src/context.rs +++ b/tests/testkit/testkit/src/context.rs @@ -317,7 +317,8 @@ impl Context { /// The gateway's compute driver, such as `docker` or `kubernetes`, for /// tests whose setup depends on it. Fails unless gateway info reports - /// exactly one driver, under the same configured and driver name. + /// exactly one driver, under the same configured and driver name (the VM + /// driver reports `openshell-driver-vm`). pub async fn compute_driver(&self) -> Result { single_compute_driver(&self.gateway_info().await?) } @@ -359,7 +360,7 @@ fn single_compute_driver(info: &proto::GetGatewayInfoResponse) -> Result }) .collect(); match drivers.as_slice() { - [(configured, reported)] if configured == reported && !configured.is_empty() => { + [(configured, reported)] if !configured.is_empty() && agree(configured, reported) => { Ok((*configured).to_string()) } _ => Err(Error::msg(format!( @@ -368,6 +369,12 @@ fn single_compute_driver(info: &proto::GetGatewayInfoResponse) -> Result } } +/// Whether a driver configured as `configured` may report itself as +/// `reported`. The VM driver reports its binary name. +fn agree(configured: &str, reported: &str) -> bool { + configured == reported || (configured, reported) == ("vm", "openshell-driver-vm") +} + /// Register the cleanup hook that deletes sandbox `name`, unless it is /// already tracked. pub(crate) fn track_sandbox(cleanup: &Cleanup, client: &WorkspaceScopedClient, name: &str) { @@ -1243,9 +1250,15 @@ mod tests { single_compute_driver(&gateway_info(&[("docker", "docker")])).expect("one driver"), "docker" ); + assert_eq!( + single_compute_driver(&gateway_info(&[("vm", "openshell-driver-vm")])) + .expect("the VM driver"), + "vm" + ); for drivers in [ &[][..], &[("docker", "podman")][..], + &[("docker", "openshell-driver-vm")][..], &[("", "")][..], &[("docker", "docker"), ("podman", "podman")][..], ] { diff --git a/tests/testkit/testkit/src/lib.rs b/tests/testkit/testkit/src/lib.rs index 4627433519..5d5b1c0ae4 100644 --- a/tests/testkit/testkit/src/lib.rs +++ b/tests/testkit/testkit/src/lib.rs @@ -78,7 +78,6 @@ pub use yaml_file::YamlFile; #[doc(hidden)] pub mod __private { - pub use crate::program::libtest_issue as unsupported_issue; pub use crate::registry::TESTS; pub use linkme; pub use tokio; diff --git a/tests/testkit/testkit/src/program/mod.rs b/tests/testkit/testkit/src/program/mod.rs index d87c689846..dedd5d2e12 100644 --- a/tests/testkit/testkit/src/program/mod.rs +++ b/tests/testkit/testkit/src/program/mod.rs @@ -29,8 +29,7 @@ //! //! `OPENSHELL_TEST_UNSUPPORTED` lists tests an environment does not support //! yet (see `unsupported.rs`). They are reported as ignored under every -//! interface, and a forced run of one fails. A test that libtest runs, outside -//! a program, passes without running and prints the issue. +//! interface, and a forced run of one fails. #[cfg(unix)] mod capture; @@ -44,7 +43,6 @@ mod supervisor; mod unsupported; pub(crate) use unsupported::Unsupported; -pub use unsupported::libtest_issue; use std::ffi::OsString; use std::path::PathBuf; diff --git a/tests/testkit/testkit/src/program/unsupported.rs b/tests/testkit/testkit/src/program/unsupported.rs index 3912eac287..8d4889afae 100644 --- a/tests/testkit/testkit/src/program/unsupported.rs +++ b/tests/testkit/testkit/src/program/unsupported.rs @@ -93,19 +93,6 @@ impl Unsupported { } } -/// The issue [`ENV`] lists for the test `name` in `module_path`, for a test -/// that libtest runs instead of a program, such as a continuity scenario. -/// Libtest can't ignore a test at run time, so the caller skips it. Panics on -/// a bad value, which fails the test. -pub fn libtest_issue(module_path: &str, name: &str) -> Option { - let unsupported = - Unsupported::from_env(&crate::registry::TESTS).unwrap_or_else(|error| panic!("{error}")); - unsupported - .0 - .get(&format!("{module_path}::{name}")) - .cloned() -} - #[cfg(test)] mod tests { use super::Unsupported; From b8b1f024f68fe2c28882c0370c796aa0fee7deda Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 4 Dec 2026 14:13:53 -0800 Subject: [PATCH 07/10] test(continuity): seed sandboxes through testkit handles Add SandboxBuilder::named and keep so a continuity seed creates sandboxes that its verify adopts, and use Sandbox::stop, expect_listed and the ready snapshot instead of CLI loops and direct gateway calls. The VM token check moves to vm-support, and seed passes values to sh as arguments. Signed-off-by: Matthew Grossman --- tests/suites/continuity/src/lib.rs | 6 +- tests/suites/continuity/src/sandbox_intent.rs | 97 ++++++------------- .../continuity/src/sandbox_workspace.rs | 20 +++- tests/suites/continuity/src/scenario.rs | 42 ++------ tests/support/vm/src/lib.rs | 29 ++++++ tests/testkit/README.md | 4 +- tests/testkit/testkit/src/context.rs | 33 ++++++- 7 files changed, 121 insertions(+), 110 deletions(-) diff --git a/tests/suites/continuity/src/lib.rs b/tests/suites/continuity/src/lib.rs index 2df09f432b..a4b403808a 100644 --- a/tests/suites/continuity/src/lib.rs +++ b/tests/suites/continuity/src/lib.rs @@ -11,9 +11,9 @@ //! //! The tests share state through names derived from [`id`], which the runner //! sets once per run, so nothing is written to disk. `seed` must not leave -//! cleanup behind that deletes what `verify` reads: it creates resources -//! through the CLI, which testkit doesn't track, and `verify` adopts them so -//! its own cleanup removes them. +//! cleanup behind that deletes what `verify` reads: it creates sandboxes with +//! [`scenario::sandbox`], which cleanup keeps, and `verify` adopts them so its +//! own cleanup removes them. pub mod probe; mod sandbox_intent; diff --git a/tests/suites/continuity/src/sandbox_intent.rs b/tests/suites/continuity/src/sandbox_intent.rs index ebe0384bc0..864f82ba57 100644 --- a/tests/suites/continuity/src/sandbox_intent.rs +++ b/tests/suites/continuity/src/sandbox_intent.rs @@ -7,54 +7,36 @@ //! again, so that sandbox's processes start after `seed`, with the same SSH //! host key. It leaves the stopped sandbox stopped. -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use testkit::sdk::SandboxPhase; -use testkit::{Context, Poll, ResultExt as _}; +use testkit::sdk::{SandboxPhase, SandboxRef}; +use testkit::{Context, ResultExt as _}; use crate::probe::Probe; -use crate::scenario::{create_and_run, name}; +use crate::scenario::{name, sandbox}; /// The time `seed` ran, in seconds since the epoch on the sandbox's clock, /// and the sandbox's SSH host key fingerprint, one per line. const MARKER: &str = "/sandbox/.continuity-intent"; -const STOP_TIMEOUT: Duration = Duration::from_secs(120); /// Creates a running sandbox that records when `seed` ran and its host key, /// and a sandbox that is stopped. #[testkit::test] async fn seed(cx: &mut Context) -> testkit::Result { - let (running, stopped) = (name("run")?, name("stop")?); - create_and_run(cx, &stopped, "true").await?; - cx.cli(["sandbox", "stop", &stopped]) + sandbox(cx, "stop")?.create_ready().await?.stop().await?; + + let running = sandbox(cx, "run")?.create_ready().await?; + let fingerprint = host_key(&running.get().await?)?; + running + .exec([ + "sh", + "-c", + "printf '%s\\n%s\\n' \"$(date +%s)\" \"$1\" > \"$2\" && sync", + "sh", + &fingerprint, + MARKER, + ]) .await? .success() - .context("stop the sandbox")?; - testkit::poll_until( - &format!("sandbox {stopped} to be Stopped"), - STOP_TIMEOUT, - Duration::from_secs(2), - async || { - let phase = cx.client().get_sandbox(&stopped).await?.phase; - Ok(if phase == SandboxPhase::Stopped { - Poll::Ready(()) - } else { - Poll::Pending(format!("phase {phase:?}")) - }) - }, - ) - .await?; - - create_and_run(cx, &running, "true").await?; - let fingerprint = host_key(cx, &running).await?; - let record = - format!("printf '%s\\n%s\\n' \"$(date +%s)\" '{fingerprint}' > '{MARKER}' && sync"); - cx.cli([ - "sandbox", "exec", "--name", &running, "--no-tty", "--", "sh", "-c", &record, - ]) - .await? - .success() - .context("record the seed time and host key")?; + .context("record the seed time and host key")?; Ok(()) } @@ -71,7 +53,7 @@ async fn verify(cx: &mut Context) -> testkit::Result { .adopt(&name("stop")?) .await .context("find the stopped sandbox")?; - running.wait_ready().await?; + let ready = running.wait_ready().await?; // The marker, the kernel's boot time, the clock tick rate, and the stat // line of the sandbox's first process. @@ -89,7 +71,7 @@ async fn verify(cx: &mut Context) -> testkit::Result { observed.started, observed.seeded ); - let fingerprint = host_key(cx, running.name()).await?; + let fingerprint = host_key(&ready)?; testkit::ensure!( fingerprint == observed.fingerprint, "sandbox {}'s host key changed from {} to {fingerprint}", @@ -98,38 +80,23 @@ async fn verify(cx: &mut Context) -> testkit::Result { ); // The running sandbox is ready, so the gateway has reconciled both. - let phase = stopped.get().await?.phase; - testkit::ensure!( - phase == SandboxPhase::Stopped, - "sandbox {} was stopped before the disruption and is {phase:?} after it", - stopped.name() - ); + stopped + .expect_listed(SandboxPhase::Stopped) + .await + .context("the sandbox stopped before the disruption")?; if cx.compute_driver().await? == "vm" { - let state = vm_support::StateDir::from_env()?; - let expiry = vm_support::token_expiry(&state.sandbox_token(running.name())?)?; - let now = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_err(|err| testkit::Error::msg(format!("read the clock: {err}")))? - .as_secs(); - // A token without a lifetime has exp 0. - testkit::ensure!( - expiry == 0 || expiry > now, - "the VM driver relaunched sandbox {} with a token that expired at {expiry}; now is {now}", - running.name() - ); + vm_support::ensure_token_live(&vm_support::StateDir::from_env()?, running.name())?; } Ok(()) } -/// The sandbox's SSH host key fingerprint. -async fn host_key(cx: &Context, sandbox: &str) -> testkit::Result { - cx.client() - .get_sandbox(sandbox) - .await - .context(format!("get sandbox {sandbox}"))? - .host_key_fingerprint - .ok_or_else(|| { - testkit::Error::msg(format!("sandbox {sandbox} has no host key fingerprint")) - }) +/// A sandbox's SSH host key fingerprint. +fn host_key(sandbox: &SandboxRef) -> testkit::Result { + sandbox.host_key_fingerprint.clone().ok_or_else(|| { + testkit::Error::msg(format!( + "sandbox {} has no host key fingerprint", + sandbox.name + )) + }) } diff --git a/tests/suites/continuity/src/sandbox_workspace.rs b/tests/suites/continuity/src/sandbox_workspace.rs index 302b4d5583..4aa3d768fc 100644 --- a/tests/suites/continuity/src/sandbox_workspace.rs +++ b/tests/suites/continuity/src/sandbox_workspace.rs @@ -5,7 +5,7 @@ use testkit::{Context, ResultExt as _}; -use crate::scenario::{create_and_run, id, name}; +use crate::scenario::{id, name, sandbox}; const MARKER: &str = "/sandbox/.continuity-marker"; @@ -13,9 +13,21 @@ const MARKER: &str = "/sandbox/.continuity-marker"; /// file in its workspace. #[testkit::test] async fn seed(cx: &mut Context) -> testkit::Result { - let (sandbox, id) = (name("ws")?, id()?); - let write = format!("printf '%s\\n' '{id}' > '{MARKER}' && sync"); - create_and_run(cx, &sandbox, &write).await + sandbox(cx, "ws")? + .create_ready() + .await? + .exec([ + "sh", + "-c", + "printf '%s\\n' \"$1\" > \"$2\" && sync", + "sh", + &id()?, + MARKER, + ]) + .await? + .success() + .context("write the marker")?; + Ok(()) } /// The sandbox is still listed and ready, its file is intact, and a sandbox diff --git a/tests/suites/continuity/src/scenario.rs b/tests/suites/continuity/src/scenario.rs index 71ac016f0c..121183c177 100644 --- a/tests/suites/continuity/src/scenario.rs +++ b/tests/suites/continuity/src/scenario.rs @@ -3,17 +3,12 @@ //! What a scenario's `seed` and `verify` share. -use std::time::Duration; - -use testkit::{Context, Result, ResultExt as _}; +use testkit::{Context, Result, SandboxBuilder}; /// The variable the runner sets to the id shared by one run's `seed` and /// `verify` tests. pub const ID_ENV: &str = "CONTINUITY_RUN_ID"; -/// How long a sandbox `seed` creates may take to run a command. -const READY_TIMEOUT: Duration = Duration::from_secs(120); - /// The id of this run. Fails when the tests were not started by the runner's /// `--disruption` mode, because a `seed` without a `verify` proves nothing. pub fn id() -> Result { @@ -32,31 +27,12 @@ pub fn name(suffix: &str) -> Result { Ok(format!("cont-{}-{suffix}", id()?)) } -/// Create a long-running sandbox through the CLI, which testkit doesn't -/// track, so it outlives `seed`, and run `script` in it once it runs -/// commands. -pub async fn create_and_run(cx: &Context, sandbox: &str, script: &str) -> Result { - cx.cli([ - "sandbox", "create", "--name", sandbox, "--detach", "--", "sleep", "infinity", - ]) - .await? - .success() - .context(format!("create sandbox {sandbox}"))?; - - let deadline = tokio::time::Instant::now() + READY_TIMEOUT; - loop { - let out = cx - .cli([ - "sandbox", "exec", "--name", sandbox, "--no-tty", "--", "sh", "-c", script, - ]) - .await?; - if out.success().is_ok() { - return Ok(()); - } - testkit::ensure!( - tokio::time::Instant::now() < deadline, - "sandbox {sandbox} did not run a command within {READY_TIMEOUT:?}" - ); - tokio::time::sleep(Duration::from_secs(2)).await; - } +/// A long-running sandbox named [`name`]`(suffix)` that `seed` creates and +/// cleanup keeps, so `verify` can adopt it. +pub fn sandbox(cx: &Context, suffix: &str) -> Result { + Ok(cx + .sandbox(suffix) + .named(name(suffix)?) + .command(["sleep", "infinity"]) + .keep()) } diff --git a/tests/support/vm/src/lib.rs b/tests/support/vm/src/lib.rs index f208d4d988..0a883b4705 100644 --- a/tests/support/vm/src/lib.rs +++ b/tests/support/vm/src/lib.rs @@ -9,6 +9,7 @@ //! the test; it never skips it. use std::path::PathBuf; +use std::time::{SystemTime, UNIX_EPOCH}; use base64::Engine as _; use openshell_core::proto::compute::v1::DriverSandbox; @@ -71,6 +72,27 @@ impl StateDir { } } +/// Fail unless the driver launches sandbox `name` with a token that hasn't +/// expired. +pub fn ensure_token_live(state: &StateDir, name: &str) -> Result { + let expiry = token_expiry(&state.sandbox_token(name)?)?; + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|err| Error::msg(format!("read the clock: {err}")))? + .as_secs(); + testkit::ensure!( + live(expiry, now), + "the VM driver launches sandbox {name} with a token that expired at {expiry}; now is {now}" + ); + Ok(()) +} + +/// Whether a token with `exp` claim `expiry` is live at `now`. A token +/// without a lifetime has 0. +fn live(expiry: u64, now: u64) -> bool { + expiry == 0 || expiry > now +} + /// The `exp` claim of JWT `token`, unverified. A token without a lifetime has /// 0. pub fn token_expiry(token: &str) -> Result { @@ -99,4 +121,11 @@ mod tests { assert_eq!(token_expiry(&format!("h.{payload}.s")).unwrap(), 42); assert!(token_expiry("no-payload").is_err()); } + + #[test] + fn a_token_is_live_until_it_expires() { + assert!(live(0, 100)); + assert!(live(101, 100)); + assert!(!live(100, 100)); + } } diff --git a/tests/testkit/README.md b/tests/testkit/README.md index 32a0f5e5ce..7965e98d36 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -71,7 +71,9 @@ fails. A killed test process skips cleanup, so names are unique to the run. long-running sandbox is `.command(["sleep", "infinity"])`. `cx.python_sandbox(suffix, policy)` builds one from `testkit::python_image()` with `policy`, for tests that run Python clients - in it. The returned + in it. `named(name)` overrides the generated name, and `keep()` leaves the + sandbox for a later test, such as a continuity `verify`, that adopts it. + The returned `Sandbox` can wait for ready or finished, stop, start, exec or `poll_exec` until the output matches, read its config and draft policy, set a setting, read `sandbox get` JSON with `get_json()`, read its policy diff --git a/tests/testkit/testkit/src/context.rs b/tests/testkit/testkit/src/context.rs index 53e124fabd..f4ce8ab127 100644 --- a/tests/testkit/testkit/src/context.rs +++ b/tests/testkit/testkit/src/context.rs @@ -205,6 +205,7 @@ impl Context { name: Some(self.sandbox_name(suffix)), ..SandboxSpec::default() }, + keep: false, } } @@ -465,9 +466,31 @@ pub struct SandboxBuilder { driver_config: Option, log_level: Option, spec: SandboxSpec, + keep: bool, } impl SandboxBuilder { + /// Name the sandbox `name` instead of `cx.name(suffix)`, for a sandbox a + /// later test finds by name. + /// + /// # Panics + /// + /// If `name` is longer than [`MAX_SANDBOX_NAME_LEN`]. + #[track_caller] + pub fn named(mut self, name: impl Into) -> Self { + let name = name.into(); + check_sandbox_name(&name); + self.spec.name = Some(name); + self + } + + /// Leave the sandbox for a later test: cleanup doesn't delete it. That + /// test should [`Context::adopt`] it, so its cleanup deletes it. + pub fn keep(mut self) -> Self { + self.keep = true; + self + } + /// The sandbox's main command. Empty selects the gateway's default. pub fn command(mut self, command: I) -> Self where @@ -541,12 +564,14 @@ impl SandboxBuilder { Ok(sandbox) } - /// Create the sandbox. It is tracked for cleanup before the request is - /// sent, so a create that fails after the gateway accepted it is still - /// cleaned up. + /// Create the sandbox. Unless it is [kept](Self::keep), it is tracked for + /// cleanup before the request is sent, so a create that fails after the + /// gateway accepted it is still cleaned up. pub async fn create(self) -> Result { let name = self.spec.name.clone().unwrap_or_default(); - self.handles.track(&name); + if !self.keep { + self.handles.track(&name); + } let id = if self.policy.is_none() && self.driver_config.is_none() && self.log_level.is_none() From e4678a9053ec32087963fa2f4ef79a4b6a28e93c Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 4 Dec 2026 14:15:52 -0800 Subject: [PATCH 08/10] test(support): typed container mounts, command and supervisor lookup Add Engine::supervisor, mounts, command, env and secret_names and a one_read_only_at helper to container-engine-support, so the Docker and Podman additional CA tests share one check without indexing JSON values. Signed-off-by: Matthew Grossman --- tests/suites/drivers/docker/Cargo.lock | 1 + .../drivers/docker/tests/additional_ca.rs | 48 ++----- tests/suites/drivers/podman/Cargo.lock | 1 + .../drivers/podman/tests/additional_ca.rs | 49 +++----- .../suites/drivers/podman/tests/lifecycle.rs | 4 +- .../drivers/podman/tests/oci_identity.rs | 4 +- tests/suites/features/Cargo.lock | 1 + .../features/oci-image/tests/oci_image.rs | 2 +- .../suites/features/ocsf/tests/ocsf_stderr.rs | 4 +- tests/support/Cargo.lock | 1 + tests/support/container-engine/Cargo.toml | 1 + tests/support/container-engine/src/lib.rs | 119 ++++++++++++++++-- 12 files changed, 144 insertions(+), 91 deletions(-) diff --git a/tests/suites/drivers/docker/Cargo.lock b/tests/suites/drivers/docker/Cargo.lock index 1bc442af24..127d0331c7 100644 --- a/tests/suites/drivers/docker/Cargo.lock +++ b/tests/suites/drivers/docker/Cargo.lock @@ -531,6 +531,7 @@ name = "container-engine-support" version = "0.0.0" dependencies = [ "openshell-testkit", + "serde", "serde_json", "tempfile", "tokio", diff --git a/tests/suites/drivers/docker/tests/additional_ca.rs b/tests/suites/drivers/docker/tests/additional_ca.rs index 8ca10935ce..ef481b03a7 100644 --- a/tests/suites/drivers/docker/tests/additional_ca.rs +++ b/tests/suites/drivers/docker/tests/additional_ca.rs @@ -9,8 +9,8 @@ //! //! Ported from `e2e/rust/tests/additional_ca.rs`. -use container_engine_support::{Engine, flag_values}; -use testkit::Context; +use container_engine_support::{Engine, flag_values, one_read_only_at}; +use testkit::{Context, ResultExt as _}; fn main() -> std::process::ExitCode { testkit::main() @@ -34,47 +34,25 @@ async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> te .command(["sleep", "infinity"]) .create_ready() .await?; - let supervisor = engine - .container_for_role(sandbox.name(), "supervisor") - .await?; + let supervisor = engine.supervisor(sandbox.name()).await?; - let mounts = engine.inspect_json(&supervisor, "{{json .Mounts}}").await?; - let mounts = mounts.as_array().cloned().unwrap_or_default(); - // Exactly one mount at the path, and it is read-only. - let one_read_only_at = |path: &str| { - let at: Vec<_> = mounts - .iter() - .filter(|mount| mount["Destination"] == path) - .collect(); - matches!(at.as_slice(), [mount] if mount["RW"] == false) - }; - testkit::ensure!( - one_read_only_at(ADDITIONAL_CA_PATH), - "the supervisor should have one read-only mount at {ADDITIONAL_CA_PATH}: {mounts:#?}" - ); - testkit::ensure!( - one_read_only_at(SUPERVISOR_STATE_PATH), - "the supervisor should have its state volume read-only at {SUPERVISOR_STATE_PATH}: \ - {mounts:#?}" - ); + let mounts = engine.mounts(&supervisor).await?; + one_read_only_at(&mounts, ADDITIONAL_CA_PATH)?; + one_read_only_at(&mounts, SUPERVISOR_STATE_PATH) + .context("the supervisor's state volume, which holds the gateway's mTLS CA")?; - let env = engine - .inspect_json(&supervisor, "{{json .Config.Env}}") - .await?; + let env = engine.env(&supervisor).await?; testkit::ensure!( - env.as_array() - .is_some_and(|env| env.iter().any(|var| var == GATEWAY_CA_ENV)), + env.iter().any(|var| var == GATEWAY_CA_ENV), "the supervisor should read the gateway's mTLS CA from its state volume ({GATEWAY_CA_ENV}): \ - {env}" + {env:?}" ); - let command = engine - .inspect_json(&supervisor, "{{json .Config.Cmd}}") - .await?; + let command = engine.command(&supervisor).await?; testkit::ensure!( - flag_values(&command, "--additional-ca-bundle")? == [ADDITIONAL_CA_PATH], + flag_values(&command, "--additional-ca-bundle") == [ADDITIONAL_CA_PATH], "the supervisor command should pass --additional-ca-bundle {ADDITIONAL_CA_PATH} once: \ - {command}" + {command:?}" ); Ok(()) } diff --git a/tests/suites/drivers/podman/Cargo.lock b/tests/suites/drivers/podman/Cargo.lock index 776518a3a5..16a2e324d0 100644 --- a/tests/suites/drivers/podman/Cargo.lock +++ b/tests/suites/drivers/podman/Cargo.lock @@ -531,6 +531,7 @@ name = "container-engine-support" version = "0.0.0" dependencies = [ "openshell-testkit", + "serde", "serde_json", "tempfile", "tokio", diff --git a/tests/suites/drivers/podman/tests/additional_ca.rs b/tests/suites/drivers/podman/tests/additional_ca.rs index 34827e22c8..ac196892e2 100644 --- a/tests/suites/drivers/podman/tests/additional_ca.rs +++ b/tests/suites/drivers/podman/tests/additional_ca.rs @@ -9,8 +9,7 @@ //! //! Ported from `e2e/rust/tests/additional_ca.rs`. -use container_engine_support::{Engine, flag_values}; -use serde_json::Value; +use container_engine_support::{Engine, flag_values, one_read_only_at}; use testkit::Context; fn main() -> std::process::ExitCode { @@ -37,56 +36,36 @@ async fn supervisor_gets_additional_ca_beside_gateway_ca(cx: &mut Context) -> te .command(["sleep", "infinity"]) .create_ready() .await?; - let supervisor = engine - .container_for_role(sandbox.name(), "supervisor") - .await?; - - let mounts = engine.inspect_json(&supervisor, "{{json .Mounts}}").await?; - let mounts = mounts.as_array().cloned().unwrap_or_default(); - let additional: Vec<&Value> = mounts - .iter() - .filter(|mount| mount["Destination"] == ADDITIONAL_CA_PATH) - .collect(); - testkit::ensure!( - matches!(additional.as_slice(), [mount] if mount["RW"] == false), - "the supervisor should have one read-only mount at {ADDITIONAL_CA_PATH}: {mounts:#?}" - ); + let supervisor = engine.supervisor(sandbox.name()).await?; + let mounts = engine.mounts(&supervisor).await?; + let additional = one_read_only_at(&mounts, ADDITIONAL_CA_PATH)?; match mounts .iter() - .find(|mount| mount["Destination"] == GATEWAY_CA_PATH) + .find(|mount| mount.destination == GATEWAY_CA_PATH) { Some(gateway) => testkit::ensure!( - gateway["Source"] != additional[0]["Source"], + gateway.source != additional.source, "the gateway's mTLS CA and the additional CA should come from different files: \ {mounts:#?}" ), None => { - let secrets = engine - .inspect_json(&supervisor, "{{json .Config.Secrets}}") - .await?; - let has_secret = secrets.as_array().is_some_and(|secrets| { - secrets.iter().any(|secret| { - secret["Name"] - .as_str() - .is_some_and(|name| name.starts_with(GATEWAY_CA_SECRET_PREFIX)) - }) - }); + let secrets = engine.secret_names(&supervisor).await?; testkit::ensure!( - has_secret, + secrets + .iter() + .any(|name| name.starts_with(GATEWAY_CA_SECRET_PREFIX)), "the supervisor should get the gateway's mTLS CA at {GATEWAY_CA_PATH} or in a \ - {GATEWAY_CA_SECRET_PREFIX}* secret; mounts: {mounts:#?}; secrets: {secrets}" + {GATEWAY_CA_SECRET_PREFIX}* secret; mounts: {mounts:#?}; secrets: {secrets:?}" ); } } - let command = engine - .inspect_json(&supervisor, "{{json .Config.Cmd}}") - .await?; + let command = engine.command(&supervisor).await?; testkit::ensure!( - flag_values(&command, "--additional-ca-bundle")? == [ADDITIONAL_CA_PATH], + flag_values(&command, "--additional-ca-bundle") == [ADDITIONAL_CA_PATH], "the supervisor command should pass --additional-ca-bundle {ADDITIONAL_CA_PATH} once: \ - {command}" + {command:?}" ); Ok(()) } diff --git a/tests/suites/drivers/podman/tests/lifecycle.rs b/tests/suites/drivers/podman/tests/lifecycle.rs index 92a311ddce..9b18f8dde3 100644 --- a/tests/suites/drivers/podman/tests/lifecycle.rs +++ b/tests/suites/drivers/podman/tests/lifecycle.rs @@ -48,9 +48,7 @@ async fn stopped_workload_container_is_terminal(cx: &mut Context) -> testkit::Re .await .context("the sandbox workload must not be able to read its bootstrap JWT")?; - let supervisor = engine - .container_for_role(sandbox.name(), "supervisor") - .await?; + let supervisor = engine.supervisor(sandbox.name()).await?; let token = engine.copy_from(&supervisor, TOKEN_PATH).await?; require_unexpired(&String::from_utf8_lossy(&token))?; diff --git a/tests/suites/drivers/podman/tests/oci_identity.rs b/tests/suites/drivers/podman/tests/oci_identity.rs index f7ab66daf4..8d4a421e34 100644 --- a/tests/suites/drivers/podman/tests/oci_identity.rs +++ b/tests/suites/drivers/podman/tests/oci_identity.rs @@ -77,9 +77,7 @@ USER {OCI_IDENTITY} .await .context("sandbox starts from the OCI identity image")?; - let supervisor = engine - .container_for_role(sandbox.name(), "supervisor") - .await?; + let supervisor = engine.supervisor(sandbox.name()).await?; let user = engine .inspect_container(&supervisor, "{{.Config.User}}") .await?; diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index 1e0e2dbb2a..af33065662 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -585,6 +585,7 @@ name = "container-engine-support" version = "0.0.0" dependencies = [ "openshell-testkit", + "serde", "serde_json", "tempfile", "tokio", diff --git a/tests/suites/features/oci-image/tests/oci_image.rs b/tests/suites/features/oci-image/tests/oci_image.rs index e46722db1b..e58bf94733 100644 --- a/tests/suites/features/oci-image/tests/oci_image.rs +++ b/tests/suites/features/oci-image/tests/oci_image.rs @@ -394,7 +394,7 @@ impl Oci<'_> { async fn container_checks(&self, sandbox: &str, image: &Image, identity: &str) -> Result { let engine = &self.engine; let workload = engine.container_for_role(sandbox, "sandbox").await?; - let supervisor = engine.container_for_role(sandbox, "supervisor").await?; + let supervisor = engine.supervisor(sandbox).await?; testkit::ensure!( workload != supervisor, "{sandbox} has no separate supervisor container" diff --git a/tests/suites/features/ocsf/tests/ocsf_stderr.rs b/tests/suites/features/ocsf/tests/ocsf_stderr.rs index fd0c6d9d26..0aa46337c8 100644 --- a/tests/suites/features/ocsf/tests/ocsf_stderr.rs +++ b/tests/suites/features/ocsf/tests/ocsf_stderr.rs @@ -61,9 +61,7 @@ async fn network_events_are_json_on_supervisor_stderr_only(cx: &mut Context) -> .log_level("info") .create_ready() .await?; - let supervisor = engine - .container_for_role(sandbox.name(), "supervisor") - .await?; + let supervisor = engine.supervisor(sandbox.name()).await?; let workload = engine.container_for_role(sandbox.name(), "sandbox").await?; let image_uid = engine.inspect_container(&workload, "{{.Image}}").await?; diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 5d4092dc5a..61bf8c2ba4 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -531,6 +531,7 @@ name = "container-engine-support" version = "0.0.0" dependencies = [ "openshell-testkit", + "serde", "serde_json", "tempfile", "tokio", diff --git a/tests/support/container-engine/Cargo.toml b/tests/support/container-engine/Cargo.toml index 4f76ba92f7..789dfac698 100644 --- a/tests/support/container-engine/Cargo.toml +++ b/tests/support/container-engine/Cargo.toml @@ -13,6 +13,7 @@ publish = false [dependencies] openshell-testkit = { path = "../../testkit/testkit" } +serde = { version = "1", features = ["derive"] } serde_json = "1" tempfile = "3" tokio = { version = "1.43", features = ["process", "time"] } diff --git a/tests/support/container-engine/src/lib.rs b/tests/support/container-engine/src/lib.rs index f7bb9c8f29..ed6670f7f6 100644 --- a/tests/support/container-engine/src/lib.rs +++ b/tests/support/container-engine/src/lib.rs @@ -25,6 +25,8 @@ mod tar; use std::path::Path; use std::time::{Duration, Instant}; +use serde::Deserialize; +use serde::de::DeserializeOwned; use testkit::{Context, Error, Result, ResultExt as _}; use tokio::process::Command; @@ -154,12 +156,54 @@ impl Engine { } /// `container inspect --format format` for one container, where `format` - /// prints JSON, such as `{{json .Mounts}}`. - pub async fn inspect_json(&self, id: &str, format: &str) -> Result { + /// prints JSON, such as `{{json .Mounts}}`, parsed as `T`. + pub async fn inspect_json(&self, id: &str, format: &str) -> Result { let output = self.inspect_container(id, format).await?; serde_json::from_str(output.trim()).context(format!("parse {format} of {id}")) } + /// The supervisor container the driver created for `sandbox`. + pub async fn supervisor(&self, sandbox: &str) -> Result { + self.container_for_role(sandbox, "supervisor").await + } + + /// A container's mounts. + pub async fn mounts(&self, id: &str) -> Result> { + self.inspect_json(id, "{{json .Mounts}}").await + } + + /// A container's command, `.Config.Cmd`. + pub async fn command(&self, id: &str) -> Result> { + Ok(self + .inspect_json::>(id, "{{json .Config.Cmd}}") + .await? + .unwrap_or_default()) + } + + /// A container's environment, `NAME=value` per entry. + pub async fn env(&self, id: &str) -> Result> { + Ok(self + .inspect_json::>(id, "{{json .Config.Env}}") + .await? + .unwrap_or_default()) + } + + /// The names of the Podman secrets a container gets. + pub async fn secret_names(&self, id: &str) -> Result> { + #[derive(Deserialize)] + struct Secret { + #[serde(rename = "Name")] + name: String, + } + let secrets: Option> = + self.inspect_json(id, "{{json .Config.Secrets}}").await?; + Ok(secrets + .unwrap_or_default() + .into_iter() + .map(|secret| secret.name) + .collect()) + } + /// The IDs of every container, running or not, that the driver labeled /// with sandbox ID `sandbox_id`. Sandbox IDs are unique, so this finds /// only the containers of the sandbox the test created. @@ -319,15 +363,68 @@ fn utf8(path: &Path) -> Result<&str> { .ok_or_else(|| Error::msg(format!("{} is not UTF-8", path.display()))) } -/// The values `command`, a container's `.Config.Cmd` as JSON, passes for -/// `flag` (` `), in order. -pub fn flag_values<'a>(command: &'a serde_json::Value, flag: &str) -> Result> { - let args = command - .as_array() - .ok_or_else(|| Error::msg(format!("the command is not a list: {command}")))?; - Ok(args +/// A container mount, as `container inspect` reports it. +#[derive(Clone, Debug, Deserialize, PartialEq, Eq)] +pub struct Mount { + #[serde(rename = "Source")] + pub source: String, + #[serde(rename = "Destination")] + pub destination: String, + #[serde(rename = "RW")] + pub rw: bool, +} + +/// The one mount at `destination`. Fails unless there is exactly one and it +/// is read-only. +pub fn one_read_only_at<'a>(mounts: &'a [Mount], destination: &str) -> Result<&'a Mount> { + let at: Vec<_> = mounts + .iter() + .filter(|mount| mount.destination == destination) + .collect(); + match at.as_slice() { + [mount] if !mount.rw => Ok(mount), + _ => Err(Error::msg(format!( + "expected one read-only mount at {destination}: {mounts:#?}" + ))), + } +} + +/// The values `command` passes for `flag` (` `), in order. +pub fn flag_values<'a>(command: &'a [String], flag: &str) -> Vec<&'a str> { + command .windows(2) .filter(|pair| pair[0] == flag) - .filter_map(|pair| pair[1].as_str()) - .collect()) + .map(|pair| pair[1].as_str()) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn mount(destination: &str, rw: bool) -> Mount { + Mount { + source: format!("/host{destination}"), + destination: destination.to_string(), + rw, + } + } + + #[test] + fn finds_the_one_read_only_mount() { + let mounts: Vec = serde_json::from_str( + r#"[{"Type":"bind","Source":"/a","Destination":"/ca","Mode":"","RW":false}]"#, + ) + .unwrap(); + assert_eq!(one_read_only_at(&mounts, "/ca").unwrap().source, "/a"); + assert!(one_read_only_at(&mounts, "/other").is_err()); + assert!(one_read_only_at(&[mount("/ca", true)], "/ca").is_err()); + assert!(one_read_only_at(&[mount("/ca", false), mount("/ca", false)], "/ca").is_err()); + } + + #[test] + fn reads_flag_values() { + let command = ["run", "--ca", "/a", "--x", "--ca", "/b"].map(String::from); + assert_eq!(flag_values(&command, "--ca"), ["/a", "/b"]); + } } From 8156a00bbc7ade8316710b555a093841e8252232 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 4 Dec 2026 14:16:58 -0800 Subject: [PATCH 09/10] test(features): split the additional CA client into probes Fetch and handshake probes each check one thing, so the test asserts on their output instead of indexing one JSON result. The test host endpoint uses allow_host. Signed-off-by: Matthew Grossman --- tests/suites/features/Cargo.lock | 1 - .../suites/features/additional-ca/Cargo.toml | 1 - .../additional-ca/tests/additional_ca.rs | 143 +++++++++--------- 3 files changed, 70 insertions(+), 75 deletions(-) diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index af33065662..c8a95549b2 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -8,7 +8,6 @@ version = "0.0.0" dependencies = [ "host-server-support", "openshell-testkit", - "serde_json", ] [[package]] diff --git a/tests/suites/features/additional-ca/Cargo.toml b/tests/suites/features/additional-ca/Cargo.toml index 61ec74a950..2e3ef52b40 100644 --- a/tests/suites/features/additional-ca/Cargo.toml +++ b/tests/suites/features/additional-ca/Cargo.toml @@ -18,4 +18,3 @@ harness = false [dependencies] host-server-support = { path = "../../../support/host-server" } openshell-testkit = { path = "../../../testkit/testkit" } -serde_json = "1" diff --git a/tests/suites/features/additional-ca/tests/additional_ca.rs b/tests/suites/features/additional-ca/tests/additional_ca.rs index 2028801eb3..ac3f82984b 100644 --- a/tests/suites/features/additional-ca/tests/additional_ca.rs +++ b/tests/suites/features/additional-ca/tests/additional_ca.rs @@ -11,7 +11,7 @@ //! the gateway's staged CA or remove it and restart the gateway were dropped //! (#5917). The driver suites check how the CA reaches the supervisor. -use host_server_support::{HttpRecorder, TEST_HOST, TestCa}; +use host_server_support::{HttpRecorder, TEST_HOST, TestCa, allow_host}; use testkit::policy::{self, Access, Endpoint as _}; use testkit::{Context, PYTHON_BINARIES, ResultExt as _}; @@ -29,50 +29,40 @@ const BODY: &str = r#"{"additional_ca":"trusted"}"#; /// across drivers. const HOST_RANGES: &[&str] = &["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]; -/// With the workload's default trust, prints one JSON object with: -/// -/// - `matching`: the body of `https://:/`, or the error. -/// - `mismatch`: the error from a TLS handshake with the same server that -/// presents `argv[2]` as the server name, or `null` if it succeeded. -/// - `public`: the status of `https:///`, or the error. -/// +/// Prints the body of `argv[1]` fetched with the workload's default trust. /// A failed request is retried, since a policy reload while the sandbox /// starts can deny it once. -const CLIENT: &str = r#" -import json, socket, ssl, sys, time, urllib.request - -host, mismatch_host, port, public_host = sys.argv[1], sys.argv[2], int(sys.argv[3]), sys.argv[4] - -def retry(attempt): - result = None - for n in range(6): - if n: - time.sleep(1) - try: - return attempt() - except Exception as error: - result = {"error": f"{type(error).__name__}: {error}"} - return result - -def matching(): - with urllib.request.urlopen(f"https://{host}:{port}/", timeout=30) as response: - return {"body": response.read().decode()} - -def mismatch(): - address = socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP)[0][4] - with socket.create_connection(address, timeout=15) as sock: - try: - ssl.create_default_context().wrap_socket(sock, server_hostname=mismatch_host).close() - except ssl.SSLCertVerificationError as error: - return {"rejected": str(error)} - return {"rejected": None} - -def public(): - with urllib.request.urlopen(f"https://{public_host}/", timeout=30) as response: - return {"status": response.status} +const FETCH: &str = r#" +import sys, time, urllib.request + +for attempt in range(6): + if attempt: + time.sleep(1) + try: + with urllib.request.urlopen(sys.argv[1], timeout=30) as response: + sys.stdout.write(response.read().decode()) + break + except Exception as error: + failure = f"{type(error).__name__}: {error}" +else: + sys.exit(failure) +"#; -results = {"matching": retry(matching), "mismatch": mismatch(), "public": retry(public)} -print(json.dumps(results)) +/// Connects to `argv[1]:argv[2]` and starts a TLS handshake with the +/// workload's default trust, presenting `argv[3]` as the server name. Prints +/// why certificate verification rejected it, and fails if it didn't. +const HANDSHAKE: &str = r#" +import socket, ssl, sys + +host, port, server_name = sys.argv[1], int(sys.argv[2]), sys.argv[3] +address = socket.getaddrinfo(host, port, proto=socket.IPPROTO_TCP)[0][4] +with socket.create_connection(address, timeout=15) as sock: + try: + ssl.create_default_context().wrap_socket(sock, server_hostname=server_name).close() + except ssl.SSLCertVerificationError as error: + print(error.verify_message) + sys.exit(0) +sys.exit(f"the handshake as {server_name} succeeded") "#; /// The workload trusts a server whose certificate the additional CA signed, @@ -86,48 +76,55 @@ async fn additional_ca_trusts_matching_and_public_hosts_and_rejects_mismatch( let server = HttpRecorder::start_tls(&identity, BODY).await?; let mut policy = policy::base(); - for host in [TEST_HOST, MISMATCH_HOST] { - let endpoint = policy::allow( - &mut policy, - "additional_ca", - host, - server.port, - PYTHON_BINARIES, - ); - endpoint.rest(Access::Full).enforce().path("/**"); - endpoint.allowed_ips = HOST_RANGES.iter().map(ToString::to_string).collect(); - } + allow_host(&mut policy, "additional_ca", server.port) + .rest(Access::Full) + .enforce() + .path("/**"); + let mismatch = policy::allow( + &mut policy, + "additional_ca_mismatch", + MISMATCH_HOST, + server.port, + PYTHON_BINARIES, + ); + mismatch.rest(Access::Full).enforce().path("/**"); + mismatch.allowed_ips = HOST_RANGES.iter().map(ToString::to_string).collect(); policy::allow(&mut policy, "public", PUBLIC_HOST, 443, PYTHON_BINARIES) .rest(Access::Full) .enforce() .path("/**"); - let sandbox = cx.python_sandbox("aca", policy).create_ready().await?; let port = server.port.to_string(); - let results = sandbox - .run_python(CLIENT, &[TEST_HOST, MISMATCH_HOST, &port, PUBLIC_HOST]) - .await? - .last_json() - .context("run the TLS client")?; - testkit::ensure!( - results["matching"]["body"] == BODY, - "the workload should trust {TEST_HOST}, whose certificate the additional CA signed: {}", - results["matching"] - ); - let rejected = results["mismatch"]["rejected"].as_str().unwrap_or_default(); + sandbox + .run_python(FETCH, &[&format!("https://{TEST_HOST}:{port}/")]) + .await? + .expect_stdout(BODY) + .context(format!( + "the workload should trust {TEST_HOST}, whose certificate the additional CA signed" + ))?; + + let rejected = sandbox + .run_python(HANDSHAKE, &[TEST_HOST, &port, MISMATCH_HOST]) + .await + .context(format!( + "a handshake with {TEST_HOST}'s server as {MISMATCH_HOST} should fail verification" + ))? + .stdout + .to_lowercase(); testkit::ensure!( ["mismatch", "doesn't match"] .iter() - .any(|reason| rejected.to_lowercase().contains(reason)), + .any(|reason| rejected.contains(reason)), "a handshake with {TEST_HOST}'s server as {MISMATCH_HOST} should fail the hostname \ - check: {}", - results["mismatch"] - ); - testkit::ensure!( - results["public"]["status"] == 200, - "the workload should still trust {PUBLIC_HOST} through the system roots: {}", - results["public"] + check, not: {rejected}" ); + + sandbox + .run_python(FETCH, &[&format!("https://{PUBLIC_HOST}/")]) + .await + .context(format!( + "the workload should still trust {PUBLIC_HOST} through the system roots" + ))?; Ok(()) } From ed0ada7bff1e0469f37e81fca182d684d499a00b Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 4 Dec 2026 14:43:34 -0800 Subject: [PATCH 10/10] test(continuity): require a margin between seed and the restart Process start times are derived from the kernel's whole-second boot time, which can move by a second, so a sandbox that never restarted could appear to start after seed. Require the restart to be at least 2 seconds later. Signed-off-by: Matthew Grossman --- tests/suites/continuity/src/sandbox_intent.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/suites/continuity/src/sandbox_intent.rs b/tests/suites/continuity/src/sandbox_intent.rs index 864f82ba57..3e68e01ee7 100644 --- a/tests/suites/continuity/src/sandbox_intent.rs +++ b/tests/suites/continuity/src/sandbox_intent.rs @@ -16,6 +16,11 @@ use crate::scenario::{name, sandbox}; /// The time `seed` ran, in seconds since the epoch on the sandbox's clock, /// and the sandbox's SSH host key fingerprint, one per line. const MARKER: &str = "/sandbox/.continuity-intent"; +/// How much later than `seed` the restarted sandbox's first process must +/// have started. Both times are whole seconds, and the kernel's boot time, +/// from which the start time is computed, can move by a second when the +/// clock is adjusted. A restart takes longer than this. +const RESTART_MARGIN_SECS: u64 = 2; /// Creates a running sandbox that records when `seed` ran and its host key, /// and a sandbox that is stopped. @@ -65,8 +70,9 @@ async fn verify(cx: &mut Context) -> testkit::Result { let observed = Probe::parse(&probe.stdout).context(format!("read the probe output {:?}", probe.stdout))?; testkit::ensure!( - observed.started > observed.seeded, - "sandbox {} has run since {}, before seed recorded {}: the disruption didn't restart it", + observed.started >= observed.seeded + RESTART_MARGIN_SECS, + "sandbox {} has run since {}, within {RESTART_MARGIN_SECS}s of seed recording {}: the \ + disruption didn't restart it", running.name(), observed.started, observed.seeded