From 0b045b10f3a702572ebfe7111cdb6c00daefe05c Mon Sep 17 00:00:00 2001 From: Gal Zaidman Date: Sun, 8 Nov 2026 22:21:16 +0200 Subject: [PATCH] feat(k8s): support the additional destination CA with shared supervisors The gateway no longer refuses [openshell.supervisor.network] additional_ca_bundle with the shared supervisor topology. The Kubernetes driver carries the normalized PEM in each generation's launch material, and the shared host writes it to the instance's private directory for the network supervisor to append. With a shared topology the gateway refuses at startup a bundle that, with the supervisor OTLP TLS files, exceeds 192 KiB, leaving 64 KiB for the rest of the launch material. Older supervisors refuse launch material carrying the bundle, so upgrade supervisors before configuring it. Signed-off-by: Gal Zaidman --- TESTING.md | 2 + .../openshell-driver-kubernetes/src/driver.rs | 84 +++++++++-- crates/openshell-gateway/src/lib.rs | 16 +-- .../openshell-server/src/config_file/mod.rs | 2 +- .../openshell-supervisor-control/src/lib.rs | 5 +- .../src/registration.rs | 9 ++ .../openshell-supervisor/src/shared_host.rs | 39 ++++- deploy/helm/openshell/README.md | 3 + deploy/helm/openshell/README.md.gotmpl | 3 + docs/how-it-works/gateways/configuration.mdx | 10 +- e2e/rust/tests/additional_ca.rs | 134 ++++++++++++++++-- skills/debug-openshell-cluster/SKILL.md | 16 ++- tasks/test.toml | 6 + 13 files changed, 280 insertions(+), 49 deletions(-) diff --git a/TESTING.md b/TESTING.md index 3e68e9c6b8..bc829b6710 100644 --- a/TESTING.md +++ b/TESTING.md @@ -1007,6 +1007,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: @@ -1020,6 +1021,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-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index fab746d814..8c46eec529 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -137,9 +137,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, @@ -1165,6 +1166,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 +1175,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( @@ -4002,8 +4006,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( @@ -4029,6 +4032,7 @@ impl KubernetesComputeDriver { provisioned.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 @@ -4370,9 +4374,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) @@ -5879,6 +5886,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 +5913,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 +5956,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(), }) } @@ -9608,6 +9643,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"; diff --git a/crates/openshell-gateway/src/lib.rs b/crates/openshell-gateway/src/lib.rs index 46bbe0a3e0..ca278d0a87 100644 --- a/crates/openshell-gateway/src/lib.rs +++ b/crates/openshell-gateway/src/lib.rs @@ -269,23 +269,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-server/src/config_file/mod.rs b/crates/openshell-server/src/config_file/mod.rs index 5c2bdf606e..6be58006f1 100644 --- a/crates/openshell-server/src/config_file/mod.rs +++ b/crates/openshell-server/src/config_file/mod.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-supervisor-control/src/lib.rs b/crates/openshell-supervisor-control/src/lib.rs index f7ddb4284d..c4a0d70be2 100644 --- a/crates/openshell-supervisor-control/src/lib.rs +++ b/crates/openshell-supervisor-control/src/lib.rs @@ -57,7 +57,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/src/shared_host.rs b/crates/openshell-supervisor/src/shared_host.rs index 32108cdce4..d3b9f14c66 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 @@ -1748,6 +1761,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/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index ad4dd9ce37..9da4676f03 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. diff --git a/deploy/helm/openshell/README.md.gotmpl b/deploy/helm/openshell/README.md.gotmpl index 4441c571d3..40573d1535 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. diff --git a/docs/how-it-works/gateways/configuration.mdx b/docs/how-it-works/gateways/configuration.mdx index 0cfc3e5ac0..6a614438ed 100644 --- a/docs/how-it-works/gateways/configuration.mdx +++ b/docs/how-it-works/gateways/configuration.mdx @@ -221,6 +221,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 @@ -1015,7 +1023,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. 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/skills/debug-openshell-cluster/SKILL.md b/skills/debug-openshell-cluster/SKILL.md index f82f67eeef..a4f422283c 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 diff --git a/tasks/test.toml b/tasks/test.toml index 783220ecee..e3dd38495b 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -352,6 +352,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" }