From de35958a64c0e047242fecd897b2a32b5fc1ad90 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Mon, 12 Oct 2026 15:43:13 +0000 Subject: [PATCH 1/2] fix: report bounded OpenShell rejections and harden teardown, locking, and test fixtures ## Failure Review of #12736 found six problems that do not depend on Kubernetes: - OpenShell rejection text was discarded. `remote_error` maps every gateway status to a fixed category, so on kind a CreateSandbox rejection for conflicting `allowed_ips` endpoint metadata reached the user only as "observation query failed". - Removing a ready sandbox still read its active-policy status, which teardown does not use; a failing status read blocked removal. - The deployment lock is an `flock` on the open file description. A child spawned concurrently holds a copy of the descriptor until `exec`, so dropping `Store` could leave the deployment locked, and the next open failed with "another operation holds the deployment lock". - Several tests wrote a script and executed it at once. A concurrent spawn that inherited the write descriptor made the exec fail with "Text file busy" (ETXTBSY). - `cargo images build --platform linux/amd64 hermes` failed with Bake's "failed to find target hermes". - The docs did not give the OpenClaw request format, how to recover when a malformed request leaves the runtime `unknown` (#12642), or that gateway profiles written before #12941 cannot be read. ## Decision - `ObservationError` gains `Rejected { operation, code, detail }`. `remote_rejection` keeps the gateway's detail only for CreateWorkspace, CreateSandbox, DeleteProvider and DeleteProviderProfile, whose requests carry no credentials, and only for FailedPrecondition, InvalidArgument, AlreadyExists, OutOfRange and ResourceExhausted. `sanitized_detail` reduces the detail to printable ASCII of at most 1024 characters and redacts bearer tokens, key/value credentials and token-like runs; `sanitized_resource_detail` also keeps one known resource name. Credential-bearing requests, reads and exec keep category-only errors. - `Rejected` owns its text, so `ObservationError` is `Clone` but no longer `Copy`; workspace callers clone it. - Teardown of a ready sandbox skips the active-policy status read. The owned identity checks still run. - `Drop for Store` unlocks before the file closes, which releases the lock for every copy of the descriptor. - Test fixtures execute an existing interpreter or binary and pass the written script as data. The provider staging test, which now runs the staged file through `/bin/sh`, asserts the executable bit that OpenTofu needs. - `images::plan` lists each platform's harnesses with `buildx bake --print agents` and names the platforms that build a requested harness; other selections keep Bake's resolution. - Docs: the headless OpenClaw request, the reported malformed-request failure and the whole-deployment replacement procedure, which rejections keep their detail, and the profile-format break. API change: `ObservationError` (also `nemoclaw_sdk::ObservationError`) is no longer `Copy` and has a new variant. Code that copies it must call `.clone()`, and exhaustive matches need a `Rejected` arm. Every use in this workspace is updated. ## Validation - `cargo ci` on linux_arm64 passed in 690 s: fmt, clippy `-D warnings`, build, 1387 nextest tests (174 skipped) and 4 doctests, schema, bundle, and 127 lifecycle tests (48 skipped). - Each new test failed with its production change reverted and passed with it: the two `remote_rejection` unit tests, the three redaction tests, the rejection-detail and ready-sandbox teardown fake-gateway tests, the lock test, and the harness-platform test. The credential-privacy test passes on v1 by design; it failed when CreateProvider was opted into rejection detail. The staging test failed when staging cleared the executable bit. - Repeated `cargo test` runs on this host: the `nemoclaw-sdk` lib suite passed 22 of 22 runs (v1: 7 of 22, with tests that reopen the deployment lock failing), and the `nemoclaw-test-fixtures` lib suite 50 of 50 (v1: 46 of 50; the kept failure logs show "Text file busy"). The other touched suites passed 10 of 10 on both. - `nemoclaw-build docs --check` passed. Split from #12736. Co-Authored-By: Claude Opus 5.5 --- Cargo.lock | 1 + crates/nemoclaw-backend/Cargo.toml | 1 + crates/nemoclaw-backend/src/contract.rs | 2 +- crates/nemoclaw-backend/src/observation.rs | 74 +++++++- crates/nemoclaw-build/src/images.rs | 51 ++++++ crates/nemoclaw-build/tests/images.rs | 31 ++++ crates/nemoclaw-discovery/src/gateway.rs | 4 +- crates/nemoclaw-openshell/src/connection.rs | 98 +++++++++++ crates/nemoclaw-openshell/src/lib.rs | 4 +- .../nemoclaw-provider/src/gateway/process.rs | 12 +- crates/nemoclaw-provider/src/hardware/ssh.rs | 62 ++++--- .../nemoclaw-provider/src/managed/backend.rs | 2 +- .../src/services/installers/ollama/backend.rs | 2 +- .../src/vllm/runtime/inline_recipe.rs | 26 ++- .../src/vllm/runtime/process.rs | 23 +-- crates/nemoclaw-sdk/src/deployment/tests.rs | 17 +- crates/nemoclaw-sdk/src/process.rs | 11 +- crates/nemoclaw-sdk/src/state/mod.rs | 8 + crates/nemoclaw-sdk/src/state/tests.rs | 23 +++ crates/nemoclaw-sdk/tests/error.rs | 45 +++++ .../tests/kubernetes_connection.rs | 6 +- .../tests/kubernetes_operations.rs | 2 +- crates/nemoclaw-sdk/tests/refresh.rs | 2 +- .../nemoclaw-test-fixtures/src/openshell.rs | 17 ++ crates/nemoclaw-test-fixtures/src/tofu.rs | 8 +- crates/openshell-provider/src/connected.rs | 11 +- .../src/fake_gateway_tests.rs | 162 ++++++++++++++++++ .../openshell-provider/src/gateway_source.rs | 2 +- crates/openshell-provider/src/transport.rs | 2 +- docs/agents.md | 24 ++- docs/provider.md | 7 + docs/troubleshooting.md | 14 +- docs/usage.md | 48 +++++- 33 files changed, 709 insertions(+), 93 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index e05e49452da..e211db9a108 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2497,6 +2497,7 @@ dependencies = [ "async-trait", "getrandom 0.4.3", "nemoclaw-runtime", + "regex", "serde", "serde_json", "thiserror 2.0.20", diff --git a/crates/nemoclaw-backend/Cargo.toml b/crates/nemoclaw-backend/Cargo.toml index b98f1b6c0f0..9ac15748b80 100644 --- a/crates/nemoclaw-backend/Cargo.toml +++ b/crates/nemoclaw-backend/Cargo.toml @@ -14,6 +14,7 @@ workspace = true nemoclaw-runtime = { path = "../nemoclaw-runtime", default-features = false } async-trait.workspace = true getrandom.workspace = true +regex.workspace = true serde.workspace = true serde_json.workspace = true thiserror.workspace = true diff --git a/crates/nemoclaw-backend/src/contract.rs b/crates/nemoclaw-backend/src/contract.rs index 283814650c2..c4f195f69c9 100644 --- a/crates/nemoclaw-backend/src/contract.rs +++ b/crates/nemoclaw-backend/src/contract.rs @@ -33,7 +33,7 @@ impl Mutation { self.state.as_ref() } pub fn error(&self) -> Option { - self.error + self.error.clone() } pub fn into_parts(self) -> (Option, Option) { (self.state, self.error) diff --git a/crates/nemoclaw-backend/src/observation.rs b/crates/nemoclaw-backend/src/observation.rs index a3b04fc1453..1c8fd80b709 100644 --- a/crates/nemoclaw-backend/src/observation.rs +++ b/crates/nemoclaw-backend/src/observation.rs @@ -51,9 +51,8 @@ pub enum Observation { Absent, } -/// Safe diagnostic categories. Raw backend messages can contain credentials and -/// must not be copied into public errors. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +/// Diagnostic categories and explicitly bounded, redacted backend rejections. +#[derive(Clone, Debug, PartialEq, Eq)] pub enum ObservationError { Authentication, Permission, @@ -64,6 +63,11 @@ pub enum ObservationError { BindingMismatch, /// A fixed, non-secret diagnostic from an owning backend. Backend(&'static str), + Rejected { + operation: &'static str, + code: &'static str, + detail: Box, + }, Hardware(nemoclaw_runtime::hardware::HardwareDiagnostic), FabricConfiguration { stage: &'static str, @@ -83,6 +87,11 @@ pub enum ObservationError { impl fmt::Display for ObservationError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { + Self::Rejected { + operation, + code, + detail, + } => write!(f, "OpenShell {operation} rejected ({code}): {detail}"), Self::SandboxConfigurationRejected { reason } => write!( f, "OpenShell configuration rejected: {reason}; resources retained" @@ -122,6 +131,65 @@ impl fmt::Display for ObservationError { impl std::error::Error for ObservationError {} +impl ObservationError { + /// Bound backend diagnostics and remove credentials before they enter public errors. + pub fn sanitized_detail(detail: &str) -> Box { + Self::sanitize_detail(detail, None) + } + + /// Preserve an exact non-secret resource name obtained from the request or + /// verified binding, never from the diagnostic. Credential fields remain redacted. + pub fn sanitized_resource_detail(detail: &str, resource_name: &str) -> Box { + Self::sanitize_detail(detail, Some(resource_name)) + } + + fn sanitize_detail(detail: &str, resource_name: Option<&str>) -> Box { + use std::sync::OnceLock; + static CREDENTIALS: OnceLock = OnceLock::new(); + static BEARER: OnceLock = OnceLock::new(); + static TOKENS: OnceLock = OnceLock::new(); + let printable: String = detail + .chars() + .map(|character| { + if character.is_ascii_graphic() || character == ' ' { + character + } else { + ' ' + } + }) + .collect(); + let bearer = BEARER.get_or_init(|| { + regex::Regex::new(r"(?i)\bbearer\s+[A-Za-z0-9._~+/=-]+") + .expect("constant diagnostic bearer pattern") + }); + let credentials = CREDENTIALS.get_or_init(|| { + regex::Regex::new(r#"(?i)["']?(?:authorization|api[_-]?key|token|password|secret)["']?\s*[:=]\s*(?:"[^"]*"|'[^']*'|[^\s,;}]+)"#) + .expect("constant diagnostic credential pattern") + }); + let tokens = TOKENS.get_or_init(|| { + regex::Regex::new(r"[A-Za-z0-9_+/=-]{32,}").expect("constant diagnostic token pattern") + }); + // Redact Bearer first: a key/value match alone would consume only the scheme. + let hidden = bearer.replace_all(&printable, "[REDACTED]"); + let hidden = credentials.replace_all(&hidden, "[REDACTED]"); + let hidden = tokens.replace_all(&hidden, |matched: ®ex::Captures<'_>| { + // Long generated object names resemble tokens. Only the caller's + // known name is exempt, after credential values have been removed. + if Some(&matched[0]) == resource_name { + matched[0].to_owned() + } else { + "[REDACTED]".into() + } + }); + let mut result = hidden.split_whitespace().collect::>().join(" "); + if result.len() > 1024 { + result.truncate(1021); + result.push_str("..."); + } + result.into_boxed_str() + } +} + /// Validate an observation against retained state without consuming that state. /// /// `Ok(None)` alone authorizes retiring the binding. Errors must stop planning; diff --git a/crates/nemoclaw-build/src/images.rs b/crates/nemoclaw-build/src/images.rs index dab0dcc3e7e..96d4b9bbd89 100644 --- a/crates/nemoclaw-build/src/images.rs +++ b/crates/nemoclaw-build/src/images.rs @@ -171,6 +171,28 @@ pub fn export_metadata(image: &str, platform: &str, output: &Path) -> Result<()> Ok(()) } +/// Harness images Bake's `agents` matrix builds for `platform`, in name order. +fn platform_harnesses(root: &Path, platform: &str) -> Result> { + // Bake prints progress on stderr; show it only when listing fails. + let listed = docker() + .current_dir(root) + .env("AGENT_PLATFORM", platform) + .args(["buildx", "bake", "--print", "agents"]) + .output() + .map_err(|_| "cannot run docker to list the agent images".to_owned())?; + if !listed.status.success() { + eprint!("{}", String::from_utf8_lossy(&listed.stderr)); + return Err(format!("docker failed to list the {platform} agent images")); + } + let plan: Value = serde_json::from_slice(&listed.stdout).map_err(|_| "unreadable bake plan")?; + Ok(plan["target"] + .as_object() + .ok_or("bake plan has no targets")? + .keys() + .cloned() + .collect()) +} + /// Bake targets for `selection`, each with the tags it should publish locally. pub fn plan( root: &Path, @@ -180,6 +202,35 @@ pub fn plan( if !PLATFORMS.contains(&platform) { return Err(format!("choose --platform {}", PLATFORMS.join(" or "))); } + // Bake reports a harness outside this platform's matrix only as an unknown + // target. Name the platforms that build it instead; other selections, such + // as groups or the reference image, keep Bake's own resolution. + let supported = platform_harnesses(root, platform)?; + let mut others = None; + for name in selection.iter().filter(|name| !supported.contains(name)) { + if others.is_none() { + others = Some( + PLATFORMS + .into_iter() + .filter(|other| *other != platform) + .map(|other| Ok((other, platform_harnesses(root, other)?))) + .collect::>>()?, + ); + } + let building: Vec<&str> = others + .iter() + .flatten() + .filter(|(_, harnesses)| harnesses.contains(name)) + .map(|(other, _)| *other) + .collect(); + if !building.is_empty() { + return Err(format!( + "{name} is built only for {}; {platform} builds {} (docs/build.md#build-agent-images)", + building.join(" and "), + supported.join(", ") + )); + } + } let printed = output( docker() .current_dir(root) diff --git a/crates/nemoclaw-build/tests/images.rs b/crates/nemoclaw-build/tests/images.rs index 9da1e954f70..392c694b694 100644 --- a/crates/nemoclaw-build/tests/images.rs +++ b/crates/nemoclaw-build/tests/images.rs @@ -37,3 +37,34 @@ fn builds_require_one_of_the_qualified_platforms() { let error = plan(Path::new("."), "linux/riscv64", &["agents".into()]).unwrap_err(); assert!(error.contains("--platform"), "{error}"); } + +#[test] +fn harnesses_missing_from_the_selected_platform_name_the_platforms_that_build_them() { + // Plans with Bake's print mode only; nothing is built. + if !std::process::Command::new("docker") + .args(["buildx", "version"]) + .output() + .is_ok_and(|output| output.status.success()) + { + eprintln!("skipping: docker buildx is unavailable"); + return; + } + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../.."); + let error = plan(&root, "linux/amd64", &["openclaw".into(), "hermes".into()]).unwrap_err(); + assert_eq!( + error, + "hermes is built only for linux/arm64; linux/amd64 builds deepagents, openclaw (docs/build.md#build-agent-images)" + ); + let planned = |platform, name: &str| { + plan(&root, platform, &[name.into()]) + .unwrap() + .into_iter() + .map(|(target, _)| target) + .collect::>() + }; + assert_eq!(planned("linux/amd64", "openclaw"), ["openclaw"]); + assert_eq!(planned("linux/arm64", "hermes"), ["hermes"]); + // Selections that are not harnesses keep Bake's own resolution. + assert_eq!(planned("linux/amd64", "dummy"), ["dummy"]); + assert!(plan(&root, "linux/amd64", &["no-such-target".into()]).is_err()); +} diff --git a/crates/nemoclaw-discovery/src/gateway.rs b/crates/nemoclaw-discovery/src/gateway.rs index 48ccf477696..cd11dcd8721 100644 --- a/crates/nemoclaw-discovery/src/gateway.rs +++ b/crates/nemoclaw-discovery/src/gateway.rs @@ -2,7 +2,9 @@ // SPDX-License-Identifier: Apache-2.0 //! An OpenShell gateway's version and compute drivers, read over its authenticated channel. -pub use nemoclaw_openshell::{capabilities, client, health, remote_error, request}; +pub use nemoclaw_openshell::{ + capabilities, client, health, remote_error, remote_rejection, request, +}; use nemoclaw_sdk::{ Secrets, config::{ComputeDriver, Gateway}, diff --git a/crates/nemoclaw-openshell/src/connection.rs b/crates/nemoclaw-openshell/src/connection.rs index 720fad7d5ae..9d3d55c82fe 100644 --- a/crates/nemoclaw-openshell/src/connection.rs +++ b/crates/nemoclaw-openshell/src/connection.rs @@ -146,11 +146,109 @@ pub fn remote_error(status: &tonic::Status) -> ObservationError { } } +/// Opt in only for gateway operations whose requests contain no credentials. +pub fn remote_rejection(operation: &'static str, status: &tonic::Status) -> ObservationError { + if !matches!( + operation, + "CreateWorkspace" | "CreateSandbox" | "DeleteProvider" | "DeleteProviderProfile" + ) { + return remote_error(status); + } + let code = match status.code() { + tonic::Code::FailedPrecondition => "FailedPrecondition", + tonic::Code::InvalidArgument => "InvalidArgument", + tonic::Code::AlreadyExists => "AlreadyExists", + tonic::Code::OutOfRange => "OutOfRange", + tonic::Code::ResourceExhausted => "ResourceExhausted", + _ => return remote_error(status), + }; + ObservationError::Rejected { + operation, + code, + detail: ObservationError::sanitized_detail(status.message()), + } +} + #[cfg(test)] mod tests { use super::*; use tonic::service::Interceptor; + #[test] + fn live_endpoint_ambiguity_keeps_its_conflict_kind() { + let detail = "network endpoint ambiguity validation failed: network policies 'nemoclaw-inference-qwen-example' endpoint[0] (nc-0123456789abcdef-model-0123456789abcdef.agents.svc.cluster.local:18888/v1/**) and '_provider_qwen_example' endpoint[0] (nc-0123456789abcdef-model-0123456789abcdef.agents.svc.cluster.local:18888/v1/**) overlap on port(s) 18888 with conflicting metadata: allowed_ips=[] vs [\"10.96.189.228/32\"]"; + let error = remote_rejection("CreateSandbox", &tonic::Status::failed_precondition(detail)); + assert!( + error + .to_string() + .contains("conflicting metadata: allowed_ips=[]") + ); + assert!(error.to_string().contains("CreateSandbox")); + } + + #[test] + fn definitive_rejections_keep_bounded_gateway_text_and_other_statuses_stay_fixed() { + for operation in [ + "CreateWorkspace", + "CreateSandbox", + "DeleteProvider", + "DeleteProviderProfile", + ] { + for code in [ + tonic::Code::FailedPrecondition, + tonic::Code::InvalidArgument, + tonic::Code::AlreadyExists, + tonic::Code::OutOfRange, + tonic::Code::ResourceExhausted, + ] { + let status = tonic::Status::new( + code, + format!("validation failed\n{}", "detail ".repeat(300)), + ); + let error = remote_rejection(operation, &status); + let ObservationError::Rejected { detail, .. } = error else { + panic!("missing operation rejection"); + }; + assert!(detail.len() <= 1024); + assert!(detail.bytes().all(|byte| (b' '..=b'~').contains(&byte))); + } + } + for operation in [ + "CreateProvider", + "UpdateProvider", + "GetSandbox", + "ExecSandbox", + "ImportProviderProfiles", + ] { + let status = tonic::Status::failed_precondition("credential-sentinel"); + assert_eq!( + remote_rejection(operation, &status), + ObservationError::Query + ); + } + for code in [ + tonic::Code::Unknown, + tonic::Code::Internal, + tonic::Code::Unauthenticated, + tonic::Code::PermissionDenied, + tonic::Code::Unavailable, + tonic::Code::DeadlineExceeded, + tonic::Code::Cancelled, + tonic::Code::NotFound, + ] { + let status = tonic::Status::new(code, "credential-sentinel"); + assert_eq!( + remote_rejection("CreateSandbox", &status), + remote_error(&status) + ); + assert!( + !remote_rejection("CreateSandbox", &status) + .to_string() + .contains("credential-sentinel") + ); + } + } + #[test] fn authentication_keeps_the_bearer_sensitive_and_requests_bounded() { let mut interceptor = authentication(Some("secret-sentinel")).unwrap(); diff --git a/crates/nemoclaw-openshell/src/lib.rs b/crates/nemoclaw-openshell/src/lib.rs index 3e7b3f5c0ed..36ebe23c854 100644 --- a/crates/nemoclaw-openshell/src/lib.rs +++ b/crates/nemoclaw-openshell/src/lib.rs @@ -17,7 +17,9 @@ pub mod runtime; pub mod search; pub use capabilities::{GatewayCapabilities, OPENSHELL_VERSION}; -pub use connection::{Connection, TlsFiles, capabilities, client, health, remote_error, request}; +pub use connection::{ + Connection, TlsFiles, capabilities, client, health, remote_error, remote_rejection, request, +}; pub use driver::ComputeDriver; pub use inputs::structured_inputs; pub use lifecycle::{ diff --git a/crates/nemoclaw-provider/src/gateway/process.rs b/crates/nemoclaw-provider/src/gateway/process.rs index 63051fb158b..0f006b09dca 100644 --- a/crates/nemoclaw-provider/src/gateway/process.rs +++ b/crates/nemoclaw-provider/src/gateway/process.rs @@ -9,7 +9,7 @@ use crate::{ use bollard::models::ContainerStateStatusEnum; use std::{future::Future, time::Duration}; -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] pub(super) enum Failure { Observation(ObservationError), Stopped { @@ -35,7 +35,7 @@ impl Failure { } } } -#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[derive(Clone, Debug, PartialEq, Eq)] enum Phase { Running, Restarting, @@ -127,12 +127,12 @@ impl ManagedGateway { let mut previous = None; loop { let phase = self.phase().await?; - if let Phase::Stopped(error) = phase - && (timeout.is_zero() || previous == Some(phase)) + if let Phase::Stopped(error) = &phase + && (timeout.is_zero() || previous.as_ref() == Some(&phase)) { - return Err(error); + return Err(error.clone()); } - previous = Some(phase); + previous = Some(phase.clone()); if phase == Phase::Running { // Keep one in-flight gateway request while checking the engine. // A stalled API cannot hide a process that exits during startup. diff --git a/crates/nemoclaw-provider/src/hardware/ssh.rs b/crates/nemoclaw-provider/src/hardware/ssh.rs index 31bef368f1f..c781961527d 100644 --- a/crates/nemoclaw-provider/src/hardware/ssh.rs +++ b/crates/nemoclaw-provider/src/hardware/ssh.rs @@ -325,43 +325,51 @@ mod tests { } } - /// Run the shipped script with fake `docker` and `nvidia-smi` on PATH, and + /// Run the shipped script with fake `docker` and `nvidia-smi` shell commands, and /// the real `uname`, `stat`, and `/proc/meminfo` of this Linux host. #[cfg(target_os = "linux")] #[test] fn collector_script_queries_compute_and_memory_and_parses_on_linux() { - use std::{fs, os::unix::fs::PermissionsExt, process::Command}; + use std::{fs, process::Command}; let root = tempfile::tempdir().unwrap(); - let bin = root.path().join("bin"); let docker_root = root.path().join("docker-root"); let calls = root.path().join("calls"); - fs::create_dir(&bin).unwrap(); fs::create_dir(&docker_root).unwrap(); let info = json!({"ID": "fixture", "OSType": "linux", "Architecture": std::env::consts::ARCH, "DockerRootDir": docker_root}); - let fakes = [ - ("docker", format!( - "case \"$1 $2\" in\n'context inspect') echo unix:///var/run/docker.sock ;;\n'info --format') if [ \"$3\" = '{{{{json .}}}}' ]; then echo '{info}'; else echo '{root}'; fi ;;\n*) exit 2 ;;\nesac\n", - root = docker_root.display() - )), - ("nvidia-smi", "[ \"$2\" = --format=csv,noheader,nounits ] || exit 2\ncase \"$1\" in\n--query-gpu=name,driver_version) echo 'NVIDIA GB10, 580.0' ;;\n--query-gpu=compute_cap) echo 12.1 ;;\n--query-gpu=memory.total,memory.free) echo '[N/A], [N/A]' ;;\n--query-compute-apps=pid) ;;\n*) exit 2 ;;\nesac\n".into()), - ]; - for (name, body) in fakes { - let path = bin.join(name); - fs::write( - &path, - format!( - "#!/bin/sh\nprintf '%s\\n' \"{name} $*\" >> '{}'\n{body}", - calls.display() - ), - ) - .unwrap(); - fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap(); - } - let path = format!("{}:{}", bin.display(), std::env::var("PATH").unwrap()); - let result = Command::new("sh") - .args(["-c", COLLECT]) - .env("PATH", path) + // Shell functions preserve the collector's command arguments without + // executing newly written files that another spawn could hold writable. + let fakes = r#"docker() { + printf '%s\n' "docker $*" >> "$TEST_COLLECT_CALLS" + case "$1 $2" in + 'context inspect') printf '%s\n' unix:///var/run/docker.sock ;; + 'info --format') + case "$3" in + '{{json .}}') printf '%s\n' "$TEST_COLLECT_INFO" ;; + '{{.DockerRootDir}}') printf '%s\n' "$TEST_COLLECT_ROOT" ;; + *) return 2 ;; + esac ;; + *) return 2 ;; + esac +} +nemoclaw_nvidia_smi() { + printf '%s\n' "nvidia-smi $*" >> "$TEST_COLLECT_CALLS" + [ "$2" = --format=csv,noheader,nounits ] || return 2 + case "$1" in + --query-gpu=name,driver_version) printf '%s\n' 'NVIDIA GB10, 580.0' ;; + --query-gpu=compute_cap) printf '%s\n' 12.1 ;; + --query-gpu=memory.total,memory.free) printf '%s\n' '[N/A], [N/A]' ;; + --query-compute-apps=pid) ;; + *) return 2 ;; + esac +} +alias nvidia-smi=nemoclaw_nvidia_smi +"#; + let result = Command::new("/bin/sh") + .args(["-c", &format!("{fakes}\n{COLLECT}")]) + .env("TEST_COLLECT_CALLS", &calls) + .env("TEST_COLLECT_INFO", info.to_string()) + .env("TEST_COLLECT_ROOT", &docker_root) .env_remove("DOCKER_HOST") .output() .unwrap(); diff --git a/crates/nemoclaw-provider/src/managed/backend.rs b/crates/nemoclaw-provider/src/managed/backend.rs index 5a1b172f710..ade1bb58eff 100644 --- a/crates/nemoclaw-provider/src/managed/backend.rs +++ b/crates/nemoclaw-provider/src/managed/backend.rs @@ -117,7 +117,7 @@ fn configured_specification(kind: &str, row: &Row) -> Result { } fn diagnostic(error: &Error) -> ObservationError { match error { - Error::Observation(error) => *error, + Error::Observation(error) => error.clone(), Error::State(message) | Error::Conflict(message) => ObservationError::Backend(message), Error::PartialRuntime => ObservationError::Backend( "managed container is absent but owned persistent resources remain", diff --git a/crates/nemoclaw-provider/src/services/installers/ollama/backend.rs b/crates/nemoclaw-provider/src/services/installers/ollama/backend.rs index f54a46342fc..01b5b2cace3 100644 --- a/crates/nemoclaw-provider/src/services/installers/ollama/backend.rs +++ b/crates/nemoclaw-provider/src/services/installers/ollama/backend.rs @@ -20,7 +20,7 @@ impl ProxyBackend { } fn diagnostic(error: &Error) -> ObservationError { match error { - Error::Observation(error) => *error, + Error::Observation(error) => error.clone(), Error::State(message) | Error::Conflict(message) => ObservationError::Backend(message), Error::PartialRuntime => { ObservationError::Backend("Ollama proxy is absent but owned persistent storage remains") diff --git a/crates/nemoclaw-runtime/src/vllm/runtime/inline_recipe.rs b/crates/nemoclaw-runtime/src/vllm/runtime/inline_recipe.rs index 11c16268210..68d8c5091e5 100644 --- a/crates/nemoclaw-runtime/src/vllm/runtime/inline_recipe.rs +++ b/crates/nemoclaw-runtime/src/vllm/runtime/inline_recipe.rs @@ -113,15 +113,18 @@ impl Runner for PackagedRecipe<'_> { #[cfg(test)] mod tests { use super::*; - use std::os::unix::fs::PermissionsExt; + use std::os::unix::fs::symlink; #[tokio::test] async fn pinned_executable_receives_structured_input_and_tampering_stops_execution() { let service = crate::fixture(); let mut recipe = service.recipe.clone().unwrap(); let root = tempfile::tempdir().unwrap(); - let executable = root.path().join("tool with spaces"); - std::fs::write(&executable, b"#!/bin/sh\ncat\n").unwrap(); - std::fs::set_permissions(&executable, std::fs::Permissions::from_mode(0o700)).unwrap(); + // Alias only the directory: the pinned executable remains a regular + // existing binary, and its path still exercises spaces without a shell. + let cat = std::fs::canonicalize("/bin/cat").unwrap(); + let directory = root.path().join("tools with spaces"); + symlink(cat.parent().unwrap(), &directory).unwrap(); + let executable = directory.join(cat.file_name().unwrap()); recipe.preparation.executable = executable.to_str().unwrap().into(); recipe.preparation.sha256 = crate::files::hash_file(&executable).unwrap(); recipe.verification = recipe.preparation.clone(); @@ -140,12 +143,17 @@ mod tests { .unwrap(); let output: serde_json::Value = serde_json::from_slice(&bytes).unwrap(); assert_eq!(output["modelDirectory"], root.path().to_str().unwrap()); - std::fs::write(&executable, b"#!/bin/sh\nexit 0\n").unwrap(); - assert!( + // Replace the alias with local tampered bytes; never modify the host binary. + std::fs::remove_file(&directory).unwrap(); + std::fs::create_dir(&directory).unwrap(); + std::fs::write(&executable, b"changed recipe executable").unwrap(); + assert!(matches!( runner .run(Action::Prepare, &request, &CancellationToken::new()) - .await - .is_err() - ); + .await, + Err(Error::Conflict( + "recipe executable does not match its declared digest" + )) + )); } } diff --git a/crates/nemoclaw-runtime/src/vllm/runtime/process.rs b/crates/nemoclaw-runtime/src/vllm/runtime/process.rs index cfe47eb00ac..20807c8cf6b 100644 --- a/crates/nemoclaw-runtime/src/vllm/runtime/process.rs +++ b/crates/nemoclaw-runtime/src/vllm/runtime/process.rs @@ -98,20 +98,16 @@ mod tests { let bin = root.path().join("bin"); std::fs::create_dir_all(&bin).unwrap(); let python = bin.join("python3"); - // A disposable executable stands in for Python/vLLM and verifies the - // process boundary. The readiness fixture independently checks HTTP. + // The existing interpreter accepts the production -m argument and + // reads the module-named fixture from the child's working directory. + // No newly written fixture is executed; inherited writable descriptors + // cannot prevent this child from starting. + std::os::unix::fs::symlink("/bin/sh", &python).unwrap(); std::fs::write( - &python, - "#!/bin/sh\ntest \"$VLLM_API_KEY\" = \"$(/bin/cat \"$TEST_KEY_FILE\")\"\n", + root.path().join("vllm.entrypoints.openai.api_server"), + "[ \"$1\" = --model ] && [ \"$2\" = \"$TEST_MODEL_DIRECTORY\" ] || exit 1\ntest \"$VLLM_API_KEY\" = \"$(/bin/cat \"$TEST_KEY_FILE\")\"\n", ) .unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - let mut permissions = std::fs::metadata(&python).unwrap().permissions(); - permissions.set_mode(0o755); - std::fs::set_permissions(&python, permissions).unwrap(); - } let prepared = PreparedModel { model: root.path().join("model"), environment: [ @@ -120,6 +116,10 @@ mod tests { "TEST_KEY_FILE".into(), root.path().join("inference-key").into_os_string(), ), + ( + "TEST_MODEL_DIRECTORY".into(), + root.path().join("model").into_os_string(), + ), ] .into(), }; @@ -131,6 +131,7 @@ mod tests { Some(key.clone()), ) .unwrap(); + command.command_mut().current_dir(root.path()); assert!(command.spawn().unwrap().wait().await.unwrap().success()); assert!(readiness.url.ends_with("/v1/models")); let expected = format!("Bearer {key}"); diff --git a/crates/nemoclaw-sdk/src/deployment/tests.rs b/crates/nemoclaw-sdk/src/deployment/tests.rs index ab22e6e3c69..0f1c56f1c1e 100644 --- a/crates/nemoclaw-sdk/src/deployment/tests.rs +++ b/crates/nemoclaw-sdk/src/deployment/tests.rs @@ -480,7 +480,6 @@ fn credential_references_cannot_override_helm_or_kubernetes_controls() { #[cfg(unix)] #[tokio::test] async fn schema_commands_do_not_require_inference_credentials() { - use std::os::unix::fs::PermissionsExt; use std::sync::atomic::{AtomicUsize, Ordering}; #[derive(Default)] @@ -494,17 +493,21 @@ async fn schema_commands_do_not_require_inference_credentials() { let bundle_directory = tempfile::tempdir().unwrap(); let bundle = fixture_bundle(bundle_directory.path()); fs::create_dir_all(bundle.tofu().parent().unwrap()).unwrap(); - fs::write( - bundle.tofu(), - b"#!/bin/sh\n[ \"$TF_IN_AUTOMATION\" = 1 ] && [ \"$TF_INPUT\" = 0 ] && [ \"$CHECKPOINT_DISABLE\" = 1 ] && [ \"$TF_CLI_CONFIG_FILE\" = \"$PWD/providers.tfrc\" ] || exit 1\nprintf '{}\\n'\n", - ) - .unwrap(); - fs::set_permissions(bundle.tofu(), fs::Permissions::from_mode(0o700)).unwrap(); + // Execute an existing interpreter so inherited writable fixture descriptors + // cannot make a newly written script fail to launch with ETXTBSY. + std::os::unix::fs::symlink("/bin/sh", bundle.tofu()).unwrap(); let state_directory = tempfile::tempdir().unwrap(); // macOS temporary paths may traverse /var -> /private/var; the shell's PWD // uses the physical directory when checking the fixture's environment. let state_path = state_directory.path().canonicalize().unwrap(); let store = Store::open(&state_path).unwrap(); + for operation in ["init", "show"] { + fs::write( + state_path.join(operation), + b"#!/bin/sh\n[ \"$TF_IN_AUTOMATION\" = 1 ] && [ \"$TF_INPUT\" = 0 ] && [ \"$CHECKPOINT_DISABLE\" = 1 ] && [ \"$TF_CLI_CONFIG_FILE\" = \"$PWD/providers.tfrc\" ] || exit 1\nprintf '{}\\n'\n", + ) + .unwrap(); + } let secrets = Arc::new(Unavailable::default()); let deployment = Deployment::new(&state_path, bundle_directory.path()).with_secrets(secrets.clone()); diff --git a/crates/nemoclaw-sdk/src/process.rs b/crates/nemoclaw-sdk/src/process.rs index 434e5672c71..be809bffd68 100644 --- a/crates/nemoclaw-sdk/src/process.rs +++ b/crates/nemoclaw-sdk/src/process.rs @@ -447,22 +447,21 @@ fn kubernetes_connection_environment_requires_explicit_operation_overrides() { #[cfg(unix)] #[tokio::test] async fn only_normal_apply_failure_can_establish_postcondition_evidence() { - use std::os::unix::fs::PermissionsExt; let directory = tempfile::tempdir().unwrap(); - let binary = directory.path().join("tofu"); + // Let the existing interpreter read the fixture even if another child + // inherited a writable descriptor while the script was being created. std::fs::write( - &binary, + directory.path().join("apply"), r##"#!/bin/sh printf '%s\n' '{"type":"version","ui":"1.2"}' '{"type":"diagnostic","diagnostic":{"severity":"error","summary":"Resource postcondition failed","snippet":{"context":"data.example_readiness.main.lifecycle.postcondition[0]"}}}' -exit "$3" +exit "$2" "##, ) .unwrap(); - std::fs::set_permissions(&binary, std::fs::Permissions::from_mode(0o700)).unwrap(); for (exit, expected) in [("1", true), ("2", false)] { let error = run_with_progress( directory.path(), - &binary, + Path::new("/bin/sh"), &["apply", "-json", exit], &BTreeMap::new(), &CancellationToken::new(), diff --git a/crates/nemoclaw-sdk/src/state/mod.rs b/crates/nemoclaw-sdk/src/state/mod.rs index 568f9b94da7..2615239d819 100644 --- a/crates/nemoclaw-sdk/src/state/mod.rs +++ b/crates/nemoclaw-sdk/src/state/mod.rs @@ -434,6 +434,14 @@ pub(crate) struct Store { pub directory: PathBuf, _lock: File, } +impl Drop for Store { + fn drop(&mut self) { + // A concurrently spawned child can retain the shared open file + // description until exec. Closing our descriptor alone would then + // leave the deployment locked after this operation has finished. + let _ = self._lock.unlock(); + } +} impl Store { pub fn open(directory: &Path) -> Result { let mut builder = fs::DirBuilder::new(); diff --git a/crates/nemoclaw-sdk/src/state/tests.rs b/crates/nemoclaw-sdk/src/state/tests.rs index e93d1b11909..276aae5d23d 100644 --- a/crates/nemoclaw-sdk/src/state/tests.rs +++ b/crates/nemoclaw-sdk/src/state/tests.rs @@ -3,6 +3,29 @@ use super::*; +#[cfg(unix)] +#[test] +fn dropping_store_releases_lock_while_a_duplicate_descriptor_remains_open() { + let directory = tempfile::tempdir().unwrap(); + let store = Store::open(directory.path()).unwrap(); + // Model the shared open file description inherited by a concurrent spawn + // before exec closes the child's copy, without depending on spawn timing. + let inherited = store._lock.try_clone().unwrap(); + assert!(Store::open(directory.path()).is_err()); + drop(store); + + let reopened = Store::open(directory.path()) + .expect("dropping the store must release ownership even while a duplicate remains open"); + assert!(Store::open(directory.path()).is_err()); + drop(inherited); + assert!( + Store::open(directory.path()).is_err(), + "closing the old descriptor must not unlock the new owner" + ); + drop(reopened); + Store::open(directory.path()).unwrap(); +} + #[test] fn lock_excludes_other_operations_and_atomic_intent_survives_reopen() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/nemoclaw-sdk/tests/error.rs b/crates/nemoclaw-sdk/tests/error.rs index 4978adef3e6..3a24bcd79c0 100644 --- a/crates/nemoclaw-sdk/tests/error.rs +++ b/crates/nemoclaw-sdk/tests/error.rs @@ -3,6 +3,51 @@ use nemoclaw_sdk::{Error, ObservationError, config::ConfigError}; use std::error::Error as _; +#[test] +fn workload_details_redact_short_bearer_and_quoted_credentials() { + for detail in [ + "Authorization: Bearer short-secret", + r#"{"api_key":"short-secret"}"#, + r#"{"Authorization": "Bearer short-secret"}"#, + "token='short-secret'", + ] { + let safe = ObservationError::sanitized_detail(detail); + assert!(!safe.contains("short-secret"), "{safe}"); + } +} + +#[test] +fn workload_details_are_single_line_bounded_and_redact_token_like_runs() { + let token = "0123456789abcdef".repeat(4); + let detail = format!( + "stopped: model digest mismatch\n\u{1b}[31m Bearer short-secret token=small {token} {}", + "diagnostic ".repeat(200) + ); + let safe = ObservationError::sanitized_detail(&detail); + assert!(safe.len() <= 1024); + assert!(safe.bytes().all(|byte| (b' '..=b'~').contains(&byte))); + assert!(safe.contains("model digest mismatch")); + for secret in [token.as_str(), "short-secret", "small"] { + assert!(!safe.contains(secret)); + } +} + +#[test] +fn resource_details_preserve_only_the_exact_known_name_outside_credentials() { + let name = "nc-0123456789abcdef-model-0123456789abcdef"; + let detail = format!( + "Pod {name:?}\n\u{1b}[31m prefix{name} {name}-suffix other-0123456789abcdef0123456789abcdef Bearer {name} api_key='{name}' {}", + "diagnostic ".repeat(200) + ); + let safe = ObservationError::sanitized_resource_detail(&detail, name); + assert!(safe.starts_with(&format!("Pod {name:?}")), "{safe}"); + assert_eq!(safe.matches(name).count(), 1, "{safe}"); + assert!(!safe.contains("other-0123456789abcdef0123456789abcdef")); + assert!(safe.len() <= 1024); + assert!(safe.bytes().all(|byte| (b' '..=b'~').contains(&byte))); + assert!(!ObservationError::sanitized_detail(&detail).contains(name)); +} + #[test] fn wrapped_sdk_errors_preserve_their_typed_sources_and_messages() { let diagnostic = nemoclaw_runtime::config::ConfigError::new("invalid configuration"); diff --git a/crates/nemoclaw-sdk/tests/kubernetes_connection.rs b/crates/nemoclaw-sdk/tests/kubernetes_connection.rs index b4b401cef67..bb96cfcd561 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_connection.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_connection.rs @@ -15,17 +15,15 @@ fn kubeconfig(directory: &std::path::Path, server: &str) -> std::path::PathBuf { "#!/bin/sh\nprintf '%s' '{\"apiVersion\":\"client.authentication.k8s.io/v1\",\"kind\":\"ExecCredential\",\"status\":{\"token\":\"from-plugin\"}}'\n", ) .unwrap(); - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(&plugin, std::fs::Permissions::from_mode(0o700)).unwrap(); let path = directory.join("kubeconfig"); std::fs::write( &path, format!( "apiVersion: v1\nkind: Config\ncurrent-context: other\n\ clusters:\n- name: selected\n cluster:\n server: {server}\n- name: other\n cluster:\n server: http://127.0.0.1:9\n\ - users:\n- name: plugin\n user:\n exec:\n apiVersion: client.authentication.k8s.io/v1\n command: {}\n interactiveMode: Never\n\ + users:\n- name: plugin\n user:\n exec:\n apiVersion: client.authentication.k8s.io/v1\n command: /bin/sh\n args: [{}]\n interactiveMode: Never\n\ contexts:\n- name: selected\n context:\n cluster: selected\n user: plugin\n- name: other\n context:\n cluster: other\n user: plugin\n", - plugin.display() + serde_json::to_string(&plugin).unwrap() ), ) .unwrap(); diff --git a/crates/nemoclaw-sdk/tests/kubernetes_operations.rs b/crates/nemoclaw-sdk/tests/kubernetes_operations.rs index 112a8557756..bffea9f7bc2 100644 --- a/crates/nemoclaw-sdk/tests/kubernetes_operations.rs +++ b/crates/nemoclaw-sdk/tests/kubernetes_operations.rs @@ -1058,7 +1058,7 @@ async fn release_storage_query_errors_stop_observation_and_issuer_cleanup() { let before = objects.0.lock().unwrap().clone(); assert_eq!( failing.read(&spec(AUTH_KIND), auth.id.as_deref()).await, - Err(error) + Err(error.clone()) ); assert_eq!( failing.remove(&spec(AUTH_KIND), auth.id.as_deref()).await, diff --git a/crates/nemoclaw-sdk/tests/refresh.rs b/crates/nemoclaw-sdk/tests/refresh.rs index 5ed352a6c7c..00dc05cebba 100644 --- a/crates/nemoclaw-sdk/tests/refresh.rs +++ b/crates/nemoclaw-sdk/tests/refresh.rs @@ -50,7 +50,7 @@ fn observation_failures_stop_refresh_without_consuming_prior_state() { ] { let prior = prior(); let saved = prior.clone(); - assert_eq!(refresh(&prior, Err(error)), Err(error)); + assert_eq!(refresh(&prior, Err(error.clone())), Err(error)); assert_eq!(prior, saved); } } diff --git a/crates/nemoclaw-test-fixtures/src/openshell.rs b/crates/nemoclaw-test-fixtures/src/openshell.rs index 5fc4e84b776..9229784005a 100644 --- a/crates/nemoclaw-test-fixtures/src/openshell.rs +++ b/crates/nemoclaw-test-fixtures/src/openshell.rs @@ -69,6 +69,9 @@ pub struct State { pub active_sandbox_creates: usize, pub peak_sandbox_creates: usize, pub fail_read: Option<(&'static str, tonic::Code)>, + /// Reject one RPC before its handler can mutate fixture state. + pub reject_rpc: Option<(&'static str, tonic::Code, String)>, + pub rejected_rpcs: Vec, } impl State { fn created(&mut self, kind: &str) { @@ -192,6 +195,20 @@ impl tower::Service> for Service { fn call(&mut self, request: http::Request) -> Self::Future { let state = self.0.clone(); Box::pin(async move { + let rejection = { + let mut state = state.lock().unwrap(); + let rejection = state + .reject_rpc + .clone() + .filter(|(rpc, _, _)| request.uri().path().rsplit('/').next() == Some(*rpc)); + rejection.map(|(rpc, code, detail)| { + state.rejected_rpcs.push(rpc.into()); + Status::new(code, detail) + }) + }; + if let Some(rejection) = rejection { + return Ok(rejection.into_http()); + } if state .lock() .unwrap() diff --git a/crates/nemoclaw-test-fixtures/src/tofu.rs b/crates/nemoclaw-test-fixtures/src/tofu.rs index 70f16b04440..c7879372833 100644 --- a/crates/nemoclaw-test-fixtures/src/tofu.rs +++ b/crates/nemoclaw-test-fixtures/src/tofu.rs @@ -105,7 +105,13 @@ mod tests { let staged = workspace .path() .join(crate::executable("terraform-provider-nemoclaw")); - let output = Command::new(&staged).output().unwrap(); + // OpenTofu executes the staged provider, so staging must keep the + // executable bit even though this test runs it through /bin/sh. + assert_ne!( + fs::metadata(&staged).unwrap().permissions().mode() & 0o111, + 0 + ); + let output = Command::new("/bin/sh").arg(&staged).output().unwrap(); assert!(output.status.success()); assert_eq!(output.stdout, selected.as_bytes()); assert_eq!(fs::read_to_string(&provider).unwrap(), script); diff --git a/crates/openshell-provider/src/connected.rs b/crates/openshell-provider/src/connected.rs index 92dd05b636a..6a46e110372 100644 --- a/crates/openshell-provider/src/connected.rs +++ b/crates/openshell-provider/src/connected.rs @@ -138,7 +138,7 @@ impl ConnectedOpenShellGateway { ..Default::default() })) .await - .map_err(|error| remote_error(&error))? + .map_err(|error| nemoclaw_openshell::remote_rejection("CreateWorkspace", &error))? .into_inner(); let row = base(response.workspace.and_then(|w| w.metadata), name, false)?; verify_identity(want, &row)?; @@ -207,7 +207,7 @@ impl ConnectedOpenShellGateway { }), ) .await - .map_err(|error| remote_error(&error))? + .map_err(|error| nemoclaw_openshell::remote_rejection("CreateSandbox", &error))? .into_inner(); let row = base(response.sandbox.and_then(|s| s.metadata), name, false)?; verify_identity(want, &row)?; @@ -339,7 +339,12 @@ impl ConnectedOpenShellGateway { if let Err(status) = result && status.code() != tonic::Code::NotFound { - return Err(remote_error(&status)); + let operation = if kind == "provider_profile" { + "DeleteProviderProfile" + } else { + "DeleteProvider" + }; + return Err(nemoclaw_openshell::remote_rejection(operation, &status)); } Ok(()) } diff --git a/crates/openshell-provider/src/fake_gateway_tests.rs b/crates/openshell-provider/src/fake_gateway_tests.rs index 0b78bedf0af..ad31e47f1d2 100644 --- a/crates/openshell-provider/src/fake_gateway_tests.rs +++ b/crates/openshell-provider/src/fake_gateway_tests.rs @@ -108,6 +108,43 @@ async fn sandbox_teardown_requires_owned_identity_but_not_its_previous_configura assert_eq!(fixture.state.lock().unwrap().delete_calls, 2); } +#[tokio::test] +async fn ready_sandbox_teardown_needs_owned_identity_but_not_active_policy_status() { + let fixture = Fixture::start().await; + let client = client(&fixture, Arc::new(EnvironmentSecrets)); + let binding = create_sandbox(&client, "local").await; + let key = key(&binding); + let original = fixture.state.lock().unwrap().sandboxes[&key].clone(); + fixture.state.lock().unwrap().fail_read = Some(("policy", tonic::Code::Unavailable)); + assert!(client.read("sandbox", &binding, false).await.is_err()); + let observed = client + .read("sandbox", &binding, true) + .await + .unwrap() + .unwrap(); + assert_eq!(observed, binding); + for field in ["id", "owner", "generation"] { + fixture + .state + .lock() + .unwrap() + .sandboxes + .insert(key.clone(), substituted(&original, field)); + assert!(client.remove("sandbox", &binding, true).await.is_err()); + assert_eq!(fixture.state.lock().unwrap().delete_calls, 0); + } + fixture + .state + .lock() + .unwrap() + .sandboxes + .insert(key.clone(), original); + client.remove("sandbox", &binding, true).await.unwrap(); + let state = fixture.state.lock().unwrap(); + assert_eq!(state.delete_calls, 1); + assert!(!state.sandboxes.contains_key(&key)); +} + struct Keys; impl Secrets for Keys { fn resolve(&self, _: &str) -> Result { @@ -115,6 +152,131 @@ impl Secrets for Keys { } } +#[tokio::test] +async fn gateway_validation_rejections_preserve_details_for_credential_free_mutations() { + const DETAIL: &str = "network endpoint ambiguity validation failed: network policies 'nemoclaw-inference-qwen' endpoint[0] (model.namespace.svc.cluster.local:18888/v1/**) and '_provider_qwen' endpoint[0] (model.namespace.svc.cluster.local:18888/v1/**) overlap on port(s) 18888 with conflicting metadata: allowed_ips=[] vs [\"10.96.189.228/32\"]"; + for (rpc, kind, creating) in [ + ("CreateWorkspace", "workspace", true), + ("CreateSandbox", "sandbox", true), + ("DeleteProvider", "provider", false), + ("DeleteProviderProfile", "provider_profile", false), + ] { + let fixture = Fixture::start().await; + let client = client(&fixture, Arc::new(Keys)); + let rows = fixture_rows("hermes-auth"); + let mut bindings = std::collections::BTreeMap::new(); + for (row_kind, row) in &rows { + if creating && *row_kind == kind { + break; + } + let result = client.ensure(row_kind, row).await; + assert!(result.error().is_none(), "{row_kind}: {:?}", result.error()); + bindings.insert(*row_kind, result.into_parts().0.unwrap()); + } + let effects = fixture.state.lock().unwrap().effects; + fixture.state.lock().unwrap().reject_rpc = + Some((rpc, tonic::Code::FailedPrecondition, DETAIL.into())); + let error = if creating { + client + .ensure( + kind, + &rows + .iter() + .find(|(row_kind, _)| *row_kind == kind) + .unwrap() + .1, + ) + .await + .error() + .unwrap() + } else { + client + .remove(kind, &bindings[kind], true) + .await + .unwrap_err() + }; + let ObservationError::Rejected { + operation, + code, + detail, + } = error + else { + panic!("missing {rpc} rejection detail: {error}"); + }; + assert_eq!(operation, rpc); + assert_eq!(code, "FailedPrecondition"); + assert_eq!(detail.as_ref(), DETAIL); + let state = fixture.state.lock().unwrap(); + assert_eq!(state.rejected_rpcs, [rpc]); + assert_eq!(state.effects, effects); + } +} + +#[tokio::test] +async fn credential_requests_reads_and_exec_keep_backend_rejection_text_private() { + for rpc in [ + "CreateProvider", + "UpdateProvider", + "GetSandbox", + "ExecSandbox", + ] { + let fixture = Fixture::start().await; + let client = client(&fixture, Arc::new(Keys)); + let rows = fixture_rows("hermes-auth"); + let mut bindings = std::collections::BTreeMap::new(); + for (kind, row) in &rows { + if rpc == "CreateProvider" && *kind == "provider" { + break; + } + let result = client.ensure(kind, row).await; + assert!(result.error().is_none(), "{kind}: {:?}", result.error()); + bindings.insert(*kind, result.into_parts().0.unwrap()); + } + fixture.state.lock().unwrap().reject_rpc = Some(( + rpc, + tonic::Code::FailedPrecondition, + "PRIVATE_SENTINEL".into(), + )); + let error = match rpc { + "CreateProvider" => client + .ensure( + "provider", + &rows.iter().find(|(kind, _)| *kind == "provider").unwrap().1, + ) + .await + .error() + .unwrap(), + "UpdateProvider" => { + let mut provider = bindings["provider"].clone(); + provider.insert("credential_env".into(), "SECOND_KEY".into()); + client.ensure("provider", &provider).await.error().unwrap() + } + "GetSandbox" => client + .read("sandbox", &bindings["sandbox"], false) + .await + .unwrap_err(), + _ => { + let error = client + .exec_bound( + &bindings["sandbox"], + vec!["true".into()], + Default::default(), + 5, + ) + .await + .unwrap_err(); + let nemoclaw_backend::Error::Observation(error) = error else { + panic!("unexpected exec error: {error}"); + }; + error + } + }; + assert_eq!(error, ObservationError::Query, "{rpc}"); + assert!(!error.to_string().contains("PRIVATE_SENTINEL")); + assert_eq!(fixture.state.lock().unwrap().rejected_rpcs, [rpc]); + } +} + #[tokio::test] async fn owning_api_reconciles_lost_create_reply_and_checks_conditional_updates() { let fixture = Fixture::start().await; diff --git a/crates/openshell-provider/src/gateway_source.rs b/crates/openshell-provider/src/gateway_source.rs index fc206966a40..c9b64f81ecf 100644 --- a/crates/openshell-provider/src/gateway_source.rs +++ b/crates/openshell-provider/src/gateway_source.rs @@ -348,7 +348,7 @@ mod wait_tests { assert_eq!( observe_with_wait::<(), _>(Duration::from_secs(2), || { calls.fetch_add(1, Ordering::SeqCst); - std::future::ready(Err(error)) + std::future::ready(Err(error.clone())) }) .await .unwrap_err(), diff --git a/crates/openshell-provider/src/transport.rs b/crates/openshell-provider/src/transport.rs index 76354530d46..9d623a5c359 100644 --- a/crates/openshell-provider/src/transport.rs +++ b/crates/openshell-provider/src/transport.rs @@ -196,7 +196,7 @@ impl ConnectedOpenShellGateway { return Ok(None); }; let (row, ready) = sandbox_row(response, name, removing)?; - if ready { + if ready && !removing { let status = self .client .raw_grpc() diff --git a/docs/agents.md b/docs/agents.md index 898a1196dfb..e294f9acbe7 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -52,7 +52,27 @@ No request walkthrough has been rehearsed yet ([#12642](https://github.com/NVIDI ### Run One Headless OpenClaw Request Headless operation follows the same public Fabric invocation boundary. -Native gateway configuration and request semantics belong to the OpenClaw adapter. +The [pinned OpenClaw adapter](https://github.com/NVIDIA/NeMo-Fabric/blob/24f068c895e5cbc30286bc743498be4e5014d658/adapters/python/openclaw/src/nemo_fabric_adapters/openclaw/adapter.py) accepts an object with exactly `agent` and `message` for an explicit native-agent request. +A request can incur inference charges and affect retained conversation history. + +**A malformed request can leave the runtime unusable.** +With the current pinned OpenClaw adapter, an operator reported later invocations failing with `runtime_unavailable`, a bridge `runtime_state` of `unknown`, and subsequent deployment operations failing with `observation is incomplete`. +Apply cannot recover while the runtime observation is `unknown`, even after a configuration edit; the operator recovered by replacing the sandbox. +The [CLI replacement procedure](usage.md#replace-workloads-after-an-unusable-openclaw-runtime) destroys all of the deployment's sandboxes, including their files and conversation history, while retaining managed model and credential storage. +The affected input cases and recovery inside the existing sandbox remain unqualified ([#12642](https://github.com/NVIDIA/NemoClaw/issues/12642)). + +With a configured runtime, run this from any directory inside the target sandbox when its YAML `agent.name` is `assistant` and its native OpenClaw agent is the default `main`: + +```sh +fabric-agent invoke --agent assistant --input - <<'JSON' +{"agent":"main","message":"Reply with exactly READY."} +JSON +``` + +The command's `--agent` selects the deployment's YAML `agent.name`; the JSON `agent` selects OpenClaw's native agent, set by `harness.settings.agent_name` and defaulting to `main`. +The bridge passes this JSON unchanged to OpenClaw; `{"text":"..."}` is not this adapter's request format. +On success, inspect `result.fabric_result.status` and `result.fabric_result.output.response`; a successful command does not establish general model compatibility. +Host-side invocation tooling also remains follow-up work ([#12642](https://github.com/NVIDIA/NemoClaw/issues/12642)). For browser access, see [agent interfaces](interfaces.md#openclaw-dashboard). ## Native Controls at Initialization @@ -165,7 +185,7 @@ Fabric's Pi adapter owns that metadata's schema and mapping. The SDK forwards the selected provider API as a public model extension and preserves each named route plus the `default` role. Model and settings updates reconcile a reconstructible agent-configuration resource for every adapter. -When sandbox identity, provider attachments, image, and policy remain unchanged, the runtime restarts inside the existing sandbox. +When sandbox identity, provider attachments, image, and policy remain unchanged and runtime observation succeeds, the runtime restarts inside the existing sandbox. In-memory conversations can be lost; retained native files remain subject to the adapter's lifecycle. Changing sandbox resources can still require a separate deployment under the normal replacement protections. diff --git a/docs/provider.md b/docs/provider.md index 21d2f8667aa..3cf8a94da6a 100644 --- a/docs/provider.md +++ b/docs/provider.md @@ -47,6 +47,13 @@ Every provider type has a [lifecycle test](contributing/integration-tests.md) th These tests do not qualify a complete standalone deployment workflow. Do not edit SDK-generated graphs or share a deployment state directory between independently managed workflows. +### Gateway Profile Format Upgrade + +The OpenShell 0.1.3 integration stores provider-profile metadata in separate annotations. +Gateway profiles created by earlier bundles used one `nemoclaw.nvidia.com/profile-v1` annotation; the current provider cannot read that format and reports an identity mismatch during plan, apply, or destroy. +There is no automatic migration. +This gateway-side format break is separate from the provider-type change described above. + ## Provider Catalog The bundle pins these providers: diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index eb77b6f1bdd..1dc4effefbf 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -15,7 +15,7 @@ The CLI writes operation results to stdout and failures to stderr; it has no sep Do not rerun apply just to collect output after an uncertain mutation. First resolve the reported failure using the table below. -When ordinary planning is appropriate, collect a read-only runtime preview from the directory containing `deployment.yaml`: +When planning is appropriate, collect a read-only runtime preview from the directory containing `deployment.yaml`: ```sh diagnostic_dir=$(mktemp -d) @@ -40,13 +40,15 @@ Do not attach environment dumps, TLS private keys, interface tokens, or the enti | `state is bound to a different deployment UID or gateway` | Restore the original UID and gateway endpoint; a new target needs separate state and resources | | `unfinished apply has different intent` | Reapply the exact YAML from the unfinished operation before trying another configuration | | Deployment lock error | Check for another operation using the same state directory; a lock failure does not authorize state deletion | -| Authentication, transport, or incomplete-observation error | Restore access to the selected service; failed observation does not establish absence or authorize recreation | +| Authentication, transport, or incomplete-observation error | Restore access to the selected service; failed observation does not establish absence or authorize recreation. For a persistently unknown OpenClaw runtime after an invocation failure, follow the [replacement procedure](usage.md#replace-workloads-after-an-unusable-openclaw-runtime) | | Ownership, generation, or durable identity mismatch | Inspect the selected gateway/engine and retained deployment identity; do not adopt or replace a different resource | +| Provider-profile identity mismatch after upgrading a bundle | Check the [gateway profile format break](provider.md#gateway-profile-format-upgrade); old `profile-v1` profiles require the original bundle for teardown or a separate deployment | | Plan would remove or replace a resource | Check [update constraints](usage.md#updates-and-recovery) and the relevant configuration guide before choosing a new deployment | | Interrupted apply | Resolve the cause and reapply the original YAML with its retained state | | Unfinished destroy | Resume destroy with the same state; other operations refuse unfinished teardown | | `adapter/ compatibility rejected` | Read the named sandbox and canonical field; for `models..max_tokens`, remove that route's `overrides.maxTokens` or choose an adapter that accepts it, then plan again | | Public Fabric configuration mismatch or native startup rejection | Follow [agent interface diagnosis](interfaces.md#diagnose-failures); retained public configuration checks do not audit native files or tokens | +| After a malformed OpenClaw request: `runtime_unavailable`, bridge `runtime_state: unknown`, then `observation is incomplete` | Apply cannot recover the unknown runtime, including through configuration edits; review the [reported failure and whole-deployment replacement procedure](usage.md#replace-workloads-after-an-unusable-openclaw-runtime), including loss of all sandbox files and history | For proxy policies, the pinned OpenShell supervisor can add read-only `/var/log` access to the loaded policy. NemoClaw accepts that runtime addition while preserving the authored policy; other loaded-policy differences still fail observation. @@ -107,10 +109,14 @@ Recognized reasons are `ControlSupervisorExited`, `ContainerExited`, `IdentityRe `ControlSupervisorStartFailed` means the control supervisor could not start; inspect the sandbox policy and attached providers. These explanations are fixed text, not the gateway's condition message. Error, completed, stopped, and deleting phases fail immediately and retain resources. -The SDK excludes unrecognized reasons and raw backend condition messages because they may contain credentials. +For sandbox status conditions, the SDK excludes unrecognized reasons and raw backend condition messages because they may contain credentials. +Synchronous OpenShell validation rejections for workspace creation, sandbox creation, and provider or provider-profile deletion preserve a sanitized printable-ASCII detail of at most 1024 characters. +For example, a network endpoint ambiguity can report conflicting `allowed_ips` metadata, identifying a policy/profile address-grant disagreement. +Credential-bearing provider creation and update requests, status reads, and exec failures retain category-only diagnostics. +This rejection reporting applies to Docker, Podman, and cluster gateways. Use the OpenShell inspection and log collection procedure below before cleanup. If startup requires a different image or policy, follow the [sandbox change procedure](usage.md#choose-the-change-path); apply protects the existing sandbox from replacement. -A failed first apply can be [destroyed](usage.md#destroy) with its retained state before a successful reapply. +A failed first apply can be [destroyed](usage.md#destroy) when the retained state accounts for its resource identities. The current CLI has no `doctor`, `status`, or diagnostic-bundle command. diff --git a/docs/usage.md b/docs/usage.md index bc8e45d8e3d..23875fdcf67 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -218,7 +218,7 @@ Use separate deployments when you need independent teardown. | Proposed change | Current behavior and next step | |---|---| -| Models, settings, or public Fabric configuration within the selected adapter | Reconciles the owned agent-configuration resource and restarts the runtime inside the existing sandbox when its image, provider attachments, and policy remain unchanged; in-memory conversations can be lost | +| Models, settings, or public Fabric configuration within the selected adapter | After successful runtime observation, reconciles the owned agent-configuration resource and restarts the runtime inside the existing sandbox when its image, provider attachments, and policy remain unchanged; in-memory conversations can be lost | | External inference endpoint, provider implementation, or authenticated/anonymous mode | Changes a selected provider's profile and registration; changes to an existing sandbox's launch specification still require a separate deployment | | Harness adapter, sandbox image, agent identity, or provider attachments | Changes the immutable sandbox specification; apply refuses replacement; use a separate deployment with a fresh UID and state | | Sandbox network policy | Changes the sandbox specification; follow [policy change constraints](sandbox-network.md) and use a separate deployment when replacement is required | @@ -228,6 +228,9 @@ Use separate deployments when you need independent teardown. | Remove a sandbox, retained storage, or a protected gateway binding | Apply refuses removal; assess a separate deployment and explicit retirement of the original | | Change a credential value behind the same environment reference | Unchanged apply does not detect rotation; see [credential lifecycle](security.md#credentials-and-authentication) | +Configuration edits do not recover a runtime whose bridge snapshot reports `runtime_state: unknown`. +The provider rejects that observation before reconciling agent configuration; see [replacement after an unusable OpenClaw runtime](#replace-workloads-after-an-unusable-openclaw-runtime). + For OpenClaw model and native-setting updates, use an [agent image built from this revision](build.md#build-agent-images). Rebuilding the CLI bundle alone does not update the adapter in an existing sandbox image; changing that image requires a separate deployment with a fresh UID and state. The packaged adapter tracks its native configuration sections, updates them during an explicit runtime restart, and preserves unrelated native bookkeeping and files. @@ -285,6 +288,8 @@ With the current bundle and bridge image, configuration failures report a fixed A failed restart retains the sandbox and its files. When Fabric cannot confirm that startup left no processes, the bridge reports `unknown` and refuses another lifecycle change; this protocol does not provide recovery for that state. An `unknown` runtime state does not establish that the old process stopped. +An invocation failure can also leave the runtime `unknown`; apply cannot reach configuration reconciliation while that observation remains incomplete. +For the operator-reported OpenClaw failure, see [workload replacement](#replace-workloads-after-an-unusable-openclaw-runtime). A sandbox in `Error` can still block apply, but its saved identity permits [teardown](#destroy) without a successful reapply. Changing a rejected sandbox policy or image does not authorize replacement; follow the [change constraints](#choose-the-change-path). @@ -294,6 +299,8 @@ Older unfinished records without per-resource recovery evidence still require th If managed gateway or inference runtime apply fails, revised intent or teardown can proceed using recorded bindings and the existing ownership checks. The same applies when an OpenShell-graph apply only observes resources, updates or deletes established bindings, or changes disposable compute. Runtime recovery does not clear pending OpenShell creations. +An OpenShell create rejection without a saved resource identity still leaves the pending-creation guard in place; automatic cleanup after a definitive rejection is not implemented. +Preserve that record and its original bundle rather than deleting state or attempting adoption from another state directory. Export remains unavailable during pending creation recovery, unfinished managed-runtime apply, or unfinished teardown. If an OpenShell-stage apply planned no non-disposable resource creations, a later export can verify its established bindings without another successful apply; incomplete or inconsistent observations still fail export. If readiness fails after resource creation, provider state and persistent data remain recorded. @@ -320,6 +327,45 @@ The installer contract has no separate recovery operation and does not create an Export preserves retained intent and validates required resource bindings without another readiness or model-inventory check. Destroy uses native provider compute/cache state and separately verified credential and gateway storage; it does not inspect model inventories. +### Replace Workloads After an Unusable OpenClaw Runtime + +Use this path when an OpenClaw runtime remains `unknown` after an invocation failure and you choose to replace its sandbox. +The [reported malformed-request failure](agents.md#run-one-headless-openclaw-request) required sandbox replacement; the exact inputs that trigger it and recovery inside the existing sandbox remain unqualified ([#12642](https://github.com/NVIDIA/NemoClaw/issues/12642)). +The CLI has no targeted sandbox replacement or runtime-reset command. +Its supported replacement path is whole-deployment destroy followed by reapplying the original configuration. + +**Destroy deletes every bound sandbox's files and conversation history, including those of other agents in this deployment.** +Preserve any native data you need before choosing removal; configuration export does not back it up and can fail while runtime observation is incomplete. +Managed model and credential storage remain tracked; that storage does not preserve sandbox files. +Keep the original YAML, matching bundle, credential references, and entire state directory. +Do not replace the state directory or change the deployment UID to bypass the failure. + +From the directory containing the original `deployment.yaml`, with the matching bundle on `PATH`, preview the removal using the deployment's existing state path: + +```sh +nemoclaw plan --destroy --state-dir .local/deployment +``` + +Teardown verifies the parent sandbox's identity without requiring a successful agent-runtime snapshot or health check. +It still requires gateway access, matching ownership, and saved bindings for pending creations; if the preview fails, retain state and resolve that error before proceeding. +After reviewing the whole-deployment removal and accepting its data loss, run: + +```sh +nemoclaw destroy --state-dir .local/deployment +``` + +Destroy does not prompt for confirmation. +If it fails or is interrupted, resolve the cause and resume destroy with the same state; do not reapply until destroy completes. +After a successful destroy, request workload recreation with the original configuration and retained storage: + +```sh +nemoclaw apply --state-dir .local/deployment deployment.yaml +``` + +This procedure follows the implemented CLI lifecycle; recovery from arbitrary malformed inputs remains unqualified. +The [Fabric health limitation](#fabric-health-during-apply) still applies after recreation. +Check the recreated runtime before using the [exact OpenClaw request](agents.md#run-one-headless-openclaw-request); do not replay an invocation whose effects are unknown merely to test recovery. + ### Recover an Interrupted Helm Removal This procedure applies to managed Kubernetes and OpenShift deployments. From 086dac1e2fb611149a247f621aee275c5566a0c6 Mon Sep 17 00:00:00 2001 From: Hai Nguyen Date: Mon, 12 Oct 2026 16:01:42 +0000 Subject: [PATCH 2/2] refactor(openshell-provider): inject a Services hook for cluster grants and profile sources ## Failure #12736 routes sandboxes to model Pods that the deployment runs in its cluster, and the OpenShell and Fabric providers could not express that: - Provider credentials are parsed and resolved only through `nemoclaw_docker::credentials`; a caller cannot supply another source. - An inference profile grants only the literal IP in its endpoint URL. A cluster model is reached by a `.svc.cluster.local` host, so a sandbox policy cannot grant its ClusterIP, and nothing checks which Service owns the address. - Two internal invariants, the profile metadata field set and the static search rule, were enforced with `expect`, so a violation would abort the provider instead of returning an observation error. Review finding N1b on #12736: only the ignored bundled lifecycle test constructed `FabricProvider::with_services`, so a regression that dropped the injected callbacks passed the regular test step. ## Decision - `openshell_provider::Services` validates and resolves credential sources, validates a cluster source, and returns a cluster Service's verified addresses. `DockerServices` keeps the Docker credential behaviour and returns `BindingMismatch` for every cluster source. `GatewayClient::with_services`, `OpenShell::connect_with_services`, `OpenShellProvider::with_services` and `FabricProvider::with_services` inject an implementation. `Default` and `OpenShell::connect` use `DockerServices`, and the bundled provider binaries still use the defaults. - `openshell_provider_profile` gains an optional `cluster_source`. It is a bound field, resets when omitted on update, and any change replaces the profile. `nemoclaw_openshell::profile::cluster_definition` accepts only an `http://.svc.cluster.local:/v1` endpoint and grants only the addresses `Services::cluster_addresses` returns, after `service_address_allowed` rejects unspecified, loopback, multicast, link-local, broadcast and IPv4-mapped addresses. The source and addresses are kept in their own annotations; refresh re-reads the addresses and refuses a profile whose endpoints no longer match. - `PolicyInput.cluster_grants` names managed rules whose `allowed_ips` come from verified cluster profiles (`RuntimeBinding::granted_policy`). Sandbox create and refresh check each grant against the deployment's own profile. The field is omitted from serialized policy when empty, so stored sandbox annotations do not change. - `nemoclaw_tofu::Definition::bound_fields`: refresh returns `BindingMismatch` when an observed bound field differs from state, treating omission as the empty value. Without it, a refresh wrote a substituted `cluster_source` into state. - `annotations()` returns `Result`, so unknown metadata returns `Incomplete`; an unparsable search rule returns `Query`. - The SDK's `image_runtime::policy_input` sets an empty `cluster_grants`; nothing in the SDK produces grants yet. Docker and Podman deployments are unchanged: the SDK emits no cluster source or cluster grants. The provider schema gains `openshell_provider_profile.cluster_source` and the `openshell_sandbox` policy block's `cluster_grants`; with `DockerServices`, a resource that sets either fails when the provider creates or reads it. ## Validation - `cargo ci` on linux_arm64 passed in 709 s: fmt, clippy `-D warnings`, build, 1393 nextest tests (174 skipped) and 4 doctests, schema, bundle, and 127 lifecycle tests (48 skipped), including all 44 `openshell-provider::contract` and 3 `fabric-provider::contract` tests. - On the base, the two new `nemoclaw-provider` refresh tests fail and the other four new tests do not compile. On this tree, each new test failed under a mutant of the production code it covers and passed without it: dropping the `bound_fields` check, restoring the v1 profile definition, making `FabricProvider::with_services` ignore its services (the N1b mutant), and restoring either `expect`. Split from #12736. Co-Authored-By: Claude Opus 5.5 --- crates/fabric-provider/src/provider.rs | 125 +++++ crates/nemoclaw-openshell/src/profile.rs | 66 ++- crates/nemoclaw-openshell/src/runtime.rs | 52 ++- crates/nemoclaw-provider/tests/refresh.rs | 99 ++++ crates/nemoclaw-provider/tests/support/mod.rs | 3 + crates/nemoclaw-sdk/src/image_runtime.rs | 6 +- crates/nemoclaw-tofu/src/lib.rs | 8 + crates/nemoclaw-tofu/src/resource.rs | 45 ++ crates/openshell-provider/src/client.rs | 24 +- crates/openshell-provider/src/connected.rs | 134 +++--- crates/openshell-provider/src/lib.rs | 99 +++- crates/openshell-provider/src/network.rs | 40 +- crates/openshell-provider/src/profile.rs | 436 +++++++++++++++--- crates/openshell-provider/src/provider.rs | 10 + crates/openshell-provider/src/transport.rs | 36 +- crates/openshell-provider/tests/schema.txt | 3 + 16 files changed, 1030 insertions(+), 156 deletions(-) diff --git a/crates/fabric-provider/src/provider.rs b/crates/fabric-provider/src/provider.rs index fdaeca833b3..64a019af1ad 100644 --- a/crates/fabric-provider/src/provider.rs +++ b/crates/fabric-provider/src/provider.rs @@ -71,6 +71,16 @@ pub struct FabricProvider { destroying: Arc, } +impl FabricProvider { + /// Observe sandbox parents with the deployment's managed service checks. + pub fn with_services(services: Arc) -> Self { + Self { + client: Arc::new(GatewayClient::with_services(services)), + destroying: Arc::default(), + } + } +} + #[async_trait] impl Provider for FabricProvider { type Config<'a> = GatewayConfig; @@ -163,4 +173,119 @@ mod tests { ); assert!(!provider.destroying.load(Ordering::Acquire)); } + + /// Accepts every cluster source, reports one Service address, and counts + /// both calls. The test uses no credential source, so those methods fail. + #[derive(Default)] + struct ClusterServices { + validations: std::sync::atomic::AtomicUsize, + address_reads: std::sync::atomic::AtomicUsize, + } + + #[async_trait] + impl openshell_provider::Services for ClusterServices { + fn validate_credential_source( + &self, + _: &str, + _: &str, + _: &str, + ) -> Result<(), ObservationError> { + Err(ObservationError::Incomplete) + } + + async fn resolve_credential_source( + &self, + _: &str, + _: &str, + _: &str, + ) -> Result { + Err(ObservationError::Incomplete) + } + + fn validate_cluster_source(&self, _: &Row) -> Result<(), ObservationError> { + self.validations.fetch_add(1, Ordering::SeqCst); + Ok(()) + } + + async fn cluster_addresses( + &self, + _: &Row, + ) -> Result, ObservationError> { + self.address_reads.fetch_add(1, Ordering::SeqCst); + Ok(vec!["10.96.0.23".parse().unwrap()]) + } + } + + #[tokio::test] + async fn configured_provider_observes_cluster_grants_through_its_injected_services() { + use nemoclaw_test_fixtures::openshell::{Fixture, contract_rows}; + + let fixture = Fixture::start().await; + let services = Arc::new(ClusterServices::default()); + let creator = GatewayClient::with_services(services.clone()); + creator + .connect(&nemoclaw_openshell::Connection { + endpoint: fixture.endpoint.clone(), + ..Default::default() + }) + .unwrap(); + let creator = creator.client().unwrap(); + let rows = contract_rows("fabric-openclaw"); + let row = |kind: &str| { + rows.iter() + .find(|(name, _)| *name == kind) + .unwrap() + .1 + .clone() + }; + let mut profile = row("provider_profile"); + profile.insert( + "endpoint".into(), + "http://model.agents.svc.cluster.local:8000/v1".into(), + ); + profile.insert("cluster_source".into(), "fixture-cluster-source".into()); + let mut saved = None; + for (kind, desired) in [ + ("workspace", row("workspace")), + ("provider_profile", profile), + ] { + let created = creator.ensure(kind, &desired).await; + assert!(created.error().is_none(), "{kind}: {:?}", created.error()); + saved = created.into_parts().0; + } + let saved = saved.unwrap(); + + let provider = FabricProvider::with_services(services.clone()); + let mut diagnostics = Diagnostics::default(); + let config = GatewayConfig { + endpoint: Value::Value(fixture.endpoint.clone()), + ..Default::default() + }; + provider + .configure(&mut diagnostics, String::new(), config) + .await + .unwrap(); + assert!(diagnostics.errors.is_empty()); + let calls = || { + ( + services.validations.load(Ordering::SeqCst), + services.address_reads.load(Ordering::SeqCst), + ) + }; + let before = calls(); + // Fabric resources and data sources observe sandbox parents through + // this client, so it must keep the injected cluster checks. + let observed = provider + .client + .client() + .unwrap() + .read("provider_profile", &saved, false) + .await; + assert_eq!(observed, Ok(Some(saved))); + let after = calls(); + assert!( + after.0 > before.0 && after.1 > before.1, + "{before:?} {after:?}" + ); + } } diff --git a/crates/nemoclaw-openshell/src/profile.rs b/crates/nemoclaw-openshell/src/profile.rs index 7b90715c95d..a866b4b2ab5 100644 --- a/crates/nemoclaw-openshell/src/profile.rs +++ b/crates/nemoclaw-openshell/src/profile.rs @@ -49,6 +49,65 @@ pub fn definition( endpoint: &str, kind: InferenceProviderKind, authenticated: bool, +) -> Result { + nemoclaw_backend::validate_endpoint(endpoint, false).map_err(|_| ObservationError::Query)?; + let url = url::Url::parse(endpoint).map_err(|_| ObservationError::Query)?; + let allowed_ips = url + .host_str() + .and_then(|host| host.parse::().ok()) + .into_iter() + .collect::>(); + profile(name, endpoint, kind, authenticated, &allowed_ips) +} + +/// Build a profile for a caller-verified cluster service endpoint. +/// Empty addresses defer destination grants until the provider observes the Service. +pub fn cluster_definition( + name: &str, + endpoint: &str, + kind: InferenceProviderKind, + authenticated: bool, + addresses: &[std::net::IpAddr], +) -> Result { + let url = url::Url::parse(endpoint).map_err(|_| ObservationError::Query)?; + if url.scheme() != "http" + || !url + .host_str() + .is_some_and(|host| host.ends_with(".svc.cluster.local")) + || url.port().is_none_or(|port| port == 0) + || url.path() != "/v1" + || !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + || addresses + .iter() + .any(|address| !service_address_allowed(address)) + { + return Err(ObservationError::BindingMismatch); + } + profile(name, endpoint, kind, authenticated, addresses) +} + +/// Accept a unicast Service address, excluding local and mapped destinations. +pub fn service_address_allowed(address: &std::net::IpAddr) -> bool { + !address.is_unspecified() + && !address.is_loopback() + && !address.is_multicast() + && match address { + std::net::IpAddr::V4(ip) => !ip.is_link_local() && !ip.is_broadcast(), + std::net::IpAddr::V6(ip) => { + !ip.is_unicast_link_local() && ip.to_ipv4_mapped().is_none() + } + } +} + +fn profile( + name: &str, + endpoint: &str, + kind: InferenceProviderKind, + authenticated: bool, + addresses: &[std::net::IpAddr], ) -> Result { if name.is_empty() || name.len() > 40 @@ -59,7 +118,6 @@ pub fn definition( { return Err(ObservationError::Query); } - nemoclaw_backend::validate_endpoint(endpoint, false).map_err(|_| ObservationError::Query)?; let url = url::Url::parse(endpoint).map_err(|_| ObservationError::Query)?; if url.query().is_some() || url.fragment().is_some() @@ -77,11 +135,9 @@ pub fn definition( let path = format!("{}/**", url.path().trim_end_matches('/')); // Private addresses require an explicit destination-validation grant. Grant // only the selected literal address, never a whole private network. - let allowed_ips: Vec = host - .parse::() - .ok() + let allowed_ips: Vec = addresses + .iter() .map(|ip| format!("{ip}/{}", if ip.is_ipv4() { 32 } else { 128 })) - .into_iter() .collect(); let policy = openshell_policy::parse_sandbox_policy( &serde_json::json!({ diff --git a/crates/nemoclaw-openshell/src/runtime.rs b/crates/nemoclaw-openshell/src/runtime.rs index 7da2345d431..877ca22874c 100644 --- a/crates/nemoclaw-openshell/src/runtime.rs +++ b/crates/nemoclaw-openshell/src/runtime.rs @@ -7,7 +7,9 @@ use crate::policy::{ExplicitPolicy, PolicyBinary, PolicyRule}; use nemoclaw_backend::ObservationError; use openshell_sdk::raw::proto; use serde::{Deserialize, Serialize}; -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; + +pub type ClusterGrants = BTreeMap>; #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] @@ -95,8 +97,56 @@ pub struct RuntimeBinding { pub struct PolicyInput { pub explicit: Option, pub managed: BTreeMap, + /// Managed rule names whose exact addresses must come from verified Services. + #[serde(default, skip_serializing_if = "BTreeSet::is_empty")] + pub cluster_grants: BTreeSet, } impl RuntimeBinding { + /// Resolve only marked Service rules; all other authored policy bytes stay intact. + pub fn granted_policy( + &self, + input: &PolicyInput, + grants: &ClusterGrants, + ) -> Result { + if input.cluster_grants.len() != grants.len() { + return Err(ObservationError::BindingMismatch); + } + let mut policy = self.policy(input)?; + for name in &input.cluster_grants { + let addresses = grants.get(name).ok_or(ObservationError::BindingMismatch)?; + if addresses.is_empty() + || addresses.len() > 2 + || addresses.iter().collect::>().len() != addresses.len() + { + return Err(ObservationError::BindingMismatch); + } + for address in addresses { + let (host, prefix) = address + .split_once('/') + .ok_or(ObservationError::BindingMismatch)?; + let ip: std::net::IpAddr = host + .parse() + .map_err(|_| ObservationError::BindingMismatch)?; + if prefix != if ip.is_ipv4() { "32" } else { "128" } + || !crate::profile::service_address_allowed(&ip) + { + return Err(ObservationError::BindingMismatch); + } + } + if !input.managed.contains_key(name) { + return Err(ObservationError::BindingMismatch); + } + let rule = policy + .network_policies + .get_mut(name) + .ok_or(ObservationError::BindingMismatch)?; + if rule.endpoints.len() != 1 || !rule.endpoints[0].allowed_ips.is_empty() { + return Err(ObservationError::BindingMismatch); + } + rule.endpoints[0].allowed_ips.clone_from(addresses); + } + Ok(policy) + } pub fn from_json(encoded: &str) -> Result { let binding: Self = serde_json::from_str(encoded).map_err(|_| ObservationError::Incomplete)?; diff --git a/crates/nemoclaw-provider/tests/refresh.rs b/crates/nemoclaw-provider/tests/refresh.rs index 171d8511d2b..4657d84fbc6 100644 --- a/crates/nemoclaw-provider/tests/refresh.rs +++ b/crates/nemoclaw-provider/tests/refresh.rs @@ -480,6 +480,105 @@ async fn retained_replacement_refusal_names_the_resource_and_changed_fields() { assert!(!text.contains("PRIVATE_"), "{text}"); } +#[tokio::test] +async fn profile_refresh_preserves_the_bound_cluster_source() { + let prior: Row = [ + ("id", "profile/1"), + ("name", "model"), + ("workspace", "owned"), + ("cluster_source", "bound-service"), + ] + .map(|(key, value)| (key.into(), value.into())) + .into(); + for source in ["bound-service", "substituted-service", ""] { + let mut observed = prior.clone(); + observed.insert("cluster_source".into(), source.into()); + let resource = ResourceAdapter::new( + support::definition( + "provider_profile", + &["name", "workspace", "cluster_source"], + &[], + ), + Arc::new(Fixture(Ok(Some(observed)))), + ); + let mut diagnostics = Diagnostics::default(); + let result = resource + .read( + &mut diagnostics, + state(prior.clone()), + Value::Null, + Value::Null, + ) + .await + .unwrap(); + assert_eq!(result.0, state(prior.clone())); + assert_eq!(diagnostics.errors.is_empty(), source == "bound-service"); + } +} + +#[tokio::test] +async fn changing_from_cluster_to_external_inference_replaces_the_owned_profile() { + let resource = ResourceAdapter::new( + support::definition("provider_profile", &["endpoint", "cluster_source"], &[]), + Arc::new(Fixture(Ok(None))), + ); + let prior = state(Row::from([ + ("id".into(), "owned/profile/1".into()), + ("endpoint".into(), "http://model.agents.svc:8000/v1".into()), + ("cluster_source".into(), "owned-cluster-storage".into()), + ])); + for omit in [true, false] { + let mut proposed = prior.clone(); + proposed.insert( + "endpoint".into(), + Value::Value("https://inference.example/v1".into()), + ); + let mut config = proposed.clone(); + if omit { + config.remove("cluster_source"); + } else { + config.insert("cluster_source".into(), Value::Null); + } + let mut diagnostics = Diagnostics::default(); + let (planned, _, replacements) = resource + .plan_update( + &mut diagnostics, + prior.clone(), + proposed, + config, + Value::Null, + Value::Null, + ) + .await + .unwrap(); + assert!(diagnostics.errors.is_empty(), "{diagnostics:?}"); + assert_eq!(planned["cluster_source"], Value::Value(String::new())); + assert_eq!( + replacements.len(), + 2, + "endpoint and cluster provenance require profile replacement" + ); + } + let mut diagnostics = Diagnostics::default(); + let (planned, _, replacements) = resource + .plan_update( + &mut diagnostics, + prior.clone(), + prior.clone(), + prior.clone(), + Value::Null, + Value::Null, + ) + .await + .unwrap(); + assert!(diagnostics.errors.is_empty(), "{diagnostics:?}"); + assert_eq!( + planned, prior, + "an explicit unchanged cluster source remains bound" + ); + assert!(replacements.is_empty()); +} + #[tokio::test] async fn removing_credential_reference_plans_unauthenticated_replacement() { let resource = ResourceAdapter::new( diff --git a/crates/nemoclaw-provider/tests/support/mod.rs b/crates/nemoclaw-provider/tests/support/mod.rs index ff6767e38a0..de083919b9a 100644 --- a/crates/nemoclaw-provider/tests/support/mod.rs +++ b/crates/nemoclaw-provider/tests/support/mod.rs @@ -45,4 +45,7 @@ pub fn definition( .reset_when_omitted .retain(|field| fields.contains(field)); definition + .bound_fields + .retain(|field| fields.contains(field)); + definition } diff --git a/crates/nemoclaw-sdk/src/image_runtime.rs b/crates/nemoclaw-sdk/src/image_runtime.rs index f67b05a60d7..a57132afe0d 100644 --- a/crates/nemoclaw-sdk/src/image_runtime.rs +++ b/crates/nemoclaw-sdk/src/image_runtime.rs @@ -73,5 +73,9 @@ pub fn policy_input( "managed inference and search policy names are reserved", )); } - Ok(PolicyInput { explicit, managed }) + Ok(PolicyInput { + explicit, + managed, + cluster_grants: Default::default(), + }) } diff --git a/crates/nemoclaw-tofu/src/lib.rs b/crates/nemoclaw-tofu/src/lib.rs index 09d8e545f01..07b0752572f 100644 --- a/crates/nemoclaw-tofu/src/lib.rs +++ b/crates/nemoclaw-tofu/src/lib.rs @@ -52,6 +52,9 @@ pub struct Definition { /// Optional inputs whose omission on update selects the empty default /// instead of carrying the prior value forward. pub reset_when_omitted: Vec<&'static str>, + /// Inputs whose observations must preserve the recorded value, including + /// the empty default of an omitted optional input. + pub bound_fields: Vec<&'static str>, /// Attributes the backend observes, with their update planning rule. pub computed: Vec<(&'static str, PlanComputed)>, /// Optional inputs the provider generates on create when omitted, then @@ -79,6 +82,7 @@ impl Definition { mutable: mutable.to_vec(), optional: Vec::new(), reset_when_omitted: Vec::new(), + bound_fields: Vec::new(), computed: Vec::new(), generated: Vec::new(), protection: Protection::None, @@ -99,6 +103,10 @@ impl Definition { self.reset_when_omitted.extend_from_slice(fields); self } + pub fn bound_fields(mut self, fields: &[&'static str]) -> Self { + self.bound_fields.extend_from_slice(fields); + self + } pub fn computed(mut self, name: &'static str, plan: PlanComputed) -> Self { self.computed.push((name, plan)); self diff --git a/crates/nemoclaw-tofu/src/resource.rs b/crates/nemoclaw-tofu/src/resource.rs index b3a2084c0e8..d2fbed0603b 100644 --- a/crates/nemoclaw-tofu/src/resource.rs +++ b/crates/nemoclaw-tofu/src/resource.rs @@ -195,6 +195,13 @@ impl ResourceAdapter { .collect() } fn checked(&self, prior: &Row, observed: Row) -> Result { + for field in &self.definition.bound_fields { + if prior.get(*field).map(String::as_str).unwrap_or("") + != observed.get(*field).map(String::as_str).unwrap_or("") + { + return Err(ObservationError::BindingMismatch); + } + } for field in self.definition.attributes() { if observed .get(field) @@ -528,3 +535,41 @@ impl Resource for ResourceAdapter { } } } +#[cfg(test)] +mod tests { + use super::*; + + struct UnusedBackend; + #[async_trait] + impl Backend for UnusedBackend { + async fn read(&self, _: &str, _: &Row, _: bool) -> Result, ObservationError> { + unreachable!("binding checks do not contact the backend") + } + async fn ensure(&self, _: &str, _: &Row) -> Mutation { + unreachable!("binding checks do not mutate resources") + } + async fn remove(&self, _: &str, _: &Row, _: bool) -> Result<(), ObservationError> { + unreachable!("binding checks do not mutate resources") + } + } + + #[test] + fn refresh_preserves_declared_bound_fields() { + let definition = Definition::new("profile", &["name", "workspace", "source"], &[]) + .optional(&["source"]) + .bound_fields(&["source"]); + let adapter = ResourceAdapter::new(definition, Arc::new(UnusedBackend)); + let prior: Row = [ + ("id", "profile/1"), + ("name", "model"), + ("workspace", "owned"), + ("source", "bound-service"), + ] + .map(|(key, value)| (key.into(), value.into())) + .into(); + assert!(adapter.checked(&prior, prior.clone()).is_ok()); + let mut changed = prior.clone(); + changed.insert("source".into(), "substituted-service".into()); + assert!(adapter.checked(&prior, changed).is_err()); + } +} diff --git a/crates/openshell-provider/src/client.rs b/crates/openshell-provider/src/client.rs index 08bda75dbcd..58090843d3d 100644 --- a/crates/openshell-provider/src/client.rs +++ b/crates/openshell-provider/src/client.rs @@ -3,7 +3,7 @@ //! The gateway client a provider configuration establishes, and the backend //! that reconciles OpenShell objects through it. -use crate::{EnvironmentSecrets, OpenShell}; +use crate::{DockerServices, EnvironmentSecrets, OpenShell, Services}; use async_trait::async_trait; use nemoclaw_backend::{Backend, Error, Mutation, ObservationError, Row}; use serde::{Deserialize, Serialize}; @@ -97,8 +97,13 @@ enum State { } /// The gateway client of the current provider configuration. -#[derive(Default)] -pub struct GatewayClient(RwLock); +pub struct GatewayClient(RwLock, Arc); + +impl Default for GatewayClient { + fn default() -> Self { + Self::with_services(Arc::new(DockerServices)) + } +} /// Gateway connection inputs of a provider configuration. pub struct GatewaySettings<'a> { @@ -177,6 +182,11 @@ impl GatewaySettings<'_> { } impl GatewayClient { + /// Use the deployment's managed service checks for each configured client. + pub fn with_services(services: Arc) -> Self { + Self(RwLock::new(State::default()), services) + } + pub fn client(&self) -> Result { match &*self.0.read().map_err(|_| ObservationError::Query)? { State::Ready(client) => Ok(client.clone()), @@ -207,8 +217,12 @@ impl GatewayClient { } /// Connect lazily to `connection`. pub fn connect(&self, connection: &nemoclaw_openshell::Connection) -> Result<(), String> { - let client = OpenShell::connect(connection, Arc::new(EnvironmentSecrets)) - .map_err(|error| error.to_string())?; + let client = OpenShell::connect_with_services( + connection, + Arc::new(EnvironmentSecrets), + self.1.clone(), + ) + .map_err(|error| error.to_string())?; self.set(State::Ready(client)).map_err(str::to_owned) } } diff --git a/crates/openshell-provider/src/connected.rs b/crates/openshell-provider/src/connected.rs index 6a46e110372..786f52fae62 100644 --- a/crates/openshell-provider/src/connected.rs +++ b/crates/openshell-provider/src/connected.rs @@ -17,6 +17,44 @@ fn labels(want: &Row) -> HashMap { .into() } +pub(super) fn create_sandbox_request( + want: &Row, + grants: &network::ClusterGrants, +) -> Result { + if value(want, "agent_runtime") != "fabric" { + return Err(ObservationError::BindingMismatch); + } + let mut labels = labels(want); + labels.insert(AGENT.into(), value(want, "agent_name").into()); + labels.insert(AGENT_RUNTIME.into(), value(want, "agent_runtime").into()); + Ok(proto::CreateSandboxRequest { + name: value(want, "name").into(), + workspace_scope: Some(proto::workspace_selector(value(want, "workspace"))), + labels, + annotations: [ + (agent::RUNTIME.into(), value(want, "runtime_json").into()), + (agent::POLICY.into(), value(want, "policy_json").into()), + ] + .into(), + spec: Some(proto::SandboxSpec { + template: Some(proto::SandboxTemplate { + image: value(want, "image").into(), + ..Default::default() + }), + command: agent::binding(want)? + .command("serve", &["--agent", value(want, "agent_name")]), + providers: inference::provider_names( + value(want, "provider_names_json"), + value(want, "agent_runtime"), + )?, + environment: inference_environment(want)?.into_iter().collect(), + policy: Some(network::granted_row_policy(want, grants)?), + ..Default::default() + }), + ..Default::default() + }) +} + impl ConnectedOpenShellGateway { pub(crate) async fn gateway_capabilities( &self, @@ -53,20 +91,32 @@ impl ConnectedOpenShellGateway { let native = search.is_none(); let source = value(want, "credential_source"); let profile = if native { - Some(inference_profile( - value(want, "name"), - value(want, "endpoint"), - kind.parse().map_err(|_| ObservationError::Query)?, - !source.is_empty() || !value(want, "credential_env").is_empty(), - )?) - } else { - None - }; - if let Some(profile) = &profile { + let id = format!("nemoclaw-inference-{}", value(want, "name")); let bound = self - .observe_profile(value(want, "workspace"), &profile.id) + .observe_profile(value(want, "workspace"), &id, false) .await? .ok_or(ObservationError::BindingMismatch)?; + let authenticated = !source.is_empty() || !value(want, "credential_env").is_empty(); + let mut profile_fields = bound.clone(); + profile_fields.insert("endpoint".into(), value(want, "endpoint").into()); + profile_fields.insert("provider_type".into(), value(want, "provider_type").into()); + profile_fields.insert("authenticated".into(), authenticated.to_string()); + let profile = if profile::cluster_source(&profile_fields, self.services.as_ref())? { + nemoclaw_openshell::profile::cluster_definition( + value(want, "name"), + value(want, "endpoint"), + kind.parse().map_err(|_| ObservationError::Query)?, + authenticated, + &[], + )? + } else { + inference_profile( + value(want, "name"), + value(want, "endpoint"), + kind.parse().map_err(|_| ObservationError::Query)?, + authenticated, + )? + }; if ["owner", "generation", "endpoint", "provider_type"] .iter() .any(|key| value(&bound, key) != value(want, key)) @@ -79,17 +129,17 @@ impl ConnectedOpenShellGateway { { return Err(ObservationError::BindingMismatch); } - } + Some(profile) + } else { + None + }; let credential = if !source.is_empty() { if !value(want, "credential_env").is_empty() { return Err(ObservationError::BindingMismatch); } - nemoclaw_docker::credentials::resolve(&nemoclaw_docker::credentials::Source::parse( - source, - value(want, "owner"), - value(want, "endpoint"), - )?) - .await? + self.services + .resolve_credential_source(source, value(want, "owner"), value(want, "endpoint")) + .await? } else { match value(want, "credential_env") { "" => "empty".into(), @@ -166,46 +216,11 @@ impl ConnectedOpenShellGateway { pub(crate) async fn create_sandbox(&self, want: &Row) -> Result { let name = value(want, "name"); - let workspace = value(want, "workspace"); - if value(want, "agent_runtime") != "fabric" { - return Err(ObservationError::BindingMismatch); - } - let mut labels = labels(want); - labels.insert(AGENT.into(), value(want, "agent_name").into()); - if !value(want, "agent_runtime").is_empty() { - labels.insert(AGENT_RUNTIME.into(), value(want, "agent_runtime").into()); - } + let grants = self.sandbox_cluster_grants(want).await?; let response = self .client .raw_grpc() - .create_sandbox( - self.request(proto::CreateSandboxRequest { - name: name.into(), - workspace_scope: Some(proto::workspace_selector(workspace)), - labels, - annotations: [ - (agent::RUNTIME.into(), value(want, "runtime_json").into()), - (agent::POLICY.into(), value(want, "policy_json").into()), - ] - .into(), - spec: Some(proto::SandboxSpec { - template: Some(proto::SandboxTemplate { - image: value(want, "image").into(), - ..Default::default() - }), - command: agent::binding(want)? - .command("serve", &["--agent", value(want, "agent_name")]), - providers: inference::provider_names( - value(want, "provider_names_json"), - value(want, "agent_runtime"), - )?, - environment: inference_environment(want)?.into_iter().collect(), - policy: Some(row_policy(want)?), - ..Default::default() - }), - ..Default::default() - }), - ) + .create_sandbox(self.request(create_sandbox_request(want, &grants)?)) .await .map_err(|error| nemoclaw_openshell::remote_rejection("CreateSandbox", &error))? .into_inner(); @@ -372,8 +387,12 @@ mod tests { endpoint: "http://127.0.0.1:1".into(), ..Default::default() }; - let client = - ConnectedOpenShellGateway::connect(&connection, Arc::new(SearchSecrets)).unwrap(); + let client = ConnectedOpenShellGateway::connect( + &connection, + Arc::new(SearchSecrets), + Arc::new(crate::DockerServices), + ) + .unwrap(); for provider in [SearchProvider::Brave, SearchProvider::Tavily] { let name = nemoclaw_openshell::search::search_provider_name( provider, @@ -411,6 +430,7 @@ mod tests { }, &name, false, + &crate::DockerServices, ) .unwrap(); assert_eq!(observed["credential_env"], "SEARCH_KEY"); diff --git a/crates/openshell-provider/src/lib.rs b/crates/openshell-provider/src/lib.rs index 1571e6e36aa..cd24aa56a26 100644 --- a/crates/openshell-provider/src/lib.rs +++ b/crates/openshell-provider/src/lib.rs @@ -30,6 +30,63 @@ pub use provider::OpenShellProvider; use transport::ConnectedOpenShellGateway; pub use transport::{OpenShell, RESPONSE_LIMIT, SandboxPhase}; +/// Deployment-owned inference service identity and credential checks. +#[async_trait::async_trait] +pub trait Services: Send + Sync { + fn validate_credential_source( + &self, + source: &str, + owner: &str, + endpoint: &str, + ) -> Result<(), ObservationError>; + async fn resolve_credential_source( + &self, + source: &str, + owner: &str, + endpoint: &str, + ) -> Result; + /// Verify the retained source owner, exact endpoint, and authentication mode. + fn validate_cluster_source(&self, row: &Row) -> Result<(), ObservationError>; + /// Observe addresses only after verifying the retained Service identity. + async fn cluster_addresses(&self, row: &Row) + -> Result, ObservationError>; +} + +/// Docker credentials for callers without managed cluster services. +pub struct DockerServices; + +#[async_trait::async_trait] +impl Services for DockerServices { + fn validate_credential_source( + &self, + source: &str, + owner: &str, + endpoint: &str, + ) -> Result<(), ObservationError> { + nemoclaw_docker::credentials::Source::parse(source, owner, endpoint).map(|_| ()) + } + + async fn resolve_credential_source( + &self, + source: &str, + owner: &str, + endpoint: &str, + ) -> Result { + nemoclaw_docker::credentials::resolve(&nemoclaw_docker::credentials::Source::parse( + source, owner, endpoint, + )?) + .await + } + + fn validate_cluster_source(&self, _: &Row) -> Result<(), ObservationError> { + Err(ObservationError::BindingMismatch) + } + + async fn cluster_addresses(&self, _: &Row) -> Result, ObservationError> { + Err(ObservationError::BindingMismatch) + } +} + pub const OWNER: &str = "nemoclaw.nvidia.com/uid"; pub const GENERATION: &str = "nemoclaw.nvidia.com/generation"; pub use nemoclaw_openshell::credential_metadata::CREDENTIAL_SOURCE; @@ -101,6 +158,7 @@ fn provider_row( response: proto::ProviderResponse, name: &str, removing: bool, + services: &dyn Services, ) -> Result { let provider = response.provider.ok_or(ObservationError::Incomplete)?; if nemoclaw_openshell::search::SearchProvider::from_profile(&provider.r#type).is_some() { @@ -143,7 +201,7 @@ fn provider_row( if !credential.is_empty() { return Err(ObservationError::BindingMismatch); } - nemoclaw_docker::credentials::Source::parse(&source, &row["owner"], endpoint)?; + services.validate_credential_source(&source, &row["owner"], endpoint)?; } row.insert("profile_name".into(), String::new()); row.insert("credential_source".into(), source); @@ -164,7 +222,7 @@ fn sandbox_row( response: proto::SandboxResponse, name: &str, removing: bool, -) -> Result<(Row, bool), ObservationError> { +) -> Result<(Row, bool, network::ClusterGrants), ObservationError> { let sandbox = response.sandbox.ok_or(ObservationError::Incomplete)?; let meta = sandbox .metadata @@ -200,9 +258,9 @@ fn sandbox_row( if !inference.is_empty() { expected_environment.insert(PROVIDERS_ENV.into(), inference.clone()); } - if policy_json(spec.policy.as_ref().ok_or(ObservationError::Incomplete)?)? - != policy_json(&binding.policy(&input)?)? - { + let observed_policy = spec.policy.as_ref().ok_or(ObservationError::Incomplete)?; + let grants = network::recorded_grants(&input, observed_policy)?; + if policy_json(observed_policy)? != policy_json(&binding.granted_policy(&input, &grants)?)? { return Err(ObservationError::BindingMismatch); } let expected_providers = inference::provider_names(&inference, &runtime)?; @@ -229,7 +287,7 @@ fn sandbox_row( row.insert("policy_json".into(), policy_input); row.insert("runtime_json".into(), runtime_json); // Phase is used by active checks, but is not a Terraform schema attribute. - Ok((row, ready)) + Ok((row, ready, grants)) } fn active_policy( response: proto::GetSandboxPolicyStatusResponse, @@ -252,6 +310,24 @@ fn active_policy( Ok(()) } +async fn checked_sandbox_row_with( + response: proto::SandboxResponse, + workspace: &str, + name: &str, + removing: bool, + check: impl FnOnce(Row) -> F, +) -> Result<(Row, bool, network::ClusterGrants), ObservationError> +where + F: std::future::Future>, +{ + let (mut row, ready, grants) = sandbox_row(response, name, removing)?; + row.insert("workspace".into(), workspace.into()); + if !removing && check(row.clone()).await? != grants { + return Err(ObservationError::BindingMismatch); + } + Ok((row, ready, grants)) +} + mod mutation; pub fn verify_identity(expected: &Row, observed: &Row) -> Result<(), ObservationError> { for field in ["owner", "generation"] { @@ -312,11 +388,18 @@ pub fn definitions() -> [nemoclaw_tofu::Definition; 4] { "provider_type", "authenticated", "binaries_json", + "cluster_source", ], &[], ) - .optional(&["endpoint", "provider_type", "authenticated"]) - .reset_when_omitted(&["provider_type"]), + .optional(&[ + "endpoint", + "provider_type", + "authenticated", + "cluster_source", + ]) + .reset_when_omitted(&["provider_type", "cluster_source"]) + .bound_fields(&["cluster_source"]), Definition::new( "sandbox", &[ diff --git a/crates/openshell-provider/src/network.rs b/crates/openshell-provider/src/network.rs index b6b4af6709b..35545723a91 100644 --- a/crates/openshell-provider/src/network.rs +++ b/crates/openshell-provider/src/network.rs @@ -2,6 +2,41 @@ // SPDX-License-Identifier: Apache-2.0 use super::*; use nemoclaw_openshell::policy::ExplicitPolicy; +pub(super) use nemoclaw_openshell::runtime::ClusterGrants; + +pub(super) fn policy_input( + row: &Row, +) -> Result { + serde_json::from_str(row.get("policy_json").ok_or(ObservationError::Incomplete)?) + .map_err(|_| ObservationError::Query) +} + +pub(super) fn granted_row_policy( + row: &Row, + grants: &ClusterGrants, +) -> Result { + agent::binding(row)?.granted_policy(&policy_input(row)?, grants) +} + +pub(super) fn recorded_grants( + input: &nemoclaw_openshell::runtime::PolicyInput, + policy: &proto::SandboxPolicy, +) -> Result { + input + .cluster_grants + .iter() + .map(|name| { + let rule = policy + .network_policies + .get(name) + .ok_or(ObservationError::BindingMismatch)?; + if rule.endpoints.len() != 1 { + return Err(ObservationError::BindingMismatch); + } + Ok((name.clone(), rule.endpoints[0].allowed_ips.clone())) + }) + .collect() +} // Baseline grants follow NVIDIA/OpenShell crates/openshell-supervisor/src/lib.rs // at 7e7a8d5610f336f5f7f9f60da0951adbf295475d (Apache-2.0). @@ -69,10 +104,7 @@ pub(super) fn loaded_policy_matches( } pub(super) fn row_policy(row: &Row) -> Result { - let input: nemoclaw_openshell::runtime::PolicyInput = - serde_json::from_str(row.get("policy_json").ok_or(ObservationError::Incomplete)?) - .map_err(|_| ObservationError::Query)?; - agent::binding(row)?.policy(&input) + agent::binding(row)?.policy(&policy_input(row)?) } pub(super) fn validate_row_policy(row: &Row) -> Result<(), ObservationError> { diff --git a/crates/openshell-provider/src/profile.rs b/crates/openshell-provider/src/profile.rs index 61235d0c494..2a8d3fbea7a 100644 --- a/crates/openshell-provider/src/profile.rs +++ b/crates/openshell-provider/src/profile.rs @@ -7,26 +7,30 @@ const BINARIES: &str = "nemoclaw.nvidia.com/binaries"; const ENDPOINT: &str = "nemoclaw.nvidia.com/endpoint"; const PROVIDER_TYPE: &str = "nemoclaw.nvidia.com/provider-type"; const AUTHENTICATED: &str = "nemoclaw.nvidia.com/authenticated"; +const CLUSTER_SOURCE: &str = "nemoclaw.nvidia.com/cluster-source"; +const CLUSTER_ADDRESSES: &str = "nemoclaw.nvidia.com/cluster-addresses"; /// Each ownership and definition field, and the profile annotation that carries it. -const FIELDS: [(&str, &str); 6] = [ +const FIELDS: [(&str, &str); 8] = [ ("owner", OWNER), ("generation", GENERATION), ("binaries_json", BINARIES), ("endpoint", ENDPOINT), ("provider_type", PROVIDER_TYPE), ("authenticated", AUTHENTICATED), + ("cluster_source", CLUSTER_SOURCE), + ("cluster_addresses", CLUSTER_ADDRESSES), ]; -fn annotations(fields: Row) -> std::collections::HashMap { +fn annotations(fields: Row) -> Result, ObservationError> { fields .into_iter() .map(|(field, value)| { let (_, key) = FIELDS .iter() .find(|(name, _)| *name == field) - .expect("profile metadata field"); - ((*key).into(), value) + .ok_or(ObservationError::Incomplete)?; + Ok(((*key).into(), value)) }) .collect() } @@ -56,7 +60,18 @@ fn definition( provider: SearchProvider, want: &Row, ) -> Result { - let mut rule = nemoclaw_openshell::search::search_policy(provider); + definition_with_rule( + provider, + want, + nemoclaw_openshell::search::search_policy(provider), + ) +} + +fn definition_with_rule( + provider: SearchProvider, + want: &Row, + mut rule: nemoclaw_openshell::policy::PolicyRule, +) -> Result { let name = &want["name"]; rule.name = name.clone(); let policy = openshell_policy::parse_sandbox_policy( @@ -65,7 +80,7 @@ fn definition( }) .to_string(), ) - .expect("static search policy"); + .map_err(|_| ObservationError::Query)?; let network = &policy.network_policies[name]; let (display, auth_style, header_name) = match provider { SearchProvider::Brave => ("Brave", "header", "X-Subscription-Token"), @@ -91,11 +106,28 @@ fn definition( ["owner", "generation", "binaries_json"] .map(|key| (key.into(), want[key].clone())) .into(), - ), + )?, ..Default::default() }) } -fn native_definition(want: &Row) -> Result { +pub(super) fn cluster_source( + want: &Row, + services: &dyn Services, +) -> Result { + let Some(_) = want + .get("cluster_source") + .filter(|source| !source.is_empty()) + else { + return Ok(false); + }; + services.validate_cluster_source(want)?; + Ok(true) +} + +fn native_definition( + want: &Row, + services: &dyn Services, +) -> Result { let name = want["name"] .strip_prefix("nemoclaw-inference-") .ok_or(ObservationError::Query)?; @@ -104,29 +136,51 @@ fn native_definition(want: &Row) -> Result false, _ => return Err(ObservationError::Query), }; - let mut profile = inference_profile( - name, - &want["endpoint"], - if want.get("provider_type").is_some_and(|s| s == "anthropic") { - nemoclaw_openshell::profile::InferenceProviderKind::Anthropic - } else { - nemoclaw_openshell::profile::InferenceProviderKind::Openai - }, - authenticated, - )?; + let kind = if want.get("provider_type").is_some_and(|s| s == "anthropic") { + nemoclaw_openshell::profile::InferenceProviderKind::Anthropic + } else { + nemoclaw_openshell::profile::InferenceProviderKind::Openai + }; + let cluster = cluster_source(want, services)?; + let mut profile = if cluster { + let addresses: Vec = serde_json::from_str( + want.get("cluster_addresses") + .ok_or(ObservationError::Incomplete)?, + ) + .map_err(|_| ObservationError::BindingMismatch)?; + if addresses.is_empty() { + return Err(ObservationError::Incomplete); + } + nemoclaw_openshell::profile::cluster_definition( + name, + &want["endpoint"], + kind, + authenticated, + &addresses, + )? + } else { + inference_profile(name, &want["endpoint"], kind, authenticated)? + }; profile.binaries = binaries(want)?; - profile.annotations = annotations( - [ - "owner", - "generation", - "endpoint", - "provider_type", - "authenticated", - "binaries_json", - ] - .map(|key| (key.into(), want.get(key).cloned().unwrap_or_default())) - .into(), - ); + let mut metadata: Row = [ + "owner", + "generation", + "endpoint", + "provider_type", + "authenticated", + "binaries_json", + ] + .into_iter() + .map(|key| (key.into(), want.get(key).cloned().unwrap_or_default())) + .collect(); + if cluster { + metadata.insert("cluster_source".into(), want["cluster_source"].clone()); + metadata.insert( + "cluster_addresses".into(), + want["cluster_addresses"].clone(), + ); + } + profile.annotations = annotations(metadata)?; Ok(profile) } @@ -135,6 +189,7 @@ fn row( workspace: &str, name: &str, catalog_entry: bool, + services: &dyn Services, ) -> Result { let metadata: Row = FIELDS .iter() @@ -163,9 +218,14 @@ fn row( profile.resource_version = 0; profile.source.clear(); profile.scope.clear(); - let mut fields: Row = ["endpoint", "provider_type", "authenticated"] - .map(|key| (key.into(), String::new())) - .into(); + let mut fields: Row = [ + "endpoint", + "provider_type", + "authenticated", + "cluster_source", + ] + .map(|key| (key.into(), String::new())) + .into(); fields.extend([ ("name".into(), name.into()), ("owner".into(), owner.clone()), @@ -193,13 +253,24 @@ fn row( .ok_or(ObservationError::Incomplete)?, ); } - native_definition(&fields)? + if let Some(source) = metadata.get("cluster_source") { + fields.insert("cluster_source".into(), source.clone()); + fields.insert( + "cluster_addresses".into(), + metadata + .get("cluster_addresses") + .cloned() + .ok_or(ObservationError::Incomplete)?, + ); + } + native_definition(&fields, services)? } else { definition(search.ok_or(ObservationError::Query)?, &fields)? }; if profile != expected { return Err(ObservationError::BindingMismatch); } + fields.remove("cluster_addresses"); fields.extend( [ ("id", id), @@ -251,13 +322,91 @@ pub(super) fn provider_row( ]); Ok(result) } +async fn checked_profile_row_with( + profile: proto::ProviderProfile, + workspace: &str, + name: &str, + catalog_entry: bool, + removing: bool, + services: &dyn Services, + check: impl FnOnce(Row) -> F, +) -> Result +where + F: std::future::Future, ObservationError>>, +{ + let fields = row(profile.clone(), workspace, name, catalog_entry, services)?; + if !removing && cluster_source(&fields, services)? { + let addresses = check(fields.clone()).await?; + let mut current = fields.clone(); + current.insert( + "cluster_addresses".into(), + serde_json::to_string(&addresses).map_err(|_| ObservationError::Incomplete)?, + ); + if native_definition(¤t, services)?.endpoints != profile.endpoints { + return Err(ObservationError::BindingMismatch); + } + } + Ok(fields) +} + impl ConnectedOpenShellGateway { + pub(super) async fn sandbox_cluster_grants( + &self, + want: &Row, + ) -> Result { + let input = network::policy_input(want)?; + let mut grants = network::ClusterGrants::new(); + for name in &input.cluster_grants { + let profile = self + .client + .raw_grpc() + .get_provider_profile(self.request(proto::GetProviderProfileRequest { + id: name.clone(), + workspace_scope: Some(proto::workspace_selector(&want["workspace"])), + })) + .await + .map_err(|error| remote_error(&error))? + .into_inner() + .profile + .ok_or(ObservationError::Incomplete)?; + let fields = self + .checked_profile_row(profile.clone(), &want["workspace"], name, true, false) + .await?; + grants.insert( + name.clone(), + cluster_grant(want, name, &profile, &fields, self.services.as_ref())?, + ); + } + network::granted_row_policy(want, &grants)?; + Ok(grants) + } + async fn checked_profile_row( + &self, + profile: proto::ProviderProfile, + workspace: &str, + name: &str, + catalog_entry: bool, + removing: bool, + ) -> Result { + checked_profile_row_with( + profile, + workspace, + name, + catalog_entry, + removing, + self.services.as_ref(), + |fields| async move { self.services.cluster_addresses(&fields).await }, + ) + .await + } + pub(super) async fn observe_profile( &self, workspace: &str, name: &str, + removing: bool, ) -> Result, ObservationError> { - authoritative( + let response = authoritative( self.client .raw_grpc() .get_provider_profile(self.request(proto::GetProviderProfileRequest { @@ -265,22 +414,37 @@ impl ConnectedOpenShellGateway { workspace_scope: Some(proto::workspace_selector(workspace)), })) .await, - )? - .map(|response| { - row( - response.profile.ok_or(ObservationError::Incomplete)?, - workspace, - name, - true, - ) - }) - .transpose() + )?; + match response { + Some(response) => self + .checked_profile_row( + response.profile.ok_or(ObservationError::Incomplete)?, + workspace, + name, + true, + removing, + ) + .await + .map(Some), + None => Ok(None), + } } pub(super) async fn create_profile(&self, want: &Row) -> Result { let search = SearchProvider::from_profile(&want["name"]); if search.is_none() && !want["name"].starts_with("nemoclaw-inference-") { return Err(ObservationError::Query); } + let mut observed = want.clone(); + if cluster_source(want, self.services.as_ref())? { + if search.is_some() { + return Err(ObservationError::Query); + } + let addresses = self.services.cluster_addresses(want).await?; + observed.insert( + "cluster_addresses".into(), + serde_json::to_string(&addresses).map_err(|_| ObservationError::Incomplete)?, + ); + } let response = self .client .raw_grpc() @@ -290,7 +454,7 @@ impl ConnectedOpenShellGateway { profile: Some(if let Some(search) = search { definition(search, want)? } else { - native_definition(want)? + native_definition(&observed, self.services.as_ref())? }), source: "NemoClaw".into(), }], @@ -302,22 +466,74 @@ impl ConnectedOpenShellGateway { if !response.imported || response.profiles.len() != 1 { return Err(ObservationError::Incomplete); } - let row = row( - response.profiles.into_iter().next().unwrap(), - &want["workspace"], - &want["name"], - false, - )?; + let row = self + .checked_profile_row( + response.profiles.into_iter().next().unwrap(), + &want["workspace"], + &want["name"], + false, + false, + ) + .await?; verify_identity(want, &row)?; Ok(row["id"].clone()) } } +fn cluster_grant( + want: &Row, + name: &str, + profile: &proto::ProviderProfile, + fields: &Row, + services: &dyn Services, +) -> Result, ObservationError> { + if want.get("owner") != fields.get("owner") + || !cluster_source(fields, services)? + || profile.id != name + { + return Err(ObservationError::BindingMismatch); + } + let provider = name + .strip_prefix("nemoclaw-inference-") + .ok_or(ObservationError::BindingMismatch)?; + if !inference::provider_names(&want["provider_names_json"], &want["agent_runtime"])? + .iter() + .any(|name| name == provider) + { + return Err(ObservationError::BindingMismatch); + } + let policy = row_policy(want)?; + let rule = policy + .network_policies + .get(name) + .ok_or(ObservationError::BindingMismatch)?; + if rule.endpoints.len() != 1 || profile.endpoints.len() != 1 { + return Err(ObservationError::BindingMismatch); + } + let mut endpoint = profile.endpoints[0].clone(); + let addresses = std::mem::take(&mut endpoint.allowed_ips); + if endpoint != rule.endpoints[0] { + return Err(ObservationError::BindingMismatch); + } + Ok(addresses) +} + #[cfg(test)] mod tests { use super::*; use prost::Message; + #[test] + fn unsupported_profile_metadata_returns_an_error_instead_of_panicking() { + let result = std::panic::catch_unwind(|| { + annotations(Row::from([("unknown_field".into(), "value".into())])) + }); + assert!( + result.is_ok(), + "unsupported metadata must return an observation error" + ); + assert_eq!(result.unwrap(), Err(ObservationError::Incomplete)); + } fn native_fields(kind: &str, authenticated: bool) -> Row { [ ("binaries_json", r#"["/srv/python3.99","/srv/bun"]"#), @@ -342,16 +558,35 @@ mod tests { definition(provider, &fields).unwrap() } + #[test] + fn unsupported_search_rules_return_an_observation_error() { + for provider in [SearchProvider::Brave, SearchProvider::Tavily] { + for invalid_tls in [true, false] { + let mut fields = native_fields("", true); + fields.insert("name".into(), provider.profile().into()); + let mut rule = nemoclaw_openshell::search::search_policy(provider); + if invalid_tls { + rule.endpoints[0].tls = Some("unsupported-mode".into()); + } else { + rule.endpoints[0].enforcement = Some("unsupported-mode".into()); + } + let error = definition_with_rule(provider, &fields, rule) + .expect_err("unsupported search policy must return an error, not panic"); + assert_eq!(error, ObservationError::Query); + } + } + } + #[test] fn executable_grants_require_observed_paths_and_reject_live_broadening() { for encoded in ["[]", "{}", r#"["python"]"#, r#"["/srv/../bin/python"]"#] { let mut want = native_fields("", true); want.insert("binaries_json".into(), encoded.into()); - assert!(native_definition(&want).is_err()); + assert!(native_definition(&want, &DockerServices).is_err()); want.insert("name".into(), SearchProvider::Brave.profile().into()); assert!(definition(SearchProvider::Brave, &want).is_err()); } - let mut profile = native_definition(&native_fields("", true)).unwrap(); + let mut profile = native_definition(&native_fields("", true), &DockerServices).unwrap(); assert_eq!( profile .binaries @@ -363,9 +598,27 @@ mod tests { profile.resource_version = 1; profile.source = "user".into(); profile.scope = "workspace".into(); - assert!(row(profile.clone(), "workspace", &profile.id, true).is_ok()); + assert!( + row( + profile.clone(), + "workspace", + &profile.id, + true, + &DockerServices + ) + .is_ok() + ); profile.binaries.clear(); - assert!(row(profile.clone(), "workspace", &profile.id, true).is_err()); + assert!( + row( + profile.clone(), + "workspace", + &profile.id, + true, + &DockerServices + ) + .is_err() + ); } #[test] @@ -376,7 +629,10 @@ mod tests { ]; for kind in ["", "anthropic"] { for authenticated in [false, true] { - profiles.push(native_definition(&native_fields(kind, authenticated)).unwrap()); + profiles.push( + native_definition(&native_fields(kind, authenticated), &DockerServices) + .unwrap(), + ); } } for mut profile in profiles { @@ -386,7 +642,8 @@ mod tests { let bytes = profile.encode_to_vec(); for _ in 0..64 { let decoded = proto::ProviderProfile::decode(bytes.as_slice()).unwrap(); - let observed = row(decoded, "workspace", &profile.id, true).unwrap(); + let observed = + row(decoded, "workspace", &profile.id, true, &DockerServices).unwrap(); assert_eq!(observed["owner"], "deployment"); assert_eq!(observed["generation"], "generation"); assert_eq!(observed["id"], format!("workspace/{}/1", profile.id)); @@ -397,11 +654,18 @@ mod tests { #[test] fn profile_observation_rejects_missing_ambiguous_or_foreign_metadata() { let want = native_fields("", true); - let mut profile = native_definition(&want).unwrap(); + let mut profile = native_definition(&want, &DockerServices).unwrap(); profile.resource_version = 1; profile.source = "user".into(); profile.scope = "workspace".into(); - let observed = row(profile.clone(), "workspace", &profile.id, true).unwrap(); + let observed = row( + profile.clone(), + "workspace", + &profile.id, + true, + &DockerServices, + ) + .unwrap(); verify_identity(&want, &observed).unwrap(); for key in [ OWNER, @@ -414,26 +678,26 @@ mod tests { let mut missing = profile.clone(); assert!(missing.annotations.remove(key).is_some(), "{key}"); assert!( - row(missing, "workspace", &profile.id, true).is_err(), + row(missing, "workspace", &profile.id, true, &DockerServices).is_err(), "missing {key}" ); } for value in ["", "{}", "null", "not JSON", "[7]"] { let mut malformed = profile.clone(); malformed.annotations.insert(BINARIES.into(), value.into()); - assert!(row(malformed, "workspace", &profile.id, true).is_err()); + assert!(row(malformed, "workspace", &profile.id, true, &DockerServices).is_err()); } let mut unknown = profile.clone(); unknown .annotations .insert("nemoclaw.nvidia.com/unexpected".into(), "value".into()); - assert!(row(unknown, "workspace", &profile.id, true).is_err()); + assert!(row(unknown, "workspace", &profile.id, true, &DockerServices).is_err()); for key in [OWNER, GENERATION] { let mut foreign = profile.clone(); foreign .annotations .insert(key.into(), "someone-else".into()); - let observed = row(foreign, "workspace", &profile.id, true).unwrap(); + let observed = row(foreign, "workspace", &profile.id, true, &DockerServices).unwrap(); assert_eq!( verify_identity(&want, &observed), Err(ObservationError::BindingMismatch) @@ -443,7 +707,7 @@ mod tests { #[test] fn profile_metadata_is_one_annotation_per_field() { - let native = native_definition(&native_fields("anthropic", true)).unwrap(); + let native = native_definition(&native_fields("anthropic", true), &DockerServices).unwrap(); assert_eq!( native.annotations, [ @@ -495,7 +759,14 @@ mod tests { profile.resource_version = 1; profile.source = "user".into(); profile.scope = "workspace".into(); - let observed = row(profile.clone(), "workspace", provider.profile(), true).unwrap(); + let observed = row( + profile.clone(), + "workspace", + provider.profile(), + true, + &DockerServices, + ) + .unwrap(); assert_eq!(observed["owner"], "deployment"); assert_eq!( observed["id"], @@ -503,12 +774,39 @@ mod tests { ); let mut changed = profile.clone(); changed.endpoints[0].host = "other.example".into(); - assert!(row(changed, "workspace", provider.profile(), true).is_err()); + assert!( + row( + changed, + "workspace", + provider.profile(), + true, + &DockerServices + ) + .is_err() + ); let mut changed = profile.clone(); changed.credentials[0].env_vars = vec!["OTHER_KEY".into()]; - assert!(row(changed, "workspace", provider.profile(), true).is_err()); + assert!( + row( + changed, + "workspace", + provider.profile(), + true, + &DockerServices + ) + .is_err() + ); profile.credentials[0].auth_style = "none".into(); - assert!(row(profile, "workspace", provider.profile(), true).is_err()); + assert!( + row( + profile, + "workspace", + provider.profile(), + true, + &DockerServices + ) + .is_err() + ); } } } diff --git a/crates/openshell-provider/src/provider.rs b/crates/openshell-provider/src/provider.rs index 6b53aa72b9f..d2582e1d713 100644 --- a/crates/openshell-provider/src/provider.rs +++ b/crates/openshell-provider/src/provider.rs @@ -27,6 +27,16 @@ pub struct OpenShellProvider { destroying: Arc, } +impl OpenShellProvider { + /// Serve resources using the deployment's managed service identity checks. + pub fn with_services(services: Arc) -> Self { + Self { + client: Arc::new(GatewayClient::with_services(services)), + destroying: Arc::default(), + } + } +} + #[async_trait] impl Provider for OpenShellProvider { type Config<'a> = GatewayConfig; diff --git a/crates/openshell-provider/src/transport.rs b/crates/openshell-provider/src/transport.rs index 9d623a5c359..7f770fe8df8 100644 --- a/crates/openshell-provider/src/transport.rs +++ b/crates/openshell-provider/src/transport.rs @@ -21,6 +21,7 @@ pub struct OpenShell { pub(super) struct ConnectedOpenShellGateway { pub(super) client: Arc, pub(super) secrets: Arc, + pub(super) services: Arc, } /// Whether a sandbox has finished starting. @@ -70,9 +71,20 @@ impl OpenShell { pub fn connect( connection: &nemoclaw_openshell::Connection, secrets: Arc, + ) -> Result { + Self::connect_with_services(connection, secrets, Arc::new(DockerServices)) + } + + /// Connect with the deployment's managed service identity checks. + pub fn connect_with_services( + connection: &nemoclaw_openshell::Connection, + secrets: Arc, + services: Arc, ) -> Result { Ok(Self { - gateway: Arc::new(ConnectedOpenShellGateway::connect(connection, secrets)?), + gateway: Arc::new(ConnectedOpenShellGateway::connect( + connection, secrets, services, + )?), }) } @@ -138,10 +150,12 @@ impl ConnectedOpenShellGateway { pub(crate) fn connect( connection: &nemoclaw_openshell::Connection, secrets: Arc, + services: Arc, ) -> Result { Ok(Self { client: Arc::new(nemoclaw_openshell::client(connection, secrets.as_ref())?), secrets, + services, }) } pub(super) fn request(&self, value: T) -> Request { @@ -167,7 +181,7 @@ impl ConnectedOpenShellGateway { ) -> Result, ObservationError> { let row = match kind { "workspace" => return self.workspace(name, removing).await, - "provider_profile" => self.observe_profile(workspace, name).await?, + "provider_profile" => self.observe_profile(workspace, name, removing).await?, "provider" => { let response = authoritative( self.client @@ -179,7 +193,7 @@ impl ConnectedOpenShellGateway { .await, )?; response - .map(|response| provider_row(response, name, removing)) + .map(|response| provider_row(response, name, removing, self.services.as_ref())) .transpose()? } "sandbox" => { @@ -195,7 +209,14 @@ impl ConnectedOpenShellGateway { else { return Ok(None); }; - let (row, ready) = sandbox_row(response, name, removing)?; + let (row, ready, grants) = checked_sandbox_row_with( + response, + workspace, + name, + removing, + |row| async move { self.sandbox_cluster_grants(&row).await }, + ) + .await?; if ready && !removing { let status = self .client @@ -210,7 +231,10 @@ impl ConnectedOpenShellGateway { .await .map_err(|error| remote_error(&error))? .into_inner(); - active_policy(status, &policy_json(&row_policy(&row)?)?)?; + active_policy( + status, + &policy_json(&network::granted_row_policy(&row, &grants)?)?, + )?; } Some(row) } @@ -375,7 +399,7 @@ impl ConnectedOpenShellGateway { binding, &base(sandbox.metadata.clone(), row_value(binding, "name"), false)?, )?; - let (observed, _) = sandbox_row( + let (observed, _, _) = sandbox_row( proto::SandboxResponse { sandbox: Some(sandbox.clone()), ..Default::default() diff --git a/crates/openshell-provider/tests/schema.txt b/crates/openshell-provider/tests/schema.txt index 0036ed976be..1c089d19b0d 100644 --- a/crates/openshell-provider/tests/schema.txt +++ b/crates/openshell-provider/tests/schema.txt @@ -23,6 +23,7 @@ provider openshell (version 0) resource openshell_provider_profile (version 0) authenticated: string, optional, computed binaries: list(string), required + cluster_source: string, optional, computed endpoint: string, optional, computed generation: string, optional, computed id: string, computed @@ -55,6 +56,8 @@ resource openshell_sandbox (version 0) runtime_json: string, required workspace: string, required block policy: optional + cluster_grants: list(string), optional + > Managed rule names whose exact addresses must come from verified Services. block explicit: optional version: number, required > Policy format version; currently 1.