From 0ea4d491bb67a1375a8dcbe31bfcdee469267946 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:44:31 -0800 Subject: [PATCH 01/14] feat(testkit): add workspaces, token clients, and per-CLI environment Signed-off-by: Matthew Grossman --- tests/testkit/README.md | 6 + tests/testkit/testkit/src/cli.rs | 15 ++- tests/testkit/testkit/src/context.rs | 5 + tests/testkit/testkit/src/gateway.rs | 26 ++++- tests/testkit/testkit/src/lib.rs | 2 + tests/testkit/testkit/src/workspace.rs | 147 +++++++++++++++++++++++++ 6 files changed, 199 insertions(+), 2 deletions(-) create mode 100644 tests/testkit/testkit/src/workspace.rs diff --git a/tests/testkit/README.md b/tests/testkit/README.md index def3f82421..af10e5c0f0 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -118,6 +118,12 @@ fails. A killed test process skips cleanup, so names are unique to the run. - `Cli::apply_env` to point another program at the same gateway, such as `ssh` with the `ProxyCommand` from `sandbox ssh-config`. `Cli::gateway` says which gateway that is. +- `Cli::with_env(name, value)` for a CLI with extra environment on every + run, such as `XDG_CONFIG_HOME` holding another user's session. +- `cx.cli_handle().gateway().connect_with_token(token)` for an SDK client that sends a + bearer token, such as an OIDC access token, and no client certificate. +- `cx.workspace(suffix)` to create a workspace with cleanup. Its + `add_member(subject, role)` and `remove_member(subject)` manage members. - `cx.on_cleanup(name, hook)` to remove something when the test ends. - `testkit::policy` for sandbox policies: `policy::base()` reads `testkit/src/base-policy.yaml`, which allows no network access, and diff --git a/tests/testkit/testkit/src/cli.rs b/tests/testkit/testkit/src/cli.rs index 2973ea045b..ecc49dacc2 100644 --- a/tests/testkit/testkit/src/cli.rs +++ b/tests/testkit/testkit/src/cli.rs @@ -8,7 +8,7 @@ //! those and observe through the SDK where they can. Rely on the CLI's exit //! code and structured output (`--output json`), not on its table text. -use std::ffi::OsStr; +use std::ffi::{OsStr, OsString}; use std::path::{Path, PathBuf}; use std::process::Stdio; use std::time::Duration; @@ -30,6 +30,7 @@ pub(crate) const BIN_ENV: &str = "OPENSHELL_BIN"; pub struct Cli { binary: PathBuf, gateway: Gateway, + env: Vec<(OsString, OsString)>, } /// The buffered result of one CLI invocation. @@ -50,9 +51,19 @@ impl Cli { Self { binary, gateway: gateway.clone(), + env: Vec::new(), } } + /// This CLI with `name` set to `value` in its environment on every run, + /// such as `XDG_CONFIG_HOME` for a CLI that reads another user's + /// credentials. The gateway and workspace selection still wins. + #[must_use] + pub fn with_env(mut self, name: impl Into, value: impl Into) -> Self { + self.env.push((name.into(), value.into())); + self + } + /// `binary` in place of the CLI, pointed at an unregistered gateway. #[cfg(test)] pub(crate) fn with_binary(binary: &str) -> Self { @@ -62,6 +73,7 @@ impl Cli { "http://127.0.0.1:1".to_string(), "default".to_string(), ), + env: Vec::new(), } } @@ -172,6 +184,7 @@ impl Cli { /// `ssh` with the `ProxyCommand` from `sandbox ssh-config`. pub fn apply_env(&self, process: &mut tokio::process::Command) { process + .envs(self.env.iter().map(|(name, value)| (name, value))) .env("NO_COLOR", "1") .env(WORKSPACE_ENV, &self.gateway.workspace); // Select exactly the gateway the SDK connected to. diff --git a/tests/testkit/testkit/src/context.rs b/tests/testkit/testkit/src/context.rs index da6e84abee..5739212759 100644 --- a/tests/testkit/testkit/src/context.rs +++ b/tests/testkit/testkit/src/context.rs @@ -171,6 +171,11 @@ impl Context { &self.handles.client } + /// The SDK client for the whole gateway, not scoped to a workspace. + pub(crate) fn gateway_client(&self) -> &OpenShellClient { + &self.handles.grpc.client + } + /// A resource name unique to this run: `test--`. /// /// Sandbox names can't exceed [`MAX_SANDBOX_NAME_LEN`], so a sandbox diff --git a/tests/testkit/testkit/src/gateway.rs b/tests/testkit/testkit/src/gateway.rs index fef05833b7..5773f924c8 100644 --- a/tests/testkit/testkit/src/gateway.rs +++ b/tests/testkit/testkit/src/gateway.rs @@ -17,7 +17,9 @@ use std::path::{Path, PathBuf}; use std::time::Duration; -use openshell_sdk::{ClientConfig, ClientIdentity, Health, OpenShellClient, ServiceStatus}; +use openshell_sdk::{ + AuthConfig, ClientConfig, ClientIdentity, Health, OpenShellClient, ServiceStatus, +}; use crate::error::{Error, Result, ResultExt}; @@ -121,6 +123,13 @@ impl Gateway { }) } + /// The directory holding the gateway's CA (`ca.crt`) and the client + /// certificate and key (`tls.crt`, `tls.key`) for mTLS, or `None` for a + /// gateway testkit reaches without a client certificate. + pub fn mtls_dir(&self) -> Option<&Path> { + self.mtls_dir.as_deref() + } + /// One line naming the gateway, for test logs. pub fn describe(&self) -> String { let auth = match (&self.mtls_dir, self.endpoint.starts_with("https://")) { @@ -157,6 +166,21 @@ impl Gateway { .context(format!("connect to {}", self.endpoint)) } + /// Connect to the gateway as the user `token` names, a bearer token such + /// as an OIDC access token, or with no credentials for `None`. The + /// connection verifies the gateway with its CA and presents no client + /// certificate, so the gateway sees only the token. + pub async fn connect_with_token(&self, token: Option<&str>) -> Result { + let mut config = ClientConfig::new(self.endpoint.clone()); + if let Some(dir) = &self.mtls_dir { + config.ca_cert = Some(read(&dir.join("ca.crt"))?); + } + config.auth = token.map(AuthConfig::oidc); + OpenShellClient::connect(config) + .await + .context(format!("connect to {} with a token", self.endpoint)) + } + /// Wait until the gateway accepts a connection and reports itself /// healthy, retrying until `timeout`. /// diff --git a/tests/testkit/testkit/src/lib.rs b/tests/testkit/testkit/src/lib.rs index d7e39746a6..bc6c122984 100644 --- a/tests/testkit/testkit/src/lib.rs +++ b/tests/testkit/testkit/src/lib.rs @@ -44,6 +44,7 @@ mod provider; mod ready; mod registry; mod run; +mod workspace; mod yaml_file; pub use cleanup::CLEANUP_TIMEOUT; @@ -68,6 +69,7 @@ pub use registry::Test; pub use run::{TestInfo, run}; pub use testkit_macros::test; pub use tonic::Code as GrpcCode; +pub use workspace::Workspace; pub use yaml_file::YamlFile; #[doc(hidden)] diff --git a/tests/testkit/testkit/src/workspace.rs b/tests/testkit/testkit/src/workspace.rs new file mode 100644 index 0000000000..37263a6bf4 --- /dev/null +++ b/tests/testkit/testkit/src/workspace.rs @@ -0,0 +1,147 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Workspaces a test creates, and their members. + +use std::collections::HashMap; +use std::time::{Duration, Instant}; + +use openshell_sdk::raw::proto; +use openshell_sdk::{DeleteOptions, OpenShellClient}; + +use crate::context::Context; +use crate::error::{Error, Result, ResultExt as _}; + +/// The longest workspace name the gateway accepts. +const MAX_WORKSPACE_NAME_LEN: usize = 19; + +/// How long cleanup waits for a workspace's resources to go before giving +/// up on deleting it. Under [`crate::CLEANUP_TIMEOUT`], so the failure +/// names the workspace. +const DELETE_RETRY_TIMEOUT: Duration = Duration::from_secs(90); +const DELETE_RETRY_INTERVAL: Duration = Duration::from_secs(2); + +impl Context { + /// Create a workspace named [`Context::name`]`(suffix)`, as the gateway + /// client testkit connects with. The suffix is at most five characters, + /// to fit the gateway's limit on workspace names. Cleanup deletes the + /// workspace after the test's sandboxes, waiting for resources still in + /// it to go. + pub async fn workspace(&self, suffix: &str) -> Result { + let name = self.name(suffix); + crate::ensure!( + name.len() <= MAX_WORKSPACE_NAME_LEN, + "workspace name {name} exceeds {MAX_WORKSPACE_NAME_LEN} characters; use a shorter suffix than {suffix:?}" + ); + let client = self.gateway_client().clone(); + // Deleting a missing workspace succeeds, so register the delete + // before the create. + let cleanup_client = client.clone(); + let owned = name.clone(); + self.on_cleanup(format!("delete workspace {name}"), move || { + delete_workspace(cleanup_client, owned) + }); + client + .create_workspace(&name, HashMap::new()) + .await + .context(format!("create workspace {name}"))?; + Ok(Workspace { name, client }) + } +} + +/// A workspace from [`Context::workspace`]. +#[derive(Clone)] +pub struct Workspace { + name: String, + client: OpenShellClient, +} + +impl Workspace { + pub fn name(&self) -> &str { + &self.name + } + + /// Make `subject`, an OIDC subject claim, a member with `role`. + pub async fn add_member(&self, subject: &str, role: proto::WorkspaceRole) -> Result { + self.client + .raw_grpc_fresh() + .await? + .add_workspace_member(proto::AddWorkspaceMemberRequest { + workspace_scope: Some(proto::workspace_selector(&self.name)), + principal_subject: subject.to_string(), + role: role.into(), + request_id: String::new(), + }) + .await + .context(format!( + "add {subject} to workspace {} as {}", + self.name, + role.as_str_name() + ))?; + Ok(()) + } + + /// Remove `subject` from the workspace's members. + pub async fn remove_member(&self, subject: &str) -> Result { + self.client + .raw_grpc_fresh() + .await? + .remove_workspace_member(proto::RemoveWorkspaceMemberRequest { + workspace_scope: Some(proto::workspace_selector(&self.name)), + principal_subject: subject.to_string(), + allow_missing: false, + request_id: String::new(), + }) + .await + .context(format!("remove {subject} from workspace {}", self.name))?; + Ok(()) + } +} + +/// Delete `name`, retrying while resources the gateway is still deleting +/// block it. +async fn delete_workspace(client: OpenShellClient, name: String) -> Result { + let started = Instant::now(); + loop { + let error = match client + .delete_workspace( + &name, + DeleteOptions { + allow_missing: true, + }, + ) + .await + { + Ok(_) => return Ok(()), + Err(error) => Error::from(error), + }; + if !still_has_resources(&error) || started.elapsed() >= DELETE_RETRY_TIMEOUT { + return Err(error).context(format!("delete workspace {name}")); + } + tokio::time::sleep(DELETE_RETRY_INTERVAL).await; + } +} + +fn still_has_resources(error: &Error) -> bool { + error.grpc_code() == Some(tonic::Code::FailedPrecondition) + && error.to_string().contains("still contains resources") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn retries_only_a_workspace_with_resources() { + let busy = Error::from(tonic::Status::failed_precondition( + "workspace 'w' still contains resources: sandbox", + )); + let other = Error::from(tonic::Status::failed_precondition( + "workspace is terminating", + )); + let denied = Error::from(tonic::Status::permission_denied("still contains resources")); + assert!(still_has_resources(&busy)); + assert!(!still_has_resources(&other)); + assert!(!still_has_resources(&denied)); + } +} From 9aa2267c43c18e5ac745d72dbd5e44a97897aca3 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:50:26 -0800 Subject: [PATCH 02/14] feat(testkit): let a CLI change its environment and workspace Signed-off-by: Matthew Grossman --- tests/testkit/README.md | 6 ++++-- tests/testkit/testkit/src/cli.rs | 28 +++++++++++++++++++++++++--- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/tests/testkit/README.md b/tests/testkit/README.md index af10e5c0f0..91d2d8b023 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -118,8 +118,10 @@ fails. A killed test process skips cleanup, so names are unique to the run. - `Cli::apply_env` to point another program at the same gateway, such as `ssh` with the `ProxyCommand` from `sandbox ssh-config`. `Cli::gateway` says which gateway that is. -- `Cli::with_env(name, value)` for a CLI with extra environment on every - run, such as `XDG_CONFIG_HOME` holding another user's session. +- `Cli::with_env(name, value)` and `Cli::without_env(name)` for a CLI with + changed environment on every run, such as `XDG_CONFIG_HOME` holding + another user's session. `Cli::in_workspace(name)` points it at another + workspace. - `cx.cli_handle().gateway().connect_with_token(token)` for an SDK client that sends a bearer token, such as an OIDC access token, and no client certificate. - `cx.workspace(suffix)` to create a workspace with cleanup. Its diff --git a/tests/testkit/testkit/src/cli.rs b/tests/testkit/testkit/src/cli.rs index ecc49dacc2..831136dbe1 100644 --- a/tests/testkit/testkit/src/cli.rs +++ b/tests/testkit/testkit/src/cli.rs @@ -30,7 +30,8 @@ pub(crate) const BIN_ENV: &str = "OPENSHELL_BIN"; pub struct Cli { binary: PathBuf, gateway: Gateway, - env: Vec<(OsString, OsString)>, + /// Variables to set, or with `None`, to remove, on every run. + env: Vec<(OsString, Option)>, } /// The buffered result of one CLI invocation. @@ -60,7 +61,23 @@ impl Cli { /// credentials. The gateway and workspace selection still wins. #[must_use] pub fn with_env(mut self, name: impl Into, value: impl Into) -> Self { - self.env.push((name.into(), value.into())); + self.env.push((name.into(), Some(value.into()))); + self + } + + /// This CLI with `name` removed from its environment on every run, such + /// as a variable the test process inherits that changes how the CLI + /// logs in. + #[must_use] + pub fn without_env(mut self, name: impl Into) -> Self { + self.env.push((name.into(), None)); + self + } + + /// This CLI pointed at `workspace` on the same gateway. + #[must_use] + pub fn in_workspace(mut self, workspace: impl Into) -> Self { + self.gateway.workspace = workspace.into(); self } @@ -183,8 +200,13 @@ impl Cli { /// invocation is. Use it for a program that runs the CLI itself, such as /// `ssh` with the `ProxyCommand` from `sandbox ssh-config`. pub fn apply_env(&self, process: &mut tokio::process::Command) { + for (name, value) in &self.env { + match value { + Some(value) => process.env(name, value), + None => process.env_remove(name), + }; + } process - .envs(self.env.iter().map(|(name, value)| (name, value))) .env("NO_COLOR", "1") .env(WORKSPACE_ENV, &self.gateway.workspace); // Select exactly the gateway the SDK connected to. From b7fe0c875081cf010b8ecb95cb2c1b929d5a439c Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:50:26 -0800 Subject: [PATCH 03/14] feat(keycloak-support): add user sessions and the browser login Signed-off-by: Matthew Grossman --- tests/support/Cargo.lock | 3 + tests/support/keycloak/Cargo.toml | 5 +- tests/support/keycloak/src/browser.rs | 245 ++++++++++++++++++++++++++ tests/support/keycloak/src/lib.rs | 82 ++++++++- tests/support/keycloak/src/session.rs | 156 ++++++++++++++++ tests/support/keycloak/src/token.rs | 84 +++++++++ 6 files changed, 569 insertions(+), 6 deletions(-) create mode 100644 tests/support/keycloak/src/browser.rs create mode 100644 tests/support/keycloak/src/session.rs create mode 100644 tests/support/keycloak/src/token.rs diff --git a/tests/support/Cargo.lock b/tests/support/Cargo.lock index 4de10e2dd6..366c494f24 100644 --- a/tests/support/Cargo.lock +++ b/tests/support/Cargo.lock @@ -1801,9 +1801,12 @@ dependencies = [ name = "keycloak-support" version = "0.0.0" dependencies = [ + "base64 0.22.1", "openshell-testkit", "serde_json", + "tempfile", "tokio", + "url", ] [[package]] diff --git a/tests/support/keycloak/Cargo.toml b/tests/support/keycloak/Cargo.toml index 5a87bbccdc..7ec57ecd57 100644 --- a/tests/support/keycloak/Cargo.toml +++ b/tests/support/keycloak/Cargo.toml @@ -13,5 +13,8 @@ publish = false [dependencies] openshell-testkit = { path = "../../testkit/testkit" } +base64 = "0.22" serde_json = "1" -tokio = { version = "1.43", features = ["io-util", "process"] } +tempfile = "3" +tokio = { version = "1.43", features = ["fs", "io-util", "process", "time"] } +url = "2" diff --git a/tests/support/keycloak/src/browser.rs b/tests/support/keycloak/src/browser.rs new file mode 100644 index 0000000000..ec48ec4afb --- /dev/null +++ b/tests/support/keycloak/src/browser.rs @@ -0,0 +1,245 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The CLI's browser (PKCE) login, with curl in place of the browser. +//! +//! The CLI opens the authorization URL with `xdg-open`. A stand-in earlier +//! on `PATH` records the URL instead, and curl signs in on Keycloak's login +//! form, following the redirect to the CLI's loopback callback. + +use std::os::unix::fs::PermissionsExt as _; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use tempfile::TempDir; +use testkit::{Cli, CliOutput, Context, Error, Poll, Result, ResultExt as _, poll_until}; +use tokio::process::Command; +use url::Url; + +use crate::{Keycloak, User}; + +const URL_FILE_ENV: &str = "OPENSHELL_TEST_BROWSER_URL_FILE"; +/// How long the CLI has to discover the issuer and open the browser. +const URL_TIMEOUT: Duration = Duration::from_secs(15); +/// How long the CLI has to exchange the code and save the session after the +/// callback. +const FINISH_TIMEOUT: Duration = Duration::from_secs(30); +const CURL_MAX_TIME: &str = "10"; + +/// A finished `openshell gateway add --oidc-issuer` browser login. +pub struct BrowserLogin { + /// The URL the CLI opened in the browser. + pub authorization_url: Url, + /// The CLI's output from `gateway add`. + pub output: CliOutput, + /// The page the CLI's callback served after the login. + pub callback_page: String, + cli: Cli, + gateway_name: String, + config_home: TempDir, +} + +/// Register the test's gateway under its own name in a fresh CLI +/// configuration with `gateway add --oidc-issuer`, and sign in as `user` in +/// the browser it opens, asking for `scopes`. Fails if the login doesn't +/// reach the CLI's callback; the test checks the rest. +pub async fn browser_login( + cx: &Context, + keycloak: &Keycloak, + user: User, + scopes: &str, +) -> Result { + let (username, password) = keycloak.credentials(user)?; + let base = cx.cli_handle(); + let gateway = base.gateway().clone(); + let gateway_name = gateway.name.clone().ok_or_else(|| { + Error::msg("the browser login registers a named gateway; testkit has only an endpoint") + })?; + + let config_home = tempfile::tempdir().context("create a CLI config directory")?; + let bin = config_home.path().join("bin"); + let url_file = config_home.path().join("browser-url"); + install_xdg_open_recorder(&bin)?; + let cli = base + .with_env("XDG_CONFIG_HOME", config_home.path()) + .with_env("HOME", config_home.path()) + .without_env("OPENSHELL_NO_BROWSER") + .without_env("OPENSHELL_OIDC_CLIENT_SECRET"); + let login = cli + .clone() + .with_env("PATH", prepend_path(&bin)?) + .with_env(URL_FILE_ENV, &url_file) + .spawn([ + "gateway", + "add", + &gateway.endpoint, + "--name", + &gateway_name, + "--local", + "--oidc-issuer", + keycloak.issuer(), + "--oidc-client-id", + keycloak.client_id(), + "--oidc-scopes", + scopes, + ])?; + + let authorization_url = wait_for_url(&url_file).await?; + let cookies = config_home.path().join("keycloak-cookies"); + let login_page = curl(&["--cookie-jar"], &cookies, authorization_url.as_str(), &[]) + .await + .context("load the Keycloak login page")?; + let action = login_form_action(&login_page)?; + let callback_page = curl( + &["--location", "--cookie-jar"], + &cookies, + &action, + &[ + &format!("username={username}"), + &format!("password={password}"), + "credentialId=", + ], + ) + .await + .context("sign in on the Keycloak login page")?; + let output = login.output(FINISH_TIMEOUT).await?; + testkit::ensure!( + callback_page.contains("Authentication successful"), + "the CLI's callback did not report success:\n{callback_page}\n{}{}", + output.stdout, + output.stderr + ); + Ok(BrowserLogin { + authorization_url, + output, + callback_page, + cli, + gateway_name, + config_home, + }) +} + +impl BrowserLogin { + /// The CLI's directory for the registered gateway, holding + /// `metadata.json` and `oidc_token.json`. + pub fn gateway_dir(&self) -> PathBuf { + self.config_home + .path() + .join("openshell") + .join("gateways") + .join(&self.gateway_name) + } + + /// The CLI signed in by this login. It trusts the gateway's CA, which an + /// OIDC registration doesn't save, so a test can make calls with it. + pub fn cli(&self, cx: &Context) -> Result { + if let Some(mtls) = cx.cli_handle().gateway().mtls_dir() { + let target = self.gateway_dir().join("mtls"); + std::fs::create_dir_all(&target).context(format!("create {}", target.display()))?; + std::fs::copy(mtls.join("ca.crt"), target.join("ca.crt")) + .context(format!("copy the gateway CA from {}", mtls.display()))?; + } + Ok(self.cli.clone()) + } +} + +fn install_xdg_open_recorder(bin: &Path) -> Result { + std::fs::create_dir_all(bin).context(format!("create {}", bin.display()))?; + let script = bin.join("xdg-open"); + std::fs::write( + &script, + format!("#!/bin/sh\nset -eu\nprintf '%s\\n' \"$1\" > \"${URL_FILE_ENV}\"\n"), + ) + .context("write the xdg-open stand-in")?; + std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)) + .context("make the xdg-open stand-in executable") +} + +fn prepend_path(bin: &Path) -> Result { + let current = std::env::var_os("PATH").unwrap_or_default(); + std::env::join_paths(std::iter::once(bin.to_path_buf()).chain(std::env::split_paths(¤t))) + .map_err(|error| Error::msg(format!("build PATH: {error}"))) +} + +async fn wait_for_url(path: &Path) -> Result { + let url = poll_until( + "the CLI to open the authorization URL", + URL_TIMEOUT, + Duration::from_millis(100), + async || { + Ok(match tokio::fs::read_to_string(path).await { + Ok(contents) if !contents.trim().is_empty() => { + Poll::Ready(contents.trim().to_string()) + } + _ => Poll::Pending(format!("nothing in {}", path.display())), + }) + }, + ) + .await?; + Url::parse(&url) + .map_err(|error| Error::msg(format!("parse the authorization URL {url}: {error}"))) +} + +/// Request `url` with curl, keeping cookies in `jar`, and POST `form` if it +/// isn't empty. Returns the body. +async fn curl(options: &[&str], jar: &Path, url: &str, form: &[&str]) -> Result { + let mut command = Command::new("curl"); + command + .args([ + "--fail", + "--silent", + "--show-error", + "--max-time", + CURL_MAX_TIME, + ]) + .args(options) + .arg(jar) + .arg("--cookie") + .arg(jar); + for field in form { + command.args(["--data-urlencode", field]); + } + let output = command + .arg(url) + .kill_on_drop(true) + .output() + .await + .context("run curl")?; + testkit::ensure!( + output.status.success(), + "curl failed ({}): {}", + output.status, + String::from_utf8_lossy(&output.stderr).trim() + ); + Ok(String::from_utf8_lossy(&output.stdout).into_owned()) +} + +/// The URL Keycloak's login form posts to. +fn login_form_action(html: &str) -> Result { + let missing = || Error::msg(format!("no Keycloak login form in the page:\n{html}")); + let id = html.find("id=\"kc-form-login\"").ok_or_else(missing)?; + let start = html[..id].rfind("').ok_or_else(missing)?; + let tag = &html[start..end]; + let action = tag + .split_once("action=\"") + .and_then(|(_, rest)| rest.split_once('"')) + .map(|(action, _)| action) + .ok_or_else(missing)?; + Ok(action.replace("&", "&").replace("&", "&")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn finds_the_login_form_action() { + let html = r#"
"#; + assert_eq!( + login_form_action(html).unwrap(), + "http://kc/login?a=1&b=2&c=3" + ); + assert!(login_form_action("").is_err()); + } +} diff --git a/tests/support/keycloak/src/lib.rs b/tests/support/keycloak/src/lib.rs index 468cf29278..6ad295d790 100644 --- a/tests/support/keycloak/src/lib.rs +++ b/tests/support/keycloak/src/lib.rs @@ -15,9 +15,14 @@ //! | `OPENSHELL_TEST_KEYCLOAK_CLIENT_ID` | `openshell-cli` | //! | `OPENSHELL_TEST_KEYCLOAK_USERNAME` | `admin@test` | //! | `OPENSHELL_TEST_KEYCLOAK_PASSWORD` | `admin` | +//! | `OPENSHELL_TEST_KEYCLOAK_USER_USERNAME` | `user@test` | +//! | `OPENSHELL_TEST_KEYCLOAK_USER_PASSWORD` | `user` | +//! | `OPENSHELL_TEST_KEYCLOAK_USER_B_USERNAME` | `user-b@test` | +//! | `OPENSHELL_TEST_KEYCLOAK_USER_B_PASSWORD` | `user-b` | //! //! The issuer must be reachable from the test process. The client must allow -//! password grants. A missing variable fails the test; it never skips it. +//! password grants. The `USER` and `USER_B` variables name plain users, and +//! are read only by tests that sign in as them ([`User`]). A missing variable fails the test; it never skips it. //! The fixture waits for the realm to answer, since Keycloak may still be //! starting when the tests begin. //! @@ -33,6 +38,13 @@ //! } //! ``` //! +//! A suite whose gateway trusts the realm signs users in to it with +//! [`KeycloakContext::session`]: a [`Session`] holds an SDK client and a CLI +//! that send the user's token. [`browser_login`] runs the CLI's own browser +//! login once, with curl as the browser. The tmachine `-oidc` +//! environment (`tests/tmachine/ansible/playbooks/oidc.yaml`) runs such a +//! gateway. +//! //! The fixture owns no Keycloak state, so it has nothing to clean up. Tests //! that create resources in Keycloak or `OpenShell` must remove them, for //! example with [`Context::on_cleanup`]. @@ -47,10 +59,26 @@ use testkit::{Context, Error, Poll, Result, ResultExt as _, poll_until}; use tokio::io::AsyncWriteExt as _; use tokio::process::Command; +mod browser; +mod session; +mod token; + +pub use browser::{BrowserLogin, browser_login}; +pub use session::Session; +pub use token::{audience_contains, claims, has_realm_role, subject}; + pub const ISSUER_ENV: &str = "OPENSHELL_TEST_KEYCLOAK_ISSUER"; pub const CLIENT_ID_ENV: &str = "OPENSHELL_TEST_KEYCLOAK_CLIENT_ID"; pub const USERNAME_ENV: &str = "OPENSHELL_TEST_KEYCLOAK_USERNAME"; pub const PASSWORD_ENV: &str = "OPENSHELL_TEST_KEYCLOAK_PASSWORD"; +pub const USER_USERNAME_ENV: &str = "OPENSHELL_TEST_KEYCLOAK_USER_USERNAME"; +pub const USER_PASSWORD_ENV: &str = "OPENSHELL_TEST_KEYCLOAK_USER_PASSWORD"; +pub const USER_B_USERNAME_ENV: &str = "OPENSHELL_TEST_KEYCLOAK_USER_B_USERNAME"; +pub const USER_B_PASSWORD_ENV: &str = "OPENSHELL_TEST_KEYCLOAK_USER_B_PASSWORD"; +/// The scopes a login asks for so the gateway authorizes its token. The +/// `OpenShell` scopes are optional on the client, so Keycloak grants them +/// only when asked. +pub const OPENSHELL_SCOPES: &str = "openid profile email openshell:all"; /// How long Keycloak has to start answering, e.g. after the environment boots. // The wait runs inside the test, so it must leave room for the test body // within the runner's 2-minute per-test budget (`slow-timeout` in @@ -73,6 +101,29 @@ pub struct Keycloak { password: String, } +/// A user in the realm. [`User::Admin`] is the user the +/// `OPENSHELL_TEST_KEYCLOAK_USERNAME` variables name; the others are plain +/// users, read from their own variables only when a test logs in as them. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum User { + /// A platform admin. + Admin, + /// A user with no platform role beyond signing in. + User, + /// A second plain user, for tests across two users' workspaces. + UserB, +} + +impl User { + fn env(self) -> (&'static str, &'static str) { + match self { + Self::Admin => (USERNAME_ENV, PASSWORD_ENV), + Self::User => (USER_USERNAME_ENV, USER_PASSWORD_ENV), + Self::UserB => (USER_B_USERNAME_ENV, USER_B_PASSWORD_ENV), + } + } +} + /// Tokens from one Keycloak login. #[derive(Clone)] pub struct Grant { @@ -175,15 +226,36 @@ impl Keycloak { /// Log in as the configured user with the password grant. pub async fn password_grant(&self) -> Result { + self.grant(&self.username, &self.password, "openid").await + } + + /// Log in as `user` with the password grant, asking for `scope`, such + /// as [`OPENSHELL_SCOPES`]. + pub async fn password_grant_as(&self, user: User, scope: &str) -> Result { + let (username, password) = self.credentials(user)?; + self.grant(&username, &password, scope).await + } + + /// The username and password of `user`. + pub fn credentials(&self, user: User) -> Result<(String, String)> { + if user == User::Admin { + return Ok((self.username.clone(), self.password.clone())); + } + let (username, password) = user.env(); + Ok((required(username)?, required(password)?)) + } + + async fn grant(&self, username: &str, password: &str, scope: &str) -> Result { let client_id = format!("client_id={}", self.client_id); - let username = format!("username={}", self.username); + let username_field = format!("username={username}"); + let scope = format!("scope={scope}"); let stdout = post_form( &self.token_endpoint(), - &["grant_type=password", &client_id, &username, "scope=openid"], - ("password", &self.password), + &["grant_type=password", &client_id, &username_field, &scope], + ("password", password), ) .await - .context("Keycloak password grant")?; + .context(format!("Keycloak password grant for {username}"))?; let response: Value = serde_json::from_slice(&stdout).context("decode Keycloak grant response")?; diff --git a/tests/support/keycloak/src/session.rs b/tests/support/keycloak/src/session.rs new file mode 100644 index 0000000000..d98eda01cb --- /dev/null +++ b/tests/support/keycloak/src/session.rs @@ -0,0 +1,156 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! A user signed in to the gateway with a Keycloak token. + +use std::fmt; +use std::path::Path; + +use serde_json::json; +use tempfile::TempDir; +use testkit::sdk::OpenShellClient; +use testkit::{Cli, Context, Error, Result, ResultExt as _}; + +use crate::{Keycloak, KeycloakContext, OPENSHELL_SCOPES, User}; + +/// A realm user signed in to the test's gateway: an SDK client and a CLI +/// that send the user's access token. Both verify the gateway with its CA +/// and present no client certificate, so the gateway authorizes the user +/// alone. +/// +/// The token comes from the password grant and isn't refreshed. Keycloak's +/// access tokens outlast a test. +pub struct Session { + user: User, + username: String, + subject: String, + access_token: String, + client: OpenShellClient, + cli: Cli, + // The CLI's configuration, holding the token. Removed on drop. + _config_home: TempDir, +} + +impl KeycloakContext<'_> { + /// Sign `user` in to the test's gateway. See [`Session::login`]. + pub async fn session(&self, user: User) -> Result { + Session::login(self, self.keycloak(), user).await + } +} + +impl Session { + /// Log `user` in with the password grant and connect as them. + pub async fn login(cx: &Context, keycloak: &Keycloak, user: User) -> Result { + let (username, _) = keycloak.credentials(user)?; + let grant = keycloak.password_grant_as(user, OPENSHELL_SCOPES).await?; + let subject = crate::subject(&grant.access_token)?; + let base = cx.cli_handle(); + let gateway = base.gateway(); + let client = gateway + .connect_with_token(Some(&grant.access_token)) + .await + .context(format!("connect as {username}"))?; + let config_home = tempfile::tempdir().context("create a CLI config directory")?; + write_cli_session(config_home.path(), gateway, keycloak, &grant.access_token)?; + let cli = base.with_env("XDG_CONFIG_HOME", config_home.path()); + Ok(Self { + user, + username, + subject, + access_token: grant.access_token, + client, + cli, + _config_home: config_home, + }) + } + + pub fn user(&self) -> User { + self.user + } + + /// The Keycloak username, such as `user@test`. + pub fn username(&self) -> &str { + &self.username + } + + /// The token's subject, which names the user in workspace memberships. + pub fn subject(&self) -> &str { + &self.subject + } + + pub fn access_token(&self) -> &str { + &self.access_token + } + + /// An SDK client that sends the user's token. + pub fn client(&self) -> &OpenShellClient { + &self.client + } + + /// The CLI, signed in as the user, pointed at the test's workspace. + pub fn cli(&self) -> &Cli { + &self.cli + } + + /// The CLI, signed in as the user, pointed at `workspace`. + pub fn cli_in(&self, workspace: &str) -> Cli { + self.cli.clone().in_workspace(workspace) + } +} + +/// Write the CLI configuration `openshell gateway add --oidc-issuer` and a +/// login would: the registration, the token, and the gateway's CA, with no +/// client certificate. +fn write_cli_session( + config_home: &Path, + gateway: &testkit::Gateway, + keycloak: &Keycloak, + access_token: &str, +) -> Result { + let name = gateway.name.as_deref().ok_or_else(|| { + Error::msg("signing a user in to the CLI needs a registered gateway, not an endpoint") + })?; + let port = url::Url::parse(&gateway.endpoint) + .ok() + .and_then(|url| url.port_or_known_default()) + .ok_or_else(|| Error::msg(format!("no port in {}", gateway.endpoint)))?; + let dir = config_home.join("openshell").join("gateways").join(name); + std::fs::create_dir_all(&dir).context(format!("create {}", dir.display()))?; + let metadata = json!({ + "name": name, + "gateway_endpoint": gateway.endpoint, + "is_remote": false, + "gateway_port": port, + "auth_mode": "oidc", + "oidc_issuer": keycloak.issuer(), + "oidc_client_id": keycloak.client_id(), + "oidc_scopes": OPENSHELL_SCOPES, + }); + write(&dir.join("metadata.json"), &metadata.to_string())?; + let token = json!({ + "access_token": access_token, + "issuer": keycloak.issuer(), + "client_id": keycloak.client_id(), + }); + write(&dir.join("oidc_token.json"), &token.to_string())?; + if let Some(mtls) = gateway.mtls_dir() { + let target = dir.join("mtls"); + std::fs::create_dir_all(&target).context(format!("create {}", target.display()))?; + std::fs::copy(mtls.join("ca.crt"), target.join("ca.crt")) + .context(format!("copy the gateway CA from {}", mtls.display()))?; + } + Ok(()) +} + +fn write(path: &Path, contents: &str) -> Result { + std::fs::write(path, contents).context(format!("write {}", path.display())) +} + +impl fmt::Debug for Session { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Session") + .field("username", &self.username) + .field("subject", &self.subject) + .finish_non_exhaustive() + } +} diff --git a/tests/support/keycloak/src/token.rs b/tests/support/keycloak/src/token.rs new file mode 100644 index 0000000000..f0bdcd3634 --- /dev/null +++ b/tests/support/keycloak/src/token.rs @@ -0,0 +1,84 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Reading the claims in a Keycloak access token. + +use base64::Engine as _; +use base64::engine::general_purpose::URL_SAFE_NO_PAD; +use serde_json::Value; +use testkit::{Error, Result, ResultExt as _}; + +/// The claims in `token`, a JWT. The signature isn't checked: the token +/// comes from the test's own login, and the gateway checks it. +pub fn claims(token: &str) -> Result { + let payload = token + .split('.') + .nth(1) + .ok_or_else(|| Error::msg("the access token is not a JWT"))?; + let bytes = URL_SAFE_NO_PAD + .decode(payload.trim_end_matches('=')) + .map_err(|error| Error::msg(format!("decode the access token's claims: {error}")))?; + serde_json::from_slice(&bytes).context("parse the access token's claims") +} + +/// The `sub` claim in `token`: the subject the gateway names the user by, +/// such as in workspace memberships. +pub fn subject(token: &str) -> Result { + claims(token)? + .get("sub") + .and_then(Value::as_str) + .filter(|subject| !subject.is_empty()) + .map(str::to_string) + .ok_or_else(|| Error::msg("the access token has no subject")) +} + +/// Whether `claims` lists `role` among its realm roles +/// (`realm_access.roles`). +pub fn has_realm_role(claims: &Value, role: &str) -> bool { + claims["realm_access"]["roles"] + .as_array() + .is_some_and(|roles| roles.iter().any(|r| r == role)) +} + +/// Whether the `aud` claim, a string or a list, includes `audience`. +pub fn audience_contains(claims: &Value, audience: &str) -> bool { + match &claims["aud"] { + Value::String(value) => value == audience, + Value::Array(values) => values.iter().any(|value| value == audience), + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn jwt(claims: &Value) -> String { + let payload = URL_SAFE_NO_PAD.encode(serde_json::to_vec(claims).unwrap()); + format!("e30.{payload}.sig") + } + + #[test] + fn reads_claims() { + let token = jwt(&serde_json::json!({ + "sub": "abc", + "aud": ["account", "openshell-cli"], + "realm_access": {"roles": ["openshell-user"]}, + })); + let claims = claims(&token).unwrap(); + assert_eq!(subject(&token).unwrap(), "abc"); + assert!(has_realm_role(&claims, "openshell-user")); + assert!(!has_realm_role(&claims, "openshell-admin")); + assert!(audience_contains(&claims, "openshell-cli")); + assert!(audience_contains( + &serde_json::json!({"aud": "openshell-cli"}), + "openshell-cli" + )); + } + + #[test] + fn rejects_a_token_without_a_subject() { + assert!(subject(&jwt(&serde_json::json!({"sub": ""}))).is_err()); + assert!(claims("not-a-jwt").is_err()); + } +} From 922f1109e873ec31ef86e78770bb759de7618081 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:54:36 -0800 Subject: [PATCH 04/14] test(tmachine): add an OIDC gateway environment Signed-off-by: Matthew Grossman --- tests/support/README.md | 4 + tests/tmachine/ansible/playbooks/oidc.yaml | 24 ++++++ .../roles/oidc_gateway/defaults/main.yaml | 5 ++ .../files/operator-client-cert.sh | 47 +++++++++++ .../roles/oidc_gateway/tasks/main.yaml | 80 +++++++++++++++++++ tests/tmachine/config.nix | 12 +++ 6 files changed, 172 insertions(+) create mode 100644 tests/tmachine/ansible/playbooks/oidc.yaml create mode 100644 tests/tmachine/ansible/roles/oidc_gateway/defaults/main.yaml create mode 100755 tests/tmachine/ansible/roles/oidc_gateway/files/operator-client-cert.sh create mode 100644 tests/tmachine/ansible/roles/oidc_gateway/tasks/main.yaml diff --git a/tests/support/README.md b/tests/support/README.md index 7b7b0a775a..a4d0f7b92a 100644 --- a/tests/support/README.md +++ b/tests/support/README.md @@ -25,6 +25,10 @@ never skips it. Add a row when you add a variable. The runner also sets | `OPENSHELL_TEST_KEYCLOAK_CLIENT_ID` | `-keycloak` | `keycloak-support` | A client in that realm that allows password grants. | | `OPENSHELL_TEST_KEYCLOAK_USERNAME` | `-keycloak` | `keycloak-support` | The realm user that tests sign in as. | | `OPENSHELL_TEST_KEYCLOAK_PASSWORD` | `-keycloak` | `keycloak-support` | That user's password. | +| `OPENSHELL_TEST_KEYCLOAK_USER_USERNAME` | `-oidc` (`playbooks/oidc.yaml`) | `keycloak-support` (`User::User`) | A realm user with no platform admin role, which the gateway signs in. | +| `OPENSHELL_TEST_KEYCLOAK_USER_PASSWORD` | `-oidc` | `keycloak-support` | That user's password. | +| `OPENSHELL_TEST_KEYCLOAK_USER_B_USERNAME` | `-oidc` | `keycloak-support` (`User::UserB`) | A second such user, for tests across two users' workspaces. | +| `OPENSHELL_TEST_KEYCLOAK_USER_B_PASSWORD` | `-oidc` | `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`. | diff --git a/tests/tmachine/ansible/playbooks/oidc.yaml b/tests/tmachine/ansible/playbooks/oidc.yaml new file mode 100644 index 0000000000..bef53c3e2c --- /dev/null +++ b/tests/tmachine/ansible/playbooks/oidc.yaml @@ -0,0 +1,24 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Sign gateway users in with the Keycloak realm keycloak.yaml runs, which +# runs first, and publish the realm's plain users for the oidc-auth suite. +--- +- name: OIDC gateway for tests + hosts: all + gather_facts: false + vars_files: + - ../roles/keycloak/defaults/main.yaml + roles: + - oidc_gateway + tasks: + # The values are the throwaway fixture realm's (scripts/keycloak-realm.json). + - name: Publish OIDC test variables + ansible.builtin.include_tasks: test-env.yaml + vars: + test_env_name: oidc + test_env_vars: + OPENSHELL_TEST_KEYCLOAK_USER_USERNAME: user@test + OPENSHELL_TEST_KEYCLOAK_USER_PASSWORD: user + OPENSHELL_TEST_KEYCLOAK_USER_B_USERNAME: user-b@test + OPENSHELL_TEST_KEYCLOAK_USER_B_PASSWORD: user-b diff --git a/tests/tmachine/ansible/roles/oidc_gateway/defaults/main.yaml b/tests/tmachine/ansible/roles/oidc_gateway/defaults/main.yaml new file mode 100644 index 0000000000..1e20e5a1da --- /dev/null +++ b/tests/tmachine/ansible/roles/oidc_gateway/defaults/main.yaml @@ -0,0 +1,5 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +--- +oidc_gateway_operator_script: /usr/local/libexec/openshell-test/operator-client-cert diff --git a/tests/tmachine/ansible/roles/oidc_gateway/files/operator-client-cert.sh b/tests/tmachine/ansible/roles/oidc_gateway/files/operator-client-cert.sh new file mode 100755 index 0000000000..72f39ff410 --- /dev/null +++ b/tests/tmachine/ansible/roles/oidc_gateway/files/operator-client-cert.sh @@ -0,0 +1,47 @@ +#!/bin/sh +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Make the packaged gateway's client certificate an operator's (OU=operator), +# so testkit, which connects with it, keeps full access when the gateway also +# accepts OIDC users. Runs as an ExecStartPre after `generate-certs`, which may +# have replaced the certificate, and does nothing if it is already an +# operator's. It then copies the certificate where the CLI finds it, since +# `generate-certs` copies its own there on every start. +set -eu + +tls_dir=${OPENSHELL_LOCAL_TLS_DIR:?OPENSHELL_LOCAL_TLS_DIR is not set} +ca_cert=$tls_dir/ca.crt +ca_key=$tls_dir/ca.key +cert=$tls_dir/client/tls.crt +key=$tls_dir/client/tls.key + +is_operator() { + openssl verify -CAfile "$ca_cert" "$cert" >/dev/null 2>&1 && + openssl x509 -in "$cert" -noout -subject -nameopt RFC2253 | grep -q 'OU=operator' +} + +if ! is_operator; then + work=$(mktemp -d) + trap 'rm -rf "$work"' EXIT + openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out "$work/tls.key" + openssl req -new -key "$work/tls.key" \ + -subj "/O=openshell/OU=operator/CN=openshell-test-operator" -out "$work/tls.csr" + cat >"$work/ext.cnf" <<'EOF' +basicConstraints=CA:FALSE +keyUsage=critical,digitalSignature +extendedKeyUsage=clientAuth +EOF + openssl x509 -req -in "$work/tls.csr" -CA "$ca_cert" -CAkey "$ca_key" \ + -set_serial "0x$(openssl rand -hex 16)" -days 3650 \ + -extfile "$work/ext.cnf" -out "$work/tls.crt" + install -m 0600 "$work/tls.key" "$key" + install -m 0644 "$work/tls.crt" "$cert" + is_operator +fi + +cli_dir=${XDG_CONFIG_HOME:-$HOME/.config}/openshell/gateways/openshell/mtls +mkdir -p "$cli_dir" +install -m 0644 "$ca_cert" "$cli_dir/ca.crt" +install -m 0644 "$cert" "$cli_dir/tls.crt" +install -m 0600 "$key" "$cli_dir/tls.key" diff --git a/tests/tmachine/ansible/roles/oidc_gateway/tasks/main.yaml b/tests/tmachine/ansible/roles/oidc_gateway/tasks/main.yaml new file mode 100644 index 0000000000..1a7666c7ca --- /dev/null +++ b/tests/tmachine/ansible/roles/oidc_gateway/tasks/main.yaml @@ -0,0 +1,80 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Make the packaged gateway trust the environment's Keycloak realm (the +# keycloak role) and keep testkit's mTLS connection working as an operator. +# +# With an OIDC issuer set, the gateway maps a client certificate to a user +# only when mTLS user authentication is on, and that user has no platform +# role. An operator certificate (OU=operator) has full access instead, so +# testkit's setup and cleanup work. The operator script re-signs the +# packaged gateway's client certificate on every start, after +# `generate-certs`, through a drop-in on the gateway's systemd user unit. +# Only the deb and rpm installers run that unit. +--- +- name: Detect the gateway user + ansible.builtin.include_role: + name: openshell_gateway + tasks_from: detect.yaml + +- name: Trust the Keycloak realm and operator certificates + ansible.builtin.include_role: + name: gateway_overrides + vars: + gateway_overrides_name: oidc + gateway_overrides_content: | + [openshell.gateway.oidc] + issuer = "http://127.0.0.1:{{ keycloak_port }}/realms/{{ keycloak_realm }}" + dangerously_allow_insecure_http = true + audience = "openshell-cli" + jwks_ttl_secs = 60 + roles_claim = "realm_access.roles" + admin_role = "openshell-admin" + user_role = "openshell-user" + scopes_claim = "scope" + + [openshell.gateway.mtls_auth] + operator_enabled = true + +- name: Create the test scripts directory + become: true + ansible.builtin.file: + path: "{{ oidc_gateway_operator_script | dirname }}" + state: directory + owner: root + group: root + mode: "0755" + +- name: Install the operator certificate script + become: true + ansible.builtin.copy: + src: operator-client-cert.sh + dest: "{{ oidc_gateway_operator_script }}" + owner: root + group: root + mode: "0755" + +- name: Create the gateway unit's drop-in directory + become: true + ansible.builtin.file: + path: "{{ openshell_gateway_home }}/{{ item }}" + state: directory + owner: "{{ openshell_gateway_user }}" + group: "{{ openshell_gateway_user }}" + mode: "0755" + loop: + - .config + - .config/systemd + - .config/systemd/user + - .config/systemd/user/openshell-gateway.service.d + +- name: Run the operator certificate script before the gateway starts + become: true + ansible.builtin.copy: + dest: "{{ openshell_gateway_home }}/.config/systemd/user/openshell-gateway.service.d/oidc-operator.conf" + owner: "{{ openshell_gateway_user }}" + group: "{{ openshell_gateway_user }}" + mode: "0644" + content: | + [Service] + ExecStartPre={{ oidc_gateway_operator_script }} diff --git a/tests/tmachine/config.nix b/tests/tmachine/config.nix index ed62c23eb6..8b64376cb2 100644 --- a/tests/tmachine/config.nix +++ b/tests/tmachine/config.nix @@ -109,6 +109,18 @@ let inputs.keycloak_realm_file = "../../scripts/keycloak-realm.json"; }; }; + # Keycloak plus a gateway that signs users in with it, for the oidc-auth + # suite. Needs the deb or rpm installer, whose gateway runs mTLS. + oidc = { + bases = dockerBases; + setup = { + playbooks = [ + "ansible/playbooks/keycloak.yaml" + "ansible/playbooks/oidc.yaml" + ]; + inputs.keycloak_realm_file = "../../scripts/keycloak-realm.json"; + }; + }; # Hardware-free CDI fixtures, for the cdi suite. cdi = { bases = dockerBases ++ podmanBases; From 7ae93ae199b27b2e95caf940977333f319cf59fa Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 16:54:36 -0800 Subject: [PATCH 05/14] docs(keycloak-support): note where the extra users come from Signed-off-by: Matthew Grossman --- tests/support/keycloak/src/lib.rs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/support/keycloak/src/lib.rs b/tests/support/keycloak/src/lib.rs index 6ad295d790..205ecb8abc 100644 --- a/tests/support/keycloak/src/lib.rs +++ b/tests/support/keycloak/src/lib.rs @@ -22,7 +22,8 @@ //! //! The issuer must be reachable from the test process. The client must allow //! password grants. The `USER` and `USER_B` variables name plain users, and -//! are read only by tests that sign in as them ([`User`]). A missing variable fails the test; it never skips it. +//! are read only by tests that sign in as them ([`User`]). The tmachine +//! `-oidc` environment publishes them (`playbooks/oidc.yaml`). A missing variable fails the test; it never skips it. //! The fixture waits for the realm to answer, since Keycloak may still be //! starting when the tests begin. //! From 5433d0d83a33b31fe25c005a8bc71e2081783558 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:06:48 -0800 Subject: [PATCH 06/14] feat(testkit): track a workspace's sandboxes, providers and profiles Signed-off-by: Matthew Grossman --- tests/testkit/README.md | 3 + tests/testkit/testkit/src/context.rs | 6 +- tests/testkit/testkit/src/workspace.rs | 77 +++++++++++++++++++++++++- 3 files changed, 83 insertions(+), 3 deletions(-) diff --git a/tests/testkit/README.md b/tests/testkit/README.md index 91d2d8b023..7777fa2fa2 100644 --- a/tests/testkit/README.md +++ b/tests/testkit/README.md @@ -126,6 +126,9 @@ fails. A killed test process skips cleanup, so names are unique to the run. bearer token, such as an OIDC access token, and no client certificate. - `cx.workspace(suffix)` to create a workspace with cleanup. Its `add_member(subject, role)` and `remove_member(subject)` manage members. + `track_sandbox(name)` and `track_provider(name)` delete what another + identity creates in it; call them before the create. `import_profile(yaml)` + imports a provider profile into it. - `cx.on_cleanup(name, hook)` to remove something when the test ends. - `testkit::policy` for sandbox policies: `policy::base()` reads `testkit/src/base-policy.yaml`, which allows no network access, and diff --git a/tests/testkit/testkit/src/context.rs b/tests/testkit/testkit/src/context.rs index 5739212759..ad75be85e0 100644 --- a/tests/testkit/testkit/src/context.rs +++ b/tests/testkit/testkit/src/context.rs @@ -176,6 +176,10 @@ impl Context { &self.handles.grpc.client } + pub(crate) fn cleanup_list(&self) -> &Cleanup { + &self.handles.cleanup + } + /// A resource name unique to this run: `test--`. /// /// Sandbox names can't exceed [`MAX_SANDBOX_NAME_LEN`], so a sandbox @@ -360,7 +364,7 @@ fn single_compute_driver(info: &proto::GetGatewayInfoResponse) -> Result /// Register the cleanup hook that deletes sandbox `name`, unless it is /// already tracked. -fn track_sandbox(cleanup: &Cleanup, client: &WorkspaceScopedClient, name: &str) { +pub(crate) fn track_sandbox(cleanup: &Cleanup, client: &WorkspaceScopedClient, name: &str) { let client = client.clone(); let owned = name.to_string(); // The timeout wraps the whole hook, not just the wait, so a gateway that diff --git a/tests/testkit/testkit/src/workspace.rs b/tests/testkit/testkit/src/workspace.rs index 37263a6bf4..c7e5711dbc 100644 --- a/tests/testkit/testkit/src/workspace.rs +++ b/tests/testkit/testkit/src/workspace.rs @@ -9,8 +9,13 @@ use std::time::{Duration, Instant}; use openshell_sdk::raw::proto; use openshell_sdk::{DeleteOptions, OpenShellClient}; -use crate::context::Context; +use serde::Deserialize; + +use crate::cleanup::Cleanup; +use crate::cli::Cli; +use crate::context::{Context, track_sandbox}; use crate::error::{Error, Result, ResultExt as _}; +use crate::yaml_file::YamlFile; /// The longest workspace name the gateway accepts. const MAX_WORKSPACE_NAME_LEN: usize = 19; @@ -45,7 +50,12 @@ impl Context { .create_workspace(&name, HashMap::new()) .await .context(format!("create workspace {name}"))?; - Ok(Workspace { name, client }) + Ok(Workspace { + cli: self.cli_handle().in_workspace(&name), + name, + client, + cleanup: self.cleanup_list().clone(), + }) } } @@ -54,6 +64,8 @@ impl Context { pub struct Workspace { name: String, client: OpenShellClient, + cli: Cli, + cleanup: Cleanup, } impl Workspace { @@ -61,6 +73,67 @@ impl Workspace { &self.name } + /// Delete sandbox `name` in the workspace when the test ends, before the + /// workspace. Call it before the sandbox is created, by whoever creates + /// it, so cleanup deletes it even if the test fails first. + pub fn track_sandbox(&self, name: &str) { + track_sandbox(&self.cleanup, &self.client.workspace(&self.name), name); + } + + /// Delete provider `name` in the workspace when the test ends, before the + /// workspace. Call it before the provider is created. + pub fn track_provider(&self, name: &str) { + let client = self.client.clone(); + let workspace = self.name.clone(); + let owned = name.to_string(); + self.cleanup.push( + format!("delete provider {name} in workspace {workspace}"), + async move || { + client + .raw_grpc_fresh() + .await? + .delete_provider(proto::DeleteProviderRequest { + workspace_scope: Some(proto::workspace_selector(&workspace)), + name: owned, + allow_missing: true, + request_id: String::new(), + }) + .await?; + Ok(()) + }, + ); + } + + /// Import `profile`, a provider profile in YAML, into the workspace and + /// return its `id`. Cleanup deletes it after the workspace's providers. + pub async fn import_profile(&self, profile: &str) -> Result { + #[derive(Deserialize)] + struct Profile { + id: String, + } + let id = serde_yml::from_str::(profile) + .context("read the provider profile's id")? + .id; + // Deleting a missing profile succeeds, so register the delete before + // the import. + let cli = self.cli.clone(); + let owned = id.clone(); + self.cleanup.push( + format!("delete profile {id} in workspace {}", self.name), + async move || { + cli.run(["profile", "delete", &owned]).await?.success()?; + Ok(()) + }, + ); + let file = YamlFile::new(profile)?; + self.cli + .run(["profile", "import", "--file", file.path()?]) + .await? + .success() + .context(format!("import profile {id} into workspace {}", self.name))?; + Ok(id) + } + /// Make `subject`, an OIDC subject claim, a member with `role`. pub async fn add_member(&self, subject: &str, role: proto::WorkspaceRole) -> Result { self.client From 92ce6533d86411a1b8662b76adfbad7bcd61bbb8 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:06:48 -0800 Subject: [PATCH 07/14] test(oidc-auth): port the OIDC authorization tests to testkit Signed-off-by: Matthew Grossman --- .github/workflows/e2e-suites.yml | 1 + tests/suites/features/Cargo.lock | 13 + tests/suites/features/Cargo.toml | 2 +- tests/suites/features/oidc-auth/Cargo.toml | 18 + .../features/oidc-auth/tests/oidc_auth.rs | 1014 +++++++++++++++++ 5 files changed, 1047 insertions(+), 1 deletion(-) create mode 100644 tests/suites/features/oidc-auth/Cargo.toml create mode 100644 tests/suites/features/oidc-auth/tests/oidc_auth.rs diff --git a/.github/workflows/e2e-suites.yml b/.github/workflows/e2e-suites.yml index c84837c976..6dc9556668 100644 --- a/.github/workflows/e2e-suites.yml +++ b/.github/workflows/e2e-suites.yml @@ -103,6 +103,7 @@ jobs: {"environment":"fedora-podman-rootful-cdi","installer":"rpm","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootless-cdi","installer":"rpm","family":"features","package":"cdi","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful-keycloak","installer":"deb","family":"features","package":"keycloak-provider-refresh","gateway":"openshell","runner":"ubuntu-24.04"}, + {"environment":"ubuntu-docker-rootful-oidc","installer":"deb","family":"features","package":"oidc-auth","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"ubuntu-docker-rootful","installer":"deb","family":"features","package":"oci-image","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootful","installer":"rpm","family":"features","package":"oci-image","gateway":"openshell","runner":"ubuntu-24.04"}, {"environment":"fedora-podman-rootless","installer":"rpm","family":"features","package":"oci-image","gateway":"openshell","runner":"ubuntu-24.04"}, diff --git a/tests/suites/features/Cargo.lock b/tests/suites/features/Cargo.lock index 04592b09f0..b09c3c2fa2 100644 --- a/tests/suites/features/Cargo.lock +++ b/tests/suites/features/Cargo.lock @@ -1845,9 +1845,12 @@ dependencies = [ name = "keycloak-support" version = "0.0.0" dependencies = [ + "base64 0.22.1", "openshell-testkit", "serde_json", + "tempfile", "tokio", + "url", ] [[package]] @@ -2310,6 +2313,16 @@ dependencies = [ "asn1-rs", ] +[[package]] +name = "oidc-auth" +version = "0.0.0" +dependencies = [ + "keycloak-support", + "openshell-testkit", + "serde_json", + "url", +] + [[package]] name = "once_cell" version = "1.21.4" diff --git a/tests/suites/features/Cargo.toml b/tests/suites/features/Cargo.toml index 7c7fe40ae7..b628972928 100644 --- a/tests/suites/features/Cargo.toml +++ b/tests/suites/features/Cargo.toml @@ -3,4 +3,4 @@ [workspace] resolver = "2" -members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "oci-image", "routable-host-ip"] +members = ["cdi", "connect-ssh-supervision", "docker-updates", "host-gateway", "keycloak-provider-refresh", "kubernetes-updates", "oci-image", "oidc-auth", "routable-host-ip"] diff --git a/tests/suites/features/oidc-auth/Cargo.toml b/tests/suites/features/oidc-auth/Cargo.toml new file mode 100644 index 0000000000..da7c0c8780 --- /dev/null +++ b/tests/suites/features/oidc-auth/Cargo.toml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "oidc-auth" +description = "Features suite: OIDC sign-in and workspace authorization against Keycloak" +version = "0.0.0" +edition = "2024" +rust-version = "1.94" +license = "Apache-2.0" +repository = "https://github.com/NVIDIA/OpenShell" +publish = false + +[dependencies] +keycloak-support = { path = "../../../support/keycloak" } +openshell-testkit = { path = "../../../testkit/testkit" } +serde_json = "1" +url = "2" diff --git a/tests/suites/features/oidc-auth/tests/oidc_auth.rs b/tests/suites/features/oidc-auth/tests/oidc_auth.rs new file mode 100644 index 0000000000..4433660168 --- /dev/null +++ b/tests/suites/features/oidc-auth/tests/oidc_auth.rs @@ -0,0 +1,1014 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! OIDC sign-in and workspace authorization against Keycloak. +//! +//! The gateway trusts the environment's Keycloak realm. Each test signs realm +//! users in with the password grant and checks what the gateway lets them +//! do, by gRPC status code and message. testkit's own connection is an mTLS +//! operator, which sets up and cleans up. The browser login runs once, and +//! a few checks run through the CLI, for what the CLI itself reports. + +use std::collections::HashMap; +use std::fmt; + +use keycloak_support::{BrowserLogin, KeycloakContext, OPENSHELL_SCOPES, Session, User}; +use serde_json::Value; +use testkit::sdk::raw::{AuthedGrpcClient, proto}; +use testkit::sdk::{DeleteOptions, ListOptions, OpenShellClient, SandboxSpec}; +use testkit::{ + Context, Credential, DELETE_TIMEOUT, Error, GrpcCode, Profile, Result, ResultExt as _, YamlFile, +}; +use url::Url; + +const ADMIN_ROLE_REQUIRED: &str = "role 'openshell-admin' required"; +const ONLY_PLATFORM_ADMINS: &str = "only platform admins can assign the workspace admin role"; +/// The provider credential the test profile defines. +const CREDENTIAL_ENV: &str = "API_KEY"; +const CREDENTIAL_VALUE: &str = "oidc-auth-test-value"; +/// A subject no realm user has. +const FAKE_SUBJECT: &str = "oidc-fake-member"; + +/// The browser (PKCE) login: the CLI opens Keycloak's authorization page +/// with a PKCE challenge, receives the code on its loopback callback, and +/// saves a session the gateway accepts. +#[testkit::test] +async fn pkce_browser_login_persists_session(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let login = keycloak_support::browser_login( + &kc, + kc.keycloak(), + User::User, + "profile email openshell:all", + ) + .await?; + check_authorization_url(&login.authorization_url, kc.keycloak().issuer())?; + let report = format!("{}{}", login.output.stdout, login.output.stderr); + testkit::ensure!( + report.contains("Authenticated successfully"), + "gateway add did not report the login:\n{report}" + ); + let subject = check_saved_session(&login, &kc)?; + + let whoami = login + .cli(&kc)? + .run(["whoami", "--output", "json"]) + .await? + .success()?; + let identity = json_object(&whoami.stdout)?; + testkit::ensure!( + identity["subject"] == subject.as_str(), + "whoami with the saved session reported {identity}, expected subject {subject}" + ); + Ok(()) +} + +/// `whoami` reports the identity the gateway validated from the token. +#[testkit::test] +async fn user_reports_gateway_validated_identity(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let user = kc.session(User::User).await?; + let output = user + .cli() + .run(["whoami", "--output", "json"]) + .await? + .success()?; + let identity = json_object(&output.stdout)?; + testkit::ensure!( + identity["subject"] == user.subject() + && identity["identity_provider"] == "oidc" + && identity["roles"] + .as_array() + .is_some_and(|roles| roles.iter().any(|role| role == "openshell-user")), + "whoami reported {identity}, expected subject {}, provider oidc and role openshell-user", + user.subject() + ); + Ok(()) +} + +/// A platform admin lists sandboxes and providers in a workspace it isn't a +/// member of, reads gateway info, manages a provider, and creates a +/// workspace. +#[testkit::test] +async fn platform_admin_smoke(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let ws = kc.workspace("adm").await?; + let profile = ws.import_profile(&test_profile(&kc.name("pf"))?).await?; + let admin = kc.session(User::Admin).await?; + let mut grpc = raw(&admin).await?; + + admin + .client() + .workspace(ws.name()) + .list_all_sandboxes(ListOptions::default()) + .await + .context("list sandboxes as platform admin")?; + grpc.list_providers(list_providers(ws.name())) + .await + .context("list providers as platform admin")?; + + let info = grpc + .get_gateway_info(proto::GetGatewayInfoRequest {}) + .await + .context("get gateway info as platform admin")? + .into_inner(); + let driver = kc.compute_driver().await?; + testkit::ensure!( + info.compute_drivers.iter().any(|d| d.name == driver), + "gateway info for the platform admin lists drivers {:?}, expected {driver}", + info.compute_drivers + .iter() + .map(|d| d.name.as_str()) + .collect::>() + ); + + let provider = kc.name("prov"); + ws.track_provider(&provider); + grpc.create_provider(provider_request(ws.name(), &provider, &profile)) + .await + .context("create a provider as platform admin")?; + let got = grpc + .get_provider(proto::GetProviderRequest { + workspace_scope: Some(proto::workspace_selector(ws.name())), + name: provider.clone(), + }) + .await + .context("get the provider as platform admin")? + .into_inner(); + let got_name = got + .provider + .and_then(|p| p.metadata) + .map(|m| m.name) + .unwrap_or_default(); + testkit::ensure!( + got_name == provider, + "provider get returned {got_name:?}, expected {provider}" + ); + grpc.delete_provider(delete_provider(ws.name(), &provider)) + .await + .context("delete the provider as platform admin")?; + + let created = kc.name("admw"); + delete_workspace_on_cleanup(&kc, admin.client(), &created); + admin + .client() + .create_workspace(&created, HashMap::new()) + .await + .context("create a workspace as platform admin")?; + let got = admin.client().get_workspace(&created).await?; + testkit::ensure!( + got.name == created, + "workspace get returned {}, expected {created}", + got.name + ); + Ok(()) +} + +/// Neither a plain user nor a workspace admin may read gateway info, or +/// create or delete workspaces. +#[testkit::test] +async fn non_admins_denied_platform_actions(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let ws = kc.workspace("pla").await?; + let admin = kc.session(User::Admin).await?; + let user = kc.session(User::User).await?; + let ws_admin = kc.session(User::UserB).await?; + ws.add_member(ws_admin.subject(), proto::WorkspaceRole::Admin) + .await?; + + for (who, session) in [("user", &user), ("workspace admin", &ws_admin)] { + let mut grpc = raw(session).await?; + expect_denied( + grpc.get_gateway_info(proto::GetGatewayInfoRequest {}).await, + ADMIN_ROLE_REQUIRED, + format!("get gateway info as {who}"), + )?; + let created = kc.name(if who == "user" { "nwu" } else { "nwa" }); + delete_workspace_on_cleanup(&kc, admin.client(), &created); + expect_denied( + session + .client() + .create_workspace(&created, HashMap::new()) + .await, + ADMIN_ROLE_REQUIRED, + format!("create a workspace as {who}"), + )?; + expect_denied( + session + .client() + .delete_workspace(ws.name(), DeleteOptions::default()) + .await, + ADMIN_ROLE_REQUIRED, + format!("delete workspace {} as {who}", ws.name()), + )?; + } + admin.client().get_workspace(ws.name()).await?; + Ok(()) +} + +/// Members, as users or admins, read their workspace, its members, its +/// sandboxes and its providers, and see it in their workspace list. +#[testkit::test] +async fn workspace_user_read_access(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let user = kc.session(User::User).await?; + for (suffix, role) in [ + ("rdu", proto::WorkspaceRole::User), + ("rda", proto::WorkspaceRole::Admin), + ] { + let ws = kc.workspace(suffix).await?; + ws.add_member(user.subject(), role).await?; + let action = |what: &str| format!("{what} as a workspace {}", role.as_str_name()); + + let got = user + .client() + .get_workspace(ws.name()) + .await + .context(action("get the workspace"))?; + testkit::ensure!(got.name == ws.name(), "workspace get returned {}", got.name); + let listed = user + .client() + .list_all_workspaces(ListOptions::default()) + .await + .context(action("list workspaces"))?; + testkit::ensure!( + listed.iter().any(|w| w.name == ws.name()), + "{} is missing from the member's workspace list", + ws.name() + ); + let members = members(&mut raw(&user).await?, ws.name()) + .await + .context(action("list members"))?; + testkit::ensure!( + members.iter().any(|m| m == user.subject()), + "the member list of {} is missing {}: {members:?}", + ws.name(), + user.subject() + ); + user.client() + .workspace(ws.name()) + .list_all_sandboxes(ListOptions::default()) + .await + .context(action("list sandboxes"))?; + raw(&user) + .await? + .list_providers(list_providers(ws.name())) + .await + .context(action("list providers"))?; + } + Ok(()) +} + +/// A platform admin and a workspace user each create a sandbox in the +/// workspace, see it listed, and delete it. +#[testkit::test] +async fn sandbox_create_delete_by_role(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let ws = kc.workspace("sbx").await?; + let admin = kc.session(User::Admin).await?; + let user = kc.session(User::User).await?; + ws.add_member(user.subject(), proto::WorkspaceRole::User) + .await?; + + for (suffix, session) in [("sba", &admin), ("sbu", &user)] { + let name = kc.name(suffix); + let client = session.client().workspace(ws.name()); + let who = session.username(); + ws.track_sandbox(&name); + // Keep the sandbox running, so this checks authorization rather + // than how fast a finished command's sandbox goes. + client + .create_sandbox(SandboxSpec { + name: Some(name.clone()), + command: vec!["sleep".to_string(), "infinity".to_string()], + ..SandboxSpec::default() + }) + .await + .context(format!("create sandbox {name} as {who}"))?; + let listed = sandbox_names(&client.list_all_sandboxes(ListOptions::default()).await?); + testkit::ensure!( + listed.contains(&name), + "{who}'s sandbox list is missing {name}: {listed:?}" + ); + client + .delete_sandbox(&name, DeleteOptions::default()) + .await + .context(format!("delete sandbox {name} as {who}"))?; + client.wait_deleted(&name, DELETE_TIMEOUT, None).await?; + let listed = sandbox_names(&client.list_all_sandboxes(ListOptions::default()).await?); + testkit::ensure!( + !listed.contains(&name), + "{name} is still listed after {who} deleted it: {listed:?}" + ); + } + Ok(()) +} + +/// A workspace user may not create or delete providers, or manage members. +/// The CLI tells them how to get the admin role. +#[testkit::test] +async fn workspace_user_denied_management(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let ws = kc.workspace("wum").await?; + let profile = ws.import_profile(&test_profile(&kc.name("pf"))?).await?; + let admin = kc.session(User::Admin).await?; + let user = kc.session(User::User).await?; + ws.add_member(user.subject(), proto::WorkspaceRole::User) + .await?; + let target = kc.name("tgt"); + ws.track_provider(&target); + raw(&admin) + .await? + .create_provider(provider_request(ws.name(), &target, &profile)) + .await + .context("create the provider to delete")?; + + let needs_admin = format!( + "workspace role 'admin' required in workspace '{}'", + ws.name() + ); + let mut grpc = raw(&user).await?; + let created = kc.name("new"); + ws.track_provider(&created); + expect_denied( + grpc.create_provider(provider_request(ws.name(), &created, &profile)) + .await, + &needs_admin, + "create a provider as a workspace user", + )?; + expect_denied( + grpc.delete_provider(delete_provider(ws.name(), &target)) + .await, + &needs_admin, + "delete a provider as a workspace user", + )?; + expect_denied( + grpc.add_workspace_member(add_member( + ws.name(), + FAKE_SUBJECT, + proto::WorkspaceRole::User, + )) + .await, + &needs_admin, + "add a member as a workspace user", + )?; + raw(&admin) + .await? + .get_provider(proto::GetProviderRequest { + workspace_scope: Some(proto::workspace_selector(ws.name())), + name: target.clone(), + }) + .await + .context("the denied delete left the provider")?; + + let denied = user + .cli_in(ws.name()) + .run([ + "workspace", + "member", + "add", + "--workspace", + ws.name(), + "--subject", + FAKE_SUBJECT, + "--role", + "user", + ]) + .await? + .failure()?; + let report = compact(&denied.report_text()); + let remediation = compact(&format!( + "openshell workspace member add --workspace '{}' --subject '{}' --role admin", + ws.name(), + user.subject() + )); + testkit::ensure!( + report.contains(&compact("workspace role 'admin'")) && report.contains(&remediation), + "the denial does not tell the user how to get the admin role:\n{}", + denied.report_text() + ); + Ok(()) +} + +/// A workspace admin creates and deletes providers and adds and removes +/// members. A removed member, by the workspace admin or a platform admin, +/// loses access. +#[testkit::test] +async fn workspace_admin_manages_providers_and_members(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let ws = kc.workspace("wam").await?; + let profile = ws.import_profile(&test_profile(&kc.name("pf"))?).await?; + let admin = kc.session(User::Admin).await?; + let ws_admin = kc.session(User::User).await?; + let member = kc.session(User::UserB).await?; + ws.add_member(ws_admin.subject(), proto::WorkspaceRole::Admin) + .await?; + let mut grpc = raw(&ws_admin).await?; + + let created = kc.name("own"); + ws.track_provider(&created); + grpc.create_provider(provider_request(ws.name(), &created, &profile)) + .await + .context("create a provider as workspace admin")?; + let target = kc.name("tgt"); + ws.track_provider(&target); + raw(&admin) + .await? + .create_provider(provider_request(ws.name(), &target, &profile)) + .await + .context("create the provider to delete")?; + grpc.delete_provider(delete_provider(ws.name(), &target)) + .await + .context("delete a provider as workspace admin")?; + + grpc.add_workspace_member(add_member( + ws.name(), + member.subject(), + proto::WorkspaceRole::User, + )) + .await + .context("add a member as workspace admin")?; + let listed = members(&mut grpc, ws.name()).await?; + testkit::ensure!( + listed.iter().any(|m| m == member.subject()), + "the added member is not listed: {listed:?}" + ); + member + .client() + .get_workspace(ws.name()) + .await + .context("get the workspace as the added member")?; + + let not_member = format!("not a member of workspace '{}'", ws.name()); + grpc.remove_workspace_member(remove_member(ws.name(), member.subject())) + .await + .context("remove a member as workspace admin")?; + expect_denied( + member.client().get_workspace(ws.name()).await, + ¬_member, + "get the workspace after the workspace admin removed the member", + )?; + + raw(&admin) + .await? + .add_workspace_member(add_member( + ws.name(), + member.subject(), + proto::WorkspaceRole::User, + )) + .await + .context("add the member back as platform admin")?; + raw(&admin) + .await? + .remove_workspace_member(remove_member(ws.name(), member.subject())) + .await + .context("remove the member as platform admin")?; + expect_denied( + member.client().get_workspace(ws.name()).await, + ¬_member, + "get the workspace after a platform admin removed the member", + )?; + Ok(()) +} + +/// Only a platform admin may make a member a workspace admin. +#[testkit::test] +async fn workspace_admin_cannot_grant_admin(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let ws = kc.workspace("wag").await?; + let ws_admin = kc.session(User::User).await?; + ws.add_member(ws_admin.subject(), proto::WorkspaceRole::Admin) + .await?; + let mut grpc = raw(&ws_admin).await?; + expect_denied( + grpc.add_workspace_member(add_member( + ws.name(), + FAKE_SUBJECT, + proto::WorkspaceRole::Admin, + )) + .await, + ONLY_PLATFORM_ADMINS, + "grant the workspace admin role as workspace admin", + )?; + let listed = members(&mut grpc, ws.name()).await?; + testkit::ensure!( + !listed.iter().any(|m| m == FAKE_SUBJECT), + "the denied grant added a member: {listed:?}" + ); + Ok(()) +} + +/// Being an admin or a user of one workspace gives no access to another. +#[testkit::test] +async fn cross_workspace_access_denied(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let ws_a = kc.workspace("xa").await?; + let ws_b = kc.workspace("xb").await?; + let admin = kc.session(User::Admin).await?; + let user = kc.session(User::User).await?; + let user_b = kc.session(User::UserB).await?; + ws_b.add_member(user_b.subject(), proto::WorkspaceRole::User) + .await?; + let b = ws_b.name(); + let not_member = format!("not a member of workspace '{b}'"); + + for (suffix, role) in [ + ("xsa", proto::WorkspaceRole::Admin), + ("xsu", proto::WorkspaceRole::User), + ] { + ws_a.add_member(user.subject(), role).await?; + let who = format!("a workspace {} of {}", role.as_str_name(), ws_a.name()); + let mut grpc = raw(&user).await?; + let client = user.client(); + + expect_denied( + client.get_workspace(b).await, + ¬_member, + format!("get {b} as {who}"), + )?; + expect_denied( + grpc.list_workspace_members(list_members(b)).await, + ¬_member, + format!("list the members of {b} as {who}"), + )?; + expect_denied( + grpc.add_workspace_member(add_member(b, FAKE_SUBJECT, proto::WorkspaceRole::User)) + .await, + ¬_member, + format!("add a member to {b} as {who}"), + )?; + expect_denied( + client + .workspace(b) + .list_all_sandboxes(ListOptions::default()) + .await, + ¬_member, + format!("list the sandboxes in {b} as {who}"), + )?; + expect_denied( + grpc.list_providers(list_providers(b)).await, + ¬_member, + format!("list the providers in {b} as {who}"), + )?; + let sandbox = kc.name(suffix); + ws_b.track_sandbox(&sandbox); + expect_denied( + client + .workspace(b) + .create_sandbox(SandboxSpec { + name: Some(sandbox.clone()), + command: vec!["sleep".to_string(), "infinity".to_string()], + ..SandboxSpec::default() + }) + .await, + ¬_member, + format!("create a sandbox in {b} as {who}"), + )?; + ws_a.remove_member(user.subject()).await?; + } + + let listed = sandbox_names( + &admin + .client() + .workspace(b) + .list_all_sandboxes(ListOptions::default()) + .await?, + ); + testkit::ensure!( + listed.is_empty(), + "the denied creates left sandboxes in {b}: {listed:?}" + ); + Ok(()) +} + +/// A user's workspace list shows their own workspace and hides another +/// user's and `default`. +#[testkit::test] +async fn workspace_list_hides_other_workspaces(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let ws_a = kc.workspace("la").await?; + let ws_b = kc.workspace("lb").await?; + let user = kc.session(User::User).await?; + let user_b = kc.session(User::UserB).await?; + ws_a.add_member(user.subject(), proto::WorkspaceRole::User) + .await?; + ws_b.add_member(user_b.subject(), proto::WorkspaceRole::User) + .await?; + + let names: Vec = user + .client() + .list_all_workspaces(ListOptions::default()) + .await + .context("list workspaces as a user")? + .into_iter() + .map(|w| w.name) + .collect(); + testkit::ensure!( + names.iter().any(|n| n == ws_a.name()), + "the user's workspace list is missing {}: {names:?}", + ws_a.name() + ); + testkit::ensure!( + !names.iter().any(|n| n == ws_b.name() || n == "default"), + "the user's workspace list shows a workspace they aren't a member of: {names:?}" + ); + Ok(()) +} + +/// A workspace admin can't create a provider in another workspace. The CLI +/// reports a permission denial without the credential, and the workspace +/// gets no provider. +#[testkit::test] +async fn workspace_admin_cannot_manage_another_workspace_providers(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let ws_a = kc.workspace("pa").await?; + let ws_b = kc.workspace("pb").await?; + let admin = kc.session(User::Admin).await?; + let ws_admin = kc.session(User::User).await?; + let user_b = kc.session(User::UserB).await?; + ws_a.add_member(ws_admin.subject(), proto::WorkspaceRole::Admin) + .await?; + ws_b.add_member(user_b.subject(), proto::WorkspaceRole::User) + .await?; + let provider = kc.name("xprov"); + ws_b.track_provider(&provider); + + let credential = format!("OPENAI_API_KEY={CREDENTIAL_VALUE}"); + let denied = ws_admin + .cli_in(ws_b.name()) + .run([ + "provider", + "create", + "--name", + &provider, + "--type", + "openai", + "--credential", + &credential, + ]) + .await? + .failure()?; + // The profile lookup redacts the gateway's membership details, so check + // the code and the guidance. + let report = compact(&denied.report_text()); + testkit::ensure!( + report.contains("PERMISSION_DENIED") + && report.contains("verifyworkspacemembershipandrequiredpermissions"), + "the cross-workspace provider create did not report a permission denial:\n{}", + denied.report_text() + ); + testkit::ensure!( + !denied.stdout.contains(CREDENTIAL_VALUE) && !denied.stderr.contains(CREDENTIAL_VALUE), + "the denial printed the credential value" + ); + + // Ask as another identity, so a provider created before the denial + // can't hide behind the failed command. + let listing = raw(&admin) + .await? + .list_providers(list_providers(ws_b.name())) + .await + .context("list providers as platform admin")? + .into_inner(); + testkit::ensure!( + listing.providers.is_empty() && listing.next_page_token.is_empty(), + "the denied create left providers in {}: {:?}", + ws_b.name(), + listing + .providers + .iter() + .filter_map(|p| p.metadata.as_ref().map(|m| m.name.as_str())) + .collect::>() + ); + Ok(()) +} + +/// A workspace user naming a platform provider profile with `--provider` +/// gets past the profile lookup without a platform-admin check. +#[testkit::test] +async fn user_can_resolve_provider_profile_for_sandbox(cx: &mut Context) -> Result { + let kc = setup(cx).await?; + let ws = kc.workspace("rp").await?; + let user = kc.session(User::User).await?; + ws.add_member(user.subject(), proto::WorkspaceRole::User) + .await?; + let profile = import_platform_profile(&kc, &kc.name("gpf")).await?; + let sandbox = kc.name("rps"); + ws.track_sandbox(&sandbox); + + // No provider of the profile's type exists, and without a terminal the + // CLI can't offer to create one, so it stops there. That error means + // the lookup worked; a permission error would mean the user was kept + // out of the catalog. + let output = user + .cli_in(ws.name()) + .run([ + "sandbox", + "create", + "--name", + &sandbox, + "--no-tty", + "--provider", + &profile, + ]) + .await?; + let report = output.report_text(); + testkit::ensure!( + !report.to_ascii_lowercase().contains("platform admin"), + "the workspace user hit a platform-admin check resolving the profile:\n{report}" + ); + testkit::ensure!( + report.contains("missing required provider"), + "expected the missing-provider error, got:\n{report}" + ); + Ok(()) +} + +// ── Helpers ──────────────────────────────────────────────────────────── + +/// Read the Keycloak configuration and check testkit connects as an +/// operator, which the tests' setup and cleanup need. +async fn setup(cx: &mut Context) -> Result> { + let kc = KeycloakContext::new(cx).await?; + let operator = kc.cli_handle().gateway().connect().await?; + match operator + .raw_grpc_fresh() + .await? + .get_current_user(proto::GetCurrentUserRequest {}) + .await + { + Err(status) if status.code() == GrpcCode::PermissionDenied => Ok(kc), + Err(status) => Err(Error::from(status).context("check testkit connects as an operator")), + Ok(user) => Err(Error::msg(format!( + "testkit's client certificate signs in as user {:?} ({}), not as an operator; \ + the -oidc environment makes it an operator's (roles/oidc_gateway)", + user.get_ref().subject, + user.get_ref().identity_provider + ))), + } +} + +async fn raw(session: &Session) -> Result { + Ok(session.client().raw_grpc_fresh().await?) +} + +/// Fail unless `result` is a permission denial whose message contains +/// `message`. +fn expect_denied>( + result: std::result::Result, + message: &str, + action: impl fmt::Display, +) -> Result { + let error = match result { + Ok(_) => return Err(Error::msg(format!("{action}: allowed, expected a denial"))), + Err(error) => error.into(), + }; + testkit::ensure!( + error.grpc_code() == Some(GrpcCode::PermissionDenied) + && error.to_string().contains(message), + "{action}: expected PERMISSION_DENIED with {message:?}, got {:?}: {error}", + error.grpc_code() + ); + Ok(()) +} + +/// A profile whose providers need one credential. +fn test_profile(id: &str) -> Result { + Profile::new(id) + .credential( + Credential::new("api_key") + .env_var(CREDENTIAL_ENV) + .required(), + ) + .to_yaml() +} + +/// Import a profile at platform scope as the operator, with cleanup. +async fn import_platform_profile(cx: &Context, id: &str) -> Result { + let cli = cx.cli_handle(); + let owned = id.to_string(); + cx.on_cleanup(format!("delete platform profile {id}"), async move || { + cli.run(["profile", "delete", "--global", &owned]) + .await? + .success()?; + Ok(()) + }); + let file = YamlFile::new(&test_profile(id)?)?; + cx.cli(["profile", "import", "--global", "--file", file.path()?]) + .await? + .success() + .context(format!("import platform profile {id}"))?; + Ok(id.to_string()) +} + +/// Delete workspace `name`, which a test asks the gateway to create, when +/// the test ends, as `admin`. +fn delete_workspace_on_cleanup(cx: &Context, admin: &OpenShellClient, name: &str) { + let admin = admin.clone(); + let owned = name.to_string(); + cx.on_cleanup(format!("delete workspace {name}"), async move || { + admin + .delete_workspace( + &owned, + DeleteOptions { + allow_missing: true, + }, + ) + .await?; + Ok(()) + }); +} + +fn provider_request(workspace: &str, name: &str, profile: &str) -> proto::CreateProviderRequest { + proto::CreateProviderRequest { + workspace_scope: Some(proto::workspace_selector(workspace)), + provider: Some(proto::Provider { + metadata: Some(proto::ObjectMeta { + name: name.to_string(), + workspace: workspace.to_string(), + ..Default::default() + }), + r#type: profile.to_string(), + credentials: [(CREDENTIAL_ENV.to_string(), CREDENTIAL_VALUE.to_string())].into(), + ..Default::default() + }), + ..Default::default() + } +} + +fn delete_provider(workspace: &str, name: &str) -> proto::DeleteProviderRequest { + proto::DeleteProviderRequest { + workspace_scope: Some(proto::workspace_selector(workspace)), + name: name.to_string(), + ..Default::default() + } +} + +fn list_providers(workspace: &str) -> proto::ListProvidersRequest { + proto::ListProvidersRequest { + workspace_scope: Some(proto::workspace_selector(workspace)), + ..Default::default() + } +} + +fn add_member( + workspace: &str, + subject: &str, + role: proto::WorkspaceRole, +) -> proto::AddWorkspaceMemberRequest { + proto::AddWorkspaceMemberRequest { + workspace_scope: Some(proto::workspace_selector(workspace)), + principal_subject: subject.to_string(), + role: role.into(), + ..Default::default() + } +} + +fn remove_member(workspace: &str, subject: &str) -> proto::RemoveWorkspaceMemberRequest { + proto::RemoveWorkspaceMemberRequest { + workspace_scope: Some(proto::workspace_selector(workspace)), + principal_subject: subject.to_string(), + ..Default::default() + } +} + +fn list_members(workspace: &str) -> proto::ListWorkspaceMembersRequest { + proto::ListWorkspaceMembersRequest { + workspace_scope: Some(proto::workspace_selector(workspace)), + ..Default::default() + } +} + +/// The subjects of `workspace`'s members. The test workspaces have a few +/// members, so the first page holds them all. +async fn members(grpc: &mut AuthedGrpcClient, workspace: &str) -> Result> { + let response = grpc + .list_workspace_members(list_members(workspace)) + .await + .context(format!("list the members of {workspace}"))? + .into_inner(); + testkit::ensure!( + response.next_page_token.is_empty(), + "the members of {workspace} span more than one page" + ); + Ok(response + .members + .into_iter() + .map(|m| m.principal_subject) + .collect()) +} + +fn sandbox_names(sandboxes: &[testkit::sdk::SandboxRef]) -> Vec { + sandboxes.iter().map(|s| s.name.clone()).collect() +} + +/// `text` without whitespace, for matching an error report the CLI may wrap +/// inside a word, such as a quoted command. +fn compact(text: &str) -> String { + text.chars().filter(|c| !c.is_whitespace()).collect() +} + +/// The JSON object in `stdout`. The CLI may print startup notices before +/// it. +fn json_object(stdout: &str) -> Result { + let start = stdout.find('{'); + let end = stdout.rfind('}'); + let (Some(start), Some(end)) = (start, end) else { + return Err(Error::msg(format!( + "no JSON object in the output:\n{stdout}" + ))); + }; + serde_json::from_str(&stdout[start..=end]).context("parse the CLI's JSON output") +} + +/// Check the URL the CLI opened asks Keycloak for a PKCE (S256) code with +/// the requested scopes, returned to the CLI's loopback callback. +fn check_authorization_url(url: &Url, issuer: &str) -> Result { + let issuer = Url::parse(issuer).map_err(|e| Error::msg(format!("parse {issuer}: {e}")))?; + let expected_path = format!( + "{}/protocol/openid-connect/auth", + issuer.path().trim_end_matches('/') + ); + testkit::ensure!( + url.path() == expected_path, + "authorization URL {url} is not {expected_path}" + ); + let params: HashMap = url.query_pairs().into_owned().collect(); + let param = |name: &str| params.get(name).map(String::as_str).unwrap_or_default(); + testkit::ensure!( + param("response_type") == "code" + && param("client_id") == "openshell-cli" + && param("code_challenge_method") == "S256", + "authorization URL {url} does not ask for a PKCE code for openshell-cli" + ); + let challenge = param("code_challenge"); + testkit::ensure!( + challenge.len() == 43 + && challenge + .bytes() + .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_')), + "PKCE challenge {challenge:?} is not an unpadded base64url SHA-256" + ); + testkit::ensure!( + !param("state").is_empty(), + "authorization URL {url} has no state" + ); + let scopes: Vec<&str> = param("scope").split_whitespace().collect(); + for scope in OPENSHELL_SCOPES.split_whitespace() { + testkit::ensure!( + scopes.contains(&scope), + "authorization URL scopes {scopes:?} lack {scope}" + ); + } + let redirect = Url::parse(param("redirect_uri")) + .map_err(|e| Error::msg(format!("parse the redirect URI in {url}: {e}")))?; + testkit::ensure!( + redirect.scheme() == "http" + && redirect.host_str() == Some("127.0.0.1") + && redirect.port().is_some() + && redirect.path() == "/callback", + "redirect URI {redirect} is not the CLI's loopback callback" + ); + Ok(()) +} + +/// Check the CLI saved the OIDC registration and the user's tokens, and +/// return the token's subject. +fn check_saved_session(login: &BrowserLogin, kc: &KeycloakContext<'_>) -> Result { + let keycloak = kc.keycloak(); + let dir = login.gateway_dir(); + let metadata = read_json(&dir.join("metadata.json"))?; + testkit::ensure!( + metadata["auth_mode"] == "oidc" + && metadata["oidc_issuer"] == keycloak.issuer() + && metadata["oidc_client_id"] == keycloak.client_id() + && metadata["oidc_scopes"] == "profile email openshell:all", + "the saved registration is not the OIDC one: {metadata}" + ); + let token = read_json(&dir.join("oidc_token.json"))?; + let access_token = token["access_token"].as_str().unwrap_or_default(); + testkit::ensure!( + !access_token.is_empty() + && token["refresh_token"] + .as_str() + .is_some_and(|t| !t.is_empty()) + && token["issuer"] == keycloak.issuer() + && token["client_id"] == keycloak.client_id(), + "the saved token file lacks the access token, refresh token, issuer or client" + ); + let (username, _) = keycloak.credentials(User::User)?; + let claims = keycloak_support::claims(access_token)?; + testkit::ensure!( + keycloak_support::audience_contains(&claims, "openshell-cli") + && claims["azp"] == "openshell-cli" + && claims["preferred_username"] == username.as_str() + && keycloak_support::has_realm_role(&claims, "openshell-user"), + "the saved access token's claims are not the user's: {claims}" + ); + keycloak_support::subject(access_token) +} + +fn read_json(path: &std::path::Path) -> Result { + let text = std::fs::read_to_string(path).context(format!("read {}", path.display()))?; + serde_json::from_str(&text).context(format!("parse {}", path.display())) +} From dc56a3be709fb1a4dda9fdcc7c0cc13071d2de94 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:08:10 -0800 Subject: [PATCH 08/14] test(e2e): drop the OIDC tests the oidc-auth suite now covers Signed-off-by: Matthew Grossman --- e2e/rust/tests/oidc_pkce.rs | 1134 +++-------------------------------- 1 file changed, 67 insertions(+), 1067 deletions(-) diff --git a/e2e/rust/tests/oidc_pkce.rs b/e2e/rust/tests/oidc_pkce.rs index 409d99bf30..461db3b287 100644 --- a/e2e/rust/tests/oidc_pkce.rs +++ b/e2e/rust/tests/oidc_pkce.rs @@ -10,912 +10,100 @@ //! callback and token exchange used by a real browser without requiring a GUI. //! It logs in as the fixture identities and verifies standard-user and admin-only //! actions against a live Docker- or Podman-backed gateway. +//! +//! The rest of this coverage lives in the `oidc-auth` testkit suite. These +//! four checks duplicate it and are not ported. -use std::collections::HashMap; -use std::ffi::OsString; -use std::fs::Permissions; -use std::os::unix::fs::PermissionsExt; -use std::path::Path; -use std::process::{Output, Stdio}; -use std::time::{Duration, Instant}; - -use base64::Engine as _; -use openshell_e2e::harness::binary::openshell_cmd; -use serde_json::Value; -use serial_test::serial; -use tokio::process::Command; -use tokio::sync::Mutex; -use url::Url; - -static SANDBOX_LIFECYCLE_LOCK: Mutex<()> = Mutex::const_new(()); - -#[derive(Clone, Copy)] -struct IdentityScenario { - gateway_name: &'static str, - username: &'static str, - password: &'static str, - expected_role: &'static str, -} - -const ADMIN: IdentityScenario = IdentityScenario { - gateway_name: "oidc-pkce-admin", - username: "admin@test", - password: "admin", - expected_role: "openshell-admin", -}; - -const USER: IdentityScenario = IdentityScenario { - gateway_name: "oidc-pkce-user", - username: "user@test", - password: "user", - expected_role: "openshell-user", -}; - -const USER_B: IdentityScenario = IdentityScenario { - gateway_name: "oidc-pkce-user-b", - username: "user-b@test", - password: "user-b", - expected_role: "openshell-user", -}; - -struct LoginSession { - config_home: tempfile::TempDir, - identity: IdentityScenario, - subject: String, -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn admin_can_list_sandboxes() { - let session = login_identity(ADMIN).await; - assert_allowed( - &session, - &["sandbox", "list", "--output", "json"], - "list sandboxes", - ) - .await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_can_report_gateway_validated_identity() { - let session = login_identity(USER).await; - let output = assert_allowed( - &session, - &["whoami", "--output", "json"], - "report current identity", - ) - .await; - let stdout = String::from_utf8(output.stdout).expect("whoami output should be UTF-8"); - let json_start = stdout.find('{').expect("whoami output should contain JSON"); - let json_end = stdout - .rfind('}') - .expect("whoami output should contain a complete JSON object"); - let identity: Value = serde_json::from_str(&stdout[json_start..=json_end]) - .expect("whoami --output json should return JSON on stdout"); - - assert_eq!(identity["subject"], session.subject); - assert_eq!(identity["identity_provider"], "oidc"); - assert!( - identity["roles"] - .as_array() - .is_some_and(|roles| roles.iter().any(|role| role == USER.expected_role)), - "whoami should report the configured user role: {identity}" - ); -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_can_list_sandboxes() { - const WORKSPACE: &str = "oidc-user-list-sb"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "user").await; - assert_workspace_allowed( - &user, - WORKSPACE, - &["sandbox", "list", "--output", "json"], - "list sandboxes", - ) - .await; - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn admin_can_create_sandbox() { - let session = login_identity(ADMIN).await; - let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await; - assert_can_create_sandbox(&session, "default", "oidc-admin-create").await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_can_create_sandbox() { - const WORKSPACE: &str = "oidc-user-create"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "user").await; - let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await; - assert_can_create_sandbox(&user, WORKSPACE, "oidc-user-create").await; - delete_workspace(&admin, WORKSPACE).await; -} - -/// Workspace users must be able to resolve a provider profile when naming a -/// provider with `--provider`, without requiring Platform Admin access. -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_can_resolve_provider_profile_for_sandbox() { - const WORKSPACE: &str = "oidc-named-provider"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "user").await; - let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await; - - // `claude-code` names no existing provider, so the CLI has to look up the - // profile of that id before it can auto-create one. The lane imported the - // example profiles at platform scope; reaching them from a workspace is - // what this test guards. - let output = run_workspace_cli( - &user, - WORKSPACE, - &[ - "sandbox", - "create", - "--name", - "oidc-named-provider", - "--no-tty", - "--provider", - "claude-code", - ], - ) - .await; - let combined = combined_output(&output); - - // The provider cannot be auto-created without a terminal to confirm at, - // so creation stops there. That error proves the profile lookup - // succeeded; a permission error would mean the workspace user was gated - // out of the catalog. - assert!( - !combined.to_ascii_lowercase().contains("platform admin"), - "workspace user hit a platform-admin gate while resolving a provider profile:\n{combined}" - ); - assert!( - combined.contains("missing required provider"), - "expected missing-provider error for non-interactive session, got:\n{combined}" - ); - - let _ = run_workspace_cli( - &user, - WORKSPACE, - &["sandbox", "delete", "oidc-named-provider"], - ) - .await; - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn admin_can_delete_sandbox() { - let session = login_identity(ADMIN).await; - let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await; - assert_can_delete_sandbox(&session, "default", "oidc-admin-delete").await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_can_delete_sandbox() { - const WORKSPACE: &str = "oidc-user-delete"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "user").await; - let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await; - assert_can_delete_sandbox(&user, WORKSPACE, "oidc-user-delete").await; - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn admin_can_inspect_gateway() { - let session = login_identity(ADMIN).await; - let output = assert_allowed(&session, &["gateway", "info"], "inspect gateway info").await; - let info = combined_output(&output); - let expected_driver = - std::env::var("OPENSHELL_E2E_DRIVER").expect("OIDC E2E requires OPENSHELL_E2E_DRIVER"); - assert!( - info.to_ascii_lowercase() - .contains(&expected_driver.to_ascii_lowercase()), - "gateway info should report the {expected_driver} compute driver: {info}" - ); -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_cannot_inspect_gateway() { - let session = login_identity(USER).await; - let output = run_session_cli(&session, &["gateway", "info"]).await; - let denied = combined_output(&output); - assert!( - !output.status.success(), - "user accessed gateway info:\n{denied}" - ); - assert!( - denied.contains("requires admin privileges"), - "gateway-info denial should explain that admin privileges are required:\n{denied}" - ); - assert_admin_role_denial(&output, "inspect gateway info"); -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn admin_can_list_providers() { - let session = login_identity(ADMIN).await; - assert_allowed( - &session, - &["provider", "list", "--output", "json"], - "list providers", - ) - .await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_can_list_providers() { - const WORKSPACE: &str = "oidc-user-list-pr"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "user").await; - assert_workspace_allowed( - &user, - WORKSPACE, - &["provider", "list", "--output", "json"], - "list providers", - ) - .await; - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn admin_can_manage_provider() { - const PROVIDER: &str = "oidc-pkce-admin-provider"; - let session = login_identity(ADMIN).await; - - assert_allowed( - &session, - &[ - "provider", - "create", - "--name", - PROVIDER, - "--type", - "openai", - "--credential", - "OPENAI_API_KEY=e2e-test-value", - ], - "create a provider", - ) - .await; - - let get = assert_allowed(&session, &["provider", "get", PROVIDER], "read a provider").await; - assert!( - combined_output(&get).contains(PROVIDER), - "provider get output should contain the created provider:\n{}", - combined_output(&get) - ); - - assert_allowed( - &session, - &["provider", "delete", PROVIDER], - "delete a provider", - ) - .await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_cannot_create_provider() { - const WORKSPACE: &str = "oidc-user-no-create"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "user").await; - let output = run_workspace_cli( - &user, - WORKSPACE, - &[ - "provider", - "create", - "--name", - "oidc-pkce-user-provider", - "--type", - "openai", - "--credential", - "OPENAI_API_KEY=e2e-test-value", - ], - ) - .await; - assert_workspace_admin_denial(&output, &user, WORKSPACE, "create a provider"); - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_cannot_delete_provider() { - const PROVIDER: &str = "oidc-pkce-user-delete-target"; - const WORKSPACE: &str = "oidc-user-no-delete"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "user").await; - assert_workspace_allowed( - &admin, - WORKSPACE, - &[ - "provider", - "create", - "--name", - PROVIDER, - "--type", - "openai", - "--credential", - "OPENAI_API_KEY=e2e-test-value", - ], - "create the provider deletion target", - ) - .await; - - let denied = run_workspace_cli(&user, WORKSPACE, &["provider", "delete", PROVIDER]).await; - assert_workspace_admin_denial(&denied, &user, WORKSPACE, "delete a provider"); - - assert_workspace_allowed( - &admin, - WORKSPACE, - &["provider", "delete", PROVIDER], - "clean up the provider deletion target", - ) - .await; - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn admin_can_create_workspace() { - const WORKSPACE: &str = "oidc-admin-create"; - let admin = login_identity(ADMIN).await; - let _ = run_session_cli(&admin, &["workspace", "delete", WORKSPACE]).await; - assert_allowed( - &admin, - &["workspace", "create", "--name", WORKSPACE], - "create a workspace", - ) - .await; - let get = assert_allowed( - &admin, - &["workspace", "get", WORKSPACE], - "read the created workspace", - ) - .await; - assert!(combined_output(&get).contains(WORKSPACE)); - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_cannot_create_workspace() { - let user = login_identity(USER).await; - let denied = run_session_cli( - &user, - &["workspace", "create", "--name", "oidc-user-denied"], - ) - .await; - assert_admin_role_denial(&denied, "create a workspace"); -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn admin_can_delete_workspace() { - const WORKSPACE: &str = "oidc-admin-delete"; - let admin = login_identity(ADMIN).await; - let _ = run_session_cli(&admin, &["workspace", "delete", WORKSPACE]).await; - assert_allowed( - &admin, - &["workspace", "create", "--name", WORKSPACE], - "create a workspace deletion target", - ) - .await; - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn user_cannot_delete_workspace() { - const WORKSPACE: &str = "oidc-user-del-deny"; - let admin = login_identity(ADMIN).await; - let user = login_identity(USER).await; - let _ = run_session_cli(&admin, &["workspace", "delete", WORKSPACE]).await; - assert_allowed( - &admin, - &["workspace", "create", "--name", WORKSPACE], - "create a workspace deletion target", - ) - .await; - let denied = run_session_cli(&user, &["workspace", "delete", WORKSPACE]).await; - assert_admin_role_denial(&denied, "delete a workspace"); - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_user_can_read_workspace() { - const WORKSPACE: &str = "oidc-ws-user-read"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "user").await; - - let get = assert_allowed( - &user, - &["workspace", "get", WORKSPACE], - "read a member workspace", - ) - .await; - let list = assert_allowed( - &user, - &["workspace", "list", "--output", "json"], - "list member workspaces", - ) - .await; - let members = assert_allowed( - &user, - &["workspace", "member", "list", "--workspace", WORKSPACE], - "list workspace members", - ) - .await; - assert!(combined_output(&get).contains(WORKSPACE)); - assert!(combined_output(&list).contains(WORKSPACE)); - assert!(combined_output(&members).contains(&user.subject)); - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_user_cannot_manage_members() { - const WORKSPACE: &str = "oidc-ws-user-deny"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "user").await; - let denied = run_session_cli( - &user, - &[ - "workspace", - "member", - "add", - "--workspace", - WORKSPACE, - "--subject", - "oidc-fake-member", - "--role", - "user", - ], - ) - .await; - assert_workspace_admin_denial(&denied, &user, WORKSPACE, "add a workspace member"); - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_can_read_workspace() { - const WORKSPACE: &str = "oidc-wsa-read"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "admin").await; - - let get = assert_allowed( - &user, - &["workspace", "get", WORKSPACE], - "read an administered workspace", - ) - .await; - assert!(combined_output(&get).contains(WORKSPACE)); - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_can_create_sandbox() { - const WORKSPACE: &str = "oidc-wsa-create-sb"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "admin").await; - let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await; - assert_can_create_sandbox(&user, WORKSPACE, "oidc-wsa-create").await; - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_can_delete_sandbox() { - const WORKSPACE: &str = "oidc-wsa-delete-sb"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "admin").await; - let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await; - assert_can_delete_sandbox(&user, WORKSPACE, "oidc-wsa-delete").await; - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_can_create_provider() { - const WORKSPACE: &str = "oidc-wsa-create-pr"; - const PROVIDER: &str = "oidc-wsa-create-provider"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "admin").await; - assert_workspace_allowed( - &user, - WORKSPACE, - &[ - "provider", - "create", - "--name", - PROVIDER, - "--type", - "openai", - "--credential", - "OPENAI_API_KEY=e2e-test-value", - ], - "create a provider as workspace admin", - ) - .await; - - assert_workspace_allowed( - &admin, - WORKSPACE, - &["provider", "delete", PROVIDER], - "clean up the provider created by a workspace admin", - ) - .await; - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_can_delete_provider() { - const WORKSPACE: &str = "oidc-wsa-delete-pr"; - const PROVIDER: &str = "oidc-wsa-delete-provider"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "admin").await; - assert_workspace_allowed( - &admin, - WORKSPACE, - &[ - "provider", - "create", - "--name", - PROVIDER, - "--type", - "openai", - "--credential", - "OPENAI_API_KEY=e2e-test-value", - ], - "create the provider deletion target", - ) - .await; - assert_workspace_allowed( - &user, - WORKSPACE, - &["provider", "delete", PROVIDER], - "delete a provider as workspace admin", - ) - .await; - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_can_add_user_member() { - const WORKSPACE: &str = "oidc-wsa-add-user"; - let workspace_admin = login_identity(USER).await; - let user = login_identity(USER_B).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &workspace_admin, WORKSPACE, "admin").await; - - assert_allowed( - &workspace_admin, - &[ - "workspace", - "member", - "add", - "--workspace", - WORKSPACE, - "--subject", - &user.subject, - "--role", - "user", - ], - "add a standard workspace member", - ) - .await; - let members = assert_allowed( - &workspace_admin, - &["workspace", "member", "list", "--workspace", WORKSPACE], - "list workspace members after adding one", - ) - .await; - assert!(combined_output(&members).contains(&user.subject)); - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_can_remove_user_member() { - const WORKSPACE: &str = "oidc-wsa-rm-user"; - let workspace_admin = login_identity(USER).await; - let user = login_identity(USER_B).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &workspace_admin, WORKSPACE, "admin").await; - assert_allowed( - &admin, - &[ - "workspace", - "member", - "add", - "--workspace", - WORKSPACE, - "--subject", - &user.subject, - "--role", - "user", - ], - "create the workspace member removal target", - ) - .await; - - assert_allowed( - &workspace_admin, - &[ - "workspace", - "member", - "remove", - "--workspace", - WORKSPACE, - "--subject", - &user.subject, - ], - "remove a standard workspace member", - ) - .await; - let denied = run_session_cli(&user, &["workspace", "get", WORKSPACE]).await; - assert_non_member_denial(&denied, "read a workspace after removal by its admin"); - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_cannot_grant_admin() { - const WORKSPACE: &str = "oidc-ws-admin-deny"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "admin").await; - let denied = run_session_cli( - &user, - &[ - "workspace", - "member", - "add", - "--workspace", - WORKSPACE, - "--subject", - "oidc-fake-admin", - "--role", - "admin", - ], - ) - .await; - assert_platform_admin_denial(&denied, "grant workspace admin"); - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_cannot_create_workspace() { - const WORKSPACE: &str = "oidc-wsa-no-create"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "admin").await; - - let denied = - run_session_cli(&user, &["workspace", "create", "--name", "oidc-wsa-denied"]).await; - assert_admin_role_denial(&denied, "create a workspace as workspace admin"); - delete_workspace(&admin, WORKSPACE).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_cannot_delete_workspace() { - const WORKSPACE: &str = "oidc-wsa-no-delete"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "admin").await; +use std::collections::HashMap; +use std::ffi::OsString; +use std::fs::Permissions; +use std::os::unix::fs::PermissionsExt; +use std::path::Path; +use std::process::{Output, Stdio}; +use std::time::{Duration, Instant}; - let denied = run_session_cli(&user, &["workspace", "delete", WORKSPACE]).await; - assert_admin_role_denial(&denied, "delete an administered workspace"); - delete_workspace(&admin, WORKSPACE).await; -} +use base64::Engine as _; +use openshell_e2e::harness::binary::openshell_cmd; +use serde_json::Value; +use serial_test::serial; +use tokio::process::Command; +use tokio::sync::Mutex; +use url::Url; -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_cannot_inspect_gateway() { - const WORKSPACE: &str = "oidc-wsa-no-gw-info"; - let user = login_identity(USER).await; - let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "admin").await; +static SANDBOX_LIFECYCLE_LOCK: Mutex<()> = Mutex::const_new(()); - let denied = run_workspace_cli(&user, WORKSPACE, &["gateway", "info"]).await; - assert_admin_role_denial(&denied, "inspect gateway info as workspace admin"); - delete_workspace(&admin, WORKSPACE).await; +#[derive(Clone, Copy)] +struct IdentityScenario { + gateway_name: &'static str, + username: &'static str, + password: &'static str, + expected_role: &'static str, } -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_cannot_read_another_workspace() { - const WORKSPACE_A: &str = "oidc-wsa-xread-a"; - const WORKSPACE_B: &str = "oidc-wsa-xread-b"; - let (admin, workspace_admin, _user_b) = - prepare_isolated_workspaces_with_admin(WORKSPACE_A, WORKSPACE_B).await; - - let denied = run_session_cli(&workspace_admin, &["workspace", "get", WORKSPACE_B]).await; - assert_non_member_denial(&denied, "read another workspace as workspace admin"); - - delete_workspace(&admin, WORKSPACE_B).await; - delete_workspace(&admin, WORKSPACE_A).await; -} +const ADMIN: IdentityScenario = IdentityScenario { + gateway_name: "oidc-pkce-admin", + username: "admin@test", + password: "admin", + expected_role: "openshell-admin", +}; -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_admin_cannot_manage_another_workspace_members() { - const WORKSPACE_A: &str = "oidc-wsa-xmem-a"; - const WORKSPACE_B: &str = "oidc-wsa-xmem-b"; - let (admin, workspace_admin, _user_b) = - prepare_isolated_workspaces_with_admin(WORKSPACE_A, WORKSPACE_B).await; +const USER: IdentityScenario = IdentityScenario { + gateway_name: "oidc-pkce-user", + username: "user@test", + password: "user", + expected_role: "openshell-user", +}; - let denied = run_session_cli( - &workspace_admin, - &[ - "workspace", - "member", - "add", - "--workspace", - WORKSPACE_B, - "--subject", - "oidc-fake-member", - "--role", - "user", - ], - ) - .await; - assert_non_member_denial( - &denied, - "manage another workspace's members as workspace admin", - ); +const USER_B: IdentityScenario = IdentityScenario { + gateway_name: "oidc-pkce-user-b", + username: "user-b@test", + password: "user-b", + expected_role: "openshell-user", +}; - delete_workspace(&admin, WORKSPACE_B).await; - delete_workspace(&admin, WORKSPACE_A).await; +struct LoginSession { + config_home: tempfile::TempDir, + identity: IdentityScenario, + subject: String, } #[tokio::test] #[serial(oidc_pkce)] -async fn workspace_admin_cannot_manage_another_workspace_providers() { - const WORKSPACE_A: &str = "oidc-wsa-xprov-a"; - const WORKSPACE_B: &str = "oidc-wsa-xprov-b"; - const PROVIDER: &str = "oidc-wsa-xprovider"; - let (admin, workspace_admin, _user_b) = - prepare_isolated_workspaces_with_admin(WORKSPACE_A, WORKSPACE_B).await; - - let denied = run_workspace_cli( - &workspace_admin, - WORKSPACE_B, - &[ - "provider", - "create", - "--name", - PROVIDER, - "--type", - "openai", - "--credential", - "OPENAI_API_KEY=e2e-test-value", - ], - ) - .await; - let diagnostic = combined_output(&denied); - let compact: String = diagnostic - .chars() - .filter(|character| !character.is_whitespace() && *character != '│') - .collect(); - // Profile lookup redacts backend diagnostics. Check the permission code and - // safe recovery guidance without requiring the server's membership details. - assert!( - !denied.status.success() - && compact.contains("PERMISSION_DENIED") - && compact.contains("verifyworkspacemembershipandrequiredpermissions"), - "cross-workspace provider creation did not report a safe permission denial:\n{diagnostic}" - ); - assert!(!diagnostic.contains("e2e-test-value")); - - // Query with an independent authorized identity so a failed command alone - // cannot hide a provider created before the denial was returned. - let listed = assert_workspace_allowed( +async fn admin_can_delete_workspace() { + const WORKSPACE: &str = "oidc-admin-delete"; + let admin = login_identity(ADMIN).await; + let _ = run_session_cli(&admin, &["workspace", "delete", WORKSPACE]).await; + assert_allowed( &admin, - WORKSPACE_B, - &["provider", "list", "--output", "json"], - "verify denied creation left the target workspace empty", + &["workspace", "create", "--name", WORKSPACE], + "create a workspace deletion target", ) .await; - // CLI startup diagnostics may precede the JSON object on stdout. - let stdout = String::from_utf8(listed.stdout).expect("provider list output should be UTF-8"); - let json_start = stdout - .find('{') - .expect("provider list output should contain JSON"); - let json_end = stdout - .rfind('}') - .expect("provider list output should contain a complete JSON object"); - let listing: Value = serde_json::from_str(&stdout[json_start..=json_end]) - .expect("provider list --output json should return JSON on stdout"); - assert_eq!( - listing["next_page_token"], "", - "provider listing is incomplete" - ); - assert!( - listing["providers"] - .as_array() - .expect("provider collection") - .is_empty(), - "denied creation added a provider to the isolated target workspace" - ); - - delete_workspace(&admin, WORKSPACE_B).await; - delete_workspace(&admin, WORKSPACE_A).await; + delete_workspace(&admin, WORKSPACE).await; } #[tokio::test] #[serial(oidc_pkce)] -async fn membership_removal_revokes_workspace_access() { - const WORKSPACE: &str = "oidc-ws-revoke"; +async fn workspace_admin_can_create_sandbox() { + const WORKSPACE: &str = "oidc-wsa-create-sb"; let user = login_identity(USER).await; let admin = login_identity(ADMIN).await; - prepare_workspace(&admin, &user, WORKSPACE, "user").await; - assert_allowed( - &admin, - &[ - "workspace", - "member", - "remove", - "--workspace", - WORKSPACE, - "--subject", - &user.subject, - ], - "remove a workspace member", - ) - .await; - let denied = run_session_cli(&user, &["workspace", "get", WORKSPACE]).await; - assert_non_member_denial(&denied, "read a workspace after membership removal"); + prepare_workspace(&admin, &user, WORKSPACE, "admin").await; + let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await; + assert_can_create_sandbox(&user, WORKSPACE, "oidc-wsa-create").await; delete_workspace(&admin, WORKSPACE).await; } #[tokio::test] #[serial(oidc_pkce)] -async fn workspace_user_cannot_read_another_users_workspace() { - const WORKSPACE_A: &str = "oidc-xread-a"; - const WORKSPACE_B: &str = "oidc-xread-b"; - let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await; - - let denied = run_session_cli(&user_a, &["workspace", "get", WORKSPACE_B]).await; - assert_non_member_denial(&denied, "read another user's workspace"); - - delete_workspace(&admin, WORKSPACE_B).await; - delete_workspace(&admin, WORKSPACE_A).await; +async fn workspace_admin_can_delete_sandbox() { + const WORKSPACE: &str = "oidc-wsa-delete-sb"; + let user = login_identity(USER).await; + let admin = login_identity(ADMIN).await; + prepare_workspace(&admin, &user, WORKSPACE, "admin").await; + let _lifecycle = SANDBOX_LIFECYCLE_LOCK.lock().await; + assert_can_delete_sandbox(&user, WORKSPACE, "oidc-wsa-delete").await; + delete_workspace(&admin, WORKSPACE).await; } #[tokio::test] @@ -932,117 +120,6 @@ async fn second_workspace_user_cannot_read_first_users_workspace() { delete_workspace(&admin, WORKSPACE_A).await; } -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_list_hides_another_users_workspace() { - const WORKSPACE_A: &str = "oidc-xlist-a"; - const WORKSPACE_B: &str = "oidc-xlist-b"; - let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await; - - let listed = assert_allowed( - &user_a, - &["workspace", "list", "--output", "json"], - "list visible workspaces", - ) - .await; - let output = combined_output(&listed); - assert!( - output.contains(WORKSPACE_A), - "workspace list should contain the caller's workspace:\n{output}" - ); - assert!( - !output.contains(WORKSPACE_B), - "workspace list exposed another user's workspace:\n{output}" - ); - - delete_workspace(&admin, WORKSPACE_B).await; - delete_workspace(&admin, WORKSPACE_A).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_user_cannot_list_another_workspace_sandboxes() { - const WORKSPACE_A: &str = "oidc-xsbox-a"; - const WORKSPACE_B: &str = "oidc-xsbox-b"; - let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await; - - let denied = run_workspace_cli( - &user_a, - WORKSPACE_B, - &["sandbox", "list", "--output", "json"], - ) - .await; - assert_non_member_denial(&denied, "list another workspace's sandboxes"); - - delete_workspace(&admin, WORKSPACE_B).await; - delete_workspace(&admin, WORKSPACE_A).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_user_cannot_create_sandbox_in_another_workspace() { - const WORKSPACE_A: &str = "oidc-xcreate-a"; - const WORKSPACE_B: &str = "oidc-xcreate-b"; - let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await; - - let denied = run_workspace_cli( - &user_a, - WORKSPACE_B, - &[ - "sandbox", - "create", - "--name", - "oidc-xcreate-denied", - "--no-tty", - "--", - "echo", - "denied", - ], - ) - .await; - assert_non_member_denial(&denied, "create a sandbox in another workspace"); - - delete_workspace(&admin, WORKSPACE_B).await; - delete_workspace(&admin, WORKSPACE_A).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_user_cannot_list_another_workspace_providers() { - const WORKSPACE_A: &str = "oidc-xprov-a"; - const WORKSPACE_B: &str = "oidc-xprov-b"; - let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await; - - let denied = run_workspace_cli( - &user_a, - WORKSPACE_B, - &["provider", "list", "--output", "json"], - ) - .await; - assert_non_member_denial(&denied, "list another workspace's providers"); - - delete_workspace(&admin, WORKSPACE_B).await; - delete_workspace(&admin, WORKSPACE_A).await; -} - -#[tokio::test] -#[serial(oidc_pkce)] -async fn workspace_user_cannot_list_another_workspace_members() { - const WORKSPACE_A: &str = "oidc-xmember-a"; - const WORKSPACE_B: &str = "oidc-xmember-b"; - let (admin, user_a, _user_b) = prepare_isolated_workspaces(WORKSPACE_A, WORKSPACE_B).await; - - let denied = run_session_cli( - &user_a, - &["workspace", "member", "list", "--workspace", WORKSPACE_B], - ) - .await; - assert_non_member_denial(&denied, "list another workspace's members"); - - delete_workspace(&admin, WORKSPACE_B).await; - delete_workspace(&admin, WORKSPACE_A).await; -} - async fn login_identity(identity: IdentityScenario) -> LoginSession { let issuer = std::env::var("OPENSHELL_E2E_OIDC_ISSUER") .unwrap_or_else(|_| "http://localhost:8180/realms/openshell".to_string()); @@ -1365,22 +442,6 @@ async fn assert_allowed(session: &LoginSession, args: &[&str], action: &str) -> output } -async fn assert_workspace_allowed( - session: &LoginSession, - workspace: &str, - args: &[&str], - action: &str, -) -> Output { - let output = run_workspace_cli(session, workspace, args).await; - assert!( - output.status.success(), - "{} should be allowed to {action} in workspace {workspace}:\n{}", - session.identity.username, - combined_output(&output) - ); - output -} - async fn prepare_workspace( admin: &LoginSession, member: &LoginSession, @@ -1424,18 +485,6 @@ async fn prepare_isolated_workspaces( (admin, user_a, user_b) } -async fn prepare_isolated_workspaces_with_admin( - workspace_a: &str, - workspace_b: &str, -) -> (LoginSession, LoginSession, LoginSession) { - let admin = login_identity(ADMIN).await; - let workspace_admin = login_identity(USER).await; - let user_b = login_identity(USER_B).await; - prepare_workspace(&admin, &workspace_admin, workspace_a, "admin").await; - prepare_workspace(&admin, &user_b, workspace_b, "user").await; - (admin, workspace_admin, user_b) -} - async fn delete_workspace(admin: &LoginSession, workspace: &str) { for attempt in 0..30 { let output = run_session_cli(admin, &["workspace", "delete", workspace]).await; @@ -1590,55 +639,6 @@ async fn run_workspace_cli(session: &LoginSession, workspace: &str, args: &[&str run_cli(session.config_home.path(), &command_args).await } -fn assert_admin_role_denial(output: &Output, action: &str) { - let denied = combined_output(output); - let compact_denial: String = denied - .chars() - .filter(|character| !character.is_whitespace() && *character != '│') - .collect(); - assert!( - !output.status.success() && compact_denial.contains("openshell-admin"), - "standard user unexpectedly authorized to {action}, or denial omitted the admin role:\n{denied}" - ); -} - -fn assert_workspace_admin_denial( - output: &Output, - session: &LoginSession, - workspace: &str, - action: &str, -) { - let denied = combined_output(output); - let remediation = format!( - "openshell workspace member add --workspace '{workspace}' --subject '{}' --role admin", - session.subject - ); - let compact_denial: String = denied - .chars() - .filter(|character| !character.is_whitespace() && *character != '│') - .collect(); - let compact_remediation: String = remediation - .chars() - .filter(|character| !character.is_whitespace()) - .collect(); - assert!( - !output.status.success() - && compact_denial - .to_ascii_lowercase() - .contains("workspacerole'admin'") - && compact_denial.contains(&compact_remediation), - "workspace user unexpectedly authorized to {action}, or denial omitted the admin remediation command:\n{denied}" - ); -} - -fn assert_platform_admin_denial(output: &Output, action: &str) { - let denied = combined_output(output); - assert!( - !output.status.success() && denied.to_ascii_lowercase().contains("platform admin"), - "non-platform-admin unexpectedly authorized to {action}, or denial omitted the required platform role:\n{denied}" - ); -} - fn assert_non_member_denial(output: &Output, action: &str) { let denied = combined_output(output); let compact_denial: String = denied From 8a9967b2f9f5ed3476dd78b6ddab78352b65b12c Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 17:08:20 -0800 Subject: [PATCH 09/14] docs(testing): describe the OIDC feature environment Signed-off-by: Matthew Grossman --- TESTING.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/TESTING.md b/TESTING.md index 42c4321aa4..6fa6282c4b 100644 --- a/TESTING.md +++ b/TESTING.md @@ -342,6 +342,15 @@ nix run .#openshell-test-runner -- run \ --family features --package keycloak-provider-refresh ``` +The `oidc-auth` suite runs in `ubuntu-docker-rootful-oidc`, which adds a gateway +that trusts the Keycloak realm and gives testkit an operator client certificate: + +```shell +nix run .#openshell-test-runner -- run \ + --environment ubuntu-docker-rootful-oidc --installer deb \ + --family features --package oidc-auth +``` + A suite that needs setup beyond a container engine runs in a feature environment, named `-`, such as `ubuntu-docker-rootful-keycloak` or `ubuntu-docker-rootful-cdi`. `features` in `tests/tmachine/config.nix` lists From bc951c32c44475b98980a50aa7a4541ca79bc290 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 23:05:06 -0800 Subject: [PATCH 10/14] fix(tmachine): give the OIDC gateway explicit TLS paths for config preflight Signed-off-by: Matthew Grossman --- .../ansible/roles/oidc_gateway/defaults/main.yaml | 2 ++ .../tmachine/ansible/roles/oidc_gateway/tasks/main.yaml | 9 +++++++++ 2 files changed, 11 insertions(+) diff --git a/tests/tmachine/ansible/roles/oidc_gateway/defaults/main.yaml b/tests/tmachine/ansible/roles/oidc_gateway/defaults/main.yaml index 1e20e5a1da..14a375559c 100644 --- a/tests/tmachine/ansible/roles/oidc_gateway/defaults/main.yaml +++ b/tests/tmachine/ansible/roles/oidc_gateway/defaults/main.yaml @@ -3,3 +3,5 @@ --- oidc_gateway_operator_script: /usr/local/libexec/openshell-test/operator-client-cert +# OPENSHELL_LOCAL_TLS_DIR in the packaged gateway's unit. +oidc_gateway_tls_dir: "{{ openshell_gateway_home }}/.local/state/openshell/tls" diff --git a/tests/tmachine/ansible/roles/oidc_gateway/tasks/main.yaml b/tests/tmachine/ansible/roles/oidc_gateway/tasks/main.yaml index 1a7666c7ca..84525eed3f 100644 --- a/tests/tmachine/ansible/roles/oidc_gateway/tasks/main.yaml +++ b/tests/tmachine/ansible/roles/oidc_gateway/tasks/main.yaml @@ -36,6 +36,15 @@ [openshell.gateway.mtls_auth] operator_enabled = true + # `config preflight` accepts operator authentication only with an + # explicit client CA; it doesn't use the local TLS files the packaged + # gateway otherwise finds on its own. These are the paths + # `generate-certs` writes to. + [openshell.gateway.tls] + cert_path = "{{ oidc_gateway_tls_dir }}/server/tls.crt" + key_path = "{{ oidc_gateway_tls_dir }}/server/tls.key" + client_ca_path = "{{ oidc_gateway_tls_dir }}/ca.crt" + - name: Create the test scripts directory become: true ansible.builtin.file: From b1706ba8dc8e21d8c953eb340753c99bc326adac Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Thu, 19 Nov 2026 23:54:15 -0800 Subject: [PATCH 11/14] fix(oidc-auth): recognize the operator by its operator role Signed-off-by: Matthew Grossman --- .../features/oidc-auth/tests/oidc_auth.rs | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/tests/suites/features/oidc-auth/tests/oidc_auth.rs b/tests/suites/features/oidc-auth/tests/oidc_auth.rs index 4433660168..3818fd0c39 100644 --- a/tests/suites/features/oidc-auth/tests/oidc_auth.rs +++ b/tests/suites/features/oidc-auth/tests/oidc_auth.rs @@ -730,22 +730,28 @@ async fn user_can_resolve_provider_profile_for_sandbox(cx: &mut Context) -> Resu /// operator, which the tests' setup and cleanup need. async fn setup(cx: &mut Context) -> Result> { let kc = KeycloakContext::new(cx).await?; - let operator = kc.cli_handle().gateway().connect().await?; - match operator + let me = kc + .cli_handle() + .gateway() + .connect() + .await? .raw_grpc_fresh() .await? .get_current_user(proto::GetCurrentUserRequest {}) .await - { - Err(status) if status.code() == GrpcCode::PermissionDenied => Ok(kc), - Err(status) => Err(Error::from(status).context("check testkit connects as an operator")), - Ok(user) => Err(Error::msg(format!( - "testkit's client certificate signs in as user {:?} ({}), not as an operator; \ - the -oidc environment makes it an operator's (roles/oidc_gateway)", - user.get_ref().subject, - user.get_ref().identity_provider - ))), - } + .context("check testkit connects as an operator")? + .into_inner(); + // The gateway gives an operator certificate's identity the `operator` + // role; any other certificate signs in as an ordinary user. + testkit::ensure!( + me.identity_provider == "mtls" && me.roles.iter().any(|role| role == "operator"), + "testkit's client certificate signs in as {:?} ({}, roles {:?}), not as an operator; \ + the -oidc environment makes it an operator's (roles/oidc_gateway)", + me.subject, + me.identity_provider, + me.roles + ); + Ok(kc) } async fn raw(session: &Session) -> Result { From a4b56f890806c721a68f1313f3a157b18b1a75e2 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Fri, 20 Nov 2026 00:38:37 -0800 Subject: [PATCH 12/14] fix(oidc-auth): create providers against the workspace's imported profile Signed-off-by: Matthew Grossman --- tests/suites/features/oidc-auth/tests/oidc_auth.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/tests/suites/features/oidc-auth/tests/oidc_auth.rs b/tests/suites/features/oidc-auth/tests/oidc_auth.rs index 3818fd0c39..1de13161e8 100644 --- a/tests/suites/features/oidc-auth/tests/oidc_auth.rs +++ b/tests/suites/features/oidc-auth/tests/oidc_auth.rs @@ -835,6 +835,7 @@ fn provider_request(workspace: &str, name: &str, profile: &str) -> proto::Create ..Default::default() }), r#type: profile.to_string(), + profile_workspace: workspace.to_string(), credentials: [(CREDENTIAL_ENV.to_string(), CREDENTIAL_VALUE.to_string())].into(), ..Default::default() }), From 97b596fd610b9a9a4c641da6a510cb1fef1b5867 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Mon, 23 Nov 2026 11:45:18 -0800 Subject: [PATCH 13/14] test(oidc-auth): run the suite through testkit's harness for the skip list Signed-off-by: Matthew Grossman --- tests/suites/features/oidc-auth/Cargo.toml | 7 ++++++- tests/suites/features/oidc-auth/tests/oidc_auth.rs | 4 ++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/tests/suites/features/oidc-auth/Cargo.toml b/tests/suites/features/oidc-auth/Cargo.toml index da7c0c8780..22009ed02f 100644 --- a/tests/suites/features/oidc-auth/Cargo.toml +++ b/tests/suites/features/oidc-auth/Cargo.toml @@ -8,9 +8,14 @@ version = "0.0.0" edition = "2024" rust-version = "1.94" license = "Apache-2.0" -repository = "https://github.com/NVIDIA/OpenShell" +repository = "https://github.com/ai-openshell/openshell" publish = false +[[test]] +name = "oidc-auth" +path = "tests/oidc_auth.rs" +harness = false + [dependencies] keycloak-support = { path = "../../../support/keycloak" } openshell-testkit = { path = "../../../testkit/testkit" } diff --git a/tests/suites/features/oidc-auth/tests/oidc_auth.rs b/tests/suites/features/oidc-auth/tests/oidc_auth.rs index 1de13161e8..e73754b5aa 100644 --- a/tests/suites/features/oidc-auth/tests/oidc_auth.rs +++ b/tests/suites/features/oidc-auth/tests/oidc_auth.rs @@ -21,6 +21,10 @@ use testkit::{ }; use url::Url; +fn main() -> std::process::ExitCode { + testkit::main() +} + const ADMIN_ROLE_REQUIRED: &str = "role 'openshell-admin' required"; const ONLY_PLATFORM_ADMINS: &str = "only platform admins can assign the workspace admin role"; /// The provider credential the test profile defines. From 24bcadbf1e5317edf2c5037ff5b136222372ce36 Mon Sep 17 00:00:00 2001 From: Matthew Grossman Date: Tue, 24 Nov 2026 15:00:12 -0800 Subject: [PATCH 14/14] refactor(testkit): share the profile id parser between context and workspace imports Signed-off-by: Matthew Grossman --- tests/testkit/testkit/src/provider.rs | 20 +++++++++++++------- tests/testkit/testkit/src/workspace.rs | 11 ++--------- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/tests/testkit/testkit/src/provider.rs b/tests/testkit/testkit/src/provider.rs index 3cd6a89114..0b04d41a9f 100644 --- a/tests/testkit/testkit/src/provider.rs +++ b/tests/testkit/testkit/src/provider.rs @@ -10,18 +10,24 @@ use crate::context::Context; use crate::error::{Result, ResultExt as _}; use crate::yaml_file::YamlFile; +/// The `id` of `profile`, a provider profile in YAML: the provider type it +/// defines. +pub(crate) fn profile_id(profile: &str) -> Result { + #[derive(Deserialize)] + struct Profile { + id: String, + } + Ok(serde_yml::from_str::(profile) + .context("read the provider profile's id")? + .id) +} + impl Context { /// Import `profile`, a provider profile in YAML, and return its `id`, the /// provider type it defines. Cleanup deletes the profile after the test's /// sandboxes and the providers created after it. pub async fn import_profile(&self, profile: &str) -> Result { - #[derive(Deserialize)] - struct Profile { - id: String, - } - let id = serde_yml::from_str::(profile) - .context("read the provider profile's id")? - .id; + let id = profile_id(profile)?; // Deleting a missing profile succeeds, so register the delete before // the import. self.on_cleanup_delete("profile", &id); diff --git a/tests/testkit/testkit/src/workspace.rs b/tests/testkit/testkit/src/workspace.rs index c7e5711dbc..b068ffb94d 100644 --- a/tests/testkit/testkit/src/workspace.rs +++ b/tests/testkit/testkit/src/workspace.rs @@ -9,12 +9,11 @@ use std::time::{Duration, Instant}; use openshell_sdk::raw::proto; use openshell_sdk::{DeleteOptions, OpenShellClient}; -use serde::Deserialize; - use crate::cleanup::Cleanup; use crate::cli::Cli; use crate::context::{Context, track_sandbox}; use crate::error::{Error, Result, ResultExt as _}; +use crate::provider::profile_id; use crate::yaml_file::YamlFile; /// The longest workspace name the gateway accepts. @@ -107,13 +106,7 @@ impl Workspace { /// Import `profile`, a provider profile in YAML, into the workspace and /// return its `id`. Cleanup deletes it after the workspace's providers. pub async fn import_profile(&self, profile: &str) -> Result { - #[derive(Deserialize)] - struct Profile { - id: String, - } - let id = serde_yml::from_str::(profile) - .context("read the provider profile's id")? - .id; + let id = profile_id(profile)?; // Deleting a missing profile succeeds, so register the delete before // the import. let cli = self.cli.clone();