Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions crates/nemoclaw-sdk/tests/inference_discovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::<Vec<_>>(),
expected,
"{endpoint}"
);
}
}
118 changes: 112 additions & 6 deletions crates/nemoclaw-sdk/tests/kubernetes_connect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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", "token": {"env": 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",
Expand All @@ -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",
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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}}));
Expand All @@ -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::path::PathBuf> {
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 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 token.env
// names one Cargo and nextest set for every test process. PATH and HOME
// 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());
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 token.env names holds no OIDC token"),
"{name}: {error}"
);
}
}
116 changes: 101 additions & 15 deletions crates/nemoclaw-sdk/tests/kubernetes_inference.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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();
Expand All @@ -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)> {
Expand Down
47 changes: 47 additions & 0 deletions crates/nemoclaw-sdk/tests/kubernetes_operations.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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", "token": {"env": "OIDC_TOKEN"}
}))
.unwrap();
spec
}

/// A cluster ready to host a gateway.
fn cluster() -> Objects {
let objects = Objects::default();
Expand Down Expand Up @@ -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();
Expand Down
Loading