diff --git a/TESTING.md b/TESTING.md index c959a505e3..ac3eddd32d 100644 --- a/TESTING.md +++ b/TESTING.md @@ -329,7 +329,9 @@ service. clients there from the variables. A missing variable fails the test; it never skips it. - **Documentation.** Document the variables in the fixture's module docs, so - anyone can run the suite against their own deployment by setting them. + anyone can run the suite against their own deployment by setting them, and + add a row for each to the + [environment contract table](tests/support/README.md#environment-contract). The Keycloak fixture is `tests/support/keycloak`. Run the suite that uses it with: @@ -639,11 +641,27 @@ nix run .#openshell-test-runner -- run \ #### Gateway overrides in an environment -An environment overrides gateway settings by writing the tables to change to -`/etc/openshell-test/gateway-overrides.toml` in a playbook that runs before the -installer. The file holds whole tables, such as `[openshell.gateway]` or -`[openshell.drivers.podman]`, and is not a complete configuration. Each -installer applies it to the gateway's own file: +An environment overrides gateway settings with the `gateway_overrides` role, +which takes a name and the tables to change, such as `[openshell.gateway]` or +`[openshell.drivers.podman]`: + +```yaml +- name: Push configuration to supervisors + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: config-push + gateway_overrides_content: | + [openshell.gateway] + config_delivery_mode = "push" +``` + +The role writes each name as its own marked block in +`/etc/openshell-test/gateway-overrides.toml`, so writers keep each other's +settings, and `gateway_overrides_state: absent` removes a name's block. +Two blocks must not declare the same table. Don't write the file +directly. The file is not a complete configuration. Each installer applies it +to the gateway's own file: - `binaries` applies it to the `/etc/openshell/gateway.toml` it generates. - `deb` and `rpm` apply it to the service user's diff --git a/tests/suites/conformance/Cargo.lock b/tests/suites/conformance/Cargo.lock index a3c191b327..a190a23ac4 100644 --- a/tests/suites/conformance/Cargo.lock +++ b/tests/suites/conformance/Cargo.lock @@ -1286,9 +1286,13 @@ dependencies = [ name = "host-server-support" version = "0.0.0" dependencies = [ + "openshell-crypto", "openshell-testkit", + "rcgen", + "rustls", "serde_json", "tokio", + "tokio-rustls", "tungstenite", ] @@ -2372,6 +2376,21 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "openshell-providers" +version = "0.0.0" +dependencies = [ + "glob", + "noyalib", + "openshell-core", + "openshell-policy", + "prost-types", + "serde", + "serde_json", + "thiserror 2.0.20", + "url", +] + [[package]] name = "openshell-sdk" version = "0.0.0" @@ -2421,6 +2440,7 @@ dependencies = [ "openshell-bootstrap", "openshell-core", "openshell-policy", + "openshell-providers", "openshell-sdk", "openshell-testkit-macros", "prost-types", diff --git a/tests/suites/conformance/src/credential_gating.rs b/tests/suites/conformance/src/credential_gating.rs index 0433f0dcbf..5230b86428 100644 --- a/tests/suites/conformance/src/credential_gating.rs +++ b/tests/suites/conformance/src/credential_gating.rs @@ -18,7 +18,9 @@ use sandbox_clients_support::{self as clients, http, scripts}; use serde_json::json; use testkit::policy::{self, Access, Endpoint as _}; use testkit::sdk::raw::proto; -use testkit::{Context, Error, GrpcCode, PYTHON_BINARIES, Result, ResultExt as _, Sandbox}; +use testkit::{ + Context, Credential, Error, GrpcCode, PYTHON_BINARIES, Profile, Result, ResultExt as _, Sandbox, +}; const BASH: &str = "/usr/bin/bash"; @@ -194,15 +196,12 @@ async fn policy_binding_updates_provider_environment_live(cx: &mut Context) -> t #[testkit::test] async fn profile_rest_endpoint_rewrites_header_and_body(cx: &mut Context) -> testkit::Result { let server = HttpRecorder::start("ok").await?; - let sandbox = profile_endpoint_sandbox( - cx, - "rwrt", - &format!( - "{{host: {TEST_HOST}, port: {}, path: /probe, protocol: rest, access: full, \ - enforcement: enforce, request_body_credential_rewrite: true}}", - server.port - ), - ) + let sandbox = profile_endpoint_sandbox(cx, "rwrt", server.port, |ep| { + ep.rest(Access::Full) + .path("/probe") + .enforce() + .request_body_credential_rewrite(true); + }) .await?; let token = provider_token(&sandbox).await?; let body = json!({ "credential": token }).to_string(); @@ -245,15 +244,10 @@ async fn profile_rest_endpoint_rewrites_header_and_body(cx: &mut Context) -> tes #[testkit::test] async fn profile_websocket_endpoint_rewrites_text_frames(cx: &mut Context) -> testkit::Result { let server = WebSocketRecorder::start().await?; - let sandbox = profile_endpoint_sandbox( - cx, - "wstxt", - &format!( - "{{host: {TEST_HOST}, port: {}, path: /ws, protocol: websocket, \ - enforcement: enforce, access: read-write, websocket_credential_rewrite: true}}", - server.port - ), - ) + let sandbox = profile_endpoint_sandbox(cx, "wstxt", server.port, |ep| { + ep.websocket(Access::ReadWrite).path("/ws").enforce(); + ep.websocket_credential_rewrite = true; + }) .await?; sandbox .run_python( @@ -380,31 +374,30 @@ async fn send_binary_frame( /// `endpoints`, its profile declares the REST and WebSocket ports as its /// endpoints; without, a policy must bind the provider explicitly. async fn install_gating_provider(cx: &Context, endpoints: Option<(u16, u16)>) -> Result { - let endpoints = endpoints.map_or_else(Vec::new, |(rest, websocket)| { - vec![ - format!("{{host: {TEST_HOST}, port: {rest}, protocol: rest, access: full}}"), - format!( - "{{host: {TEST_HOST}, port: {websocket}, protocol: websocket, access: read-write}}" - ), - ] - }); - install_provider_with_endpoints(cx, &endpoints).await + let mut profile = gating_profile(&cx.name("cg")); + if let Some((rest, websocket)) = endpoints { + profile = profile + .endpoint(TEST_HOST, rest, |ep| { + ep.rest(Access::Full); + }) + .endpoint(TEST_HOST, websocket, |ep| { + ep.websocket(Access::ReadWrite); + }); + } + install_gating_profile(cx, &profile).await } -/// A long-running sandbox with a provider from -/// [`install_provider_with_endpoints`] whose profile declares `endpoint`, a -/// YAML flow mapping, and a policy that allows the same endpoint. -async fn profile_endpoint_sandbox(cx: &Context, suffix: &str, endpoint: &str) -> Result { - let provider = install_provider_with_endpoints(cx, &[endpoint.to_string()]).await?; - let policy = policy::base_with(&format!( - "network_policies: - credential_gating: - name: credential_gating - endpoints: [{endpoint}] - binaries: {binaries} -", - binaries = policy::binaries_yaml(PYTHON_BINARIES), - ))?; +/// A long-running sandbox with the same endpoint in its provider profile and policy. +async fn profile_endpoint_sandbox( + cx: &Context, + suffix: &str, + port: u16, + configure: impl Fn(&mut proto::NetworkEndpoint), +) -> Result { + let profile = gating_profile(&cx.name("cg")).endpoint(TEST_HOST, port, &configure); + let provider = install_gating_profile(cx, &profile).await?; + let mut policy = policy::base(); + configure(allow_host(&mut policy, "credential_gating", port)); create_sandbox(cx, suffix, policy, &[&provider]).await } @@ -419,55 +412,42 @@ async fn install_bound_provider( port: u16, ) -> Result { let name = cx.name(suffix); - let profile = format!( - "id: {name} -display_name: E2E static endpoint binding -category: other -credentials: - - name: bound_token - env_vars: [{env_var}] - required: true - auth_style: bearer - header_name: authorization -endpoints: - - {{host: {TEST_HOST}, port: {port}, path: /allowed/**, protocol: rest, access: full, enforcement: enforce}} -binaries: [{BASH}] -" - ); + let profile = Profile::new(&name) + .display_name("E2E static endpoint binding") + .credential(bearer_credential("bound_token", env_var)) + .endpoint(TEST_HOST, port, |ep| { + ep.rest(Access::Full).path("/allowed/**").enforce(); + }) + .binaries([BASH]) + .to_yaml()?; cx.install_provider(&name, &profile, &[(env_var, secret)]) .await?; Ok(name) } -/// Install a run-unique provider holding `TEST_SECRET` in `TOKEN_ENV`, whose -/// profile declares `endpoints`, each a YAML flow mapping. -async fn install_provider_with_endpoints(cx: &Context, endpoints: &[String]) -> Result { - let name = cx.name("cg"); - let endpoints = if endpoints.is_empty() { - String::new() - } else { - format!("endpoints: [{}]\n", endpoints.join(", ")) - }; - let binaries: String = PYTHON_BINARIES - .iter() - .map(|path| format!(" - path: {path}\n")) - .collect(); - let profile = format!( - "id: {name} -display_name: E2E Credential Gating -category: other -credentials: - - name: token - env_vars: [{TOKEN_ENV}] - required: true - auth_style: bearer - header_name: authorization -{endpoints}binaries: -{binaries}" - ); - cx.install_provider(&name, &profile, &[(TOKEN_ENV, TEST_SECRET)]) - .await?; - Ok(name) +fn bearer_credential(name: &str, env_var: &str) -> Credential { + Credential::new(name) + .env_var(env_var) + .required() + .auth_style("bearer") + .header_name("authorization") +} + +fn gating_profile(name: &str) -> Profile { + Profile::new(name) + .display_name("E2E Credential Gating") + .credential(bearer_credential("token", TOKEN_ENV)) + .binaries(PYTHON_BINARIES.iter().copied()) +} + +async fn install_gating_profile(cx: &Context, profile: &Profile) -> Result { + cx.install_provider( + profile.id(), + &profile.to_yaml()?, + &[(TOKEN_ENV, TEST_SECRET)], + ) + .await?; + Ok(profile.id().to_string()) } fn sandbox_with( diff --git a/tests/suites/continuity/Cargo.lock b/tests/suites/continuity/Cargo.lock index d73a9e10e7..debee2c0d9 100644 --- a/tests/suites/continuity/Cargo.lock +++ b/tests/suites/continuity/Cargo.lock @@ -2356,6 +2356,21 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "openshell-providers" +version = "0.0.0" +dependencies = [ + "glob", + "noyalib", + "openshell-core", + "openshell-policy", + "prost-types", + "serde", + "serde_json", + "thiserror 2.0.20", + "url", +] + [[package]] name = "openshell-sdk" version = "0.0.0" @@ -2405,6 +2420,7 @@ dependencies = [ "openshell-bootstrap", "openshell-core", "openshell-policy", + "openshell-providers", "openshell-sdk", "openshell-testkit-macros", "prost-types", diff --git a/tests/suites/drivers/podman/Cargo.lock b/tests/suites/drivers/podman/Cargo.lock index b56975e757..7619e2adf4 100644 --- a/tests/suites/drivers/podman/Cargo.lock +++ b/tests/suites/drivers/podman/Cargo.lock @@ -2357,6 +2357,21 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "openshell-providers" +version = "0.0.0" +dependencies = [ + "glob", + "noyalib", + "openshell-core", + "openshell-policy", + "prost-types", + "serde", + "serde_json", + "thiserror 2.0.20", + "url", +] + [[package]] name = "openshell-sdk" version = "0.0.0" @@ -2406,6 +2421,7 @@ dependencies = [ "openshell-bootstrap", "openshell-core", "openshell-policy", + "openshell-providers", "openshell-sdk", "openshell-testkit-macros", "prost-types", diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index ba47285c9a..168105f654 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -1317,9 +1317,13 @@ dependencies = [ name = "host-server-support" version = "0.0.0" dependencies = [ + "openshell-crypto", "openshell-testkit", + "rcgen", + "rustls", "serde_json", "tokio", + "tokio-rustls", "tungstenite", ] @@ -1834,7 +1838,7 @@ version = "0.0.0" dependencies = [ "keycloak-support", "openshell-testkit", - "tempfile", + "prost-types", ] [[package]] @@ -2430,6 +2434,21 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "openshell-providers" +version = "0.0.0" +dependencies = [ + "glob", + "noyalib", + "openshell-core", + "openshell-policy", + "prost-types", + "serde", + "serde_json", + "thiserror 2.0.20", + "url", +] + [[package]] name = "openshell-sdk" version = "0.0.0" @@ -2491,6 +2510,7 @@ dependencies = [ "openshell-bootstrap", "openshell-core", "openshell-policy", + "openshell-providers", "openshell-sdk", "openshell-testkit-macros", "prost-types", diff --git a/tests/suites/features/keycloak-provider-refresh/Cargo.toml b/tests/suites/features/keycloak-provider-refresh/Cargo.toml index 4442429c0a..4709dab450 100644 --- a/tests/suites/features/keycloak-provider-refresh/Cargo.toml +++ b/tests/suites/features/keycloak-provider-refresh/Cargo.toml @@ -19,4 +19,4 @@ harness = false [dependencies] keycloak-support = { path = "../../../support/keycloak" } openshell-testkit = { path = "../../../testkit/testkit" } -tempfile = "3" +prost-types = "0.14" diff --git a/tests/suites/features/keycloak-provider-refresh/tests/provider_refresh.rs b/tests/suites/features/keycloak-provider-refresh/tests/provider_refresh.rs index c8dbd60c29..0c1734b56a 100644 --- a/tests/suites/features/keycloak-provider-refresh/tests/provider_refresh.rs +++ b/tests/suites/features/keycloak-provider-refresh/tests/provider_refresh.rs @@ -6,10 +6,10 @@ //! Keycloak is only the provider's token issuer here; the CLI still reaches //! the gateway the usual way. -use std::io::Write as _; - use keycloak_support::KeycloakContext; -use testkit::{CliOutput, Context, ResultExt as _}; +use testkit::policy::{Access, Endpoint as _}; +use testkit::sdk::raw::proto; +use testkit::{CliOutput, Context, Credential, Profile}; fn main() -> std::process::ExitCode { testkit::main() @@ -24,34 +24,14 @@ const CREDENTIAL_KEY: &str = "KEYCLOAK_ACCESS_TOKEN"; async fn revoked_refresh_grant_requires_user_reauthorization(cx: &mut Context) -> testkit::Result { let kc = KeycloakContext::new(cx).await?; let provider = kc.name("kc-refresh"); - let profile_id = kc.name("kc-refresh-profile"); let grant = kc.keycloak().password_grant().await?; - let profile = write_profile(&profile_id, kc.keycloak())?; - let profile_path = profile.path().to_string_lossy().into_owned(); - - // Register each delete before its create, so cleanup also covers a create - // the gateway applied but the CLI reported as failed. Both deletes succeed - // when there is nothing to delete. - delete_on_cleanup(&kc, "profile", &profile_id); - kc.cli(["profile", "import", "--file", &profile_path]) - .await? - .success()?; - delete_on_cleanup(&kc, "provider", &provider); - kc.cli_with_env( + let profile = refresh_profile(&kc.name("kc-refresh-profile"), kc.keycloak()).to_yaml()?; + kc.install_provider( + &provider, + &profile, &[(CREDENTIAL_KEY, &grant.access_token)], - [ - "provider", - "create", - "--name", - &provider, - "--type", - &profile_id, - "--credential", - CREDENTIAL_KEY, - ], ) - .await? - .success()?; + .await?; let client_id = format!("client_id={}", kc.keycloak().client_id()); kc.cli_with_env( &[("KEYCLOAK_REFRESH_TOKEN", &grant.refresh_token)], @@ -121,64 +101,43 @@ async fn revoked_refresh_grant_requires_user_reauthorization(cx: &mut Context) - Ok(()) } -/// Delete the `kind` named `name` when the test ends, since testkit only -/// cleans up sandboxes by itself. -fn delete_on_cleanup(cx: &Context, kind: &'static str, name: &str) { - let cli = cx.cli_handle(); - let name = name.to_string(); - cx.on_cleanup(format!("delete {kind} {name}"), async move || { - cli.run([kind, "delete", &name]).await?.success()?; - Ok(()) - }); -} - fn combined(output: &CliOutput) -> String { format!("{}{}", output.stdout, output.stderr) } -fn write_profile( - profile_id: &str, - keycloak: &keycloak_support::Keycloak, -) -> testkit::Result { - let issuer_token_url = keycloak.token_endpoint(); - let profile = format!( - r#"id: {profile_id} -display_name: Keycloak provider refresh test -category: other -credentials: - - name: access_token - env_vars: [{CREDENTIAL_KEY}] - required: true - auth_style: bearer - header_name: authorization - refresh: - strategy: oauth2_refresh_token - token_url: {issuer_token_url} - scopes: [openid] - refresh_before_seconds: 60 - max_lifetime_seconds: 3600 - material: - - name: client_id - required: true - - name: refresh_token - required: true - secret: true -endpoints: - - host: keycloak.test.invalid - port: 443 - protocol: rest - access: read-only - enforcement: enforce -binaries: - - /usr/bin/curl -"# - ); - let mut file = tempfile::Builder::new() - .suffix(".yaml") - .tempfile() - .context("create provider profile")?; - file.write_all(profile.as_bytes()) - .and_then(|()| file.flush()) - .context("write provider profile")?; - Ok(file) +/// A profile whose `access_token` the gateway refreshes from `keycloak` +/// with the OAuth refresh-token grant. +fn refresh_profile(id: &str, keycloak: &keycloak_support::Keycloak) -> Profile { + let material = |name: &str, secret: bool| proto::ProviderCredentialRefreshMaterial { + name: name.to_string(), + required: true, + secret, + ..proto::ProviderCredentialRefreshMaterial::default() + }; + let seconds = |seconds| Some(prost_types::Duration { seconds, nanos: 0 }); + Profile::new(id) + .display_name("Keycloak provider refresh test") + .credential( + Credential::new("access_token") + .env_var(CREDENTIAL_KEY) + .required() + .auth_style("bearer") + .header_name("authorization") + .refresh(proto::ProviderCredentialRefresh { + strategy: proto::ProviderCredentialRefreshStrategy::Oauth2RefreshToken as i32, + token_url: keycloak.token_endpoint(), + scopes: vec!["openid".to_string()], + refresh_before: seconds(60), + max_lifetime: seconds(3600), + material: vec![ + material("client_id", false), + material("refresh_token", true), + ], + ..proto::ProviderCredentialRefresh::default() + }), + ) + .endpoint("keycloak.test.invalid", 443, |ep| { + ep.rest(Access::ReadOnly).enforce(); + }) + .binaries(["/usr/bin/curl"]) } diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 8ba9df07e9..aed9e521a4 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -1281,9 +1281,14 @@ dependencies = [ name = "host-server-support" version = "0.0.0" dependencies = [ + "openshell-crypto", "openshell-testkit", + "rcgen", + "rustls", "serde_json", + "tempfile", "tokio", + "tokio-rustls", "tungstenite", ] @@ -2376,6 +2381,21 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "openshell-providers" +version = "0.0.0" +dependencies = [ + "glob", + "noyalib", + "openshell-core", + "openshell-policy", + "prost-types", + "serde", + "serde_json", + "thiserror 2.0.20", + "url", +] + [[package]] name = "openshell-sdk" version = "0.0.0" @@ -2425,6 +2445,7 @@ dependencies = [ "openshell-bootstrap", "openshell-core", "openshell-policy", + "openshell-providers", "openshell-sdk", "openshell-testkit-macros", "prost-types", diff --git a/tests/support/README.md b/tests/support/README.md new file mode 100644 index 0000000000..7b7b0a775a --- /dev/null +++ b/tests/support/README.md @@ -0,0 +1,48 @@ +# Test support crates + +Each crate here is a fixture for one concern, such as a service the +environment runs, and any suite can depend on it by path. See +[Adding a feature suite](../../TESTING.md#adding-a-feature-suite) for how an +environment and a fixture share a contract. + +## Environment contract + +These are the variables that an environment, the test runner or CI sets for +tests to read. A tmachine environment publishes its variables with +`tests/tmachine/ansible/playbooks/test-env.yaml`, and `openshell-test-runner` +passes them to the tests. To run a suite against your own deployment, set them +yourself. A fixture fails the test when a variable it needs is missing; it +never skips it. Add a row when you add a variable. The runner also sets +`OPENSHELL_GATEWAY` and `OPENSHELL_BIN`, which testkit reads; see +[Running against a gateway](../testkit/README.md#running-against-a-gateway). + +| Variable | Set by | Read by | Meaning | +|---|---|---|---| +| `OPENSHELL_TEST_CONTAINER_ENGINE` | Every Docker and Podman base environment (`playbooks/docker.yaml`, `podman-rootful.yaml`, `podman-rootless.yaml`); `e2e:oci-image` tasks | `container-engine-support` | The command that reaches the gateway's container engine, split on whitespace, such as `docker` or `sudo -n podman`. | +| `OPENSHELL_TEST_PODMAN_USERNS` | `-userns-` (`playbooks/drivers/podman/userns.yaml`) | `podman-support` | The gateway's Podman user-namespace mode: `default`, `auto`, `keep-id` or `private`. | +| `OPENSHELL_TEST_CDI_SCENARIOS` | `-cdi` (`playbooks/cdi.yaml`) | `tests/suites/features/cdi` | The path of the document that names the CDI device kind, each scenario and the checks it expects. | +| `OPENSHELL_TEST_KEYCLOAK_ISSUER` | `-keycloak` (`playbooks/keycloak.yaml`) | `keycloak-support` | The OIDC issuer URL of the test realm, reachable from the test process. | +| `OPENSHELL_TEST_KEYCLOAK_CLIENT_ID` | `-keycloak` | `keycloak-support` | A client in that realm that allows password grants. | +| `OPENSHELL_TEST_KEYCLOAK_USERNAME` | `-keycloak` | `keycloak-support` | The realm user that tests sign in as. | +| `OPENSHELL_TEST_KEYCLOAK_PASSWORD` | `-keycloak` | `keycloak-support` | That user's password. | +| `OPENSHELL_TEST_ADDITIONAL_CA_CERT` | The additional-CA environment, which sets `openshell.supervisor.network.additional_ca_bundle` (added by #5729) | `host-server-support` (`TestCa::from_env`) | The path of the CA certificate, in PEM, that the supervisor trusts for sandbox egress. | +| `OPENSHELL_TEST_ADDITIONAL_CA_KEY` | The additional-CA environment | `host-server-support` (`TestCa::from_env`) | The path of that CA's private key, in PEM, readable by the test user. Tests sign server certificates with it. | +| `OPENSHELL_TEST_BASE_IMAGE` | Optional; you, for example to use a mirror | `testkit::base_image()` | The default sandbox image. Unset, it is `nvcr.io/nvidia/base/ubuntu:24.04`. | +| `OPENSHELL_TEST_PYTHON_IMAGE` | Optional; `e2e/rust/e2e-kubernetes.sh` and `e2e-vm.sh` set a pullable image | `testkit::python_image()` | The workload image for tests that run `python3`, curl, git or openssl. Unset, it is `openshell/e2e-python:dev`, which the tmachine installers load. | +| `OPENSHELL_TEST_UNSUPPORTED` | CI and `e2e/support/conformance.sh` derive it from `tests/suites/unsupported.yaml` with `tasks/scripts/suite-unsupported.sh` | testkit programs | Tests the environment can't pass yet, as `=` entries. See [Unsupported tests](../testkit/README.md#unsupported-tests). | +| `OPENSHELL_TEST_POSTGRES_URL` | `tasks/scripts/run-postgres-tests.sh` (`mise run test:rust:postgres`), or you | `openshell-server`'s PostgreSQL tests | A disposable PostgreSQL database. Never point it at one a gateway uses. | + +Other `OPENSHELL_TEST_*` names are internal test hooks and are left out on +purpose: unit-test child-process markers, the re-entry markers in +`tests/support/environment.rs`, Nix guest-cache settings, `install.sh` test +hooks and crate test settings. + +### Ports the environment chooses + +When a test must listen on a port the environment picked, because the gateway +or another service is configured to call it, the environment publishes it as +`OPENSHELL_TEST__PORT` and the test binds that port on every IPv4 +host address, for example with `HttpRecorder::builder().port(port)` from +`host-server-support`. The host servers don't listen on IPv6, so the +environment must point the caller at an IPv4 address of the test host. The +test never picks the port itself. Give each concurrent test a distinct port. diff --git a/tests/support/host-server/Cargo.toml b/tests/support/host-server/Cargo.toml index 920eed96ca..725e12242b 100644 --- a/tests/support/host-server/Cargo.toml +++ b/tests/support/host-server/Cargo.toml @@ -12,10 +12,15 @@ repository = "https://github.com/ai-openshell/openshell" publish = false [dependencies] +openshell-crypto = { path = "../../../crates/openshell-crypto" } openshell-testkit = { path = "../../testkit/testkit" } +rcgen = { version = "0.14.10", default-features = false, features = ["pem"] } +rustls = { version = "0.23", default-features = false, features = ["std", "tls12"] } serde_json = "1" tokio = { version = "1.43", features = ["io-util", "net", "rt", "time"] } +tokio-rustls = { version = "0.26", default-features = false, features = ["tls12"] } tungstenite = "0.26" [dev-dependencies] +tempfile = "3" tokio = { version = "1.43", features = ["macros", "rt"] } diff --git a/tests/support/host-server/src/http.rs b/tests/support/host-server/src/http.rs index 0845b0af5e..887d5690d4 100644 --- a/tests/support/host-server/src/http.rs +++ b/tests/support/host-server/src/http.rs @@ -6,9 +6,10 @@ use std::net::SocketAddr; use std::sync::{Arc, Mutex, PoisonError}; use testkit::{Poll, Result}; -use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; -use tokio::net::TcpStream; +use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _}; +use tokio_rustls::TlsAcceptor; +use crate::tls::Identity; use crate::{MAX_REQUEST, READ_TIMEOUT, Server, WAIT_INTERVAL, WAIT_TIMEOUT, find, header}; /// A request an [`HttpRecorder`] read. A chunked body arrives decoded. @@ -168,12 +169,61 @@ impl HttpRecorder { /// Answer every request with `handler`'s response. pub async fn serve( handler: impl Fn(&Request) -> Response + Send + Sync + 'static, + ) -> Result { + Self::builder().serve(handler).await + } + + /// A recorder on a chosen port or with TLS, such as on a port the + /// environment published: + /// + /// ```ignore + /// let upstream = HttpRecorder::builder().port(port).tls(&identity).start("ok").await?; + /// ``` + pub fn builder() -> HttpRecorderBuilder { + HttpRecorderBuilder::default() + } + + /// Answer every request over TLS with `200` and `body`, presenting + /// `identity`'s certificate. + pub async fn start_tls(identity: &Identity, body: impl Into) -> Result { + Self::builder().tls(identity).start(body).await + } + + /// Answer every request over TLS with `handler`'s response, presenting + /// `identity`'s certificate. A connection that fails the TLS handshake + /// counts in [`connections`](Self::connections) but records no request. + pub async fn serve_tls( + identity: &Identity, + handler: impl Fn(&Request) -> Response + Send + Sync + 'static, + ) -> Result { + Self::builder().tls(identity).serve(handler).await + } + + async fn listen( + port: u16, + tls: Option, + 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 server = Server::start(move |stream| { - respond(stream, Arc::clone(&handler), Arc::clone(&task_requests)) + let server = Server::start(port, move |stream| { + let _ = stream.set_nodelay(true); + let local_addr = stream.local_addr().ok(); + let handler = Arc::clone(&handler); + let requests = Arc::clone(&task_requests); + let tls = tls.clone(); + async move { + match tls { + None => respond(stream, local_addr, handler, requests).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; + } + } + } + } }) .await?; Ok(Self { @@ -218,12 +268,57 @@ impl HttpRecorder { } } +/// Options for an [`HttpRecorder`], from [`HttpRecorder::builder`]. +#[derive(Debug, Default)] +pub struct HttpRecorderBuilder { + port: u16, + tls: Option, +} + +impl HttpRecorderBuilder { + /// Listen on `port` instead of a random free one. Fails to start if + /// something already listens there. + #[must_use] + pub fn port(mut self, port: u16) -> Self { + self.port = port; + self + } + + /// Serve TLS, presenting `identity`'s certificate. A connection that + /// fails the TLS handshake counts in + /// [`connections`](HttpRecorder::connections) but records no request. + #[must_use] + pub fn tls(mut self, identity: &Identity) -> Self { + self.tls = Some(identity.clone()); + self + } + + /// Answer every request with `200` and `body`. + pub async fn start(self, body: impl Into) -> Result { + let body = body.into(); + self.serve(move |_| Response::text(body.clone())).await + } + + /// Answer every request with `handler`'s response. + pub async fn serve( + self, + 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 + } +} + /// Read requests, record each, and answer with `handler` until a response /// or request closes the connection. -async fn respond(mut stream: TcpStream, handler: Arc, requests: Arc>>) { - let _ = stream.set_nodelay(true); +async fn respond( + mut stream: impl AsyncRead + AsyncWrite + Unpin, + local_addr: Option, + handler: Arc, + requests: Arc>>, +) { let mut buffer = Vec::new(); - while let Some(request) = read_request(&mut stream, &mut buffer).await { + while let Some(request) = read_request(&mut stream, local_addr, &mut buffer).await { let response = handler(&request); let close = !response.keep_alive || request @@ -241,13 +336,18 @@ async fn respond(mut stream: TcpStream, handler: Arc, requests: Arc) -> Option { +/// `buffer`, and leave any bytes after it in `buffer`. `local_addr` is the +/// address the connection arrived on. +pub(crate) async fn read_request( + stream: &mut (impl AsyncRead + Unpin), + 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); - request.local_addr = stream.local_addr().ok(); + request.local_addr = local_addr; return Some(request); } match tokio::time::timeout(READ_TIMEOUT, stream.read(&mut chunk)).await { @@ -318,6 +418,8 @@ fn decode_chunked(bytes: &[u8]) -> Option<(Vec, usize)> { #[cfg(test)] mod tests { + use tokio::net::TcpStream; + use super::*; async fn connect(port: u16) -> TcpStream { @@ -377,6 +479,34 @@ mod tests { ); } + #[tokio::test] + async fn http_recorder_listens_on_a_chosen_port() { + let port = crate::free_port().await.unwrap(); + let recorder = HttpRecorder::builder() + .port(port) + .start("fixed") + .await + .unwrap(); + assert_eq!(recorder.port, port); + let mut stream = connect(port).await; + stream + .write_all(b"GET / HTTP/1.1\r\nHost: test\r\n\r\n") + .await + .unwrap(); + assert!(read_to_end(&mut stream).await.ends_with("fixed")); + + let error = HttpRecorder::builder() + .port(port) + .start("taken") + .await + .err() + .unwrap(); + assert!( + error.to_string().contains(&format!("port {port}")), + "{error}" + ); + } + #[tokio::test] async fn http_recorder_keeps_a_connection_alive_until_the_request_closes_it() { let recorder = diff --git a/tests/support/host-server/src/lib.rs b/tests/support/host-server/src/lib.rs index a481c1d5f3..c4cb350428 100644 --- a/tests/support/host-server/src/lib.rs +++ b/tests/support/host-server/src/lib.rs @@ -5,13 +5,17 @@ //! `host.openshell.internal`, and that record what arrived, so a test can //! check what the supervisor forwarded upstream. //! -//! The servers listen on every host address, since drivers map +//! The servers listen on every IPv4 host address, since drivers map //! `host.openshell.internal` to different ones, and stop when dropped. They -//! run where the tests run, so a gateway whose sandboxes can't reach the test -//! host, such as one on a remote cluster, can't run tests that use them. +//! don't listen on IPv6, so `host.openshell.internal` must resolve to an IPv4 +//! address of the test host. They run where the tests run, so a gateway whose +//! sandboxes can't reach the test host, such as one on a remote cluster, can't +//! run tests that use them. //! //! - [`HttpRecorder`] answers HTTP requests with a fixed body or a handler's -//! [`Response`], and records each parsed [`Request`]. +//! [`Response`], and records each parsed [`Request`]. It serves HTTPS with +//! a certificate from a [`TestCa`], and listens on a random free port unless +//! [`HttpRecorder::builder`] names one. //! - [`WebSocketRecorder`] completes the WebSocket handshake and records the //! frames that arrive. //! - [`TcpServer`] records raw bytes, and echoes them or answers once the @@ -21,6 +25,7 @@ mod http; mod tcp; +mod tls; mod websocket; use std::sync::Arc; @@ -32,8 +37,9 @@ use testkit::{PYTHON_BINARIES, Result, ResultExt as _, policy}; use tokio::net::{TcpListener, TcpStream}; use tokio::task::JoinHandle; -pub use http::{HttpRecorder, Request, Response}; +pub use http::{HttpRecorder, HttpRecorderBuilder, Request, Response}; pub use tcp::{TcpServer, exchange}; +pub use tls::{ADDITIONAL_CA_CERT_ENV, ADDITIONAL_CA_KEY_ENV, Identity, TestCa}; pub use websocket::{TEXT_REPLY, WebSocketRecorder}; /// The name a sandbox reaches these servers by. @@ -54,10 +60,15 @@ const WAIT_INTERVAL: Duration = Duration::from_millis(100); const READ_TIMEOUT: Duration = Duration::from_secs(10); const MAX_REQUEST: usize = 1024 * 1024; -async fn bind() -> Result<(TcpListener, u16)> { - let listener = TcpListener::bind(("0.0.0.0", 0)) +/// Listen on every IPv4 host address at `port`, or at a random free port for 0. +async fn bind(port: u16) -> Result<(TcpListener, u16)> { + let listener = TcpListener::bind(("0.0.0.0", port)) .await - .context("bind a host server")?; + .context(if port == 0 { + "bind a host server".to_string() + } else { + format!("bind a host server on port {port}") + })?; let port = listener .local_addr() .context("read the host server's address")? @@ -74,12 +85,12 @@ struct Server { } impl Server { - async fn start(serve: F) -> Result + async fn start(port: u16, serve: F) -> Result where F: Fn(TcpStream) -> Fut + Send + 'static, Fut: Future + Send + 'static, { - let (listener, port) = bind().await?; + let (listener, port) = bind(port).await?; let connections = Arc::new(AtomicUsize::new(0)); let task_connections = Arc::clone(&connections); let task = tokio::spawn(async move { @@ -108,7 +119,7 @@ impl Drop for Server { /// A port that nothing on the test host listened on when this returned. pub async fn free_port() -> Result { - let (_listener, port) = bind().await?; + let (_listener, port) = bind(0).await?; Ok(port) } diff --git a/tests/support/host-server/src/tcp.rs b/tests/support/host-server/src/tcp.rs index 14292306eb..ef45a30680 100644 --- a/tests/support/host-server/src/tcp.rs +++ b/tests/support/host-server/src/tcp.rs @@ -44,9 +44,10 @@ impl TcpServer { async fn start(mode: Mode) -> Result { let received = Arc::new(Mutex::new(Vec::new())); let task_received = Arc::clone(&received); - let server = - Server::start(move |stream| serve(stream, mode.clone(), Arc::clone(&task_received))) - .await?; + let server = Server::start(0, move |stream| { + serve(stream, mode.clone(), Arc::clone(&task_received)) + }) + .await?; Ok(Self { port: server.port, received, diff --git a/tests/support/host-server/src/tls.rs b/tests/support/host-server/src/tls.rs new file mode 100644 index 0000000000..71df5e7c8b --- /dev/null +++ b/tests/support/host-server/src/tls.rs @@ -0,0 +1,349 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Certificate authorities for TLS host servers. +//! +//! A test signs a server certificate with a [`TestCa`] and serves it with +//! [`HttpRecorder::serve_tls`](crate::HttpRecorder::serve_tls): +//! +//! - [`TestCa::new`] makes a CA that only the test knows, so nothing trusts it +//! unless the test hands over [`TestCa::cert_pem`]. +//! - [`TestCa::from_env`] loads the environment's additional CA, which the +//! supervisor trusts for sandbox egress +//! (`openshell.supervisor.network.additional_ca_bundle`). The environment +//! publishes the paths of its PEM certificate and key in +//! `OPENSHELL_TEST_ADDITIONAL_CA_CERT` and `OPENSHELL_TEST_ADDITIONAL_CA_KEY`. + +use std::path::Path; +use std::sync::Arc; + +use openshell_crypto::pki::{self, KeyPair}; +use rcgen::{ + BasicConstraints, CertificateParams, DnType, ExtendedKeyUsagePurpose, IsCa, Issuer, + KeyUsagePurpose, +}; +use rustls::pki_types::pem::PemObject as _; +use rustls::pki_types::{CertificateDer, PrivateKeyDer}; +use testkit::{Error, Result}; +use tokio_rustls::TlsAcceptor; + +/// The path of the environment's additional CA certificate, in PEM. +pub const ADDITIONAL_CA_CERT_ENV: &str = "OPENSHELL_TEST_ADDITIONAL_CA_CERT"; +/// The path of the environment's additional CA private key, in PEM. +pub const ADDITIONAL_CA_KEY_ENV: &str = "OPENSHELL_TEST_ADDITIONAL_CA_KEY"; + +/// A certificate authority that signs server certificates for host servers. +pub struct TestCa { + cert_pem: String, + issuer: Issuer<'static, KeyPair>, +} + +impl TestCa { + /// A new CA that only this test knows. + pub fn new() -> Result { + let key = pki::generate_keypair().map_err(failed("generate a test CA key"))?; + let cert = pki::self_signed(ca_params(), &key).map_err(failed("sign the test CA"))?; + Ok(Self { + cert_pem: cert.pem(), + issuer: cert.into_issuer(key), + }) + } + + /// The environment's additional CA, from the files that + /// `OPENSHELL_TEST_ADDITIONAL_CA_CERT` and `OPENSHELL_TEST_ADDITIONAL_CA_KEY` + /// name. Fails if either is unset. + pub fn from_env() -> Result { + Self::from_vars(|name| std::env::var(name).ok()) + } + + fn from_vars(var: impl Fn(&str) -> Option) -> Result { + let path = |name: &str| { + var(name) + .filter(|value| !value.trim().is_empty()) + .ok_or_else(|| { + Error::msg(format!( + "{name} is not set; run this test in an environment with an additional CA" + )) + }) + }; + let cert = path(ADDITIONAL_CA_CERT_ENV)?; + let key = path(ADDITIONAL_CA_KEY_ENV)?; + Self::from_files(cert.as_ref(), key.as_ref()) + } + + /// A CA from its PEM certificate and private key files. + pub fn from_files(cert: &Path, key: &Path) -> Result { + let read = |path: &Path| { + std::fs::read_to_string(path) + .map_err(|error| Error::msg(format!("read {}: {error}", path.display()))) + }; + let cert_pem = read(cert)?; + let key_pem = read(key)?; + let der = CertificateDer::from_pem_slice(cert_pem.as_bytes()).map_err(failed(format!( + "parse the CA certificate {}", + cert.display() + )))?; + let key_pair = KeyPair::from_pem(&key_pem) + .map_err(failed(format!("parse the CA key {}", key.display())))?; + // issuer_from_der reads the certificate's metadata only, so check the + // key here rather than at the first client handshake. + let key_der = key_pair + .serialize_der() + .map_err(failed(format!("export the CA key {}", key.display())))?; + openshell_crypto::tls::try_server_builder() + .map_err(failed("build a TLS server configuration"))? + .with_no_client_auth() + .with_single_cert(vec![der.clone()], PrivateKeyDer::Pkcs8(key_der.into())) + .map_err(failed(format!( + "load the CA key {} with the CA certificate {}", + key.display(), + cert.display() + )))?; + let issuer = pki::issuer_from_der(&der, key_pair) + .map_err(failed(format!("load the CA {}", cert.display())))?; + Ok(Self { cert_pem, issuer }) + } + + /// The CA certificate, in PEM, for a client that should trust it. + pub fn cert_pem(&self) -> &str { + &self.cert_pem + } + + /// A server certificate for `names`, signed by this CA. A name that parses + /// as an IP address becomes an IP address entry. + pub fn leaf(&self, names: &[&str]) -> Result { + let names: Vec = names.iter().map(ToString::to_string).collect(); + let first = names + .first() + .cloned() + .ok_or_else(|| Error::msg("a server certificate needs at least one name"))?; + let mut params = CertificateParams::new(names.clone()) + .map_err(failed(format!("server certificate names {names:?}")))?; + params.distinguished_name.push(DnType::CommonName, first); + params.key_usages = vec![KeyUsagePurpose::DigitalSignature]; + params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; + // Strict verifiers, such as Python 3.13 and later, require it. + params.use_authority_key_identifier_extension = true; + let key = pki::generate_keypair().map_err(failed("generate a server key"))?; + let cert = pki::signed_by_issuer(params, &key, &self.issuer) + .map_err(failed(format!("sign a server certificate for {names:?}")))?; + let key_der = key + .serialize_der() + .map_err(failed("export the server key"))?; + let key_pem = key + .serialize_pem() + .map_err(failed("export the server key"))?; + Ok(Identity { + cert_pem: cert.pem(), + key_pem, + cert_der: cert.der().clone(), + key_der, + }) + } +} + +/// A server certificate and its private key. +#[derive(Clone)] +pub struct Identity { + pub cert_pem: String, + pub key_pem: String, + cert_der: CertificateDer<'static>, + key_der: Vec, +} + +impl Identity { + pub(crate) fn acceptor(&self) -> Result { + let key = PrivateKeyDer::Pkcs8(self.key_der.clone().into()); + let mut config = openshell_crypto::tls::try_server_builder() + .map_err(failed("build a TLS server configuration"))? + .with_no_client_auth() + .with_single_cert(vec![self.cert_der.clone()], key) + .map_err(failed("load the server certificate"))?; + config.alpn_protocols = vec![b"http/1.1".to_vec()]; + Ok(TlsAcceptor::from(Arc::new(config))) + } +} + +impl std::fmt::Debug for Identity { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Identity") + .field("cert_pem", &self.cert_pem) + .finish_non_exhaustive() + } +} + +fn ca_params() -> CertificateParams { + let mut params = CertificateParams::default(); + params + .distinguished_name + .push(DnType::CommonName, "OpenShell test CA"); + params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + params.key_usages = vec![ + KeyUsagePurpose::KeyCertSign, + KeyUsagePurpose::CrlSign, + KeyUsagePurpose::DigitalSignature, + ]; + params +} + +fn failed(context: impl std::fmt::Display) -> impl FnOnce(E) -> Error { + move |error| Error::msg(format!("{context}: {error}")) +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + + use rustls::pki_types::ServerName; + use tempfile::TempDir; + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + use tokio::net::TcpStream; + use tokio_rustls::TlsConnector; + use tokio_rustls::client::TlsStream; + + use super::*; + use crate::{HttpRecorder, Response}; + + /// Open a TLS connection to `port` on loopback as `name`, trusting `ca`. + async fn connect(ca: &str, name: &str, port: u16) -> std::io::Result> { + let mut roots = rustls::RootCertStore::empty(); + roots + .add(CertificateDer::from_pem_slice(ca.as_bytes()).unwrap()) + .unwrap(); + let config = openshell_crypto::tls::try_client_builder() + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + #[allow( + clippy::disallowed_methods, + reason = "standalone test support has no openshell-core dependency and enables TCP_NODELAY below" + )] + let stream = TcpStream::connect(("127.0.0.1", port)).await?; + stream.set_nodelay(true)?; + TlsConnector::from(Arc::new(config)) + .connect(ServerName::try_from(name.to_string()).unwrap(), stream) + .await + } + + async fn get(stream: &mut TlsStream, path: &str) -> String { + stream + .write_all(format!("GET {path} HTTP/1.1\r\nHost: test\r\n\r\n").as_bytes()) + .await + .unwrap(); + let mut response = Vec::new(); + stream.read_to_end(&mut response).await.unwrap(); + String::from_utf8_lossy(&response).into_owned() + } + + fn write_ca(dir: &TempDir) -> (PathBuf, PathBuf, String) { + let key = pki::generate_keypair().unwrap(); + let cert = pki::self_signed(ca_params(), &key).unwrap(); + let (cert_path, key_path) = (dir.path().join("ca.pem"), dir.path().join("ca-key.pem")); + std::fs::write(&cert_path, cert.pem()).unwrap(); + std::fs::write(&key_path, key.serialize_pem().unwrap()).unwrap(); + (cert_path, key_path, cert.pem()) + } + + #[tokio::test] + async fn serve_tls_answers_a_client_that_trusts_the_ca() { + let ca = TestCa::new().unwrap(); + let identity = ca.leaf(&["localhost", "127.0.0.1"]).unwrap(); + let recorder = HttpRecorder::serve_tls(&identity, |request| { + Response::text(format!("tls {}", request.path())) + }) + .await + .unwrap(); + for name in ["localhost", "127.0.0.1"] { + let mut stream = connect(ca.cert_pem(), name, recorder.port).await.unwrap(); + let response = get(&mut stream, "/hello").await; + assert!(response.starts_with("HTTP/1.1 200 OK"), "{response}"); + assert!(response.ends_with("tls /hello"), "{response}"); + } + let requests = recorder.wait_for_requests(2).await.unwrap(); + assert_eq!(requests[0].path(), "/hello"); + } + + #[tokio::test] + async fn serve_tls_is_rejected_for_another_name_or_ca() { + let ca = TestCa::new().unwrap(); + let recorder = HttpRecorder::start_tls(&ca.leaf(&["localhost"]).unwrap(), "ok") + .await + .unwrap(); + let wrong_name = connect(ca.cert_pem(), "other.test", recorder.port).await; + assert!( + wrong_name.is_err(), + "a certificate for another name was accepted" + ); + let other = TestCa::new().unwrap(); + let wrong_ca = connect(other.cert_pem(), "localhost", recorder.port).await; + assert!( + wrong_ca.is_err(), + "a certificate from another CA was accepted" + ); + assert!(recorder.requests().is_empty()); + } + + #[tokio::test] + async fn from_vars_loads_the_environment_ca() { + let dir = TempDir::new().unwrap(); + let (cert, key, cert_pem) = write_ca(&dir); + let ca = TestCa::from_vars(|name| match name { + ADDITIONAL_CA_CERT_ENV => Some(cert.display().to_string()), + ADDITIONAL_CA_KEY_ENV => Some(key.display().to_string()), + _ => None, + }) + .unwrap(); + assert_eq!(ca.cert_pem(), cert_pem); + let recorder = HttpRecorder::start_tls(&ca.leaf(&["localhost"]).unwrap(), "env") + .await + .unwrap(); + let mut stream = connect(&cert_pem, "localhost", recorder.port) + .await + .unwrap(); + assert!(get(&mut stream, "/").await.ends_with("env")); + } + + #[test] + fn from_vars_fails_when_a_variable_is_missing() { + let error = TestCa::from_vars(|name| { + (name == ADDITIONAL_CA_CERT_ENV).then(|| "/nonexistent/ca.pem".to_string()) + }) + .err() + .unwrap(); + assert!(error.to_string().contains(ADDITIONAL_CA_KEY_ENV), "{error}"); + let error = TestCa::from_vars(|_| None).err().unwrap(); + assert!( + error.to_string().contains(ADDITIONAL_CA_CERT_ENV), + "{error}" + ); + } + + #[test] + fn from_files_rejects_a_key_from_another_ca() { + let (a, b) = (TempDir::new().unwrap(), TempDir::new().unwrap()); + let (cert, _, _) = write_ca(&a); + let (_, other_key, _) = write_ca(&b); + let error = TestCa::from_files(&cert, &other_key).err().unwrap(); + assert!( + error.to_string().contains("with the CA certificate"), + "{error}" + ); + } + + #[test] + fn leaf_names_its_issuer_key() { + const AUTHORITY_KEY_IDENTIFIER: &[u8] = &[0x06, 0x03, 0x55, 0x1d, 0x23]; + let leaf = TestCa::new().unwrap().leaf(&["localhost"]).unwrap(); + assert!( + leaf.cert_der + .windows(AUTHORITY_KEY_IDENTIFIER.len()) + .any(|window| window == AUTHORITY_KEY_IDENTIFIER), + "the server certificate has no authority key identifier" + ); + } + + #[test] + fn leaf_needs_a_name() { + assert!(TestCa::new().unwrap().leaf(&[]).is_err()); + } +} diff --git a/tests/support/host-server/src/websocket.rs b/tests/support/host-server/src/websocket.rs index fc3e83575f..74fedd7da7 100644 --- a/tests/support/host-server/src/websocket.rs +++ b/tests/support/host-server/src/websocket.rs @@ -35,8 +35,10 @@ impl WebSocketRecorder { pub async fn start() -> Result { let state = Arc::new(WebSocketState::default()); let task_state = Arc::clone(&state); - let server = - Server::start(move |stream| accept_websocket(stream, Arc::clone(&task_state))).await?; + let server = Server::start(0, move |stream| { + accept_websocket(stream, Arc::clone(&task_state)) + }) + .await?; Ok(Self { port: server.port, state, @@ -98,7 +100,8 @@ impl WebSocketRecorder { async fn accept_websocket(mut stream: TcpStream, state: Arc) { let _ = stream.set_nodelay(true); - let Some(request) = read_request(&mut stream, &mut Vec::new()).await else { + let local_addr = stream.local_addr().ok(); + let Some(request) = read_request(&mut stream, local_addr, &mut Vec::new()).await else { return; }; let Some(key) = header(&request.head, "sec-websocket-key") else { diff --git a/tests/testkit/Cargo.lock b/tests/testkit/Cargo.lock index 9874313ea9..6e033cc738 100644 --- a/tests/testkit/Cargo.lock +++ b/tests/testkit/Cargo.lock @@ -2348,6 +2348,21 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "openshell-providers" +version = "0.0.0" +dependencies = [ + "glob", + "noyalib", + "openshell-core", + "openshell-policy", + "prost-types", + "serde", + "serde_json", + "thiserror 2.0.20", + "url", +] + [[package]] name = "openshell-sdk" version = "0.0.0" @@ -2397,6 +2412,7 @@ dependencies = [ "openshell-bootstrap", "openshell-core", "openshell-policy", + "openshell-providers", "openshell-sdk", "openshell-testkit-macros", "prost-types", diff --git a/tests/testkit/README.md b/tests/testkit/README.md index 994cc93b46..def3f82421 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -135,7 +135,11 @@ fails. A killed test process skips cleanup, so names are unique to the run. - `cx.import_profile(profile)` to import a provider profile and return its `id`, and `cx.create_provider(name, type, credentials)` to create a provider, each with cleanup. `cx.install_provider(name, profile, - credentials)` does both. + credentials)` does both. Chain `.config(key, value)` before the `.await` + to set provider config. Build the profile with `testkit::Profile` and + `testkit::Credential`, whose setters are named after the profile YAML + fields; `policy::Endpoint` configures its endpoints. `profile.to_yaml()` + renders it for these calls. - `testkit::YamlFile` for YAML a CLI command reads from a file. - `cx.client()` for SDK calls testkit does not wrap. - In `tests/support`: `host-server` starts servers on the machine that runs diff --git a/tests/testkit/testkit/Cargo.toml b/tests/testkit/testkit/Cargo.toml index a761272e5a..4a1b32b045 100644 --- a/tests/testkit/testkit/Cargo.toml +++ b/tests/testkit/testkit/Cargo.toml @@ -18,6 +18,7 @@ name = "testkit" openshell-bootstrap = { path = "../../../crates/openshell-bootstrap" } openshell-core = { path = "../../../crates/openshell-core", default-features = false } openshell-policy = { path = "../../../crates/openshell-policy" } +openshell-providers = { path = "../../../crates/openshell-providers" } openshell-sdk = { path = "../../../crates/openshell-sdk" } openshell-testkit-macros = { path = "../testkit-macros" } clap = { version = "4", features = ["derive"] } diff --git a/tests/testkit/testkit/src/lib.rs b/tests/testkit/testkit/src/lib.rs index e24a9e6c60..d7e39746a6 100644 --- a/tests/testkit/testkit/src/lib.rs +++ b/tests/testkit/testkit/src/lib.rs @@ -38,6 +38,7 @@ mod logs; mod output; pub mod policy; mod poll; +pub mod profile; pub mod program; mod provider; mod ready; @@ -59,7 +60,9 @@ pub use image::{PYTHON_BINARIES, base_image, python_image}; pub use logs::{LOGS_TIMEOUT, Logs}; pub use openshell_sdk as sdk; pub use poll::{Poll, poll_until, with_deadline}; +pub use profile::{Credential, Profile}; pub use program::main; +pub use provider::ProviderBuilder; pub use ready::check as check_ready; pub use registry::Test; pub use run::{TestInfo, run}; diff --git a/tests/testkit/testkit/src/policy.rs b/tests/testkit/testkit/src/policy.rs index 080c585bf7..efbdcf1038 100644 --- a/tests/testkit/testkit/src/policy.rs +++ b/tests/testkit/testkit/src/policy.rs @@ -150,6 +150,10 @@ pub trait Endpoint { fn credential_binding(&mut self, provider: &str) -> &mut Self; /// `allow_uninspected_credentials: true`. fn allow_uninspected_credentials(&mut self) -> &mut Self; + /// `enforcement: enforce`. + fn enforce(&mut self) -> &mut Self; + /// `path: `. + fn path(&mut self, path: &str) -> &mut Self; } impl Endpoint for proto::NetworkEndpoint { @@ -186,6 +190,16 @@ impl Endpoint for proto::NetworkEndpoint { self.allow_uninspected_credentials = true; self } + + fn enforce(&mut self) -> &mut Self { + self.enforcement = proto::NetworkEnforcementMode::Enforce as i32; + self + } + + fn path(&mut self, path: &str) -> &mut Self { + self.path = path.to_string(); + self + } } #[cfg(test)] @@ -216,7 +230,9 @@ mod tests { &["/usr/bin/python*"], ) .websocket(Access::ReadWrite) - .allow_uninspected_credentials(); + .allow_uninspected_credentials() + .enforce() + .path("/ws"); let yaml = format!( "{BASE}network_policies: @@ -235,6 +251,8 @@ mod tests { protocol: websocket access: read-write allow_uninspected_credentials: true + enforcement: enforce + path: /ws binaries: - path: /usr/bin/python* " diff --git a/tests/testkit/testkit/src/profile.rs b/tests/testkit/testkit/src/profile.rs new file mode 100644 index 0000000000..ad2d61020d --- /dev/null +++ b/tests/testkit/testkit/src/profile.rs @@ -0,0 +1,332 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Provider profiles for tests, built in Rust and rendered as the YAML that +//! [`Context::import_profile`](crate::Context::import_profile) and +//! [`Context::install_provider`](crate::Context::install_provider) take. +//! +//! ```ignore +//! use testkit::policy::{Access, Endpoint as _}; +//! +//! let profile = testkit::Profile::new(&cx.name("auto")) +//! .credential( +//! testkit::Credential::new("api_key") +//! .env_var("API_KEY") +//! .required() +//! .auth_style("header") +//! .header_name("x-api-key"), +//! ) +//! .endpoint("api.example.test", 443, |ep| { +//! ep.rest(Access::ReadWrite).enforce(); +//! }) +//! .binaries(["/usr/bin/curl"]); +//! cx.import_profile(&profile.to_yaml()?).await?; +//! ``` +//! +//! [`policy::Endpoint`] configures profile endpoints. Setters are named after +//! the YAML fields they set, but explicit credential bindings belong in +//! sandbox policy, not reusable profiles. +//! +//! [`policy::Endpoint`]: crate::policy::Endpoint + +use openshell_providers::{ProviderTypeProfile, profile_to_yaml}; +use openshell_sdk::raw::proto; + +use crate::error::{Error, Result, ResultExt as _}; + +pub use proto::ProviderProfileCategory as Category; + +/// A provider profile. Its display name defaults to its id, and its category +/// to `other`. +#[derive(Clone, Debug)] +#[must_use] +pub struct Profile { + profile: proto::ProviderProfile, +} + +impl Profile { + /// A profile with `id`, the provider type it defines. + pub fn new(id: &str) -> Self { + Self { + profile: proto::ProviderProfile { + id: id.to_string(), + display_name: id.to_string(), + category: Category::Other as i32, + ..proto::ProviderProfile::default() + }, + } + } + + /// The profile's `id`. + pub fn id(&self) -> &str { + &self.profile.id + } + + /// `display_name`. + pub fn display_name(mut self, name: &str) -> Self { + self.profile.display_name = name.to_string(); + self + } + + /// `category`. + pub fn category(mut self, category: Category) -> Self { + self.profile.category = category as i32; + self + } + + /// Add `credential` to `credentials`. + pub fn credential(mut self, credential: Credential) -> Self { + self.profile.credentials.push(credential.credential); + self + } + + /// `discovery: {credentials: [..]}`: the credentials the CLI looks for in + /// its environment when it creates the provider itself. + pub fn discover(mut self, credentials: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.profile + .discovery + .get_or_insert_with(proto::ProviderProfileDiscovery::default) + .credentials + .extend(credentials.into_iter().map(Into::into)); + self + } + + /// Add an endpoint for `host:port` to `endpoints`, configured by + /// `configure` with [`policy::Endpoint`](crate::policy::Endpoint). + pub fn endpoint( + mut self, + host: &str, + port: u16, + configure: impl FnOnce(&mut proto::NetworkEndpoint), + ) -> Self { + let mut endpoint = proto::NetworkEndpoint { + host: host.to_string(), + port: port.into(), + ..proto::NetworkEndpoint::default() + }; + configure(&mut endpoint); + self.profile.endpoints.push(endpoint); + self + } + + /// Add `paths` to `binaries`. + pub fn binaries(mut self, paths: I) -> Self + where + I: IntoIterator, + S: Into, + { + self.profile.binaries.extend( + paths + .into_iter() + .map(|path| proto::NetworkBinary { path: path.into() }), + ); + self + } + + /// The profile as YAML, as `profile export` writes it. + /// Returns an error if an endpoint specifies `credential_binding`. + pub fn to_yaml(&self) -> Result { + for endpoint in &self.profile.endpoints { + if endpoint.credential_binding.is_some() { + return Err(Error::msg(format!( + "provider profile {} endpoint {}:{} cannot set credential_binding; \ + set it in sandbox policy to bind a concrete provider", + self.profile.id, endpoint.host, endpoint.port + ))); + } + } + profile_to_yaml(&ProviderTypeProfile::from_proto(&self.profile)) + .map_err(Error::from_display) + .context(format!("render provider profile {}", self.profile.id)) + } +} + +/// A credential in a [`Profile`]. +#[derive(Clone, Debug)] +#[must_use] +pub struct Credential { + credential: proto::ProviderProfileCredential, +} + +impl Credential { + /// A credential called `name`. + pub fn new(name: &str) -> Self { + Self { + credential: proto::ProviderProfileCredential { + name: name.to_string(), + ..proto::ProviderProfileCredential::default() + }, + } + } + + /// Add `var` to `env_vars`. + pub fn env_var(mut self, var: &str) -> Self { + self.credential.env_vars.push(var.to_string()); + self + } + + /// `required: true`. + pub fn required(mut self) -> Self { + self.credential.required = true; + self + } + + /// `auth_style`, such as `bearer` or `header`. + pub fn auth_style(mut self, style: &str) -> Self { + self.credential.auth_style = style.to_string(); + self + } + + /// `header_name`. + pub fn header_name(mut self, name: &str) -> Self { + self.credential.header_name = name.to_string(); + self + } + + /// `refresh`, for a credential the gateway refreshes. + pub fn refresh(mut self, refresh: proto::ProviderCredentialRefresh) -> Self { + self.credential.refresh = Some(refresh); + self + } +} + +#[cfg(test)] +mod tests { + use openshell_providers::parse_profile_yaml; + + use super::*; + use crate::policy::{Access, Endpoint as _}; + + fn parsed(yaml: &str) -> ProviderTypeProfile { + parse_profile_yaml(yaml).expect("the YAML parses") + } + + /// Each setter sets the YAML field it is named after, so the gateway + /// can't tell a built profile from the YAML. + #[test] + fn setters_match_the_yaml_they_name() { + let profile = Profile::new("example") + .display_name("Example") + .category(Category::Inference) + .credential( + Credential::new("api_key") + .env_var("API_KEY") + .env_var("OTHER_KEY") + .required() + .auth_style("header") + .header_name("x-api-key"), + ) + .discover(["api_key"]) + .endpoint("api.example.test", 443, |ep| { + ep.rest(Access::ReadWrite).enforce().path("/v1/**"); + }) + .endpoint("ws.example.test", 8443, |ep| { + ep.websocket(Access::ReadOnly); + }) + .binaries(["/usr/bin/curl", "/usr/bin/python*"]); + + let expected = parsed( + "id: example +display_name: Example +category: inference +credentials: + - name: api_key + env_vars: [API_KEY, OTHER_KEY] + required: true + auth_style: header + header_name: x-api-key +discovery: + credentials: [api_key] +endpoints: + - host: api.example.test + port: 443 + path: /v1/** + protocol: rest + access: read-write + enforcement: enforce + - host: ws.example.test + port: 8443 + protocol: websocket + access: read-only +binaries: [/usr/bin/curl, /usr/bin/python*] +", + ); + let yaml = profile.to_yaml().expect("renders"); + assert_eq!(parsed(&yaml), expected, "rendered:\n{yaml}"); + } + + #[test] + fn rejects_explicit_credential_binding() { + let error = Profile::new("example") + .endpoint("api.example.test", 443, |ep| { + ep.credential_binding("provider"); + }) + .to_yaml() + .expect_err("a profile must not silently drop an explicit binding") + .to_string(); + assert!(error.contains("api.example.test:443"), "{error}"); + assert!(error.contains("credential_binding"), "{error}"); + assert!(error.contains("sandbox policy"), "{error}"); + } + + /// A profile with only an id has the display name and category the + /// gateway requires. + #[test] + fn defaults() { + let yaml = Profile::new("bare").to_yaml().expect("renders"); + assert_eq!( + parsed(&yaml), + parsed("id: bare\ndisplay_name: bare\ncategory: other\n"), + "rendered:\n{yaml}" + ); + } + + #[test] + fn refresh() { + let refresh = proto::ProviderCredentialRefresh { + strategy: proto::ProviderCredentialRefreshStrategy::Oauth2RefreshToken as i32, + token_url: "https://issuer.example.test/token".to_string(), + scopes: vec!["openid".to_string()], + refresh_before: Some(prost_types::Duration { + seconds: 60, + nanos: 0, + }), + material: vec![proto::ProviderCredentialRefreshMaterial { + name: "refresh_token".to_string(), + required: true, + secret: true, + ..proto::ProviderCredentialRefreshMaterial::default() + }], + ..proto::ProviderCredentialRefresh::default() + }; + let yaml = Profile::new("refreshing") + .credential(Credential::new("token").refresh(refresh)) + .to_yaml() + .expect("renders"); + assert_eq!( + parsed(&yaml), + parsed( + "id: refreshing +display_name: refreshing +category: other +credentials: + - name: token + refresh: + strategy: oauth2_refresh_token + token_url: https://issuer.example.test/token + scopes: [openid] + refresh_before: 60s + material: + - name: refresh_token + required: true + secret: true +" + ), + "rendered:\n{yaml}" + ); + } +} diff --git a/tests/testkit/testkit/src/provider.rs b/tests/testkit/testkit/src/provider.rs index b68b20989c..3cd6a89114 100644 --- a/tests/testkit/testkit/src/provider.rs +++ b/tests/testkit/testkit/src/provider.rs @@ -1,6 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +use std::future::{Future, IntoFuture}; +use std::pin::Pin; + use serde::Deserialize; use crate::context::Context; @@ -31,57 +34,126 @@ impl Context { } /// Create a provider called `name` of `provider_type` with `credentials`, - /// as pairs of environment variable and value. Cleanup deletes the - /// provider after the test's sandboxes. + /// as pairs of environment variable and value, when awaited. Cleanup + /// deletes the provider after the test's sandboxes. /// /// The CLI reads the credential values from its environment, so they - /// aren't in the reported command. - pub async fn create_provider( - &self, - name: &str, - provider_type: &str, - credentials: &[(&str, &str)], - ) -> Result { + /// aren't in the reported command. [`ProviderBuilder`] sets other + /// `provider create` options before the await. + pub fn create_provider<'a>( + &'a self, + name: &'a str, + provider_type: &'a str, + credentials: &'a [(&'a str, &'a str)], + ) -> ProviderBuilder<'a> { + ProviderBuilder::new(self, name, ProviderType::Named(provider_type), credentials) + } + + /// Import `profile` with [`Context::import_profile`] and create a provider + /// called `name` of its type with [`Context::create_provider`], when + /// awaited. + pub fn install_provider<'a>( + &'a self, + name: &'a str, + profile: &'a str, + credentials: &'a [(&'a str, &'a str)], + ) -> ProviderBuilder<'a> { + ProviderBuilder::new(self, name, ProviderType::Profile(profile), credentials) + } + + fn on_cleanup_delete(&self, kind: &'static str, name: &str) { + let cli = self.cli_handle(); + let owned = name.to_string(); + self.on_cleanup(format!("delete {kind} {name}"), async move || { + cli.run([kind, "delete", &owned]).await?.success()?; + Ok(()) + }); + } +} + +/// Where a [`ProviderBuilder`] gets its provider type. +enum ProviderType<'a> { + /// A profile already on the gateway. + Named(&'a str), + /// A profile, in YAML, to import first. + Profile(&'a str), +} + +/// A provider to create, from [`Context::create_provider`] or +/// [`Context::install_provider`]. Awaiting it creates the provider. +/// +/// ```ignore +/// cx.create_provider(&name, &provider_type, &[]) +/// .config("project", "production") +/// .await?; +/// ``` +#[must_use = "a ProviderBuilder does nothing until awaited"] +pub struct ProviderBuilder<'a> { + cx: &'a Context, + name: &'a str, + provider_type: ProviderType<'a>, + credentials: &'a [(&'a str, &'a str)], + config: Vec, +} + +impl<'a> ProviderBuilder<'a> { + fn new( + cx: &'a Context, + name: &'a str, + provider_type: ProviderType<'a>, + credentials: &'a [(&'a str, &'a str)], + ) -> Self { + Self { + cx, + name, + provider_type, + credentials, + config: Vec::new(), + } + } + + /// Set the provider config `key` to `value` (`--config key=value`). + pub fn config(mut self, key: &str, value: &str) -> Self { + self.config.push(format!("{key}={value}")); + self + } + + async fn create(self) -> Result { + let provider_type = match self.provider_type { + ProviderType::Named(provider_type) => provider_type.to_string(), + ProviderType::Profile(profile) => self.cx.import_profile(profile).await?, + }; // Deleting a missing provider succeeds, so register the delete before // the create. - self.on_cleanup_delete("provider", name); + self.cx.on_cleanup_delete("provider", self.name); let mut args = vec![ "provider", "create", "--name", - name, + self.name, "--type", - provider_type, + &provider_type, ]; - for (key, _) in credentials { + for (key, _) in self.credentials { args.extend(["--credential", key]); } - self.cli_with_env(credentials, args) + for setting in &self.config { + args.extend(["--config", setting]); + } + self.cx + .cli_with_env(self.credentials, args) .await? .success() - .context(format!("create provider {name}"))?; + .context(format!("create provider {}", self.name))?; Ok(()) } +} - /// Import `profile` with [`Context::import_profile`] and create a provider - /// called `name` of its type with [`Context::create_provider`]. - pub async fn install_provider( - &self, - name: &str, - profile: &str, - credentials: &[(&str, &str)], - ) -> Result { - let provider_type = self.import_profile(profile).await?; - self.create_provider(name, &provider_type, credentials) - .await - } +impl<'a> IntoFuture for ProviderBuilder<'a> { + type Output = Result; + type IntoFuture = Pin + 'a>>; - fn on_cleanup_delete(&self, kind: &'static str, name: &str) { - let cli = self.cli_handle(); - let owned = name.to_string(); - self.on_cleanup(format!("delete {kind} {name}"), async move || { - cli.run([kind, "delete", &owned]).await?.success()?; - Ok(()) - }); + fn into_future(self) -> Self::IntoFuture { + Box::pin(self.create()) } } diff --git a/tests/tmachine/ansible/playbooks/drivers/podman/userns.yaml b/tests/tmachine/ansible/playbooks/drivers/podman/userns.yaml index 202270100f..feb3b3c323 100644 --- a/tests/tmachine/ansible/playbooks/drivers/podman/userns.yaml +++ b/tests/tmachine/ansible/playbooks/drivers/podman/userns.yaml @@ -4,18 +4,16 @@ # Configure the Podman gateway's user-namespace mode and publish it. # # `podman_userns_mode` is default, auto, keep-id or private. Every mode except -# default writes its `[openshell.drivers.podman]` settings to -# `/etc/openshell-test/gateway-overrides.toml`, which every installer applies to the active -# gateway-overrides.toml (the openshell_gateway role for `binaries`, the -# openshell_packaged_gateway role for the packages); default removes the file. The -# Podman support crate (tests/support/podman) reads the published mode and -# runs Podman's own reference container in it. +# default adds its `[openshell.drivers.podman]` settings to the gateway +# overrides (the gateway_overrides role), which every installer applies to the +# gateway's configuration. Default mode removes them, so userns, uidmap and +# gidmap stay unset. The Podman support crate (tests/support/podman) reads the +# published mode and runs Podman's own reference container in it. --- - name: Podman user namespaces for tests hosts: all gather_facts: false vars: - podman_userns_driver_config: /etc/openshell-test/gateway-overrides.toml podman_userns_settings: default: "" auto: | @@ -43,33 +41,13 @@ {{ podman_userns_settings.keys() | join(', ') }}, not {{ podman_userns_mode | default('unset') }} - - name: Create the test configuration directory - become: true - ansible.builtin.file: - path: "{{ podman_userns_driver_config | dirname }}" - state: directory - owner: root - group: root - mode: "0755" - - name: Write the Podman driver user-namespace settings - become: true - ansible.builtin.copy: - dest: "{{ podman_userns_driver_config }}" - content: "{{ podman_userns_settings[podman_userns_mode] }}" - owner: root - group: root - mode: "0644" - when: podman_userns_mode != "default" - - # The fragment is the only source of userns, uidmap and gidmap settings in - # the gateway's configuration, so default mode leaves them unset. - - name: Remove Podman driver user-namespace settings for default mode - become: true - ansible.builtin.file: - path: "{{ podman_userns_driver_config }}" - state: absent - when: podman_userns_mode == "default" + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: podman-userns + gateway_overrides_content: "{{ podman_userns_settings[podman_userns_mode] }}" + gateway_overrides_state: "{{ 'absent' if podman_userns_mode == 'default' else 'present' }}" - name: Publish Podman user-namespace test variables ansible.builtin.include_tasks: ../../test-env.yaml diff --git a/tests/tmachine/ansible/roles/cdi_fixtures/tasks/main.yaml b/tests/tmachine/ansible/roles/cdi_fixtures/tasks/main.yaml index 5f0c04586c..250629d90b 100644 --- a/tests/tmachine/ansible/roles/cdi_fixtures/tasks/main.yaml +++ b/tests/tmachine/ansible/roles/cdi_fixtures/tasks/main.yaml @@ -38,25 +38,11 @@ # The tests select the scenario device per sandbox through driver config, which # the gateway rejects unless an administrator allows it. The installers add # this to the active driver's settings. -- name: Create the test settings directory - become: true - ansible.builtin.file: - path: /etc/openshell-test - state: directory - owner: root - group: root - mode: "0755" - -# The gateway must accept a per-sandbox CDI device, which it does only when the -# driver allows caller driver config. Every installer merges this override into -# the gateway's own configuration (see openshell_gateway/tasks/merge-settings.yaml). - name: Allow caller driver config for the CDI tests - become: true - ansible.builtin.copy: - dest: /etc/openshell-test/gateway-overrides.toml - content: | + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: cdi + gateway_overrides_content: | [openshell.drivers.{{ environment_driver }}] allow_driver_config = true - owner: root - group: root - mode: "0644" diff --git a/tests/tmachine/ansible/roles/gateway_overrides/defaults/main.yaml b/tests/tmachine/ansible/roles/gateway_overrides/defaults/main.yaml new file mode 100644 index 0000000000..8e9f90608e --- /dev/null +++ b/tests/tmachine/ansible/roles/gateway_overrides/defaults/main.yaml @@ -0,0 +1,6 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +--- +gateway_overrides_path: /etc/openshell-test/gateway-overrides.toml +gateway_overrides_state: present diff --git a/tests/tmachine/ansible/roles/gateway_overrides/tasks/main.yaml b/tests/tmachine/ansible/roles/gateway_overrides/tasks/main.yaml new file mode 100644 index 0000000000..5da35a936f --- /dev/null +++ b/tests/tmachine/ansible/roles/gateway_overrides/tasks/main.yaml @@ -0,0 +1,76 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Add gateway settings to /etc/openshell-test/gateway-overrides.toml, which +# the `binaries`, `deb` and `rpm` installers apply to the gateway's +# configuration (openshell_gateway/tasks/merge-settings.yaml; k3s installers +# ignore it). +# +# Inputs: +# gateway_overrides_name names the marked block, such as `cdi`; writing +# the same name again replaces its block +# gateway_overrides_content whole TOML tables, such as +# `[openshell.drivers.podman]` +# gateway_overrides_state `absent` removes the name's block and keeps the +# others; the default is `present` +# +# Each name gets its own marked block, so writers keep each other's settings +# and may run in any order. Two blocks must not declare the same table: TOML +# rejects a table defined twice, and the installer fails on it. +# +# TODO: https://github.com/NVIDIA/OpenShell/pull/5489 reads gateway.d drop-in +# files. When it lands, write each name to its own drop-in here instead. +--- +- name: Require a gateway override name and content + ansible.builtin.assert: + that: + - gateway_overrides_name is defined + - gateway_overrides_name is match('^[a-z0-9][a-z0-9-]*$') + - gateway_overrides_state in ['present', 'absent'] + - >- + gateway_overrides_state == 'absent' or + (gateway_overrides_content is defined and + gateway_overrides_content | trim is match('\\[')) + fail_msg: >- + gateway_overrides needs gateway_overrides_name (lowercase letters, + digits and dashes), gateway_overrides_state present or absent, and + gateway_overrides_content that starts with a table header, such as + `[openshell.gateway]`, unless the state is absent + +- name: Create the test configuration directory + become: true + when: gateway_overrides_state == 'present' + ansible.builtin.file: + path: "{{ gateway_overrides_path | dirname }}" + state: directory + owner: root + group: root + mode: "0755" + +- name: Write the {{ gateway_overrides_name }} gateway overrides + become: true + ansible.builtin.blockinfile: + path: "{{ gateway_overrides_path }}" + create: true + owner: root + group: root + mode: "0644" + marker: "# {mark} {{ gateway_overrides_name }}" + block: "{{ gateway_overrides_content }}" + when: gateway_overrides_state == 'present' + +- name: Check for the gateway overrides file + ansible.builtin.stat: + path: "{{ gateway_overrides_path }}" + register: gateway_overrides_file + when: gateway_overrides_state == 'absent' + +- name: Remove the {{ gateway_overrides_name }} gateway overrides + become: true + ansible.builtin.blockinfile: + path: "{{ gateway_overrides_path }}" + marker: "# {mark} {{ gateway_overrides_name }}" + state: absent + when: + - gateway_overrides_state == 'absent' + - gateway_overrides_file.stat.exists diff --git a/tests/tmachine/ansible/roles/openshell_external_driver/tasks/main.yaml b/tests/tmachine/ansible/roles/openshell_external_driver/tasks/main.yaml index a31363d57d..2f3d4e3872 100644 --- a/tests/tmachine/ansible/roles/openshell_external_driver/tasks/main.yaml +++ b/tests/tmachine/ansible/roles/openshell_external_driver/tasks/main.yaml @@ -108,18 +108,11 @@ ansible.builtin.fail: msg: The external driver socket did not appear -- name: Create the environment settings directory - become: true - ansible.builtin.file: - path: /etc/openshell-test - state: directory - mode: "0755" - - name: Point the gateway at the external driver - become: true - ansible.builtin.copy: - dest: /etc/openshell-test/gateway-overrides.toml - mode: "0644" - content: | + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: external-driver + gateway_overrides_content: | [openshell.drivers.{{ openshell_external_driver_name }}] socket_path = "{{ openshell_external_driver_socket }}" diff --git a/tests/tmachine/ansible/roles/openshell_gateway/files/merge_gateway_toml_test.py b/tests/tmachine/ansible/roles/openshell_gateway/files/merge_gateway_toml_test.py index ba6926169a..3f37c15178 100644 --- a/tests/tmachine/ansible/roles/openshell_gateway/files/merge_gateway_toml_test.py +++ b/tests/tmachine/ansible/roles/openshell_gateway/files/merge_gateway_toml_test.py @@ -98,3 +98,25 @@ def test_creates_from_default_else_minimal(tmp_path): run, base = merge(other, None, '[openshell.drivers.podman]\nuserns = "auto"\n') parsed = tomllib.loads(base.read_text()) assert parsed["openshell"]["version"] == 2 + + +def test_applies_every_marked_block(tmp_path): + overrides = ( + "# BEGIN podman-userns\n[openshell.drivers.podman]\nuserns = \"auto\"\n# END podman-userns\n" + "# BEGIN config-push\n[openshell.gateway]\nconfig_delivery_mode = \"push\"\n# END config-push\n" + ) + run, base = merge(tmp_path, BASE, overrides) + assert run.returncode == 0, run.stderr + parsed = tomllib.loads(base.read_text()) + assert parsed["openshell"]["drivers"]["podman"]["userns"] == "auto" + assert parsed["openshell"]["gateway"]["config_delivery_mode"] == "push" + + +def test_rejects_blocks_that_declare_the_same_table(tmp_path): + overrides = ( + "# BEGIN cdi\n[openshell.drivers.podman]\nallow_driver_config = true\n# END cdi\n" + "# BEGIN podman-userns\n[openshell.drivers.podman]\nuserns = \"auto\"\n# END podman-userns\n" + ) + run, base = merge(tmp_path, BASE, overrides) + assert run.returncode != 0 + assert base.read_text() == BASE diff --git a/tests/tmachine/ansible/roles/openshell_gateway/tasks/merge-settings.yaml b/tests/tmachine/ansible/roles/openshell_gateway/tasks/merge-settings.yaml index 6d167a3ec8..05a679b2f5 100644 --- a/tests/tmachine/ansible/roles/openshell_gateway/tasks/merge-settings.yaml +++ b/tests/tmachine/ansible/roles/openshell_gateway/tasks/merge-settings.yaml @@ -1,10 +1,11 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 -# An environment overrides gateway settings by writing the tables to change, +# An environment overrides gateway settings by adding the tables to change, # such as `[openshell.drivers.podman]`, to -# /etc/openshell-test/gateway-overrides.toml before the installer runs (for -# example playbooks/drivers/podman/userns.yaml). Apply them to +# /etc/openshell-test/gateway-overrides.toml with the gateway_overrides role +# before the installer runs (for example playbooks/drivers/podman/userns.yaml). +# Apply them to # `openshell_gateway_merge_target` without replacing the file; see # files/merge-gateway-toml.py. # @@ -27,4 +28,4 @@ {{ '--default ' ~ openshell_gateway_merge_default if openshell_gateway_merge_default | default('') else '' }} executable: /usr/bin/python3 - when: openshell_gateway_overrides.stat.exists + when: openshell_gateway_overrides.stat.exists and openshell_gateway_overrides.stat.size > 0