From b583dbb0b4cd3f3a43df1657eaeb2176c3f36a92 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Tue, 17 Nov 2026 11:29:33 -0800 Subject: [PATCH 1/3] test(testkit): let create_provider set provider config create_provider and install_provider return a builder that creates the provider when awaited, so tests can chain .config(key, value) for provider create --config. Existing callers are unchanged. Signed-off-by: Matthew Grossman --- tests/testkit/README.md | 3 +- tests/testkit/testkit/src/lib.rs | 1 + tests/testkit/testkit/src/provider.rs | 140 +++++++++++++++++++------- 3 files changed, 109 insertions(+), 35 deletions(-) diff --git a/tests/testkit/README.md b/tests/testkit/README.md index 994cc93b46..c2c7e3b5be 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -135,7 +135,8 @@ 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. - `testkit::YamlFile` for YAML a CLI command reads from a file. - `cx.client()` for SDK calls testkit does not wrap. - In `tests/support`: `host-server` starts servers on the machine that runs diff --git a/tests/testkit/testkit/src/lib.rs b/tests/testkit/testkit/src/lib.rs index e24a9e6c60..2363fd6e10 100644 --- a/tests/testkit/testkit/src/lib.rs +++ b/tests/testkit/testkit/src/lib.rs @@ -60,6 +60,7 @@ pub use logs::{LOGS_TIMEOUT, Logs}; pub use openshell_sdk as sdk; pub use poll::{Poll, poll_until, with_deadline}; 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/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()) } } From a15b4614051baa983421662cc224a45b3a9c004d Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Tue, 17 Nov 2026 21:21:23 -0800 Subject: [PATCH 2/3] test(testkit): add a typed provider profile builder Signed-off-by: Matthew Grossman --- tests/suites/conformance/Cargo.lock | 16 ++ tests/suites/drivers/podman/Cargo.lock | 16 ++ tests/support/Cargo.lock | 16 ++ tests/testkit/Cargo.lock | 16 ++ tests/testkit/README.md | 5 +- tests/testkit/testkit/Cargo.toml | 4 + tests/testkit/testkit/src/lib.rs | 2 + tests/testkit/testkit/src/policy.rs | 20 +- tests/testkit/testkit/src/profile.rs | 307 +++++++++++++++++++++++++ 9 files changed, 400 insertions(+), 2 deletions(-) create mode 100644 tests/testkit/testkit/src/profile.rs diff --git a/tests/suites/conformance/Cargo.lock b/tests/suites/conformance/Cargo.lock index a3c191b327..dd6b5fb483 100644 --- a/tests/suites/conformance/Cargo.lock +++ b/tests/suites/conformance/Cargo.lock @@ -2372,6 +2372,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 +2436,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/support/Cargo.lock b/tests/support/Cargo.lock index 8ba9df07e9..7d69ea932f 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -2376,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" @@ -2425,6 +2440,7 @@ dependencies = [ "openshell-bootstrap", "openshell-core", "openshell-policy", + "openshell-providers", "openshell-sdk", "openshell-testkit-macros", "prost-types", 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 c2c7e3b5be..def3f82421 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -136,7 +136,10 @@ fails. A killed test process skips cleanup, so names are unique to the run. `id`, and `cx.create_provider(name, type, credentials)` to create a provider, each with cleanup. `cx.install_provider(name, profile, credentials)` does both. Chain `.config(key, value)` before the `.await` - to set provider config. + 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..84b309fb8f 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"] } @@ -37,6 +38,9 @@ tonic = "0.14" [target.'cfg(unix)'.dependencies] libc = "0.2" +[dev-dependencies] +prost-types = "0.14" + # A test program, run by `cargo test` and nextest through `testkit::main`'s # libtest interface, that checks the program's own subcommands. [[test]] diff --git a/tests/testkit/testkit/src/lib.rs b/tests/testkit/testkit/src/lib.rs index 2363fd6e10..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,6 +60,7 @@ 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; 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..10217ff040 --- /dev/null +++ b/tests/testkit/testkit/src/profile.rs @@ -0,0 +1,307 @@ +// 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?; +//! ``` +//! +//! Profile endpoints are policy endpoints, so [`policy::Endpoint`] configures +//! them. Setters are named after the YAML fields they set. +//! +//! [`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. + pub fn to_yaml(&self) -> Result { + 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}"); + } + + /// 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}" + ); + } +} From bf8267854470f76f51a4ec6843160887c231cae2 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 21:22:55 -0800 Subject: [PATCH 3/3] test(e2e): use typed profiles in existing provider tests Signed-off-by: Matthew Grossman --- .../conformance/src/credential_gating.rs | 152 ++++++++---------- tests/suites/continuity/Cargo.lock | 16 ++ tests/suites/features/Cargo.lock | 18 ++- .../keycloak-provider-refresh/Cargo.toml | 2 +- .../tests/provider_refresh.rs | 127 +++++---------- 5 files changed, 143 insertions(+), 172 deletions(-) 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/features/Cargo.lock b/tests/suites/features/Cargo.lock index ba47285c9a..f316a951aa 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -1834,7 +1834,7 @@ version = "0.0.0" dependencies = [ "keycloak-support", "openshell-testkit", - "tempfile", + "prost-types", ] [[package]] @@ -2430,6 +2430,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 +2506,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"]) }