Skip to content

Commit 59479f4

Browse files
feat(k8s): add namespace-per-workspace support (RFC 0011 Phase 3) (#2656)
* feat(k8s): add namespace-per-workspace support (RFC 0011 Phase 3) Implement three workspace namespace modes for the Kubernetes compute driver: shared (default, preserves current single-namespace behavior), managed (auto-creates/deletes namespaces per workspace), and operator (pre-provisioned namespaces with dynamic discovery via label selector or drop-in allowlist file). Key changes: - WorkspaceMode enum and namespace resolution in driver config - Managed namespace lifecycle with ServiceAccount and OpenShift SCC annotation propagation - Cluster-wide sandbox CR watchers for managed/operator modes - NamespaceValidator (Exact/Prefix/Allowlist) for SA token auth - Workspace-aware credential secret storage - Helm ClusterRole for multi-namespace RBAC - Gateway config, architecture, and reference docs Signed-off-by: Derek Carr <decarr@redhat.com> * test(k8s): add e2e tests for workspace namespace modes Add end-to-end tests for managed and operator workspace modes introduced in RFC 0011 Phase 3. The managed mode tests verify namespace creation with correct labels, ServiceAccount provisioning, sandbox CR placement, and namespace survival with remaining sandboxes. The operator mode tests verify rejection of unlabeled and nonexistent namespaces. The positive operator path (sandbox in labeled namespace) is known to fail due to an RBAC gap and will be addressed separately. Also fixes Helm 4 compatibility: move SPDX license headers inside conditional guards in 8 chart templates to prevent empty comment-only documents, and fix a trailing whitespace trimmer in clusterrole.yaml that concatenated the license header with apiVersion. Adds cleanup sweep in with-kube-gateway.sh to remove managed and operator namespaces before Helm uninstall, and mise tasks for running each mode independently. Signed-off-by: Derek Carr <decarr@redhat.com> * feat(k8s): add operator namespace label watcher Spawn a background kube::runtime::watcher in the K8s driver that watches namespaces matching the configured label selector and populates the OperatorNamespaceAllowlist at runtime. The driver owns the allowlist and exposes its Arc so the server can share the same set with the SA token authenticator. create_sandbox now gates pod creation on the allowlist in operator mode — workspaces whose namespace is not yet labeled are rejected at resource render time rather than silently proceeding. Workspace lifecycle itself is unaffected; only sandbox (resource) creation is gated. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(k8s): harden operator mode and address review findings Close the fail-open gap in operator mode when only operator_namespace_file is configured: the allowlist is now created unconditionally in operator mode (fail-closed from startup). Implement the namespace file watcher using the notify crate, following the TLS hot-reload pattern (parent-directory watch, 1s debounce, ConfigMap symlink-swap safe). The file format is a JSON array of namespace name strings. Additional fixes from the 10-reviewer audit: - Change allowlist rejection from InvalidArgument to FailedPrecondition so callers know the request may succeed later once the namespace is provisioned. - NamespaceValidator::Allowlist now holds the OperatorNamespaceAllowlist newtype instead of a raw Arc<RwLock<BTreeSet>>, eliminating silent denial on RwLock poison. - Verify LABEL_MANAGED_BY and LABEL_GATEWAY_ID ownership before deleting a managed namespace. - Replace fixed 5s sleep in operator e2e test with a 30s poll loop. - Add Helm validation for workspaceMode values. - Fix Helm README type column and description for operator fields. - Add insert/remove methods to OperatorNamespaceAllowlist; label watcher now uses them instead of reaching through shared(). - Reject configs with both operator_namespace_label and operator_namespace_file set. Signed-off-by: Derek Carr <decarr@redhat.com> * feat(k8s): add workspace-level compute driver RPCs and harden RBAC Decouple namespace lifecycle from sandbox lifecycle by adding EnsureWorkspace/DeleteWorkspace RPCs to the ComputeDriver service. Namespace creation now happens before credential storage and namespace deletion happens on workspace delete, fixing credential storage in managed workspace mode. - Add EnsureWorkspace and DeleteWorkspace proto RPCs with implementations across all compute drivers (K8s managed delegates to ensure_namespace/delete_namespace_if_empty; others no-op) - Wire ensure_workspace into provider create/update/refresh paths so the namespace exists before the credential driver writes secrets - Wire delete_workspace into workspace deletion for cleanup - Remove delete_namespace_if_empty from sandbox deletion path - Scope ClusterRole secrets access to non-shared workspace modes - Add TODO for TLS cert hot-reload in sandbox gRPC client - Harden e2e tests with control-plane sandbox resolution assertions - Fix docker image save --platform flag for OCI index manifests Signed-off-by: Derek Carr <decarr@redhat.com> * fix(k8s): address re-review findings and add test coverage - Use server-side apply for TLS secret sync (fixes second sandbox creation failure when TLS is enabled) - Scope gateway-ID label selector unconditionally across all workspace modes (fixes operator reads/watches/deletes seeing foreign sandboxes) - Validate operator allowlist in EnsureWorkspace and DeleteWorkspace RPCs (prevents credential writes to namespaces outside the allowlist) - Extend ClusterRole secrets patch+delete to all non-shared modes with credential driver enabled (fixes operator credential storage RBAC) - Validate namespace ownership on 409 conflict in ensure_namespace (prevents adopting unowned namespaces in managed mode) - Replace delete_namespace_if_empty with unconditional delete_namespace letting Kubernetes cascade cleanup (fixes stuck terminating CRs) - Strengthen NetworkPolicy TODO to cover both managed and operator modes - Extract selector and ownership logic into testable free functions - Add unit tests for gateway-ID selectors and namespace ownership - Add Helm ClusterRole RBAC tests for operator credential driver Signed-off-by: Derek Carr <decarr@redhat.com> * ci(k8s): add workspace managed and operator mode e2e to CI Wire the existing e2e:kubernetes:workspace-managed and e2e:kubernetes:workspace-operator mise tasks into the branch-e2e workflow so they run alongside the other core Kubernetes e2e suites. Both are gated by run_core_e2e and included in the Core E2E result gate. Signed-off-by: Derek Carr <decarr@redhat.com> * test(k8s): add e2e tests for workspace namespace modes Add 7 new e2e tests covering workspace namespace lifecycle, TLS secret copying, ownership conflict detection, DNS-1123 validation, operator namespace preservation, and dynamic label watcher behavior. Fix async sandbox deletion race condition in existing tests by polling sandbox list instead of asserting immediately after delete. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(k8s): grant secrets/patch unconditionally and backfill gateway-id labels Address two review findings: 1. RBAC: server-side apply (PATCH) is used for TLS secret sync in multi-namespace modes, but the ClusterRole only granted patch when the kubernetes-secrets credential driver was enabled. Grant patch unconditionally for non-shared modes since TLS sync always needs it; keep delete gated on the credential driver. 2. Upgrade safety: the new gateway-id label selector would orphan legacy Sandbox CRs that predate its introduction. Add a startup backfill in shared mode that patches any managed Sandbox CR missing the gateway-id label before the driver begins serving requests. Signed-off-by: Derek Carr <decarr@redhat.com> * fix(k8s): address workspace namespace review findings Signed-off-by: Derek Carr <decarr@redhat.com> * fix(k8s): address follow-up review findings Signed-off-by: Derek Carr <decarr@redhat.com> * fix(k8s): preserve workspace lookup after rebase Signed-off-by: Derek Carr <decarr@redhat.com> * fix(helm): allow managed secret creation Signed-off-by: Derek Carr <decarr@redhat.com> * fix(k8s): stop pods in workspace namespace Signed-off-by: Derek Carr <decarr@redhat.com> * test(k8s): scope pod deletion check to v1alpha1 Signed-off-by: Derek Carr <decarr@redhat.com> * fix(k8s): address workspace namespace review findings Signed-off-by: Derek Carr <decarr@redhat.com> --------- Signed-off-by: Derek Carr <decarr@redhat.com>
1 parent 3581b9e commit 59479f4

50 files changed

Lines changed: 4937 additions & 368 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.github/workflows/branch-e2e.yml‎

Lines changed: 34 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,34 @@ jobs:
182182
extra-helm-values: ${{ matrix.extra_helm_values }}
183183
cli-artifact-prefix: rust-binary-cli
184184

185+
kubernetes-workspace-managed-e2e:
186+
needs: [pr_metadata, build-gateway, build-supervisor, build-cli]
187+
if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_core_e2e == 'true'
188+
permissions:
189+
actions: read
190+
contents: read
191+
packages: read
192+
uses: ./.github/workflows/e2e-kubernetes-test.yml
193+
with:
194+
image-tag: ${{ github.sha }}
195+
job-name: Kubernetes E2E (workspace managed mode)
196+
e2e-task: e2e:kubernetes:workspace-managed
197+
cli-artifact-prefix: rust-binary-cli
198+
199+
kubernetes-workspace-operator-e2e:
200+
needs: [pr_metadata, build-gateway, build-supervisor, build-cli]
201+
if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_core_e2e == 'true'
202+
permissions:
203+
actions: read
204+
contents: read
205+
packages: read
206+
uses: ./.github/workflows/e2e-kubernetes-test.yml
207+
with:
208+
image-tag: ${{ github.sha }}
209+
job-name: Kubernetes E2E (workspace operator mode)
210+
e2e-task: e2e:kubernetes:workspace-operator
211+
cli-artifact-prefix: rust-binary-cli
212+
185213
kubernetes-ha-e2e:
186214
needs: [pr_metadata, build-gateway, build-supervisor, build-cli]
187215
if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_kubernetes_ha_e2e == 'true'
@@ -212,7 +240,7 @@ jobs:
212240

213241
core-e2e-result:
214242
name: Core E2E result
215-
needs: [pr_metadata, build-gateway, build-supervisor, build-cli, build-driver-vm-linux, e2e, kubernetes-e2e]
243+
needs: [pr_metadata, build-gateway, build-supervisor, build-cli, build-driver-vm-linux, e2e, kubernetes-e2e, kubernetes-workspace-managed-e2e, kubernetes-workspace-operator-e2e]
216244
if: always() && needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_core_e2e == 'true'
217245
runs-on: ubuntu-latest
218246
steps:
@@ -224,6 +252,8 @@ jobs:
224252
BUILD_DRIVER_VM_RESULT: ${{ needs.build-driver-vm-linux.result }}
225253
E2E_RESULT: ${{ needs.e2e.result }}
226254
KUBERNETES_E2E_RESULT: ${{ needs.kubernetes-e2e.result }}
255+
KUBERNETES_WORKSPACE_MANAGED_E2E_RESULT: ${{ needs.kubernetes-workspace-managed-e2e.result }}
256+
KUBERNETES_WORKSPACE_OPERATOR_E2E_RESULT: ${{ needs.kubernetes-workspace-operator-e2e.result }}
227257
run: |
228258
set -euo pipefail
229259
failed=0
@@ -233,7 +263,9 @@ jobs:
233263
"build-cli:$BUILD_CLI_RESULT" \
234264
"build-driver-vm-linux:$BUILD_DRIVER_VM_RESULT" \
235265
"e2e:$E2E_RESULT" \
236-
"kubernetes-e2e:$KUBERNETES_E2E_RESULT"; do
266+
"kubernetes-e2e:$KUBERNETES_E2E_RESULT" \
267+
"kubernetes-workspace-managed-e2e:$KUBERNETES_WORKSPACE_MANAGED_E2E_RESULT" \
268+
"kubernetes-workspace-operator-e2e:$KUBERNETES_WORKSPACE_OPERATOR_E2E_RESULT"; do
237269
name="${item%%:*}"
238270
result="${item#*:}"
239271
if [ "$result" != "success" ]; then

‎Cargo.lock‎

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎architecture/compute-runtimes.md‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -309,5 +309,99 @@ Standalone local deployments start the gateway with a selected runtime such as
309309
Docker, Podman, or VM. The CLI can register multiple gateways and switch between
310310
them without changing the sandbox architecture.
311311

312+
## Workspace Namespace Modes (Kubernetes)
313+
314+
The Kubernetes driver maps workspaces to namespaces through the `workspace_mode`
315+
configuration field (`WorkspaceMode` in `crates/openshell-driver-kubernetes/src/config.rs`).
316+
The mode controls namespace resolution, resource naming, sandbox CR watching, SA
317+
token authentication, and RBAC requirements.
318+
319+
| Mode | Namespace resolution | Resource name | Namespace lifecycle |
320+
|---|---|---|---|
321+
| **Shared** (default) | Single static namespace from config | `{workspace}--{name}` | None |
322+
| **Managed** | `openshell-{gateway_id}-{workspace}` | bare sandbox name | Driver creates and deletes |
323+
| **Operator** | Workspace name maps 1:1 to a pre-provisioned namespace | bare sandbox name | External (platform team) |
324+
325+
**Shared** renders all sandboxes into one configured namespace. Resource names
326+
embed the workspace prefix for collision avoidance. No namespace lifecycle
327+
management. RBAC uses a namespace-scoped Role.
328+
329+
**Managed** auto-creates a K8s namespace per workspace on first sandbox create.
330+
Each new namespace receives a ServiceAccount and the configured gateway-only
331+
SSH ingress NetworkPolicy. Configured image-pull Secrets are copied from the
332+
driver's source namespace on every sandbox create so registry credential
333+
rotations propagate. The namespace also copies OpenShift SCC UID-range and
334+
supplemental-group annotations from the gateway namespace when present. The
335+
driver deletes the namespace during workspace deletion. The workspace remains
336+
durably `Terminating` until the Kubernetes API accepts namespace cleanup, so a
337+
transient failure can be retried. Namespace deletion uses the fetched UID as a
338+
precondition to avoid deleting a replacement namespace. Requires a non-empty
339+
`gateway_id` (validated as a
340+
DNS-1123 label at startup) so the namespace prefix fits within the K8s 63-character
341+
limit. RBAC promotes sandbox CRD permissions to a ClusterRole and adds namespace
342+
`create`/`delete` and ServiceAccount `create`/`get` permissions.
343+
344+
Secret copies use server-side apply. Kubernetes authorizes an apply to an
345+
existing Secret as `patch`, but also requires `create` authorization when the
346+
target does not exist. RBAC cannot constrain `create` by `resourceNames`, so
347+
managed mode grants cluster-wide Secret `create` while keeping source reads and
348+
subsequent patches restricted to the explicitly configured TLS and image-pull
349+
Secret names. The driver exercises `create` only in gateway-owned managed
350+
namespaces. This depends on the managed-mode ownership invariant described
351+
below; the gateway ServiceAccount must not be shared with unrelated workloads.
352+
353+
Operator mode does not create NetworkPolicies or copy image-pull Secrets.
354+
Platform teams must apply the gateway ingress boundary and provision configured
355+
image-pull Secrets in every operator-managed namespace.
356+
357+
**Operator** uses pre-provisioned namespaces discovered through two optional
358+
sources: a K8s label selector (`operator_namespace_label`) and a drop-in
359+
allowlist file (`operator_namespace_file`). At least one must be configured.
360+
The `OperatorNamespaceAllowlist` (`Arc<RwLock<BTreeSet<String>>>`) is populated
361+
at runtime by background watchers and read by the namespace resolver. Sandbox
362+
creation fails closed if the workspace is not in the current allowlist. Platform
363+
teams manage namespace lifecycle externally. RBAC uses the same ClusterRole as
364+
managed mode but without namespace `create`/`delete` or ServiceAccount
365+
permissions.
366+
367+
### Watching and Querying
368+
369+
Managed and operator modes set `is_multi_namespace() == true`, which switches
370+
sandbox CR watchers from namespace-scoped `Api::namespaced` to cluster-wide
371+
`Api::all_with`. In managed mode the driver scopes cluster-wide queries with a
372+
`LABEL_GATEWAY_ID` label selector to support multiple gateways on the same
373+
cluster. K8s Events are not watched in cluster-wide mode — the cluster-wide
374+
watcher emits only sandbox CR changes, not platform events.
375+
376+
### SA Token Authentication
377+
378+
The gateway's `K8sServiceAccountAuthenticator` adapts its `NamespaceValidator`
379+
per mode (`crates/openshell-server/src/auth/k8s_sa.rs`):
380+
381+
- **Shared:** `Exact` — accepts only the single configured namespace.
382+
- **Managed:** `Prefix` — accepts any namespace starting with `openshell-{gateway_id}-`.
383+
- **Operator:** `Allowlist` — accepts namespaces present in the dynamic
384+
`BTreeSet` populated by the label/file watchers. Starts empty (fail-closed)
385+
until the first watcher update.
386+
387+
These checks rely on an ownership invariant. In shared and managed modes, the
388+
gateway and its trusted Agent Sandbox controller exclusively administer the
389+
sandbox namespace, Sandbox CRs, sandbox pods, and configured sandbox
390+
ServiceAccount. Other principals must not create or mutate those resources or
391+
use that ServiceAccount. In operator mode, the platform operator retains
392+
namespace lifecycle ownership, but must preserve the same exclusive control of
393+
Sandbox CRs and the pods and ServiceAccount used for sandbox token bootstrap.
394+
An allowlisted namespace is therefore a trust grant, not a tenant isolation
395+
boundary. Kubernetes owner references alone do not prove which controller
396+
created a pod, so admitting principals that can fabricate that resource chain
397+
would allow them to claim an existing sandbox identity.
398+
399+
### Credential Driver Integration
400+
401+
The Kubernetes Secrets credential driver (`openshell-driver-kubernetes-secrets`)
402+
stores secrets in workspace-specific namespaces when `workspace_mode` is managed
403+
or operator. In shared mode, all secrets render into the single configured
404+
namespace.
405+
312406
When runtime infrastructure changes, validate the relevant sandbox e2e path and
313407
update the matching driver README if a maintainer-facing constraint changes.

‎crates/openshell-core/src/driver_utils.rs‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ pub const LABEL_SANDBOX_NAMESPACE: &str = "openshell.ai/sandbox-namespace";
3535
/// Container/pod label carrying the sandbox workspace.
3636
pub const LABEL_SANDBOX_WORKSPACE: &str = "openshell.ai/sandbox-workspace";
3737

38+
/// Label carrying the gateway identity on managed namespaces.
39+
pub const LABEL_GATEWAY_ID: &str = "openshell.ai/gateway-id";
40+
3841
/// Label selector that matches all OpenShell-managed resources which carry a
3942
/// sandbox ID label. Used by list and watch operations to exclude foreign
4043
/// resources from the same namespace.

‎crates/openshell-core/src/grpc_client.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,10 @@ async fn build_plain_channel(endpoint: &str) -> Result<Channel> {
147147

148148
let tls_enabled = endpoint.starts_with("https://");
149149

150+
// TODO: TLS certs are loaded once here and never re-read. The gateway
151+
// server side supports hot-reload (ArcSwap + notify in tls.rs). The
152+
// supervisor should do the same so that cert-manager rotations take
153+
// effect without restarting the sandbox.
150154
if tls_enabled {
151155
let ca_path = std::env::var(sandbox_env::TLS_CA)
152156
.into_diagnostic()

‎crates/openshell-driver-docker/src/lib.rs‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,9 @@ use openshell_core::progress::{
3838
};
3939
use openshell_core::proto::compute::v1::{
4040
CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse,
41-
DriverCondition, DriverPlatformEvent, DriverSandbox, DriverSandboxStatus,
42-
DriverSandboxTemplate, GatewayListenerRequirement, GetCapabilitiesRequest,
41+
DeleteWorkspaceRequest, DeleteWorkspaceResponse, DriverCondition, DriverPlatformEvent,
42+
DriverSandbox, DriverSandboxStatus, DriverSandboxTemplate, EnsureWorkspaceRequest,
43+
EnsureWorkspaceResponse, GatewayListenerRequirement, GetCapabilitiesRequest,
4344
GetCapabilitiesResponse, GetGatewayListenerRequirementsRequest,
4445
GetGatewayListenerRequirementsResponse, GetSandboxRequest, GetSandboxResponse,
4546
GpuResourceRequirements, ListSandboxesRequest, ListSandboxesResponse, StartSandboxRequest,
@@ -1761,6 +1762,20 @@ impl ComputeDriver for DockerComputeDriver {
17611762

17621763
Ok(Response::new(Box::pin(ReceiverStream::new(out_rx))))
17631764
}
1765+
1766+
async fn ensure_workspace(
1767+
&self,
1768+
_request: Request<EnsureWorkspaceRequest>,
1769+
) -> Result<Response<EnsureWorkspaceResponse>, Status> {
1770+
Ok(Response::new(EnsureWorkspaceResponse {}))
1771+
}
1772+
1773+
async fn delete_workspace(
1774+
&self,
1775+
_request: Request<DeleteWorkspaceRequest>,
1776+
) -> Result<Response<DeleteWorkspaceResponse>, Status> {
1777+
Ok(Response::new(DeleteWorkspaceResponse {}))
1778+
}
17641779
}
17651780

17661781
impl DockerProvisioningFailure {

0 commit comments

Comments
 (0)