diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index c84837c976..641cb0381f 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -116,6 +116,9 @@ jobs: {"environment":"ubuntu-k3s","installer":"k3s","family":"features","package":"routable-host-ip","gateway":"tmachine","runner":"ubuntu-24.04"}, {"environment":"ubuntu-k3s","installer":"k3s-ha","family":"features","package":"routable-host-ip","gateway":"tmachine","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"connect-ssh-supervision","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"fedora-podman-rootless-otlp","installer":"rpm","family":"features","package":"otlp-relay","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"otlp-relay-inactive","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"fedora-podman-rootless-spiffe","installer":"rpm","family":"features","package":"provider-token-exchange","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-keycloak","installer":"rpm","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootless-keycloak","installer":"rpm","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful-userns-default","installer":"rpm","family":"drivers/podman","gateway":"openshell","runner":"ubuntu-24.04"}, diff --git a/e2e/rust/Cargo.lock b/e2e/rust/Cargo.lock index d4afe2b166..b5f42d20de 100644 --- a/e2e/rust/Cargo.lock +++ b/e2e/rust/Cargo.lock @@ -46,15 +46,6 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" -[[package]] -name = "android_system_properties" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" -dependencies = [ - "libc", -] - [[package]] name = "annotate-snippets" version = "0.12.18" @@ -468,20 +459,6 @@ dependencies = [ "rand_core 0.10.1", ] -[[package]] -name = "chrono" -version = "0.4.45" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" -dependencies = [ - "iana-time-zone", - "js-sys", - "num-traits", - "serde", - "wasm-bindgen", - "windows-link", -] - [[package]] name = "cmake" version = "0.1.58" @@ -1008,7 +985,6 @@ checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218" dependencies = [ "futures-channel", "futures-core", - "futures-executor", "futures-io", "futures-sink", "futures-task", @@ -1436,30 +1412,6 @@ dependencies = [ "tower-service", ] -[[package]] -name = "iana-time-zone" -version = "0.1.65" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" -dependencies = [ - "android_system_properties", - "core-foundation-sys", - "iana-time-zone-haiku", - "js-sys", - "log", - "wasm-bindgen", - "windows-core", -] - -[[package]] -name = "iana-time-zone-haiku" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" -dependencies = [ - "cc", -] - [[package]] name = "icu_collections" version = "2.4.0" @@ -1925,7 +1877,7 @@ dependencies = [ "tokio", "tokio-util", "tower", - "tower-http 0.7.1", + "tower-http", "tracing", ] @@ -2054,15 +2006,6 @@ version = "0.4.33" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad" -[[package]] -name = "matchers" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" -dependencies = [ - "regex-automata", -] - [[package]] name = "matchit" version = "0.8.4" @@ -2085,16 +2028,6 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" -[[package]] -name = "metrics" -version = "0.24.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "89550ee9f79e88fef3119de263694973a8adb26c21d75322164fb8c493039fe2" -dependencies = [ - "portable-atomic", - "rapidhash", -] - [[package]] name = "micromap" version = "0.3.0" @@ -2219,15 +2152,6 @@ dependencies = [ "smallvec", ] -[[package]] -name = "nu-ansi-term" -version = "0.50.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "num" version = "0.4.3" @@ -2426,8 +2350,6 @@ dependencies = [ "openshell-core", "openshell-crypto", "openshell-ocsf-validate", - "openshell-otel-test-support", - "opentelemetry-proto", "prost", "rand 0.9.5", "rustls", @@ -2458,19 +2380,6 @@ dependencies = [ "tower", ] -[[package]] -name = "openshell-ocsf" -version = "0.0.0" -dependencies = [ - "chrono", - "serde", - "serde_json", - "serde_repr", - "tracing", - "tracing-subscriber", - "uuid", -] - [[package]] name = "openshell-ocsf-validate" version = "0.0.0" @@ -2480,60 +2389,6 @@ dependencies = [ "thiserror", ] -[[package]] -name = "openshell-otel" -version = "0.0.0" -dependencies = [ - "async-trait", - "bytes", - "futures", - "http", - "http-body-util", - "hyper-rustls", - "hyper-util", - "metrics", - "openshell-crypto", - "openshell-ocsf", - "opentelemetry", - "opentelemetry-http", - "opentelemetry-otlp", - "opentelemetry_sdk", - "rustls", - "rustls-native-certs", - "serde_json", - "thiserror", - "tokio", - "tonic", - "tower-http 0.6.11", - "tracing", - "tracing-opentelemetry", - "tracing-subscriber", - "zeroize", -] - -[[package]] -name = "openshell-otel-test-support" -version = "0.0.0" -dependencies = [ - "bytes", - "http", - "http-body-util", - "hyper", - "hyper-util", - "openshell-crypto", - "openshell-otel", - "opentelemetry-proto", - "prost", - "rcgen", - "rustls", - "tokio", - "tokio-rustls", - "tokio-stream", - "tonic", - "tracing", - "tracing-subscriber", -] - [[package]] name = "openshell-policy-schema" version = "0.0.0" @@ -2563,83 +2418,6 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" -[[package]] -name = "opentelemetry" -version = "0.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8c1f1a6ac9c875a4941e4c7c085b61e8f4daa326de03b4701768c3491a6ad9ee" -dependencies = [ - "futures-core", - "futures-sink", - "js-sys", - "pin-project-lite", - "thiserror", - "tracing", -] - -[[package]] -name = "opentelemetry-http" -version = "0.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "302249bd8ee804789faaa7b5b2cbf79bc61cb864714079c644e3828af5b7e811" -dependencies = [ - "async-trait", - "bytes", - "http", - "opentelemetry", -] - -[[package]] -name = "opentelemetry-otlp" -version = "0.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0756af24841e367128ef31c831999937b8b5c5197d47914590d8f4e2e88c2e1a" -dependencies = [ - "flate2", - "http", - "httpdate", - "opentelemetry", - "opentelemetry-http", - "opentelemetry-proto", - "opentelemetry_sdk", - "prost", - "thiserror", - "tokio", - "tonic", - "tonic-types", -] - -[[package]] -name = "opentelemetry-proto" -version = "0.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d576f5dddc3299341bcd85a04be17b2564844c0c9563214f02d85f2524d1afae" -dependencies = [ - "opentelemetry", - "opentelemetry_sdk", - "prost", - "tonic", - "tonic-prost", -] - -[[package]] -name = "opentelemetry_sdk" -version = "0.33.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "372a912db2974d1990207006fd0e3aa0ef3fd4ad3be43c65cfaadf2206866061" -dependencies = [ - "futures-channel", - "futures-executor", - "futures-util", - "opentelemetry", - "percent-encoding", - "portable-atomic", - "rand 0.9.5", - "thiserror", - "tokio", - "tokio-stream", -] - [[package]] name = "ordered-float" version = "2.10.1" @@ -3074,15 +2852,6 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" -[[package]] -name = "rapidhash" -version = "4.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5da7e78a036ce858e8d55b7e7dc8ba3a88b78350fd2155d3591bbd966b58589e" -dependencies = [ - "rustversion", -] - [[package]] name = "rcgen" version = "0.14.10" @@ -3587,15 +3356,6 @@ dependencies = [ "digest 0.11.3", ] -[[package]] -name = "sharded-slab" -version = "0.1.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" -dependencies = [ - "lazy_static", -] - [[package]] name = "shlex" version = "2.0.1" @@ -4035,15 +3795,6 @@ dependencies = [ "syn 3.0.3", ] -[[package]] -name = "thread_local" -version = "1.1.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" -dependencies = [ - "cfg-if", -] - [[package]] name = "time" version = "0.3.54" @@ -4165,7 +3916,6 @@ dependencies = [ "axum", "base64 0.22.1", "bytes", - "flate2", "h2", "http", "http-body", @@ -4256,23 +4006,6 @@ dependencies = [ "tracing", ] -[[package]] -name = "tower-http" -version = "0.6.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" -dependencies = [ - "bitflags 2.13.1", - "bytes", - "http", - "http-body", - "pin-project-lite", - "tower-layer", - "tower-service", - "tracing", - "uuid", -] - [[package]] name = "tower-http" version = "0.7.1" @@ -4335,64 +4068,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - -[[package]] -name = "tracing-opentelemetry" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a904802a1b902f43638b677ff2a650847e3b4404101b6c586d648e8c1e3e8fe" -dependencies = [ - "js-sys", - "opentelemetry", - "tracing", - "tracing-core", - "tracing-log", - "tracing-subscriber", - "web-time", -] - -[[package]] -name = "tracing-serde" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" -dependencies = [ - "serde", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" -dependencies = [ - "matchers", - "nu-ansi-term", - "once_cell", - "regex-automata", - "serde", - "serde_json", - "sharded-slab", - "smallvec", - "thread_local", - "tracing", - "tracing-core", - "tracing-log", - "tracing-serde", ] [[package]] @@ -4515,12 +4190,6 @@ dependencies = [ "vsimd", ] -[[package]] -name = "valuable" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" - [[package]] name = "vcpkg" version = "0.2.15" @@ -4628,16 +4297,6 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "web-time" -version = "1.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - [[package]] name = "webpki-root-certs" version = "1.0.12" @@ -4699,65 +4358,12 @@ version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -[[package]] -name = "windows-core" -version = "0.62.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" -dependencies = [ - "windows-implement", - "windows-interface", - "windows-link", - "windows-result", - "windows-strings", -] - -[[package]] -name = "windows-implement" -version = "0.60.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "windows-interface" -version = "0.59.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", -] - [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" -[[package]] -name = "windows-result" -version = "0.4.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" -dependencies = [ - "windows-link", -] - -[[package]] -name = "windows-strings" -version = "0.5.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" -dependencies = [ - "windows-link", -] - [[package]] name = "windows-sys" version = "0.52.0" diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 6b0f5d5d1e..b12093d845 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -173,11 +173,6 @@ name = "vm_corporate_proxy" path = "tests/vm_corporate_proxy.rs" required-features = ["e2e-vm"] -[[test]] -name = "provider_token_exchange" -path = "tests/provider_token_exchange.rs" -required-features = ["e2e-podman"] - [[test]] name = "kubernetes_ha_rebalancing" path = "tests/kubernetes_ha_rebalancing.rs" @@ -233,16 +228,9 @@ name = "gpu" path = "tests/gpu.rs" required-features = ["e2e-gpu"] -[[test]] -name = "otlp_relay" -path = "tests/otlp_relay.rs" -required-features = ["e2e-local-container-driver"] - [dependencies] openshell-core = { path = "../../crates/openshell-core", default-features = false, features = ["jwt"], optional = true } openshell-crypto = { path = "../../crates/openshell-crypto" } -openshell-otel-test-support = { path = "../../crates/openshell-otel-test-support" } -opentelemetry-proto = { version = "0.33", default-features = false, features = ["gen-tonic", "trace"] } base64 = "0.22" bollard = "0.20" bytes = "1" diff --git a/e2e/rust/e2e-podman.sh b/e2e/rust/e2e-podman.sh index db4c26dbe8..78afd1f7f2 100755 --- a/e2e/rust/e2e-podman.sh +++ b/e2e/rust/e2e-podman.sh @@ -28,12 +28,10 @@ PODMAN_CI_TESTS=( host_gateway_alias local_driver_token_restart ocsf_jsonl_conformance - otlp_relay podman_corporate_proxy podman_gateway_start podman_host_gateway provider_github_app - provider_token_exchange sandbox_compat_signals_sched ) @@ -87,21 +85,6 @@ if [ "${1:-}" = "${RUN_WITH_GATEWAY_COMMAND}" ]; then exit 0 fi -# An empty selector runs the full Podman suite, including provider_token_exchange. -if [ "${#SELECTED_TESTS[@]}" -eq 0 ] || [[ " ${SELECTED_TESTS[*]} " == *" provider_token_exchange "* ]]; then - export OPENSHELL_E2E_SPIFFE_FIXTURE="${OPENSHELL_E2E_SPIFFE_FIXTURE:-1}" -fi - -# When the selection includes otlp_relay, enable OTLP export in the generated -# gateway config so the test can bind a collector stub on this port. All -# selected tests share the gateway, so they run with the relay enabled too. -# Containers reach the host through host.containers.internal. Set the -# variable to an empty string to disable export and run the relay's inert -# case instead. -if [ "${#SELECTED_TESTS[@]}" -eq 0 ] || [[ " ${SELECTED_TESTS[*]} " == *" otlp_relay "* ]]; then - export OPENSHELL_E2E_OTLP_ENDPOINT="${OPENSHELL_E2E_OTLP_ENDPOINT-http://host.containers.internal:4317}" -fi - if [ -n "${OPENSHELL_GATEWAY_ENDPOINT:-}" ] && [ -z "${OPENSHELL_BIN:-}" ]; then cargo build -p openshell-cli export OPENSHELL_BIN="${ROOT}/target/debug/openshell" diff --git a/e2e/rust/tests/otlp_relay.rs b/e2e/rust/tests/otlp_relay.rs deleted file mode 100644 index fe53630044..0000000000 --- a/e2e/rust/tests/otlp_relay.rs +++ /dev/null @@ -1,420 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -//! Supervisor-direct OTLP trace relay. -//! -//! The gateway wrapper writes `[openshell.gateway.otlp].endpoint` from -//! `OPENSHELL_E2E_OTLP_ENDPOINT` and enables `[openshell.gateway.otlp.agent]` -//! unless `OPENSHELL_E2E_OTLP_AGENT=0`. These tests bind a collector stub on -//! that endpoint's port and prove that a span exported from inside a sandbox -//! arrives with the supervisor's attribution. With the variable unset or -//! empty, or with the relay disabled, the inert case runs instead. - -#![cfg(feature = "e2e-local-container-driver")] - -use std::collections::HashMap; -use std::net::SocketAddr; -use std::time::Duration; - -use base64::Engine as _; -use openshell_e2e::harness::cli; -use openshell_e2e::harness::sandbox::SandboxGuard; -use openshell_otel_test_support::OtlpTestServer; -use openshell_otel_test_support::relay::{ - SANDBOX_ID_KEY, SOURCE_KEY, SOURCE_VALUE, encoded_trace_request, -}; -use serial_test::serial; - -const ENV_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_ENDPOINT"; -const ENV_PROTOCOL: &str = "OTEL_EXPORTER_OTLP_PROTOCOL"; -const ENV_COLLECTOR: &str = "OPENSHELL_OTLP_ENDPOINT"; - -/// Posts the base64 body from `OTLP_BODY_B64` to the relay and prints the -/// status plus the complete environment, one `ENV key=value` line each, so -/// the test can check values and prove the collector address is nowhere. -const EXPORT_SCRIPT: &str = r#" -import base64, os, requests -body = base64.b64decode(os.environ["OTLP_BODY_B64"]) -url = os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] + "/v1/traces" -response = requests.post(url, data=body, headers={"Content-Type": "application/x-protobuf"}, timeout=10) -print("STATUS", response.status_code) -for key, value in sorted(os.environ.items()): - if key != "OTLP_BODY_B64": - print("ENV " + key + "=" + value) -"#; - -/// Main-process variant: the payload is embedded so no `--env` is needed, -/// and the process exits the moment the POST returns. -fn exit_script(body_b64: &str) -> String { - format!( - r#" -import base64, os, requests -body = base64.b64decode("{body_b64}") -url = os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] + "/v1/traces" -response = requests.post(url, data=body, headers={{"Content-Type": "application/x-protobuf"}}, timeout=10) -raise SystemExit(0 if response.status_code == 200 else 1) -"# - ) -} - -/// For the inert case: reports whether an endpoint was injected, then posts -/// to the relay address directly and reports the failure class instead of -/// raising. -const INERT_SCRIPT: &str = r#" -import os, requests -print("ENDPOINT", os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "unset")) -url = "http://192.0.0.8:4318/v1/traces" -try: - response = requests.post(url, data=b"", headers={"Content-Type": "application/x-protobuf"}, timeout=3) - print("STATUS", response.status_code) -except Exception as error: - print("ERROR", type(error).__name__) -"#; - -/// The collector the relay forwards to, when the harness enabled both OTLP -/// export and the agent trace relay. -fn collector_endpoint() -> Option { - let relay_enabled = std::env::var("OPENSHELL_E2E_OTLP_AGENT").as_deref() != Ok("0"); - std::env::var("OPENSHELL_E2E_OTLP_ENDPOINT") - .ok() - .filter(|value| !value.is_empty() && relay_enabled) -} - -fn collector_bind_addr(endpoint: &str) -> SocketAddr { - let url = url::Url::parse(endpoint).expect("OPENSHELL_E2E_OTLP_ENDPOINT is a URL"); - let port = url - .port_or_known_default() - .expect("OPENSHELL_E2E_OTLP_ENDPOINT names a port"); - // Containers reach the host through its bridge address, not loopback. - SocketAddr::from(([0, 0, 0, 0], port)) -} - -/// `host:port` of the collector as the gateway configures it, the string -/// that must not appear anywhere in the sandbox environment. -fn collector_host_port(endpoint: &str) -> String { - let url = url::Url::parse(endpoint).expect("OPENSHELL_E2E_OTLP_ENDPOINT is a URL"); - format!( - "{}:{}", - url.host_str().expect("collector host"), - url.port_or_known_default().expect("collector port") - ) -} - -/// One span with the agent's own service name and spoofed values for both -/// attribution keys, base64-encoded for the workload's environment. -fn encoded_request(span_name: &str) -> String { - let request = encoded_trace_request( - span_name, - &[ - ("service.name", "e2e-agent"), - (SANDBOX_ID_KEY, "spoofed"), - (SOURCE_KEY, "infrastructure"), - ], - ); - base64::engine::general_purpose::STANDARD.encode(request) -} - -/// The harness CLI runner with a `Result` for the failure path. -async fn run_cli(args: &[&str]) -> Result { - let (output, code) = cli::run_cli(args).await; - if code != 0 { - return Err(format!( - "openshell {} failed (exit {code}):\n{output}", - args.join(" ") - )); - } - Ok(output) -} - -async fn sandbox_id(name: &str) -> Result { - let details = run_cli(&["sandbox", "get", name, "--output", "json"]).await?; - let details: serde_json::Value = - serde_json::from_str(&details).map_err(|e| format!("parse sandbox JSON: {e}"))?; - details["id"] - .as_str() - .map(str::to_string) - .ok_or_else(|| format!("sandbox has no id: {details}")) -} - -/// Polls `sandbox get` until the gateway no longer knows the sandbox, so -/// the next create does not overlap the previous teardown. -async fn wait_for_sandbox_gone(name: &str) { - let deadline = tokio::time::Instant::now() + Duration::from_secs(60); - while run_cli(&["sandbox", "get", name]).await.is_ok() { - if tokio::time::Instant::now() >= deadline { - eprintln!("sandbox {name} still listed after delete; continuing"); - return; - } - tokio::time::sleep(Duration::from_millis(250)).await; - } -} - -/// Waits for the sandbox to reach `phase` through the harness, then returns -/// its details for further assertions. -async fn wait_for_sandbox_phase(name: &str, phase: &str) -> Result { - cli::wait_for_sandbox_phase(name, phase, Duration::from_secs(60)).await?; - run_cli(&["sandbox", "get", name]).await -} - -async fn wait_for_sandbox_logs( - sandbox_name: &str, - expected: impl Fn(&str) -> bool, -) -> Result { - let deadline = tokio::time::Instant::now() + Duration::from_secs(15); - loop { - let logs = run_cli(&[ - "logs", - sandbox_name, - "-n", - "500", - "--since", - "5m", - "--source", - "sandbox", - ]) - .await?; - if expected(&logs) { - return Ok(logs); - } - if tokio::time::Instant::now() >= deadline { - return Err(format!( - "timed out waiting for expected sandbox logs:\n{logs}" - )); - } - tokio::time::sleep(Duration::from_millis(250)).await; - } -} - -/// Waits up to `within` until the collector holds every span in `names`, -/// returning the resource attributes keyed by span name. -async fn wait_for_spans( - collector: &OtlpTestServer, - names: &[&str], - within: Duration, -) -> Result>, String> { - let deadline = tokio::time::Instant::now() + within; - loop { - let received = collector.received(); - let received_names: Vec<&str> = received - .spans - .iter() - .map(|span| span.name.as_str()) - .collect(); - if names.iter().all(|name| received_names.contains(name)) { - // Supervisor batches share the collector; `span_resources` pairs - // every span with the resource of the batch it arrived in. - let by_name = received - .spans - .iter() - .zip(received.span_resources.iter()) - .map(|(span, attributes)| (span.name.clone(), attributes.clone())) - .collect(); - return Ok(by_name); - } - if tokio::time::Instant::now() >= deadline { - return Err(format!( - "collector received {received_names:?}, expected all of {names:?}" - )); - } - tokio::time::sleep(Duration::from_millis(250)).await; - } -} - -/// The collector keeps the last value per key, so a spoofed attribute that -/// was appended to rather than replaced is only visible as a duplicate. -fn assert_no_duplicate_resource_keys(collector: &OtlpTestServer) { - let duplicates = collector.received().duplicate_resource_keys; - assert!( - duplicates.is_empty(), - "attribution keys were appended, not replaced: {duplicates:?}" - ); -} - -fn assert_attribution(attributes: &HashMap, sandbox_id: &str) { - assert!( - !attributes - .values() - .any(|value| value == "spoofed" || value == "infrastructure"), - "agent-supplied attribution values must be discarded: {attributes:?}" - ); - assert_eq!( - attributes.get("service.name").map(String::as_str), - Some("e2e-agent"), - "agent service name is preserved: {attributes:?}" - ); - assert_eq!( - attributes.get(SOURCE_KEY).map(String::as_str), - Some(SOURCE_VALUE), - "{attributes:?}" - ); - assert_eq!( - attributes.get(SANDBOX_ID_KEY).map(String::as_str), - Some(sandbox_id), - "spoofed sandbox id is replaced: {attributes:?}" - ); -} - -#[tokio::test] -#[serial] -async fn agent_span_reaches_collector_with_attribution() { - let Some(endpoint) = collector_endpoint() else { - eprintln!("OPENSHELL_E2E_OTLP_ENDPOINT is unset; skipping the collector case"); - return; - }; - let collector = OtlpTestServer::start_on(collector_bind_addr(&endpoint)).await; - - let body = format!("OTLP_BODY_B64={}", encoded_request("e2e-span")); - let mut sandbox = SandboxGuard::create(&[ - "--env", - &body, - "--no-auto-providers", - "--", - "python3", - "-c", - EXPORT_SCRIPT, - ]) - .await - .expect("sandbox exports one span to the relay"); - let output = sandbox.create_output.clone(); - assert!( - output.contains("STATUS 200"), - "relay must accept the export:\n{output}" - ); - // US1-S3: the exact values a standard SDK needs. - assert!( - output.contains(&format!("ENV {ENV_ENDPOINT}=http://192.0.0.8:4318")), - "the relay endpoint is set for the workload:\n{output}" - ); - assert!( - output.contains(&format!("ENV {ENV_PROTOCOL}=http/protobuf")), - "the exporter protocol is set for the workload:\n{output}" - ); - // US1-S4: neither the variable nor the address itself is present anywhere. - assert!( - !output.contains(ENV_COLLECTOR), - "the collector variable must not be visible inside the sandbox:\n{output}" - ); - let host_port = collector_host_port(&endpoint); - assert!( - !output.contains(&host_port), - "the collector address {host_port} must not appear in the sandbox environment:\n{output}" - ); - - let id = sandbox_id(&sandbox.name).await.expect("sandbox id"); - // US1-S1: within 5 seconds. - let spans = wait_for_spans(&collector, &["e2e-span"], Duration::from_secs(5)) - .await - .expect("span reaches the collector stub within 5 s"); - assert_no_duplicate_resource_keys(&collector); - assert_attribution(&spans["e2e-span"], &id); - - sandbox.cleanup().await; - drop(collector.shutdown().await); -} - -#[tokio::test] -#[serial] -async fn relay_is_inert_without_collector() { - if collector_endpoint().is_some() { - eprintln!("the agent trace relay is enabled; skipping the inert case"); - return; - } - - let mut sandbox = - SandboxGuard::create(&["--no-auto-providers", "--", "python3", "-c", INERT_SCRIPT]) - .await - .expect("sandbox attempts an export without a collector"); - let output = sandbox.create_output.clone(); - assert!( - output.contains("ENDPOINT unset"), - "no relay endpoint is injected while the relay is inactive:\n{output}" - ); - assert!( - output.contains("ERROR ConnectionError"), - "the export must fail with a connection error, not a timeout:\n{output}" - ); - - let logs = wait_for_sandbox_logs(&sandbox.name, |logs| { - logs.contains("OTLP agent trace relay inactive") - }) - .await - .expect("supervisor reports the relay as inactive"); - assert!(!logs.contains("OTLP agent trace relay enabled"), "{logs}"); - - sandbox.cleanup().await; -} - -#[tokio::test] -#[serial] -async fn span_emitted_before_exit_is_delivered() { - let Some(endpoint) = collector_endpoint() else { - eprintln!("OPENSHELL_E2E_OTLP_ENDPOINT is unset; skipping the flush case"); - return; - }; - let collector = OtlpTestServer::start_on(collector_bind_addr(&endpoint)).await; - - // The main process posts and exits at once; the supervisor must flush - // the batch before it reports the exit. Five cycles stand in for SC-005. - let names: Vec = (1..=5).map(|i| format!("exit-span-{i}")).collect(); - let mut ids = HashMap::new(); - for name in &names { - let script = exit_script(&encoded_request(name)); - let mut sandbox = SandboxGuard::create_detached_main(&["python3", "-c", &script]) - .await - .expect("sandbox whose main process exports one span and exits"); - let details = match wait_for_sandbox_phase(&sandbox.name, "Completed").await { - Ok(details) => details, - Err(error) => { - let logs = run_cli(&[ - "logs", - &sandbox.name, - "-n", - "500", - "--since", - "5m", - "--source", - "sandbox", - ]) - .await - .unwrap_or_else(|e| format!("(logs unavailable: {e})")); - sandbox.cleanup().await; - panic!( - "main process did not exit after the export: {error}\nsupervisor logs:\n{logs}" - ); - } - }; - assert!( - !details.contains("Exit Code: 1"), - "relay must accept the export:\n{details}" - ); - // US4-S1: the gateway marks the sandbox Completed only after the - // supervisor's exit report, and the supervisor flushes before that - // report, so the span must already be at the collector now. - let snapshot = collector.received(); - assert!( - snapshot.spans.iter().any(|span| &span.name == name), - "{name} must reach the collector before the exit is reported; collector holds {:?}", - snapshot - .spans - .iter() - .map(|span| span.name.as_str()) - .collect::>() - ); - ids.insert( - name.clone(), - sandbox_id(&sandbox.name).await.expect("sandbox id"), - ); - sandbox.cleanup().await; - wait_for_sandbox_gone(&sandbox.name).await; - } - - let name_refs: Vec<&str> = names.iter().map(String::as_str).collect(); - let spans = wait_for_spans(&collector, &name_refs, Duration::from_secs(15)) - .await - .expect("every span emitted right before exit reaches the collector"); - assert_no_duplicate_resource_keys(&collector); - for name in &names { - assert_attribution(&spans[name], &ids[name]); - } - drop(collector.shutdown().await); -} diff --git a/e2e/rust/tests/provider_token_exchange.rs b/e2e/rust/tests/provider_token_exchange.rs deleted file mode 100644 index 9105be98bc..0000000000 --- a/e2e/rust/tests/provider_token_exchange.rs +++ /dev/null @@ -1,1466 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -#![cfg(feature = "e2e-podman")] - -use std::collections::HashMap; -use std::convert::Infallible; -use std::fs; -use std::io::Write as _; -use std::net::{Ipv4Addr, SocketAddr}; -use std::os::unix::fs::PermissionsExt as _; -use std::path::{Path, PathBuf}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; -use std::sync::{Arc, Mutex}; -use std::task::{Context, Poll}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; - -use base64::Engine as _; -use futures_util::future::BoxFuture; -use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey, Header, Validation}; -use openshell_e2e::harness::binary::openshell_cmd; -use openshell_e2e::harness::port::find_free_port; -use openshell_e2e::harness::sandbox::SandboxGuard; -use serde_json::json; -use tempfile::NamedTempFile; -use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; -use tokio::net::{TcpListener, TcpStream, UnixListener}; -use tokio_stream::wrappers::{ReceiverStream, TcpListenerStream, UnixListenerStream}; -use tonic::body::Body as TonicBody; -use tonic::codegen::{Body, http}; -use tonic::{Request, Response, Status}; - -const TRUST_DOMAIN: &str = "openshell-e2e.test"; -const ISSUER: &str = "https://spiffe.openshell-e2e.test"; -const KEY_ID: &str = "openshell-e2e-test-key"; -const USER_SUBJECT_TOKEN: &str = "stored-user-token"; -const INTERMEDIATE_TOKEN: &str = "intermediate-token"; -const FINAL_ACCESS_TOKEN: &str = "final-access-token"; -const TOKEN_TYPE_ACCESS_TOKEN: &str = "urn:ietf:params:oauth:token-type:access_token"; -const CLIENT_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe"; -const IDENTITY_AUDIENCE: &str = "identity-proxy"; -const IDENTITY_JWT_AUDIENCE: &str = "https://identity.openshell-e2e.test"; -const IDENTITY_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; - -// The harness gives this test binary one pair of SPIFFE listener endpoints. -// Serialize their ownership even when the Rust test runner uses many threads. -static SPIFFE_FIXTURE_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(()); - -#[derive(Default)] -struct GrantObservations { - service_issued: [AtomicUsize; 2], - identity_issued: [AtomicUsize; 2], - service_denied: AtomicUsize, - identity_denied: AtomicUsize, - target_requests: AtomicUsize, - target_rejected: AtomicUsize, -} - -impl GrantObservations { - fn issued(&self) -> [(usize, usize); 2] { - std::array::from_fn(|index| { - ( - self.service_issued[index].load(Ordering::SeqCst), - self.identity_issued[index].load(Ordering::SeqCst), - ) - }) - } -} - -const TEST_RSA_PRIVATE_KEY: &str = r"-----BEGIN PRIVATE KEY----- -MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCvCoZ0mVHpCHsF -zeeqw2caNIe/eb4BQUccFPhZfRnF7sCfyB84zTBmuwG2umRBdjFnVsfIIZRp2HcD -OESrRYYiE1RGfjBXImGVg2Wtza0HYhL1sLyX1eaEefylxoilmApAgWDh9p36h8J2 -s5YHwyXPTttx4DpdWDnxju1iNmwoIB8uVE/5amWgbNvlETMBOcB1RxDHtnVy+xJz -jjjrzK4Qz9WsUTHAvngdi4Yyxvci+yKpjYTg5+UWxmAN6iW522TpLe32MDb5Ug1d -trBvvepWmdQ6CBwPhBHCt/sMoSJAYSO4RKeBnBjeLQBXFTxaOv5iTGIsRTX3K471 -epHp3cT5AgMBAAECggEASQlRv/4nZN5SgsH/K8v7zb3kdHsmUly8AJYpaCGgauvr -uN/mUyueyga2uNl+MqhQBef6VWHZjO6y/gdw86v/Q2GgVQebQQhKAnpAp2w+Ceoc -siKMFqi8VkOWLU+xPbM6d97kH3TpRxt1g1T8wYFmWeF0BEiE4eUJzGaQW14M9BJ+ -G0QxmP/zjX9cNpVeApKTjBWKiH4CXG3DuI3pJ93VOMpUlOsrdLXvKGTze0e01itr -MX/MHHTE+VXB4FB+/zKSA4c36egi676OSXrGC/GDmM8ntJ4CUGeD5uZsMSADiAUn -iccv5iGRWVMIKxUS5Q4k0jy8uWuK+QVP4Y6cQWYArwKBgQDhuSNORBNpIGRfsKGN -iJo/h+qinz6pEIpa3D3oVl7rpkyvgIyaTwfXvC1vfdS9V5VIel2gV2Cx0OrI8yrr -nQu1JuNV/rLmtvqX321fgBLRdoiqF3pAy1gbmdUz1elerAIYL578gXQ6jg1bbdic -kJpn0MsoDUJGwvJnXcgLqG7q3wKBgQDGhRIa4oJsj1vqICc8zt8YsCAcot3vjWLH -588X7JdBGOWJdWxfdmGXQRn5Zw9UhMQnYa3uyTBPeVcXopThlPotYeuFhLSU856T -IJzfpzCJzC4zIQayoyvJFrKe7N70iUQ986dewYy9oxQhHvFKd/qe4ylbzZJXpthX -eWEuuBSjJwKBgGkqXt6qLPj/1IQYwUw15tfOtW0LEKCoSi3HCzjidNsJ4hSqqdeD -Fr5WuDyHvcRxt+XKzTBVRYHTOnBhiw+3XasK8UQxpJyFh/+WY1jpTNs2hLnqslTZ -6LUDWSgLc+1d6qPmHAa9Ma/OWz7L0O4xGR9hUiXY95YMYe/y668yzGq1AoGBAJyU -Gsqfu7U6gYmxoKEine6QBFPx1dD7GF2KJdq93jMXGvyHZFoLOkAdtgnz0rCcI0bY -kWKUxwj4MMxQjNM8OPMQl75xBCmz2XA8Od9htDQLmqjzNKAzePabc3lMZTJFDlE6 -29kuGf79IIRbLn/JECDAFT/2baW60Ep2T0OVJ5njAoGAfaCaQ4aVgjI027q7Y5qP -KfNSI8uuA8PLqmUY30I9KFWzN6VDLu00eKa90F4w3CeWRRQWXW1+007tTz3V1mNw -20A24Fi3HGQmXc7NyuLDODTJsWBICuOemCnRkvcxIlxb+ec7jp+XRmzDwKkzSnVN -pM2zFU8SeVkvHKlEuoHaP0s= ------END PRIVATE KEY-----"; //notsecret - -const TEST_RSA_MODULUS_HEX: &str = concat!( - "af0a86749951e9087b05cde7aac3671a3487bf79be0141471c14f8597d19c5eec09fc81f38cd3066bb01b6ba", - "644176316756c7c8219469d877033844ab4586221354467e30572261958365adcdad076212f5b0bc97d5e684", - "79fca5c688a5980a408160e1f69dfa87c276b39607c325cf4edb71e03a5d5839f18eed62366c28201f2e54", - "4ff96a65a06cdbe511330139c0754710c7b67572fb12738e38ebccae10cfd5ac5131c0be781d8b8632c6", - "f722fb22a98d84e0e7e516c6600dea25b9db64e92dedf63036f9520d5db6b06fbdea5699d43a081c0f84", - "11c2b7fb0ca122406123b844a7819c18de2d0057153c5a3afe624c622c4535f72b8ef57a91e9ddc4f9" -); - -#[derive(Clone, PartialEq, prost::Message)] -struct JwtsvidRequest { - #[prost(string, repeated, tag = "1")] - audience: Vec, - #[prost(string, tag = "2")] - spiffe_id: String, -} - -#[derive(Clone, PartialEq, prost::Message)] -struct JwtsvidResponse { - #[prost(message, repeated, tag = "1")] - svids: Vec, -} - -#[derive(Clone, PartialEq, prost::Message)] -struct Jwtsvid { - #[prost(string, tag = "1")] - spiffe_id: String, - #[prost(string, tag = "2")] - svid: String, - #[prost(string, tag = "3")] - hint: String, -} - -#[derive(Clone, PartialEq, prost::Message)] -struct JwtBundlesRequest {} - -#[derive(Clone, PartialEq, prost::Message)] -struct JwtBundlesResponse { - #[prost(map = "string, bytes", tag = "1")] - bundles: HashMap>, -} - -#[derive(Clone)] -struct SpiffeWorkloadApi { - subject: Arc, - jwks: Arc>, - encoding_key: Arc, -} - -impl SpiffeWorkloadApi { - fn jwt_svid(&self, audience: &[String]) -> Result { - let now = unix_timestamp(); - let mut header = Header::new(Algorithm::RS256); - header.kid = Some(KEY_ID.to_string()); - let claims = json!({ - "iss": ISSUER, - "sub": self.subject.as_ref(), - "aud": audience, - "iat": now, - "exp": now + 3600, - }); - openshell_crypto::jwt::encode(&header, &claims, &self.encoding_key) - .map_err(|err| Status::internal(format!("sign JWT-SVID: {err}"))) - } -} - -#[derive(Clone)] -struct SpiffeWorkloadApiServer { - inner: Arc, -} - -impl SpiffeWorkloadApiServer { - fn new(inner: SpiffeWorkloadApi) -> Self { - Self { - inner: Arc::new(inner), - } - } -} - -impl tower::Service> for SpiffeWorkloadApiServer -where - B: Body + Send + 'static, - B::Error: Into> + Send + 'static, -{ - type Response = http::Response; - type Error = Infallible; - type Future = BoxFuture<'static, Result>; - - fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { - Poll::Ready(Ok(())) - } - - fn call(&mut self, req: http::Request) -> Self::Future { - match req.uri().path() { - "/SpiffeWorkloadAPI/FetchJWTSVID" => { - #[derive(Clone)] - struct FetchJwtsvidSvc(Arc); - impl tonic::server::UnaryService for FetchJwtsvidSvc { - type Response = JwtsvidResponse; - type Future = BoxFuture<'static, Result, Status>>; - - fn call(&mut self, request: Request) -> Self::Future { - let inner = Arc::clone(&self.0); - Box::pin(async move { - let request = request.into_inner(); - let svid = inner.jwt_svid(&request.audience)?; - Ok(Response::new(JwtsvidResponse { - svids: vec![Jwtsvid { - spiffe_id: inner.subject.to_string(), - svid, - hint: String::new(), - }], - })) - }) - } - } - - let inner = Arc::clone(&self.inner); - Box::pin(async move { - let codec = tonic_prost::ProstCodec::default(); - let mut grpc = tonic::server::Grpc::new(codec); - Ok(grpc.unary(FetchJwtsvidSvc(inner), req).await) - }) - } - "/SpiffeWorkloadAPI/FetchJWTBundles" => { - #[derive(Clone)] - struct FetchJwtBundlesSvc(Arc); - impl tonic::server::ServerStreamingService for FetchJwtBundlesSvc { - type Response = JwtBundlesResponse; - type ResponseStream = ReceiverStream>; - type Future = - BoxFuture<'static, Result, Status>>; - - fn call(&mut self, _request: Request) -> Self::Future { - let inner = Arc::clone(&self.0); - Box::pin(async move { - let mut bundles = HashMap::new(); - bundles.insert(TRUST_DOMAIN.to_string(), inner.jwks.as_ref().clone()); - let (tx, rx) = tokio::sync::mpsc::channel(1); - tx.send(Ok(JwtBundlesResponse { bundles })) - .await - .map_err(|err| Status::internal(format!("send bundle: {err}")))?; - Ok(Response::new(ReceiverStream::new(rx))) - }) - } - } - - let inner = Arc::clone(&self.inner); - Box::pin(async move { - let codec = tonic_prost::ProstCodec::default(); - let mut grpc = tonic::server::Grpc::new(codec); - Ok(grpc.server_streaming(FetchJwtBundlesSvc(inner), req).await) - }) - } - _ => Box::pin(async move { - let mut response = http::Response::new(TonicBody::empty()); - response.headers_mut().insert( - tonic::Status::GRPC_STATUS, - (tonic::Code::Unimplemented as i32).into(), - ); - response.headers_mut().insert( - http::header::CONTENT_TYPE, - tonic::metadata::GRPC_CONTENT_TYPE, - ); - Ok(response) - }), - } - } -} - -impl tonic::server::NamedService for SpiffeWorkloadApiServer { - const NAME: &'static str = "SpiffeWorkloadAPI"; -} - -struct FixtureHandle { - task: tokio::task::JoinHandle<()>, -} - -impl FixtureHandle { - async fn shutdown(mut self) { - self.task.abort(); - let _ = (&mut self.task).await; - } -} - -impl Drop for FixtureHandle { - fn drop(&mut self) { - self.task.abort(); - } -} - -fn unix_timestamp() -> i64 { - SystemTime::now() - .duration_since(UNIX_EPOCH) - .expect("system time should be after unix epoch") - .as_secs() - .try_into() - .expect("timestamp should fit i64") -} - -fn jwks() -> Vec { - let modulus = hex::decode(TEST_RSA_MODULUS_HEX).expect("valid test RSA modulus hex"); - let n = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(modulus); - let e = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([0x01, 0x00, 0x01]); - serde_json::to_vec(&json!({ - "keys": [{ - "kty": "RSA", - "kid": KEY_ID, - "use": "sig", - "alg": "RS256", - "n": n, - "e": e, - }] - })) - .expect("JWKS should serialize") -} - -async fn start_spiffe_workload_api(path: &Path, subject: &str) -> FixtureHandle { - let api = SpiffeWorkloadApi { - subject: Arc::::from(subject), - jwks: Arc::new(jwks()), - encoding_key: Arc::new( - EncodingKey::from_rsa_pem(TEST_RSA_PRIVATE_KEY.as_bytes()) - .expect("test RSA key should parse"), - ), - }; - let endpoint = path.to_string_lossy(); - if endpoint.starts_with("tcp:") { - let listen = std::env::var("OPENSHELL_E2E_PROVIDER_SPIFFE_LISTEN") - .expect("OPENSHELL_E2E_PROVIDER_SPIFFE_LISTEN must be set for TCP SPIFFE fixture"); - let listener = TcpListener::bind(&listen) - .await - .expect("bind TCP SPIFFE Workload API fixture"); - let incoming = TcpListenerStream::new(listener); - let task = tokio::spawn(async move { - let result = tonic::transport::Server::builder() - .add_service(SpiffeWorkloadApiServer::new(api)) - .serve_with_incoming(incoming) - .await; - if let Err(err) = result { - eprintln!("SPIFFE Workload API fixture failed: {err}"); - } - }); - return FixtureHandle { task }; - } - let _ = fs::remove_file(path); - let listener = UnixListener::bind(path).expect("bind SPIFFE Workload API socket"); - let mut permissions = fs::metadata(path) - .expect("stat SPIFFE Workload API socket") - .permissions(); - permissions.set_mode(0o777); - fs::set_permissions(path, permissions).expect("chmod SPIFFE Workload API socket"); - let incoming = UnixListenerStream::new(listener); - let task = tokio::spawn(async move { - let result = tonic::transport::Server::builder() - .add_service(SpiffeWorkloadApiServer::new(api)) - .serve_with_incoming(incoming) - .await; - if let Err(err) = result { - eprintln!("SPIFFE Workload API fixture failed: {err}"); - } - }); - FixtureHandle { task } -} - -// Forms and JWT headers can span TCP reads. Read the bounded, Content-Length -// framed request completely so packet boundaries cannot change fixture results. -async fn read_http_request(stream: &mut TcpStream) -> Option { - tokio::time::timeout(Duration::from_secs(5), async { - let mut request = Vec::new(); - let mut buffer = [0_u8; 4096]; - loop { - let length = stream.read(&mut buffer).await.ok()?; - if length == 0 || request.len() + length > 32 * 1024 { - return None; - } - request.extend_from_slice(&buffer[..length]); - if let Some(end) = request.windows(4).position(|bytes| bytes == b"\r\n\r\n") { - let headers = std::str::from_utf8(&request[..end]).ok()?; - let content_length = headers - .lines() - .filter_map(|line| line.split_once(':')) - .find(|(name, _)| name.eq_ignore_ascii_case("content-length")) - .map_or(Some(0), |(_, value)| value.trim().parse::().ok())?; - if request.len() >= end.checked_add(4)?.checked_add(content_length)? { - return String::from_utf8(request).ok(); - } - } - } - }) - .await - .ok() - .flatten() -} - -fn verifies_jwt_svid(token: &str, instance: &str) -> bool { - let keys: jsonwebtoken::jwk::JwkSet = - serde_json::from_slice(&jwks()).expect("fixture JWKS should parse"); - let key = DecodingKey::from_jwk(keys.find(KEY_ID).expect("fixture signing key exists")) - .expect("fixture verification key should parse"); - let mut validation = Validation::new(Algorithm::RS256); - validation.set_issuer(&[ISSUER]); - validation.set_audience(&[format!("{IDENTITY_JWT_AUDIENCE}/{instance}")]); - validation.sub = Some(format!("spiffe://{TRUST_DOMAIN}/openshell/sandbox/e2e")); - validation.set_required_spec_claims(&["exp", "iat", "iss", "sub", "aud"]); - jsonwebtoken::decode::(token, &key, &validation) - .is_ok_and(|verified| verified.header.kid.as_deref() == Some(KEY_ID)) -} - -fn token_form(request: &str) -> HashMap { - let (_, body) = request.split_once("\r\n\r\n").unwrap_or_default(); - url::form_urlencoded::parse(body.as_bytes()) - .into_owned() - .collect() -} - -async fn write_token_response(stream: &mut TcpStream, access_token: Option<&str>, ttl: u64) { - let (status, body) = if let Some(access_token) = access_token { - ( - "HTTP/1.1 200 OK", - json!({"access_token": access_token, "token_type": "Bearer", "expires_in": ttl}) - .to_string(), - ) - } else { - ( - "HTTP/1.1 400 Bad Request", - json!({"error": "invalid_grant"}).to_string(), - ) - }; - let response = format!( - "{status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", - body.len() - ); - let _ = stream.write_all(response.as_bytes()).await; -} - -async fn start_gateway_token_endpoint( - port: u16, - observations: Arc, -) -> FixtureHandle { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) - .await - .expect("bind gateway token endpoint"); - let task = tokio::spawn(async move { - loop { - let Ok((mut stream, _peer)) = listener.accept().await else { - break; - }; - let observations = Arc::clone(&observations); - tokio::spawn(async move { - let Some(request) = read_http_request(&mut stream).await else { - return; - }; - let form = token_form(&request); - let field = |name: &str| form.get(name).map_or("", String::as_str); - let valid = request.starts_with("POST /token ") - && field("grant_type") == "urn:ietf:params:oauth:grant-type:token-exchange" - && field("client_assertion_type") == CLIENT_ASSERTION_TYPE - && field("subject_token_type") == TOKEN_TYPE_ACCESS_TOKEN - && field("requested_token_type") == TOKEN_TYPE_ACCESS_TOKEN - && !field("client_assertion").is_empty(); - let mut access_token = None; - for (index, instance) in ["a", "b"].into_iter().enumerate() { - if valid - && field("subject_token") == format!("{USER_SUBJECT_TOKEN}-{instance}") - && field("audience") - == format!("spiffe://{TRUST_DOMAIN}/openshell/sandbox/e2e") - && field("scope").is_empty() - { - access_token = Some(format!("{INTERMEDIATE_TOKEN}-{instance}")); - } else if valid - && field("subject_token") == format!("{INTERMEDIATE_TOKEN}-{instance}") - && field("scope") == "service.read" - { - if field("audience") == format!("service-{instance}") { - observations.service_issued[index].fetch_add(1, Ordering::SeqCst); - access_token = Some(format!("{FINAL_ACCESS_TOKEN}-{instance}")); - } else if field("audience") == format!("denied-service-{instance}") { - observations.service_denied.fetch_add(1, Ordering::SeqCst); - } - } - } - write_token_response(&mut stream, access_token.as_deref(), 600).await; - }); - } - }); - FixtureHandle { task } -} - -// This issuer returns the actual Workload API JWT-SVID after checking its -// signature and audience. No new production grant type or sandbox-visible -// credential is needed to exercise custom-header injection. -async fn start_identity_token_endpoint( - port: u16, - observations: Arc, -) -> FixtureHandle { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) - .await - .expect("bind identity token endpoint"); - let task = tokio::spawn(async move { - loop { - let Ok((mut stream, _peer)) = listener.accept().await else { - break; - }; - let observations = Arc::clone(&observations); - tokio::spawn(async move { - let Some(request) = read_http_request(&mut stream).await else { - return; - }; - let form = token_form(&request); - let field = |name: &str| form.get(name).map_or("", String::as_str); - let mut access_token = None; - for (index, instance) in ["a", "b"].into_iter().enumerate() { - let valid = request.starts_with("POST /identity-token ") - && field("grant_type") == "client_credentials" - && field("client_assertion_type") == IDENTITY_ASSERTION_TYPE - && field("scope") == "identity.read" - && verifies_jwt_svid(field("client_assertion"), instance); - if valid && field("audience") == format!("{IDENTITY_AUDIENCE}-{instance}") { - observations.identity_issued[index].fetch_add(1, Ordering::SeqCst); - access_token = Some(field("client_assertion")); - } else if valid && field("audience") == format!("denied-identity-{instance}") { - observations.identity_denied.fetch_add(1, Ordering::SeqCst); - } - } - write_token_response(&mut stream, access_token, 900).await; - }); - } - }); - FixtureHandle { task } -} - -async fn start_protected_target(port: u16, observations: Arc) -> FixtureHandle { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, port))) - .await - .expect("bind protected target"); - let task = tokio::spawn(async move { - loop { - let Ok((mut stream, _peer)) = listener.accept().await else { - break; - }; - let observations = Arc::clone(&observations); - tokio::spawn(async move { - // Count any request bytes, including an incomplete header. A - // failed grant may open a TCP stream but must send no request. - let mut byte = [0_u8; 1]; - if !matches!( - tokio::time::timeout(Duration::from_secs(5), stream.peek(&mut byte)).await, - Ok(Ok(1)) - ) { - return; - } - observations.target_requests.fetch_add(1, Ordering::SeqCst); - let Some(request) = read_http_request(&mut stream).await else { - return; - }; - let headers = request.split("\r\n\r\n").next().unwrap_or_default(); - let header_values = |name: &str| { - headers - .lines() - .filter_map(|line| line.split_once(':')) - .filter(|(key, _)| key.eq_ignore_ascii_case(name)) - .map(|(_, value)| value.trim()) - .collect::>() - }; - let bearer = header_values("authorization"); - let identity = header_values("x-workload-jwt"); - let ok = ["a", "b"].into_iter().any(|instance| { - request.starts_with(&format!("GET /resource/{instance} ")) - && bearer.len() == 1 - && bearer[0] == format!("Bearer {FINAL_ACCESS_TOKEN}-{instance}") - && identity.len() == 1 - && verifies_jwt_svid(identity[0], instance) - }); - let (status, body) = if ok { - ("HTTP/1.1 200 OK", "independent-grants-ok") - } else { - // Keep rejection evidence even if the workload retries and - // a later request happens to receive the correct credentials. - observations.target_rejected.fetch_add(1, Ordering::SeqCst); - ( - "HTTP/1.1 401 Unauthorized", - "credential-verification-failed", - ) - }; - let response = format!( - "{status}\r\ncontent-type: text/plain\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}", - body.len() - ); - let _ = stream.write_all(response.as_bytes()).await; - }); - } - }); - FixtureHandle { task } -} - -async fn run_cli(args: &[&str]) -> Result<(), String> { - let output = openshell_cmd() - .args(args) - .output() - .await - .map_err(|_| "could not spawn openshell CLI".to_string())?; - if output.status.success() { - Ok(()) - } else { - // Provider creation arguments contain the stored subject token. - // Keep command arguments and raw diagnostics out of test failures. - Err(format!( - "openshell command failed; exit={:?}", - output.status.code() - )) - } -} - -async fn run_cli_ignore_error(args: &[&str]) { - let _ = openshell_cmd().args(args).output().await; -} - -fn write_profile( - profile_type: &str, - token_port: u16, - identity_port: u16, - target_port: u16, - instance: &str, -) -> NamedTempFile { - let token_endpoint = format!("http://127.0.0.1:{token_port}/token"); - let mut file = tempfile::Builder::new() - .suffix(".yaml") - .tempfile() - .expect("create provider profile temp file"); - let profile = format!( - r"id: {profile_type} -display_name: Podman token exchange e2e -description: Independent bearer and JWT-SVID grants for one request -category: other -credentials: - - name: subject_token - description: Stored user subject token - required: true - - name: access_token - description: Access token obtained through token exchange - required: false - auth_style: bearer - header_name: Authorization - token_grant: - grant_type: token_exchange - token_endpoint: {token_endpoint} - audience: service-{instance} - scopes: [service.read] - jwt_svid_audience: {token_endpoint} - client_assertion_type: {CLIENT_ASSERTION_TYPE} - requested_token_type: {TOKEN_TYPE_ACCESS_TOKEN} - cache_ttl_seconds: 300 - audience_overrides: - - path: /deny-service/{instance} - audience: denied-service-{instance} - subject_token: - source: provider_credential - credential: subject_token - subject_token_type: {TOKEN_TYPE_ACCESS_TOKEN} - - name: workload_identity - description: Signed workload identity for the identity proxy - required: false - auth_style: header - header_name: X-Workload-Jwt - token_grant: - grant_type: client_credentials - token_endpoint: http://127.0.0.1:{identity_port}/identity-token - audience: {IDENTITY_AUDIENCE}-{instance} - scopes: [identity.read] - jwt_svid_audience: {IDENTITY_JWT_AUDIENCE}/{instance} - client_assertion_type: {IDENTITY_ASSERTION_TYPE} - cache_ttl_seconds: 600 - audience_overrides: - - path: /deny-identity/{instance} - audience: denied-identity-{instance} -endpoints: - - host: host.openshell.internal - port: {target_port} - path: /** - protocol: rest - access: read-write - enforcement: enforce - allowed_ips: - - 10.0.0.0/8 - - 169.254.0.0/16 - - 172.0.0.0/8 - - 192.168.0.0/16 -binaries: - - /** -" - ); - file.write_all(profile.as_bytes()) - .expect("write provider profile"); - file.flush().expect("flush provider profile"); - file -} - -/// Writes a profile with one bearer token-exchange grant bound to `/{route}/**`. -/// Each route carries its own audience so the token endpoint can tell which -/// endpoint's grant the supervisor selected. -fn write_route_profile( - profile_type: &str, - token_port: u16, - target_port: u16, - route: &str, -) -> NamedTempFile { - let token_endpoint = format!("http://127.0.0.1:{token_port}/token"); - let mut file = tempfile::Builder::new() - .suffix(".yaml") - .tempfile() - .expect("create provider profile temp file"); - let profile = format!( - r"id: {profile_type} -display_name: Podman token exchange route e2e -description: Route-bound bearer grant -category: other -credentials: - - name: subject_token - description: Stored user subject token - required: true - - name: access_token - description: Access token obtained through token exchange - required: false - auth_style: bearer - header_name: Authorization - token_grant: - grant_type: token_exchange - token_endpoint: {token_endpoint} - audience: audience-{route} - jwt_svid_audience: {token_endpoint} - client_assertion_type: {CLIENT_ASSERTION_TYPE} - requested_token_type: {TOKEN_TYPE_ACCESS_TOKEN} - cache_ttl_seconds: 300 - subject_token: - source: provider_credential - credential: subject_token - subject_token_type: {TOKEN_TYPE_ACCESS_TOKEN} -endpoints: - - host: host.openshell.internal - port: {target_port} - path: /{route}/** - protocol: rest - access: read-write - enforcement: enforce - allowed_ips: - - 10.0.0.0/8 - - 169.254.0.0/16 - - 172.0.0.0/8 - - 192.168.0.0/16 -binaries: - - /** -" - ); - file.write_all(profile.as_bytes()) - .expect("write provider profile"); - file.flush().expect("flush provider profile"); - file -} - -fn sandbox_script() -> String { - r"set -eu -echo token-server-ready -while true; do sleep 60; done -" - .to_string() -} - -async fn sandbox_exec_http( - sandbox_name: &str, - target_port: u16, - path: &str, - expect_denied: bool, -) -> Result { - let url = format!("http://host.openshell.internal:{target_port}{path}"); - let expect_denied_python = if expect_denied { "True" } else { "False" }; - let script = format!( - r#"import base64, json, os, re, urllib.error, urllib.request, uuid - -def contains_credential(value): - if any(marker in value for marker in ( - "stored-user-token", "intermediate-token", "final-access-token", "openshell:resolve:" - )): - return True - for token in re.findall(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", value): - try: - payload = token.split(".")[1] - claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) - if claims.get("iss") == "{ISSUER}": - return True - except (ValueError, UnicodeError): - pass - return False - -if any(contains_credential(value) for value in os.environ.values()): - raise RuntimeError("provider credential material reached the workload environment") -request = urllib.request.Request({url:?}, headers={{ - "Authorization": "Bearer agent-supplied", - "X-Workload-Jwt": "agent-supplied", -}}) -try: - with urllib.request.urlopen(request, timeout=10) as response: - body = response.read().decode() - if contains_credential(body): - raise RuntimeError("provider credential material reached the workload response") - if {expect_denied_python}: - raise RuntimeError("failed grant unexpectedly reached the target") - print(body) -except urllib.error.HTTPError as error: - body = error.read().decode() - if contains_credential(body): - raise RuntimeError("provider credential material reached the workload error") - if not {expect_denied_python} or error.code != 502: - raise RuntimeError("unexpected HTTP response") from None - # The refusal names the exchange with an opaque ID and nothing else. - request_id = error.headers.get("x-openshell-request-id", "") - if str(uuid.UUID(request_id)) != request_id: - raise RuntimeError("refusal did not carry a canonical request ID") - print("grant-denied") -"# - ); - let mut last_status = None; - for _ in 0..20 { - let output = openshell_cmd() - .args([ - "sandbox", - "exec", - "--name", - sandbox_name, - "--no-tty", - "--", - "python3", - "-c", - &script, - ]) - .output() - .await - .map_err(|_| "could not spawn sandbox HTTP probe".to_string())?; - if output.status.success() { - // The child emits fixed markers only. Never return raw stderr: - // runtime failures can include request or credential diagnostics. - let stdout = String::from_utf8_lossy(&output.stdout); - let expected = if expect_denied { - "grant-denied" - } else { - "independent-grants-ok" - }; - if stdout.trim() == expected { - return Ok(expected.to_string()); - } - return Err("sandbox probe returned unexpected output".to_string()); - } - last_status = output.status.code(); - tokio::time::sleep(Duration::from_millis(500)).await; - } - Err(format!("sandbox HTTP probe failed; exit={last_status:?}")) -} - -async fn create_provider_instance( - token_port: u16, - identity_port: u16, - target_port: u16, - instance: &str, -) -> String { - let name = format!("podman-grants-{instance}-{}", std::process::id()); - run_cli_ignore_error(&["provider", "delete", &name, "--yes"]).await; - run_cli_ignore_error(&["profile", "delete", &name, "--yes"]).await; - let profile = write_profile(&name, token_port, identity_port, target_port, instance); - let profile_path = profile - .path() - .to_str() - .expect("profile path should be UTF-8"); - run_cli(&["profile", "import", "-f", profile_path]) - .await - .expect("import independent-grant profile"); - run_cli(&[ - "provider", - "create", - "--name", - &name, - "--type", - &name, - "--credential", - &format!("subject_token={USER_SUBJECT_TOKEN}-{instance}"), - ]) - .await - .expect("create provider instance"); - name -} - -#[tokio::test] -async fn podman_provider_token_exchange_injects_independent_grants_across_sandboxes() { - let _fixture_guard = SPIFFE_FIXTURE_LOCK.lock().await; - let gateway_socket = PathBuf::from( - std::env::var("OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET") - .expect("OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET must be set by e2e-podman.sh"), - ); - let provider_socket = PathBuf::from( - std::env::var("OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET") - .expect("OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET must be set by e2e-podman.sh"), - ); - let token_port = find_free_port(); - let identity_port = find_free_port(); - let target_port = find_free_port(); - let gateway_subject = format!("spiffe://{TRUST_DOMAIN}/openshell/gateway"); - // The mock shares a workload subject. Distinct providers and JWT audiences - // test cross-sandbox credential isolation, not production SPIRE attestation. - let supervisor_subject = format!("spiffe://{TRUST_DOMAIN}/openshell/sandbox/e2e"); - let observations = Arc::new(GrantObservations::default()); - let _gateway_spiffe = start_spiffe_workload_api(&gateway_socket, &gateway_subject).await; - let _provider_spiffe = start_spiffe_workload_api(&provider_socket, &supervisor_subject).await; - let _gateway_token = start_gateway_token_endpoint(token_port, Arc::clone(&observations)).await; - let _identity_token = - start_identity_token_endpoint(identity_port, Arc::clone(&observations)).await; - let _target = start_protected_target(target_port, Arc::clone(&observations)).await; - - let mut provider_names = Vec::new(); - for instance in ["a", "b"] { - provider_names - .push(create_provider_instance(token_port, identity_port, target_port, instance).await); - } - - let script = sandbox_script(); - let mut sandbox_a = SandboxGuard::create_keep_with_args( - &["--provider", &provider_names[0]], - &["sh", "-lc", &script], - "token-server-ready", - ) - .await - .expect("create sandbox A"); - let mut sandbox_b = SandboxGuard::create_keep_with_args( - &["--provider", &provider_names[1]], - &["sh", "-lc", &script], - "token-server-ready", - ) - .await - .expect("create sandbox B"); - - // Both supervisors request the same host/port concurrently. The target - // verifies each path's distinct bearer and signed JWT audience together. - let initial = tokio::join!( - sandbox_exec_http(&sandbox_a.name, target_port, "/resource/a", false), - sandbox_exec_http(&sandbox_b.name, target_port, "/resource/b", false), - ); - let before_cache = observations.issued(); - let cached = tokio::join!( - sandbox_exec_http(&sandbox_a.name, target_port, "/resource/a", false), - sandbox_exec_http(&sandbox_b.name, target_port, "/resource/b", false), - ); - let after_cache = observations.issued(); - let target_requests = observations.target_requests.load(Ordering::SeqCst); - // An audience override forces acquisition of only the failing credential; - // the other credential remains cached from the successful request. - let denied = tokio::join!( - sandbox_exec_http(&sandbox_a.name, target_port, "/deny-service/a", true), - sandbox_exec_http(&sandbox_b.name, target_port, "/deny-identity/b", true), - ); - - sandbox_a.cleanup().await; - sandbox_b.cleanup().await; - for name in &provider_names { - run_cli_ignore_error(&["provider", "delete", name, "--yes"]).await; - run_cli_ignore_error(&["profile", "delete", name, "--yes"]).await; - } - // Release the shared SPIFFE endpoints before the next test binds them. - _target.shutdown().await; - _identity_token.shutdown().await; - _gateway_token.shutdown().await; - _provider_spiffe.shutdown().await; - _gateway_spiffe.shutdown().await; - - for outcome in [initial.0, initial.1, cached.0, cached.1] { - assert_eq!( - outcome.expect("independent grant request should succeed"), - "independent-grants-ok" - ); - } - assert_eq!( - observations.target_rejected.load(Ordering::SeqCst), - 0, - "no request may present mismatched or untrusted credentials, even before a retry" - ); - assert!( - before_cache - .iter() - .all(|(service, identity)| *service > 0 && *identity > 0), - "each provider instance must acquire both credentials" - ); - assert_eq!( - after_cache, before_cache, - "repeat requests should use both caches" - ); - for outcome in [denied.0, denied.1] { - assert_eq!( - outcome.expect("failed grant should return 502"), - "grant-denied" - ); - } - assert!(observations.service_denied.load(Ordering::SeqCst) > 0); - assert!(observations.identity_denied.load(Ordering::SeqCst) > 0); - assert_eq!( - observations.target_requests.load(Ordering::SeqCst), - target_requests, - "neither failed grant may forward any request bytes" - ); -} - -// Read one whole fixture request without consuming the following keepalive -// request. OAuth forms can arrive separately from their headers. -async fn read_route_fixture_request( - stream: &mut TcpStream, - observed_bytes: Option<&AtomicUsize>, -) -> Result, String> { - tokio::time::timeout(Duration::from_secs(30), async { - let mut bytes = Vec::new(); - while !bytes.ends_with(b"\r\n\r\n") { - let mut byte = [0]; - if stream - .read(&mut byte) - .await - .map_err(|err| err.to_string())? - == 0 - { - return if bytes.is_empty() { - Ok(None) - } else { - Err("partial fixture header".into()) - }; - } - bytes.push(byte[0]); - if let Some(observed) = observed_bytes { - observed.fetch_add(1, Ordering::Relaxed); - } - if bytes.len() > 16 * 1024 { - return Err("fixture header exceeds limit".into()); - } - } - let header = std::str::from_utf8(&bytes).map_err(|err| err.to_string())?; - let length = header - .lines() - .filter_map(|line| line.split_once(':')) - .find(|(name, _)| name.eq_ignore_ascii_case("content-length")) - .map(|(_, value)| value.trim().parse::()) - .transpose() - .map_err(|err| err.to_string())? - .unwrap_or(0); - if length > 64 * 1024 { - return Err("fixture body exceeds limit".into()); - } - let header_len = bytes.len(); - bytes.resize(header_len + length, 0); - stream - .read_exact(&mut bytes[header_len..]) - .await - .map_err(|err| err.to_string())?; - if let Some(observed) = observed_bytes { - observed.fetch_add(length, Ordering::Relaxed); - } - String::from_utf8(bytes) - .map(Some) - .map_err(|err| err.to_string()) - }) - .await - .map_err(|_| "fixture request timed out".to_owned())? -} - -#[derive(Default)] -struct RouteGrantState { - fail_next_b: AtomicBool, - supervisor_requests: Mutex>, - failed_request_id: Mutex>, -} - -async fn start_route_token_endpoint(port: u16, state: Arc) -> FixtureHandle { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) - .await - .expect("bind route token endpoint"); - let task = tokio::spawn(async move { - let mut requests = tokio::task::JoinSet::new(); - loop { - tokio::select! { - accepted = listener.accept() => { - let Ok((mut stream, _)) = accepted else { break; }; - let state = state.clone(); - requests.spawn(async move { - let Ok(Some(request)) = read_route_fixture_request(&mut stream, None).await else { return; }; - let form = request.split_once("\r\n\r\n").map_or("", |(_, body)| body); - let fields = form.split('&').filter_map(|part| part.split_once('=')).collect::>(); - let subject = fields.get("subject_token").copied().unwrap_or_default(); - let route = match subject { - "stored-a" | "intermediate-a" => "a", - "stored-b" | "intermediate-b" => "b", - _ => "", - }; - let supervisor = subject.starts_with("intermediate-"); - let valid = !route.is_empty() && request.starts_with("POST /token ") - && fields.get("client_assertion").is_some_and(|value| !value.is_empty()) - // Gateway exchange targets the supervisor's SPIFFE - // subject; final exchange targets the route audience. - && fields.get("audience").is_some_and(|value| !value.is_empty() - && (!supervisor || *value == format!("audience-{route}"))); - let fail = if valid && supervisor { - state.supervisor_requests.lock().expect("route grant requests lock").push(route.to_owned()); - route == "b" && state.fail_next_b.swap(false, Ordering::SeqCst) - } else { false }; - let (status, body) = if fail { - let request_id = request.split_once("\r\n\r\n") - .map(|(headers, _)| headers) - .unwrap_or_default() - .lines() - .filter_map(|line| line.split_once(':')) - .find(|(name, _)| name.eq_ignore_ascii_case("x-openshell-request-id")) - .map(|(_, value)| value.trim().to_owned()); - *state.failed_request_id.lock().expect("failed grant request ID lock") = request_id; - ("HTTP/1.1 503 Service Unavailable", json!({"error": "temporary_failure"}).to_string()) - } else if valid { - let stage = if supervisor { "final" } else { "intermediate" }; - ("HTTP/1.1 200 OK", json!({ - "access_token": format!("{stage}-{route}"), "token_type": "Bearer", "expires_in": 300 - }).to_string()) - } else { - ("HTTP/1.1 400 Bad Request", json!({"error": "unexpected_route_exchange"}).to_string()) - }; - let response = format!("{status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len()); - let _ = tokio::time::timeout(Duration::from_secs(5), stream.write_all(response.as_bytes())).await; - }); - } - _ = requests.join_next(), if !requests.is_empty() => {} - } - } - }); - FixtureHandle { task } -} - -struct RouteTargetRequest { - connection: usize, - path: String, - authorization: Vec, - bytes: usize, -} - -struct RouteTargetHandle { - stop: Option>, - task: tokio::task::JoinHandle>, -} - -impl RouteTargetHandle { - async fn drain(mut self) -> Result<(), String> { - if let Some(stop) = self.stop.take() { - // A closed receiver means the task already stopped; joining still - // reports its error rather than hiding it behind the stop signal. - let _ = stop.send(()); - } - tokio::time::timeout(Duration::from_secs(35), &mut self.task) - .await - .map_err(|_| "route target did not drain accepted connections".to_owned())? - .map_err(|err| format!("route target task failed: {err}"))? - } -} - -impl Drop for RouteTargetHandle { - fn drop(&mut self) { - // Failure and timeout cleanup must also cancel the owned JoinSet. - self.task.abort(); - } -} - -async fn start_route_target( - port: u16, - observed: Arc>>, - observed_bytes: Arc, -) -> RouteTargetHandle { - let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, port))) - .await - .expect("bind route target"); - let (stop, mut stopped) = tokio::sync::oneshot::channel(); - let task = tokio::spawn(async move { - let next_connection = AtomicUsize::new(1); - let mut connections = tokio::task::JoinSet::new(); - let mut completed = Vec::new(); - let mut accept_error = None; - loop { - tokio::select! { - // Once the workload has closed, accept queued connections - // before stopping so their buffered bytes are also observed. - biased; - accepted = listener.accept() => { - let (mut stream, _) = match accepted { - Ok(accepted) => accepted, - Err(err) => { - accept_error = Some(format!("route target accept failed: {err}")); - break; - } - }; - let connection = next_connection.fetch_add(1, Ordering::Relaxed); - let observed = observed.clone(); - let observed_bytes = observed_bytes.clone(); - connections.spawn(async move { - loop { - let Some(request) = read_route_fixture_request(&mut stream, Some(&observed_bytes)).await? else { return Ok::<(), String>(()); }; - let path = request.lines().next().and_then(|line| line.split_whitespace().nth(1)).unwrap_or_default().to_owned(); - let authorization = request.lines().filter_map(|line| line.split_once(':')) - .filter(|(name, _)| name.eq_ignore_ascii_case("authorization")) - .map(|(_, value)| value.trim().to_owned()).collect::>(); - let expected = if path.starts_with("/a/") { "Bearer final-a" } else { "Bearer final-b" }; - let valid = authorization.len() == 1 && authorization[0] == expected; - observed.lock().expect("route target observations lock").push(RouteTargetRequest { connection, path, authorization, bytes: request.len() }); - let status = if valid { "HTTP/1.1 200 OK" } else { "HTTP/1.1 401 Unauthorized" }; - let response = format!("{status}\r\nContent-Length: 0\r\n\r\n"); - tokio::time::timeout(Duration::from_secs(5), stream.write_all(response.as_bytes())).await - .map_err(|_| "route target response write timed out".to_owned())? - .map_err(|err| format!("route target response write failed: {err}"))?; - } - }); - } - _ = &mut stopped => break, - Some(result) = connections.join_next(), if !connections.is_empty() => completed.push(result), - } - } - drop(listener); - // Only EOF proves that the byte counter includes everything sent on - // each accepted connection. Do not abort pending readers on success. - while let Some(result) = connections.join_next().await { - completed.push(result); - } - if let Some(error) = accept_error { - return Err(error); - } - for result in completed { - result.map_err(|err| format!("route target reader task failed: {err}"))??; - } - Ok(()) - }); - RouteTargetHandle { - stop: Some(stop), - task, - } -} - -async fn exec_within(sandbox: &SandboxGuard, script: &str) -> Result { - tokio::time::timeout( - Duration::from_secs(60), - sandbox.exec(&["python3", "-c", script]), - ) - .await - .map_err(|_| "route workload timed out".to_owned())? -} - -/// Poll `sandbox get` until the last token-grant failure is present or absent. -async fn wait_for_token_grant_failure( - name: &str, - present: bool, -) -> Result { - for _ in 0..30 { - let output = openshell_cmd() - .args(["sandbox", "get", name, "--output", "json"]) - .output() - .await - .map_err(|_| "could not spawn openshell CLI".to_owned())?; - if output.status.success() - && let Ok(sandbox) = serde_json::from_slice::(&output.stdout) - && sandbox["last_token_grant_failure"].is_null() != present - { - return Ok(sandbox["last_token_grant_failure"].clone()); - } - tokio::time::sleep(Duration::from_secs(1)).await; - } - Err(format!( - "last token-grant failure present={present} not observed" - )) -} - -#[tokio::test] -async fn podman_provider_routes_recover_and_select_a_b_a_on_one_connection() { - let _fixture_guard = SPIFFE_FIXTURE_LOCK.lock().await; - let gateway_socket = PathBuf::from( - std::env::var("OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET") - .expect("gateway SPIFFE fixture endpoint"), - ); - let provider_socket = PathBuf::from( - std::env::var("OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET") - .expect("provider SPIFFE fixture endpoint"), - ); - // A remote Podman VM can forward this fixed loopback port to the test - // process. Keep the issuer URL on loopback so the fixture obeys the - // production token endpoint transport policy on both sides of the tunnel. - let token_port = std::env::var("OPENSHELL_E2E_TOKEN_PORT").map_or_else( - |_| find_free_port(), - |port| { - let port = port - .parse::() - .expect("OPENSHELL_E2E_TOKEN_PORT must be a valid TCP port"); - assert_ne!(port, 0, "OPENSHELL_E2E_TOKEN_PORT must be nonzero"); - port - }, - ); - let target_port = find_free_port(); - let grants = Arc::new(RouteGrantState::default()); - let observed = Arc::new(Mutex::new(Vec::new())); - let observed_bytes = Arc::new(AtomicUsize::new(0)); - let _gateway_spiffe = start_spiffe_workload_api( - &gateway_socket, - &format!("spiffe://{TRUST_DOMAIN}/openshell/gateway"), - ) - .await; - let _provider_spiffe = start_spiffe_workload_api( - &provider_socket, - &format!("spiffe://{TRUST_DOMAIN}/openshell/sandbox/e2e"), - ) - .await; - let _token_endpoint = start_route_token_endpoint(token_port, grants.clone()).await; - let _target = start_route_target(target_port, observed.clone(), observed_bytes.clone()).await; - let names = ["a", "b"].map(|route| format!("podman-route-{route}-{}", std::process::id())); - for name in &names { - run_cli_ignore_error(&["provider", "delete", name, "--yes"]).await; - run_cli_ignore_error(&["profile", "delete", name, "--yes"]).await; - } - let result: Result = async { - for (route, name) in ["a", "b"].iter().zip(&names) { - let profile = write_route_profile(name, token_port, target_port, route); - run_cli(&[ - "profile", - "import", - "-f", - profile.path().to_str().expect("UTF-8 profile path"), - ]) - .await?; - run_cli(&[ - "provider", - "create", - "--name", - name, - "--type", - name, - "--credential", - &format!("subject_token=stored-{route}"), - ]) - .await?; - } - let mut sandbox = SandboxGuard::create_keep_with_args( - &["--provider", &names[0], "--provider", &names[1]], - &["sh", "-lc", &sandbox_script()], - "token-server-ready", - ) - .await?; - grants.fail_next_b.store(true, Ordering::SeqCst); - // The supervisor mediates direct workload connections as CONNECT. - // HTTPConnection keeps one client socket for the successful A/B/A run. - let failure_script = format!( - r#"import http.client, uuid -first = http.client.HTTPConnection('host.openshell.internal', {target_port}, timeout=10) -first.request('GET', '/b/failure', headers={{'Authorization': 'Bearer stale-value'}}) -failed = first.getresponse() -failed.read() -assert failed.status == 502, 'the controlled grant failure must return 502' -request_id = failed.getheader('x-openshell-request-id', '') -assert str(uuid.UUID(request_id)) == request_id, 'the refusal must carry a canonical request ID' -print('failed-request-id=' + request_id) -assert failed.will_close, 'the failed tunnel must close' -first.close() -"# - ); - let recovery_script = format!( - r#"import http.client -host = 'host.openshell.internal' -port = {target_port} -recovered = http.client.HTTPConnection(host, port, timeout=10) -connection = None -for path in ['/a/first', '/b/second', '/a/third']: - recovered.request('GET', path, headers={{'Authorization': 'Bearer stale-value'}}) - if connection is None: - connection = recovered.sock - assert recovered.sock is connection, 'client connection was replaced' - response = recovered.getresponse() - response.read() - assert response.status == 200, 'upstream rejected the selected credential' - assert recovered.sock is connection and connection.fileno() >= 0, 'keepalive connection closed' -recovered.close() -print('route-recovery-a-b-a-ok') -"# - ); - let output = async { - let mut output = exec_within(&sandbox, &failure_script).await?; - // An authorized reader sees the cause of the refused grant. - let failure = wait_for_token_grant_failure(&sandbox.name, true).await?; - output.push_str(&format!("reported-failure={failure}\n")); - output.push_str(&exec_within(&sandbox, &recovery_script).await?); - // The matching grant's later success clears it. - wait_for_token_grant_failure(&sandbox.name, false).await?; - Ok::<_, String>(output) - } - .await; - sandbox.cleanup().await; - output - } - .await; - for name in &names { - run_cli_ignore_error(&["provider", "delete", name, "--yes"]).await; - run_cli_ignore_error(&["profile", "delete", name, "--yes"]).await; - } - let target_result = _target.drain().await; - _token_endpoint.shutdown().await; - _provider_spiffe.shutdown().await; - _gateway_spiffe.shutdown().await; - let output = result.expect("gateway-configured route workload succeeds"); - target_result.expect("route target observes EOF on every accepted connection"); - assert!(output.contains("route-recovery-a-b-a-ok")); - let response_request_id = output - .lines() - .find_map(|line| line.strip_prefix("failed-request-id=")) - .expect("workload prints the refused response's request ID"); - assert_eq!( - grants.failed_request_id.lock().unwrap().as_deref(), - Some(response_request_id), - "the token service and refused response must identify the same exchange" - ); - let reported: serde_json::Value = serde_json::from_str( - output - .lines() - .find_map(|line| line.strip_prefix("reported-failure=")) - .expect("the refused grant reached sandbox status"), - ) - .expect("reported failure is JSON"); - assert_eq!(reported["destination_port"], u64::from(target_port)); - let failure = &reported["failure"]; - assert_eq!(failure["request_id"], response_request_id); - assert_eq!(failure["code"], "unavailable"); - assert_eq!(failure["recovery_action"], "retry"); - assert_eq!(failure["stage"], "token_endpoint"); - assert_eq!(failure["upstream_http_status"], 503); - assert_eq!(failure["provider"], names[1].as_str()); - assert_eq!(failure["credential_key"], "access_token"); - let requests = observed.lock().expect("route target observations lock"); - assert_eq!(requests.len(), 3, "failed grant must not reach the target"); - assert_eq!( - observed_bytes.load(Ordering::Relaxed), - requests.iter().map(|request| request.bytes).sum::(), - "no partial failed request reached the target" - ); - for ((request, path), token) in requests - .iter() - .zip(["/a/first", "/b/second", "/a/third"]) - .zip(["Bearer final-a", "Bearer final-b", "Bearer final-a"]) - { - assert_eq!(request.path, path); - assert_eq!( - request.connection, requests[0].connection, - "upstream connection reused" - ); - assert_eq!( - request.authorization.len(), - 1, - "one Authorization replacement" - ); - assert!( - request.authorization[0] == token, - "the admitted path owns the injected token" - ); - } - assert_eq!( - *grants - .supervisor_requests - .lock() - .expect("route grant requests lock"), - ["b", "a", "b"], - "failed grant retries; repeated A uses its own cached token" - ); -} diff --git a/e2e/support/podman-gateway-config.sh b/e2e/support/podman-gateway-config.sh index 580ad0673d..0be7ab7576 100755 --- a/e2e/support/podman-gateway-config.sh +++ b/e2e/support/podman-gateway-config.sh @@ -30,10 +30,9 @@ e2e_write_podman_gateway_config() { local stop_timeout_secs=${11} local supervisor_image=${12} local sandbox_runtime_image=${13} - local provider_spiffe_socket=${14} - local podman_socket=${15} - local oidc_mode=${16} - local oidc_issuer=${17} + local podman_socket=${14} + local oidc_mode=${15} + local oidc_issuer=${16} local configured_with_tls cp "${root}/deploy/rpm/gateway.toml.default" "${output}" @@ -67,9 +66,6 @@ e2e_write_podman_gateway_config() { printf 'supervisor_image = %s\n' "$(e2e_podman_toml_string "${supervisor_image}")" printf 'sandbox_runtime_image = %s\n' "$(e2e_podman_toml_string "${sandbox_runtime_image}")" printf 'enable_bind_mounts = true\n' - if [ -n "${provider_spiffe_socket}" ]; then - printf 'provider_spiffe_workload_api_socket = %s\n' "$(e2e_podman_toml_string "${provider_spiffe_socket}")" - fi if [ -n "${podman_socket}" ]; then printf 'socket_path = %s\n' "$(e2e_podman_toml_string "${podman_socket}")" fi @@ -83,17 +79,5 @@ e2e_write_podman_gateway_config() { e2e_write_gateway_oidc_config "${oidc_issuer}" fi fi - # Opt-in OTLP export so the otlp_relay e2e can bind a collector stub on - # the referenced port. Supervisors connect lazily, so the gateway may - # start before the stub exists. - if [ -n "${OPENSHELL_E2E_OTLP_ENDPOINT:-}" ]; then - printf '\n[openshell.gateway.otlp]\n' - printf 'endpoint = %s\n' "$(e2e_podman_toml_string "${OPENSHELL_E2E_OTLP_ENDPOINT}")" - # The agent trace relay is opt-in; OPENSHELL_E2E_OTLP_AGENT=0 runs the - # relay's inert case with trace export still on. - if [ "${OPENSHELL_E2E_OTLP_AGENT:-1}" != "0" ]; then - printf '\n[openshell.gateway.otlp.agent]\nenabled = true\n' - fi - fi } >>"${output}" } diff --git a/e2e/with-docker-gateway.sh b/e2e/with-docker-gateway.sh index 8f62245c9c..90dc957745 100755 --- a/e2e/with-docker-gateway.sh +++ b/e2e/with-docker-gateway.sh @@ -645,18 +645,6 @@ GATEWAY_CONFIG="${STATE_DIR}/gateway.toml" printf 'additional_ca_bundle = %s\n\n' \ "$(toml_string "${ADDITIONAL_CA_DIR}/ca.crt")" fi - # Opt-in OTLP export so the otlp_relay e2e can bind a collector stub on - # the referenced port. Supervisors connect lazily, so the gateway may - # start before the stub exists. - if [ -n "${OPENSHELL_E2E_OTLP_ENDPOINT:-}" ]; then - printf '[openshell.gateway.otlp]\n' - printf 'endpoint = %s\n\n' "$(toml_string "${OPENSHELL_E2E_OTLP_ENDPOINT}")" - # The agent trace relay is opt-in; OPENSHELL_E2E_OTLP_AGENT=0 runs the - # relay's inert case with trace export still on. - if [ "${OPENSHELL_E2E_OTLP_AGENT:-1}" != "0" ]; then - printf '[openshell.gateway.otlp.agent]\nenabled = true\n\n' - fi - fi printf '[openshell.drivers.docker]\n' if [ -n "${SUPERVISOR_NETWORK_MODE}" ]; then printf 'supervisor_network_mode = %s\n' "$(toml_string "${SUPERVISOR_NETWORK_MODE}")" diff --git a/e2e/with-podman-gateway.sh b/e2e/with-podman-gateway.sh index 96b2091380..62841d9665 100755 --- a/e2e/with-podman-gateway.sh +++ b/e2e/with-podman-gateway.sh @@ -97,18 +97,6 @@ podman_cmd() { WORKDIR_PARENT="${TMPDIR:-/tmp}" WORKDIR_PARENT="${WORKDIR_PARENT%/}" WORKDIR="$(mktemp -d "${WORKDIR_PARENT}/openshell-e2e-podman.XXXXXX")" -if [ "${OPENSHELL_E2E_SPIFFE_FIXTURE:-0}" = "1" ]; then - mkdir -p "${WORKDIR}/spiffe" - export OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET="${OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET:-${WORKDIR}/spiffe/gateway.sock}" - export OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET="${OPENSHELL_E2E_GATEWAY_SPIFFE_SOCKET}" - if [ -z "${OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET:-}" ]; then - OPENSHELL_E2E_PROVIDER_SPIFFE_PORT="$(e2e_pick_port)" - export OPENSHELL_E2E_PROVIDER_SPIFFE_LISTEN="0.0.0.0:${OPENSHELL_E2E_PROVIDER_SPIFFE_PORT}" - # Podman supervisors run with host networking, so reach the host-side - # Workload API fixture over loopback rather than the workload bridge. - export OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET="tcp:127.0.0.1:${OPENSHELL_E2E_PROVIDER_SPIFFE_PORT}" - fi -fi GATEWAY_BIN="" CLI_BIN="" GATEWAY_PID="" @@ -583,7 +571,6 @@ e2e_write_podman_gateway_config \ "${PODMAN_STOP_TIMEOUT_SECS}" \ "${SUPERVISOR_IMAGE}" \ "${SANDBOX_BOUNDARY_IMAGE}" \ - "${OPENSHELL_E2E_PROVIDER_SPIFFE_SOCKET:-}" \ "${OPENSHELL_PODMAN_SOCKET:-}" \ "${OIDC_MODE}" \ "${OPENSHELL_OIDC_ISSUER:-}" diff --git a/tasks/scripts/test-gateway-config.sh b/tasks/scripts/test-gateway-config.sh index bc36c9c55c..109fed8a76 100755 --- a/tasks/scripts/test-gateway-config.sh +++ b/tasks/scripts/test-gateway-config.sh @@ -43,12 +43,12 @@ mkdir -p "${WORK}/pki/client" "${WORK}/jwt" e2e_write_podman_gateway_config \ "${WORK}/podman.toml" "${ROOT}" "${WORK}/pki" "${WORK}/jwt" \ test-gateway 0 "${WORK}/driver.sock" test-network 18181 \ - workload:test 15 supervisor:test sandbox:test "${WORK}/spiffe.sock" \ + workload:test 15 supervisor:test sandbox:test \ "${WORK}/podman.sock" 0 "" e2e_write_podman_gateway_config \ "${WORK}/podman-external.toml" "${ROOT}" "${WORK}/pki" "${WORK}/jwt" \ test-gateway 1 "${WORK}/driver.sock" test-network 18181 \ - workload:test 15 supervisor:test sandbox:test "${WORK}/spiffe.sock" \ + workload:test 15 supervisor:test sandbox:test \ "${WORK}/podman.sock" 0 "" printf '%s\n' \ @@ -65,7 +65,6 @@ printf '%s\n' \ 'assert driver["image_pull_policy"] == "if_not_present"' \ 'assert driver["supervisor_image"] == "supervisor:test"' \ 'assert driver["sandbox_runtime_image"] == "sandbox:test"' \ - 'assert driver["provider_spiffe_workload_api_socket"].endswith("/spiffe.sock")' \ 'assert driver["socket_path"].endswith("/podman.sock")' \ 'assert driver["resource_admission"] == {"enabled": False}' \ 'external_driver = external["openshell"]["drivers"]["podman"]' \ diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index 04592b09f0..eb912e6e98 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -616,6 +616,15 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + [[package]] name = "critical-section" version = "1.2.0" @@ -976,6 +985,16 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + [[package]] name = "flume" version = "0.12.0" @@ -2063,6 +2082,15 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + [[package]] name = "matchit" version = "0.8.4" @@ -2085,6 +2113,16 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "metrics" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5312e9ba3771cfa961b585728215e3d972c950a3eed9252aa093d6301277e8" +dependencies = [ + "ahash", + "portable-atomic", +] + [[package]] name = "miette" version = "7.6.0" @@ -2134,6 +2172,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", + "simd-adler32", ] [[package]] @@ -2211,6 +2250,15 @@ dependencies = [ "smallvec", ] +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -2408,6 +2456,73 @@ dependencies = [ "tower", ] +[[package]] +name = "openshell-ocsf" +version = "0.0.0" +dependencies = [ + "chrono", + "serde", + "serde_json", + "serde_repr", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "openshell-otel" +version = "0.0.0" +dependencies = [ + "async-trait", + "bytes", + "futures", + "http", + "http-body-util", + "hyper-rustls", + "hyper-util", + "metrics", + "openshell-crypto", + "openshell-ocsf", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-otlp", + "opentelemetry_sdk", + "rustls", + "rustls-native-certs", + "serde_json", + "thiserror 2.0.20", + "tokio", + "tonic", + "tower-http 0.6.8", + "tracing", + "tracing-opentelemetry", + "tracing-subscriber", + "zeroize", +] + +[[package]] +name = "openshell-otel-test-support" +version = "0.0.0" +dependencies = [ + "bytes", + "http", + "http-body-util", + "hyper", + "hyper-util", + "openshell-crypto", + "openshell-otel", + "opentelemetry-proto", + "prost", + "rcgen", + "rustls", + "tokio", + "tokio-rustls", + "tokio-stream", + "tonic", + "tracing", + "tracing-subscriber", +] + [[package]] name = "openshell-policy" version = "0.0.0" @@ -2538,6 +2653,83 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "opentelemetry" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c1f1a6ac9c875a4941e4c7c085b61e8f4daa326de03b4701768c3491a6ad9ee" +dependencies = [ + "futures-core", + "futures-sink", + "js-sys", + "pin-project-lite", + "thiserror 2.0.20", + "tracing", +] + +[[package]] +name = "opentelemetry-http" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302249bd8ee804789faaa7b5b2cbf79bc61cb864714079c644e3828af5b7e811" +dependencies = [ + "async-trait", + "bytes", + "http", + "opentelemetry", +] + +[[package]] +name = "opentelemetry-otlp" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0756af24841e367128ef31c831999937b8b5c5197d47914590d8f4e2e88c2e1a" +dependencies = [ + "flate2", + "http", + "httpdate", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-proto", + "opentelemetry_sdk", + "prost", + "thiserror 2.0.20", + "tokio", + "tonic", + "tonic-types", +] + +[[package]] +name = "opentelemetry-proto" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d576f5dddc3299341bcd85a04be17b2564844c0c9563214f02d85f2524d1afae" +dependencies = [ + "opentelemetry", + "opentelemetry_sdk", + "prost", + "tonic", + "tonic-prost", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "372a912db2974d1990207006fd0e3aa0ef3fd4ad3be43c65cfaadf2206866061" +dependencies = [ + "futures-channel", + "futures-executor", + "futures-util", + "opentelemetry", + "percent-encoding", + "portable-atomic", + "rand 0.9.4", + "thiserror 2.0.20", + "tokio", + "tokio-stream", +] + [[package]] name = "ordered-float" version = "2.10.1" @@ -2547,6 +2739,31 @@ dependencies = [ "num-traits", ] +[[package]] +name = "otlp-relay" +version = "0.0.0" +dependencies = [ + "base64 0.22.1", + "openshell-testkit", + "otlp-support", +] + +[[package]] +name = "otlp-relay-inactive" +version = "0.0.0" +dependencies = [ + "openshell-testkit", +] + +[[package]] +name = "otlp-support" +version = "0.0.0" +dependencies = [ + "openshell-otel-test-support", + "openshell-testkit", + "serde_json", +] + [[package]] name = "owo-colors" version = "4.3.0" @@ -2869,6 +3086,18 @@ version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" +[[package]] +name = "provider-token-exchange" +version = "0.0.0" +dependencies = [ + "host-server-support", + "openshell-testkit", + "serde_json", + "spiffe-support", + "tokio", + "url", +] + [[package]] name = "pulldown-cmark" version = "0.13.6" @@ -3463,6 +3692,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_repr" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -3519,6 +3759,15 @@ dependencies = [ "digest 0.11.2", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "1.3.0" @@ -3544,6 +3793,12 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simd-adler32" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -3597,6 +3852,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spiffe-support" +version = "0.0.0" +dependencies = [ + "jsonwebtoken", + "openshell-crypto", + "openshell-testkit", + "serde_json", +] + [[package]] name = "spin" version = "0.9.9" @@ -3952,6 +4217,15 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + [[package]] name = "time" version = "0.3.47" @@ -4098,6 +4372,7 @@ dependencies = [ "axum", "base64 0.22.1", "bytes", + "flate2", "h2", "http", "http-body", @@ -4204,6 +4479,8 @@ dependencies = [ "tower", "tower-layer", "tower-service", + "tracing", + "uuid", ] [[package]] @@ -4268,6 +4545,64 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-opentelemetry" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a904802a1b902f43638b677ff2a650847e3b4404101b6c586d648e8c1e3e8fe" +dependencies = [ + "js-sys", + "opentelemetry", + "tracing", + "tracing-core", + "tracing-log", + "tracing-subscriber", + "web-time", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", ] [[package]] @@ -4418,6 +4753,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "vcpkg" version = "0.2.15" @@ -4581,6 +4922,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-root-certs" version = "1.0.10" @@ -4958,6 +5309,20 @@ name = "zeroize" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] name = "zerotrie" diff --git a/tests/suites/features/Cargo.toml b/tests/suites/features/Cargo.toml index 7c7fe40ae7..1686166660 100644 --- a/tests/suites/features/Cargo.toml +++ b/tests/suites/features/Cargo.toml @@ -3,4 +3,4 @@ [workspace] resolver = "2" -members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "oci-image", "routable-host-ip"] +members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "oci-image", "otlp-relay", "otlp-relay-inactive", "provider-token-exchange", "routable-host-ip"] diff --git a/tests/suites/features/otlp-relay-inactive/Cargo.toml b/tests/suites/features/otlp-relay-inactive/Cargo.toml new file mode 100644 index 0000000000..856283c6ea --- /dev/null +++ b/tests/suites/features/otlp-relay-inactive/Cargo.toml @@ -0,0 +1,20 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "otlp-relay-inactive" +description = "Features suite: the supervisor's agent trace relay without a collector" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[[test]] +name = "otlp-relay-inactive" +path = "tests/otlp_relay_inactive.rs" +harness = false + +[dependencies] +openshell-testkit = { path = "../../../testkit/testkit" } diff --git a/tests/suites/features/otlp-relay-inactive/tests/otlp_relay_inactive.rs b/tests/suites/features/otlp-relay-inactive/tests/otlp_relay_inactive.rs new file mode 100644 index 0000000000..842335dcf5 --- /dev/null +++ b/tests/suites/features/otlp-relay-inactive/tests/otlp_relay_inactive.rs @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The supervisor's agent trace relay when the gateway configures no +//! collector. The test needs a gateway without OTLP export or the agent trace +//! relay, such as an environment's default gateway. `features/otlp-relay` +//! tests the relay with a collector. + +use testkit::Context; + +fn main() -> std::process::ExitCode { + testkit::main() +} + +/// Reports whether an endpoint was injected, then posts to the relay address +/// directly and reports the failure class instead of raising. +const INERT_SCRIPT: &str = r#" +import http.client, os +print("ENDPOINT", os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT", "unset")) +connection = http.client.HTTPConnection("192.0.0.8", 4318, timeout=3) +try: + connection.request("POST", "/v1/traces", body=b"", headers={"Content-Type": "application/x-protobuf"}) + print("STATUS", connection.getresponse().status) +except TimeoutError: + print("ERROR Timeout") +except OSError: + print("ERROR ConnectionError") +"#; + +/// Without a collector, the supervisor injects no relay endpoint, nothing +/// listens on the relay address, and the supervisor logs that the relay is +/// inactive. +#[testkit::test] +async fn relay_is_inert_without_collector(cx: &mut Context) -> testkit::Result { + testkit::ensure!( + std::env::var_os("OPENSHELL_TEST_OTLP_ENDPOINT").is_none(), + "OPENSHELL_TEST_OTLP_ENDPOINT is set; this suite needs a gateway without an OTLP collector" + ); + let builder = cx + .cli_sandbox("otlpi") + .image(testkit::python_image()) + .args(["--no-auto-providers"]) + .command(["python3", "-c", INERT_SCRIPT]); + let name = builder.name().to_string(); + let run = builder.run().await?.success()?; + let output = format!("{}{}", run.stdout, run.stderr); + testkit::ensure!( + output.contains("ENDPOINT unset"), + "a relay endpoint was injected while the relay is inactive:\n{output}" + ); + testkit::ensure!( + output.contains("ERROR ConnectionError"), + "the export did not fail with a connection error:\n{output}" + ); + + let sandbox = cx.adopt(&name).await?; + let logs = sandbox + .logs_until("that the OTLP agent trace relay is inactive", |logs| { + logs.contains("OTLP agent trace relay inactive") + }) + .await?; + testkit::ensure!( + !logs.contains("OTLP agent trace relay enabled"), + "the supervisor also reported the relay enabled:\n{logs}" + ); + Ok(()) +} diff --git a/tests/suites/features/otlp-relay/Cargo.toml b/tests/suites/features/otlp-relay/Cargo.toml new file mode 100644 index 0000000000..5a96684810 --- /dev/null +++ b/tests/suites/features/otlp-relay/Cargo.toml @@ -0,0 +1,22 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "otlp-relay" +description = "Features suite: the supervisor's agent trace relay with a collector" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[[test]] +name = "otlp-relay" +path = "tests/otlp_relay.rs" +harness = false + +[dependencies] +base64 = "0.22" +openshell-testkit = { path = "../../../testkit/testkit" } +otlp-support = { path = "../../../support/otlp" } diff --git a/tests/suites/features/otlp-relay/tests/otlp_relay.rs b/tests/suites/features/otlp-relay/tests/otlp_relay.rs new file mode 100644 index 0000000000..74d06e12b6 --- /dev/null +++ b/tests/suites/features/otlp-relay/tests/otlp_relay.rs @@ -0,0 +1,212 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The supervisor's agent trace relay. +//! +//! The tests need a gateway whose OTLP export and agent trace relay point at +//! the environment's collector ([`otlp_support`]). Each names its spans with +//! [`Context::name`] and checks only those, so the tests share the collector +//! with each other and with the gateway's own traces. `features/otlp-relay-inactive` +//! tests the relay without a collector. + +use std::collections::HashMap; +use std::time::Duration; + +use base64::Engine as _; +use otlp_support::{Collector, SANDBOX_ID_KEY, SOURCE_KEY, SOURCE_VALUE, Span}; +use testkit::sdk::SandboxPhase; +use testkit::{Context, Error, Poll, Result, ResultExt as _, poll_until}; + +fn main() -> std::process::ExitCode { + testkit::main() +} + +const ENV_ENDPOINT: &str = "OTEL_EXPORTER_OTLP_ENDPOINT"; +const ENV_PROTOCOL: &str = "OTEL_EXPORTER_OTLP_PROTOCOL"; +const ENV_COLLECTOR: &str = "OPENSHELL_OTLP_ENDPOINT"; +const RELAY_ENDPOINT: &str = "http://192.0.0.8:4318"; + +/// Posts the base64 body from `OTLP_BODY_B64` to the relay and prints the +/// status plus the complete environment, one `ENV key=value` line each, so +/// the test can check values and prove the collector address is nowhere. +const EXPORT_SCRIPT: &str = r#" +import base64, os, requests +body = base64.b64decode(os.environ["OTLP_BODY_B64"]) +url = os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] + "/v1/traces" +response = requests.post(url, data=body, headers={"Content-Type": "application/x-protobuf"}, timeout=10) +print("STATUS", response.status_code) +for key, value in sorted(os.environ.items()): + if key != "OTLP_BODY_B64": + print("ENV " + key + "=" + value) +"#; + +/// A main process that posts one span with the payload embedded, and exits +/// as soon as the POST returns: 0 if the relay accepted it. +fn exit_script(body_b64: &str) -> String { + format!( + r#" +import base64, os, requests +body = base64.b64decode("{body_b64}") +url = os.environ["OTEL_EXPORTER_OTLP_ENDPOINT"] + "/v1/traces" +response = requests.post(url, data=body, headers={{"Content-Type": "application/x-protobuf"}}, timeout=10) +raise SystemExit(0 if response.status_code == 200 else 1) +"# + ) +} + +/// A span exported from a sandbox reaches the collector within 5 seconds, +/// with the supervisor's attribution in place of the agent's spoofed values. +/// The workload gets the relay endpoint and protocol, and never the +/// collector's address. +#[testkit::test] +async fn agent_span_reaches_collector_with_attribution(cx: &mut Context) -> testkit::Result { + let collector = Collector::from_env()?; + let span = cx.name("span"); + let body = format!("OTLP_BODY_B64={}", encoded_request(&span)); + let builder = cx + .cli_sandbox("otlp") + .image(testkit::python_image()) + .args(["--env", &body, "--no-auto-providers"]) + .command(["python3", "-c", EXPORT_SCRIPT]); + let name = builder.name().to_string(); + let run = builder.run().await?.success()?; + let output = format!("{}{}", run.stdout, run.stderr); + + testkit::ensure!( + output.contains("STATUS 200"), + "the relay did not accept the export:\n{output}" + ); + for expected in [ + format!("ENV {ENV_ENDPOINT}={RELAY_ENDPOINT}"), + format!("ENV {ENV_PROTOCOL}=http/protobuf"), + ] { + testkit::ensure!( + output.contains(&expected), + "the workload environment lacks {expected}:\n{output}" + ); + } + testkit::ensure!( + !output.contains(ENV_COLLECTOR), + "{ENV_COLLECTOR} is visible inside the sandbox:\n{output}" + ); + let host_port = collector.host_port(); + testkit::ensure!( + !output.contains(host_port), + "the collector address {host_port} appears in the sandbox environment:\n{output}" + ); + + let sandbox = cx.adopt(&name).await?; + let spans = collector + .wait_for_spans(&[&span], Duration::from_secs(5)) + .await?; + for received in &spans[&span] { + expect_attribution(received, sandbox.id())?; + } + Ok(()) +} + +/// A main process that exports a span and exits at once still delivers it: +/// the supervisor flushes before it reports the exit, so the span is at the +/// collector by the time the sandbox is Completed. Five sandboxes in a row. +#[testkit::test] +async fn span_emitted_before_exit_is_delivered(cx: &mut Context) -> testkit::Result { + let collector = Collector::from_env()?; + let names: Vec = (1..=5) + .map(|i| cx.name(&format!("exit-span-{i}"))) + .collect(); + let mut ids = HashMap::new(); + for (index, name) in names.iter().enumerate() { + let sandbox = cx + .cli_sandbox(&format!("otlp{index}")) + .image(testkit::python_image()) + .command(["python3", "-c", &exit_script(&encoded_request(name))]) + .create() + .await?; + let finished = sandbox.wait_finished().await?; + if finished.phase != SandboxPhase::Completed || finished.exit_code != Some(0) { + let logs = sandbox.logs().await?; + return Err(Error::msg(format!( + "sandbox {} finished in {:?} with exit code {:?}; expected Completed with 0. Supervisor logs:\n{logs}", + sandbox.name(), + finished.phase, + finished.exit_code + ))); + } + // The collector acknowledges an export before its log shows it, and + // flushes the log every 10 ms. + poll_until( + &format!("{name} to reach the collector by the time the exit was reported"), + Duration::from_secs(1), + Duration::from_millis(50), + async || { + Ok(if collector.spans(&[name])?.is_empty() { + Poll::Pending("not in the log".to_string()) + } else { + Poll::Ready(()) + }) + }, + ) + .await?; + ids.insert(name.clone(), sandbox.id().to_string()); + sandbox.delete().await?; + sandbox + .wait_absent(Duration::from_secs(60)) + .await + .context("let the sandbox's teardown finish before the next create")?; + } + + let name_refs: Vec<&str> = names.iter().map(String::as_str).collect(); + let spans = collector + .wait_for_spans(&name_refs, Duration::from_secs(15)) + .await?; + for name in &names { + for received in &spans[name] { + expect_attribution(received, &ids[name])?; + } + } + Ok(()) +} + +/// One span with the agent's own service name and spoofed values for both +/// attribution keys, base64-encoded. +fn encoded_request(span_name: &str) -> String { + let request = otlp_support::encoded_trace_request( + span_name, + &[ + ("service.name", "e2e-agent"), + (SANDBOX_ID_KEY, "spoofed"), + (SOURCE_KEY, "infrastructure"), + ], + ); + base64::engine::general_purpose::STANDARD.encode(request) +} + +/// The received attributes keep the last value of a key, so a spoofed +/// attribute that was appended to rather than replaced shows only as a +/// duplicate. +fn expect_attribution(span: &Span, sandbox_id: &str) -> Result { + let duplicates = &span.duplicate_resource_keys; + testkit::ensure!( + duplicates.is_empty(), + "attribution keys of {} were appended, not replaced: {duplicates:?}", + span.name + ); + let attributes = &span.attributes; + testkit::ensure!( + !attributes + .values() + .any(|value| value == "spoofed" || value == "infrastructure"), + "the agent's attribution values were kept: {attributes:?}" + ); + for (key, expected) in [ + ("service.name", "e2e-agent"), + (SOURCE_KEY, SOURCE_VALUE), + (SANDBOX_ID_KEY, sandbox_id), + ] { + testkit::ensure!( + attributes.get(key).map(String::as_str) == Some(expected), + "resource attribute {key} is not {expected}: {attributes:?}" + ); + } + Ok(()) +} diff --git a/tests/suites/features/provider-token-exchange/Cargo.toml b/tests/suites/features/provider-token-exchange/Cargo.toml new file mode 100644 index 0000000000..0132e2e1da --- /dev/null +++ b/tests/suites/features/provider-token-exchange/Cargo.toml @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "provider-token-exchange" +description = "Features suite: provider token grants that exchange SPIFFE JWT-SVIDs at token endpoints the test runs" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[[test]] +name = "provider-token-exchange" +path = "tests/token_exchange.rs" +harness = false + +[dependencies] +host-server-support = { path = "../../../support/host-server" } +openshell-testkit = { path = "../../../testkit/testkit" } +serde_json = "1" +spiffe-support = { path = "../../../support/spiffe" } +tokio = { version = "1.43", features = ["macros"] } +url = "2" diff --git a/tests/suites/features/provider-token-exchange/tests/token_exchange.rs b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs new file mode 100644 index 0000000000..0e3c04d226 --- /dev/null +++ b/tests/suites/features/provider-token-exchange/tests/token_exchange.rs @@ -0,0 +1,723 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Provider token grants: the gateway and the supervisor exchange SPIFFE +//! JWT-SVIDs at token endpoints the test runs, and the supervisor injects the +//! results into requests to a protected target. +//! +//! The gateway and supervisors fetch JWT-SVIDs from the environment's +//! Workload APIs ([`spiffe_support`]). The token endpoints and targets are +//! [`HttpRecorder`]s on the test host. The gateway and Podman's host-network +//! supervisors reach the token endpoints on loopback, which the token +//! endpoint transport policy allows over plain HTTP. Sandboxes reach the +//! targets through [`TEST_HOST`]. Tests never print the fixture tokens, +//! though none are real. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use host_server_support::{HttpRecorder, Request, Response, TEST_HOST}; +use serde_json::json; +use spiffe_support::{Bundle, ISSUER, SUPERVISOR_SUBJECT}; +use testkit::{Context, Error, Poll, Result, ResultExt as _, Sandbox, poll_until}; + +fn main() -> std::process::ExitCode { + testkit::main() +} + +/// How long the route servers wait for a request before closing the +/// connection. +const ROUTE_READ_TIMEOUT: Duration = Duration::from_secs(30); +const USER_SUBJECT_TOKEN: &str = "stored-user-token"; +const INTERMEDIATE_TOKEN: &str = "intermediate-token"; +const FINAL_ACCESS_TOKEN: &str = "final-access-token"; +const TOKEN_TYPE_ACCESS_TOKEN: &str = "urn:ietf:params:oauth:token-type:access_token"; +const CLIENT_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-spiffe"; +const IDENTITY_AUDIENCE: &str = "identity-proxy"; +const IDENTITY_JWT_AUDIENCE: &str = "https://identity.openshell-e2e.test"; +const IDENTITY_ASSERTION_TYPE: &str = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer"; +const SUBJECT_TOKEN_ENV: &str = "subject_token"; + +/// Two sandboxes, each with its own provider, request the same host and +/// port at the same time. Each request carries its provider's bearer token, +/// from a two-stage token exchange, and its own signed JWT-SVID, from a +/// client-credentials grant; the target checks both. Repeat requests use the +/// cached credentials. A failed grant returns 502 and sends the target no +/// bytes, and the other credential stays cached. No credential reaches the +/// workload. +#[testkit::test] +async fn independent_grants_across_sandboxes(cx: &mut Context) -> testkit::Result { + let bundle = Arc::new(Bundle::from_env()?); + let observations = Arc::new(GrantObservations::default()); + let token = HttpRecorder::serve({ + let observations = Arc::clone(&observations); + move |request| exchange_token(request, &observations) + }) + .await?; + let identity = HttpRecorder::serve({ + let observations = Arc::clone(&observations); + let bundle = Arc::clone(&bundle); + move |request| issue_identity(request, &observations, &bundle) + }) + .await?; + let target = HttpRecorder::serve({ + let observations = Arc::clone(&observations); + let bundle = Arc::clone(&bundle); + move |request| protected_target(request, &observations, &bundle) + }) + .await?; + let target_port = target.port; + + let mut sandboxes = Vec::new(); + for instance in ["a", "b"] { + let provider = cx.name(&format!("grants-{instance}")); + let profile = grants_profile(&provider, token.port, identity.port, target_port, instance); + let subject = format!("{USER_SUBJECT_TOKEN}-{instance}"); + cx.install_provider(&provider, &profile, &[(SUBJECT_TOKEN_ENV, &subject)]) + .await?; + sandboxes.push( + cx.sandbox(&format!("pte{instance}")) + .image(testkit::python_image()) + .providers([provider.as_str()]) + .create_ready() + .await?, + ); + } + let [a, b] = &sandboxes[..] else { + unreachable!("two sandboxes") + }; + + let mut after_first = None; + for round in ["first", "cached"] { + let (from_a, from_b) = tokio::join!( + probe(a, target_port, "/resource/a", false), + probe(b, target_port, "/resource/b", false), + ); + from_a.context(format!("the {round} request from sandbox A"))?; + from_b.context(format!("the {round} request from sandbox B"))?; + if round == "first" { + let issued = observations.issued(); + testkit::ensure!( + issued + .iter() + .all(|(service, identity)| *service > 0 && *identity > 0), + "each provider did not acquire both credentials: {issued:?}" + ); + after_first = Some(issued); + } + } + testkit::ensure!( + observations.target_rejected.load(Ordering::SeqCst) == 0, + "the target rejected a request with mismatched or untrusted credentials, even if a retry then passed" + ); + let issued = observations.issued(); + testkit::ensure!( + Some(issued) == after_first, + "repeat requests acquired credentials again instead of using the caches: {after_first:?} after the first round, {issued:?} after the cached round" + ); + + let target_bytes = target.received(); + // An audience override forces acquisition of only the failing credential; + // the other stays cached from the successful requests. + let (from_a, from_b) = tokio::join!( + probe(a, target_port, "/deny-service/a", true), + probe(b, target_port, "/deny-identity/b", true), + ); + from_a.context("the request from sandbox A whose service grant fails")?; + from_b.context("the request from sandbox B whose identity grant fails")?; + testkit::ensure!( + observations.service_denied.load(Ordering::SeqCst) > 0, + "the token endpoint saw no request for the denied service audience" + ); + testkit::ensure!( + observations.identity_denied.load(Ordering::SeqCst) > 0, + "the identity endpoint saw no request for the denied identity audience" + ); + testkit::ensure!( + target.received() == target_bytes, + "a failed grant forwarded request bytes to the target" + ); + Ok(()) +} + +/// A sandbox with two providers, each bound to its own path, reaches one +/// target. A transient grant failure on B returns 502 with a request ID the +/// token endpoint also saw, closes the tunnel, and shows in the sandbox's +/// status as a retryable failure. Then requests to A, B and A on one client +/// connection each carry only their own route's token, over one upstream +/// connection, and the success clears the reported failure. The failed +/// grant sends the target nothing. +#[testkit::test] +async fn routes_recover_and_select_a_b_a_on_one_connection(cx: &mut Context) -> testkit::Result { + let grants = Arc::new(RouteGrantState::default()); + let token = HttpRecorder::builder() + .read_timeout(ROUTE_READ_TIMEOUT) + .serve({ + let grants = Arc::clone(&grants); + move |request| route_token(request, &grants) + }) + .await?; + let target = HttpRecorder::builder() + .read_timeout(ROUTE_READ_TIMEOUT) + .serve(route_target) + .await?; + let target_port = target.port; + + let mut providers = Vec::new(); + for route in ["a", "b"] { + let provider = cx.name(&format!("route-{route}")); + let profile = route_profile(&provider, token.port, target_port, route); + let stored = format!("stored-{route}"); + cx.install_provider(&provider, &profile, &[(SUBJECT_TOKEN_ENV, &stored)]) + .await?; + providers.push(provider); + } + let sandbox = cx + .sandbox("pter") + .image(testkit::python_image()) + .providers(providers.iter().map(String::as_str)) + .create_ready() + .await?; + + grants.fail_next_b.store(true, Ordering::SeqCst); + // The supervisor mediates direct workload connections as CONNECT. + // HTTPConnection keeps one client socket for the A/B/A run. + let failure_script = format!( + r#"import http.client, uuid +first = http.client.HTTPConnection({TEST_HOST:?}, {target_port}, timeout=10) +first.request('GET', '/b/failure', headers={{'Authorization': 'Bearer stale-value'}}) +failed = first.getresponse() +failed.read() +assert failed.status == 502, 'the controlled grant failure must return 502' +request_id = failed.getheader('x-openshell-request-id', '') +assert str(uuid.UUID(request_id)) == request_id, 'the refusal must carry a canonical request ID' +print('failed-request-id=' + request_id) +assert failed.will_close, 'the failed tunnel must close' +first.close() +"# + ); + let recovery_script = format!( + r#"import http.client +recovered = http.client.HTTPConnection({TEST_HOST:?}, {target_port}, timeout=10) +connection = None +for path in ['/a/first', '/b/second', '/a/third']: + recovered.request('GET', path, headers={{'Authorization': 'Bearer stale-value'}}) + if connection is None: + connection = recovered.sock + assert recovered.sock is connection, 'client connection was replaced' + response = recovered.getresponse() + response.read() + assert response.status == 200, 'upstream rejected the selected credential' + assert recovered.sock is connection and connection.fileno() >= 0, 'keepalive connection closed' +recovered.close() +print('route-recovery-a-b-a-ok') +"# + ); + + let failed = sandbox.run_python(&failure_script, &[]).await?; + let request_id = failed + .stdout + .lines() + .find_map(|line| line.strip_prefix("failed-request-id=")) + .ok_or_else(|| Error::msg("the workload did not print the refusal's request ID"))? + .to_string(); + // An authorized reader sees the cause of the refused grant. + let reported = wait_for_grant_failure(&sandbox, true).await?; + let recovered = sandbox.run_python(&recovery_script, &[]).await?; + testkit::ensure!( + recovered.stdout.contains("route-recovery-a-b-a-ok"), + "the A/B/A requests did not finish: {}", + recovered.stdout + ); + // The matching grant's later success clears it. + wait_for_grant_failure(&sandbox, false).await?; + sandbox.delete().await?; + sandbox.wait_absent(Duration::from_secs(60)).await?; + // Only EOF on every connection proves the byte count includes all that + // reached the target. + target + .wait_closed(Duration::from_secs(35)) + .await + .context("the route target saw EOF on every accepted connection")?; + + testkit::ensure!( + grants.failed_request_id.lock().expect("lock").as_deref() == Some(request_id.as_str()), + "the token endpoint and the refused response named different exchanges" + ); + let expected_failure = [ + ("request_id", json!(request_id)), + ("code", json!("unavailable")), + ("recovery_action", json!("retry")), + ("stage", json!("token_endpoint")), + ("upstream_http_status", json!(503)), + ("provider", json!(providers[1])), + ("credential_key", json!("access_token")), + ]; + testkit::ensure!( + reported["destination_port"] == json!(target_port), + "the reported failure names destination port {}, not {target_port}", + reported["destination_port"] + ); + for (key, expected) in expected_failure { + testkit::ensure!( + reported["failure"][key] == expected, + "the reported failure's {key} is {}, not {expected}", + reported["failure"][key] + ); + } + + let requests = target.requests(); + let summary: Vec<(usize, &str)> = requests + .iter() + .map(|request| (request.connection, request.path())) + .collect(); + testkit::ensure!( + requests.len() == 3, + "the target saw {summary:?}; the failed grant must not reach it" + ); + testkit::ensure!( + target.received() == requests.iter().map(|request| request.size).sum::(), + "part of the failed request reached the target" + ); + for ((request, path), token) in requests + .iter() + .zip(["/a/first", "/b/second", "/a/third"]) + .zip(["Bearer final-a", "Bearer final-b", "Bearer final-a"]) + { + testkit::ensure!( + request.path() == path && request.connection == requests[0].connection, + "the target saw {summary:?}; expected the A/B/A paths on one upstream connection" + ); + testkit::ensure!( + request.headers("authorization") == [token], + "{path} did not carry exactly its own route's token" + ); + } + let exchanges = grants.supervisor_requests.lock().expect("lock").clone(); + testkit::ensure!( + exchanges == ["b", "a", "b"], + "the supervisor exchanged tokens for routes {exchanges:?}; expected B (failed), A, B and A from its cache" + ); + Ok(()) +} + +#[derive(Default)] +struct GrantObservations { + service_issued: [AtomicUsize; 2], + identity_issued: [AtomicUsize; 2], + service_denied: AtomicUsize, + identity_denied: AtomicUsize, + target_rejected: AtomicUsize, +} + +impl GrantObservations { + fn issued(&self) -> [(usize, usize); 2] { + std::array::from_fn(|index| { + ( + self.service_issued[index].load(Ordering::SeqCst), + self.identity_issued[index].load(Ordering::SeqCst), + ) + }) + } +} + +/// The gateway's and the supervisor's token exchanges. The gateway trades +/// the stored subject token for an intermediate token addressed to the +/// supervisor's SPIFFE ID; the supervisor trades that for the final token. +fn exchange_token(request: &Request, observations: &GrantObservations) -> Response { + let form = token_form(request); + let field = |name: &str| form.get(name).map_or("", String::as_str); + let valid = is_post(request, "/token") + && field("grant_type") == "urn:ietf:params:oauth:grant-type:token-exchange" + && field("client_assertion_type") == CLIENT_ASSERTION_TYPE + && field("subject_token_type") == TOKEN_TYPE_ACCESS_TOKEN + && field("requested_token_type") == TOKEN_TYPE_ACCESS_TOKEN + && !field("client_assertion").is_empty(); + let mut access_token = None; + for (index, instance) in ["a", "b"].into_iter().enumerate() { + if !valid { + break; + } + if field("subject_token") == format!("{USER_SUBJECT_TOKEN}-{instance}") + && field("audience") == SUPERVISOR_SUBJECT + && field("scope").is_empty() + { + access_token = Some(format!("{INTERMEDIATE_TOKEN}-{instance}")); + } else if field("subject_token") == format!("{INTERMEDIATE_TOKEN}-{instance}") + && field("scope") == "service.read" + { + if field("audience") == format!("service-{instance}") { + observations.service_issued[index].fetch_add(1, Ordering::SeqCst); + access_token = Some(format!("{FINAL_ACCESS_TOKEN}-{instance}")); + } else if field("audience") == format!("denied-service-{instance}") { + observations.service_denied.fetch_add(1, Ordering::SeqCst); + } + } + } + token_response(access_token.as_deref(), 600) +} + +/// A client-credentials grant that checks the supervisor's JWT-SVID and +/// returns it as the access token. No new grant type or sandbox-visible +/// credential is needed to exercise custom-header injection. +fn issue_identity( + request: &Request, + observations: &GrantObservations, + bundle: &Bundle, +) -> Response { + let form = token_form(request); + let field = |name: &str| form.get(name).map_or("", String::as_str); + let mut access_token = None; + for (index, instance) in ["a", "b"].into_iter().enumerate() { + let valid = is_post(request, "/identity-token") + && field("grant_type") == "client_credentials" + && field("client_assertion_type") == IDENTITY_ASSERTION_TYPE + && field("scope") == "identity.read" + && bundle.verify_supervisor_svid( + field("client_assertion"), + &identity_jwt_audience(instance), + ); + if valid && field("audience") == format!("{IDENTITY_AUDIENCE}-{instance}") { + observations.identity_issued[index].fetch_add(1, Ordering::SeqCst); + access_token = Some(field("client_assertion")); + } else if valid && field("audience") == format!("denied-identity-{instance}") { + observations.identity_denied.fetch_add(1, Ordering::SeqCst); + } + } + token_response(access_token, 900) +} + +/// Accepts `GET /resource/` only with exactly one bearer token and +/// one JWT-SVID, both for that instance. +fn protected_target( + request: &Request, + observations: &GrantObservations, + bundle: &Bundle, +) -> Response { + let bearer = request.headers("authorization"); + let identity = request.headers("x-workload-jwt"); + let ok = ["a", "b"].into_iter().any(|instance| { + request.method() == "GET" + && request.path() == format!("/resource/{instance}") + && bearer == [format!("Bearer {FINAL_ACCESS_TOKEN}-{instance}")] + && identity.len() == 1 + && bundle.verify_supervisor_svid(&identity[0], &identity_jwt_audience(instance)) + }); + if ok { + Response::text("independent-grants-ok") + } else { + // Keep the rejection even if the workload retries and a later + // request gets the right credentials. + observations.target_rejected.fetch_add(1, Ordering::SeqCst); + Response::text("credential-verification-failed").status(401) + } +} + +fn identity_jwt_audience(instance: &str) -> String { + format!("{IDENTITY_JWT_AUDIENCE}/{instance}") +} + +/// Request `path` from the target with agent-supplied credentials the +/// supervisor must replace, and fail if any credential reaches the workload. +/// `expect_denied` expects the supervisor's 502 refusal with a request ID. +/// Retries while the exec fails, as when a grant is still settling. +async fn probe(sandbox: &Sandbox, target_port: u16, path: &str, expect_denied: bool) -> Result { + let url = format!("http://{TEST_HOST}:{target_port}{path}"); + let expect_denied_python = if expect_denied { "True" } else { "False" }; + let expected = if expect_denied { + "grant-denied" + } else { + "independent-grants-ok" + }; + // The script prints fixed markers only, so its output never holds a + // credential. + let script = format!( + r#"import base64, json, os, re, urllib.error, urllib.request, uuid + +def contains_credential(value): + if any(marker in value for marker in ( + "stored-user-token", "intermediate-token", "final-access-token", "openshell:resolve:" + )): + return True + for token in re.findall(r"[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+", value): + try: + payload = token.split(".")[1] + claims = json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + if claims.get("iss") == "{ISSUER}": + return True + except (ValueError, UnicodeError, AttributeError): + pass + return False + +if any(contains_credential(value) for value in os.environ.values()): + raise SystemExit("provider credential material reached the workload environment") +request = urllib.request.Request({url:?}, headers={{ + "Authorization": "Bearer agent-supplied", + "X-Workload-Jwt": "agent-supplied", +}}) +try: + with urllib.request.urlopen(request, timeout=10) as response: + body = response.read().decode() + if contains_credential(body): + raise SystemExit("provider credential material reached the workload response") + if {expect_denied_python}: + raise SystemExit("failed grant unexpectedly reached the target") + print(body) +except urllib.error.HTTPError as error: + body = error.read().decode() + if contains_credential(body): + raise SystemExit("provider credential material reached the workload error") + if not {expect_denied_python} or error.code != 502: + raise SystemExit("unexpected HTTP status " + str(error.code)) + # The refusal names the exchange with an opaque ID and nothing else. + request_id = error.headers.get("x-openshell-request-id", "") + if str(uuid.UUID(request_id)) != request_id: + raise SystemExit("refusal did not carry a canonical request ID") + print("grant-denied") +"# + ); + let output = sandbox + .poll_exec( + &format!("{path} to answer from sandbox {}", sandbox.name()), + Duration::from_secs(20), + ["python3", "-c", &script], + |output| output.exit_code == 0, + ) + .await?; + testkit::ensure!( + output.stdout.trim() == expected, + "{path} from sandbox {} printed {:?}, not {expected}", + sandbox.name(), + output.stdout.trim() + ); + Ok(()) +} + +/// A profile with two grants for one request: a token-exchange bearer token +/// and a client-credentials JWT-SVID header. Each has a path whose audience +/// the token endpoints deny. +fn grants_profile( + profile_type: &str, + token_port: u16, + identity_port: u16, + target_port: u16, + instance: &str, +) -> String { + let token_endpoint = format!("http://127.0.0.1:{token_port}/token"); + let identity_jwt_audience = identity_jwt_audience(instance); + format!( + r"id: {profile_type} +display_name: Token exchange test +description: Independent bearer and JWT-SVID grants for one request +category: other +credentials: + - name: subject_token + description: Stored user subject token + required: true + - name: access_token + description: Access token obtained through token exchange + required: false + auth_style: bearer + header_name: Authorization + token_grant: + grant_type: token_exchange + token_endpoint: {token_endpoint} + audience: service-{instance} + scopes: [service.read] + jwt_svid_audience: {token_endpoint} + client_assertion_type: {CLIENT_ASSERTION_TYPE} + requested_token_type: {TOKEN_TYPE_ACCESS_TOKEN} + cache_ttl_seconds: 300 + audience_overrides: + - path: /deny-service/{instance} + audience: denied-service-{instance} + subject_token: + source: provider_credential + credential: subject_token + subject_token_type: {TOKEN_TYPE_ACCESS_TOKEN} + - name: workload_identity + description: Signed workload identity for the identity proxy + required: false + auth_style: header + header_name: X-Workload-Jwt + token_grant: + grant_type: client_credentials + token_endpoint: http://127.0.0.1:{identity_port}/identity-token + audience: {IDENTITY_AUDIENCE}-{instance} + scopes: [identity.read] + jwt_svid_audience: {identity_jwt_audience} + client_assertion_type: {IDENTITY_ASSERTION_TYPE} + cache_ttl_seconds: 600 + audience_overrides: + - path: /deny-identity/{instance} + audience: denied-identity-{instance} +{}", + endpoints(target_port, "/**") + ) +} + +/// A profile with one token-exchange bearer grant bound to `//**`. +/// Each route has its own audience, so the token endpoint can tell which +/// endpoint's grant the supervisor selected. +fn route_profile(profile_type: &str, token_port: u16, target_port: u16, route: &str) -> String { + let token_endpoint = format!("http://127.0.0.1:{token_port}/token"); + format!( + r"id: {profile_type} +display_name: Token exchange route test +description: Route-bound bearer grant +category: other +credentials: + - name: subject_token + description: Stored user subject token + required: true + - name: access_token + description: Access token obtained through token exchange + required: false + auth_style: bearer + header_name: Authorization + token_grant: + grant_type: token_exchange + token_endpoint: {token_endpoint} + audience: audience-{route} + jwt_svid_audience: {token_endpoint} + client_assertion_type: {CLIENT_ASSERTION_TYPE} + requested_token_type: {TOKEN_TYPE_ACCESS_TOKEN} + cache_ttl_seconds: 300 + subject_token: + source: provider_credential + credential: subject_token + subject_token_type: {TOKEN_TYPE_ACCESS_TOKEN} +{}", + endpoints(target_port, &format!("/{route}/**")) + ) +} + +fn endpoints(target_port: u16, path: &str) -> String { + format!( + r"endpoints: + - host: {TEST_HOST} + port: {target_port} + path: {path} + protocol: rest + access: read-write + enforcement: enforce + allowed_ips: + - 10.0.0.0/8 + - 169.254.0.0/16 + - 172.0.0.0/8 + - 192.168.0.0/16 +binaries: + - /** +" + ) +} + +/// Poll the sandbox's status until its last token-grant failure is present +/// or absent, and return it. +async fn wait_for_grant_failure(sandbox: &Sandbox, present: bool) -> Result { + let what = if present { + "to report a token-grant failure" + } else { + "to clear its token-grant failure" + }; + poll_until( + &format!("sandbox {} {what}", sandbox.name()), + Duration::from_secs(30), + Duration::from_secs(1), + async || { + let failure = sandbox.get_json().await?["last_token_grant_failure"].clone(); + Ok(if failure.is_null() == present { + Poll::Pending(format!("last_token_grant_failure is {failure}")) + } else { + Poll::Ready(failure) + }) + }, + ) + .await +} + +#[derive(Default)] +struct RouteGrantState { + fail_next_b: AtomicBool, + supervisor_requests: Mutex>, + failed_request_id: Mutex>, +} + +/// The route grants' token endpoint. It records each supervisor exchange's +/// route, and fails the next one for B with a 503 when `fail_next_b` is set. +fn route_token(request: &Request, state: &RouteGrantState) -> Response { + let form = token_form(request); + let field = |name: &str| form.get(name).map_or("", String::as_str); + let subject = field("subject_token"); + let route = match subject { + "stored-a" | "intermediate-a" => "a", + "stored-b" | "intermediate-b" => "b", + _ => "", + }; + let supervisor = subject.starts_with("intermediate-"); + // The gateway's exchange targets the supervisor's SPIFFE ID; the + // supervisor's targets the route's audience. + let valid = !route.is_empty() + && is_post(request, "/token") + && !field("client_assertion").is_empty() + && !field("audience").is_empty() + && (!supervisor || field("audience") == format!("audience-{route}")); + let fail = if valid && supervisor { + state + .supervisor_requests + .lock() + .expect("lock") + .push(route.to_owned()); + route == "b" && state.fail_next_b.swap(false, Ordering::SeqCst) + } else { + false + }; + if fail { + *state.failed_request_id.lock().expect("lock") = request.header("x-openshell-request-id"); + Response::json(&json!({"error": "temporary_failure"})).status(503) + } else if valid { + let stage = if supervisor { "final" } else { "intermediate" }; + Response::json( + &json!({"access_token": format!("{stage}-{route}"), "token_type": "Bearer", "expires_in": 300}), + ) + } else { + Response::json(&json!({"error": "unexpected_route_exchange"})).status(400) + } +} + +/// The route grants' target. It keeps each connection open across requests, +/// and accepts a request only with exactly its route's token. +fn route_target(request: &Request) -> Response { + let expected = if request.path().starts_with("/a/") { + "Bearer final-a" + } else { + "Bearer final-b" + }; + let status = if request.headers("authorization") == [expected] { + 200 + } else { + 401 + }; + Response::new(status).keep_alive() +} + +fn is_post(request: &Request, path: &str) -> bool { + request.method() == "POST" && request.path() == path +} + +fn token_form(request: &Request) -> HashMap { + url::form_urlencoded::parse(request.body.as_bytes()) + .into_owned() + .collect() +} + +fn token_response(access_token: Option<&str>, ttl: u64) -> Response { + match access_token { + Some(access_token) => Response::json( + &json!({"access_token": access_token, "token_type": "Bearer", "expires_in": ttl}), + ), + None => Response::json(&json!({"error": "invalid_grant"})).status(400), + } +} diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 4de10e2dd6..49a11f007d 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -599,6 +599,15 @@ version = "2.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" +[[package]] +name = "crc32fast" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9481c1c90cbf2ac953f07c8d4a58aa3945c425b7185c9154d67a65e4230da511" +dependencies = [ + "cfg-if", +] + [[package]] name = "critical-section" version = "1.2.0" @@ -948,6 +957,16 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" +[[package]] +name = "flate2" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "843fba2746e448b37e26a819579957415c8cef339bf08564fe8b7ddbd959573c" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + [[package]] name = "flume" version = "0.12.0" @@ -2019,6 +2038,15 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + [[package]] name = "matchit" version = "0.8.4" @@ -2041,6 +2069,16 @@ version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79" +[[package]] +name = "metrics" +version = "0.24.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5312e9ba3771cfa961b585728215e3d972c950a3eed9252aa093d6301277e8" +dependencies = [ + "ahash", + "portable-atomic", +] + [[package]] name = "miette" version = "7.6.0" @@ -2090,6 +2128,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" dependencies = [ "adler2", + "simd-adler32", ] [[package]] @@ -2167,6 +2206,15 @@ dependencies = [ "smallvec", ] +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "num-bigint" version = "0.4.8" @@ -2355,6 +2403,73 @@ dependencies = [ "tower", ] +[[package]] +name = "openshell-ocsf" +version = "0.0.0" +dependencies = [ + "chrono", + "serde", + "serde_json", + "serde_repr", + "tracing", + "tracing-subscriber", + "uuid", +] + +[[package]] +name = "openshell-otel" +version = "0.0.0" +dependencies = [ + "async-trait", + "bytes", + "futures", + "http", + "http-body-util", + "hyper-rustls", + "hyper-util", + "metrics", + "openshell-crypto", + "openshell-ocsf", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-otlp", + "opentelemetry_sdk", + "rustls", + "rustls-native-certs", + "serde_json", + "thiserror 2.0.20", + "tokio", + "tonic", + "tower-http 0.6.8", + "tracing", + "tracing-opentelemetry", + "tracing-subscriber", + "zeroize", +] + +[[package]] +name = "openshell-otel-test-support" +version = "0.0.0" +dependencies = [ + "bytes", + "http", + "http-body-util", + "hyper", + "hyper-util", + "openshell-crypto", + "openshell-otel", + "opentelemetry-proto", + "prost", + "rcgen", + "rustls", + "tokio", + "tokio-rustls", + "tokio-stream", + "tonic", + "tracing", + "tracing-subscriber", +] + [[package]] name = "openshell-policy" version = "0.0.0" @@ -2473,6 +2588,83 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" +[[package]] +name = "opentelemetry" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c1f1a6ac9c875a4941e4c7c085b61e8f4daa326de03b4701768c3491a6ad9ee" +dependencies = [ + "futures-core", + "futures-sink", + "js-sys", + "pin-project-lite", + "thiserror 2.0.20", + "tracing", +] + +[[package]] +name = "opentelemetry-http" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "302249bd8ee804789faaa7b5b2cbf79bc61cb864714079c644e3828af5b7e811" +dependencies = [ + "async-trait", + "bytes", + "http", + "opentelemetry", +] + +[[package]] +name = "opentelemetry-otlp" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0756af24841e367128ef31c831999937b8b5c5197d47914590d8f4e2e88c2e1a" +dependencies = [ + "flate2", + "http", + "httpdate", + "opentelemetry", + "opentelemetry-http", + "opentelemetry-proto", + "opentelemetry_sdk", + "prost", + "thiserror 2.0.20", + "tokio", + "tonic", + "tonic-types", +] + +[[package]] +name = "opentelemetry-proto" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d576f5dddc3299341bcd85a04be17b2564844c0c9563214f02d85f2524d1afae" +dependencies = [ + "opentelemetry", + "opentelemetry_sdk", + "prost", + "tonic", + "tonic-prost", +] + +[[package]] +name = "opentelemetry_sdk" +version = "0.33.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "372a912db2974d1990207006fd0e3aa0ef3fd4ad3be43c65cfaadf2206866061" +dependencies = [ + "futures-channel", + "futures-executor", + "futures-util", + "opentelemetry", + "percent-encoding", + "portable-atomic", + "rand 0.9.4", + "thiserror 2.0.20", + "tokio", + "tokio-stream", +] + [[package]] name = "ordered-float" version = "2.10.1" @@ -2482,6 +2674,15 @@ dependencies = [ "num-traits", ] +[[package]] +name = "otlp-support" +version = "0.0.0" +dependencies = [ + "openshell-otel-test-support", + "openshell-testkit", + "serde_json", +] + [[package]] name = "owo-colors" version = "4.3.0" @@ -3397,6 +3598,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_repr" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "serde_urlencoded" version = "0.7.1" @@ -3453,6 +3665,15 @@ dependencies = [ "digest 0.11.2", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "1.3.0" @@ -3478,6 +3699,12 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "simd-adler32" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -3531,6 +3758,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spiffe-support" +version = "0.0.0" +dependencies = [ + "jsonwebtoken", + "openshell-crypto", + "openshell-testkit", + "serde_json", +] + [[package]] name = "spin" version = "0.9.9" @@ -3886,6 +4123,15 @@ dependencies = [ "syn 3.0.5", ] +[[package]] +name = "thread_local" +version = "1.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" +dependencies = [ + "cfg-if", +] + [[package]] name = "time" version = "0.3.47" @@ -4032,6 +4278,7 @@ dependencies = [ "axum", "base64 0.22.1", "bytes", + "flate2", "h2", "http", "http-body", @@ -4138,6 +4385,8 @@ dependencies = [ "tower", "tower-layer", "tower-service", + "tracing", + "uuid", ] [[package]] @@ -4202,6 +4451,64 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-opentelemetry" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a904802a1b902f43638b677ff2a650847e3b4404101b6c586d648e8c1e3e8fe" +dependencies = [ + "js-sys", + "opentelemetry", + "tracing", + "tracing-core", + "tracing-log", + "tracing-subscriber", + "web-time", +] + +[[package]] +name = "tracing-serde" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "704b1aeb7be0d0a84fc9828cae51dab5970fee5088f83d1dd7ee6f6246fc6ff1" +dependencies = [ + "serde", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "serde", + "serde_json", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", + "tracing-serde", ] [[package]] @@ -4352,6 +4659,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + [[package]] name = "vcpkg" version = "0.2.15" @@ -4515,6 +4828,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "webpki-root-certs" version = "1.0.10" @@ -4892,6 +5215,20 @@ name = "zeroize" version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] [[package]] name = "zerotrie" diff --git a/tests/support/Cargo.toml b/tests/support/Cargo.toml index e3dae4234d..e47dbc2d8a 100644 --- a/tests/support/Cargo.toml +++ b/tests/support/Cargo.toml @@ -5,4 +5,4 @@ # environment runs. Suites depend on them by path. [workspace] resolver = "2" -members = ["container-engine", "host-server", "keycloak", "podman", "sandbox-clients"] +members = ["container-engine", "host-server", "keycloak", "otlp", "podman", "sandbox-clients", "spiffe"] diff --git a/tests/support/README.md b/tests/support/README.md index 7b7b0a775a..c2208e8629 100644 --- a/tests/support/README.md +++ b/tests/support/README.md @@ -25,6 +25,9 @@ never skips it. Add a row when you add a variable. The runner also sets | `OPENSHELL_TEST_KEYCLOAK_CLIENT_ID` | `-keycloak` | `keycloak-support` | A client in that realm that allows password grants. | | `OPENSHELL_TEST_KEYCLOAK_USERNAME` | `-keycloak` | `keycloak-support` | The realm user that tests sign in as. | | `OPENSHELL_TEST_KEYCLOAK_PASSWORD` | `-keycloak` | `keycloak-support` | That user's password. | +| `OPENSHELL_TEST_OTLP_LOG` | `-otlp` (`playbooks/otlp.yaml`) | `otlp-support` | The JSONL file where the environment's OTLP collector appends every trace export it receives, readable by the test user. Tests read only spans they named. | +| `OPENSHELL_TEST_OTLP_ENDPOINT` | `-otlp` | `otlp-support` | The collector endpoint in the gateway's `[openshell.gateway.otlp]`, which also enables the agent trace relay. Tests check that sandboxes never see it. | +| `OPENSHELL_TEST_SPIFFE_JWKS` | `-spiffe` (`playbooks/spiffe.yaml`) | `spiffe-support` | The JWKS that verifies the JWT-SVIDs the environment's gateway and supervisor Workload APIs issue. | | `OPENSHELL_TEST_ADDITIONAL_CA_CERT` | The additional-CA environment, which sets `openshell.supervisor.network.additional_ca_bundle` (added by #5729) | `host-server-support` (`TestCa::from_env`) | The path of the CA certificate, in PEM, that the supervisor trusts for sandbox egress. | | `OPENSHELL_TEST_ADDITIONAL_CA_KEY` | The additional-CA environment | `host-server-support` (`TestCa::from_env`) | The path of that CA's private key, in PEM, readable by the test user. Tests sign server certificates with it. | | `OPENSHELL_TEST_BASE_IMAGE` | Optional; you, for example to use a mirror | `testkit::base_image()` | The default sandbox image. Unset, it is `nvcr.io/nvidia/base/ubuntu:24.04`. | diff --git a/tests/support/host-server/src/http.rs b/tests/support/host-server/src/http.rs index 887d5690d4..d32aaeb4c6 100644 --- a/tests/support/host-server/src/http.rs +++ b/tests/support/host-server/src/http.rs @@ -3,7 +3,9 @@ use std::fmt::Write as _; use std::net::SocketAddr; +use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; use testkit::{Poll, Result}; use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _}; @@ -21,6 +23,11 @@ pub struct Request { /// The server's address on the connection the request arrived on: the /// address of the test host the client reached it by. pub local_addr: Option, + /// The connection the request arrived on, numbered from 1 in the order + /// the server accepted them. + pub connection: usize, + /// The number of bytes the request took on the connection. + pub size: usize, } impl Request { @@ -38,6 +45,17 @@ impl Request { header(&self.head, name) } + /// The values of every header named `name`, in any case. + pub fn headers(&self, name: &str) -> Vec { + self.head + .lines() + .skip(1) + .filter_map(|line| line.split_once(':')) + .filter(|(header, _)| header.trim().eq_ignore_ascii_case(name)) + .map(|(_, value)| value.trim().to_string()) + .collect() + } + fn request_line(&self) -> (&str, &str) { let line = self.head.lines().next().unwrap_or_default(); let mut parts = line.split(' '); @@ -140,22 +158,34 @@ fn reason(status: u16) -> &'static str { 202 => "Accepted", 204 => "No Content", 400 => "Bad Request", + 401 => "Unauthorized", 403 => "Forbidden", 404 => "Not Found", 405 => "Method Not Allowed", 418 => "I'm a teapot", + 503 => "Service Unavailable", _ => "Status", } } type Handler = dyn Fn(&Request) -> Response + Send + Sync; +/// What an [`HttpRecorder`]'s connections have shared with the test. +#[derive(Default)] +struct Recorded { + requests: Mutex>, + accepted: AtomicUsize, + open: AtomicUsize, + received: AtomicUsize, + cut: AtomicUsize, +} + /// An HTTP server that records each request it read and answers it with a /// handler's response. A connection stays open for another request while /// the responses keep it alive and the requests don't close it. pub struct HttpRecorder { pub port: u16, - requests: Arc>>, + recorded: Arc, server: Server, } @@ -202,40 +232,52 @@ impl HttpRecorder { async fn listen( port: u16, tls: Option, + read_timeout: Duration, handler: impl Fn(&Request) -> Response + Send + Sync + 'static, ) -> Result { let handler: Arc = Arc::new(handler); - let requests = Arc::new(Mutex::new(Vec::new())); - let task_requests = Arc::clone(&requests); + let recorded = Arc::new(Recorded::default()); + let task_recorded = Arc::clone(&recorded); let server = Server::start(port, move |stream| { let _ = stream.set_nodelay(true); - let local_addr = stream.local_addr().ok(); + let peer = Peer { + local_addr: stream.local_addr().ok(), + connection: task_recorded.accepted.fetch_add(1, Ordering::AcqRel) + 1, + read_timeout, + }; + task_recorded.open.fetch_add(1, Ordering::AcqRel); let handler = Arc::clone(&handler); - let requests = Arc::clone(&task_requests); + let recorded = Arc::clone(&task_recorded); let tls = tls.clone(); async move { - match tls { - None => respond(stream, local_addr, handler, requests).await, + let clean = match tls { + None => respond(stream, &peer, &*handler, &recorded).await, Some(tls) => { - let handshake = tokio::time::timeout(READ_TIMEOUT, tls.accept(stream)); - if let Ok(Ok(stream)) = handshake.await { - respond(stream, local_addr, handler, requests).await; + let handshake = tokio::time::timeout(read_timeout, tls.accept(stream)); + match handshake.await { + Ok(Ok(stream)) => respond(stream, &peer, &*handler, &recorded).await, + _ => false, } } + }; + if !clean { + recorded.cut.fetch_add(1, Ordering::AcqRel); } + recorded.open.fetch_sub(1, Ordering::AcqRel); } }) .await?; Ok(Self { port: server.port, - requests, + recorded, server, }) } /// The requests the server has read so far. pub fn requests(&self) -> Vec { - self.requests + self.recorded + .requests .lock() .unwrap_or_else(PoisonError::into_inner) .clone() @@ -246,6 +288,12 @@ impl HttpRecorder { self.server.connections() } + /// The number of bytes the server has read, including any it never + /// parsed into a whole request. + pub fn received(&self) -> usize { + self.recorded.received.load(Ordering::Acquire) + } + /// The requests the server has read, once there are at least `count`. pub async fn wait_for_requests(&self, count: usize) -> Result> { testkit::poll_until( @@ -266,6 +314,37 @@ impl HttpRecorder { ) .await } + + /// Wait up to `timeout` for every connection the server accepted to + /// close, so [`received`](Self::received) counts all they sent. Fails if + /// a connection ended other than at a request boundary: by a read + /// timeout or error, or partway through a request. + pub async fn wait_closed(&self, timeout: Duration) -> Result { + testkit::poll_until( + &format!( + "every connection to the host server on port {} to close", + self.port + ), + timeout, + WAIT_INTERVAL, + async || { + let open = self.recorded.open.load(Ordering::Acquire); + Ok(if open == 0 { + Poll::Ready(()) + } else { + Poll::Pending(format!("{open} open connection(s)")) + }) + }, + ) + .await?; + let cut = self.recorded.cut.load(Ordering::Acquire); + testkit::ensure!( + cut == 0, + "{cut} connection(s) to the host server on port {} ended without closing at a request boundary", + self.port + ); + Ok(()) + } } /// Options for an [`HttpRecorder`], from [`HttpRecorder::builder`]. @@ -273,6 +352,7 @@ impl HttpRecorder { pub struct HttpRecorderBuilder { port: u16, tls: Option, + read_timeout: Option, } impl HttpRecorderBuilder { @@ -293,6 +373,15 @@ impl HttpRecorderBuilder { self } + /// Close a connection that sends nothing for `timeout` while the server + /// waits for the rest of a request or the next one, instead of 10 + /// seconds. + #[must_use] + pub fn read_timeout(mut self, timeout: Duration) -> Self { + self.read_timeout = Some(timeout); + self + } + /// Answer every request with `200` and `body`. pub async fn start(self, body: impl Into) -> Result { let body = body.into(); @@ -305,34 +394,100 @@ impl HttpRecorderBuilder { handler: impl Fn(&Request) -> Response + Send + Sync + 'static, ) -> Result { let tls = self.tls.as_ref().map(Identity::acceptor).transpose()?; - HttpRecorder::listen(self.port, tls, handler).await + let read_timeout = self.read_timeout.unwrap_or(READ_TIMEOUT); + HttpRecorder::listen(self.port, tls, read_timeout, handler).await } } +/// The connection an [`HttpRecorder`] serves. +struct Peer { + local_addr: Option, + connection: usize, + read_timeout: Duration, +} + /// Read requests, record each, and answer with `handler` until a response -/// or request closes the connection. +/// or request closes the connection. Returns whether the connection closed +/// at a request boundary. async fn respond( mut stream: impl AsyncRead + AsyncWrite + Unpin, - local_addr: Option, - handler: Arc, - requests: Arc>>, -) { + peer: &Peer, + handler: &Handler, + recorded: &Recorded, +) -> bool { let mut buffer = Vec::new(); - while let Some(request) = read_request(&mut stream, local_addr, &mut buffer).await { + let clean = loop { + let read = next_request( + &mut stream, + &mut buffer, + &recorded.received, + peer.read_timeout, + ); + let mut request = match read.await { + Next::Request(request) => request, + Next::Closed => break true, + Next::Cut => break false, + }; + request.local_addr = peer.local_addr; + request.connection = peer.connection; let response = handler(&request); let close = !response.keep_alive || request .header("connection") .is_some_and(|value| value.eq_ignore_ascii_case("close")); - requests + recorded + .requests .lock() .unwrap_or_else(PoisonError::into_inner) .push(request); - if stream.write_all(&response.encode(close)).await.is_err() || close { - break; + if stream.write_all(&response.encode(close)).await.is_err() { + break false; } - } + if close { + break true; + } + }; let _ = stream.shutdown().await; + clean +} + +/// How reading the next request from a connection ended. +enum Next { + Request(Request), + /// The client closed the connection before sending another byte. + Closed, + /// A read timed out or failed, or the client closed the connection or + /// exceeded the size limit partway through a request. + Cut, +} + +/// Read the next request from `stream`, starting with the bytes already in +/// `buffer`, and leave any bytes after it in `buffer`. Counts every byte read +/// in `received`. +async fn next_request( + stream: &mut (impl AsyncRead + Unpin), + buffer: &mut Vec, + received: &AtomicUsize, + timeout: Duration, +) -> Next { + let mut chunk = [0_u8; 4096]; + loop { + if let Some((request, length)) = parse_request(buffer) { + buffer.drain(..length); + return Next::Request(request); + } + match tokio::time::timeout(timeout, stream.read(&mut chunk)).await { + Ok(Ok(0)) if buffer.is_empty() => return Next::Closed, + Ok(Ok(read)) if read > 0 => { + received.fetch_add(read, Ordering::AcqRel); + if buffer.len() >= MAX_REQUEST { + return Next::Cut; + } + buffer.extend_from_slice(&chunk[..read]); + } + _ => return Next::Cut, + } + } } /// Read one request from `stream`, starting with the bytes already in @@ -343,19 +498,12 @@ pub(crate) async fn read_request( local_addr: Option, buffer: &mut Vec, ) -> Option { - let mut chunk = [0_u8; 4096]; - loop { - if let Some((mut request, length)) = parse_request(buffer) { - buffer.drain(..length); + match next_request(stream, buffer, &AtomicUsize::new(0), READ_TIMEOUT).await { + Next::Request(mut request) => { request.local_addr = local_addr; - return Some(request); - } - match tokio::time::timeout(READ_TIMEOUT, stream.read(&mut chunk)).await { - Ok(Ok(read)) if read > 0 && buffer.len() < MAX_REQUEST => { - buffer.extend_from_slice(&chunk[..read]); - } - _ => return None, + Some(request) } + Next::Closed | Next::Cut => None, } } @@ -380,6 +528,8 @@ fn parse_request(bytes: &[u8]) -> Option<(Request, usize)> { head, body, local_addr: None, + connection: 0, + size: end + 4 + length, }, end + 4 + length, )) @@ -530,15 +680,19 @@ mod tests { response.ends_with("Connection: close\r\n\r\n/two"), "{response}" ); - let paths: Vec<_> = recorder - .wait_for_requests(2) - .await - .unwrap() + let requests = recorder.wait_for_requests(2).await.unwrap(); + let paths: Vec<_> = requests .iter() .map(|request| request.path().to_string()) .collect(); assert_eq!(paths, ["/one", "/two"]); + assert!(requests.iter().all(|request| request.connection == 1)); assert_eq!(recorder.connections(), 1); + recorder.wait_closed(READ_TIMEOUT).await.unwrap(); + assert_eq!( + recorder.received(), + requests.iter().map(|request| request.size).sum::() + ); } #[tokio::test] diff --git a/tests/support/otlp/Cargo.toml b/tests/support/otlp/Cargo.toml new file mode 100644 index 0000000000..6357db8cb4 --- /dev/null +++ b/tests/support/otlp/Cargo.toml @@ -0,0 +1,17 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "otlp-support" +description = "OTLP collector fixture for test suites whose gateway exports to a collector the test runs" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[dependencies] +openshell-otel-test-support = { path = "../../../crates/openshell-otel-test-support" } +openshell-testkit = { path = "../../testkit/testkit" } +serde_json = "1" diff --git a/tests/support/otlp/src/lib.rs b/tests/support/otlp/src/lib.rs new file mode 100644 index 0000000000..36d0f117a2 --- /dev/null +++ b/tests/support/otlp/src/lib.rs @@ -0,0 +1,190 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! What an environment's OTLP collector received, for suites whose gateway +//! exports to it. +//! +//! The environment runs the collector, configures the gateway's +//! `[openshell.gateway.otlp]` endpoint and publishes both in +//! `OPENSHELL_TEST_OTLP_*` variables. The collector appends each trace export +//! to a JSONL log, one OTLP/JSON `ExportTraceServiceRequest` per line, as the +//! OpenTelemetry Collector's file exporter writes it. Under +//! `openshell-test-runner`, the tmachine `-otlp` environments do +//! that (`tests/tmachine/ansible/playbooks/otlp.yaml`); against your own +//! deployment, set them yourself: +//! +//! | Variable | Example | +//! |---|---| +//! | `OPENSHELL_TEST_OTLP_LOG` | `/var/lib/openshell-test/otlp/traces.jsonl` | +//! | `OPENSHELL_TEST_OTLP_ENDPOINT` | `http://host.containers.internal:4317` | +//! +//! The log holds every test's spans, and the gateway's, so a test reads only +//! spans it named, with [`testkit::Context::name`]. A missing variable fails +//! the test; it never skips it. + +use std::collections::HashMap; +use std::path::PathBuf; +use std::time::Duration; + +use serde_json::Value; +use testkit::{Error, Poll, Result, ResultExt as _, poll_until}; + +pub use openshell_otel_test_support::relay::{ + SANDBOX_ID_KEY, SOURCE_KEY, SOURCE_VALUE, encoded_trace_request, +}; + +pub const LOG_ENV: &str = "OPENSHELL_TEST_OTLP_LOG"; +pub const ENDPOINT_ENV: &str = "OPENSHELL_TEST_OTLP_ENDPOINT"; + +/// String resource attributes, keyed by name. +pub type Attributes = HashMap; + +/// One span the collector received. +#[derive(Clone, Debug)] +pub struct Span { + pub name: String, + /// The string attributes of the resource the span arrived with. A + /// duplicated key keeps its last value. + pub attributes: Attributes, + /// Keys that resource carried more than once. + pub duplicate_resource_keys: Vec, +} + +/// The environment's collector. +pub struct Collector { + log: PathBuf, + endpoint: String, +} + +impl Collector { + /// The collector [`LOG_ENV`] and [`ENDPOINT_ENV`] describe. + pub fn from_env() -> Result { + Ok(Self { + log: PathBuf::from(required(LOG_ENV)?), + endpoint: required(ENDPOINT_ENV)?, + }) + } + + /// The endpoint the gateway exports to, such as + /// `http://host.containers.internal:4317`. + pub fn endpoint(&self) -> &str { + &self.endpoint + } + + /// The `host:port` of [`Self::endpoint`]. + pub fn host_port(&self) -> &str { + let authority = self + .endpoint + .split_once("://") + .map_or(self.endpoint.as_str(), |(_, rest)| rest); + authority.split('/').next().unwrap_or(authority) + } + + /// Every span received so far whose name is in `names`, in arrival + /// order. + pub fn spans(&self, names: &[&str]) -> Result> { + let log = std::fs::read_to_string(&self.log).context(format!( + "read the OTLP collector log {}", + self.log.display() + ))?; + // The collector may be part way through writing the last line. + let complete = log.rfind('\n').map_or("", |end| &log[..end]); + let mut spans = Vec::new(); + for (index, line) in complete.lines().enumerate() { + if line.trim().is_empty() { + continue; + } + let request: Value = serde_json::from_str(line).context(format!( + "parse line {} of {}", + index + 1, + self.log.display() + ))?; + collect_spans(&request, names, &mut spans); + } + Ok(spans) + } + + /// Wait up to `within` until every span in `names` has arrived. Returns + /// each name's spans; a name that arrived more than once has more than + /// one. + pub async fn wait_for_spans( + &self, + names: &[&str], + within: Duration, + ) -> Result>> { + poll_until( + &format!("the collector to receive spans {names:?}"), + within, + Duration::from_millis(250), + async || { + let mut by_name: HashMap> = HashMap::new(); + for span in self.spans(names)? { + by_name.entry(span.name.clone()).or_default().push(span); + } + let missing: Vec<&str> = names + .iter() + .copied() + .filter(|name| !by_name.contains_key(*name)) + .collect(); + Ok(if missing.is_empty() { + Poll::Ready(by_name) + } else { + Poll::Pending(format!("spans {missing:?} have not arrived")) + }) + }, + ) + .await + } +} + +fn collect_spans(request: &Value, names: &[&str], spans: &mut Vec) { + for resource_spans in array(&request["resourceSpans"]) { + let mut attributes = Attributes::new(); + let mut seen = Vec::new(); + let mut duplicate_resource_keys = Vec::new(); + for attribute in array(&resource_spans["resource"]["attributes"]) { + let Some(key) = attribute["key"].as_str() else { + continue; + }; + // Track duplicates for every value type; the map keeps only + // string values. + if seen.contains(&key) { + duplicate_resource_keys.push(key.to_string()); + } else { + seen.push(key); + } + if let Some(value) = attribute["value"]["stringValue"].as_str() { + attributes.insert(key.to_string(), value.to_string()); + } + } + for scope_spans in array(&resource_spans["scopeSpans"]) { + for span in array(&scope_spans["spans"]) { + let Some(name) = span["name"].as_str() else { + continue; + }; + if names.contains(&name) { + spans.push(Span { + name: name.to_string(), + attributes: attributes.clone(), + duplicate_resource_keys: duplicate_resource_keys.clone(), + }); + } + } + } + } +} + +fn array(value: &Value) -> &[Value] { + value.as_array().map_or(&[], Vec::as_slice) +} + +fn required(name: &str) -> Result { + std::env::var(name) + .ok() + .filter(|value| !value.is_empty()) + .ok_or_else(|| { + Error::msg(format!( + "{name} is not set; this suite needs a gateway that exports to the environment's OTLP collector (see the otlp-support crate docs)" + )) + }) +} diff --git a/tests/support/spiffe/Cargo.toml b/tests/support/spiffe/Cargo.toml new file mode 100644 index 0000000000..db321b6b78 --- /dev/null +++ b/tests/support/spiffe/Cargo.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "spiffe-support" +description = "Verifies JWT-SVIDs from the SPIFFE Workload APIs a test environment runs" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/ai-openshell/openshell" +publish = false + +[dependencies] +jsonwebtoken = { version = "10", default-features = false } +openshell-crypto = { path = "../../../crates/openshell-crypto" } +openshell-testkit = { path = "../../testkit/testkit" } +serde_json = "1" diff --git a/tests/support/spiffe/src/lib.rs b/tests/support/spiffe/src/lib.rs new file mode 100644 index 0000000000..153a2b3be8 --- /dev/null +++ b/tests/support/spiffe/src/lib.rs @@ -0,0 +1,89 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The environment's SPIFFE Workload APIs, for suites whose gateway and +//! supervisors fetch JWT-SVIDs from them. +//! +//! The environment runs a Workload API for the gateway and one for the +//! supervisors, points the gateway's Workload API socket and the driver's +//! `provider_spiffe_workload_api_socket` at them, and publishes the bundle +//! that verifies their JWT-SVIDs in `OPENSHELL_TEST_SPIFFE_JWKS`. Under +//! `openshell-test-runner`, the tmachine `-spiffe` environments +//! do that (`tests/tmachine/ansible/playbooks/spiffe.yaml`); against your own +//! deployment, set it yourself: +//! +//! | Variable | Example | +//! |---|---| +//! | `OPENSHELL_TEST_SPIFFE_JWKS` | `/var/lib/openshell-test/spiffe/jwks.json` | +//! +//! The Workload APIs issue JWT-SVIDs with issuer [`ISSUER`], to +//! [`GATEWAY_SUBJECT`] for the gateway and to [`SUPERVISOR_SUBJECT`] for +//! every supervisor: suites test credential isolation with distinct providers +//! and audiences, not SPIRE attestation. A missing variable fails the test; +//! it never skips it. + +use std::path::PathBuf; + +use jsonwebtoken::{Algorithm, DecodingKey, Validation}; +use testkit::{Error, Result, ResultExt as _}; + +pub const JWKS_ENV: &str = "OPENSHELL_TEST_SPIFFE_JWKS"; + +pub const TRUST_DOMAIN: &str = "openshell-e2e.test"; +/// The `iss` of every JWT-SVID. +pub const ISSUER: &str = "https://spiffe.openshell-e2e.test"; +/// The SPIFFE ID the gateway's Workload API issues. +pub const GATEWAY_SUBJECT: &str = "spiffe://openshell-e2e.test/openshell/gateway"; +/// The SPIFFE ID the supervisors' Workload API issues. +pub const SUPERVISOR_SUBJECT: &str = "spiffe://openshell-e2e.test/openshell/sandbox/e2e"; + +/// The key that verifies the Workload APIs' JWT-SVIDs. +pub struct Bundle { + key_id: String, + key: DecodingKey, +} + +impl Bundle { + /// The RS256 key in the JWKS [`JWKS_ENV`] names. + pub fn from_env() -> Result { + let path = PathBuf::from( + std::env::var(JWKS_ENV) + .ok() + .filter(|value| !value.is_empty()) + .ok_or_else(|| { + Error::msg(format!( + "{JWKS_ENV} is not set; this suite needs a gateway and supervisors that use the environment's SPIFFE Workload APIs (see the spiffe-support crate docs)" + )) + })?, + ); + let jwks = std::fs::read(&path).context(format!("read {}", path.display()))?; + Self::from_jwks(&jwks).context(format!("read the bundle in {}", path.display())) + } + + fn from_jwks(jwks: &[u8]) -> Result { + let jwks: serde_json::Value = serde_json::from_slice(jwks).context("parse the JWKS")?; + let key = &jwks["keys"][0]; + let component = |name: &str| { + key[name] + .as_str() + .ok_or_else(|| Error::msg(format!("the JWKS key has no {name}"))) + }; + Ok(Self { + key_id: component("kid")?.to_string(), + key: DecodingKey::from_rsa_components(component("n")?, component("e")?) + .map_err(|error| Error::msg(format!("read the JWKS key: {error}")))?, + }) + } + + /// Whether `token` is a JWT-SVID the Workload APIs issued to a + /// supervisor for `audience`, with a valid signature and lifetime. + pub fn verify_supervisor_svid(&self, token: &str, audience: &str) -> bool { + let mut validation = Validation::new(Algorithm::RS256); + validation.set_issuer(&[ISSUER]); + validation.set_audience(&[audience]); + validation.sub = Some(SUPERVISOR_SUBJECT.to_string()); + validation.set_required_spec_claims(&["exp", "iat", "iss", "sub", "aud"]); + openshell_crypto::jwt::decode::(token, &self.key, &validation) + .is_ok_and(|verified| verified.header.kid.as_deref() == Some(self.key_id.as_str())) + } +} diff --git a/tests/tmachine/ansible/playbooks/files/spiffe-workload-api.py b/tests/tmachine/ansible/playbooks/files/spiffe-workload-api.py new file mode 100644 index 0000000000..3800363298 --- /dev/null +++ b/tests/tmachine/ansible/playbooks/files/spiffe-workload-api.py @@ -0,0 +1,227 @@ +#!/usr/bin/python3 +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +"""SPIFFE Workload APIs for an OpenShell test environment. + +Serves FetchJWTSVID and FetchJWTBundles twice: for the gateway on a Unix +socket and for supervisors on a TCP address. Each issues RS256 JWT-SVIDs for +one SPIFFE ID, whoever asks: suites test credential isolation with distinct +providers and audiences, not attestation. Both sign with one key, which is +created on first start, and serve its JWKS as the trust domain's bundle. The +JWKS is also written to a file, for tests to verify SVIDs with. + +The messages are hand-encoded, so the stub needs only grpcio and +cryptography, not generated code. +""" + +import argparse +import base64 +import json +import os +import time +from concurrent import futures +from pathlib import Path + +import grpc +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import padding, rsa + +KEY_ID = "openshell-test-key" +SVID_LIFETIME_SECONDS = 3600 + + +def b64url(data): + return base64.urlsafe_b64encode(data).rstrip(b"=").decode() + + +def varint(value): + out = bytearray() + while True: + byte = value & 0x7F + value >>= 7 + if value: + out.append(byte | 0x80) + else: + out.append(byte) + return bytes(out) + + +def field(number, data): + """A length-delimited protobuf field.""" + if isinstance(data, str): + data = data.encode() + return varint(number << 3 | 2) + varint(len(data)) + data + + +def read_varint(data, index): + value = shift = 0 + while True: + byte = data[index] + index += 1 + value |= (byte & 0x7F) << shift + shift += 7 + if not byte & 0x80: + return value, index + + +def string_fields(data, number): + """The values of every length-delimited field `number` in a message.""" + values = [] + index = 0 + while index < len(data): + key, index = read_varint(data, index) + wire_type = key & 7 + if wire_type == 0: + _, index = read_varint(data, index) + elif wire_type == 1: + index += 8 + elif wire_type == 2: + length, index = read_varint(data, index) + if key >> 3 == number: + values.append(data[index : index + length].decode()) + index += length + elif wire_type == 5: + index += 4 + else: + raise ValueError(f"unsupported wire type {wire_type}") + return values + + +def load_key(path, jwks_path): + path = Path(path) + jwks_path = Path(jwks_path) + if not path.exists(): + key = rsa.generate_private_key(public_exponent=65537, key_size=2048) + pem = key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(descriptor, "wb") as file: + file.write(pem) + key = serialization.load_pem_private_key(path.read_bytes(), password=None) + numbers = key.public_key().public_numbers() + jwks = json.dumps( + { + "keys": [ + { + "kty": "RSA", + "kid": KEY_ID, + "use": "sig", + "alg": "RS256", + "n": b64url( + numbers.n.to_bytes((numbers.n.bit_length() + 7) // 8, "big") + ), + "e": b64url( + numbers.e.to_bytes((numbers.e.bit_length() + 7) // 8, "big") + ), + } + ] + } + ).encode() + partial = jwks_path.with_name(f"{jwks_path.name}.partial") + partial.write_bytes(jwks) + partial.chmod(0o644) + partial.replace(jwks_path) + return key, jwks + + +class WorkloadApi: + def __init__(self, key, jwks, issuer, trust_domain, spiffe_id): + self.key = key + self.jwks = jwks + self.issuer = issuer + self.trust_domain = trust_domain + self.spiffe_id = spiffe_id + + def jwt_svid(self, audience): + now = int(time.time()) + header = {"alg": "RS256", "kid": KEY_ID, "typ": "JWT"} + claims = { + "iss": self.issuer, + "sub": self.spiffe_id, + "aud": audience, + "iat": now, + "exp": now + SVID_LIFETIME_SECONDS, + } + signing_input = ( + b64url(json.dumps(header).encode()) + + "." + + b64url(json.dumps(claims).encode()) + ) + signature = self.key.sign( + signing_input.encode(), padding.PKCS1v15(), hashes.SHA256() + ) + return signing_input + "." + b64url(signature) + + def fetch_jwt_svid(self, request, _context): + audience = string_fields(request, 1) + svid = field(1, self.spiffe_id) + field(2, self.jwt_svid(audience)) + return field(1, svid) + + def fetch_jwt_bundles(self, _request, _context): + yield field(1, field(1, self.trust_domain) + field(2, self.jwks)) + + def handler(self): + identity = lambda data: data # noqa: E731 + return grpc.method_handlers_generic_handler( + "SpiffeWorkloadAPI", + { + "FetchJWTSVID": grpc.unary_unary_rpc_method_handler( + self.fetch_jwt_svid, + request_deserializer=identity, + response_serializer=identity, + ), + "FetchJWTBundles": grpc.unary_stream_rpc_method_handler( + self.fetch_jwt_bundles, + request_deserializer=identity, + response_serializer=identity, + ), + }, + ) + + +def serve(api, address): + server = grpc.server(futures.ThreadPoolExecutor(max_workers=16)) + server.add_generic_rpc_handlers((api.handler(),)) + if server.add_insecure_port(address) == 0: + raise SystemExit(f"cannot listen on {address}") + server.start() + return server + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--key", required=True, help="signing key, created if missing") + parser.add_argument("--jwks", required=True, help="where to write the bundle") + parser.add_argument("--issuer", required=True) + parser.add_argument("--trust-domain", required=True) + parser.add_argument("--gateway-socket", required=True) + parser.add_argument("--gateway-id", required=True) + parser.add_argument("--supervisor-address", required=True, help="host:port") + parser.add_argument("--supervisor-id", required=True) + args = parser.parse_args() + + key, jwks = load_key(args.key, args.jwks) + Path(args.gateway_socket).unlink(missing_ok=True) + servers = [ + serve( + WorkloadApi(key, jwks, args.issuer, args.trust_domain, args.gateway_id), + f"unix:{args.gateway_socket}", + ), + serve( + WorkloadApi(key, jwks, args.issuer, args.trust_domain, args.supervisor_id), + args.supervisor_address, + ), + ] + # The gateway may run as another user. + Path(args.gateway_socket).chmod(0o777) + print(f"serving {args.gateway_socket} and {args.supervisor_address}", flush=True) + for server in servers: + server.wait_for_termination() + + +if __name__ == "__main__": + main() diff --git a/tests/tmachine/ansible/playbooks/otlp.yaml b/tests/tmachine/ansible/playbooks/otlp.yaml new file mode 100644 index 0000000000..970c35c068 --- /dev/null +++ b/tests/tmachine/ansible/playbooks/otlp.yaml @@ -0,0 +1,172 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Run an OTLP collector in the environment, point the gateway's OTLP export +# and agent trace relay at it, and publish where tests read what it received. +# +# The collector is a stock OpenTelemetry Collector whose file exporter appends +# every trace export it receives to a JSONL file, one +# ExportTraceServiceRequest per line. Tests find their own spans in it by +# name, so any number of them can share the collector. Environment setup +# applies this once and caches the disk, so the container restarts on every +# boot. Supervisors in Podman containers reach the test VM as +# host.containers.internal. The OTLP fixture (tests/support/otlp) reads the +# variables published below. +--- +- name: OTLP collector for tests + hosts: all + gather_facts: false + vars: + otlp_container_name: openshell-otlp-collector + otlp_image: ghcr.io/open-telemetry/opentelemetry-collector-releases/opentelemetry-collector:0.166.0 + otlp_port: 4317 + otlp_endpoint: "http://host.containers.internal:{{ otlp_port }}" + otlp_directory: /var/lib/openshell-test/otlp + otlp_log: "{{ otlp_directory }}/traces.jsonl" + tasks: + - name: Wait for SSH + ansible.builtin.wait_for_connection: + + - name: Detect tmachine container runtime + ansible.builtin.include_role: + name: tmachine_container_runtime + + - name: Set collector runtime values + ansible.builtin.set_fact: + otlp_runtime_user: >- + {{ 'tmachine' if tmachine_container_runtime_is_rootless else 'root' }} + otlp_runtime_home: >- + {{ '/home/tmachine' if tmachine_container_runtime_is_rootless else '/root' }} + # Docker restarts the container itself. Podman has no daemon: its + # podman-restart.service starts `--restart always` containers at boot. + otlp_restart_policy: >- + {{ 'unless-stopped' if tmachine_container_runtime_name == 'docker' else 'always' }} + + # The collector runs as its image's own user, which owns nothing here, so + # it needs a directory anyone can write. It creates the log with mode + # 0644, which the test user can read. + - name: Create the collector directory + become: true + ansible.builtin.file: + path: "{{ otlp_directory }}" + state: directory + owner: tmachine + group: tmachine + mode: "0777" + + - name: Configure the collector + become: true + ansible.builtin.copy: + dest: "{{ otlp_directory }}/config.yaml" + owner: tmachine + group: tmachine + mode: "0644" + content: | + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + exporters: + file: + path: /otlp/{{ otlp_log | basename }} + # A restarted collector keeps what it already received. + append: true + # otlp-relay expects a span in the log within 1 s of the + # collector acknowledging it. + flush_interval: 10ms + service: + pipelines: + traces: + receivers: [otlp] + exporters: [file] + + - name: Remove an existing collector + become: true + become_user: "{{ otlp_runtime_user }}" + ansible.builtin.command: + argv: + - "{{ tmachine_container_runtime_name }}" + - rm + - --force + - "{{ otlp_container_name }}" + environment: + HOME: "{{ otlp_runtime_home }}" + changed_when: false + failed_when: false + + - name: Start the collector + become: true + become_user: "{{ otlp_runtime_user }}" + ansible.builtin.command: + argv: + - "{{ tmachine_container_runtime_name }}" + - run + - --detach + - --name + - "{{ otlp_container_name }}" + - --restart + - "{{ otlp_restart_policy }}" + # Every host address, so supervisors reach it through the host alias. + - --publish + - "{{ otlp_port }}:4317" + - --volume + - "{{ otlp_directory }}:/otlp:z" + - "{{ otlp_image }}" + - --config + - /otlp/config.yaml + environment: + HOME: "{{ otlp_runtime_home }}" + changed_when: true + + - name: Restart the collector with rootful Podman at boot + become: true + ansible.builtin.systemd_service: + name: podman-restart.service + enabled: true + when: + - tmachine_container_runtime_name == 'podman' + - not tmachine_container_runtime_is_rootless + + # tmachine lingers (see podman-rootless.yaml), so its user manager, and + # this unit, start at boot. + - name: Restart the collector with rootless Podman at boot + become: true + become_user: tmachine + ansible.builtin.systemd_service: + name: podman-restart.service + scope: user + enabled: true + environment: + HOME: /home/tmachine + XDG_RUNTIME_DIR: "/run/user/{{ tmachine_container_runtime_tmachine_uid.stdout }}" + DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/{{ tmachine_container_runtime_tmachine_uid.stdout }}/bus" + when: + - tmachine_container_runtime_name == 'podman' + - tmachine_container_runtime_is_rootless + + - name: Wait for the collector + ansible.builtin.wait_for: + host: 127.0.0.1 + port: "{{ otlp_port }}" + timeout: 60 + + - name: Export traces and relay agent traces to the collector + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: otlp + gateway_overrides_content: | + [openshell.gateway.otlp] + endpoint = "{{ otlp_endpoint }}" + + [openshell.gateway.otlp.agent] + enabled = true + + - name: Publish OTLP test variables + ansible.builtin.include_tasks: test-env.yaml + vars: + test_env_name: otlp + test_env_vars: + OPENSHELL_TEST_OTLP_LOG: "{{ otlp_log }}" + OPENSHELL_TEST_OTLP_ENDPOINT: "{{ otlp_endpoint }}" diff --git a/tests/tmachine/ansible/playbooks/spiffe.yaml b/tests/tmachine/ansible/playbooks/spiffe.yaml new file mode 100644 index 0000000000..33c4ae8b10 --- /dev/null +++ b/tests/tmachine/ansible/playbooks/spiffe.yaml @@ -0,0 +1,151 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Run SPIFFE Workload APIs in the environment, point the gateway and the +# supervisors at them, and publish the bundle tests verify their SVIDs with. +# +# files/spiffe-workload-api.py serves the gateway's Workload API on a Unix +# socket and the supervisors' on a loopback port, as a system service that +# environment setup enables, so it starts on every boot of the cached disk. +# The gateway reads its Workload API socket only from +# OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET. The packaged gateway is a +# systemd user service whose installer rewrites gateway.env, and the binaries +# installer runs a system service, so a drop-in for each unit sets the +# variable. Supervisors use the driver's +# provider_spiffe_workload_api_socket. Podman supervisors share the test VM's +# network, so they reach theirs over loopback. The SPIFFE fixture +# (tests/support/spiffe) reads the variable published below, and holds the +# issuer and SPIFFE IDs set here. +--- +- name: SPIFFE Workload APIs for tests + hosts: all + gather_facts: false + vars: + spiffe_directory: /var/lib/openshell-test/spiffe + spiffe_gateway_socket: "{{ spiffe_directory }}/gateway.sock" + spiffe_jwks: "{{ spiffe_directory }}/jwks.json" + spiffe_supervisor_port: 17690 + spiffe_trust_domain: openshell-e2e.test + spiffe_issuer: "https://spiffe.{{ spiffe_trust_domain }}" + spiffe_gateway_id: "spiffe://{{ spiffe_trust_domain }}/openshell/gateway" + spiffe_supervisor_id: "spiffe://{{ spiffe_trust_domain }}/openshell/sandbox/e2e" + spiffe_program: /usr/local/libexec/openshell-test/spiffe-workload-api + tasks: + - name: Wait for SSH + ansible.builtin.wait_for_connection: + + - name: Require the environment's driver + ansible.builtin.assert: + that: [environment_driver is defined] + fail_msg: environment_driver names the gateway driver and comes from the environment's base in config.nix + + - name: Install the Workload APIs' dependencies + become: true + ansible.builtin.package: + name: [python3-grpcio, python3-cryptography] + state: present + + - name: Create the Workload APIs' program directory + become: true + ansible.builtin.file: + path: "{{ spiffe_program | dirname }}" + state: directory + owner: root + group: root + mode: "0755" + + - name: Install the Workload APIs + become: true + ansible.builtin.copy: + src: files/spiffe-workload-api.py + dest: "{{ spiffe_program }}" + owner: root + group: root + mode: "0755" + + # The service runs as tmachine. A root gateway connects anyway. + - name: Create the Workload APIs' state directory + become: true + ansible.builtin.file: + path: "{{ spiffe_directory }}" + state: directory + owner: tmachine + group: tmachine + mode: "0755" + + - name: Define the Workload APIs' service + become: true + ansible.builtin.copy: + dest: /etc/systemd/system/openshell-test-spiffe.service + owner: root + group: root + mode: "0644" + content: | + [Unit] + Description=SPIFFE Workload APIs for OpenShell tests + After=network.target + + [Service] + User=tmachine + ExecStart={{ spiffe_program }} --key {{ spiffe_directory }}/key.pem --jwks {{ spiffe_jwks }} --issuer {{ spiffe_issuer }} --trust-domain {{ spiffe_trust_domain }} --gateway-socket {{ spiffe_gateway_socket }} --gateway-id {{ spiffe_gateway_id }} --supervisor-address 127.0.0.1:{{ spiffe_supervisor_port }} --supervisor-id {{ spiffe_supervisor_id }} + Restart=always + + [Install] + WantedBy=multi-user.target + + - name: Start the Workload APIs + become: true + ansible.builtin.systemd_service: + name: openshell-test-spiffe.service + state: restarted + enabled: true + daemon_reload: true + + - name: Wait for the gateway's Workload API + ansible.builtin.wait_for: + path: "{{ spiffe_gateway_socket }}" + timeout: 60 + + - name: Wait for the supervisors' Workload API + ansible.builtin.wait_for: + host: 127.0.0.1 + port: "{{ spiffe_supervisor_port }}" + timeout: 60 + + - name: Create the gateway unit drop-in directories + become: true + ansible.builtin.file: + path: "{{ item }}/openshell-gateway.service.d" + state: directory + owner: root + group: root + mode: "0755" + loop: [/etc/systemd/user, /etc/systemd/system] + + - name: Point the gateway at its Workload API + become: true + ansible.builtin.copy: + dest: "{{ item }}/openshell-gateway.service.d/spiffe.conf" + owner: root + group: root + mode: "0644" + content: | + [Service] + Environment=OPENSHELL_GATEWAY_SPIFFE_WORKLOAD_API_SOCKET={{ spiffe_gateway_socket }} + loop: [/etc/systemd/user, /etc/systemd/system] + + - name: Point supervisors at their Workload API + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: spiffe + gateway_overrides_content: | + [openshell.drivers.{{ environment_driver }}] + provider_spiffe_workload_api_socket = "tcp:127.0.0.1:{{ spiffe_supervisor_port }}" + + - name: Publish SPIFFE test variables + ansible.builtin.include_tasks: test-env.yaml + vars: + test_env_name: spiffe + test_env_vars: + OPENSHELL_TEST_SPIFFE_JWKS: "{{ spiffe_jwks }}" diff --git a/tests/tmachine/artifacts.nix b/tests/tmachine/artifacts.nix index d8b743b803..e25d04d03e 100644 --- a/tests/tmachine/artifacts.nix +++ b/tests/tmachine/artifacts.nix @@ -100,8 +100,6 @@ let # Its move to conformance is deferred until the isolation work in #4120; see # #4246. "provider_auto_create" - # Needs the SPIFFE fixtures that the wrapper sets up. Wrapper lane. - "provider_token_exchange" # Holds only the on-failure restart test until #5507; the rest moved to # testkit. Nextest archive filters cannot select individual tests, so keep # the complete binary in the follow-up bucket. diff --git a/tests/tmachine/config.nix b/tests/tmachine/config.nix index ed62c23eb6..fa741b0de5 100644 --- a/tests/tmachine/config.nix +++ b/tests/tmachine/config.nix @@ -114,6 +114,19 @@ let bases = dockerBases ++ podmanBases; setup.playbooks = [ "ansible/playbooks/cdi.yaml" ]; }; + # An OTLP collector for the gateway and the agent trace relay, for the + # otlp-relay suite. Its endpoint names Podman's host alias. + otlp = { + bases = podmanBases; + setup.playbooks = [ "ansible/playbooks/otlp.yaml" ]; + }; + # SPIFFE Workload APIs for the gateway and supervisors, for the + # provider-token-exchange suite. Supervisors reach theirs over loopback, + # which needs Podman's host-network supervisors. + spiffe = { + bases = podmanBases; + setup.playbooks = [ "ansible/playbooks/spiffe.yaml" ]; + }; }; featureEnvironments = pkgs.lib.concatMap ( feature: map (base: withSetup base feature features.${feature}.setup) features.${feature}.bases