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 f880cc2b721..22f01e0b4c9 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| remote_rejection(RejectableOperation::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.