From 17a419e2f2b6887bb09bdb52dc7ac379259ca43b Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Mon, 19 Oct 2026 15:28:00 +0000 Subject: [PATCH 1/2] test(kubernetes): cover managed-gateway OIDC and three agents on one in-cluster route ## Failure #12734 asks for unit and fixture coverage of managed-gateway OIDC authentication, token refresh and authentication failures, and of per-agent identity and routing for agents that use cluster-local inference. The Kubernetes gateway code that #13414 and #13063 added had little of either. **OIDC.** Every SDK Kubernetes operations and connect test used the development profile, so the `oidc` branches from #13414 had no unit or fixture test: the auth resource identified by its namespace once ready, no issuer objects or signing material, and the token read from the variable `tokenEnv` names. The forwarded fake-gateway tests always supplied the token the gateway expected. Only the live `kubernetes_live::oidc` test refuses a token on the managed Kubernetes path, and it checks neither the error class nor that nothing changed. **Several agents on an in-cluster model.** `kubernetes_inference` covered one sandbox, from the `local.yaml` fixture. No test checked per-agent names or routes for the three-agent cluster examples: `example_configurations_are_valid_fabric_configurations` compiles them only to validate their Fabric configurations. The #13063 commit message names catalog-skip tests, such as `kubernetes_inference::cluster_gateways_read_no_model_catalog_for_a_cluster_service`, that v1 does not have. ## Decision These tests characterize existing behavior; no production code changes. ### OIDC - `kubernetes_operations`: with an `oidc` spec, `ensure` of the auth resource adds no cluster objects and no local signing material. `read` reports no identity before the resource is ready, and the namespace UID after. - `kubernetes_connect`: `running` takes the spec to prepare from. A connection's token equals the value of the variable `tokenEnv` names, and no state file contains it. When that variable is unset or empty, `connect` fails with the `tokenEnv` message. - Tests can't safely set a variable while others run, so `tokenEnv` names variables that Cargo and nextest set for every test process: `CARGO_MANIFEST_DIR` holds a token, and `CARGO_PKG_LICENSE_FILE` is empty because the package declares an SPDX license. `PATH`, the precedent in `fake_gateway_tests`, can't be used: the schema forbids it as `tokenEnv`, so the operations refuse the spec with `Query` before `connect` reads a token. - `fake_gateway_tests`: the `Forward` stub's token is now a field, and `Forward::client` opens a new `GatewayClient`. A gateway that requires a fresh token refuses every call with a stale one, so nothing changes, and the provider reports `ObservationError::Authentication` without state. That variant carries no gateway text, so it can't echo the token. A new client with the fresh token then succeeds, as the next command's provider process would; a `GatewayClient` keeps its client for the process's lifetime. No test changes a variable's value between commands. That a refreshed token takes effect on the next command follows from these tests and `an_existing_issuers_token_reaches_gateway_only_runs`, which resolves `tokenEnv` into OpenTofu's environment on each command. ### Three agents on one in-cluster route `three_agents_on_a_cluster_gateway_share_one_service_registration_with_their_own_rules` compiles `examples/kubernetes/external-gateway.yaml` and `examples/openshift/external-gateway.yaml` with the provider endpoint set to `http://qwen.models.svc.cluster.local:8000/v1`. It checks: - one `openshell_inference` whose server is the Service endpoint with the example provider's credential, and no `cluster_source`; - in each of the three sandboxes, an FQDN rule for the Service's host, port and `/v1/**`, without `allowed_ips` or `cluster_grants`; - one `fabric_agent` per sandbox, named by that sandbox's `agent.name`, whose models use the Service as `base_url`; - the same graph with `spec.sandboxes` reversed. `examples/kubernetes/managed-development.yaml` keeps its hosted endpoint, because its explicit policies name it, and is checked only for agent names. The test reads agent names from each document: `main` in the external examples, `primary` in managed-development. `a_cluster_service_endpoint_reads_no_catalog_while_https_and_private_addresses_keep_theirs` pins the skip that #13063 landed in `endpoint_requests`: an endpoint that fails `validate_endpoint`, such as plain HTTP to a Service name, has no catalog request, while an HTTPS endpoint and plain HTTP to `10.0.0.5` each keep one. The rule lookup and the expected Service rule endpoints move into helpers that the single-sandbox test also uses. Its assertions are unchanged. ## Validation The tests passed when added. If one fails later, the fix belongs in its own PR, with that test as its failing test. - `cargo ci` passed: tools, fmt, clippy, build, test (1606 passed), schema, bundle, and lifecycle (150 passed), within budget. - `cargo nextest run -p nemoclaw-sdk -E 'test(/kubernetes_connect|kubernetes_operations|kubernetes_inference|inference_discovery/)'` and `cargo nextest run -p openshell-provider --lib` pass. - `cargo test -p nemoclaw-sdk --test integration` on the three new OIDC tests passes, so both Cargo variables are set under `cargo test` too. - Each key assertion failed against a temporary change, since reverted. - OIDC inputs and fixtures: development auth on `ensure`; an existing auth directory; a receipt already marked ready; `tokenEnv` naming another variable; the token copied into the state directory; a set variable in the missing-token test; a missing client TLS Secret; the stale forward supplying the fresh token; a gateway accepting any token; a new client with a third token. - Production mutations: `operations.rs` identifying the `oidc` auth resource by its first issuer object; `operations.rs` accepting an empty token; `Mutation::failed` carrying state; no credential on a registration that several sandboxes share. - Routing inputs: a second registration, another Service port, a `cluster_source`, a cluster grant or `allowed_ips` on one sandbox, agents named after their sandboxes (also for managed-development alone), another model `base_url`, agent metadata that depends on sandbox order, no validation skip, rejected private HTTP, and skipped HTTPS. - Deferred to CI: `cargo ci live-docker` and `cargo ci live-kind`, which `cargo ci` selects because `openshell-provider` changed. Docker isn't installed on this host. Co-Authored-By: Claude Opus 5.5 --- .../nemoclaw-sdk/tests/inference_discovery.rs | 28 +++++ .../nemoclaw-sdk/tests/kubernetes_connect.rs | 118 +++++++++++++++++- .../tests/kubernetes_inference.rs | 116 ++++++++++++++--- .../tests/kubernetes_operations.rs | 47 +++++++ .../src/fake_gateway_tests.rs | 75 ++++++++--- 5 files changed, 349 insertions(+), 35 deletions(-) diff --git a/crates/nemoclaw-sdk/tests/inference_discovery.rs b/crates/nemoclaw-sdk/tests/inference_discovery.rs index 3376caea06c..cbeffa03638 100644 --- a/crates/nemoclaw-sdk/tests/inference_discovery.rs +++ b/crates/nemoclaw-sdk/tests/inference_discovery.rs @@ -70,3 +70,31 @@ fn managed_services_keep_their_owner_readiness_queries_instead_of_anonymous_cata .is_empty() ); } + +/// NemoClaw reads a model catalog itself only from an endpoint its own +/// connection rules allow: HTTPS, or plain HTTP to a literal loopback or +/// private address. Plain HTTP to a cluster Service name fails those rules, so +/// it has no catalog read. +#[test] +fn a_cluster_service_endpoint_reads_no_catalog_while_https_and_private_addresses_keep_theirs() { + use nemoclaw_sdk::{config::Document, inference_discovery::endpoint_requests}; + for (endpoint, read) in [ + ("http://qwen.models.svc.cluster.local:8000/v1", false), + ("https://inference.example.com/v1", true), + ("http://10.0.0.5:8000/v1", true), + ] { + let mut input = crate::support::example("kubernetes/external-gateway.yaml"); + input["spec"]["inferenceProviders"][0]["endpoint"] = serde_json::json!(endpoint); + let document = Document::parse(input.to_string().as_bytes()).unwrap(); + let requests = endpoint_requests(&document).unwrap(); + let expected: &[&str] = if read { &[endpoint] } else { &[] }; + assert_eq!( + requests + .iter() + .map(|request| request.endpoint.as_str()) + .collect::>(), + expected, + "{endpoint}" + ); + } +} diff --git a/crates/nemoclaw-sdk/tests/kubernetes_connect.rs b/crates/nemoclaw-sdk/tests/kubernetes_connect.rs index 805b57e922f..4c966d16481 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_connect.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_connect.rs @@ -54,6 +54,25 @@ fn free_port() -> u16 { } fn spec(kind: &str, port: u16) -> Spec { + authenticated(kind, port, json!({"profile": "development"})) +} + +/// A spec whose gateway trusts an existing OIDC issuer, with its token in +/// the variable `token_env` names. +fn oidc_spec(token_env: &str) -> impl Fn(&str, u16) -> Spec { + move |kind, port| { + authenticated( + kind, + port, + json!({ + "profile": "oidc", "issuer": "https://login.example.com", + "audience": "openshell", "tokenEnv": token_env + }), + ) + } +} + +fn authenticated(kind: &str, port: u16, authentication: serde_json::Value) -> Spec { serde_json::from_value(json!({ "layout": 1, "kind": kind, "name": NAME, "owner": OWNER, "generation": "0123456789abcdef0123456789abcdef", @@ -62,15 +81,20 @@ fn spec(kind: &str, port: u16) -> Spec { "endpoint": format!("https://127.0.0.1:{port}"), "kubernetes": { "kubeconfig": {"env": "TEST_CLUSTER_CONFIG"}, "context": "selected", "namespace": "agents", - "authentication": {"profile": "development"} + "authentication": authentication } } })) .unwrap() } -/// A cluster with a running gateway and the chart's client TLS Secret. -async fn running(objects: &Objects, directory: &Path) -> (crate::transport::Fixture, Operations) { +/// A cluster with a running gateway and the chart's client TLS Secret, each +/// resource prepared from `spec`. +async fn running( + objects: &Objects, + directory: &Path, + spec: impl Fn(&str, u16) -> Spec, +) -> (crate::transport::Fixture, Operations) { for object in [ json!({"apiVersion": "v1", "kind": "Namespace", "metadata": {"name": "kube-system", "uid": "system-1"}}), json!({"apiVersion": "storage.k8s.io/v1", "kind": "StorageClass", @@ -120,7 +144,7 @@ async fn running(objects: &Objects, directory: &Path) -> (crate::transport::Fixt async fn a_connection_supplies_private_client_credentials_and_a_token() { let objects = Objects::default(); let directory = tempfile::tempdir().unwrap(); - let (_fixture, operations) = running(&objects, directory.path()).await; + let (_fixture, operations) = running(&objects, directory.path(), spec).await; let connection = operations .connect(&spec(GATEWAY_KIND, free_port())) .await @@ -167,7 +191,7 @@ async fn a_connection_supplies_private_client_credentials_and_a_token() { async fn connections_do_not_need_the_authored_loopback_port() { let objects = Objects::default(); let directory = tempfile::tempdir().unwrap(); - let (_fixture, operations) = running(&objects, directory.path()).await; + let (_fixture, operations) = running(&objects, directory.path(), spec).await; let held = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); let authored = held.local_addr().unwrap().port(); let first = operations @@ -186,7 +210,7 @@ async fn connections_do_not_need_the_authored_loopback_port() { async fn a_gateway_that_is_not_running_cannot_be_connected() { let objects = Objects::default(); let directory = tempfile::tempdir().unwrap(); - let (_fixture, operations) = running(&objects, directory.path()).await; + let (_fixture, operations) = running(&objects, directory.path(), spec).await; objects.insert(json!({"apiVersion": "apps/v1", "kind": "StatefulSet", "metadata": {"name": NAME, "namespace": "agents", "uid": "gateway-uid", "generation": 2}, "status": {"readyReplicas": 0, "observedGeneration": 2}})); @@ -197,3 +221,85 @@ async fn a_gateway_that_is_not_running_cannot_be_connected() { .is_err() ); } + +/// Every regular file under `directory`. +fn files(directory: &Path) -> Vec { + std::fs::read_dir(directory) + .unwrap() + .flat_map(|entry| { + let path = entry.unwrap().path(); + if path.is_dir() { + files(&path) + } else { + vec![path] + } + }) + .collect() +} + +/// A connection takes its token from the variable tokenEnv names when it +/// opens, and no state file keeps a copy. +#[tokio::test] +async fn an_oidc_connection_passes_the_variable_tokenenv_names() { + // A test cannot set a variable safely while other tests run, so tokenEnv + // names one Cargo and nextest set for every test process. PATH and HOME + // are reserved names that tokenEnv may not use. + let name = "CARGO_MANIFEST_DIR"; + let token = std::env::var(name).unwrap(); + assert!(!token.is_empty()); + let objects = Objects::default(); + let directory = tempfile::tempdir().unwrap(); + let spec = oidc_spec(name); + let (_fixture, operations) = running(&objects, directory.path(), &spec).await; + let connection = operations + .connect(&spec(GATEWAY_KIND, free_port())) + .await + .unwrap(); + let environment = connection.environment(); + assert_eq!(environment[TOKEN_ENV], token); + let state = files(&directory.path().join("state")); + assert!(!state.is_empty()); + for file in state { + let content = std::fs::read(&file).unwrap(); + assert!( + !content + .windows(token.len()) + .any(|window| window == token.as_bytes()), + "{} holds the token", + file.display() + ); + } +} + +/// An unset or empty variable holds no token. +#[tokio::test] +async fn an_oidc_connection_without_its_token_names_tokenenv() { + let unset = "NEMOCLAW_TEST_UNSET_OIDC_TOKEN"; + assert!(std::env::var_os(unset).is_none()); + // Cargo and nextest set this empty: the package declares an SPDX license, + // not a license file. + let empty = "CARGO_PKG_LICENSE_FILE"; + assert_eq!(std::env::var(empty).as_deref(), Ok("")); + for name in [unset, empty] { + let objects = Objects::default(); + let directory = tempfile::tempdir().unwrap(); + let spec = oidc_spec(name); + let (_fixture, operations) = running(&objects, directory.path(), &spec).await; + let Err(error) = operations.connect(&spec(GATEWAY_KIND, free_port())).await else { + panic!("a connection without its token in {name}"); + }; + assert!( + matches!( + error, + nemoclaw_sdk::Error::Observation(nemoclaw_sdk::ObservationError::Backend(_)) + ), + "{name}: {error}" + ); + assert!( + error + .to_string() + .starts_with("the variable tokenEnv names holds no OIDC token"), + "{name}: {error}" + ); + } +} diff --git a/crates/nemoclaw-sdk/tests/kubernetes_inference.rs b/crates/nemoclaw-sdk/tests/kubernetes_inference.rs index 9c8e5b472f0..c409b4296b7 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_inference.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_inference.rs @@ -68,6 +68,30 @@ fn only<'a>(graph: &'a Value, kind: &str) -> &'a Value { objects.values().next().unwrap() } +/// `sandbox`'s policy rule for the one inference registration in `graph`. +fn service_rule<'a>(graph: &'a Value, sandbox: &str) -> &'a Value { + let inference = only(graph, "openshell_inference"); + let name = format!("nemoclaw-inference-{}", inference["name"].as_str().unwrap()); + graph["resource"]["openshell_sandbox"][sandbox]["policy"]["managed"] + .as_array() + .unwrap() + .iter() + .find(|rule| rule["name"] == name.as_str()) + .unwrap() +} + +/// The endpoints of a sandbox rule for `SERVICE`: its host and port, without +/// addresses. +fn service_endpoints() -> Value { + json!([{ + "host": "qwen.models.svc.cluster.local", + "port": 8000, + "path": "/v1/**", + "protocol": "rest", + "access": "full" + }]) +} + /// The registration names the Service literally, and the sandbox's rule for /// it names the same host and port without addresses. OpenShell decides which /// addresses the name may reach, so NemoClaw adds no grant. @@ -90,22 +114,9 @@ fn a_cluster_service_compiles_to_a_literal_server_and_an_fqdn_sandbox_rule() { assert!(inference.get("cluster_source").is_none(), "{driver}"); let policy = &graph["resource"]["openshell_sandbox"]["assistant"]["policy"]; assert!(policy.get("cluster_grants").is_none(), "{driver}"); - let name = format!("nemoclaw-inference-{}", inference["name"].as_str().unwrap()); - let rule = policy["managed"] - .as_array() - .unwrap() - .iter() - .find(|rule| rule["name"] == name.as_str()) - .unwrap(); assert_eq!( - rule["endpoints"], - json!([{ - "host": "qwen.models.svc.cluster.local", - "port": 8000, - "path": "/v1/**", - "protocol": "rest", - "access": "full" - }]), + service_rule(&graph, "assistant")["endpoints"], + service_endpoints(), "{driver}" ); let models = only(&graph, "fabric_agent")["models"].as_object().unwrap(); @@ -116,6 +127,81 @@ fn a_cluster_service_compiles_to_a_literal_server_and_an_fqdn_sandbox_rule() { } } +/// The agent row of each of the three sandboxes in `input`, each named by its +/// sandbox's `agent.name`, which Fabric receives as `metadata.name`. +fn agents<'a>(input: &Value, graph: &'a Value) -> Vec<&'a Value> { + let rows = graph["resource"]["fabric_agent"].as_object().unwrap(); + let sandboxes = parse(input).spec.sandboxes; + assert_eq!(rows.len(), 3); + assert_eq!(sandboxes.len(), 3); + sandboxes + .iter() + .map(|sandbox| { + let row = &rows[&sandbox.name]; + assert_eq!(row["name"], sandbox.agent.name.as_str(), "{}", sandbox.name); + row + }) + .collect() +} + +/// Three agents on one cluster gateway share one registration of the Service, +/// and each agent's sandbox has its own rule for it. Each agent keeps its +/// sandbox's agent name, whatever the order of the sandboxes. +#[test] +fn three_agents_on_a_cluster_gateway_share_one_service_registration_with_their_own_rules() { + for example in [ + "kubernetes/external-gateway.yaml", + "openshift/external-gateway.yaml", + ] { + let mut input = crate::support::example(example); + input["spec"]["inferenceProviders"][0]["endpoint"] = json!(SERVICE); + let graph = compile(&parse(&input), &generations(), "0.1.0").unwrap(); + let inference = only(&graph, "openshell_inference"); + assert_eq!( + inference["server"], + json!({ + "type": "inference_server", + "endpoint": SERVICE, + "credential_env": input["spec"]["inferenceProviders"][0]["credential"]["env"], + "credential_source": "" + }), + "{example}" + ); + assert!(inference.get("cluster_source").is_none(), "{example}"); + let sandboxes = graph["resource"]["openshell_sandbox"].as_object().unwrap(); + assert_eq!(sandboxes.len(), 3, "{example}"); + for (sandbox, resource) in sandboxes { + assert!( + resource["policy"].get("cluster_grants").is_none(), + "{example} {sandbox}" + ); + assert_eq!( + service_rule(&graph, sandbox)["endpoints"], + service_endpoints(), + "{example} {sandbox}" + ); + } + for agent in agents(&input, &graph) { + let models = agent["models"].as_object().unwrap(); + assert!(!models.is_empty(), "{example}"); + for model in models.values() { + assert_eq!(model["base_url"], SERVICE, "{example}"); + } + } + input["spec"]["sandboxes"].as_array_mut().unwrap().reverse(); + assert_eq!( + compile(&parse(&input), &generations(), "0.1.0").unwrap(), + graph, + "{example}" + ); + } + // This example's explicit sandbox policies name its hosted endpoint, so it + // keeps that endpoint and only its agent names are checked. + let input = crate::support::example("kubernetes/managed-development.yaml"); + let graph = compile(&parse(&input), &generations(), "0.1.0").unwrap(); + agents(&input, &graph); +} + /// `input` with its one provider given a key and declared, in turn, in each /// place a document can declare an inference provider. fn keyed_providers(input: &Value) -> Vec<(&'static str, Value)> { diff --git a/crates/nemoclaw-sdk/tests/kubernetes_operations.rs b/crates/nemoclaw-sdk/tests/kubernetes_operations.rs index bffea9f7bc2..c81ced91d94 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_operations.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_operations.rs @@ -38,6 +38,17 @@ fn spec_on(kind: &str, provider: &str) -> Spec { .unwrap() } +/// A spec whose gateway trusts an existing OIDC issuer. +fn oidc_spec(kind: &str) -> Spec { + let mut spec = spec(kind); + spec.settings.kubernetes.as_mut().unwrap().authentication = serde_json::from_value(json!({ + "profile": "oidc", "issuer": "https://login.example.com", + "audience": "openshell", "tokenEnv": "OIDC_TOKEN" + })) + .unwrap(); + spec +} + /// A cluster ready to host a gateway. fn cluster() -> Objects { let objects = Objects::default(); @@ -366,6 +377,42 @@ async fn storage_and_authentication_are_prepared_before_the_gateway_is_observed( assert_eq!(read.running, Some(true)); } +#[tokio::test] +async fn an_oidc_profile_writes_no_issuer_and_identifies_authentication_by_its_namespace() { + let objects = cluster(); + let directory = tempfile::tempdir().unwrap(); + let (_fixture, operations) = operations(&objects, directory.path()).await; + operations + .ensure(&oidc_spec(STORAGE_KIND), None) + .await + .unwrap(); + let unready = operations.read(&oidc_spec(AUTH_KIND), None).await.unwrap(); + assert_eq!((unready.id, unready.running), (None, None)); + let before = objects.0.lock().unwrap().clone(); + let auth = operations + .ensure(&oidc_spec(AUTH_KIND), None) + .await + .unwrap(); + assert!( + *objects.0.lock().unwrap() == before, + "an existing issuer needs no issuer Deployment, Secret or ConfigMap" + ); + assert!( + !operations.state.join("auth").exists(), + "an existing issuer needs no local signing material" + ); + let namespace = objects.get("v1", "Namespace", "", "agents").unwrap(); + assert_eq!(auth.id.as_deref(), namespace["metadata"]["uid"].as_str()); + assert_eq!(auth.running, Some(true)); + assert_eq!( + operations + .read(&oidc_spec(AUTH_KIND), auth.id.as_deref()) + .await + .unwrap(), + auth + ); +} + /// The namespace annotations OpenShift writes when it creates a project. fn assign_openshift_range(objects: &Objects) { let mut namespace = objects.get("v1", "Namespace", "", "agents").unwrap(); diff --git a/crates/openshell-provider/src/fake_gateway_tests.rs b/crates/openshell-provider/src/fake_gateway_tests.rs index 5341b9171f3..d05a98dc576 100644 --- a/crates/openshell-provider/src/fake_gateway_tests.rs +++ b/crates/openshell-provider/src/fake_gateway_tests.rs @@ -763,13 +763,15 @@ async fn native_provider_union_is_attached_and_attachment_drift_is_rejected() { assert!(client.read("sandbox", &row, false).await.is_err()); } -/// The bearer token the forward below supplies. +/// The bearer token the gateway from `forwarded` requires. const FORWARD_TOKEN: &str = "forward-token-sentinel"; /// A forward that supplies a bearer token and TLS files, as `SdkKubernetes` /// does, to a fixture gateway that requires them. +#[derive(Clone)] struct Forward { endpoint: String, + token: String, tls: [String; 3], } @@ -778,17 +780,28 @@ impl KubernetesConnector for Forward { async fn open(&self, _: &str) -> Result { Ok(KubernetesConnection { endpoint: self.endpoint.clone(), - token: Some(FORWARD_TOKEN.into()), + token: Some(self.token.clone()), tls: Some(self.tls.clone()), forward: Box::new(()), }) } } -/// A fixture gateway that requires mutual TLS and the forward's token, and a -/// client that reaches it as a managed Kubernetes gateway. The TLS files are -/// written to `directory`. -async fn forwarded(directory: &std::path::Path) -> (Fixture, OpenShell) { +impl Forward { + /// The client a new provider process opens to the gateway through this + /// forward. + async fn client(self) -> OpenShell { + GatewayClient::default() + .with_kubernetes(Arc::new(self)) + .connect(&GatewayConnection::Kubernetes("{}".into())) + .await + .unwrap() + } +} + +/// A fixture gateway that requires mutual TLS and `FORWARD_TOKEN`, and a +/// forward that supplies them. The TLS files are written to `directory`. +async fn forwarded(directory: &std::path::Path) -> (Fixture, Forward) { use rcgen::{ BasicConstraints, CertificateParams, ExtendedKeyUsagePurpose, IsCa, Issuer, KeyPair, KeyUsagePurpose, @@ -830,14 +843,10 @@ async fn forwarded(directory: &std::path::Path) -> (Fixture, OpenShell) { }); let forward = Forward { endpoint: fixture.endpoint.clone(), + token: FORWARD_TOKEN.into(), tls, }; - let client = GatewayClient::default() - .with_kubernetes(Arc::new(forward)) - .connect(&GatewayConnection::Kubernetes("{}".into())) - .await - .unwrap(); - (fixture, client) + (fixture, forward) } /// A provider's credential variable through a managed Kubernetes gateway @@ -850,7 +859,8 @@ async fn a_managed_kubernetes_gateway_resolves_provider_credentials_from_the_env let value = std::env::var("PATH").unwrap(); assert!(!value.is_empty()); let directory = tempfile::tempdir().unwrap(); - let (fixture, client) = forwarded(directory.path()).await; + let (fixture, forward) = forwarded(directory.path()).await; + let client = forward.client().await; let mut rows = fixture_rows("hermes-auth"); let (_, registration) = rows .iter_mut() @@ -876,7 +886,8 @@ async fn a_managed_kubernetes_gateway_resolves_provider_credentials_from_the_env #[tokio::test] async fn a_providers_credential_variable_never_resolves_to_the_forwards_credentials() { let directory = tempfile::tempdir().unwrap(); - let (fixture, client) = forwarded(directory.path()).await; + let (fixture, forward) = forwarded(directory.path()).await; + let client = forward.client().await; let rows = fixture_rows("hermes-auth"); let [(_, workspace), (_, profile), (_, registration), ..] = rows.as_slice() else { panic!("hermes-auth declares a workspace, a profile, and a registration"); @@ -902,3 +913,39 @@ async fn a_providers_credential_variable_never_resolves_to_the_forwards_credenti } assert!(fixture.state.lock().unwrap().providers.is_empty()); } + +/// A managed gateway that refuses the forward's token refuses every call, so +/// nothing changes, and the provider reports an authentication failure without +/// state. A `GatewayClient` keeps the client it opened for its process's +/// lifetime, so a refreshed token takes effect in the next command's provider +/// process, modeled here by a new one. +#[tokio::test] +async fn a_refused_forward_token_is_an_authentication_failure_without_effects() { + let directory = tempfile::tempdir().unwrap(); + let (fixture, forward) = forwarded(directory.path()).await; + fixture.state.lock().unwrap().expected_bearer = Some("Bearer fresh-token-sentinel".into()); + let rows = fixture_rows("hermes-auth"); + let (_, workspace) = rows.iter().find(|(kind, _)| *kind == "workspace").unwrap(); + let stale = Forward { + token: "stale-token-sentinel".into(), + ..forward.clone() + } + .client() + .await; + // An authentication failure carries no gateway text, so it cannot echo + // the token. + assert_eq!( + stale.ensure("workspace", workspace).await.into_parts(), + (None, Some(ObservationError::Authentication)) + ); + assert_eq!(fixture.state.lock().unwrap().effects, 0); + let fresh = Forward { + token: "fresh-token-sentinel".into(), + ..forward + } + .client() + .await; + let result = fresh.ensure("workspace", workspace).await; + assert!(result.error().is_none(), "{:?}", result.error()); + assert_eq!(fixture.state.lock().unwrap().effects, 1); +} From 24711a1f27dc4fd0485d64c328467846b6bcc146 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 19 Oct 2026 14:59:58 -0700 Subject: [PATCH 2/2] test: use the token reference shape from #13222 --- crates/nemoclaw-sdk/tests/kubernetes_connect.rs | 10 +++++----- crates/nemoclaw-sdk/tests/kubernetes_operations.rs | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/crates/nemoclaw-sdk/tests/kubernetes_connect.rs b/crates/nemoclaw-sdk/tests/kubernetes_connect.rs index 4c966d16481..46b0b4e267e 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_connect.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_connect.rs @@ -66,7 +66,7 @@ fn oidc_spec(token_env: &str) -> impl Fn(&str, u16) -> Spec { port, json!({ "profile": "oidc", "issuer": "https://login.example.com", - "audience": "openshell", "tokenEnv": token_env + "audience": "openshell", "token": {"env": token_env} }), ) } @@ -237,13 +237,13 @@ fn files(directory: &Path) -> Vec { .collect() } -/// A connection takes its token from the variable tokenEnv names when it +/// A connection takes its token from the variable token.env names when it /// opens, and no state file keeps a copy. #[tokio::test] async fn an_oidc_connection_passes_the_variable_tokenenv_names() { - // A test cannot set a variable safely while other tests run, so tokenEnv + // A test cannot set a variable safely while other tests run, so token.env // names one Cargo and nextest set for every test process. PATH and HOME - // are reserved names that tokenEnv may not use. + // are reserved names that token.env may not use. let name = "CARGO_MANIFEST_DIR"; let token = std::env::var(name).unwrap(); assert!(!token.is_empty()); @@ -298,7 +298,7 @@ async fn an_oidc_connection_without_its_token_names_tokenenv() { assert!( error .to_string() - .starts_with("the variable tokenEnv names holds no OIDC token"), + .starts_with("the variable token.env names holds no OIDC token"), "{name}: {error}" ); } diff --git a/crates/nemoclaw-sdk/tests/kubernetes_operations.rs b/crates/nemoclaw-sdk/tests/kubernetes_operations.rs index c81ced91d94..ec4ad5d4c10 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_operations.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_operations.rs @@ -43,7 +43,7 @@ fn oidc_spec(kind: &str) -> Spec { let mut spec = spec(kind); spec.settings.kubernetes.as_mut().unwrap().authentication = serde_json::from_value(json!({ "profile": "oidc", "issuer": "https://login.example.com", - "audience": "openshell", "tokenEnv": "OIDC_TOKEN" + "audience": "openshell", "token": {"env": "OIDC_TOKEN"} })) .unwrap(); spec