diff --git a/.agents/skills/helm-dev-environment/SKILL.md b/.agents/skills/helm-dev-environment/SKILL.md index 170bdd7c16..5fc3661e20 100644 --- a/.agents/skills/helm-dev-environment/SKILL.md +++ b/.agents/skills/helm-dev-environment/SKILL.md @@ -143,6 +143,10 @@ shared process namespace. The sidecar sends SIGKILL to the supervisor as the same UID; it needs no host PID namespace, capabilities, or runtime socket. The default k3d/kind test continues to kill through the node container runtime. +`mise run e2e:kubernetes:shared-supervisor-node` runs the +`supervisor_topology: node` e2e (`ci/values-supervisor-node.yaml`) on a +two-node k3d cluster. + ### Shared supervisor high availability `mise run e2e:kubernetes:shared-supervisor-spiffe-node-local` validates direct diff --git a/.config/nextest.toml b/.config/nextest.toml index c5a25293b4..2d045e5c11 100644 --- a/.config/nextest.toml +++ b/.config/nextest.toml @@ -32,7 +32,7 @@ test-group = "kubernetes-ha" # they kill members or gateways, or scale the pool. Never run them at once. # Test names, not binary(), for the reason above. [[profile.e2e-kubernetes.overrides]] -filter = "test(/^(losing_a_supervisor_pod_moves_its_sandboxes_without_restarting_them|scaling_a_supervisor_pool_up_and_down_keeps_its_sandboxes_running|pool_sessions_follow_their_supervisors_gateway|shared_supervisor_acts_as_each_sandboxs_stable_spiffe_identity|supervisors_spread_evenly_across_gateways)$/)" +filter = "test(/^(losing_a_supervisor_pod_moves_its_sandboxes_without_restarting_them|scaling_a_supervisor_pool_up_and_down_keeps_its_sandboxes_running|pool_sessions_follow_their_supervisors_gateway|shared_supervisor_acts_as_each_sandboxs_stable_spiffe_identity|supervisors_spread_evenly_across_gateways|each_workload_is_served_by_its_own_nodes_supervisor|a_supervisor_claiming_another_nodes_member_id_is_refused)$/)" test-group = "kubernetes-shared-supervisor-pool" # Scaling the pool runs two bounded Helm upgrades (up to 6 minutes each), waits @@ -59,6 +59,12 @@ slow-timeout = { period = "60s", terminate-after = 15 } filter = "test(/^supervisors_spread_evenly_across_gateways$/)" slow-timeout = { period = "60s", terminate-after = 20 } +# Restarting a node supervisor waits for its replacement to receive the +# supervisor token, attach, and re-adopt the node's instances. +[[profile.e2e-kubernetes.overrides]] +filter = "test(/^each_workload_is_served_by_its_own_nodes_supervisor$/)" +slow-timeout = { period = "60s", terminate-after = 12 } + # Relative to the profile store dir (`e2e/rust/target/nextest/e2e-kubernetes/`). [profile.e2e-kubernetes.junit] path = "../../../../../results/e2e-kubernetes.xml" diff --git a/TESTING.md b/TESTING.md index e837e91fd2..7346526d75 100644 --- a/TESTING.md +++ b/TESTING.md @@ -992,6 +992,7 @@ Available task variants: | `e2e:kubernetes:shared-supervisor` | One-member shared supervisor pool for the gateway's sandboxes (gateway TLS through the port-forward) | | `e2e:kubernetes:shared-supervisor-ha` | Two-replica shared supervisor pool behind two gateway replicas on PostgreSQL: kills the member that owns a sandbox and checks the sandbox is adopted, not restarted; crashes and restarts gateways and checks each sandbox's session stays on its supervisor's gateway | | `e2e:kubernetes:shared-supervisor-scaling` | One-member shared supervisor pool: scales it to two members and back with `helm upgrade`, checking sandboxes stay running and the removed member hands its sandboxes off | +| `e2e:kubernetes:additional-ca-shared` | Additional destination CA with a one-member shared supervisor pool: checks the bundle reaches sandboxes without a ConfigMap or mount, and that removing it applies after a gateway restart and sandbox stop/start | | `e2e:kubernetes:tracing` | Deploys a Jaeger collector, exports gateway traces to it, and fails unless Jaeger receives gateway and Kubernetes compute-driver spans for a new sandbox. The only Kubernetes lane that exports traces | Kubernetes e2e environment variables: @@ -1005,6 +1006,7 @@ Kubernetes e2e environment variables: | `OPENSHELL_E2E_KUBE_CONFORMANCE` | `0` skips the conformance suites that otherwise run before the lane's Rust tests | | `OPENSHELL_E2E_KUBE_JAEGER` | `1` deploys a Jaeger collector, points gateway OTLP export at it, and sets `OPENSHELL_E2E_JAEGER_QUERY_URL` to its query API. Unset, the gateway exports no traces | | `OPENSHELL_E2E_KUBE_TLS` | `1` reaches the gateway over mTLS through the port-forward; pair it with an overlay that keeps gateway TLS on, such as `ci/values-tls-port-forward.yaml` | +| `OPENSHELL_E2E_KUBE_SUPERVISOR_TOPOLOGY` | `gateway` tells the `additional_ca` test the release uses shared supervisors, such as with `ci/values-supervisor.yaml` | | `OPENSHELL_E2E_KUBERNETES_FEATURES` | Cargo feature flags (default: `e2e,e2e-host-gateway,e2e-kubernetes`) | | `IMAGE_TAG` | Gateway/supervisor image tag (default: `latest` for existing clusters) | | `OPENSHELL_REGISTRY` | Image registry prefix (default: `ghcr.io/ai-openshell/openshell`) | diff --git a/crates/openshell-cli/src/run.rs b/crates/openshell-cli/src/run.rs index bd44344b43..efa5d0c1e5 100644 --- a/crates/openshell-cli/src/run.rs +++ b/crates/openshell-cli/src/run.rs @@ -1021,6 +1021,18 @@ pub async fn sandbox_create( config: SandboxCreateConfig<'_>, workspace: &str, tls: &TlsOptions, +) -> Result { + // The create flow holds several sandbox records; keep it off the + // caller's stack (clippy::large_futures). + Box::pin(create_sandbox(server, gateway_name, config, workspace, tls)).await +} + +async fn create_sandbox( + server: &str, + gateway_name: &str, + config: SandboxCreateConfig<'_>, + workspace: &str, + tls: &TlsOptions, ) -> Result { let SandboxCreateConfig { name, @@ -2174,6 +2186,7 @@ where let config_result = client .get_sandbox_config(GetSandboxConfigRequest { + sandbox_id: String::new(), name: name.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( workspace.to_string(), @@ -6016,6 +6029,7 @@ pub async fn sandbox_settings_get( let mut client = grpc_client(server, tls).await?; let response = client .get_sandbox_config(GetSandboxConfigRequest { + sandbox_id: String::new(), name: name.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( workspace.to_string(), @@ -6373,13 +6387,10 @@ pub async fn sandbox_policy_set( // Poll for status until loaded, failed, or timeout. let deadline = Instant::now() + Duration::from_secs(timeout_secs); + let mut supervisor_loaded = false; loop { if Instant::now() > deadline { - eprintln!( - "{} Timeout waiting for policy version {} to load", - "✗".red().bold(), - resp.version - ); + print_policy_wait_timeout(resp.version, supervisor_loaded); std::process::exit(124); } @@ -6428,7 +6439,7 @@ pub async fn sandbox_policy_set( ); return Ok(()); } - _ => {} // still pending, keep polling + _ => supervisor_loaded = rev.loaded_time.is_some(), } } } @@ -6473,6 +6484,7 @@ pub async fn sandbox_policy_update( let mut client = grpc_client(server, tls).await?; let current = client .get_sandbox_config(GetSandboxConfigRequest { + sandbox_id: String::new(), name: name.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( workspace.to_string(), @@ -6551,13 +6563,10 @@ pub async fn sandbox_policy_update( } let deadline = Instant::now() + Duration::from_secs(timeout_secs); + let mut supervisor_loaded = false; loop { if Instant::now() > deadline { - eprintln!( - "{} Timeout waiting for policy version {} to load", - "✗".red().bold(), - response.version - ); + print_policy_wait_timeout(response.version, supervisor_loaded); std::process::exit(124); } @@ -6606,12 +6615,28 @@ pub async fn sandbox_policy_update( ); return Ok(()); } - _ => {} + _ => supervisor_loaded = rev.loaded_time.is_some(), } } } } +/// A loaded time on a pending revision means the supervisor loaded it and +/// the native-network enforcer has not accepted it yet. +fn print_policy_wait_timeout(version: u32, supervisor_loaded: bool) { + let detail = if supervisor_loaded { + ": the supervisor loaded it; waiting for the network enforcer" + } else { + "" + }; + eprintln!( + "{} Timeout waiting for policy version {} to load{}", + "✗".red().bold(), + version, + detail + ); +} + pub async fn sandbox_policy_get( server: &str, name: &str, @@ -6771,6 +6796,7 @@ where let config = client .get_sandbox_config(GetSandboxConfigRequest { + sandbox_id: String::new(), name: name.to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( workspace.to_string(), diff --git a/crates/openshell-core/src/grpc_client.rs b/crates/openshell-core/src/grpc_client.rs index 2429f255cc..c51b335960 100644 --- a/crates/openshell-core/src/grpc_client.rs +++ b/crates/openshell-core/src/grpc_client.rs @@ -1284,6 +1284,7 @@ async fn fetch_settings_snapshot_with_client( supported_capabilities, workspace_scope: workspace.map(crate::proto::workspace_selector), name: sandbox_name.to_string(), + sandbox_id: String::new(), }) .await .map_err(grpc_status_error)?; @@ -2062,6 +2063,11 @@ pub struct SettingsPollResult { pub service_routes: Vec, pub configuration_instance_id: String, pub configuration_admitted: bool, + /// The gateway holds this instance's first activation; neither activate + /// nor report a rejection. + pub activation_pending: bool, + /// Native-network mode: the provider revision the enforcer accepted. + pub enforcer_provider_env_revision: u64, pub configuration_error: String, pub policy: Option, pub version: u32, @@ -2090,6 +2096,8 @@ fn settings_poll_result(inner: crate::proto::GetSandboxConfigResponse) -> Settin service_routes: inner.service_routes, configuration_instance_id: inner.configuration_instance_id, configuration_admitted: inner.configuration_admitted, + activation_pending: inner.activation_pending, + enforcer_provider_env_revision: inner.enforcer_provider_env_revision, configuration_error: inner.configuration_error, policy: inner.policy, version: inner.version, @@ -2131,6 +2139,8 @@ impl From for SettingsPollResult { policy_validation_failure_mode: snapshot.policy_validation_failure_mode, extension_authentication_enabled: snapshot.extension_authentication_enabled, configuration_admitted: snapshot.configuration_admitted, + activation_pending: snapshot.activation_pending, + enforcer_provider_env_revision: snapshot.enforcer_provider_env_revision, provider_attachment_epoch: snapshot.provider_attachment_epoch, configuration_instance_id: snapshot.configuration_instance_id, configuration_error: snapshot.configuration_error, @@ -2308,6 +2318,7 @@ mod provider_snapshot_tests { ..Default::default() }, ProviderEnvironmentValue { + workload_placeholder: String::new(), name: "TOKEN".to_string(), value: "redacted".to_string(), classification: ProviderEnvironmentValueClassification::StaticCredential.into(), @@ -2423,6 +2434,7 @@ impl CachedOpenShellClient { supported_capabilities: self.supported_capabilities.clone(), workspace_scope, name: sandbox_name.to_string(), + sandbox_id: String::new(), }) .await .into_diagnostic()?; diff --git a/crates/openshell-core/src/jwt.rs b/crates/openshell-core/src/jwt.rs index 84ffe98ec0..375d5e6ac2 100644 --- a/crates/openshell-core/src/jwt.rs +++ b/crates/openshell-core/src/jwt.rs @@ -50,6 +50,10 @@ mod session { /// JOSE `typ` of the supervisor token: the credential of the gateway's /// shared supervisor process for the assignment stream, and nothing else. pub const SUPERVISOR_JWT_TYPE: &str = "openshell-supervisor+jwt"; + /// JOSE `typ` of the enforcer token: the credential of an external + /// enforcer host on the assignment stream and its read and acknowledgement + /// RPCs. + pub const ENFORCER_JWT_TYPE: &str = "openshell-enforcer+jwt"; /// JOSE `typ` of a supervisor takeover grant. /// /// The grant is the gateway's authorization for one supervisor process to @@ -70,6 +74,31 @@ mod session { const GATEWAY_ISSUER_PREFIX: &str = "openshell-gateway:"; const SANDBOX_SUBJECT_PREFIX: &str = "spiffe://openshell/sandbox/"; const SUPERVISOR_SUBJECT_PREFIX: &str = "openshell-supervisor:"; + const ENFORCER_SUBJECT_PREFIX: &str = "openshell-enforcer:"; + + /// The two host token profiles: same claims and key, distinct `typ` and + /// subject, so neither is ever accepted as the other. + #[derive(Clone, Copy, Debug, PartialEq, Eq)] + pub enum HostTokenProfile { + Supervisor, + Enforcer, + } + + impl HostTokenProfile { + const fn jwt_type(self) -> &'static str { + match self { + Self::Supervisor => SUPERVISOR_JWT_TYPE, + Self::Enforcer => ENFORCER_JWT_TYPE, + } + } + + const fn subject_prefix(self) -> &'static str { + match self { + Self::Supervisor => SUPERVISOR_SUBJECT_PREFIX, + Self::Enforcer => ENFORCER_SUBJECT_PREFIX, + } + } + } /// Canonical sandbox identity carried by both session-token profiles. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] @@ -913,6 +942,15 @@ mod session { pub fn mint_supervisor_token( &self, ttl: Duration, + ) -> Result { + self.mint_host_token(HostTokenProfile::Supervisor, ttl) + } + + /// Mint a host token of `profile` with its own bounded lifetime. + pub fn mint_host_token( + &self, + profile: HostTokenProfile, + ttl: Duration, ) -> Result { validate_ttl(ttl)?; let issued_at = self.clock.now_unix_seconds(); @@ -922,7 +960,7 @@ mod session { let gateway_id = &self.issuer[GATEWAY_ISSUER_PREFIX.len()..]; let claims = SupervisorClaims { iss: self.issuer.clone(), - sub: format!("{SUPERVISOR_SUBJECT_PREFIX}{gateway_id}"), + sub: format!("{}{gateway_id}", profile.subject_prefix()), aud: self.issuer.clone(), iat: issued_at, exp: expires_at, @@ -931,7 +969,7 @@ mod session { }; let mut header = Header::new(Algorithm::EdDSA); header.kid = Some(self.key_id.clone()); - header.typ = Some(SUPERVISOR_JWT_TYPE.to_string()); + header.typ = Some(profile.jwt_type().to_string()); let token = encode(&header, &claims, &self.encoding_key) .map_err(|_| SessionJwtError::SigningFailed)?; Ok(MintedSessionToken { @@ -1162,20 +1200,22 @@ mod session { } } - /// A verified supervisor token. + /// A verified host token. #[derive(Clone, Debug, PartialEq, Eq)] pub struct AuthenticatedSupervisor { - /// `openshell-supervisor:`. + /// `openshell-supervisor:` or + /// `openshell-enforcer:`. pub subject: String, pub token_id: Uuid, pub issued_at: i64, pub expires_at: i64, } - /// Strict gateway-side verifier of supervisor tokens. Accepts only the - /// supervisor profile signed by this gateway for this gateway. + /// Strict gateway-side verifier of host tokens. Accepts only its profile + /// signed by this gateway for this gateway. pub struct SupervisorJwtVerifier { keys: BTreeMap, + profile: HostTokenProfile, issuer: String, subject: String, clock: Arc, @@ -1196,13 +1236,23 @@ mod session { gateway_id: &str, keys: impl IntoIterator, clock: Arc, + ) -> Result { + Self::for_profile(HostTokenProfile::Supervisor, gateway_id, keys, clock) + } + + pub fn for_profile( + profile: HostTokenProfile, + gateway_id: &str, + keys: impl IntoIterator, + clock: Arc, ) -> Result { install_crypto_provider(); let gateway_id = validate_gateway_id(gateway_id)?; Ok(Self { keys: parse_verification_keys(keys)?, + profile, issuer: format!("{GATEWAY_ISSUER_PREFIX}{gateway_id}"), - subject: format!("{SUPERVISOR_SUBJECT_PREFIX}{gateway_id}"), + subject: format!("{}{gateway_id}", profile.subject_prefix()), clock, }) } @@ -1211,7 +1261,7 @@ mod session { let claims = decode_signed::( &self.keys, token, - SUPERVISOR_JWT_TYPE, + self.profile.jwt_type(), &["iss", "aud", "iat", "exp", "sub", "jti"], )?; if claims.iss != self.issuer { @@ -1661,6 +1711,37 @@ mod tests { assert_eq!(authenticated.token_id, minted.token_id); assert_eq!(authenticated.expires_at, 1_900_000_900); + // Enforcer tokens are their own profile: neither verifier accepts + // the other's token. + let enforcer_verifier = SupervisorJwtVerifier::for_profile( + HostTokenProfile::Enforcer, + "gw-a", + [verification_key()], + Arc::new(FixedClock(1_900_000_100)), + ) + .unwrap(); + let enforcer = issuer("gw-a", 1_900_000_000) + .mint_host_token( + HostTokenProfile::Enforcer, + std::time::Duration::from_mins(15), + ) + .unwrap(); + assert_eq!( + enforcer_verifier + .verify(enforcer.token.expose_secret()) + .unwrap() + .subject, + "openshell-enforcer:gw-a" + ); + assert_eq!( + verifier("gw-a", 1_900_000_100).verify(enforcer.token.expose_secret()), + Err(SessionJwtError::WrongTokenType) + ); + assert_eq!( + enforcer_verifier.verify(minted.token.expose_secret()), + Err(SessionJwtError::WrongTokenType) + ); + // Another gateway's token is refused by issuer, audience, and subject. assert_eq!( verifier("gw-b", 1_900_000_100).verify(minted.token.expose_secret()), diff --git a/crates/openshell-core/src/secrets.rs b/crates/openshell-core/src/secrets.rs index 38be363a0e..be43921dc7 100644 --- a/crates/openshell-core/src/secrets.rs +++ b/crates/openshell-core/src/secrets.rs @@ -496,16 +496,11 @@ impl SecretResolver { .copied() .unwrap_or_default(), }; - let placeholder = stable_handles.get(&key).map_or_else( - || { - let placeholder = placeholder_for_env_key_for_revision(&key, revision); - if revision != 0 { - generation_values.insert(placeholder.clone(), secret.clone()); - } - placeholder - }, - |handle| placeholder_for_env_key_for_stable_handle(&key, handle), - ); + let handle = stable_handles.get(&key).map(String::as_str); + let placeholder = workload_placeholder(&key, revision, handle); + if handle.is_none() && revision != 0 { + generation_values.insert(placeholder.clone(), secret.clone()); + } child_env.insert(key.clone(), placeholder.clone()); current_values.insert(placeholder, secret.clone()); current_values.insert(placeholder_for_env_key(&key), secret); @@ -1235,10 +1230,22 @@ pub fn placeholder_for_env_key_for_revision(key: &str, revision: u64) -> String } } -pub(crate) fn placeholder_for_env_key_for_stable_handle(key: &str, handle: &str) -> String { +pub fn placeholder_for_env_key_for_stable_handle(key: &str, handle: &str) -> String { format!("{PLACEHOLDER_PREFIX}s{handle}_{key}") } +/// The placeholder a workload receives for static credential `key` at +/// provider revision `revision`. +/// +/// It takes the stable-handle form when the credential's binding carries a +/// workload credential `handle`, otherwise the revisioned form. +pub fn workload_placeholder(key: &str, revision: u64, handle: Option<&str>) -> String { + handle.map_or_else( + || placeholder_for_env_key_for_revision(key, revision), + |handle| placeholder_for_env_key_for_stable_handle(key, handle), + ) +} + // --------------------------------------------------------------------------- // Secret validation (F1 — CWE-113) // --------------------------------------------------------------------------- diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index bb2c4e49fb..eafee2b5f2 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -220,7 +220,17 @@ fails closed. replaces the `token` key of the chart-created `shared_supervisor.token_secret_name` Secret in `service_namespace`, which the supervisor Pod mounts, and names a missing Secret or a denied patch in - the retried error. + the retried error. With `external_enforcer`, a second writer delivers the + enforcer token the same way to `external_enforcer.token_secret_name` in + `external_enforcer.namespace`. +- **Pod identity.** The driver registers + `shared_supervisor.service_account_name`, the ServiceAccount the supervisor + Pods run as, with the controller (`require_host_identity`), and with + `external_enforcer` its `service_account_name` in its `namespace` for the + enforcer. A projected ServiceAccount token sent with a host token must + resolve to a live Pod of its role's account. The enforcer always needs one; + with `shared_supervisor.require_identity_token`, or in the node topology, so + does a supervisor, so a copy of the token Secret alone admits no caller. - **Create and start.** The driver creates a per-sandbox egress allowance `os-shared-control-` from the workload Pod to the Pods the shared supervisor's Service selects, on the runtime port, binds its UID and @@ -280,6 +290,30 @@ When the setting is removed, reconciliation suspends shared generations, and a restart creates the dedicated generation's boundary Service the shared one never had. +#### Node topology + +`supervisor_topology = "node"` runs the same shared pool with one supervisor +per node, and pins each generation to the supervisor on its workload's node. +The driver binds pool members to nodes (`bind_members_to_nodes`): the gateway +accepts a supervisor only when the Pod its identity token resolves to is +scheduled on the node it claims as its pool member ID. + +- **Placement.** The driver removes the scheduling gate and returns from + create or restart before it assigns the instance. The bootstrap task watches + the workload Pod and launches on the node in its `spec.nodeName`. A Pod that + is deleted or replaced, or a node supervisor that refuses the instance, rolls + the bootstrap back. So does a Pod that isn't scheduled within + `runtime_bootstrap_grace_seconds`. + The Sandbox's `openshell.ai/sandbox-runtime-supervisor-member` annotation + records the pinned node. The bootstrap Secret exists before the gate is removed; until the + launch places the route, the supervisor refuses the runtime's dials and the + workload does not start. +- **Recovery and takeover.** Recovery reads the member annotation and skips a + node-topology generation that lacks one. Placement, takeover, and recovery + of a pinned instance only consider its own member, so a lost node + supervisor's instances wait for it to return. A restart clears the + annotation, and the new generation records its own node. + ## Sandbox Resource The driver works with the `agents.x-k8s.io` `Sandbox` custom resource. It @@ -405,6 +439,54 @@ for `nvidia.com/gpu` and requests the configured GPU count in the workload spec. When no count is set, the driver requests one GPU resource. The sandbox image must provide the user-space libraries needed by the agent workload. +## External Enforcer + +`external_enforcer` selects native-network mode and owns the only Multus +networks the driver attaches, so no setting attaches a sandbox to a network +that bypasses both the supervisor and an enforcer. +`external_enforcer.network.sandbox` sets `v1.multus-cni.io/default-network` +on every new workload Pod, overriding any caller annotation. When `resource` is +set, the +agent container requests and limits `1` of it, and resource admission accepts +it next to `nvidia.com/gpu` at create and at reconcile. Reconcile suspends +stored sandboxes that request a resource the config no longer names. Restarts +reuse the stored template. See +[gateway configuration](../../docs/how-it-works/gateways/configuration.mdx#kubernetes) +for operator requirements. + +In native-network mode `provision()` writes the resource claim +`openshell.native_network = "true"` into both the boundary config and the +runtime descriptor. `validate_configuration` enforces the mode's requirements +in the gateway configuration reference, including the refusal of the Multus +annotation domains, which would let a sandbox creator add a network interface +the enforcer doesn't own. The gateway reads the mode and the +resolvers through `ComputeDriverFactory::native_network`. The workload Pod's +`dnsConfig` names `network.sandbox.nameservers` instead of the supervisor's policy DNS on +`127.0.0.53`, and the launch posture check holds the Pod to them; a restart +applies the current list. +The mode also sets +`node-restriction.kubernetes.io/openshell-external-enforcer-ready: "true"` in +every workload Pod's `nodeSelector`, after caller driver config, so a caller +can't schedule a sandbox to a node the enforcer doesn't cover. +Each launch patches the Sandbox with the workload Pod's UID in +`openshell.ai/sandbox-runtime-workload-uid` and the gateway's runtime +generation in `openshell.ai/sandbox-runtime-gateway-generation`. An enforcer +matches a Pod to the generation it reports against through these two +annotations. +Create marks a native-network Sandbox with `openshell.ai/native-network: +"true"`. Stored-resource admission refuses a Sandbox whose mark differs from the +current mode, so reconcile suspends it and launch, restart and image update +fail with `FailedPrecondition`. + +With `external_enforcer.network.supervisor`, the boundary listener dials the workload +node's supervisor at its address on that network, with the runtime port, +instead of the Service `ClusterIP`. The TLS authority stays the Service name. +The driver reads the address after scheduling from the `network-status` of the +node's Ready supervisor Pods. Each Ready Pod must report the same single +routable IPv4 address, or the launch fails. Because the address is part of the +boundary config, the driver writes the bootstrap Secret then too, and the +workload Pod waits in `ContainerCreating` until it exists. + ## Driver Config Following RFC 0006, this driver accepts the selected @@ -443,7 +525,9 @@ Resource keys use native Kubernetes resource names and quantity strings. The parser renders the keys listed above and rejects unknown fields. `pod.runtime_class_name` maps to PodSpec `runtimeClassName` and overrides the driver's configured `default_runtime_class_name`; the typed public -`SandboxTemplate.runtime_class_name` still takes precedence when set. Use the +`SandboxTemplate.runtime_class_name` still takes precedence when set. +The driver overrides any `containers.agent.resources` value for +`external_enforcer.network.sandbox.resource` with `1`. Use the public `--gpu` flag for the default GPU request, pass a count to `--gpu` for counted GPU requests, and use `driver_config` only for additional driver-owned resource details. diff --git a/crates/openshell-driver-kubernetes/src/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index 82f98cdb54..32f27f5209 100644 --- a/crates/openshell-driver-kubernetes/src/config.rs +++ b/crates/openshell-driver-kubernetes/src/config.rs @@ -7,6 +7,7 @@ use serde::{Deserialize, Deserializer, Serialize}; use std::collections::BTreeMap; #[cfg(test)] use std::collections::BTreeSet; +use std::net::IpAddr; use std::path::Path; use std::str::FromStr; @@ -220,10 +221,13 @@ where #[serde(rename_all = "snake_case")] pub enum SupervisorTopology { Gateway, + /// One shared supervisor per node, serving the sandboxes whose workload + /// Pods run on that node. + Node, Workspace, } -/// The supervisor Helm deploys for the gateway topology. +/// The supervisor Helm deploys for the gateway or node topology. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct SharedSupervisorConfig { @@ -236,6 +240,13 @@ pub struct SharedSupervisorConfig { /// gateway-minted supervisor token (key `token`); the supervisor Pod /// mounts it and presents the token on its assignment stream. pub token_secret_name: String, + /// `ServiceAccount` in `service_namespace` the supervisor Pods run as; a + /// pod-bound token for it accompanies the supervisor token. + pub service_account_name: String, + /// Refuse a supervisor token without the pod-bound token. A present + /// token is verified either way. + #[serde(default)] + pub require_identity_token: bool, } impl SharedSupervisorConfig { @@ -251,6 +262,11 @@ impl SharedSupervisorConfig { if !is_dns_subdomain(&self.token_secret_name) { return Err("shared_supervisor token_secret_name must be a DNS subdomain name".into()); } + if !is_dns_subdomain(&self.service_account_name) { + return Err( + "shared_supervisor service_account_name must be a DNS subdomain name".into(), + ); + } Ok(()) } @@ -261,6 +277,160 @@ impl SharedSupervisorConfig { } } +/// A Multus network attachment and its optional device resource. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct PodNetwork { + /// Multus `NetworkAttachmentDefinition`, as `namespace/name` or `name`. + pub network_attachment: String, + /// Extended resource the attachment's device plugin allocates, requested + /// once per Pod. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub resource: Option, +} + +impl PodNetwork { + fn validate(&self, table: &str) -> Result<(), String> { + let (namespace, name) = self.network_attachment.split_once('/').map_or( + (None, self.network_attachment.as_str()), + |(namespace, name)| (Some(namespace), name), + ); + if namespace.is_some_and(|namespace| !is_dns_label(namespace)) || !is_dns_subdomain(name) { + return Err(format!( + "{table}.network_attachment must be / or " + )); + } + if let Some(resource) = &self.resource { + let qualified = resource.split_once('/').is_some_and(|(domain, name)| { + is_dns_subdomain(domain) && is_qualified_name_segment(name) + }); + if !qualified { + return Err(format!( + "{table}.resource must be an extended resource name such as example.com/device" + )); + } + let domain = resource.split_once('/').map_or("", |(domain, _)| domain); + if domain == "kubernetes.io" || domain.ends_with(".kubernetes.io") { + return Err(format!( + "{table}.resource cannot be in the kubernetes.io domain, which Kubernetes reserves" + )); + } + if resource == "nvidia.com/gpu" { + return Err(format!( + "{table}.resource cannot be nvidia.com/gpu; GPUs are requested per sandbox" + )); + } + } + Ok(()) + } +} + +/// Node label the external enforcer keeps at `true` on exactly the nodes +/// where it can enforce. +/// +/// Native-network workload Pods and node supervisors select it. With the +/// `NodeRestriction` admission plugin, kubelets can't set labels under +/// `node-restriction.kubernetes.io/` on their own node. +pub const EXTERNAL_ENFORCER_READY_NODE_LABEL: &str = + "node-restriction.kubernetes.io/openshell-external-enforcer-ready"; + +/// Kubernetes refuses a Pod whose `dnsConfig` names more nameservers. +const MAX_POD_NAMESERVERS: usize = 3; + +/// An external enforcer outside the Pod enforces network policy and injects +/// credentials. Configuring it launches every new runtime in native-network +/// mode: the runtime hands agent sockets to the kernel. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExternalEnforcerConfig { + /// Namespace the external enforcer runs in, distinct from the + /// supervisor's. + pub namespace: String, + /// Secret in `namespace` the driver keeps current with the gateway-minted + /// external enforcer token (key `token`), which the external enforcer + /// mounts. + pub token_secret_name: String, + /// `ServiceAccount` in `namespace` the external enforcer's Pods run as; a + /// pod-bound token for it must accompany the external enforcer token. + pub service_account_name: String, + pub network: ExternalEnforcerNetwork, +} + +/// The networks the external enforcer owns. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct ExternalEnforcerNetwork { + /// The only network of every new workload Pod, with its device requested + /// on the agent container. + pub sandbox: SandboxNetwork, + /// Additional network sandbox runtimes reach the node supervisor on. The + /// driver gives each runtime the address of its node's supervisor on this + /// network instead of the Service `ClusterIP`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub supervisor: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(deny_unknown_fields)] +pub struct SandboxNetwork { + #[serde(flatten)] + pub network: PodNetwork, + /// The sandboxes' only DNS servers, answered by the external enforcer on + /// port 53. + pub nameservers: Vec, +} + +impl ExternalEnforcerConfig { + /// The sandboxes' resolvers. + #[must_use] + pub fn nameservers(&self) -> &[IpAddr] { + &self.network.sandbox.nameservers + } + + fn validate(&self, shared: &SharedSupervisorConfig) -> Result<(), String> { + if !is_dns_label(&self.namespace) || self.namespace == shared.service_namespace { + return Err( + "external_enforcer.namespace must be a DNS label distinct from \ + shared_supervisor.service_namespace" + .into(), + ); + } + if !is_dns_subdomain(&self.token_secret_name) { + return Err("external_enforcer.token_secret_name must be a DNS subdomain name".into()); + } + if !is_dns_subdomain(&self.service_account_name) { + return Err( + "external_enforcer.service_account_name must be a DNS subdomain name".into(), + ); + } + let sandbox = &self.network.sandbox; + sandbox + .network + .validate("external_enforcer.network.sandbox")?; + if sandbox.nameservers.is_empty() { + return Err("external_enforcer.network.sandbox.nameservers must not be empty".into()); + } + if sandbox.nameservers.len() > MAX_POD_NAMESERVERS { + return Err(format!( + "external_enforcer.network.sandbox.nameservers accepts at most \ + {MAX_POD_NAMESERVERS} addresses, as a Pod's dnsConfig does" + )); + } + for (index, nameserver) in sandbox.nameservers.iter().enumerate() { + if sandbox.nameservers[..index].contains(nameserver) { + return Err(format!( + "external_enforcer.network.sandbox.nameservers lists {nameserver} more \ + than once" + )); + } + } + if let Some(supervisor) = &self.network.supervisor { + supervisor.validate("external_enforcer.network.supervisor")?; + } + Ok(()) + } +} + /// RFC 1123 subdomain, as Kubernetes object names require. fn is_dns_subdomain(value: &str) -> bool { !value.is_empty() @@ -430,6 +600,10 @@ pub struct KubernetesComputeConfig { /// by the gateway administrator; sandbox creators cannot change it, and /// it never inherits the workload class. Empty (default) = omit the field. pub supervisor_runtime_class_name: String, + /// External enforcer of network policy; selects native-network mode for + /// every new runtime. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub external_enforcer: Option, /// Pod annotation keys that sandbox templates may set. Each entry is an /// exact key (`example.com/team`) or a prefix wildcard (`example.com/*`). /// Empty (default) rejects every caller-supplied pod annotation. @@ -552,6 +726,7 @@ impl Default for KubernetesComputeConfig { workspace_storage_class: String::new(), default_runtime_class_name: String::new(), supervisor_runtime_class_name: String::new(), + external_enforcer: None, allowed_pod_annotations: Vec::new(), allowed_pod_labels: Vec::new(), sa_token_ttl_secs: 3600, @@ -574,7 +749,60 @@ impl KubernetesComputeConfig { self.validate_upstream_proxy_config()?; self.validate_allowed_pod_annotations()?; self.validate_allowed_pod_labels()?; - self.ipv6_egress_config().validate() + self.ipv6_egress_config().validate()?; + let Some(enforcer) = &self.external_enforcer else { + return Ok(()); + }; + // Native-network workloads dial a shared supervisor; there is no + // dedicated supervisor Pod to reach them. + let shared = self + .shared_supervisor + .as_ref() + .ok_or("external_enforcer requires supervisor_topology=gateway or node")?; + enforcer.validate(shared)?; + // App endpoints require the advertised runtime address to be the Pod + // IP, which the supervisor network attachment replaces. + if enforcer.network.supervisor.is_some() && self.sandbox_runtime.app_listener.common.enabled + { + return Err( + "external_enforcer.network.supervisor does not support the supervisor app listener" + .into(), + ); + } + if let Some(entry) = self.allowed_pod_annotations.iter().find(|entry| { + let key = entry.strip_suffix("/*").unwrap_or(entry); + let domain = key.split_once('/').map_or(key, |(domain, _)| domain); + MULTUS_ANNOTATION_DOMAINS.contains(&domain) + }) { + return Err(format!( + "external_enforcer refuses allowed_pod_annotations entry {entry:?}, which would \ + let a sandbox add a network interface the external enforcer doesn't own" + )); + } + Ok(()) + } + + /// The external enforcer, when new runtimes launch in native-network + /// mode. + #[must_use] + pub fn external_enforcer(&self) -> Option<&ExternalEnforcerConfig> { + self.external_enforcer.as_ref() + } + + /// The extended resource the sandbox network requests. + #[must_use] + pub fn sandbox_network_resource(&self) -> Option<&str> { + self.external_enforcer + .as_ref() + .and_then(|enforcer| enforcer.network.sandbox.network.resource.as_deref()) + } + + /// The sandboxes' resolvers, empty outside native-network mode. + #[must_use] + pub fn sandbox_nameservers(&self) -> &[IpAddr] { + self.external_enforcer + .as_ref() + .map_or(&[], ExternalEnforcerConfig::nameservers) } fn validate_bootstrap_windows(&self) -> Result<(), String> { @@ -602,16 +830,23 @@ impl KubernetesComputeConfig { match self.supervisor_topology { None => { if self.shared_supervisor.is_some() { - return Err("shared_supervisor requires supervisor_topology=gateway".into()); + return Err( + "shared_supervisor requires supervisor_topology=gateway or node".into(), + ); } Ok(()) } Some(SupervisorTopology::Workspace) => { Err("supervisor_topology=workspace is not implemented".into()) } - Some(SupervisorTopology::Gateway) => { + Some(topology @ (SupervisorTopology::Gateway | SupervisorTopology::Node)) => { + let topology_name = if topology == SupervisorTopology::Node { + "node" + } else { + "gateway" + }; let shared = self.shared_supervisor.as_ref().ok_or_else(|| { - "supervisor_topology=gateway requires shared_supervisor".to_string() + format!("supervisor_topology={topology_name} requires shared_supervisor") })?; shared.validate()?; if self.sandbox_runtime.app_listener.common.enabled @@ -623,10 +858,9 @@ impl KubernetesComputeConfig { || self.proxy_auth_secret_name.is_some() || self.proxy_ca_bundle.is_some() { - return Err( - "supervisor_topology=gateway does not support upstream proxy settings" - .into(), - ); + return Err(format!( + "supervisor_topology={topology_name} does not support upstream proxy settings" + )); } Ok(()) } @@ -1108,6 +1342,9 @@ fn validate_pod_metadata_allowlist(field: &str, entries: &[String]) -> Result<() Ok(()) } +/// Annotation domains through which Multus adds or replaces Pod networks. +const MULTUS_ANNOTATION_DOMAINS: [&str; 2] = ["k8s.v1.cni.cncf.io", "v1.multus-cni.io"]; + fn pod_metadata_key_allowed(entries: &[String], key: &str) -> bool { let prefix = key.split_once('/').map(|(prefix, _)| prefix); if prefix.is_some_and(is_reserved_pod_metadata_domain) { @@ -1212,6 +1449,8 @@ mod tests { service_namespace: "openshell".to_string(), runtime_port: 8443, token_secret_name: "openshell-supervisor-token".to_string(), + service_account_name: "openshell-supervisor".to_string(), + require_identity_token: false, }; let gateway = |shared: Option| KubernetesComputeConfig { supervisor_topology: Some(SupervisorTopology::Gateway), @@ -1243,6 +1482,10 @@ mod tests { token_secret_name: "Not_A_Secret_Name".to_string(), ..shared() }, + SharedSupervisorConfig { + service_account_name: "Not_A_Name".to_string(), + ..shared() + }, ] { assert!( gateway(Some(invalid)) @@ -1441,6 +1684,256 @@ mod tests { assert_eq!(cfg.default_runtime_class_name, "nvidia"); } + fn external_enforcer_config(extra: &str) -> KubernetesComputeConfig { + toml::from_str(&format!( + r#" + supervisor_topology = "node" + {extra} + + [shared_supervisor] + service_name = "openshell-supervisor" + service_namespace = "openshell" + runtime_port = 5500 + token_secret_name = "openshell-supervisor-token" + service_account_name = "openshell-supervisor" + + [external_enforcer] + namespace = "openshell-enforcer" + token_secret_name = "openshell-enforcer-token" + service_account_name = "external-enforcer" + + [external_enforcer.network.sandbox] + network_attachment = "openshell/sandbox-vf" + resource = "example.com/vf" + nameservers = ["192.168.100.1", "fd00::1"] + + [external_enforcer.network.supervisor] + network_attachment = "openshell/supervisor-vf" + resource = "example.com/supervisor-vf" + "# + )) + .unwrap() + } + + #[test] + fn external_enforcer_parses_and_requires_a_shared_supervisor() { + let config = external_enforcer_config(""); + config.validate_configuration().unwrap(); + let enforcer = config.external_enforcer().unwrap(); + assert_eq!( + enforcer.nameservers(), + [ + "192.168.100.1".parse::().unwrap(), + "fd00::1".parse().unwrap() + ] + ); + assert_eq!(config.sandbox_nameservers(), enforcer.nameservers()); + assert_eq!(config.sandbox_network_resource(), Some("example.com/vf")); + assert_eq!( + enforcer.network.supervisor, + Some(PodNetwork { + network_attachment: "openshell/supervisor-vf".to_string(), + resource: Some("example.com/supervisor-vf".to_string()), + }) + ); + assert!( + KubernetesComputeConfig::default() + .external_enforcer() + .is_none() + ); + assert!( + KubernetesComputeConfig::default() + .sandbox_nameservers() + .is_empty() + ); + + let mut without_supervisor_network = config.clone(); + without_supervisor_network + .external_enforcer + .as_mut() + .unwrap() + .network + .supervisor = None; + without_supervisor_network.validate_configuration().unwrap(); + + let mut gateway = config.clone(); + gateway.supervisor_topology = Some(SupervisorTopology::Gateway); + gateway.validate_configuration().unwrap(); + let dedicated = KubernetesComputeConfig { + supervisor_topology: None, + shared_supervisor: None, + ..config.clone() + }; + let error = dedicated.validate_configuration().unwrap_err(); + assert!( + error.contains("supervisor_topology=gateway or node"), + "{error}" + ); + + let mut app_listener = without_supervisor_network; + app_listener.sandbox_runtime.app_listener.tls_secret_name = "app-tls".into(); + app_listener.sandbox_runtime.app_listener.common = + openshell_core::app_listener::AppListenerConfig { + base_url: Some("https://services.example.com".into()), + enabled: true, + port: 9443, + }; + app_listener.validate_configuration().unwrap(); + app_listener.external_enforcer = config.external_enforcer.clone(); + let error = app_listener.validate_configuration().unwrap_err(); + assert!(error.contains("app listener"), "{error}"); + } + + #[test] + fn external_enforcer_runs_in_its_own_namespace_with_valid_names() { + let config = external_enforcer_config(""); + let with = |change: &dyn Fn(&mut ExternalEnforcerConfig)| { + let mut config = config.clone(); + change(config.external_enforcer.as_mut().unwrap()); + config.validate_configuration() + }; + + let error = with(&|enforcer| enforcer.namespace = "openshell".to_string()).unwrap_err(); + assert!( + error.contains("distinct from shared_supervisor.service_namespace"), + "{error}" + ); + let error = with(&|enforcer| enforcer.namespace = "Not_A_Label".to_string()).unwrap_err(); + assert!(error.contains("external_enforcer.namespace"), "{error}"); + let error = with(&|enforcer| enforcer.token_secret_name.clear()).unwrap_err(); + assert!( + error.contains("external_enforcer.token_secret_name"), + "{error}" + ); + let error = with(&|enforcer| enforcer.service_account_name.clear()).unwrap_err(); + assert!( + error.contains("external_enforcer.service_account_name"), + "{error}" + ); + + for missing in ["namespace", "token_secret_name", "service_account_name"] { + let mut value = toml::Value::try_from(&config).unwrap(); + value["external_enforcer"] + .as_table_mut() + .unwrap() + .remove(missing); + assert!( + value.try_into::().is_err(), + "{missing} is required" + ); + } + } + + #[test] + fn external_enforcer_networks_validate() { + let config = external_enforcer_config(""); + let with = |change: &dyn Fn(&mut ExternalEnforcerNetwork)| { + let mut config = config.clone(); + change(&mut config.external_enforcer.as_mut().unwrap().network); + config.validate_configuration() + }; + + for resource in ["nvidia.com/nvidia_sriov", "example.com/VF.pool-1"] { + with(&|network| network.sandbox.network.resource = Some(resource.to_string())).unwrap(); + } + for (network, message) in [ + ( + serde_json::json!({"network_attachment": "Bad/Name"}), + "network_attachment", + ), + ( + serde_json::json!({"network_attachment": ""}), + "network_attachment", + ), + ( + serde_json::json!({"network_attachment": "net", "resource": "vf"}), + "extended resource", + ), + ( + serde_json::json!({"network_attachment": "net", "resource": "example.com/_vf"}), + "extended resource", + ), + ( + serde_json::json!({"network_attachment": "net", "resource": "nvidia.com/gpu"}), + "nvidia.com/gpu", + ), + ( + serde_json::json!({"network_attachment": "net", "resource": "kubernetes.io/vf"}), + "kubernetes.io", + ), + ( + serde_json::json!({"network_attachment": "net", "resource": "dev.kubernetes.io/vf"}), + "kubernetes.io", + ), + ] { + let network: PodNetwork = serde_json::from_value(network).unwrap(); + let error = with(&|enforcer| enforcer.sandbox.network = network.clone()).unwrap_err(); + assert!( + error.contains("external_enforcer.network.sandbox"), + "{error}" + ); + assert!(error.contains(message), "{error}"); + let error = with(&|enforcer| enforcer.supervisor = Some(network.clone())).unwrap_err(); + assert!( + error.contains("external_enforcer.network.supervisor"), + "{error}" + ); + assert!(error.contains(message), "{error}"); + } + + let error = with(&|network| network.sandbox.nameservers.clear()).unwrap_err(); + assert!(error.contains("must not be empty"), "{error}"); + let error = with(&|network| { + network.sandbox.nameservers = ["10.0.0.1", "10.0.0.2", "10.0.0.3", "10.0.0.4"] + .map(|address| address.parse().unwrap()) + .to_vec(); + }) + .unwrap_err(); + assert!(error.contains("at most 3"), "{error}"); + let error = with(&|network| { + network.sandbox.nameservers = ["10.0.0.1", "10.0.0.1"] + .map(|address| address.parse().unwrap()) + .to_vec(); + }) + .unwrap_err(); + assert!(error.contains("more than once"), "{error}"); + + for entry in ["k8s.v1.cni.cncf.io/networks", "v1.multus-cni.io/*"] { + let error = external_enforcer_config(&format!("allowed_pod_annotations = [{entry:?}]")) + .validate_configuration() + .unwrap_err(); + assert!(error.contains(entry), "{error}"); + } + external_enforcer_config(r#"allowed_pod_annotations = ["sub.k8s.v1.cni.cncf.io/*"]"#) + .validate_configuration() + .unwrap(); + } + + #[test] + fn external_enforcer_rejects_unknown_keys() { + let base = toml::Value::try_from(external_enforcer_config("")).unwrap(); + for path in [ + &["external_enforcer"][..], + &["external_enforcer", "network"], + &["external_enforcer", "network", "sandbox"], + &["external_enforcer", "network", "supervisor"], + ] { + let mut value = base.clone(); + let mut table = &mut value; + for segment in path { + table = &mut table[*segment]; + } + table + .as_table_mut() + .unwrap() + .insert("extra".to_string(), true.into()); + assert!( + value.try_into::().is_err(), + "{path:?}.extra" + ); + } + } + fn with_allowed_pod_annotations(entries: &[&str]) -> KubernetesComputeConfig { KubernetesComputeConfig { allowed_pod_annotations: entries.iter().map(ToString::to_string).collect(), diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index fab746d814..9b512efd68 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -6,8 +6,8 @@ use crate::config::{ DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, DEFAULT_SANDBOX_UID, DEFAULT_WORKSPACE_STORAGE_SIZE, KubernetesComputeConfig, KubernetesControlConnection, OperatorNamespaceAllowlist, - WorkspaceMode, is_dns_1123_label, managed_namespace, managed_namespace_prefix, - validate_managed_namespace_name, + SupervisorTopology, WorkspaceMode, is_dns_1123_label, managed_namespace, + managed_namespace_prefix, validate_managed_namespace_name, }; use crate::isolation::{ BOUNDARY_PAIR_LABEL, BOUNDARY_ROLE_LABEL, KubernetesControlPath, @@ -23,8 +23,9 @@ use crate::sandbox_runtime::{ shared_instance_secret, supervisor_bootstrap_secret, supervisor_pod, workload_fence, }; use crate::shared_supervisor::{ - ANNOTATION_SUPERVISOR_SESSION, ANNOTATION_SUPERVISOR_TOPOLOGY, GATEWAY_TOPOLOGY, - SharedSupervisor, SupervisorPlacement, supervisor_placement, + ANNOTATION_SANDBOX_RUNTIME_NODE, ANNOTATION_SUPERVISOR_MEMBER, ANNOTATION_SUPERVISOR_SESSION, + ANNOTATION_SUPERVISOR_TOPOLOGY, GATEWAY_TOPOLOGY, SharedSupervisor, SupervisorPlacement, + supervisor_placement, }; use futures::{Stream, StreamExt, TryStreamExt}; use k8s_openapi::api::authentication::v1::{ @@ -76,7 +77,7 @@ use openshell_sandbox_backend::boundary_protocol::{ generate_sandbox_tls_material, }; use openshell_supervisor_control::{ - InstanceSupervision, LaunchError, RecoverableInstance, RecoveryBaseline, + HostAccount, HostRole, InstanceSupervision, LaunchError, RecoverableInstance, RecoveryBaseline, RegistrationTraceContext, SandboxInstanceRegistration, SharedSupervision, }; use serde::Deserialize; @@ -108,8 +109,15 @@ const ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: &str = const ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_SESSION: &str = "openshell.ai/sandbox-runtime-bootstrap-session"; const ANNOTATION_SANDBOX_RUNTIME_GENERATION: &str = "openshell.ai/sandbox-runtime-generation"; +/// Set to `true` on a Sandbox created in native-network mode. +const ANNOTATION_NATIVE_NETWORK: &str = "openshell.ai/native-network"; const ANNOTATION_SANDBOX_RUNTIME_READINESS: &str = "openshell.ai/sandbox-runtime-readiness"; const ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: &str = "openshell.ai/sandbox-runtime-workload-uid"; +/// The gateway's runtime generation of the workload named by +/// `ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID`, written in the same patch. It +/// differs from `ANNOTATION_SANDBOX_RUNTIME_GENERATION`, the driver's own token. +const ANNOTATION_SANDBOX_RUNTIME_GATEWAY_GENERATION: &str = + "openshell.ai/sandbox-runtime-gateway-generation"; const ANNOTATION_SANDBOX_RUNTIME_SUPERVISOR_UID: &str = "openshell.ai/sandbox-runtime-supervisor-uid"; const ANNOTATION_SANDBOX_RUNTIME_MAIN_PROCESS_SPEC: &str = @@ -137,9 +145,10 @@ const ANNOTATION_ADDITIONAL_CA_GENERATION: &str = "openshell.ai/additional-ca-ge const ADDITIONAL_CA_CONFIG_MAP_PREFIX: &str = "openshell-additional-ca-"; const ADDITIONAL_CA_DATA_KEY: &str = "ca.crt"; -/// A validated immutable `ConfigMap` generation selected for a supervisor Pod. -/// This contains only an object name and non-secret digest; PEM bytes remain in -/// the API object and are never copied into a workload template or Secret. +/// A validated immutable `ConfigMap` generation selected for a dedicated +/// supervisor Pod. This contains only an object name and non-secret digest; +/// PEM bytes remain in the API object and are never copied into a workload +/// template. Shared generations carry the public PEM in their launch material. #[derive(Clone, Debug, PartialEq, Eq)] struct NetworkAdditionalCaConfigMap { name: String, @@ -438,6 +447,37 @@ impl GenerationLaunchTarget { } } +/// A generation ready to launch once its node is known. +struct PreparedGeneration { + namespace: String, + cr_name: String, + sandbox_api: AgentSandboxApi, + sandbox_id: String, + cr_uid: String, + names: SandboxRuntimeNames, + launch_authentication: openshell_core::jwt::SandboxLaunchAuthentication, + staged: StagedBootstrapMaterial, + boundary: GenerationBoundary, + proxy_ca: crate::sandbox_runtime::ProxyCaMaterial, + target: GenerationLaunchTarget, + admission_object: DynamicObject, + workload_pod_uid: String, + workload_pod_name: String, +} + +/// A generation's workload boundary: provisioned into its bootstrap Secret, +/// or waiting for the node whose supervisor address it names. +enum GenerationBoundary { + Installed(Box), + Pending(Box), +} + +struct PendingBoundary { + spec: KubernetesSandboxRuntimeBoundarySpec, + certificate_chain_pem: Vec, + private_key_pem: Vec, +} + /// Where workload runtimes reach the gateway's shared supervisor. struct SharedSupervisorTarget { namespace: String, @@ -682,6 +722,7 @@ const POD_UID_EXTRA: &str = "authentication.kubernetes.io/pod-uid"; const GPU_RESOURCE_NAME: &str = "nvidia.com/gpu"; const SPIFFE_WORKLOAD_API_VOLUME_NAME: &str = "spiffe-workload-api"; +#[derive(Clone)] struct AgentSandboxApi { api: Api, resource: ApiResource, @@ -1165,6 +1206,8 @@ impl KubernetesComputeDriver { config: KubernetesComputeConfig, shutdown_rx: tokio::sync::watch::Receiver, supervision: SharedSupervision, + network_trust_bundle: Option, + supervisor_otlp_tls_bytes: usize, ) -> Result { if config.shared_supervisor.is_none() { return Err(KubernetesDriverError::Precondition( @@ -1172,10 +1215,11 @@ impl KubernetesComputeDriver { .to_string(), )); } - // The gateway refuses the additional destination CA under the shared - // supervisor topology fail-closed, so no trust bundle reaches this - // constructor. - Self::build(config, shutdown_rx, Some(supervision), None).await + validate_shared_network_trust_bundle( + network_trust_bundle.as_ref(), + supervisor_otlp_tls_bytes, + )?; + Self::build(config, shutdown_rx, Some(supervision), network_trust_bundle).await } async fn build( @@ -1266,7 +1310,38 @@ impl KubernetesComputeDriver { .zip(supervision) .map(|(config, supervision)| SharedSupervisor::new(config, supervision)); if let Some(shared) = &shared_supervisor { - shared.spawn_token_secret_writer(client.clone(), shutdown_rx.clone()); + let node_topology = config.supervisor_topology == Some(SupervisorTopology::Node); + let controller = shared.supervision().controller(); + let account = |service_account: &String, identity_required| HostAccount { + namespace: shared.config().service_namespace.clone(), + service_account: service_account.clone(), + identity_required, + }; + controller.require_host_identity( + HostRole::Supervisor, + account( + &shared.config().service_account_name, + shared.config().require_identity_token || node_topology, + ), + ); + if node_topology { + controller.bind_members_to_nodes(); + } + if let Some(enforcer) = config.external_enforcer() { + controller.require_host_identity( + HostRole::Enforcer, + HostAccount { + namespace: enforcer.namespace.clone(), + service_account: enforcer.service_account_name.clone(), + identity_required: true, + }, + ); + } + shared.spawn_token_secret_writer( + client.clone(), + shutdown_rx.clone(), + config.external_enforcer(), + ); } if shared_supervisor.is_some() && !config.supervisor_otlp.is_empty() { warn!( @@ -2153,6 +2228,12 @@ impl KubernetesComputeDriver { default_image: &self.config.default_image, image_pull_secrets: &self.config.image_pull_secrets, default_runtime_class_name: &self.config.default_runtime_class_name, + sandbox_network: self + .config + .external_enforcer() + .map(|enforcer| &enforcer.network.sandbox.network), + native_network: self.config.external_enforcer().is_some(), + nameservers: self.config.sandbox_nameservers(), service_account_name: &self.config.service_account_name, ..Default::default() }; @@ -2165,6 +2246,7 @@ impl KubernetesComputeDriver { &namespace, &rendered["spec"]["podTemplate"]["spec"], params.sandbox_secret_name, + self.config.sandbox_network_resource(), ) .await } @@ -2172,6 +2254,8 @@ impl KubernetesComputeDriver { async fn admit_stored_resources(&self, object: &DynamicObject) -> Result<(), tonic::Status> { validate_stored_kubernetes_pvc_mounts(&object.data["spec"]["podTemplate"]["spec"]) .map_err(tonic::Status::failed_precondition)?; + check_native_network_mode(object, self.config.external_enforcer().is_some()) + .map_err(tonic::Status::failed_precondition)?; if self.config.allow_driver_config && !self.config.resource_admission.enabled { return Ok(()); } @@ -2209,6 +2293,7 @@ impl KubernetesComputeDriver { namespace, spec, private_secret, + self.config.sandbox_network_resource(), ) .await?; if actual != expected { @@ -2268,7 +2353,7 @@ impl KubernetesComputeDriver { let Some(owner) = view .owners .get(route) - .filter(|_| view.desired.contains(route)) + .filter(|_| view.desired.contains_key(route)) else { return Ok(None); }; @@ -2652,6 +2737,12 @@ impl KubernetesComputeDriver { workspace_default_storage_size: &self.config.workspace_default_storage_size, workspace_storage_class: &self.config.workspace_storage_class, default_runtime_class_name: &self.config.default_runtime_class_name, + sandbox_network: self + .config + .external_enforcer() + .map(|enforcer| &enforcer.network.sandbox.network), + native_network: self.config.external_enforcer().is_some(), + nameservers: self.config.sandbox_nameservers(), sandbox_uid: resolved_user_id, sandbox_gid: resolved_group_id, boundary_port: self.config.sandbox_runtime.boundary_port, @@ -2687,6 +2778,9 @@ impl KubernetesComputeDriver { .is_some_and(|config| !config.fields.is_empty()) .to_string(), ); + if self.config.external_enforcer().is_some() { + annotations.insert(ANNOTATION_NATIVE_NETWORK.to_string(), "true".to_string()); + } add_trace_context_annotation(&mut annotations); annotations.insert( ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAPPING.to_string(), @@ -3112,6 +3206,7 @@ impl KubernetesComputeDriver { uid: u32, gid: u32, sandbox_secret_name: &str, + nameservers: &[std::net::IpAddr], ) -> Result<(), KubernetesDriverError> { let fail = |message: &str| { KubernetesDriverError::Precondition(format!( @@ -3170,10 +3265,9 @@ impl KubernetesComputeDriver { } if spec.restart_policy.as_deref() != Some("Never") || spec.dns_policy.as_deref() != Some("None") - || spec - .dns_config - .as_ref() - .is_none_or(|dns| dns.nameservers.as_deref() != Some(&["127.0.0.53".to_string()])) + || spec.dns_config.as_ref().is_none_or(|dns| { + dns.nameservers.as_deref() != Some(workload_resolvers(nameservers).as_slice()) + }) { return Err(fail("restart or DNS posture changed")); } @@ -3647,6 +3741,77 @@ impl KubernetesComputeDriver { )) } + /// Provision the workload boundary and write it to the bootstrap Secret + /// the workload Pod mounts. + async fn install_bootstrap_boundary( + &self, + namespace: &str, + names: &SandboxRuntimeNames, + sandbox_id: &str, + pending: PendingBoundary, + owner: OwnerReference, + ) -> Result< + openshell_sandbox_backend::boundary_protocol::SandboxRuntimeDescriptor, + KubernetesDriverError, + > { + let provisioned = pending + .spec + .provision() + .map_err(|error| KubernetesDriverError::Message(error.to_string()))?; + let sandbox_secret = sandbox_bootstrap_secret( + namespace, + names, + sandbox_id, + provisioned + .boundary_config + .encode() + .map_err(|error| KubernetesDriverError::Message(error.to_string()))?, + pending.certificate_chain_pem, + pending.private_key_pem, + owner, + ); + Api::::namespaced(self.client.clone(), namespace) + .create(&PostParams::default(), &sandbox_secret) + .await + .map_err(KubernetesDriverError::from_kube)?; + Ok(provisioned.runtime_descriptor) + } + + /// The address of `node`'s Ready supervisor on `network`, from the Multus + /// `network-status` of the Pods the shared supervisor Service selects. + async fn node_supervisor_network_address( + &self, + target: &SharedSupervisorTarget, + network: &crate::PodNetwork, + node: &str, + ) -> Result { + let pods = Api::::namespaced(self.client.clone(), &target.namespace); + let selector = target + .selector + .iter() + .map(|(key, value)| format!("{key}={value}")) + .collect::>() + .join(","); + let list = tokio::time::timeout( + KUBE_API_TIMEOUT, + pods.list( + &ListParams::default() + .labels(&selector) + .fields(&format!("spec.nodeName={node}")), + ), + ) + .await + .map_err(|_| { + KubernetesDriverError::Message("timed out listing the node supervisor Pods".to_string()) + })? + .map_err(KubernetesDriverError::from_kube)?; + supervisor_network_address( + &list.items, + &qualified_network_attachment(&network.network_attachment, &target.namespace), + node, + ) + } + /// Create or validate this sandbox's egress allowance to the shared /// supervisor and return the stored coordinates bound into its evidence. async fn ensure_sandbox_runtime_shared_control_policy( @@ -3841,6 +4006,7 @@ impl KubernetesComputeDriver { agent_uid, agent_gid, &names.sandbox_secret, + self.config.sandbox_nameservers(), )?; let workload_pod_uid = workload_pod.metadata.uid.clone().ok_or_else(|| { @@ -3851,6 +4017,8 @@ impl KubernetesComputeDriver { })?; let mut annotations = serde_json::json!({ ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: workload_pod_uid.clone(), + ANNOTATION_SANDBOX_RUNTIME_GATEWAY_GENERATION: + launch_authentication.supervisor.runtime_generation.to_string(), ANNOTATION_SANDBOX_RUNTIME_NETWORK_POLICY_UID: fence_uid.clone(), ANNOTATION_SANDBOX_RUNTIME_NETWORK_POLICY_GENERATION: fence_generation.to_string(), }); @@ -3914,7 +4082,7 @@ impl KubernetesComputeDriver { }, ), }; - let provisioned = KubernetesSandboxRuntimeBoundarySpec { + let spec = KubernetesSandboxRuntimeBoundarySpec { boundary_id: sandbox_id.to_string(), generation: launch_authentication .supervisor @@ -3930,8 +4098,8 @@ impl KubernetesComputeDriver { workload_pod_uid: workload_pod_uid.clone(), workload_pod_uid_path: PathBuf::from(SANDBOX_POD_UID_PATH), supervisor: supervisor_claim, - egress_policy_uid: fence_uid.clone(), - egress_policy_resource_version: fence_resource_version.clone(), + egress_policy_uid: fence_uid, + egress_policy_resource_version: fence_resource_version, control_path, sandbox_tls: SandboxTlsServerConfig { certificate_chain_path: PathBuf::from(BOUNDARY_CERTIFICATE_PATH), @@ -3944,32 +4112,272 @@ impl KubernetesComputeDriver { host_gateway_ip: self.config.host_gateway_ip.parse().ok(), workload_identity, child_env, - } - .provision() - .map_err(|error| KubernetesDriverError::Message(error.to_string()))?; + native_network: self.config.external_enforcer().is_some(), + }; let workload_owner = runtime_pod_owner(&workload_pod_name, &workload_pod_uid); - let instance_owner = workload_owner.clone(); - let sandbox_secret = sandbox_bootstrap_secret( + let pending = PendingBoundary { + spec, + certificate_chain_pem: tls.certificate_chain_pem.into_bytes(), + private_key_pem: tls.private_key_pem.into_bytes(), + }; + // In the node topology on a supervisor network, the runtime dials its + // own node's supervisor address, known only once the Pod is scheduled. + let dials_node_supervisor = self.config.supervisor_topology + == Some(SupervisorTopology::Node) + && self + .config + .external_enforcer() + .is_some_and(|enforcer| enforcer.network.supervisor.is_some()); + let boundary = + if matches!(target, GenerationLaunchTarget::Shared { .. }) && dials_node_supervisor { + GenerationBoundary::Pending(Box::new(pending)) + } else { + GenerationBoundary::Installed(Box::new( + self.install_bootstrap_boundary( + namespace, + names, + sandbox_id, + pending, + workload_owner.clone(), + ) + .await?, + )) + }; + if matches!(target, GenerationLaunchTarget::Shared { .. }) { + self.create_generation_image_pull_secrets( + namespace, + names, + sandbox_id, + vec![workload_owner], + ) + .await?; + } + + let generation = PreparedGeneration { + namespace: namespace.to_string(), + cr_name: cr_name.to_string(), + sandbox_api: sandbox_api.clone(), + sandbox_id: sandbox_id.to_string(), + cr_uid: cr_uid.to_string(), + names: names.clone(), + launch_authentication: launch_authentication.clone(), + staged, + boundary, + proxy_ca, + target, + admission_object, + workload_pod_uid, + workload_pod_name, + }; + // A node supervisor serves only its own node, and enforcer shards + // select native-network instances by node, so the scheduler picks the + // node first. Until the launch places the route, the runtime's dials + // are refused and the workload doesn't start. + if let GenerationLaunchTarget::Shared { route, .. } = &generation.target + && (self.config.supervisor_topology == Some(SupervisorTopology::Node) + || self.config.external_enforcer().is_some()) + { + let placement = SupervisorPlacement::Shared { + route: route.clone(), + }; + remove_scheduling_gates(&pods, &generation.workload_pod_name).await?; + tokio::spawn(Box::pin( + self.clone().launch_on_scheduled_node(generation, placement), + )); + return Ok(()); + } + Box::pin(self.launch_sandbox_runtime_generation(generation, None)).await + } + + /// Finish a launch that needs its node once the scheduler binds the + /// workload Pod. A failed launch rolls the bootstrap back as a stale one + /// would be. + async fn launch_on_scheduled_node( + self, + generation: PreparedGeneration, + placement: SupervisorPlacement, + ) { + let bootstrap_grace = Duration::from_secs(self.config.runtime_bootstrap_grace_seconds); + let deadline = tokio::time::Instant::now() + bootstrap_grace; + let sandbox_api = generation.sandbox_api.clone(); + let cr_name = generation.cr_name.clone(); + let cr_uid = generation.cr_uid.clone(); + let workload_pod_uid = generation.workload_pod_uid.clone(); + let pods = Api::::namespaced(self.client.clone(), &generation.namespace); + let scheduled_or_replaced = + |pod: Option<&Pod>| workload_pod_scheduled_or_replaced(pod, &workload_pod_uid); + let pod = loop { + match tokio::time::timeout_at( + deadline, + await_condition( + pods.clone(), + &generation.workload_pod_name, + scheduled_or_replaced, + ), + ) + .await + { + Ok(Ok(pod)) => break pod, + Err(_) => { + warn!( + sandbox = cr_name, + "the workload Pod was not scheduled within the bootstrap grace; the stale bootstrap will be rolled back" + ); + return; + } + Ok(Err(error)) => { + debug!(%error, sandbox = cr_name, "workload Pod scheduling watch failed; retrying"); + tokio::time::sleep_until( + deadline.min(tokio::time::Instant::now() + Duration::from_secs(1)), + ) + .await; + } + } + }; + // A deleted or replaced Pod leaves its bootstrap to the reaper. + let Some(node) = pod + .filter(|pod| pod.metadata.uid.as_deref() == Some(workload_pod_uid.as_str())) + .and_then(|pod| pod.spec?.node_name) + else { + return; + }; + let _guard = self + .lifecycle_gates + .gate_for(&generation.sandbox_id) + .lock_owned() + .await; + // A stop, delete, reaper, or newer attempt may have run while the + // Pod waited for a node, and the reaper rolls back a stale bootstrap. + let read_awaiting = || async { + tokio::time::timeout(KUBE_API_TIMEOUT, sandbox_api.api.get_opt(&cr_name)) + .await + .ok() + .and_then(Result::ok) + .flatten() + .filter(|object| { + sandbox_runtime_awaits_launch(object, &cr_uid, &workload_pod_uid) + && !sandbox_runtime_bootstrap_is_stale( + object, + SystemTime::now(), + bootstrap_grace, + ) + }) + }; + if read_awaiting().await.is_none() { + return; + } + let launch = Box::pin(self.launch_sandbox_runtime_generation(generation, Some(node))).await; + if let Err(error) = launch { + warn!(sandbox = cr_name, %error, "sandbox-runtime launch on the scheduled node failed; rolling back"); + self.remove_shared_instance(&placement); + if let Some(object) = read_awaiting().await { + self.roll_back_sandbox_runtime_bootstrap(&sandbox_api, &object) + .await; + } + } + } + + /// Install the parts of a generation that depend on its node: the + /// supervisor launch and the workload's release. `node` is the scheduled + /// node when the launch waited for it; in the node topology it is also + /// the pool member the instance is pinned to. + async fn launch_sandbox_runtime_generation( + &self, + generation: PreparedGeneration, + node: Option, + ) -> Result<(), KubernetesDriverError> { + let node_member = node + .clone() + .filter(|_| self.config.supervisor_topology == Some(SupervisorTopology::Node)); + let PreparedGeneration { namespace, - names, + cr_name, + sandbox_api, sandbox_id, - provisioned - .boundary_config - .encode() - .map_err(|error| KubernetesDriverError::Message(error.to_string()))?, - tls.certificate_chain_pem.into_bytes(), - tls.private_key_pem.into_bytes(), - workload_owner.clone(), + cr_uid, + names, + launch_authentication, + staged, + boundary, + proxy_ca, + target, + admission_object, + workload_pod_uid, + workload_pod_name, + } = generation; + let (namespace, cr_name, sandbox_id, cr_uid, names) = ( + namespace.as_str(), + cr_name.as_str(), + sandbox_id.as_str(), + cr_uid.as_str(), + &names, ); + let launch_authentication = &launch_authentication; + let pods = Api::::namespaced(self.client.clone(), namespace); + if let Some(node) = &node { + let mut annotations = serde_json::json!({ANNOTATION_SANDBOX_RUNTIME_NODE: node}); + if let Some(member) = &node_member { + annotations[ANNOTATION_SUPERVISOR_MEMBER] = member.as_str().into(); + } + patch_dynamic_object_with_resource_version_retry( + &sandbox_api.api, + cr_name, + |version| { + serde_json::json!({ + "metadata": { + "resourceVersion": version, + "annotations": annotations, + } + }) + }, + ) + .await?; + } + + let workload_owner = runtime_pod_owner(&workload_pod_name, &workload_pod_uid); + let runtime_descriptor = match boundary { + GenerationBoundary::Installed(descriptor) => *descriptor, + GenerationBoundary::Pending(mut pending) => { + let (GenerationLaunchTarget::Shared { target, .. }, Some(node)) = + (&target, &node_member) + else { + return Err(KubernetesDriverError::Message( + "a pending sandbox boundary needs a scheduled node supervisor".to_string(), + )); + }; + let network = self + .config + .external_enforcer() + .and_then(|enforcer| enforcer.network.supervisor.as_ref()) + .ok_or_else(|| { + KubernetesDriverError::Message( + "a pending sandbox boundary needs external_enforcer.network.supervisor" + .to_string(), + ) + })?; + let address = self + .node_supervisor_network_address(target, network, node) + .await?; + if let KubernetesControlPath::RuntimeInitiatedShared { + supervisor_address, .. + } = &mut pending.spec.control_path + { + *supervisor_address = std::net::SocketAddr::new(address, target.address.port()); + } + self.install_bootstrap_boundary( + namespace, + names, + sandbox_id, + *pending, + workload_owner.clone(), + ) + .await? + } + }; let secrets = Api::::namespaced(self.client.clone(), namespace); - secrets - .create(&PostParams::default(), &sandbox_secret) - .await - .map_err(KubernetesDriverError::from_kube)?; match &target { GenerationLaunchTarget::Dedicated { pod_uid, .. } => { - let descriptor = provisioned - .runtime_descriptor + let descriptor = runtime_descriptor .backend_descriptor() .map_err(|error| KubernetesDriverError::Message(error.to_string()))?; let supervisor_owner = runtime_pod_owner(&names.supervisor_pod, pod_uid); @@ -4002,8 +4410,7 @@ impl KubernetesComputeDriver { .await?; // A restarted generation must revalidate immediately before // resuming the gated supervisor as well as before creating - // it. The shared topology never carries an additional CA: - // the gateway refuses that combination fail-closed. + // it. self.ensure_network_additional_ca_config_map(namespace) .await?; pods.patch( @@ -4015,20 +4422,14 @@ impl KubernetesComputeDriver { .map_err(KubernetesDriverError::from_kube)?; } GenerationLaunchTarget::Shared { shared, route, .. } => { - self.create_generation_image_pull_secrets( - namespace, - names, - sandbox_id, - vec![workload_owner], - ) - .await?; let registration = shared_instance_registration( &admission_object, route, sandbox_id, - provisioned.runtime_descriptor, + runtime_descriptor, launch_authentication, proxy_ca, + self.network_trust_bundle.as_ref(), )?; // The coordinator persists the launch material with the // generation before it assigns the instance, so a restarted @@ -4037,22 +4438,27 @@ impl KubernetesComputeDriver { // the host without waiting for the runtime. shared .supervision() - .launch(®istration, |launch_material| async { - secrets - .create( - &PostParams::default(), - &shared_instance_secret( - namespace, - names, - sandbox_id, - launch_material, - instance_owner, - ), - ) - .await - .map(|_| ()) - .map_err(KubernetesDriverError::from_kube) - }) + .launch( + ®istration, + node_member.as_deref(), + node.as_deref(), + |launch_material| async { + secrets + .create( + &PostParams::default(), + &shared_instance_secret( + namespace, + names, + sandbox_id, + launch_material, + workload_owner, + ), + ) + .await + .map(|_| ()) + .map_err(KubernetesDriverError::from_kube) + }, + ) .await .map_err(|error| match error { LaunchError::Persist(error) => error, @@ -4071,20 +4477,16 @@ impl KubernetesComputeDriver { })?; } } - pods.patch( - &workload_pod_name, - &PatchParams::default(), - &Patch::Merge(&serde_json::json!({"spec": {"schedulingGates": []}})), - ) - .await - .map_err(KubernetesDriverError::from_kube)?; + if node.is_none() { + remove_scheduling_gates(&pods, &workload_pod_name).await?; + } patch_dynamic_object_with_resource_version_retry(&sandbox_api.api, cr_name, |version| { sandbox_runtime_bootstrap_phase_patch(version, SandboxRuntimeBootstrapPhase::Released) }) .await?; let control = match target { GenerationLaunchTarget::Dedicated { .. } => BootstrapControl::SupervisorPod { - pods, + pods: Box::new(pods), name: names.supervisor_pod.clone(), }, GenerationLaunchTarget::Shared { shared, route, .. } => { @@ -4370,9 +4772,12 @@ impl KubernetesComputeDriver { // Validate the current gateway generation before touching a stopped // sandbox's stale companion. This detects equal-generation // delete/recreate tampering before a supervisor can be created or - // released, while running supervisors remain untouched. - self.ensure_network_additional_ca_config_map(&namespace) - .await?; + // released, while running supervisors remain untouched. Shared + // generations carry the bundle in their launch material instead. + if placement == SupervisorPlacement::Dedicated { + self.ensure_network_additional_ca_config_map(&namespace) + .await?; + } let mut stale_generations = sandbox_runtime_generation(&object).as_slice().to_vec(); stale_generations.push(generation.as_str()); self.delete_sandbox_runtime_supervisor(sandbox_id, &namespace, &stale_generations) @@ -4533,11 +4938,15 @@ impl KubernetesComputeDriver { ANNOTATION_SANDBOX_RUNTIME_CONTROL_GENERATION: generation.as_str(), ANNOTATION_SUPERVISOR_TOPOLOGY: topology, ANNOTATION_SUPERVISOR_SESSION: instance_route, + // The new generation records its own node once scheduled. + ANNOTATION_SUPERVISOR_MEMBER: serde_json::Value::Null, + ANNOTATION_SANDBOX_RUNTIME_NODE: serde_json::Value::Null, }); running_patch["spec"]["podTemplate"]["spec"] = restart_pod_template_spec( &volumes, &init_containers, &image_pull_secrets, + self.config.sandbox_nameservers(), ); running_patch }, @@ -5269,25 +5678,18 @@ impl KubernetesComputeDriver { let Some(shared) = &self.shared_supervisor else { return; }; + let node_topology = self.config.supervisor_topology == Some(SupervisorTopology::Node); + let needs_node = node_topology || self.config.external_enforcer().is_some(); let candidates = runnable_shared_generations(sandboxes) .into_iter() .filter_map(|(object, route)| { - let sandbox_id = sandbox_id_from_object(object).ok()?; - let generation = sandbox_runtime_generation(object)?.to_string(); - let namespace = object - .metadata - .namespace - .clone() - .unwrap_or_else(|| self.config.namespace.clone()); - Some(RecoverableInstance { + recoverable_instance( + object, route, - sandbox_id: sandbox_id.clone(), - record: SharedInstanceSecretRecord { - namespace, - sandbox_id, - generation, - }, - }) + node_topology, + needs_node, + &self.config.namespace, + ) }) .collect(); // Outcomes are logged by the coordinator; a conflict is derived again @@ -5536,6 +5938,16 @@ impl KubernetesComputeDriver { ) { return; } + self.roll_back_sandbox_runtime_bootstrap(lookup_api, object) + .await; + } + + /// Delete a failed create, or suspend a failed restart. + async fn roll_back_sandbox_runtime_bootstrap( + &self, + lookup_api: &AgentSandboxApi, + object: &DynamicObject, + ) { if sandbox_runtime_bootstrap_operation(object) != Some("create") { warn!( sandbox = object.metadata.name.as_deref().unwrap_or(""), @@ -5839,6 +6251,52 @@ fn placement_for_release(object: &DynamicObject, sandbox_id: &str) -> Supervisor }) } +/// The instance a shared generation recovers as, or `None` when its record is +/// incomplete: a node-topology generation needs its member, and with +/// `needs_node` every generation needs its node. +fn recoverable_instance( + object: &DynamicObject, + route: String, + node_topology: bool, + needs_node: bool, + default_namespace: &str, +) -> Option> { + let sandbox_id = sandbox_id_from_object(object).ok()?; + let generation = sandbox_runtime_generation(object)?.to_string(); + let namespace = object + .metadata + .namespace + .clone() + .unwrap_or_else(|| default_namespace.to_string()); + let annotation = |key: &str| { + object + .metadata + .annotations + .as_ref() + .and_then(|annotations| annotations.get(key)) + .filter(|value| !value.is_empty()) + .cloned() + }; + let member = annotation(ANNOTATION_SUPERVISOR_MEMBER); + let node = annotation(ANNOTATION_SANDBOX_RUNTIME_NODE).or_else(|| member.clone()); + // A node generation without its node could land on any node, and a + // native-network one would be in no enforcer's shard. + if (node_topology && member.is_none()) || (needs_node && node.is_none()) { + return None; + } + Some(RecoverableInstance { + route, + sandbox_id: sandbox_id.clone(), + member, + node, + record: SharedInstanceSecretRecord { + namespace, + sandbox_id, + generation, + }, + }) +} + /// Shared generations that may currently run, with their sandbox instance /// routes: the desired set of the shared supervisor. fn runnable_shared_generations(sandboxes: &[DynamicObject]) -> Vec<(&DynamicObject, String)> { @@ -5879,6 +6337,23 @@ struct SharedInstanceSecretRecord { generation: String, } +fn validate_shared_network_trust_bundle( + bundle: Option<&NetworkSupervisorTrustBundle>, + otlp_tls_bytes: usize, +) -> Result<(), KubernetesDriverError> { + let limit = openshell_supervisor_control::MAX_SHARED_TRUST_MATERIAL_BYTES; + let Some(bundle) = bundle else { + return Ok(()); + }; + let total = bundle.pem().len() + otlp_tls_bytes; + if total > limit { + return Err(KubernetesDriverError::Precondition(format!( + "the network supervisor additional destination CA and supervisor OTLP TLS files total {total} bytes, more than the {limit}-byte limit with a shared supervisor topology" + ))); + } + Ok(()) +} + /// Launch material of one shared-supervisor sandbox instance, taken from the /// generation's own Sandbox resource and gateway-issued credentials. The /// coordinator validates, encodes, persists, and assigns it. @@ -5889,7 +6364,17 @@ fn shared_instance_registration( runtime_descriptor: openshell_sandbox_backend::boundary_protocol::SandboxRuntimeDescriptor, launch_authentication: &openshell_core::jwt::SandboxLaunchAuthentication, proxy_ca: crate::sandbox_runtime::ProxyCaMaterial, + network_trust_bundle: Option<&NetworkSupervisorTrustBundle>, ) -> Result { + let additional_ca_bundle = network_trust_bundle + .map(|bundle| { + String::from_utf8(bundle.pem().to_vec()).map_err(|_| { + KubernetesDriverError::Precondition( + "the network supervisor additional destination CA is not UTF-8 PEM".to_string(), + ) + }) + }) + .transpose()?; Ok(SandboxInstanceRegistration { route: route.to_string(), sandbox_id: sandbox_id.to_string(), @@ -5922,6 +6407,7 @@ fn shared_instance_registration( certificate_pem: proxy_ca.certificate_pem, private_key_pem: openshell_supervisor_control::SecretPem::new(proxy_ca.private_key_pem), }, + additional_ca_bundle, trace_context: RegistrationTraceContext::current(), }) } @@ -5929,7 +6415,7 @@ fn shared_instance_registration( /// What bootstrap completion waits for before the runtime is declared ready. enum BootstrapControl { /// The generation's dedicated supervisor Pod becomes Ready. - SupervisorPod { pods: Api, name: String }, + SupervisorPod { pods: Box>, name: String }, /// The gateway accepts the generation's shared-supervisor sandbox instance. SharedInstance { shared: SharedSupervisor, @@ -5948,7 +6434,7 @@ impl BootstrapControl { == SandboxRuntimeControlAvailability::Available }) }; - match await_condition(pods, &name, available).await { + match await_condition(*pods, &name, available).await { Ok(Some(_)) => true, Ok(None) => false, Err(error) => { @@ -6406,16 +6892,19 @@ fn runtime_pod_owner(name: &str, uid: &str) -> OwnerReference { } /// Pod template fields replaced when a stopped sandbox starts a new runtime -/// generation. +/// generation. `dnsConfig` follows the current gateway config, which the +/// posture check holds the new Pod to. fn restart_pod_template_spec( volumes: &[serde_json::Value], init_containers: &[serde_json::Value], image_pull_secrets: &[String], + nameservers: &[std::net::IpAddr], ) -> serde_json::Value { serde_json::json!({ "volumes": volumes, "initContainers": init_containers, "imagePullSecrets": image_pull_secret_refs(image_pull_secrets), + "dnsConfig": workload_dns_config(nameservers), }) } @@ -7390,13 +7879,155 @@ const SANDBOX_PROXY_CA_VOLUME_NAME: &str = "openshell-run"; const SANDBOX_PROXY_CA_MOUNT_PATH: &str = "/run"; const SANDBOX_BOOTSTRAP_SCHEDULING_GATE: &str = "openshell.ai/bootstrap"; -fn sandbox_bootstrap_secret_name(spec: &serde_json::Value) -> Option<&str> { - spec["volumes"] - .as_array()? - .iter() - .find(|volume| volume["name"] == SANDBOX_BOOTSTRAP_VOLUME_NAME)?["secret"]["secretName"] - .as_str() - .filter(|name| !name.is_empty()) +async fn remove_scheduling_gates(pods: &Api, name: &str) -> Result<(), KubernetesDriverError> { + pods.patch( + name, + &PatchParams::default(), + &Patch::Merge(&serde_json::json!({"spec": {"schedulingGates": []}})), + ) + .await + .map(drop) + .map_err(KubernetesDriverError::from_kube) +} + +/// Refuse a Sandbox created under the other native-network mode: its stored +/// Pod template lacks, or still carries, the mode's network placement. +fn check_native_network_mode(object: &DynamicObject, native_network: bool) -> Result<(), String> { + let created_native = object + .metadata + .annotations + .as_ref() + .and_then(|annotations| annotations.get(ANNOTATION_NATIVE_NETWORK)) + .is_some_and(|value| value == "true"); + match (created_native, native_network) { + (true, false) => Err( + "the sandbox was created in native-network mode, which is now off; recreate it".into(), + ), + (false, true) => Err( + "the sandbox was created outside native-network mode, which is now on; recreate it" + .into(), + ), + _ => Ok(()), + } +} + +/// Whether workload Pod `uid` is bound to a node, or was deleted or replaced, +/// which the launch then reports. +fn workload_pod_scheduled_or_replaced(pod: Option<&Pod>, uid: &str) -> bool { + pod.is_none_or(|pod| { + pod.metadata.uid.as_deref() != Some(uid) + || pod + .spec + .as_ref() + .and_then(|spec| spec.node_name.as_deref()) + .is_some_and(|node| !node.is_empty()) + }) +} + +/// Whether `object` is still the bootstrap attempt that prepared workload Pod +/// `workload_pod_uid`, waiting for its node-dependent launch. +fn sandbox_runtime_awaits_launch( + object: &DynamicObject, + cr_uid: &str, + workload_pod_uid: &str, +) -> bool { + object.metadata.uid.as_deref() == Some(cr_uid) + && sandbox_runtime_bootstrap_phase(object) == Some(SandboxRuntimeBootstrapPhase::Preparing) + && object + .metadata + .annotations + .as_ref() + .and_then(|annotations| annotations.get(ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID)) + .map(String::as_str) + == Some(workload_pod_uid) +} + +/// Multus names a network by `namespace/name`, resolving a bare name in the +/// Pod's namespace. +fn qualified_network_attachment(attachment: &str, namespace: &str) -> String { + if attachment.contains('/') { + attachment.to_string() + } else { + format!("{namespace}/{attachment}") + } +} + +/// The IPv4 address the Ready supervisor `pods` on `node` have on +/// `attachment`. Every Ready Pod must report exactly one, and all the same. +fn supervisor_network_address( + pods: &[Pod], + attachment: &str, + node: &str, +) -> Result { + let mut address = None; + for pod in pods.iter().filter(|pod| { + matches!( + sandbox_runtime_control_availability_from_pod(pod), + SandboxRuntimeControlAvailability::Available + ) + }) { + let found = pod + .metadata + .annotations + .as_ref() + .and_then(|annotations| annotations.get(MULTUS_NETWORK_STATUS_ANNOTATION)) + .and_then(|status| network_status_ipv4(status, attachment)) + .ok_or_else(|| { + KubernetesDriverError::Precondition(format!( + "the supervisor on node {node} has no single IPv4 address on network {attachment}" + )) + })?; + if address.is_some_and(|address| address != found) { + return Err(KubernetesDriverError::Precondition(format!( + "the supervisors on node {node} report different addresses on network {attachment}" + ))); + } + address = Some(found); + } + address.map(std::net::IpAddr::V4).ok_or_else(|| { + KubernetesDriverError::Precondition(format!("no Ready supervisor runs on node {node}")) + }) +} + +/// The only routable IPv4 address of the `network-status` entry named +/// `attachment`, ignoring link-local ones as the supervisor does. Multus may +/// report an address with or without its prefix length. +fn network_status_ipv4(status: &str, attachment: &str) -> Option { + let entries: Vec = serde_json::from_str(status).ok()?; + let mut matching = entries + .iter() + .filter(|entry| entry["name"].as_str() == Some(attachment)); + let entry = matching.next()?; + if matching.next().is_some() { + return None; + } + let mut addresses = entry["ips"].as_array()?.iter().filter_map(|ip| { + let ip = ip.as_str()?; + ip.split_once('/') + .map_or(ip, |(address, _)| address) + .parse::() + .ok() + .filter(|address| { + !(address.is_link_local() + || address.is_loopback() + || address.is_unspecified() + || address.is_multicast() + || address.is_broadcast()) + }) + }); + match (addresses.next(), addresses.next()) { + (Some(address), None) => Some(address), + _ => None, + } +} + +fn sandbox_bootstrap_secret_name(spec: &serde_json::Value) -> Option<&str> { + spec["volumes"] + .as_array()? + .iter() + .find(|volume| volume["name"] == SANDBOX_BOOTSTRAP_VOLUME_NAME)?["secret"]["secretName"] + .as_str() + .filter(|name| !name.is_empty()) } /// Render the trusted init container that stages the sandbox runtime binary. @@ -7430,6 +8061,30 @@ fn sandbox_bootstrap_init_container( bootstrap } +/// The supervisor's policy DNS, which the workload reaches over loopback. +const POLICY_DNS_RESOLVER: &str = "127.0.0.53"; + +/// The workload Pod's resolvers: `nameservers`, or the supervisor's policy +/// DNS when empty. +fn workload_resolvers(nameservers: &[std::net::IpAddr]) -> Vec { + if nameservers.is_empty() { + vec![POLICY_DNS_RESOLVER.to_string()] + } else { + nameservers.iter().map(ToString::to_string).collect() + } +} + +fn workload_dns_config(nameservers: &[std::net::IpAddr]) -> serde_json::Value { + serde_json::json!({ + "nameservers": workload_resolvers(nameservers), + "options": [ + {"name": "ndots", "value": "5"}, + {"name": "timeout", "value": "2"}, + {"name": "attempts", "value": "2"} + ] + }) +} + /// Render the workload Pod that runs the `OpenShell` sandbox runtime. /// /// The pod receives no gateway credential or endpoint. Its non-root sandbox @@ -7482,14 +8137,7 @@ fn apply_supervisor_sandbox_runtime_boundary( ); spec.insert( "dnsConfig".to_string(), - serde_json::json!({ - "nameservers": ["127.0.0.53"], - "options": [ - {"name": "ndots", "value": "5"}, - {"name": "timeout", "value": "2"}, - {"name": "attempts", "value": "2"} - ] - }), + workload_dns_config(params.nameservers), ); spec.insert( "securityContext".to_string(), @@ -7827,6 +8475,14 @@ struct SandboxPodParams<'a> { workspace_default_storage_size: &'a str, workspace_storage_class: &'a str, default_runtime_class_name: &'a str, + /// The external enforcer's sandbox network; overrides the caller's + /// annotation and resource. + sandbox_network: Option<&'a crate::PodNetwork>, + /// Schedules the Pod only to nodes where the external enforcer is ready, + /// overriding the caller's value for that label. + native_network: bool, + /// Workload resolvers. Empty uses the supervisor's policy DNS. + nameservers: &'a [std::net::IpAddr], /// Resolved sandbox UID for supervisor `runAsUser` and env var. sandbox_uid: u32, /// Resolved sandbox GID for PVC init container operations. @@ -7837,6 +8493,10 @@ struct SandboxPodParams<'a> { sandbox_secret_name: &'a str, } +/// Multus replaces the Pod's cluster network with this attachment. +const MULTUS_DEFAULT_NETWORK_ANNOTATION: &str = "v1.multus-cni.io/default-network"; +const MULTUS_NETWORK_STATUS_ANNOTATION: &str = "k8s.v1.cni.cncf.io/network-status"; + impl Default for SandboxPodParams<'_> { fn default() -> Self { Self { @@ -7851,6 +8511,9 @@ impl Default for SandboxPodParams<'_> { workspace_default_storage_size: DEFAULT_WORKSPACE_STORAGE_SIZE, workspace_storage_class: "", default_runtime_class_name: "", + sandbox_network: None, + native_network: false, + nameservers: &[], sandbox_uid: DEFAULT_SANDBOX_UID, sandbox_gid: DEFAULT_SANDBOX_UID, boundary_port: 5500, @@ -8030,6 +8693,12 @@ fn sandbox_template_to_k8s_with_validated_config( serde_json::Value::String(params.sandbox_id.to_string()), ); } + if let Some(network) = params.sandbox_network { + pod_annotations.insert( + MULTUS_DEFAULT_NETWORK_ANNOTATION.to_string(), + serde_json::json!(network.network_attachment), + ); + } if !pod_annotations.is_empty() { metadata.insert( "annotations".to_string(), @@ -8060,6 +8729,15 @@ fn sandbox_template_to_k8s_with_validated_config( spec.insert("tolerations".to_string(), tolerations); } apply_pod_driver_config(&mut spec, &driver_config.pod); + if params.native_network { + use crate::config::EXTERNAL_ENFORCER_READY_NODE_LABEL as READY_NODE_LABEL; + let node_selector = spec + .entry("nodeSelector".to_string()) + .or_insert_with(|| serde_json::json!({})); + if let Some(node_selector) = node_selector.as_object_mut() { + node_selector.insert(READY_NODE_LABEL.to_string(), serde_json::json!("true")); + } + } // Per-sandbox portable intent overrides the cluster-wide default. This // driver owns the Kubernetes-specific `hostUsers` translation. @@ -8140,6 +8818,17 @@ fn sandbox_template_to_k8s_with_validated_config( container.insert("resources".to_string(), resources); } apply_agent_driver_resources(&mut container, &driver_config.containers.agent.resources); + if let Some(resource) = params.sandbox_network.and_then(|n| n.resource.as_deref()) { + let resources = container + .entry("resources".to_string()) + .or_insert_with(|| serde_json::json!({})); + for section in ["requests", "limits"] { + if !resources[section].is_object() { + resources[section] = serde_json::json!({}); + } + resources[section][resource] = serde_json::json!("1"); + } + } spec.insert( "containers".to_string(), serde_json::Value::Array(vec![serde_json::Value::Object(container)]), @@ -8853,9 +9542,12 @@ fn sandbox_runtime_suspension_completion_patch(resource_version: &str) -> serde_ ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_SESSION: serde_json::Value::Null, ANNOTATION_SANDBOX_RUNTIME_GENERATION: serde_json::Value::Null, ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: serde_json::Value::Null, + ANNOTATION_SANDBOX_RUNTIME_GATEWAY_GENERATION: serde_json::Value::Null, ANNOTATION_SANDBOX_RUNTIME_SUPERVISOR_UID: serde_json::Value::Null, ANNOTATION_SUPERVISOR_TOPOLOGY: serde_json::Value::Null, ANNOTATION_SUPERVISOR_SESSION: serde_json::Value::Null, + ANNOTATION_SUPERVISOR_MEMBER: serde_json::Value::Null, + ANNOTATION_SANDBOX_RUNTIME_NODE: serde_json::Value::Null, ANNOTATION_SANDBOX_RUNTIME_NETWORK_POLICY_UID: serde_json::Value::Null, ANNOTATION_SANDBOX_RUNTIME_NETWORK_POLICY_GENERATION: serde_json::Value::Null, ANNOTATION_SANDBOX_RUNTIME_READINESS: "unavailable", @@ -9333,6 +10025,97 @@ mod tests { ); } + fn external_enforcer_config(resource: Option<&str>) -> KubernetesComputeConfig { + KubernetesComputeConfig { + external_enforcer: Some(crate::ExternalEnforcerConfig { + namespace: "openshell-enforcer".to_string(), + token_secret_name: "enforcer-token".to_string(), + service_account_name: "enforcer".to_string(), + network: crate::ExternalEnforcerNetwork { + sandbox: crate::SandboxNetwork { + network: crate::PodNetwork { + network_attachment: "net".to_string(), + resource: resource.map(str::to_string), + }, + nameservers: vec![std::net::IpAddr::from([192, 168, 100, 1])], + }, + supervisor: None, + }, + }), + ..KubernetesComputeConfig::default() + } + } + + #[tokio::test] + async fn admission_accepts_only_the_configured_sandbox_network_resource() { + let network_config = || external_enforcer_config(Some("example.com/vf")); + let sandbox = Sandbox { + workspace: "team-a".into(), + name: "networked".into(), + spec: Some(SandboxSpec { + template: Some(SandboxTemplate { + image: "test".into(), + ..Default::default() + }), + ..Default::default() + }), + ..Default::default() + }; + KubernetesComputeDriver::new_for_test(network_config()) + .admit_requested_resources(&sandbox) + .await + .expect("create admits the configured resource"); + + let resource = ApiResource::from_gvk(&GroupVersionKind::gvk( + SANDBOX_GROUP, + SANDBOX_VERSION_V1BETA1, + SANDBOX_KIND, + )); + let mut stored = DynamicObject::new("networked", &resource); + stored.metadata.namespace = Some("openshell".to_string()); + stored.metadata.labels = Some(BTreeMap::from([ + (LABEL_SANDBOX_ID.to_string(), "sandbox-id".to_string()), + (LABEL_SANDBOX_WORKSPACE.to_string(), "team-a".to_string()), + ])); + stored.metadata.annotations = Some(BTreeMap::from([ + ( + crate::resource_admission::CONFIG_USED.to_string(), + "false".to_string(), + ), + ( + crate::resource_admission::IDENTITIES.to_string(), + "{}".to_string(), + ), + (ANNOTATION_NATIVE_NETWORK.to_string(), "true".to_string()), + ])); + stored.data = serde_json::json!({ + "spec": { + "podTemplate": { + "spec": { + "automountServiceAccountToken": false, + "containers": [{ + "name": "agent", + "resources": {"limits": {"example.com/vf": "1"}} + }], + "volumes": [{ + "name": SANDBOX_BOOTSTRAP_VOLUME_NAME, + "secret": {"secretName": "os-sandbox-sandbox-id-generation"} + }] + } + } + } + }); + KubernetesComputeDriver::new_for_test(network_config()) + .admit_stored_resources(&stored) + .await + .expect("reconcile admits the configured resource"); + let error = KubernetesComputeDriver::new_for_test(external_enforcer_config(None)) + .admit_stored_resources(&stored) + .await + .unwrap_err(); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + } + #[tokio::test] async fn admission_revalidates_stopped_sandbox_without_runtime_generation() { let driver = KubernetesComputeDriver::new_for_test(KubernetesComputeConfig::default()); @@ -9599,6 +10382,368 @@ mod tests { ) } + const SCHEDULED_SANDBOX_PATH: &str = + "/apis/agents.x-k8s.io/v1beta1/namespaces/openshell/sandboxes/sandbox-cr"; + const WORKLOAD_PODS_PATH: &str = "/api/v1/namespaces/openshell/pods"; + + fn scheduled_sandbox(phase: SandboxRuntimeBootstrapPhase, started_at_ms: i64) -> DynamicObject { + serde_json::from_value(serde_json::json!({ + "apiVersion": "agents.x-k8s.io/v1beta1", + "kind": "Sandbox", + "metadata": { + "name": "sandbox-cr", + "namespace": "openshell", + "uid": "cr-uid", + "resourceVersion": "7", + "annotations": { + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: phase.as_str(), + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_OPERATION: "create", + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_STARTED_AT: started_at_ms.to_string(), + ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: "pod-uid", + LABEL_SANDBOX_NAME: "sandbox-name", + ANNOTATION_SANDBOX_RUNTIME_MAIN_PROCESS_SPEC: + openshell_core::sandbox_env::MainProcessConfig::encode_driver_spec(None) + .unwrap(), + }, + }, + })) + .unwrap() + } + + fn scheduled_sandbox_json( + phase: SandboxRuntimeBootstrapPhase, + started_at_ms: i64, + ) -> http::Response { + kube_test_response( + http::StatusCode::OK, + serde_json::to_value(scheduled_sandbox(phase, started_at_ms)).unwrap(), + ) + } + + fn bound_workload_pods_json() -> http::Response { + kube_test_response( + http::StatusCode::OK, + serde_json::json!({ + "apiVersion": "v1", + "kind": "PodList", + "metadata": {"resourceVersion": "1"}, + "items": [{ + "metadata": {"name": "workload", "namespace": "openshell", "uid": "pod-uid"}, + "spec": {"containers": [], "nodeName": "node-a"}, + }], + }), + ) + } + + /// A shared generation of `sandbox-cr`, prepared but not yet launched. + fn scheduled_generation(driver: &KubernetesComputeDriver) -> PreparedGeneration { + let route = openshell_sandbox_backend::runtime_routed::new_route_handle(); + let session_id = openshell_core::SandboxSessionId::new(); + let launch_authentication = openshell_core::jwt::SandboxLaunchAuthentication { + supervisor: openshell_core::jwt::SupervisorAuthBundle { + session_id, + runtime_generation: openshell_core::sandbox_generation::SandboxGenerationId::parse( + "generation-1", + ) + .unwrap(), + session_rotation: openshell_core::jwt::SessionRotation::new(1).unwrap(), + auth_epoch: openshell_core::jwt::CredentialEpoch::new(1).unwrap(), + gateway_token: openshell_core::jwt::SecretJwt::parse("gateway.token.value") + .unwrap(), + gateway_expires_at: i64::MAX, + sandbox_token: openshell_core::jwt::SecretJwt::parse("sandbox.token.value") + .unwrap(), + sandbox_expires_at: i64::MAX, + ssh_host_private_key: None, + traces_otlp_headers: None, + ocsf_otlp_headers: None, + agent_otlp_headers: None, + otlp_tls: Vec::new(), + traces_otlp_tls: None, + ocsf_otlp_tls: None, + agent_otlp_tls: None, + }, + gateway_id: "gateway-a".to_string(), + verification_keys: vec![openshell_core::jwt::SessionVerificationKey { + key_id: "key-1".to_string(), + public_key_pem: b"public-key".to_vec(), + }], + }; + let target = SharedSupervisorTarget { + namespace: "openshell".to_string(), + authority: "openshell-supervisor.openshell.svc:5500".to_string(), + address: "10.43.0.9:5500".parse().unwrap(), + selector: BTreeMap::new(), + }; + let tls = generate_sandbox_tls_material(session_id).unwrap(); + let provisioned = KubernetesSandboxRuntimeBoundarySpec { + boundary_id: "sandbox-id".to_string(), + generation: "generation-1".to_string(), + session_id, + session_rotation: launch_authentication.supervisor.session_rotation, + auth_epoch: launch_authentication.supervisor.auth_epoch, + gateway_id: launch_authentication.gateway_id.clone(), + verification_keys: gateway_verification_keys(&launch_authentication.verification_keys) + .unwrap(), + namespace_uid: "namespace-uid".to_string(), + sandbox_resource_uid: "cr-uid".to_string(), + workload_pod_uid: "pod-uid".to_string(), + workload_pod_uid_path: PathBuf::from(SANDBOX_POD_UID_PATH), + supervisor: KubernetesSupervisorClaim::SandboxInstance(route.clone()), + egress_policy_uid: "fence-uid".to_string(), + egress_policy_resource_version: "1".to_string(), + control_path: KubernetesControlPath::RuntimeInitiatedShared { + control_authority: target.authority.clone(), + supervisor_address: target.address, + supervisor_namespace: target.namespace.clone(), + route: route.clone(), + control_policy_uid: "control-uid".to_string(), + control_policy_resource_version: "1".to_string(), + }, + sandbox_tls: SandboxTlsServerConfig { + certificate_chain_path: PathBuf::from(BOUNDARY_CERTIFICATE_PATH), + private_key_path: PathBuf::from(BOUNDARY_PRIVATE_KEY_PATH), + }, + supervisor_tls: SandboxTlsClientConfig { + server_name: tls.server_name, + trust_anchor_pem: tls.trust_anchor_pem, + }, + host_gateway_ip: None, + workload_identity: ResolvedWorkloadIdentity::new( + 1000, + 1000, + Vec::new(), + "kubernetes-config".to_string(), + "sandbox:cr-uid".to_string(), + ) + .unwrap(), + child_env: std::collections::HashMap::new(), + native_network: false, + } + .provision() + .unwrap(); + let shared = SharedSupervisor::new( + crate::config::SharedSupervisorConfig { + service_name: "openshell-supervisor".to_string(), + service_namespace: "openshell".to_string(), + runtime_port: 5500, + token_secret_name: "openshell-supervisor-token".to_string(), + service_account_name: "openshell-supervisor".to_string(), + require_identity_token: true, + }, + SharedSupervision::new(), + ); + PreparedGeneration { + namespace: "openshell".to_string(), + cr_name: "sandbox-cr".to_string(), + sandbox_api: KubernetesComputeDriver::agent_sandbox_api( + driver.client.clone(), + "v1beta1", + "openshell", + ), + sandbox_id: "sandbox-id".to_string(), + cr_uid: "cr-uid".to_string(), + names: SandboxRuntimeNames::new("sandbox-id"), + launch_authentication, + staged: StagedBootstrapMaterial { + upstream_proxy_ca_bundle: None, + client_tls: None, + }, + boundary: GenerationBoundary::Installed(Box::new(provisioned.runtime_descriptor)), + proxy_ca: generate_proxy_ca_material().unwrap(), + target: GenerationLaunchTarget::Shared { + shared, + route, + target, + control_policy: VerifiedControlPolicy { + uid: "control-uid".to_string(), + resource_version: "1".to_string(), + generation: 1, + }, + }, + admission_object: scheduled_sandbox( + SandboxRuntimeBootstrapPhase::Preparing, + openshell_core::time::now_ms(), + ), + workload_pod_uid: "pod-uid".to_string(), + workload_pod_name: "workload".to_string(), + } + } + + #[tokio::test] + async fn scheduled_launch_the_pool_cannot_place_is_rolled_back() { + let awaiting = || { + scheduled_sandbox_json( + SandboxRuntimeBootstrapPhase::Preparing, + openshell_core::time::now_ms(), + ) + }; + let (driver, steps, bodies) = scripted_driver( + managed_config(&[]), + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + (http::Method::PATCH, SCHEDULED_SANDBOX_PATH, awaiting()), + ( + http::Method::POST, + "/api/v1/namespaces/openshell/secrets", + kube_test_response( + http::StatusCode::CREATED, + serde_json::json!({ + "apiVersion": "v1", + "kind": "Secret", + "metadata": {"name": "instance", "namespace": "openshell"}, + }), + ), + ), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, awaiting()), + ( + http::Method::DELETE, + SCHEDULED_SANDBOX_PATH, + kube_test_response(http::StatusCode::OK, serde_json::json!({})), + ), + ], + ); + let generation = scheduled_generation(&driver); + let GenerationLaunchTarget::Shared { route, .. } = &generation.target else { + unreachable!(); + }; + let placement = SupervisorPlacement::Shared { + route: route.clone(), + }; + Box::pin( + driver + .clone() + .launch_on_scheduled_node(generation, placement), + ) + .await; + assert!(steps.lock().unwrap().is_empty()); + let bodies = bodies.lock().unwrap(); + let delete = bodies.last().unwrap(); + assert_eq!(delete["preconditions"]["uid"], "cr-uid"); + assert_eq!(delete["preconditions"]["resourceVersion"], "7"); + } + + #[tokio::test] + async fn scheduled_launch_skips_a_sandbox_that_moved_on_or_went_stale() { + let now = openshell_core::time::now_ms(); + for sandbox in [ + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Suspending, now), + scheduled_sandbox_json(SandboxRuntimeBootstrapPhase::Preparing, 0), + ] { + let (driver, steps, bodies) = scripted_driver( + managed_config(&[]), + vec![ + ( + http::Method::GET, + WORKLOAD_PODS_PATH, + bound_workload_pods_json(), + ), + (http::Method::GET, SCHEDULED_SANDBOX_PATH, sandbox), + ], + ); + let generation = scheduled_generation(&driver); + Box::pin( + driver + .clone() + .launch_on_scheduled_node(generation, SupervisorPlacement::Dedicated), + ) + .await; + assert!(steps.lock().unwrap().is_empty()); + assert!(bodies.lock().unwrap().is_empty()); + } + } + + #[test] + fn sandboxes_run_only_under_the_native_network_mode_they_were_created_in() { + let mut native = sandbox_object_for_test("uid", "sandbox-a"); + native.metadata.annotations = Some(BTreeMap::from([( + ANNOTATION_NATIVE_NETWORK.to_string(), + "true".to_string(), + )])); + let mediated = sandbox_object_for_test("uid", "sandbox-b"); + assert!(check_native_network_mode(&native, true).is_ok()); + assert!(check_native_network_mode(&mediated, false).is_ok()); + assert!( + check_native_network_mode(&native, false) + .unwrap_err() + .contains("now off") + ); + assert!( + check_native_network_mode(&mediated, true) + .unwrap_err() + .contains("now on") + ); + } + + #[test] + fn scheduled_launch_runs_only_for_the_attempt_that_prepared_it() { + let sandbox = |uid: &str, phase: &str, workload_uid: &str| { + serde_json::from_value::(serde_json::json!({ + "apiVersion": "agents.x-k8s.io/v1beta1", + "kind": "Sandbox", + "metadata": { + "name": "sandbox-cr", + "namespace": "openshell", + "uid": uid, + "annotations": { + ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_PHASE: phase, + ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID: workload_uid, + }, + }, + })) + .unwrap() + }; + let preparing = SandboxRuntimeBootstrapPhase::Preparing.as_str(); + assert!(sandbox_runtime_awaits_launch( + &sandbox("cr-1", preparing, "pod-1"), + "cr-1", + "pod-1" + )); + // Stopped or suspended while it waited. + assert!(!sandbox_runtime_awaits_launch( + &sandbox( + "cr-1", + SandboxRuntimeBootstrapPhase::Suspending.as_str(), + "pod-1" + ), + "cr-1", + "pod-1" + )); + // A retried or newer attempt prepared another workload Pod. + assert!(!sandbox_runtime_awaits_launch( + &sandbox("cr-1", preparing, "pod-2"), + "cr-1", + "pod-1" + )); + // Already launched, or a stop is releasing it. + for phase in [ + SandboxRuntimeBootstrapPhase::Released, + SandboxRuntimeBootstrapPhase::Releasing, + ] { + assert!(!sandbox_runtime_awaits_launch( + &sandbox("cr-1", phase.as_str(), "pod-1"), + "cr-1", + "pod-1" + )); + } + // The bootstrap completed and its annotations were cleared. + let mut completed = sandbox("cr-1", preparing, "pod-1"); + completed.metadata.annotations = None; + assert!(!sandbox_runtime_awaits_launch(&completed, "cr-1", "pod-1")); + // Deleted and recreated under the same name. + assert!(!sandbox_runtime_awaits_launch( + &sandbox("cr-2", preparing, "pod-1"), + "cr-1", + "pod-1" + )); + } + fn network_trust_bundle(gateway_id: &str, digest: &str) -> NetworkSupervisorTrustBundle { NetworkSupervisorTrustBundle::new( b"-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----\n".to_vec(), @@ -9608,6 +10753,31 @@ mod tests { ) } + #[test] + fn shared_topology_bounds_the_additional_ca_bundle() { + let limit = openshell_supervisor_control::MAX_SHARED_TRUST_MATERIAL_BYTES; + let bundle_of = |len: usize| { + NetworkSupervisorTrustBundle::new( + vec![b'a'; len], + 1, + "sha256:fixture", + PathBuf::from("/gateway-state/ca.crt"), + ) + }; + + assert!(validate_shared_network_trust_bundle(None, 0).is_ok()); + assert!(validate_shared_network_trust_bundle(None, limit + 1).is_ok()); + assert!(validate_shared_network_trust_bundle(Some(&bundle_of(limit)), 0).is_ok()); + assert!(matches!( + validate_shared_network_trust_bundle(Some(&bundle_of(limit + 1)), 0), + Err(KubernetesDriverError::Precondition(_)) + )); + assert!(matches!( + validate_shared_network_trust_bundle(Some(&bundle_of(limit - 10)), 11), + Err(KubernetesDriverError::Precondition(_)) + )); + } + #[test] fn destination_trust_config_map_is_immutable_content_addressed_and_retained() { let digest = "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"; @@ -10218,6 +11388,55 @@ mod tests { sandbox } + #[test] + fn generations_recover_only_with_the_placement_they_need() { + let generation = |member: Option<&str>, node: Option<&str>| { + let mut object = sandbox_object_for_test("uid", "sandbox-a"); + let mut annotations = BTreeMap::from([( + ANNOTATION_SANDBOX_RUNTIME_GENERATION.to_string(), + "gen-1".to_string(), + )]); + if let Some(member) = member { + annotations.insert(ANNOTATION_SUPERVISOR_MEMBER.to_string(), member.to_string()); + } + if let Some(node) = node { + annotations.insert( + ANNOTATION_SANDBOX_RUNTIME_NODE.to_string(), + node.to_string(), + ); + } + object.metadata.annotations = Some(annotations); + object + }; + let recover = |object: &DynamicObject, node_topology: bool, needs_node: bool| { + recoverable_instance( + object, + "route".to_string(), + node_topology, + needs_node, + "default", + ) + }; + + let pinned = recover(&generation(Some("node-a"), None), true, true).expect("pinned"); + assert_eq!(pinned.member.as_deref(), Some("node-a")); + // A node generation recorded before its node annotation is on its member. + assert_eq!(pinned.node.as_deref(), Some("node-a")); + assert_eq!(pinned.record.generation, "gen-1"); + assert_eq!(pinned.record.namespace, "sandbox-namespace"); + assert!(recover(&generation(None, None), true, true).is_none()); + assert!(recover(&generation(Some(""), None), true, true).is_none()); + assert!(recover(&generation(None, Some("node-a")), true, true).is_none()); + + let unpinned = recover(&generation(None, None), false, false).unwrap(); + assert!(unpinned.member.is_none() && unpinned.node.is_none()); + // A native-network gateway-topology generation needs its node. + assert!(recover(&generation(None, None), false, true).is_none()); + let native = recover(&generation(None, Some("node-b")), false, true).unwrap(); + assert!(native.member.is_none()); + assert_eq!(native.node.as_deref(), Some("node-b")); + } + #[test] fn only_runnable_shared_generations_keep_their_instances() { let shared = |route: &str, operating_mode: &str, annotations: &[(&str, &str)]| { @@ -10270,12 +11489,13 @@ mod tests { let annotations = &patch["metadata"]["annotations"]; assert!(annotations[ANNOTATION_SUPERVISOR_TOPOLOGY].is_null()); assert!(annotations[ANNOTATION_SUPERVISOR_SESSION].is_null()); - assert!( - annotations - .as_object() - .unwrap() - .contains_key(ANNOTATION_SUPERVISOR_SESSION) - ); + for key in [ + ANNOTATION_SUPERVISOR_SESSION, + ANNOTATION_SUPERVISOR_MEMBER, + ANNOTATION_SANDBOX_RUNTIME_NODE, + ] { + assert!(annotations.as_object().unwrap().contains_key(key), "{key}"); + } } #[test] @@ -11970,6 +13190,80 @@ mod tests { ); } + fn admitted_workload_pod(nameservers: &[std::net::IpAddr]) -> Pod { + let params = SandboxPodParams { + default_image: "agent:latest", + sandbox_runtime_image: "sandbox-runtime-image:latest", + sandbox_id: "sandbox-123", + sandbox_uid: 1500, + sandbox_gid: 1500, + nameservers, + ..SandboxPodParams::default() + }; + let template = sandbox_template_to_k8s( + &SandboxTemplate::default(), + false, + &std::collections::HashMap::new(), + true, + ¶ms, + ); + serde_json::from_value(serde_json::json!({ + "metadata": { + "name": "sandbox-123-workload", + "uid": "pod-uid", + "labels": template["metadata"]["labels"], + "ownerReferences": [{ + "apiVersion": "agents.x-k8s.io/v1alpha1", + "kind": SANDBOX_KIND, + "name": "sandbox-123", + "uid": "cr-uid", + "controller": true + }] + }, + "spec": template["spec"] + })) + .unwrap() + } + + #[test] + fn workload_resolvers_are_the_configured_list_or_policy_dns() { + let resolver: std::net::IpAddr = "192.168.100.1".parse().unwrap(); + + for (nameservers, want) in [ + (&[][..], serde_json::json!(["127.0.0.53"])), + (&[resolver][..], serde_json::json!(["192.168.100.1"])), + ] { + let pod = serde_json::to_value(admitted_workload_pod(nameservers)).unwrap(); + assert_eq!(pod["spec"]["dnsPolicy"], "None"); + assert_eq!(pod["spec"]["dnsConfig"]["nameservers"], want); + } + } + + #[test] + fn posture_check_holds_the_pod_to_the_current_resolvers() { + let resolver: std::net::IpAddr = "192.168.100.1".parse().unwrap(); + let check = |pod: &Pod, nameservers: &[std::net::IpAddr]| { + KubernetesComputeDriver::validate_capability_free_workload_pod( + pod, + "cr-uid", + "sandbox-123", + 1500, + 1500, + "os-sandbox-test-generation", + nameservers, + ) + }; + + let loopback = admitted_workload_pod(&[]); + let provider = admitted_workload_pod(&[resolver]); + check(&loopback, &[]).unwrap(); + check(&provider, &[resolver]).unwrap(); + for (pod, nameservers) in [(&loopback, &[resolver][..]), (&provider, &[][..])] { + let error = check(pod, nameservers).unwrap_err().to_string(); + assert!(error.contains("DNS posture changed"), "{error}"); + } + } + #[test] fn sandbox_runtime_renders_credential_free_boundary_workload() { let params = SandboxPodParams { @@ -13087,6 +14381,137 @@ mod tests { assert_eq!(tolerations[0]["effect"], "NoSchedule"); } + #[test] + fn native_network_pins_pods_to_ready_nodes() { + use crate::config::EXTERNAL_ENFORCER_READY_NODE_LABEL as READY_NODE_LABEL; + let template = SandboxTemplate { + driver_config: Some(json_struct(serde_json::json!({ + "pod": { + "node_selector": { + READY_NODE_LABEL: "false", + "accelerator": "nvidia" + } + } + }))), + ..SandboxTemplate::default() + }; + let render = |native_network| { + sandbox_template_to_k8s( + &template, + false, + &std::collections::HashMap::new(), + false, + &SandboxPodParams { + native_network, + ..SandboxPodParams::default() + }, + ) + }; + + assert_eq!( + render(true)["spec"]["nodeSelector"], + serde_json::json!({READY_NODE_LABEL: "true", "accelerator": "nvidia"}) + ); + assert_eq!( + render(false)["spec"]["nodeSelector"], + serde_json::json!({READY_NODE_LABEL: "false", "accelerator": "nvidia"}) + ); + let stock = sandbox_template_to_k8s( + &SandboxTemplate::default(), + false, + &std::collections::HashMap::new(), + false, + &SandboxPodParams::default(), + ); + assert!(stock["spec"].get("nodeSelector").is_none()); + } + + #[test] + fn sandbox_network_sets_the_default_network_and_overrides_the_device_request() { + let template = SandboxTemplate { + platform_config: Some(json_struct(serde_json::json!({ + "annotations": {MULTUS_DEFAULT_NETWORK_ANNOTATION: "caller/other"} + }))), + driver_config: Some(json_struct(serde_json::json!({ + "containers": {"agent": {"resources": { + "requests": {"example.com/vf": "4", "cpu": "1"}, + "limits": {"example.com/vf": "4"} + }}} + }))), + ..SandboxTemplate::default() + }; + let network = crate::PodNetwork { + network_attachment: "openshell/sandbox-vf".into(), + resource: Some("example.com/vf".into()), + }; + + let pod_template = sandbox_template_to_k8s( + &template, + false, + &std::collections::HashMap::new(), + false, + &SandboxPodParams { + sandbox_network: Some(&network), + ..SandboxPodParams::default() + }, + ); + + assert_eq!( + pod_template["metadata"]["annotations"][MULTUS_DEFAULT_NETWORK_ANNOTATION], + "openshell/sandbox-vf" + ); + let resources = &pod_template["spec"]["containers"][0]["resources"]; + assert_eq!(resources["requests"]["example.com/vf"], "1"); + assert_eq!(resources["limits"]["example.com/vf"], "1"); + assert_eq!(resources["requests"]["cpu"], "1"); + } + + #[test] + fn sandbox_network_without_a_resource_requests_no_device() { + let network = crate::PodNetwork { + network_attachment: "sandbox-net".into(), + resource: None, + }; + + let pod_template = sandbox_template_to_k8s( + &SandboxTemplate::default(), + false, + &std::collections::HashMap::new(), + false, + &SandboxPodParams { + sandbox_network: Some(&network), + ..SandboxPodParams::default() + }, + ); + + assert_eq!( + pod_template["metadata"]["annotations"][MULTUS_DEFAULT_NETWORK_ANNOTATION], + "sandbox-net" + ); + assert!( + pod_template["spec"]["containers"][0] + .get("resources") + .is_none() + ); + } + + #[test] + fn no_sandbox_network_leaves_the_pod_network_alone() { + let pod_template = sandbox_template_to_k8s( + &SandboxTemplate::default(), + false, + &std::collections::HashMap::new(), + false, + &SandboxPodParams::default(), + ); + + assert!( + pod_template["metadata"]["annotations"] + .get(MULTUS_DEFAULT_NETWORK_ANNOTATION) + .is_none() + ); + } + #[test] fn driver_config_applies_pod_scheduling_and_agent_resources() { let template = SandboxTemplate { @@ -14041,6 +15466,7 @@ mod tests { &volumes, &init_containers, &["os-pull-sandbox-1-gen7-0".to_string()], + &[], ); assert_eq!(spec["volumes"], serde_json::json!(volumes)); assert_eq!(spec["initContainers"], serde_json::json!(init_containers)); @@ -14048,6 +15474,12 @@ mod tests { spec["imagePullSecrets"], serde_json::json!([{"name": "os-pull-sandbox-1-gen7-0"}]) ); + assert_eq!(spec["dnsConfig"], workload_dns_config(&[])); + let resolver: std::net::IpAddr = "192.168.100.1".parse().unwrap(); + assert_eq!( + restart_pod_template_spec(&[], &[], &[], &[resolver])["dnsConfig"], + workload_dns_config(&[resolver]) + ); } #[test] @@ -14340,6 +15772,192 @@ mod tests { assert!(gpu.count_selection_supported); } + fn supervisor_pod(ready: bool, network_status: Option) -> Pod { + let mut pod = serde_json::json!({ + "metadata": {"name": "openshell-supervisor-abc"}, + "status": { + "phase": "Running", + "conditions": [{"type": "Ready", "status": if ready { "True" } else { "False" }}] + } + }); + if let Some(status) = network_status { + pod["metadata"]["annotations"] = + serde_json::json!({MULTUS_NETWORK_STATUS_ANNOTATION: status.to_string()}); + } + serde_json::from_value(pod).unwrap() + } + + #[test] + fn supervisor_network_address_uses_the_named_attachment_entry() { + let status = serde_json::json!([ + {"name": "cluster-default", "interface": "eth0", "ips": ["10.244.1.5"], "default": true}, + {"name": "openshell/supervisor-vf", "interface": "net1", "ips": ["fd00::2", "192.168.100.2/24"]} + ]); + let pods = [ + supervisor_pod(true, Some(status)), + // A Pod that isn't Ready is ignored, even with another address. + supervisor_pod( + false, + Some(serde_json::json!([ + {"name": "openshell/supervisor-vf", "ips": ["192.168.100.9"]} + ])), + ), + ]; + assert_eq!( + supervisor_network_address(&pods, "openshell/supervisor-vf", "node-a").unwrap(), + std::net::IpAddr::from([192, 168, 100, 2]) + ); + let link_local = serde_json::json!([ + {"name": "openshell/supervisor-vf", "ips": ["169.254.1.1", "192.168.100.2"]} + ]); + assert_eq!( + supervisor_network_address( + &[supervisor_pod(true, Some(link_local))], + "openshell/supervisor-vf", + "node-a" + ) + .unwrap(), + std::net::IpAddr::from([192, 168, 100, 2]) + ); + for unroutable in ["127.0.0.1", "0.0.0.0", "224.0.0.1"] { + let status = + serde_json::json!([{"name": "openshell/supervisor-vf", "ips": [unroutable]}]); + assert!( + supervisor_network_address( + &[supervisor_pod(true, Some(status))], + "openshell/supervisor-vf", + "node-a" + ) + .is_err(), + "{unroutable}" + ); + } + assert_eq!( + qualified_network_attachment("supervisor-vf", "openshell"), + "openshell/supervisor-vf" + ); + assert_eq!( + qualified_network_attachment("other/supervisor-vf", "openshell"), + "other/supervisor-vf" + ); + } + + #[tokio::test] + async fn node_supervisor_lookup_lists_the_service_pods_on_the_workload_node() { + let pod = supervisor_pod( + true, + Some(serde_json::json!([ + {"name": "openshell/supervisor-vf", "interface": "net1", "ips": ["192.168.100.2"]} + ])), + ); + let service = tower::service_fn(move |request: http::Request| { + let pod = pod.clone(); + async move { + assert_eq!(request.method(), http::Method::GET); + assert_eq!(request.uri().path(), "/api/v1/namespaces/openshell/pods"); + let query = request.uri().query().unwrap_or_default().to_string(); + assert!( + query.contains("labelSelector=app.kubernetes.io%2Fname%3Dsupervisor"), + "{query}" + ); + assert!( + query.contains("fieldSelector=spec.nodeName%3Dnode-a"), + "{query}" + ); + Ok::<_, std::convert::Infallible>(kube_test_response( + http::StatusCode::OK, + serde_json::json!({ + "apiVersion": "v1", + "kind": "PodList", + "metadata": {}, + "items": [pod] + }), + )) + } + }); + let client = Client::new(service, "openshell"); + let driver = KubernetesComputeDriver { + client: client.clone(), + watch_client: client, + sandbox_api_version: Arc::new(OnceCell::new()), + lifecycle_gates: Arc::default(), + config: KubernetesComputeConfig::default(), + network_trust_bundle: None, + operator_allowlist: None, + shared_supervisor: None, + }; + let target = SharedSupervisorTarget { + namespace: "openshell".to_string(), + authority: "openshell-supervisor.openshell.svc:5500".to_string(), + address: "10.96.0.10:5500".parse().unwrap(), + selector: BTreeMap::from([( + "app.kubernetes.io/name".to_string(), + "supervisor".to_string(), + )]), + }; + let network = crate::PodNetwork { + network_attachment: "supervisor-vf".to_string(), + resource: None, + }; + assert_eq!( + driver + .node_supervisor_network_address(&target, &network, "node-a") + .await + .unwrap(), + std::net::IpAddr::from([192, 168, 100, 2]) + ); + } + + #[test] + fn supervisor_network_address_fails_without_one_agreed_address() { + let no_ready = supervisor_network_address( + &[supervisor_pod(false, None)], + "openshell/supervisor-vf", + "node-a", + ) + .unwrap_err(); + assert!( + no_ready.to_string().contains("no Ready supervisor"), + "{no_ready}" + ); + + let only_default = serde_json::json!([ + {"name": "cluster-default", "interface": "eth0", "ips": ["10.244.1.5"], "default": true} + ]); + let two_addresses = serde_json::json!([ + {"name": "openshell/supervisor-vf", "ips": ["192.168.100.2", "192.168.100.3"]} + ]); + for status in [None, Some(only_default), Some(two_addresses)] { + let error = supervisor_network_address( + &[supervisor_pod(true, status)], + "openshell/supervisor-vf", + "node-a", + ) + .unwrap_err(); + assert!( + error.to_string().contains("no single IPv4 address"), + "{error}" + ); + } + + let address = |ip: &str| { + supervisor_pod( + true, + Some(serde_json::json!([{"name": "openshell/supervisor-vf", "ips": [ip]}])), + ) + }; + let disagree = supervisor_network_address( + &[address("192.168.100.2"), address("192.168.100.9")], + "openshell/supervisor-vf", + "node-a", + ) + .unwrap_err(); + assert!( + disagree.to_string().contains("different addresses"), + "{disagree}" + ); + } + #[test] fn sandbox_runtime_control_availability_requires_a_ready_pod() { let mut pod = Pod::default(); @@ -14507,6 +16125,7 @@ mod tests { ANNOTATION_SANDBOX_RUNTIME_BOOTSTRAP_SESSION, ANNOTATION_SANDBOX_RUNTIME_GENERATION, ANNOTATION_SANDBOX_RUNTIME_WORKLOAD_UID, + ANNOTATION_SANDBOX_RUNTIME_GATEWAY_GENERATION, ANNOTATION_SANDBOX_RUNTIME_SUPERVISOR_UID, ANNOTATION_SANDBOX_RUNTIME_NETWORK_POLICY_UID, ANNOTATION_SANDBOX_RUNTIME_NETWORK_POLICY_GENERATION, diff --git a/crates/openshell-driver-kubernetes/src/isolation.rs b/crates/openshell-driver-kubernetes/src/isolation.rs index d943bac705..d6e06dfa1d 100644 --- a/crates/openshell-driver-kubernetes/src/isolation.rs +++ b/crates/openshell-driver-kubernetes/src/isolation.rs @@ -408,6 +408,8 @@ pub struct KubernetesSandboxRuntimeBoundarySpec { pub host_gateway_ip: Option, pub workload_identity: ResolvedWorkloadIdentity, pub child_env: HashMap, + /// Claim native-network mode for the runtime. + pub native_network: bool, } /// Protected workload-pod config and matching sandbox-runtime descriptor. @@ -448,6 +450,20 @@ impl KubernetesSandboxRuntimeBoundarySpec { self.egress_policy_resource_version, ), ]); + if self.native_network { + if !matches!( + self.control_path, + KubernetesControlPath::RuntimeInitiatedShared { .. } + ) { + return Err(BackendError::Descriptor( + "native-network mode requires the shared supervisor control path".into(), + )); + } + resource_claims.insert( + openshell_sandbox_backend::NATIVE_NETWORK_RESOURCE_CLAIM.to_string(), + "true".to_string(), + ); + } let mut supervisor_namespace = None; let mut shared_port = None; let (listener, transport) = match self.control_path { @@ -676,7 +692,41 @@ mod tests { ) .unwrap(), child_env: HashMap::new(), + native_network: false, + } + } + + #[test] + fn native_network_claim_is_written_on_both_sides_only_when_set() { + let claim = openshell_sandbox_backend::NATIVE_NETWORK_RESOURCE_CLAIM; + let stock = spec().provision().unwrap(); + assert!(!stock.runtime_descriptor.resource_claims.contains_key(claim)); + + let dedicated = KubernetesSandboxRuntimeBoundarySpec { + native_network: true, + ..spec() + }; + assert!(dedicated.provision().is_err()); + + let native = KubernetesSandboxRuntimeBoundarySpec { + native_network: true, + control_path: KubernetesControlPath::RuntimeInitiatedShared { + control_authority: "openshell-supervisor.openshell.svc:5500".to_string(), + supervisor_address: "10.43.0.9:5500".parse().expect("valid target"), + supervisor_namespace: "openshell".to_string(), + route: "route-1".to_string(), + control_policy_uid: "control-policy-uid".to_string(), + control_policy_resource_version: "7".to_string(), + }, + ..spec() } + .provision() + .unwrap(); + assert_eq!(native.runtime_descriptor.resource_claims[claim], "true"); + assert_eq!( + native.boundary_config.resource_claims, + native.runtime_descriptor.resource_claims + ); } #[test] diff --git a/crates/openshell-driver-kubernetes/src/lib.rs b/crates/openshell-driver-kubernetes/src/lib.rs index f3a1e419ec..2d343b61b2 100644 --- a/crates/openshell-driver-kubernetes/src/lib.rs +++ b/crates/openshell-driver-kubernetes/src/lib.rs @@ -14,8 +14,9 @@ mod shared_supervisor; pub use config::{ DEFAULT_GATEWAY_ID, DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, DEFAULT_WORKSPACE_STORAGE_SIZE, - KubernetesComputeConfig, KubernetesControlConnection, KubernetesImagePullPolicy, - KubernetesSandboxRuntimeConfig, ManagedSshIngressConfig, SharedSupervisorConfig, + ExternalEnforcerConfig, ExternalEnforcerNetwork, KubernetesComputeConfig, + KubernetesControlConnection, KubernetesImagePullPolicy, KubernetesSandboxRuntimeConfig, + ManagedSshIngressConfig, PodNetwork, SandboxNetwork, SharedSupervisorConfig, SupervisorTopology, WorkspaceMode, managed_namespace_prefix, }; pub use driver::{KubernetesComputeDriver, KubernetesDriverError}; diff --git a/crates/openshell-driver-kubernetes/src/main.rs b/crates/openshell-driver-kubernetes/src/main.rs index 9f2b18068a..f38281dd54 100644 --- a/crates/openshell-driver-kubernetes/src/main.rs +++ b/crates/openshell-driver-kubernetes/src/main.rs @@ -336,6 +336,7 @@ async fn main() -> Result<()> { "OPENSHELL_K8S_SUPERVISOR_RUNTIME_CLASS_NAME", ) .unwrap_or_default(), + external_enforcer: None, allowed_pod_annotations: args.allowed_pod_annotations, allowed_pod_labels: args.allowed_pod_labels, sa_token_ttl_secs: args.sa_token_ttl_secs, diff --git a/crates/openshell-driver-kubernetes/src/resource_admission.rs b/crates/openshell-driver-kubernetes/src/resource_admission.rs index 339572d1f2..c30e4efcd7 100644 --- a/crates/openshell-driver-kubernetes/src/resource_admission.rs +++ b/crates/openshell-driver-kubernetes/src/resource_admission.rs @@ -84,7 +84,12 @@ fn reference(refs: &mut BTreeSet, kind: &'static str, name: Option<&s } } -fn inventory(spec: &Value, private_secret: &str) -> Result, Status> { +/// `network_resource` is the workload network device the driver requests itself. +fn inventory( + spec: &Value, + private_secret: &str, + network_resource: Option<&str>, +) -> Result, Status> { let deny = || { Status::failed_precondition("workload contains an unsupported external resource attachment") }; @@ -155,7 +160,10 @@ fn inventory(spec: &Value, private_secret: &str) -> Result, .into_iter() .flatten() { - if resource.contains('/') && resource != "nvidia.com/gpu" { + if resource.contains('/') + && resource != "nvidia.com/gpu" + && Some(resource.as_str()) != network_resource + { return Err(deny()); } } @@ -175,13 +183,14 @@ pub async fn admit( namespace: &str, spec: &Value, private_secret: &str, + network_resource: Option<&str>, ) -> Result { policy.validate().map_err(Status::failed_precondition)?; if !policy.enabled { return Ok(BTreeMap::new()); } let mut identities = BTreeMap::new(); - for reference in inventory(spec, private_secret)? { + for reference in inventory(spec, private_secret, network_resource)? { let (group, version, plural, cluster) = match reference.kind { "PersistentVolumeClaim" => ("", "v1", "persistentvolumeclaims", false), "RuntimeClass" => ("node.k8s.io", "v1", "runtimeclasses", true), @@ -325,6 +334,7 @@ mod tests { "shared", &spec, "private", + None, ) .await; assert_eq!(result.is_ok(), allowed, "{result:?}"); @@ -392,6 +402,7 @@ mod tests { "shared", &spec, "private", + None, ) .await .expect_err("lookup must fail"); @@ -442,6 +453,7 @@ mod tests { "shared", &spec, "private", + None, ) .await .expect_err("unlabelled RuntimeClass must be denied"); @@ -458,7 +470,7 @@ mod tests { let pod = serde_json::json!({"automountServiceAccountToken":false,"runtimeClassName":"r","priorityClassName":"p", "volumes":[{"name":"data","persistentVolumeClaim":{"claimName":"gateway-db","readOnly":true}}], "imagePullSecrets":[{"name":"regcred"}]}); - let refs = inventory(&pod, "private").unwrap(); + let refs = inventory(&pod, "private", None).unwrap(); assert_eq!(refs.len(), 3); assert!( refs.iter() @@ -472,13 +484,23 @@ mod tests { #[test] fn rejects_unsupported_volume_sources_but_allows_gpu() { for kind in ["hostPath", "csi", "projected", "image", "configMap"] { - assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"volumes":[{"name":"x",kind:{}}]}), "private").is_err()); + assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"volumes":[{"name":"x",kind:{}}]}), "private", None).is_err()); } - assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"volumes":[{"name":"x","secret":{"secretName":"external"}}]}), "private").is_err()); - assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"volumes":[{"name":"x","secret":{"secretName":"private"}}]}), "private").is_ok()); - assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"containers":[{"envFrom":[{"secretRef":{"name":"external"}}]}]}), "private").is_err()); - assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"containers":[{"env":[{"valueFrom":{"configMapKeyRef":{"name":"external"}}}]}]}), "private").is_err()); - assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"containers":[{"resources":{"limits":{"nvidia.com/gpu":"1"}}}]}), "private").is_ok()); + assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"volumes":[{"name":"x","secret":{"secretName":"external"}}]}), "private", None).is_err()); + assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"volumes":[{"name":"x","secret":{"secretName":"private"}}]}), "private", None).is_ok()); + assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"containers":[{"envFrom":[{"secretRef":{"name":"external"}}]}]}), "private", None).is_err()); + assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"containers":[{"env":[{"valueFrom":{"configMapKeyRef":{"name":"external"}}}]}]}), "private", None).is_err()); + assert!(inventory(&serde_json::json!({"automountServiceAccountToken":false,"containers":[{"resources":{"limits":{"nvidia.com/gpu":"1"}}}]}), "private", None).is_ok()); + } + #[test] + fn accepts_only_the_configured_sandbox_network_resource() { + let pod = |resource: &str| { + serde_json::json!({"automountServiceAccountToken":false,"containers":[{"resources":{ + "requests":{resource:"1"},"limits":{resource:"1"}}}]}) + }; + assert!(inventory(&pod("example.com/vf"), "private", None).is_err()); + assert!(inventory(&pod("example.com/vf"), "private", Some("example.com/vf")).is_ok()); + assert!(inventory(&pod("example.com/other"), "private", Some("example.com/vf")).is_err()); } #[test] fn legacy_and_forbidden_config_records_fail_closed() { diff --git a/crates/openshell-driver-kubernetes/src/shared_supervisor.rs b/crates/openshell-driver-kubernetes/src/shared_supervisor.rs index 850e261e34..0091764783 100644 --- a/crates/openshell-driver-kubernetes/src/shared_supervisor.rs +++ b/crates/openshell-driver-kubernetes/src/shared_supervisor.rs @@ -25,7 +25,7 @@ use kube::core::DynamicObject; use openshell_supervisor_control::{SharedSupervision, SupervisorCredential, deliver_credentials}; use tracing::info; -use crate::config::SharedSupervisorConfig; +use crate::config::{ExternalEnforcerConfig, SharedSupervisorConfig}; use crate::driver::KubernetesDriverError; /// Supervisor placement of the current generation; absent means a dedicated @@ -35,6 +35,14 @@ pub const ANNOTATION_SUPERVISOR_TOPOLOGY: &str = "openshell.ai/sandbox-runtime-s /// annotation key keeps its established `-session` name. pub const ANNOTATION_SUPERVISOR_SESSION: &str = "openshell.ai/sandbox-runtime-supervisor-session"; pub const GATEWAY_TOPOLOGY: &str = "gateway"; +/// Pool member, the node name, that alone may supervise a node-topology +/// generation. Recovery reads it from the Sandbox resource, since the +/// workload Pod may be gone. +pub const ANNOTATION_SUPERVISOR_MEMBER: &str = "openshell.ai/sandbox-runtime-supervisor-member"; +/// Node a native-network generation's workload was scheduled to, which +/// enforcer shards select by. Recovery reads it from the Sandbox resource; +/// node-topology generations recorded before it fall back to their member. +pub const ANNOTATION_SANDBOX_RUNTIME_NODE: &str = "openshell.ai/sandbox-runtime-node"; /// Key of the supervisor token in `shared_supervisor.token_secret_name`. pub const TOKEN_SECRET_KEY: &str = "token"; /// Annotation recording the token's expiry (Unix seconds) for operators. @@ -84,38 +92,53 @@ pub fn supervisor_placement( /// coordination of its sandbox instances. #[derive(Clone, Debug)] pub struct SharedSupervisor { - config: SharedSupervisorConfig, + config: std::sync::Arc, supervision: SharedSupervision, } impl SharedSupervisor { pub fn new(config: SharedSupervisorConfig, supervision: SharedSupervision) -> Self { Self { - config, + config: std::sync::Arc::new(config), supervision, } } - /// Keep the supervisor token Secret current with every token the gateway - /// publishes, until shutdown. The Secret itself is deployment packaging - /// (the chart creates it empty); the driver only replaces its token. + /// Keep the supervisor token Secret, and the external enforcer's token + /// Secret when configured, current with every token the gateway + /// publishes, until shutdown. The Secrets themselves are deployment + /// packaging (the chart creates them empty); the driver only replaces + /// their tokens. pub fn spawn_token_secret_writer( &self, client: kube::Client, shutdown_rx: tokio::sync::watch::Receiver, + external_enforcer: Option<&ExternalEnforcerConfig>, ) { - let secrets = Api::::namespaced(client, &self.config.service_namespace); - let name = self.config.token_secret_name.clone(); - tokio::spawn(deliver_credentials( + let mut writers = vec![( + Api::::namespaced(client.clone(), &self.config.service_namespace), + self.config.token_secret_name.clone(), self.supervision.credentials(), - shutdown_rx, - TOKEN_WRITE_RETRY, - move |credential| { - let secrets = secrets.clone(); - let name = name.clone(); - async move { write_token_secret(&secrets, &name, &credential).await } - }, - )); + )]; + if let Some(enforcer) = external_enforcer { + writers.push(( + Api::::namespaced(client, &enforcer.namespace), + enforcer.token_secret_name.clone(), + self.supervision.enforcer_credentials(), + )); + } + for (secrets, name, credentials) in writers { + tokio::spawn(deliver_credentials( + credentials, + shutdown_rx.clone(), + TOKEN_WRITE_RETRY, + move |credential| { + let secrets = secrets.clone(); + let name = name.clone(); + async move { write_token_secret(&secrets, &name, &credential).await } + }, + )); + } } pub fn config(&self) -> &SharedSupervisorConfig { @@ -154,19 +177,19 @@ async fn write_token_secret( .await .map_err(|error| match &error { kube::Error::Api(response) if response.code == 404 => format!( - "the supervisor token Secret {name} does not exist; the chart creates it, \ - restore it (helm upgrade) so the shared supervisor can authenticate" + "the token Secret {name} does not exist; the chart creates it, restore it \ + (helm upgrade) so its host can authenticate" ), kube::Error::Api(response) if response.code == 403 => format!( - "the gateway may not patch the supervisor token Secret {name}; check the \ + "the gateway may not patch the token Secret {name}; check the \ chart's gateway Role" ), - _ => format!("failed to write the supervisor token Secret {name}: {error}"), + _ => format!("failed to write the token Secret {name}: {error}"), })?; info!( secret = %name, expires_at = credential.expires_at, - "wrote the supervisor token Secret" + "wrote the host token Secret" ); Ok(()) } diff --git a/crates/openshell-gateway/src/lib.rs b/crates/openshell-gateway/src/lib.rs index 46bbe0a3e0..3c88fb3809 100644 --- a/crates/openshell-gateway/src/lib.rs +++ b/crates/openshell-gateway/src/lib.rs @@ -245,6 +245,15 @@ impl openshell_server::ComputeDriverFactory for KubernetesFactory { Ok(kubernetes_config(context)?.shared_supervisor.is_some()) } + fn native_network( + &self, + context: openshell_server::ComputeDriverConfigContext<'_>, + ) -> openshell_core::Result>> { + Ok(kubernetes_config(context)? + .external_enforcer() + .map(|enforcer| enforcer.nameservers().to_vec())) + } + async fn build( &self, context: openshell_server::ComputeDriverBuildContext<'_>, @@ -269,23 +278,17 @@ impl openshell_server::ComputeDriverFactory for KubernetesFactory { config.supervisor_gateway_name = Some(context.gateway_name().to_string()); // With the gateway supervisor topology, the gateway owns the shared // supervisor's assignments and token; the driver adapts them to - // Kubernetes objects. The experimental shared supervisor topology - // does not support the network supervisor additional destination CA; - // refuse the combination fail-closed rather than silently - // supervising generations without the operator's trust bundle. + // Kubernetes objects. let network_trust = context.network_trust_bundle().cloned(); let driver = if config.shared_supervisor.is_some() { - if network_trust.is_some() { - return Err(openshell_core::Error::execution( - "the experimental shared supervisor topology does not support the \ - network supervisor additional destination CA" - .to_string(), - )); - } openshell_driver_kubernetes::KubernetesComputeDriver::with_shared_supervision( config, context.shutdown_receiver(), context.shared_supervision(), + network_trust, + context + .otlp_config() + .map_or(0, OtlpConfig::supervisor_tls_bytes), ) .await } else { diff --git a/crates/openshell-sandbox-backend/README.md b/crates/openshell-sandbox-backend/README.md index f64330c8da..930bc7cdac 100644 --- a/crates/openshell-sandbox-backend/README.md +++ b/crates/openshell-sandbox-backend/README.md @@ -197,7 +197,8 @@ preface: `OSRP`, version `1`, a length byte, and an opaque route handle of 16 to 64 lowercase letters, digits, or hyphens. The handle is untrusted; it only selects which instance's generation-pinned TLS identity the supervisor then demands. Unknown, removed, and replaced handles are closed before any -handshake. Handshakes are bounded globally and per route, and an +handshake. Handshakes are bounded globally and per route, each source address +keeps one handshake outside the global bound, and an authenticated connection only fills its own instance's spare queue. A routed instance waits up to its configured initial attachment budget (five minutes by default) for its first connection, since it is registered before its diff --git a/crates/openshell-sandbox-backend/src/lib.rs b/crates/openshell-sandbox-backend/src/lib.rs index 3df3f90ef7..8e435eaeb9 100644 --- a/crates/openshell-sandbox-backend/src/lib.rs +++ b/crates/openshell-sandbox-backend/src/lib.rs @@ -37,6 +37,23 @@ pub const BACKEND_NAME: &str = openshell_core::isolation_registration::BUILTIN_B /// Resource claim set by compute drivers when the workload requests GPU access. pub const GPU_RESOURCE_CLAIM: &str = "openshell.gpu"; +/// Resource claim that selects native-network mode. +/// +/// The Kubernetes driver sets it on every new runtime when its workload +/// network sets `native_network`. An enforcer outside the sandbox then +/// enforces network policy, so the runtime hands agent sockets to the kernel +/// instead of mediating them. +pub const NATIVE_NETWORK_RESOURCE_CLAIM: &str = "openshell.native_network"; + +/// Whether `claims` select native-network mode. The supervisor and the +/// sandbox both decide with this, so they agree on the mode. +#[must_use] +pub fn native_network_claimed(claims: &std::collections::BTreeMap) -> bool { + claims + .get(NATIVE_NETWORK_RESOURCE_CLAIM) + .is_some_and(|value| value == "true") +} + /// Resource claim set when the runtime may retain supplementary groups in /// addition to the image-derived workload identity. pub const ALLOW_EXTRA_SUPPLEMENTARY_GROUPS_RESOURCE_CLAIM: &str = diff --git a/crates/openshell-sandbox-backend/src/runtime_routed.rs b/crates/openshell-sandbox-backend/src/runtime_routed.rs index f3d959dd38..0b0c8d55ee 100644 --- a/crates/openshell-sandbox-backend/src/runtime_routed.rs +++ b/crates/openshell-sandbox-backend/src/runtime_routed.rs @@ -27,8 +27,9 @@ //! request still carries the bearer token. use std::collections::{HashMap, HashSet}; -use std::net::SocketAddr; -use std::sync::{Arc, Mutex}; +use std::net::{IpAddr, SocketAddr}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use async_trait::async_trait; @@ -57,8 +58,10 @@ const ROUTE_REPLY_REDIRECT: u8 = 0x02; const ROUTE_REPLY_UNKNOWN: u8 = 0x03; /// Unauthenticated sockets the listener handshakes at once, across sandbox -/// instances. +/// instances, beyond each source's free slot. const MAX_PENDING_HANDSHAKES: usize = 64; +/// Bounds the memory of tracking free-slot sources; see `admit`. +const MAX_FREE_SLOTS: usize = 1024; /// Unauthenticated sockets naming one handle; one handle cannot exhaust the /// listener for every other sandbox instance. const MAX_PENDING_HANDSHAKES_PER_ROUTE: usize = 4; @@ -491,12 +494,71 @@ impl Drop for RouteRegistration { } } -fn lock(routes: &Mutex) -> std::sync::MutexGuard<'_, Routes> { - routes +fn lock(mutex: &Mutex) -> MutexGuard<'_, T> { + mutex .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) } +/// Sources holding their one handshake outside the shared bound. +#[derive(Default)] +struct FreeSlots { + taken: Mutex>, + exhausted_warned: AtomicBool, +} + +struct FreeSlot { + slots: Arc, + source: IpAddr, +} + +impl FreeSlots { + fn try_take(self: &Arc, source: IpAddr) -> Option { + let mut taken = lock(&self.taken); + if taken.len() >= MAX_FREE_SLOTS { + if !self.exhausted_warned.swap(true, Ordering::Relaxed) { + tracing::warn!("routed runtime free handshake slots exhausted"); + } + return None; + } + taken.insert(source).then(|| FreeSlot { + slots: self.clone(), + source, + }) + } +} + +impl Drop for FreeSlot { + fn drop(&mut self) { + let mut taken = lock(&self.slots.taken); + taken.remove(&self.source); + // Half the cap re-arms the warning, so a listener that stays + // saturated warns once per episode rather than per handshake. + if taken.len() <= MAX_FREE_SLOTS / 2 { + self.slots.exhausted_warned.store(false, Ordering::Relaxed); + } + } +} + +enum HandshakePermit { + Free { _slot: FreeSlot }, + Shared { _permit: OwnedSemaphorePermit }, +} + +/// The first pending handshake of each of up to `MAX_FREE_SLOTS` sources is +/// admitted outside the shared bound; any other needs a shared permit. +fn admit( + free: &Arc, + shared: &Arc, + source: IpAddr, +) -> Option { + if let Some(slot) = free.try_take(source.to_canonical()) { + return Some(HandshakePermit::Free { _slot: slot }); + } + let permit = shared.clone().try_acquire_owned().ok()?; + Some(HandshakePermit::Shared { _permit: permit }) +} + fn bind_tcp(address: SocketAddr) -> std::io::Result { let socket = socket2::Socket::new( socket2::Domain::for_address(address), @@ -510,16 +572,18 @@ fn bind_tcp(address: SocketAddr) -> std::io::Result { tokio::net::TcpListener::from_std(socket.into()) } -/// Route each accepted socket within global and per-handle handshake bounds. +/// Route each accepted socket within the bounds `admit` and +/// `route_connection` enforce. async fn accept_loop(listener: tokio::net::TcpListener, routes: Arc>) { + let free = Arc::new(FreeSlots::default()); let pending = Arc::new(Semaphore::new(MAX_PENDING_HANDSHAKES)); // Owned here so aborting the listener also cancels pending handshakes. let mut handshakes = tokio::task::JoinSet::new(); loop { tokio::select! { accepted = listener.accept() => { - let stream = match accepted { - Ok((stream, _)) => stream, + let (stream, peer) = match accepted { + Ok(accepted) => accepted, Err(error) => { // Descriptor exhaustion and similar errors are transient. tracing::warn!(%error, "routed runtime accept failed"); @@ -527,8 +591,12 @@ async fn accept_loop(listener: tokio::net::TcpListener, routes: Arc, - _listener_permit: OwnedSemaphorePermit, + _permit: HandshakePermit, ) -> Result<(), String> { let deadline = tokio::time::Instant::now() + HANDSHAKE_TIMEOUT; let (version, handle) = tokio::time::timeout_at(deadline, read_route_preface(&mut stream)) @@ -1033,4 +1101,61 @@ mod tests { assert!(negotiate_scripted(malformed).await.0.is_err()); } } + + fn source(index: u32) -> IpAddr { + IpAddr::V4(std::net::Ipv4Addr::from(0x0a00_0000 + index)) + } + + #[test] + fn each_source_keeps_one_handshake_outside_the_shared_bound() { + let free = Arc::new(FreeSlots::default()); + let shared = Arc::new(Semaphore::new(MAX_PENDING_HANDSHAKES)); + let first = admit(&free, &shared, source(0)).unwrap(); + assert!(matches!(first, HandshakePermit::Free { .. })); + let mut flood = Vec::new(); + while let Some(permit) = admit(&free, &shared, source(0)) { + assert!(matches!(permit, HandshakePermit::Shared { .. })); + flood.push(permit); + } + assert_eq!(flood.len(), MAX_PENDING_HANDSHAKES); + let others = (1..=u32::try_from(MAX_PENDING_HANDSHAKES).unwrap() + 1) + .map(|index| admit(&free, &shared, source(index)).unwrap()) + .collect::>(); + assert!( + others + .iter() + .all(|permit| matches!(permit, HandshakePermit::Free { .. })) + ); + // An IPv4-mapped peer is its IPv4 source. + let mapped = match source(1) { + IpAddr::V4(address) => IpAddr::V6(address.to_ipv6_mapped()), + IpAddr::V6(_) => unreachable!(), + }; + assert!(admit(&free, &shared, mapped).is_none()); + + drop((first, flood, others)); + assert!(lock(&free.taken).is_empty()); + assert_eq!(shared.available_permits(), MAX_PENDING_HANDSHAKES); + } + + #[test] + fn sources_past_the_free_slot_bound_share_the_global_bound() { + let free = Arc::new(FreeSlots::default()); + let shared = Arc::new(Semaphore::new(1)); + let bound = u32::try_from(MAX_FREE_SLOTS).unwrap(); + let held = (0..bound) + .map(|index| admit(&free, &shared, source(index)).unwrap()) + .collect::>(); + assert!(!free.exhausted_warned.load(Ordering::Relaxed)); + let fallback = admit(&free, &shared, source(bound)).unwrap(); + assert!(matches!(fallback, HandshakePermit::Shared { .. })); + assert!(free.exhausted_warned.load(Ordering::Relaxed)); + assert!(admit(&free, &shared, source(bound + 1)).is_none()); + drop((held, fallback)); + assert!(lock(&free.taken).is_empty()); + assert!( + !free.exhausted_warned.load(Ordering::Relaxed), + "draining the free slots re-arms the warning" + ); + } } diff --git a/crates/openshell-sandbox/README.md b/crates/openshell-sandbox/README.md index 1f2bce2033..933c3d34cb 100644 --- a/crates/openshell-sandbox/README.md +++ b/crates/openshell-sandbox/README.md @@ -69,6 +69,22 @@ endpoint in the image `ENV` does the same for the main process; exec children start from a cleared environment (`ChildEnvironment::Cleared`), never see the image's endpoint, and still get the relay default. +## Native-network mode + +The `openshell.native_network = "true"` resource claim +(`openshell_sandbox_backend::native_network_claimed`) selects +native-network mode for the sandbox's life. An external enforcer filters the +workload's connections, so `install_workload_listener(true)` notifies only +signals, opens, and the scheduling, priority, and resource-limit calls, the kernel creates the workload's sockets with no broker +registration or loopback pinning, and the workload resolves through the +driver's configured `nameservers`. The DNS relay on `127.0.0.53` serves only +registered sockets, so it serves nothing in this mode. The broker +doesn't refuse connections to the protected control port; the routed runtime +listener's per-source admission bounds that exposure. The socket domain +allowlist, the ptrace, BPF, `io_uring`, and mount blocks, Landlock, child +self-protection, close-on-exec, and the runtime control connection are +unchanged. + ## Supervisor takeover The boundary advertises `openshell.sandbox.supervisor-takeover`. A replacement diff --git a/crates/openshell-sandbox/src/boundary_exec.rs b/crates/openshell-sandbox/src/boundary_exec.rs index 40c433adff..28a9606cf8 100644 --- a/crates/openshell-sandbox/src/boundary_exec.rs +++ b/crates/openshell-sandbox/src/boundary_exec.rs @@ -190,8 +190,8 @@ impl LocalBoundaryExec { command.env(key, value); } } - if let Some((ca_cert_path, combined_bundle_path)) = self.ca_file_paths.as_deref() { - for (key, value) in crate::child_env::tls_env_vars(ca_cert_path, combined_bundle_path) { + if let Some((_, combined_bundle_path)) = self.ca_file_paths.as_deref() { + for (key, value) in crate::child_env::tls_env_vars(combined_bundle_path) { command.env(key, value); } } diff --git a/crates/openshell-sandbox/src/boundary_server.rs b/crates/openshell-sandbox/src/boundary_server.rs index 7a74565139..670111cdc7 100644 --- a/crates/openshell-sandbox/src/boundary_server.rs +++ b/crates/openshell-sandbox/src/boundary_server.rs @@ -276,7 +276,8 @@ mod linux { } crate::managed_children::start_orphan_reaper() .map_err(|error| format!("start sandbox orphan reaper: {error}"))?; - let (launcher, listener) = crate::linux::workload_launcher::start() + let native_network = announce_native_network(&config.resource_claims); + let (launcher, listener) = crate::linux::workload_launcher::start_with(native_network) .map_err(|error| format!("start sandbox workload launcher: {error}"))?; let protected_control_port = match &config.listener { BoundaryListenerConfig::TlsTcp { address, .. } => Some(address.port()), @@ -508,6 +509,25 @@ mod linux { tls.certificate_chain_path.is_absolute() && tls.private_key_path.is_absolute() } + /// Whether the claims select native-network mode, fixed for the sandbox's + /// life. + fn announce_native_network(claims: &std::collections::BTreeMap) -> bool { + let native_network = openshell_sandbox_backend::native_network_claimed(claims); + if native_network { + openshell_ocsf::ocsf_emit!( + openshell_ocsf::ConfigStateChangeBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(openshell_ocsf::SeverityId::Informational) + .status(openshell_ocsf::StatusId::Success) + .state(openshell_ocsf::StateId::Enabled, "native_network") + .message( + "Native-network mode enabled; an external enforcer filters workload connections", + ) + .build() + ); + } + native_network + } + fn validate_runtime_resource_claims(config: &BoundaryConfig) -> Result<(), String> { for (claim, path) in &config.resource_claim_files { let expected = config @@ -5827,6 +5847,38 @@ mod linux { assert!(allows_runtime_supplementary_groups(&config)); } + #[test] + fn native_network_is_announced_only_when_claimed() { + let claim = openshell_sandbox_backend::NATIVE_NETWORK_RESOURCE_CLAIM; + for (claims, expected) in [ + (std::collections::BTreeMap::new(), false), + ( + std::collections::BTreeMap::from([(claim.to_string(), "false".to_string())]), + false, + ), + ( + std::collections::BTreeMap::from([(claim.to_string(), "true".to_string())]), + true, + ), + ] { + let capture = openshell_ocsf::test_support::OcsfCapture::default(); + let _capture = capture.install(); + assert_eq!(announce_native_network(&claims), expected); + let events = capture.json_events(); + if expected { + assert_eq!(events.len(), 1); + assert_eq!(events[0]["class_uid"], 5019); + assert!( + events[0]["message"] + .as_str() + .is_some_and(|message| message.contains("Native-network mode enabled")) + ); + } else { + assert!(events.is_empty()); + } + } + } + #[test] fn control_connection_slots_bound_authenticated_sessions() { let active = Arc::new(AtomicUsize::new(MAX_CONTROL_CONNECTIONS - 1)); diff --git a/crates/openshell-sandbox/src/child_env.rs b/crates/openshell-sandbox/src/child_env.rs index 5d9c90a20f..5996a993f6 100644 --- a/crates/openshell-sandbox/src/child_env.rs +++ b/crates/openshell-sandbox/src/child_env.rs @@ -33,12 +33,11 @@ pub fn is_tls_environment_variable(key: &str) -> bool { } pub fn tls_env_vars_for_mode( - ca_cert_path: &Path, combined_bundle_path: &Path, mode: TlsEnvironmentMode, user_environment: &HashMap, ) -> Vec<(&'static str, String)> { - tls_env_vars(ca_cert_path, combined_bundle_path) + tls_env_vars(combined_bundle_path) .into_iter() .filter(|(key, _)| { matches!(mode, TlsEnvironmentMode::Override) || !user_environment.contains_key(*key) @@ -164,15 +163,13 @@ impl EnvTarget for tokio::process::Command { } } -pub fn tls_env_vars( - ca_cert_path: &Path, - combined_bundle_path: &Path, -) -> [(&'static str, String); 6] { - let ca_cert_path = ca_cert_path.display().to_string(); +/// Every variable names the combined bundle: an external enforcer re-signs +/// with the operator's additional CA, which the bundle alone carries. +pub fn tls_env_vars(combined_bundle_path: &Path) -> [(&'static str, String); 6] { let combined_bundle_path = combined_bundle_path.display().to_string(); [ - ("NODE_EXTRA_CA_CERTS", ca_cert_path.clone()), - ("DENO_CERT", ca_cert_path), + ("NODE_EXTRA_CA_CERTS", combined_bundle_path.clone()), + ("DENO_CERT", combined_bundle_path.clone()), ("SSL_CERT_FILE", combined_bundle_path.clone()), ("REQUESTS_CA_BUNDLE", combined_bundle_path.clone()), ("CURL_CA_BUNDLE", combined_bundle_path.clone()), @@ -195,29 +192,28 @@ mod tests { .stdout(Stdio::piped()) .stderr(Stdio::null()); - let ca_cert_path = Path::new("/etc/openshell-tls/openshell-ca.pem"); let combined_bundle_path = Path::new("/etc/openshell-tls/ca-bundle.pem"); - for (key, value) in tls_env_vars(ca_cert_path, combined_bundle_path) { + for (key, value) in tls_env_vars(combined_bundle_path) { cmd.env(key, value); } let output = cmd.output().expect("spawn env"); let stdout = String::from_utf8(output.stdout).expect("utf8"); - assert!(stdout.contains("NODE_EXTRA_CA_CERTS=/etc/openshell-tls/openshell-ca.pem")); - assert!(stdout.contains("DENO_CERT=/etc/openshell-tls/openshell-ca.pem")); + assert!(stdout.contains("NODE_EXTRA_CA_CERTS=/etc/openshell-tls/ca-bundle.pem")); + assert!(stdout.contains("DENO_CERT=/etc/openshell-tls/ca-bundle.pem")); assert!(stdout.contains("SSL_CERT_FILE=/etc/openshell-tls/ca-bundle.pem")); assert!(stdout.contains("REQUESTS_CA_BUNDLE=/etc/openshell-tls/ca-bundle.pem")); assert!(stdout.contains("CURL_CA_BUNDLE=/etc/openshell-tls/ca-bundle.pem")); assert!(stdout.contains("GIT_SSL_CAINFO=/etc/openshell-tls/ca-bundle.pem")); - let keys = tls_env_vars(ca_cert_path, combined_bundle_path).map(|(key, _)| key); + let keys = tls_env_vars(combined_bundle_path).map(|(key, _)| key); assert!( !keys.contains(&openshell_core::sandbox_env::TLS_CA), "destination/child trust must not overwrite gateway mTLS trust" ); assert_ne!( - ca_cert_path, + combined_bundle_path, Path::new(openshell_core::container_paths::TLS_CA_MOUNT_PATH) ); } diff --git a/crates/openshell-sandbox/src/linux/process_signal.rs b/crates/openshell-sandbox/src/linux/process_signal.rs index c77a797584..9b1f1e107c 100644 --- a/crates/openshell-sandbox/src/linux/process_signal.rs +++ b/crates/openshell-sandbox/src/linux/process_signal.rs @@ -294,7 +294,7 @@ mod tests { fn filtered_worker_cannot_signal_the_sandbox_through_a_tid() { let (sender, receiver) = std::sync::mpsc::sync_channel(1); let worker = std::thread::spawn(move || { - let listener = crate::linux::seccomp_notify::install_workload_listener().unwrap(); + let listener = crate::linux::seccomp_notify::install_workload_listener(false).unwrap(); sender.send(listener).unwrap(); // SAFETY: gettid has no arguments; signal zero checks permission // without delivering a signal to the disposable test thread. @@ -354,7 +354,7 @@ mod tests { let (sender, receiver) = std::sync::mpsc::sync_channel(1); let target = u32::try_from(child).expect("child PID fits u32"); let worker = std::thread::spawn(move || { - let listener = crate::linux::seccomp_notify::install_workload_listener().unwrap(); + let listener = crate::linux::seccomp_notify::install_workload_listener(false).unwrap(); sender.send(listener).unwrap(); let info = queued_siginfo(); // SAFETY: `info` outlives the kernel's copy; the worker blocks in diff --git a/crates/openshell-sandbox/src/linux/seccomp_notify.rs b/crates/openshell-sandbox/src/linux/seccomp_notify.rs index b45dbccd93..ca1d5064fc 100644 --- a/crates/openshell-sandbox/src/linux/seccomp_notify.rs +++ b/crates/openshell-sandbox/src/linux/seccomp_notify.rs @@ -354,17 +354,26 @@ pub fn install_listener(syscalls: &[i64]) -> io::Result { /// `sendto()` retains the audited cBPF fast path. `accept`/`accept4` run /// natively: the broker binds every INET socket to loopback before injecting /// it, and accepted sockets inherit their listener's binding. -pub fn install_workload_listener() -> io::Result { - #[allow(unused_mut)] // SYS_open is unavailable on some architectures. - let mut syscalls = vec![ - libc::SYS_socket, - libc::SYS_connect, - libc::SYS_bind, - libc::SYS_listen, - libc::SYS_sendto, - libc::SYS_sendmsg, - libc::SYS_sendmmsg, - libc::SYS_setsockopt, +/// +/// With `native_network`, an external enforcer filters the workload's +/// connections, so only signals, opens, and the scheduling, priority, and +/// resource-limit calls notify, and the kernel creates the workload's sockets. +pub fn install_workload_listener(native_network: bool) -> io::Result { + let mut syscalls = if native_network { + Vec::new() + } else { + vec![ + libc::SYS_socket, + libc::SYS_connect, + libc::SYS_bind, + libc::SYS_listen, + libc::SYS_sendto, + libc::SYS_sendmsg, + libc::SYS_sendmmsg, + libc::SYS_setsockopt, + ] + }; + syscalls.extend([ libc::SYS_kill, libc::SYS_tkill, libc::SYS_tgkill, @@ -372,7 +381,7 @@ pub fn install_workload_listener() -> io::Result { libc::SYS_rt_sigqueueinfo, libc::SYS_openat, libc::SYS_openat2, - ]; + ]); syscalls.extend( crate::linux::process_sched::MEDIATED_PROCESS_SCHED_SYSCALLS .iter() diff --git a/crates/openshell-sandbox/src/linux/workload_launcher.rs b/crates/openshell-sandbox/src/linux/workload_launcher.rs index 26431a2a81..a8e1084b81 100644 --- a/crates/openshell-sandbox/src/linux/workload_launcher.rs +++ b/crates/openshell-sandbox/src/linux/workload_launcher.rs @@ -72,6 +72,12 @@ impl WorkloadLauncher { /// Start the only workload launcher and return its listener to an unfiltered /// sandbox thread. pub fn start() -> io::Result<(WorkloadLauncher, NotificationListener)> { + start_with(false) +} + +/// Start the launcher with the listener filter for `native_network`; see +/// [`install_workload_listener`]. +pub fn start_with(native_network: bool) -> io::Result<(WorkloadLauncher, NotificationListener)> { let (jobs_tx, jobs_rx) = mpsc::sync_channel::(64); let (ready_tx, ready_rx) = mpsc::sync_channel(1); let alive = Arc::new(AtomicBool::new(true)); @@ -79,7 +85,7 @@ pub fn start() -> io::Result<(WorkloadLauncher, NotificationListener)> { thread::Builder::new() .name("openshell-workload-launcher".to_string()) .spawn(move || { - match install_workload_listener() { + match install_workload_listener(native_network) { Ok(listener) => { if ready_tx.send(Ok(listener)).is_err() { thread_alive.store(false, Ordering::Release); diff --git a/crates/openshell-sandbox/src/network_broker.rs b/crates/openshell-sandbox/src/network_broker.rs index 761f281ba3..9596271f67 100644 --- a/crates/openshell-sandbox/src/network_broker.rs +++ b/crates/openshell-sandbox/src/network_broker.rs @@ -3767,6 +3767,55 @@ mod tests { ); } + #[test] + fn native_network_filter_leaves_inet_sockets_to_the_kernel() { + let control = TcpListener::bind("127.0.0.1:0").unwrap(); + let control_address = control.local_addr().unwrap(); + let (launcher, listener) = + crate::linux::workload_launcher::start_with(true).expect("start workload launcher"); + let broker = NetworkBroker::start_with_dns_address( + listener, + "127.0.0.1:0".parse().unwrap(), + Some(control_address.port()), + ) + .expect("start network broker"); + let receiver = UdpSocket::bind("127.0.0.1:0").unwrap(); + receiver + .set_read_timeout(Some(Duration::from_secs(2))) + .unwrap(); + let receiver_address = receiver.local_addr().unwrap(); + let (service, client, unconnected, connected) = launcher + .execute(move || -> io::Result<_> { + let service = TcpListener::bind("127.0.0.1:0")?; + let client = TcpStream::connect(service.local_addr()?)?; + // No broker refuses the protected port in this mode. + drop(TcpStream::connect(control_address)?); + let unconnected = UdpSocket::bind("127.0.0.1:0")?; + unconnected.send_to(b"a", receiver_address)?; + let connected = UdpSocket::bind("127.0.0.1:0")?; + connected.connect(receiver_address)?; + connected.send(b"b")?; + Ok((service, client, unconnected, connected)) + }) + .expect("launcher result") + .expect("kernel-created sockets"); + let registry = lock(&broker.registry); + for socket in [ + service.as_raw_fd(), + client.as_raw_fd(), + unconnected.as_raw_fd(), + connected.as_raw_fd(), + ] { + assert!(registry.resolve(std::process::id(), socket).is_err()); + } + drop(registry); + assert!(control.accept().is_ok()); + let mut datagram = [0_u8; 1]; + for _ in 0..2 { + assert_eq!(receiver.recv(&mut datagram).unwrap(), 1); + } + } + #[test] fn dns_tcp_accept_errors_map_to_keep_serving_actions() { for error in [ @@ -4071,8 +4120,16 @@ mod tests { /// The launcher thread inherits the workload listener, so every mediated /// syscall inside `operation` blocks until the broker answers it. fn mediated(operation: impl FnOnce() -> T + Send + 'static) -> T { - let (launcher, listener) = - crate::linux::workload_launcher::start().expect("start workload launcher"); + mediated_with(false, operation) + } + + /// [`mediated`] under the listener filter for `native_network`. + fn mediated_with( + native_network: bool, + operation: impl FnOnce() -> T + Send + 'static, + ) -> T { + let (launcher, listener) = crate::linux::workload_launcher::start_with(native_network) + .expect("start workload launcher"); let _broker = NetworkBroker::start_for_test(listener).expect("start network broker"); launcher.execute(operation).expect("launcher result") } @@ -4355,27 +4412,34 @@ mod tests { .spawn() .expect("spawn target"); let target_tgid = libc::pid_t::try_from(target.id()).expect("target PID fits pid_t"); - let (affinity, limits) = mediated(move || { - // SAFETY: the target is this test's live disposable child, the - // affinity mask is the caller's own, and both limit pointers are - // null, so the continued call would only validate the target. - unsafe { - ( - affinity_errno(target_tgid), - errno(libc::syscall( - libc::SYS_prlimit64, - target_tgid, - libc::c_long::from(libc::RLIMIT_CORE), - std::ptr::null::(), - std::ptr::null::(), - )), - ) - } - }); + for native_network in [false, true] { + let (affinity, limits) = mediated_with(native_network, move || { + // SAFETY: the target is this test's live disposable child, the + // affinity mask is the caller's own, and both limit pointers + // are null, so the continued call would only validate the + // target. + unsafe { + ( + affinity_errno(target_tgid), + errno(libc::syscall( + libc::SYS_prlimit64, + target_tgid, + libc::c_long::from(libc::RLIMIT_CORE), + std::ptr::null::(), + std::ptr::null::(), + )), + ) + } + }); + assert_eq!( + affinity, + Some(libc::EPERM), + "native_network={native_network}" + ); + assert_eq!(limits, Some(libc::EPERM), "native_network={native_network}"); + } let _ = target.kill(); let _ = target.wait(); - assert_eq!(affinity, Some(libc::EPERM)); - assert_eq!(limits, Some(libc::EPERM)); } /// The broker resolves every `sched_set*` target against the caller's diff --git a/crates/openshell-sandbox/src/process.rs b/crates/openshell-sandbox/src/process.rs index 4967d20086..d75930fa1f 100644 --- a/crates/openshell-sandbox/src/process.rs +++ b/crates/openshell-sandbox/src/process.rs @@ -303,7 +303,7 @@ fn compose_canonical_process_environment( strip_proxy_env(cmd); // In interception mode OpenShell trust is authoritative. In direct // additional-CA mode, retain all caller values and only fill gaps. - if let Some((ca_cert_path, combined_bundle_path)) = ca_paths { + if let Some((_, combined_bundle_path)) = ca_paths { // Provider credentials are injected before this point. Reassert // caller TLS values in additive mode so a provider environment // cannot accidentally replace a caller-selected trust store. @@ -318,7 +318,6 @@ fn compose_canonical_process_environment( } } for (key, value) in child_env::tls_env_vars_for_mode( - ca_cert_path, combined_bundle_path, tls_environment_mode, user_environment, @@ -1570,9 +1569,7 @@ mod tests { PathBuf::from("/etc/openshell-tls/ca-bundle.pem"), ); let openshell_trust: HashMap<&str, String> = - child_env::tls_env_vars(&ca_paths.0, &ca_paths.1) - .into_iter() - .collect(); + child_env::tls_env_vars(&ca_paths.1).into_iter().collect(); let declared = HashMap::from([("SSL_CERT_FILE".to_string(), "/caller.pem".to_string())]); let provider_env = HashMap::from([ ("SSL_CERT_FILE".to_string(), "/provider.pem".to_string()), diff --git a/crates/openshell-sdk/src/client.rs b/crates/openshell-sdk/src/client.rs index 7d11bf3e9c..032241cb0e 100644 --- a/crates/openshell-sdk/src/client.rs +++ b/crates/openshell-sdk/src/client.rs @@ -1056,13 +1056,15 @@ impl OpenShellClient { workspace: &str, options: CreateRetryOptions, ) -> Result { - self.create_with_retry_using( + // The retry loop holds whole sandbox responses; keep it off the + // caller's stack (clippy::large_futures). + Box::pin(self.create_with_retry_using( request, workspace, options, create_retry_seed(), tokio::time::sleep, - ) + )) .await } diff --git a/crates/openshell-sdk/tests/sandbox_status_compatibility.rs b/crates/openshell-sdk/tests/sandbox_status_compatibility.rs index 7a080a381f..aed0d8ee33 100644 --- a/crates/openshell-sdk/tests/sandbox_status_compatibility.rs +++ b/crates/openshell-sdk/tests/sandbox_status_compatibility.rs @@ -26,6 +26,7 @@ fn baseline_exhaustive_sandbox_status_literal_still_compiles() { next_restart_time: None, main_process_started_time: None, last_token_grant_failure: None, + enforcer_admission: None, }; assert_eq!(status, SandboxStatus::default()); } diff --git a/crates/openshell-server/README.md b/crates/openshell-server/README.md index 61e458a23f..a79687cd01 100644 --- a/crates/openshell-server/README.md +++ b/crates/openshell-server/README.md @@ -123,6 +123,48 @@ or two minutes after the withdrawal, after their owner was told to stop them. Pool members still authenticate with the one shared supervisor token, so a member identity is asserted by its hello rather than bound to its Pod. +## Native-network enforcer + +In native-network mode a host enforcer applies each sandbox's network policy, +and the gateway treats it as a second party to the sandbox's configuration. +The enforcer selects a sandbox by `GetSandboxConfigRequest.sandbox_id`, which +other callers must leave empty, and reads the configuration without the +activation hold, with the sandbox's runtime generation as +`configuration_instance_id`. It reports `ACCEPTED` or `REJECTED` for that +generation through `ReportSandboxConfiguration`, under the sandbox's mutation +guard, and the gateway stores the verdict as `SandboxStatus.enforcer_admission`. +`ACCEPTED` must name the admitted policy version, hash, config revision, and +provider environment revision, or the report is `ABORTED`. A rejection after an +acceptance keeps the accepted tuple and records only the error. + +- **Activation hold.** Until the supervisor first accepts a configuration, its + snapshot is not admitted and sets `activation_pending` while the enforcer + has not accepted the current generation. The supervisor waits without + reporting. An enforcer rejection of the current policy hash and provider + environment revision replaces the wait with the enforcer's message, so the + supervisor reports the rejection. Readiness shows `EnforcerPending` while + the hold lasts. Snapshots carry the enforcer's accepted provider environment + revision as `enforcer_provider_env_revision`. +- **Two-sided policy status.** A revision becomes the current policy version + once both the supervisor and the enforcer accept it. Policy + status shows a revision the supervisor loaded as `PENDING` until then. An + enforcer rejection of a newer revision marks it `failed` with a load error + prefixed `enforcer:`, which a later supervisor load does not clear. A later + enforcer acceptance of that revision returns it to `loaded` if the supervisor + loaded it, otherwise to `pending`. A rejection of a revision the enforcer + already accepted, or of a configuration that has since changed, changes no + revision; a rejection of the exact configuration the enforcer accepted is + ignored entirely, since it comes from a replica that lost the sandbox. +- **Credentials.** The enforcer reads `GetSandboxProviderEnvironment` by + sandbox ID, and each static credential carries the placeholder the workload + receives (`workload_placeholder`, from `openshell_core::secrets`, which the + supervisor's resolver uses too). A polling supervisor installs a rotated + provider revision only once it equals `enforcer_provider_env_revision`, so + new processes never present placeholders the enforcer doesn't know. +- **Middleware.** The enforcer runs the middleware chain, so snapshots carry + no `supervisor_middleware_services`, and policy validation and the + snapshot's registration check reject built-in `openshell/` middleware. + ## Optional in-process sandbox updates `SharedComputeDriver` retains the generated baseline compute-driver trait, and diff --git a/crates/openshell-server/src/auth/method_authz.rs b/crates/openshell-server/src/auth/method_authz.rs index fcdc1e25df..4f7c58e60f 100644 --- a/crates/openshell-server/src/auth/method_authz.rs +++ b/crates/openshell-server/src/auth/method_authz.rs @@ -129,10 +129,34 @@ pub fn is_supervisor_callable(method: &str) -> bool { ) } +/// Methods an external enforcer host may call with its enforcer token: the +/// assignment stream, and the reads and acknowledgement it makes for the +/// sandboxes it enforces. The handlers admit the enforcer only in +/// native-network mode. +pub const ENFORCER_METHODS: [&str; 4] = [ + "/openshell.supervisor.host.v1.SupervisorHost/Attach", + "/openshell.v1.OpenShell/GetSandboxConfig", + "/openshell.v1.OpenShell/GetSandboxProviderEnvironment", + "/openshell.v1.OpenShell/ReportSandboxConfiguration", +]; + +/// `true` if the method is callable by an external enforcer host. +#[must_use] +pub fn is_enforcer_callable(method: &str) -> bool { + ENFORCER_METHODS.contains(&method) +} + #[cfg(test)] mod tests { use super::*; + #[test] + fn enforcer_methods_exist() { + for path in ENFORCER_METHODS { + assert!(lookup(path).is_some(), "{path}"); + } + } + /// Every RPC path in the descriptor pool is resolvable through this /// delegation layer. #[test] diff --git a/crates/openshell-server/src/auth/peer.rs b/crates/openshell-server/src/auth/peer.rs index 7ee198e775..f480f8fb1d 100644 --- a/crates/openshell-server/src/auth/peer.rs +++ b/crates/openshell-server/src/auth/peer.rs @@ -55,6 +55,8 @@ const POD_UID_EXTRA: &str = "authentication.kubernetes.io/pod-uid"; pub struct ResolvedGatewayPeerIdentity { pub pod_name: String, pub pod_uid: String, + /// `spec.nodeName` of the live Pod; `None` while it is unscheduled. + pub node_name: Option, } #[async_trait] @@ -279,9 +281,15 @@ impl GatewayPeerIdentityResolver for LiveGatewayPeerResolver { "validated gateway peer ServiceAccount token via TokenReview" ); + let node_name = pod + .spec + .as_ref() + .and_then(|spec| spec.node_name.clone()) + .filter(|node| !node.is_empty()); Ok(Some(ResolvedGatewayPeerIdentity { pod_name: identity.pod_name, pod_uid: identity.pod_uid, + node_name, })) } } @@ -302,6 +310,14 @@ pub struct CachingGatewayPeerResolver { entries: Mutex>, } +impl std::fmt::Debug for CachingGatewayPeerResolver { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("CachingGatewayPeerResolver") + .field("ttl", &self.ttl) + .finish_non_exhaustive() + } +} + impl CachingGatewayPeerResolver { pub fn new(inner: Arc, ttl: Duration) -> Self { Self { @@ -812,6 +828,7 @@ mod tests { ResolvedGatewayPeerIdentity { pod_name: "openshell-0".to_string(), pod_uid: "uid-a".to_string(), + node_name: None, }, )))); let auth = PeerServiceAccountAuthenticator::new(resolver); @@ -836,6 +853,7 @@ mod tests { ResolvedGatewayPeerIdentity { pod_name: "openshell-0".to_string(), pod_uid: "uid-a".to_string(), + node_name: None, }, )))); let auth = PeerServiceAccountAuthenticator::new(resolver.clone()); @@ -867,6 +885,7 @@ mod tests { ResolvedGatewayPeerIdentity { pod_name: "openshell-0".to_string(), pod_uid: "uid-a".to_string(), + node_name: None, } } diff --git a/crates/openshell-server/src/auth/sandbox_jwt.rs b/crates/openshell-server/src/auth/sandbox_jwt.rs index 5d37d6c8a5..aefde4f2fb 100644 --- a/crates/openshell-server/src/auth/sandbox_jwt.rs +++ b/crates/openshell-server/src/auth/sandbox_jwt.rs @@ -38,10 +38,10 @@ use x509_parser::{oid_registry::OID_SIG_ED25519, prelude::FromDer, x509::Subject use openshell_core::SandboxSessionId; use openshell_core::jwt::{ AuthenticatedSandboxSession, AuthenticatedSupervisor, CredentialEpoch, - GATEWAY_SESSION_JWT_TYPE, MintedSessionToken, SandboxId, SandboxLaunchAuthentication, - SandboxRuntimeIdentity, SessionJwtError, SessionJwtIssuer, SessionJwtVerifier, - SessionTokenProfile, SessionVerificationKey, SupervisorAuthBundle, SupervisorJwtVerifier, - SystemJwtClock, + GATEWAY_SESSION_JWT_TYPE, HostTokenProfile, MintedSessionToken, SandboxId, + SandboxLaunchAuthentication, SandboxRuntimeIdentity, SessionJwtError, SessionJwtIssuer, + SessionJwtVerifier, SessionTokenProfile, SessionVerificationKey, SupervisorAuthBundle, + SupervisorJwtVerifier, SystemJwtClock, }; use openshell_core::sandbox_generation::SandboxGenerationId; @@ -106,6 +106,7 @@ pub struct SandboxSessionJwtAuthority { issuer: SessionJwtIssuer, gateway_verifier: SessionJwtVerifier, supervisor_verifier: SupervisorJwtVerifier, + enforcer_verifier: SupervisorJwtVerifier, gateway_id: String, verification_keys: Vec, } @@ -156,12 +157,20 @@ impl SandboxSessionJwtAuthority { ) .map_err(|error| error.to_string())?; let supervisor_verifier = - SupervisorJwtVerifier::new(gateway_id, verification_keys.clone(), clock) + SupervisorJwtVerifier::new(gateway_id, verification_keys.clone(), clock.clone()) .map_err(|error| error.to_string())?; + let enforcer_verifier = SupervisorJwtVerifier::for_profile( + HostTokenProfile::Enforcer, + gateway_id, + verification_keys.clone(), + clock, + ) + .map_err(|error| error.to_string())?; Ok(Self { issuer, gateway_verifier, supervisor_verifier, + enforcer_verifier, gateway_id: gateway_id.to_string(), verification_keys, }) @@ -301,6 +310,15 @@ impl SandboxSessionJwtAuthority { self.issuer.mint_supervisor_token(ttl) } + /// Mint the external enforcer's token for the assignment stream and its + /// read and acknowledgement RPCs. + pub fn mint_enforcer_token( + &self, + ttl: Duration, + ) -> Result { + self.issuer.mint_host_token(HostTokenProfile::Enforcer, ttl) + } + /// Mint the takeover grant of one supervisor term of a shared pool /// instance. The caller has already advanced the sandbox's persisted /// credential epoch to the grant's. @@ -317,20 +335,36 @@ impl SandboxSessionJwtAuthority { &self, token: &str, ) -> Result { - self.supervisor_verifier.verify(token).map_err(|error| { - let reason = match error { - SessionJwtError::SubjectMismatch => AuthFailureReason::AudienceOrIssuerMismatch, - ref other => session_failure_reason(other), - }; - AuthRejection::new( - AuthMechanism::SupervisorToken, - reason, - Status::unauthenticated(format!("invalid supervisor token: {error}")), - ) - }) + verify_host_token(&self.supervisor_verifier, token, "supervisor") + } + + /// Verify a presented enforcer token. + pub fn verify_enforcer_token( + &self, + token: &str, + ) -> Result { + verify_host_token(&self.enforcer_verifier, token, "enforcer") } } +fn verify_host_token( + verifier: &SupervisorJwtVerifier, + token: &str, + kind: &str, +) -> Result { + verifier.verify(token).map_err(|error| { + let reason = match error { + SessionJwtError::SubjectMismatch => AuthFailureReason::AudienceOrIssuerMismatch, + ref other => session_failure_reason(other), + }; + AuthRejection::new( + AuthMechanism::SupervisorToken, + reason, + Status::unauthenticated(format!("invalid {kind} token: {error}")), + ) + }) +} + /// Authenticates launch-scoped supervisor tokens and checks their identity /// against the durable sandbox record. pub struct SandboxSessionJwtAuthenticator { diff --git a/crates/openshell-server/src/auth/supervisor_token.rs b/crates/openshell-server/src/auth/supervisor_token.rs index b8c77ec233..72c2cec353 100644 --- a/crates/openshell-server/src/auth/supervisor_token.rs +++ b/crates/openshell-server/src/auth/supervisor_token.rs @@ -9,17 +9,24 @@ //! key, key ID, and gateway identity as the sandbox session tokens, under a //! distinct profile (`typ`, subject, claims), so no sandbox, extension, user, //! or peer credential is accepted on the stream and the supervisor token is -//! accepted nowhere else. [`SupervisorTokenAuthenticator`] slots the verifier -//! into the gateway's authenticator chain. +//! accepted nowhere else. The enforcer token of an external enforcer host is a +//! second profile of the same authority with its own `typ` and subject. A +//! pod-bound token for the role's `ServiceAccount` that accompanies either +//! must verify, and may be required. [`SupervisorTokenAuthenticator`] slots +//! both verifiers into the gateway's authenticator chain. use std::sync::Arc; use async_trait::async_trait; use jsonwebtoken::decode_header; -use openshell_core::jwt::SUPERVISOR_JWT_TYPE; -use openshell_supervisor_control::HostIdentity; +use openshell_core::jwt::{ENFORCER_JWT_TYPE, SUPERVISOR_JWT_TYPE}; +use openshell_supervisor_control::{HOST_IDENTITY_TOKEN_HEADER, HostIdentity, HostRole}; -use super::authenticator::{AuthRejection, Authentication, Authenticator, bearer_credential}; +use super::authenticator::{ + AuthFailureReason, AuthMechanism, AuthRejection, Authentication, Authenticator, + bearer_credential, +}; +use super::peer::GatewayPeerIdentityResolver; use super::principal::{Principal, SupervisorPrincipal}; use super::sandbox_jwt::SandboxSessionJwtAuthority; @@ -28,11 +35,107 @@ use super::sandbox_jwt::SandboxSessionJwtAuthority; /// verification ends the chain. pub struct SupervisorTokenAuthenticator { authority: Arc, + supervisor_identity: Option, + enforcer_identity: Option, +} + +struct IdentityCheck { + resolver: Arc, + required: bool, } impl SupervisorTokenAuthenticator { pub fn new(authority: Arc) -> Self { - Self { authority } + Self { + authority, + supervisor_identity: None, + enforcer_identity: None, + } + } + + /// Accept `role`'s host tokens only when the identity token in + /// [`HOST_IDENTITY_TOKEN_HEADER`] resolves through `resolver`, or, unless + /// `required`, is absent. Without a resolver, every token of the role is + /// refused. + #[must_use] + pub fn with_identity_resolver( + mut self, + role: HostRole, + resolver: Arc, + required: bool, + ) -> Self { + let check = Some(IdentityCheck { resolver, required }); + match role { + HostRole::Supervisor => self.supervisor_identity = check, + HostRole::Enforcer => self.enforcer_identity = check, + } + self + } + + /// The node the host's Pod runs on, or `None` for a host that sent no + /// identity token where none is required. Resolved only after the host + /// token verified, so callers without it can't trigger a `TokenReview`. + async fn resolve_identity( + &self, + role: HostRole, + headers: &http::HeaderMap, + ) -> Result, AuthRejection> { + let (check, name) = match role { + HostRole::Supervisor => (&self.supervisor_identity, "supervisor"), + HostRole::Enforcer => (&self.enforcer_identity, "enforcer"), + }; + let refuse = |reason, message: String| { + AuthRejection::new( + AuthMechanism::SupervisorToken, + reason, + tonic::Status::unauthenticated(message), + ) + }; + let Some(check) = check else { + return Err(refuse( + AuthFailureReason::InvalidCredential, + format!("this gateway accepts no {name}"), + )); + }; + let Some(token) = headers + .get(HOST_IDENTITY_TOKEN_HEADER) + .and_then(|value| value.to_str().ok()) + .filter(|value| !value.is_empty()) + else { + if check.required { + return Err(refuse( + AuthFailureReason::MissingCredential, + format!("{name} identity token is required"), + )); + } + return Ok(None); + }; + let identity = check + .resolver + .resolve(token) + .await + .map_err(|rejection| { + AuthRejection::new( + AuthMechanism::SupervisorToken, + rejection.reason, + tonic::Status::new( + rejection.status.code(), + format!("{name} identity: {}", rejection.status.message()), + ), + ) + })? + .ok_or_else(|| { + refuse( + AuthFailureReason::InvalidCredential, + format!("{name} identity token is invalid"), + ) + })?; + identity.node_name.map(Some).ok_or_else(|| { + refuse( + AuthFailureReason::InvalidCredential, + format!("{name} identity token names an unscheduled pod"), + ) + }) } } @@ -57,16 +160,27 @@ impl Authenticator for SupervisorTokenAuthenticator { let Ok(header) = decode_header(token) else { return Ok(Authentication::NotApplicable); }; - if header.typ.as_deref() != Some(SUPERVISOR_JWT_TYPE) { - return Ok(Authentication::NotApplicable); - } - let authenticated = self.authority.verify_supervisor_token(token)?; + let (authenticated, role) = match header.typ.as_deref() { + Some(SUPERVISOR_JWT_TYPE) => ( + self.authority.verify_supervisor_token(token)?, + HostRole::Supervisor, + ), + Some(ENFORCER_JWT_TYPE) => ( + self.authority.verify_enforcer_token(token)?, + HostRole::Enforcer, + ), + _ => return Ok(Authentication::NotApplicable), + }; + let node = self.resolve_identity(role, headers).await?; Ok(Authentication::Accepted(Principal::Supervisor( SupervisorPrincipal { identity: HostIdentity { subject: authenticated.subject, token_id: authenticated.token_id.to_string(), expires_at: authenticated.expires_at, + // An enforcer is no node's supervisor. + node: node.filter(|_| role == HostRole::Supervisor), + role, }, }, ))) @@ -78,9 +192,11 @@ mod tests { use std::time::Duration; use super::*; - use crate::auth::authenticator::{AuthFailureReason, AuthMechanism}; + use crate::auth::peer::test_support::FakeGatewayPeerResolver; use openshell_bootstrap::jwt::generate_jwt_key; + const ATTACH: &str = "/openshell.supervisor.host.v1.SupervisorHost/Attach"; + fn authority(gateway_id: &str) -> Arc { let material = generate_jwt_key().expect("jwt key"); Arc::new( @@ -104,17 +220,40 @@ mod tests { headers } + fn with_identity(token: &str) -> http::HeaderMap { + let mut headers = headers(token); + headers.insert(HOST_IDENTITY_TOKEN_HEADER, "pod-token".parse().unwrap()); + headers + } + + fn resolving(node_name: Option<&str>) -> Arc { + Arc::new(FakeGatewayPeerResolver::returning(Ok(Some( + crate::auth::peer::ResolvedGatewayPeerIdentity { + pod_name: "openshell-supervisor-abc".to_string(), + pod_uid: "uid".to_string(), + node_name: node_name.map(ToString::to_string), + }, + )))) + } + + fn accepting(gateway: Arc) -> SupervisorTokenAuthenticator { + SupervisorTokenAuthenticator::new(gateway).with_identity_resolver( + HostRole::Supervisor, + resolving(Some("node-a")), + true, + ) + } + #[tokio::test] async fn supervisor_tokens_authenticate_only_as_the_supervisor() { - let attach = "/openshell.supervisor.host.v1.SupervisorHost/Attach"; let gateway = authority("test-gateway"); let minted = gateway .mint_supervisor_token(Duration::from_mins(15)) .expect("mint"); - let authenticator = SupervisorTokenAuthenticator::new(gateway.clone()); + let authenticator = accepting(gateway.clone()); let accepted = authenticator - .authenticate(&headers(minted.token.expose_secret()), attach) + .authenticate(&with_identity(minted.token.expose_secret()), ATTACH) .await .expect("valid token"); match accepted { @@ -125,6 +264,7 @@ mod tests { ); assert_eq!(supervisor.identity.token_id, minted.token_id.to_string()); assert_eq!(supervisor.identity.expires_at, minted.expires_at); + assert_eq!(supervisor.identity.role, HostRole::Supervisor); } other => panic!("unexpected outcome {other:?}"), } @@ -142,7 +282,7 @@ mod tests { ] { assert!(matches!( authenticator - .authenticate(&headers(bearer), attach) + .authenticate(&with_identity(bearer), ATTACH) .await .unwrap(), Authentication::NotApplicable @@ -162,26 +302,154 @@ mod tests { .mint_supervisor_token(Duration::from_mins(15)) .unwrap(); let rejection = authenticator - .authenticate(&headers(foreign.token.expose_secret()), attach) + .authenticate(&with_identity(foreign.token.expose_secret()), ATTACH) .await .expect_err("foreign key must be rejected"); assert_eq!(rejection.mechanism, AuthMechanism::SupervisorToken); assert_eq!(rejection.reason, AuthFailureReason::InvalidCredential); assert_eq!(rejection.status.code(), tonic::Code::Unauthenticated); let other_gateway = authority("other-gateway"); - let rejection = SupervisorTokenAuthenticator::new(other_gateway.clone()) + let rejection = accepting(other_gateway.clone()) .authenticate( - &headers( + &with_identity( other_gateway .mint_supervisor_token(Duration::from_mins(15)) .unwrap() .token .expose_secret(), ), - attach, + ATTACH, ) .await .expect("own token verifies"); assert!(matches!(rejection, Authentication::Accepted(_))); } + + #[tokio::test] + async fn host_tokens_require_their_roles_pod_identity_after_they_verify() { + let gateway = authority("test-gateway"); + let supervisor = gateway + .mint_supervisor_token(Duration::from_mins(15)) + .unwrap(); + let enforcer = gateway + .mint_enforcer_token(Duration::from_mins(15)) + .unwrap(); + let supervisors = resolving(Some("node-a")); + let enforcers = resolving(Some("node-b")); + let authenticator = SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver(HostRole::Supervisor, supervisors.clone(), true) + .with_identity_resolver(HostRole::Enforcer, enforcers.clone(), true); + + for (token, role, node) in [ + (&supervisor, HostRole::Supervisor, Some("node-a")), + (&enforcer, HostRole::Enforcer, None), + ] { + match authenticator + .authenticate(&with_identity(token.token.expose_secret()), ATTACH) + .await + .expect("valid host token") + { + Authentication::Accepted(Principal::Supervisor(host)) => { + assert_eq!(host.identity.role, role); + assert_eq!(host.identity.node.as_deref(), node); + } + other => panic!("unexpected outcome {other:?}"), + } + + let missing = authenticator + .authenticate(&headers(token.token.expose_secret()), ATTACH) + .await + .expect_err("a host token alone must be refused"); + assert_eq!(missing.reason, AuthFailureReason::MissingCredential); + assert_eq!(missing.status.code(), tonic::Code::Unauthenticated); + } + // Each role's identity token went to that role's resolver only. + assert_eq!(*supervisors.seen_tokens.lock().unwrap(), ["pod-token"]); + assert_eq!(*enforcers.seen_tokens.lock().unwrap(), ["pod-token"]); + + // A forged host token never reaches a resolver. + let foreign = authority("test-gateway"); + for forged in [ + foreign + .mint_supervisor_token(Duration::from_mins(15)) + .unwrap(), + foreign + .mint_enforcer_token(Duration::from_mins(15)) + .unwrap(), + ] { + assert!( + authenticator + .authenticate(&with_identity(forged.token.expose_secret()), ATTACH) + .await + .is_err() + ); + } + assert_eq!(supervisors.seen_tokens.lock().unwrap().len(), 1); + assert_eq!(enforcers.seen_tokens.lock().unwrap().len(), 1); + + // Unless required, a supervisor without an identity token attaches + // with no node, but one it sends is still verified. + let optional = SupervisorTokenAuthenticator::new(gateway.clone()).with_identity_resolver( + HostRole::Supervisor, + supervisors.clone(), + false, + ); + match optional + .authenticate(&headers(supervisor.token.expose_secret()), ATTACH) + .await + .unwrap() + { + Authentication::Accepted(Principal::Supervisor(host)) => { + assert_eq!(host.identity.node, None); + } + other => panic!("unexpected outcome {other:?}"), + } + assert_eq!(supervisors.seen_tokens.lock().unwrap().len(), 1); + assert!( + SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver( + HostRole::Supervisor, + Arc::new(FakeGatewayPeerResolver::returning(Ok(None))), + false + ) + .authenticate(&with_identity(supervisor.token.expose_secret()), ATTACH) + .await + .is_err() + ); + } + + #[tokio::test] + async fn host_tokens_are_refused_without_a_valid_pod_identity() { + let gateway = authority("test-gateway"); + let minted = gateway + .mint_supervisor_token(Duration::from_mins(15)) + .unwrap(); + let headers = with_identity(minted.token.expose_secret()); + + let unconfigured = SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver(HostRole::Enforcer, resolving(Some("node-a")), true) + .authenticate(&headers, ATTACH) + .await + .expect_err("a gateway without a supervisor account accepts no supervisor"); + assert_eq!(unconfigured.reason, AuthFailureReason::InvalidCredential); + + let unknown = SupervisorTokenAuthenticator::new(gateway.clone()) + .with_identity_resolver( + HostRole::Supervisor, + Arc::new(FakeGatewayPeerResolver::returning(Ok(None))), + true, + ) + .authenticate(&headers, ATTACH) + .await + .expect_err("an identity token for another account must be refused"); + assert_eq!(unknown.reason, AuthFailureReason::InvalidCredential); + assert_eq!(unknown.status.code(), tonic::Code::Unauthenticated); + + let unscheduled = SupervisorTokenAuthenticator::new(gateway) + .with_identity_resolver(HostRole::Supervisor, resolving(None), true) + .authenticate(&headers, ATTACH) + .await + .expect_err("an unscheduled pod proves no node"); + assert_eq!(unscheduled.mechanism, AuthMechanism::SupervisorToken); + } } diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index 8b2adb5570..e6ad0f2fdc 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -11,8 +11,9 @@ pub mod provisioning_deadline; mod provisioning_operation; pub mod rootfs_tar; +pub use mutation_guard::MutationGuard; pub use mutation_guard::MutationScope; -use mutation_guard::{LocalMutationGuard, LocalMutationLocks, MutationGuard}; +use mutation_guard::{LocalMutationGuard, LocalMutationLocks}; use crate::grpc::policy::SANDBOX_SETTINGS_OBJECT_TYPE; use crate::otel_tracing::TraceContextInterceptor; @@ -1387,6 +1388,9 @@ pub struct ComputeRuntime { /// Desired assignments of the shared supervisor host, when the gateway /// coordinates one for the in-process driver. supervisor_host: Option, + /// The sandboxes' resolvers when the driver launches every new runtime in + /// native-network mode. + native_network: Option>, service_route_index: Arc>>, #[cfg(test)] sandbox_update_conflict_hook: Arc, @@ -1506,6 +1510,7 @@ impl ComputeRuntime { supervisor_otlp_headers: Arc::new(OnceLock::new()), supervisor_otlp_tls: Arc::new(OnceLock::new()), supervisor_host: None, + native_network: None, service_route_index: Arc::new(OnceLock::new()), #[cfg(test)] sandbox_update_conflict_hook: Arc::new( @@ -1524,6 +1529,23 @@ impl ComputeRuntime { self } + /// Launch every new runtime in native-network mode, with these + /// resolvers. + pub(crate) fn with_native_network( + mut self, + nameservers: Option>, + ) -> Self { + self.native_network = nameservers.map(Into::into); + self + } + + /// The sandboxes' resolvers when new runtimes launch in + /// native-network mode, which an external enforcer serves. + #[must_use] + pub fn native_network(&self) -> Option<&[std::net::IpAddr]> { + self.native_network.as_deref() + } + /// Gateway-owned assignments of the shared supervisor host, if any. #[must_use] pub fn supervisor_host( @@ -2730,9 +2752,13 @@ impl ComputeRuntime { Ok(settled) } Err(err) => { - if let Some(terminal) = self - .recover_failed_lifecycle(&lifecycle_guard, &transition, &previous, true) - .await + if let Some(terminal) = Box::pin(self.recover_failed_lifecycle( + &lifecycle_guard, + &transition, + &previous, + true, + )) + .await { return Ok(terminal); } @@ -3013,6 +3039,7 @@ impl ComputeRuntime { intent, ); } + apply_configuration_readiness(sandbox); }, ) .await @@ -3213,9 +3240,13 @@ impl ComputeRuntime { settled, }) => { provisioning_operation::ensure_current_result(&settled, &settled)?; - let _ = self - .recover_failed_lifecycle(&lifecycle_guard, &settled, &previous, false) - .await; + let _ = Box::pin(self.recover_failed_lifecycle( + &lifecycle_guard, + &settled, + &previous, + false, + )) + .await; Err(Status::new( err.code(), format!("start sandbox failed: {}", err.message()), @@ -5587,14 +5618,20 @@ impl ComputeRuntime { sandbox_id, sandbox_resource_version(¤t), |sandbox| { - if let (Some(identity), Some(metadata)) = + let new_generation = if let (Some(identity), Some(metadata)) = (next_identity.as_ref(), sandbox.metadata.as_mut()) { identity.write(&mut metadata.annotations); - } + true + } else { + false + }; provisioning_operation::claim_record(sandbox); let status = sandbox.status.get_or_insert_with(Default::default); set_next_restart_at_ms(status, 0); + if new_generation { + reset_configuration_admission(status); + } upsert_ready_condition( &mut sandbox.status, SandboxCondition { @@ -5607,6 +5644,9 @@ impl ComputeRuntime { transition_time: None, }, ); + if new_generation { + apply_configuration_readiness(sandbox); + } }, ) .await @@ -8224,7 +8264,32 @@ fn sandbox_compute_runtime_identity(sandbox: &Sandbox) -> String { .unwrap_or_default() } -fn sandbox_runtime_generation( +/// The native-network enforcer's admission for the sandbox's current runtime +/// generation. +pub fn current_enforcer_admission( + sandbox: &Sandbox, +) -> Option<&openshell_core::proto::SandboxConfigurationAdmission> { + let generation = sandbox_runtime_generation(sandbox).ok()?; + sandbox + .status + .as_ref()? + .enforcer_admission + .as_ref() + .filter(|admission| admission.instance_id == generation.as_str()) +} + +/// The native-network enforcer's admission when it is ACCEPTED for the +/// sandbox's current runtime generation. A later rejection keeps the accepted +/// tuple, so this is the newest configuration the enforcer enforces. +pub fn accepted_enforcer_admission( + sandbox: &Sandbox, +) -> Option<&openshell_core::proto::SandboxConfigurationAdmission> { + current_enforcer_admission(sandbox).filter(|admission| { + admission.state == i32::from(openshell_core::proto::ConfigurationAdmissionState::Accepted) + }) +} + +pub fn sandbox_runtime_generation( sandbox: &Sandbox, ) -> Result { let persisted = sandbox.metadata.as_ref().and_then(|metadata| { @@ -8279,6 +8344,7 @@ fn public_status_from_driver( next_restart_time: None, main_process_started_time: None, last_token_grant_failure: None, + enforcer_admission: None, } } @@ -8434,6 +8500,9 @@ fn apply_driver_snapshot( status .configuration_admission .clone_from(¤t_status.configuration_admission); + status + .enforcer_admission + .clone_from(¤t_status.enforcer_admission); status.configuration_activated = current_status.configuration_activated; status.provisioning.clone_from(¤t_status.provisioning); } @@ -8530,9 +8599,35 @@ fn admitted_provisioning( Ok(Some(record)) } +/// `ConfigurationReady` reason while a native-network sandbox waits for the +/// enforcer to accept its runtime generation. +pub const ENFORCER_PENDING: &str = "EnforcerPending"; + +/// Why a native-network sandbox's workload waits, until the enforcer reports. +pub const ENFORCER_PENDING_MESSAGE: &str = + "Waiting for the network enforcer to accept the configuration before workload activation"; + +/// Reason a native-network sandbox's configuration condition carries while +/// the enforcer rejects its current configuration. +pub const ENFORCER_REJECTED: &str = "EnforcerRejected"; + +pub fn enforcer_rejection_message(error: &str) -> String { + format!("The network enforcer rejected the configuration: {error}") +} + /// Configuration readiness is independent of compute/container readiness. pub fn apply_configuration_readiness(sandbox: &mut Sandbox) { use openshell_core::proto::ConfigurationAdmissionState; + let current_enforcer = current_enforcer_admission(sandbox); + let enforcer_accepted = current_enforcer.is_some_and(|admission| { + admission.state == i32::from(ConfigurationAdmissionState::Accepted) + }); + let enforcer_rejected = current_enforcer.is_some_and(|admission| { + admission.state == i32::from(ConfigurationAdmissionState::Rejected) + }); + let current_enforcer_error = current_enforcer + .map(|admission| admission.error.clone()) + .unwrap_or_default(); let Some(status) = sandbox.status.as_mut() else { return; }; @@ -8541,16 +8636,53 @@ pub fn apply_configuration_readiness(sandbox: &mut Sandbox) { return; }; let accepted = admission.state == i32::from(ConfigurationAdmissionState::Accepted); + // Sandboxes created in native-network mode carry an enforcer admission; + // until the enforcer accepts their generation, a pending supervisor is + // waiting for it. + let enforcer_error = status + .enforcer_admission + .as_ref() + .filter(|_| admission.state == i32::from(ConfigurationAdmissionState::Pending)) + .filter(|_| !enforcer_accepted) + .map(|_| current_enforcer_error.clone()); + // A held supervisor reports the enforcer's rejection as its own. + let echoes_enforcer_rejection = + enforcer_rejected && admission.error == enforcer_rejection_message(¤t_enforcer_error); let reason = if accepted { "ConfigurationAccepted" + } else if admission.state == i32::from(ConfigurationAdmissionState::Rejected) + && echoes_enforcer_rejection + { + ENFORCER_REJECTED } else if admission.state == i32::from(ConfigurationAdmissionState::Rejected) { "ConfigurationInvalid" + } else if enforcer_error.is_some() && enforcer_rejected { + ENFORCER_REJECTED + } else if enforcer_error.is_some() { + ENFORCER_PENDING } else { "ConfigurationPending" }; - let desired_error = admission.error.clone(); + // An accepted configuration whose update one side rejected keeps + // running; the update's rejection is reported separately. + let desired_rejection = if !admission.error.is_empty() { + Some(("ConfigurationInvalid", admission.error.clone())) + } else if !current_enforcer_error.is_empty() { + Some(( + ENFORCER_REJECTED, + enforcer_rejection_message(¤t_enforcer_error), + )) + } else { + None + }; let message = if accepted { String::new() + } else if let Some(error) = enforcer_error { + if error.is_empty() { + ENFORCER_PENDING_MESSAGE.to_string() + } else { + enforcer_rejection_message(&error) + } } else if admission.error.is_empty() { "Waiting for effective configuration validation before workload activation".to_string() } else { @@ -8566,12 +8698,12 @@ pub fn apply_configuration_readiness(sandbox: &mut Sandbox) { message: message.clone(), ..Default::default() }); - if accepted && !desired_error.is_empty() { + if accepted && let Some((reason, message)) = desired_rejection { status.conditions.push(SandboxCondition { r#type: "DesiredConfigurationReady".to_string(), status: "False".to_string(), - reason: "ConfigurationInvalid".to_string(), - message: desired_error, + reason: reason.to_string(), + message, ..Default::default() }); } @@ -8913,13 +9045,7 @@ fn apply_lifecycle_phase( image_preparation_timeout_seconds, provisioning_repair_window_ms, )); - status.configuration_admission = - Some(openshell_core::proto::SandboxConfigurationAdmission { - // Fence delayed registrations from the previous runtime. - instance_id: uuid::Uuid::new_v4().to_string(), - state: openshell_core::proto::ConfigurationAdmissionState::Pending.into(), - ..Default::default() - }); + reset_configuration_admission(status); } } upsert_ready_condition( @@ -8934,6 +9060,16 @@ fn apply_lifecycle_phase( ); } +/// Make a new runtime generation wait for its supervisor's admission. +fn reset_configuration_admission(status: &mut SandboxStatus) { + status.configuration_admission = Some(openshell_core::proto::SandboxConfigurationAdmission { + // Fence delayed registrations from the previous runtime. + instance_id: uuid::Uuid::new_v4().to_string(), + state: openshell_core::proto::ConfigurationAdmissionState::Pending.into(), + ..Default::default() + }); +} + /// Whether a `Starting` transition boots fresh or restores retained state. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum StartIntent { @@ -9397,6 +9533,7 @@ pub fn new_test_runtime_with_driver( supervisor_otlp_headers: Arc::new(OnceLock::new()), supervisor_otlp_tls: Arc::new(OnceLock::new()), supervisor_host: None, + native_network: None, service_route_index: Arc::new(OnceLock::new()), #[cfg(test)] sandbox_update_conflict_hook: Arc::new( @@ -10942,6 +11079,7 @@ mod tests { supervisor_otlp_headers: Arc::new(OnceLock::new()), supervisor_otlp_tls: Arc::new(OnceLock::new()), supervisor_host: None, + native_network: None, service_route_index: Arc::new(OnceLock::new()), sandbox_update_conflict_hook: Arc::new( sandbox_update_conflict_hook::SandboxUpdateConflictHook::default(), diff --git a/crates/openshell-server/src/compute/provisioning_deadline.rs b/crates/openshell-server/src/compute/provisioning_deadline.rs index 5f74a7b65f..711124312f 100644 --- a/crates/openshell-server/src/compute/provisioning_deadline.rs +++ b/crates/openshell-server/src/compute/provisioning_deadline.rs @@ -645,10 +645,21 @@ impl super::ComputeRuntime { .expect("provisioning record exists"), ); status.phase = SandboxPhase::Error.into(); + let enforcer_wait = status.conditions.iter().find(|condition| { + condition.r#type == "ConfigurationReady" + && matches!( + condition.reason.as_str(), + super::ENFORCER_PENDING | super::ENFORCER_REJECTED + ) + }); let diagnostic = status .configuration_admission .as_ref() - .map_or("", |admission| admission.error.as_str()); + .map(|admission| admission.error.as_str()) + .filter(|error| !error.is_empty()) + .or_else(|| enforcer_wait.map(|condition| condition.message.as_str())) + .unwrap_or_default() + .to_string(); let message = if preparation_expired { "Image preparation or initial supervisor startup exceeded its absolute deadline".to_string() } else if diagnostic.is_empty() { diff --git a/crates/openshell-server/src/compute_factory_compatibility.rs b/crates/openshell-server/src/compute_factory_compatibility.rs index 57552446de..aebe1593e9 100644 --- a/crates/openshell-server/src/compute_factory_compatibility.rs +++ b/crates/openshell-server/src/compute_factory_compatibility.rs @@ -69,12 +69,21 @@ impl ComputeDriverFactory for OptInFactory { } async fn registered_runtime(factory: impl ComputeDriverFactory + 'static) -> crate::ComputeRuntime { + build_runtime(factory, openshell_core::Config::new(None)) + .await + .unwrap() + .with_sandbox_updates(true) +} + +async fn build_runtime( + factory: impl ComputeDriverFactory + 'static, + config: openshell_core::Config, +) -> openshell_core::Result { let mut registry = ComputeDriverRegistry::new(); registry .install(ComputeDriverRegistration::new("fixture", 0, None, factory).unwrap()) .unwrap(); let selection = registry.select(Some("fixture")).unwrap(); - let config = openshell_core::Config::new(None); let overrides = BTreeMap::new(); let startup = crate::compute::driver_config::DriverStartupContext { file: None, @@ -119,8 +128,52 @@ async fn registered_runtime(factory: impl ComputeDriverFactory + 'static) -> cra tokio::sync::watch::channel(false).1, ) .await - .unwrap() - .with_sandbox_updates(true) +} + +struct NativeNetworkFactory; + +#[async_trait::async_trait] +impl ComputeDriverFactory for NativeNetworkFactory { + fn native_network( + &self, + _context: crate::ComputeDriverConfigContext<'_>, + ) -> openshell_core::Result>> { + Ok(Some(vec!["192.168.100.1".parse().unwrap()])) + } + + async fn build( + &self, + _context: ComputeDriverBuildContext<'_>, + ) -> openshell_core::Result { + Ok(ComputeDriverInstance::InProcess(Arc::new( + crate::compute::NoopTestDriver::default(), + ))) + } +} + +#[tokio::test] +async fn native_network_is_stored_and_refuses_push_delivery() { + let runtime = build_runtime(NativeNetworkFactory, openshell_core::Config::new(None)) + .await + .unwrap(); + assert_eq!( + runtime.native_network(), + Some(&["192.168.100.1".parse::().unwrap()][..]) + ); + let baseline = registered_runtime(BaselineFactory { + driver: Arc::new(crate::compute::NoopTestDriver::default()), + calls: Arc::new(AtomicUsize::new(0)), + }) + .await; + assert_eq!(baseline.native_network(), None); + + let mut push = openshell_core::Config::new(None); + push.config_delivery_mode = openshell_core::config::ConfigDeliveryMode::Push; + let error = build_runtime(NativeNetworkFactory, push).await.unwrap_err(); + assert!( + error.to_string().contains("config_delivery_mode"), + "{error}" + ); } #[tokio::test] diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index abcad0cfc9..6ecaa39ca6 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -508,7 +508,7 @@ impl OtlpConfig { /// Bytes of TLS files sent to supervisors, counting files shared by /// several exports once. - fn supervisor_tls_bytes(&self) -> usize { + pub fn supervisor_tls_bytes(&self) -> usize { crate::otel_tracing::supervisor_otlp_tls(Some(self)) .materials .iter() diff --git a/crates/openshell-server/src/grpc/auth_rpc.rs b/crates/openshell-server/src/grpc/auth_rpc.rs index 1f56bd708b..76b364fd35 100644 --- a/crates/openshell-server/src/grpc/auth_rpc.rs +++ b/crates/openshell-server/src/grpc/auth_rpc.rs @@ -348,6 +348,7 @@ pub async fn handle_refresh_sandbox_token( )); } else { let mut config_request = Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), supported_capabilities: vec![ openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), ], diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index 5bfb592196..eacb81ca5a 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -1645,6 +1645,18 @@ pub mod test_support { test_server_state_with_driver("test").await } + /// Build a test state whose driver launches sandboxes in + /// native-network mode. + pub async fn test_native_network_server_state() -> Arc { + let mut state = test_server_state().await; + let shared = Arc::get_mut(&mut state).expect("test state is not shared yet"); + shared.compute = shared + .compute + .clone() + .with_native_network(Some(vec!["192.168.100.1".parse().unwrap()])); + state + } + /// Build a test state for a gateway with nothing imported. /// /// Its profile catalog is empty, which is the state a freshly installed diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index b9d5fa8fff..f90f8563d4 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -13,6 +13,7 @@ mod config_inputs; mod discovery_inputs; mod endpoint_status; +mod enforcer; mod provisioning_clock; #[cfg(test)] mod token_grant_owners_tests; @@ -2811,6 +2812,16 @@ pub(super) async fn handle_get_sandbox_config( state: &Arc, request: Request, ) -> Result, Status> { + if enforcer::is_enforcer(&request) { + return enforcer::sandbox_config(state, request.get_ref()) + .await + .map(Response::new); + } + if !request.get_ref().sandbox_id.is_empty() { + return Err(Status::invalid_argument( + "sandbox_id selects a sandbox only for the native-network enforcer; select it by name", + )); + } let principal = super::extract_principal(&request)?; let sandbox_name = request.get_ref().name.clone(); let workspace = match (&principal, request.get_ref().workspace_scope.as_ref()) { @@ -2939,6 +2950,17 @@ pub(super) async fn load_sandbox_config( pub async fn build_sandbox_config_snapshot( state: &ServerState, sandbox: &Sandbox, +) -> Result { + let mut snapshot = build_base_sandbox_config_snapshot(state, sandbox).await?; + enforcer::apply_enforcer_hold(state, &mut snapshot, sandbox); + Ok(snapshot) +} + +/// The effective configuration without the native-network activation hold, +/// as the enforcer judges it. +async fn build_base_sandbox_config_snapshot( + state: &ServerState, + sandbox: &Sandbox, ) -> Result { let inputs = load_sandbox_config_inputs(state, sandbox.clone()).await?; build_sandbox_config_snapshot_from_inputs(state, &inputs).await @@ -3087,10 +3109,19 @@ async fn build_sandbox_config_snapshot_with_sources( policy_hash = deterministic_policy_hash(effective_policy); } + let native_network = state.compute.native_network().is_some(); if let Some(policy) = policy.as_ref() { state .middleware_registry .ensure_policy_middlewares_registered(policy) + .map_err(|error| error.to_string()) + .and_then(|()| { + if native_network { + crate::middleware::reject_builtin_middleware(policy) + } else { + Ok(()) + } + }) .map_err(|error| { Status::failed_precondition(format!( "effective policy middleware registration is invalid: {error}" @@ -3099,8 +3130,13 @@ async fn build_sandbox_config_snapshot_with_sources( } let settings = merge_effective_settings(global_settings, &sandbox_settings)?; - let supervisor_middleware_services = - state.middleware_registry.required_services(policy.as_ref()); + // The native-network enforcer runs the middleware chain, not the + // supervisor. + let supervisor_middleware_services = if native_network { + Vec::new() + } else { + state.middleware_registry.required_services(policy.as_ref()) + }; let mut config_revision = compute_config_revision_with_validation_mode( policy.as_ref(), &settings, @@ -3174,6 +3210,8 @@ async fn build_sandbox_config_snapshot_with_sources( .as_ref() .map(|spec| spec.provider_attachment_epoch.clone()) .unwrap_or_default(), + activation_pending: false, + enforcer_provider_env_revision: 0, }) } @@ -3197,6 +3235,8 @@ fn sandbox_config_response(snapshot: SandboxConfigSnapshot) -> GetSandboxConfigR configuration_admitted: snapshot.configuration_admitted, configuration_error: snapshot.configuration_error, configuration_instance_id: snapshot.configuration_instance_id, + activation_pending: snapshot.activation_pending, + enforcer_provider_env_revision: snapshot.enforcer_provider_env_revision, } } @@ -3891,6 +3931,11 @@ pub(super) async fn handle_get_sandbox_provider_environment( state: &Arc, request: Request, ) -> Result, Status> { + if enforcer::is_enforcer(&request) { + return enforcer::provider_environment(state, request.get_ref()) + .await + .map(Response::new); + } let sandbox_id = request.get_ref().sandbox_id.clone(); let supports_static_credential_bindings = request.get_ref().supports_static_credential_bindings; let supports_stable_placeholder_environment_keys = request @@ -4168,6 +4213,7 @@ pub async fn build_provider_environment_snapshot_from_inputs( ))); } values.push(ProviderEnvironmentValue { + workload_placeholder: String::new(), name: name.clone(), value, expiration_time: provider_environment @@ -4209,8 +4255,12 @@ fn provider_environment_response( let mut static_credential_bindings = HashMap::new(); let mut non_secret_environment_keys = Vec::new(); let mut stable_placeholder_environment_keys = Vec::new(); + let mut workload_placeholders = HashMap::new(); for value in snapshot.values { environment.insert(value.name.clone(), value.value); + if !value.workload_placeholder.is_empty() { + workload_placeholders.insert(value.name.clone(), value.workload_placeholder); + } if value.stable_placeholder { stable_placeholder_environment_keys.push(value.name.clone()); } @@ -4244,6 +4294,7 @@ fn provider_environment_response( provider_attachment_epoch: snapshot.provider_attachment_epoch, policy_hash: snapshot.policy_hash, readiness_reason: snapshot.readiness_reason, + workload_placeholders, } } @@ -4379,8 +4430,7 @@ async fn handle_update_config_inner( validate_no_reserved_provider_policy_keys(&new_policy)?; new_policy = validate_and_canonicalize_policy(new_policy)?; validate_policy_safety(&new_policy)?; - crate::middleware::validate_policy(state.middleware_registry.as_ref(), &new_policy) - .await?; + crate::middleware::validate_policy_for_gateway(state, &new_policy).await?; validate_candidate_effective_policy(&new_policy, &[])?; if !policy_static_credential_endpoint_bindings(Some(&new_policy))?.is_empty() { return Err(Status::failed_precondition( @@ -4811,7 +4861,7 @@ async fn handle_update_config_inner( new_policy = validate_and_canonicalize_policy(new_policy)?; let backfill_policy = should_backfill_policy.then(|| new_policy.clone()); validate_policy_safety(&new_policy)?; - crate::middleware::validate_policy(state.middleware_registry.as_ref(), &new_policy).await?; + crate::middleware::validate_policy_for_gateway(state, &new_policy).await?; let provider_layers = provider_policy_layers_for_sandbox(state, &workspace, &sandbox, &spec.providers).await?; validate_candidate_effective_policy(&new_policy, &provider_layers)?; @@ -5022,9 +5072,13 @@ pub(super) async fn handle_get_sandbox_policy_status( "no policy revision found for this sandbox" }; let record = record.ok_or_else(|| Status::not_found(not_found_msg))?; + let mut revision = policy_record_to_revision(&record, true)?; + if !req.global { + pending_until_enforced(state, &mut revision, active_version); + } Ok(Response::new(GetSandboxPolicyStatusResponse { - revision: Some(policy_record_to_revision(&record, true)?), + revision: Some(revision), active_version, })) } @@ -5094,9 +5148,19 @@ pub(super) async fn handle_list_sandbox_policies( .flatten(), ); + let active_version = sandbox + .as_ref() + .filter(|_| !req.global) + .map(Sandbox::current_policy_version); let revisions = records .iter() - .map(|r| policy_record_to_revision(r, false)) + .map(|r| { + let mut revision = policy_record_to_revision(r, false)?; + if let Some(active_version) = active_version { + pending_until_enforced(state, &mut revision, active_version); + } + Ok(revision) + }) .collect::, Status>>()?; Ok(Response::new(ListSandboxPoliciesResponse { @@ -5105,10 +5169,31 @@ pub(super) async fn handle_list_sandbox_policies( })) } +/// A sandbox revision the supervisor loaded is still pending until the +/// native-network enforcer accepts it too. +fn pending_until_enforced( + state: &ServerState, + revision: &mut SandboxPolicyRevision, + active_version: u32, +) { + if state.compute.native_network().is_some() + && revision.status == PolicyStatus::Loaded as i32 + && revision.version > active_version + { + revision.status = PolicyStatus::Pending as i32; + } +} + fn bounded_configuration_diagnostic(message: &str) -> String { message .chars() - .filter(|character| !character.is_control()) + .map(|character| { + if character.is_control() { + ' ' + } else { + character + } + }) .take(512) .collect() } @@ -5146,8 +5231,23 @@ fn configuration_generation_matches( pub(super) async fn handle_report_sandbox_configuration( state: &Arc, request: Request, +) -> Result, Status> { + // The report holds several sandbox records; keep it off the caller's + // stack (clippy::large_futures). + Box::pin(report_sandbox_configuration(state, request)).await +} + +async fn report_sandbox_configuration( + state: &Arc, + request: Request, ) -> Result, Status> { use openshell_core::proto::ConfigurationAdmissionState; + if enforcer::is_enforcer(&request) { + enforcer::report_configuration(state, request.into_inner()).await?; + return Ok(Response::new( + openshell_core::proto::ReportSandboxConfigurationResponse {}, + )); + } let sandbox_id = request.get_ref().sandbox_id.clone(); crate::auth::guard::enforce_sandbox_scope(&request, &sandbox_id)?; let mut admission = request @@ -5216,6 +5316,7 @@ pub(super) async fn handle_report_sandbox_configuration( } if reported == ConfigurationAdmissionState::Accepted { let mut config_request = Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), supported_capabilities: vec![ openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), ], @@ -5237,6 +5338,7 @@ pub(super) async fn handle_report_sandbox_configuration( // Runtime error strings may contain parser payloads. Only gateway-authored // diagnostics may be exposed verbatim through public sandbox status. let mut config_request = Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), supported_capabilities: vec![ openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), ], @@ -5395,6 +5497,36 @@ pub async fn record_policy_apply_result( .collect::() }); let version_i64 = i64::from(version); + // The enforcer writes revision rows too, so in native-network mode the + // row and the current version change under the sandbox's guard. + let _guard = if loaded || state.compute.native_network().is_some() { + Some(acquire_policy_guard(state, sandbox_id).await?) + } else { + None + }; + if loaded + && state.compute.native_network().is_some() + && let Some(rejected) = enforcer::rejected_revision(state, sandbox_id, version).await? + { + // The revision stays failed, and records that the supervisor + // loaded it for a later enforcer acceptance. + state + .store + .update_policy_status( + sandbox_id, + version_i64, + "failed", + rejected.load_error.as_deref(), + Some(current_time_ms()), + ) + .await + .map_err(|error| Status::internal(format!("update policy status failed: {error}")))?; + info!( + sandbox_id, + version, source, "the enforcer rejected this policy revision; keeping it failed" + ); + return Ok(()); + } let updated = state .store .update_policy_status( @@ -5410,67 +5542,7 @@ pub async fn record_policy_apply_result( return Err(Status::not_found("policy revision not found")); } if loaded { - let newest_loaded = { - let Some(_mutation_guard) = state - .compute - .sandbox_mutation_guard_by_id(sandbox_id) - .await - .map_err(|error| { - super::persistence_error_to_status(error, "acquire policy mutation lock") - })? - else { - return Err(Status::not_found("sandbox not found")); - }; - let sandbox = state - .store - .get_message::(sandbox_id) - .await - .map_err(|error| Status::internal(format!("fetch sandbox failed: {error}")))? - .ok_or_else(|| Status::not_found("sandbox not found"))?; - let current_version = sandbox.current_policy_version(); - if current_version > version { - // A result can arrive after a newer revision loaded, such as - // one queued by a replaced supervisor session. The newer - // policy stays active, and so does its endpoint inventory. - current_version - } else { - let endpoint_reset = endpoint_status::endpoint_status_reset_for_loaded_policy( - state.as_ref(), - &sandbox, - version_i64, - ) - .await?; - let updated = state - .store - .update_message_cas::(sandbox_id, 0, |sandbox| { - if sandbox.current_policy_version() < version { - sandbox.set_current_policy_version(version); - } - if let Some(endpoints) = &endpoint_reset { - endpoint_status::reset_endpoint_statuses( - sandbox, - endpoints, - &prost_types::Timestamp::default(), - ); - } - }) - .await - .map_err(|error| { - super::persistence_error_to_status(error, "update current_policy_version") - })?; - state.sandbox_index.update_from_sandbox(&updated); - state.sandbox_watch_bus.notify(sandbox_id); - updated.current_policy_version() - } - }; - // Supersede below the newest loaded revision, after the current - // version settles. Of two results racing, the one finishing last then - // supersedes the older revision, even when the older revision's status - // write landed after the newer result superseded it. - let _ = state - .store - .supersede_older_policies(sandbox_id, i64::from(newest_loaded)) - .await; + advance_and_supersede(state, sandbox_id, version).await?; } info!( sandbox_id, @@ -5479,6 +5551,92 @@ pub async fn record_policy_apply_result( Ok(()) } +async fn acquire_policy_guard( + state: &Arc, + sandbox_id: &str, +) -> Result { + state + .compute + .sandbox_mutation_guard_by_id(sandbox_id) + .await + .map_err(|error| super::persistence_error_to_status(error, "acquire policy mutation lock"))? + .ok_or_else(|| Status::not_found("sandbox not found")) +} + +/// Make `version` current once it loaded, then supersede the revisions below +/// the current version. The caller holds the sandbox's mutation guard, so of +/// two results racing, the later one supersedes the older revision. +async fn advance_and_supersede( + state: &Arc, + sandbox_id: &str, + version: u32, +) -> Result<(), Status> { + let current = advance_current_policy_version(state, sandbox_id, version).await?; + let _ = state + .store + .supersede_older_policies(sandbox_id, i64::from(current)) + .await; + Ok(()) +} + +/// Make `version` the sandbox's current policy version once it loaded, and +/// return the current version. A version below the current one leaves it. +/// In native-network mode a version is current only once the enforcer has +/// accepted it too, so the advance stops at the enforcer's accepted version. +/// The caller holds the sandbox's mutation guard. +async fn advance_current_policy_version( + state: &Arc, + sandbox_id: &str, + version: u32, +) -> Result { + let sandbox = state + .store + .get_message::(sandbox_id) + .await + .map_err(|error| Status::internal(format!("fetch sandbox failed: {error}")))? + .ok_or_else(|| Status::not_found("sandbox not found"))?; + let current_version = sandbox.current_policy_version(); + let version = if state.compute.native_network().is_some() { + crate::compute::accepted_enforcer_admission(&sandbox) + .map_or(0, |admission| version.min(admission.policy_version)) + } else { + version + }; + if current_version >= version { + // A result can arrive after a newer revision loaded, such as one + // queued by a replaced supervisor session. The newer policy stays + // active, and so does its endpoint inventory. + return Ok(current_version); + } + let endpoint_reset = endpoint_status::endpoint_status_reset_for_loaded_policy( + state.as_ref(), + &sandbox, + i64::from(version), + ) + .await?; + let updated = state + .store + .update_message_cas::(sandbox_id, 0, |sandbox| { + if sandbox.current_policy_version() < version { + sandbox.set_current_policy_version(version); + } + if let Some(endpoints) = &endpoint_reset { + endpoint_status::reset_endpoint_statuses( + sandbox, + endpoints, + &prost_types::Timestamp::default(), + ); + } + }) + .await + .map_err(|error| { + super::persistence_error_to_status(error, "update current_policy_version") + })?; + state.sandbox_index.update_from_sandbox(&updated); + state.sandbox_watch_bus.notify(sandbox_id); + Ok(updated.current_policy_version()) +} + // --------------------------------------------------------------------------- // Sandbox logs handlers // --------------------------------------------------------------------------- @@ -9398,6 +9556,7 @@ mod tests { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "admission".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -9586,6 +9745,7 @@ mod tests { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "image-admission".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -9619,6 +9779,7 @@ mod tests { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "image-admission".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -9887,6 +10048,7 @@ mod tests { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: sandbox_id.clone(), workspace_scope: None, ..Default::default() @@ -9936,6 +10098,7 @@ mod tests { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: sandbox_id.to_string(), workspace_scope: None, ..Default::default() @@ -10001,6 +10164,7 @@ mod tests { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: sandbox_id.clone(), workspace_scope: None, ..Default::default() @@ -10158,6 +10322,7 @@ mod tests { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: sandbox_id.to_string(), workspace_scope: None, ..Default::default() @@ -10270,6 +10435,7 @@ mod tests { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: sandbox_id.to_string(), workspace_scope: None, ..Default::default() @@ -10340,6 +10506,7 @@ mod tests { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: sandbox_id.to_string(), workspace_scope: None, ..Default::default() @@ -12208,6 +12375,7 @@ mod tests { } let req = with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "sb-b".to_string(), workspace_scope: None, ..Default::default() @@ -12225,6 +12393,7 @@ mod tests { let state = test_server_state().await; let req = with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "missing-sandbox".to_string(), workspace_scope: None, ..Default::default() @@ -12264,6 +12433,7 @@ mod tests { state.store.put_message(&sandbox).await.unwrap(); let req = with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "self".to_string(), workspace_scope: None, ..Default::default() @@ -12280,6 +12450,7 @@ mod tests { let state = test_server_state().await; let req = with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "self".to_string(), workspace_scope: Some(openshell_core::proto::all_workspaces_selector()), ..Default::default() @@ -12496,6 +12667,7 @@ mod tests { sandbox.set_phase(SandboxPhase::Provisioning as i32); state.store.put_message(&sandbox).await.unwrap(); let req = with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "x".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -12733,6 +12905,7 @@ mod tests { handle_get_sandbox_config( state, with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: sandbox.object_name().to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( (sandbox.object_workspace()).to_string(), @@ -12851,6 +13024,7 @@ mod tests { let first = handle_get_sandbox_config( &state, with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "snapshot-consistency".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -12877,6 +13051,7 @@ mod tests { let second = handle_get_sandbox_config( &state, with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "snapshot-consistency".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -13627,6 +13802,7 @@ mod tests { let response = handle_get_sandbox_config( &state, with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "mcp-default-composed".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -14553,6 +14729,7 @@ mod tests { let error = handle_get_sandbox_config( &state, with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "invalid-composed-policy".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -14700,6 +14877,7 @@ mod tests { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "invalid-legacy".to_string(), supported_capabilities: vec![ openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), @@ -15383,6 +15561,7 @@ mod tests { let config = handle_get_sandbox_config( &state, with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "policy-binding".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -15509,6 +15688,7 @@ mod tests { let next_config = handle_get_sandbox_config( &state, with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "policy-binding".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -15576,6 +15756,7 @@ mod tests { let unbound_config = handle_get_sandbox_config( &state, with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "policy-binding".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -16924,6 +17105,7 @@ mod tests { let response = handle_get_sandbox_config( &state, with_user(Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "global-profile-sandbox".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "default".to_string(), @@ -24054,6 +24236,7 @@ mod tests { let request = || { Request::new(GetSandboxConfigRequest { name: "cedar".to_string(), + sandbox_id: String::new(), supported_capabilities: vec![ openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), ], @@ -25031,6 +25214,7 @@ mod tests { let alpha_req = with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "work".to_string(), workspace_scope: None, ..Default::default() @@ -25045,6 +25229,7 @@ mod tests { let beta_req = with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "work".to_string(), workspace_scope: None, ..Default::default() @@ -26828,6 +27013,7 @@ mod tests { let err = handle_get_sandbox_config( &state, non_member_request(GetSandboxConfigRequest { + sandbox_id: String::new(), name: "other".to_string(), workspace_scope: Some(openshell_core::proto::workspace_selector( "other-workspace".to_string(), @@ -26916,6 +27102,7 @@ mod tests { ..Default::default() }, ProviderEnvironmentValue { + workload_placeholder: String::new(), name: "TOKEN".into(), value: "secret".into(), expiration_time: openshell_core::time::timestamp_from_millis(123).ok(), diff --git a/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs b/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs index aaa9108cf9..c78be3a076 100644 --- a/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs +++ b/crates/openshell-server/src/grpc/policy/endpoint_status_tests.rs @@ -597,6 +597,7 @@ async fn report_endpoint_status_rejects_stale_configuration_epoch() { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: sandbox_id.to_string(), workspace_scope: None, ..Default::default() @@ -2122,6 +2123,7 @@ async fn report_endpoint_status_is_session_bound_and_retry_idempotent() { &state, with_sandbox( Request::new(GetSandboxConfigRequest { + sandbox_id: String::new(), name: sandbox_id.to_string(), workspace_scope: None, ..Default::default() diff --git a/crates/openshell-server/src/grpc/policy/enforcer.rs b/crates/openshell-server/src/grpc/policy/enforcer.rs new file mode 100644 index 0000000000..bfff7c6a2b --- /dev/null +++ b/crates/openshell-server/src/grpc/policy/enforcer.rs @@ -0,0 +1,1475 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! The native-network enforcer's side of sandbox configuration. +//! +//! In native-network mode a host enforcer applies each sandbox's network +//! policy outside the workload. The gateway holds workload activation until +//! the enforcer accepts the sandbox's current runtime generation, and a policy +//! revision becomes current only once both the supervisor and the enforcer +//! have accepted it. + +use super::{ + acquire_policy_guard, advance_and_supersede, bounded_configuration_diagnostic, + build_base_sandbox_config_snapshot, build_provider_environment_snapshot, + configuration_generation_matches, is_configuration_rejection, provider_environment_response, + sandbox_config_response, unadmitted_sandbox_config, +}; +use crate::ServerState; +use crate::auth::principal::Principal; +use crate::persistence::PolicyRecord; +use crate::policy_store::PolicyStoreExt; +use openshell_core::ObjectId; +use openshell_core::proto::{ + ConfigurationAdmissionState, GetSandboxConfigRequest, GetSandboxConfigResponse, + GetSandboxProviderEnvironmentRequest, GetSandboxProviderEnvironmentResponse, + ProviderEnvironmentValueClassification, ReportSandboxConfigurationRequest, Sandbox, + SandboxConfigSnapshot, SandboxConfigurationAdmission, +}; +use openshell_supervisor_control::HostRole; +use std::sync::Arc; +use tonic::{Request, Status}; +use tracing::info; + +/// Prefix of a policy revision's load error written for an enforcer rejection. +/// It keeps a later supervisor load result from marking the revision loaded. +/// The row keeps `loaded_at_ms`, which records whether the supervisor loaded +/// the revision. +pub(super) const ENFORCER_LOAD_ERROR_PREFIX: &str = "enforcer: "; + +pub(super) fn is_enforcer(request: &Request) -> bool { + matches!( + request.extensions().get::(), + Some(Principal::Supervisor(host)) if host.identity.role == HostRole::Enforcer + ) +} + +fn check_enforcer_request(state: &ServerState, sandbox_id: &str) -> Result<(), Status> { + if state.compute.native_network().is_none() { + return Err(Status::permission_denied( + "the gateway does not run in native-network mode", + )); + } + if sandbox_id.is_empty() { + return Err(Status::invalid_argument("sandbox_id is required")); + } + Ok(()) +} + +/// Resolve the sandbox an enforcer request names by ID. The enforcer reaches +/// only sandboxes created in native-network mode that have a runtime +/// generation, never a stock sandbox left from before the mode was enabled. +async fn enforcer_sandbox(state: &ServerState, sandbox_id: &str) -> Result { + check_enforcer_request(state, sandbox_id)?; + let sandbox = state + .store + .get_message::(sandbox_id) + .await + .map_err(|error| Status::internal(format!("fetch sandbox failed: {error}")))? + .ok_or_else(|| Status::not_found("sandbox not found"))?; + if sandbox + .status + .as_ref() + .and_then(|status| status.enforcer_admission.as_ref()) + .is_none() + { + return Err(Status::permission_denied( + "the sandbox was not created in native-network mode", + )); + } + crate::compute::sandbox_runtime_generation(&sandbox).map_err(Status::failed_precondition)?; + Ok(sandbox) +} + +/// The enforcer's accepted `provider_env_revision` for the sandbox's current +/// runtime generation, or 0. +fn accepted_provider_env_revision(sandbox: &Sandbox) -> u64 { + crate::compute::accepted_enforcer_admission(sandbox) + .map_or(0, |admission| admission.provider_env_revision) +} + +/// The configuration the enforcer judges: the base snapshot, unaffected by the +/// activation hold, with the runtime generation the enforcer reports against. +pub(super) async fn sandbox_config( + state: &Arc, + request: &GetSandboxConfigRequest, +) -> Result { + if !request.name.is_empty() || request.workspace_scope.is_some() { + return Err(Status::invalid_argument( + "the enforcer selects a sandbox by sandbox_id only; leave name and workspace_scope empty", + )); + } + let sandbox = enforcer_sandbox(state, &request.sandbox_id).await?; + let generation = crate::compute::sandbox_runtime_generation(&sandbox) + .map_err(Status::failed_precondition)?; + let mut snapshot = match build_base_sandbox_config_snapshot(state, &sandbox).await { + Ok(snapshot) => snapshot, + Err(error) if is_configuration_rejection(&error) => { + unadmitted_sandbox_config(state, &sandbox, &error) + } + Err(error) => return Err(error), + }; + super::require_policy_capabilities( + request.supported_capabilities.clone(), + snapshot.policy.as_ref(), + )?; + snapshot.configuration_instance_id = generation.as_str().to_string(); + snapshot.enforcer_provider_env_revision = accepted_provider_env_revision(&sandbox); + Ok(sandbox_config_response(snapshot)) +} + +/// The sandbox's provider environment with the placeholder the workload +/// receives for each static credential, so the enforcer can substitute it. +pub(super) async fn provider_environment( + state: &Arc, + request: &GetSandboxProviderEnvironmentRequest, +) -> Result { + let sandbox = enforcer_sandbox(state, &request.sandbox_id).await?; + if !request.supports_static_credential_bindings + || !request.supports_stable_placeholder_environment_keys + { + return Err(Status::invalid_argument( + "the enforcer must support static credential bindings and stable placeholder keys", + )); + } + let mut snapshot = build_provider_environment_snapshot( + state, + &sandbox, + request.supports_static_credential_bindings, + request.supports_stable_placeholder_environment_keys, + ) + .await?; + let revision = snapshot.provider_env_revision; + for value in &mut snapshot.values { + if value.classification + != i32::from(ProviderEnvironmentValueClassification::StaticCredential) + { + continue; + } + let handle = value + .static_credential_binding + .as_ref() + .map(|binding| binding.workload_credential_handle.as_str()) + .filter(|_| value.stable_placeholder); + value.workload_placeholder = + openshell_core::secrets::workload_placeholder(&value.name, revision, handle); + } + Ok(provider_environment_response(snapshot)) +} + +/// Hold a sandbox's first activation until the enforcer accepts its current +/// runtime generation. Once the supervisor has accepted a configuration, the +/// workload runs and later updates reach both sides without a hold. +pub(super) fn apply_enforcer_hold( + state: &ServerState, + snapshot: &mut SandboxConfigSnapshot, + sandbox: &Sandbox, +) { + if state.compute.native_network().is_none() { + return; + } + snapshot.enforcer_provider_env_revision = accepted_provider_env_revision(sandbox); + let status = sandbox.status.as_ref(); + let supervisor_accepted = status + .and_then(|status| status.configuration_admission.as_ref()) + .is_some_and(|admission| { + admission.state == i32::from(ConfigurationAdmissionState::Accepted) + }); + if !snapshot.configuration_admitted + || supervisor_accepted + || crate::compute::accepted_enforcer_admission(sandbox).is_some() + { + return; + } + let rejection = crate::compute::current_enforcer_admission(sandbox).filter(|admission| { + admission.state == i32::from(ConfigurationAdmissionState::Rejected) + && admission.policy_hash == snapshot.policy_hash + && admission.provider_env_revision == snapshot.provider_env_revision + }); + snapshot.configuration_admitted = false; + if let Some(rejection) = rejection { + snapshot.configuration_error = crate::compute::enforcer_rejection_message(&rejection.error); + } else { + snapshot.activation_pending = true; + snapshot.configuration_error = crate::compute::ENFORCER_PENDING_MESSAGE.to_string(); + } +} + +/// Policy revision `version` when the enforcer rejected it. The caller holds +/// the sandbox's mutation guard. +pub(super) async fn rejected_revision( + state: &ServerState, + sandbox_id: &str, + version: u32, +) -> Result, Status> { + Ok(fetch_revision(state, sandbox_id, version) + .await? + .filter(is_enforcer_failure)) +} + +async fn fetch_revision( + state: &ServerState, + sandbox_id: &str, + version: u32, +) -> Result, Status> { + state + .store + .get_policy_by_version(sandbox_id, i64::from(version)) + .await + .map_err(|error| Status::internal(format!("fetch policy revision failed: {error}"))) +} + +async fn set_revision_status( + state: &ServerState, + record: &PolicyRecord, + status: &str, + load_error: Option<&str>, +) -> Result<(), Status> { + state + .store + .update_policy_status( + &record.sandbox_id, + record.version, + status, + load_error, + record.loaded_at_ms, + ) + .await + .map(|_| ()) + .map_err(|error| Status::internal(format!("update policy status failed: {error}"))) +} + +fn is_enforcer_failure(record: &PolicyRecord) -> bool { + record.status == "failed" + && record + .load_error + .as_deref() + .is_some_and(|error| error.starts_with(ENFORCER_LOAD_ERROR_PREFIX)) +} + +/// Record the enforcer's verdict on a sandbox's configuration. +pub(super) async fn report_configuration( + state: &Arc, + request: ReportSandboxConfigurationRequest, +) -> Result<(), Status> { + let sandbox_id = request.sandbox_id; + let mut admission = request + .admission + .ok_or_else(|| Status::invalid_argument("admission is required"))?; + let reported = ConfigurationAdmissionState::try_from(admission.state) + .map_err(|_| Status::invalid_argument("invalid admission state"))?; + if !matches!( + reported, + ConfigurationAdmissionState::Accepted | ConfigurationAdmissionState::Rejected + ) { + return Err(Status::invalid_argument( + "the enforcer reports ACCEPTED or REJECTED", + )); + } + check_enforcer_request(state, &sandbox_id)?; + let _guard = acquire_policy_guard(state, &sandbox_id).await?; + let mut sandbox = enforcer_sandbox(state, &sandbox_id).await?; + check_report_generation(&sandbox, &admission)?; + // A verdict on a configuration that has since changed is stale either way. + let snapshot = build_base_sandbox_config_snapshot(state, &sandbox) + .await + .map_err(|error| { + if is_configuration_rejection(&error) { + Status::aborted("configuration is not admitted; fetch and validate again") + } else { + error + } + })?; + let config = sandbox_config_response(snapshot); + // While the enforcer holds back a policy update, it may still accept the + // current provider revision under the policy it already enforces, so + // credential rotation doesn't wait on an unrelated policy fix. + let accepted_policy = crate::compute::accepted_enforcer_admission(&sandbox) + .filter(|accepted| same_policy(accepted, &admission)) + .cloned(); + let rotation = accepted_policy + .filter(|_| reported == ConfigurationAdmissionState::Accepted) + .filter(|_| admission.provider_env_revision == config.provider_env_revision) + .filter(|accepted| accepted.provider_env_revision != admission.provider_env_revision); + if !config.configuration_admitted + || (rotation.is_none() && !configuration_generation_matches(&admission, &config)) + { + return Err(Status::aborted( + "configuration changed or is not admitted; fetch and validate again", + )); + } + if reported == ConfigurationAdmissionState::Accepted { + admission.error.clear(); + } else { + admission.error = bounded_configuration_diagnostic(&admission.error) + .trim() + .to_string(); + if admission.error.is_empty() { + admission.error = "no reason given".to_string(); + } + } + // A rejection of the configuration the enforcer already accepted comes + // from a replica that lost the sandbox; the accepting replica enforces it. + if reported == ConfigurationAdmissionState::Rejected + && crate::compute::accepted_enforcer_admission(&sandbox) + .is_some_and(|accepted| same_configuration(accepted, &admission)) + { + return Ok(()); + } + // The guard excludes every configuration writer, but driver status + // writes still race the slow snapshot build above. + let mut attempts = 0; + let updated = loop { + // A rejected update does not undo the configuration the enforcer + // already applies. + let stored_admission = match crate::compute::accepted_enforcer_admission(&sandbox) { + Some(current) if rotation.is_some() => { + if !same_policy(current, &admission) { + return Err(Status::aborted( + "configuration changed; fetch and validate again", + )); + } + SandboxConfigurationAdmission { + provider_env_revision: admission.provider_env_revision, + ..current.clone() + } + } + None if rotation.is_some() => { + return Err(Status::aborted( + "configuration changed; fetch and validate again", + )); + } + Some(current) if reported == ConfigurationAdmissionState::Rejected => { + SandboxConfigurationAdmission { + error: admission.error.clone(), + ..current.clone() + } + } + _ => admission.clone(), + }; + let expected_version = sandbox + .metadata + .as_ref() + .map_or(0, |metadata| metadata.resource_version); + match state + .store + .update_message_cas::(&sandbox_id, expected_version, |sandbox| { + sandbox + .status + .get_or_insert_with(Default::default) + .enforcer_admission = Some(stored_admission.clone()); + crate::compute::apply_configuration_readiness(sandbox); + }) + .await + { + Ok(updated) => break updated, + Err(crate::persistence::PersistenceError::Conflict { .. }) if attempts < 3 => { + attempts += 1; + sandbox = enforcer_sandbox(state, &sandbox_id).await?; + check_report_generation(&sandbox, &admission)?; + } + Err(error) => { + return Err(super::super::persistence_error_to_status( + error, + "report enforcer admission", + )); + } + } + }; + state.sandbox_index.update_from_sandbox(&updated); + state.sandbox_watch_bus.notify(&sandbox_id); + if rotation.is_some() { + return Ok(()); + } + match reported { + ConfigurationAdmissionState::Accepted => { + record_accepted_revision(state, &updated, admission.policy_version).await + } + _ => record_rejected_revision(state, &updated, &admission).await, + } +} + +fn check_report_generation( + sandbox: &Sandbox, + admission: &SandboxConfigurationAdmission, +) -> Result<(), Status> { + let generation = + crate::compute::sandbox_runtime_generation(sandbox).map_err(Status::failed_precondition)?; + if admission.instance_id != generation.as_str() { + return Err(Status::failed_precondition( + "sandbox runtime generation has changed", + )); + } + Ok(()) +} + +fn same_policy( + left: &SandboxConfigurationAdmission, + right: &SandboxConfigurationAdmission, +) -> bool { + ( + &left.instance_id, + left.policy_version, + &left.policy_hash, + left.config_revision, + ) == ( + &right.instance_id, + right.policy_version, + &right.policy_hash, + right.config_revision, + ) +} + +fn same_configuration( + left: &SandboxConfigurationAdmission, + right: &SandboxConfigurationAdmission, +) -> bool { + ( + &left.instance_id, + left.policy_version, + &left.policy_hash, + left.config_revision, + left.provider_env_revision, + ) == ( + &right.instance_id, + right.policy_version, + &right.policy_hash, + right.config_revision, + right.provider_env_revision, + ) +} + +/// Mark the rejected revision failed so `policy --wait` reports the +/// enforcer's rejection. The current revision stays active on both sides. +/// The admission names the revision by version: its hash is of the effective +/// policy, which differs from the revision's once providers add rules. A +/// revision the supervisor failed keeps the supervisor's error. A revision the +/// enforcer has accepted stays accepted: a late rejection, such as one from a +/// replica that lost the sandbox, must not fail it. +async fn record_rejected_revision( + state: &ServerState, + sandbox: &Sandbox, + admission: &SandboxConfigurationAdmission, +) -> Result<(), Status> { + let accepted_version = crate::compute::accepted_enforcer_admission(sandbox) + .map_or(0, |accepted| accepted.policy_version); + if admission.policy_version <= sandbox.current_policy_version() + || admission.policy_version <= accepted_version + { + return Ok(()); + } + let Some(rejected) = + fetch_revision(state, sandbox.object_id(), admission.policy_version).await? + else { + return Ok(()); + }; + if !matches!(rejected.status.as_str(), "pending" | "loaded") && !is_enforcer_failure(&rejected) + { + return Ok(()); + } + let load_error = format!("{ENFORCER_LOAD_ERROR_PREFIX}{}", admission.error); + set_revision_status(state, &rejected, "failed", Some(&load_error)).await?; + info!( + sandbox_id = sandbox.object_id(), + version = rejected.version, + "the network enforcer rejected a policy revision" + ); + Ok(()) +} + +/// Advance the current policy version to the accepted revision when the +/// supervisor has loaded it too. A revision a prior enforcer rejection failed +/// returns to the status the supervisor's result gives it. +async fn record_accepted_revision( + state: &Arc, + sandbox: &Sandbox, + version: u32, +) -> Result<(), Status> { + let Some(record) = fetch_revision(state, sandbox.object_id(), version).await? else { + return Ok(()); + }; + let loaded = if is_enforcer_failure(&record) { + let loaded = record.loaded_at_ms.is_some(); + set_revision_status( + state, + &record, + if loaded { "loaded" } else { "pending" }, + None, + ) + .await?; + loaded + } else { + record.status == "loaded" + }; + if loaded { + advance_and_supersede(state, sandbox.object_id(), version).await?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::super::tests::{test_provider, test_sandbox, with_sandbox}; + use super::super::{ + deterministic_policy_hash, handle_get_sandbox_config, handle_get_sandbox_policy_status, + handle_get_sandbox_provider_environment, handle_report_policy_status, + handle_report_sandbox_configuration, + }; + use crate::auth::principal::{Principal, SupervisorPrincipal}; + use crate::grpc::test_support::{authed_request, test_native_network_server_state}; + use crate::policy_store::PolicyStoreExt; + use openshell_core::proto::{ + ConfigurationAdmissionState as Admission, GetSandboxConfigRequest, + GetSandboxConfigResponse, GetSandboxPolicyStatusRequest, + GetSandboxProviderEnvironmentRequest, NetworkMiddlewareConfig, PolicyStatus, + ReportPolicyStatusRequest, ReportSandboxConfigurationRequest, Sandbox, + SandboxConfigurationAdmission, + }; + use openshell_core::sandbox_generation::SandboxGenerationId; + use openshell_supervisor_control::{HostIdentity, HostRole}; + use prost::Message; + use std::sync::Arc; + use tonic::{Code, Request}; + + const SANDBOX_ID: &str = "sb-enforced"; + + fn as_enforcer(mut request: Request) -> Request { + request + .extensions_mut() + .insert(Principal::Supervisor(SupervisorPrincipal { + identity: HostIdentity { + subject: "openshell-enforcer:test".to_string(), + token_id: "token".to_string(), + expires_at: i64::MAX, + node: None, + role: HostRole::Enforcer, + }, + })); + request + } + + /// A native-network sandbox whose supervisor registered, with policy + /// revision 1 stored. + async fn enforced_sandbox() -> (Arc, String) { + enforced_sandbox_with(openshell_policy::restrictive_default_policy(), Vec::new()).await + } + + async fn enforced_sandbox_with( + policy: openshell_core::proto::SandboxPolicy, + providers: Vec, + ) -> (Arc, String) { + let state = test_native_network_server_state().await; + let mut sandbox = test_sandbox(SANDBOX_ID, "enforced", policy.clone(), providers); + let generation = SandboxGenerationId::from_start_resource_version(7); + sandbox.metadata.as_mut().unwrap().annotations.insert( + crate::auth::sandbox_session::RUNTIME_GENERATION_ANNOTATION.to_string(), + generation.as_str().to_string(), + ); + let status = sandbox.status.get_or_insert_with(Default::default); + status.configuration_admission = Some(SandboxConfigurationAdmission { + instance_id: uuid::Uuid::new_v4().to_string(), + state: Admission::Pending.into(), + ..Default::default() + }); + status.enforcer_admission = Some(SandboxConfigurationAdmission { + state: Admission::Pending.into(), + ..Default::default() + }); + state.store.put_message(&sandbox).await.unwrap(); + put_revision(&state, 1, &policy).await; + (state, generation.into_string()) + } + + async fn put_revision( + state: &crate::ServerState, + version: i64, + policy: &openshell_core::proto::SandboxPolicy, + ) { + state + .store + .put_policy_revision( + &format!("{SANDBOX_ID}-v{version}"), + SANDBOX_ID, + "default", + version, + &policy.encode_to_vec(), + &deterministic_policy_hash(policy), + ) + .await + .unwrap(); + } + + async fn supervisor_config(state: &Arc) -> GetSandboxConfigResponse { + handle_get_sandbox_config( + state, + with_sandbox( + Request::new(GetSandboxConfigRequest { + name: "enforced".to_string(), + ..Default::default() + }), + SANDBOX_ID, + ), + ) + .await + .unwrap() + .into_inner() + } + + async fn enforcer_config(state: &Arc) -> GetSandboxConfigResponse { + handle_get_sandbox_config( + state, + as_enforcer(Request::new(GetSandboxConfigRequest { + sandbox_id: SANDBOX_ID.to_string(), + ..Default::default() + })), + ) + .await + .unwrap() + .into_inner() + } + + async fn enforcer_report( + state: &Arc, + admission: SandboxConfigurationAdmission, + ) -> Result<(), tonic::Status> { + handle_report_sandbox_configuration( + state, + as_enforcer(Request::new(ReportSandboxConfigurationRequest { + sandbox_id: SANDBOX_ID.to_string(), + admission: Some(admission), + expected_instance_id: String::new(), + })), + ) + .await + .map(|_| ()) + } + + fn verdict( + config: &GetSandboxConfigResponse, + state: Admission, + ) -> SandboxConfigurationAdmission { + SandboxConfigurationAdmission { + instance_id: config.configuration_instance_id.clone(), + state: state.into(), + policy_version: config.version, + policy_hash: config.policy_hash.clone(), + config_revision: config.config_revision, + provider_env_revision: config.provider_env_revision, + error: String::new(), + } + } + + async fn stored(state: &crate::ServerState) -> Sandbox { + state + .store + .get_message::(SANDBOX_ID) + .await + .unwrap() + .unwrap() + } + + fn ready_reason(sandbox: &Sandbox) -> String { + sandbox + .status + .as_ref() + .unwrap() + .conditions + .iter() + .find(|condition| condition.r#type == "ConfigurationReady") + .map(|condition| condition.reason.clone()) + .unwrap_or_default() + } + + #[tokio::test] + async fn activation_waits_for_the_enforcer_to_accept_the_generation() { + let (state, generation) = enforced_sandbox().await; + let mut sandbox = stored(&state).await; + crate::compute::apply_configuration_readiness(&mut sandbox); + assert_eq!(ready_reason(&sandbox), crate::compute::ENFORCER_PENDING); + + let held = supervisor_config(&state).await; + assert!(!held.configuration_admitted); + assert!(held.activation_pending); + + let judged = enforcer_config(&state).await; + assert!( + judged.configuration_admitted, + "the enforcer reads the base snapshot" + ); + assert!(!judged.activation_pending); + assert_eq!(judged.configuration_instance_id, generation); + + let mut rejected = verdict(&judged, Admission::Rejected); + rejected.error = "VF unavailable\non node".to_string(); + enforcer_report(&state, rejected).await.unwrap(); + let refused = supervisor_config(&state).await; + assert!(!refused.configuration_admitted); + assert!(!refused.activation_pending, "a rejection is not a wait"); + assert_eq!( + refused.configuration_error, + "The network enforcer rejected the configuration: VF unavailable on node" + ); + assert_eq!( + ready_reason(&stored(&state).await), + crate::compute::ENFORCER_REJECTED + ); + let mut echoed = stored(&state).await; + let status = echoed.status.as_mut().unwrap(); + let supervisor = status.configuration_admission.as_mut().unwrap(); + supervisor.state = Admission::Rejected.into(); + supervisor.error.clone_from(&refused.configuration_error); + crate::compute::apply_configuration_readiness(&mut echoed); + assert_eq!( + ready_reason(&echoed), + crate::compute::ENFORCER_REJECTED, + "the supervisor's echo of the rejection keeps the enforcer as its source" + ); + echoed + .status + .as_mut() + .unwrap() + .configuration_admission + .as_mut() + .unwrap() + .error = "invalid policy".to_string(); + crate::compute::apply_configuration_readiness(&mut echoed); + assert_eq!(ready_reason(&echoed), "ConfigurationInvalid"); + + let mut old_generation = verdict(&judged, Admission::Accepted); + old_generation.instance_id = + SandboxGenerationId::from_start_resource_version(3).into_string(); + assert_eq!( + enforcer_report(&state, old_generation) + .await + .unwrap_err() + .code(), + Code::FailedPrecondition + ); + let mut outdated = verdict(&judged, Admission::Accepted); + outdated.policy_hash = "outdated".to_string(); + assert_eq!( + enforcer_report(&state, outdated).await.unwrap_err().code(), + Code::Aborted + ); + + enforcer_report(&state, verdict(&judged, Admission::Accepted)) + .await + .unwrap(); + let released = supervisor_config(&state).await; + assert!(released.configuration_admitted); + assert!(!released.activation_pending); + assert_eq!( + released.enforcer_provider_env_revision, + judged.provider_env_revision + ); + } + + #[tokio::test] + async fn readiness_ignores_a_previous_generations_rejection() { + let (state, _) = enforced_sandbox().await; + let mut rejected = verdict(&enforcer_config(&state).await, Admission::Rejected); + rejected.error = "VF unavailable".to_string(); + enforcer_report(&state, rejected).await.unwrap(); + let mut sandbox = stored(&state).await; + sandbox.metadata.as_mut().unwrap().annotations.insert( + crate::auth::sandbox_session::RUNTIME_GENERATION_ANNOTATION.to_string(), + SandboxGenerationId::from_start_resource_version(9).into_string(), + ); + crate::compute::apply_configuration_readiness(&mut sandbox); + let condition = sandbox + .status + .as_ref() + .unwrap() + .conditions + .iter() + .find(|condition| condition.r#type == "ConfigurationReady") + .unwrap(); + assert_eq!(condition.reason, crate::compute::ENFORCER_PENDING); + assert_eq!(condition.message, crate::compute::ENFORCER_PENDING_MESSAGE); + } + + #[cfg(feature = "experimental")] + #[tokio::test] + async fn a_cedar_policy_needs_an_enforcer_with_cedar_support() { + let cedar_policy = openshell_core::proto::SandboxPolicy { + version: 1, + cedar_policy: Some(openshell_core::proto::CedarPolicy { + source: "permit(principal, \ + action == Sandbox::Action::\"NetworkConnect\", \ + resource == Sandbox::NetworkEndpoint::\"api.github.com:443\");" + .to_string(), + }), + ..Default::default() + }; + let (state, _) = enforced_sandbox_with(cedar_policy, Vec::new()).await; + let request = |supported_capabilities: Vec| { + as_enforcer(Request::new(GetSandboxConfigRequest { + sandbox_id: SANDBOX_ID.to_string(), + supported_capabilities, + ..Default::default() + })) + }; + let error = handle_get_sandbox_config(&state, request(Vec::new())) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::Unimplemented); + let config = handle_get_sandbox_config( + &state, + request(vec![ + openshell_core::extension_protocol::POLICY_CEDAR_V1.to_string(), + ]), + ) + .await + .unwrap() + .into_inner(); + assert!( + config + .policy + .is_some_and(|policy| policy.cedar_policy.is_some()) + ); + } + + #[tokio::test] + async fn only_the_enforcer_selects_a_sandbox_by_id() { + let (state, _) = enforced_sandbox().await; + let error = handle_get_sandbox_config( + &state, + with_sandbox( + Request::new(GetSandboxConfigRequest { + sandbox_id: SANDBOX_ID.to_string(), + name: "enforced".to_string(), + ..Default::default() + }), + SANDBOX_ID, + ), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::InvalidArgument); + + let error = handle_get_sandbox_config( + &state, + as_enforcer(Request::new(GetSandboxConfigRequest::default())), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::InvalidArgument); + for request in [ + GetSandboxConfigRequest { + sandbox_id: SANDBOX_ID.to_string(), + name: "enforced".to_string(), + ..Default::default() + }, + GetSandboxConfigRequest { + sandbox_id: SANDBOX_ID.to_string(), + workspace_scope: Some( + openshell_core::proto::datamodel::v1::WorkspaceSelector::default(), + ), + ..Default::default() + }, + ] { + let error = handle_get_sandbox_config(&state, as_enforcer(Request::new(request))) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::InvalidArgument); + } + + let judged = enforcer_config(&state).await; + assert_eq!( + enforcer_report(&state, verdict(&judged, Admission::Pending)) + .await + .unwrap_err() + .code(), + Code::InvalidArgument + ); + } + + async fn supervisor_loaded(state: &Arc, version: u32) { + handle_report_policy_status( + state, + with_sandbox( + Request::new(ReportPolicyStatusRequest { + sandbox_id: SANDBOX_ID.to_string(), + version, + status: PolicyStatus::Loaded as i32, + load_error: String::new(), + }), + SANDBOX_ID, + ), + ) + .await + .unwrap(); + } + + async fn policy_status(state: &Arc, version: u32) -> (PolicyStatus, u32) { + let response = handle_get_sandbox_policy_status( + state, + authed_request(GetSandboxPolicyStatusRequest { + sandbox: "enforced".to_string(), + version, + workspace_scope: Some(openshell_core::proto::workspace_selector( + "default".to_string(), + )), + ..Default::default() + }), + ) + .await + .unwrap() + .into_inner(); + let revision = response.revision.unwrap(); + ( + PolicyStatus::try_from(revision.status).unwrap(), + response.active_version, + ) + } + + #[tokio::test] + async fn a_revision_is_current_once_both_sides_accept_it() { + let (state, _) = enforced_sandbox().await; + enforcer_report( + &state, + verdict(&enforcer_config(&state).await, Admission::Accepted), + ) + .await + .unwrap(); + supervisor_loaded(&state, 1).await; + assert_eq!(policy_status(&state, 1).await, (PolicyStatus::Loaded, 1)); + + let mut update = openshell_policy::restrictive_default_policy(); + update + .filesystem + .as_mut() + .unwrap() + .read_only + .push("/opt".to_string()); + put_revision(&state, 2, &update).await; + supervisor_loaded(&state, 2).await; + assert_eq!( + policy_status(&state, 2).await, + (PolicyStatus::Pending, 1), + "the supervisor alone does not make a revision current" + ); + + let judged = enforcer_config(&state).await; + assert_eq!(judged.version, 2); + let mut rejected = verdict(&judged, Admission::Rejected); + rejected.error = "rule unsupported".to_string(); + enforcer_report(&state, rejected).await.unwrap(); + assert_eq!(policy_status(&state, 2).await, (PolicyStatus::Failed, 1)); + let accepted = stored(&state).await; + let kept = crate::compute::accepted_enforcer_admission(&accepted) + .expect("a rejected update keeps the accepted configuration"); + assert_eq!(kept.policy_version, 1); + assert_eq!(kept.error, "rule unsupported"); + + supervisor_loaded(&state, 2).await; + assert_eq!( + policy_status(&state, 2).await, + (PolicyStatus::Failed, 1), + "a supervisor load does not clear the enforcer's rejection" + ); + + enforcer_report(&state, verdict(&judged, Admission::Accepted)) + .await + .unwrap(); + assert_eq!(policy_status(&state, 2).await, (PolicyStatus::Loaded, 2)); + assert_eq!(policy_status(&state, 1).await.0, PolicyStatus::Superseded); + } + + async fn supervisor_failed(state: &Arc, version: u32) { + handle_report_policy_status( + state, + with_sandbox( + Request::new(ReportPolicyStatusRequest { + sandbox_id: SANDBOX_ID.to_string(), + version, + status: PolicyStatus::Failed as i32, + load_error: "landlock refused".to_string(), + }), + SANDBOX_ID, + ), + ) + .await + .unwrap(); + } + + fn update_policy() -> openshell_core::proto::SandboxPolicy { + let mut update = openshell_policy::restrictive_default_policy(); + update + .filesystem + .as_mut() + .unwrap() + .read_only + .push("/opt".to_string()); + update + } + + #[tokio::test] + async fn an_accepted_rejection_waits_for_the_supervisor_load() { + let (state, _) = enforced_sandbox().await; + enforcer_report( + &state, + verdict(&enforcer_config(&state).await, Admission::Accepted), + ) + .await + .unwrap(); + supervisor_loaded(&state, 1).await; + put_revision(&state, 2, &update_policy()).await; + + let judged = enforcer_config(&state).await; + let mut rejected = verdict(&judged, Admission::Rejected); + rejected.error = "rule unsupported".to_string(); + enforcer_report(&state, rejected).await.unwrap(); + assert_eq!(policy_status(&state, 2).await, (PolicyStatus::Failed, 1)); + + enforcer_report(&state, verdict(&judged, Admission::Accepted)) + .await + .unwrap(); + assert_eq!( + policy_status(&state, 2).await, + (PolicyStatus::Pending, 1), + "the supervisor has not loaded the revision" + ); + supervisor_loaded(&state, 2).await; + assert_eq!(policy_status(&state, 2).await, (PolicyStatus::Loaded, 2)); + } + + #[tokio::test] + async fn a_late_rejection_does_not_fail_an_accepted_revision() { + let (state, _) = enforced_sandbox().await; + enforcer_report( + &state, + verdict(&enforcer_config(&state).await, Admission::Accepted), + ) + .await + .unwrap(); + supervisor_loaded(&state, 1).await; + put_revision(&state, 2, &update_policy()).await; + + let judged = enforcer_config(&state).await; + enforcer_report(&state, verdict(&judged, Admission::Accepted)) + .await + .unwrap(); + let mut late = verdict(&judged, Admission::Rejected); + late.error = "replica lost the node".to_string(); + enforcer_report(&state, late).await.unwrap(); + assert_eq!(policy_status(&state, 2).await, (PolicyStatus::Pending, 1)); + let sandbox = stored(&state).await; + let status = sandbox.status.as_ref().unwrap(); + assert!(status.enforcer_admission.as_ref().unwrap().error.is_empty()); + assert!( + !status + .conditions + .iter() + .any(|condition| condition.reason == crate::compute::ENFORCER_REJECTED) + ); + + supervisor_loaded(&state, 2).await; + assert_eq!(policy_status(&state, 2).await, (PolicyStatus::Loaded, 2)); + } + + #[tokio::test] + async fn a_rejection_of_a_changed_configuration_is_stale() { + let (state, _) = enforced_sandbox().await; + let judged = enforcer_config(&state).await; + let mut outdated = verdict(&judged, Admission::Rejected); + outdated.policy_hash = "outdated".to_string(); + assert_eq!( + enforcer_report(&state, outdated).await.unwrap_err().code(), + Code::Aborted + ); + assert!(supervisor_config(&state).await.activation_pending); + } + + #[tokio::test] + async fn a_rejected_update_of_an_active_sandbox_is_reported() { + let (state, _) = enforced_sandbox().await; + enforcer_report( + &state, + verdict(&enforcer_config(&state).await, Admission::Accepted), + ) + .await + .unwrap(); + let mut sandbox = stored(&state).await; + let status = sandbox.status.as_mut().unwrap(); + status.configuration_admission.as_mut().unwrap().state = Admission::Accepted.into(); + state.store.put_message(&sandbox).await.unwrap(); + put_revision(&state, 2, &update_policy()).await; + + let mut rejected = verdict(&enforcer_config(&state).await, Admission::Rejected); + rejected.error = "rule unsupported".to_string(); + enforcer_report(&state, rejected).await.unwrap(); + let sandbox = stored(&state).await; + let condition = sandbox + .status + .as_ref() + .unwrap() + .conditions + .iter() + .find(|condition| condition.r#type == "DesiredConfigurationReady") + .expect("the rejected update is reported"); + assert_eq!(condition.reason, crate::compute::ENFORCER_REJECTED); + assert_eq!( + condition.message, + "The network enforcer rejected the configuration: rule unsupported" + ); + assert_eq!(ready_reason(&sandbox), "ConfigurationAccepted"); + } + + #[tokio::test] + async fn credentials_rotate_while_a_policy_update_is_rejected() { + use crate::persistence::{ObjectId, ObjectName, ObjectType, ObjectWorkspace}; + use openshell_core::proto::Provider; + + let (state, _) = enforced_sandbox_with( + openshell_policy::restrictive_default_policy(), + vec!["work-github".to_string()], + ) + .await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + let accepted = enforcer_config(&state).await; + enforcer_report(&state, verdict(&accepted, Admission::Accepted)) + .await + .unwrap(); + supervisor_loaded(&state, 1).await; + put_revision(&state, 2, &update_policy()).await; + let mut rejected = verdict(&enforcer_config(&state).await, Admission::Rejected); + rejected.error = "rule unsupported".to_string(); + enforcer_report(&state, rejected).await.unwrap(); + + let mut rotated = test_provider("work-github", "github"); + rotated + .credentials + .insert("GITHUB_TOKEN".to_string(), "ghp-rotated".to_string()); + state + .store + .put_if( + Provider::object_type(), + rotated.object_id(), + rotated.object_name(), + rotated.object_workspace(), + &rotated.encode_to_vec(), + None, + crate::persistence::WriteCondition::Unconditional, + ) + .await + .unwrap(); + let current = enforcer_config(&state).await; + assert_ne!( + current.provider_env_revision, + accepted.provider_env_revision + ); + + let mut rotation = verdict(&accepted, Admission::Accepted); + rotation.provider_env_revision = current.provider_env_revision; + enforcer_report(&state, rotation).await.unwrap(); + + let sandbox = stored(&state).await; + let admission = crate::compute::accepted_enforcer_admission(&sandbox).unwrap(); + assert_eq!(admission.policy_version, 1); + assert_eq!( + admission.provider_env_revision, + current.provider_env_revision + ); + assert_eq!(admission.error, "rule unsupported"); + assert_eq!( + supervisor_config(&state) + .await + .enforcer_provider_env_revision, + current.provider_env_revision + ); + assert_eq!(policy_status(&state, 2).await, (PolicyStatus::Failed, 1)); + } + + #[tokio::test] + async fn a_supervisor_takeover_after_acceptance_is_not_held() { + let (state, _) = enforced_sandbox().await; + let accepted = enforcer_config(&state).await; + enforcer_report(&state, verdict(&accepted, Admission::Accepted)) + .await + .unwrap(); + put_revision(&state, 2, &update_policy()).await; + let mut rejected = verdict(&enforcer_config(&state).await, Admission::Rejected); + rejected.error = "rule unsupported".to_string(); + enforcer_report(&state, rejected).await.unwrap(); + + let mut sandbox = stored(&state).await; + sandbox + .status + .as_mut() + .unwrap() + .configuration_admission + .as_mut() + .unwrap() + .instance_id = uuid::Uuid::new_v4().to_string(); + state.store.put_message(&sandbox).await.unwrap(); + let config = supervisor_config(&state).await; + assert!(config.configuration_admitted); + assert!(!config.activation_pending); + assert_eq!( + config.enforcer_provider_env_revision, + accepted.provider_env_revision + ); + } + + #[tokio::test] + async fn enforcer_calls_need_the_native_network_mode() { + let state = crate::grpc::test_support::test_server_state().await; + let config = handle_get_sandbox_config( + &state, + as_enforcer(Request::new(GetSandboxConfigRequest { + sandbox_id: SANDBOX_ID.to_string(), + ..Default::default() + })), + ) + .await + .unwrap_err(); + assert_eq!(config.code(), Code::PermissionDenied); + let environment = handle_get_sandbox_provider_environment( + &state, + as_enforcer(Request::new(GetSandboxProviderEnvironmentRequest { + sandbox_id: SANDBOX_ID.to_string(), + ..Default::default() + })), + ) + .await + .unwrap_err(); + assert_eq!(environment.code(), Code::PermissionDenied); + let report = enforcer_report( + &state, + SandboxConfigurationAdmission { + state: Admission::Accepted.into(), + ..Default::default() + }, + ) + .await + .unwrap_err(); + assert_eq!(report.code(), Code::PermissionDenied); + } + + #[tokio::test] + async fn the_enforcer_reaches_only_native_network_sandboxes() { + let (state, _) = enforced_sandbox().await; + let enforcer_reads = |state: Arc| async move { + let config = handle_get_sandbox_config( + &state, + as_enforcer(Request::new(GetSandboxConfigRequest { + sandbox_id: SANDBOX_ID.to_string(), + ..Default::default() + })), + ) + .await + .unwrap_err(); + let environment = handle_get_sandbox_provider_environment( + &state, + as_enforcer(Request::new(GetSandboxProviderEnvironmentRequest { + sandbox_id: SANDBOX_ID.to_string(), + supports_static_credential_bindings: true, + supports_stable_placeholder_environment_keys: true, + })), + ) + .await + .unwrap_err(); + (config.code(), environment.code()) + }; + + let mut stock = state + .store + .get_message::(SANDBOX_ID) + .await + .unwrap() + .unwrap(); + stock.status.as_mut().unwrap().enforcer_admission = None; + state.store.put_message(&stock).await.unwrap(); + assert_eq!( + enforcer_reads(state.clone()).await, + (Code::PermissionDenied, Code::PermissionDenied) + ); + + let mut ungenerated = stock; + ungenerated.status.as_mut().unwrap().enforcer_admission = + Some(SandboxConfigurationAdmission { + state: Admission::Pending.into(), + ..Default::default() + }); + ungenerated + .metadata + .as_mut() + .unwrap() + .annotations + .remove(crate::auth::sandbox_session::RUNTIME_GENERATION_ANNOTATION); + state.store.put_message(&ungenerated).await.unwrap(); + assert_eq!( + enforcer_reads(state).await, + (Code::FailedPrecondition, Code::FailedPrecondition) + ); + } + + #[tokio::test] + async fn a_rejection_keeps_the_supervisor_failure() { + let (state, _) = enforced_sandbox().await; + enforcer_report( + &state, + verdict(&enforcer_config(&state).await, Admission::Accepted), + ) + .await + .unwrap(); + supervisor_loaded(&state, 1).await; + put_revision(&state, 2, &update_policy()).await; + supervisor_failed(&state, 2).await; + + let judged = enforcer_config(&state).await; + let mut rejected = verdict(&judged, Admission::Rejected); + rejected.error = "rule unsupported".to_string(); + enforcer_report(&state, rejected).await.unwrap(); + enforcer_report(&state, verdict(&judged, Admission::Accepted)) + .await + .unwrap(); + let record = state + .store + .get_policy_by_version(SANDBOX_ID, 2) + .await + .unwrap() + .unwrap(); + assert_eq!(record.status, "failed"); + assert_eq!(record.load_error.as_deref(), Some("landlock refused")); + assert_eq!(policy_status(&state, 2).await.1, 1); + } + + #[tokio::test] + async fn a_rejection_names_the_revision_when_providers_change_the_hash() { + let (state, _) = enforced_sandbox_with( + openshell_policy::restrictive_default_policy(), + vec!["work-github".to_string()], + ) + .await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + enforcer_report( + &state, + verdict(&enforcer_config(&state).await, Admission::Accepted), + ) + .await + .unwrap(); + supervisor_loaded(&state, 1).await; + put_revision(&state, 2, &update_policy()).await; + + let judged = enforcer_config(&state).await; + assert_eq!(judged.version, 2); + assert_ne!( + judged.policy_hash, + deterministic_policy_hash(&update_policy()), + "the provider adds rules to the effective policy" + ); + enforcer_report(&state, verdict(&judged, Admission::Rejected)) + .await + .unwrap(); + assert_eq!(policy_status(&state, 2).await, (PolicyStatus::Failed, 1)); + } + + #[tokio::test] + async fn the_enforcer_receives_each_static_credential_placeholder() { + let (state, _) = enforced_sandbox_with( + openshell_policy::restrictive_default_policy(), + vec!["work-github".to_string()], + ) + .await; + state + .store + .put_message(&test_provider("work-github", "github")) + .await + .unwrap(); + let request = GetSandboxProviderEnvironmentRequest { + sandbox_id: SANDBOX_ID.to_string(), + supports_static_credential_bindings: true, + supports_stable_placeholder_environment_keys: true, + }; + let environment = handle_get_sandbox_provider_environment( + &state, + as_enforcer(Request::new(request.clone())), + ) + .await + .unwrap() + .into_inner(); + let binding = &environment.static_credential_bindings["GITHUB_TOKEN"]; + let handle = environment + .stable_placeholder_environment_keys + .contains(&"GITHUB_TOKEN".to_string()) + .then_some(binding.workload_credential_handle.as_str()); + assert_eq!( + environment.workload_placeholders["GITHUB_TOKEN"], + openshell_core::secrets::workload_placeholder( + "GITHUB_TOKEN", + environment.provider_env_revision, + handle + ) + ); + + let supervisor = handle_get_sandbox_provider_environment( + &state, + with_sandbox(Request::new(request), SANDBOX_ID), + ) + .await + .unwrap() + .into_inner(); + assert!(supervisor.workload_placeholders.is_empty()); + + for (bindings, stable) in [(false, true), (true, false)] { + let error = handle_get_sandbox_provider_environment( + &state, + as_enforcer(Request::new(GetSandboxProviderEnvironmentRequest { + sandbox_id: SANDBOX_ID.to_string(), + supports_static_credential_bindings: bindings, + supports_stable_placeholder_environment_keys: stable, + })), + ) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::InvalidArgument); + } + } + + #[tokio::test] + async fn native_network_refuses_built_in_middleware_and_sends_no_services() { + let mut policy = openshell_policy::restrictive_default_policy(); + policy.network_middlewares.insert( + "scan".to_string(), + NetworkMiddlewareConfig { + middleware: "openshell/regex".to_string(), + ..Default::default() + }, + ); + let (mut state, _) = enforced_sandbox_with(policy.clone(), Vec::new()).await; + let registry = Arc::new( + openshell_supervisor_middleware::MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await + .unwrap(), + ); + Arc::get_mut(&mut state).unwrap().middleware_registry = registry; + let judged = enforcer_config(&state).await; + assert!(!judged.configuration_admitted); + let error = crate::middleware::validate_policy_for_gateway(&state, &policy) + .await + .unwrap_err(); + assert_eq!(error.code(), Code::InvalidArgument); + assert!(error.message().contains("native-network mode"), "{error}"); + + let (state, _) = enforced_sandbox().await; + assert!( + enforcer_config(&state) + .await + .supervisor_middleware_services + .is_empty() + ); + } +} diff --git a/crates/openshell-server/src/grpc/sandbox.rs b/crates/openshell-server/src/grpc/sandbox.rs index 8e5762a33b..25d565b040 100644 --- a/crates/openshell-server/src/grpc/sandbox.rs +++ b/crates/openshell-server/src/grpc/sandbox.rs @@ -560,6 +560,24 @@ fn sandbox_create_telemetry_attrs( } } +/// Give a sandbox with neither its own policy nor a global policy the +/// restrictive default in native-network mode. The enforcer programs the +/// network before the runtime can reach its supervisor, so the supervisor +/// can't supply a baseline, and the gateway can't read one from the image. +async fn materialize_initial_policy( + state: &ServerState, + spec: &mut SandboxSpec, +) -> Result<(), Status> { + if state.compute.native_network().is_none() + || spec.policy.is_some() + || !super::policy::provider_policy_composition_enabled(state.store.as_ref()).await? + { + return Ok(()); + } + spec.policy = Some(openshell_policy::restrictive_default_policy()); + Ok(()) +} + async fn handle_create_sandbox_inner( state: &Arc, request: Request, @@ -685,6 +703,7 @@ async fn handle_create_sandbox_inner( template.image = state.compute.default_image().to_string(); } + materialize_initial_policy(state, &mut spec).await?; if let Some(ref mut policy) = spec.policy { super::policy::clear_provider_credentialed_markers(policy); validate_no_reserved_provider_policy_keys(policy)?; @@ -699,7 +718,7 @@ async fn handle_create_sandbox_inner( if let Some(ref policy) = spec.policy { validate_policy_safety(policy)?; - crate::middleware::validate_policy(state.middleware_registry.as_ref(), policy).await?; + crate::middleware::validate_policy_for_gateway(state, policy).await?; } super::policy::validate_candidate_sandbox_credential_policy( state, @@ -740,6 +759,16 @@ async fn handle_create_sandbox_inner( .as_mut() .expect("status initialized") .configuration_activated = Some(false); + if state.compute.native_network().is_some() { + sandbox + .status + .as_mut() + .expect("status initialized") + .enforcer_admission = Some(openshell_core::proto::SandboxConfigurationAdmission { + state: openshell_core::proto::ConfigurationAdmissionState::Pending.into(), + ..Default::default() + }); + } sandbox .status .as_mut() @@ -4479,8 +4508,8 @@ mod tests { assert!(exec_loop_result(None, true).is_err()); } use crate::grpc::test_support::{ - authed_request, test_server_state, test_server_state_with_compute_driver, - test_server_state_with_driver, + authed_request, test_native_network_server_state, test_server_state, + test_server_state_with_compute_driver, test_server_state_with_driver, }; use openshell_core::proto::datamodel::v1::ObjectMeta; use openshell_core::proto::{ @@ -5635,6 +5664,49 @@ mod tests { sandbox } + #[tokio::test] + async fn native_network_mode_materializes_the_default_policy() { + let with_policy = test_sandbox("work", Vec::new()).spec.unwrap(); + let mut without_policy = with_policy.clone(); + without_policy.policy = None; + + let stock = test_server_state().await; + let mut spec = without_policy.clone(); + materialize_initial_policy(&stock, &mut spec).await.unwrap(); + assert!(spec.policy.is_none()); + + let native = test_native_network_server_state().await; + let mut spec = without_policy.clone(); + materialize_initial_policy(&native, &mut spec) + .await + .unwrap(); + assert_eq!( + spec.policy, + Some(openshell_policy::restrictive_default_policy()) + ); + let mut spec = with_policy.clone(); + materialize_initial_policy(&native, &mut spec) + .await + .unwrap(); + assert_eq!(spec.policy, with_policy.policy); + + super::super::policy::handle_update_config( + &native, + authed_request(openshell_core::proto::UpdateConfigRequest { + global: true, + policy: Some(openshell_policy::restrictive_default_policy()), + ..Default::default() + }), + ) + .await + .unwrap(); + let mut spec = without_policy; + materialize_initial_policy(&native, &mut spec) + .await + .unwrap(); + assert!(spec.policy.is_none()); + } + fn test_workload_template(name: &str) -> SandboxWorkloadTemplate { SandboxWorkloadTemplate { metadata: Some(ObjectMeta { diff --git a/crates/openshell-server/src/grpc/supervisor_host.rs b/crates/openshell-server/src/grpc/supervisor_host.rs index d095741770..9f5ccac9bc 100644 --- a/crates/openshell-server/src/grpc/supervisor_host.rs +++ b/crates/openshell-server/src/grpc/supervisor_host.rs @@ -69,6 +69,7 @@ impl SupervisorHost for SupervisorHostService { return Err(Status::unavailable("gateway is shutting down")); } let state = self.state.clone(); + let enforcer = identity.role == openshell_supervisor_control::HostRole::Enforcer; let (member_id, outbound) = controller .attach( identity, @@ -78,7 +79,7 @@ impl SupervisorHost for SupervisorHostService { .await?; let handoff = futures::stream::once(async move { let stopping = *state.supervisor_sessions.subscribe_shutdown().borrow(); - stopping + (stopping && !enforcer) .then(|| host_home(&state, &member_id, true)) .flatten() .map(|peer_endpoint| Ok(redirect(peer_endpoint))) diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 48140e872d..b80a31833a 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -259,18 +259,25 @@ fn spawn_gateway_extension_token_refresh( }); } -/// Mint the shared supervisor's token and renew it at half its lifetime so -/// the delivered copy is never close to expiry when the supervisor restarts -/// or reconnects. Minting failures are logged and retried shortly. -fn spawn_supervisor_token_refresh( - authority: Arc, +/// Mint a host token and renew it at half its lifetime so the delivered copy +/// is never close to expiry when the host restarts or reconnects. Minting +/// failures are logged and retried shortly. +fn spawn_host_token_refresh( + role: &'static str, ttl: Duration, - controller: openshell_supervisor_control::SupervisorHostController, + mint: impl Fn( + Duration, + ) -> std::result::Result< + openshell_core::jwt::MintedSessionToken, + openshell_core::jwt::SessionJwtError, + > + Send + + 'static, + publish: impl Fn(openshell_supervisor_control::SupervisorCredential) + Send + 'static, mut shutdown_rx: watch::Receiver, ) { tokio::spawn(async move { loop { - let delay = match authority.mint_supervisor_token(ttl) { + let delay = match mint(ttl) { Ok(minted) => { let remaining = minted.expires_at.saturating_sub( i64::try_from( @@ -280,17 +287,15 @@ fn spawn_supervisor_token_refresh( ) .unwrap_or(i64::MAX), ); - controller.publish_credential( - openshell_supervisor_control::SupervisorCredential { - token: minted.token, - expires_at: minted.expires_at, - }, - ); + publish(openshell_supervisor_control::SupervisorCredential { + token: minted.token, + expires_at: minted.expires_at, + }); Duration::from_secs(u64::try_from(remaining).unwrap_or(0) / 2) .max(Duration::from_secs(1)) } Err(error) => { - warn!(%error, "failed to mint the supervisor token; retrying"); + warn!(%error, role, "failed to mint the host token; retrying"); Duration::from_secs(10) } }; @@ -427,6 +432,15 @@ pub struct ServerState { /// Optional K8s `ServiceAccount` authenticator for gateway peer RPCs. pub peer_authenticator: Option>, + /// Resolves each host role's identity tokens, and whether the role's + /// host tokens are refused without one. A role without a resolver has + /// every host token refused. + pub host_identity_resolvers: Vec<( + openshell_supervisor_control::HostRole, + Arc, + bool, + )>, + /// Credentials that have recently logged on, so each records one /// authentication success rather than one per request. pub(crate) logons: auth::audit::Logons, @@ -714,6 +728,7 @@ impl ServerState { sandbox_session_jwt_authority: None, compute_driver_authenticator: None, peer_authenticator: None, + host_identity_resolvers: Vec::new(), logons: auth::audit::Logons::default(), grpc_rate_limiter, provider_token_rate_limiter, @@ -1060,6 +1075,47 @@ pub(crate) async fn run_server( validate_peer_endpoint_scheme(&state.config, peer_endpoint)?; } controller.set_peer_endpoint(state.peer_endpoint.clone().unwrap_or_default()); + let native_network = state.compute.native_network(); + let mut roles = vec![openshell_supervisor_control::HostRole::Supervisor]; + if native_network.is_some() { + roles.push(openshell_supervisor_control::HostRole::Enforcer); + } + let client = kube::Client::try_default().await.map_err(|error| { + Error::config(format!( + "shared supervisor hosts prove their Pod with Kubernetes TokenReview, but the \ + in-cluster client failed: {error}" + )) + })?; + for role in roles { + let account = controller.host_account(role).ok_or_else(|| { + Error::config(format!( + "the compute driver registered no ServiceAccount for {role:?} hosts, whose \ + pod-bound tokens prove their identity" + )) + })?; + let resolver = Arc::new(auth::peer::LiveGatewayPeerResolver::new( + client.clone(), + &account.namespace, + role.identity_audience().to_string(), + account.service_account.clone(), + Vec::new(), + )); + state.host_identity_resolvers.push(( + role, + Arc::new(auth::peer::CachingGatewayPeerResolver::new( + resolver, + auth::peer::peer_token_cache_ttl_from_env(), + )), + account.identity_required, + )); + info!( + ?role, + namespace = %account.namespace, + service_account = %account.service_account, + required = account.identity_required, + "host identity verification enabled" + ); + } supervisor_pool::SupervisorPool::new( state.store.clone(), controller.clone(), @@ -1069,7 +1125,26 @@ pub(crate) async fn run_server( state.supervisor_spread.clone(), ) .start(shutdown_rx.clone()); - spawn_supervisor_token_refresh(authority, ttl, controller.clone(), shutdown_rx.clone()); + if let Some(nameservers) = native_network { + controller.accept_enforcers(nameservers); + let enforcer_authority = authority.clone(); + let enforcer_controller = controller.clone(); + spawn_host_token_refresh( + "enforcer", + ttl, + move |ttl| enforcer_authority.mint_enforcer_token(ttl), + move |credential| enforcer_controller.publish_enforcer_credential(credential), + shutdown_rx.clone(), + ); + } + let supervisor_controller = controller.clone(); + spawn_host_token_refresh( + "supervisor", + ttl, + move |ttl| authority.mint_supervisor_token(ttl), + move |credential| supervisor_controller.publish_credential(credential), + shutdown_rx.clone(), + ); } if state.sandbox_session_jwt_authority.is_some() @@ -1877,6 +1952,16 @@ pub trait ComputeDriverFactory: Send + Sync { Ok(false) } + /// The sandboxes' resolvers when this configuration launches every new + /// runtime in native-network mode, where an external enforcer owns + /// the workload network. Same constraints as [`Self::validate_config`]. + fn native_network( + &self, + _context: ComputeDriverConfigContext<'_>, + ) -> Result>> { + Ok(None) + } + async fn build(&self, context: ComputeDriverBuildContext<'_>) -> Result; /// Build with a separately registered, optional in-process image updater. @@ -2570,6 +2655,27 @@ async fn build_compute_runtime( &config.log_level, driver_startup, )?; + let native_network = + match &driver { + ConfiguredComputeDriver::Registered(registration) => registration + .factory + .native_network(ComputeDriverConfigContext { + driver_name: ®istration.name, + gateway_name: &config.name, + gateway_bind_address: config.bind_address, + gateway_log_level: &config.log_level, + driver_startup, + })?, + ConfiguredComputeDriver::Remote { .. } => None, + }; + if native_network.is_some() && !cfg!(feature = "experimental") { + return Err(Error::config(NATIVE_NETWORK_WITHOUT_EXPERIMENTAL)); + } + if native_network.is_some() + && config.config_delivery_mode == openshell_core::config::ConfigDeliveryMode::Push + { + return Err(Error::config(NATIVE_NETWORK_WITH_PUSH_DELIVERY)); + } let telemetry_compute_driver = driver.telemetry_compute_driver(registry); let admission = match &driver { ConfiguredComputeDriver::Registered(registration) => registration @@ -2702,9 +2808,18 @@ async fn build_compute_runtime( .with_provisioning_repair_window_seconds(config.provisioning_repair_window_seconds) }) .map_err(Error::config)?; - Ok(runtime.with_telemetry_compute_driver(telemetry_compute_driver)) + Ok(runtime + .with_telemetry_compute_driver(telemetry_compute_driver) + .with_native_network(native_network)) } +const NATIVE_NETWORK_WITHOUT_EXPERIMENTAL: &str = "external_enforcer requires a gateway \ + built with the experimental feature"; + +const NATIVE_NETWORK_WITH_PUSH_DELIVERY: &str = "external_enforcer requires \ + config_delivery_mode = \"poll\": the supervisor must poll for the enforcer's acceptance \ + before it installs a new provider environment"; + #[derive(Debug, Clone)] enum ConfiguredComputeDriver { Registered(ComputeDriverRegistration), diff --git a/crates/openshell-server/src/middleware.rs b/crates/openshell-server/src/middleware.rs index a86c64f9a7..2dd19b3e3a 100644 --- a/crates/openshell-server/src/middleware.rs +++ b/crates/openshell-server/src/middleware.rs @@ -1,10 +1,42 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +use crate::ServerState; use openshell_core::proto::SandboxPolicy; use openshell_supervisor_middleware::MiddlewareRegistry; use tonic::Status; +/// Validate a policy's middleware against this gateway's registry and mode. +pub async fn validate_policy_for_gateway( + state: &ServerState, + policy: &SandboxPolicy, +) -> Result<(), Status> { + validate_policy(state.middleware_registry.as_ref(), policy).await?; + if state.compute.native_network().is_some() { + reject_builtin_middleware(policy).map_err(|error| { + Status::invalid_argument(format!("policy middleware validation failed: {error}")) + })?; + } + Ok(()) +} + +/// In native-network mode the supervisor runs no proxy, so built-in +/// middleware would be enforced by no one. Registration names can't use the +/// `openshell/` prefix, so it identifies exactly the built-ins. +pub fn reject_builtin_middleware(policy: &SandboxPolicy) -> Result<(), String> { + match policy + .network_middlewares + .iter() + .find(|(_, config)| config.middleware.starts_with("openshell/")) + { + Some((name, config)) => Err(format!( + "built-in middleware '{}' used by config '{name}' isn't enforced in native-network mode", + config.middleware + )), + None => Ok(()), + } +} + /// Validate implementation-owned middleware config, and the HTTP hook version /// rules, before accepting a policy. pub async fn validate_policy( diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 6b8a4d1406..edfbbb858c 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -1153,9 +1153,12 @@ fn build_authenticator_chain(state: &ServerState) -> Option authenticators.push(driver); } if let Some(authority) = state.sandbox_session_jwt_authority.clone() { - authenticators.push(Arc::new( - crate::auth::supervisor_token::SupervisorTokenAuthenticator::new(authority.clone()), - )); + let mut supervisor = + crate::auth::supervisor_token::SupervisorTokenAuthenticator::new(authority.clone()); + for (role, resolver, required) in &state.host_identity_resolvers { + supervisor = supervisor.with_identity_resolver(*role, resolver.clone(), *required); + } + authenticators.push(Arc::new(supervisor)); authenticators.push(Arc::new( crate::auth::sandbox_jwt::SandboxSessionJwtAuthenticator::new( authority, @@ -1425,22 +1428,31 @@ where Principal::Peer(_) if !crate::auth::method_authz::is_peer_callable(&path) => { method_denied("gateway peer principals may not call this method") } - Principal::Supervisor(_) - if !crate::auth::method_authz::is_supervisor_callable(&path) => - { - method_denied( - "supervisor tokens may call only the supervisor assignment stream", - ) - } + Principal::Supervisor(ref host) => match host.identity.role { + openshell_supervisor_control::HostRole::Enforcer + if !crate::auth::method_authz::is_enforcer_callable(&path) => + { + method_denied( + "enforcer tokens may call only the assignment stream and the \ + enforcer's sandbox configuration methods", + ) + } + openshell_supervisor_control::HostRole::Supervisor + if !crate::auth::method_authz::is_supervisor_callable(&path) => + { + method_denied( + "supervisor tokens may call only the supervisor assignment stream", + ) + } + openshell_supervisor_control::HostRole::Enforcer + | openshell_supervisor_control::HostRole::Supervisor => None, + }, Principal::Anonymous => { return Ok(status_response(tonic::Status::unauthenticated( "anonymous callers may not call authenticated methods", ))); } - Principal::Operator(_) - | Principal::Sandbox(_) - | Principal::Peer(_) - | Principal::Supervisor(_) => None, + Principal::Operator(_) | Principal::Sandbox(_) | Principal::Peer(_) => None, }; if let Some((denial, status)) = denial { audit::emit_authorization_denial_for(&path, &origin, &principal, denial); @@ -3851,6 +3863,48 @@ mod tests { } } + #[tokio::test] + async fn enforcer_tokens_reach_only_the_enforcer_methods() { + let enforcer = Principal::Supervisor(crate::auth::principal::SupervisorPrincipal { + identity: openshell_supervisor_control::HostIdentity { + subject: "openshell-enforcer:test".to_string(), + token_id: "token".to_string(), + expires_at: i64::MAX, + node: None, + role: openshell_supervisor_control::HostRole::Enforcer, + }, + }); + for (method, permitted) in [ + ("/openshell.supervisor.host.v1.SupervisorHost/Attach", true), + ("/openshell.v1.OpenShell/GetSandboxConfig", true), + ( + "/openshell.v1.OpenShell/GetSandboxProviderEnvironment", + true, + ), + ("/openshell.v1.OpenShell/ReportSandboxConfiguration", true), + ("/openshell.v1.OpenShell/ListSandboxes", false), + ("/openshell.v1.OpenShell/ConnectSupervisor", false), + ("/openshell.v1.OpenShell/GetProviderCredentials", false), + ("/openshell.v1.OpenShell/ReportPolicyStatus", false), + ("/openshell.v1.OpenShell/RefreshSandboxToken", false), + ("/openshell.v1.OpenShell/Unknown", false), + ] { + let chain = AuthenticatorChain::new(vec![Arc::new(MockAuthenticator::returning( + Ok(Authentication::Accepted(enforcer.clone())), + ))]); + let (recorder, _) = PrincipalRecorder::new(); + let response = AuthGrpcRouter::new(recorder, Some(chain), None) + .call(empty_request(method)) + .await + .unwrap(); + if permitted { + assert!(grpc_status(&response).is_none(), "{method}"); + } else { + assert_eq!(grpc_status(&response).as_deref(), Some("7"), "{method}"); + } + } + } + #[tokio::test] async fn supervisor_tokens_reach_only_the_assignment_stream() { let attach = "/openshell.supervisor.host.v1.SupervisorHost/Attach"; @@ -3859,6 +3913,8 @@ mod tests { subject: "openshell-supervisor:test".to_string(), token_id: "token".to_string(), expires_at: i64::MAX, + node: None, + role: openshell_supervisor_control::HostRole::Supervisor, }, }); let supervisor_chain = || { diff --git a/crates/openshell-server/src/storage_proto.rs b/crates/openshell-server/src/storage_proto.rs index 4c452c7cf3..a7cc2dac36 100644 --- a/crates/openshell-server/src/storage_proto.rs +++ b/crates/openshell-server/src/storage_proto.rs @@ -252,11 +252,11 @@ mod tests { // The service backend HTTP version is part of both schemas. Legacy // endpoint records omit it and continue to use HTTP/1.1. const PUBLIC_RPC_SCHEMA_SHA256: &str = - "edfc80ad192e77e1a9d1e1d6e3342280e4438f8bf7cb49969f580060df9a056a"; + "fb0246d3c698efe031297d9c24988e95ccb80bcf10734619c5708137a9905bcf"; // The storage.v2 refresh root adds retired handles and the first mint's // provider revision. All fields from the prior root retain their wire tags. const DURABLE_SCHEMA_SHA256: &str = - "ca31950286327bc385fae933bbb9e34d3c9191214f9b549c558bba40957fcc65"; + "6e83e79a8002712d0ecfb508464d20a8ea108a491e7edaf79dc9f6e674ad3aa6"; const PUBLIC_DURABLE_OVERLAP_SHA256: &str = "d0eead2cd403f6f52ecd9b7df73ca7db15e84dd847e11bc9d50469970204e589"; // Encoded with the schema that omitted stable_placeholder. Keep these @@ -817,7 +817,7 @@ mod tests { overlap_hash.as_str(), ), ( - (369, 32), + (370, 32), (104, 23), (88, 23), PUBLIC_RPC_SCHEMA_SHA256, diff --git a/crates/openshell-server/src/supervisor_pool.rs b/crates/openshell-server/src/supervisor_pool.rs index c5e8d10812..995e1df79d 100644 --- a/crates/openshell-server/src/supervisor_pool.rs +++ b/crates/openshell-server/src/supervisor_pool.rs @@ -257,6 +257,13 @@ struct AssignmentPayload { /// Credential handle of the launch material (encoded `CredentialHandle`); /// empty in a reservation. material_handle: Vec, + /// The pinned member, as [`PlacementRequest::member`] describes. + #[serde(default, skip_serializing_if = "Option::is_none")] + member_id: Option, + /// The node the instance's workload runs on. Node-topology records + /// written without it are on their pinned member, which is the node. + #[serde(default, skip_serializing_if = "Option::is_none")] + node: Option, } #[derive(Debug, Clone)] @@ -604,7 +611,8 @@ fn ring_of(members: &[LiveMember]) -> GatewayRing { /// Only members with fewer than `max_instances` routes, or already charged /// for this one, are listed; the owner change itself re-checks room /// atomically. `charges` counts the routes each member is charged for and -/// lists them. +/// lists them. With `pinned`, only that member is listed. +#[allow(clippy::too_many_arguments)] fn candidates<'a>( ring: &GatewayRing, members: &'a [LiveMember], @@ -613,12 +621,14 @@ fn candidates<'a>( charges: &BTreeMap>, same: Option<&str>, max_instances: usize, + pinned: Option<&str>, ) -> Vec<&'a LiveMember> { use std::hash::{Hash as _, Hasher as _}; let routes_of = |member: &LiveMember| charges.get(&member.member_id); let has_room = |member: &&LiveMember| { - !member.leaving + pinned.is_none_or(|pinned| member.member_id == pinned) + && !member.leaving && routes_of(member) .is_none_or(|routes| routes.contains(route) || routes.len() < max_instances) }; @@ -1144,7 +1154,7 @@ impl SupervisorPool { } let suspects = previous .desired - .iter() + .keys() .chain(owners.keys()) .filter(|route| !desired.contains_key(*route) && !withdrawals.contains(*route)) .cloned() @@ -1547,8 +1557,10 @@ impl SupervisorPool { async fn record_assignment( &self, assignment: &SandboxInstanceAssignment, + member: Option<&str>, + node: Option<&str>, ) -> Result { - self.record_assignment_as(assignment, RecordPhase::Published) + self.record_assignment_as(assignment, RecordPhase::Published, member, node) .await .map(|recording| recording.record) } @@ -1558,19 +1570,24 @@ impl SupervisorPool { async fn record_admitting( &self, assignment: &SandboxInstanceAssignment, + member: Option<&str>, + node: Option<&str>, ) -> Result { - self.record_assignment_as(assignment, RecordPhase::Admitting) + self.record_assignment_as(assignment, RecordPhase::Admitting, member, node) .await } /// [`Self::record_assignment`], publishing the record as `phase` /// ([`RecordPhase::Published`] or [`RecordPhase::Admitting`]). An /// admitting record keeps its material candidate, which this recording - /// reports; a published one releases it. + /// reports; a published one releases it. `member` pins the instance to + /// that pool member; `node` is where its workload runs. async fn record_assignment_as( &self, assignment: &SandboxInstanceAssignment, phase: RecordPhase, + member: Option<&str>, + node: Option<&str>, ) -> Result { let read = |error: PersistenceError| format!("read supervisor pool instance: {error}"); let existing = |record: AssignmentRecord| match record.payload.phase { @@ -1607,6 +1624,8 @@ impl SupervisorPool { phase: RecordPhase::Reserved, writer: Uuid::new_v4().to_string(), material_handle: Vec::new(), + member_id: member.map(str::to_string), + node: node.map(str::to_string), }; let id = assignment_object_id(&payload.route, &payload.writer); let encode = |payload: &AssignmentPayload| { @@ -1975,6 +1994,7 @@ impl SupervisorPool { return Err("no shared supervisor replica is attached to the gateway".to_string()); } let ring = ring_of(&members); + let pinned = request.member.as_deref(); let max_instances = self.max_instances_per_member(); let targets = candidates( &ring, @@ -1984,15 +2004,27 @@ impl SupervisorPool { &charges, None, max_instances, + pinned, ); let no_room = || { - warn!(max_instances, "every supervisor is at its sandbox limit"); - CAPACITY_REACHED.to_string() + pinned.map_or_else( + || { + warn!(max_instances, "every supervisor is at its sandbox limit"); + CAPACITY_REACHED.to_string() + }, + |member| { + format!( + "the shared supervisor {member:?} is not attached or has no room for another sandbox" + ) + }, + ) }; if targets.is_empty() { return Err(no_room()); } - let recording = self.record_admitting(assignment).await?; + let recording = self + .record_admitting(assignment, pinned, request.node.as_deref()) + .await?; let admitting = (recording.record.payload.phase == RecordPhase::Admitting).then_some(&recording.record); let mut placed = None; @@ -2225,8 +2257,15 @@ impl SupervisorPool { } match failure { Ok(Some(cause)) if takeovers_allowed => { - self.take_over(record, cause, &ring, &members, &charges) - .await + self.take_over( + record, + cause, + &ring, + &members, + &charges, + instance.payload.member_id.as_deref(), + ) + .await } Ok(_) => Ok(Reconciled::Unchanged), Err(error) => Err(error), @@ -2636,6 +2675,13 @@ impl SupervisorPool { if unowned_for.is_none_or(|elapsed| elapsed < self.unowned_grace) { return Ok(Reconciled::Unchanged); } + if self.refuses_unpinned(assignment.member_id.as_deref()) { + warn!( + route, + "refusing to place an instance without a node pin under supervisor_topology=node; restart the sandbox" + ); + return Ok(Reconciled::Unchanged); + } let targets = candidates( ring, members, @@ -2644,6 +2690,7 @@ impl SupervisorPool { charges, None, self.max_instances_per_member(), + assignment.member_id.as_deref(), ); if targets.is_empty() { return Ok(Reconciled::Unchanged); @@ -2718,8 +2765,16 @@ impl SupervisorPool { Ok(takeover_cause(owner, member.as_ref())) } + /// Whether an unpinned instance (launched under the gateway topology) + /// must stay put. With members bound to nodes, it would reach another + /// node's supervisor with its launch material, so it waits until the + /// recovery timeout ends it. + fn refuses_unpinned(&self, member: Option<&str>) -> bool { + member.is_none() && self.controller.members_bound_to_nodes() + } + /// Move an instance whose owner failed or left, for `cause`, to the - /// ring's choice. + /// ring's choice, or only to `pinned` when the instance is pinned. async fn take_over( &self, record: &OwnerRecord, @@ -2727,7 +2782,15 @@ impl SupervisorPool { ring: &GatewayRing, members: &[LiveMember], charges: &BTreeMap>, + pinned: Option<&str>, ) -> Result { + if self.refuses_unpinned(pinned) { + warn!( + route = %record.payload.route, + "refusing to take over an instance without a node pin under supervisor_topology=node; restart the sandbox" + ); + return Ok(Reconciled::Unchanged); + } // A member whose process restarted re-adopts its routes first: their // slots are already charged to it, so this needs no free capacity. let targets = candidates( @@ -2738,6 +2801,7 @@ impl SupervisorPool { charges, Some(&record.payload.member_id), self.max_instances_per_member(), + pinned, ); for target in targets { let intent = OwnerPayload { @@ -2872,7 +2936,23 @@ impl SupervisorPool { }) .collect(), owners: BTreeMap::new(), - desired: desired.keys().cloned().collect(), + desired: desired + .iter() + .map(|(route, record)| { + ( + route.clone(), + openshell_supervisor_control::DesiredInstance { + sandbox_id: record.payload.sandbox_id.clone(), + generation: record.payload.generation.clone(), + node: record + .payload + .node + .clone() + .or_else(|| record.payload.member_id.clone()), + }, + ) + }) + .collect(), assignments, reports, expired, @@ -3033,10 +3113,17 @@ impl InstancePlacement for PoolPlacement { Box::pin(async move { pool.recorded().await }) } - fn record_recovered(&self, assignment: SandboxInstanceAssignment) -> PlacementFuture { + fn record_recovered( + &self, + assignment: SandboxInstanceAssignment, + member: Option, + node: Option, + ) -> PlacementFuture { let pool = self.0.clone(); Box::pin(detached(async move { - pool.record_assignment(&assignment).await.map(drop) + pool.record_assignment(&assignment, member.as_deref(), node.as_deref()) + .await + .map(drop) })) } } @@ -3277,6 +3364,8 @@ mod tests { phase: RecordPhase::Published, writer: Uuid::new_v4().to_string(), material_handle: b"handle".to_vec(), + member_id: None, + node: None, }; self.store .put_if( @@ -3402,6 +3491,8 @@ mod tests { PlacementRequest { assignment: assignment(route, sandbox_id, generation), auth_epoch: 1, + member: None, + node: None, } } @@ -3463,6 +3554,132 @@ mod tests { ); } + #[tokio::test] + async fn unpinned_launches_keep_their_workloads_node() { + let fixture = Fixture::new().await; + fixture.member("m1", "p1", false).await; + fixture + .sandbox("sandbox-a", "generation-1", SandboxPhase::Ready) + .await; + fixture + .replica("gw-a") + .place_launch(PlacementRequest { + node: Some("node-a".to_string()), + ..launch("rt-route-a000", "sandbox-a", "generation-1") + }) + .await + .unwrap(); + let other = fixture.replica("gw-b"); + other.reconcile_once().await.unwrap(); + assert_eq!( + other.controller.pool_view().unwrap().desired["rt-route-a000"] + .node + .as_deref(), + Some("node-a") + ); + } + + #[tokio::test] + async fn pinned_instances_stay_on_their_member() { + let fixture = Fixture::new().await; + fixture.member("m1", "p1", false).await; + fixture.member("m2", "p2", false).await; + let pool = fixture.replica("gw-a"); + let pinned = |route: &str, sandbox: &str, member: &str| PlacementRequest { + member: Some(member.to_string()), + ..launch(route, sandbox, "generation-1") + }; + // Pinned to m2 even where the ring prefers m1. + let ring = GatewayRing::new(["m1", "m2"]); + let sandbox = (0..64) + .map(|index| format!("sandbox-{index}")) + .find(|sandbox| ring.owner_for(sandbox) == Some("m1")) + .unwrap(); + fixture + .sandbox(&sandbox, "generation-1", SandboxPhase::Ready) + .await; + pool.place_launch(pinned("rt-route-p000", &sandbox, "m2")) + .await + .unwrap(); + assert_eq!( + fixture.owner("rt-route-p000").await.unwrap().member_id, + "m2" + ); + assert_eq!( + fixture + .instance("rt-route-p000") + .await + .unwrap() + .payload + .member_id + .as_deref(), + Some("m2") + ); + // Every replica's view takes the pin as the instance's node. + let other = fixture.replica("gw-b"); + other.reconcile_once().await.unwrap(); + assert_eq!( + other.controller.pool_view().unwrap().desired["rt-route-p000"] + .node + .as_deref(), + Some("m2") + ); + + // A member that is not attached refuses the launch instead of the + // ring choosing another. + fixture + .sandbox("sandbox-x", "generation-1", SandboxPhase::Ready) + .await; + let refused = pool + .place_launch(pinned("rt-route-x000", "sandbox-x", "node-gone")) + .await + .unwrap_err(); + assert!(refused.contains("\"node-gone\""), "{refused}"); + + // While m2 is gone the instance waits for it; its next process + // re-adopts it. + fixture.remove_member("m2").await; + pool.reconcile_once().await.unwrap(); + pool.reconcile_once().await.unwrap(); + assert_eq!( + fixture.owner("rt-route-p000").await.unwrap().process_id, + "p2" + ); + fixture.member("m2", "p2b", false).await; + pool.reconcile_once().await.unwrap(); + pool.reconcile_once().await.unwrap(); + let owner = fixture.owner("rt-route-p000").await.unwrap(); + assert_eq!( + (owner.member_id.as_str(), owner.process_id.as_str()), + ("m2", "p2b") + ); + } + + #[tokio::test] + async fn node_bound_members_never_take_an_unpinned_instance() { + let fixture = Fixture::new().await; + fixture.member("m1", "p1", false).await; + fixture + .sandbox("sandbox-a", "generation-1", SandboxPhase::Ready) + .await; + fixture + .replica("gw-a") + .place_launch(launch("rt-route-a000", "sandbox-a", "generation-1")) + .await + .unwrap(); + + // After a switch to the node topology, the gateway-topology owner is + // gone and a node supervisor is live: the instance is not moved to it. + let pool = fixture.replica("gw-b"); + pool.controller.bind_members_to_nodes(); + fixture.member("node-a", "p2", false).await; + fixture.remove_member("m1").await; + pool.reconcile_once().await.unwrap(); + pool.reconcile_once().await.unwrap(); + let owner = fixture.owner("rt-route-a000").await.unwrap(); + assert_eq!((owner.member_id.as_str(), owner.auth_epoch), ("m1", 1)); + } + #[tokio::test] async fn a_failed_owner_is_taken_over_once_and_fenced_everywhere() { let fixture = Fixture::new().await; @@ -3669,7 +3886,7 @@ mod tests { // recorded owners. ("rt-route-b000", "sandbox-b"), ] { - pool.record_assignment(&assignment(route, sandbox, "generation-1")) + pool.record_assignment(&assignment(route, sandbox, "generation-1"), None, None) .await .unwrap(); } @@ -3758,7 +3975,7 @@ mod tests { ("rt-route-c000", "sandbox-c"), ("rt-route-d000", "sandbox-d"), ] { - pool.record_assignment(&assignment(route, sandbox, "generation-1")) + pool.record_assignment(&assignment(route, sandbox, "generation-1"), None, None) .await .unwrap(); } @@ -3899,7 +4116,7 @@ mod tests { // derives the instance, its owner, and its material from the records. other.reconcile_once().await.unwrap(); let view = other.controller.pool_view().unwrap(); - assert!(view.desired.contains("rt-route-a000")); + assert!(view.desired.contains_key("rt-route-a000")); assert_eq!(view.owners["rt-route-a000"].member_id, "m1"); assert_eq!( other.load_material(&record.payload).await.unwrap(), @@ -3915,11 +4132,18 @@ mod tests { // Recording the generation again keeps the first record and material; // another generation on its route is refused. - other.record_assignment(&launched).await.unwrap(); + other + .record_assignment(&launched, None, None) + .await + .unwrap(); assert_eq!(fixture.credentials.stored_credential_count(), Some(1)); assert!( other - .record_assignment(&assignment("rt-route-a000", "sandbox-a", "generation-2")) + .record_assignment( + &assignment("rt-route-a000", "sandbox-a", "generation-2"), + None, + None + ) .await .is_err() ); @@ -3937,7 +4161,7 @@ mod tests { .pool_view() .unwrap() .desired - .contains("rt-route-a000") + .contains_key("rt-route-a000") ); } @@ -3950,8 +4174,8 @@ mod tests { let (first, second) = (fixture.replica("gw-a"), fixture.replica("gw-b")); let instance = assignment("rt-route-a000", "sandbox-a", "generation-1"); let results: [_; 2] = tokio::join!( - first.record_assignment(&instance), - second.record_assignment(&instance) + first.record_assignment(&instance, None, None), + second.record_assignment(&instance, None, None) ) .into(); // One recording reserves the route and publishes; the other finds the @@ -3986,7 +4210,7 @@ mod tests { let (staged, publish) = pool.pause_next_recording_after_staging(); let recording = { let (pool, instance) = (pool.clone(), instance.clone()); - tokio::spawn(async move { pool.record_assignment(&instance).await }) + tokio::spawn(async move { pool.record_assignment(&instance, None, None).await }) }; staged.await.unwrap(); // The instance is withdrawn while it is being recorded: removing its @@ -4021,7 +4245,7 @@ mod tests { let (staged, publish) = pool.pause_next_recording_after_staging(); let recording = { let (pool, instance) = (pool.clone(), instance.clone()); - tokio::spawn(async move { pool.record_assignment(&instance).await }) + tokio::spawn(async move { pool.record_assignment(&instance, None, None).await }) }; staged.await.unwrap(); // Staged and unpublished: material stored, candidate written, the @@ -4081,7 +4305,7 @@ mod tests { let (staged, publish) = pool.pause_next_recording_after_staging(); let recording = { let (pool, instance) = (pool.clone(), instance.clone()); - tokio::spawn(async move { pool.record_assignment(&instance).await }) + tokio::spawn(async move { pool.record_assignment(&instance, None, None).await }) }; staged.await.unwrap(); // The recording outlives its reservation's grace: a pass fences it and @@ -4097,7 +4321,7 @@ mod tests { assert!(fixture.instance("rt-route-a000").await.is_none()); assert_eq!(fixture.credentials.stored_credential_count(), Some(0)); // The route can be recorded again. - let record = pool.record_assignment(&instance).await.unwrap(); + let record = pool.record_assignment(&instance, None, None).await.unwrap(); assert_eq!( pool.load_material(&record.payload).await.unwrap(), instance.launch_material @@ -4114,7 +4338,8 @@ mod tests { let record_paused = |pool: Arc| { let (staged, publish) = pool.pause_next_recording_after_staging(); let instance = instance.clone(); - let recording = tokio::spawn(async move { pool.record_assignment(&instance).await }); + let recording = + tokio::spawn(async move { pool.record_assignment(&instance, None, None).await }); (staged, publish, recording) }; // The first recording stalls after staging and is fenced; its @@ -4357,7 +4582,7 @@ mod tests { .pool_view() .unwrap() .desired - .contains(&routes[count - 1]) + .contains_key(&routes[count - 1]) ); (routes, pool) } @@ -4399,7 +4624,7 @@ mod tests { // The live route stays desired and owned, so its owner is never told // to stop it; the withdrawn one is no longer desired. let view = pool.controller.pool_view().unwrap(); - assert!(view.desired.contains(live)); + assert!(view.desired.contains_key(live)); assert_eq!(view.owners[live.as_str()].member_id, "m1"); assert!(!pool.controller.stopping_routes().contains(live)); pool.reconcile_once().await.unwrap(); @@ -4409,7 +4634,7 @@ mod tests { .pool_view() .unwrap() .desired - .contains(&routes[0]) + .contains_key(&routes[0]) ); } @@ -4572,11 +4797,11 @@ mod tests { fixture.withdraw_record("rt-route-gone").await; pool.reconcile_once().await.unwrap(); let view = pool.controller.pool_view().unwrap(); - assert!(view.desired.contains("rt-route-live")); + assert!(view.desired.contains_key("rt-route-live")); assert!(view.owners.contains_key("rt-route-live")); assert!(!pool.controller.stopping_routes().contains("rt-route-live")); // The confirmed withdrawal still stops its instance. - assert!(!view.desired.contains("rt-route-gone")); + assert!(!view.desired.contains_key("rt-route-gone")); assert!(pool.controller.stopping_routes().contains("rt-route-gone")); } @@ -4661,7 +4886,7 @@ mod tests { taking.pause_next_transition(barrier.clone()); launching.pause_next_transition(barrier); let (taken, launched) = tokio::join!( - taking.take_over(&record, "expired", &ring, &members, &charges), + taking.take_over(&record, "expired", &ring, &members, &charges, None), launching.place_launch(launch("rt-route-new0", "sandbox-new", "generation-1")), ); taken.unwrap(); @@ -5640,10 +5865,12 @@ mod tests { ) }; let order = |charges: BTreeMap>, route: &str, same| { - candidates(&ring, &members, &sandbox, route, &charges, same, MEMBER_CAP) - .into_iter() - .map(|member| member.member_id.clone()) - .collect::>() + candidates( + &ring, &members, &sandbox, route, &charges, same, MEMBER_CAP, None, + ) + .into_iter() + .map(|member| member.member_id.clone()) + .collect::>() }; let charges = |m1, m2| BTreeMap::from([routes_for("m1", m1), routes_for("m2", m2)]); // The least charged member comes first, even against the ring. @@ -5664,6 +5891,27 @@ mod tests { order(charges(MEMBER_CAP, MEMBER_CAP), "rt-m2-0", Some("m2")), ["m2"] ); + // A pinned instance lists only its member, never the ring's choice, + // and nothing when that member is full, leaving, or gone. + let pinned = |charges: BTreeMap>, member: &str| { + candidates( + &ring, + &members, + &sandbox, + "rt-new", + &charges, + None, + MEMBER_CAP, + Some(member), + ) + .into_iter() + .map(|member| member.member_id.clone()) + .collect::>() + }; + assert_eq!(pinned(charges(0, 0), "m2"), ["m2"]); + assert!(pinned(charges(0, MEMBER_CAP), "m2").is_empty()); + assert!(pinned(charges(0, 0), "m3").is_empty()); + assert!(pinned(charges(0, 0), "m4").is_empty()); } #[test] @@ -5683,6 +5931,7 @@ mod tests { charges, None, CAP, + None, ) .first() .map(|member| member.member_id.clone()) diff --git a/crates/openshell-supervisor-control/README.md b/crates/openshell-supervisor-control/README.md index 2758f38338..d4f452200b 100644 --- a/crates/openshell-supervisor-control/README.md +++ b/crates/openshell-supervisor-control/README.md @@ -17,9 +17,15 @@ re-implementing the control contracts. are served at once and each instance has one durable owner: a member, its process, and an ownership term. Every member names itself in its hello; a hello without a member, or with an invalid one, is refused with the - `OPENSHELL_SUPERVISOR_POOL_*` setting to fix. One session per member: a - newer connection epoch of the same member process or a new process of the - member supersedes its stream, a delayed older hello is refused, and reports + `OPENSHELL_SUPERVISOR_POOL_*` setting to fix. `require_host_identity` names + the `HostAccount` whose pod-bound tokens, sent in + `HOST_IDENTITY_TOKEN_HEADER` with the role's `identity_audience`, prove that + a host token's holder is that role's Pod; a supervisor's token also proves + its node (`HostIdentity.node`). `HostAccount.identity_required` refuses a + host token without one. After `bind_members_to_nodes`, a supervisor's member + ID must be that node. One session per + member: a newer connection epoch of the same member process or a new + process of the member supersedes its stream, a delayed older hello is refused, and reports from superseded streams, acks of revisions never sent, regressing acks, and oversized reports are dropped. A stream ends when the token that opened it expires; hosted instances keep running. The pool's recovery deadline @@ -54,6 +60,18 @@ re-implementing the control contracts. replica on its ring below an even share of supervisors, counting placements the records do not show yet. A host follows at most two redirects in a row. Replicas place hosts without coordinating, so the spread is best effort. + In native-network mode (`accept_enforcers`) an external enforcer attaches + with the enforcer token (`HostRole::Enforcer`), its identity token, and an + `EnforcerHello` that must declare exactly the configured workload + nameservers; + `proto/supervisor_host.proto` defines its snapshots and reports. Enforcer + sessions live in their own map, are never redirected, and supersede only + enforcer sessions of the same member ID. A snapshot is sent only once a view + was listed after the stream attached, so a view older than the stream never + clears a generation another replica just published. An enforcer that + declares `enforced_shards` in its status receives only the instances whose + pinned node hashes into those shards, and its session alone is resent a + snapshot when the declaration changes. - `pool_timing`: the timing contract between pool hosts and the gateway: the 15 s membership TTL, the 2 s record refresh, 1 s heartbeats, host silence detection and bounded reconnect attempts, and `reconnect_budget`, the worst @@ -86,8 +104,8 @@ re-implementing the control contracts. that has not reconciled to the assignment yet is degraded, and only a host that reconciled past it without hosting the instance, hosts it for another sandbox, or reports it ended makes it unavailable. -- `credential`: `deliver_credentials` delivers the current supervisor token - and every renewal through the driver's operation, retrying a failed +- `credential`: `deliver_credentials` delivers the current supervisor or + enforcer token and every renewal through the driver's operation, retrying a failed delivery until it succeeds or a newer token supersedes it. - `proto`: the private wire protocol, generated in `openshell-core`. diff --git a/crates/openshell-supervisor-control/src/controller.rs b/crates/openshell-supervisor-control/src/controller.rs index 4cd45d6078..ec1779b9c8 100644 --- a/crates/openshell-supervisor-control/src/controller.rs +++ b/crates/openshell-supervisor-control/src/controller.rs @@ -30,7 +30,8 @@ //! at once. use std::collections::{BTreeMap, BTreeSet}; -use std::sync::atomic::{AtomicUsize, Ordering}; +use std::net::IpAddr; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::{Duration, SystemTime, UNIX_EPOCH}; @@ -41,9 +42,10 @@ use tonic::{Status, Streaming}; use crate::pool_limits::PoolLimits; use crate::proto::{ - AssignmentSnapshot, HostAccepted, HostGatewayHeartbeat, HostGatewayMessage, HostHello, - HostMessage, HostRedirect, HostStatus, PoolMember, RouteOwner, SandboxInstanceAssignment, - SandboxInstanceStatus, SandboxInstanceTakeover, host_gateway_message, host_message, + AssignmentSnapshot, EnforcerHello, HostAccepted, HostGatewayHeartbeat, HostGatewayMessage, + HostHello, HostMessage, HostRedirect, HostStatus, PoolMember, RouteOwner, + SandboxInstanceAssignment, SandboxInstanceStatus, SandboxInstanceTakeover, + host_gateway_message, host_message, }; /// Recovery deadline a supervisor pool offers each sandbox runtime unless the @@ -76,15 +78,48 @@ const POOL_STOP_RETENTION: Duration = Duration::from_mins(2); /// supervisor token that authenticated its stream. #[derive(Clone, Debug, PartialEq, Eq)] pub struct HostIdentity { - /// Subject of the supervisor token (`openshell-supervisor:`). + /// Subject of the host token (`openshell-supervisor:` or + /// `openshell-enforcer:`). pub subject: String, /// `jti` of the supervisor token. pub token_id: String, /// `exp` of the supervisor token (Unix seconds). The gateway ends the /// stream when it passes; the host reconnects with a renewed token. pub expires_at: i64, + /// Node a supervisor's identity token proves its Pod runs on; `None` for + /// an enforcer. + pub node: Option, + /// The role the host's token grants. + pub role: HostRole, } +/// What a connected host may do, from the profile of the token that +/// authenticated it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum HostRole { + /// A shared supervisor: owns assigned instances and receives their launch + /// material and takeover grants. + Supervisor, + /// An external enforcer: receives the pool's desired set without launch + /// material and acknowledges what it enforces. + Enforcer, +} + +impl HostRole { + /// Audience of the role's identity token. + #[must_use] + pub const fn identity_audience(self) -> &'static str { + match self { + Self::Supervisor => "openshell-supervisor", + Self::Enforcer => "openshell-enforcer", + } + } +} + +/// Metadata header carrying a host's pod-bound projected `ServiceAccount` +/// token, audience [`HostRole::identity_audience`], beside its host token. +pub const HOST_IDENTITY_TOKEN_HEADER: &str = "x-openshell-host-identity-token"; + /// The current supervisor token, as the gateway mints and renews it. /// /// A compute driver delivers it to the supervisor process by whatever means @@ -149,6 +184,26 @@ impl InstanceOwner { } } +/// The sandbox generation a desired route runs, as enforcers are sent it. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct DesiredInstance { + pub sandbox_id: String, + pub generation: String, + /// The node the instance's workload runs on; an enforcer that declared + /// shards is sent it only when the node is in one. + pub node: Option, +} + +impl DesiredInstance { + fn of(assignment: &SandboxInstanceAssignment) -> Self { + Self { + sandbox_id: assignment.sandbox_id.clone(), + generation: assignment.generation.clone(), + node: None, + } + } +} + /// A live pool member as the gateway's durable membership records show it. #[derive(Clone, Debug, PartialEq, Eq)] pub struct MemberView { @@ -170,7 +225,7 @@ pub struct PoolView { pub owners: BTreeMap, /// Every route the pool must run, from the gateway's durable records. An /// owned route that is not desired was withdrawn. - pub desired: BTreeSet, + pub desired: BTreeMap, /// Assignments, launch material included, this gateway replica loaded /// for routes its members own. An owned desired route missing here is /// kept by its owner as it is. @@ -279,11 +334,15 @@ struct Pool { withdrawals: BTreeSet, /// Recovery deadline offered to every instance's runtime. recovery_timeout_secs: u32, + /// When the records of the latest view were listed, whether or not the + /// view changed anything. + listed_at: Option, } impl Pool { fn new(recovery_timeout_secs: u32) -> Self { Self { + listed_at: None, loaded: false, view: PoolView::default(), owned_since: BTreeMap::new(), @@ -308,6 +367,7 @@ struct HostSession { /// Latest report of this session. status: Option, connected_at_ms: i64, + attached_at: tokio::time::Instant, /// Ownership term of each route the snapshots sent on this stream assign /// or keep, with the revision that first installed that term. terms: BTreeMap, @@ -332,10 +392,22 @@ impl HostSession { #[derive(Default)] struct Observed { + /// Pool member sessions. sessions: BTreeMap, + /// Enforcer sessions; never pool members. + enforcers: BTreeMap, next_session: u64, } +impl Observed { + fn session_mut(&mut self, id: u64) -> Option<&mut HostSession> { + match self.sessions.get_mut(&id) { + Some(session) => Some(session), + None => self.enforcers.get_mut(&id), + } + } +} + struct Inner { desired: Mutex, /// The supervisor pool: its durable view and what this gateway placed, @@ -345,6 +417,11 @@ struct Inner { placement: Mutex>>, /// Latest supervisor token the gateway minted; `None` until the first. credential: watch::Sender>, + /// Latest enforcer token; `None` unless native-network mode mints one. + enforcer_credential: watch::Sender>, + /// The workload nameservers enforcers must declare; `None` refuses + /// enforcers. + enforcer_nameservers: Mutex>>, /// Current revision of everything snapshots are derived from; 0 while /// uninitialized. revision: watch::Sender, @@ -358,6 +435,21 @@ struct Inner { limits: Mutex, /// Live gateway replicas serving the pool, which scale its capacity. gateway_replicas: AtomicUsize, + /// Set by [`SupervisorHostController::require_host_identity`]. + supervisor_account: Mutex>, + enforcer_account: Mutex>, + /// Set by [`SupervisorHostController::bind_members_to_nodes`]. + members_bound_to_nodes: AtomicBool, +} + +/// The Kubernetes `ServiceAccount` whose pod-bound tokens prove that a +/// holder of a role's host token is one of that role's Pods. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HostAccount { + pub namespace: String, + pub service_account: String, + /// Refuse a host token that arrives without an identity token. + pub identity_required: bool, } /// Gateway-owned desired assignments and observed status of the shared @@ -405,12 +497,17 @@ impl SupervisorHostController { pool: Mutex::new(Pool::new(POOL_RECOVERY_TIMEOUT_SECS)), placement: Mutex::new(None), credential: watch::Sender::new(None), + enforcer_credential: watch::Sender::new(None), + enforcer_nameservers: Mutex::new(None), revision: watch::Sender::new(0), membership: watch::Sender::new(0), observed: Mutex::new(Observed::default()), peer_endpoint: Mutex::new(String::new()), limits: Mutex::new(PoolLimits::default()), gateway_replicas: AtomicUsize::new(1), + supervisor_account: Mutex::new(None), + enforcer_account: Mutex::new(None), + members_bound_to_nodes: AtomicBool::new(false), }), } } @@ -442,6 +539,40 @@ impl SupervisorHostController { .max_pool_instances(self.inner.gateway_replicas.load(Ordering::Relaxed)) } + fn account_slot(&self, role: HostRole) -> &Mutex> { + match role { + HostRole::Supervisor => &self.inner.supervisor_account, + HostRole::Enforcer => &self.inner.enforcer_account, + } + } + + /// Verify `role`'s identity tokens as issued for `account`. Call it + /// before any host attaches. + pub fn require_host_identity(&self, role: HostRole, account: HostAccount) { + *lock(self.account_slot(role)) = Some(account); + } + + /// The account `role`'s identity tokens must be issued for, when set. + #[must_use] + pub fn host_account(&self, role: HostRole) -> Option { + lock(self.account_slot(role)).clone() + } + + /// Accept only supervisors whose pool member ID is the node their + /// identity token proves, and keep unpinned instances off them. Call it + /// before any host attaches. + pub fn bind_members_to_nodes(&self) { + self.inner + .members_bound_to_nodes + .store(true, Ordering::Relaxed); + } + + /// Whether [`Self::bind_members_to_nodes`] was called. + #[must_use] + pub fn members_bound_to_nodes(&self) -> bool { + self.inner.members_bound_to_nodes.load(Ordering::Relaxed) + } + /// Tell attaching hosts to dial their sandbox sessions to `peer_endpoint`. /// Call it before any host attaches. pub fn set_peer_endpoint(&self, peer_endpoint: String) { @@ -476,6 +607,25 @@ impl SupervisorHostController { self.inner.credential.subscribe() } + /// Accept enforcer streams that declare exactly these workload + /// nameservers. + pub fn accept_enforcers(&self, nameservers: &[IpAddr]) { + *lock(&self.inner.enforcer_nameservers) = Some(nameservers.iter().copied().collect()); + } + + /// Publish a freshly minted enforcer token for delivery to the enforcer. + pub fn publish_enforcer_credential(&self, credential: SupervisorCredential) { + self.inner + .enforcer_credential + .send_replace(Some(credential)); + } + + /// The current enforcer token and every renewal after it. + #[must_use] + pub fn enforcer_credential(&self) -> watch::Receiver> { + self.inner.enforcer_credential.subscribe() + } + /// The complete desired set has been derived from durable records at /// least once. #[must_use] @@ -519,8 +669,13 @@ impl SupervisorHostController { /// Assign one instance, served at once and kept over views listed /// before it; its durable record makes it desired on every gateway /// replica. Refused beyond the pool's capacity, so the caller fails its - /// create before anything runs. - pub fn assign(&self, assignment: SandboxInstanceAssignment) -> Result<(), AssignmentError> { + /// create before anything runs. `node` is the node the instance's + /// workload runs on, if known. + pub fn assign( + &self, + assignment: SandboxInstanceAssignment, + node: Option<&str>, + ) -> Result<(), AssignmentError> { let max_pool_instances = self.max_pool_instances(); let mut desired = lock(&self.inner.desired); if !desired.assignments.contains_key(&assignment.route) @@ -533,7 +688,13 @@ impl SupervisorHostController { pool.launched .insert(assignment.route.clone(), tokio::time::Instant::now()); pool.withdrawals.remove(&assignment.route); - pool.view.desired.insert(assignment.route.clone()); + pool.view.desired.insert( + assignment.route.clone(), + DesiredInstance { + node: node.map(str::to_string), + ..DesiredInstance::of(&assignment) + }, + ); } let next = desired.revision + 1; desired.stopping.remove(&assignment.route); @@ -581,6 +742,7 @@ impl SupervisorHostController { let mut desired = lock(&self.inner.desired); let mut pool_guard = lock(&self.inner.pool); let pool = &mut *pool_guard; + pool.listed_at = Some(pool.listed_at.map_or(listed_at, |last| last.max(listed_at))); pool.placed .retain(|_, (_, placed_at)| *placed_at >= listed_at); for (route, (owner, _)) in &pool.placed { @@ -591,8 +753,19 @@ impl SupervisorHostController { pool.launched .retain(|_, launched_at| *launched_at >= listed_at); for route in pool.launched.keys() { - view.desired.insert(route.clone()); if let Some(assigned) = desired.assignments.get(route) { + let node = pool + .view + .desired + .get(route) + .and_then(|instance| instance.node.clone()); + view.desired.insert( + route.clone(), + DesiredInstance { + node, + ..DesiredInstance::of(&assigned.assignment) + }, + ); view.assignments .entry(route.clone()) .or_insert_with(|| assigned.assignment.clone()); @@ -605,7 +778,12 @@ impl SupervisorHostController { let now = tokio::time::Instant::now(); let stopping_before = desired.stopping.len(); if pool.loaded { - for route in pool.view.desired.difference(&view.desired) { + for route in pool + .view + .desired + .keys() + .filter(|route| !view.desired.contains_key(*route)) + { if let Some(owner) = pool.view.owners.get(route) { desired .stopping @@ -618,7 +796,7 @@ impl SupervisorHostController { // withdrawal recorded. desired .stopping - .retain(|route, _| !view.desired.contains(route)); + .retain(|route, _| !view.desired.contains_key(route)); let stops_changed = desired.stopping.len() != stopping_before; if pool.loaded && desired.initialized && pool.view == view && !stops_changed { return; @@ -881,13 +1059,33 @@ impl SupervisorHostController { "supervisor host hello names no instance", )); } + let enforcer = identity.role == HostRole::Enforcer; let Some(member) = &hello.member else { - return Err(Status::failed_precondition(MISSING_MEMBER)); + return Err(Status::failed_precondition(if enforcer { + MISSING_ENFORCER_MEMBER + } else { + MISSING_MEMBER + })); }; - validate_member(member).map_err(Status::invalid_argument)?; + validate_enforcer( + identity.role, + hello.enforcer.as_ref(), + lock(&self.inner.enforcer_nameservers).as_ref(), + )?; + if enforcer { + validate_enforcer_member(member).map_err(Status::invalid_argument)?; + } else { + validate_member(member).map_err(Status::invalid_argument)?; + if self.members_bound_to_nodes() { + validate_node(identity.node.as_deref(), &member.member_id)?; + } + } let member_id = member.member_id.clone(); let (tx, rx) = mpsc::channel(OUTBOUND_QUEUE); - let home = home(&member_id, hello.accepts_redirect); + // Enforcers are served by whichever replica they dial. + let home = (!enforcer) + .then(|| home(&member_id, hello.accepts_redirect)) + .flatten(); if hello.accepts_redirect && let Some(peer_endpoint) = home { @@ -907,7 +1105,8 @@ impl SupervisorHostController { nanos: 0, }), peer_endpoint, - route_lookups: true, + // Route owners name supervisors; an enforcer needs none. + route_lookups: !enforcer, })), })) .await @@ -915,7 +1114,7 @@ impl SupervisorHostController { let controller = self.clone(); tokio::spawn(async move { controller - .run_session(session_id, expires_at, inbound, tx, superseded) + .run_session(session_id, expires_at, inbound, tx, superseded, !enforcer) .await; controller.end_session(session_id); }); @@ -937,15 +1136,20 @@ impl SupervisorHostController { .ok_or_else(|| Status::failed_precondition(MISSING_MEMBER))?; let mut observed = lock(&self.inner.observed); let member_id = member.member_id.clone(); - let replaced = observed - .sessions + let enforcer = identity.role == HostRole::Enforcer; + let sessions = if enforcer { + &observed.enforcers + } else { + &observed.sessions + }; + let replaced = sessions .values() .filter(|session| session.member_id() == member_id) .map(|session| session.id) .collect::>(); if let Some(current) = replaced .iter() - .filter_map(|id| observed.sessions.get(id)) + .filter_map(|id| sessions.get(id)) .find(|session| session.instance_id == hello.instance_id) && hello.connection_epoch <= current.connection_epoch { @@ -955,8 +1159,13 @@ impl SupervisorHostController { } observed.next_session += 1; let id = observed.next_session; + let sessions = if enforcer { + &mut observed.enforcers + } else { + &mut observed.sessions + }; for previous in replaced { - if let Some(previous) = observed.sessions.remove(&previous) { + if let Some(previous) = sessions.remove(&previous) { tracing::info!( subject = %previous.identity.subject, instance_id = %previous.instance_id, @@ -969,6 +1178,7 @@ impl SupervisorHostController { } tracing::info!( subject = %identity.subject, + role = ?identity.role, instance_id = %hello.instance_id, member = %member_id, connection_epoch = hello.connection_epoch, @@ -976,7 +1186,7 @@ impl SupervisorHostController { "supervisor host attached" ); let (superseded, watch) = watch::channel(false); - observed.sessions.insert( + sessions.insert( id, HostSession { id, @@ -988,19 +1198,26 @@ impl SupervisorHostController { sent_revision: 0, status: None, connected_at_ms: unix_millis(), + attached_at: tokio::time::Instant::now(), terms: BTreeMap::new(), pending_terms: None, }, ); drop(observed); - self.membership_changed(); + if !enforcer { + self.membership_changed(); + } Ok((id, watch)) } fn end_session(&self, id: u64) { let mut observed = lock(&self.inner.observed); - let Some(session) = observed.sessions.remove(&id) else { - return; + let (session, member) = match observed.sessions.remove(&id) { + Some(session) => (session, true), + None => match observed.enforcers.remove(&id) { + Some(session) => (session, false), + None => return, + }, }; drop(observed); tracing::info!( @@ -1010,7 +1227,9 @@ impl SupervisorHostController { session = id, "supervisor host detached; hosted instances keep running" ); - self.membership_changed(); + if member { + self.membership_changed(); + } } /// Note that `revision` was sent on session `id`. A route keeps the @@ -1019,7 +1238,7 @@ impl SupervisorHostController { /// it already had, and a route the snapshot omits has none. fn record_sent(&self, id: u64, revision: u64) { let mut observed = lock(&self.inner.observed); - if let Some(session) = observed.sessions.get_mut(&id) { + if let Some(session) = observed.session_mut(id) { session.sent_revision = session.sent_revision.max(revision); if let Some(pending) = session .pending_terms @@ -1049,15 +1268,21 @@ impl SupervisorHostController { } } - /// Record a report from session `id`. Reports from other sessions, acks - /// of revisions never sent on this session, regressing acks, and - /// oversized reports are dropped. - fn record_status(&self, id: u64, status: HostStatus) -> Result<(), &'static str> { + /// Record a report from session `id`, returning whether an enforcer + /// changed the shards it declared. Reports from other sessions, acks of + /// revisions never sent on this session, regressing acks, and oversized + /// reports are dropped. + fn record_status(&self, id: u64, mut status: HostStatus) -> Result { let max_reported_instances = self.pool_limits().max_reported_instances(); let mut observed = lock(&self.inner.observed); - let Some(session) = observed.sessions.get_mut(&id) else { + let Some(session) = observed.session_mut(id) else { return Err("report from a superseded supervisor host session"); }; + if session.identity.role == HostRole::Enforcer + && (!status.instances.is_empty() || status.leaving) + { + return Err("an enforcer host reports only its applied revision"); + } if status.applied_revision > session.sent_revision { return Err("supervisor host acknowledged a revision it was never sent"); } @@ -1076,6 +1301,18 @@ impl SupervisorHostController { .status .as_ref() .is_some_and(|previous| previous.leaving); + // The order and repeats of declared shards mean nothing, so neither + // counts as a change. + if let Some(shards) = status.enforced_shards.as_mut() { + shards.ids.sort_unstable(); + shards.ids.dedup(); + } + let declared = session.identity.role == HostRole::Enforcer + && session + .status + .as_ref() + .and_then(|previous| previous.enforced_shards.as_ref()) + != status.enforced_shards.as_ref(); session.status = Some(status); drop(observed); if leaving { @@ -1084,7 +1321,7 @@ impl SupervisorHostController { let mut desired = lock(&self.inner.desired); self.bump(&mut desired); } - Ok(()) + Ok(declared) } /// Where `route` is supervised: the runtime listener of the live member @@ -1121,6 +1358,9 @@ impl SupervisorHostController { return None; } let mut observed = lock(&self.inner.observed); + if let Some(enforcer) = observed.enforcers.get(&id) { + return enforcer_snapshot(desired.revision, &pool, enforcer); + } let session = observed.sessions.get_mut(&id)?; let member_id = session.member_id().to_string(); let instance_id = session.instance_id.clone(); @@ -1157,7 +1397,7 @@ impl SupervisorHostController { .iter() .filter(|(route, owner)| { owner.member_id == *member_id - && !pool.view.desired.contains(*route) + && !pool.view.desired.contains_key(*route) && !desired.stopping.contains_key(*route) }) .map(|(route, _)| route.clone()), @@ -1173,7 +1413,7 @@ impl SupervisorHostController { .iter() .filter(|(route, owner)| { owned_by_session(owner) - && pool.view.desired.contains(*route) + && pool.view.desired.contains_key(*route) && !desired.assignments.contains_key(*route) && !desired.stopping.contains_key(*route) }) @@ -1206,6 +1446,7 @@ impl SupervisorHostController { mut inbound: Streaming, tx: mpsc::Sender>, mut superseded: watch::Receiver, + route_lookups: bool, ) { // A bearer is verified once per stream, so the stream lives no longer // than the token did. Hosted instances are unaffected; the host @@ -1272,14 +1513,20 @@ impl SupervisorHostController { message = inbound.next() => match message { Some(Ok(HostMessage { payload: Some(host_message::Payload::Status(status)) })) => { last_heard = tokio::time::Instant::now(); - if let Err(reason) = self.record_status(session_id, status) { - tracing::warn!(session = session_id, reason, "dropped supervisor host status report"); + match self.record_status(session_id, status) { + // Only this session's snapshot follows its + // declaration; every sent revision is at least 1. + Ok(true) => sent_revision = 0, + Ok(false) => {} + Err(reason) => { + tracing::warn!(session = session_id, reason, "dropped supervisor host status report"); + } } } Some(Ok(HostMessage { payload: Some(host_message::Payload::Heartbeat(_)) })) => { last_heard = tokio::time::Instant::now(); } - Some(Ok(HostMessage { payload: Some(host_message::Payload::RouteLookup(lookup)) })) => { + Some(Ok(HostMessage { payload: Some(host_message::Payload::RouteLookup(lookup)) })) if route_lookups => { last_heard = tokio::time::Instant::now(); let owner = self.route_owner(lookup.route); if !send(host_gateway_message::Payload::RouteOwner(owner)).await { @@ -1322,10 +1569,116 @@ impl SupervisorHostController { } } +/// The pool's whole desired set for an enforcer stream, once listed after the +/// stream attached. An earlier view, as another replica's could be, may lack +/// a generation just published elsewhere, and the enforcer would clear it. +/// A launch is published before it is assigned, and records are listed after +/// `listed_at` is taken, so a later listing includes it. An enforcer that +/// declared shards is sent only the instances on nodes of those shards. +fn enforcer_snapshot( + revision: u64, + pool: &Pool, + session: &HostSession, +) -> Option { + if pool + .listed_at + .is_none_or(|listed_at| listed_at < session.attached_at) + { + return None; + } + let declared = session + .status + .as_ref() + .and_then(|status| status.enforced_shards.as_ref()) + .map(|shards| { + ( + shards.count, + shards.ids.iter().copied().collect::>(), + ) + }); + let enforced = |instance: &DesiredInstance| { + declared.as_ref().is_none_or(|(count, ids)| { + instance + .node + .as_deref() + .and_then(|node| shard_of(node, *count)) + .is_some_and(|shard| ids.contains(&shard)) + }) + }; + Some(AssignmentSnapshot { + revision, + instances: pool + .view + .desired + .values() + .filter(|instance| enforced(instance)) + .map(|instance| SandboxInstanceAssignment { + sandbox_id: instance.sandbox_id.clone(), + generation: instance.generation.clone(), + ..SandboxInstanceAssignment::default() + }) + .collect(), + pool: false, + ..AssignmentSnapshot::default() + }) +} + +/// The enforcer shard of `node`: FNV-1a 32 of its name, modulo `count`. Part +/// of the contract with enforcers; `None` for no shards. +fn shard_of(node: &str, count: u32) -> Option { + let hash = node.bytes().fold(0x811c_9dc5_u32, |hash, byte| { + (hash ^ u32::from(byte)).wrapping_mul(0x0100_0193) + }); + hash.checked_rem(count) +} + +/// A hello carries an enforcer section exactly when an enforcer token opened +/// the stream, and an enforcer declares the configured workload nameservers. +fn validate_enforcer( + role: HostRole, + hello: Option<&EnforcerHello>, + configured: Option<&BTreeSet>, +) -> Result<(), Status> { + let hello = match (role, hello) { + (HostRole::Supervisor, None) => return Ok(()), + (HostRole::Supervisor, Some(_)) => { + return Err(Status::invalid_argument( + "a supervisor token cannot attach as an enforcer", + )); + } + (HostRole::Enforcer, None) => { + return Err(Status::invalid_argument( + "an enforcer token must attach with an enforcer hello", + )); + } + (HostRole::Enforcer, Some(hello)) => hello, + }; + let Some(configured) = configured else { + return Err(Status::failed_precondition( + "this gateway accepts no enforcer; configure external_enforcer", + )); + }; + let declared = hello + .workload_nameservers + .iter() + .map(|address| address.parse::()) + .collect::, _>>() + .map_err(|_| Status::invalid_argument("the enforcer declared an invalid nameserver"))?; + if declared != *configured { + return Err(Status::failed_precondition(format!( + "the enforcer's workload nameservers {declared:?} are not the configured \ + external_enforcer.network.sandbox.nameservers {configured:?}" + ))); + } + Ok(()) +} + /// Why a hello without a pool member is refused. const MISSING_MEMBER: &str = "the shared supervisor did not name its pool member; set \ OPENSHELL_SUPERVISOR_POOL_MEMBER_ID to a stable member ID and \ OPENSHELL_SUPERVISOR_POOL_ADVERTISE_IP to an IP reachable from sandbox runtimes"; +const MISSING_ENFORCER_MEMBER: &str = "the enforcer did not name its replica; send a pool member \ +with a stable, non-empty member ID per enforcer replica"; /// Sends a host to another gateway replica. #[must_use] @@ -1337,17 +1690,48 @@ pub fn redirect(peer_endpoint: String) -> HostGatewayMessage { } } -/// Check a pool member's identity, naming the setting that is wrong. -fn validate_member(member: &PoolMember) -> Result<(), &'static str> { - let valid = |value: &str| { - !value.is_empty() && value.len() <= 253 && !value.chars().any(char::is_whitespace) - }; - if !valid(&member.member_id) { +/// A node supervisor's member ID is its node name, so the node its token +/// proves must be that member. +fn validate_node(node: Option<&str>, member_id: &str) -> Result<(), Status> { + if node == Some(member_id) { + Ok(()) + } else { + Err(Status::permission_denied( + "the shared supervisor's pool member id is not the node its identity token proves", + )) + } +} + +/// Check a host's member ID, naming the setting that is wrong. +fn validate_member_id(member_id: &str) -> Result<(), &'static str> { + if member_id.is_empty() || member_id.len() > 253 || member_id.chars().any(char::is_whitespace) { return Err( "the shared supervisor's pool member id is empty or invalid; set \ OPENSHELL_SUPERVISOR_POOL_MEMBER_ID to a stable member ID", ); } + Ok(()) +} + +/// An enforcer names its replica and hosts no sandbox runtimes. +fn validate_enforcer_member(member: &PoolMember) -> Result<(), &'static str> { + if member.member_id.is_empty() { + return Err(MISSING_ENFORCER_MEMBER); + } + if member.member_id.len() > 253 || member.member_id.chars().any(char::is_whitespace) { + return Err( + "the enforcer's replica name is invalid; use at most 253 characters and no whitespace", + ); + } + if !member.runtime_address.is_empty() { + return Err("an enforcer hosts no sandbox runtimes; leave runtime_address empty"); + } + Ok(()) +} + +/// Check a pool member's identity, naming the setting that is wrong. +fn validate_member(member: &PoolMember) -> Result<(), &'static str> { + validate_member_id(&member.member_id)?; if member .runtime_address .parse::() @@ -1382,6 +1766,7 @@ fn credential_remaining(expires_at: i64) -> Duration { #[cfg(test)] mod tests { use super::*; + use crate::proto::EnforcedShards; fn assignment(route: &str, material: &[u8]) -> SandboxInstanceAssignment { SandboxInstanceAssignment { @@ -1408,6 +1793,17 @@ mod tests { error: String::new(), }) .collect(), + enforced_shards: None, + } + } + + fn declared(applied_revision: u64, count: u32, ids: &[u32]) -> HostStatus { + HostStatus { + enforced_shards: Some(EnforcedShards { + count, + ids: ids.to_vec(), + }), + ..status(applied_revision, &[]) } } @@ -1418,20 +1814,20 @@ mod tests { assert_eq!(controller.max_pool_instances(), 32); for index in 0..32 { controller - .assign(assignment(&format!("rt-{index}"), b"x")) + .assign(assignment(&format!("rt-{index}"), b"x"), None) .unwrap(); } assert_eq!( - controller.assign(assignment("rt-one-too-many", b"x")), + controller.assign(assignment("rt-one-too-many", b"x"), None), Err(AssignmentError::Capacity) ); // Assigning a route again is not a new instance. - assert_eq!(controller.assign(assignment("rt-0", b"x")), Ok(())); + assert_eq!(controller.assign(assignment("rt-0", b"x"), None), Ok(())); // Another live gateway replica adds its members' capacity. controller.set_gateway_replicas(2); assert_eq!(controller.max_pool_instances(), 64); assert_eq!( - controller.assign(assignment("rt-one-too-many", b"x")), + controller.assign(assignment("rt-one-too-many", b"x"), None), Ok(()) ); } @@ -1485,7 +1881,7 @@ mod tests { // A newer instance of the process is pending until its member // reconciles past it; a route without an owner has no verdict. - controller.assign(assignment("rt-b", b"b")).unwrap(); + controller.assign(assignment("rt-b", b"b"), None).unwrap(); controller.place_owner("rt-b", owner("m1", "boot-1", 1)); assert_eq!(controller.observed("rt-b"), ObservedInstance::Pending); assert_eq!(controller.observed("rt-unknown"), ObservedInstance::NoHost); @@ -1516,6 +1912,7 @@ mod tests { runtime_address: format!("10.0.0.{}:5500", member.len()), }), accepts_redirect: false, + enforcer: None, } } @@ -1548,6 +1945,8 @@ mod tests { subject: "openshell-supervisor:test".to_string(), token_id: "token".to_string(), expires_at: i64::MAX, + node: None, + role: HostRole::Supervisor, } } @@ -1562,7 +1961,15 @@ mod tests { .collect::>(); PoolView { members, - desired: owners.keys().cloned().collect(), + desired: owners + .keys() + .map(|route| { + ( + route.clone(), + DesiredInstance::of(&assignment(route, route.as_bytes())), + ) + }) + .collect(), assignments: owners .keys() .map(|route| (route.clone(), assignment(route, route.as_bytes()))) @@ -1581,6 +1988,367 @@ mod tests { .collect() } + fn enforcer_identity() -> HostIdentity { + HostIdentity { + subject: "openshell-enforcer:test".to_string(), + role: HostRole::Enforcer, + ..identity() + } + } + + fn enforcer_hello(member: &str, process: &str, connection_epoch: u64) -> HostHello { + HostHello { + member: Some(PoolMember { + member_id: member.to_string(), + runtime_address: String::new(), + }), + enforcer: Some(EnforcerHello { + workload_nameservers: vec!["192.168.100.1".to_string()], + }), + ..member_hello(member, process, connection_epoch) + } + } + + #[test] + fn enforcer_hellos_match_the_token_and_the_configured_nameservers() { + let configured = + BTreeSet::from(["192.168.100.1".parse().unwrap(), "fd00::1".parse().unwrap()]); + let declared = |nameservers: &[&str]| EnforcerHello { + workload_nameservers: nameservers.iter().map(ToString::to_string).collect(), + }; + let both = declared(&["fd00::1", "192.168.100.1"]); + validate_enforcer(HostRole::Supervisor, None, Some(&configured)).unwrap(); + validate_enforcer(HostRole::Enforcer, Some(&both), Some(&configured)).unwrap(); + for (role, hello, configured, message) in [ + ( + HostRole::Supervisor, + Some(&both), + Some(&configured), + "cannot attach as an enforcer", + ), + ( + HostRole::Enforcer, + None, + Some(&configured), + "must attach with an enforcer hello", + ), + (HostRole::Enforcer, Some(&both), None, "accepts no enforcer"), + ( + HostRole::Enforcer, + Some(&declared(&["192.168.100.1"])), + Some(&configured), + "not the configured", + ), + ( + HostRole::Enforcer, + Some(&declared(&["resolver.example"])), + Some(&configured), + "invalid nameserver", + ), + ] { + let error = validate_enforcer(role, hello, configured).unwrap_err(); + assert!(error.message().contains(message), "{}", error.message()); + } + } + + #[test] + fn enforcers_get_the_desired_set_and_are_never_members() { + let controller = SupervisorHostController::new(); + let mut changes = controller.membership_changes(); + changes.mark_unchanged(); + let before_attach = tokio::time::Instant::now(); + let (first, superseded) = controller + .begin_session( + enforcer_identity(), + &enforcer_hello("enforcer-0", "boot-1", 1), + ) + .unwrap(); + let (member, _) = controller + .begin_session(identity(), &member_hello("enforcer-0", "boot-1", 1)) + .unwrap(); + changes.mark_unchanged(); + // An enforcer named like a member supersedes only enforcers. + let (enforcer, _) = controller + .begin_session( + enforcer_identity(), + &enforcer_hello("enforcer-0", "boot-1", 2), + ) + .unwrap(); + assert!(*superseded.borrow()); + assert!(!changes.has_changed().unwrap()); + assert_eq!(controller.connected_members().len(), 1); + controller.end_session(member); + assert!(!controller.host_connected()); + changes.mark_unchanged(); + + // A view listed before the stream attached may lack a generation + // another replica just published; nothing is sent until a later one. + let view = loaded_view( + vec![member_view("m1", "p1")], + [("rt-a", owner("m1", "p1", 1))], + ); + controller.update_pool(view.clone(), before_attach); + assert!(controller.snapshot(enforcer).is_none()); + // An unchanged view listed later is enough. + controller.update_pool(view, tokio::time::Instant::now()); + let snapshot = controller.snapshot(enforcer).unwrap(); + assert!(!snapshot.pool); + assert_eq!( + snapshot.instances, + vec![SandboxInstanceAssignment { + sandbox_id: "sandbox-rt-a".to_string(), + generation: "gen".to_string(), + ..SandboxInstanceAssignment::default() + }] + ); + assert!(snapshot.stop_routes.is_empty() && snapshot.route_directory.is_empty()); + assert!(snapshot.recovery_timeout.is_none()); + + // Launches and withdrawals here reach the enforcer at once. + controller.assign(assignment("rt-b", b"b"), None).unwrap(); + assert_eq!(controller.snapshot(enforcer).unwrap().instances.len(), 2); + controller.unassign("rt-a"); + let snapshot = controller.snapshot(enforcer).unwrap(); + assert_eq!(snapshot.instances.len(), 1); + assert_eq!(snapshot.instances[0].sandbox_id, "sandbox-rt-b"); + + // An enforcer reports only the revision it applied. + controller.record_sent(enforcer, snapshot.revision); + assert!( + controller + .record_status(enforcer, status(snapshot.revision, &["rt-b"])) + .is_err() + ); + let leaving = HostStatus { + leaving: true, + ..status(snapshot.revision, &[]) + }; + assert!(controller.record_status(enforcer, leaving).is_err()); + controller + .record_status(enforcer, status(snapshot.revision, &[])) + .unwrap(); + assert!(controller.member_reports().is_empty()); + controller.end_session(first); + controller.end_session(enforcer); + assert!(!changes.has_changed().unwrap()); + } + + fn sandbox_ids(snapshot: &AssignmentSnapshot) -> Vec<&str> { + snapshot + .instances + .iter() + .map(|instance| instance.sandbox_id.as_str()) + .collect() + } + + #[test] + fn enforcers_get_the_instances_of_the_shards_they_declare() { + let controller = SupervisorHostController::new(); + let (enforcer, _) = controller + .begin_session( + enforcer_identity(), + &enforcer_hello("enforcer-0", "boot-1", 1), + ) + .unwrap(); + let (member, _) = controller + .begin_session(identity(), &member_hello("m1", "p1", 1)) + .unwrap(); + // With 4 shards, node-a is in shard 3, node-b in 2, node-c in 1. + let mut view = loaded_view( + vec![member_view("m1", "p1")], + [ + ("rt-a", owner("m1", "p1", 1)), + ("rt-b", owner("m1", "p1", 1)), + ("rt-x", owner("m1", "p1", 1)), + ], + ); + for (route, node) in [("rt-a", "node-a"), ("rt-b", "node-b")] { + view.desired.get_mut(route).unwrap().node = Some(node.to_string()); + } + controller.update_pool(view.clone(), tokio::time::Instant::now()); + let snapshot = controller.snapshot(enforcer).unwrap(); + assert_eq!( + sandbox_ids(&snapshot), + ["sandbox-rt-a", "sandbox-rt-b", "sandbox-rt-x"], + "an enforcer that declared nothing gets every instance" + ); + controller.record_sent(enforcer, snapshot.revision); + + assert_eq!( + controller.record_status(enforcer, declared(0, 4, &[3])), + Ok(true) + ); + assert_eq!( + sandbox_ids(&controller.snapshot(enforcer).unwrap()), + ["sandbox-rt-a"], + "an instance without a node is in no shard" + ); + assert_eq!( + controller.record_status(enforcer, declared(snapshot.revision, 4, &[3])), + Ok(false), + "an ack with the same declaration changes nothing" + ); + assert_eq!( + controller.record_status(enforcer, declared(snapshot.revision, 4, &[2, 3])), + Ok(true) + ); + assert_eq!( + controller.record_status(enforcer, declared(snapshot.revision, 4, &[3, 2, 3])), + Ok(false), + "a reordered or repeated declaration of the same shards changes nothing" + ); + assert_eq!( + sandbox_ids(&controller.snapshot(enforcer).unwrap()), + ["sandbox-rt-a", "sandbox-rt-b"] + ); + assert_eq!( + controller.record_status(enforcer, declared(snapshot.revision, 4, &[])), + Ok(true) + ); + assert!(controller.snapshot(enforcer).unwrap().instances.is_empty()); + assert_eq!( + controller.record_status(enforcer, declared(snapshot.revision, 0, &[0])), + Ok(true) + ); + assert!( + controller.snapshot(enforcer).unwrap().instances.is_empty(), + "no shards match nothing" + ); + assert_eq!( + controller.record_status(enforcer, declared(snapshot.revision, 4, &[1])), + Ok(true) + ); + + // A launch here carries its node, and keeps it over views listed + // before it. + let before_launch = tokio::time::Instant::now(); + controller + .assign(assignment("rt-c", b"c"), Some("node-c")) + .unwrap(); + assert_eq!( + sandbox_ids(&controller.snapshot(enforcer).unwrap()), + ["sandbox-rt-c"] + ); + controller.update_pool(view, before_launch); + assert_eq!( + sandbox_ids(&controller.snapshot(enforcer).unwrap()), + ["sandbox-rt-c"] + ); + + // Enforcer reports still carry no instances, and a member's + // declaration is ignored. + assert!( + controller + .record_status( + enforcer, + HostStatus { + enforced_shards: Some(EnforcedShards { + count: 4, + ids: vec![1] + }), + ..status(snapshot.revision, &["rt-c"]) + } + ) + .is_err() + ); + assert_eq!( + controller.record_status(member, declared(0, 4, &[1])), + Ok(false) + ); + } + + #[test] + fn a_reconnected_enforcer_is_undeclared_until_it_reports() { + let controller = SupervisorHostController::new(); + let mut view = loaded_view( + vec![member_view("m1", "p1")], + [ + ("rt-a", owner("m1", "p1", 1)), + ("rt-b", owner("m1", "p1", 1)), + ], + ); + view.desired.get_mut("rt-a").unwrap().node = Some("node-a".to_string()); + let (first, _) = controller + .begin_session( + enforcer_identity(), + &enforcer_hello("enforcer-0", "boot-1", 1), + ) + .unwrap(); + controller + .record_status(first, declared(0, 4, &[3])) + .unwrap(); + let (second, _) = controller + .begin_session( + enforcer_identity(), + &enforcer_hello("enforcer-0", "boot-1", 2), + ) + .unwrap(); + controller.update_pool(view, tokio::time::Instant::now()); + assert_eq!(controller.snapshot(second).unwrap().instances.len(), 2); + controller + .record_status(second, declared(0, 4, &[3])) + .unwrap(); + assert_eq!( + sandbox_ids(&controller.snapshot(second).unwrap()), + ["sandbox-rt-a"] + ); + } + + #[test] + fn shard_of_matches_the_enforcer_hash() { + for (node, count, shard) in [ + ("node-a", 1, 0), + ("node-a", 4, 3), + ("node-a", 64, 19), + ("node-a", 1000, 867), + ("node-b", 64, 38), + ("node-c", 64, 57), + ("worker-17", 1000, 134), + ("host-0001.example.internal", 64, 40), + ("", 64, 5), + ] { + assert_eq!(shard_of(node, count), Some(shard), "{node} of {count}"); + } + assert_eq!(shard_of("node-a", 0), None); + } + + #[test] + fn a_full_enforcer_snapshot_fits_the_enforcer_receive_limit() { + use prost::Message as _; + const INSTANCES: usize = 131_072; + const ENFORCER_RECEIVE_LIMIT: usize = 16 << 20; + let controller = SupervisorHostController::new(); + let (enforcer, _) = controller + .begin_session( + enforcer_identity(), + &enforcer_hello("enforcer-0", "boot-1", 1), + ) + .unwrap(); + let view = PoolView { + desired: (0..INSTANCES) + .map(|index| { + ( + format!("rt-{index}"), + DesiredInstance { + sandbox_id: format!("{index:08x}-0000-4000-8000-000000000000"), + generation: "g".repeat(64), + node: Some(format!("node-{index}")), + }, + ) + }) + .collect(), + ..PoolView::default() + }; + controller.update_pool(view, tokio::time::Instant::now()); + let snapshot = controller.snapshot(enforcer).unwrap(); + assert_eq!(snapshot.instances.len(), INSTANCES); + let encoded = HostGatewayMessage { + payload: Some(host_gateway_message::Payload::Assignments(snapshot)), + } + .encoded_len(); + assert!(encoded < ENFORCER_RECEIVE_LIMIT, "{encoded} bytes"); + } + #[test] fn membership_changes_follow_member_streams_and_leaving() { let controller = SupervisorHostController::new(); @@ -1604,6 +2372,7 @@ mod tests { applied_revision: 0, instances: Vec::new(), leaving, + enforced_shards: None, }; controller.record_status(second, status(false)).unwrap(); assert!(!changes.has_changed().unwrap(), "an ordinary report"); @@ -1628,7 +2397,14 @@ mod tests { ); for index in 0..crate::pool_limits::MAX_POOL_INSTANCES_CEILING { let route = format!("rt-{index:029}"); - view.desired.insert(route.clone()); + view.desired.insert( + route.clone(), + DesiredInstance { + sandbox_id: route.clone(), + generation: "generation".to_string(), + node: None, + }, + ); view.owners.insert(route, owner("m-2", "p2", 1)); } controller.update_pool(view, tokio::time::Instant::now()); @@ -1950,7 +2726,7 @@ mod tests { // view must not release the new instance. let listed_before_launch = tokio::time::Instant::now(); controller.place_owner("rt-b", owner("m1", "p1", 1)); - controller.assign(assignment("rt-b", b"b")).unwrap(); + controller.assign(assignment("rt-b", b"b"), None).unwrap(); controller.update_pool(view(&["rt-a"], &["rt-a"]), listed_before_launch); assert_eq!(routes(&controller.snapshot(one).unwrap()), ["rt-a", "rt-b"]); controller.update_pool( @@ -2058,6 +2834,7 @@ mod tests { connection_epoch: 1, member: None, accepts_redirect: false, + enforcer: None, }, ) .unwrap_err(); diff --git a/crates/openshell-supervisor-control/src/coordinator.rs b/crates/openshell-supervisor-control/src/coordinator.rs index c17ab899a3..2ebc04590d 100644 --- a/crates/openshell-supervisor-control/src/coordinator.rs +++ b/crates/openshell-supervisor-control/src/coordinator.rs @@ -67,6 +67,11 @@ pub struct PlacementRequest { pub assignment: crate::proto::SandboxInstanceAssignment, /// Credential epoch of the launch credentials. pub auth_epoch: u64, + /// The only pool member that may supervise the instance, at launch and + /// on every takeover; `None` lets the pool choose. + pub member: Option, + /// The node the instance's workload runs on, when known. + pub node: Option, } impl std::fmt::Debug for PlacementRequest { @@ -77,6 +82,8 @@ impl std::fmt::Debug for PlacementRequest { .field("sandbox_id", &self.assignment.sandbox_id) .field("generation", &self.assignment.generation) .field("auth_epoch", &self.auth_epoch) + .field("member", &self.member) + .field("node", &self.node) .finish_non_exhaustive() } } @@ -92,9 +99,10 @@ pub type PlacementFuture = Pin /// driver's watch. pub trait InstancePlacement: Send + Sync + std::fmt::Debug { /// Durably record a new instance, launch material included, and the - /// owner of its launch term: the pool member the consistent-hash ring - /// prefers among live members with room, and its current process. Fails - /// when no live member has room. + /// owner of its launch term: the request's member, or else the pool + /// member the consistent-hash ring prefers among live members with room, + /// and its current process. Fails when that member, or every live + /// member, has no room. fn place_launch(&self, request: PlacementRequest) -> PlacementFuture; /// Routes of the durably recorded instances, with when each was @@ -103,10 +111,13 @@ pub trait InstancePlacement: Send + Sync + std::fmt::Debug { /// Durably record an instance a driver recovery found without a record, /// such as one launched before the host became a pool; the pool places - /// it, fencing whichever process may supervise it. + /// it, fencing whichever process may supervise it, on `member` only when + /// one is given, and records the `node` its workload runs on. fn record_recovered( &self, assignment: crate::proto::SandboxInstanceAssignment, + member: Option, + node: Option, ) -> PlacementFuture; } @@ -126,6 +137,10 @@ pub struct RecoveryBaseline { pub struct RecoverableInstance { pub route: String, pub sandbox_id: String, + /// The pool member the instance was launched on, when it is pinned. + pub member: Option, + /// The node its workload runs on, when recorded. + pub node: Option, pub record: R, } @@ -201,6 +216,13 @@ impl SharedSupervision { self.controller.credential() } + /// The current enforcer token and every renewal after it; never set + /// unless the deployment runs in native-network mode. + #[must_use] + pub fn enforcer_credentials(&self) -> watch::Receiver> { + self.controller.enforcer_credential() + } + /// Register a generation's sandbox instance: validate `registration`, /// persist its encoded launch material through `persist`, and only then /// assign the instance so the host starts it. The launch material is @@ -209,10 +231,15 @@ impl SharedSupervision { /// every gateway replica, on a live member with room; without one the /// launch fails as [`LaunchError::Unplaced`], and beyond the pool's /// capacity as [`LaunchError::Refused`], so the caller fails its create - /// before the workload runs. An identical assignment changes nothing. + /// before the workload runs. `member` pins the instance, as + /// [`PlacementRequest::member`] describes. `node` is the node the + /// workload runs on, which enforcers' shards select by. An identical + /// assignment changes nothing. pub async fn launch( &self, registration: &SandboxInstanceRegistration, + member: Option<&str>, + node: Option<&str>, persist: impl FnOnce(Vec) -> F + Send, ) -> Result<(), LaunchError> where @@ -236,6 +263,8 @@ impl SharedSupervision { .place_launch(PlacementRequest { assignment: assignment.clone(), auth_epoch: registration.auth.auth_epoch.get(), + member: member.map(str::to_string), + node: node.map(str::to_string), }) .await { @@ -248,7 +277,7 @@ impl SharedSupervision { return Err(LaunchError::Unplaced(error)); } let route = assignment.route.clone(); - self.controller.assign(assignment).map_err(|error| { + self.controller.assign(assignment, node).map_err(|error| { // A refused instance must not stay desired durably. self.controller.unassign(&route); LaunchError::Refused(error) @@ -338,7 +367,15 @@ impl SharedSupervision { } }; let recorded = match assignment { - Ok(assignment) => placement.record_recovered(assignment).await, + Ok(assignment) => { + placement + .record_recovered( + assignment, + candidate.member.clone(), + candidate.node.clone(), + ) + .await + } Err(error) => Err(error.to_string()), }; if let Err(error) = recorded { @@ -465,7 +502,12 @@ mod tests { Box::pin(async move { Ok(recorded) }) } - fn record_recovered(&self, assignment: SandboxInstanceAssignment) -> PlacementFuture { + fn record_recovered( + &self, + assignment: SandboxInstanceAssignment, + _member: Option, + _node: Option, + ) -> PlacementFuture { self.recovered.lock().unwrap().push(assignment.route); Box::pin(async { Ok(()) }) } @@ -475,6 +517,8 @@ mod tests { RecoverableInstance { route: route.to_string(), sandbox_id: sandbox_id.to_string(), + member: None, + node: None, record: if route.starts_with("rt-unreadable") { "unreadable" } else { diff --git a/crates/openshell-supervisor-control/src/lib.rs b/crates/openshell-supervisor-control/src/lib.rs index f7ddb4284d..caeb824650 100644 --- a/crates/openshell-supervisor-control/src/lib.rs +++ b/crates/openshell-supervisor-control/src/lib.rs @@ -41,9 +41,10 @@ pub mod proto { } pub use controller::{ - AssignmentError, ConnectedMember, HostIdentity, InstanceOwner, MemberReport, MemberView, - ObservedInstance, POOL_HEARTBEAT_INTERVAL, POOL_RECOVERY_TIMEOUT_RANGE, - POOL_RECOVERY_TIMEOUT_SECS, PoolView, SupervisorCredential, SupervisorHostController, + AssignmentError, ConnectedMember, DesiredInstance, HOST_IDENTITY_TOKEN_HEADER, HostAccount, + HostIdentity, HostRole, InstanceOwner, MemberReport, MemberView, ObservedInstance, + POOL_HEARTBEAT_INTERVAL, POOL_RECOVERY_TIMEOUT_RANGE, POOL_RECOVERY_TIMEOUT_SECS, PoolView, + SupervisorCredential, SupervisorHostController, }; pub use coordinator::{ InstancePlacement, InstanceSupervision, LaunchError, PlacementFuture, PlacementRequest, @@ -57,7 +58,8 @@ pub use pool_limits::{ MAX_POOL_INSTANCES_CEILING, PoolLimits, PoolLimitsError, }; pub use registration::{ - INSTANCE_REMOVAL_GRACE, MAX_LAUNCH_MATERIAL_BYTES, ProxyCaMaterial, RegistrationError, - RegistrationTraceContext, SandboxInstanceRegistration, SecretPem, + INSTANCE_REMOVAL_GRACE, MAX_LAUNCH_MATERIAL_BYTES, MAX_SHARED_TRUST_MATERIAL_BYTES, + ProxyCaMaterial, RegistrationError, RegistrationTraceContext, SandboxInstanceRegistration, + SecretPem, }; pub use status::{SandboxInstancePhaseReport, SandboxInstanceStatusReport}; diff --git a/crates/openshell-supervisor-control/src/registration.rs b/crates/openshell-supervisor-control/src/registration.rs index dfd80910c3..3d4eb65406 100644 --- a/crates/openshell-supervisor-control/src/registration.rs +++ b/crates/openshell-supervisor-control/src/registration.rs @@ -22,6 +22,10 @@ use crate::proto::SandboxInstanceAssignment; /// Largest launch material one assignment may carry. pub const MAX_LAUNCH_MATERIAL_BYTES: usize = 256 * 1024; +/// Largest total of the additional CA bundle and supervisor OTLP TLS files +/// that shared launch material carries, leaving the rest of +/// [`MAX_LAUNCH_MATERIAL_BYTES`] to the launch credentials. +pub const MAX_SHARED_TRUST_MATERIAL_BYTES: usize = 192 * 1024; /// Time a shared supervisor gives a withdrawn sandbox instance's workload to /// stop before cancelling the instance. pub const INSTANCE_REMOVAL_GRACE: Duration = Duration::from_secs(20); @@ -117,6 +121,11 @@ pub struct SandboxInstanceRegistration { #[serde(default)] pub container_image: String, pub proxy_ca: ProxyCaMaterial, + /// Operator destination CA bundle (PEM) the instance appends to its + /// sandbox trust bundle. Omitted when unset so supervisors that refuse it + /// still accept the material. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub additional_ca_bundle: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub trace_context: Option, } diff --git a/crates/openshell-supervisor-network/README.md b/crates/openshell-supervisor-network/README.md index c50383d556..c2c6e038ba 100644 --- a/crates/openshell-supervisor-network/README.md +++ b/crates/openshell-supervisor-network/README.md @@ -43,6 +43,10 @@ several instances serves `/v1/denials` from a per-instance `SandboxInstanceDenialLog` instead of the shared shorthand log files. +`SandboxInstanceNetwork.native_network` means an external enforcer filters the +workload's sockets. `run_networking` then starts neither mediated policy DNS +nor the egress proxy, but still writes the trust files. + ## Policy DNS expiry Synthetic identities remain allocated after their DNS mappings expire. New diff --git a/crates/openshell-supervisor-network/src/run.rs b/crates/openshell-supervisor-network/src/run.rs index b6b8b7cf59..92cf980378 100644 --- a/crates/openshell-supervisor-network/src/run.rs +++ b/crates/openshell-supervisor-network/src/run.rs @@ -212,6 +212,9 @@ pub struct SandboxInstanceNetwork { pub denial_log: DenialLogSource, /// Proxy interception CA and trust-file directory. pub proxy_tls: ProxyTlsFiles, + /// An external enforcer filters the workload's sockets, so the instance + /// mediates no DNS or connections. + pub native_network: bool, } /// Provisioned proxy CA files and the directory that receives trust files. @@ -316,6 +319,7 @@ pub async fn run_networking( provider_identity, denial_log, proxy_tls, + native_network, } = instance; // Choose how this instance obtains provider tokens once, for every grant. let token_grants: Arc = match (provider_identity, gateway.clone()) { @@ -553,9 +557,14 @@ pub async fn run_networking( (None, None) }; + let network_mediation_source = network_mediation_source.filter(|_| !native_network); + // Register NAT64 prefixes before any egress path starts, so SSRF checks - // classify translated addresses by their embedded IPv4 address. - configure_nat64(nat64_prefixes).await; + // classify translated addresses by their embedded IPv4 address. A + // native-network sandbox starts no egress path. + if !native_network { + configure_nat64(nat64_prefixes).await; + } // One decision for every policy DNS runtime this supervisor starts. let ipv6_egress = crate::policy_dns::Ipv6EgressDecision::resolve( @@ -586,7 +595,7 @@ pub async fn run_networking( None }; - let proxy_handle = if matches!(policy.network.mode, NetworkMode::Proxy) { + let proxy_handle = if !native_network && matches!(policy.network.mode, NetworkMode::Proxy) { let proxy_policy = policy.network.proxy.as_ref().ok_or_else(|| { miette::miette!("Network mode is set to proxy but no proxy configuration was provided") })?; @@ -828,3 +837,103 @@ async fn configure_nat64(configured: Vec) { }; crate::telemetry::egress_emit!(setup.event()); } + +#[cfg(test)] +#[expect( + clippy::used_underscore_binding, + reason = "production only holds the policy DNS handle to keep it running" +)] +mod native_network_tests { + use super::*; + use openshell_core::policy::{NetworkPolicy, ProxyPolicy}; + use openshell_isolation_interface::contract::{BackendError, PendingDnsQuery, PendingTcpOpen}; + use openshell_sandbox_backend::test_support as rpc_test; + use std::collections::HashMap; + + struct IdleSource; + + #[async_trait::async_trait] + impl rpc_test::NetworkMediationSource for IdleSource { + async fn accept_tcp(&self) -> std::result::Result { + std::future::pending().await + } + + async fn accept_dns(&self) -> std::result::Result { + std::future::pending().await + } + } + + async fn start(native_network: bool, tls_dir: &std::path::Path) -> Networking { + let mut policy = SandboxPolicy::try_from(ProtoSandboxPolicy::default()).unwrap(); + policy.network = NetworkPolicy { + mode: NetworkMode::Proxy, + proxy: Some(ProxyPolicy { + http_addr: Some("127.0.0.1:0".parse().unwrap()), + }), + }; + let engine = crate::policy_engine::PolicyEngine::from(Arc::new( + crate::opa::OpaEngine::from_strings( + include_str!("../data/sandbox-policy.rego"), + "network_policies: {}\n", + ) + .unwrap(), + )); + let (_, workspace_rx) = tokio::sync::watch::channel(String::new()); + run_networking( + &policy, + None, + Some(&engine), + None, + Arc::new(AtomicU32::new(0)), + false, + &ProviderCredentialState::from_environment( + 0, + HashMap::default(), + HashMap::default(), + HashMap::default(), + ), + SandboxInstanceNetwork { + proxy_tls: ProxyTlsFiles { + directory: Some(tls_dir.to_path_buf()), + ..Default::default() + }, + native_network, + ..Default::default() + }, + None, + None, + None, + AgentProposals::new(false), + workspace_rx, + &crate::upstream_proxy::UpstreamProxyArgs::default(), + None, + PolicyDnsIpv6Egress::default(), + Vec::new(), + None, + #[cfg(target_os = "linux")] + None, + Some(rpc_test::network(Arc::new(IdleSource))), + None, + None, + ) + .await + .unwrap() + } + + #[tokio::test] + async fn native_network_starts_no_proxy_or_policy_dns_but_writes_trust_files() { + let tls_dir = tempfile::tempdir().unwrap(); + let networking = start(true, tls_dir.path()).await; + assert!(networking.proxy.is_none()); + assert!(networking._mediated_policy_dns.is_none()); + assert!(networking.ca_file_paths.is_some()); + } + + #[tokio::test] + async fn mediated_network_starts_the_proxy_and_policy_dns() { + let tls_dir = tempfile::tempdir().unwrap(); + let networking = start(false, tls_dir.path()).await; + assert!(networking.proxy.is_some()); + assert!(networking._mediated_policy_dns.is_some()); + } +} diff --git a/crates/openshell-supervisor-process/src/debug_rpc.rs b/crates/openshell-supervisor-process/src/debug_rpc.rs index 1d648bf8d9..7b64989a9d 100644 --- a/crates/openshell-supervisor-process/src/debug_rpc.rs +++ b/crates/openshell-supervisor-process/src/debug_rpc.rs @@ -88,6 +88,7 @@ async fn run_get_sandbox_config( supported_capabilities, name: sandbox_name.to_string(), workspace_scope: None, + sandbox_id: String::new(), }) .await; match resp { diff --git a/crates/openshell-supervisor/Cargo.toml b/crates/openshell-supervisor/Cargo.toml index 488a9b4b46..d34fe45473 100644 --- a/crates/openshell-supervisor/Cargo.toml +++ b/crates/openshell-supervisor/Cargo.toml @@ -41,7 +41,7 @@ http-body-util = { workspace = true } hyper = { workspace = true } hyper-util = { workspace = true, features = ["tokio", "http1", "server", "server-graceful"] } miette = { workspace = true } -nix = { workspace = true } +nix = { workspace = true, features = ["net"] } opentelemetry = { workspace = true } opentelemetry-proto = { workspace = true } prost = { workspace = true } diff --git a/crates/openshell-supervisor/README.md b/crates/openshell-supervisor/README.md index a56b522951..9919956e91 100644 --- a/crates/openshell-supervisor/README.md +++ b/crates/openshell-supervisor/README.md @@ -10,6 +10,8 @@ Shared startup checks the admitted backend name before passing the opaque payloa The built-in decoder also carries the VM driver's fixed workload identity into shared policy validation. Startup and later policy updates must reject selectors that conflict with that identity. Other launch descriptors do not enable this VM-specific check. +Both built-in decoders, the dedicated one and the routed one for shared instances, read the `openshell.native_network` resource claim into `LaunchIdentity.native_network`. The claim means an external enforcer filters the workload's connections, so `SelectedBackend::native_network()` makes startup skip policy DNS, the egress proxy and the agent trace relay, with `AgentSpec::otlp_relay_active` false. + The supervisor admits policy and prepares credentials before constructing and attaching the selected client. It uses the concrete RPC client handles `BoundBoundary` and `ConfirmedBoundary` from `openshell-sandbox-backend`: confirm the attached boundary, prepare network mediation, then start the workload. Backends supply native enforcement evidence through the Sandbox Protocol; the client validates it before exposing the confirmed handle. The client receives the supervisor's live provider state, bearer-token slot, and CA-path slot. Provider refresh, token rotation, and later CA publication must remain visible through those shared handles. Startup does not create independent copies of their current values. @@ -192,9 +194,18 @@ control listener: it dials the gateway and receives its assignments from it. expired token as a reason to retry later, and the gateway ends a stream when the token that opened it expires, so the host reconnects with the renewed one. The host never acts with any other identity and has no - Kubernetes identity. The stream starts with a hello carrying a per-process - instance id and a connection epoch; the gateway supersedes an older stream - of the same process and refuses a delayed older connection. + Kubernetes API access. Beside the token, the host sends its Pod's projected + `ServiceAccount` token (audience `openshell-supervisor`) from + `--identity-token-file` (`OPENSHELL_SUPERVISOR_IDENTITY_TOKEN_FILE`) in the + `x-openshell-host-identity-token` header, re-read on every connection + attempt. The gateway verifies it, and refuses the supervisor token without + it under `require_identity_token` or the node topology. With + `--node-supervisor` (`OPENSHELL_SUPERVISOR_NODE`), the host serves only its + node's sandboxes, and the gateway requires its member ID to be the node its + identity token proves. The stream starts + with a hello carrying a per-process instance id and a connection epoch; the + gateway supersedes an older stream of the same process and refuses a delayed + older connection. - **Assignments.** The gateway owns the desired set and sends it as complete `AssignmentSnapshot`s with session-scoped revisions. `shared_host::SharedHost::reconcile` validates the snapshot as a whole (at most 256 instances, no route twice), @@ -238,7 +249,10 @@ control listener: it dials the gateway and receives its assignments from it. and relinquishes whatever it still hosts; their workloads keep running. - **Pool members.** `--pool-member-id` and `--pool-advertise-ip` (or `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` and `_ADVERTISE_IP`) are required with - `--mode=shared`: every shared supervisor is a member of the gateway's + `--mode=shared`. `--pool-advertise-interface` (`_ADVERTISE_INTERFACE`) + replaces the IP with the only non-link-local IPv4 address of the named + interface, resolved at startup, for a supervisor runtimes reach on an + additional Pod network. Every shared supervisor is a member of the gateway's high-availability pool, and its hello names the member and its runtime address. The member ID is an opaque, stable logical ID served by one process at a time; the hello's `instance_id` and `connection_epoch` identify diff --git a/crates/openshell-supervisor/src/app_listener.rs b/crates/openshell-supervisor/src/app_listener.rs index 455e0c810e..7098d727e8 100644 --- a/crates/openshell-supervisor/src/app_listener.rs +++ b/crates/openshell-supervisor/src/app_listener.rs @@ -1379,6 +1379,8 @@ mod tests { fn installed(routes: Vec) -> SettingsPollResult { SettingsPollResult { + activation_pending: false, + enforcer_provider_env_revision: 0, service_routes: routes, settings_revision: 1, configuration_instance_id: "runtime-a".into(), diff --git a/crates/openshell-supervisor/src/backend_setup.rs b/crates/openshell-supervisor/src/backend_setup.rs index eacec32962..e9cddbba42 100644 --- a/crates/openshell-supervisor/src/backend_setup.rs +++ b/crates/openshell-supervisor/src/backend_setup.rs @@ -28,6 +28,9 @@ pub struct LaunchIdentity { pub workload_identity: ResolvedWorkloadIdentity, /// Preserve driver-fixed VM selectors during shared startup and reload. pub vm_policy_identity: Option, + /// An external enforcer filters the workload's connections, so startup + /// skips policy DNS, the egress proxy and the agent trace relay. + pub native_network: bool, } /// Runtime state remains owned by the supervisor. @@ -156,13 +159,23 @@ impl SelectedBackend { self.identity.vm_policy_identity } + /// Whether the descriptor claims native-network mode. + pub const fn native_network(&self) -> bool { + self.identity.native_network + } + /// Delegate image discovery only after shared name and identity checks. /// Callers may retry this read; discovery cannot authorize workload launch. + /// Native-network mode never reads the image's policy, so a sandbox + /// without one gets the restrictive default. pub async fn discover_policy( &self, bearer: SessionBearerTokenSlot, attach_request_timeout: std::time::Duration, ) -> Result<(Option, bool)> { + if self.native_network() { + return Ok((None, false)); + } self.prepared .discover_policy(bearer, attach_request_timeout) .await @@ -237,6 +250,9 @@ impl BackendSetup for OpenShellBackendSetup { uid: descriptor.workload_identity.uid, gid: descriptor.workload_identity.gid, }), + native_network: openshell_sandbox_backend::native_network_claimed( + &descriptor.resource_claims, + ), }; let transport = openshell_sandbox_backend::BoundaryTransport::for_descriptor(&descriptor)?; Ok(( @@ -293,6 +309,9 @@ impl BackendSetup for RoutedBackendSetup { session_id: descriptor.session_id, workload_identity: descriptor.workload_identity.clone(), vm_policy_identity: None, + native_network: openshell_sandbox_backend::native_network_claimed( + &descriptor.resource_claims, + ), }; Ok(( identity, diff --git a/crates/openshell-supervisor/src/backend_setup/registration.rs b/crates/openshell-supervisor/src/backend_setup/registration.rs index 978ef65033..97049fbff6 100644 --- a/crates/openshell-supervisor/src/backend_setup/registration.rs +++ b/crates/openshell-supervisor/src/backend_setup/registration.rs @@ -78,6 +78,7 @@ impl BackendSetup for RegisteredBackendSetup { session_id: self.descriptor.session_id, workload_identity: self.descriptor.workload_identity.clone(), vm_policy_identity: None, + native_network: false, }, Box::new(RegisteredLaunch { name: self.name.clone(), diff --git a/crates/openshell-supervisor/src/backend_setup/tests.rs b/crates/openshell-supervisor/src/backend_setup/tests.rs index 0f5b2ec5e2..40914c080b 100644 --- a/crates/openshell-supervisor/src/backend_setup/tests.rs +++ b/crates/openshell-supervisor/src/backend_setup/tests.rs @@ -114,6 +114,7 @@ struct Observed { events: Mutex>, services: Mutex>, discovery_unavailable: AtomicBool, + native_network: AtomicBool, deny_confirmation: AtomicBool, require_networking: AtomicBool, active: AtomicBool, @@ -255,6 +256,7 @@ impl BackendSetup for TestSetup { session_id: self.auth.session_id, workload_identity: identity(), vm_policy_identity: None, + native_network: self.observed.native_network.load(Ordering::SeqCst), }, Box::new(TestLaunch { name: self.built_name, @@ -522,6 +524,22 @@ fn shared_identity_rejection_stops_before_discovery() { assert_eq!(setup.observed.starts.load(Ordering::SeqCst), 0); } +#[tokio::test] +async fn native_network_never_reads_the_image_policy() { + let setup = TestSetup::new(); + setup.observed.native_network.store(true, Ordering::SeqCst); + let discovered = setup + .select() + .discover_policy( + setup.auth.sandbox_bearer_slot().unwrap(), + std::time::Duration::from_secs(1), + ) + .await + .unwrap(); + assert_eq!(discovered, (None, false)); + assert_eq!(setup.observed.events(), vec!["decode"]); +} + #[tokio::test] async fn attachment_receives_live_supervisor_services() { let setup = TestSetup::new(); @@ -765,6 +783,85 @@ fn standard_setup_decodes_native_descriptor_and_preserves_vm_identity() { } } +/// Both descriptor decoders read the native-network claim. The routed one +/// serves shared instances, which the node topology uses. +#[tokio::test] +async fn both_decoders_read_the_native_network_claim() { + use openshell_sandbox_backend::boundary_protocol::{ + SandboxRuntimeDescriptor, SandboxTlsClientConfig, SandboxTransport, + generate_sandbox_tls_material, + }; + use openshell_sandbox_backend::runtime_routed::{RuntimeRouter, new_route_handle}; + + let setup = TestSetup::new(); + let tls = generate_sandbox_tls_material(setup.auth.session_id).unwrap(); + let router = RuntimeRouter::bind("127.0.0.1:0".parse().unwrap()).unwrap(); + let descriptor = |transport: SandboxTransport, claimed: bool| { + let mut resource_claims = BTreeMap::new(); + if claimed { + resource_claims.insert( + openshell_sandbox_backend::NATIVE_NETWORK_RESOURCE_CLAIM.into(), + "true".into(), + ); + } + SandboxRuntimeDescriptor { + boundary_id: setup.sandbox_id.clone(), + generation: setup.auth.runtime_generation.to_string(), + session_id: setup.auth.session_id, + workload_identity: ResolvedWorkloadIdentity::new( + 1000, + 1001, + vec![], + "test".into(), + "test-resource".into(), + ) + .unwrap(), + transport, + tls: SandboxTlsClientConfig { + server_name: tls.server_name.clone(), + trust_anchor_pem: tls.trust_anchor_pem.clone(), + }, + host_gateway_ip: None, + resource_claims, + provisioning_evidence: ProvisioningEvidence::from_enforcement_evidence( + "generation-1", + b"test-evidence", + ) + .unwrap(), + } + }; + for claimed in [false, true] { + let route = new_route_handle(); + let shared_instance = RoutedBackendSetup::new(router.clone(), route.clone()); + let cases: [(&dyn BackendSetup, SandboxTransport); 2] = [ + ( + &OpenShellBackendSetup, + SandboxTransport::Unix { + socket_path: "/unused-test-runtime".into(), + }, + ), + ( + &shared_instance, + SandboxTransport::RuntimeInitiatedRouted { + authority: router.local_addr().to_string(), + route, + }, + ), + ]; + for (backend_setup, transport) in cases { + let selected = SelectedBackend::select( + backend_setup, + descriptor(transport, claimed).backend_descriptor().unwrap(), + Some(openshell_sandbox_backend::BACKEND_NAME), + Some(&setup.sandbox_id), + &setup.auth, + ) + .unwrap(); + assert_eq!(selected.native_network(), claimed); + } + } +} + /// Auth slots and shutdown signals are process-wide. Run the real startup in a /// child so parallel tests cannot replace credentials or consume its SIGTERM. #[cfg(unix)] diff --git a/crates/openshell-supervisor/src/config_runtime.rs b/crates/openshell-supervisor/src/config_runtime.rs index 46c4f8751b..53832c66cd 100644 --- a/crates/openshell-supervisor/src/config_runtime.rs +++ b/crates/openshell-supervisor/src/config_runtime.rs @@ -274,10 +274,22 @@ impl ConfigRuntime { let config_changed = result.config_revision != self.config_revision; let desired_identity = EnvironmentIdentity::from_settings(result); + // Workload placeholders of a revision the enforcer hasn't accepted + // would fail at the enforcer, so the installed revision stays. + let awaiting_enforcer = ctx.native_network + && result.provider_env_revision != result.enforcer_provider_env_revision; + if awaiting_enforcer && result.provider_env_revision != self.provider_env_revision { + debug!( + revision = result.provider_env_revision, + accepted_revision = result.enforcer_provider_env_revision, + "Deferring the provider credential install until the network enforcer accepts it" + ); + } let provider_env_changed = match &provider { ProviderSource::Fetch => { - result.provider_env_revision != self.provider_env_revision - || ctx.provider_readiness.needs_environment(&desired_identity) + !awaiting_enforcer + && (result.provider_env_revision != self.provider_env_revision + || ctx.provider_readiness.needs_environment(&desired_identity)) } ProviderSource::Delivered(provider) => provider.is_some(), }; @@ -2706,6 +2718,65 @@ mod tests { let _ = task.await; } + #[tokio::test] + async fn native_network_installs_a_provider_revision_once_the_enforcer_accepts_it() { + let engine = Arc::new(OpaEngine::from_proto(&proto_policy_fixture()).unwrap()); + let initial = settings_poll_result( + Some(proto_policy_fixture()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ); + let mut ctx = policy_poll_test_context( + engine, + LoadedPolicyOrigin::Gateway { + revision: Some(LoadedPolicyRevision::from_snapshot(&initial)), + has_last_valid_policy: true, + }, + default_middleware_connector(), + ); + ctx.native_network = true; + let state = ctx.provider_credentials.clone(); + let (policy, polls, mut reports) = scripted_policy_gateway(); + let (requests, mut received) = tokio::sync::mpsc::unbounded_channel(); + polls.send(initial.clone()).unwrap(); + let task = tokio::spawn(run_policy_poll_loop_with_client( + ctx, + ScriptedProviderGateway { policy, requests }, + )); + expect_policy_report(&mut reports, 1).await; + + let mut rotated = initial.clone(); + rotated.provider_env_revision = 2; + polls.send(rotated.clone()).unwrap(); + assert!( + timeout(Duration::from_millis(200), received.recv()) + .await + .is_err(), + "a revision the enforcer hasn't accepted is not fetched" + ); + + rotated.enforcer_provider_env_revision = 2; + polls.send(rotated).unwrap(); + let (_, response) = timeout(Duration::from_secs(5), received.recv()) + .await + .expect("provider refresh requested") + .expect("poll loop active"); + assert!( + response + .send(Ok(static_provider_environment(2, Some("rotated")))) + .is_ok() + ); + timeout(Duration::from_secs(5), async { + while state.revision() != 2 { + tokio::task::yield_now().await; + } + }) + .await + .expect("the accepted revision installs"); + task.abort(); + let _ = task.await; + } + #[tokio::test] async fn provider_poll_preserves_stable_delivery_across_rotation_failure_and_detach() { let engine = Arc::new(OpaEngine::from_proto(&proto_policy_fixture()).unwrap()); @@ -2850,6 +2921,7 @@ mod tests { endpoint_status_rx: None, endpoint_policy: None, supervisor_session_id: tokio::sync::watch::channel(None).1, + native_network: false, } } diff --git a/crates/openshell-supervisor/src/endpoint_status.rs b/crates/openshell-supervisor/src/endpoint_status.rs index c3946312a8..35769ce8fd 100644 --- a/crates/openshell-supervisor/src/endpoint_status.rs +++ b/crates/openshell-supervisor/src/endpoint_status.rs @@ -15,7 +15,7 @@ use openshell_core::endpoint_status::{ }; use openshell_core::proto::SandboxPolicy; use tokio::time::timeout; -use tracing::warn; +use tracing::{debug, warn}; use crate::{PolicyGatewayClient, is_retryable_error}; @@ -33,6 +33,10 @@ pub async fn run_reporter( ) { const REPORT_TIMEOUT: Duration = Duration::from_secs(10); const OBSERVATION_COALESCE_WINDOW: Duration = Duration::from_millis(250); + // A newly loaded policy is rejected until the gateway makes it current, + // which in native-network mode waits for the enforcer to accept it too. + // Retries shorter than this are expected and log at debug level. + const PERSISTENT_FAILURE_AFTER: Duration = Duration::from_mins(1); let mut tracker = commands.tracker(); // Adopting the current value also acknowledges its watch notification. @@ -155,6 +159,7 @@ pub async fn run_reporter( dirty = false; let mut attempt = 1_u32; + let mut failing_since = None; 'retry: loop { let mut report = Box::pin(timeout( REPORT_TIMEOUT, @@ -207,18 +212,29 @@ pub async fn run_reporter( } }; - match result { + // The console format keeps only the message, so it carries the + // error and attempt as well as the structured fields. + let error = match result { Ok(Ok(())) => continue 'outbox, Ok(Err(error)) if !is_retryable_error(&error) => { - warn!(%error, "Discarding terminal endpoint status snapshot"); + warn!(%error, "Discarding terminal endpoint status snapshot: {error}"); continue 'outbox; } - Ok(Err(error)) => { - warn!(%error, attempt, "Endpoint status report failed transiently; retaining immutable snapshot"); - } - Err(error) => { - warn!(%error, attempt, "Endpoint status report timed out; retaining immutable snapshot"); - } + Ok(Err(error)) => error.to_string(), + Err(error) => format!("no response within {}s ({error})", REPORT_TIMEOUT.as_secs()), + }; + let failing_for = failing_since + .get_or_insert_with(tokio::time::Instant::now) + .elapsed(); + if failing_for < PERSISTENT_FAILURE_AFTER { + debug!(%error, attempt, "Endpoint status report failed (attempt {attempt}): {error}; retrying"); + } else { + warn!( + %error, + attempt, + "Endpoint status report still failing after {}s (attempt {attempt}): {error}; retaining immutable snapshot", + failing_for.as_secs() + ); } let retry_at = tokio::time::Instant::now() @@ -853,6 +869,127 @@ mod tests { reporter.abort(); } + const PENDING_CONFIGURATION: &str = + "tool server endpoint status revisions do not match the current sandbox configuration"; + + #[derive(Clone)] + struct RejectingEndpointStatusGateway; + + impl PolicyGatewayClient for RejectingEndpointStatusGateway { + async fn poll_settings( + &self, + _sandbox_id: &str, + ) -> Result { + Err(miette::miette!( + "endpoint-status test does not poll settings" + )) + } + + async fn report_policy_status( + &self, + _sandbox_id: &str, + _version: u32, + _loaded: bool, + _error: &str, + ) -> Result<()> { + Ok(()) + } + + async fn report_endpoint_status( + &self, + _sandbox_id: &str, + _snapshot: &EndpointStatusSnapshot, + ) -> Result<()> { + Err(miette::miette!("{PENDING_CONFIGURATION}")) + } + + fn workspace(&self) -> String { + String::new() + } + } + + #[derive(Clone, Default)] + struct Captured(Arc>>); + + impl Captured { + fn text(&self) -> String { + String::from_utf8(self.0.lock().unwrap().clone()).unwrap() + } + } + + impl std::io::Write for Captured { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(bytes); + Ok(bytes.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + + /// A report waiting for the gateway to make its policy current must not + /// warn, and a persistent failure must name its cause in the shorthand + /// console output, which keeps only an event's message. + #[tokio::test(start_paused = true)] + async fn reporter_warns_only_on_persistent_failure_and_names_the_cause() { + use tracing_subscriber::layer::SubscriberExt as _; + let captured = Captured::default(); + // Keep two dispatchers alive so tracing consults registered subscribers + // when caching callsite interest. With only one, a parallel test thread + // without a default subscriber can cache `Interest::never` for our events. + let _other_dispatch = tracing::Dispatch::new(tracing::subscriber::NoSubscriber::default()); + let _logging = + tracing::subscriber::set_default(tracing_subscriber::registry().with( + openshell_ocsf::OcsfShorthandLayer::new(captured.clone()).with_non_ocsf(true), + )); + let (sender, receiver) = endpoint_status_channel(); + let (_session_tx, session_rx) = + tokio::sync::watch::channel(Some("session-test".to_string())); + let reporter = tokio::spawn(run_reporter( + RejectingEndpointStatusGateway, + "sandbox-test".to_string(), + receiver, + session_rx, + )); + sender + .reset( + EndpointConfigVersion { + policy_hash: "policy-a".to_string(), + provider_env_revision: 1, + }, + vec![EndpointInventoryEntry { + endpoint_id: "endpoint:public".to_string(), + uses_provider_credentials: false, + }], + ) + .await + .expect("reporter remains active"); + + // Attempts at 0, 1, 3, 7, 15 and 31 seconds. + tokio::time::sleep(Duration::from_secs(40)).await; + let early = captured.text(); + assert!( + early.contains(&format!("(attempt 6): {PENDING_CONFIGURATION}")), + "retries log their cause: {early}" + ); + assert!( + !early.contains("WARN"), + "early retries must not warn: {early}" + ); + + // The attempt at 63 seconds has been failing for over a minute. + tokio::time::sleep(Duration::from_secs(30)).await; + let persistent = captured.text(); + assert!( + persistent.lines().any(|line| line.contains("WARN") + && line.contains("still failing after 63s (attempt 7)") + && line.contains(PENDING_CONFIGURATION)), + "a persistent failure warns with its cause: {persistent}" + ); + reporter.abort(); + } + struct ControlledEndpointStatusAttempt { snapshot: EndpointStatusSnapshot, complete: tokio::sync::oneshot::Sender>, diff --git a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs index b3c56facda..a1b7cc0a51 100644 --- a/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs +++ b/crates/openshell-supervisor/src/legacy_startup_regression_tests.rs @@ -222,6 +222,7 @@ impl BackendSetup for HeldBackendSetup { "test-image".into(), )?, vm_policy_identity: None, + native_network: false, }, Box::new(HeldPreparedBackend(self.probe.clone())), )) diff --git a/crates/openshell-supervisor/src/lib.rs b/crates/openshell-supervisor/src/lib.rs index 6278307846..159f6eee08 100644 --- a/crates/openshell-supervisor/src/lib.rs +++ b/crates/openshell-supervisor/src/lib.rs @@ -1032,8 +1032,8 @@ pub struct SandboxInstanceControls { /// Completes when the owner asks the instance to stop its workload. It is /// first polled once the workload has started. pub shutdown: Pin + Send>>, - /// True when `shutdown` also ends this process, so its boundary may be - /// stopping too and a lost connection is not worth recovering. + /// True when `shutdown` also ends this process, so the whole stop must + /// finish within the process shutdown deadline. pub shutdown_ends_process: bool, /// Requests to suspend only this instance. A failed suspension can be /// retried by sending another request. Closing the stream disables it. @@ -1237,6 +1237,19 @@ pub async fn run_sandbox_instance( }; let vm_policy_identity = selected_backend.vm_policy_identity(); + let native_network = selected_backend.native_network(); + if native_network { + ocsf_emit!( + ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .state(StateId::Enabled, "native_network") + .message( + "Native-network mode; an external enforcer mediates workload network traffic", + ) + .build() + ); + } // Load policy and initialize OPA engine let sandbox_name_for_agg = sandbox.clone(); @@ -1358,14 +1371,19 @@ pub async fn run_sandbox_instance( // The agent trace relay must exist before networking starts so the // handler is installed when the first staged connection arrives, and // before attach so the agent spec can tell the boundary whether to point - // workload SDKs at it. - let (mut otlp_relay, otlp_reserved_destination) = otlp_relay::activate( - otlp_agent_endpoint, - otlp_agent_protocol, - auth_bundle.agent_otlp().headers.cloned(), - auth_bundle.agent_otlp().tls.cloned(), - sandbox_id.clone(), - ); + // workload SDKs at it. No proxy runs in native-network mode, so a + // relay address would only time out. + let (mut otlp_relay, otlp_reserved_destination) = if native_network { + (None, None) + } else { + otlp_relay::activate( + otlp_agent_endpoint, + otlp_agent_protocol, + auth_bundle.agent_otlp().headers.cloned(), + auth_bundle.agent_otlp().tls.cloned(), + sandbox_id.clone(), + ) + }; // Construct the selected client only after shared policy and credential // setup has completed. Keep live credentials and later CA publication in @@ -1500,6 +1518,7 @@ pub async fn run_sandbox_instance( provider_identity, denial_log, proxy_tls, + native_network, }, denial_tx, activity_tx, @@ -1721,6 +1740,7 @@ pub async fn run_sandbox_instance( endpoint_status_rx, endpoint_policy: poll_endpoint_policy, supervisor_session_id: supervisor_session_id.clone(), + native_network, }; tokio::spawn(async move { @@ -1846,9 +1866,11 @@ pub async fn run_sandbox_instance( )); } () = &mut shutdown_requested => { + // A workload that is already gone must not hold the stop + // until a reconnect to it times out. + running.begin_stop(); if shutdown_ends_process { shutdown_deadline = Some(tokio::time::Instant::now() + SHUTDOWN_TIMEOUT); - running.begin_stop(); } let wait = async { let _ = agent @@ -3055,6 +3077,7 @@ async fn load_policy_with_gateway( let discovery = image_discovery.unwrap_or_else(discover_image_policy); let mut reconciliation_attempts = 0u32; let mut rejection_log = StartupRejectionLog::default(); + let mut activation_hold_logged = false; loop { if reconciliation_attempts == 5 { return Err(miette::miette!( @@ -3210,6 +3233,28 @@ async fn load_policy_with_gateway( snapshot = canonical; } + // A held activation is an ordinary wait: no rejection report, and + // it doesn't count toward the attempt limit. + if snapshot.activation_pending { + if !activation_hold_logged { + ocsf_emit!( + ConfigStateChangeBuilder::new(ocsf_ctx()) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .state(StateId::Other, "activation_pending") + .message(format!( + "Gateway is holding workload activation; waiting [reason:{}]", + snapshot.configuration_error + )) + .build() + ); + activation_hold_logged = true; + } + reconciliation_attempts = 0; + tokio::time::sleep(Duration::from_secs(2)).await; + continue; + } + let loaded_policy_revision = Some({ let mut revision = LoadedPolicyRevision::from_snapshot(&snapshot); revision.admission_instance_id = Some(instance_id.clone()); @@ -4430,6 +4475,9 @@ struct PolicyPollLoopContext { endpoint_policy: Option, /// Session accepted by `ConnectSupervisor`; `None` suspends endpoint reports. supervisor_session_id: tokio::sync::watch::Receiver>, + /// A native-network enforcer substitutes credentials, so a provider + /// revision installs only once the enforcer accepted it. + native_network: bool, } type MiddlewareConnector = Arc< @@ -5381,6 +5429,8 @@ network_policies: source: openshell_core::proto::PolicySource, ) -> openshell_core::grpc_client::SettingsPollResult { openshell_core::grpc_client::SettingsPollResult { + activation_pending: false, + enforcer_provider_env_revision: 0, service_routes: Vec::new(), policy, version, @@ -5578,6 +5628,68 @@ network_policies: .expect("matching repair should permit startup"); } + #[tokio::test(start_paused = true)] + async fn startup_waits_without_reporting_while_activation_is_held() { + use openshell_core::proto::{ConfigurationAdmissionState, PolicySource}; + let mut held = settings_poll_result(Some(proto_policy_fixture()), 1, PolicySource::Sandbox); + held.configuration_admitted = false; + held.activation_pending = true; + let (reports, mut reported) = tokio::sync::mpsc::unbounded_channel(); + let gateway = TestStartupGateway { + desired: Arc::new(std::sync::Mutex::new(held)), + reports, + reject_next_accept: Arc::new(AtomicBool::new(false)), + snapshot_error: None, + report_error: None, + pending_snapshot: false, + pending_acceptance: false, + }; + let active_gateway = gateway.clone(); + let handle = tokio::spawn(async move { + load_policy_with_gateway( + Some("sandbox-id".into()), + Some("sandbox".into()), + Some(test_gateway()), + None, + None, + &openshell_extension_core::ExtensionCredentialStore::new(), + LocalPolicyIdentity::Required, + None, + Some(ImagePolicyDiscovery::Missing), + &active_gateway, + ) + .await + }); + assert_eq!( + reported.recv().await, + Some(ConfigurationAdmissionState::Pending) + ); + // Far more passes than the five-attempt limit, with no report. + tokio::time::sleep(Duration::from_mins(1)).await; + assert!( + reported.try_recv().is_err(), + "a held activation reports nothing" + ); + assert!( + !handle.is_finished(), + "a held activation never activates or fails" + ); + + { + let mut desired = gateway.desired.lock().unwrap(); + desired.activation_pending = false; + desired.configuration_admitted = true; + } + assert_eq!( + reported.recv().await, + Some(ConfigurationAdmissionState::Accepted) + ); + handle + .await + .unwrap() + .expect("an admitted configuration permits startup"); + } + #[test] fn vm_startup_identity_validates_selectors_independently() { let identity = VmPolicyIdentity { diff --git a/crates/openshell-supervisor/src/main.rs b/crates/openshell-supervisor/src/main.rs index b455799f1e..795a6dea92 100644 --- a/crates/openshell-supervisor/src/main.rs +++ b/crates/openshell-supervisor/src/main.rs @@ -108,6 +108,22 @@ struct Args { #[arg(long, required_if_eq("mode", "shared"))] token_file: Option, + /// File holding this Pod's projected `ServiceAccount` token, audience + /// `openshell-supervisor`, sent beside the supervisor token. Re-read on + /// every connection attempt. + #[arg( + long, + env = "OPENSHELL_SUPERVISOR_IDENTITY_TOKEN_FILE", + required_if_eq("mode", "shared") + )] + identity_token_file: Option, + + /// Serve only this node's sandboxes, as one supervisor per node: the + /// pool member ID must be the node name, and the supervisor doesn't leave + /// the pool on shutdown, since no other member may take its instances. + #[arg(long, env = "OPENSHELL_SUPERVISOR_NODE")] + node_supervisor: bool, + /// Listener for routed runtime-initiated Sandbox Protocol connections. #[arg(long, required_if_eq("mode", "shared"))] runtime_listen: Option, @@ -141,6 +157,16 @@ struct Args { )] pool_max_instances: u32, + /// Network interface whose only IPv4 address is advertised in place of + /// `--pool-advertise-ip`, for a supervisor that sandbox runtimes reach on + /// an additional Pod network. + #[arg( + long, + env = "OPENSHELL_SUPERVISOR_POOL_ADVERTISE_INTERFACE", + conflicts_with = "pool_advertise_ip" + )] + pool_advertise_interface: Option, + /// Supervisor responsibility to run. #[arg(long, value_enum, default_value_t)] role: SupervisorRole, @@ -533,6 +559,8 @@ fn main() -> Result<()> { if args.gateway_endpoint.is_some() || args.address.is_some() || args.token_file.is_some() + || args.identity_token_file.is_some() + || args.node_supervisor || args.runtime_listen.is_some() || args.session_root.is_some() { diff --git a/crates/openshell-supervisor/src/shared.rs b/crates/openshell-supervisor/src/shared.rs index a1403bb5bb..ee5ef49485 100644 --- a/crates/openshell-supervisor/src/shared.rs +++ b/crates/openshell-supervisor/src/shared.rs @@ -33,6 +33,10 @@ fn run_platform(args: crate::Args) -> Result<()> { let token_file = args .token_file .ok_or_else(|| miette::miette!("--token-file is required for --mode=shared"))?; + let identity_token_file = args + .identity_token_file + .ok_or_else(|| miette::miette!("--identity-token-file is required for --mode=shared"))?; + let node_supervisor = args.node_supervisor; let runtime_listen = args .runtime_listen .ok_or_else(|| miette::miette!("--runtime-listen is required for --mode=shared"))?; @@ -40,6 +44,11 @@ fn run_platform(args: crate::Args) -> Result<()> { let instance_root = args .session_root .ok_or_else(|| miette::miette!("--session-root is required for --mode=shared"))?; + let advertise_ip = match (args.pool_advertise_ip, &args.pool_advertise_interface) { + (Some(ip), _) => Some(ip), + (None, Some(interface)) => Some(std::net::IpAddr::V4(interface_ipv4(interface)?)), + (None, None) => None, + }; // Every shared supervisor is a member of the gateway's supervisor pool. let missing = [ ( @@ -47,15 +56,16 @@ fn run_platform(args: crate::Args) -> Result<()> { "--pool-member-id (OPENSHELL_SUPERVISOR_POOL_MEMBER_ID, a stable member ID)", ), ( - args.pool_advertise_ip.is_none(), + advertise_ip.is_none(), "--pool-advertise-ip (OPENSHELL_SUPERVISOR_POOL_ADVERTISE_IP, an IP reachable \ -from sandbox runtimes)", +from sandbox runtimes) or --pool-advertise-interface \ +(OPENSHELL_SUPERVISOR_POOL_ADVERTISE_INTERFACE)", ), ] .into_iter() .filter_map(|(missing, setting)| missing.then_some(setting)) .collect::>(); - let (Some(name), Some(advertise_ip)) = (args.pool_member_id, args.pool_advertise_ip) else { + let (Some(name), Some(advertise_ip)) = (args.pool_member_id, advertise_ip) else { return Err(miette::miette!( "--mode=shared runs a supervisor pool member and needs {}", missing.join(", ") @@ -124,6 +134,7 @@ from sandbox runtimes)", endpoint: gateway_endpoint.clone(), token_file, limits, + identity_token_file, }; let host = openshell_supervisor::shared_host::SharedHost::start( openshell_supervisor::shared_host::SharedHostConfig { @@ -166,8 +177,11 @@ from sandbox runtimes)", _ = interrupt.recv() => {} } // A pool member hands its instances to other members while it still - // hears from the gateway. - host.leave(POOL_LEAVE_TIMEOUT).await; + // hears from the gateway. A node supervisor's instances are pinned to + // its node, so leaving would only wait for moves that never happen. + if !node_supervisor { + host.leave(POOL_LEAVE_TIMEOUT).await; + } stop.send_replace(true); let _ = probes.await; let _ = attachment.await; @@ -195,7 +209,70 @@ async fn serve_health(listener: tokio::net::TcpListener, shutdown: impl Future Result { + let addresses = nix::ifaddrs::getifaddrs() + .map_err(|error| miette::miette!("listing network interfaces failed: {error}"))? + .filter(|entry| entry.interface_name == interface) + .filter_map(|entry| { + entry + .address? + .as_sockaddr_in() + .map(nix::sys::socket::SockaddrIn::ip) + }); + only_ipv4(interface, addresses) +} + +#[cfg(unix)] +fn only_ipv4( + interface: &str, + addresses: impl Iterator, +) -> Result { + let mut addresses = addresses.filter(|address| !address.is_link_local()); + match (addresses.next(), addresses.next()) { + (Some(address), None) => Ok(address), + (None, _) => Err(miette::miette!( + "--pool-advertise-interface {interface} has no IPv4 address" + )), + (Some(_), Some(_)) => Err(miette::miette!( + "--pool-advertise-interface {interface} has more than one IPv4 address" + )), + } +} + #[cfg(not(unix))] fn run_platform(_args: crate::Args) -> Result<()> { Err(miette::miette!("--mode=shared requires Unix")) } + +#[cfg(all(test, unix))] +mod tests { + use super::*; + use std::net::Ipv4Addr; + + #[test] + fn advertise_interface_needs_exactly_one_routable_ipv4_address() { + let vf = Ipv4Addr::new(192, 168, 100, 2); + let link_local = Ipv4Addr::new(169, 254, 1, 1); + assert_eq!(only_ipv4("net1", [link_local, vf].into_iter()).unwrap(), vf); + let none = only_ipv4("net1", [link_local].into_iter()).unwrap_err(); + assert!(none.to_string().contains("no IPv4 address"), "{none}"); + let two = only_ipv4("net1", [vf, Ipv4Addr::new(10, 0, 0, 2)].into_iter()).unwrap_err(); + assert!(two.to_string().contains("more than one"), "{two}"); + } + + #[test] + fn loopback_resolves_to_its_address() { + assert_eq!( + interface_ipv4(if cfg!(target_os = "linux") { + "lo" + } else { + "lo0" + }) + .unwrap(), + Ipv4Addr::LOCALHOST + ); + assert!(interface_ipv4("openshell-missing0").is_err()); + } +} diff --git a/crates/openshell-supervisor/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index 32108cdce4..58c588b8fe 100644 --- a/crates/openshell-supervisor/src/shared_host.rs +++ b/crates/openshell-supervisor/src/shared_host.rs @@ -868,6 +868,9 @@ impl SharedHost { .as_bytes(), ) .map_err(failure)?; + let additional_ca_bundle = + write_additional_ca_bundle(dir, registration.additional_ca_bundle.as_deref()) + .map_err(failure)?; let trust_dir = dir.join("trust"); crate::sandbox_instance_host::prepare_private_dir(&trust_dir).map_err(failure)?; let ssh_socket = dir.join("ssh.sock"); @@ -892,11 +895,10 @@ impl SharedHost { ssh_socket_path: Some(ssh_socket.to_string_lossy().into_owned()), shared_ssh_socket: false, // The Kubernetes driver refuses the gateway topology when an - // upstream proxy is configured, - // and it configures no extra CA for dedicated supervisors. + // upstream proxy is configured. upstream_proxy_args: openshell_supervisor_network::upstream_proxy::UpstreamProxyArgs::default(), - additional_ca_bundle: None, + additional_ca_bundle, policy_dns_ipv6_egress: self.policy_dns_ipv6_egress, nat64_prefixes: self.nat64_prefixes.clone(), backend_descriptor: descriptor, @@ -1030,6 +1032,17 @@ fn write_private_file(_path: &Path, _contents: &[u8]) -> Result<()> { Err(miette::miette!("shared supervision requires a Unix host")) } +/// Write the instance's additional CA bundle into `dir`, returning the path +/// the network supervisor reads it from. +fn write_additional_ca_bundle(dir: &Path, pem: Option<&str>) -> Result> { + let Some(pem) = pem else { + return Ok(None); + }; + let path = dir.join("additional-ca.pem"); + write_private_file(&path, pem.as_bytes())?; + Ok(Some(path.to_string_lossy().into_owned())) +} + /// How the host reaches the gateway's supervisor host service. pub struct GatewayLink { /// Gateway gRPC endpoint; must be `https`, since the supervisor token is @@ -1042,9 +1055,29 @@ pub struct GatewayLink { pub token_file: PathBuf, /// Sizes the stream's message bounds; the host's limits. pub limits: PoolLimits, + /// File holding this Pod's projected `ServiceAccount` token, which proves + /// to the gateway that the supervisor token's holder is a supervisor Pod. + /// Re-read on every connection attempt, as the kubelet rotates it. + pub identity_token_file: PathBuf, } impl GatewayLink { + fn read_identity_token(&self) -> Result { + use miette::{IntoDiagnostic as _, WrapErr as _}; + + let path = &self.identity_token_file; + let contents = std::fs::read_to_string(path) + .into_diagnostic() + .wrap_err_with(|| format!("read identity token {}", path.display()))?; + let token = contents.trim(); + if token.is_empty() { + return Err(miette::miette!("the identity token file is empty")); + } + token + .parse() + .map_err(|_| miette::miette!("the identity token is not a valid header value")) + } + /// Read the current supervisor token. A missing, empty, malformed, or /// already expired token is an error; the gateway keeps the file fresh, /// so the caller retries later. @@ -1085,6 +1118,7 @@ fn status_message(host: &SharedHost, applied_revision: u64) -> HostMessage { .iter() .map(SandboxInstanceStatusReport::to_proto) .collect(), + enforced_shards: None, })), } } @@ -1144,6 +1178,9 @@ impl GatewayConnector for GatewayLink { let token = self .read_token() .map_err(|error| format!("no usable supervisor token: {error}"))?; + let identity_token = self + .read_identity_token() + .map_err(|error| format!("no usable identity token: {error}"))?; let connect = openshell_core::grpc_client::connect_gateway_channel(endpoint); let channel = tokio::time::timeout_at(deadline, connect) .await @@ -1152,7 +1189,13 @@ impl GatewayConnector for GatewayLink { let mut client = SupervisorHostClient::with_interceptor(channel, token.interceptor()) .max_decoding_message_size(self.limits.max_gateway_message_bytes()) .max_encoding_message_size(self.limits.max_host_message_bytes()); - let attach = client.attach(tokio_stream::wrappers::ReceiverStream::new(outbound)); + let mut request = + tonic::Request::new(tokio_stream::wrappers::ReceiverStream::new(outbound)); + request.metadata_mut().insert( + openshell_supervisor_control::HOST_IDENTITY_TOKEN_HEADER, + identity_token, + ); + let attach = client.attach(request); let response = tokio::time::timeout_at(deadline, attach) .await .map_err(|_| { @@ -1216,6 +1259,7 @@ async fn attach_with( } else { hops < REDIRECT_HOPS }, + enforcer: None, }; let accepts_redirect = hello.accepts_redirect; let attempt_timeout = timings.attempt_timeout(unanswered); @@ -1548,7 +1592,7 @@ async fn run_stream( let mut inbound = match opened { Ok(inbound) => inbound, Err(error) => { - tracing::warn!(%error, "could not open the supervisor host stream"); + tracing::warn!("could not open the supervisor host stream: {error}"); return lost(false); } }; @@ -1577,7 +1621,7 @@ async fn run_stream( let payload = match message { Some(Ok(message)) => message.payload, Some(Err(status)) => { - tracing::warn!(%status, "gateway assignment stream failed"); + tracing::warn!("gateway assignment stream failed: {status}"); break lost(accepted); } None => break lost(accepted), @@ -1748,6 +1792,26 @@ mod tests { } } + #[cfg(unix)] + #[test] + fn additional_ca_bundle_is_written_privately_only_when_present() { + use std::os::unix::fs::PermissionsExt as _; + + let dir = tempfile::tempdir().unwrap(); + assert_eq!(write_additional_ca_bundle(dir.path(), None).unwrap(), None); + assert!(!dir.path().join("additional-ca.pem").exists()); + + let pem = "-----BEGIN CERTIFICATE-----\nfixture\n-----END CERTIFICATE-----\n"; + let path = write_additional_ca_bundle(dir.path(), Some(pem)) + .unwrap() + .expect("a bundle yields a path"); + assert_eq!(std::fs::read_to_string(&path).unwrap(), pem); + assert_eq!( + std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, + 0o600 + ); + } + /// A hosted instance whose stop path reports on `stopped`. fn admit_supervising(host: &SharedHost, route: &str, stopped: tokio::sync::mpsc::Sender<()>) { let bindings = crate::SandboxInstanceBindings { diff --git a/crates/openshell-tui/src/lib.rs b/crates/openshell-tui/src/lib.rs index c6464157a9..5b13e89555 100644 --- a/crates/openshell-tui/src/lib.rs +++ b/crates/openshell-tui/src/lib.rs @@ -2645,7 +2645,10 @@ fn sandbox_notes_for_view( status.conditions.iter().find(|condition| { matches!(condition.r#type.as_str(), "ConfigurationReady" | "Ready") && condition.status == "False" - && condition.reason == "ConfigurationInvalid" + && matches!( + condition.reason.as_str(), + "ConfigurationInvalid" | "EnforcerRejected" + ) }) }); let Some(rejection) = rejection else { diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index ad4dd9ce37..b42c451aaa 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -296,6 +296,9 @@ driver creates a separate managed ConfigMap in each target sandbox namespace and mounts it only in the dedicated supervisor Pod at `/etc/openshell/tls/additional/ca-bundle.pem`. That supervisor receives the path through `--additional-ca-bundle` and folds the bundle into system roots. +With the shared supervisor topology, the driver creates no ConfigMap; each +sandbox generation's launch material carries the bundle to the shared +supervisor. The configured roots augment default destination trust. They do not configure the corporate proxy, OIDC, or gateway callback mTLS trust. @@ -522,6 +525,10 @@ explicitly. Existing sandboxes stay on their owners when scaling up, and memory-based scaling does not guarantee spare capacity for handoff. See the [shared supervisor autoscaling guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#autoscale-shared-supervisors-by-memory). +Set `supervisor_topology: node` in `gatewayConfig.openshell.drivers.kubernetes` +to run one shared supervisor per node as a DaemonSet. See the +[per-node supervisor guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#run-one-supervisor-per-node). + ## Secure metrics scraping Metrics are enabled by default on `service.metricsPort: 9090`. Set @@ -652,6 +659,14 @@ for peer identity policies, multi-node registrations, and authorization. | certManager.serverIpAddresses | list | `["127.0.0.1"]` | IP SANs on the cert-manager-issued server certificate. | | certManager.serverIssuerRef | object | `{"group":"","kind":"","name":""}` | Override the issuerRef for the external server Certificate (e.g. a real LetsEncrypt/ACME ClusterIssuer for a publicly-trusted cert on an external hostname). When set, the chart creates a second server certificate from this issuer with only the hostnames in serverDnsNames; the internal server certificate is always signed by the chart's own CA. Leave name empty to use the chart CA for all server certificates (default). Requires certManager.enabled=true. | | credentialDrivers.vault.caConfigMapName | string | `""` | ConfigMap containing the private Vault/OpenBao CA certificate under the ca.crt key. Helm mounts it only when the Vault driver is selected. | +| externalEnforcer.enabled | bool | `false` | Run new sandboxes in native-network mode under an external enforcer. | +| externalEnforcer.namespace | string | `""` | Existing namespace the external enforcer runs in, distinct from the release namespace. The chart creates the external enforcer's token Secret and the gateway's Role there. | +| externalEnforcer.network.sandbox.nameservers | list | `[]` | The sandboxes' only DNS servers, answered by the external enforcer. | +| externalEnforcer.network.sandbox.networkAttachment | string | `""` | Multus NetworkAttachmentDefinition, as namespace/name or a name in the sandbox namespace. | +| externalEnforcer.network.sandbox.resource | string | `""` | Extended resource the attachment's device plugin allocates, requested once per sandbox Pod. Empty requests none. | +| externalEnforcer.network.supervisor.networkAttachment | string | `""` | Multus NetworkAttachmentDefinition, as namespace/name or a name in the release namespace, attached to each supervisor as net1. Empty keeps runtimes on the supervisor Service ClusterIP. | +| externalEnforcer.network.supervisor.resource | string | `""` | Extended resource the attachment's device plugin allocates, requested once per supervisor Pod. Empty requests none. | +| externalEnforcer.serviceAccountName | string | `""` | ServiceAccount in `namespace` the external enforcer's Pods run as. The gateway accepts the external enforcer token only beside a pod-bound token for it (audience `openshell-enforcer`). | | fullnameOverride | string | `""` | Override the full generated resource name. | | gateway.image.digest | string | `""` | Gateway image digest. When set, this takes precedence over tag. | | gateway.image.pullPolicy | string | `nil` | Gateway image pull policy. Empty uses global.image.pullPolicy. | @@ -830,7 +845,7 @@ for peer identity policies, multi-node registrations, and authorization. | serviceAccount.create | bool | `true` | Create a service account for the gateway. | | serviceAccount.name | string | `""` | Existing service account name to use when serviceAccount.create is false. | | storageClass.preflight.enabled | bool | `false` | On a fresh StatefulSet install with no server.dataStorageClass, check for a default StorageClass. The Helm identity must be allowed to list StorageClasses. | -| supervisor.affinity | object | `{}` | Affinity rules for the shared supervisor pod, rendered only when gatewayConfig selects supervisor_topology = "gateway". Top-level affinity applies only to the gateway pod. | +| supervisor.affinity | object | `{}` | Affinity rules for the shared supervisor pod, rendered only when gatewayConfig selects supervisor_topology = "gateway" or "node". Top-level affinity applies only to the gateway pod. | | supervisor.autoscaling.behavior | object | `{"scaleDown":{"policies":[{"periodSeconds":120,"type":"Pods","value":1}],"stabilizationWindowSeconds":300}}` | HPA scaling behavior. Remove at most one member every two minutes, after a five-minute stabilization window, to allow ownership handoff. | | supervisor.autoscaling.enabled | bool | `false` | Enable memory-based autoscaling of the shared supervisor Deployment. Requires supervisor_topology = "gateway" and the Kubernetes resource metrics API (usually Metrics Server). When enabled, the HPA owns the replica count and supervisor.replicas is ignored. | | supervisor.autoscaling.maxReplicas | int | `4` | Maximum supervisor replicas. Must not exceed the gateway replica count * supervisor.pool.maxMembersPerGateway. | @@ -843,18 +858,21 @@ for peer identity policies, multi-node registrations, and authorization. | supervisor.image.tag | string | `""` | Supervisor image tag. Defaults to the chart appVersion when empty. | | supervisor.listenAddress | string | `"0.0.0.0"` | Shared supervisor listener IP. Use `::` for IPv6. | | supervisor.network.additionalCaConfigMapName | string | `""` | Name of an operator-owned ConfigMap with a `ca.crt` key containing additional destination CA certificates for sandbox supervisors. Empty disables additional destination trust. | +| supervisor.nodeSelector | object | `{}` | Node selector for the shared supervisor pod. With supervisor_topology = "node", it must cover every node that can host sandboxes, and `externalEnforcer.enabled` adds `node-restriction.kubernetes.io/openshell-external-enforcer-ready: "true"`. | | supervisor.podDisruptionBudget.enabled | bool | `true` | Render a PodDisruptionBudget with maxUnavailable 1 for the shared supervisor, used only when gatewayConfig selects supervisor_topology = "gateway". Disable it only when maintenance must evict more than one supervisor Pod at a time, or evict a member while another is unavailable. | | supervisor.podSecurityContext.fsGroup | int | `65534` | fsGroup assigned to the shared supervisor pod. | | supervisor.podSecurityContext.runAsGroup | int | `65534` | Primary GID assigned to the shared supervisor pod. | | supervisor.podSecurityContext.runAsNonRoot | bool | `true` | Require the shared supervisor to run as a non-root user. | | supervisor.podSecurityContext.runAsUser | int | `65534` | UID assigned to the shared supervisor pod. | | supervisor.podSecurityContext.seccompProfile.type | string | `"RuntimeDefault"` | Seccomp profile applied to the shared supervisor pod. | -| supervisor.pool.maxInstancesPerMember | int | `128` | Most sandboxes one supervisor runs, rendered as [openshell.gateway.supervisor_pool] max_instances_per_member and passed to each supervisor. Must be an integer from 1 to 1024. The gateway refuses a sandbox when every supervisor is full. | +| supervisor.pool.maxInstancesPerMember | int | `128` | Most sandboxes one supervisor runs, rendered as [openshell.gateway.supervisor_pool] max_instances_per_member and passed to each supervisor. Must be an integer from 1 to 1024. The gateway refuses a sandbox when every supervisor is full. Ignored with supervisor_topology = "node", which uses 1024. | | supervisor.pool.maxMembersPerGateway | int | `32` | Most supervisors one gateway replica serves, rendered as [openshell.gateway.supervisor_pool] max_members_per_gateway. Must be a positive integer. The pool runs at most gateway replicas times maxMembersPerGateway times maxInstancesPerMember sandboxes, never more than 131072. | | supervisor.recoveryTimeoutSeconds | int | `60` | Seconds a sandbox workload stays frozen after losing its pool member's supervision before the sandbox runtime terminates it, rendered as [openshell.gateway.supervisor_pool] recovery_timeout_secs. Must be an integer from 30 to 300. Null leaves the gateway's pool default of 60 seconds. | -| supervisor.replicas | int | `1` | Shared supervisor pool members, used only when gatewayConfig selects supervisor_topology = "gateway". The gateway always coordinates the shared supervisor as a high-availability pool: when a member fails or leaves, another member takes over its sandboxes without restarting their workloads. 1 has no failover; use 2 or more to survive losing a member. Only the supervisor Deployment's replica count depends on this value, so changing it neither restarts the gateway nor replaces running members. Ignored when supervisor.autoscaling.enabled is true. Must not exceed replicaCount * supervisor.pool.maxMembersPerGateway. | +| supervisor.replicas | int | `1` | Shared supervisor pool members, used only when gatewayConfig selects supervisor_topology = "gateway". The gateway always coordinates the shared supervisor as a high-availability pool: when a member fails or leaves, another member takes over its sandboxes without restarting their workloads. 1 has no failover; use 2 or more to survive losing a member. Only the supervisor Deployment's replica count depends on this value, so changing it neither restarts the gateway nor replaces running members. Ignored when supervisor.autoscaling.enabled is true or supervisor_topology = "node". Must not exceed replicaCount * supervisor.pool.maxMembersPerGateway. | +| supervisor.requireIdentityToken | bool | `false` | Refuse gateway-topology supervisors that attach without their pod-bound identity token. Node-topology supervisors always need it. Refer to the High Availability guide before enabling it on an upgrade. | | supervisor.resources | object | `{"limits":{"cpu":"1","memory":"1.5Gi"},"requests":{"cpu":"250m","memory":"768Mi"}}` | Resources of each shared supervisor container, initially sized for 128 sandboxes. Increase these with pool.maxInstancesPerMember and allow for failover. Refer to Size Sandbox Capacity in the High Availability guide. Set resources to null to omit the budget, or limits to null to omit limits. | | supervisor.sandboxRuntime.boundaryPort | int | `5500` | Workload boundary TLS listener port. | +| supervisor.tolerations | list | `[]` | Tolerations for the shared supervisor pod. With supervisor_topology = "node", tolerate every taint a sandbox template tolerates, such as `nvidia.com/gpu` on GPU nodes. | | tolerations | list | `[]` | Tolerations for the gateway pod. | | topologySpreadConstraints | list | `[]` | Topology spread constraints for the gateway pod, used to spread replicas across zones or nodes. Empty = omit the field. | | upstreamProxy | object | `{"authAllowInsecure":false,"authSecret":{"key":"","name":""},"caBundle":{"configMapName":"","key":"ca.crt"},"connectByHostname":false,"noProxy":"","url":""}` | Operator-owned corporate forward proxy for policy-approved TLS egress from Kubernetes sandboxes. The workload cannot select or override it. | diff --git a/deploy/helm/openshell/README.md.gotmpl b/deploy/helm/openshell/README.md.gotmpl index 4441c571d3..a6e5ebfa6f 100644 --- a/deploy/helm/openshell/README.md.gotmpl +++ b/deploy/helm/openshell/README.md.gotmpl @@ -297,6 +297,9 @@ driver creates a separate managed ConfigMap in each target sandbox namespace and mounts it only in the dedicated supervisor Pod at `/etc/openshell/tls/additional/ca-bundle.pem`. That supervisor receives the path through `--additional-ca-bundle` and folds the bundle into system roots. +With the shared supervisor topology, the driver creates no ConfigMap; each +sandbox generation's launch material carries the bundle to the shared +supervisor. The configured roots augment default destination trust. They do not configure the corporate proxy, OIDC, or gateway callback mTLS trust. @@ -523,6 +526,10 @@ explicitly. Existing sandboxes stay on their owners when scaling up, and memory-based scaling does not guarantee spare capacity for handoff. See the [shared supervisor autoscaling guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#autoscale-shared-supervisors-by-memory). +Set `supervisor_topology: node` in `gatewayConfig.openshell.drivers.kubernetes` +to run one shared supervisor per node as a DaemonSet. See the +[per-node supervisor guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#run-one-supervisor-per-node). + ## Secure metrics scraping Metrics are enabled by default on `service.metricsPort: 9090`. Set diff --git a/deploy/helm/openshell/ci/values-external-enforcer.yaml b/deploy/helm/openshell/ci/values-external-enforcer.yaml new file mode 100644 index 0000000000..21404abe00 --- /dev/null +++ b/deploy/helm/openshell/ci/values-external-enforcer.yaml @@ -0,0 +1,26 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Render-only overlay for native-network mode. Running it needs an external +# enforcer on the sandbox network. +server: + sandboxNamespace: openshell-sandboxes + +externalEnforcer: + enabled: true + namespace: openshell-enforcer + serviceAccountName: external-enforcer + network: + sandbox: + networkAttachment: openshell-sandboxes/sandbox-vf + resource: example.com/sandbox-vf + nameservers: ["192.168.100.1"] + supervisor: + networkAttachment: openshell/supervisor-vf + resource: example.com/supervisor-vf + +gatewayConfig: + openshell.gateway: + config_delivery_mode: poll + openshell.drivers.kubernetes: + supervisor_topology: node diff --git a/deploy/helm/openshell/ci/values-supervisor-node.yaml b/deploy/helm/openshell/ci/values-supervisor-node.yaml new file mode 100644 index 0000000000..35b030832c --- /dev/null +++ b/deploy/helm/openshell/ci/values-supervisor-node.yaml @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# E2E overlay: supervise new sandbox generations with one shared supervisor per +# node. Each generation is pinned to the supervisor on its workload's node. +gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + +supervisor: + recoveryTimeoutSeconds: 60 diff --git a/deploy/helm/openshell/templates/_helpers.tpl b/deploy/helm/openshell/templates/_helpers.tpl index d174315813..efe34f36a3 100644 --- a/deploy/helm/openshell/templates/_helpers.tpl +++ b/deploy/helm/openshell/templates/_helpers.tpl @@ -359,12 +359,75 @@ flag — so the default value works for any release name or namespace without override. */}} {{/* -Whether the gateway supervisor topology is enabled. Read from the -raw gateway configuration so openshell.effectiveKubernetesConfig can use it. +Whether a shared supervisor topology (gateway or node) is enabled. Read from +the raw gateway configuration so openshell.effectiveKubernetesConfig can use it. */}} {{- define "openshell.supervisorEnabled" -}} {{- $kubernetes := get (.Values.gatewayConfig | default dict) "openshell.drivers.kubernetes" | default dict -}} -{{- if eq (get $kubernetes "supervisor_topology" | default "") "gateway" -}}true{{- end -}} +{{- if has (get $kubernetes "supervisor_topology" | default "") (list "gateway" "node") -}}true{{- end -}} +{{- end }} + +{{/* +Whether the shared supervisor runs one Pod per node (a DaemonSet) instead of a +replicated Deployment. +*/}} +{{- define "openshell.supervisorNodeTopology" -}} +{{- $kubernetes := get (.Values.gatewayConfig | default dict) "openshell.drivers.kubernetes" | default dict -}} +{{- if eq (get $kubernetes "supervisor_topology" | default "") "node" -}}true{{- end -}} +{{- end }} + +{{/* +"true" when an external enforcer enforces network policy, which selects +native-network mode for every new sandbox. +*/}} +{{- define "openshell.externalEnforcer" -}} +{{- if get (.Values.externalEnforcer | default dict) "enabled" -}}true{{- end -}} +{{- end }} + +{{/* +Node label the external enforcer keeps at "true" on the nodes where it +enforces. Must match +openshell_driver_kubernetes::config::EXTERNAL_ENFORCER_READY_NODE_LABEL. +Empty without an external enforcer. +*/}} +{{- define "openshell.externalEnforcerReadyNodeLabel" -}} +{{- if include "openshell.externalEnforcer" . -}} +node-restriction.kubernetes.io/openshell-external-enforcer-ready +{{- end -}} +{{- end }} + +{{/* +Secret in externalEnforcer.namespace that delivers the external enforcer's +token. +*/}} +{{- define "openshell.externalEnforcerTokenSecretName" -}} +{{- printf "%s-external-enforcer-token" (include "openshell.fullname" .) -}} +{{- end }} + +{{/* +A network table from externalEnforcer.network values, or empty when it names +no attachment. +*/}} +{{- define "openshell.externalEnforcerPodNetwork" -}} +{{- with get . "networkAttachment" -}} +network_attachment: {{ . | quote }} +{{- end -}} +{{- with get . "resource" }} +resource: {{ . | quote }} +{{- end -}} +{{- end }} + +{{/* +The node supervisors' additional network, the driver's +external_enforcer.network.supervisor table, or empty when none is configured. +*/}} +{{- define "openshell.supervisorPodNetwork" -}} +{{- if include "openshell.externalEnforcer" . -}} +{{- $network := get (.Values.externalEnforcer.network | default dict) "supervisor" | default dict -}} +{{- if get $network "networkAttachment" -}} +{{- include "openshell.externalEnforcerPodNetwork" $network -}} +{{- end -}} +{{- end -}} {{- end }} {{/* @@ -514,9 +577,17 @@ key, default, and optionally max. {{- end -}} {{- end }} -{{/* Most sandboxes one supervisor runs (supervisor.pool.maxInstancesPerMember). */}} +{{/* +Most sandboxes one supervisor runs (supervisor.pool.maxInstancesPerMember). +A node supervisor takes every sandbox the kubelet admits on its node, so the +node topology always uses the largest cap. +*/}} {{- define "openshell.supervisorMaxInstancesPerMember" -}} +{{- if include "openshell.supervisorNodeTopology" . -}} +1024 +{{- else -}} {{- include "openshell.supervisorPoolLimit" (dict "root" . "key" "maxInstancesPerMember" "max" 1024 "default" 128) -}} +{{- end -}} {{- end }} {{/* Most supervisors one gateway replica serves (supervisor.pool.maxMembersPerGateway). */}} @@ -563,7 +634,9 @@ TOML form. {{- fail "supervisor_pool is rendered by the chart; set supervisor.replicas, supervisor.pool, and supervisor.recoveryTimeoutSeconds" -}} {{- end -}} {{- if include "openshell.supervisorEnabled" . -}} +{{- if not (include "openshell.supervisorNodeTopology" .) -}} {{- include "openshell.validateSupervisorMembers" . -}} +{{- end -}} {{- $table := dict "max_instances_per_member" (int64 (include "openshell.supervisorMaxInstancesPerMember" .)) "max_members_per_gateway" (int64 (include "openshell.supervisorMaxMembersPerGateway" .)) -}} {{- $recoveryTimeout := include "openshell.supervisorRecoveryTimeoutSeconds" . -}} {{- if $recoveryTimeout -}} @@ -832,7 +905,19 @@ like user-supplied schema-v2 fields during compatibility resolution. */}} {{- $_ := set $kubernetes "sandbox_runtime" $runtimeConfig -}} {{/* The chart owns the shared supervisor and the Secret that delivers its token. */}} {{- if include "openshell.supervisorEnabled" . -}} -{{- $_ := set $kubernetes "shared_supervisor" (dict "service_name" (include "openshell.supervisorName" .) "service_namespace" .Release.Namespace "runtime_port" 5500 "token_secret_name" (printf "%s-token" (include "openshell.supervisorName" .))) -}} +{{- $_ := set $kubernetes "shared_supervisor" (dict "service_name" (include "openshell.supervisorName" .) "service_namespace" .Release.Namespace "runtime_port" 5500 "token_secret_name" (printf "%s-token" (include "openshell.supervisorName" .)) "service_account_name" (include "openshell.supervisorName" .) "require_identity_token" (.Values.supervisor.requireIdentityToken | default false)) -}} +{{- end -}} +{{/* The chart owns the external enforcer table and its token Secret. */}} +{{- if include "openshell.externalEnforcer" . -}} +{{- $values := .Values.externalEnforcer -}} +{{- $networkValues := $values.network | default dict -}} +{{- $sandboxValues := get $networkValues "sandbox" | default dict -}} +{{- $sandbox := include "openshell.externalEnforcerPodNetwork" $sandboxValues | fromYaml | default dict -}} +{{- $_ := set $sandbox "nameservers" (get $sandboxValues "nameservers" | default list) -}} +{{- $network := dict "sandbox" $sandbox -}} +{{- $supervisor := include "openshell.supervisorPodNetwork" . | fromYaml -}} +{{- if $supervisor -}}{{- $_ := set $network "supervisor" $supervisor -}}{{- end -}} +{{- $_ := set $kubernetes "external_enforcer" (dict "namespace" (get $values "namespace" | default "") "token_secret_name" (include "openshell.externalEnforcerTokenSecretName" .) "service_account_name" (get $values "serviceAccountName" | default "") "network" $network) -}} {{- end -}} {{- toYaml $kubernetes -}} {{- end }} @@ -845,8 +930,8 @@ Validate chart values that Helm would otherwise accept silently. {{- $kubernetes := include "openshell.effectiveKubernetesConfig" . | fromYaml -}} {{- if hasKey $kubernetes "supervisor_topology" -}} {{- $topology := get $kubernetes "supervisor_topology" -}} -{{- if not (has $topology (list "gateway" "workspace")) -}} -{{- fail "supervisor_topology must be gateway or workspace; omit it to disable the shared supervisor" -}} +{{- if not (has $topology (list "gateway" "node" "workspace")) -}} +{{- fail "supervisor_topology must be gateway, node, or workspace; omit it to disable the shared supervisor" -}} {{- end -}} {{- if eq $topology "workspace" -}} {{- fail "supervisor_topology=workspace is not implemented" -}} @@ -856,28 +941,63 @@ Validate chart values that Helm would otherwise accept silently. {{- fail "supervisor_topology requires the kubernetes compute driver" -}} {{- end -}} {{- if or (get $kubernetes "https_proxy") (get $kubernetes "proxy_ca_bundle") (get $kubernetes "proxy_auth_secret_name") -}} -{{- fail "supervisor_topology=gateway does not support upstream proxy settings" -}} +{{- fail (printf "supervisor_topology=%s does not support upstream proxy settings" $topology) -}} {{- end -}} {{- if .Values.server.disableTls -}} -{{- fail "supervisor_topology=gateway requires gateway TLS; the supervisor token travels only over TLS" -}} +{{- fail (printf "supervisor_topology=%s requires gateway TLS; the supervisor token travels only over TLS" $topology) -}} {{- end -}} {{- if and (eq (get $kubernetes "workspace_mode" | default "shared") "operator") (not (regexMatch "^[A-Za-z0-9][-A-Za-z0-9_./]*==?[-A-Za-z0-9_.]*$" (get $kubernetes "operator_namespace_label" | default ""))) -}} -{{- fail "supervisor_topology=gateway in operator workspace mode requires operator_namespace_label of the form key=value" -}} +{{- fail (printf "supervisor_topology=%s in operator workspace mode requires operator_namespace_label of the form key=value" $topology) -}} {{- end -}} {{- end -}} {{- $broker := get (.Values.gatewayConfig | default dict) "openshell.gateway.spiffe_broker" | default dict -}} -{{- if and (eq (get $kubernetes "supervisor_topology" | default "") "gateway") (get $kubernetes "provider_spiffe_workload_api_socket_path") (empty $broker) -}} +{{- if and (include "openshell.supervisorEnabled" .) (get $kubernetes "provider_spiffe_workload_api_socket_path") (empty $broker) -}} {{- fail "shared supervisor SPIFFE grants require spiffe_broker; remove provider_spiffe_workload_api_socket_path from the shared supervisor" -}} {{- end -}} {{- if $broker -}} -{{- if ne (get $kubernetes "supervisor_topology" | default "") "gateway" -}} -{{- fail "spiffe_broker requires supervisor_topology=gateway" -}} +{{- if not (include "openshell.supervisorEnabled" .) -}} +{{- fail "spiffe_broker requires supervisor_topology=gateway or node" -}} {{- end -}} {{- include "openshell.validateSpiffeBroker" (dict "broker" $broker) -}} {{- end -}} {{- if hasKey (get (.Values.gatewayConfig | default dict) "openshell.drivers.kubernetes" | default dict) "shared_supervisor" -}} {{- fail "shared_supervisor is rendered by the chart; set only supervisor_topology" -}} {{- end -}} +{{- range $key := keys (.Values.gatewayConfig | default dict) -}} +{{- if hasPrefix "openshell.drivers.kubernetes.external_enforcer" $key -}} +{{- fail "external_enforcer is rendered by the chart; set externalEnforcer instead" -}} +{{- end -}} +{{- end -}} +{{- if hasKey (get (.Values.gatewayConfig | default dict) "openshell.drivers.kubernetes" | default dict) "external_enforcer" -}} +{{- fail "external_enforcer is rendered by the chart; set externalEnforcer instead" -}} +{{- end -}} +{{- if include "openshell.externalEnforcer" . -}} +{{- $enforcer := .Values.externalEnforcer -}} +{{- $network := $enforcer.network | default dict -}} +{{- $sandbox := get $network "sandbox" | default dict -}} +{{- $supervisor := get $network "supervisor" | default dict -}} +{{- if not (get $enforcer "namespace") -}} +{{- fail "externalEnforcer.namespace is required; the external enforcer runs in its own namespace" -}} +{{- end -}} +{{- if eq (get $enforcer "namespace") .Release.Namespace -}} +{{- fail "externalEnforcer.namespace must differ from the release namespace, which holds the supervisor's credentials" -}} +{{- end -}} +{{- if not (get $enforcer "serviceAccountName") -}} +{{- fail "externalEnforcer.serviceAccountName is required; the gateway accepts the external enforcer token only beside a pod-bound token for that ServiceAccount" -}} +{{- end -}} +{{- if not (get $sandbox "networkAttachment") -}} +{{- fail "externalEnforcer.network.sandbox.networkAttachment is required" -}} +{{- end -}} +{{- if not (get $sandbox "nameservers") -}} +{{- fail "externalEnforcer.network.sandbox.nameservers is required; the external enforcer answers the sandboxes' DNS" -}} +{{- end -}} +{{- if and (get $supervisor "resource") (not (get $supervisor "networkAttachment")) -}} +{{- fail "externalEnforcer.network.supervisor.resource requires externalEnforcer.network.supervisor.networkAttachment" -}} +{{- end -}} +{{- if and (include "openshell.supervisorPodNetwork" .) (get (include "openshell.appListenerConfig" . | fromYaml) "enabled") -}} +{{- fail "externalEnforcer.network.supervisor does not support the supervisor app listener" -}} +{{- end -}} +{{- end -}} {{- include "openshell.validateSupervisorAutoscaling" . -}} {{- $pdb := get (.Values.supervisor | default dict) "podDisruptionBudget" | default dict -}} {{- if not (kindIs "map" $pdb) -}} diff --git a/deploy/helm/openshell/templates/_supervisor-autoscaling.tpl b/deploy/helm/openshell/templates/_supervisor-autoscaling.tpl index 3d25ebcf09..99f7a3955c 100644 --- a/deploy/helm/openshell/templates/_supervisor-autoscaling.tpl +++ b/deploy/helm/openshell/templates/_supervisor-autoscaling.tpl @@ -16,7 +16,7 @@ {{- fail "supervisor.autoscaling.enabled must be a boolean" -}} {{- end -}} {{- if eq (include "openshell.supervisorAutoscalingEnabled" .) "true" -}} -{{- if not (include "openshell.supervisorEnabled" .) -}} +{{- if or (not (include "openshell.supervisorEnabled" .)) (include "openshell.supervisorNodeTopology" .) -}} {{- fail "supervisor.autoscaling.enabled requires supervisor_topology = gateway" -}} {{- end -}} {{- $min := include "openshell.wholeNumber" (get $a "minReplicas") -}} diff --git a/deploy/helm/openshell/templates/external-enforcer-role.yaml b/deploy/helm/openshell/templates/external-enforcer-role.yaml new file mode 100644 index 0000000000..4aa0eb954e --- /dev/null +++ b/deploy/helm/openshell/templates/external-enforcer-role.yaml @@ -0,0 +1,47 @@ +{{- if and (include "openshell.rbacCreate" .) (include "openshell.externalEnforcer" .) }} +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: {{ include "openshell.fullname" . }}-external-enforcer + namespace: {{ .Values.externalEnforcer.namespace }} + labels: + {{- include "openshell.labels" . | nindent 4 }} +rules: + # External enforcer identity: TokenReview authenticates its projected token, + # then the gateway resolves the returned pod name and UID to the live Pod. + - apiGroups: + - "" + resources: + - pods + verbs: + - get + # The gateway delivers the external enforcer token it mints by replacing the + # token in the chart-created Secret; it creates no Secrets here. + - apiGroups: + - "" + resources: + - secrets + resourceNames: + - {{ include "openshell.externalEnforcerTokenSecretName" . }} + verbs: + - get + - patch +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: {{ include "openshell.fullname" . }}-external-enforcer + namespace: {{ .Values.externalEnforcer.namespace }} + labels: + {{- include "openshell.labels" . | nindent 4 }} +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: {{ include "openshell.fullname" . }}-external-enforcer +subjects: + - kind: ServiceAccount + name: {{ include "openshell.serviceAccountName" . }} + namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/deploy/helm/openshell/templates/peer-role.yaml b/deploy/helm/openshell/templates/peer-role.yaml index d7fa148658..be76d02996 100644 --- a/deploy/helm/openshell/templates/peer-role.yaml +++ b/deploy/helm/openshell/templates/peer-role.yaml @@ -9,9 +9,9 @@ metadata: labels: {{- include "openshell.labels" . | nindent 4 }} rules: - # Gateway peer identity: TokenReview authenticates the projected token, then - # the receiver resolves the returned pod name and UID to the live gateway pod - # in the release namespace. + # Gateway peer and shared supervisor identity: TokenReview authenticates the + # projected token, then the receiver resolves the returned pod name and UID + # to the live gateway or supervisor pod in the release namespace. - apiGroups: - "" resources: @@ -19,6 +19,16 @@ rules: verbs: - get {{- if include "openshell.supervisorEnabled" . }} + {{- if include "openshell.supervisorPodNetwork" . }} + # The Kubernetes driver lists the supervisor Pods on a workload's node to + # read their address on the supervisor network. + - apiGroups: + - "" + resources: + - pods + verbs: + - list + {{- end }} # The Kubernetes driver reads the shared supervisor Service to scope each # sandbox's control egress to the supervisor Pods it selects. - apiGroups: diff --git a/deploy/helm/openshell/templates/supervisor-pdb.yaml b/deploy/helm/openshell/templates/supervisor-pdb.yaml index ab1f8bc37d..75d7074a62 100644 --- a/deploy/helm/openshell/templates/supervisor-pdb.yaml +++ b/deploy/helm/openshell/templates/supervisor-pdb.yaml @@ -1,7 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 {{- include "openshell.validateValues" . }} -{{- if and (include "openshell.supervisorEnabled" .) (eq (include "openshell.supervisorPodDisruptionBudgetEnabled" .) "true") }} +{{- if and (include "openshell.supervisorEnabled" .) (not (include "openshell.supervisorNodeTopology" .)) (eq (include "openshell.supervisorPodDisruptionBudgetEnabled" .) "true") }} # Voluntary disruptions, such as node drains, evict one member at a time, so # the remaining members can take over its instances. apiVersion: policy/v1 diff --git a/deploy/helm/openshell/templates/supervisor-service.yaml b/deploy/helm/openshell/templates/supervisor-service.yaml index e91832afd1..78e68408ab 100644 --- a/deploy/helm/openshell/templates/supervisor-service.yaml +++ b/deploy/helm/openshell/templates/supervisor-service.yaml @@ -13,6 +13,10 @@ metadata: {{- include "openshell.labels" . | nindent 4 }} app.kubernetes.io/component: supervisor spec: + {{- if include "openshell.supervisorNodeTopology" . }} + # A runtime that dials the Service reaches its own node's supervisor. + internalTrafficPolicy: Local + {{- end }} selector: {{- include "openshell.supervisorSelectorLabels" . | nindent 4 }} ports: diff --git a/deploy/helm/openshell/templates/supervisor-serviceaccount.yaml b/deploy/helm/openshell/templates/supervisor-serviceaccount.yaml new file mode 100644 index 0000000000..14c2bf5cd4 --- /dev/null +++ b/deploy/helm/openshell/templates/supervisor-serviceaccount.yaml @@ -0,0 +1,18 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +{{- include "openshell.validateValues" . }} +{{- if include "openshell.supervisorEnabled" . }} +# Supervisors prove their Pod, and in the node topology their node, with +# this account's Pod-bound tokens. The gateway only reviews them, so bind no +# RBAC to it. Restrict creating Pods with it and `create` on its +# `serviceaccounts/token` to cluster administrators. +apiVersion: v1 +kind: ServiceAccount +metadata: + name: {{ include "openshell.supervisorName" . }} + namespace: {{ .Release.Namespace }} + labels: + {{- include "openshell.labels" . | nindent 4 }} + app.kubernetes.io/component: supervisor +automountServiceAccountToken: false +{{- end }} diff --git a/deploy/helm/openshell/templates/supervisor-token-secret.yaml b/deploy/helm/openshell/templates/supervisor-token-secret.yaml index d49d1897dc..ba68f678a5 100644 --- a/deploy/helm/openshell/templates/supervisor-token-secret.yaml +++ b/deploy/helm/openshell/templates/supervisor-token-secret.yaml @@ -16,3 +16,18 @@ metadata: app.kubernetes.io/component: supervisor type: Opaque {{- end }} +{{- if include "openshell.externalEnforcer" . }} +--- +# Delivery of the gateway-minted external enforcer token, in the external +# enforcer's own namespace, which must already exist. The external enforcer +# mounts this Secret as the supervisor mounts its own. +apiVersion: v1 +kind: Secret +metadata: + name: {{ include "openshell.externalEnforcerTokenSecretName" . }} + namespace: {{ .Values.externalEnforcer.namespace }} + labels: + {{- include "openshell.labels" . | nindent 4 }} + app.kubernetes.io/component: external-enforcer +type: Opaque +{{- end }} diff --git a/deploy/helm/openshell/templates/supervisor.yaml b/deploy/helm/openshell/templates/supervisor.yaml index 96d4a1e687..e371eaac3d 100644 --- a/deploy/helm/openshell/templates/supervisor.yaml +++ b/deploy/helm/openshell/templates/supervisor.yaml @@ -23,14 +23,16 @@ {{- $endpoint := get $kubernetes "grpc_endpoint" }} {{- $endpointUrl := urlParse $endpoint }} {{- $gatewayTls := and (not .Values.server.disableTls) .Values.server.tls.clientTlsSecretName }} +{{- $node := include "openshell.supervisorNodeTopology" . }} +{{- $podNetwork := include "openshell.supervisorPodNetwork" . | fromYaml }} # One supervisor process per replica hosts a sandbox instance for each sandbox # generation placed on it. The process dials the gateway over TLS with the # supervisor token the gateway mints for it and receives its assignments from # it; nothing but sandbox runtimes and kubelet probes connect to it. The Pod -# holds no Kubernetes identity of its own: each instance acts only with the +# holds no Kubernetes API identity of its own: each instance acts only with the # credentials the gateway issued for its generation. apiVersion: apps/v1 -kind: Deployment +kind: {{ ternary "DaemonSet" "Deployment" (eq $node "true") }} metadata: name: {{ $name }} namespace: {{ .Release.Namespace }} @@ -38,6 +40,15 @@ metadata: {{- include "openshell.labels" . | nindent 4 }} app.kubernetes.io/component: supervisor spec: + {{- if $node }} + # No surge: two live members with one node's ID would keep superseding each + # other. + updateStrategy: + type: RollingUpdate + rollingUpdate: + maxSurge: 0 + maxUnavailable: 1 + {{- else }} # The replicas form a high-availability pool. Each instance lives in the # process hosting it; the pool rolls one member at a time, starting a new # member before an old one leaves, and the gateway hands a failed or leaving @@ -53,6 +64,7 @@ spec: rollingUpdate: maxSurge: 1 maxUnavailable: 0 + {{- end }} selector: matchLabels: {{- include "openshell.supervisorSelectorLabels" . | nindent 6 }} @@ -60,12 +72,31 @@ spec: metadata: labels: {{- include "openshell.supervisorSelectorLabels" . | nindent 8 }} + {{- with $podNetwork }} + # Sandbox runtimes on this node dial the supervisor's net1 address. + annotations: + k8s.v1.cni.cncf.io/networks: {{ printf "%s@net1" (get . "network_attachment") | quote }} + {{- end }} spec: + serviceAccountName: {{ $name }} automountServiceAccountToken: false enableServiceLinks: false + {{- if not $node }} # A stopping member announces that it is leaving, and the gateway moves # its instances to the remaining members before it exits. + {{- end }} terminationGracePeriodSeconds: 60 + {{- $nodeSelector := deepCopy (.Values.supervisor.nodeSelector | default dict) }} + {{- with (include "openshell.externalEnforcerReadyNodeLabel" .) }} + {{- if $node }} + {{- /* The Kubernetes driver schedules every workload Pod to these nodes. */}} + {{- $_ := set $nodeSelector . "true" }} + {{- end }} + {{- end }} + {{- with $nodeSelector }} + nodeSelector: + {{- toYaml . | nindent 8 }} + {{- end }} {{- with ($imagePullSecrets | uniq) }} imagePullSecrets: {{- range . }} @@ -80,6 +111,10 @@ spec: affinity: {{- toYaml . | nindent 8 }} {{- end }} + {{- with .Values.supervisor.tolerations }} + tolerations: + {{- toYaml . | nindent 8 }} + {{- end }} containers: - name: supervisor image: {{ get $kubernetes "supervisor_image" | quote }} @@ -92,6 +127,8 @@ spec: - {{ printf "%s:5501" $listenHost | quote }} - --token-file - /etc/openshell/supervisor-token/token + - --identity-token-file + - /var/run/secrets/openshell-supervisor/token - --runtime-listen - {{ printf "%s:%v" $listenHost (get $shared "runtime_port") | quote }} - --session-root @@ -104,6 +141,9 @@ spec: - --nat64-prefix - {{ . | quote }} {{- end }} + {{- if $node }} + - --node-supervisor + {{- end }} env: {{- if get $app "enabled" }} - name: OPENSHELL_APP_LISTENER_ENABLED @@ -129,17 +169,23 @@ spec: - name: OPENSHELL_GATEWAY_TLS_SERVER_NAME value: {{ get $endpointUrl "hostname" | quote }} {{- end }} - # Pool membership: the Pod name is this member's stable ID, and - # other members redirect the runtimes of its instances to its Pod - # IP. + # Pool membership: the Pod name (the node name in the node + # topology) is this member's stable ID, and other members redirect + # the runtimes of its instances to its Pod IP, or to its net1 + # address on the supervisor network. - name: OPENSHELL_SUPERVISOR_POOL_MEMBER_ID valueFrom: fieldRef: - fieldPath: metadata.name + fieldPath: {{ ternary "spec.nodeName" "metadata.name" (eq $node "true") }} + {{- if $podNetwork }} + - name: OPENSHELL_SUPERVISOR_POOL_ADVERTISE_INTERFACE + value: net1 + {{- else }} - name: OPENSHELL_SUPERVISOR_POOL_ADVERTISE_IP valueFrom: fieldRef: fieldPath: status.podIP + {{- end }} # The same per-member cap the gateway places by. - name: OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES value: {{ include "openshell.supervisorMaxInstancesPerMember" . | quote }} @@ -160,7 +206,12 @@ spec: readOnlyRootFilesystem: true capabilities: drop: [ALL] - {{- with .Values.supervisor.resources }} + {{- $resources := deepCopy (.Values.supervisor.resources | default dict) }} + {{- with get $podNetwork "resource" }} + {{- $_ := set $resources "requests" (merge (dict . "1") (get $resources "requests" | default dict)) }} + {{- $_ := set $resources "limits" (merge (dict . "1") (get $resources "limits" | default dict)) }} + {{- end }} + {{- with $resources }} resources: {{- toYaml . | nindent 12 }} {{- end }} @@ -186,6 +237,9 @@ spec: - name: supervisor-token mountPath: /etc/openshell/supervisor-token readOnly: true + - name: identity + mountPath: /var/run/secrets/openshell-supervisor + readOnly: true {{- if $gatewayTls }} - name: gateway-ca mountPath: /var/run/secrets/openshell-tls @@ -204,6 +258,13 @@ spec: - name: supervisor-token secret: secretName: {{ $name }}-token + - name: identity + projected: + sources: + - serviceAccountToken: + audience: openshell-supervisor + expirationSeconds: 600 + path: token {{- if $gatewayTls }} - name: gateway-ca secret: diff --git a/deploy/helm/openshell/tests/supervisor_test.yaml b/deploy/helm/openshell/tests/supervisor_test.yaml index e3d8afbc5c..f2719ba6a0 100644 --- a/deploy/helm/openshell/tests/supervisor_test.yaml +++ b/deploy/helm/openshell/tests/supervisor_test.yaml @@ -7,7 +7,9 @@ templates: - templates/supervisor-networkpolicy.yaml - templates/supervisor-token-secret.yaml - templates/supervisor-pdb.yaml + - templates/supervisor-serviceaccount.yaml - templates/gateway-config.yaml + - templates/external-enforcer-role.yaml release: name: openshell namespace: gateway @@ -43,7 +45,7 @@ tests: value: "[::]:5501" documentIndex: 0 - equal: - path: spec.template.spec.containers[0].args[8] + path: spec.template.spec.containers[0].args[10] value: "[::]:5500" documentIndex: 0 - notContains: @@ -60,22 +62,22 @@ tests: nat64_prefixes: ["2001:db8:64::/96"] asserts: - equal: - path: spec.template.spec.containers[0].args[11] + path: spec.template.spec.containers[0].args[13] value: --policy-dns-ipv6-egress documentIndex: 0 - equal: - path: spec.template.spec.containers[0].args[12] + path: spec.template.spec.containers[0].args[14] value: enabled documentIndex: 0 - equal: - path: spec.template.spec.containers[0].args[13] + path: spec.template.spec.containers[0].args[15] value: --nat64-prefix documentIndex: 0 - equal: - path: spec.template.spec.containers[0].args[14] + path: spec.template.spec.containers[0].args[16] value: 2001:db8:64::/96 documentIndex: 0 - - it: deploys the supervisor pool without Kubernetes identity in the gateway namespace + - it: deploys the supervisor pool with a Pod identity and no Kubernetes API access in the gateway namespace template: templates/supervisor.yaml set: gatewayConfig: @@ -98,6 +100,9 @@ tests: - hasDocuments: count: 1 template: templates/supervisor-pdb.yaml + - hasDocuments: + count: 1 + template: templates/supervisor-serviceaccount.yaml - equal: path: kind value: Deployment @@ -106,6 +111,28 @@ tests: path: metadata.namespace value: gateway documentIndex: 0 + - equal: + path: spec.template.spec.serviceAccountName + value: openshell-supervisor + documentIndex: 0 + - contains: + path: spec.template.spec.containers[0].volumeMounts + content: + name: identity + mountPath: /var/run/secrets/openshell-supervisor + readOnly: true + documentIndex: 0 + - contains: + path: spec.template.spec.volumes + content: + name: identity + projected: + sources: + - serviceAccountToken: + audience: openshell-supervisor + expirationSeconds: 600 + path: token + documentIndex: 0 - equal: path: spec.replicas value: 1 @@ -128,6 +155,8 @@ tests: - 0.0.0.0:5501 - --token-file - /etc/openshell/supervisor-token/token + - --identity-token-file + - /var/run/secrets/openshell-supervisor/token - --runtime-listen - 0.0.0.0:5500 - --session-root @@ -350,7 +379,7 @@ tests: pattern: 'supervisor_topology = "gateway"' - matchRegex: path: data["gateway.toml"] - pattern: 'shared_supervisor = \{ runtime_port = 5500, service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' + pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' - it: runs one replica as a high-availability pool by default template: templates/supervisor.yaml set: @@ -624,7 +653,7 @@ tests: template: templates/supervisor.yaml - matchRegex: path: data["gateway.toml"] - pattern: 'shared_supervisor = \{ runtime_port = 5500, service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' + pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' template: templates/gateway-config.yaml - notMatchRegex: path: data["gateway.toml"] @@ -660,7 +689,7 @@ tests: asserts: - matchRegex: path: data["gateway.toml"] - pattern: 'shared_supervisor = \{ runtime_port = 5500, service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' + pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' - matchRegex: path: data["gateway.toml"] pattern: '\[openshell\.gateway\.supervisor_pool\]\nmax_instances_per_member = 128\nmax_members_per_gateway = 32\nrecovery_timeout_secs = 60\n' @@ -700,7 +729,7 @@ tests: pattern: '\[openshell\.gateway\.supervisor_pool\]\n(max_[a-z_]+ = [0-9]+\n)*recovery_timeout_secs = 45\n' - matchRegex: path: data["gateway.toml"] - pattern: 'shared_supervisor = \{ runtime_port = 5500, service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' + pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' - it: renders no supervisor pool without the gateway topology template: templates/gateway-config.yaml set: @@ -778,6 +807,26 @@ tests: value: 512Mi template: templates/supervisor.yaml documentIndex: 0 + - it: gives node supervisors the largest per-member cap + set: + supervisor: + pool: + maxInstancesPerMember: 16 + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '\[openshell\.gateway\.supervisor_pool\]\nmax_instances_per_member = 1024\n' + template: templates/gateway-config.yaml + - contains: + path: spec.template.spec.containers[0].env + content: + name: OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES + value: "1024" + template: templates/supervisor.yaml + documentIndex: 0 - it: accepts a per-member cap of one sandbox template: templates/supervisor.yaml set: @@ -858,6 +907,20 @@ tests: asserts: - failedTemplate: errorMessage: supervisor.replicas (3) exceeds replicaCount (1) * supervisor.pool.maxMembersPerGateway (2) = 2; add gateway replicas or raise maxMembersPerGateway + - it: ignores supervisor.replicas when counting node-topology members + template: templates/supervisor.yaml + set: + supervisor: + replicas: 3 + pool: + maxMembersPerGateway: 2 + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - isKind: + of: DaemonSet + documentIndex: 0 - it: rejects a supervisor HPA maximum above what the gateways serve template: templates/supervisor.yaml set: @@ -1001,7 +1064,7 @@ tests: supervisor_topology: invalid asserts: - failedTemplate: - errorMessage: supervisor_topology must be gateway or workspace; omit it to disable the shared supervisor + errorMessage: supervisor_topology must be gateway, node, or workspace; omit it to disable the shared supervisor - it: rejects enabled topology for another compute driver template: templates/supervisor.yaml set: @@ -1013,3 +1076,476 @@ tests: asserts: - failedTemplate: errorMessage: supervisor_topology requires the kubernetes compute driver + - it: runs one supervisor per node bound to its node in the node topology + template: templates/supervisor.yaml + set: + supervisor: + replicas: 3 + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: kind + value: DaemonSet + - notExists: + path: spec.replicas + - notExists: + path: spec.strategy + - equal: + path: spec.updateStrategy + value: + type: RollingUpdate + rollingUpdate: + maxSurge: 0 + maxUnavailable: 1 + - equal: + path: spec.template.spec.serviceAccountName + value: openshell-supervisor + - equal: + path: spec.template.spec.automountServiceAccountToken + value: false + - notExists: + path: spec.template.spec.nodeSelector + - notExists: + path: spec.template.spec.tolerations + - contains: + path: spec.template.spec.containers[0].env + content: + name: OPENSHELL_SUPERVISOR_POOL_MEMBER_ID + valueFrom: + fieldRef: + fieldPath: spec.nodeName + - contains: + path: spec.template.spec.containers[0].args + content: --node-supervisor + - contains: + path: spec.template.spec.containers[0].args + content: /var/run/secrets/openshell-supervisor/token + - it: places node supervisors on tainted and selected nodes + template: templates/supervisor.yaml + set: + supervisor: + nodeSelector: + openshell.ai/sandbox-pool: gpu + tolerations: + - key: nvidia.com/gpu + operator: Exists + effect: NoSchedule + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: kind + value: DaemonSet + - equal: + path: spec.template.spec.nodeSelector + value: + openshell.ai/sandbox-pool: gpu + - equal: + path: spec.template.spec.tolerations + value: + - key: nvidia.com/gpu + operator: Exists + effect: NoSchedule + - it: runs node supervisors only on external-enforcer-ready nodes + template: templates/supervisor.yaml + set: + externalEnforcer: &externalEnforcer + enabled: true + namespace: openshell-enforcer + serviceAccountName: external-enforcer + network: + sandbox: + networkAttachment: openshell/sandbox-vf + resource: example.com/sandbox-vf + nameservers: ["192.168.100.1"] + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: spec.template.spec.nodeSelector + value: + node-restriction.kubernetes.io/openshell-external-enforcer-ready: "true" + - it: creates the external enforcer token Secret in its namespace and renders the driver table + set: + externalEnforcer: *externalEnforcer + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - hasDocuments: + count: 2 + template: templates/supervisor-token-secret.yaml + - equal: + path: metadata.name + value: openshell-external-enforcer-token + documentIndex: 1 + template: templates/supervisor-token-secret.yaml + - equal: + path: metadata.namespace + value: openshell-enforcer + documentIndex: 1 + template: templates/supervisor-token-secret.yaml + - matchRegex: + path: data["gateway.toml"] + pattern: 'external_enforcer = \{ namespace = "openshell-enforcer", network = \{ sandbox = \{ nameservers = \["192.168.100.1"\], network_attachment = "openshell/sandbox-vf", resource = "example.com/sandbox-vf" \} \}, service_account_name = "external-enforcer", token_secret_name = "openshell-external-enforcer-token" \}' + template: templates/gateway-config.yaml + - notMatchRegex: + path: data["gateway.toml"] + pattern: 'shared_supervisor = \{[^\n]*enforcer' + template: templates/gateway-config.yaml + - it: requires the external enforcer's namespace + template: templates/supervisor.yaml + set: + externalEnforcer: + enabled: true + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - failedTemplate: + errorPattern: externalEnforcer.namespace is required + - it: requires the external enforcer ServiceAccount + template: templates/supervisor.yaml + set: + externalEnforcer: + enabled: true + namespace: openshell-enforcer + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - failedTemplate: + errorPattern: externalEnforcer.serviceAccountName is required + - it: requires the sandbox network + template: templates/supervisor.yaml + set: + externalEnforcer: + enabled: true + namespace: openshell-enforcer + serviceAccountName: external-enforcer + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - failedTemplate: + errorPattern: externalEnforcer.network.sandbox.networkAttachment is required + - it: keeps the external enforcer out of the release namespace + template: templates/supervisor.yaml + set: + externalEnforcer: + enabled: true + namespace: gateway + serviceAccountName: external-enforcer + network: + sandbox: + networkAttachment: openshell/sandbox-vf + nameservers: ["192.168.100.1"] + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - failedTemplate: + errorPattern: externalEnforcer.namespace must differ from the release namespace + - it: requires the sandbox network nameservers + template: templates/supervisor.yaml + set: + externalEnforcer: + enabled: true + namespace: openshell-enforcer + serviceAccountName: external-enforcer + network: + sandbox: + networkAttachment: openshell/sandbox-vf + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - failedTemplate: + errorPattern: externalEnforcer.network.sandbox.nameservers is required + - it: runs gateway-topology supervisors on any node with an external enforcer + template: templates/supervisor.yaml + set: + externalEnforcer: *externalEnforcer + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: gateway + asserts: + - isKind: + of: Deployment + - notExists: + path: spec.template.spec.nodeSelector + - it: refuses an external_enforcer table in gatewayConfig + template: templates/supervisor.yaml + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + external_enforcer: + namespace: openshell-enforcer + asserts: + - failedTemplate: + errorPattern: external_enforcer is rendered by the chart + - it: refuses a flattened external_enforcer table in gatewayConfig + template: templates/supervisor.yaml + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + openshell.drivers.kubernetes.external_enforcer.network.sandbox: + network_attachment: openshell/sandbox-vf + asserts: + - failedTemplate: + errorPattern: external_enforcer is rendered by the chart + - it: creates no external enforcer token Secret without an external enforcer + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - hasDocuments: + count: 1 + template: templates/supervisor-token-secret.yaml + - hasDocuments: + count: 0 + template: templates/external-enforcer-role.yaml + - notMatchRegex: + path: data["gateway.toml"] + pattern: external_enforcer + template: templates/gateway-config.yaml + - it: merges the external-enforcer-ready label into the configured node selector + template: templates/supervisor.yaml + set: + externalEnforcer: *externalEnforcer + supervisor: + nodeSelector: + openshell.ai/sandbox-pool: gpu + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: spec.template.spec.nodeSelector + value: + openshell.ai/sandbox-pool: gpu + node-restriction.kubernetes.io/openshell-external-enforcer-ready: "true" + - it: keeps node-topology runtimes on their node and renders no disruption budget + template: templates/supervisor-service.yaml + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: spec.internalTrafficPolicy + value: Local + template: templates/supervisor-service.yaml + - hasDocuments: + count: 0 + template: templates/supervisor-pdb.yaml + - hasDocuments: + count: 1 + template: templates/supervisor-serviceaccount.yaml + - equal: + path: automountServiceAccountToken + value: false + template: templates/supervisor-serviceaccount.yaml + - matchRegex: + path: data["gateway.toml"] + pattern: 'shared_supervisor = \{ require_identity_token = false, runtime_port = 5500, service_account_name = "openshell-supervisor", service_name = "openshell-supervisor", service_namespace = "gateway", token_secret_name = "openshell-supervisor-token" \}' + template: templates/gateway-config.yaml + - matchRegex: + path: data["gateway.toml"] + pattern: 'supervisor_topology = "node"' + template: templates/gateway-config.yaml + - it: keeps the gateway topology a Deployment unbound to nodes + template: templates/supervisor.yaml + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: gateway + asserts: + - equal: + path: kind + value: Deployment + template: templates/supervisor.yaml + - notContains: + path: spec.template.spec.containers[0].args + content: --node-supervisor + template: templates/supervisor.yaml + - notExists: + path: spec.internalTrafficPolicy + template: templates/supervisor-service.yaml + - it: rejects autoscaling in the node topology + template: templates/supervisor.yaml + set: + supervisor: + autoscaling: + enabled: true + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - failedTemplate: + errorMessage: supervisor.autoscaling.enabled requires supervisor_topology = gateway + - it: names the node topology in its refusals + template: templates/supervisor.yaml + set: + upstreamProxy: + url: http://proxy.example:3128 + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - failedTemplate: + errorMessage: supervisor_topology=node does not support upstream proxy settings + - it: attaches node supervisors to the external enforcer's supervisor network + template: templates/supervisor.yaml + set: + externalEnforcer: &supervisorNetworkEnforcer + enabled: true + namespace: openshell-enforcer + serviceAccountName: external-enforcer + network: + sandbox: + networkAttachment: openshell/sandbox-vf + nameservers: ["192.168.100.1"] + supervisor: + networkAttachment: openshell/supervisor-vf + resource: example.com/supervisor-vf + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: spec.template.metadata.annotations["k8s.v1.cni.cncf.io/networks"] + value: openshell/supervisor-vf@net1 + - equal: + path: spec.template.spec.containers[0].resources.requests["example.com/supervisor-vf"] + value: "1" + - equal: + path: spec.template.spec.containers[0].resources.limits["example.com/supervisor-vf"] + value: "1" + - contains: + path: spec.template.spec.containers[0].env + content: + name: OPENSHELL_SUPERVISOR_POOL_ADVERTISE_INTERFACE + value: net1 + - notContains: + path: spec.template.spec.containers[0].env + content: + name: OPENSHELL_SUPERVISOR_POOL_ADVERTISE_IP + valueFrom: + fieldRef: + fieldPath: status.podIP + - it: adds the supervisor network resource to the configured resources + template: templates/supervisor.yaml + set: + supervisor: + resources: + requests: + cpu: 250m + limits: + memory: 1536Mi + externalEnforcer: *supervisorNetworkEnforcer + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: spec.template.spec.containers[0].resources + value: + requests: + cpu: 250m + memory: 768Mi + example.com/supervisor-vf: "1" + limits: + cpu: "1" + memory: 1536Mi + example.com/supervisor-vf: "1" + - it: renders the supervisor network into the driver config + template: templates/gateway-config.yaml + set: + externalEnforcer: *supervisorNetworkEnforcer + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: 'supervisor = \{ network_attachment = "openshell/supervisor-vf", resource = "example.com/supervisor-vf" \}' + - it: keeps node supervisors on the Pod network without a supervisor network + template: templates/supervisor.yaml + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - notExists: + path: spec.template.metadata.annotations + - contains: + path: spec.template.spec.containers[0].env + content: + name: OPENSHELL_SUPERVISOR_POOL_ADVERTISE_IP + valueFrom: + fieldRef: + fieldPath: status.podIP + - equal: + path: spec.template.spec.containers[0].resources + value: + requests: + cpu: 250m + memory: 768Mi + limits: + cpu: "1" + memory: 1.5Gi + - it: ignores the supervisor network values without an external enforcer + template: templates/supervisor.yaml + set: + externalEnforcer: + network: + supervisor: + networkAttachment: openshell/supervisor-vf + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - notExists: + path: spec.template.metadata.annotations + - it: rejects a supervisor network with the app listener + template: templates/supervisor.yaml + set: + externalEnforcer: *supervisorNetworkEnforcer + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + openshell.supervisor.app_listener: + enabled: true + domain: services.example.com + openshell.drivers.kubernetes.sandbox_runtime.app_listener: + tls_secret_name: app-tls + asserts: + - failedTemplate: + errorMessage: externalEnforcer.network.supervisor does not support the supervisor app listener + - it: rejects a supervisor network resource without an attachment + template: templates/supervisor.yaml + set: + externalEnforcer: + enabled: true + namespace: openshell-enforcer + serviceAccountName: external-enforcer + network: + sandbox: + networkAttachment: openshell/sandbox-vf + nameservers: ["192.168.100.1"] + supervisor: + resource: example.com/supervisor-vf + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - failedTemplate: + errorMessage: externalEnforcer.network.supervisor.resource requires externalEnforcer.network.supervisor.networkAttachment diff --git a/deploy/helm/openshell/tests/supervisor_wiring_test.yaml b/deploy/helm/openshell/tests/supervisor_wiring_test.yaml index a9d757697f..b04755d3e2 100644 --- a/deploy/helm/openshell/tests/supervisor_wiring_test.yaml +++ b/deploy/helm/openshell/tests/supervisor_wiring_test.yaml @@ -4,6 +4,7 @@ suite: supervisor gateway wiring templates: - templates/certgen.yaml - templates/peer-role.yaml + - templates/external-enforcer-role.yaml - templates/statefulset.yaml - templates/gateway-config.yaml release: @@ -29,6 +30,25 @@ tests: csi: driver: csi.spiffe.io readOnly: true + - it: accepts the Broker with node-topology supervisors + template: templates/statefulset.yaml + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + openshell.gateway.spiffe_broker: + spiffe_id_prefix: spiffe://example.org/openshell + endpoint: https://spire-broker.spire.svc:8443 + server_spiffe_id_prefix: spiffe://example.org/spire/agent/k8s_psat/cluster + workload_api_socket_path: /spiffe-workload-api/spire-agent.sock + asserts: + - contains: + path: spec.template.spec.volumes + content: + name: spiffe-workload-api + csi: + driver: csi.spiffe.io + readOnly: true - it: refuses ambiguous Broker peer policies template: templates/statefulset.yaml set: @@ -89,6 +109,50 @@ tests: verbs: - get documentIndex: 0 + - it: lets the gateway list Pods only with a supervisor pod network + template: templates/peer-role.yaml + set: + externalEnforcer: + enabled: true + namespace: openshell-enforcer + serviceAccountName: external-enforcer + network: + sandbox: + networkAttachment: openshell/sandbox-vf + nameservers: ["192.168.100.1"] + supervisor: + networkAttachment: openshell/supervisor-vf + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - contains: + path: rules + content: + apiGroups: + - "" + resources: + - pods + verbs: + - list + documentIndex: 0 + - it: grants no Pod list without a supervisor pod network + template: templates/peer-role.yaml + set: + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - notContains: + path: rules + content: + apiGroups: + - "" + resources: + - pods + verbs: + - list + documentIndex: 0 - it: lets the gateway replace only the supervisor token in its Secret template: templates/peer-role.yaml set: @@ -109,6 +173,48 @@ tests: - get - patch documentIndex: 0 + - it: lets the gateway replace the external enforcer token and verify its Pods in its namespace + template: templates/external-enforcer-role.yaml + set: + externalEnforcer: + enabled: true + namespace: openshell-enforcer + serviceAccountName: external-enforcer + network: + sandbox: + networkAttachment: openshell/sandbox-vf + nameservers: ["192.168.100.1"] + gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node + asserts: + - equal: + path: metadata.namespace + value: openshell-enforcer + documentIndex: 0 + - equal: + path: rules + value: + - apiGroups: + - "" + resources: + - pods + verbs: + - get + - apiGroups: + - "" + resources: + - secrets + resourceNames: + - openshell-external-enforcer-token + verbs: + - get + - patch + documentIndex: 0 + - equal: + path: subjects[0].namespace + value: gateway + documentIndex: 1 - it: grants no supervisor Secret access without the topology template: templates/peer-role.yaml asserts: diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 809f992703..ba9314d7f9 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -73,6 +73,10 @@ supervisor: digest: "" # -- Shared supervisor listener IP. Use `::` for IPv6. listenAddress: 0.0.0.0 + # -- Refuse gateway-topology supervisors that attach without their + # pod-bound identity token. Node-topology supervisors always need it. Refer + # to the High Availability guide before enabling it on an upgrade. + requireIdentityToken: false # -- Shared supervisor pool members, used only when gatewayConfig selects # supervisor_topology = "gateway". The gateway always coordinates the shared # supervisor as a high-availability pool: when a member fails or leaves, @@ -80,14 +84,15 @@ supervisor: # workloads. 1 has no failover; use 2 or more to survive losing a member. # Only the supervisor Deployment's replica count depends on this value, so # changing it neither restarts the gateway nor replaces running members. - # Ignored when supervisor.autoscaling.enabled is true. Must not exceed - # replicaCount * supervisor.pool.maxMembersPerGateway. + # Ignored when supervisor.autoscaling.enabled is true or supervisor_topology + # = "node". Must not exceed replicaCount * supervisor.pool.maxMembersPerGateway. replicas: 1 pool: # -- Most sandboxes one supervisor runs, rendered as # [openshell.gateway.supervisor_pool] max_instances_per_member and passed # to each supervisor. Must be an integer from 1 to 1024. The gateway - # refuses a sandbox when every supervisor is full. + # refuses a sandbox when every supervisor is full. Ignored with + # supervisor_topology = "node", which uses 1024. maxInstancesPerMember: 128 # -- Most supervisors one gateway replica serves, rendered as # [openshell.gateway.supervisor_pool] max_members_per_gateway. Must be a @@ -143,10 +148,11 @@ supervisor: # integer from 30 to 300. Null leaves the gateway's pool default of 60 # seconds. recoveryTimeoutSeconds: 60 - # Pod security context for the shared supervisor Deployment, rendered only - # when gatewayConfig selects supervisor_topology = "gateway". On OpenShift, - # set the user and group IDs to null so the restricted-v2 SCC can assign the - # namespace range; ci/values-openshift-scc.yaml does this. + # Pod security context for the shared supervisor Deployment or DaemonSet, + # rendered only when gatewayConfig selects supervisor_topology = "gateway" or + # "node". On OpenShift, set the user and group IDs to null so the + # restricted-v2 SCC can assign the namespace range; + # ci/values-openshift-scc.yaml does this. podSecurityContext: # -- Require the shared supervisor to run as a non-root user. runAsNonRoot: true @@ -160,9 +166,18 @@ supervisor: # -- Seccomp profile applied to the shared supervisor pod. type: RuntimeDefault # -- Affinity rules for the shared supervisor pod, rendered only when - # gatewayConfig selects supervisor_topology = "gateway". Top-level affinity - # applies only to the gateway pod. + # gatewayConfig selects supervisor_topology = "gateway" or "node". Top-level + # affinity applies only to the gateway pod. affinity: {} + # -- Node selector for the shared supervisor pod. With + # supervisor_topology = "node", it must cover every node that can host + # sandboxes, and `externalEnforcer.enabled` adds + # `node-restriction.kubernetes.io/openshell-external-enforcer-ready: "true"`. + nodeSelector: {} + # -- Tolerations for the shared supervisor pod. With + # supervisor_topology = "node", tolerate every taint a sandbox template + # tolerates, such as `nvidia.com/gpu` on GPU nodes. + tolerations: [] network: # -- Name of an operator-owned ConfigMap with a `ca.crt` key containing additional destination CA certificates for sandbox supervisors. Empty disables additional destination trust. additionalCaConfigMapName: "" @@ -170,6 +185,44 @@ supervisor: # -- Workload boundary TLS listener port. boundaryPort: 5500 +# An external enforcer outside the sandbox enforces network policy and injects +# credentials. Enabling it runs every new sandbox in native-network mode and +# renders the Kubernetes driver's external_enforcer table. Experimental: it +# requires a gateway image built with the experimental feature. +externalEnforcer: + # -- Run new sandboxes in native-network mode under an external enforcer. + enabled: false + # -- Existing namespace the external enforcer runs in, distinct from the + # release namespace. The chart creates the external enforcer's token Secret + # and the gateway's Role there. + namespace: "" + # -- ServiceAccount in `namespace` the external enforcer's Pods run as. The + # gateway accepts the external enforcer token only beside a pod-bound token + # for it (audience `openshell-enforcer`). + serviceAccountName: "" + network: + # The only network of every new sandbox Pod. + sandbox: + # -- Multus NetworkAttachmentDefinition, as namespace/name or a name in + # the sandbox namespace. + networkAttachment: "" + # -- Extended resource the attachment's device plugin allocates, + # requested once per sandbox Pod. Empty requests none. + resource: "" + # -- The sandboxes' only DNS servers, answered by the external enforcer. + nameservers: [] + # Additional network sandbox runtimes reach their node's supervisor on. + # It must give each node's supervisor a fixed address, for example + # through static IPAM keyed by node. + supervisor: + # -- Multus NetworkAttachmentDefinition, as namespace/name or a name in + # the release namespace, attached to each supervisor as net1. Empty + # keeps runtimes on the supervisor Service ClusterIP. + networkAttachment: "" + # -- Extended resource the attachment's device plugin allocates, + # requested once per supervisor Pod. Empty requests none. + resource: "" + sandbox: image: # -- Default standalone sandbox image repository. diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 404cbfd454..0eae69a456 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -172,7 +172,10 @@ The normalized certificates augment the default bundled, system, or native roots used for sandbox destination TLS. Normal certificate-chain and hostname verification remains enabled. A configured CA can authenticate every policy-permitted endpoint whose certificate chains to that CA and matches the -requested hostname, so scope private CAs accordingly. +requested hostname, so scope private CAs accordingly. Agent processes trust +them too: `SSL_CERT_FILE`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`, +`GIT_SSL_CAINFO`, `NODE_EXTRA_CA_CERTS`, and `DENO_CERT` all name the sandbox's combined bundle, +which holds the system roots, the OpenShell CA, and these certificates. This setting is separate from all other trust domains: @@ -195,6 +198,14 @@ reads the mounted bundle and folds it into its system roots. Remote and custom compute drivers reject this setting because the compute-driver protocol does not carry the normalized material. +With a shared Kubernetes supervisor topology, each sandbox generation's launch +material carries the bundle instead of a ConfigMap. The bundle and +the supervisor OTLP TLS files (`ca_file`, `cert_file`, and `key_file`) together +must be at most 192 KiB; the gateway refuses a larger total at startup. Upgrade +the shared supervisors before you configure the bundle, because older +supervisors refuse launch material that carries it. To downgrade, remove the +bundle and stop and start every affected sandbox first. + ### Lifecycle and certificate rollover This is **global gateway configuration**, not a per-sandbox setting. Source @@ -238,6 +249,109 @@ bindings when this read boundary matters. Updating only the source ConfigMap does not trigger the gateway workload checksum, so explicitly restart or redeploy the gateway and then stop/start every affected sandbox. +## Native Network Mode + +Native-network mode is experimental. A gateway built without the experimental +feature bundle refuses to start with `external_enforcer` configured. Build it +with `cargo build -p openshell-gateway --features experimental`, or use +published Release Dev artifacts. + +With `[openshell.drivers.kubernetes.external_enforcer]` configured, every new +sandbox runs in native-network mode. An external enforcer on the sandbox +network enforces the sandbox's network policy, and the sandbox doesn't mediate +the agent's sockets: the agent opens TCP and UDP sockets over IPv4 and IPv6 +directly, and the enforcer filters them. The sandbox and supervisor Multus +networks exist only under this table, so no configuration attaches a sandbox to +a network that bypasses both the supervisor and an enforcer. Agents see these +differences: + +- DNS goes to the enforcer's resolvers in `network.sandbox.nameservers`. +- A connection to a blocked destination times out instead of failing with a + permission error. +- Denied connections produce no policy proposals. +- The agent trace relay is off. +- The image's `/etc/openshell/policy.yaml` is ignored. A sandbox with neither + its own nor a global policy gets the restrictive default policy, which blocks + all network access except provider endpoints. + +The driver schedules every sandbox Pod only to nodes labeled +`node-restriction.kubernetes.io/openshell-external-enforcer-ready=true`. The +enforcer must keep that label `true` on exactly the nodes where it enforces. +Until a node carries it, new sandbox Pods stay `Pending`. In the `node` +topology the Helm chart runs the node supervisors on the same nodes, so +removing the label from a node removes the node's supervisor, which leaves +every sandbox on it unreachable. Enable the `NodeRestriction` admission plugin +so a kubelet can't set the label on its own node. + +The mode works with `supervisor_topology = "gateway"` or `"node"`, and requires +`config_delivery_mode = "poll"`; the gateway refuses to start otherwise. In the +`gateway` topology each sandbox dials the supervisor Service's ClusterIP and +may be redirected to the supervisor that owns it, so the sandbox network must +route to the Service and to every supervisor Pod's runtime port. + +A sandbox runs only under the mode it was created in. After you add or remove +`external_enforcer`, the gateway stops the sandboxes created under the other +mode and refuses to restart them; delete and recreate them. + +The enforcer runs in its own namespace, `external_enforcer.namespace`, which +must differ from the supervisor's. It authenticates to the gateway with an +enforcer token. The gateway mints and renews it like the supervisor token and +writes it to the `external_enforcer.token_secret_name` Secret in that +namespace. The gateway accepts the enforcer token only with a Pod-bound +projected ServiceAccount token (audience `openshell-enforcer`) for +`external_enforcer.service_account_name` in that namespace, which it checks +with Kubernetes TokenReview, so the Secret alone doesn't admit a caller. An +enforcer can attach to the assignment stream and read and acknowledge sandbox +configuration only; it can't launch, take over, or act as a sandbox. + +With Helm, set `externalEnforcer.enabled`, `externalEnforcer.namespace`, +`externalEnforcer.serviceAccountName`, and `externalEnforcer.network`. The +namespace must already exist; the chart creates the +`-external-enforcer-token` Secret there and a Role that lets the +gateway update it and read the enforcer's Pods. Without the chart, create the +Secret and grant the gateway `get` and `patch` on it and `get` on Pods in that +namespace. + +A new sandbox's agent starts only after the enforcer accepts its +configuration. Until then the sandbox's `ConfigurationReady` condition reports +`EnforcerPending`, or `EnforcerRejected` with the enforcer's message. Without an +enforcer on the node, the sandbox fails when its provisioning deadline expires. +A policy update takes effect once both the supervisor and the enforcer apply +it; `openshell policy set --wait` waits for both and reports an enforcer +rejection as a failed revision. After a credential +rotation, new processes receive the rotated credentials once the enforcer +accepts them, even while it rejects a policy update. When the enforcer rejects an update of a running sandbox, the +`DesiredConfigurationReady` condition reports `EnforcerRejected`. + +The enforcer runs the policy's middleware, not the supervisor. Register only +middleware the enforcer serves under `[[openshell.supervisor.middleware]]`. +The gateway rejects policies that use built-in `openshell/` middleware in this +mode. + +The mode is safe only when the deployment guarantees all of the following: + +1. Every packet leaving the sandbox Pod, of any IP protocol, is checked against + the sandbox's policy, and everything else is dropped. +2. The Pod's source MAC and IP addresses are pinned, so spoofed packets are + dropped. +3. Nothing can open a new connection into the sandbox Pod. +4. Traffic between sandboxes is dropped. +5. The only supervisor address the Pod can reach is its own supervisor's + runtime port, and new connections to it are rate-limited per sandbox. +6. When the policy uses TLS interception, the enforcer terminates TLS and + publishes the CA that sandboxes trust. Trust it with + [`additional_ca_bundle`](#additional-destination-cas). +7. The workload network doesn't enforce Kubernetes NetworkPolicy. The driver + writes a deny-all egress NetworkPolicy for every workload Pod, which would + block all of the agent's traffic. +8. Only sandbox Pods request the workload network's `resource`. The enforcer + identifies a sandbox's network interface by the Pod that holds it. + +A stopped sandbox whose next runtime launches in native-network mode uses the +network its stored Pod template names. Recreate sandboxes created before the +workload network was set or before the gateway ran in native-network mode; +their policy updates never become current. + ## Migrate to schema version 2 Schema version 2 is an intentional breaking cutover. The gateway rejects files @@ -879,7 +993,7 @@ On SQLite, writers are serialized regardless of pool size, so a larger ceiling b ## Shared Supervisor Pool -`[openshell.gateway.supervisor_pool]` tunes the shared supervisor pool used with the Kubernetes driver's `supervisor_topology = "gateway"`. The Helm chart renders this table from `supervisor.*` values and rejects a hand-written one. +`[openshell.gateway.supervisor_pool]` tunes the shared supervisor pool used with the Kubernetes driver's `supervisor_topology = "gateway"` or `"node"`. The Helm chart renders this table from `supervisor.*` values and rejects a hand-written one. ```toml [openshell.gateway.supervisor_pool] @@ -894,7 +1008,7 @@ max_members_per_gateway = 32 | `max_instances_per_member` | `128` | `1` to `1024` | `supervisor.pool.maxInstancesPerMember` | | `max_members_per_gateway` | `32` | `1` or more | `supervisor.pool.maxMembersPerGateway` | -The gateway never places more than `max_instances_per_member` sandboxes on one supervisor and refuses a create when every supervisor is full. The pool runs at most live gateway replicas × `max_members_per_gateway` × `max_instances_per_member` sandboxes, never more than 131,072. Start each supervisor with the same cap through `--pool-max-instances` or `OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES`; the chart sets it. Values outside the ranges fail at startup. +The gateway never places more than `max_instances_per_member` sandboxes on one supervisor and refuses a create when every supervisor is full. The pool runs at most live gateway replicas × `max_members_per_gateway` × `max_instances_per_member` sandboxes, never more than 131,072. Start each supervisor with the same cap through `--pool-max-instances` or `OPENSHELL_SUPERVISOR_POOL_MAX_INSTANCES`; the chart sets it. With `supervisor_topology = "node"`, the chart sets `1024`; see [Run one supervisor per node](/kubernetes/high-availability#run-one-supervisor-per-node). Values outside the ranges fail at startup. ## OCSF JSONL Output @@ -989,7 +1103,7 @@ protocol = "http/protobuf" headers = { x-mlflow-experiment-id = "0" } ``` -Use an `https://` endpoint for TLS over either protocol. The gateway verifies the collector certificate against the system trust roots, or only against the PEM certificates in `ca_file` when it is set. Set `cert_file` and `key_file` together to present a PEM client certificate to a collector that requires one. The gateway reads these files at startup and fails to start if one is unreadable, larger than 64 KiB, or holds no usable PEM, if the key does not match the certificate, or if one is set for an `http://` endpoint. A relative path uses the gateway's working directory. Supervisors receive each distinct set of files once, however many tables share it, and the files they receive may total at most 192 KiB. A shared supervisor's launch credentials, these files and headers included, may total at most 256 KiB, so large headers alongside large TLS files can still stop sandboxes from launching on one. Compute drivers and supervisors use the same CA and client certificate for their own exports, and the agent trace relay uses its collector's. Supervisors receive the file contents with their launch credentials, never through the sandbox environment or file system, so the collector cannot tell a supervisor's exports from the gateway's by certificate. The private key is stored with each sandbox's launch credentials wherever its compute driver keeps them, such as a Kubernetes Secret. The VM driver receives the trace collector's file paths. A standalone compute driver reads its own with `--otlp-ca-file`, `--otlp-cert-file`, and `--otlp-key-file`. +Use an `https://` endpoint for TLS over either protocol. The gateway verifies the collector certificate against the system trust roots, or only against the PEM certificates in `ca_file` when it is set. Set `cert_file` and `key_file` together to present a PEM client certificate to a collector that requires one. The gateway reads these files at startup and fails to start if one is unreadable, larger than 64 KiB, or holds no usable PEM, if the key does not match the certificate, or if one is set for an `http://` endpoint. A relative path uses the gateway's working directory. Supervisors receive each distinct set of files once, however many tables share it, and the files they receive may total at most 192 KiB. A shared supervisor's launch credentials, these files, headers, and any additional destination CA included, may total at most 256 KiB, so large headers alongside large TLS files can still stop sandboxes from launching on one. Compute drivers and supervisors use the same CA and client certificate for their own exports, and the agent trace relay uses its collector's. Supervisors receive the file contents with their launch credentials, never through the sandbox environment or file system, so the collector cannot tell a supervisor's exports from the gateway's by certificate. The private key is stored with each sandbox's launch credentials wherever its compute driver keeps them, such as a Kubernetes Secret. The VM driver receives the trace collector's file paths. A standalone compute driver reads its own with `--otlp-ca-file`, `--otlp-cert-file`, and `--otlp-key-file`. The files are read once. To rotate a certificate, restart the gateway; running sandboxes keep the previous certificate until they restart. Supervisors and external compute drivers from an earlier release than the gateway reject launch credentials that carry TLS material, and an earlier VM driver rejects the TLS file flags, so when a collector sets TLS files, upgrade them with or before the gateway. A gateway rolled back to an earlier release cannot read the stored launch credentials of sandboxes created with TLS material, so delete and recreate those sandboxes after a rollback. @@ -1555,7 +1669,7 @@ The Kubernetes, Docker, Podman, and MicroVM driver tables accept two keys that t - `policy_dns_ipv6_egress` sets how mediated policy DNS answers AAAA queries: `auto` (default), `enabled`, or `disabled`. `auto` answers AAAA only when the supervisor network namespace has an IPv6 default route and no IPv4 default route. `disabled` answers AAAA with an empty response so dual-stack clients fall back to IPv4. - `nat64_prefixes` lists the NAT64 prefixes of the sandbox network as RFC 6052 CIDRs (`/32`, `/40`, `/48`, `/56`, `/64`, or `/96`). The supervisor applies the IPv4 SSRF rules to the IPv4 address embedded in any destination inside these prefixes. It always recognizes the well-known prefix `64:ff9b::/96` and also discovers the network prefix through `ipv4only.arpa` (RFC 7050), so set this key when the network uses a prefix that discovery cannot find. -With `supervisor_topology = "gateway"`, the Helm chart passes the Kubernetes keys to the shared supervisors. +With `supervisor_topology = "gateway"` or `"node"`, the Helm chart passes the Kubernetes keys to the shared supervisors. The gateway rejects an unknown mode or a malformed prefix at startup. @@ -1731,6 +1845,68 @@ provider_spiffe_workload_api_socket_path = "/spiffe-workload-api/spire-agent.soc # (hot-reloaded on change, e.g. via ConfigMap volume mount). # operator_namespace_file = "/etc/openshell/workspace-namespaces.json" +# Shared supervisor topology for new sandbox generations: "gateway" runs a +# replicated pool, and "node" runs one supervisor per node that hosts the +# sandboxes scheduled to its node. Omit it for a supervisor Pod per sandbox. +# Only the in-process Kubernetes driver supports it. Helm renders the +# shared_supervisor table and refuses a hand-written one. +# supervisor_topology = "node" +# [openshell.drivers.kubernetes.shared_supervisor] +# service_name = "openshell-supervisor" +# service_namespace = "openshell" +# runtime_port = 5500 +# token_secret_name = "openshell-supervisor-token" +# The ServiceAccount the supervisors run as in service_namespace. The gateway +# verifies the pod-bound token for it that accompanies the supervisor token, +# and in the "node" topology that token proves each supervisor's node. +# service_account_name = "openshell-supervisor" +# Refuse supervisors that attach without the pod-bound token. Helm renders +# supervisor.requireIdentityToken here; the "node" topology always requires it. +# require_identity_token = false + +# An external enforcer launches every new sandbox in native-network mode (see +# Native Network Mode). Helm renders this table from externalEnforcer and +# refuses a hand-written one. It requires supervisor_topology = "gateway" or +# "node" and config_delivery_mode = "poll". Don't allowlist the `v1.multus-cni.io` or +# `k8s.v1.cni.cncf.io` domains in `allowed_pod_annotations` while it is set. +# namespace is where the enforcer runs, distinct from +# shared_supervisor.service_namespace. The gateway keeps token_secret_name +# there current with the enforcer token and accepts that token only beside a +# pod-bound token for service_account_name there. +# [openshell.drivers.kubernetes.external_enforcer] +# namespace = "openshell-enforcer" +# token_secret_name = "openshell-external-enforcer-token" +# service_account_name = "external-enforcer" +# +# Multus network that replaces the cluster network of every new sandbox pod +# (`v1.multus-cni.io/default-network`), the extended resource its device +# plugin allocates, requested once on the agent container, and the sandboxes' +# only DNS servers (one to three, answered by the enforcer). The attachment +# must route to the supervisor Service, or, with network.supervisor, to each +# node supervisor's address on that network. Its CNI might not enforce the +# driver's NetworkPolicy fences. A bare `network_attachment` name resolves in +# each sandbox's namespace; with per-workspace namespaces, use +# `/` and let Multus namespace isolation allow that namespace. +# Changing `network_attachment` affects new sandboxes only. Drain sandboxes before +# removing or renaming `resource`: reconcile re-admits running sandboxes and +# suspends those that request a resource it no longer accepts. +# [openshell.drivers.kubernetes.external_enforcer.network.sandbox] +# network_attachment = "openshell/sandbox-vf" +# resource = "example.com/sriov_vf" +# nameservers = ["192.168.100.1"] +# +# Optional: the Multus network each supervisor joins as net1. In the "node" +# topology each sandbox dials its node supervisor's net1 address instead of the +# Service ClusterIP; in the "gateway" topology sandboxes still dial the Service. +# The gateway reads it from the supervisor Pod's network-status at launch and +# fails the launch without one. The address is fixed in the sandbox's boundary +# config, so the attachment must give each node's supervisor a stable address, +# for example through static IPAM keyed by node. The gateway needs list on Pods +# in service_namespace. It doesn't support the supervisor app listener. +# [openshell.drivers.kubernetes.external_enforcer.network.supervisor] +# network_attachment = "openshell/supervisor-vf" +# resource = "example.com/sriov_supervisor_vf" + [openshell.drivers.kubernetes.managed_ssh_ingress] enabled = true gateway_namespace = "openshell" @@ -1744,7 +1920,8 @@ boundary_port = 5500 The Kubernetes driver always creates the workload `NetworkPolicy` before releasing a sandbox Pod. Your cluster CNI must enforce ingress and egress `NetworkPolicy` in every sandbox namespace; the Kubernetes API does not verify -enforcement. +enforcement. With `external_enforcer`, the sandbox attachment's CNI decides whether the +policy applies to sandbox Pods. In managed workspace mode, the Kubernetes driver copies each explicitly named `image_pull_secrets` Secret from `namespace` into the managed workspace diff --git a/docs/how-it-works/sandboxes/runtimes.mdx b/docs/how-it-works/sandboxes/runtimes.mdx index 199894599b..22594bdef3 100644 --- a/docs/how-it-works/sandboxes/runtimes.mdx +++ b/docs/how-it-works/sandboxes/runtimes.mdx @@ -318,6 +318,7 @@ Only the OpenShell gateway and the Agent Sandbox controller should be able to ma | `supervisor_image` | `supervisor.image.*` | Override the supervisor image. | | `workspace_default_storage_size` | `server.workspaceDefaultStorageSize` | Default workspace PVC size. | | `workspace_storage_class` | `server.workspaceStorageClass` | `StorageClass` for workspace PVCs. Set this if the cluster has no default `StorageClass`. | +| `external_enforcer` | `externalEnforcer.*` | External enforcer that runs every new sandbox in native-network mode, with the Multus network that replaces each new sandbox pod's cluster network. See [gateway configuration](/how-it-works/gateways/configuration#native-network-mode) for its fields and the routing and drain requirements. | | `allowed_pod_annotations` | `gatewayConfig["openshell.drivers.kubernetes"].allowed_pod_annotations` | Pod annotation keys that sandbox templates may set, as exact keys or `/*` wildcards. Empty (default) rejects all template annotations. Keys under `openshell.ai` and `agents.x-k8s.io` are reserved and can't be allowlisted. | | `allowed_pod_labels` | `gatewayConfig["openshell.drivers.kubernetes"].allowed_pod_labels` | Pod label keys that sandbox templates may set, in the same format as `allowed_pod_annotations`. Empty (default) rejects all template labels. Labels select pods for NetworkPolicy rules and Services, so only allow keys that no other rule in the sandbox namespace selects on. | | `sandbox_uid` / `sandbox_gid` | `server.sandboxUid` / `server.sandboxGid` | Sandbox pod UID and GID. Takes priority over OpenShift SCC namespace annotations. `sandbox_gid` defaults to the UID. | diff --git a/docs/kubernetes/access-control.mdx b/docs/kubernetes/access-control.mdx index b938c7f5aa..570c62a16a 100644 --- a/docs/kubernetes/access-control.mdx +++ b/docs/kubernetes/access-control.mdx @@ -25,7 +25,8 @@ For how the CLI resolves gateways and stores credentials, refer to [Gateway Auth Kubernetes sandbox supervisors use gateway-issued session JWTs for sandbox-specific RPCs. A dedicated supervisor reads its preissued credential bundle from a mounted Secret. A shared supervisor receives each sandbox's bundle through its assignment -stream, authenticated with a separate supervisor-host JWT. See +stream, authenticated with a separate supervisor-host JWT and a Pod-bound +token for the supervisor's ServiceAccount. See [Getting the first credential](/about/architecture#getting-the-first-credential). The separate `IssueSandboxToken` bootstrap exchange remains available. When used, diff --git a/docs/kubernetes/high-availability.mdx b/docs/kubernetes/high-availability.mdx index 5bf5ba2a30..2e7a33ac98 100644 --- a/docs/kubernetes/high-availability.mdx +++ b/docs/kubernetes/high-availability.mdx @@ -598,7 +598,7 @@ replicas so sandboxes can fail over: gatewayConfig: openshell.drivers.kubernetes: # Creates a supervisor Deployment alongside the gateway. - # Per-workspace and per-node supervisor options are planned. + # Use supervisor_topology: node for one supervisor per node. supervisor_topology: gateway supervisor: @@ -617,6 +617,17 @@ supervisor: The chart creates the supervisor Deployment and connects it to the gateway. Tune the pool through the top-level `supervisor` values. +Each supervisor authenticates with a gateway-minted supervisor token and a +Pod-bound token for the chart's `-supervisor` ServiceAccount. Allow +only cluster administrators to create Pods that use that ServiceAccount or to +`create` its `serviceaccounts/token` subresource. + +Supervisors from earlier releases send no Pod-bound token, so the gateway +admits a supervisor without one until you set +`supervisor.requireIdentityToken=true`. Set it after an upgrade finishes +rolling every supervisor Pod; from then on, a copy of the token Secret alone +can't attach as a supervisor. + The chart sets no supervisor affinity by default. The example rule places each supervisor replica on a different node, so losing one node leaves another supervisor to take over. Replace `openshell` in `app.kubernetes.io/instance` @@ -743,6 +754,56 @@ helm install openshell ./openshell -n openshell \ -f openshell/values-scale-10k.yaml --set server.externalDbSecret= ``` +### Run one supervisor per node + +With `supervisor_topology: node`, the chart runs the shared supervisor as a +DaemonSet, and each sandbox is served by the supervisor on its workload's node. +The scheduler picks the node. A sandbox never moves to another node's +supervisor. In +[native-network mode](/how-it-works/gateways/configuration#native-network-mode), +the DaemonSet and every sandbox run only on nodes the enforcer labels +`node-restriction.kubernetes.io/openshell-external-enforcer-ready=true`. + +```yaml +gatewayConfig: + openshell.drivers.kubernetes: + supervisor_topology: node +``` + +Each supervisor's Pod-bound token also proves its node: the gateway accepts a +supervisor only for the node that the token's Pod runs on. The ServiceAccount +restriction above still applies: anyone who can create its Pods or tokens can +claim any node. We recommend running the API server with the `Node` authorizer +and the `NodeRestriction` admission plugin, so a compromised node's kubelet +cannot obtain tokens for another node's supervisor. + +If the scheduler places a workload on a node without an attached supervisor, +or no node accepts it within `runtime_bootstrap_grace_seconds`, the gateway +deletes the new sandbox or stops the restarted one. A supervisor must run on +every node that can host a sandbox. If sandbox templates tolerate node taints, +set the same tolerations in `supervisor.tolerations`; if they select a node pool, cover it with +`supervisor.nodeSelector`. GPU nodes usually need: + +```yaml +supervisor: + tolerations: + - key: nvidia.com/gpu + operator: Exists + effect: NoSchedule +``` + +The chart renders no PodDisruptionBudget or HPA for the DaemonSet and ignores +`supervisor.replicas`. It also ignores `supervisor.pool.maxInstancesPerMember` +and sets each supervisor's cap to 1024, so a supervisor accepts every sandbox +the kubelet admits on its node. Size `supervisor.resources` for the kubelet's +`maxPods` on your sandbox nodes. When a node's supervisor restarts, its sandboxes pause +until the replacement attaches within `supervisor.recoveryTimeoutSeconds`. +A lost node takes its sandboxes with it. + +Switching `supervisor_topology` between `gateway` and `node` terminates +running shared sandboxes at the recovery timeout. Restart them to run under +the new topology. + ## Next Steps - To expose the gateway through a highly available data path, refer to diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index 5720620c00..146d52db92 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -48,6 +48,8 @@ e2e-kubernetes-shared-supervisor-ha = ["e2e-kubernetes", "e2e-host-gateway"] # Scaling a one-member high-availability pool of shared supervisors to two # members and back. It upgrades the release, so it runs on its own release. e2e-kubernetes-shared-supervisor-scaling = ["e2e-kubernetes", "e2e-host-gateway"] +# One shared supervisor per node on a cluster of at least two nodes. +e2e-kubernetes-shared-supervisor-node = ["e2e-kubernetes", "e2e-host-gateway"] e2e-podman = ["e2e", "e2e-host-gateway", "e2e-local-container-driver"] e2e-podman-gpu = ["e2e-podman", "e2e-gpu"] e2e-oidc-pkce = [] diff --git a/e2e/rust/tests/additional_ca.rs b/e2e/rust/tests/additional_ca.rs index 99599b37d0..03de58a34d 100644 --- a/e2e/rust/tests/additional_ca.rs +++ b/e2e/rust/tests/additional_ca.rs @@ -26,6 +26,7 @@ const LIFECYCLE_READY_MARKER: &str = "additional-ca-lifecycle-ready"; const LIFECYCLE_DURABLE_MARKER: &str = "additional-ca-lifecycle-durable"; const LIFECYCLE_DURABLE_PATH: &str = "/sandbox/additional-ca-lifecycle-marker"; const ADDITIONAL_CA_VOLUME: &str = "openshell-additional-ca"; +const MANAGED_CONFIG_MAP_PREFIX: &str = "openshell-additional-ca-"; struct PortForwardGuard { child: Child, @@ -361,7 +362,7 @@ fn inspect_kubernetes_pod() -> Result { let managed_name = volume["configMap"]["name"] .as_str() .ok_or("managed destination CA ConfigMap name missing")?; - if !managed_name.starts_with("openshell-additional-ca-") + if !managed_name.starts_with(MANAGED_CONFIG_MAP_PREFIX) || volume["configMap"]["items"].as_array().is_none_or(|items| { items != &vec![serde_json::json!({"key": "ca.crt", "path": "ca.crt"})] }) @@ -448,6 +449,74 @@ fn inspect_kubernetes_pod() -> Result { Ok(format!("{namespace}/{managed_name}/{supervisor_name}")) } +fn kubernetes_shared_supervisor() -> bool { + std::env::var("OPENSHELL_E2E_KUBE_SUPERVISOR_TOPOLOGY").as_deref() == Ok("gateway") +} + +/// Shared supervisors receive the bundle in each generation's launch +/// material, so no managed ConfigMap or CA volume may appear in the sandbox +/// namespace or on the shared supervisor Pods. +fn inspect_kubernetes_shared_delivery() -> Result<(), String> { + let namespace = std::env::var("OPENSHELL_E2E_SANDBOX_NAMESPACE") + .map_err(|error| format!("sandbox namespace missing: {error}"))?; + let release_namespace = std::env::var("OPENSHELL_E2E_ADDITIONAL_CA_HELM_NAMESPACE") + .map_err(|error| format!("Helm namespace missing: {error}"))?; + + let config_maps = kubectl_json(&["-n", &namespace, "get", "configmaps", "-o", "json"])?; + let managed = config_maps["items"] + .as_array() + .ok_or("Kubernetes ConfigMap list missing items")? + .iter() + .filter_map(|config_map| config_map["metadata"]["name"].as_str()) + .filter(|name| name.starts_with(MANAGED_CONFIG_MAP_PREFIX)) + .collect::>(); + if !managed.is_empty() { + return Err(format!( + "shared supervisor topology created destination CA ConfigMaps: {managed:?}" + )); + } + + let workloads = kubectl_json(&["-n", &namespace, "get", "pods", "-o", "json"])?; + let supervisors = kubectl_json(&[ + "-n", + &release_namespace, + "get", + "pods", + "-l", + "app.kubernetes.io/component=supervisor", + "-o", + "json", + ])?; + let supervisor_pods = supervisors["items"] + .as_array() + .ok_or("shared supervisor Pod list missing items")?; + if supervisor_pods.is_empty() { + return Err("no shared supervisor Pods found".to_string()); + } + for pod in workloads["items"] + .as_array() + .ok_or("Kubernetes Pod list missing items")? + .iter() + .chain(supervisor_pods) + { + let carries_ca = pod["spec"]["volumes"].as_array().is_some_and(|volumes| { + volumes.iter().any(|volume| { + volume["name"] == ADDITIONAL_CA_VOLUME + || volume["configMap"]["name"] + .as_str() + .is_some_and(|name| name.starts_with(MANAGED_CONFIG_MAP_PREFIX)) + }) + }); + if carries_ca { + return Err(format!( + "Pod {} mounts destination CA material under the shared supervisor topology", + pod["metadata"]["name"] + )); + } + } + Ok(()) +} + #[cfg(feature = "e2e-vm")] fn inspect_vm_overlay() -> Result<(), String> { use sha2::{Digest, Sha256}; @@ -1051,7 +1120,12 @@ async fn additional_ca_trusts_matching_and_public_hosts_and_rejects_mismatch() { // Reaching the workload command and then using sandbox exec below requires // the supervisor's independently configured gateway callback mTLS path. - let kubernetes_identity = if driver == "kubernetes" { + let shared = driver == "kubernetes" && kubernetes_shared_supervisor(); + let kubernetes_identity = if shared { + inspect_kubernetes_shared_delivery() + .expect("shared supervisors receive the CA without ConfigMaps or mounts"); + None + } else if driver == "kubernetes" { Some(inspect_kubernetes_pod().expect("inspect Kubernetes ConfigMap and pod placement")) } else if driver == "vm" { #[cfg(feature = "e2e-vm")] @@ -1076,10 +1150,44 @@ async fn additional_ca_trusts_matching_and_public_hosts_and_rejects_mismatch() { } }; - replace_staged_material(driver, kubernetes_identity.as_deref()) + // Shared supervisors keep no staged copy in the cluster to tamper with. + if !shared { + assert_staged_material_tampering_fails_closed( + driver, + &mut sandbox, + kubernetes_identity.as_deref(), + policy_path, + &matching_url, + script.as_str(), + ) + .await; + } + + // Remove the sandbox whose startup trust and staged material were mutated + // before restoring delivery. For Kubernetes, remove the deliberately + // replaced immutable map so the driver's ensure path can recreate the + // exact gateway startup snapshot for the next sandbox. + sandbox.cleanup().await; + if !shared { + restore_staged_material(driver, kubernetes_identity.as_deref()) + .expect("restore destination trust after invalid-material check"); + } + + assert_configuration_removal_applies_on_restart(driver, policy_path, &matching_url).await; +} + +async fn assert_staged_material_tampering_fails_closed( + driver: &str, + sandbox: &mut SandboxGuard, + kubernetes_identity: Option<&str>, + policy_path: &str, + matching_url: &str, + script: &str, +) { + replace_staged_material(driver, kubernetes_identity) .expect("replace staged destination trust with invalid material"); if driver == "kubernetes" || driver == "vm" { - let fetch_argv = python_fetch_argv(driver, &matching_url); + let fetch_argv = python_fetch_argv(driver, matching_url); let fetch_argv = fetch_argv.iter().map(String::as_str).collect::>(); let output = sandbox .exec(&fetch_argv) @@ -1098,7 +1206,7 @@ async fn additional_ca_trusts_matching_and_public_hosts_and_rejects_mismatch() { } else if driver == "vm" { let mut retained_snapshot_sandbox = SandboxGuard::create_keep_with_args( &["--policy", policy_path], - &[python_binary_for_driver(driver), "-c", script.as_str()], + &[python_binary_for_driver(driver), "-c", script], READY_MARKER, ) .await @@ -1112,15 +1220,13 @@ async fn additional_ca_trusts_matching_and_public_hosts_and_rejects_mismatch() { } else { assert_invalid_staged_material_fails_closed(policy_path).await; } +} - // Remove the sandbox whose startup trust and staged material were mutated - // before restoring delivery. For Kubernetes, remove the deliberately - // replaced immutable map so the driver's ensure path can recreate the - // exact gateway startup snapshot for the next sandbox. - sandbox.cleanup().await; - restore_staged_material(driver, kubernetes_identity.as_deref()) - .expect("restore destination trust after invalid-material check"); - +async fn assert_configuration_removal_applies_on_restart( + driver: &str, + policy_path: &str, + matching_url: &str, +) { // Use a neutral, long-running main process so stop/start is the only // lifecycle transition. The exec calls below prove both destination trust // and gateway-authenticated control traffic independently of that process. @@ -1132,7 +1238,7 @@ async fn additional_ca_trusts_matching_and_public_hosts_and_rejects_mismatch() { ) .await .expect("create lifecycle sandbox using restored destination CA"); - let lifecycle_fetch_argv = python_fetch_argv(driver, &matching_url); + let lifecycle_fetch_argv = python_fetch_argv(driver, matching_url); let lifecycle_fetch_argv = lifecycle_fetch_argv .iter() .map(String::as_str) diff --git a/e2e/rust/tests/kubernetes_shared_supervisor_node.rs b/e2e/rust/tests/kubernetes_shared_supervisor_node.rs new file mode 100644 index 0000000000..bdecfdb6e5 --- /dev/null +++ b/e2e/rust/tests/kubernetes_shared_supervisor_node.rs @@ -0,0 +1,302 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#![cfg(feature = "e2e-kubernetes-shared-supervisor-node")] + +//! One shared supervisor per node (`supervisor_topology = "node"`) on a +//! cluster of at least two nodes. + +mod shared_supervisor; + +use std::collections::{BTreeMap, BTreeSet}; +use std::process::Stdio; +use std::time::Duration; + +use shared_supervisor::{ + ATTACH_TIMEOUT, HostEndpoint, SUPERVISOR_CONTAINER, call_host, counts_past, create, generation, + kubectl, kubectl_command, kubectl_json, main_process, owner_of, policy, release_namespace, + supervisor_pod_items, wait_for_owner, wait_until_attached, +}; + +/// Bound on a deleted node supervisor's replacement starting, attaching, and +/// re-adopting its node's instances. +const READOPT_DEADLINE: Duration = Duration::from_mins(3); +/// What the gateway answers a supervisor whose member ID is not its node. +const MEMBER_MISMATCH: &str = "is not the node its identity token proves"; +/// What a supervisor logs when the gateway accepts its stream. +const ATTACHED: &str = "gateway accepted the supervisor host"; +const FORGED_POD: &str = "openshell-e2e-forged-supervisor"; + +/// Running supervisor Pods by name, with the node each runs on. +async fn supervisor_nodes() -> BTreeMap { + supervisor_pod_items() + .await + .iter() + .filter(|pod| { + pod["metadata"]["deletionTimestamp"].is_null() && pod["status"]["phase"] == "Running" + }) + .filter_map(|pod| { + Some(( + pod["metadata"]["name"].as_str()?.to_string(), + pod["spec"]["nodeName"].as_str()?.to_string(), + )) + }) + .collect() +} + +/// `kubectl` with the harness's kubeconfig and context, for use in `Drop`. +fn blocking_kubectl(args: &[&str]) { + let mut command = std::process::Command::new("kubectl"); + for (flag, variable) in [ + ("--kubeconfig", "OPENSHELL_E2E_KUBECONFIG"), + ("--context", "OPENSHELL_E2E_KUBE_CONTEXT_ACTIVE"), + ] { + if let Some(value) = std::env::var(variable) + .ok() + .filter(|value| !value.trim().is_empty()) + { + command.arg(flag).arg(value); + } + } + let _ = command + .args(args) + .stdin(Stdio::null()) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); +} + +/// Keeps new Pods off a node until dropped. +struct Cordoned(String); + +impl Cordoned { + async fn new(node: &str) -> Self { + kubectl(&["cordon", node]).await; + Self(node.to_string()) + } +} + +impl Drop for Cordoned { + fn drop(&mut self) { + blocking_kubectl(&["uncordon", &self.0]); + } +} + +/// Deletes a test-created Pod when dropped. +struct TestPod(String); + +impl Drop for TestPod { + fn drop(&mut self) { + blocking_kubectl(&[ + "-n", + &release_namespace(), + "delete", + "pod", + &self.0, + "--ignore-not-found", + "--wait=false", + ]); + } +} + +async fn supervisor_logs(pod: &str) -> String { + let output = kubectl_command() + .args([ + "-n", + &release_namespace(), + "logs", + pod, + "-c", + SUPERVISOR_CONTAINER, + ]) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .output() + .await + .expect("spawn kubectl logs"); + String::from_utf8_lossy(&output.stdout).into_owned() +} + +#[tokio::test] +#[allow(clippy::too_many_lines)] +async fn each_workload_is_served_by_its_own_nodes_supervisor() { + let nodes = supervisor_nodes().await; + let distinct: BTreeSet<&String> = nodes.values().collect(); + assert!( + distinct.len() >= 2, + "the node topology needs supervisors on at least two nodes: {nodes:?}" + ); + wait_until_attached(&nodes.keys().cloned().collect::>()).await; + let endpoint = HostEndpoint::start().await; + let policy = policy(endpoint.port); + + // The first sandbox lands wherever the scheduler puts it; the second is + // kept off that node so the two run on different nodes. + let mut first = create(&policy).await; + let first_generation = generation(&first.name).await; + let first_node = first_generation + .workload_node + .clone() + .expect("the first workload is scheduled"); + let mut second = { + let _cordoned = Cordoned::new(&first_node).await; + create(&policy).await + }; + let second_generation = generation(&second.name).await; + let second_node = second_generation + .workload_node + .clone() + .expect("the second workload is scheduled"); + assert_ne!(first_node, second_node); + + let mut owners = Vec::new(); + for (sandbox, sandbox_generation, node) in [ + (&first, &first_generation, &first_node), + (&second, &second_generation, &second_node), + ] { + assert_eq!( + sandbox_generation.member.as_ref(), + Some(node), + "{} records its workload's node as its member", + sandbox.name + ); + let owner = wait_for_owner(&sandbox_generation.route).await; + assert_eq!( + nodes.get(&owner), + Some(node), + "{} is served by {owner}, not by the supervisor on {node}", + sandbox.name + ); + assert_eq!(call_host(sandbox, endpoint.port).await, "HA_OK"); + owners.push(owner); + } + let [first_owner, second_owner] = owners.as_slice() else { + unreachable!() + }; + + // Restarting the first node's supervisor re-adopts its running workload + // on the same node; the other node's sandbox keeps its owner. + let before = main_process(&first).await.expect("main process before"); + kubectl(&[ + "-n", + &release_namespace(), + "delete", + "pod", + first_owner, + "--wait=false", + ]) + .await; + let replacement = tokio::time::timeout(READOPT_DEADLINE, async { + loop { + if let Some((pod, _)) = supervisor_nodes() + .await + .into_iter() + .find(|(pod, node)| pod != first_owner && *node == first_node) + { + return pod; + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + }) + .await + .unwrap_or_else(|_| panic!("no supervisor replaced {first_owner} on {first_node}")); + wait_until_attached(std::slice::from_ref(&replacement)).await; + let adopted = tokio::time::timeout(READOPT_DEADLINE, async { + loop { + if owner_of(&first_generation.route).await.as_ref() == Some(&replacement) { + return; + } + tokio::time::sleep(Duration::from_secs(1)).await; + } + }) + .await; + assert!( + adopted.is_ok(), + "{replacement} did not re-adopt {} within {READOPT_DEADLINE:?}", + first_generation.route + ); + counts_past(&first, &before).await; + assert_eq!(generation(&first.name).await, first_generation); + assert_eq!(call_host(&first, endpoint.port).await, "HA_OK"); + assert_eq!( + owner_of(&second_generation.route).await.as_ref(), + Some(second_owner) + ); + + first.cleanup().await; + second.cleanup().await; +} + +#[tokio::test] +async fn a_supervisor_claiming_another_nodes_member_id_is_refused() { + let nodes = supervisor_nodes().await; + let mut by_node: BTreeMap<&String, &String> = BTreeMap::new(); + for (pod, node) in &nodes { + by_node.entry(node).or_insert(pod); + } + let mut pairs = by_node.into_iter(); + let (Some((node, pod)), Some((other_node, other_pod))) = (pairs.next(), pairs.next()) else { + panic!("the node topology needs supervisors on at least two nodes: {nodes:?}"); + }; + wait_until_attached(&[pod.clone(), other_pod.clone()]).await; + + // A copy of the genuine supervisor Pod on `node`: the same ServiceAccount, + // shared supervisor token, and identity token, but the other node's + // member ID and labels no Service or DaemonSet selects. + let mut forged = + kubectl_json(&["-n", &release_namespace(), "get", "pod", pod, "-o", "json"]).await; + forged["metadata"] = serde_json::json!({ + "name": FORGED_POD, + "namespace": release_namespace(), + "labels": {"app.kubernetes.io/name": FORGED_POD}, + }); + forged.as_object_mut().expect("Pod object").remove("status"); + let env = forged["spec"]["containers"][0]["env"] + .as_array_mut() + .expect("supervisor env"); + let member = env + .iter_mut() + .find(|entry| entry["name"] == "OPENSHELL_SUPERVISOR_POOL_MEMBER_ID") + .expect("pool member ID env"); + *member = serde_json::json!({ + "name": "OPENSHELL_SUPERVISOR_POOL_MEMBER_ID", + "value": other_node, + }); + let mut manifest = tempfile::Builder::new() + .suffix(".json") + .tempfile() + .expect("create Pod manifest"); + std::io::Write::write_all(&mut manifest, forged.to_string().as_bytes()) + .expect("write Pod manifest"); + let _forged = TestPod(FORGED_POD.to_string()); + kubectl(&[ + "-n", + &release_namespace(), + "create", + "-f", + manifest.path().to_str().expect("UTF-8 manifest path"), + ]) + .await; + + let refused = tokio::time::timeout(ATTACH_TIMEOUT, async { + loop { + let logs = supervisor_logs(FORGED_POD).await; + assert!( + !logs.contains(ATTACHED), + "the gateway accepted a supervisor on {node} claiming {other_node}:\n{logs}" + ); + if logs.contains(MEMBER_MISMATCH) { + return; + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + }) + .await; + assert!( + refused.is_ok(), + "the forged supervisor was not refused within {ATTACH_TIMEOUT:?}:\n{}", + supervisor_logs(FORGED_POD).await + ); + // The genuine member of the claimed node stays attached. + wait_until_attached(std::slice::from_ref(other_pod)).await; +} diff --git a/e2e/rust/tests/shared_supervisor/mod.rs b/e2e/rust/tests/shared_supervisor/mod.rs index 45eed8deef..c84ac8fdf2 100644 --- a/e2e/rust/tests/shared_supervisor/mod.rs +++ b/e2e/rust/tests/shared_supervisor/mod.rs @@ -20,6 +20,7 @@ pub const TEST_HOST: &str = "host.openshell.internal"; pub const SUPERVISOR_COMPONENT: &str = "app.kubernetes.io/component=supervisor"; const INSTANCE_ROUTE_ANNOTATION: &str = "openshell.ai/sandbox-runtime-supervisor-session"; const GENERATION_ANNOTATION: &str = "openshell.ai/sandbox-runtime-generation"; +const MEMBER_ANNOTATION: &str = "openshell.ai/sandbox-runtime-supervisor-member"; /// The workload's main process: it records its PID once and a counter that /// lives only in its memory every second. A restarted process would start /// counting from one again. @@ -350,6 +351,10 @@ pub struct Generation { pub route: String, pub runtime: String, pub workload_pod_uid: String, + /// Node the workload Pod is scheduled to. + pub workload_node: Option, + /// Pool member the generation is pinned to (node topology only). + pub member: Option, } pub async fn generation(name: &str) -> Generation { @@ -397,6 +402,8 @@ pub async fn generation(name: &str) -> Generation { .as_str() .expect("workload Pod UID") .to_string(), + workload_node: workload["spec"]["nodeName"].as_str().map(str::to_string), + member: annotations[MEMBER_ANNOTATION].as_str().map(str::to_string), } } diff --git a/proto/README.md b/proto/README.md index 7a313009cf..12581eca2f 100644 --- a/proto/README.md +++ b/proto/README.md @@ -58,7 +58,8 @@ identifies the service being exposed. - Requests whose primary resource is a workspace use `name`, not `workspace_scope`. - Document every request that permits an omitted selector. Current exceptions - are platform provider-profile scope and authenticated sandbox bootstrap. + are platform provider-profile scope, authenticated sandbox bootstrap, and the + native-network enforcer, which selects a sandbox by ID. ## Field and message design @@ -108,7 +109,9 @@ a gateway and the supervisor process it shares among its sandboxes: the supervisor attaches, the gateway sends complete assignment snapshots, and the supervisor reports what it hosts. It is a version-locked deployment protocol served on the gateway listener but authorized only for the gateway-minted -supervisor token (`auth_mode: "supervisor"`). It is not imported by +supervisor token (`auth_mode: "supervisor"`) and, in native-network mode, the +gateway-minted enforcer token, which attaches with the enforcer role and may +call only the enforcer's methods. It is not imported by `openshell.proto`, so SDK generation and gRPC reflection exclude it; the server's schema inventory test classifies it explicitly. `SandboxInstanceAssignment.launch_material` carries the existing diff --git a/proto/openshell.proto b/proto/openshell.proto index 4212445623..cce60d20c7 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -1398,6 +1398,10 @@ message SandboxStatus { // failures before a configured endpoint or credential could be selected. // Matching grant success or a policy, provider, or supervisor reset clears it. TokenGrantFailureObservation last_token_grant_failure = 17; + // Native-network mode: the external enforcer's admission of the current + // configuration. `instance_id` is the runtime generation it programmed. + // Present, PENDING at first, on sandboxes created in native-network mode. + SandboxConfigurationAdmission enforcer_admission = 18; } // User-facing sandbox condition derived from platform or gateway observations. @@ -3055,7 +3059,8 @@ message RevealSecretResponse { google.protobuf.Timestamp value_update_time = 2; } -// Get sandbox provider environment request. +// Get sandbox provider environment request. A native-network enforcer must +// set both capabilities. message GetSandboxProviderEnvironmentRequest { // The sandbox ID. string sandbox_id = 1; @@ -3132,6 +3137,9 @@ message GetSandboxProviderEnvironmentResponse { // require acknowledgment for declared or previously activated external // stable credentials; ordinary legacy delivery does not require it. bool supports_stable_placeholder_environment_keys = 12; + // Native-network enforcer callers only. The placeholder the workload + // receives for each static_credential_bindings key at this revision. + map workload_placeholders = 13; } // Receivers treat UNSPECIFIED and unknown values as secret. @@ -3156,6 +3164,10 @@ message ProviderEnvironmentValue { // provider revisions. Set only for STATIC_CREDENTIAL values whose binding // carries a workload_credential_handle. bool stable_placeholder = 6; + // Native-network enforcer callers only. The placeholder the workload + // receives for this STATIC_CREDENTIAL key at this provider revision. Not + // secret: the workload's environment holds it. + string workload_placeholder = 7; } // Complete provider environment state delivered to a supervisor. This is the diff --git a/proto/sandbox.proto b/proto/sandbox.proto index 4699ee244d..9964166063 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -389,12 +389,16 @@ message NetworkBinary { reserved "harness"; } -// Request to get sandbox settings by sandbox name. +// Request to get sandbox settings. message GetSandboxConfigRequest { // Workspace scope. Select one named workspace; authenticated sandbox callers may omit it during bootstrap. openshell.datamodel.v1.WorkspaceSelector workspace_scope = 3; string name = 1; - // Policy capabilities of sandbox-authenticated callers receiving config. + // Native-network enforcer callers only, which select the sandbox by ID and + // leave `name` and `workspace_scope` empty. Rejected from other callers. + string sandbox_id = 4; + // Policy capabilities of sandbox-authenticated and enforcer callers + // receiving config. repeated string supported_capabilities = 5; } @@ -466,6 +470,8 @@ message SandboxConfigSnapshot { uint64 settings_revision = 17; // Explicit application ingress allowlist. Absent means no app routes. repeated SandboxServiceRoute service_routes = 18; + bool activation_pending = 19; + uint64 enforcer_provider_env_revision = 20; } // Response containing effective sandbox settings and policy, projected from @@ -517,6 +523,14 @@ message GetSandboxConfigResponse { // Monotonic revision of the sandbox-scoped settings row. uint64 settings_revision = 17; repeated SandboxServiceRoute service_routes = 18; + // Native-network mode: the gateway holds this instance's first activation + // until the enforcer accepts it. Neither activate nor report a rejection; + // poll again. Never set for an admitted configuration. + bool activation_pending = 19; + // Native-network mode: the provider environment revision the enforcer + // accepted for this runtime generation, or 0. A supervisor installs a new + // provider revision only once it equals this. + uint64 enforcer_provider_env_revision = 20; } // Gateway-declared service installed by a supervisor; this does not grant diff --git a/proto/supervisor_host.proto b/proto/supervisor_host.proto index f0275a803f..282a275cf5 100644 --- a/proto/supervisor_host.proto +++ b/proto/supervisor_host.proto @@ -24,9 +24,18 @@ import "options.proto"; // each member only the instances it owns, and moves an instance only when its // owner fails or leaves. A pool host releases an instance a snapshot omits // without stopping its workload; only `stop_routes` stops workloads. +// +// In native-network mode an external enforcer also attaches, with the +// gateway-minted enforcer token and `HostHello.enforcer` set. It is never a +// pool member: its snapshots (`pool = false`) list every desired instance by +// `sandbox_id` and `generation` only, and it reports `applied_revision` only. +// It acknowledges each instance's enforcement through +// `ReportSandboxConfiguration`. While it holds back a policy update, it may +// accept the current `provider_env_revision` with the policy fields it already +// accepted, so credential rotation continues. service SupervisorHost { - // Supervisor-initiated assignment stream. Only the gateway-minted - // supervisor token may call it. + // Host-initiated assignment stream. Only the gateway-minted supervisor and + // enforcer tokens may call it. rpc Attach(stream HostMessage) returns (stream HostGatewayMessage) { option (openshell.options.v1.authorization) = { auth_mode: "supervisor" @@ -71,6 +80,17 @@ message HostHello { // redials the replica that last accepted it. Hosts that predate // HostRedirect never set it. bool accepts_redirect = 4; + // Enforcer hosts only. The gateway rejects a hello whose resolvers don't + // equal the configured workload nameservers, or that is set on a supervisor + // token, or missing on an enforcer token. + EnforcerHello enforcer = 5; +} + +// The external enforcer of native-network sandboxes. +message EnforcerHello { + // DNS servers (IPv4 or IPv6, port 53) the enforcer answers on; the + // sandboxes' only resolvers. + repeated string workload_nameservers = 1; } // One member of a supervisor pool. @@ -120,7 +140,10 @@ message AssignmentSnapshot { uint64 revision = 1; repeated SandboxInstanceAssignment instances = 2; // The host is a pool member: release omitted instances instead of - // stopping them, and stop only the routes listed in `stop_routes`. + // stopping them, and stop only the routes listed in `stop_routes`. False + // for an enforcer, which clears the enforcement of omitted instances. An + // enforcer that declared `enforced_shards` receives only the instances + // pinned to nodes of those shards; an unpinned instance is in none. bool pool = 3; // Pool hosts only: routes whose sandbox is stopping or deleted; the host // stops their workloads if it still hosts them. @@ -204,6 +227,20 @@ message HostStatus { // A pool host is shutting down: the gateway moves its instances to other // members at once. Its workloads keep running. bool leaving = 3; + // Enforcers only: the shards this replica holds, on every status; each + // status replaces the previous declaration. Unset, the enforcer receives + // every instance. + EnforcedShards enforced_shards = 4; +} + +// The node shards an enforcer replica holds. A node's shard is the FNV-1a +// 32-bit hash of its name's UTF-8 bytes, modulo count. An instance's node is +// the node its workload runs on. +message EnforcedShards { + // The number of shards nodes hash into; 0 matches no node. + uint32 count = 1; + // In any order; repeats are ignored. + repeated uint32 ids = 2; } // Lifecycle phase of a hosted sandbox instance. diff --git a/rfc/0012-isolation-backend/README.md b/rfc/0012-isolation-backend/README.md index 85385bdc50..61629e6391 100644 --- a/rfc/0012-isolation-backend/README.md +++ b/rfc/0012-isolation-backend/README.md @@ -320,7 +320,7 @@ struct PendingDnsQuery { Every backend may use the same supervisor-owned mediation libraries or services; the source does not require a backend-specific policy engine. -Shared implementations isolate each boundary's state and enforcement. Failure or teardown of one boundary cannot weaken another. Network-mediation unavailability never enables direct egress. +Shared implementations isolate each boundary's state and enforcement. Failure or teardown of one boundary cannot weaken another. Network-mediation unavailability never enables direct egress. The only exception is [native-network mode](#native-network-mode). ### Binary identity @@ -345,7 +345,7 @@ If binary identity cannot be resolved, the connection is denied. `ResolveError` Every identity field used for authorization is obtained by a trusted component from boundary or kernel state, rather than accepted as a workload claim. The result is bound to the active boundary and accepted connection; a transport tuple or workload-supplied identifier alone is not authoritative. Workload-supplied identity may be retained only as non-authorizing diagnostic context. If attribution is ambiguous or any required identity field cannot be established, the connection is denied. -Binary identity is mandatory conformance: RFC 0002 makes it part of the outbound-policy baseline. There is no capability flag and no mode that exempts a backend from resolving identity. +Binary identity is mandatory conformance: RFC 0002 makes it part of the outbound-policy baseline. There is no capability flag and no mode that exempts a backend from resolving identity for the connections it accepts; see [Native-network mode](#native-network-mode). ### The supervisor sequence @@ -389,6 +389,10 @@ Whenever a boundary ends, the backend terminates remaining workload processes an The contract fixes the roles; each compute driver decides where they run. Components may be co-located with the workload or hosted in trusted services, and one component may implement multiple roles. Every arrangement preserves the same lifecycle, interfaces, and invariants. Actual containment depends on the workload's kernel relationship to the trusted components. The non-normative [driver placement guide](./driver-placement.md) describes the supported mappings. +### Native-network mode + +*Amendment.* A backend may stop mediating agent egress only when a protected resource claim says an external enforcer enforces the sandbox's network policy ([RFC 0029](../0029-external-network-enforcer/README.md)). For agent egress in that mode, invariant 1, the network-mediation clause of invariant 3, the network-mediation sentence of invariant 6, and binary identity don't apply, and the supervisor calls `confirm` without connecting the boundary's network-mediation source (step 4 of its sequence). Every other control and invariant applies, and workload input can't select or change the mode. RFC 0029 also defines the selection, the behavior of the built-in backend, and the enforcer's requirements. + ## Conformance Every admitted backend and compute driver must pass tests for the six contract invariants plus descriptor verification, lifecycle ordering, runtime operations, and failure semantics. @@ -443,4 +447,4 @@ That would make known deployments explicit, but it would also encode current pla ## Open questions -None. +- Should the conformance suite gain a native-network profile that checks the in-boundary controls the mode keeps? diff --git a/rfc/0018-multi-sandbox-ha-supervisors/README.md b/rfc/0018-multi-sandbox-ha-supervisors/README.md index 81dfa7a96e..5690a7b9ae 100644 --- a/rfc/0018-multi-sandbox-ha-supervisors/README.md +++ b/rfc/0018-multi-sandbox-ha-supervisors/README.md @@ -6,6 +6,7 @@ links: - https://github.com/ai-openshell/openshell/issues/4311 - https://github.com/ai-openshell/openshell/issues/2385 - https://github.com/ai-openshell/openshell/pull/3661 + - https://github.com/ai-openshell/openshell/issues/6026 --- # RFC 0018 - Multi-sandbox and HA Supervisors @@ -71,7 +72,7 @@ Each deployment answers two questions: **where the supervisor runs** (per worksp | Model | One supervisor serves | Good | Hard | | --- | --- | --- | --- | | Per workspace | A pool for one workspace | Trust and quotas stay inside the workspace. Fewer Pods. | One failure hits the whole pool. Small workspaces pay for spare capacity. | -| Per node | The sandboxes on one node (DaemonSet) | Traffic stays on the node. Pod count follows node count. | One failure hits the node, possibly across workspaces. No ready standby on the node. Fits poorly with backends that move sandboxes between nodes. | +| Per node | The sandboxes on one node (DaemonSet) | Traffic stays on the node. Pod count follows node count. The kubelet's Pod limit, not a supervisor cap, bounds its sandboxes. | One failure hits the node, possibly across workspaces. No ready standby on the node. Fits poorly with backends that move sandboxes between nodes. Its resources must fit the node's Pod limit. | | Per sandbox (today) | One sandbox, with an optional warm standby | Smallest failure. Simplest isolation. | Most Pods. Slow cold start. | | Per gateway | A group tied to one gateway replica | Easy to run as a group. | Gateway rollouts and scale-in also move the group. Needs its own identity and spare capacity. | @@ -138,6 +139,7 @@ sequenceDiagram How it stays safe: - **Identity is checked.** The gateway's compute driver (for Kubernetes, `openshell-driver-kubernetes`) verifies the candidate's service account token with the Kubernetes TokenReview API and checks that the candidate may serve this sandbox; labels, namespace, and reachability prove nothing. The gateway then issues a short-lived `RecoveryGrant` bound to the candidate's key, sandbox, run, and new epoch. Launch credentials never authorize a takeover, and each candidate gets new TLS keys. +- **Each shared supervisor proves its Pod.** It presents a pod-bound token for the supervisor service account, which the gateway checks with TokenReview and a live-Pod lookup. In the per-node model the member ID must be that Pod's node. Run the `Node` authorizer and `NodeRestriction` admission plugin so a compromised node cannot obtain tokens for another node's supervisor. - **A missing heartbeat is not proof.** A new owner is reserved only after the old one released, its lease expired, or the runtime proved it cut the old one off. - **The runtime enforces it.** It accepts only the newer epoch, closes old channels, and stays frozen until activation. A database row alone cannot stop a live socket. - **If in doubt, stop.** If the runtime cannot freeze or verify enforcement, it stops the agent. @@ -172,6 +174,7 @@ During resume: - **The network fence needs work.** Today a Kubernetes NetworkPolicy lets only supervisors in the sandbox's own namespace reach it. A per-node or per-gateway supervisor usually lives in another namespace, so it would be blocked. Changing that policy in place stops every sandbox in the namespace, so each model needs its own reviewed policy instead. - **One IP for many sandboxes.** All traffic from a shared supervisor leaves from one Pod IP. Outside firewalls and logs can no longer tell sandboxes apart by IP. - **Sharing a process.** Each sandbox still gets its own policy, credentials, connections, logs, and limits inside the shared supervisor. A bug or compromise in that process can still reach every sandbox it serves, which a separate Pod would prevent. +- **Per node.** An attacker who controls one node can affect only that node's sandboxes. Its supervisor can claim only its own node's member ID (section 3), capacity is per member, and runtime traffic stays on the node. ### 5. Workload identity @@ -216,12 +219,13 @@ New settings choose the model, recovery mode, allowed fallbacks, spare capacity, | Workload node or runtime lost | Restart if policy allows. Process memory is lost. | | Workload node drain | Draining evicts the workload Pods too, so this is the node lost case in every model. | | Supervisor upgrade, scale-in, or drain of a supervisor-only node | Stop new assignments, hand each session over with fencing within the grace period, then stop. | +| Per-node supervisor rollout or crash | No handover. The node's sandboxes freeze and resume when the new Pod on that node attaches within the runtime's recovery timeout. | | Sandbox stop or delete, or authority revoked | Cancel grants. Cleanup wins over a pending recovery and does not touch other sessions. | Operations notes: - Draining a gateway does not drain supervisors, and the reverse. -- A per-node supervisor uses a supervisor on another node only if the operator allows it. +- A per-node sandbox never uses a supervisor on another node. - Spread supervisors across nodes and reserve resources for them. Extra Pods during an upgrade do not replace a standby for crashes. Pod disruption budgets do not prevent crashes ([Kubernetes disruptions](https://kubernetes.io/docs/concepts/workloads/pods/disruptions/)). - Show operators who owns each sandbox, how recoveries went, and spare capacity. Keep sandbox IDs out of metric labels. - Measure how long agents stay frozen, and publish recovery times for each backend. @@ -244,7 +248,7 @@ This work targets the Kubernetes driver only, and all of it sits behind a Kubern 4. Measure recovery time and noisy neighbors, then **decide which models to implement** and which is the default. Record the decision in this RFC. 5. Release the chosen models behind opt-in settings, with docs and a rollback path. -Some details are left to implementation and are out of scope for this RFC: how a per-node supervisor is bound to a sandbox, whether the lease is per replica or per sandbox, how launch material reaches a shared or replacement supervisor, and how the lease is renewed. +Some details are left to implementation and are out of scope for this RFC: whether the lease is per replica or per sandbox, how launch material reaches a shared or replacement supervisor, and how the lease is renewed. ## Risks @@ -281,4 +285,4 @@ Some details are left to implementation and are out of scope for this RFC: how a We are not picking one model over the others. Teams have different requirements for failure scope, isolation, and security, so one choice cannot fit every deployment. All four models share the safety rules in this RFC, so adding a model later does not change those rules. -Implementation starts with the per-gateway model, which is already in progress. We will add the per-node, per-workspace, or warm-standby per-sandbox models when a deployment needs them, each behind its own opt-in setting and only after it passes the failure tests. +Implementation starts with the per-gateway model, which is already in progress. The per-node model follows, for deployments that need node isolation. We will add the per-workspace or warm-standby per-sandbox models when a deployment needs them, each behind its own opt-in setting and only after it passes the failure tests. diff --git a/rfc/0029-external-network-enforcer/README.md b/rfc/0029-external-network-enforcer/README.md new file mode 100644 index 0000000000..202e039bd0 --- /dev/null +++ b/rfc/0029-external-network-enforcer/README.md @@ -0,0 +1,457 @@ +--- +authors: + - "@Gal-Zaidman" +state: draft +links: + - https://github.com/ai-openshell/openshell/issues/6024 +--- + +# RFC 0029 - External Policy Enforcer + +## Summary + +Let an external policy enforcer, instead of the supervisor, enforce a +sandbox's network policy and inject its credentials. The external policy +enforcer attaches to the gateway on the existing `SupervisorHost` stream with +a separate external policy enforcer role and token. It learns which sandbox +generations exist from that stream, reads their configuration and provider +environment through the existing supervisor RPCs, and reports what it enforces +with `ReportSandboxConfiguration`. The gateway keeps the supervisor and the +external policy enforcer in step: a generation's agent doesn't start until the +external policy enforcer accepts its configuration, the supervisor doesn't +install a credential revision the external policy enforcer hasn't accepted, +and a policy revision stays pending until both have applied it. + +To give the external policy enforcer the agent's traffic, sandboxes it serves +run in native-network mode: the agent's sockets belong to the kernel and leave +on the network interface the external policy enforcer owns, without the +supervisor's proxy. The operator selects the mode by configuring the +Kubernetes driver's `external_enforcer`. Without an attached external policy +enforcer, new sandboxes stay pending rather than run unenforced. + +## Motivation + +Many products enforce network policy outside the workload, for example on a +device that owns each sandbox's network interface. Deployments that run one +want it to enforce the OpenShell policy rather than duplicate that enforcement +in the sandbox supervisor. To do so, the external policy enforcer needs each +sandbox's effective policy and credentials, and OpenShell needs to know the +external policy enforcer applied them before the agent runs, to prevent the +agent from running unenforced. OpenShell has no way to hand either to an +external component today. + +The stock data path also defeats such an external policy enforcer. The sandbox +runtime intercepts every socket the agent opens and the supervisor proxies the +connection, so all agent traffic leaves from the supervisor's address. An +external policy enforcer on the wire sees one source for every sandbox on a +node and can't apply each sandbox's policy. + +## Non-goals + +- How the external policy enforcer filters traffic or injects credentials on + the wire. +- A stable public API for external policy enforcers: the external policy + enforcer uses the private `SupervisorHost` service and is released alongside + it. +- Enforcing filesystem or process policy externally; the supervisor keeps + enforcing both in the sandbox. +- Compute drivers other than Kubernetes, and dedicated supervisors. +- Choosing the mode or the pod network per sandbox; both are deployment + decisions. + +## Proposal + +### Overview + +| Component | Owns | Credential | +| ------------------------ | -------------------------------------------------------------------------------------------------------------------- | ------------------------------- | +| Gateway | Desired state, the holds, and the two-sided status. | — | +| Supervisor host | Its assigned instances: launch, runtime control, `exec`, SSH, filesystem and process policy. | Supervisor token. | +| External policy enforcer | Network policy and credential injection for every native-network instance. | External policy enforcer token. | +| Gateway interceptor | Refuses requests the external policy enforcer can't honor, as in [RFC 0010](../0010-gateway-interceptors/README.md). | Gateway-minted extension token. | + +The gateway trusts the external policy enforcer to report what it enforces. +The external policy enforcer receives each sandbox's policy and provider +credentials, but never launch material, takeover grants or sandbox tokens, and +it can't act as a supervisor. + +Users see three differences from a stock sandbox. A new sandbox waits in +`EnforcerPending` until the external policy enforcer accepts it, or reports +`EnforcerRejected` with the external policy enforcer's message. `openshell policy set --wait` returns once both the supervisor and the external policy +enforcer apply the revision, and fails when the external policy enforcer +rejects it. A policy using a feature the external policy enforcer can't honor +is refused at the API. + +```mermaid +sequenceDiagram + participant U as User + participant G as Gateway + participant D as Kubernetes driver + participant E as External policy enforcer + participant S as Supervisor + participant A as Agent + U->>G: CreateSandbox + G->>G: store restrictive default policy + G->>D: provision generation + D->>D: schedule Pod to a node the external policy enforcer marks ready + E->>G: Attach (HostHello with EnforcerHello) + G-->>E: AssignmentSnapshot lists the generation + E->>G: GetSandboxConfig, GetSandboxProviderEnvironment + E->>G: ReportSandboxConfiguration ACCEPTED + S->>G: GetSandboxConfig (activation_pending until accepted) + S->>A: start the agent + A->>E: egress on the external policy enforcer's interface +``` + +### Native-network mode + +**Selection.** The mode is driver configuration: + +```toml +[openshell.drivers.kubernetes.external_enforcer] +namespace = "openshell-enforcer" +token_secret_name = "openshell-external-enforcer-token" +service_account_name = "external-enforcer" + +[openshell.drivers.kubernetes.external_enforcer.network.sandbox] +network_attachment = "openshell-sandboxes/sandbox-vf" +resource = "example.com/sandbox-vf" +nameservers = ["192.168.100.1"] + +# Optional. +[openshell.drivers.kubernetes.external_enforcer.network.supervisor] +network_attachment = "openshell/supervisor-vf" +resource = "example.com/supervisor-vf" +``` + +With `external_enforcer` configured, every new sandbox runs in +native-network mode, and a sandbox runs only under the mode it was created +in. `network.sandbox` makes a Multus network attachment the workload Pod's +only network, with an extended resource such as an SR-IOV device as its +interface. The optional `network.supervisor` attaches supervisors to a +network; in the node topology it points each sandbox runtime at its node +supervisor's address there. Both live under `external_enforcer` because neither is safe without +one: a sandbox network the supervisor doesn't mediate and no external policy +enforcer filters would leave egress unenforced. + +The mode requires a shared supervisor topology of [RFC +0018](../0018-multi-sandbox-ha-supervisors/README.md) and +`config_delivery_mode = "poll"`; the gateway refuses to start otherwise. In +both topologies the workload dials its supervisor, and the external policy +enforcer makes the supervisor's address reachable over the sandbox network. +The driver launches a sandbox only after its workload Pod is scheduled, and +records the node. It schedules workload Pods, and node supervisors, only to +nodes the external policy enforcer labels +`node-restriction.kubernetes.io/openshell-external-enforcer-ready=true`, and +refuses pod annotations that would add a network interface the external policy +enforcer doesn't own. The gateway reads the mode and the resolvers at startup, +and they can't change while it runs. + +**Data path.** The driver marks each instance with the protected resource +claim `openshell.native_network`, delivered to both the supervisor and the +sandbox runtime, which must agree. With the claim, the sandbox runtime stops +intercepting the agent's socket calls, so the kernel owns the agent's sockets. +Every other control is unchanged, including Landlock, the socket-domain +allowlist and the other seccomp blocks, `exec`, SSH and the freeze on control +loss, and the runtime emits one OCSF event recording the mode. The supervisor +starts neither the egress proxy nor policy DNS, and doesn't offer the agent +trace relay. Instead, the driver points the workload's DNS at the resolvers, +so the external policy enforcer sees names as well as connections. The +supervisor still writes the workload's trust files, whose bundle includes the +external policy enforcer's CA. + +### Connecting the external policy enforcer + +**Identity.** The driver keeps the external policy enforcer token in +`token_secret_name` in the external policy enforcer's own namespace, and the +gateway accepts that token only beside a Pod-bound token for +`service_account_name` there. The external policy enforcer needs nothing from +the supervisor's namespace. + +**Reporting.** The external policy enforcer reports through the supervisor's +`ReportSandboxConfiguration`, with the same rules: it reports `ACCEPTED` or +`REJECTED` with the `policy_version`, `policy_hash`, `config_revision` and +`provider_env_revision` it programmed. A report for another instance is +`FAILED_PRECONDITION`, one that doesn't match the current configuration is +`ABORTED`, and a rejection doesn't revoke an earlier acceptance. The gateway +stores the result in a new `SandboxStatus.enforcer_admission`, separate from +the supervisor's admission. + +The report differs from the supervisor's in three ways. + +- It names the runtime generation rather than a supervisor instance. +- Its rejection message reaches users, because the operator trusts the + external policy enforcer. +- The supervisor reports loading a revision separately with + `ReportPolicyStatus`, while the external policy enforcer has no such call. + Its acceptance lets the revision become current once the supervisor has + loaded it too, and its rejection of a newer revision marks that revision + failed. + +**Teardown.** Teardown isn't gated: when a generation leaves the snapshot, +the external policy enforcer removes its enforcement. + +**Replicas.** The external policy enforcer can run several replicas, and the +gateway takes any replica's report as the external policy enforcer's. Without +shards, every replica's stream receives the same snapshot and splitting work +between replicas is the external policy enforcer's concern; with +[node shards](#node-shards-optional), each replica receives only the +generations on its nodes. + +### Keeping the supervisor and external policy enforcer in step + +**Initial policy.** In stock OpenShell, the supervisor reads a sandbox's +policy from its image when it starts, or falls back to the restrictive +default, and writes it to the gateway. In this mode the external policy +enforcer must accept a policy before the workload can reach its supervisor, so +the gateway stores the restrictive default when it creates a sandbox with +neither its own nor a global policy, and the image's policy file isn't read. + +**Activation hold.** Until the external policy enforcer first accepts a +native-network generation, the supervisor waits without reporting a rejection, +and the sandbox's `ConfigurationReady` condition reports `EnforcerPending`. If +the external policy enforcer rejected the current configuration, the +configuration is unadmitted with its message and the condition reports +`EnforcerRejected`. After the first acceptance the hold no longer applies, +including across a supervisor takeover; the external policy enforcer keeps +enforcing the configuration it accepted until it accepts a newer one. + +**Two-sided policy status.** A sandbox's current policy version advances only +to the lowest version both the supervisor and the external policy enforcer +have applied, and `GetSandboxPolicyStatus` and `ListSandboxPolicies` report +the newer revision `PENDING` until then. + +**Credential install hold.** The supervisor's configuration carries the +provider revision the external policy enforcer accepted, and a native-network +supervisor doesn't install a newer one, so new processes don't present +placeholders the external policy enforcer doesn't know, outside the startup +window described in [Risks](#risks). This is why the mode requires poll +delivery: under push delivery the supervisor would acknowledge a revision it +hasn't installed. While the external policy enforcer holds back a policy +update, it may accept the current provider revision under the policy it +already enforces, so a rejected update doesn't stall credential rotation. + +**Middleware.** The supervisor runs no network middleware in this mode. +Middleware the external policy enforcer serves is registered as ordinary +supervisor middleware, so the gateway's existing `Describe` and +`ValidateConfig` checks apply, and policies naming built-in `openshell/` +middleware are refused. + +**Policy refusals.** An external policy enforcer may not support every policy +feature. It should also register as a gateway interceptor, as in +[RFC 0010](../0010-gateway-interceptors/README.md), and refuse policy and +provider requests it can't enforce, so users get the error from the API +instead of from a held sandbox. Anything that reaches a sandbox anyway is +reported `REJECTED`, and the holds keep the agent from running under it. + +Every failure leaves the agent stopped or restricted: + +| Situation | Result | +| --- | --- | +| No external policy enforcer attached | New generations stay `EnforcerPending` until the provisioning deadline; running sandboxes keep running. | +| No replica declares a node's shard | New generations on that node stay `EnforcerPending`; running ones keep the enforcement they have. | +| External policy enforcer rejects a new generation | The configuration is unadmitted with the external policy enforcer's message. | +| External policy enforcer hasn't applied a policy revision | The revision stays `PENDING`. | +| Credential rotation the external policy enforcer doesn't know | The supervisor doesn't install it. | +| Resolvers differ from the driver's | The external policy enforcer's hello is rejected. | +| Push delivery configured | The gateway refuses to start. | +| Sandbox from the other mode | The driver suspends it and refuses its restart. | + +### Security and deployment requirements + +The mode is safe only when the external policy enforcer: + +- denies all sandbox traffic by default, as the driver's NetworkPolicy + fences do in stock mode; +- checks every packet leaving the sandbox, of any IP protocol, against the + sandbox's policy and drops the rest; +- answers the workload's DNS at `network.sandbox.nameservers`; +- accepts traffic from a sandbox's interface via workload's source addresses only (anti-spoofing); +- admits no new inbound connections and drops sandbox-to-sandbox traffic; +- lets the workload reach only the supervisors' runtime port, rate-limited; +- terminates TLS itself when the policy intercepts TLS, publishing the CA the + sandbox trusts; +- injects the credentials of the sandbox's providers; +- doesn't accept a network interface whose previous holder it hasn't + cleared, and reports only for sandboxes it enforces. + +The sandbox network must have the external policy enforcer on its path and +must route to the supervisor's address. The driver still writes its deny-all +egress NetworkPolicy for every workload Pod, so the sandbox network must not +enforce Kubernetes NetworkPolicy; enforcing what those policies define in stock +mode is the external policy enforcer's responsibility. The external policy enforcer runs in its own +namespace under its dedicated service account, and only its Pods may run as +that account or read its token Secret. OpenShell can't verify these requirements; the deployment +documentation lists them. + +### Node shards (optional) + +Shards are optional: a replica that declares none receives every sandbox. +They let several replicas split the nodes, so each receives only its share. + +- A replica declares a shard `count` and its shard `ids` in + `HostStatus.enforced_shards`, on every status. +- A node's shard is `fnv1a_32(node_name) % count`. A sandbox's node is the + node its workload runs on, in either supervisor topology; a restart can + move it to another node and shard. +- The gateway sends the replica only sandboxes on nodes of its shards, and + a whole snapshot when the declaration changes. +- The gateway doesn't place, fence or rebalance shards; that is the external + policy enforcer's decision. + +When it declares shards, the external policy enforcer must: + +- use one shard count on every replica; +- let one replica at a time write a node, and stop a replica's writes before + another takes its shards; +- remove enforcement only on nodes of its own shards; +- adopt a taken-over node's enforcement and clean up sandboxes deleted or + moved off the node while no replica held the shard; +- keep every shard held, or new sandboxes on uncovered nodes stay + `EnforcerPending`. + +### Amendment to RFC 0012 + +[RFC 0012](../0012-isolation-backend/README.md) gains a native-network +section: a backend may stop mediating agent egress only when a protected +resource claim says an external policy enforcer enforces the sandbox's network +policy. For agent egress in that mode, invariant 1, the network-mediation +clause of invariant 3, the network-mediation sentence of invariant 6, and +binary identity don't apply, and the supervisor confirms the runtime without +connecting the network mediation source. Every other control and invariant +applies, and workload input can't select or change the mode. + +## Implementation plan + +The mode needs only the gateway supervisor topology of +[RFC 0018](../0018-multi-sandbox-ha-supervisors/README.md), which is already +on `main`. Support for the node topology lands separately, with that topology. The mode +ships behind the gateway's `experimental` feature until it has run end to end +against an external policy enforcer. Each phase below ships its docs and tests +and is inert without `external_enforcer`: + +1. Selection: the `external_enforcer` table, its sandbox and supervisor + networks and their validation, the push-delivery refusal, the claim, the + resolvers, the restrictive default policy, and the ready-node selector. +2. Data path: the supervisor without the egress proxy, policy DNS or trace + relay, and the sandbox runtime's reduced notification filter. +3. External policy enforcer identity: the external policy enforcer token, its + role, the method allow-list, the Secret, and the Pod-bound identity token. +4. External policy enforcer session: `EnforcerHello`, external policy enforcer + sessions in the supervisor host controller, the snapshot rules, each + generation's node, and the shard declaration and snapshot filter. +5. Holds: `GetSandboxConfig` by sandbox ID, the external policy enforcer's + report, the activation and credential install holds, two-sided status, + `workload_placeholder`, and the middleware rules. +6. A reference external policy enforcer, kept outside the core build. + +Validation: unit tests for Pod rendering, admission, the claim, the +resolvers, the filter, the skipped supervisor runtimes, the token, the +snapshot rules, the shard filter and its resend, and each hold; Helm unit +tests for the chart values; the stock sandbox and Kubernetes e2e unchanged +without the settings; and the full path against an external policy enforcer +that meets the requirements, including a supervisor Pod replacement and the +loss of the replica holding a node's shard. + +## Risks + +- **The external policy enforcer is trusted.** OpenShell trusts it to + implement the network controls the supervisor implements in stock mode, + including L7 rules, binary identity, middleware and credential injection, + and to refuse what it doesn't implement, as in + [Policy refusals](#keeping-the-supervisor-and-external-policy-enforcer-in-step). + An external policy enforcer that accepts without enforcing, or a deployment + that misses a requirement, leaves egress unenforced, and OpenShell can't + detect it. +- **Availability depends on the external policy enforcer.** New sandboxes + don't start while no external policy enforcer is attached, and an external + policy enforcer that stops answering DNS breaks name resolution for every + sandbox on its node. `EnforcerPending` and the provisioning deadline make + the first visible. +- **Policy windows.** A policy change, or a supervisor takeover, takes effect + only after both the supervisor and the external policy enforcer apply it. + Until both do, the new revision is reported `PENDING`, and the sandbox can + run under either the previous policy or the new one. Requests with + credential placeholders the external policy enforcer doesn't know yet fail + closed. +- **Misconfigured networks strand sandboxes.** A sandbox network that can't + reach the supervisor, or a supervisor network without stable addresses, + fails launches until the recovery timeout. The debug guide shows how to + check a Pod's network status. + +## Alternatives + +### Do nothing + +Without this mode, an external policy enforcer can only sit on the +supervisor's network, where every sandbox on a node shares the supervisor's +source address, so it can't apply each sandbox's policy. Deployments that +need one stay off OpenShell. + +### Other ways to select the mode + +The external policy enforcer could declare at gateway startup that it enforces +the network policy, and the declaration would select the mode. That needs the +external policy enforcer reachable before the gateway starts and a second +channel from the gateway to the external policy enforcer. The activation hold +already ties the mode to an external policy enforcer: configuring the mode +without one leaves new sandboxes pending, not unenforced. + +The mode could also be a new isolation backend name. It changes a few +behaviors of the built-in sandbox runtime and keeps everything else, so a new +backend would duplicate process launch, identity, and every other control. + +### A separate policy-provider service + +A new gRPC service the gateway calls to program each sandbox, with its own +capability negotiation, reconciliation loop and status. It duplicates the +supervisor protocol's desired state, admission and authentication, and puts +a synchronous dependency in the gateway's policy handlers. + +### The external policy enforcer as a supervisor + +The external policy enforcer could reuse the supervisor token, or connect once +per sandbox as a sandbox's supervisor does. Either way it would hold launch +material and sandbox tokens it shouldn't, could take over instances, and would +cost the gateway one session per sandbox per external policy enforcer. A role +claim on the supervisor token doesn't fix this: during a rolling upgrade, an +older replica that ignores the claim accepts the external policy enforcer as a +supervisor. + +### Gateway-assigned nodes + +The gateway could assign nodes to replicas itself, with per-node owner +records in the supervisor pool, rebalancing, a handover delay and a write +fence sent in `HostAccepted`. This puts placement, fencing and durable +records in the gateway for one consumer, and ties the fence to gateway view +staleness. The external policy enforcer can instead elect a writer per shard +with platform primitives such as Kubernetes Leases. + +## Prior art + +- Envoy's xDS protocol has the control plane push versioned configuration and + each data plane acknowledge or reject every version. The control plane + tracks what each consumer applied instead of assuming delivery; the external + policy enforcer's `ACCEPTED` and `REJECTED` reports and the two-sided policy + status follow the same model. +- Kubernetes NetworkPolicy is declared centrally and enforced by the cluster's + network plugin, and a cluster whose plugin doesn't implement it silently + ignores it. The activation hold avoids that failure: without an external + policy enforcer, sandboxes stay pending instead of running unenforced. +- Kubernetes controllers elect a single writer with a Lease and step down + before it expires; external policy enforcer replicas can hold one per shard + the same way. +- [RFC 0012](../0012-isolation-backend/README.md) defines the mediation + requirement this mode is the exception to. +- [RFC 0018](../0018-multi-sandbox-ha-supervisors/README.md) defines the + supervisor host, the pool and its snapshots, and the shared topologies + this mode depends on. +- [RFC 0009](../0009-supervisor-middleware/README.md) and [RFC + 0010](../0010-gateway-interceptors/README.md) define the middleware registry + the external policy enforcer's middleware joins and the interceptors its + refusals use; [RFC 0023](../0023-credential-issuer-service/README.md) + defines the provider environment and its placeholders. + +## Open questions + +None. diff --git a/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index 9351671c0d..22af14774d 100644 --- a/skills/debug-openshell-cluster/SKILL.md +++ b/skills/debug-openshell-cluster/SKILL.md @@ -647,19 +647,25 @@ kubectl -n openshell get pod -o jsonpath='{.spec.containers[0].vol kubectl -n openshell get pod -o jsonpath='{.spec.volumes[?(@.name=="gateway-state")]}{"\n"}' ``` -At sandbox creation or restart, the Kubernetes driver creates or verifies an -immutable, content-addressed ConfigMap in the target sandbox namespace. Its -name binds the effective gateway identity and normalized trust digest. The -managed ConfigMap must have `openshell.ai/managed-by=openshell`, the matching +At sandbox creation or restart of a dedicated-supervisor generation, the +Kubernetes driver creates or verifies an immutable, content-addressed +ConfigMap in the target sandbox namespace. Its name binds the effective +gateway identity and normalized trust digest. The managed ConfigMap must have `openshell.ai/managed-by=openshell`, the matching `openshell.ai/gateway-id` label, and an `openshell.ai/additional-ca-generation` annotation. Different trust generations intentionally coexist so running sandboxes retain their startup -trust. The supervisor Pod mounts the ConfigMap read-only at +trust. The dedicated supervisor Pod mounts the ConfigMap read-only at `/etc/openshell/tls/additional/ca-bundle.pem` and receives `--additional-ca-bundle` for that path; the immutable flag plus the driver's per-creation digest and exact-byte validation close deletion/recreation races after the API check. +With the shared supervisor topology, the driver creates no ConfigMap and the +shared supervisor Pod has no mount. Each generation's launch material carries +the bundle, and the shared supervisor writes it to that sandbox's private +directory as `additional-ca.pem`. Older shared supervisors refuse launch +material carrying the bundle; upgrade them before configuring it. + Kubernetes RBAC cannot restrict `create` by `resourceNames` or restrict `get` by a name prefix. When this feature is enabled, the chart grants the gateway service account ConfigMap `get`/`create` in the shared sandbox namespace. In @@ -1475,6 +1481,47 @@ kubectl -n logs -l openshell.ai/sandbox-id=,open --tail=200 | grep -E 'sandbox-supervisor-|Supervisor takeover' ``` +With `supervisor_topology = "node"`, `-supervisor` is a DaemonSet +and each Pod's member ID is its node name; see the +[per-node supervisor guide](https://docs.nvidia.com/openshell/latest/kubernetes/high-availability#run-one-supervisor-per-node). +A supervisor OOM-killed on a dense node needs larger `supervisor.resources`. +The Sandbox's `openshell.ai/sandbox-runtime-supervisor-member` annotation +records its node. Until the workload Pod is scheduled, the runtime logs +`Runtime-initiated control cannot reach the supervisor; retrying`. + +With `externalEnforcer.enabled` and `supervisor_topology = "gateway"`, the +driver also launches only once the workload Pod is scheduled, and records the +node in the Sandbox's `openshell.ai/sandbox-runtime-node` annotation; enforcer +shards select sandboxes by it. Sandboxes dial the supervisor Service's +ClusterIP, so the sandbox network must route to it and to every supervisor +Pod's runtime port. + +With `externalEnforcer.network.supervisor.networkAttachment` set, each node +supervisor joins that Multus network as `net1` (annotation +`k8s.v1.cni.cncf.io/networks`), requests +`externalEnforcer.network.supervisor.resource`, and advertises `net1`'s address +(`OPENSHELL_SUPERVISOR_POOL_ADVERTISE_INTERFACE=net1`). The driver reads that +address from the node supervisor's `k8s.v1.cni.cncf.io/network-status` at +launch and gives it to the sandbox instead of the Service ClusterIP. The launch +rolls back with `no Ready supervisor runs on node`, `has no single IPv4 address +on network`, or `report different addresses` in the gateway's `sandbox-runtime +launch on the scheduled node failed; rolling back` log. A supervisor restart must +keep the same `net1` address, or that node's sandboxes lose their supervisor. + +```bash +kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor \ + --field-selector spec.nodeName= \ + -o jsonpath='{.items[*].metadata.annotations.k8s\.v1\.cni\.cncf\.io/network-status}' +``` + +```bash +kubectl -n openshell get daemonset,pod -l app.kubernetes.io/component=supervisor -o wide +kubectl get sandboxes.agents.x-k8s.io -A \ + -o custom-columns=NAME:.metadata.name,MEMBER:'.metadata.annotations.openshell\.ai/sandbox-runtime-supervisor-member' +kubectl -n openshell logs daemonset/-supervisor --prefix --tail=200 \ + | grep -E 'gateway accepted the supervisor host|could not open the supervisor host stream|gateway assignment stream failed' +``` + Each sandbox instance runs on one member, and a live owner keeps it. A member's console log names an instance by its route (the Sandbox's `openshell.ai/sandbox-runtime-supervisor-session` annotation) at the end of @@ -1739,6 +1786,13 @@ credential failures. | Kubernetes gateway pod crash loops | Missing secret, bad DB URL, bad TLS config | `kubectl -n openshell logs deployment/openshell -c openshell-gateway` or `kubectl -n openshell logs statefulset/openshell -c openshell-gateway` | | Mutating RPCs return `UNAVAILABLE` with "timed out waiting for a concurrent mutation" | Advisory-lock contention, a full lock pool on one replica (4 connections unless `database_lock_max_connections` is set), a slow PostgreSQL, or older gateways still running during an upgrade | `openshell_server_mutation_lock_timeouts_total`, `openshell_server_mutation_lock_connections_in_use` against its capacity, the `detail` field of `mutation lock acquisition timed out` in gateway logs, `mutation lock held longer than the lock wait timeout` warnings and `openshell_server_mutation_lock_hold_seconds`, the `pg_locks` query in Step 6 | | RPCs fail after about 5 seconds with `UNAVAILABLE` `DATABASE_UNAVAILABLE` or "database unavailable: pool timed out" | PostgreSQL unreachable or not answering, or every data-pool connection busy | `database health check` warnings and `/readyz` on the gateway, PostgreSQL logs, `database_max_connections` and the connection sizing in the High Availability guide | +| With `externalEnforcer.enabled`, new sandbox Pods stay `Pending` with `didn't match Pod's node affinity/selector` and no node supervisor runs on the expected node | The driver selects and the chart's supervisor DaemonSet runs only on nodes labeled `node-restriction.kubernetes.io/openshell-external-enforcer-ready=true`, and the enforcer has not set it on any schedulable node | `kubectl get nodes -L node-restriction.kubernetes.io/openshell-external-enforcer-ready`; the enforcer's node-labeling logs; `kubectl -n describe pod ` | +| With `externalEnforcer.enabled`, every sandbox on one node stops responding and the node has no supervisor Pod | The enforcer removed `node-restriction.kubernetes.io/openshell-external-enforcer-ready` from the node, so the supervisor DaemonSet deleted its Pod there | `kubectl get nodes -L node-restriction.kubernetes.io/openshell-external-enforcer-ready`; the enforcer's node-labeling logs; `kubectl -n openshell get pods -o wide` | +| With `externalEnforcer.enabled`, a sandbox's agent never starts and `ConfigurationReady` reports `EnforcerPending` or `EnforcerRejected` | The enforcer has not accepted the sandbox's configuration: it isn't attached to the gateway, can't read the enforcer token, doesn't enforce the sandbox's node, or rejected the configuration (the condition message gives its reason) | `kubectl -n get secret -external-enforcer-token`; a `supervisor host attached` gateway log with `role=Enforcer`; the enforcer's logs for its attach error and the sandbox ID | +| With `externalEnforcer.enabled`, the enforcer's calls fail with `enforcer identity token is required`, `enforcer identity token is invalid`, or `this gateway accepts no enforcer` | The enforcer Pod sends no projected ServiceAccount token with audience `openshell-enforcer`, runs as a ServiceAccount other than `externalEnforcer.serviceAccountName`, or runs outside `externalEnforcer.namespace` | `kubectl -n get pod -o jsonpath='{.spec.serviceAccountName}'`; the `external_enforcer` line of the rendered `gateway.toml`; a `host identity verification enabled` gateway startup log with `role=Enforcer` | +| With `externalEnforcer.enabled`, the gateway exits at startup with `external_enforcer requires a gateway built with the experimental feature` | Native-network mode is experimental and the gateway image is a stable build | Use a Release Dev gateway image or build `openshell-gateway` with `--features experimental` | +| With `externalEnforcer.enabled`, the gateway exits at startup with `requires config_delivery_mode = "poll"` | Native-network mode needs poll delivery so the supervisor waits for the enforcer's acceptance | Set `config_delivery_mode = "poll"` under `[openshell.gateway]` | +| With `externalEnforcer.enabled`, a policy is rejected with `built-in middleware ... isn't enforced in native-network mode` | The supervisor runs no proxy in this mode, so `openshell/` middleware can't run | Use middleware the enforcer serves, registered under `[[openshell.supervisor.middleware]]` | | Kubernetes gateway pod Running but never Ready, logging `database unreachable; retrying` | The gateway started while PostgreSQL was unreachable and waits for it | PostgreSQL pod and Service endpoints, the host and port in the database URL, network policy between the gateway and PostgreSQL | | Mutating RPCs return `INTERNAL` with "could not open a mutation lock connection" | PostgreSQL out of connection slots, restarting, or unreachable | `openshell_server_mutation_lock_errors_total`, PostgreSQL logs, `SELECT count(*) FROM pg_stat_activity` against `max_connections`, `database_max_connections` and `database_lock_max_connections`, the connection sizing in the High Availability guide | | `helm upgrade` fails with an `autoscaling.*` message | HPA values invalid: missing `resources.requests` (or `resources.limits`), `maxReplicas` above 1 without `server.externalDbSecret` (or on a StatefulSet without `workload.allowMultiReplicaStatefulSet`), no metric target, or min/max out of order. "`minReplicas` and `maxReplicas` are not set" means `--reuse-values` kept a release without the chart's autoscaling defaults | Fix the values named in the error; upgrade with `--reset-then-reuse-values` instead of `--reuse-values` | @@ -1749,9 +1803,13 @@ credential failures. | OpenShift gateway pod fails to start with an SCC/`runAsUser` error (e.g. `unable to validate against any security context constraint`) | Chart's default `podSecurityContext`/`securityContext` hardcodes `runAsUser`/`fsGroup`, which the restricted-v2 SCC rejects; it must instead inject the namespace-assigned UID/GID range | `oc -n openshell describe pod `; deploy with `podSecurityContext: null` and clear `securityContext.runAsUser` (see `deploy/helm/openshell/ci/values-openshift-scc.yaml`) | | OpenShift `-supervisor` Deployment never creates pods after setting `supervisor_topology = "gateway"` (SCC `runAsUser`/`fsGroup` not in the namespace range) | `supervisor.podSecurityContext` defaults `runAsUser`, `runAsGroup`, and `fsGroup` to 65534, outside the namespace's assigned UID/GID ranges | `kubectl -n openshell get events --field-selector reason=FailedCreate`; compare with the `openshift.io/sa.scc.*` annotations from `oc describe ns openshell`; set `supervisor.podSecurityContext.runAsUser`, `.runAsGroup`, and `.fsGroup` to `null`, as `deploy/helm/openshell/ci/values-openshift-scc.yaml` does, and keep `runAsNonRoot` and `seccompProfile` | | Shared sandboxes stay `Starting` or report `unavailable` readiness with `supervisor_topology = "gateway"`, gateway logs say no shared supervisor host is connected | The `-supervisor` Pod cannot reach or authenticate to the gateway: wrong `OPENSHELL_TLS_CA`, the `-supervisor-token` Secret is missing or still empty (gateway logs `wrote the supervisor token Secret` once it has delivered a token; `no usable supervisor token` in the supervisor means it has not; right after a fresh install the kubelet can take about 90 seconds to project the written token into the already-ready Pod, so launches can be refused for no live pool member until the supervisor logs `gateway accepted the supervisor host`), or the gateway was deployed without TLS or without the sandbox-JWT signing key | `kubectl -n openshell logs deployment/-supervisor` for `gateway accepted the supervisor host` or a refusal (a refusal or startup failure naming `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` or `_ADVERTISE_IP` means the Pod lacks its member identity; the chart sets them from the Pod name and IP); gateway logs for `supervisor host attached`, `wrote the supervisor token Secret`, or `failed to write the supervisor token Secret`; `kubectl -n openshell get secret -supervisor-token -o jsonpath='{.metadata.annotations}'` shows the token expiry; the gateway refuses to start the topology without TLS or `gateway_jwt` | +| A node supervisor logs `could not open the supervisor host stream` with `is not the node its identity token proves` (`supervisor_topology = "node"`) | The Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` is not its `spec.nodeName` | `kubectl -n openshell get pod -o jsonpath='{.spec.nodeName}'` and the Pod's `OPENSHELL_SUPERVISOR_POOL_MEMBER_ID` env | +| Sandbox disappears after create, or a restart ends stopped (`supervisor_topology = "node"`). Gateway logs show `sandbox-runtime launch on the scheduled node failed; rolling back` (for example with `the shared supervisor "" is not attached or has no room`), or, once `runtime_bootstrap_grace_seconds` passes, `rolled back stale fail-closed sandbox-runtime bootstrap` (create) or `suspending stale sandbox-runtime restart bootstrap` (restart) | The workload Pod stayed Pending, or the scheduler bound it to a node whose supervisor is missing, not yet attached, or full: a node taint (such as `nvidia.com/gpu` on GPU nodes) that sandbox tolerations cover and `supervisor.tolerations` doesn't, a node outside `supervisor.nodeSelector`, or a supervisor still rolling out | `kubectl -n describe pod ` for scheduling events; `kubectl describe node ` for its taints; `kubectl -n openshell get pod -l app.kubernetes.io/component=supervisor -o wide` for a Running supervisor on that node; its log for `gateway accepted the supervisor host` | +| With `externalEnforcer.enabled`, a sandbox Pod stays Pending or never reaches its supervisor; after `externalEnforcer.network.sandbox.resource` changed, restart, resume, or image update fails with `workload contains an unsupported external resource attachment` and running sandboxes are suspended | The node lacks the attachment's device, the attachment doesn't route to the supervisor Service, or resource admission no longer accepts a resource stored sandboxes request | `kubectl -n get pod -o jsonpath='{.metadata.annotations}'` for `v1.multus-cni.io/default-network` and `k8s.v1.cni.cncf.io/network-status`; the agent container's `resources` for the device; `kubectl describe node` for its allocatable count; drain sandboxes before removing or renaming `resource` | | Shared sandbox workloads terminate after a supervisor Pod or node failure (`sandbox-supervisor-recovery-expired`) | One supervisor replica (no member to fail over to), no live pool member took over, or the recovery timeout is shorter than detection plus takeover | `supervisor.replicas` and the `-supervisor` PodDisruptionBudget; gateway `taking over a shared sandbox instance` logs; workload Pod `sandbox-supervisor-*` findings; `supervisor.recoveryTimeoutSeconds`. See "Shared supervisor high availability" in Step 6 | | Shared-sandbox grants fail with `code=unavailable stage=workload_identity` | The gateway cannot reach the SPIFFE Broker endpoint or obtain credentials from its CSI Workload API socket | Gateway logs for `dynamic token grant failed`; check Broker endpoint connectivity, the gateway's Workload API CSI mount and agent health | | Shared-sandbox grants fail with `code=workload_identity_rejected stage=workload_identity` | Broker mTLS verification fails, an agent has no Sandbox UID registration, or the gateway lacks `impersonate-via-spire` authorization | Check trust, the exact or prefix peer policy, and Sandbox registrations on the gateway's node-local agent or the configured endpoint's agents. Verify the gateway SPIFFE identity's namespace-scoped authorization. Use a node alias to cover eligible agents | +| A shared supervisor logs `could not open the supervisor host stream` with `supervisor identity token is required`, `supervisor identity token is invalid`, or a `supervisor identity:` credential refusal, or logs `no usable identity token` | Its projected token is missing or for an audience other than `openshell-supervisor`, or it runs as a ServiceAccount other than `shared_supervisor.service_account_name` | `kubectl -n openshell get pod -o jsonpath='{.spec.serviceAccountName}'`; check the `identity` projected volume and `--identity-token-file` argument; the gateway needs `create` on `tokenreviews` and `get` on Pods in the release namespace | | OpenShift sandbox pod fails to start (`unable to validate against any security context constraint`) | An explicit sandbox UID/GID override or custom security context conflicts with the namespace's SCC range | Inspect pod events and the namespace's `openshift.io/sa.scc.uid-range` and `openshift.io/sa.scc.supplemental-groups` annotations; remove incompatible `sandbox_uid` / `sandbox_gid` overrides so the driver uses the namespace-assigned identity. Current sandbox pods use `restricted-v2` without a privileged SCC grant; see the [OpenShift guide](https://docs.nvidia.com/openshell/latest/kubernetes/openshift) and [RFC 0012](https://github.com/ai-openshell/openshell/blob/main/rfc/0012-isolation-backend/README.md#motivation). | | OpenShift self-hosted Vault/OpenBao credential store pod never schedules (waits time out with `no matching resources found`) | The store's Helm chart pins `runAsUser`/`fsGroup`/seccomp, which restricted-v2 rejects, so the StatefulSet controller never creates the pod | Deploy the store's chart in its OpenShift mode (`--set global.openshift=true` for the OpenBao/Vault chart) so the namespace SCC assigns a compliant security context — no manual SCC grant needed | | Vault credential driver returns HTTP 403 / `Vault Kubernetes auth denied the configured role` on provider create | Vault's `auth/kubernetes` method or the gateway login role is not provisioned, or the role is not bound to the gateway service account and namespace | In Vault: `bao auth enable kubernetes` and `bao write auth/kubernetes/config kubernetes_host=... kubernetes_ca_cert=@...`; ensure the login role's `bound_service_account_names`/`bound_service_account_namespaces` match the gateway SA and namespace and its policy grants the credential paths | diff --git a/tasks/test.toml b/tasks/test.toml index bdd923de3f..cac1a78584 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -357,6 +357,12 @@ env = { OPENSHELL_E2E_KUBE_TEST = "kubernetes_shared_supervisor", OPENSHELL_E2E_ # turn off. run = 'OPENSHELL_E2E_KUBE_EXTRA_VALUES="deploy/helm/openshell/ci/values-supervisor.yaml:deploy/helm/openshell/ci/values-tls-port-forward.yaml${OPENSHELL_E2E_KUBE_EXTRA_VALUES:+:$OPENSHELL_E2E_KUBE_EXTRA_VALUES}" e2e/rust/e2e-kubernetes.sh' +["e2e:kubernetes:additional-ca-shared"] +description = "Run the Kubernetes additional destination CA e2e with a one-member shared supervisor pool (gateway supervisor topology)" +env = { OPENSHELL_E2E_KUBE_TEST = "additional_ca", OPENSHELL_E2E_KUBE_TLS = "1", OPENSHELL_E2E_KUBE_SUPERVISOR_TOPOLOGY = "gateway" } +# The shared supervisor requires gateway TLS, which the Skaffold values turn off. +run = 'OPENSHELL_E2E_KUBE_EXTRA_VALUES="deploy/helm/openshell/ci/values-supervisor.yaml:deploy/helm/openshell/ci/values-tls-port-forward.yaml${OPENSHELL_E2E_KUBE_EXTRA_VALUES:+:$OPENSHELL_E2E_KUBE_EXTRA_VALUES}" e2e/rust/e2e-kubernetes.sh' + ["e2e:kubernetes:shared-supervisor-ha"] description = "Run Kubernetes e2e for a two-replica shared supervisor pool behind two gateway replicas: a killed owning member's sandboxes are adopted, not restarted, and each pool sandbox's session stays on its supervisor's gateway through gateway and supervisor failures" env = { OPENSHELL_E2E_KUBE_EXTERNAL_POSTGRES_SECRET = "openshell-ha-pg", OPENSHELL_E2E_KUBE_TEST = "kubernetes_shared_supervisor_ha", OPENSHELL_E2E_KUBE_TLS = "1", OPENSHELL_E2E_KUBERNETES_FEATURES = "e2e,e2e-host-gateway,e2e-kubernetes,e2e-kubernetes-shared-supervisor-ha" } @@ -385,6 +391,14 @@ description = "Run node-local SPIFFE Broker coverage with gateway relocation acr env = { HELM_K3S_AGENT_COUNT = "2", OPENSHELL_E2E_SPIRE_MIN_AGENTS = "3", OPENSHELL_E2E_KUBE_SPIRE_NODE_LOCAL = "1", OPENSHELL_E2E_KUBE_EXTERNAL_POSTGRES_SECRET = "e2e-spiffe-postgres", OPENSHELL_E2E_KUBE_SPIRE_BROKER = "1", OPENSHELL_E2E_KUBE_TLS = "1", OPENSHELL_E2E_KUBE_TEST = "kubernetes_shared_supervisor_spiffe", OPENSHELL_E2E_KUBERNETES_FEATURES = "e2e,e2e-host-gateway,e2e-kubernetes,e2e-kubernetes-shared-supervisor-spiffe" } run = 'OPENSHELL_E2E_KUBE_EXTRA_VALUES="deploy/helm/openshell/ci/values-supervisor-spiffe-node-local.yaml:deploy/helm/openshell/ci/values-tls-port-forward.yaml${OPENSHELL_E2E_KUBE_EXTRA_VALUES:+:$OPENSHELL_E2E_KUBE_EXTRA_VALUES}" e2e/rust/e2e-kubernetes.sh' +["e2e:kubernetes:shared-supervisor-node"] +description = "Run Kubernetes e2e for one shared supervisor per node on a two-node cluster" +env = { HELM_K3S_AGENT_COUNT = "1", OPENSHELL_E2E_KUBE_TEST = "kubernetes_shared_supervisor_node", OPENSHELL_E2E_KUBE_TLS = "1", OPENSHELL_E2E_KUBERNETES_FEATURES = "e2e,e2e-host-gateway,e2e-kubernetes,e2e-kubernetes-shared-supervisor-node" } +# The ephemeral k3d cluster gets one agent beside its server node; an existing +# context must already have two schedulable nodes. The shared supervisor +# requires gateway TLS, which the Skaffold values turn off. +run = 'OPENSHELL_E2E_KUBE_EXTRA_VALUES="deploy/helm/openshell/ci/values-supervisor-node.yaml:deploy/helm/openshell/ci/values-tls-port-forward.yaml${OPENSHELL_E2E_KUBE_EXTRA_VALUES:+:$OPENSHELL_E2E_KUBE_EXTRA_VALUES}" e2e/rust/e2e-kubernetes.sh' + ["e2e:kubernetes:workspace-operator"] description = "Run Kubernetes e2e with operator workspace mode (pre-provisioned per-workspace namespaces)" env = { OPENSHELL_E2E_KUBE_EXTRA_VALUES = "deploy/helm/openshell/ci/values-workspace-operator.yaml", OPENSHELL_E2E_KUBE_TEST = "workspace_namespace_operator", OPENSHELL_E2E_KUBERNETES_FEATURES = "e2e,e2e-kubernetes,e2e-kubernetes-workspace-operator" } diff --git a/tests/testkit/testkit/src/context.rs b/tests/testkit/testkit/src/context.rs index da6e84abee..400e868b7f 100644 --- a/tests/testkit/testkit/src/context.rs +++ b/tests/testkit/testkit/src/context.rs @@ -815,6 +815,7 @@ impl Sandbox { ], name: self.name.clone(), workspace_scope: self.handles.grpc.scope(), + sandbox_id: String::new(), }; Ok(self .handles