diff --git a/.agents/skills/debug-openshell-cluster/SKILL.md b/.agents/skills/debug-openshell-cluster/SKILL.md index c407823aff..7f11fd9ca5 100644 --- a/.agents/skills/debug-openshell-cluster/SKILL.md +++ b/.agents/skills/debug-openshell-cluster/SKILL.md @@ -85,26 +85,26 @@ The custom driver name must not be a reserved built-in name (`docker`, `podman`, For configured gateway interceptors, inspect `[[openshell.gateway.interceptors]]`, their Unix or network endpoints, and gateway startup logs: ```bash -rg -n 'interceptors|provider_profile_sources|grpc_endpoint|binding_policy|failure_policy' /etc/openshell/gateway.toml +rg -n 'interceptors|provider_profile_sources|grpc_endpoint|tls_ca_cert_path|audience|allow_insecure_transport|binding_policy|failure_policy|gateway_jwt' /etc/openshell/gateway.toml stat /run/openshell/interceptors/.sock journalctl -u --no-pager --lines=200 journalctl -u openshell-gateway --no-pager --lines=200 ``` -The gateway calls each interceptor's `Describe` RPC and validates its manifest at startup. Check for unreachable endpoints, invalid RPC/phase bindings, strict `allowlist` or `exact` mismatches, and `post_commit` bindings that resolve to `fail_closed`. If `provider_profile_sources` names an interceptor, that interceptor must advertise provider-profile capability and return a valid, duplicate-free catalog. A selected interceptor-only source is authoritative; include `builtin` or `user` sources explicitly when composition is intended. +The gateway calls each interceptor's `Describe` RPC and validates its manifest at startup. Check for unreachable endpoints, invalid RPC/phase bindings, strict `allowlist` or `exact` mismatches, and `post_commit` bindings that resolve to `fail_closed`. If gateway JWT signing is enabled, authenticated network interceptors require HTTPS and a valid bearer token; check the private CA path, endpoint hostname, expected audience, issuer, `kid`, and interceptor logs for token rejection. `allow_insecure_transport = true` explicitly preserves unauthenticated plaintext behavior. If `provider_profile_sources` names an interceptor, that interceptor must advertise provider-profile capability and return a valid, duplicate-free catalog. A selected interceptor-only source is authoritative; include `builtin` or `user` sources explicitly when composition is intended. For operator-run supervisor middleware, inspect `[[openshell.supervisor.middleware]]`, service reachability, and both gateway and supervisor logs: ```bash -rg -n 'supervisor|middleware|grpc_endpoint|max_body_bytes|timeout' /etc/openshell/gateway.toml +rg -n 'supervisor|middleware|grpc_endpoint|tls_ca_cert_path|audience|allow_insecure_transport|max_payload_bytes|timeout|gateway_jwt' /etc/openshell/gateway.toml journalctl -u --no-pager --lines=200 journalctl -u openshell-gateway --no-pager --lines=200 openshell logs --tail --source sandbox ``` -The middleware service must start before the gateway and be reachable from both the gateway and sandbox supervisors. Gateway startup fails if `Describe` is unavailable, a manifest exposes duplicate `HttpRequest/pre_credentials` bindings, the registration claims the reserved `openshell/` namespace, or body and timeout limits are invalid. Changing a registration requires a gateway restart. A policy update can also fail before persistence if the selected implementation rejects its `network_middlewares` config. +The middleware service must start before the gateway and be reachable from both the gateway and sandbox supervisors. Gateway startup fails if `Describe` is unavailable, a manifest exposes duplicate operation/phase bindings, the registration claims the reserved `openshell/` namespace, or payload and timeout limits are invalid. Supported V1 bindings are `HTTP_REQUEST/PRE_CREDENTIALS` and `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. When gateway JWT signing is disabled, supervisors preserve the legacy unauthenticated connector and do not request extension credentials. When signing is enabled, credential acquisition and verification failures are fail closed: check HTTPS trust and hostname validation, audience and issuer agreement, the token `kid`, gateway `RefreshSandboxToken` errors, and middleware logs. Changing a registration requires a gateway restart. A policy update can also fail before persistence if the selected implementation rejects its `network_middlewares` config. -At request time, distinguish an explicit `middleware_denied` result from `middleware_failed`. A denial is always enforced. A failure follows the policy-local `on_error`: `fail_closed` blocks the request, while `fail_open` bypasses only that stage and emits a detection finding. If a running supervisor cannot install a new registry, it preserves its last-known-good generation and emits a configuration failure event. +At request time, distinguish attachment, binding selection, coverage, denial, and failure. A host-matched HTTP-only attachment can inspect the upgrade GET but does not join the WebSocket chain; the connection proceeds under either `on_error` mode and emits `binding_not_selected` coverage. A selected WebSocket stage receives text messages only. Binary messages pass under both modes, emit `unsupported_message_type` coverage, and consume a session sequence without an RPC. An explicit `middleware_denied` result is always enforced. WebSocket preflight returns `INSPECT`, voluntary `SKIP`, or authoritative `DENY`; `DENY` rejects the upgrade before upstream contact under both `on_error` modes. A selected-stage failure follows the policy-local `on_error`: `fail_closed` blocks the HTTP request or closes the WebSocket, while `fail_open` bypasses only that stage and emits a detection finding. A fail-open per-message capacity failure bypasses that message without disabling the stage. A timeout, transport failure, stream closure, missing or invalid response, duplicate or regressed sequence, or other failure that makes an established WebSocket stream unreliable disables that stage for later messages on the connection and emits `openshell.middleware.websocket_stage_disabled`. Confirm preflight, session-start, and session-end in service logs. OpenShell best-effort sends at most one session-end to each still-writable opened stage, including a preflight that terminates before session start; distinguish `MIDDLEWARE_DENIAL` from `MIDDLEWARE_FAILURE`. WebSocket message sequences are allocated session-wide; each stage receives a strictly increasing subset, so gaps are valid when binary messages or other units are not delivered to that stage. Zero, duplicate, or regressed sequences are protocol errors. If a running supervisor cannot install a new registry, it preserves its last-known-good generation and emits a configuration failure event. For network policy validation failures, first distinguish a gateway mutation rejection from a supervisor runtime rejection. Direct policy updates, @@ -555,12 +555,17 @@ openshell logs | CLI TLS error | Local mTLS bundle does not match server cert/CA | Check `~/.config/openshell/gateways//mtls/` | | Edge or OIDC gateway returns `Unauthenticated` | Stored login expired, audience/scopes mismatch, or gateway auth configuration changed | `openshell gateway info`, `openshell gateway login `, gateway auth logs | | Gateway fails before serving health after enabling an interceptor | Interceptor endpoint unavailable or manifest/binding validation failed | Gateway and interceptor logs; interceptor socket; `binding_policy`, phases, and failure policy | +| Authenticated interceptor or middleware rejects gateway calls | Private CA or hostname mismatch, expected audience or issuer mismatch, stale/unknown `kid`, or malformed extension token | `tls_ca_cert_path`, registration `audience`, service verifier config and logs; fetch well-known metadata only through the already-trusted gateway TLS endpoint | | Provider profiles disappear after enabling an interceptor catalog | `provider_profile_sources` selected only an authoritative interceptor or returned invalid/duplicate IDs | Inspect source list and interceptor `Describe`/catalog logs; include `builtin` and `user` when intended | -| Gateway fails after registering supervisor middleware | Service unavailable, invalid manifest, duplicate binding, reserved name, or invalid body/timeout limit | Middleware service and gateway logs; `[[openshell.supervisor.middleware]]`; `Describe` response | +| Gateway fails after registering supervisor middleware | Service unavailable, invalid manifest, duplicate binding, reserved name, or invalid payload/timeout limit | Middleware service and gateway logs; `[[openshell.supervisor.middleware]]`; `Describe` response | | Policy update rejects `network_middlewares` | Unknown middleware name, implementation-owned config invalid, duplicate order, broad/invalid host selector, or fail-closed coverage of `tls: skip` | Policy error, gateway logs, middleware `ValidateConfig`, selector and order fields | | Policy mutation returns `FAILED_PRECONDITION` for endpoint ambiguity | Equally specific effective endpoint selectors disagree on connection or request-processing metadata | CLI error, base and provider-composed policy, affected profile attachments; confirm no new revision was stored | | Supervisor enters policy quarantine | A runtime candidate failed validation while `policy_validation_failure_mode = "fail_closed"` | Sandbox OCSF config/finding events, validation rationale, active generation, `previous_policy_active` | -| HTTP request returns `middleware_failed` or `middleware_denied` | Selected stage failed or explicitly denied the admitted request | Sandbox OCSF logs; policy-local middleware config; service availability; `on_error` | +| HTTP request returns `middleware_failed` or `middleware_denied`, or WebSocket closes with `1008` | Selected stage failed or explicitly denied admitted traffic | Sandbox OCSF logs; policy-local middleware config; service availability; binding operation; `on_error` | +| WebSocket upgrades but a host-matched middleware receives no preflight or message RPC | The implementation did not advertise `WEBSOCKET_MESSAGE/PRE_CREDENTIALS` | `WEBSOCKET_MIDDLEWARE_COVERAGE state=binding_not_selected`; service `Describe`; the upgrade GET may still have used its HTTP binding | +| Binary WebSocket message passes without a middleware RPC | Binary is unsupported by the V1 text-message binding under both `on_error` modes | `WEBSOCKET_MIDDLEWARE_COVERAGE state=unsupported_message_type`; the next text RPC may have a valid sequence gap | +| WebSocket messages stop reaching middleware after one failure | A fail-open stage stream was disabled for the rest of the connection | `openshell.middleware.websocket_stage_disabled`; middleware timeout/stream/protocol logs. A per-message capacity bypass alone leaves the stage active. Reconnect to create a fresh stream after a genuine stream failure | +| Supervisor repeatedly fails to install middleware after enabling gateway JWT signing | Extension credential minting, distribution, or authenticated service connection failed; last-known-good registry remains active | Gateway `RefreshSandboxToken` logs, sandbox configuration events, service token-verification logs, registration TLS/audience settings | | Custom compute driver is unavailable | Driver process/socket missing, inaccessible, or configured with a reserved/mismatched name | Socket ownership/mode, driver service logs, gateway `GetCapabilities` logs | | Sandbox remains `Stopping` or `Starting` | Driver stop/start failed, retained resource is missing, or a fresh supervisor has not connected | Gateway and driver logs; `docker inspect`, `podman inspect`, Agent Sandbox status/PVC, or VM state marker and launcher process | | Image pull failure | Gateway or sandbox image cannot be pulled | Runtime events and image pull credentials | diff --git a/.agents/skills/generate-sandbox-policy/SKILL.md b/.agents/skills/generate-sandbox-policy/SKILL.md index 592a352a2e..cfdc14e1b5 100644 --- a/.agents/skills/generate-sandbox-policy/SKILL.md +++ b/.agents/skills/generate-sandbox-policy/SKILL.md @@ -79,7 +79,7 @@ Regardless of tier, extract (or infer) these from the user's description: | **Paths** | Specific URL paths or patterns | Only for custom/fine-grained | | **Enforcement** | `enforce` or `audit`? Default to `enforce`. | No — has a default | | **Binary** | Which binary/process should have access | Yes — ask if not stated | -| **Middleware** | Whether admitted HTTP requests need an ordered built-in or operator-run processing stage | No | +| **Middleware** | Whether admitted HTTP requests or client WebSocket text messages need an ordered built-in or operator-run processing stage | No | If the host and access level are clear but binaries are not specified, ask the user which binary or process will be making the requests. Suggest common defaults like `/usr/bin/curl`, `/usr/local/bin/claude`, etc. @@ -216,10 +216,14 @@ Is L7 inspection needed? ### Middleware Decision -Add `network_middlewares` only when the user asks to inspect, transform, redact, or independently authorize admitted HTTP requests. Middleware runs after network and L7 policy admission and before provider credential injection. +Add `network_middlewares` only when the user asks to inspect, transform, redact, or independently authorize admitted HTTP requests or client WebSocket text messages. Middleware runs after network and L7 policy admission and before provider credential injection. -- Use a built-in name such as `openshell/regex` without gateway registration. +- Use `openshell/regex` without gateway registration for fixed-pattern redaction of UTF-8 HTTP request bodies or complete client-to-upstream WebSocket text messages. - Use an operator-owned middleware name only when it is already registered under `[[openshell.supervisor.middleware]]` and reachable from both the gateway and sandbox supervisors. +- Confirm that a requested WebSocket implementation exposes a `WEBSOCKET_MESSAGE/PRE_CREDENTIALS` binding. `openshell/regex` exposes this binding. A host-matched HTTP-only implementation may inspect the upgrade GET but does not join the post-upgrade chain; messages pass and OpenShell emits `binding_not_selected` coverage regardless of `on_error`. +- WebSocket middleware runs for both `ws://` and `wss://` and receives complete client text messages only. Binary messages pass under both error modes and emit `unsupported_message_type` coverage for active stages. Upstream-to-client messages remain uninspected. Do not claim that V1 provides all-message WebSocket inspection. +- Treat `fail_open` on WebSocket as a session-scoped bypass: if the stage stream fails, OpenShell disables it for later messages on that connection and emits a state-change finding. Prefer `fail_closed` for required redaction or authorization. +- `on_error` governs failures after an advertised operation binding is selected. It does not apply to an unadvertised WebSocket binding or binary-message pass-through. An explicit HTTP, WebSocket preflight, or WebSocket message denial is authoritative under both `fail_open` and `fail_closed`. - Default `on_error` to `fail_closed`. Use `fail_open` only when bypassing the stage preserves the user's stated security requirement. - Assign unique `order` values across the complete policy. Lower values run first, and at most 10 configs may be selected. - Match the narrowest destination hosts possible with `endpoints.include`; use `exclude` when a broad selector has trusted exceptions. @@ -379,6 +383,7 @@ Before presenting the policy to the user, verify correctness **and** flag breadt - [ ] Every middleware config has a non-empty `middleware` name and non-empty `endpoints.include` - [ ] Middleware `order` values are unique and no selected chain exceeds 10 stages - [ ] No fail-closed middleware selector can cover a `tls: skip` endpoint +- [ ] Any required WebSocket control advertises `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`, and the user understands that V1 does not inspect binary messages ### Schema Warnings (log-only, but should be fixed) @@ -412,7 +417,7 @@ Evaluate the generated policy for overly broad access and **include warnings in | **Hostless `allowed_ips`** (no `host` field) | "This endpoint has no `host` — any domain resolving to the allowed IP range on this port will be permitted. Consider adding a `host` field to restrict which domains can use this allowlist." | | **Broad CIDR** in `allowed_ips` (e.g., `10.0.0.0/8`) | "This `allowed_ips` entry covers a very broad range. Consider narrowing to a specific subnet (e.g., `10.0.5.0/24`) to minimize exposure." | | **`on_error: fail_open`** | "This middleware can be bypassed when it is unavailable, rejects configuration, returns an invalid result, or exceeds its body limit. Use `fail_closed` unless availability is more important than this control." | -| **Broad middleware host selector** | "This middleware applies independently of the admitting network rule to every matching HTTP destination. Narrow `endpoints.include` or add exclusions if the stage is not required for every matching host." | +| **Broad middleware host selector** | "This middleware attaches independently of the admitting network rule to every matching destination, then runs only for operation bindings its implementation advertises. Narrow `endpoints.include` or add exclusions if the attachment is not required for every matching host." | Format breadth warnings clearly in the output, e.g.: diff --git a/.agents/skills/openshell-cli/SKILL.md b/.agents/skills/openshell-cli/SKILL.md index b49b82c5ec..c1f180b1e2 100644 --- a/.agents/skills/openshell-cli/SKILL.md +++ b/.agents/skills/openshell-cli/SKILL.md @@ -382,10 +382,12 @@ Edit `current-policy.yaml` to allow the blocked actions. **For policy content au - TLS termination configuration - Enforcement modes (`audit` vs `enforce`) - Binary matching patterns -- Ordered `network_middlewares`, host selection, and `fail_open` or `fail_closed` behavior +- Ordered `network_middlewares`, host selection, HTTP and WebSocket bindings, and `fail_open` or `fail_closed` behavior `network_policies` and `network_middlewares` can be modified at runtime. If `filesystem_policy`, `landlock`, or `process` need changes, the sandbox must be recreated. Built-in middleware such as `openshell/regex` needs no gateway registration. An operator-run middleware must already be registered under `[[openshell.supervisor.middleware]]`; changing that static registration requires a gateway restart. +Middleware can inspect parsed HTTP request bodies and complete client-to-upstream WebSocket text messages over both `ws://` and `wss://` when the implementation advertises the matching binding. The built-in `openshell/regex` advertises both bindings and applies its fixed patterns to UTF-8 text. A host-matched HTTP-only attachment can inspect the upgrade GET but does not join the WebSocket chain; look for `binding_not_selected` coverage. Binary messages pass under both `on_error` modes and active stages emit `unsupported_message_type` coverage; upstream-to-client messages remain uninspected. A broken fail-open WebSocket stage is disabled for the rest of that connection; inspect sandbox OCSF logs for `openshell.middleware.websocket_stage_disabled`. + ### Step 5: Push the updated policy ```bash diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index b569db2a7c..4d32b414c1 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -1,5 +1,5 @@ # Broad ownership — core team reviews everything -* @NVIDIA/openshell-codeowners @mrunalp @maxamillion @derekwaynecarr +* @NVIDIA/openshell-codeowners @mrunalp @sjenning @derekwaynecarr # Vouch list — maintainers only (bot commits bypass, but manual edits need review) .github/VOUCHED.td @NVIDIA/openshell-codeowners diff --git a/.github/workflows/branch-e2e.yml b/.github/workflows/branch-e2e.yml index 3d68746b82..37154c75df 100644 --- a/.github/workflows/branch-e2e.yml +++ b/.github/workflows/branch-e2e.yml @@ -182,6 +182,34 @@ jobs: extra-helm-values: ${{ matrix.extra_helm_values }} cli-artifact-prefix: rust-binary-cli + kubernetes-workspace-managed-e2e: + needs: [pr_metadata, build-gateway, build-supervisor, build-cli] + if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_core_e2e == 'true' + permissions: + actions: read + contents: read + packages: read + uses: ./.github/workflows/e2e-kubernetes-test.yml + with: + image-tag: ${{ github.sha }} + job-name: Kubernetes E2E (workspace managed mode) + e2e-task: e2e:kubernetes:workspace-managed + cli-artifact-prefix: rust-binary-cli + + kubernetes-workspace-operator-e2e: + needs: [pr_metadata, build-gateway, build-supervisor, build-cli] + if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_core_e2e == 'true' + permissions: + actions: read + contents: read + packages: read + uses: ./.github/workflows/e2e-kubernetes-test.yml + with: + image-tag: ${{ github.sha }} + job-name: Kubernetes E2E (workspace operator mode) + e2e-task: e2e:kubernetes:workspace-operator + cli-artifact-prefix: rust-binary-cli + kubernetes-ha-e2e: needs: [pr_metadata, build-gateway, build-supervisor, build-cli] if: needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_kubernetes_ha_e2e == 'true' @@ -212,7 +240,7 @@ jobs: core-e2e-result: name: Core E2E result - needs: [pr_metadata, build-gateway, build-supervisor, build-cli, build-driver-vm-linux, e2e, kubernetes-e2e] + needs: [pr_metadata, build-gateway, build-supervisor, build-cli, build-driver-vm-linux, e2e, kubernetes-e2e, kubernetes-workspace-managed-e2e, kubernetes-workspace-operator-e2e] if: always() && needs.pr_metadata.outputs.should_run == 'true' && needs.pr_metadata.outputs.run_core_e2e == 'true' runs-on: ubuntu-latest steps: @@ -224,6 +252,8 @@ jobs: BUILD_DRIVER_VM_RESULT: ${{ needs.build-driver-vm-linux.result }} E2E_RESULT: ${{ needs.e2e.result }} KUBERNETES_E2E_RESULT: ${{ needs.kubernetes-e2e.result }} + KUBERNETES_WORKSPACE_MANAGED_E2E_RESULT: ${{ needs.kubernetes-workspace-managed-e2e.result }} + KUBERNETES_WORKSPACE_OPERATOR_E2E_RESULT: ${{ needs.kubernetes-workspace-operator-e2e.result }} run: | set -euo pipefail failed=0 @@ -233,7 +263,9 @@ jobs: "build-cli:$BUILD_CLI_RESULT" \ "build-driver-vm-linux:$BUILD_DRIVER_VM_RESULT" \ "e2e:$E2E_RESULT" \ - "kubernetes-e2e:$KUBERNETES_E2E_RESULT"; do + "kubernetes-e2e:$KUBERNETES_E2E_RESULT" \ + "kubernetes-workspace-managed-e2e:$KUBERNETES_WORKSPACE_MANAGED_E2E_RESULT" \ + "kubernetes-workspace-operator-e2e:$KUBERNETES_WORKSPACE_OPERATOR_E2E_RESULT"; do name="${item%%:*}" result="${item#*:}" if [ "$result" != "success" ]; then diff --git a/AGENTS.md b/AGENTS.md index fd1b97e258..bd532c1971 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,11 +39,13 @@ These pipelines connect skills into end-to-end workflows. Individual skill files | `crates/openshell-ocsf/` | OCSF logging | OCSF v1.7.0 event types, builders, shorthand/JSONL formatters, tracing layers | | `crates/openshell-otel/` | OpenTelemetry support | Shared OTLP trace provider, resource, and tracing-layer construction | | `crates/openshell-core/` | Shared core | Common types, configuration, error handling | +| `crates/openshell-extension-core/` | Extension core | Shared extension identity, JWT claims, bearer-token rotation, and TLS transport primitives | | `crates/openshell-sdk/` | Shared client SDK | Async Rust gateway client (gRPC transport, TLS, OIDC refresh, edge tunnel); consumed by CLI, TUI, and `@openshell/sdk` | | `crates/openshell-providers/` | Provider management | Credential provider backends | | `crates/openshell-tui/` | Terminal UI | Ratatui-based dashboard for monitoring | | `crates/openshell-driver-kubernetes-secrets/` | Kubernetes Secrets credential driver | In-process `CredentialDriver` backend for OpenShell-managed K8s Secret storage | | `crates/openshell-driver-vault/` | Vault credential driver | In-process `CredentialDriver` backend for Vault-compatible KV storage | +| `crates/openshell-driver-db-credstore/` | Database credential driver | In-process `CredentialDriver` backend for gateway database credential storage | | `crates/openshell-driver-kubernetes/` | Kubernetes compute driver | In-process `ComputeDriver` backend for K8s sandbox pods | | `crates/openshell-driver-docker/` | Docker compute driver | In-process `ComputeDriver` backend for local Docker sandbox containers | | `crates/openshell-driver-podman/` | Podman compute driver | In-process `ComputeDriver` backend for local Podman sandbox containers | diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2562e8f11c..cc52782560 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -82,7 +82,6 @@ Skills live in `.agents/skills/`. Your agent's harness can discover and load the | Contributing | `create-github-issue` | Create well-structured GitHub issues | | Contributing | `create-github-pr` | Create pull requests with proper conventions | | Reviewing | `review-github-pr` | Summarize PR diffs and key design decisions | -| Reviewing | `review-security-changes` | Review code changes for security vulnerabilities and boundary regressions | | Reviewing | `review-security-issue` | Assess security issues for severity and remediation | | Reviewing | `fix-security-issue` | Implement an approved security remediation plan | | Reviewing | `watch-github-actions` | Monitor CI pipeline status and logs | diff --git a/Cargo.lock b/Cargo.lock index 37b9140600..d676de7782 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3712,6 +3712,7 @@ dependencies = [ "ipnet", "miette", "nix 0.29.0", + "openshell-extension-core", "prost", "prost-types", "protoc-bin-vendored", @@ -3721,6 +3722,7 @@ dependencies = [ "tempfile", "thiserror 2.0.18", "tokio", + "tokio-stream", "tonic", "tonic-prost", "tonic-prost-build", @@ -3777,6 +3779,7 @@ dependencies = [ "kube", "kube-runtime", "miette", + "notify", "openshell-core", "openshell-policy", "prost", @@ -3902,13 +3905,30 @@ dependencies = [ ] [[package]] -name = "openshell-gateway-interceptors" +name = "openshell-extension-core" version = "0.0.0" dependencies = [ + "http 1.4.0", "hyper-util", + "rcgen", + "rustls 0.23.38", + "serde", + "serde_json", + "thiserror 2.0.18", + "tokio", + "tokio-stream", + "tonic", + "tower 0.5.3", +] + +[[package]] +name = "openshell-gateway-interceptors" +version = "0.0.0" +dependencies = [ "json-patch", "metrics", "openshell-core", + "openshell-extension-core", "prost", "prost-reflect", "prost-types", @@ -3917,7 +3937,6 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tonic", - "tower 0.5.3", "tracing", "tracing-subscriber", ] @@ -4017,6 +4036,7 @@ dependencies = [ "miette", "nix 0.29.0", "openshell-core", + "openshell-extension-core", "openshell-ocsf", "openshell-policy", "openshell-supervisor-middleware", @@ -4105,6 +4125,7 @@ dependencies = [ "openshell-driver-kubernetes-secrets", "openshell-driver-podman", "openshell-driver-vault", + "openshell-extension-core", "openshell-gateway-interceptors", "openshell-ocsf", "openshell-otel", @@ -4167,8 +4188,10 @@ dependencies = [ name = "openshell-supervisor-middleware" version = "0.0.0" dependencies = [ + "futures", "miette", "openshell-core", + "openshell-extension-core", "openshell-supervisor-middleware-builtins", "prost", "prost-types", @@ -4189,6 +4212,8 @@ dependencies = [ "serde", "serde_json", "tokio", + "tokio-stream", + "tonic", ] [[package]] @@ -4233,6 +4258,7 @@ dependencies = [ "thiserror 2.0.18", "tokio", "tokio-rustls 0.26.4", + "tokio-stream", "tokio-tungstenite 0.26.2", "tonic", "tower-mcp-types", diff --git a/architecture/README.md b/architecture/README.md index 9453d59826..d6cde146b2 100644 --- a/architecture/README.md +++ b/architecture/README.md @@ -163,6 +163,7 @@ that crate's `README.md`. |---|---| | [Gateway](gateway.md) | Gateway control plane, auth, APIs, persistence, settings, and relay coordination. | | [Sandbox](sandbox.md) | Sandbox supervisor, child process isolation, proxy, credentials, inference, connect, and logs. | +| [Sandbox Limits](sandbox-limits.md) | Sandbox supervisor and egress safety ceilings, ownership rules, current enforcement, and known gaps. | | [Security Policy](security-policy.md) | Policy model, enforcement layers, policy updates, policy advisor, and security logging. | | [Compute Runtimes](compute-runtimes.md) | Docker, Podman, Kubernetes, VM, sandbox images, and runtime-specific responsibilities. | | [Build](build.md) | Build artifacts, CI/E2E, docs site validation, and release packaging. | diff --git a/architecture/compute-runtimes.md b/architecture/compute-runtimes.md index e4224232dd..42c53abc6a 100644 --- a/architecture/compute-runtimes.md +++ b/architecture/compute-runtimes.md @@ -309,5 +309,99 @@ Standalone local deployments start the gateway with a selected runtime such as Docker, Podman, or VM. The CLI can register multiple gateways and switch between them without changing the sandbox architecture. +## Workspace Namespace Modes (Kubernetes) + +The Kubernetes driver maps workspaces to namespaces through the `workspace_mode` +configuration field (`WorkspaceMode` in `crates/openshell-driver-kubernetes/src/config.rs`). +The mode controls namespace resolution, resource naming, sandbox CR watching, SA +token authentication, and RBAC requirements. + +| Mode | Namespace resolution | Resource name | Namespace lifecycle | +|---|---|---|---| +| **Shared** (default) | Single static namespace from config | `{workspace}--{name}` | None | +| **Managed** | `openshell-{gateway_id}-{workspace}` | bare sandbox name | Driver creates and deletes | +| **Operator** | Workspace name maps 1:1 to a pre-provisioned namespace | bare sandbox name | External (platform team) | + +**Shared** renders all sandboxes into one configured namespace. Resource names +embed the workspace prefix for collision avoidance. No namespace lifecycle +management. RBAC uses a namespace-scoped Role. + +**Managed** auto-creates a K8s namespace per workspace on first sandbox create. +Each new namespace receives a ServiceAccount and the configured gateway-only +SSH ingress NetworkPolicy. Configured image-pull Secrets are copied from the +driver's source namespace on every sandbox create so registry credential +rotations propagate. The namespace also copies OpenShift SCC UID-range and +supplemental-group annotations from the gateway namespace when present. The +driver deletes the namespace during workspace deletion. The workspace remains +durably `Terminating` until the Kubernetes API accepts namespace cleanup, so a +transient failure can be retried. Namespace deletion uses the fetched UID as a +precondition to avoid deleting a replacement namespace. Requires a non-empty +`gateway_id` (validated as a +DNS-1123 label at startup) so the namespace prefix fits within the K8s 63-character +limit. RBAC promotes sandbox CRD permissions to a ClusterRole and adds namespace +`create`/`delete` and ServiceAccount `create`/`get` permissions. + +Secret copies use server-side apply. Kubernetes authorizes an apply to an +existing Secret as `patch`, but also requires `create` authorization when the +target does not exist. RBAC cannot constrain `create` by `resourceNames`, so +managed mode grants cluster-wide Secret `create` while keeping source reads and +subsequent patches restricted to the explicitly configured TLS and image-pull +Secret names. The driver exercises `create` only in gateway-owned managed +namespaces. This depends on the managed-mode ownership invariant described +below; the gateway ServiceAccount must not be shared with unrelated workloads. + +Operator mode does not create NetworkPolicies or copy image-pull Secrets. +Platform teams must apply the gateway ingress boundary and provision configured +image-pull Secrets in every operator-managed namespace. + +**Operator** uses pre-provisioned namespaces discovered through two optional +sources: a K8s label selector (`operator_namespace_label`) and a drop-in +allowlist file (`operator_namespace_file`). At least one must be configured. +The `OperatorNamespaceAllowlist` (`Arc>>`) is populated +at runtime by background watchers and read by the namespace resolver. Sandbox +creation fails closed if the workspace is not in the current allowlist. Platform +teams manage namespace lifecycle externally. RBAC uses the same ClusterRole as +managed mode but without namespace `create`/`delete` or ServiceAccount +permissions. + +### Watching and Querying + +Managed and operator modes set `is_multi_namespace() == true`, which switches +sandbox CR watchers from namespace-scoped `Api::namespaced` to cluster-wide +`Api::all_with`. In managed mode the driver scopes cluster-wide queries with a +`LABEL_GATEWAY_ID` label selector to support multiple gateways on the same +cluster. K8s Events are not watched in cluster-wide mode — the cluster-wide +watcher emits only sandbox CR changes, not platform events. + +### SA Token Authentication + +The gateway's `K8sServiceAccountAuthenticator` adapts its `NamespaceValidator` +per mode (`crates/openshell-server/src/auth/k8s_sa.rs`): + +- **Shared:** `Exact` — accepts only the single configured namespace. +- **Managed:** `Prefix` — accepts any namespace starting with `openshell-{gateway_id}-`. +- **Operator:** `Allowlist` — accepts namespaces present in the dynamic + `BTreeSet` populated by the label/file watchers. Starts empty (fail-closed) + until the first watcher update. + +These checks rely on an ownership invariant. In shared and managed modes, the +gateway and its trusted Agent Sandbox controller exclusively administer the +sandbox namespace, Sandbox CRs, sandbox pods, and configured sandbox +ServiceAccount. Other principals must not create or mutate those resources or +use that ServiceAccount. In operator mode, the platform operator retains +namespace lifecycle ownership, but must preserve the same exclusive control of +Sandbox CRs and the pods and ServiceAccount used for sandbox token bootstrap. +An allowlisted namespace is therefore a trust grant, not a tenant isolation +boundary. Kubernetes owner references alone do not prove which controller +created a pod, so admitting principals that can fabricate that resource chain +would allow them to claim an existing sandbox identity. + +### Credential Driver Integration + +The Kubernetes Secrets credential driver (`openshell-driver-kubernetes-secrets`) +stores secrets in workspace-specific namespaces when `workspace_mode` is managed +or operator. In shared mode, all secrets render into the single configured +namespace. + When runtime infrastructure changes, validate the relevant sandbox e2e path and update the matching driver README if a maintainer-facing constraint changes. diff --git a/architecture/gateway.md b/architecture/gateway.md index a9831ae220..db8f2508e8 100644 --- a/architecture/gateway.md +++ b/architecture/gateway.md @@ -72,6 +72,26 @@ until deliberately added to this allowlist. Interception remains centralized: allowlisting a unary RPC does not require method-specific gateway instrumentation. +Remote extension clients share `openshell-extension-core` transport and bearer +primitives. When gateway JWT signing is configured, the gateway mints +short-lived, exact-audience EdDSA credentials for middleware and interceptors, +rotates their in-memory slots without rebuilding clients, and publishes the +public verification key at `/.well-known/jwks.json` alongside OIDC-shaped +discovery metadata at `/.well-known/openid-configuration`. HTTPS extensions can +pin an operator-provided CA while retaining endpoint-hostname verification. + +Extension credentials reuse the sandbox signing key and are separated from +sandbox-to-gateway admission tokens by exact audience and by an explicit +`typ` of `openshell-ext+jwt`, so a verifier that checks either one alone +cannot confuse the two. After authenticated `Describe` succeeds, a service may +advertise `expected_audience` as a post-authentication consistency assertion; +a mismatch against operator configuration fails gateway startup. A strict +verifier may reject an incorrect audience before returning the manifest. A +registration may opt out of extension authentication entirely with +`allow_insecure_transport`, which permits a plaintext endpoint, attaches no +credential, and warns at every startup. Credential minting is bounded per +sandbox because it resolves the caller's effective policy. + Each configured interceptor selects a binding policy. `dynamic` accepts valid manifest declarations and preserves the compatibility behavior. `allowlist` enables only operator-configured RPCs and phases, while `exact` requires the @@ -422,6 +442,9 @@ each service and validates its described bindings and operator body limit. Policies attach a complete external middleware by its operator-owned registration name. Manifest bindings are identified by operation and phase, and each manifest may declare at most one binding for an operation and phase pair. +Attaching a registration does not require it to advertise every supported +operation. Supervisors select only the manifest bindings that match the current +operation; policy-local config identity remains internal audit metadata. Before persisting a policy, the gateway asks each selected implementation to validate its config. The effective sandbox config contains only the registered services required by that policy; supervisors invoke those services directly on diff --git a/architecture/sandbox-limits.md b/architecture/sandbox-limits.md new file mode 100644 index 0000000000..49f1ab7ce9 --- /dev/null +++ b/architecture/sandbox-limits.md @@ -0,0 +1,173 @@ +# Sandbox Limits + +The sandbox supervisor processes untrusted agent traffic while sharing one +process across connections. Limits protect that process from unbounded memory, +work queues, parser effort, and waits. They are safety boundaries, not capacity +targets or compatibility guarantees. OpenShell is still early, so the values +and some ownership boundaries will change as production evidence improves. + +This document inventories durable sandbox supervisor and egress limits. It +intentionally omits retry cadence, test-only values, and ordinary buffer chunk +sizes that do not cap aggregate resource use. + +## Limit Model + +OpenShell uses three kinds of limits: + +| Kind | Purpose | Configuration | +|---|---|---| +| Platform ceiling | Protect the supervisor even when policy or an external service is hostile or mistaken. | Fixed in code by default. | +| Operator ceiling | Bound an operator-run integration below the platform maximum. | Configurable within platform validation bounds. | +| Policy inspection bound | State how much application data a policy needs the supervisor to buffer and inspect. | Configurable when the application protocol needs it, preferably below a platform ceiling. | + +The component that first allocates, queues, or waits on a resource owns its +limit. Network frame and message assembly belongs to the network supervisor; +middleware RPC and envelope limits belong to the middleware runner; application +inspection limits belong to the corresponding L7 parser. + +New limits should follow these rules: + +- Enforce the bound before allocation or admission whenever possible. +- Acquire shared capacity before buffering and retain it through the complete + buffered operation. +- Give partial-progress protocols both an idle bound and an absolute bound when + either one alone still permits resource pinning. +- Let operator or policy configuration narrow a platform ceiling, never raise + it silently. +- Define the terminal behavior: reject, close, truncate, shed, or backpressure. +- Do not let `fail_open` bypass a platform safety or protocol-integrity bound. +- Emit safe saturation or limit telemetry without request bodies, credentials, + query parameters, or external free-form diagnostics. +- Test time bounds with simulated time and test shared budgets under saturation. + +## Middleware + +Middleware limits are process-wide per sandbox. Registry replacement preserves +the shared work, waiter, and persistent-session admission state so activity +retained by an older generation still consumes the same process-lifetime +budgets as new activity. + +| Resource | Current bound | Scope and behavior | +|---|---:|---| +| Concurrent buffered work | 32 | Shared by HTTP requests, WebSocket messages, and WebSocket preflight. One permit covers one complete unit of work. | +| Admission waiters | 64 | Additional work is shed when both the active budget and waiter budget are full. HTTP receives a complete 503 response before its body is buffered. | +| Persistent middleware sessions | 32 | Shared process-wide session budget for streaming middleware protocols. WebSocket preflight uses immediate admission before opening streams and retains one permit while any stage remains active. | +| HTTP body or WebSocket text message | 4 MiB | Platform maximum for input and replacement payloads. Service, operator, and stage limits may narrow it. | +| Middleware configs and stages | 10 | At most 10 configs in policy and 10 selected stages in one chain. | +| Selector patterns | 32 | Combined include and exclude patterns per middleware config. | +| Per-stage RPC | 500 ms default, 10 ms–30 s | An operator timeout caps a binding timeout. | +| Complete message chain | 30 s | Starts after work admission; admission backpressure does not consume the chain budget. | +| WebSocket preflight | 1 s maximum | Caps handshake delay independently of the message RPC timeout. | +| Remote service connect | 5 s | Applies while establishing a middleware gRPC channel. | + +Middleware also validates every non-body envelope component. Important examples +include 64 KiB service config, 4 KiB request context, 32 KiB target data, 128 +request headers totaling 64 KiB, 64 header mutations, 32 findings per stage, +and 64 metadata entries. The detailed external contract lives in +[Supervisor Middleware](../docs/extensibility/supervisor-middleware.mdx). + +The work semaphore bounds aggregate buffered middleware input to approximately +`32 × 4 MiB`, plus bounded envelope and parser overhead. It is a concurrency +safety valve, not rate limiting or a promise that 32 simultaneous maximum-size +messages are inexpensive. + +The persistent session semaphore is independent from the work semaphore. One +WebSocket middleware session consumes one permit regardless of its active-stage +fan-out, which is separately capped at 10 stages. All-skip preflight releases +the permit immediately. A retained session releases it at connection end or as +soon as its last active stage is disabled. Session admission does not wait: +capacity exhaustion follows each selected config's `on_error` behavior before +any stream opens. The protocol-neutral registry ownership allows future +streaming HTTP middleware to use the same process-wide budget. + +## Egress Framing and Inspection + +| Path | Current bound | Terminal behavior | +|---|---:|---| +| Initial CONNECT request headers | 8 KiB | Reject the proxy request. | +| Inspected HTTP/1 request headers | 16 KiB | Reject the request. | +| Credential-rewritten HTTP body | 256 KiB | Reject when rewriting requires a larger buffered body. | +| SigV4 body signing | 10 MiB | Reject when signing requires a larger buffered body. | +| GraphQL request body | 64 KiB default | Policy can set a positive `graphql_max_body_bytes`; there is no shared platform ceiling yet. | +| MCP or JSON-RPC request body | 64 KiB default | Policy can set a positive `max_body_bytes`; there is no shared platform ceiling yet. | +| Parsed WebSocket client text message | 4 MiB | Close with `1009` when the complete or decompressed message is larger. | +| Concurrent parsed WebSocket text assemblies | 32 active, 64 waiters | Shared process-wide across all parsed relays. Additional messages close with `1013` before payload allocation or reading when both bounds are full. | +| Parsed WebSocket fragments per message | 4,096 | Close with `1002`. | +| Parsed WebSocket text assembly | 30 s input idle, 2 min total | Close with `1002`; the total includes initial and continuation payloads, continuation headers, and interleaved control frames. These deliberately permissive initial bounds can be tightened, or made operator-tunable within platform bounds, after production behavior is understood. | +| Parsed WebSocket text forwarding | 2 min total | End the relay and release assembly capacity. A timeout does not append a close frame to a partially written data frame. | +| Parsed raw WebSocket binary frame | 16 MiB | Close with `1002`; binary messages are relayed rather than inspected. | +| HTTP relay waiting for EOF | 5 s input idle | End the relay with a timeout. | +| TLS certificate cache | 256 hosts | Clear the cache before inserting another host. | + +Ordinary allowed traffic is streamed rather than accumulated to a +connection-sized buffer. A parsing or transformation feature introduces a +buffer only when it owns an explicit bound. + +Every parsed WebSocket text message acquires network-owned assembly capacity before payload allocation or reading, including relays used only for native policy, credential rewriting, compression, or a disabled fail-open middleware session. The process-lifetime budget survives policy reloads, and the assembly retains its permit through decompression, policy and middleware evaluation, credential rewriting, and upstream forwarding. Active middleware sessions additionally acquire shared middleware work before buffering. Input progress resets only the idle deadline. Forwarding uses one total deadline across the complete frame header, payload, and flush. Every timeout and terminal parser error releases both permits through ordinary ownership. Queue exhaustion emits a payload-free network denial event. + +The operator middleware `max_payload_bytes` ceiling applies to payloads exposed +through HTTP-body and WebSocket text-message bindings. It does not replace the +raw binary frame safety bound because binary messages are never delivered to V1 +middleware. A passed binary logical message still advances the active +middleware session sequence and emits coverage telemetry, so a later text RPC +can contain a valid sequence gap. + +## Inference and Upstream Proxying + +| Path | Current bound | Terminal behavior | +|---|---:|---| +| `inference.local` request parse buffer | 10 MiB | Return `413` for an oversized request. | +| Chunked inference request | 10 MiB and 4,096 chunks | Reject an invalid or over-limit request. | +| Streaming inference response | 32 MiB and 120 s chunk idle | Truncate the stream and attempt a safe SSE error. | +| Corporate proxy CONNECT response headers | 8 KiB | Fail the tunnel. | +| Corporate proxy CONNECT handshake | 30 s total | Fail the tunnel; validated-address attempts share the aggregate budget. | +| Token-grant HTTP request | 30 s request and connect | Fail credential resolution. | +| Response-derived token cache TTL | 5 min default; 1 h response cap; 30 s expiry margin | A positive profile `cache_ttl_seconds` override replaces the response-derived calculation. | + +Streaming response byte limits are integrity-relevant. Protocols whose clients +require one complete buffered object do not use the truncating SSE path. + +## Sandbox-Local Surfaces + +| Surface | Current bound | Scope and behavior | +|---|---:|---| +| `policy.local` request body | 64 KiB and 15 s read | Reject an oversized or stalled local request. | +| Policy proposal long-poll | 60 s default, 1–300 s | Clamp the requested hold time; clients can issue another poll. | +| `policy.local` denial read | 100 records, 4 KiB per surfaced line | Bound response and log parsing work. | +| Log push reconnect buffer | 200 records | Drop new records above the local batch ceiling while disconnected. | +| Log push reconnect backoff | 30 s maximum | Cap the delay between reconnect attempts. | +| Policy status outbox | No fixed capacity | Preserve FIFO revision status without blocking policy reconciliation. | +| Policy status retry backoff | 32 s maximum | Retain a retryable update and retry independently of enforcement. | + +The bounded log batch favors supervisor health over retaining an unbounded +diagnostic backlog. The policy status outbox makes the opposite tradeoff: +revision ordering and delivery survive an extended gateway outage at the cost +of potential queue growth. + +## Known Gaps and Review Triggers + +The current limits grew with individual features and are not yet a complete +resource model. Known gaps include: + +- GraphQL, MCP, and JSON-RPC policy body limits have defaults but no common + platform maximum. +- A positive token-cache TTL override replaces the response-derived one-hour + ceiling rather than narrowing it. +- Socket read deadlines are not expressed consistently as idle plus total + budgets across every parser. +- There is no documented aggregate connection budget or per-destination + fairness policy in the supervisor. +- The policy status outbox is intentionally unbounded and can grow if policy + revisions continue while its gateway endpoint remains unavailable. +- Limit telemetry is not yet uniform enough to derive saturation trends across + all paths. + +Revisit this document when adding a parser, body transformation, persistent +stream, shared queue, cache, or external call. A change should state: + +1. What untrusted resource can grow or wait. +2. Which component owns the bound. +3. Whether the scope is per message, connection, destination, or sandbox. +4. Whether configuration can narrow the limit. +5. How saturation or timeout terminates. +6. Which telemetry and deterministic tests prove the behavior. diff --git a/architecture/sandbox.md b/architecture/sandbox.md index 82e3d046ea..e6ec528bd8 100644 --- a/architecture/sandbox.md +++ b/architecture/sandbox.md @@ -51,6 +51,9 @@ paths, such as proxy support files or GPU device paths when a GPU is present. ## Network and Inference +See [Sandbox Limits](sandbox-limits.md) for the current numeric safety ceilings, +their ownership, terminal behavior, and known gaps. + All ordinary agent egress is routed through the sandbox proxy. The proxy identifies the calling binary, checks trust-on-first-use binary identity, rejects unsafe internal destinations, and evaluates the active policy. On Linux, it @@ -93,12 +96,11 @@ finding without logging the placeholder, environment key, secret, or query. For inspected HTTP traffic, the proxy can enforce REST method/path rules, WebSocket upgrade and text-message rules, GraphQL operation rules, and MCP method, tool, and supported params rules or generic JSON-RPC method rules -on sandbox-to-server request bodies. MCP and JSON-RPC inspection buffers up to -the endpoint `mcp.max_body_bytes` or `json_rpc.max_body_bytes` limit. MCP -`tools/call` tool names are checked against the spec-recommended syntax by -default before policy evaluation, with a per-endpoint `mcp.strict_tool_names` -compatibility opt-out. Generic JSON-RPC policies do not support `params` -matchers; generic JSON-RPC rules match only the method. +on sandbox-to-server request bodies. MCP and JSON-RPC inspection buffers +bounded request bodies. MCP `tools/call` tool names are checked against the +spec-recommended syntax by default before policy evaluation, with a per-endpoint +`mcp.strict_tool_names` compatibility opt-out. Generic JSON-RPC policies do not +support `params` matchers; generic JSON-RPC rules match only the method. JSON-RPC responses and server-to-client MCP messages on response or SSE streams are relayed but are not currently parsed for policy enforcement. @@ -108,20 +110,51 @@ host selectors choose the chain independently of the network rule that admitted the request. Policy-local map keys identify configs, while built-in names or operator-owned registration names identify implementations. -Built-ins run in-process against a borrowed view of the chain's current request state. Operator services retain the bounded protobuf/gRPC contract, and the remote adapter materializes an owned evaluation only when the request crosses that transport boundary. `openshell-policy` validates policy-owned structure, and the active middleware registry validates implementation-owned config. The generic registry and chain runner live in `openshell-supervisor-middleware`; first-party implementations live in `openshell-supervisor-middleware-builtins`. +Built-ins run in-process against a borrowed view of the chain's current HTTP +request state. Operator services retain the bounded protobuf/gRPC contract, and +the remote adapter materializes an owned HTTP evaluation only when a request +crosses that transport boundary. Both paths support bounded bidirectional +WebSocket sessions, so a manifest advertises capabilities independently of +transport. +The runtime keeps three states distinct: host selection attaches policy configs, +manifest operation and phase bindings select the active chain, and the parsed +message type determines whether that chain can inspect an individual payload. +An attachment without a WebSocket binding is not a failed WebSocket stage. +Binary messages are outside the V1 text-message binding. Both cases pass through +with informational coverage telemetry rather than applying `on_error`. +The chain runner owns shared sequencing, deadlines, backpressure, and response +validation. `openshell-policy` validates policy-owned structure, and the active +middleware registry validates implementation-owned config. The generic +registry and chain runner live in `openshell-supervisor-middleware`; first-party +implementations live in `openshell-supervisor-middleware-builtins`. The supervisor installs policy and middleware registry changes as one runtime generation and preserves the last-known-good generation if preparation fails. Policy-only updates reuse the connected registry, so an external middleware outage cannot block unrelated policy changes. +For authenticated operator middleware, the supervisor requests credentials by +registration name through `RefreshSandboxToken`. The gateway resolves names +against the effective policy and mints exact-audience credentials. The +supervisor keeps them in refreshable in-memory slots outside stable middleware +configuration, so rotation neither changes `config_revision` nor reconnects +the registry. Public custom-CA PEM travels with the stable registration. + +The slots live in a supervisor-owned `ExtensionCredentialStore` shared by every +gateway connection the supervisor opens, so the registry's clients and the +polling loop that rotates them observe the same credentials. Configuration +polling runs far more frequently than credentials expire, so the loop rotates +only when a credential is missing or has passed four fifths of its lifetime, +and bounds its sleep by the soonest rotation deadline. + Middleware cannot observe injected credentials or mutate supervisor-owned credential, routing, or framing headers. Body transformations are re-evaluated against body-aware L7 policy before later stages or the upstream can observe them. Requests, results, chain length, execution time, and diagnostics are bounded; external free-form diagnostic text is not exposed in responses or -security logs. See [Supervisor Middleware](../docs/extensibility/supervisor-middleware.mdx) -for configuration and protocol details. +security logs. See +[Supervisor Middleware](../docs/extensibility/supervisor-middleware.mdx) for +configuration and protocol details. `https://inference.local` is special. It bypasses OPA network policy and is handled by the inference interception path: @@ -234,8 +267,7 @@ exchanges it for an OAuth2 access token, caches the token, and injects it as an `Authorization: Bearer` header before forwarding the request. Token grant endpoints are HTTPS-only except for loopback and Kubernetes service DNS hosts, and returned access tokens must be bearer-compatible before they are cached or -injected. Token response lifetimes are capped and cached with an expiry margin -unless a profile supplies an explicit cache TTL override. +injected. Token caching follows response-derived and profile override TTL rules. For AWS endpoints that require request-level signing, the proxy supports SigV4 re-signing. When `credential_signing: sigv4` is set on an L7 endpoint, the proxy @@ -248,9 +280,8 @@ an attached endpointless AWS profile explicitly named by the endpoint's sources atomically. The signing mode is auto-detected from the client SDK's `x-amz-content-sha256` header: -- **Signed body** (hex hash): buffers the request body (up to 10 MiB), computes - its SHA-256, and includes the hash in the signature. Used by Bedrock and most - AWS services. +- **Signed body** (hex hash): buffers the request body, computes its SHA-256, + and includes the hash in the signature. Used by Bedrock and most AWS services. - **Streaming unsigned** (`STREAMING-UNSIGNED-PAYLOAD-TRAILER`): signs headers only and streams the body through without buffering. Used by S3 uploads with `aws-chunked` encoding. diff --git a/crates/openshell-core/Cargo.toml b/crates/openshell-core/Cargo.toml index 602386fff1..9fc56106d7 100644 --- a/crates/openshell-core/Cargo.toml +++ b/crates/openshell-core/Cargo.toml @@ -12,12 +12,14 @@ repository.workspace = true [dependencies] async-trait = "0.1" +openshell-extension-core = { path = "../openshell-extension-core" } glob = { workspace = true } prost = { workspace = true } prost-types = { workspace = true } tonic = { workspace = true, features = ["channel", "tls-ring"] } tonic-prost = { workspace = true } tokio = { workspace = true } +tokio-stream = { workspace = true } thiserror = { workspace = true } miette = { workspace = true } serde = { workspace = true } diff --git a/crates/openshell-core/src/config.rs b/crates/openshell-core/src/config.rs index 1b47917fa6..fcbdeb73b6 100644 --- a/crates/openshell-core/src/config.rs +++ b/crates/openshell-core/src/config.rs @@ -4,6 +4,7 @@ //! Configuration management for `OpenShell` components. use serde::{Deserialize, Serialize}; +use std::borrow::Cow; use std::collections::BTreeMap; use std::fmt; #[cfg(unix)] @@ -642,6 +643,19 @@ pub struct GatewayInterceptorConfig { /// Interceptor gRPC endpoint. Supports `http://`, `https://`, and /// `unix://` endpoints. pub grpc_endpoint: String, + /// Optional PEM trust-root bundle for an HTTPS endpoint. The gateway + /// loads this file during interceptor initialization. + #[serde(default)] + pub tls_ca_cert_path: Option, + /// Exact JWT audience for this service. When omitted, a kind-scoped value + /// is derived from the configured registration name. + #[serde(default)] + pub audience: Option, + /// Opt out of extension authentication for this interceptor, permitting a + /// plaintext `http://` endpoint with no bearer credential. Development and + /// trusted-network deployments only. + #[serde(default)] + pub allow_insecure_transport: bool, /// Deterministic service ordering. Lower values run first. #[serde(default)] pub order: i32, @@ -667,6 +681,19 @@ pub struct GatewayInterceptorConfig { pub bindings: Vec, } +impl GatewayInterceptorConfig { + /// Resolve the configured JWT audience to its deterministic default. + pub fn resolved_audience(&self) -> Cow<'_, str> { + self.audience + .as_deref() + .filter(|audience| !audience.is_empty()) + .map_or_else( + || Cow::Owned(format!("urn:openshell:extension:interceptor:{}", self.name)), + Cow::Borrowed, + ) + } +} + /// Operator policy for authorizing interceptor manifest bindings. #[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] @@ -1217,6 +1244,19 @@ mod tests { defaulted.binding_policy, GatewayInterceptorBindingPolicy::Dynamic ); + assert_eq!( + defaulted.resolved_audience(), + "urn:openshell:extension:interceptor:governance" + ); + let explicitly_empty = GatewayInterceptorConfig { + name: "governance".to_string(), + audience: Some(String::new()), + ..GatewayInterceptorConfig::default() + }; + assert_eq!( + explicitly_empty.resolved_audience(), + "urn:openshell:extension:interceptor:governance" + ); assert_eq!(allowlist, GatewayInterceptorBindingPolicy::Allowlist); assert_eq!(exact, GatewayInterceptorBindingPolicy::Exact); } diff --git a/crates/openshell-core/src/driver_utils.rs b/crates/openshell-core/src/driver_utils.rs index 79f2eed3aa..be0d8beb36 100644 --- a/crates/openshell-core/src/driver_utils.rs +++ b/crates/openshell-core/src/driver_utils.rs @@ -35,6 +35,9 @@ pub const LABEL_SANDBOX_NAMESPACE: &str = "openshell.ai/sandbox-namespace"; /// Container/pod label carrying the sandbox workspace. pub const LABEL_SANDBOX_WORKSPACE: &str = "openshell.ai/sandbox-workspace"; +/// Label carrying the gateway identity on managed namespaces. +pub const LABEL_GATEWAY_ID: &str = "openshell.ai/gateway-id"; + /// Label selector that matches all OpenShell-managed resources which carry a /// sandbox ID label. Used by list and watch operations to exclude foreign /// resources from the same namespace. diff --git a/crates/openshell-core/src/grpc_client.rs b/crates/openshell-core/src/grpc_client.rs index 1640fd6cf7..e5f246e4c0 100644 --- a/crates/openshell-core/src/grpc_client.rs +++ b/crates/openshell-core/src/grpc_client.rs @@ -32,6 +32,7 @@ use crate::proto::{ }; use crate::sandbox_env; use miette::{IntoDiagnostic, Result, WrapErr}; +use openshell_extension_core::{BearerTokenSlot, ExtensionCredentialStore}; use tonic::Status; use tonic::metadata::AsciiMetadataValue; use tonic::service::interceptor::InterceptedService; @@ -146,6 +147,10 @@ async fn build_plain_channel(endpoint: &str) -> Result { let tls_enabled = endpoint.starts_with("https://"); + // TODO: TLS certs are loaded once here and never re-read. The gateway + // server side supports hot-reload (ArcSwap + notify in tls.rs). The + // supervisor should do the same so that cert-manager rotations take + // effect without restarting the sandbox. if tls_enabled { let ca_path = std::env::var(sandbox_env::TLS_CA) .into_diagnostic() @@ -349,7 +354,9 @@ async fn refresh_token_loop( let sleep = compute_refresh_delay(&slot); tokio::time::sleep(sleep).await; match client - .refresh_sandbox_token(RefreshSandboxTokenRequest {}) + .refresh_sandbox_token(RefreshSandboxTokenRequest { + extension_service_names: Vec::new(), + }) .await { Ok(resp) => { @@ -414,6 +421,91 @@ async fn refresh_token_loop( } } +fn now_ms() -> i64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| { + i64::try_from(duration.as_millis()).unwrap_or(i64::MAX) + }) +} + +/// Registration names to request credentials for. +/// +/// Registrations the operator opted out of extension authentication have no +/// credential to request; asking for one is rejected by the gateway. +fn authenticated_service_names( + services: &[crate::proto::SupervisorMiddlewareService], +) -> Vec { + services + .iter() + .filter(|service| !service.allow_insecure_transport) + .map(|service| service.name.clone()) + .collect() +} + +async fn refresh_extension_credentials_with_client( + client: &mut OpenShellClient, + store: &ExtensionCredentialStore, + services: &[crate::proto::SupervisorMiddlewareService], +) -> Result> { + let names = authenticated_service_names(services); + if names.is_empty() { + return Ok(HashMap::new()); + } + + let response = client + .refresh_sandbox_token(RefreshSandboxTokenRequest { + extension_service_names: names.clone(), + }) + .await + .into_diagnostic() + .wrap_err("failed to refresh extension service credentials")? + .into_inner(); + + // The same refresh response renews the gateway credential. Install it + // before returning so all process-wide gateway clients stay current. This + // is a superset of what the dedicated renewal loop would do, so letting it + // land early is harmless. + install_token_slot(&response.token)?; + + // Validate the whole response before mutating any slot, so a malformed or + // partial reply cannot leave the store half-rotated. + let expected = names + .iter() + .map(String::as_str) + .collect::>(); + let mut validated = HashMap::with_capacity(response.extension_credentials.len()); + for credential in response.extension_credentials { + if !expected.contains(credential.service_name.as_str()) + || validated.contains_key(&credential.service_name) + { + return Err(miette::miette!( + "gateway returned an unexpected or duplicate extension credential" + )); + } + validated.insert( + credential.service_name, + (credential.token, credential.expires_at_ms), + ); + } + if validated.len() != expected.len() { + return Err(miette::miette!( + "gateway omitted one or more requested extension credentials" + )); + } + + let now_ms = now_ms(); + let mut selected = HashMap::with_capacity(validated.len()); + for (name, (token, expires_at_ms)) in validated { + let slot = store + .install(&name, &token, expires_at_ms, now_ms) + .into_diagnostic() + .wrap_err("gateway returned an invalid extension credential")?; + selected.insert(name, slot); + } + Ok(selected) +} + /// Compute the next refresh delay: 80 % of the time remaining until the /// current token's `exp`, plus up to 10 % jitter, with a small lower bound /// for already-expired tokens and capped at 12 h. If the token can't be parsed @@ -776,6 +868,10 @@ pub async fn fetch_provider_environment( pub struct CachedOpenShellClient { client: OpenShellClient, workspace: Arc>, + /// Extension credentials for this supervisor. Cloning the client shares + /// the store, so the middleware registry and the polling loop that rotates + /// it observe the same slots. + extension_credentials: ExtensionCredentialStore, } /// Settings poll result returned by [`CachedOpenShellClient::poll_settings`]. @@ -796,6 +892,8 @@ pub struct SettingsPollResult { pub workspace: String, /// Gateway-configured posture for rejected policy generations. pub policy_validation_failure_mode: crate::PolicyValidationFailureMode, + /// Whether the gateway can mint authenticated extension credentials. + pub extension_authentication_enabled: bool, } fn settings_poll_result(inner: crate::proto::GetSandboxConfigResponse) -> SettingsPollResult { @@ -815,6 +913,7 @@ fn settings_poll_result(inner: crate::proto::GetSandboxConfigResponse) -> Settin .policy_validation_failure_mode .parse() .unwrap_or_default(), + extension_authentication_enabled: inner.extension_authentication_enabled, } } @@ -847,6 +946,18 @@ mod settings_poll_tests { PolicyValidationFailureMode::FailClosed ); } + + #[test] + fn extension_authentication_capability_round_trips_and_defaults_disabled() { + let enabled = settings_poll_result(GetSandboxConfigResponse { + extension_authentication_enabled: true, + ..Default::default() + }); + assert!(enabled.extension_authentication_enabled); + + let legacy = settings_poll_result(GetSandboxConfigResponse::default()); + assert!(!legacy.extension_authentication_enabled); + } } pub struct ProviderEnvironmentResult { @@ -860,11 +971,25 @@ pub struct ProviderEnvironmentResult { impl CachedOpenShellClient { pub async fn connect(endpoint: &str) -> Result { + Self::connect_with_credentials(endpoint, ExtensionCredentialStore::new()).await + } + + /// Connect while sharing an existing credential store. + /// + /// The supervisor opens the gateway channel more than once (policy load, + /// then the polling loop). Both must observe the same slots, otherwise the + /// credentials handed to the middleware registry are not the ones the loop + /// rotates. + pub async fn connect_with_credentials( + endpoint: &str, + extension_credentials: ExtensionCredentialStore, + ) -> Result { debug!(endpoint = %endpoint, "Connecting openshell gRPC client for policy polling"); let client = connect(endpoint).await?; Ok(Self { client, workspace: Arc::new(tokio::sync::OnceCell::new()), + extension_credentials, }) } @@ -889,6 +1014,67 @@ impl CachedOpenShellClient { Ok(result) } + /// The credential store backing this connection's extension clients. + #[must_use] + pub fn extension_credentials(&self) -> &ExtensionCredentialStore { + &self.extension_credentials + } + + /// Return the slots for `services`, rotating only when one is missing or + /// due. + /// + /// Configuration polling runs far more often than credentials expire, so + /// rotating unconditionally would mint tokens and re-run gateway policy + /// authorization roughly ninety times per useful rotation. + pub async fn extension_credentials_for( + &self, + services: &[crate::proto::SupervisorMiddlewareService], + ) -> Result> { + let names = authenticated_service_names(services); + if names.is_empty() { + return Ok(HashMap::new()); + } + if !self.extension_credentials.needs_refresh(&names, now_ms()) + && let Some(slots) = self.extension_credentials.slots_for(&names) + { + return Ok(slots); + } + self.refresh_extension_credentials(services).await + } + + /// Rotate credentials for `services` unconditionally. + pub async fn refresh_extension_credentials( + &self, + services: &[crate::proto::SupervisorMiddlewareService], + ) -> Result> { + let mut client = self.client.clone(); + refresh_extension_credentials_with_client( + &mut client, + &self.extension_credentials, + services, + ) + .await + } + + /// Rotate every credential currently retained by the installed registry. + /// This remains available when configuration polling fails independently. + pub async fn refresh_installed_extension_credentials(&self) -> Result<()> { + let names = self.extension_credentials.names(); + if names.is_empty() || !self.extension_credentials.needs_refresh(&names, now_ms()) { + return Ok(()); + } + let services = names + .into_iter() + .map(|name| crate::proto::SupervisorMiddlewareService { + name, + ..Default::default() + }) + .collect::>(); + self.refresh_extension_credentials(&services) + .await + .map(drop) + } + /// Returns the workspace learned from the server, or empty if not yet polled. pub fn workspace(&self) -> String { self.workspace.get().cloned().unwrap_or_default() diff --git a/crates/openshell-core/src/middleware.rs b/crates/openshell-core/src/middleware.rs index dc792085ad..2b3fb18982 100644 --- a/crates/openshell-core/src/middleware.rs +++ b/crates/openshell-core/src/middleware.rs @@ -1,17 +1,54 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -//! Supervisor middleware in-process contracts and platform-wide limits. +//! Supervisor middleware contracts and platform-wide limits. +use std::pin::Pin; use std::time::Duration; use miette::Result; +use tokio::sync::mpsc; +use tonic::{Request, Response, Status}; use crate::proto::{ - HttpHeader, HttpRequestResult, HttpRequestTarget, MiddlewareManifest, RequestContext, - SupervisorMiddlewarePhase, + HttpHeader, HttpRequestEvaluation, HttpRequestResult, HttpRequestTarget, MiddlewareManifest, + RequestContext, SupervisorMiddlewarePhase, ValidateConfigRequest, ValidateConfigResponse, + WebSocketSessionEvent, WebSocketSessionEventResult, }; +/// Transport-neutral response stream for one WebSocket middleware stage. +pub type WebSocketResponseStream = Pin< + Box< + dyn tokio_stream::Stream> + + Send + + 'static, + >, +>; + +/// A middleware implementation reachable either in-process or over a transport. +/// +/// Capability is defined by the implementation's manifest. The endpoint hides +/// whether invocations are direct calls or serialized gRPC requests. +#[tonic::async_trait] +pub trait SupervisorMiddlewareEndpoint: Send + Sync { + async fn describe(&self, request: Request<()>) -> Result, Status>; + + async fn validate_config( + &self, + request: Request, + ) -> Result, Status>; + + async fn evaluate_http_request( + &self, + request: Request, + ) -> Result, Status>; + + async fn open_websocket_session( + &self, + requests: mpsc::Receiver, + ) -> Result; +} + /// Borrowed request state exposed to one in-process middleware invocation. /// /// The view reflects every transformation applied by earlier stages. It is valid @@ -94,11 +131,13 @@ impl<'a> HttpRequestView<'a> { } } -/// Asynchronous contract for supervisor middleware that runs in the process. +/// Asynchronous contract for supervisor middleware that runs in-process. /// /// Remote services use the protobuf `SupervisorMiddleware` contract instead. /// The borrowed view remains valid for the evaluation future, so implementations /// can yield without constructing an owned protobuf request envelope. +/// WebSocket sessions already use bounded channel and stream ownership, so that +/// operation is shared with the transport-neutral endpoint contract. /// /// Downstream implementations must apply `#[async_trait::async_trait]` to each /// `impl InProcessMiddleware` block. The macro's default expansion creates @@ -135,9 +174,10 @@ impl<'a> HttpRequestView<'a> { /// bindings: vec![MiddlewareBinding { /// operation: SupervisorMiddlewareOperation::HttpRequest as i32, /// phase: SupervisorMiddlewarePhase::PreCredentials as i32, -/// max_body_bytes: 1024, +/// max_payload_bytes: 1024, /// timeout: String::new(), /// }], +/// expected_audience: String::new(), /// } /// } /// @@ -190,6 +230,18 @@ pub trait InProcessMiddleware: Send + Sync { &self, request: HttpRequestView<'_>, ) -> Result; + + /// Open one persistent WebSocket middleware session. + /// + /// HTTP-only implementations may keep the default unsupported response. + async fn open_websocket_session( + &self, + _requests: mpsc::Receiver, + ) -> std::result::Result { + Err(Status::unimplemented( + "middleware does not implement WebSocket sessions", + )) + } } /// Default timeout for one supervisor middleware RPC. @@ -198,6 +250,18 @@ pub const DEFAULT_MIDDLEWARE_TIMEOUT: Duration = Duration::from_millis(500); pub const MIN_MIDDLEWARE_TIMEOUT: Duration = Duration::from_millis(10); /// Largest operator-configured supervisor middleware RPC timeout. pub const MAX_MIDDLEWARE_TIMEOUT: Duration = Duration::from_secs(30); +/// Maximum time a complete message may spend in all middleware stages. +pub const MAX_MIDDLEWARE_CHAIN_TIMEOUT: Duration = Duration::from_secs(30); +/// Maximum time WebSocket preflight may delay an upstream handshake. +pub const MAX_MIDDLEWARE_PREFLIGHT_TIMEOUT: Duration = Duration::from_secs(1); +/// Process-wide safety valve for concurrently buffered middleware work. +pub const MAX_CONCURRENT_MIDDLEWARE_WORK: usize = 32; +/// Process-wide safety valve for retained streaming middleware sessions. +/// +/// A session consumes one permit regardless of its protocol or stage fan-out. +/// Persistent middleware protocols must acquire from this shared budget before +/// opening streams and retain the permit while any stage remains active. +pub const MAX_CONCURRENT_MIDDLEWARE_SESSIONS: usize = 32; /// Largest number of middleware configurations accepted in one sandbox policy. pub const MAX_MIDDLEWARE_CONFIGS: usize = 10; diff --git a/crates/openshell-driver-docker/src/lib.rs b/crates/openshell-driver-docker/src/lib.rs index 4621852fc9..9ac14c1871 100644 --- a/crates/openshell-driver-docker/src/lib.rs +++ b/crates/openshell-driver-docker/src/lib.rs @@ -38,8 +38,9 @@ use openshell_core::progress::{ }; use openshell_core::proto::compute::v1::{ CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, - DriverCondition, DriverPlatformEvent, DriverSandbox, DriverSandboxStatus, - DriverSandboxTemplate, GatewayListenerRequirement, GetCapabilitiesRequest, + DeleteWorkspaceRequest, DeleteWorkspaceResponse, DriverCondition, DriverPlatformEvent, + DriverSandbox, DriverSandboxStatus, DriverSandboxTemplate, EnsureWorkspaceRequest, + EnsureWorkspaceResponse, GatewayListenerRequirement, GetCapabilitiesRequest, GetCapabilitiesResponse, GetGatewayListenerRequirementsRequest, GetGatewayListenerRequirementsResponse, GetSandboxRequest, GetSandboxResponse, GpuResourceRequirements, ListSandboxesRequest, ListSandboxesResponse, StartSandboxRequest, @@ -1761,6 +1762,20 @@ impl ComputeDriver for DockerComputeDriver { Ok(Response::new(Box::pin(ReceiverStream::new(out_rx)))) } + + async fn ensure_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(EnsureWorkspaceResponse {})) + } + + async fn delete_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(DeleteWorkspaceResponse {})) + } } impl DockerProvisioningFailure { diff --git a/crates/openshell-driver-kubernetes-secrets/src/lib.rs b/crates/openshell-driver-kubernetes-secrets/src/lib.rs index 65c655be16..91224212bd 100644 --- a/crates/openshell-driver-kubernetes-secrets/src/lib.rs +++ b/crates/openshell-driver-kubernetes-secrets/src/lib.rs @@ -48,10 +48,33 @@ impl CredentialDriverService { } } +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Deserialize)] +#[serde(rename_all = "snake_case")] +enum WorkspaceMode { + #[default] + Shared, + Managed, + Operator, +} + #[derive(Debug, Clone, PartialEq, Eq)] struct KubernetesSecretsDriverSettings { namespace: String, allow_reference_namespace: bool, + workspace_mode: WorkspaceMode, + gateway_id: String, +} + +impl KubernetesSecretsDriverSettings { + fn target_namespace(&self, workspace: &str) -> String { + match self.workspace_mode { + WorkspaceMode::Shared => self.namespace.clone(), + WorkspaceMode::Managed => { + format!("openshell-{}-{}", self.gateway_id, workspace) + } + WorkspaceMode::Operator => workspace.to_string(), + } + } } #[derive(Debug, Clone, Default, serde::Deserialize)] @@ -59,6 +82,8 @@ struct KubernetesSecretsDriverSettings { struct KubernetesSecretsDriverConfig { namespace: Option, allow_reference_namespace: bool, + workspace_mode: WorkspaceMode, + gateway_id: Option, } #[derive(Debug, Clone, PartialEq, Eq)] @@ -134,7 +159,10 @@ impl KubernetesSecretsCredentialDriver { credential_key: &str, ) -> Result { let reference = Self::parse_handle(handle, credential_key)?; - if reference.namespace != self.settings.namespace + // In managed/operator modes secrets live in workspace-specific + // namespaces so cross-namespace handles are expected. + if self.settings.workspace_mode == WorkspaceMode::Shared + && reference.namespace != self.settings.namespace && !self.settings.allow_reference_namespace { return Err(Status::permission_denied(format!( @@ -175,7 +203,7 @@ impl KubernetesSecretsCredentialDriver { reference } else { KubernetesSecretReference { - namespace: self.settings.namespace.clone(), + namespace: self.settings.target_namespace(&request.workspace), secret_name: managed_secret_name( &request.workspace, &request.provider_id, @@ -504,10 +532,29 @@ impl KubernetesSecretsDriverSettings { } None => default_namespace(), }; + let gateway_id = config.gateway_id.unwrap_or_default(); + if config.workspace_mode == WorkspaceMode::Managed { + let gateway_id = trimmed_config_string("gateway_id", &gateway_id)?; + if !is_dns_label(gateway_id) { + return Err(Error::config( + "[openshell.credential_drivers.kubernetes-secrets] gateway_id must be a DNS-1123 label in managed workspace mode", + )); + } + // Workspace names are limited to 19 characters by the gateway. + // Keep the longest generated namespace within Kubernetes' 63-char + // DNS label limit, matching the Kubernetes compute driver. + if "openshell-".len() + gateway_id.len() + 1 + 19 > 63 { + return Err(Error::config( + "[openshell.credential_drivers.kubernetes-secrets] gateway_id is too long for managed workspace mode", + )); + } + } Ok(Self { namespace, allow_reference_namespace: config.allow_reference_namespace, + workspace_mode: config.workspace_mode, + gateway_id, }) } } @@ -778,6 +825,50 @@ mod tests { assert!(err.to_string().contains("namespace")); } + #[test] + fn settings_managed_mode_requires_gateway_id() { + let err = KubernetesSecretsDriverSettings::from_table(&toml::toml! { + workspace_mode = "managed" + }) + .unwrap_err(); + + assert!(err.to_string().contains("gateway_id")); + } + + #[test] + fn settings_managed_mode_rejects_invalid_gateway_id() { + let err = KubernetesSecretsDriverSettings::from_table(&toml::toml! { + workspace_mode = "managed" + gateway_id = "Invalid_Gateway" + }) + .unwrap_err(); + + assert!(err.to_string().contains("DNS-1123")); + } + + #[test] + fn settings_managed_mode_rejects_gateway_id_that_is_too_long() { + let gateway_id = "a".repeat(35); + let err = KubernetesSecretsDriverSettings::from_table(&toml::toml! { + workspace_mode = "managed" + gateway_id = gateway_id + }) + .unwrap_err(); + + assert!(err.to_string().contains("too long")); + } + + #[test] + fn settings_managed_mode_accepts_valid_gateway_id() { + let settings = KubernetesSecretsDriverSettings::from_table(&toml::toml! { + workspace_mode = "managed" + gateway_id = "gateway-1" + }) + .unwrap(); + + assert_eq!(settings.gateway_id, "gateway-1"); + } + #[test] fn handle_resolves_secret_reference() { let reference = KubernetesSecretsCredentialDriver::parse_handle( @@ -842,6 +933,8 @@ mod tests { let settings = KubernetesSecretsDriverSettings { namespace: "openshell".to_string(), allow_reference_namespace: false, + workspace_mode: WorkspaceMode::Shared, + gateway_id: String::new(), }; let reference = KubernetesSecretsCredentialDriver::parse_handle( &handle("v1:other-namespace:provider-secret"), @@ -865,6 +958,8 @@ mod tests { let settings = KubernetesSecretsDriverSettings { namespace: "openshell".to_string(), allow_reference_namespace: true, + workspace_mode: WorkspaceMode::Shared, + gateway_id: String::new(), }; let reference = KubernetesSecretsCredentialDriver::parse_handle( &handle("v1:other-namespace:provider-secret"), @@ -1065,4 +1160,40 @@ mod tests { assert_eq!(err.code(), Code::FailedPrecondition); assert!(err.message().contains("is not managed by OpenShell")); } + + #[test] + fn target_namespace_shared_returns_static_namespace() { + let settings = KubernetesSecretsDriverSettings { + namespace: "openshell".to_string(), + allow_reference_namespace: false, + workspace_mode: WorkspaceMode::Shared, + gateway_id: String::new(), + }; + assert_eq!(settings.target_namespace("team-a"), "openshell"); + assert_eq!(settings.target_namespace("team-b"), "openshell"); + } + + #[test] + fn target_namespace_managed_computes_from_workspace() { + let settings = KubernetesSecretsDriverSettings { + namespace: "openshell".to_string(), + allow_reference_namespace: false, + workspace_mode: WorkspaceMode::Managed, + gateway_id: "gw1".to_string(), + }; + assert_eq!(settings.target_namespace("team-a"), "openshell-gw1-team-a"); + assert_eq!(settings.target_namespace("team-b"), "openshell-gw1-team-b"); + } + + #[test] + fn target_namespace_operator_uses_workspace_name() { + let settings = KubernetesSecretsDriverSettings { + namespace: "openshell".to_string(), + allow_reference_namespace: false, + workspace_mode: WorkspaceMode::Operator, + gateway_id: String::new(), + }; + assert_eq!(settings.target_namespace("team-a"), "team-a"); + assert_eq!(settings.target_namespace("prod-ns"), "prod-ns"); + } } diff --git a/crates/openshell-driver-kubernetes/Cargo.toml b/crates/openshell-driver-kubernetes/Cargo.toml index f9f5bba398..714b7d05c9 100644 --- a/crates/openshell-driver-kubernetes/Cargo.toml +++ b/crates/openshell-driver-kubernetes/Cargo.toml @@ -34,6 +34,7 @@ tracing = { workspace = true } tracing-subscriber = { workspace = true } thiserror = { workspace = true } miette = { workspace = true } +notify = "8" [dev-dependencies] temp-env = "0.3" diff --git a/crates/openshell-driver-kubernetes/README.md b/crates/openshell-driver-kubernetes/README.md index d9c0e17fd8..ec37c4e67a 100644 --- a/crates/openshell-driver-kubernetes/README.md +++ b/crates/openshell-driver-kubernetes/README.md @@ -3,8 +3,31 @@ Kubernetes-backed compute driver for OpenShell cluster deployments. The driver uses the Kubernetes API to create, delete, fetch, and watch sandbox -custom resources in the configured namespace. It runs in-process with the -gateway server. +custom resources. It runs in-process with the gateway server and supports three +workspace namespace modes via `workspace_mode`: + +- **Shared** (default): All sandboxes render into a single static namespace. + Resource names use `{workspace}--{name}` for collision avoidance. +- **Managed**: The driver auto-creates/deletes a K8s namespace per workspace + (`openshell-{gateway_id}-{workspace_name}`), creates a ServiceAccount in each, + and copies OpenShift SCC annotations from the gateway namespace when present. +- **Operator**: Workspace names map 1:1 to pre-provisioned namespaces discovered + through exactly one source: either a label selector + (`operator_namespace_label`) or a drop-in allowlist file + (`operator_namespace_file`). Sandbox creation fails closed if the workspace + namespace is not in the current allowlist. Workspace deletion only removes + gateway state; it never deletes or otherwise accesses the operator-managed + Kubernetes namespace. + +Workspace namespace modes assume exclusive control of the sandbox identity +resource chain. In shared and managed modes, only the gateway and its trusted +Agent Sandbox controller may administer the sandbox namespace, Sandbox CRs, +sandbox pods, or configured sandbox ServiceAccount. In operator mode, the +platform operator owns namespace lifecycle but must prevent other principals +from creating or mutating Sandbox CRs, creating sandbox pods with fabricated +owner references, or using the configured sandbox ServiceAccount. Treat adding +a namespace to the operator allowlist as granting this trust; the allowlist is +not a tenant isolation boundary. ## Runtime Model diff --git a/crates/openshell-driver-kubernetes/src/config.rs b/crates/openshell-driver-kubernetes/src/config.rs index 4ca02bd71c..bfa08a6642 100644 --- a/crates/openshell-driver-kubernetes/src/config.rs +++ b/crates/openshell-driver-kubernetes/src/config.rs @@ -3,8 +3,13 @@ use openshell_core::config; use serde::{Deserialize, Deserializer, Serialize}; +use std::collections::{BTreeMap, BTreeSet}; use std::path::Path; use std::str::FromStr; +use std::sync::{Arc, RwLock}; + +/// Default gateway identity used in managed-mode namespace naming. +pub const DEFAULT_GATEWAY_ID: &str = "openshell"; /// Default Kubernetes namespace for sandbox resources. pub const DEFAULT_K8S_NAMESPACE: &str = "openshell"; @@ -88,6 +93,48 @@ impl FromStr for SupervisorTopology { } } +/// How workspaces map to Kubernetes namespaces. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "kebab-case")] +pub enum WorkspaceMode { + /// All sandboxes render into a single statically-configured namespace. + /// Resource names use `{workspace}--{name}` for collision avoidance. + #[default] + Shared, + /// The driver creates and deletes K8s namespaces on demand using the + /// convention `openshell-{gateway_id}-{workspace_name}`. + Managed, + /// Sandboxes render into pre-existing K8s namespaces. The driver has no + /// namespace create/delete permissions. Platform teams manage namespaces + /// via their existing tooling. + Operator, +} + +impl std::fmt::Display for WorkspaceMode { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Shared => f.write_str("shared"), + Self::Managed => f.write_str("managed"), + Self::Operator => f.write_str("operator"), + } + } +} + +impl FromStr for WorkspaceMode { + type Err = String; + + fn from_str(s: &str) -> Result { + match s { + "shared" => Ok(Self::Shared), + "managed" => Ok(Self::Managed), + "operator" => Ok(Self::Operator), + other => Err(format!( + "unknown workspace mode '{other}'; expected 'shared', 'managed', or 'operator'" + )), + } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct KubernetesSidecarConfig { @@ -232,7 +279,24 @@ where #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(default, deny_unknown_fields)] pub struct KubernetesComputeConfig { + /// How workspaces map to Kubernetes namespaces. `"shared"` (default) + /// renders all sandboxes into `namespace`; `"managed"` creates per-workspace + /// namespaces on demand; `"operator"` uses pre-provisioned namespaces. + pub workspace_mode: WorkspaceMode, + /// Stable gateway identity used in managed-mode namespace naming + /// (`openshell-{gateway_id}-{workspace}`). Propagated from + /// `gateway_jwt.gateway_id`. + pub gateway_id: String, pub namespace: String, + /// K8s label selector for operator-mode namespace discovery (e.g., + /// `"openshell.ai/workspace=true"`). The driver watches namespaces matching + /// this label and builds the allowlist dynamically. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub operator_namespace_label: Option, + /// Path to a JSON file containing an array of namespace names allowed in + /// operator mode. Hot-reloaded on change. Delivered via `ConfigMap` volume mount. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub operator_namespace_file: Option, /// Kubernetes `ServiceAccount` assigned to sandbox pods and accepted by /// the gateway's `TokenReview` bootstrap authenticator. pub service_account_name: String, @@ -240,6 +304,10 @@ pub struct KubernetesComputeConfig { pub image_pull_policy: String, /// Kubernetes `imagePullSecrets` names attached to sandbox pods. pub image_pull_secrets: Vec, + /// Managed-mode SSH ingress isolation. When enabled, the driver creates a + /// `NetworkPolicy` in each managed workspace namespace that permits TCP 2222 + /// only from gateway pods matching this peer. + pub managed_ssh_ingress: ManagedSshIngressConfig, /// Image that provides the `openshell-sandbox` supervisor binary. /// Mounted directly as an image volume, or copied via an init container, /// depending on `supervisor_sideload_method`. @@ -328,6 +396,14 @@ pub struct KubernetesComputeConfig { pub sandbox_gid: Option, } +#[derive(Debug, Clone, Default, Serialize, Deserialize)] +#[serde(default, deny_unknown_fields)] +pub struct ManagedSshIngressConfig { + pub enabled: bool, + pub gateway_namespace: String, + pub gateway_pod_selector: BTreeMap, +} + /// Lower bound enforced by kubelet for projected SA tokens. pub const MIN_SA_TOKEN_TTL_SECS: i64 = 600; @@ -351,7 +427,11 @@ pub const ANNOTATION_SCC_SUPPLEMENTAL_GROUPS: &str = "openshift.io/sa.scc.supple impl Default for KubernetesComputeConfig { fn default() -> Self { Self { + workspace_mode: WorkspaceMode::default(), + gateway_id: DEFAULT_GATEWAY_ID.to_string(), namespace: DEFAULT_K8S_NAMESPACE.to_string(), + operator_namespace_label: None, + operator_namespace_file: None, service_account_name: DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME.to_string(), default_image: openshell_core::image::default_sandbox_image(), // Default empty so the gateway omits `imagePullPolicy` from pod @@ -360,6 +440,7 @@ impl Default for KubernetesComputeConfig { // is Podman vocabulary and is not a valid Kubernetes value. image_pull_policy: String::new(), image_pull_secrets: Vec::new(), + managed_ssh_ingress: ManagedSshIngressConfig::default(), supervisor_image: config::default_supervisor_image(), supervisor_image_pull_policy: String::new(), supervisor_sideload_method: SupervisorSideloadMethod::default(), @@ -525,7 +606,7 @@ impl KubernetesComputeConfig { /// 3. Fallback defaults: UID=`1000`, GID=UID pub fn resolve_sandbox_uid( &self, - namespace_annotations: Option<&std::collections::BTreeMap>, + namespace_annotations: Option<&BTreeMap>, ) -> u32 { if let Some(uid) = self.sandbox_uid { return uid; @@ -543,7 +624,7 @@ impl KubernetesComputeConfig { pub fn resolve_sandbox_gid( &self, resolved_uid: u32, - _namespace_annotations: Option<&std::collections::BTreeMap>, + _namespace_annotations: Option<&BTreeMap>, ) -> u32 { self.sandbox_gid .or(self.sandbox_uid) @@ -593,6 +674,251 @@ impl KubernetesComputeConfig { } Ok(()) } + + /// Resolve the K8s namespace for a workspace. + /// + /// - **Shared:** returns the static `namespace` config field. + /// - **Managed:** computes `openshell-{gateway_id}-{workspace_name}`. + /// - **Operator:** looks up `workspace` in the dynamic allowlist. Fails + /// closed if the workspace is not found. + pub fn namespace_for_workspace( + &self, + workspace: &str, + operator_allowlist: Option<&OperatorNamespaceAllowlist>, + ) -> Result { + match self.workspace_mode { + WorkspaceMode::Shared => Ok(self.namespace.clone()), + WorkspaceMode::Managed => Ok(managed_namespace(&self.gateway_id, workspace)), + WorkspaceMode::Operator => { + let allowlist = + operator_allowlist.ok_or("operator mode requires a namespace allowlist")?; + let namespaces = allowlist.read(); + if namespaces.contains(workspace) { + Ok(workspace.to_string()) + } else { + Err(format!( + "workspace '{workspace}' is not in the operator namespace allowlist" + )) + } + } + } + } + + /// Whether the driver operates across multiple namespaces. + #[must_use] + pub fn is_multi_namespace(&self) -> bool { + !matches!(self.workspace_mode, WorkspaceMode::Shared) + } + + /// Compute the K8s resource name for a sandbox. + /// + /// - **Shared:** `{workspace}--{name}` (namespace doesn't provide isolation). + /// - **Managed/Operator:** bare sandbox name (namespace provides isolation). + #[must_use] + pub fn kube_resource_name(&self, workspace: &str, name: &str) -> String { + match self.workspace_mode { + WorkspaceMode::Shared => format!("{workspace}--{name}"), + WorkspaceMode::Managed | WorkspaceMode::Operator => name.to_string(), + } + } + + /// Validate workspace-mode-specific configuration at startup. + pub fn validate_workspace_mode(&self) -> Result<(), String> { + match self.workspace_mode { + WorkspaceMode::Shared => Ok(()), + WorkspaceMode::Managed => { + if self.gateway_id.is_empty() { + return Err("managed workspace mode requires a non-empty gateway_id".into()); + } + if !is_dns_1123_label(&self.gateway_id) { + return Err(format!( + "gateway_id '{}' is not a valid DNS-1123 label", + self.gateway_id + )); + } + // Workspace names can be up to 19 chars (MAX_ROUTABLE_NAME_LEN + // in the server crate). The managed namespace prefix + + // workspace must fit within 63 chars. + let prefix = managed_namespace_prefix(&self.gateway_id); + if prefix.len() + 19 > 63 { + return Err(format!( + "gateway_id '{}' is too long for managed mode; \ + the namespace prefix '{}' ({} chars) plus the \ + maximum workspace name (19 chars) exceeds the \ + 63-char K8s namespace limit", + self.gateway_id, + prefix, + prefix.len() + )); + } + if self.managed_ssh_ingress.enabled { + if self.managed_ssh_ingress.gateway_namespace.is_empty() { + return Err( + "managed SSH ingress isolation requires gateway_namespace".into() + ); + } + if self.managed_ssh_ingress.gateway_pod_selector.is_empty() { + return Err( + "managed SSH ingress isolation requires gateway_pod_selector".into(), + ); + } + } + Ok(()) + } + WorkspaceMode::Operator => { + if self.operator_namespace_label.is_none() && self.operator_namespace_file.is_none() + { + return Err("operator workspace mode requires exactly one of \ + operator_namespace_label or operator_namespace_file" + .into()); + } + if self.operator_namespace_label.is_some() && self.operator_namespace_file.is_some() + { + return Err("operator workspace mode requires exactly one of \ + operator_namespace_label or operator_namespace_file, not both" + .into()); + } + if let Some(ref label) = self.operator_namespace_label + && label.is_empty() + { + return Err("operator_namespace_label must not be empty when set".into()); + } + if let Some(ref file) = self.operator_namespace_file + && file.is_empty() + { + return Err("operator_namespace_file must not be empty when set".into()); + } + Ok(()) + } + } + } +} + +/// Compute the managed-mode namespace name for a workspace. +#[must_use] +pub fn managed_namespace(gateway_id: &str, workspace: &str) -> String { + format!("openshell-{gateway_id}-{workspace}") +} + +/// The managed-mode namespace prefix used for SA token validation. +#[must_use] +pub fn managed_namespace_prefix(gateway_id: &str) -> String { + format!("openshell-{gateway_id}-") +} + +/// Check whether a string is a valid DNS-1123 label (lowercase alphanumeric +/// and hyphens, 1-63 chars, must start and end with alphanumeric). +#[must_use] +pub fn is_dns_1123_label(s: &str) -> bool { + let len = s.len(); + if len == 0 || len > 63 { + return false; + } + let bytes = s.as_bytes(); + if !bytes[0].is_ascii_lowercase() && !bytes[0].is_ascii_digit() { + return false; + } + if !bytes[len - 1].is_ascii_lowercase() && !bytes[len - 1].is_ascii_digit() { + return false; + } + bytes + .iter() + .all(|&b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +/// Validate that a workspace name produces a valid K8s namespace name in +/// managed mode (combined length <= 63, DNS-1123 compliant). +pub fn validate_managed_namespace_name(gateway_id: &str, workspace: &str) -> Result<(), String> { + let ns = managed_namespace(gateway_id, workspace); + if !is_dns_1123_label(&ns) { + return Err(format!( + "managed namespace '{ns}' (from workspace '{workspace}') is not a valid DNS-1123 label" + )); + } + Ok(()) +} + +/// Thread-safe dynamic allowlist of valid operator-mode namespaces. +/// +/// Backed by an `Arc>>` that is updated by background +/// tasks (label selector watcher, drop-in file watcher) and read by the SA +/// authenticator and namespace resolver. +#[derive(Debug, Clone)] +pub struct OperatorNamespaceAllowlist { + inner: Arc>>, +} + +impl OperatorNamespaceAllowlist { + fn read_guard(&self) -> std::sync::RwLockReadGuard<'_, BTreeSet> { + self.inner + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn write_guard(&self) -> std::sync::RwLockWriteGuard<'_, BTreeSet> { + self.inner + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + #[must_use] + pub fn new() -> Self { + Self { + inner: Arc::new(RwLock::new(BTreeSet::new())), + } + } + + #[must_use] + pub fn from_set(set: BTreeSet) -> Self { + Self { + inner: Arc::new(RwLock::new(set)), + } + } + + /// Replace the entire allowlist (used by background watchers on refresh). + pub fn replace(&self, new_set: BTreeSet) { + let mut guard = self.write_guard(); + *guard = new_set; + } + + /// Merge additional namespaces into the allowlist. + pub fn merge(&self, additional: &BTreeSet) { + let mut guard = self.write_guard(); + guard.extend(additional.iter().cloned()); + } + + /// Read the current allowlist snapshot. + pub fn read(&self) -> std::sync::RwLockReadGuard<'_, BTreeSet> { + self.read_guard() + } + + /// Check whether a namespace is in the allowlist. + #[must_use] + pub fn contains(&self, namespace: &str) -> bool { + self.read_guard().contains(namespace) + } + + /// Insert a namespace into the allowlist. Returns `true` if it was new. + pub fn insert(&self, name: String) -> bool { + self.write_guard().insert(name) + } + + /// Remove a namespace from the allowlist. Returns `true` if it was present. + pub fn remove(&self, name: &str) -> bool { + self.write_guard().remove(name) + } + + /// Return a clone of the inner `Arc` for sharing with background tasks. + #[must_use] + pub fn shared(&self) -> Arc>> { + Arc::clone(&self.inner) + } +} + +impl Default for OperatorNamespaceAllowlist { + fn default() -> Self { + Self::new() + } } fn is_dns1123_subdomain(value: &str) -> bool { @@ -1176,6 +1502,46 @@ mod tests { } } + // -- WorkspaceMode tests -- + + #[test] + fn default_workspace_mode_is_shared() { + let cfg = KubernetesComputeConfig::default(); + assert_eq!(cfg.workspace_mode, WorkspaceMode::Shared); + } + + #[test] + fn serde_override_workspace_mode_managed() { + let json = serde_json::json!({ "workspace_mode": "managed" }); + let cfg: KubernetesComputeConfig = serde_json::from_value(json).unwrap(); + assert_eq!(cfg.workspace_mode, WorkspaceMode::Managed); + } + + #[test] + fn serde_override_workspace_mode_operator() { + let json = serde_json::json!({ "workspace_mode": "operator" }); + let cfg: KubernetesComputeConfig = serde_json::from_value(json).unwrap(); + assert_eq!(cfg.workspace_mode, WorkspaceMode::Operator); + } + + #[test] + fn serde_rejects_invalid_workspace_mode() { + let json = serde_json::json!({ "workspace_mode": "invalid" }); + let err = serde_json::from_value::(json).unwrap_err(); + assert!(err.to_string().contains("unknown variant")); + } + + #[test] + fn workspace_mode_display_roundtrips() { + for mode in [ + WorkspaceMode::Shared, + WorkspaceMode::Managed, + WorkspaceMode::Operator, + ] { + assert_eq!(mode.to_string().parse::().unwrap(), mode); + } + } + #[test] fn upstream_proxy_config_rejects_unsupported_proxy_scheme() { let cfg = KubernetesComputeConfig { @@ -1261,4 +1627,306 @@ mod tests { }; assert!(cfg.validate_upstream_proxy_config().is_ok()); } + + #[test] + fn namespace_for_workspace_shared() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Shared, + namespace: "sandbox-ns".to_string(), + ..KubernetesComputeConfig::default() + }; + assert_eq!( + cfg.namespace_for_workspace("team-a", None).unwrap(), + "sandbox-ns" + ); + assert_eq!( + cfg.namespace_for_workspace("team-b", None).unwrap(), + "sandbox-ns" + ); + } + + #[test] + fn namespace_for_workspace_managed() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Managed, + gateway_id: "gw1".to_string(), + ..KubernetesComputeConfig::default() + }; + assert_eq!( + cfg.namespace_for_workspace("team-a", None).unwrap(), + "openshell-gw1-team-a" + ); + } + + #[test] + fn namespace_for_workspace_operator() { + let allowlist = OperatorNamespaceAllowlist::from_set(BTreeSet::from(["prod".to_string()])); + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Operator, + operator_namespace_label: Some("openshell.ai/workspace=true".to_string()), + ..KubernetesComputeConfig::default() + }; + assert_eq!( + cfg.namespace_for_workspace("prod", Some(&allowlist)) + .unwrap(), + "prod" + ); + assert!( + cfg.namespace_for_workspace("unknown", Some(&allowlist)) + .is_err() + ); + } + + #[test] + fn namespace_for_workspace_operator_requires_allowlist() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Operator, + operator_namespace_label: Some("openshell.ai/workspace=true".to_string()), + ..KubernetesComputeConfig::default() + }; + + let err = cfg.namespace_for_workspace("prod", None).unwrap_err(); + assert_eq!(err, "operator mode requires a namespace allowlist"); + } + + #[test] + fn kube_resource_name_shared_prefixes_workspace() { + let cfg = KubernetesComputeConfig::default(); + assert_eq!(cfg.kube_resource_name("ws", "box1"), "ws--box1"); + } + + #[test] + fn kube_resource_name_managed_uses_bare_name() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Managed, + ..KubernetesComputeConfig::default() + }; + assert_eq!(cfg.kube_resource_name("ws", "box1"), "box1"); + } + + #[test] + fn kube_resource_name_operator_uses_bare_name() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Operator, + operator_namespace_label: Some("x=y".to_string()), + ..KubernetesComputeConfig::default() + }; + assert_eq!(cfg.kube_resource_name("ws", "box1"), "box1"); + } + + #[test] + fn is_multi_namespace() { + assert!(!KubernetesComputeConfig::default().is_multi_namespace()); + assert!( + KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Managed, + ..KubernetesComputeConfig::default() + } + .is_multi_namespace() + ); + assert!( + KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Operator, + operator_namespace_label: Some("x=y".to_string()), + ..KubernetesComputeConfig::default() + } + .is_multi_namespace() + ); + } + + #[test] + fn validate_workspace_mode_shared_always_ok() { + let cfg = KubernetesComputeConfig::default(); + cfg.validate_workspace_mode().unwrap(); + } + + #[test] + fn validate_workspace_mode_managed_requires_gateway_id() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Managed, + gateway_id: String::new(), + ..KubernetesComputeConfig::default() + }; + assert!(cfg.validate_workspace_mode().is_err()); + } + + #[test] + fn validate_workspace_mode_managed_rejects_invalid_gateway_id() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Managed, + gateway_id: "INVALID".to_string(), + ..KubernetesComputeConfig::default() + }; + assert!(cfg.validate_workspace_mode().is_err()); + } + + #[test] + fn validate_workspace_mode_managed_rejects_long_gateway_id() { + // prefix = "openshell-{id}-" = 11 + id.len() + // 11 + 34 + 19 = 64 > 63 → rejected + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Managed, + gateway_id: "a".repeat(34), + ..KubernetesComputeConfig::default() + }; + let err = cfg.validate_workspace_mode().unwrap_err(); + assert!(err.contains("too long for managed mode"), "{err}"); + } + + #[test] + fn validate_workspace_mode_managed_accepts_max_gateway_id() { + // 11 + 33 + 19 = 63 → accepted + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Managed, + gateway_id: "a".repeat(33), + ..KubernetesComputeConfig::default() + }; + cfg.validate_workspace_mode().unwrap(); + } + + #[test] + fn validate_workspace_mode_managed_requires_complete_ssh_ingress_peer() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Managed, + managed_ssh_ingress: ManagedSshIngressConfig { + enabled: true, + gateway_namespace: "gateway".to_string(), + gateway_pod_selector: BTreeMap::new(), + }, + ..KubernetesComputeConfig::default() + }; + let err = cfg.validate_workspace_mode().unwrap_err(); + assert!(err.contains("gateway_pod_selector"), "{err}"); + } + + #[test] + fn validate_workspace_mode_managed_accepts_complete_ssh_ingress_peer() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Managed, + managed_ssh_ingress: ManagedSshIngressConfig { + enabled: true, + gateway_namespace: "gateway".to_string(), + gateway_pod_selector: BTreeMap::from([( + "app.kubernetes.io/name".to_string(), + "openshell".to_string(), + )]), + }, + ..KubernetesComputeConfig::default() + }; + cfg.validate_workspace_mode().unwrap(); + } + + #[test] + fn validate_workspace_mode_operator_requires_discovery() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Operator, + ..KubernetesComputeConfig::default() + }; + assert!(cfg.validate_workspace_mode().is_err()); + } + + #[test] + fn validate_workspace_mode_operator_accepts_label_only() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Operator, + operator_namespace_label: Some("openshell.ai/workspace=true".to_string()), + ..KubernetesComputeConfig::default() + }; + cfg.validate_workspace_mode().unwrap(); + } + + #[test] + fn validate_workspace_mode_operator_accepts_file_only() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Operator, + operator_namespace_file: Some("/etc/openshell/namespaces.json".to_string()), + ..KubernetesComputeConfig::default() + }; + cfg.validate_workspace_mode().unwrap(); + } + + #[test] + fn validate_workspace_mode_operator_rejects_label_and_file() { + let cfg = KubernetesComputeConfig { + workspace_mode: WorkspaceMode::Operator, + operator_namespace_label: Some("openshell.ai/workspace=true".to_string()), + operator_namespace_file: Some("/etc/openshell/namespaces.json".to_string()), + ..KubernetesComputeConfig::default() + }; + + let err = cfg.validate_workspace_mode().unwrap_err(); + assert!(err.contains("not both"), "{err}"); + } + + #[test] + fn dns_1123_label_validation() { + assert!(is_dns_1123_label("openshell")); + assert!(is_dns_1123_label("my-gateway-1")); + assert!(is_dns_1123_label("a")); + assert!(!is_dns_1123_label("")); + assert!(!is_dns_1123_label("UPPER")); + assert!(!is_dns_1123_label("-starts-with-dash")); + assert!(!is_dns_1123_label("ends-with-dash-")); + assert!(!is_dns_1123_label("has_underscore")); + assert!(!is_dns_1123_label(&"a".repeat(64))); + } + + #[test] + fn managed_namespace_naming() { + assert_eq!( + managed_namespace("openshell", "default"), + "openshell-openshell-default" + ); + assert_eq!(managed_namespace("gw1", "team-a"), "openshell-gw1-team-a"); + } + + #[test] + fn validate_managed_namespace_name_accepts_valid() { + validate_managed_namespace_name("gw1", "team-a").unwrap(); + } + + #[test] + fn validate_managed_namespace_name_rejects_invalid_workspace_characters() { + let err = validate_managed_namespace_name("gw1", "INVALID").unwrap_err(); + assert!(err.contains("not a valid DNS-1123 label")); + } + + #[test] + fn validate_managed_namespace_name_rejects_too_long() { + let long_workspace = "a".repeat(50); + assert!(validate_managed_namespace_name("openshell", &long_workspace).is_err()); + } + + #[test] + fn operator_allowlist_operations() { + let al = OperatorNamespaceAllowlist::new(); + assert!(!al.contains("ns1")); + + al.replace(BTreeSet::from(["ns1".to_string(), "ns2".to_string()])); + assert!(al.contains("ns1")); + assert!(al.contains("ns2")); + assert!(!al.contains("ns3")); + + al.merge(&BTreeSet::from(["ns3".to_string()])); + assert!(al.contains("ns3")); + + al.replace(BTreeSet::new()); + assert!(!al.contains("ns1")); + } + + #[test] + fn operator_allowlist_recovers_from_poisoned_lock() { + let al = OperatorNamespaceAllowlist::from_set(BTreeSet::from(["ns1".to_string()])); + let shared = al.shared(); + let _ = std::thread::spawn(move || { + let _guard = shared.write().unwrap(); + panic!("poison allowlist lock"); + }) + .join(); + + assert!(al.contains("ns1")); + assert!(al.insert("ns2".to_string())); + assert!(al.read().contains("ns2")); + assert!(al.remove("ns1")); + } } diff --git a/crates/openshell-driver-kubernetes/src/driver.rs b/crates/openshell-driver-kubernetes/src/driver.rs index 0965c3676e..ddc7fe2a4f 100644 --- a/crates/openshell-driver-kubernetes/src/driver.rs +++ b/crates/openshell-driver-kubernetes/src/driver.rs @@ -6,14 +6,21 @@ use super::AppArmorProfile; use crate::config::{ DEFAULT_PROXY_UID, DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, DEFAULT_SANDBOX_UID, - DEFAULT_WORKSPACE_STORAGE_SIZE, KubernetesComputeConfig, SupervisorSideloadMethod, - SupervisorTopology, + DEFAULT_WORKSPACE_STORAGE_SIZE, KubernetesComputeConfig, OperatorNamespaceAllowlist, + SupervisorSideloadMethod, SupervisorTopology, WorkspaceMode, is_dns_1123_label, + managed_namespace, validate_managed_namespace_name, }; use futures::{Stream, StreamExt, TryStreamExt}; use k8s_openapi::api::core::v1::{ - Event as KubeEventObj, Namespace, Node, PersistentVolumeClaimVolumeSource, Pod, Volume, - VolumeMount, + Event as KubeEventObj, Namespace, Node, PersistentVolumeClaimVolumeSource, Pod, Secret, + ServiceAccount, Volume, VolumeMount, }; +use k8s_openapi::api::networking::v1::{ + NetworkPolicy, NetworkPolicyIngressRule, NetworkPolicyPeer, NetworkPolicyPort, + NetworkPolicySpec, +}; +use k8s_openapi::apimachinery::pkg::apis::meta::v1::LabelSelector; +use k8s_openapi::apimachinery::pkg::util::intstr::IntOrString; use kube::api::{ Api, ApiResource, DeleteParams, ListParams, Patch, PatchParams, PostParams, Preconditions, }; @@ -23,8 +30,9 @@ use kube::runtime::watcher::{self, Event}; use kube::{Client, Error as KubeError}; use openshell_core::driver_mounts; use openshell_core::driver_utils::{ - LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_SANDBOX_ID, LABEL_SANDBOX_NAME, - LABEL_SANDBOX_WORKSPACE, SUPERVISOR_IMAGE_BINARY_PATH, openshell_sandbox_label_selector, + LABEL_GATEWAY_ID, LABEL_MANAGED_BY, LABEL_MANAGED_BY_VALUE, LABEL_SANDBOX_ID, + LABEL_SANDBOX_NAME, LABEL_SANDBOX_WORKSPACE, SUPERVISOR_IMAGE_BINARY_PATH, + openshell_sandbox_label_selector, }; use openshell_core::gpu::{driver_gpu_requirements, effective_driver_gpu_count}; use openshell_core::progress::{ @@ -42,10 +50,10 @@ use openshell_core::proto::compute::v1::{ use openshell_core::proto_struct::{struct_to_json_object, value_to_json}; use serde::Deserialize; use std::collections::{BTreeMap, HashSet}; -use std::path::Path; +use std::path::{Path, PathBuf}; use std::pin::Pin; use std::sync::Arc; -use std::time::Duration; +use std::time::{Duration, SystemTime}; use tokio::sync::{OnceCell, mpsc}; use tokio_stream::wrappers::ReceiverStream; use tracing::{debug, info, warn}; @@ -53,10 +61,14 @@ use tracing::{debug, info, warn}; pub type WatchStream = Pin> + Send>>; +const MANAGED_SSH_NETWORK_POLICY_NAME: &str = "openshell-sandbox-ssh"; + #[derive(Debug, thiserror::Error)] pub enum KubernetesDriverError { #[error("sandbox already exists")] AlreadyExists, + #[error("sandbox not found")] + NotFound, #[error("{0}")] InvalidArgument(String), #[error("{0}")] @@ -78,6 +90,7 @@ impl From for openshell_core::ComputeDriverError { fn from(err: KubernetesDriverError) -> Self { match err { KubernetesDriverError::AlreadyExists => Self::AlreadyExists, + KubernetesDriverError::NotFound => Self::NotFound, KubernetesDriverError::InvalidArgument(m) => Self::InvalidArgument(m), KubernetesDriverError::Precondition(m) => Self::Precondition(m), KubernetesDriverError::Message(m) => Self::Message(m), @@ -344,23 +357,13 @@ fn validate_kubernetes_driver_volume_mounts( Ok(()) } -// TODO: replace with an openshell_core Kubernetes-name helper once available. -fn is_dns_label(label: &str) -> bool { - if label.is_empty() || label.len() > 63 || label.starts_with('-') || label.ends_with('-') { - return false; - } - label - .bytes() - .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-') -} - // TODO: replace with an openshell_core Kubernetes-name helper once available. fn is_dns_subdomain(value: &str) -> bool { - value.len() <= 253 && value.split('.').all(is_dns_label) + value.len() <= 253 && value.split('.').all(is_dns_1123_label) } fn validate_kubernetes_dns1123_label(value: &str, field: &str) -> Result<(), String> { - if !is_dns_label(value) { + if !is_dns_1123_label(value) { return Err(format!( "{field} must be a DNS-1123 label: use lowercase alphanumeric characters or '-', start and end with an alphanumeric character, and use at most 63 characters" )); @@ -450,6 +453,7 @@ pub struct KubernetesComputeDriver { watch_client: Client, sandbox_api_version: Arc>, config: KubernetesComputeConfig, + operator_allowlist: Option, } impl std::fmt::Debug for KubernetesComputeDriver { @@ -463,7 +467,13 @@ impl std::fmt::Debug for KubernetesComputeDriver { } impl KubernetesComputeDriver { - pub async fn new(config: KubernetesComputeConfig) -> Result { + pub async fn new( + config: KubernetesComputeConfig, + shutdown_rx: tokio::sync::watch::Receiver, + ) -> Result { + config + .validate_workspace_mode() + .map_err(KubernetesDriverError::Precondition)?; config .validate_provider_spiffe_workload_api_socket_path() .map_err(KubernetesDriverError::Precondition)?; @@ -497,12 +507,40 @@ impl KubernetesComputeDriver { let watch_client = Client::try_from(watch_kube_config).map_err(KubernetesDriverError::from_kube)?; - Ok(Self { + let operator_allowlist = if matches!(config.workspace_mode, WorkspaceMode::Operator) { + let allowlist = OperatorNamespaceAllowlist::new(); + + if let Some(ref label) = config.operator_namespace_label { + spawn_namespace_label_watcher( + watch_client.clone(), + label.clone(), + allowlist.clone(), + shutdown_rx.clone(), + ); + } + + if let Some(ref path) = config.operator_namespace_file { + spawn_namespace_file_watcher(path.into(), allowlist.clone(), shutdown_rx.clone()); + } + + Some(allowlist) + } else { + None + }; + + let driver = Self { client, watch_client, sandbox_api_version: Arc::new(OnceCell::new()), config, - }) + operator_allowlist, + }; + + if driver.workspace_mode() == WorkspaceMode::Shared { + driver.backfill_gateway_id_labels().await?; + } + + Ok(driver) } pub fn capabilities(&self) -> Result { @@ -513,6 +551,10 @@ impl KubernetesComputeDriver { )) } + pub fn operator_allowlist(&self) -> Option<&OperatorNamespaceAllowlist> { + self.operator_allowlist.as_ref() + } + pub fn default_image(&self) -> &str { &self.config.default_image } @@ -525,6 +567,437 @@ impl KubernetesComputeDriver { &self.config.ssh_socket_path } + pub fn workspace_mode(&self) -> WorkspaceMode { + self.config.workspace_mode + } + + pub(crate) fn validate_workspace_namespace( + &self, + workspace: &str, + ) -> Result<(), KubernetesDriverError> { + if self.config.workspace_mode == WorkspaceMode::Managed { + validate_managed_namespace_name(&self.config.gateway_id, workspace) + .map_err(KubernetesDriverError::InvalidArgument)?; + } + Ok(()) + } + + /// Backfill the `openshell.ai/gateway-id` label on Sandbox CRs that + /// predate its introduction. Runs once at startup in shared mode so that + /// label-selector based lookups continue to find legacy resources. + async fn backfill_gateway_id_labels(&self) -> Result<(), KubernetesDriverError> { + let sandbox_api = self + .supported_sandbox_api_for_lookup(self.client.clone()) + .await + .map_err(KubernetesDriverError::Message)?; + + let selector = openshell_sandbox_label_selector(); + let list = match tokio::time::timeout( + KUBE_API_TIMEOUT, + sandbox_api + .api + .list(&ListParams::default().labels(&selector)), + ) + .await + { + Ok(Ok(list)) => list, + Ok(Err(e)) => return Err(KubernetesDriverError::from_kube(e)), + Err(_) => { + return Err(KubernetesDriverError::Message( + "timeout listing Sandbox resources for gateway-id label backfill".to_string(), + )); + } + }; + + let gateway_id = &self.config.gateway_id; + for obj in &list { + if !gateway_id_label_needs_backfill(obj.metadata.labels.as_ref(), gateway_id) { + continue; + } + let Some(name) = obj.metadata.name.as_deref() else { + continue; + }; + let patch = serde_json::json!({ + "metadata": { + "labels": { + LABEL_GATEWAY_ID: gateway_id + } + } + }); + match tokio::time::timeout( + KUBE_API_TIMEOUT, + sandbox_api + .api + .patch(name, &PatchParams::default(), &Patch::Merge(&patch)), + ) + .await + { + Ok(Ok(_)) => { + info!(sandbox = %name, gateway_id, "backfilled gateway-id label"); + } + Ok(Err(e)) => return Err(KubernetesDriverError::from_kube(e)), + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout backfilling gateway-id label on Sandbox {name}" + ))); + } + } + } + + Ok(()) + } + + /// Ensure the K8s namespace for a workspace exists (managed mode only). + /// + /// Idempotent: returns the namespace name whether it was just created or + /// already existed. Also creates the sandbox `ServiceAccount` in the + /// namespace. + /// + pub async fn ensure_namespace(&self, workspace: &str) -> Result { + let ns_name = managed_namespace(&self.config.gateway_id, workspace); + let ns_api: Api = Api::all(self.client.clone()); + + let gateway_ns_annotations = match tokio::time::timeout( + KUBE_API_TIMEOUT, + ns_api.get(&self.config.namespace), + ) + .await + { + Ok(Ok(ns)) => ns.metadata.annotations.unwrap_or_default(), + Ok(Err(error)) => return Err(KubernetesDriverError::from_kube(error)), + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout getting gateway namespace {} for SCC annotations", + self.config.namespace + ))); + } + }; + + let mut labels = BTreeMap::new(); + labels.insert( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + ); + labels.insert(LABEL_GATEWAY_ID.to_string(), self.config.gateway_id.clone()); + labels.insert(LABEL_SANDBOX_WORKSPACE.to_string(), workspace.to_string()); + + let mut annotations = BTreeMap::new(); + for key in [ + crate::config::ANNOTATION_SCC_UID_RANGE, + crate::config::ANNOTATION_SCC_SUPPLEMENTAL_GROUPS, + ] { + if let Some(val) = gateway_ns_annotations.get(key) { + annotations.insert(key.to_string(), val.clone()); + } + } + + let ns = Namespace { + metadata: ObjectMeta { + name: Some(ns_name.clone()), + labels: Some(labels), + annotations: if annotations.is_empty() { + None + } else { + Some(annotations) + }, + ..Default::default() + }, + ..Default::default() + }; + + match tokio::time::timeout(KUBE_API_TIMEOUT, ns_api.create(&PostParams::default(), &ns)) + .await + { + Ok(Ok(_)) => { + info!(namespace = %ns_name, workspace = %workspace, "created managed namespace"); + } + Ok(Err(KubeError::Api(api))) if api.code == 409 => { + let existing = + match tokio::time::timeout(KUBE_API_TIMEOUT, ns_api.get(&ns_name)).await { + Ok(Ok(ns)) => ns, + Ok(Err(e)) => return Err(KubernetesDriverError::from_kube(e)), + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout reading namespace {ns_name}" + ))); + } + }; + if !is_namespace_owned_by_gateway( + existing.metadata.labels.as_ref(), + &self.config.gateway_id, + ) { + return Err(KubernetesDriverError::Precondition(format!( + "namespace {ns_name} exists but is not owned by this gateway" + ))); + } + debug!(namespace = %ns_name, "managed namespace already exists"); + } + Ok(Err(e)) => return Err(KubernetesDriverError::from_kube(e)), + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout creating namespace {ns_name}" + ))); + } + } + + self.ensure_service_account(&ns_name).await?; + self.ensure_managed_ssh_network_policy(&ns_name).await?; + + Ok(ns_name) + } + + async fn ensure_managed_ssh_network_policy( + &self, + namespace: &str, + ) -> Result<(), KubernetesDriverError> { + if !self.config.managed_ssh_ingress.enabled { + return Ok(()); + } + + let policy = managed_ssh_network_policy(namespace, &self.config); + let policy_api: Api = Api::namespaced(self.client.clone(), namespace); + match tokio::time::timeout( + KUBE_API_TIMEOUT, + policy_api.patch( + MANAGED_SSH_NETWORK_POLICY_NAME, + &PatchParams::apply("openshell"), + &Patch::Apply(&policy), + ), + ) + .await + { + Ok(Ok(_)) => { + info!(namespace, "applied managed sandbox SSH NetworkPolicy"); + Ok(()) + } + Ok(Err(error)) => Err(KubernetesDriverError::from_kube(error)), + Err(_) => Err(KubernetesDriverError::Message(format!( + "timeout applying SSH NetworkPolicy in {namespace}" + ))), + } + } + + async fn ensure_service_account(&self, namespace: &str) -> Result<(), KubernetesDriverError> { + let sa_api: Api = Api::namespaced(self.client.clone(), namespace); + let sa = ServiceAccount { + metadata: ObjectMeta { + name: Some(self.config.service_account_name.clone()), + labels: Some(BTreeMap::from([( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + )])), + ..Default::default() + }, + ..Default::default() + }; + + match tokio::time::timeout(KUBE_API_TIMEOUT, sa_api.create(&PostParams::default(), &sa)) + .await + { + Ok(Ok(_)) => { + info!(namespace = %namespace, sa = %self.config.service_account_name, "created service account"); + } + Ok(Err(KubeError::Api(api))) if api.code == 409 => {} + Ok(Err(e)) => return Err(KubernetesDriverError::from_kube(e)), + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout creating service account in {namespace}" + ))); + } + } + + Ok(()) + } + + /// Ensure the client TLS Secret exists in `namespace` by copying it from + /// the gateway's Helm release namespace. Idempotent: creates the Secret on + /// first call, updates it on subsequent calls to pick up cert rotations. + /// No-op when `client_tls_secret_name` is empty (TLS disabled). + async fn ensure_tls_secret(&self, namespace: &str) -> Result<(), KubernetesDriverError> { + if self.config.client_tls_secret_name.is_empty() { + return Ok(()); + } + + let source_api: Api = Api::namespaced(self.client.clone(), &self.config.namespace); + let source = match tokio::time::timeout( + KUBE_API_TIMEOUT, + source_api.get(&self.config.client_tls_secret_name), + ) + .await + { + Ok(Ok(s)) => s, + Ok(Err(e)) => { + warn!( + secret = %self.config.client_tls_secret_name, + source_namespace = %self.config.namespace, + error = %e, + "failed to read source TLS secret" + ); + return Err(KubernetesDriverError::from_kube(e)); + } + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout reading TLS secret {} from {}", + self.config.client_tls_secret_name, self.config.namespace + ))); + } + }; + + let target_api: Api = Api::namespaced(self.client.clone(), namespace); + let copy = Secret { + metadata: ObjectMeta { + name: Some(self.config.client_tls_secret_name.clone()), + namespace: Some(namespace.to_string()), + labels: Some(BTreeMap::from([( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + )])), + ..Default::default() + }, + data: source.data, + type_: source.type_, + ..Default::default() + }; + + match tokio::time::timeout( + KUBE_API_TIMEOUT, + target_api.patch( + &self.config.client_tls_secret_name, + &PatchParams::apply("openshell"), + &Patch::Apply(©), + ), + ) + .await + { + Ok(Ok(_)) => { + info!( + namespace = %namespace, + secret = %self.config.client_tls_secret_name, + "applied TLS secret copy" + ); + } + Ok(Err(e)) => return Err(KubernetesDriverError::from_kube(e)), + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout applying TLS secret in {namespace}" + ))); + } + } + + Ok(()) + } + + /// Copy the explicitly configured image-pull Secrets into a managed + /// workspace namespace. Server-side apply refreshes rotated credentials + /// without forcibly taking fields owned by another manager. + async fn ensure_image_pull_secrets( + &self, + namespace: &str, + ) -> Result<(), KubernetesDriverError> { + let source_api: Api = Api::namespaced(self.client.clone(), &self.config.namespace); + let target_api: Api = Api::namespaced(self.client.clone(), namespace); + + for secret_name in &self.config.image_pull_secrets { + let source = match tokio::time::timeout(KUBE_API_TIMEOUT, source_api.get(secret_name)) + .await + { + Ok(Ok(secret)) => secret, + Ok(Err(KubeError::Api(error))) if error.code == 404 => { + return Err(KubernetesDriverError::Precondition(format!( + "configured image-pull Secret {secret_name} does not exist in source namespace {}", + self.config.namespace + ))); + } + Ok(Err(error)) => return Err(KubernetesDriverError::from_kube(error)), + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout reading image-pull Secret {secret_name} from {}", + self.config.namespace + ))); + } + }; + + let copy = image_pull_secret_copy(secret_name, namespace, source); + match tokio::time::timeout( + KUBE_API_TIMEOUT, + target_api.patch( + secret_name, + &PatchParams::apply("openshell"), + &Patch::Apply(©), + ), + ) + .await + { + Ok(Ok(_)) => { + info!(namespace, secret = %secret_name, "applied image-pull Secret copy"); + } + Ok(Err(error)) => return Err(KubernetesDriverError::from_kube(error)), + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout applying image-pull Secret {secret_name} in {namespace}" + ))); + } + } + } + + Ok(()) + } + + /// Delete the managed namespace and all its contents (managed mode only). + /// Called via the `DeleteWorkspace` RPC after workspace deletion. + /// Kubernetes cascades namespace deletion to all resources within it. + pub async fn delete_namespace(&self, workspace: &str) -> Result<(), KubernetesDriverError> { + let ns_name = managed_namespace(&self.config.gateway_id, workspace); + let ns_api: Api = Api::all(self.client.clone()); + + let ns = match tokio::time::timeout(KUBE_API_TIMEOUT, ns_api.get(&ns_name)).await { + Ok(Ok(ns)) => ns, + Ok(Err(KubeError::Api(api))) if api.code == 404 => { + debug!(namespace = %ns_name, "managed namespace already deleted"); + return Ok(()); + } + Ok(Err(e)) => return Err(KubernetesDriverError::from_kube(e)), + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout getting namespace {ns_name}" + ))); + } + }; + + if !is_namespace_owned_by_gateway(ns.metadata.labels.as_ref(), &self.config.gateway_id) { + debug!( + namespace = %ns_name, + "namespace not owned by this gateway, skipping delete" + ); + return Ok(()); + } + + let namespace_uid = ns.metadata.uid.ok_or_else(|| { + KubernetesDriverError::Message(format!( + "namespace {ns_name} has no UID; refusing an unguarded delete" + )) + })?; + let delete_params = namespace_delete_params(namespace_uid); + + match tokio::time::timeout(KUBE_API_TIMEOUT, ns_api.delete(&ns_name, &delete_params)).await + { + Ok(Ok(_)) => { + info!(namespace = %ns_name, workspace = %workspace, "deleted managed namespace"); + } + Ok(Err(KubeError::Api(api))) if api.code == 404 => { + debug!(namespace = %ns_name, "managed namespace already deleted"); + } + Ok(Err(e)) => return Err(KubernetesDriverError::from_kube(e)), + Err(_) => { + return Err(KubernetesDriverError::Message(format!( + "timeout deleting namespace {ns_name}" + ))); + } + } + + Ok(()) + } + fn validate_driver_config_for_sandbox( &self, sandbox: &Sandbox, @@ -539,16 +1012,59 @@ impl KubernetesComputeDriver { ) } - fn agent_sandbox_api(&self, client: Client, sandbox_api_version: &str) -> AgentSandboxApi { + fn agent_sandbox_api( + client: Client, + sandbox_api_version: &str, + namespace: &str, + ) -> AgentSandboxApi { let gvk = GroupVersionKind::gvk(SANDBOX_GROUP, sandbox_api_version, SANDBOX_KIND); let resource = ApiResource::from_gvk(&gvk); - let api = Api::namespaced_with(client, &self.config.namespace, &resource); + let api = Api::namespaced_with(client, namespace, &resource); AgentSandboxApi { api, resource } } - async fn supported_agent_sandbox_api(&self, client: Client) -> Result { + fn cluster_wide_sandbox_api(client: Client, sandbox_api_version: &str) -> AgentSandboxApi { + let gvk = GroupVersionKind::gvk(SANDBOX_GROUP, sandbox_api_version, SANDBOX_KIND); + let resource = ApiResource::from_gvk(&gvk); + let api = Api::all_with(client, &resource); + AgentSandboxApi { api, resource } + } + + async fn supported_agent_sandbox_api( + &self, + client: Client, + namespace: &str, + ) -> Result { + let sandbox_api_version = self.supported_sandbox_api_version(client.clone()).await?; + Ok(Self::agent_sandbox_api( + client, + sandbox_api_version, + namespace, + )) + } + + async fn supported_sandbox_api_for_lookup( + &self, + client: Client, + ) -> Result { let sandbox_api_version = self.supported_sandbox_api_version(client.clone()).await?; - Ok(self.agent_sandbox_api(client, sandbox_api_version)) + if self.config.is_multi_namespace() { + Ok(Self::cluster_wide_sandbox_api(client, sandbox_api_version)) + } else { + Ok(Self::agent_sandbox_api( + client, + sandbox_api_version, + &self.config.namespace, + )) + } + } + + fn sandbox_lookup_selector(&self, sandbox_id: &str) -> String { + sandbox_lookup_selector_for(sandbox_id, &self.config.gateway_id) + } + + fn openshell_sandbox_selector(&self) -> String { + openshell_sandbox_selector_for(&self.config.gateway_id) } async fn supported_sandbox_api_version(&self, client: Client) -> Result<&'static str, String> { @@ -565,7 +1081,11 @@ impl KubernetesComputeDriver { client: Client, ) -> Result<&'static str, String> { for sandbox_api_version in SANDBOX_VERSIONS { - let agent_sandbox_api = self.agent_sandbox_api(client.clone(), sandbox_api_version); + let agent_sandbox_api = Self::agent_sandbox_api( + client.clone(), + sandbox_api_version, + &self.config.namespace, + ); match tokio::time::timeout( KUBE_API_TIMEOUT, agent_sandbox_api.api.list(&ListParams::default().limit(1)), @@ -603,39 +1123,27 @@ impl KubernetesComputeDriver { )) } - /// Resolve sandbox UID/GID from config or `OpenShift` SCC namespace annotations. - /// - /// Returns `(uid, gid, ns_annotations_map)`: - /// - If `sandbox_uid` is set in config, returns that (with fallback GID) - /// - Otherwise fetches the target namespace and checks for - /// `openshift.io/sa.scc.uid-range` / `openshift.io/sa.scc.supplemental-groups` - /// annotations. - /// - If neither config nor `OpenShift` is found, returns `(1000, 1000, {})` as defaults. - async fn resolve_sandbox_identity(&self) -> (u32, u32, BTreeMap) { - // Explicit config takes priority — skip namespace lookup entirely. + async fn resolve_sandbox_identity_in_namespace( + &self, + namespace: &str, + ) -> (u32, u32, BTreeMap) { if self.config.sandbox_uid.is_some() { let uid = self.config.resolve_sandbox_uid(None); let gid = self.config.resolve_sandbox_gid(uid, None); return (uid, gid, BTreeMap::new()); } - // Try to read namespace annotations for OpenShift SCC. - // Namespace is namespaced so Api::all works (it's cluster-scoped but - // can list all namespaces) and we filter by name, or use Api::namespaced. let ns_api: Api = Api::all(self.client.clone()); - match tokio::time::timeout(KUBE_API_TIMEOUT, ns_api.get(self.config.namespace.as_str())) - .await - { + match tokio::time::timeout(KUBE_API_TIMEOUT, ns_api.get(namespace)).await { Ok(Ok(ns)) => { let anns = ns.metadata.annotations.unwrap_or_default(); tracing::info!( - namespace = %self.config.namespace, + namespace = %namespace, uid_range = ?anns.get(crate::config::ANNOTATION_SCC_UID_RANGE), sup_groups = ?anns.get(crate::config::ANNOTATION_SCC_SUPPLEMENTAL_GROUPS), "Resolved namespace annotations for sandbox identity" ); let uid = self.config.resolve_sandbox_uid(Some(&anns)); - // Explicit sandbox_gid config wins; SCC annotation only applies when not set. let baseline_gid = self.config.resolve_sandbox_gid(uid, None); let gid = self.config.sandbox_gid.map_or_else( || { @@ -654,7 +1162,7 @@ impl KubernetesComputeDriver { } Ok(Err(e)) => { tracing::warn!( - namespace = %self.config.namespace, + namespace = %namespace, error = %e, "Failed to fetch namespace for SCC annotations, falling back to defaults" ); @@ -664,7 +1172,7 @@ impl KubernetesComputeDriver { } Err(_) => { tracing::warn!( - namespace = %self.config.namespace, + namespace = %namespace, "Namespace fetch timed out, falling back to defaults" ); let uid = DEFAULT_SANDBOX_UID; @@ -689,7 +1197,15 @@ impl KubernetesComputeDriver { let _ = self .validate_driver_config_for_sandbox(sandbox) .map_err(tonic::Status::invalid_argument)?; - validate_kube_resource_name_length(&sandbox.workspace, &sandbox.name)?; + match self.config.workspace_mode { + WorkspaceMode::Shared => { + validate_kube_resource_name_length(&sandbox.workspace, &sandbox.name)?; + } + WorkspaceMode::Managed | WorkspaceMode::Operator => { + validate_kubernetes_dns1123_label(&sandbox.name, "sandbox name") + .map_err(tonic::Status::invalid_argument)?; + } + } let gpu_requirements = sandbox .spec .as_ref() @@ -710,15 +1226,14 @@ impl KubernetesComputeDriver { pub async fn get_sandbox(&self, sandbox_id: &str) -> Result, String> { info!( sandbox_id = %sandbox_id, - namespace = %self.config.namespace, + workspace_mode = %self.config.workspace_mode, "Fetching sandbox from Kubernetes" ); let agent_sandbox_api = self - .supported_agent_sandbox_api(self.client.clone()) + .supported_sandbox_api_for_lookup(self.client.clone()) .await?; - let selector = - format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE},{LABEL_SANDBOX_ID}={sandbox_id}"); + let selector = self.sandbox_lookup_selector(sandbox_id); let lp = ListParams::default().labels(&selector); match tokio::time::timeout(KUBE_API_TIMEOUT, agent_sandbox_api.api.list(&lp)).await { Ok(Ok(list)) => list.items.into_iter().next().map_or_else( @@ -727,9 +1242,12 @@ impl KubernetesComputeDriver { Ok(None) }, |obj| { - Ok(sandbox_from_object(&self.config.namespace, obj) - .ok() - .map(|(_, s)| s)) + let ns = obj + .metadata + .namespace + .clone() + .unwrap_or_else(|| self.config.namespace.clone()); + Ok(sandbox_from_object(&ns, obj).ok().map(|(_, s)| s)) }, ), Ok(Err(err)) => { @@ -756,18 +1274,19 @@ impl KubernetesComputeDriver { pub async fn list_sandboxes(&self) -> Result, String> { info!( - namespace = %self.config.namespace, + workspace_mode = %self.config.workspace_mode, "Listing sandboxes from Kubernetes" ); let agent_sandbox_api = self - .supported_agent_sandbox_api(self.client.clone()) + .supported_sandbox_api_for_lookup(self.client.clone()) .await?; + let selector = self.openshell_sandbox_selector(); match tokio::time::timeout( KUBE_API_TIMEOUT, agent_sandbox_api .api - .list(&ListParams::default().labels(&openshell_sandbox_label_selector())), + .list(&ListParams::default().labels(&selector)), ) .await { @@ -777,7 +1296,12 @@ impl KubernetesComputeDriver { .into_iter() .filter_map(|obj| { let name = obj.metadata.name.clone().unwrap_or_default(); - match sandbox_from_object(&self.config.namespace, obj) { + let ns = obj + .metadata + .namespace + .clone() + .unwrap_or_else(|| self.config.namespace.clone()); + match sandbox_from_object(&ns, obj) { Ok((_, s)) => Some(s), Err(err) => { warn!(object_name = %name, error = %err, "skipping unrecognized Sandbox in list"); @@ -795,7 +1319,6 @@ impl KubernetesComputeDriver { } Ok(Err(err)) => { warn!( - namespace = %self.config.namespace, error = %err, "Failed to list sandboxes from Kubernetes" ); @@ -803,7 +1326,6 @@ impl KubernetesComputeDriver { } Err(_elapsed) => { warn!( - namespace = %self.config.namespace, timeout_secs = KUBE_API_TIMEOUT.as_secs(), "Timed out listing sandboxes from Kubernetes" ); @@ -830,21 +1352,50 @@ impl KubernetesComputeDriver { .map_err(KubernetesDriverError::InvalidArgument)?; let name = sandbox.name.as_str(); + let workspace = sandbox.workspace.as_str(); + self.validate_workspace_namespace(workspace)?; + + let target_namespace = match self.config.workspace_mode { + WorkspaceMode::Shared => self.config.namespace.clone(), + WorkspaceMode::Managed => { + let namespace = self.ensure_namespace(workspace).await?; + self.ensure_image_pull_secrets(&namespace).await?; + namespace + } + WorkspaceMode::Operator => { + if let Some(ref allowlist) = self.operator_allowlist + && !allowlist.contains(workspace) + { + return Err(KubernetesDriverError::Precondition(format!( + "workspace '{workspace}' is not in the operator namespace allowlist" + ))); + } + workspace.to_string() + } + }; + + if self.config.is_multi_namespace() { + self.ensure_tls_secret(&target_namespace).await?; + } + info!( sandbox_id = %sandbox.id, sandbox_name = %name, - namespace = %self.config.namespace, + namespace = %target_namespace, + workspace = %workspace, + workspace_mode = %self.config.workspace_mode, "Creating sandbox in Kubernetes" ); let agent_sandbox_api = self - .supported_agent_sandbox_api(self.client.clone()) + .supported_agent_sandbox_api(self.client.clone(), &target_namespace) .await .map_err(KubernetesDriverError::Message)?; // Resolve sandbox UID/GID from config or OpenShift SCC namespace annotations. - let (resolved_user_id, resolved_group_id, ns_annotations) = - self.resolve_sandbox_identity().await; + let (resolved_user_id, resolved_group_id, ns_annotations) = self + .resolve_sandbox_identity_in_namespace(&target_namespace) + .await; let params = SandboxPodParams { default_image: &self.config.default_image, @@ -889,11 +1440,8 @@ impl KubernetesComputeDriver { let data = sandbox_to_k8s_spec(sandbox.spec.as_ref(), ¶ms) .map_err(KubernetesDriverError::InvalidArgument)?; - let kube_name = kube_resource_name(&sandbox.workspace, name); + let kube_name = self.config.kube_resource_name(workspace, name); let mut obj = DynamicObject::new(&kube_name, &agent_sandbox_api.resource); - // Copy only the SCC-related annotations onto the Sandbox CR for - // traceability. Copying the full namespace annotation map exposes - // unrelated cluster metadata and can fail with oversized annotations. let mut annotations = sandbox_annotations(sandbox); for key in [ crate::config::ANNOTATION_SCC_UID_RANGE, @@ -905,8 +1453,8 @@ impl KubernetesComputeDriver { } obj.metadata = ObjectMeta { name: Some(kube_name), - namespace: Some(self.config.namespace.clone()), - labels: Some(sandbox_labels(sandbox)), + namespace: Some(target_namespace), + labels: Some(sandbox_labels(sandbox, Some(&self.config.gateway_id))), annotations: Some(annotations), ..Default::default() }; @@ -950,22 +1498,22 @@ impl KubernetesComputeDriver { } } - pub async fn stop_sandbox(&self, sandbox_id: &str) -> Result<(), String> { - let (agent_sandbox_api, kube_name, pod_name, stop_timeout) = self + pub async fn stop_sandbox(&self, sandbox_id: &str) -> Result<(), KubernetesDriverError> { + let (agent_sandbox_api, kube_name, pod_name, namespace, stop_timeout) = self .patch_sandbox_operating_state(sandbox_id, false) .await?; let legacy_pod_api = (agent_sandbox_api.resource.version == SANDBOX_VERSION_V1ALPHA1) - .then(|| Api::::namespaced(self.client.clone(), &self.config.namespace)); + .then(|| Api::::namespaced(self.client.clone(), &namespace)); let deadline = tokio::time::Instant::now() + stop_timeout; let mut poll_interval = STOP_INITIAL_POLL_INTERVAL; loop { let now = tokio::time::Instant::now(); if now >= deadline { - return Err(format!( + return Err(KubernetesDriverError::Message(format!( "timed out after {}s waiting for Kubernetes sandbox to stop", stop_timeout.as_secs() - )); + ))); } let request_timeout = KUBE_API_TIMEOUT.min(deadline.saturating_duration_since(now)); let object = tokio::time::timeout( @@ -974,36 +1522,38 @@ impl KubernetesComputeDriver { ) .await .map_err(|_| { - format!( + KubernetesDriverError::Message(format!( "timed out after {}s waiting for Kubernetes API while checking sandbox stop", request_timeout.as_secs() - ) + )) })? - .map_err(|err| err.to_string())?; + .map_err(KubernetesDriverError::from_kube)?; if kubernetes_sandbox_has_stopped_condition(&object) { return Ok(()); } if let Some(error) = kubernetes_sandbox_stop_failure(&object) { - return Err(error); + return Err(KubernetesDriverError::Message(error)); } if let Some(pod_api) = legacy_pod_api.as_ref() - && kubernetes_sandbox_pod_is_gone(pod_api, &pod_name, deadline).await? + && kubernetes_sandbox_pod_is_gone(pod_api, &pod_name, deadline) + .await + .map_err(KubernetesDriverError::Message)? { return Ok(()); } let now = tokio::time::Instant::now(); if now >= deadline { - return Err(format!( + return Err(KubernetesDriverError::Message(format!( "timed out after {}s waiting for Kubernetes sandbox to stop", stop_timeout.as_secs() - )); + ))); } tokio::time::sleep(poll_interval.min(deadline.saturating_duration_since(now))).await; poll_interval = next_stop_poll_interval(poll_interval); } } - pub async fn start_sandbox(&self, sandbox_id: &str) -> Result<(), String> { + pub async fn start_sandbox(&self, sandbox_id: &str) -> Result<(), KubernetesDriverError> { self.patch_sandbox_operating_state(sandbox_id, true) .await .map(|_| ()) @@ -1013,36 +1563,45 @@ impl KubernetesComputeDriver { &self, sandbox_id: &str, running: bool, - ) -> Result<(AgentSandboxApi, String, String, Duration), String> { - let agent_sandbox_api = self - .supported_agent_sandbox_api(self.client.clone()) - .await?; - let selector = - format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE},{LABEL_SANDBOX_ID}={sandbox_id}"); + ) -> Result<(AgentSandboxApi, String, String, String, Duration), KubernetesDriverError> { + let lookup_api = self + .supported_sandbox_api_for_lookup(self.client.clone()) + .await + .map_err(KubernetesDriverError::Message)?; + let selector = self.sandbox_lookup_selector(sandbox_id); let list = tokio::time::timeout( KUBE_API_TIMEOUT, - agent_sandbox_api + lookup_api .api .list(&ListParams::default().labels(&selector)), ) .await .map_err(|_| { - format!( + KubernetesDriverError::Message(format!( "timed out after {}s waiting for Kubernetes API", KUBE_API_TIMEOUT.as_secs() - ) + )) })? - .map_err(|err| err.to_string())?; + .map_err(KubernetesDriverError::from_kube)?; let object = list .items .into_iter() .next() - .ok_or_else(|| "sandbox not found".to_string())?; - let stop_timeout = kubernetes_sandbox_stop_timeout(&object); - let kube_name = object + .ok_or(KubernetesDriverError::NotFound)?; + let namespace = object .metadata - .name - .ok_or_else(|| "sandbox resource has no name".to_string())?; + .namespace + .clone() + .unwrap_or_else(|| self.config.namespace.clone()); + let agent_sandbox_api = Self::agent_sandbox_api( + self.client.clone(), + &lookup_api.resource.version, + &namespace, + ); + let stop_timeout = kubernetes_sandbox_stop_timeout(&object); + let kube_name = object.metadata.name.ok_or_else(|| { + KubernetesDriverError::Message("sandbox resource has no name".to_string()) + })?; let pod_name = object .metadata .annotations @@ -1066,12 +1625,12 @@ impl KubernetesComputeDriver { ) .await .map_err(|_| { - format!( + KubernetesDriverError::Message(format!( "timed out after {}s waiting for Kubernetes API", KUBE_API_TIMEOUT.as_secs() - ) + )) })? - .map_err(|err| err.to_string())?; + .map_err(KubernetesDriverError::from_kube)?; info!( sandbox_id, @@ -1079,25 +1638,30 @@ impl KubernetesComputeDriver { running, "Updated Kubernetes sandbox operating state" ); - Ok((agent_sandbox_api, kube_name, pod_name, stop_timeout)) + Ok(( + agent_sandbox_api, + kube_name, + pod_name, + namespace, + stop_timeout, + )) } pub async fn delete_sandbox(&self, sandbox_id: &str) -> Result { info!( sandbox_id = %sandbox_id, - namespace = %self.config.namespace, + workspace_mode = %self.config.workspace_mode, "Deleting sandbox from Kubernetes" ); - let agent_sandbox_api = self - .supported_agent_sandbox_api(self.client.clone()) + let lookup_api = self + .supported_sandbox_api_for_lookup(self.client.clone()) .await?; - let selector = - format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE},{LABEL_SANDBOX_ID}={sandbox_id}"); + let selector = self.sandbox_lookup_selector(sandbox_id); let lp = ListParams::default().labels(&selector); - let (kube_name, preconditions) = match tokio::time::timeout( + let (kube_name, obj_namespace, _workspace, preconditions) = match tokio::time::timeout( KUBE_API_TIMEOUT, - agent_sandbox_api.api.list(&lp), + lookup_api.api.list(&lp), ) .await { @@ -1105,11 +1669,22 @@ impl KubernetesComputeDriver { if let Some(obj) = list.items.into_iter().next() { match obj.metadata.name { Some(name) => { + let ns = obj + .metadata + .namespace + .clone() + .unwrap_or_else(|| self.config.namespace.clone()); + let ws = obj + .metadata + .labels + .as_ref() + .and_then(|l| l.get(LABEL_SANDBOX_WORKSPACE).cloned()) + .unwrap_or_default(); let pc = Preconditions { uid: obj.metadata.uid, resource_version: obj.metadata.resource_version, }; - (name, pc) + (name, ns, ws, pc) } None => return Ok(false), } @@ -1139,15 +1714,13 @@ impl KubernetesComputeDriver { } }; + let delete_api = self + .supported_agent_sandbox_api(self.client.clone(), &obj_namespace) + .await?; let dp = DeleteParams::default().preconditions(preconditions); - match tokio::time::timeout( - KUBE_API_TIMEOUT, - agent_sandbox_api.api.delete(&kube_name, &dp), - ) - .await - { + match tokio::time::timeout(KUBE_API_TIMEOUT, delete_api.api.delete(&kube_name, &dp)).await { Ok(Ok(_response)) => { - info!(sandbox_id = %sandbox_id, "Sandbox deleted from Kubernetes"); + info!(sandbox_id = %sandbox_id, namespace = %obj_namespace, "Sandbox deleted from Kubernetes"); Ok(true) } Ok(Err(KubeError::Api(err))) if err.code == 404 || err.code == 409 => { @@ -1178,10 +1751,9 @@ impl KubernetesComputeDriver { pub async fn sandbox_exists(&self, sandbox_id: &str) -> Result { let agent_sandbox_api = self - .supported_agent_sandbox_api(self.client.clone()) + .supported_sandbox_api_for_lookup(self.client.clone()) .await?; - let selector = - format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE},{LABEL_SANDBOX_ID}={sandbox_id}"); + let selector = self.sandbox_lookup_selector(sandbox_id); let lp = ListParams::default().labels(&selector); match tokio::time::timeout(KUBE_API_TIMEOUT, agent_sandbox_api.api.list(&lp)).await { Ok(Ok(list)) => Ok(!list.items.is_empty()), @@ -1196,9 +1768,17 @@ impl KubernetesComputeDriver { // Kept `async` to match the gRPC handler signature in `grpc.rs`, which awaits this method. #[allow(clippy::unused_async)] pub async fn watch_sandboxes(&self) -> Result { + if self.config.is_multi_namespace() { + self.watch_sandboxes_cluster_wide().await + } else { + self.watch_sandboxes_single_namespace().await + } + } + + async fn watch_sandboxes_single_namespace(&self) -> Result { let namespace = self.config.namespace.clone(); let agent_sandbox_api = self - .supported_agent_sandbox_api(self.watch_client.clone()) + .supported_agent_sandbox_api(self.watch_client.clone(), &self.config.namespace) .await?; let event_api: Api = Api::namespaced(self.watch_client.clone(), &namespace); let watcher_config = watcher::Config::default().labels(&openshell_sandbox_label_selector()); @@ -1284,13 +1864,92 @@ impl KubernetesComputeDriver { } } } - Ok(Some(Event::Deleted(_))) => {} - Ok(Some(Event::Restarted(_))) => { - debug!(namespace = %namespace, "Kubernetes event watcher restarted"); - } + Ok(Some(Event::Deleted(_))) => {} + Ok(Some(Event::Restarted(_))) => { + debug!(namespace = %namespace, "Kubernetes event watcher restarted"); + } + Ok(None) => { + let _ = tx.send(Err(KubernetesDriverError::Message( + "kubernetes event watcher stream ended".to_string() + ))).await; + break; + } + Err(err) => { + let _ = tx.send(Err(KubernetesDriverError::Message(err.to_string()))).await; + break; + } + }, + () = tx.closed() => break, + } + } + }); + + Ok(Box::pin(ReceiverStream::new(rx))) + } + + async fn watch_sandboxes_cluster_wide(&self) -> Result { + let sandbox_api_version = self + .supported_sandbox_api_version(self.watch_client.clone()) + .await?; + let cluster_api = + Self::cluster_wide_sandbox_api(self.watch_client.clone(), sandbox_api_version); + let selector = self.openshell_sandbox_selector(); + let watcher_config = watcher::Config::default().labels(&selector); + let mut sandbox_stream = watcher::watcher(cluster_api.api, watcher_config).boxed(); + let (tx, rx) = mpsc::channel(256); + let default_namespace = self.config.namespace.clone(); + + tokio::spawn(async move { + loop { + tokio::select! { + result = sandbox_stream.try_next() => match result { + Ok(Some(Event::Applied(obj))) => { + let ns = obj.metadata.namespace.clone() + .unwrap_or_else(|| default_namespace.clone()); + if let Ok((_kube_name, sandbox)) = sandbox_from_object(&ns, obj) { + let event = WatchSandboxesEvent { + payload: Some(watch_sandboxes_event::Payload::Sandbox( + WatchSandboxesSandboxEvent { sandbox: Some(sandbox) } + )), + }; + if tx.send(Ok(event)).await.is_err() { + break; + } + } + } + Ok(Some(Event::Deleted(obj))) => { + if is_openshell_managed(&obj) + && let Ok(sandbox_id) = sandbox_id_from_object(&obj) + { + let event = WatchSandboxesEvent { + payload: Some(watch_sandboxes_event::Payload::Deleted( + WatchSandboxesDeletedEvent { sandbox_id } + )), + }; + if tx.send(Ok(event)).await.is_err() { + break; + } + } + } + Ok(Some(Event::Restarted(objs))) => { + for obj in objs { + let ns = obj.metadata.namespace.clone() + .unwrap_or_else(|| default_namespace.clone()); + if let Ok((_kube_name, sandbox)) = sandbox_from_object(&ns, obj) { + let event = WatchSandboxesEvent { + payload: Some(watch_sandboxes_event::Payload::Sandbox( + WatchSandboxesSandboxEvent { sandbox: Some(sandbox) } + )), + }; + if tx.send(Ok(event)).await.is_err() { + return; + } + } + } + } Ok(None) => { let _ = tx.send(Err(KubernetesDriverError::Message( - "kubernetes event watcher stream ended".to_string() + "sandbox watcher stream ended unexpectedly".to_string() ))).await; break; } @@ -1324,10 +1983,6 @@ fn validate_gpu_request( Ok(()) } -fn kube_resource_name(workspace: &str, name: &str) -> String { - format!("{workspace}--{name}") -} - const MAX_KUBE_NAME_LEN: usize = 63; fn validate_kube_resource_name_length(workspace: &str, name: &str) -> Result<(), tonic::Status> { @@ -1341,7 +1996,48 @@ fn validate_kube_resource_name_length(workspace: &str, name: &str) -> Result<(), Ok(()) } -fn sandbox_labels(sandbox: &Sandbox) -> BTreeMap { +fn is_namespace_owned_by_gateway( + labels: Option<&BTreeMap>, + gateway_id: &str, +) -> bool { + labels + .and_then(|l| l.get(LABEL_MANAGED_BY)) + .is_some_and(|v| v == LABEL_MANAGED_BY_VALUE) + && labels + .and_then(|l| l.get(LABEL_GATEWAY_ID)) + .is_some_and(|v| v == gateway_id) +} + +fn gateway_id_label_needs_backfill( + labels: Option<&BTreeMap>, + gateway_id: &str, +) -> bool { + labels + .and_then(|labels| labels.get(LABEL_GATEWAY_ID)) + .is_none_or(|value| value != gateway_id) +} + +fn namespace_delete_params(uid: String) -> DeleteParams { + DeleteParams::default().preconditions(Preconditions { + uid: Some(uid), + resource_version: None, + }) +} + +fn sandbox_lookup_selector_for(sandbox_id: &str, gateway_id: &str) -> String { + format!( + "{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE},{LABEL_SANDBOX_ID}={sandbox_id},{LABEL_GATEWAY_ID}={gateway_id}" + ) +} + +fn openshell_sandbox_selector_for(gateway_id: &str) -> String { + use std::fmt::Write; + let mut selector = openshell_sandbox_label_selector(); + write!(selector, ",{LABEL_GATEWAY_ID}={gateway_id}").unwrap(); + selector +} + +fn sandbox_labels(sandbox: &Sandbox, gateway_id: Option<&str>) -> BTreeMap { let mut labels = BTreeMap::new(); labels.insert(LABEL_SANDBOX_ID.to_string(), sandbox.id.clone()); labels.insert(LABEL_SANDBOX_NAME.to_string(), sandbox.name.clone()); @@ -1353,9 +2049,76 @@ fn sandbox_labels(sandbox: &Sandbox) -> BTreeMap { LABEL_MANAGED_BY.to_string(), LABEL_MANAGED_BY_VALUE.to_string(), ); + if let Some(gw_id) = gateway_id { + labels.insert(LABEL_GATEWAY_ID.to_string(), gw_id.to_string()); + } labels } +fn managed_ssh_network_policy(namespace: &str, config: &KubernetesComputeConfig) -> NetworkPolicy { + NetworkPolicy { + metadata: ObjectMeta { + name: Some(MANAGED_SSH_NETWORK_POLICY_NAME.to_string()), + namespace: Some(namespace.to_string()), + labels: Some(BTreeMap::from([( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + )])), + ..Default::default() + }, + spec: Some(NetworkPolicySpec { + pod_selector: LabelSelector { + match_labels: Some(BTreeMap::from([( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + )])), + ..Default::default() + }, + policy_types: Some(vec!["Ingress".to_string()]), + ingress: Some(vec![NetworkPolicyIngressRule { + from: Some(vec![NetworkPolicyPeer { + namespace_selector: Some(LabelSelector { + match_labels: Some(BTreeMap::from([( + "kubernetes.io/metadata.name".to_string(), + config.managed_ssh_ingress.gateway_namespace.clone(), + )])), + ..Default::default() + }), + pod_selector: Some(LabelSelector { + match_labels: Some(config.managed_ssh_ingress.gateway_pod_selector.clone()), + ..Default::default() + }), + ..Default::default() + }]), + ports: Some(vec![NetworkPolicyPort { + port: Some(IntOrString::Int(2222)), + protocol: Some("TCP".to_string()), + ..Default::default() + }]), + }]), + ..Default::default() + }), + status: None, + } +} + +fn image_pull_secret_copy(secret_name: &str, namespace: &str, source: Secret) -> Secret { + Secret { + metadata: ObjectMeta { + name: Some(secret_name.to_string()), + namespace: Some(namespace.to_string()), + labels: Some(BTreeMap::from([( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + )])), + ..Default::default() + }, + data: source.data, + type_: source.type_, + ..Default::default() + } +} + fn sandbox_annotations(sandbox: &Sandbox) -> BTreeMap { let mut annotations = BTreeMap::new(); annotations.insert(LABEL_SANDBOX_ID.to_string(), sandbox.id.clone()); @@ -3529,6 +4292,241 @@ fn condition_from_value(value: &serde_json::Value) -> Option { }) } +fn spawn_namespace_label_watcher( + client: Client, + label_selector: String, + allowlist: OperatorNamespaceAllowlist, + mut shutdown_rx: tokio::sync::watch::Receiver, +) { + let ns_api: Api = Api::all(client); + let watcher_config = watcher::Config::default().labels(&label_selector); + let jitter_seed = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .map_or(0, |duration| { + duration.as_secs() ^ u64::from(duration.subsec_nanos()) + }); + + tokio::spawn(async move { + let mut retry_attempt = 0; + loop { + let mut stream = watcher::watcher(ns_api.clone(), watcher_config.clone()).boxed(); + + loop { + let event = tokio::select! { + result = stream.try_next() => result, + changed = shutdown_rx.changed() => { + if changed.is_err() || *shutdown_rx.borrow() { + return; + } + continue; + } + }; + match event { + Ok(Some(Event::Applied(ns))) => { + retry_attempt = 0; + if let Some(name) = ns.metadata.name.as_deref() + && allowlist.insert(name.to_string()) + { + info!(namespace = name, "operator namespace added to allowlist"); + } + } + Ok(Some(Event::Deleted(ns))) => { + retry_attempt = 0; + if let Some(name) = ns.metadata.name.as_deref() + && allowlist.remove(name) + { + info!( + namespace = name, + "operator namespace removed from allowlist" + ); + } + } + Ok(Some(Event::Restarted(namespaces))) => { + retry_attempt = 0; + let names: std::collections::BTreeSet = namespaces + .into_iter() + .filter_map(|ns| ns.metadata.name) + .collect(); + let count = names.len(); + allowlist.replace(names); + info!( + total = count, + "operator namespace allowlist replaced from full relist" + ); + } + Ok(None) => { + warn!("operator namespace watcher stream ended unexpectedly"); + break; + } + Err(err) => { + warn!(error = %err, "operator namespace watcher stream error"); + break; + } + } + } + + let retry_delay = namespace_watcher_retry_delay(retry_attempt, jitter_seed); + warn!(?retry_delay, "operator namespace watcher reconnecting"); + tokio::select! { + () = tokio::time::sleep(retry_delay) => {} + changed = shutdown_rx.changed() => { + if changed.is_err() || *shutdown_rx.borrow() { + return; + } + } + } + retry_attempt = retry_attempt.saturating_add(1); + } + }); + + info!( + label_selector = %label_selector, + "operator namespace label watcher spawned" + ); +} + +fn namespace_watcher_retry_delay(attempt: u32, jitter_seed: u64) -> Duration { + let base_secs = 2_u64.saturating_mul(1_u64 << attempt.min(4)).min(24); + let max_jitter_secs = base_secs / 4; + let mixed_seed = + jitter_seed.wrapping_add(u64::from(attempt).wrapping_mul(0x9e37_79b9_7f4a_7c15)); + let jitter_secs = mixed_seed % (max_jitter_secs + 1); + Duration::from_secs(base_secs + jitter_secs) +} + +fn load_namespace_file(path: &Path) -> Result, String> { + let contents = std::fs::read_to_string(path) + .map_err(|e| format!("failed to read {}: {e}", path.display()))?; + let names: Vec = serde_json::from_str(&contents) + .map_err(|e| format!("failed to parse {}: {e}", path.display()))?; + Ok(names.into_iter().collect()) +} + +fn spawn_namespace_file_watcher( + path: PathBuf, + allowlist: OperatorNamespaceAllowlist, + mut shutdown_rx: tokio::sync::watch::Receiver, +) { + match load_namespace_file(&path) { + Ok(names) => { + let count = names.len(); + allowlist.replace(names); + info!( + path = %path.display(), + total = count, + "operator namespace allowlist loaded from file" + ); + } + Err(err) => { + warn!( + error = %err, + "failed to load initial operator namespace file, allowlist empty" + ); + } + } + + let watch_dir = path + .parent() + .unwrap_or_else(|| Path::new(".")) + .to_path_buf(); + let debounce = Duration::from_secs(1); + + tokio::spawn(async move { + let (tx, mut rx) = mpsc::unbounded_channel(); + + let mut watcher = + match notify::recommended_watcher(move |res: Result| { + if let Ok(event) = res + && matches!( + event.kind, + notify::EventKind::Modify(_) | notify::EventKind::Create(_) + ) + { + let _ = tx.send(()); + } + }) { + Ok(w) => w, + Err(e) => { + warn!( + error = %e, + "failed to start operator namespace file watcher, hot-reload disabled" + ); + return; + } + }; + + if let Err(e) = notify::Watcher::watch( + &mut watcher, + &watch_dir, + notify::RecursiveMode::NonRecursive, + ) { + warn!( + error = %e, + dir = %watch_dir.display(), + "failed to watch operator namespace file directory, hot-reload disabled" + ); + return; + } + + info!( + path = %path.display(), + "operator namespace file watcher started" + ); + + loop { + let got_event = tokio::select! { + event = rx.recv() => event.is_some(), + changed = shutdown_rx.changed() => { + if changed.is_err() || *shutdown_rx.borrow() { + return; + } + continue; + } + }; + if !got_event { + warn!("operator namespace file watcher disconnected"); + break; + } + + loop { + tokio::select! { + () = tokio::time::sleep(debounce) => { + match load_namespace_file(&path) { + Ok(names) => { + let count = names.len(); + allowlist.replace(names); + info!( + total = count, + "operator namespace allowlist reloaded from file" + ); + } + Err(err) => { + warn!( + error = %err, + "failed to reload operator namespace file, keeping existing allowlist" + ); + } + } + break; + } + r = rx.recv() => { + if r.is_some() { + continue; + } + warn!("operator namespace file watcher disconnected"); + return; + } + changed = shutdown_rx.changed() => { + if changed.is_err() || *shutdown_rx.borrow() { + return; + } + } + } + } + } + }); +} + #[cfg(test)] mod tests { use super::*; @@ -6348,22 +7346,6 @@ mod tests { assert!(validate_kubernetes_dns1123_label("dotted.name", "sandbox name").is_err()); } - #[test] - fn kube_resource_name_qualifies_with_workspace() { - assert_eq!(kube_resource_name("alpha", "work"), "alpha--work"); - assert_eq!( - kube_resource_name("default", "my-sandbox"), - "default--my-sandbox" - ); - } - - #[test] - fn kube_resource_name_different_workspaces_produce_different_names() { - let alpha = kube_resource_name("alpha", "work"); - let beta = kube_resource_name("beta", "work"); - assert_ne!(alpha, beta); - } - #[test] fn kube_resource_name_length_validation_accepts_short_names() { validate_kube_resource_name_length("default", "my-sandbox").unwrap(); @@ -6460,6 +7442,37 @@ mod tests { assert!(result.unwrap_err().contains("not managed by openshell")); } + #[test] + fn sandbox_from_object_uses_object_namespace_over_fallback() { + let obj = DynamicObject { + types: None, + metadata: ObjectMeta { + name: Some("work".to_string()), + namespace: Some("openshell-gw1-team-a".to_string()), + annotations: Some(BTreeMap::from([ + (LABEL_SANDBOX_ID.to_string(), "uuid-cross".to_string()), + (LABEL_SANDBOX_NAME.to_string(), "work".to_string()), + (LABEL_SANDBOX_WORKSPACE.to_string(), "team-a".to_string()), + ])), + labels: Some(BTreeMap::from([ + (LABEL_SANDBOX_ID.to_string(), "uuid-cross".to_string()), + (LABEL_SANDBOX_NAME.to_string(), "work".to_string()), + (LABEL_SANDBOX_WORKSPACE.to_string(), "team-a".to_string()), + ( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + ), + ])), + ..Default::default() + }, + data: serde_json::json!({}), + }; + + let (_, sandbox) = sandbox_from_object("openshell", obj).unwrap(); + assert_eq!(sandbox.namespace, "openshell-gw1-team-a"); + assert_eq!(sandbox.workspace, "team-a"); + } + #[test] fn sandbox_from_object_warns_on_managed_cr_missing_workspace() { let obj = DynamicObject { @@ -6493,7 +7506,7 @@ mod tests { workspace: "alpha".to_string(), ..Default::default() }; - let labels = sandbox_labels(&sandbox); + let labels = sandbox_labels(&sandbox, None); assert_eq!(labels.get(LABEL_SANDBOX_ID).unwrap(), "uuid-1"); assert_eq!(labels.get(LABEL_SANDBOX_NAME).unwrap(), "work"); assert_eq!(labels.get(LABEL_SANDBOX_WORKSPACE).unwrap(), "alpha"); @@ -6501,6 +7514,19 @@ mod tests { labels.get(LABEL_MANAGED_BY).unwrap(), LABEL_MANAGED_BY_VALUE ); + assert!(!labels.contains_key(LABEL_GATEWAY_ID)); + } + + #[test] + fn sandbox_labels_includes_gateway_id_when_provided() { + let sandbox = Sandbox { + id: "uuid-1".to_string(), + name: "work".to_string(), + workspace: "alpha".to_string(), + ..Default::default() + }; + let labels = sandbox_labels(&sandbox, Some("gw-42")); + assert_eq!(labels.get(LABEL_GATEWAY_ID).unwrap(), "gw-42"); } #[test] @@ -6664,4 +7690,220 @@ mod tests { ); assert_eq!(volume["secret"]["defaultMode"], 0o440); } + + #[test] + fn sandbox_lookup_selector_always_includes_gateway_id() { + let sel = sandbox_lookup_selector_for("sb-123", "gw-42"); + assert!( + sel.contains(&format!("{LABEL_GATEWAY_ID}=gw-42")), + "selector must include gateway ID: {sel}" + ); + assert!( + sel.contains(&format!("{LABEL_SANDBOX_ID}=sb-123")), + "selector must include sandbox ID: {sel}" + ); + assert!( + sel.contains(&format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE}")), + "selector must include managed-by: {sel}" + ); + } + + #[test] + fn openshell_sandbox_selector_always_includes_gateway_id() { + let sel = openshell_sandbox_selector_for("gw-99"); + assert!( + sel.contains(&format!("{LABEL_GATEWAY_ID}=gw-99")), + "selector must include gateway ID: {sel}" + ); + assert!( + sel.contains(&format!("{LABEL_MANAGED_BY}={LABEL_MANAGED_BY_VALUE}")), + "selector must include managed-by: {sel}" + ); + } + + #[test] + fn gateway_id_backfill_adopts_unlabelled_sandbox() { + let labels = BTreeMap::from([( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + )]); + assert!(gateway_id_label_needs_backfill(Some(&labels), "gw-1")); + } + + #[test] + fn gateway_id_backfill_adopts_sandbox_from_previous_gateway() { + let labels = BTreeMap::from([(LABEL_GATEWAY_ID.to_string(), "gw-old".to_string())]); + assert!(gateway_id_label_needs_backfill(Some(&labels), "gw-1")); + } + + #[test] + fn gateway_id_backfill_skips_sandbox_already_owned_by_gateway() { + let labels = BTreeMap::from([(LABEL_GATEWAY_ID.to_string(), "gw-1".to_string())]); + assert!(!gateway_id_label_needs_backfill(Some(&labels), "gw-1")); + } + + #[test] + fn managed_ssh_policy_allows_only_gateway_peer_on_port_2222() { + let config = KubernetesComputeConfig { + managed_ssh_ingress: crate::config::ManagedSshIngressConfig { + enabled: true, + gateway_namespace: "gateway-ns".to_string(), + gateway_pod_selector: BTreeMap::from([( + "app.kubernetes.io/name".to_string(), + "openshell".to_string(), + )]), + }, + ..KubernetesComputeConfig::default() + }; + let policy = managed_ssh_network_policy("workspace-ns", &config); + let spec = policy.spec.unwrap(); + assert_eq!( + spec.policy_types.as_deref(), + Some(["Ingress".to_string()].as_slice()) + ); + let ingress = &spec.ingress.unwrap()[0]; + assert_eq!( + ingress.ports.as_ref().unwrap()[0].port, + Some(IntOrString::Int(2222)) + ); + let peer = &ingress.from.as_ref().unwrap()[0]; + assert_eq!( + peer.namespace_selector + .as_ref() + .unwrap() + .match_labels + .as_ref() + .unwrap() + .get("kubernetes.io/metadata.name") + .map(String::as_str), + Some("gateway-ns") + ); + assert_eq!( + peer.pod_selector + .as_ref() + .unwrap() + .match_labels + .as_ref() + .unwrap() + .get("app.kubernetes.io/name") + .map(String::as_str), + Some("openshell") + ); + } + + #[test] + fn image_pull_secret_copy_keeps_only_portable_secret_fields() { + let source: Secret = serde_json::from_value(serde_json::json!({ + "apiVersion": "v1", + "kind": "Secret", + "metadata": { + "name": "regcred", + "namespace": "gateway", + "uid": "source-uid", + "resourceVersion": "42", + "labels": { "source-only": "true" }, + "annotations": { "source-only": "true" }, + "finalizers": ["example.test/finalizer"] + }, + "type": "kubernetes.io/dockerconfigjson", + "data": { ".dockerconfigjson": "e30=" } + })) + .unwrap(); + + let copy = image_pull_secret_copy("regcred", "workspace", source); + assert_eq!(copy.metadata.name.as_deref(), Some("regcred")); + assert_eq!(copy.metadata.namespace.as_deref(), Some("workspace")); + assert_eq!( + copy.type_.as_deref(), + Some("kubernetes.io/dockerconfigjson") + ); + assert!( + copy.data + .as_ref() + .unwrap() + .contains_key(".dockerconfigjson") + ); + assert_eq!( + copy.metadata + .labels + .as_ref() + .unwrap() + .get(LABEL_MANAGED_BY) + .map(String::as_str), + Some(LABEL_MANAGED_BY_VALUE) + ); + assert!(copy.metadata.uid.is_none()); + assert!(copy.metadata.resource_version.is_none()); + assert!(copy.metadata.annotations.is_none()); + assert!(copy.metadata.finalizers.is_none()); + } + + #[test] + fn namespace_owned_with_correct_labels() { + let labels = BTreeMap::from([ + ( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + ), + (LABEL_GATEWAY_ID.to_string(), "gw-1".to_string()), + ]); + assert!(is_namespace_owned_by_gateway(Some(&labels), "gw-1")); + } + + #[test] + fn namespace_not_owned_missing_managed_by() { + let labels = BTreeMap::from([(LABEL_GATEWAY_ID.to_string(), "gw-1".to_string())]); + assert!(!is_namespace_owned_by_gateway(Some(&labels), "gw-1")); + } + + #[test] + fn namespace_not_owned_wrong_gateway_id() { + let labels = BTreeMap::from([ + ( + LABEL_MANAGED_BY.to_string(), + LABEL_MANAGED_BY_VALUE.to_string(), + ), + (LABEL_GATEWAY_ID.to_string(), "gw-other".to_string()), + ]); + assert!(!is_namespace_owned_by_gateway(Some(&labels), "gw-1")); + } + + #[test] + fn namespace_not_owned_no_labels() { + assert!(!is_namespace_owned_by_gateway(None, "gw-1")); + } + + #[test] + fn namespace_delete_is_guarded_by_fetched_uid() { + let params = namespace_delete_params("namespace-uid".to_string()); + assert_eq!( + params + .preconditions + .and_then(|preconditions| preconditions.uid), + Some("namespace-uid".to_string()) + ); + } + + #[test] + fn namespace_watcher_retry_delay_is_bounded_exponential_with_jitter() { + let seed = 42; + let expected_ranges = [(2, 2), (4, 5), (8, 10), (16, 20), (24, 30), (24, 30)]; + + for (attempt, (minimum, maximum)) in expected_ranges.into_iter().enumerate() { + let attempt = u32::try_from(attempt).unwrap(); + let delay = namespace_watcher_retry_delay(attempt, seed).as_secs(); + assert!( + (minimum..=maximum).contains(&delay), + "attempt {attempt} produced {delay}s" + ); + } + } + + #[test] + fn namespace_watcher_retry_delay_uses_seeded_jitter() { + assert_ne!( + namespace_watcher_retry_delay(3, 1), + namespace_watcher_retry_delay(3, 2) + ); + } } diff --git a/crates/openshell-driver-kubernetes/src/grpc.rs b/crates/openshell-driver-kubernetes/src/grpc.rs index ef2e2686e4..ce23cf0189 100644 --- a/crates/openshell-driver-kubernetes/src/grpc.rs +++ b/crates/openshell-driver-kubernetes/src/grpc.rs @@ -6,17 +6,19 @@ use futures::{Stream, StreamExt}; use openshell_core::proto::compute::v1::{ CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, - GetCapabilitiesRequest, GetCapabilitiesResponse, GetGatewayListenerRequirementsRequest, - GetGatewayListenerRequirementsResponse, GetSandboxRequest, GetSandboxResponse, - ListSandboxesRequest, ListSandboxesResponse, StartSandboxRequest, StartSandboxResponse, - StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest, - ValidateSandboxCreateResponse, WatchSandboxesEvent, WatchSandboxesRequest, - compute_driver_server::ComputeDriver, + DeleteWorkspaceRequest, DeleteWorkspaceResponse, EnsureWorkspaceRequest, + EnsureWorkspaceResponse, GetCapabilitiesRequest, GetCapabilitiesResponse, + GetGatewayListenerRequirementsRequest, GetGatewayListenerRequirementsResponse, + GetSandboxRequest, GetSandboxResponse, ListSandboxesRequest, ListSandboxesResponse, + StartSandboxRequest, StartSandboxResponse, StopSandboxRequest, StopSandboxResponse, + ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, WatchSandboxesEvent, + WatchSandboxesRequest, compute_driver_server::ComputeDriver, }; use std::pin::Pin; use tonic::{Request, Response, Status}; use crate::KubernetesComputeDriver; +use crate::WorkspaceMode; #[derive(Debug, Clone)] pub struct ComputeDriverService { @@ -122,7 +124,7 @@ impl ComputeDriver for ComputeDriverService { self.driver .stop_sandbox(&request.sandbox_id) .await - .map_err(kubernetes_lifecycle_status)?; + .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; Ok(Response::new(StopSandboxResponse {})) } @@ -137,7 +139,7 @@ impl ComputeDriver for ComputeDriverService { self.driver .start_sandbox(&request.sandbox_id) .await - .map_err(kubernetes_lifecycle_status)?; + .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; Ok(Response::new(StartSandboxResponse {})) } @@ -172,18 +174,67 @@ impl ComputeDriver for ComputeDriverService { let stream = stream.map(|item| item.map_err(|err| Status::internal(err.to_string()))); Ok(Response::new(Box::pin(stream))) } -} -fn kubernetes_lifecycle_status(message: String) -> Status { - if message == "sandbox not found" { - Status::not_found(message) - } else { - Status::internal(message) + async fn ensure_workspace( + &self, + request: Request, + ) -> Result, Status> { + let workspace = request.into_inner().workspace; + if workspace.is_empty() { + return Err(Status::invalid_argument("workspace is required")); + } + self.driver + .validate_workspace_namespace(&workspace) + .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; + match self.driver.workspace_mode() { + WorkspaceMode::Managed => { + self.driver + .ensure_namespace(&workspace) + .await + .map_err(|e| Status::internal(e.to_string()))?; + } + WorkspaceMode::Operator => { + if let Some(allowlist) = self.driver.operator_allowlist() + && !allowlist.contains(&workspace) + { + return Err(Status::permission_denied(format!( + "workspace '{workspace}' is not in the operator namespace allowlist" + ))); + } + } + WorkspaceMode::Shared => {} + } + Ok(Response::new(EnsureWorkspaceResponse {})) + } + + async fn delete_workspace( + &self, + request: Request, + ) -> Result, Status> { + let workspace = request.into_inner().workspace; + if workspace.is_empty() { + return Err(Status::invalid_argument("workspace is required")); + } + if workspace_delete_requires_namespace_access(self.driver.workspace_mode()) { + self.driver + .validate_workspace_namespace(&workspace) + .map_err(|error| Status::from(openshell_core::ComputeDriverError::from(error)))?; + self.driver + .delete_namespace(&workspace) + .await + .map_err(|e| Status::internal(e.to_string()))?; + } + Ok(Response::new(DeleteWorkspaceResponse {})) } } +fn workspace_delete_requires_namespace_access(mode: WorkspaceMode) -> bool { + matches!(mode, WorkspaceMode::Managed) +} + #[cfg(test)] mod tests { + use super::{WorkspaceMode, workspace_delete_requires_namespace_access}; use crate::KubernetesDriverError; use openshell_core::ComputeDriverError; use tonic::Status; @@ -199,6 +250,17 @@ mod tests { assert_eq!(status.message(), "sandbox agent pod IP is not available"); } + #[test] + fn invalid_workspace_driver_errors_map_to_invalid_argument_status() { + let status: Status = ComputeDriverError::from(KubernetesDriverError::InvalidArgument( + "managed namespace is invalid".to_string(), + )) + .into(); + + assert_eq!(status.code(), tonic::Code::InvalidArgument); + assert_eq!(status.message(), "managed namespace is invalid"); + } + #[test] fn already_exists_driver_errors_map_to_already_exists_status() { let status: Status = ComputeDriverError::from(KubernetesDriverError::AlreadyExists).into(); @@ -206,4 +268,25 @@ mod tests { assert_eq!(status.code(), tonic::Code::AlreadyExists); assert_eq!(status.message(), "sandbox already exists"); } + + #[test] + fn not_found_driver_errors_map_to_not_found_status() { + let status: Status = ComputeDriverError::from(KubernetesDriverError::NotFound).into(); + + assert_eq!(status.code(), tonic::Code::NotFound); + assert_eq!(status.message(), "sandbox not found"); + } + + #[test] + fn only_managed_workspace_delete_accesses_the_namespace() { + assert!(workspace_delete_requires_namespace_access( + WorkspaceMode::Managed + )); + assert!(!workspace_delete_requires_namespace_access( + WorkspaceMode::Operator + )); + assert!(!workspace_delete_requires_namespace_access( + WorkspaceMode::Shared + )); + } } diff --git a/crates/openshell-driver-kubernetes/src/lib.rs b/crates/openshell-driver-kubernetes/src/lib.rs index 7c56c8de5b..1a234385c6 100644 --- a/crates/openshell-driver-kubernetes/src/lib.rs +++ b/crates/openshell-driver-kubernetes/src/lib.rs @@ -6,9 +6,10 @@ pub mod driver; pub mod grpc; pub use config::{ - AppArmorProfile, DEFAULT_PROXY_UID, DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, + AppArmorProfile, DEFAULT_GATEWAY_ID, DEFAULT_PROXY_UID, DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, DEFAULT_WORKSPACE_STORAGE_SIZE, KubernetesComputeConfig, KubernetesSidecarConfig, - SupervisorSideloadMethod, SupervisorTopology, + ManagedSshIngressConfig, OperatorNamespaceAllowlist, SupervisorSideloadMethod, + SupervisorTopology, WorkspaceMode, managed_namespace_prefix, }; pub use driver::{KubernetesComputeDriver, KubernetesDriverError}; pub use grpc::ComputeDriverService; diff --git a/crates/openshell-driver-kubernetes/src/main.rs b/crates/openshell-driver-kubernetes/src/main.rs index 99df4ea165..30b4fcada9 100644 --- a/crates/openshell-driver-kubernetes/src/main.rs +++ b/crates/openshell-driver-kubernetes/src/main.rs @@ -3,6 +3,7 @@ use clap::{ArgAction, Parser}; use miette::{IntoDiagnostic, Result}; +use std::collections::BTreeMap; use std::net::SocketAddr; use tracing::info; use tracing_subscriber::EnvFilter; @@ -10,9 +11,10 @@ use tracing_subscriber::EnvFilter; use openshell_core::VERSION; use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; use openshell_driver_kubernetes::{ - AppArmorProfile, ComputeDriverService, DEFAULT_PROXY_UID, DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, - KubernetesComputeConfig, KubernetesComputeDriver, KubernetesSidecarConfig, - SupervisorSideloadMethod, SupervisorTopology, + AppArmorProfile, ComputeDriverService, DEFAULT_GATEWAY_ID, DEFAULT_PROXY_UID, + DEFAULT_SANDBOX_SERVICE_ACCOUNT_NAME, KubernetesComputeConfig, KubernetesComputeDriver, + KubernetesSidecarConfig, ManagedSshIngressConfig, SupervisorSideloadMethod, SupervisorTopology, + WorkspaceMode, }; #[derive(Parser, Debug)] @@ -30,9 +32,25 @@ struct Args { #[arg(long, env = "OPENSHELL_LOG_LEVEL", default_value = "info")] log_level: String, + #[arg(long, env = "OPENSHELL_WORKSPACE_MODE", default_value = "shared")] + workspace_mode: WorkspaceMode, + + #[arg( + long, + env = "OPENSHELL_GATEWAY_ID", + default_value = DEFAULT_GATEWAY_ID + )] + gateway_id: String, + #[arg(long, env = "OPENSHELL_SANDBOX_NAMESPACE", default_value = "default")] sandbox_namespace: String, + #[arg(long, env = "OPENSHELL_OPERATOR_NAMESPACE_LABEL")] + operator_namespace_label: Option, + + #[arg(long, env = "OPENSHELL_OPERATOR_NAMESPACE_FILE")] + operator_namespace_file: Option, + #[arg( long, env = "OPENSHELL_K8S_SANDBOX_SERVICE_ACCOUNT", @@ -53,6 +71,19 @@ struct Args { )] sandbox_image_pull_secrets: Vec, + #[arg(long, env = "OPENSHELL_MANAGED_SSH_INGRESS_ENABLED")] + managed_ssh_ingress_enabled: bool, + + #[arg(long, env = "OPENSHELL_MANAGED_SSH_GATEWAY_NAMESPACE")] + managed_ssh_gateway_namespace: Option, + + #[arg( + long, + env = "OPENSHELL_MANAGED_SSH_GATEWAY_POD_SELECTOR", + value_delimiter = ',' + )] + managed_ssh_gateway_pod_selector: Vec, + #[arg(long, env = "OPENSHELL_GRPC_ENDPOINT")] grpc_endpoint: Option, @@ -148,6 +179,29 @@ struct Args { sandbox_gid: Option, } +async fn shutdown_signal() { + #[cfg(unix)] + { + let terminate = async { + match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { + Ok(mut signal) => { + signal.recv().await; + } + Err(_) => std::future::pending::<()>().await, + } + }; + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + () = terminate => {} + } + } + + #[cfg(not(unix))] + { + let _ = tokio::signal::ctrl_c().await; + } +} + #[tokio::main] async fn main() -> Result<()> { let args = Args::parse(); @@ -157,58 +211,88 @@ async fn main() -> Result<()> { ) .init(); - let driver = KubernetesComputeDriver::new(KubernetesComputeConfig { - namespace: args.sandbox_namespace, - service_account_name: args.sandbox_service_account, - default_image: args.sandbox_image.unwrap_or_default(), - image_pull_policy: args.sandbox_image_pull_policy.unwrap_or_default(), - image_pull_secrets: args.sandbox_image_pull_secrets, - supervisor_image: args - .supervisor_image - .unwrap_or_else(openshell_core::config::default_supervisor_image), - supervisor_image_pull_policy: args.supervisor_image_pull_policy.unwrap_or_default(), - supervisor_sideload_method: args.supervisor_sideload_method, - topology: args.topology, - sidecar: KubernetesSidecarConfig { - proxy_uid: args.sidecar_proxy_uid, - process_binary_aware_network_policy: args.sidecar_process_binary_aware_network_policy, + let managed_ssh_gateway_pod_selector = args + .managed_ssh_gateway_pod_selector + .iter() + .map(|entry| { + entry + .split_once('=') + .map(|(key, value)| (key.to_string(), value.to_string())) + .ok_or_else(|| { + miette::miette!("managed SSH gateway pod selector must use key=value: {entry}") + }) + }) + .collect::>>()?; + + let (shutdown_tx, shutdown_rx) = tokio::sync::watch::channel(false); + let driver = KubernetesComputeDriver::new( + KubernetesComputeConfig { + workspace_mode: args.workspace_mode, + gateway_id: args.gateway_id, + namespace: args.sandbox_namespace, + operator_namespace_label: args.operator_namespace_label, + operator_namespace_file: args.operator_namespace_file, + service_account_name: args.sandbox_service_account, + default_image: args.sandbox_image.unwrap_or_default(), + image_pull_policy: args.sandbox_image_pull_policy.unwrap_or_default(), + image_pull_secrets: args.sandbox_image_pull_secrets, + managed_ssh_ingress: ManagedSshIngressConfig { + enabled: args.managed_ssh_ingress_enabled, + gateway_namespace: args.managed_ssh_gateway_namespace.unwrap_or_default(), + gateway_pod_selector: managed_ssh_gateway_pod_selector, + }, + supervisor_image: args + .supervisor_image + .unwrap_or_else(openshell_core::config::default_supervisor_image), + supervisor_image_pull_policy: args.supervisor_image_pull_policy.unwrap_or_default(), + supervisor_sideload_method: args.supervisor_sideload_method, + topology: args.topology, + sidecar: KubernetesSidecarConfig { + proxy_uid: args.sidecar_proxy_uid, + process_binary_aware_network_policy: args + .sidecar_process_binary_aware_network_policy, + }, + https_proxy: args.https_proxy, + no_proxy: args.no_proxy, + proxy_auth_secret_name: args.proxy_auth_secret_name, + proxy_auth_secret_key: args.proxy_auth_secret_key, + proxy_auth_allow_insecure: args.proxy_auth_allow_insecure.then_some(true), + proxy_connect_by_hostname: args.proxy_connect_by_hostname.then_some(true), + grpc_endpoint: args.grpc_endpoint.unwrap_or_default(), + ssh_socket_path: args.sandbox_ssh_socket_path, + client_tls_secret_name: args.client_tls_secret_name.unwrap_or_default(), + host_gateway_ip: args.host_gateway_ip.unwrap_or_default(), + enable_user_namespaces: args.enable_user_namespaces, + app_armor_profile: args.app_armor_profile, + workspace_default_storage_size: std::env::var( + "OPENSHELL_K8S_WORKSPACE_DEFAULT_STORAGE_SIZE", + ) + .unwrap_or_else(|_| { + openshell_driver_kubernetes::DEFAULT_WORKSPACE_STORAGE_SIZE.to_string() + }), + workspace_storage_class: std::env::var("OPENSHELL_K8S_WORKSPACE_STORAGE_CLASS") + .unwrap_or_default(), + default_runtime_class_name: std::env::var("OPENSHELL_K8S_DEFAULT_RUNTIME_CLASS_NAME") + .unwrap_or_default(), + sa_token_ttl_secs: args.sa_token_ttl_secs, + provider_spiffe_workload_api_socket_path: args + .provider_spiffe_workload_api_socket_path + .unwrap_or_default(), + sandbox_uid: args.sandbox_uid, + sandbox_gid: args.sandbox_gid, }, - https_proxy: args.https_proxy, - no_proxy: args.no_proxy, - proxy_auth_secret_name: args.proxy_auth_secret_name, - proxy_auth_secret_key: args.proxy_auth_secret_key, - proxy_auth_allow_insecure: args.proxy_auth_allow_insecure.then_some(true), - proxy_connect_by_hostname: args.proxy_connect_by_hostname.then_some(true), - grpc_endpoint: args.grpc_endpoint.unwrap_or_default(), - ssh_socket_path: args.sandbox_ssh_socket_path, - client_tls_secret_name: args.client_tls_secret_name.unwrap_or_default(), - host_gateway_ip: args.host_gateway_ip.unwrap_or_default(), - enable_user_namespaces: args.enable_user_namespaces, - app_armor_profile: args.app_armor_profile, - workspace_default_storage_size: std::env::var( - "OPENSHELL_K8S_WORKSPACE_DEFAULT_STORAGE_SIZE", - ) - .unwrap_or_else(|_| { - openshell_driver_kubernetes::DEFAULT_WORKSPACE_STORAGE_SIZE.to_string() - }), - workspace_storage_class: std::env::var("OPENSHELL_K8S_WORKSPACE_STORAGE_CLASS") - .unwrap_or_default(), - default_runtime_class_name: std::env::var("OPENSHELL_K8S_DEFAULT_RUNTIME_CLASS_NAME") - .unwrap_or_default(), - sa_token_ttl_secs: args.sa_token_ttl_secs, - provider_spiffe_workload_api_socket_path: args - .provider_spiffe_workload_api_socket_path - .unwrap_or_default(), - sandbox_uid: args.sandbox_uid, - sandbox_gid: args.sandbox_gid, - }) + shutdown_rx, + ) .await .into_diagnostic()?; info!(address = %args.bind_address, "Starting Kubernetes compute driver"); tonic::transport::Server::builder() .add_service(ComputeDriverServer::new(ComputeDriverService::new(driver))) - .serve(args.bind_address) + .serve_with_shutdown(args.bind_address, async move { + shutdown_signal().await; + let _ = shutdown_tx.send(true); + }) .await .into_diagnostic() } diff --git a/crates/openshell-driver-podman/src/grpc.rs b/crates/openshell-driver-podman/src/grpc.rs index 8d34660514..19d0b55254 100644 --- a/crates/openshell-driver-podman/src/grpc.rs +++ b/crates/openshell-driver-podman/src/grpc.rs @@ -6,12 +6,13 @@ use futures::{Stream, StreamExt}; use openshell_core::proto::compute::v1::{ CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, - GetCapabilitiesRequest, GetCapabilitiesResponse, GetGatewayListenerRequirementsRequest, - GetGatewayListenerRequirementsResponse, GetSandboxRequest, GetSandboxResponse, - ListSandboxesRequest, ListSandboxesResponse, StartSandboxRequest, StartSandboxResponse, - StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest, - ValidateSandboxCreateResponse, WatchSandboxesEvent, WatchSandboxesRequest, - compute_driver_server::ComputeDriver, + DeleteWorkspaceRequest, DeleteWorkspaceResponse, EnsureWorkspaceRequest, + EnsureWorkspaceResponse, GetCapabilitiesRequest, GetCapabilitiesResponse, + GetGatewayListenerRequirementsRequest, GetGatewayListenerRequirementsResponse, + GetSandboxRequest, GetSandboxResponse, ListSandboxesRequest, ListSandboxesResponse, + StartSandboxRequest, StartSandboxResponse, StopSandboxRequest, StopSandboxResponse, + ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, WatchSandboxesEvent, + WatchSandboxesRequest, compute_driver_server::ComputeDriver, }; use std::pin::Pin; use tonic::{Request, Response, Status}; @@ -170,6 +171,20 @@ impl ComputeDriver for ComputeDriverService { let stream = stream.map(|item| item.map_err(|err| Status::internal(err.to_string()))); Ok(Response::new(Box::pin(stream))) } + + async fn ensure_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(EnsureWorkspaceResponse {})) + } + + async fn delete_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(DeleteWorkspaceResponse {})) + } } #[cfg(test)] diff --git a/crates/openshell-driver-vm/src/driver.rs b/crates/openshell-driver-vm/src/driver.rs index af914ec467..4dd2ea059b 100644 --- a/crates/openshell-driver-vm/src/driver.rs +++ b/crates/openshell-driver-vm/src/driver.rs @@ -38,15 +38,17 @@ use openshell_core::progress::{ }; use openshell_core::proto::compute::v1::{ CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, - DriverCondition as SandboxCondition, DriverPlatformEvent as PlatformEvent, - DriverSandbox as Sandbox, DriverSandboxStatus as SandboxStatus, - DriverSandboxTemplate as SandboxTemplate, GetCapabilitiesRequest, GetCapabilitiesResponse, - GetGatewayListenerRequirementsRequest, GetGatewayListenerRequirementsResponse, - GetSandboxRequest, GetSandboxResponse, ListSandboxesRequest, ListSandboxesResponse, - StartSandboxRequest, StartSandboxResponse, StopSandboxRequest, StopSandboxResponse, - ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, WatchSandboxesDeletedEvent, - WatchSandboxesEvent, WatchSandboxesPlatformEvent, WatchSandboxesRequest, - WatchSandboxesSandboxEvent, compute_driver_server::ComputeDriver, watch_sandboxes_event, + DeleteWorkspaceRequest, DeleteWorkspaceResponse, DriverCondition as SandboxCondition, + DriverPlatformEvent as PlatformEvent, DriverSandbox as Sandbox, + DriverSandboxStatus as SandboxStatus, DriverSandboxTemplate as SandboxTemplate, + EnsureWorkspaceRequest, EnsureWorkspaceResponse, GetCapabilitiesRequest, + GetCapabilitiesResponse, GetGatewayListenerRequirementsRequest, + GetGatewayListenerRequirementsResponse, GetSandboxRequest, GetSandboxResponse, + ListSandboxesRequest, ListSandboxesResponse, StartSandboxRequest, StartSandboxResponse, + StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest, + ValidateSandboxCreateResponse, WatchSandboxesDeletedEvent, WatchSandboxesEvent, + WatchSandboxesPlatformEvent, WatchSandboxesRequest, WatchSandboxesSandboxEvent, + compute_driver_server::ComputeDriver, watch_sandboxes_event, }; use openshell_core::proto_struct::{ deserialize_optional_non_empty_string_list, struct_to_json_value, @@ -3432,6 +3434,20 @@ impl ComputeDriver for VmDriver { let stream: Self::WatchSandboxesStream = Box::pin(ReceiverStream::new(out_rx)); Ok(Response::new(stream)) } + + async fn ensure_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(EnsureWorkspaceResponse {})) + } + + async fn delete_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(DeleteWorkspaceResponse {})) + } } #[cfg(target_os = "linux")] diff --git a/crates/openshell-extension-core/BUILD.bazel b/crates/openshell-extension-core/BUILD.bazel new file mode 100644 index 0000000000..bd8cf31ab9 --- /dev/null +++ b/crates/openshell-extension-core/BUILD.bazel @@ -0,0 +1,27 @@ +load("@crates//:defs.bzl", "aliases", "all_crate_deps") +load("@rules_rs//rs:rust_library.bzl", "rust_library") +load("@rules_rs//rs:rust_test.bzl", "rust_test") +load("@rules_rust//rust:defs.bzl", "rustfmt_test") + +rust_library( + name = "openshell-extension-core", + srcs = glob(["src/**/*.rs"]), + aliases = aliases(), + visibility = ["//visibility:public"], + deps = all_crate_deps(normal = True), +) + +rust_test( + name = "openshell-extension-core_test", + crate = ":openshell-extension-core", + deps = all_crate_deps(normal_dev = True), +) + +rustfmt_test( + name = "rustfmt_test", + targets = [ + ":openshell-extension-core", + ":openshell-extension-core_test", + ], + visibility = ["//crates:__pkg__"], +) diff --git a/crates/openshell-extension-core/Cargo.toml b/crates/openshell-extension-core/Cargo.toml new file mode 100644 index 0000000000..babbeca295 --- /dev/null +++ b/crates/openshell-extension-core/Cargo.toml @@ -0,0 +1,30 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +[package] +name = "openshell-extension-core" +description = "Shared extension identity, authentication, and transport primitives for OpenShell" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true + +[dependencies] +hyper-util = { workspace = true, features = ["tokio"] } +serde = { workspace = true, features = ["derive"] } +thiserror = { workspace = true } +tokio = { workspace = true } +tonic = { workspace = true, features = ["channel", "tls-native-roots"] } +tower = { workspace = true } + +[dev-dependencies] +http = { workspace = true } +rcgen = { workspace = true } +rustls = { workspace = true } +serde_json = { workspace = true } +tokio-stream = { workspace = true, features = ["net"] } +tonic = { workspace = true, features = ["server", "tls-native-roots"] } + +[lints] +workspace = true diff --git a/crates/openshell-extension-core/README.md b/crates/openshell-extension-core/README.md new file mode 100644 index 0000000000..e8f342bbd4 --- /dev/null +++ b/crates/openshell-extension-core/README.md @@ -0,0 +1,25 @@ +# OpenShell extension core + +`openshell-extension-core` contains protocol-neutral primitives shared by two or +more OpenShell extension mechanisms. It currently owns extension identity and +audience values, the extension JWT claim contract, refreshable bearer +credentials and the per-service store that holds them, and outbound gRPC +transport construction for HTTP, HTTPS, and Unix sockets. + +`ExtensionKind` is non-exhaustive so additional extension points can join the +shared identity and audience model without breaking consumers. A new kind must +still define its own registration, transport, and authorization semantics +before gateway wiring accepts it. + +Outbound HTTPS authentication is selected through the shared +`ExtensionServerTrust` policy. Platform roots and operator-provided CA bundles +are implemented today. The non-exhaustive policy boundary allows future +SPIFFE X.509-SVID or public-key pinning support to be added once without +changing middleware and interceptor clients independently. Unix sockets retain +their local operating-system access boundary. + +Middleware- or interceptor-specific protobuf clients, policy selection, +orchestration, and lifecycle management stay in their owning crates. Gateway +signing authority also stays in `openshell-server`. This ownership rule keeps +this crate from becoming a general-purpose dumping ground as extension support +grows. diff --git a/crates/openshell-extension-core/src/auth.rs b/crates/openshell-extension-core/src/auth.rs new file mode 100644 index 0000000000..cc559754a3 --- /dev/null +++ b/crates/openshell-extension-core/src/auth.rs @@ -0,0 +1,252 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::fmt; +use std::sync::{Arc, RwLock}; +use std::time::{SystemTime, UNIX_EPOCH}; + +use tonic::metadata::AsciiMetadataValue; +use tonic::{Request, Status}; + +#[derive(Clone)] +pub struct BearerTokenSlot { + inner: Arc>>, +} + +#[derive(Clone)] +struct Token { + authorization: AsciiMetadataValue, + expires_at_ms: i64, +} + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum TokenSlotError { + #[error("extension bearer token is not valid for an HTTP authorization header")] + InvalidToken, + #[error("extension bearer token expiry must be a positive Unix timestamp in milliseconds")] + InvalidExpiry, +} + +impl BearerTokenSlot { + /// Create an empty slot. Requests fail closed until [`Self::update`] is called. + pub fn empty() -> Self { + Self { + inner: Arc::new(RwLock::new(None)), + } + } + + pub fn new(token: &str, expires_at_ms: i64) -> Result { + let slot = Self::empty(); + slot.update(token, expires_at_ms)?; + Ok(slot) + } + + /// Replace the credential without rebuilding channels or generated clients. + pub fn update(&self, token: &str, expires_at_ms: i64) -> Result<(), TokenSlotError> { + if expires_at_ms <= 0 { + return Err(TokenSlotError::InvalidExpiry); + } + if token.is_empty() || token.bytes().any(|byte| byte.is_ascii_whitespace()) { + return Err(TokenSlotError::InvalidToken); + } + let authorization = AsciiMetadataValue::try_from(format!("Bearer {token}")) + .map_err(|_| TokenSlotError::InvalidToken)?; + *self + .inner + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Token { + authorization, + expires_at_ms, + }); + Ok(()) + } + + /// Remove the credential immediately. Subsequent requests fail closed. + pub fn clear(&self) { + *self + .inner + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) = None; + } + + pub fn expires_at_ms(&self) -> Option { + self.inner + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .as_ref() + .map(|token| token.expires_at_ms) + } + + pub fn interceptor(&self) -> BearerTokenInterceptor { + BearerTokenInterceptor { + slot: Some(self.clone()), + } + } + + fn authorization_at(&self, now_ms: i64) -> Result { + let guard = self + .inner + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let token = guard + .as_ref() + .ok_or_else(|| Status::unauthenticated("extension bearer token is unavailable"))?; + if token.expires_at_ms <= now_ms { + return Err(Status::unauthenticated( + "extension bearer token has expired", + )); + } + Ok(token.authorization.clone()) + } +} + +impl Default for BearerTokenSlot { + fn default() -> Self { + Self::empty() + } +} + +impl fmt::Debug for BearerTokenSlot { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BearerTokenSlot") + .field("expires_at_ms", &self.expires_at_ms()) + .finish_non_exhaustive() + } +} + +#[derive(Clone)] +pub struct BearerTokenInterceptor { + slot: Option, +} + +impl BearerTokenInterceptor { + /// Create an explicit no-op interceptor for legacy registrations that have + /// not opted into audience authentication. + pub const fn disabled() -> Self { + Self { slot: None } + } +} + +impl fmt::Debug for BearerTokenInterceptor { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_struct("BearerTokenInterceptor") + .field("enabled", &self.slot.is_some()) + .field("slot", &self.slot) + .finish() + } +} + +impl tonic::service::Interceptor for BearerTokenInterceptor { + fn call(&mut self, mut request: Request<()>) -> Result, Status> { + let Some(slot) = &self.slot else { + return Ok(request); + }; + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| { + i64::try_from(duration.as_millis()).unwrap_or(i64::MAX) + }); + let authorization = slot.authorization_at(now_ms)?; + request + .metadata_mut() + .insert("authorization", authorization); + Ok(request) + } +} + +#[cfg(test)] +mod tests { + use tonic::service::Interceptor; + + use super::*; + + #[test] + fn slot_rotates_all_interceptor_clones_in_place() { + let slot = BearerTokenSlot::new("first-secret", i64::MAX).unwrap(); + let mut first = slot.interceptor(); + let mut second = first.clone(); + + assert_eq!( + first + .call(Request::new(())) + .unwrap() + .metadata() + .get("authorization") + .unwrap(), + "Bearer first-secret" + ); + slot.update("second-secret", i64::MAX).unwrap(); + assert_eq!( + second + .call(Request::new(())) + .unwrap() + .metadata() + .get("authorization") + .unwrap(), + "Bearer second-secret" + ); + } + + #[test] + fn empty_expired_and_cleared_slots_fail_closed() { + let slot = BearerTokenSlot::empty(); + assert_eq!( + slot.interceptor() + .call(Request::new(())) + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + + slot.update("expired", 1).unwrap(); + assert_eq!( + slot.interceptor() + .call(Request::new(())) + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + + slot.update("current", i64::MAX).unwrap(); + slot.clear(); + assert_eq!( + slot.interceptor() + .call(Request::new(())) + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + } + + #[test] + fn debug_and_errors_do_not_expose_token_material() { + let secret = "super-secret-extension-token"; + let slot = BearerTokenSlot::new(secret, i64::MAX).unwrap(); + assert!(!format!("{slot:?}").contains(secret)); + assert!(!format!("{:?}", slot.interceptor()).contains(secret)); + + let error = BearerTokenSlot::new("contains\nnewline", i64::MAX).unwrap_err(); + assert!(!error.to_string().contains("contains")); + assert_eq!( + BearerTokenSlot::new("", i64::MAX).unwrap_err(), + TokenSlotError::InvalidToken + ); + } + + #[test] + fn disabled_interceptor_leaves_authorization_untouched() { + let mut interceptor = BearerTokenInterceptor::disabled(); + let mut request = Request::new(()); + request + .metadata_mut() + .insert("authorization", "Bearer caller-value".parse().unwrap()); + let request = interceptor.call(request).unwrap(); + assert_eq!( + request.metadata().get("authorization").unwrap(), + "Bearer caller-value" + ); + assert!(format!("{interceptor:?}").contains("enabled: false")); + } +} diff --git a/crates/openshell-extension-core/src/identity.rs b/crates/openshell-extension-core/src/identity.rs new file mode 100644 index 0000000000..88de7ec867 --- /dev/null +++ b/crates/openshell-extension-core/src/identity.rs @@ -0,0 +1,180 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::fmt; +use std::str::FromStr; + +use serde::{Deserialize, Serialize}; + +/// Extension mechanism that owns a service registration. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +#[non_exhaustive] +pub enum ExtensionKind { + Middleware, + Interceptor, +} + +impl ExtensionKind { + pub const fn as_str(self) -> &'static str { + match self { + Self::Middleware => "middleware", + Self::Interceptor => "interceptor", + } + } +} + +impl fmt::Display for ExtensionKind { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(self.as_str()) + } +} + +/// A gateway-owned registration name for a middleware or interceptor service. +#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ExtensionIdentity(String); + +/// The exact JWT audience expected by an extension service. +/// +/// Audiences are intentionally opaque. Callers must resolve them from trusted +/// gateway configuration rather than constructing them from untrusted input. +#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub struct ExtensionAudience(String); + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum IdentityError { + #[error("extension {kind} must not be empty")] + Empty { kind: &'static str }, + #[error("extension {kind} must not have leading or trailing whitespace")] + SurroundingWhitespace { kind: &'static str }, + #[error("extension {kind} must not contain control characters")] + ControlCharacter { kind: &'static str }, +} + +macro_rules! opaque_value { + ($ty:ident, $kind:literal) => { + impl $ty { + pub fn new(value: impl Into) -> Result { + let value = value.into(); + validate(&value, $kind)?; + Ok(Self(value)) + } + + pub fn as_str(&self) -> &str { + &self.0 + } + + pub fn into_inner(self) -> String { + self.0 + } + } + + impl fmt::Debug for $ty { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter + .debug_tuple(stringify!($ty)) + .field(&self.0) + .finish() + } + } + + impl fmt::Display for $ty { + fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str(&self.0) + } + } + + impl AsRef for $ty { + fn as_ref(&self) -> &str { + self.as_str() + } + } + + impl FromStr for $ty { + type Err = IdentityError; + + fn from_str(value: &str) -> Result { + Self::new(value) + } + } + }; +} + +opaque_value!(ExtensionIdentity, "identity"); +opaque_value!(ExtensionAudience, "audience"); + +impl ExtensionAudience { + /// Build the deterministic fallback audience for a validated registration. + /// + /// Explicit operator-configured audiences remain opaque and take precedence. + /// This helper gives both extension mechanisms the same fallback namespace. + pub fn for_registration( + kind: ExtensionKind, + registration_name: &str, + ) -> Result { + let identity = ExtensionIdentity::new(registration_name)?; + Ok(Self(format!("urn:openshell:extension:{kind}:{identity}"))) + } +} + +fn validate(value: &str, kind: &'static str) -> Result<(), IdentityError> { + if value.is_empty() { + return Err(IdentityError::Empty { kind }); + } + if value.trim() != value { + return Err(IdentityError::SurroundingWhitespace { kind }); + } + if value.chars().any(char::is_control) { + return Err(IdentityError::ControlCharacter { kind }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn identity_and_audience_are_opaque_exact_values() { + let identity = ExtensionIdentity::new("content-filter").unwrap(); + let audience = ExtensionAudience::new("https://filters.example/openshell").unwrap(); + assert_eq!(identity.as_str(), "content-filter"); + assert_eq!(audience.as_str(), "https://filters.example/openshell"); + } + + #[test] + fn values_reject_ambiguous_whitespace_and_controls() { + assert_eq!( + ExtensionIdentity::new(" content-filter").unwrap_err(), + IdentityError::SurroundingWhitespace { kind: "identity" } + ); + assert_eq!( + ExtensionAudience::new("audience\n").unwrap_err(), + IdentityError::SurroundingWhitespace { kind: "audience" } + ); + assert_eq!( + ExtensionAudience::new("").unwrap_err(), + IdentityError::Empty { kind: "audience" } + ); + } + + #[test] + fn fallback_audience_is_kind_scoped_and_validates_registration() { + assert_eq!( + ExtensionAudience::for_registration(ExtensionKind::Middleware, "content-filter") + .unwrap() + .as_str(), + "urn:openshell:extension:middleware:content-filter" + ); + assert_eq!( + ExtensionAudience::for_registration(ExtensionKind::Interceptor, "content-filter") + .unwrap() + .as_str(), + "urn:openshell:extension:interceptor:content-filter" + ); + assert!(matches!( + ExtensionAudience::for_registration(ExtensionKind::Middleware, " bad-name"), + Err(IdentityError::SurroundingWhitespace { kind: "identity" }) + )); + } +} diff --git a/crates/openshell-extension-core/src/jwt.rs b/crates/openshell-extension-core/src/jwt.rs new file mode 100644 index 0000000000..4bf5d39189 --- /dev/null +++ b/crates/openshell-extension-core/src/jwt.rs @@ -0,0 +1,80 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::time::Duration; + +use serde::{Deserialize, Serialize}; + +/// Maximum accepted lifetime for an extension bearer token. +/// +/// Extension credentials cross the gateway trust boundary and must remain +/// short-lived even when legacy sandbox bootstrap credentials do not expire. +pub const MAX_EXTENSION_TOKEN_TTL: Duration = Duration::from_secs(3_600); + +/// Explicit `typ` header value carried by every extension bearer token. +/// +/// Extension tokens and sandbox-to-gateway bootstrap tokens are signed by the +/// same key and differ only in their audience. Explicit typing (RFC 8725 +/// section 3.11) gives verifiers a second, independent discriminator: a +/// service that requires this `typ` cannot accept a sandbox bootstrap +/// credential even if it forgets to check `aud`. +pub const EXTENSION_JWT_TYP: &str = "openshell-ext+jwt"; + +/// `OpenShell` component calling an extension service. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum ExtensionCallerKind { + Gateway, + Supervisor, +} + +/// JWT claim set accepted by external extension services. +/// +/// This intentionally differs from sandbox bootstrap claims. Sharing a signing +/// key does not make a sandbox-to-gateway credential valid at an extension. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct ExtensionJwtClaims { + pub iss: String, + pub aud: String, + pub sub: String, + pub iat: i64, + pub exp: i64, + pub jti: String, + pub caller_kind: ExtensionCallerKind, + #[serde(skip_serializing_if = "Option::is_none")] + pub sandbox_id: Option, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn caller_kind_uses_stable_snake_case_wire_values() { + assert_eq!( + serde_json::to_string(&ExtensionCallerKind::Gateway).unwrap(), + "\"gateway\"" + ); + assert_eq!( + serde_json::to_string(&ExtensionCallerKind::Supervisor).unwrap(), + "\"supervisor\"" + ); + } + + #[test] + fn gateway_claims_omit_sandbox_id() { + let claims = ExtensionJwtClaims { + iss: "openshell-gateway:test".to_string(), + aud: "urn:openshell:extension:interceptor:test".to_string(), + sub: "openshell-gateway:test".to_string(), + iat: 1, + exp: 2, + jti: "unique".to_string(), + caller_kind: ExtensionCallerKind::Gateway, + sandbox_id: None, + }; + let json = serde_json::to_value(claims).unwrap(); + assert!(json.get("sandbox_id").is_none()); + assert_eq!(json["caller_kind"], "gateway"); + } +} diff --git a/crates/openshell-extension-core/src/lib.rs b/crates/openshell-extension-core/src/lib.rs new file mode 100644 index 0000000000..d24621f205 --- /dev/null +++ b/crates/openshell-extension-core/src/lib.rs @@ -0,0 +1,22 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Protocol-neutral primitives shared by `OpenShell` extension mechanisms. +//! +//! Subsystem-specific protobuf clients and orchestration do not belong here. + +mod auth; +mod identity; +mod jwt; +mod store; +mod transport; + +pub use auth::{BearerTokenInterceptor, BearerTokenSlot, TokenSlotError}; +pub use identity::{ExtensionAudience, ExtensionIdentity, ExtensionKind, IdentityError}; +pub use jwt::{ + EXTENSION_JWT_TYP, ExtensionCallerKind, ExtensionJwtClaims, MAX_EXTENSION_TOKEN_TTL, +}; +pub use store::ExtensionCredentialStore; +pub use transport::{ + ExtensionChannelConfig, ExtensionServerTrust, TransportError, connect_channel, +}; diff --git a/crates/openshell-extension-core/src/store.rs b/crates/openshell-extension-core/src/store.rs new file mode 100644 index 0000000000..2e6b94be25 --- /dev/null +++ b/crates/openshell-extension-core/src/store.rs @@ -0,0 +1,317 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::collections::{HashMap, HashSet}; +use std::sync::{Arc, RwLock}; + +use crate::auth::{BearerTokenSlot, TokenSlotError}; + +/// Fraction of a credential's remaining lifetime to consume before rotating. +/// Matches the gateway-token renewal policy so both credentials refresh well +/// before expiry rather than at it. +const REFRESH_AT_FRACTION: (i64, i64) = (4, 5); + +/// Shortest interval a caller is asked to wait before retrying a rotation. +const MIN_REFRESH_DELAY_MS: i64 = 1_000; + +#[derive(Clone)] +struct Entry { + slot: BearerTokenSlot, + /// Wall-clock point after which this credential should be rotated. Derived + /// once at install time because a slot records only its expiry, not the + /// lifetime it was issued with. + refresh_after_ms: i64, +} + +/// Per-service extension credentials held by one supervisor. +/// +/// Cloning shares the underlying map, so the registry's middleware clients and +/// the polling loop that rotates them observe the same slots. Ownership is +/// explicit rather than process-global: tests construct independent stores and +/// cannot interfere with each other. +#[derive(Clone, Default)] +pub struct ExtensionCredentialStore { + inner: Arc>>, +} + +impl ExtensionCredentialStore { + #[must_use] + pub fn new() -> Self { + Self::default() + } + + fn read(&self) -> std::sync::RwLockReadGuard<'_, HashMap> { + self.inner + .read() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + fn write(&self) -> std::sync::RwLockWriteGuard<'_, HashMap> { + self.inner + .write() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + + /// Install or rotate one credential, returning the shared slot. + /// + /// An existing slot is updated in place so clients already holding a clone + /// pick up the new token without rebuilding their channel. + pub fn install( + &self, + name: &str, + token: &str, + expires_at_ms: i64, + now_ms: i64, + ) -> Result { + let refresh_after_ms = refresh_deadline_ms(expires_at_ms, now_ms); + let mut slots = self.write(); + if let Some(entry) = slots.get_mut(name) { + entry.slot.update(token, expires_at_ms)?; + entry.refresh_after_ms = refresh_after_ms; + return Ok(entry.slot.clone()); + } + let slot = BearerTokenSlot::new(token, expires_at_ms)?; + slots.insert( + name.to_string(), + Entry { + slot: slot.clone(), + refresh_after_ms, + }, + ); + Ok(slot) + } + + #[must_use] + pub fn get(&self, name: &str) -> Option { + self.read().get(name).map(|entry| entry.slot.clone()) + } + + /// Snapshot the slots for `names`, or `None` if any is absent. + #[must_use] + pub fn slots_for(&self, names: &[String]) -> Option> { + let slots = self.read(); + names + .iter() + .map(|name| { + slots + .get(name) + .map(|entry| (name.clone(), entry.slot.clone())) + }) + .collect() + } + + #[must_use] + pub fn names(&self) -> Vec { + self.read().keys().cloned().collect() + } + + #[must_use] + pub fn is_empty(&self) -> bool { + self.read().is_empty() + } + + /// True when any requested credential is missing or due for rotation. + /// + /// Callers use this to avoid rotating on every configuration poll: a + /// 15-minute credential polled every 10 seconds would otherwise mint and + /// re-authorize roughly ninety times per useful rotation. + #[must_use] + pub fn needs_refresh(&self, names: &[String], now_ms: i64) -> bool { + let slots = self.read(); + names.iter().any(|name| { + slots + .get(name) + .is_none_or(|entry| entry.refresh_after_ms <= now_ms) + }) + } + + /// Bound `fallback` by the soonest rotation deadline so a caller's sleep + /// never overshoots a credential that must be rotated sooner. + #[must_use] + pub fn next_refresh_delay( + &self, + fallback: std::time::Duration, + now_ms: i64, + ) -> std::time::Duration { + let Some(earliest) = self + .read() + .values() + .map(|entry| entry.refresh_after_ms) + .min() + else { + return fallback; + }; + let remaining_ms = earliest.saturating_sub(now_ms).max(MIN_REFRESH_DELAY_MS); + fallback.min(std::time::Duration::from_millis( + u64::try_from(remaining_ms).unwrap_or(u64::MAX), + )) + } + + /// Drop credentials for services no longer in the installed registry. + /// + /// Detached slots are cleared before removal so any client still holding a + /// clone fails closed instead of continuing with a valid token. + pub fn retain(&self, names: &HashSet<&str>) { + self.write().retain(|name, entry| { + let keep = names.contains(name.as_str()); + if !keep { + entry.slot.clear(); + } + keep + }); + } +} + +impl std::fmt::Debug for ExtensionCredentialStore { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ExtensionCredentialStore") + .field("services", &self.names()) + .finish_non_exhaustive() + } +} + +fn refresh_deadline_ms(expires_at_ms: i64, now_ms: i64) -> i64 { + let remaining_ms = expires_at_ms.saturating_sub(now_ms); + if remaining_ms <= 0 { + return now_ms; + } + let consumed = remaining_ms + .saturating_mul(REFRESH_AT_FRACTION.0) + .checked_div(REFRESH_AT_FRACTION.1) + .unwrap_or(remaining_ms); + now_ms.saturating_add(consumed.max(MIN_REFRESH_DELAY_MS)) +} + +#[cfg(test)] +mod tests { + use std::time::Duration; + + use tonic::service::Interceptor; + + use super::*; + + const NOW: i64 = 1_000_000; + + /// Interceptor assertions compare against the real clock, so tests that + /// exercise a live slot need an expiry in the actual future rather than + /// the synthetic `NOW` used for deterministic scheduling arithmetic. + const FAR_FUTURE_MS: i64 = 4_102_444_800_000; + + #[test] + fn rotation_updates_existing_slots_in_place() { + let store = ExtensionCredentialStore::new(); + let first = store + .install("guard", "first-secret", FAR_FUTURE_MS, NOW) + .unwrap(); + let mut interceptor = first.interceptor(); + + store + .install("guard", "second-secret", FAR_FUTURE_MS, NOW) + .unwrap(); + + // The registry's client holds a clone from the first install; rotation + // must reach it without rebuilding the channel. + assert_eq!( + interceptor + .call(tonic::Request::new(())) + .unwrap() + .metadata() + .get("authorization") + .unwrap(), + "Bearer second-secret" + ); + } + + #[test] + fn refresh_is_due_only_after_four_fifths_of_the_lifetime() { + let store = ExtensionCredentialStore::new(); + let names = vec!["guard".to_string()]; + store + .install("guard", "secret", NOW + 900_000, NOW) + .unwrap(); + + assert!(!store.needs_refresh(&names, NOW)); + assert!(!store.needs_refresh(&names, NOW + 719_000)); + assert!(store.needs_refresh(&names, NOW + 720_001)); + + // An unknown service always forces a refresh so newly attached + // middleware acquires a credential before it is used. + assert!(store.needs_refresh(&["other".to_string()], NOW)); + } + + #[test] + fn poll_delay_is_bounded_by_the_soonest_rotation() { + let store = ExtensionCredentialStore::new(); + let fallback = Duration::from_secs(10); + assert_eq!(store.next_refresh_delay(fallback, NOW), fallback); + + // 15-minute credential: rotation is due long after the poll interval, + // so polling cadence is unchanged. + store + .install("guard", "secret", NOW + 900_000, NOW) + .unwrap(); + assert_eq!(store.next_refresh_delay(fallback, NOW), fallback); + + // Short-lived credential: the caller must wake before it is stale. + store.install("brief", "secret", NOW + 5_000, NOW).unwrap(); + assert_eq!( + store.next_refresh_delay(fallback, NOW), + Duration::from_secs(4) + ); + } + + #[test] + fn detached_credentials_are_cleared_before_removal() { + let store = ExtensionCredentialStore::new(); + let slot = store + .install("detached", "secret", FAR_FUTURE_MS, NOW) + .unwrap(); + store.install("kept", "secret", FAR_FUTURE_MS, NOW).unwrap(); + + store.retain(&HashSet::from(["kept"])); + + assert_eq!(store.names(), vec!["kept".to_string()]); + // A client still holding the detached slot must fail closed rather + // than keep using a token that is technically still valid. + assert_eq!( + slot.interceptor() + .call(tonic::Request::new(())) + .unwrap_err() + .code(), + tonic::Code::Unauthenticated + ); + } + + #[test] + fn slots_for_requires_every_requested_service() { + let store = ExtensionCredentialStore::new(); + store + .install("guard", "secret", NOW + 900_000, NOW) + .unwrap(); + + assert!(store.slots_for(&["guard".to_string()]).is_some()); + assert!( + store + .slots_for(&["guard".to_string(), "missing".to_string()]) + .is_none() + ); + } + + #[test] + fn already_expired_credentials_are_immediately_due() { + let store = ExtensionCredentialStore::new(); + store.install("guard", "secret", NOW - 1, NOW).unwrap(); + assert!(store.needs_refresh(&["guard".to_string()], NOW)); + } + + #[test] + fn stores_are_independent() { + let first = ExtensionCredentialStore::new(); + let second = ExtensionCredentialStore::new(); + first + .install("guard", "secret", NOW + 900_000, NOW) + .unwrap(); + assert!(second.is_empty()); + } +} diff --git a/crates/openshell-extension-core/src/transport.rs b/crates/openshell-extension-core/src/transport.rs new file mode 100644 index 0000000000..2f9a633237 --- /dev/null +++ b/crates/openshell-extension-core/src/transport.rs @@ -0,0 +1,345 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +use std::path::PathBuf; +use std::time::Duration; + +#[cfg(unix)] +use hyper_util::rt::TokioIo; +#[cfg(unix)] +use tokio::net::UnixStream; +#[cfg(unix)] +use tonic::transport::Uri; +use tonic::transport::{Certificate, Channel, ClientTlsConfig, Endpoint}; +#[cfg(unix)] +use tower::service_fn; + +const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); +const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(10); +const KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(20); + +/// Trust policy used to authenticate a remote extension service. +/// +/// This enum is intentionally independent of middleware and interceptor +/// protocols. Future transport identities, such as SPIFFE X.509-SVIDs or +/// pinned public keys, can be added here without changing either caller. +#[derive(Clone, PartialEq, Eq, Default)] +#[non_exhaustive] +pub enum ExtensionServerTrust { + /// Authenticate the HTTPS service with the platform trust store and the + /// endpoint's DNS name. + #[default] + PlatformRoots, + /// Authenticate the HTTPS service with only this PEM CA bundle and the + /// endpoint's DNS name. + CustomCaPem(Vec), +} + +impl std::fmt::Debug for ExtensionServerTrust { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::PlatformRoots => formatter.write_str("PlatformRoots"), + Self::CustomCaPem(_) => formatter.write_str("CustomCaPem()"), + } + } +} + +/// Configuration for an outbound extension gRPC channel. +#[derive(Clone, PartialEq, Eq)] +pub struct ExtensionChannelConfig { + endpoint: String, + server_trust: ExtensionServerTrust, +} + +impl ExtensionChannelConfig { + pub fn new(endpoint: impl Into) -> Self { + Self { + endpoint: endpoint.into(), + server_trust: ExtensionServerTrust::default(), + } + } + + /// Select how the remote extension service is authenticated. + #[must_use] + pub fn with_server_trust(mut self, server_trust: ExtensionServerTrust) -> Self { + self.server_trust = server_trust; + self + } + + /// Pin HTTPS verification to this CA bundle instead of platform roots. + /// Normal TLS hostname verification remains enabled. + #[must_use] + pub fn with_custom_ca_pem(self, custom_ca_pem: impl Into>) -> Self { + self.with_server_trust(ExtensionServerTrust::CustomCaPem(custom_ca_pem.into())) + } + + pub fn endpoint(&self) -> &str { + &self.endpoint + } + + pub fn server_trust(&self) -> &ExtensionServerTrust { + &self.server_trust + } + + /// Returns whether HTTPS verification uses an operator-provided CA bundle. + pub fn has_custom_ca(&self) -> bool { + matches!(&self.server_trust, ExtensionServerTrust::CustomCaPem(_)) + } +} + +impl std::fmt::Debug for ExtensionChannelConfig { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ExtensionChannelConfig") + .field("endpoint", &self.endpoint) + .field("server_trust", &self.server_trust) + .finish() + } +} + +#[derive(Debug, thiserror::Error)] +pub enum TransportError { + #[error("extension endpoint must not be empty")] + EmptyEndpoint, + #[error("extension endpoint must use http://, https://, or unix://")] + UnsupportedScheme, + #[error("custom CA certificates require an https:// extension endpoint")] + CustomCaRequiresHttps, + #[error("unix extension endpoint must contain an absolute socket path")] + InvalidUnixPath, + #[error("unix extension endpoints are not supported on this platform")] + UnixUnsupported, + #[error("invalid extension endpoint: {0}")] + InvalidEndpoint(#[source] tonic::transport::Error), + #[error("could not configure extension TLS: {0}")] + Tls(#[source] tonic::transport::Error), + #[error("could not connect to extension service: {0}")] + Connect(#[source] tonic::transport::Error), +} + +pub async fn connect_channel(config: &ExtensionChannelConfig) -> Result { + validate_config(config)?; + if let Some(path) = config.endpoint.strip_prefix("unix://") { + return connect_unix(PathBuf::from(path)).await; + } + + let mut endpoint = standard_endpoint(&config.endpoint)?; + if config.endpoint.starts_with("https://") { + let tls = match &config.server_trust { + ExtensionServerTrust::PlatformRoots => ClientTlsConfig::new().with_enabled_roots(), + ExtensionServerTrust::CustomCaPem(pem) => { + ClientTlsConfig::new().ca_certificate(Certificate::from_pem(pem)) + } + }; + endpoint = endpoint.tls_config(tls).map_err(TransportError::Tls)?; + } + endpoint.connect().await.map_err(TransportError::Connect) +} + +fn validate_config(config: &ExtensionChannelConfig) -> Result<(), TransportError> { + if config.endpoint.is_empty() { + return Err(TransportError::EmptyEndpoint); + } + let is_https = config.endpoint.starts_with("https://"); + let is_http = config.endpoint.starts_with("http://"); + let is_unix = config.endpoint.starts_with("unix://"); + if !is_https && !is_http && !is_unix { + return Err(TransportError::UnsupportedScheme); + } + if !matches!(&config.server_trust, ExtensionServerTrust::PlatformRoots) && !is_https { + return Err(TransportError::CustomCaRequiresHttps); + } + if let Some(path) = config.endpoint.strip_prefix("unix://") + && (path.is_empty() || !PathBuf::from(path).is_absolute()) + { + return Err(TransportError::InvalidUnixPath); + } + Ok(()) +} + +fn standard_endpoint(uri: &str) -> Result { + Endpoint::from_shared(uri.to_string()) + .map(|endpoint| { + endpoint + .connect_timeout(CONNECT_TIMEOUT) + .http2_keep_alive_interval(KEEP_ALIVE_INTERVAL) + .keep_alive_while_idle(true) + .keep_alive_timeout(KEEP_ALIVE_TIMEOUT) + .http2_adaptive_window(true) + }) + .map_err(TransportError::InvalidEndpoint) +} + +#[cfg(unix)] +async fn connect_unix(path: PathBuf) -> Result { + standard_endpoint("http://[::]:50051")? + .connect_with_connector(service_fn(move |_: Uri| { + let path = path.clone(); + async move { UnixStream::connect(path).await.map(TokioIo::new) } + })) + .await + .map_err(TransportError::Connect) +} + +#[cfg(not(unix))] +async fn connect_unix(_path: PathBuf) -> Result { + Err(TransportError::UnixUnsupported) +} + +#[cfg(test)] +mod tests { + use std::convert::Infallible; + use std::future::{Ready, ready}; + use std::task::{Context, Poll}; + + use rcgen::{BasicConstraints, CertificateParams, ExtendedKeyUsagePurpose, IsCa, KeyPair}; + use tokio::net::TcpListener; + use tokio_stream::wrappers::TcpListenerStream; + use tonic::body::Body; + use tonic::server::NamedService; + use tonic::transport::{Identity, Server, ServerTlsConfig}; + use tower::Service; + + use super::*; + + #[derive(Clone)] + struct NoopGrpcService; + + impl NamedService for NoopGrpcService { + const NAME: &'static str = "openshell.test.Noop"; + } + + impl Service> for NoopGrpcService { + type Response = http::Response; + type Error = Infallible; + type Future = Ready>; + + fn poll_ready(&mut self, _context: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, _request: http::Request) -> Self::Future { + ready(Ok(http::Response::new(Body::empty()))) + } + } + + #[test] + fn accepts_supported_endpoint_forms() { + for endpoint in [ + "http://127.0.0.1:50051", + "https://middleware.example:443", + "unix:///run/openshell/middleware.sock", + ] { + validate_config(&ExtensionChannelConfig::new(endpoint)).unwrap(); + } + } + + #[test] + fn server_trust_is_an_explicit_shared_policy() { + let default = ExtensionChannelConfig::new("https://middleware.example"); + assert!(matches!( + default.server_trust(), + ExtensionServerTrust::PlatformRoots + )); + + let custom = + default.with_server_trust(ExtensionServerTrust::CustomCaPem(b"test CA".to_vec())); + assert!(matches!( + custom.server_trust(), + ExtensionServerTrust::CustomCaPem(pem) if pem == b"test CA" + )); + } + + #[test] + fn custom_ca_is_restricted_to_https() { + for endpoint in [ + "http://127.0.0.1:50051", + "unix:///run/openshell/middleware.sock", + ] { + let config = ExtensionChannelConfig::new(endpoint).with_custom_ca_pem(b"test CA"); + assert!(matches!( + validate_config(&config), + Err(TransportError::CustomCaRequiresHttps) + )); + } + validate_config( + &ExtensionChannelConfig::new("https://middleware.example") + .with_custom_ca_pem(b"test CA"), + ) + .unwrap(); + } + + #[test] + fn rejects_unsupported_schemes_and_relative_unix_paths() { + assert!(matches!( + validate_config(&ExtensionChannelConfig::new("tcp://middleware:50051")), + Err(TransportError::UnsupportedScheme) + )); + assert!(matches!( + validate_config(&ExtensionChannelConfig::new("unix://relative.sock")), + Err(TransportError::InvalidUnixPath) + )); + } + + #[test] + fn debug_does_not_render_ca_contents() { + let secretish_pem = b"private deployment CA material"; + let config = ExtensionChannelConfig::new("https://middleware.example") + .with_custom_ca_pem(secretish_pem); + assert!(!format!("{config:?}").contains("private deployment")); + } + + #[tokio::test] + async fn custom_ca_verifies_certificate_and_hostname() { + let _ = rustls::crypto::ring::default_provider().install_default(); + let ca_key = KeyPair::generate().unwrap(); + let mut ca_params = CertificateParams::new(Vec::::new()).unwrap(); + ca_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + let ca = ca_params.self_signed(&ca_key).unwrap(); + + let server_key = KeyPair::generate().unwrap(); + let mut server_params = CertificateParams::new(vec!["localhost".to_string()]).unwrap(); + server_params.extended_key_usages = vec![ExtendedKeyUsagePurpose::ServerAuth]; + let server_cert = server_params.signed_by(&server_key, &ca, &ca_key).unwrap(); + + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let incoming = TcpListenerStream::new(listener); + let tls = ServerTlsConfig::new().identity(Identity::from_pem( + server_cert.pem(), + server_key.serialize_pem(), + )); + tokio::spawn(async move { + Server::builder() + .tls_config(tls) + .unwrap() + .add_service(NoopGrpcService) + .serve_with_incoming(incoming) + .await + .unwrap(); + }); + + let trusted = ExtensionChannelConfig::new(format!("https://localhost:{}", address.port())) + .with_custom_ca_pem(ca.pem()); + connect_channel(&trusted).await.unwrap(); + + let wrong_hostname = + ExtensionChannelConfig::new(format!("https://127.0.0.1:{}", address.port())) + .with_custom_ca_pem(ca.pem()); + assert!(matches!( + connect_channel(&wrong_hostname).await, + Err(TransportError::Connect(_)) + )); + + let rogue_key = KeyPair::generate().unwrap(); + let mut rogue_params = CertificateParams::new(Vec::::new()).unwrap(); + rogue_params.is_ca = IsCa::Ca(BasicConstraints::Unconstrained); + let rogue_ca = rogue_params.self_signed(&rogue_key).unwrap(); + let wrong_ca = ExtensionChannelConfig::new(format!("https://localhost:{}", address.port())) + .with_custom_ca_pem(rogue_ca.pem()); + assert!(matches!( + connect_channel(&wrong_ca).await, + Err(TransportError::Connect(_)) + )); + } +} diff --git a/crates/openshell-gateway-interceptors/Cargo.toml b/crates/openshell-gateway-interceptors/Cargo.toml index 7bcdd6eebf..f336562ec1 100644 --- a/crates/openshell-gateway-interceptors/Cargo.toml +++ b/crates/openshell-gateway-interceptors/Cargo.toml @@ -12,8 +12,8 @@ repository.workspace = true [dependencies] openshell-core = { path = "../openshell-core", default-features = false } +openshell-extension-core = { path = "../openshell-extension-core" } -hyper-util = { workspace = true, features = ["client", "http1", "http2", "tokio"] } json-patch = "1.4" metrics = { workspace = true } prost = { workspace = true } @@ -24,7 +24,6 @@ sha2 = { workspace = true } thiserror = { workspace = true } tokio = { workspace = true } tonic = { workspace = true, features = ["channel", "tls-native-roots"] } -tower = { workspace = true } tracing = { workspace = true } [dev-dependencies] diff --git a/crates/openshell-gateway-interceptors/src/lib.rs b/crates/openshell-gateway-interceptors/src/lib.rs index 32b4f3e525..d5bb5df59e 100644 --- a/crates/openshell-gateway-interceptors/src/lib.rs +++ b/crates/openshell-gateway-interceptors/src/lib.rs @@ -11,7 +11,12 @@ #![allow(clippy::result_large_err)] +use std::collections::BTreeMap; + use openshell_core::config::GatewayInterceptorConfig; +use openshell_extension_core::{BearerTokenInterceptor, BearerTokenSlot}; +use tonic::service::interceptor::InterceptedService; +use tonic::transport::Channel; pub(crate) mod plan; pub(crate) mod profile_source; @@ -38,13 +43,33 @@ pub enum InterceptorError { pub type Result = std::result::Result; +pub(crate) type ExtensionChannel = InterceptedService; + /// Return `None` when no interceptors are configured. pub async fn initialize( configs: Vec, +) -> Result> { + initialize_configured(configs, None).await +} + +/// Initialize gateway interceptors with rotating bearer-token slots. +/// +/// Every configured interceptor must have a corresponding slot. Slots may be +/// updated in place without rebuilding the execution plan or its gRPC clients. +pub async fn initialize_authenticated( + configs: Vec, + token_slots: BTreeMap, +) -> Result> { + initialize_configured(configs, Some(token_slots)).await +} + +async fn initialize_configured( + configs: Vec, + token_slots: Option>, ) -> Result> { if configs.is_empty() { return Ok(None); } - let runtime = GatewayInterceptorRuntime::build(configs).await?; + let runtime = GatewayInterceptorRuntime::build(configs, token_slots).await?; Ok(Some(runtime)) } diff --git a/crates/openshell-gateway-interceptors/src/plan.rs b/crates/openshell-gateway-interceptors/src/plan.rs index df6b940a85..c89de6f6ee 100644 --- a/crates/openshell-gateway-interceptors/src/plan.rs +++ b/crates/openshell-gateway-interceptors/src/plan.rs @@ -4,11 +4,8 @@ //! Interceptor configuration and immutable execution planning. use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::path::PathBuf; use std::time::Duration; -#[cfg(unix)] -use hyper_util::rt::TokioIo; use openshell_core::config::{ GatewayInterceptorBindingOverride, GatewayInterceptorBindingPolicy, GatewayInterceptorConfig, GatewayInterceptorFailurePolicy, GatewayInterceptorPhaseConfig, @@ -17,23 +14,16 @@ use openshell_core::proto::gateway_interceptor::v1::{ DescribeRequest, GatewayInterceptorPhase, InterceptorBinding, InterceptorSelector, gateway_interceptor_client::GatewayInterceptorClient, }; -#[cfg(unix)] -use tokio::net::UnixStream; +use openshell_extension_core::{ + BearerTokenInterceptor, BearerTokenSlot, ExtensionChannelConfig, ExtensionServerTrust, + connect_channel, +}; use tonic::Request; -#[cfg(unix)] -use tonic::codegen::http::Uri; -use tonic::transport::{Channel, ClientTlsConfig, Endpoint}; -#[cfg(unix)] -use tower::service_fn; use tracing::{info, warn}; use crate::profile_source::GatewayInterceptorProfileSource; use crate::routes::OpenShellRouteIndex; -use crate::{InterceptorError, Result}; - -const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); -const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(10); -const KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(20); +use crate::{ExtensionChannel, InterceptorError, Result}; pub const DEFAULT_TIMEOUT: Duration = Duration::from_millis(500); pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 1_048_576; @@ -145,7 +135,7 @@ pub struct BindingPlan { pub(crate) timeout: Duration, pub(crate) max_response_bytes: usize, pub(crate) max_patches: usize, - pub(crate) client: GatewayInterceptorClient, + pub(crate) client: GatewayInterceptorClient, } impl std::fmt::Debug for BindingPlan { @@ -183,15 +173,31 @@ impl ExecutionPlan { pub(crate) async fn load( mut configs: Vec, routes: OpenShellRouteIndex, + token_slots: Option>, ) -> Result { validate_interceptor_configs(&configs)?; + validate_authenticated_slots(&configs, token_slots.as_ref())?; configs.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name))); let mut bindings: BTreeMap<(RpcSelector, Phase), Vec> = BTreeMap::new(); let mut profile_sources = BTreeMap::new(); for config in configs { - let channel = connect_endpoint(&config.grpc_endpoint).await?; + let channel = connect_endpoint(&config).await?; + let interceptor = match token_slots.as_ref() { + Some(_) if config.allow_insecure_transport => BearerTokenInterceptor::disabled(), + Some(slots) => slots + .get(&config.name) + .ok_or_else(|| { + InterceptorError::Config(format!( + "authenticated interceptor '{}' is missing a bearer-token slot", + config.name + )) + })? + .interceptor(), + None => BearerTokenInterceptor::disabled(), + }; + let channel = ExtensionChannel::new(channel, interceptor); let timeout = match config.timeout.as_deref() { Some(timeout) => parse_duration(timeout)?, None => DEFAULT_TIMEOUT, @@ -218,6 +224,11 @@ impl ExecutionPlan { )) })? .into_inner(); + validate_expected_audience( + &config, + &manifest.expected_audience, + token_slots.is_some(), + )?; let service_default = match config.binding_policy { GatewayInterceptorBindingPolicy::Dynamic => { let manifest_default = parse_optional_failure_policy(&manifest.failure_policy)?; @@ -356,6 +367,54 @@ impl ExecutionPlan { } } +/// After authenticated Describe succeeds, reject an interceptor whose +/// configured audience differs from the one the service says it verifies. +/// +/// This is a post-authentication consistency assertion, not audience discovery: +/// a strict verifier may reject an incorrect audience before returning its +/// manifest. A service that does not advertise an audience is accepted unchanged. +fn validate_expected_audience( + config: &GatewayInterceptorConfig, + advertised: &str, + authenticated: bool, +) -> Result<()> { + if !authenticated || config.allow_insecure_transport || advertised.is_empty() { + return Ok(()); + } + let configured = config.resolved_audience(); + if advertised != configured { + return Err(InterceptorError::Config(format!( + "interceptor '{}' expects audience '{advertised}' but the gateway \ + is configured to mint '{configured}'", + config.name + ))); + } + Ok(()) +} + +fn validate_authenticated_slots( + configs: &[GatewayInterceptorConfig], + token_slots: Option<&BTreeMap>, +) -> Result<()> { + let Some(token_slots) = token_slots else { + return Ok(()); + }; + for config in configs { + // Registrations the operator opted out of extension authentication + // intentionally have no slot; everything else must fail closed. + if config.allow_insecure_transport { + continue; + } + if !token_slots.contains_key(&config.name) { + return Err(InterceptorError::Config(format!( + "authenticated interceptor '{}' is missing a bearer-token slot", + config.name + ))); + } + } + Ok(()) +} + #[derive(Debug, Clone)] struct NormalizedBinding { binding_id: String, @@ -865,63 +924,31 @@ pub fn parse_duration(value: &str) -> Result { ))) } -/// Repo-standard channel tuning (matches `openshell-core` / `openshell-sdk`): -/// bounded dial + HTTP/2 keepalive so idle interceptor channels survive -/// intermediary idle timeouts and dead peers are detected proactively. -fn tune_endpoint(endpoint: Endpoint) -> Endpoint { - endpoint - .connect_timeout(CONNECT_TIMEOUT) - .http2_keep_alive_interval(HTTP2_KEEP_ALIVE_INTERVAL) - .keep_alive_while_idle(true) - .keep_alive_timeout(KEEP_ALIVE_TIMEOUT) - .http2_adaptive_window(true) -} - -async fn connect_endpoint(endpoint: &str) -> Result { - let endpoint = endpoint.trim(); - if let Some(path) = endpoint.strip_prefix("unix://") { - return connect_unix_endpoint(PathBuf::from(path)).await; +async fn connect_endpoint(config: &GatewayInterceptorConfig) -> Result { + let endpoint = config.grpc_endpoint.trim(); + let mut channel_config = ExtensionChannelConfig::new(endpoint); + if let Some(path) = &config.tls_ca_cert_path { + let pem = tokio::fs::read(path).await.map_err(|error| { + InterceptorError::Config(format!( + "failed to read TLS CA certificate for interceptor '{}' from {}: {error}", + config.name, + path.display() + )) + })?; + channel_config = channel_config.with_server_trust(ExtensionServerTrust::CustomCaPem(pem)); } - let mut ep = Endpoint::from_shared(endpoint.to_string()).map_err(|e| { - InterceptorError::Config(format!("invalid interceptor endpoint '{endpoint}': {e}")) - })?; - if ep.uri().scheme_str() == Some("https") { - ep = ep - .tls_config(ClientTlsConfig::new().with_enabled_roots()) - .map_err(|e| { - InterceptorError::Config(format!( - "TLS config for interceptor endpoint '{endpoint}': {e}" - )) - })?; - } - tune_endpoint(ep) - .connect() - .await - .map_err(|e| InterceptorError::Transport(format!("connect {endpoint}: {e}"))) -} - -#[cfg(unix)] -async fn connect_unix_endpoint(path: PathBuf) -> Result { - let display = path.display().to_string(); - tune_endpoint(Endpoint::from_static("http://[::]:50051")) - .connect_with_connector(service_fn(move |_: Uri| { - let path = path.clone(); - async move { UnixStream::connect(path).await.map(TokioIo::new) } - })) - .await - .map_err(|e| InterceptorError::Transport(format!("connect unix://{display}: {e}"))) -} - -#[cfg(not(unix))] -async fn connect_unix_endpoint(path: PathBuf) -> Result { - Err(InterceptorError::Config(format!( - "unix interceptor endpoints are not supported on this platform: {}", - path.display() - ))) + connect_channel(&channel_config).await.map_err(|error| { + InterceptorError::Transport(format!( + "connect interceptor '{}' at {endpoint}: {error}", + config.name + )) + }) } #[cfg(test)] mod tests { + use std::path::PathBuf; + use openshell_core::config::{ GatewayInterceptorBindingOverride, GatewayInterceptorBindingPolicy, GatewayInterceptorConfig, GatewayInterceptorPhaseConfig, @@ -992,6 +1019,92 @@ mod tests { ); } + #[test] + fn authenticated_interceptors_require_a_token_slot_per_registration() { + let config = GatewayInterceptorConfig { + name: "governance".to_string(), + grpc_endpoint: "http://127.0.0.1:18081".to_string(), + ..GatewayInterceptorConfig::default() + }; + let error = + validate_authenticated_slots(std::slice::from_ref(&config), Some(&BTreeMap::new())) + .expect_err("missing token slot must fail closed"); + assert_eq!( + error.to_string(), + "invalid interceptor config: authenticated interceptor 'governance' is missing a bearer-token slot" + ); + + let slots = BTreeMap::from([(config.name.clone(), BearerTokenSlot::empty())]); + validate_authenticated_slots(&[config], Some(&slots)).unwrap(); + } + + #[test] + fn advertised_audience_mismatch_fails_at_startup() { + let config = GatewayInterceptorConfig { + name: "governance".to_string(), + grpc_endpoint: "https://governance.example".to_string(), + ..GatewayInterceptorConfig::default() + }; + + // Matching and unadvertised audiences both pass. + validate_expected_audience(&config, "", true).expect("unadvertised audience is accepted"); + validate_expected_audience( + &config, + "urn:openshell:extension:interceptor:governance", + true, + ) + .expect("matching audience is accepted"); + + // Once authenticated Describe succeeds, reject a manifest that + // contradicts the operator-owned audience configuration. + let error = validate_expected_audience(&config, "urn:example:something-else", true) + .expect_err("mismatched audience must fail closed at startup"); + let message = error.to_string(); + assert!(message.contains("urn:example:something-else")); + assert!(message.contains("urn:openshell:extension:interceptor:governance")); + + // With gateway JWT signing disabled no token is minted at all, so the + // advertised audience is not something OpenShell can be wrong about. + validate_expected_audience(&config, "urn:example:something-else", false) + .expect("unauthenticated gateways skip the handshake"); + + // The check likewise does not apply where the registration opted out. + let opted_out = GatewayInterceptorConfig { + allow_insecure_transport: true, + ..config + }; + validate_expected_audience(&opted_out, "urn:example:something-else", true) + .expect("opted-out interceptors mint no token to mismatch"); + } + + #[test] + fn opted_out_interceptors_do_not_require_a_token_slot() { + let config = GatewayInterceptorConfig { + name: "governance".to_string(), + grpc_endpoint: "http://127.0.0.1:18081".to_string(), + allow_insecure_transport: true, + ..GatewayInterceptorConfig::default() + }; + validate_authenticated_slots(&[config], Some(&BTreeMap::new())) + .expect("explicit opt-out needs no credential"); + } + + #[tokio::test] + async fn configured_ca_read_failure_names_interceptor_without_certificate_contents() { + let config = GatewayInterceptorConfig { + name: "governance".to_string(), + grpc_endpoint: "https://governance.example".to_string(), + tls_ca_cert_path: Some(PathBuf::from("/definitely/missing/openshell-ca.pem")), + ..GatewayInterceptorConfig::default() + }; + let error = connect_endpoint(&config) + .await + .expect_err("missing CA must prevent connection"); + let message = error.to_string(); + assert!(message.contains("governance")); + assert!(message.contains("/definitely/missing/openshell-ca.pem")); + } + #[test] fn interceptor_binding_policy_defaults_to_dynamic() { assert_eq!( diff --git a/crates/openshell-gateway-interceptors/src/profile_source.rs b/crates/openshell-gateway-interceptors/src/profile_source.rs index 74cd3b26c2..48014258a2 100644 --- a/crates/openshell-gateway-interceptors/src/profile_source.rs +++ b/crates/openshell-gateway-interceptors/src/profile_source.rs @@ -11,9 +11,9 @@ use openshell_core::proto::gateway_interceptor::v1::{ }; use prost::Message as _; use sha2::Digest as _; -use tonic::{Request, transport::Channel}; +use tonic::Request; -use crate::{InterceptorError, Result}; +use crate::{ExtensionChannel, InterceptorError, Result}; #[derive(Debug, Clone)] pub struct ProviderProfileSourceSnapshot { @@ -26,7 +26,7 @@ pub struct GatewayInterceptorProfileSource { interceptor_name: String, source_id: String, timeout: Duration, - client: GatewayInterceptorClient, + client: GatewayInterceptorClient, } impl GatewayInterceptorProfileSource { @@ -34,7 +34,7 @@ impl GatewayInterceptorProfileSource { interceptor_name: String, source_id: String, timeout: Duration, - client: GatewayInterceptorClient, + client: GatewayInterceptorClient, ) -> Self { Self { interceptor_name, diff --git a/crates/openshell-gateway-interceptors/src/proto_json.rs b/crates/openshell-gateway-interceptors/src/proto_json.rs index 7938644b66..f6aecbcf67 100644 --- a/crates/openshell-gateway-interceptors/src/proto_json.rs +++ b/crates/openshell-gateway-interceptors/src/proto_json.rs @@ -371,6 +371,7 @@ mod tests { ("openshell.compute.v1.DriverSandboxSpec", "sandbox_token"), ("openshell.v1.IssueSandboxTokenResponse", "token"), ("openshell.v1.RefreshSandboxTokenResponse", "token"), + ("openshell.v1.ExtensionServiceCredential", "token"), ("openshell.v1.CreateSshSessionResponse", "token"), ("openshell.v1.RevokeSshSessionRequest", "token"), ("openshell.v1.TcpForwardInit", "authorization_token"), diff --git a/crates/openshell-gateway-interceptors/src/runtime.rs b/crates/openshell-gateway-interceptors/src/runtime.rs index d510956aed..4e7f5ba613 100644 --- a/crates/openshell-gateway-interceptors/src/runtime.rs +++ b/crates/openshell-gateway-interceptors/src/runtime.rs @@ -14,6 +14,7 @@ use openshell_core::proto::gateway_interceptor::v1::{ InterceptorEvaluation, InterceptorResult, JsonPatch, ModifyOperationEvaluation, PostCommitEvaluation, ValidateEvaluation, interceptor_evaluation, }; +use openshell_extension_core::BearerTokenSlot; use prost::Message as _; use prost_types::Struct; use serde_json::{Map, Value}; @@ -77,10 +78,13 @@ impl ValidatedOperation { } impl GatewayInterceptorRuntime { - pub(crate) async fn build(configs: Vec) -> Result { + pub(crate) async fn build( + configs: Vec, + token_slots: Option>, + ) -> Result { let codec = ProtoJsonCodec::openshell()?; let routes = routes::OpenShellRouteIndex::from_descriptor_pool(codec.descriptor_pool())?; - let plan = ExecutionPlan::load(configs, routes).await?; + let plan = ExecutionPlan::load(configs, routes, token_slots).await?; Ok(Self { plan: Arc::new(plan), codec, @@ -602,6 +606,7 @@ mod tests { CreateProviderRequest, CreateSandboxRequest, Provider, SandboxSpec, SandboxTemplate, UpdateConfigRequest, }; + use openshell_extension_core::BearerTokenInterceptor; use serde_json::json; use std::collections::HashMap; use std::sync::{ @@ -724,8 +729,9 @@ mod tests { timeout: DEFAULT_TIMEOUT, max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES, max_patches: DEFAULT_MAX_PATCHES, - client: GatewayInterceptorClient::new( + client: GatewayInterceptorClient::with_interceptor( Channel::from_static("http://127.0.0.1:1").connect_lazy(), + BearerTokenInterceptor::disabled(), ), } } @@ -923,8 +929,9 @@ mod tests { timeout: DEFAULT_TIMEOUT, max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES, max_patches: DEFAULT_MAX_PATCHES, - client: GatewayInterceptorClient::new( + client: GatewayInterceptorClient::with_interceptor( Channel::from_static("http://127.0.0.1:1").connect_lazy(), + BearerTokenInterceptor::disabled(), ), }; let result = InterceptorResult { @@ -1107,8 +1114,9 @@ mod tests { timeout: DEFAULT_TIMEOUT, max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES, max_patches: DEFAULT_MAX_PATCHES, - client: GatewayInterceptorClient::new( + client: GatewayInterceptorClient::with_interceptor( Channel::from_static("http://127.0.0.1:1").connect_lazy(), + BearerTokenInterceptor::disabled(), ), }; let operation = json!({ "name": "demo" }); diff --git a/crates/openshell-sandbox/Cargo.toml b/crates/openshell-sandbox/Cargo.toml index 94cbb4ad51..70603524a8 100644 --- a/crates/openshell-sandbox/Cargo.toml +++ b/crates/openshell-sandbox/Cargo.toml @@ -16,6 +16,7 @@ path = "src/main.rs" [dependencies] openshell-core = { path = "../openshell-core", default-features = false } +openshell-extension-core = { path = "../openshell-extension-core" } openshell-ocsf = { path = "../openshell-ocsf" } openshell-policy = { path = "../openshell-policy" } openshell-supervisor-network = { path = "../openshell-supervisor-network", default-features = false } diff --git a/crates/openshell-sandbox/src/lib.rs b/crates/openshell-sandbox/src/lib.rs index 0d26067f6b..9394037c84 100644 --- a/crates/openshell-sandbox/src/lib.rs +++ b/crates/openshell-sandbox/src/lib.rs @@ -155,6 +155,11 @@ pub async fn run_sandbox( None }; + // Extension credentials are owned by this supervisor and shared by every + // gateway connection it opens, so the middleware registry's bearer slots + // and the policy poll loop that rotates them stay the same objects. + let extension_credentials = openshell_extension_core::ExtensionCredentialStore::new(); + // Load policy and initialize OPA engine let openshell_endpoint_for_proxy = openshell_endpoint.clone(); let sandbox_name_for_agg = sandbox.clone(); @@ -165,6 +170,7 @@ pub async fn run_sandbox( middleware_registry_status, loaded_policy_origin, initial_agent_proposals_enabled, + initial_extension_authentication_enabled, ) = if let Some(bootstrap) = sidecar_bootstrap.as_ref() { let (policy, opa_engine, retained_proto, loaded_policy_origin) = load_policy_from_sidecar_bootstrap(bootstrap)?; @@ -175,6 +181,7 @@ pub async fn run_sandbox( MiddlewareRegistryStatus::Synchronized, loaded_policy_origin, bootstrap.agent_proposals_enabled, + false, ) } else { load_policy( @@ -183,6 +190,7 @@ pub async fn run_sandbox( openshell_endpoint.clone(), policy_rules, policy_data, + &extension_credentials, ) .await? }; @@ -629,6 +637,8 @@ pub async fn run_sandbox( middleware_registry_status, sidecar_control_publisher: sidecar_control_publisher.clone(), workspace_tx, + extension_credentials: extension_credentials.clone(), + extension_authentication_enabled: initial_extension_authentication_enabled, middleware_connector: default_middleware_connector(), }; @@ -1883,6 +1893,7 @@ async fn load_policy( openshell_endpoint: Option, policy_rules: Option, policy_data: Option, + extension_credentials: &openshell_extension_core::ExtensionCredentialStore, ) -> Result<( SandboxPolicy, Option>, @@ -1890,6 +1901,7 @@ async fn load_policy( MiddlewareRegistryStatus, LoadedPolicyOrigin, bool, + bool, )> { // File mode: load OPA engine from rego rules + YAML data (dev override) if let (Some(policy_file), Some(data_file)) = (&policy_rules, &policy_data) { @@ -1939,6 +1951,7 @@ async fn load_policy( MiddlewareRegistryStatus::Synchronized, LoadedPolicyOrigin::LocalOverride, false, + false, )); } @@ -2101,10 +2114,32 @@ async fn load_policy( let middleware_registry_status = if middleware_services.is_empty() { MiddlewareRegistryStatus::Synchronized } else if let Err(error) = grpc_retry("Middleware connect", || { - openshell_supervisor_middleware::MiddlewareRegistry::connect_services( - openshell_supervisor_middleware_builtins::services(), - middleware_services.clone(), - ) + let middleware_services = middleware_services.clone(); + let extension_credentials = extension_credentials.clone(); + let extension_authentication_enabled = snapshot.extension_authentication_enabled; + async move { + let credentials = if extension_authentication_enabled { + // Share the supervisor's store so the slots installed here + // are the ones the policy poll loop later rotates in place. + openshell_core::grpc_client::CachedOpenShellClient::connect_with_credentials( + endpoint, + extension_credentials, + ) + .await? + .refresh_extension_credentials(&middleware_services) + .await? + } else { + std::collections::HashMap::new() + }; + connect_middleware_registry( + &middleware_services, + &MiddlewareAuthentication { + credentials, + enabled: extension_authentication_enabled, + }, + ) + .await + } }) .await .and_then(|registry| engine.replace_middleware_registry(registry)) @@ -2147,6 +2182,7 @@ async fn load_policy( has_last_valid_policy, }, agent_proposals_enabled_from_settings(&snapshot.settings), + snapshot.extension_authentication_enabled, )); } @@ -2315,14 +2351,16 @@ async fn reload_gateway_policy_runtime( policy: Option<&openshell_core::proto::SandboxPolicy>, entrypoint_pid: u32, desired_services: &[openshell_core::proto::SupervisorMiddlewareService], + middleware_authentication: &MiddlewareAuthentication, middleware_registry_changed: bool, middleware_connector: &MiddlewareConnector, ) -> std::result::Result<(), GatewayRuntimeReloadError> { match policy { Some(policy) if middleware_registry_changed => { - let registry = middleware_connector(desired_services.to_vec()) - .await - .map_err(GatewayRuntimeReloadError::MiddlewareRegistry)?; + let registry = + middleware_connector(desired_services.to_vec(), middleware_authentication.clone()) + .await + .map_err(GatewayRuntimeReloadError::MiddlewareRegistry)?; engine .reload_policy_and_middleware_from_proto_with_pid(policy, entrypoint_pid, registry) .map_err(GatewayRuntimeReloadError::PolicyValidation) @@ -2588,6 +2626,17 @@ trait PolicyGatewayClient: Clone + Send + Sync + 'static { error: &str, ) -> Result<()>; + async fn refresh_installed_extension_credentials(&self) -> Result<()> { + Ok(()) + } + + async fn extension_credentials_for( + &self, + _services: &[openshell_core::proto::SupervisorMiddlewareService], + ) -> Result> { + Ok(std::collections::HashMap::new()) + } + fn workspace(&self) -> String; } @@ -2611,6 +2660,17 @@ impl PolicyGatewayClient for openshell_core::grpc_client::CachedOpenShellClient .await } + async fn refresh_installed_extension_credentials(&self) -> Result<()> { + self.refresh_installed_extension_credentials().await + } + + async fn extension_credentials_for( + &self, + services: &[openshell_core::proto::SupervisorMiddlewareService], + ) -> Result> { + self.extension_credentials_for(services).await + } + fn workspace(&self) -> String { self.workspace() } @@ -2773,12 +2833,15 @@ struct PolicyPollLoopContext { middleware_registry_status: MiddlewareRegistryStatus, sidecar_control_publisher: Option, workspace_tx: tokio::sync::watch::Sender, + extension_credentials: openshell_extension_core::ExtensionCredentialStore, + extension_authentication_enabled: bool, middleware_connector: MiddlewareConnector, } type MiddlewareConnector = Arc< dyn Fn( Vec, + MiddlewareAuthentication, ) -> std::pin::Pin< Box< dyn std::future::Future< @@ -2789,18 +2852,36 @@ type MiddlewareConnector = Arc< + Sync, >; +#[derive(Clone, Default)] +struct MiddlewareAuthentication { + credentials: std::collections::HashMap, + enabled: bool, +} + fn default_middleware_connector() -> MiddlewareConnector { - Arc::new(|services| Box::pin(async move { connect_middleware_registry(&services).await })) + Arc::new(|services, authentication| { + Box::pin(async move { connect_middleware_registry(&services, &authentication).await }) + }) } async fn connect_middleware_registry( services: &[openshell_core::proto::SupervisorMiddlewareService], + authentication: &MiddlewareAuthentication, ) -> Result { - openshell_supervisor_middleware::MiddlewareRegistry::connect_services( - openshell_supervisor_middleware_builtins::services(), - services.to_vec(), - ) - .await + if authentication.enabled { + openshell_supervisor_middleware::MiddlewareRegistry::connect_services_authenticated( + openshell_supervisor_middleware_builtins::services(), + services.to_vec(), + &authentication.credentials, + ) + .await + } else { + openshell_supervisor_middleware::MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + services.to_vec(), + ) + .await + } } async fn install_builtin_middleware_registry(opa_engine: &OpaEngine) -> Result<()> { @@ -2812,27 +2893,76 @@ async fn install_builtin_middleware_registry(opa_engine: &OpaEngine) -> Result<( opa_engine.replace_middleware_registry(registry) } +/// Wait the configured poll interval, but never past the point at which an +/// installed extension credential must be rotated. +fn next_poll_delay( + store: &openshell_extension_core::ExtensionCredentialStore, + interval: Duration, +) -> Duration { + let now_ms = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |elapsed| { + i64::try_from(elapsed.as_millis()).unwrap_or(i64::MAX) + }); + store.next_refresh_delay(interval, now_ms) +} + +/// Drop credentials for services no longer in the installed registry. +/// +/// Call only after a registry swap succeeds, so a failed candidate cannot +/// invalidate the last-known-good clients. +fn retain_extension_credentials( + store: &openshell_extension_core::ExtensionCredentialStore, + installed: &[openshell_core::proto::SupervisorMiddlewareService], + extension_authentication_enabled: bool, +) { + let retained = if extension_authentication_enabled { + installed + .iter() + .map(|service| service.name.as_str()) + .collect() + } else { + std::collections::HashSet::default() + }; + store.retain(&retained); +} + +struct MiddlewareRegistryReconciliation<'a> { + desired_services: &'a [openshell_core::proto::SupervisorMiddlewareService], + authentication: MiddlewareAuthentication, + registry_changed: bool, + extension_credentials: &'a openshell_extension_core::ExtensionCredentialStore, + current_services: &'a mut Vec, + status: &'a mut MiddlewareRegistryStatus, +} + async fn reconcile_middleware_registry( opa_engine: &OpaEngine, middleware_connector: &MiddlewareConnector, - desired_services: &[openshell_core::proto::SupervisorMiddlewareService], - current_services: &mut Vec, - status: &mut MiddlewareRegistryStatus, + reconciliation: MiddlewareRegistryReconciliation<'_>, ) { - if *status == MiddlewareRegistryStatus::Synchronized - && desired_services == current_services.as_slice() - { + if !reconciliation.registry_changed { return; } - match middleware_connector(desired_services.to_vec()) - .await - .and_then(|registry| opa_engine.replace_middleware_registry(registry)) + match middleware_connector( + reconciliation.desired_services.to_vec(), + reconciliation.authentication.clone(), + ) + .await + .and_then(|registry| opa_engine.replace_middleware_registry(registry)) { Ok(()) => { - current_services.clear(); - current_services.extend_from_slice(desired_services); - *status = MiddlewareRegistryStatus::Synchronized; + retain_extension_credentials( + reconciliation.extension_credentials, + reconciliation.desired_services, + reconciliation.authentication.enabled, + ); + reconciliation.current_services.clear(); + reconciliation + .current_services + .extend_from_slice(reconciliation.desired_services); + *reconciliation.status = MiddlewareRegistryStatus::Synchronized; ocsf_emit!( ConfigStateChangeBuilder::new(ocsf_ctx()) .severity(SeverityId::Informational) @@ -2840,11 +2970,11 @@ async fn reconcile_middleware_registry( .state(StateId::Enabled, "loaded") .unmapped( "supervisor_middleware_service_count", - serde_json::json!(current_services.len()) + serde_json::json!(reconciliation.current_services.len()) ) .message(format!( "Supervisor middleware registry reloaded [service_count:{}]", - current_services.len() + reconciliation.current_services.len() )) .build() ); @@ -2852,7 +2982,7 @@ async fn reconcile_middleware_registry( Err(error) => { // Emit only on the transition into the failed state to avoid // repeating the same finding on every poll during an outage. - if *status == MiddlewareRegistryStatus::Synchronized { + if *reconciliation.status == MiddlewareRegistryStatus::Synchronized { ocsf_emit!( ConfigStateChangeBuilder::new(ocsf_ctx()) .severity(SeverityId::Medium) @@ -2864,7 +2994,7 @@ async fn reconcile_middleware_registry( .build() ); } - *status = MiddlewareRegistryStatus::NeedsReconciliation; + *reconciliation.status = MiddlewareRegistryStatus::NeedsReconciliation; } } } @@ -3051,7 +3181,11 @@ fn emit_policy_validation_failure( } async fn run_policy_poll_loop(ctx: PolicyPollLoopContext) -> Result<()> { - let client = openshell_core::grpc_client::CachedOpenShellClient::connect(&ctx.endpoint).await?; + let client = openshell_core::grpc_client::CachedOpenShellClient::connect_with_credentials( + &ctx.endpoint, + ctx.extension_credentials.clone(), + ) + .await?; run_policy_poll_loop_with_client(ctx, client).await } @@ -3074,6 +3208,7 @@ async fn run_policy_poll_loop_with_client( let mut current_policy_version: u32 = 0; let mut current_policy_hash = String::new(); let mut current_middleware_services = Vec::new(); + let mut current_extension_authentication_enabled = ctx.extension_authentication_enabled; let mut middleware_registry_status = ctx.middleware_registry_status; let mut current_settings: std::collections::HashMap< String, @@ -3110,6 +3245,8 @@ async fn run_policy_poll_loop_with_client( current_policy_version = candidate.version; current_policy_hash.clone_from(&candidate.policy_hash); current_middleware_services = result.supervisor_middleware_services; + current_extension_authentication_enabled = + result.extension_authentication_enabled; current_settings = result.settings; enqueue_policy_status( &status_sender, @@ -3134,6 +3271,8 @@ async fn run_policy_poll_loop_with_client( current_config_revision = result.config_revision; current_policy_hash = result.policy_hash.clone(); current_middleware_services = result.supervisor_middleware_services; + current_extension_authentication_enabled = + result.extension_authentication_enabled; current_settings = result.settings; debug!( config_revision = current_config_revision, @@ -3152,7 +3291,7 @@ async fn run_policy_poll_loop_with_client( let result = if let Some(result) = pending_result.take() { result } else { - tokio::time::sleep(interval).await; + tokio::time::sleep(next_poll_delay(&ctx.extension_credentials, interval)).await; match client.poll_settings(&ctx.sandbox_id).await { Ok(result) => { let _ = ctx.workspace_tx.send(client.workspace()); @@ -3160,19 +3299,50 @@ async fn run_policy_poll_loop_with_client( } Err(e) => { debug!(error = %e, "Settings poll: server unreachable, will retry"); + if current_extension_authentication_enabled + && let Err(refresh_error) = + client.refresh_installed_extension_credentials().await + { + warn!( + error = %refresh_error, + "Settings poll: extension credential refresh failed while configuration was unavailable" + ); + } continue; } } }; + // Reuse installed per-service credentials, rotating only when one is + // missing or due. Rotation happens on the existing gateway channel and + // updates slots in place, so it is independent of config revision and + // registry equality. + let middleware_credentials = if result.extension_authentication_enabled { + match client + .extension_credentials_for(&result.supervisor_middleware_services) + .await + { + Ok(credentials) => credentials, + Err(error) => { + warn!(error = %error, "Settings poll: extension credential refresh failed"); + std::collections::HashMap::new() + } + } + } else { + std::collections::HashMap::new() + }; + let config_changed = result.config_revision != current_config_revision; let provider_env_changed = result.provider_env_revision != current_provider_env_revision; let policy_changed = result.policy_hash != current_policy_hash; - let middleware_registry_changed = middleware_registry_needs_rebuild( - middleware_registry_status, - ¤t_middleware_services, - &result.supervisor_middleware_services, - ); + let extension_authentication_changed = + current_extension_authentication_enabled != result.extension_authentication_enabled; + let middleware_registry_changed = extension_authentication_changed + || middleware_registry_needs_rebuild( + middleware_registry_status, + ¤t_middleware_services, + &result.supervisor_middleware_services, + ); // A valid candidate may intentionally restore byte-for-byte policy // content that was active before a rejected update. Its hash then // equals `current_policy_hash`, but the runtime is still quarantined @@ -3182,6 +3352,7 @@ async fn run_policy_poll_loop_with_client( .as_ref() .is_some_and(|rejected| rejected.policy_hash != result.policy_hash); let policy_runtime_changed = recovering_rejected_policy + || extension_authentication_changed || gateway_policy_runtime_needs_reconciliation( reloads_gateway_policy, ¤t_policy_hash, @@ -3210,11 +3381,22 @@ async fn run_policy_poll_loop_with_client( reconcile_middleware_registry( &ctx.opa_engine, &ctx.middleware_connector, - &result.supervisor_middleware_services, - &mut current_middleware_services, - &mut middleware_registry_status, + MiddlewareRegistryReconciliation { + desired_services: &result.supervisor_middleware_services, + authentication: MiddlewareAuthentication { + credentials: middleware_credentials.clone(), + enabled: result.extension_authentication_enabled, + }, + registry_changed: middleware_registry_changed, + extension_credentials: &ctx.extension_credentials, + current_services: &mut current_middleware_services, + status: &mut middleware_registry_status, + }, ) .await; + if middleware_registry_status == MiddlewareRegistryStatus::Synchronized { + current_extension_authentication_enabled = result.extension_authentication_enabled; + } } if !config_changed @@ -3349,6 +3531,10 @@ async fn run_policy_poll_loop_with_client( result.policy.as_ref(), pid, &result.supervisor_middleware_services, + &MiddlewareAuthentication { + credentials: middleware_credentials.clone(), + enabled: result.extension_authentication_enabled, + }, middleware_registry_changed, &ctx.middleware_connector, ) @@ -3449,6 +3635,13 @@ async fn run_policy_poll_loop_with_client( current_policy_hash.clone_from(&result.policy_hash); current_middleware_services.clone_from(&result.supervisor_middleware_services); + current_extension_authentication_enabled = + result.extension_authentication_enabled; + retain_extension_credentials( + &ctx.extension_credentials, + &result.supervisor_middleware_services, + result.extension_authentication_enabled, + ); middleware_registry_status = MiddlewareRegistryStatus::Synchronized; last_failed_runtime_revision = None; } @@ -4058,6 +4251,7 @@ filesystem_policy: supervisor_middleware_services: Vec::new(), workspace: String::new(), policy_validation_failure_mode: PolicyValidationFailureMode::default(), + extension_authentication_enabled: false, } } @@ -4104,6 +4298,49 @@ filesystem_policy: } } + #[derive(Clone)] + struct CredentialRejectingPolicyGateway { + inner: ScriptedPolicyGateway, + credential_requests: Arc, + } + + #[tonic::async_trait] + impl PolicyGatewayClient for CredentialRejectingPolicyGateway { + async fn poll_settings( + &self, + sandbox_id: &str, + ) -> Result { + self.inner.poll_settings(sandbox_id).await + } + + async fn report_policy_status( + &self, + sandbox_id: &str, + version: u32, + loaded: bool, + error: &str, + ) -> Result<()> { + self.inner + .report_policy_status(sandbox_id, version, loaded, error) + .await + } + + async fn extension_credentials_for( + &self, + _services: &[openshell_core::proto::SupervisorMiddlewareService], + ) -> Result> + { + self.credential_requests.fetch_add(1, Ordering::SeqCst); + Err(miette::miette!( + "gateway extension authentication is unavailable" + )) + } + + fn workspace(&self) -> String { + self.inner.workspace() + } + } + fn scripted_policy_gateway() -> ( ScriptedPolicyGateway, UnboundedSender, @@ -4144,6 +4381,8 @@ filesystem_policy: middleware_registry_status: MiddlewareRegistryStatus::Synchronized, sidecar_control_publisher: None, workspace_tx, + extension_credentials: openshell_extension_core::ExtensionCredentialStore::new(), + extension_authentication_enabled: false, middleware_connector, } } @@ -4234,14 +4473,14 @@ filesystem_policy: let (attempt_tx, mut attempt_rx) = tokio::sync::mpsc::unbounded_channel(); let middleware_connector: MiddlewareConnector = { let connector_attempts = connector_attempts.clone(); - Arc::new(move |_services| { + Arc::new(move |_services, _authentication| { let attempt = connector_attempts.fetch_add(1, Ordering::SeqCst) + 1; attempt_tx.send(attempt).unwrap(); Box::pin(async move { if attempt == 1 { Err(miette::miette!("scripted middleware connection failure")) } else { - connect_middleware_registry(&[]).await + connect_middleware_registry(&[], &MiddlewareAuthentication::default()).await } }) }) @@ -4290,6 +4529,134 @@ filesystem_policy: handle.abort(); } + #[tokio::test] + async fn no_signer_capability_uses_legacy_middleware_connector_without_credentials() { + let mut v1 = settings_poll_result( + Some(proto_policy_fixture()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ); + v1.policy_hash = "same-policy".to_string(); + let mut v2 = v1.clone(); + v2.version = 2; + v2.config_revision = 200; + v2.supervisor_middleware_services = + vec![openshell_core::proto::SupervisorMiddlewareService { + name: "legacy-guard".to_string(), + grpc_endpoint: "http://legacy.invalid".to_string(), + ..Default::default() + }]; + assert!(!v2.extension_authentication_enabled); + + let (inner, polls, mut reports) = scripted_policy_gateway(); + let credential_requests = Arc::new(AtomicUsize::new(0)); + let client = CredentialRejectingPolicyGateway { + inner, + credential_requests: credential_requests.clone(), + }; + let (connector_tx, mut connector_rx) = tokio::sync::mpsc::unbounded_channel(); + let connector: MiddlewareConnector = Arc::new(move |_services, authentication| { + connector_tx + .send((authentication.credentials.len(), authentication.enabled)) + .unwrap(); + Box::pin(async move { + connect_middleware_registry(&[], &MiddlewareAuthentication::default()).await + }) + }); + let engine = + Arc::new(OpaEngine::from_proto(&proto_policy_fixture()).expect("build OPA engine")); + let loaded_revision = LoadedPolicyRevision::from_snapshot(&v1); + let ctx = policy_poll_test_context( + engine, + LoadedPolicyOrigin::Gateway { + revision: Some(loaded_revision), + has_last_valid_policy: true, + }, + connector, + ); + + polls.send(v1).unwrap(); + let handle = tokio::spawn(run_policy_poll_loop_with_client(ctx, client)); + expect_policy_report(&mut reports, 1).await; + polls.send(v2).unwrap(); + assert_eq!( + timeout(Duration::from_secs(1), connector_rx.recv()) + .await + .unwrap(), + Some((0, false)) + ); + expect_policy_report(&mut reports, 2).await; + assert_eq!(credential_requests.load(Ordering::SeqCst), 0); + handle.abort(); + } + + #[tokio::test] + async fn enabled_extension_authentication_keeps_credential_failure_fail_closed() { + let mut v1 = settings_poll_result( + Some(proto_policy_fixture()), + 1, + openshell_core::proto::PolicySource::Sandbox, + ); + v1.policy_hash = "same-policy".to_string(); + let mut v2 = v1.clone(); + v2.version = 2; + v2.config_revision = 200; + v2.extension_authentication_enabled = true; + v2.supervisor_middleware_services = + vec![openshell_core::proto::SupervisorMiddlewareService { + name: "authenticated-guard".to_string(), + grpc_endpoint: "https://guard.invalid".to_string(), + ..Default::default() + }]; + + let (inner, polls, mut reports) = scripted_policy_gateway(); + let credential_requests = Arc::new(AtomicUsize::new(0)); + let client = CredentialRejectingPolicyGateway { + inner, + credential_requests: credential_requests.clone(), + }; + let (connector_tx, mut connector_rx) = tokio::sync::mpsc::unbounded_channel(); + let connector: MiddlewareConnector = Arc::new(move |_services, authentication| { + connector_tx + .send((authentication.credentials.len(), authentication.enabled)) + .unwrap(); + Box::pin(async move { + if authentication.enabled && authentication.credentials.is_empty() { + Err(miette::miette!( + "missing authenticated middleware credential" + )) + } else { + connect_middleware_registry(&[], &authentication).await + } + }) + }); + let engine = + Arc::new(OpaEngine::from_proto(&proto_policy_fixture()).expect("build OPA engine")); + let loaded_revision = LoadedPolicyRevision::from_snapshot(&v1); + let ctx = policy_poll_test_context( + engine, + LoadedPolicyOrigin::Gateway { + revision: Some(loaded_revision), + has_last_valid_policy: true, + }, + connector, + ); + + polls.send(v1).unwrap(); + let handle = tokio::spawn(run_policy_poll_loop_with_client(ctx, client)); + expect_policy_report(&mut reports, 1).await; + polls.send(v2).unwrap(); + assert_eq!( + timeout(Duration::from_secs(1), connector_rx.recv()) + .await + .unwrap(), + Some((0, true)) + ); + expect_no_policy_report(&mut reports).await; + assert_eq!(credential_requests.load(Ordering::SeqCst), 1); + handle.abort(); + } + async fn assert_poll_does_not_use_same_hash_acknowledgement( initial: openshell_core::grpc_client::SettingsPollResult, next: openshell_core::grpc_client::SettingsPollResult, @@ -4443,10 +4810,10 @@ filesystem_policy: let invalid_external = openshell_core::proto::SupervisorMiddlewareService { name: "unavailable-guard".into(), grpc_endpoint: "http://127.0.0.1:1".into(), - max_body_bytes: 1024, + max_payload_bytes: 1024, ..Default::default() }; - connect_middleware_registry(&[invalid_external]) + connect_middleware_registry(&[invalid_external], &MiddlewareAuthentication::default()) .await .expect_err("unavailable external service must not replace built-ins"); @@ -4463,7 +4830,7 @@ filesystem_policy: let unavailable_service = openshell_core::proto::SupervisorMiddlewareService { name: "unavailable-guard".into(), grpc_endpoint: "http://127.0.0.1:1".into(), - max_body_bytes: 1024, + max_payload_bytes: 1024, ..Default::default() }; @@ -4472,6 +4839,7 @@ filesystem_policy: Some(&proto_policy_fixture()), 0, &[unavailable_service], + &MiddlewareAuthentication::default(), true, &default_middleware_connector(), ) diff --git a/crates/openshell-server/Cargo.toml b/crates/openshell-server/Cargo.toml index 6329bad823..772590d1b0 100644 --- a/crates/openshell-server/Cargo.toml +++ b/crates/openshell-server/Cargo.toml @@ -20,6 +20,7 @@ openshell-core = { path = "../openshell-core", default-features = false } openshell-driver-db-credstore = { path = "../openshell-driver-db-credstore" } openshell-driver-kubernetes-secrets = { path = "../openshell-driver-kubernetes-secrets" } openshell-driver-vault = { path = "../openshell-driver-vault" } +openshell-extension-core = { path = "../openshell-extension-core" } openshell-gateway-interceptors = { path = "../openshell-gateway-interceptors" } openshell-ocsf = { path = "../openshell-ocsf" } openshell-otel = { path = "../openshell-otel" } diff --git a/crates/openshell-server/src/auth/extension_mint_limit.rs b/crates/openshell-server/src/auth/extension_mint_limit.rs new file mode 100644 index 0000000000..0495cf0347 --- /dev/null +++ b/crates/openshell-server/src/auth/extension_mint_limit.rs @@ -0,0 +1,156 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Per-sandbox bound on extension credential minting. +//! +//! Minting resolves the sandbox's effective policy to decide which extension +//! registrations the caller may hold credentials for. That resolution reads +//! policy history, settings, and the provider profile catalog, so an +//! unbounded caller inside a sandbox could impose real gateway cost by +//! requesting credentials in a loop. +//! +//! A well-behaved supervisor rotates at roughly 80% of the credential +//! lifetime — about once every twelve minutes for the fifteen-minute default — +//! plus a small burst at startup and on retry. The default bound leaves ample +//! headroom for that while capping what a compromised sandbox can drive. + +use std::collections::HashMap; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +const DEFAULT_WINDOW: Duration = Duration::from_secs(60); +const DEFAULT_MAX_PER_WINDOW: u32 = 10; + +/// Number of tracked sandboxes above which expired windows are pruned. +const PRUNE_THRESHOLD: usize = 1_024; + +struct Window { + started: Instant, + count: u32, +} + +pub struct ExtensionMintLimiter { + window: Duration, + max_per_window: u32, + windows: Mutex>, +} + +impl Default for ExtensionMintLimiter { + fn default() -> Self { + Self::new(DEFAULT_WINDOW, DEFAULT_MAX_PER_WINDOW) + } +} + +impl std::fmt::Debug for ExtensionMintLimiter { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("ExtensionMintLimiter") + .field("window", &self.window) + .field("max_per_window", &self.max_per_window) + .finish_non_exhaustive() + } +} + +impl ExtensionMintLimiter { + #[must_use] + pub fn new(window: Duration, max_per_window: u32) -> Self { + Self { + window, + max_per_window, + windows: Mutex::new(HashMap::new()), + } + } + + /// Record one minting request, returning `false` when the sandbox has + /// exhausted its window. + pub fn try_acquire(&self, sandbox_id: &str) -> bool { + self.try_acquire_at(sandbox_id, Instant::now()) + } + + fn try_acquire_at(&self, sandbox_id: &str, now: Instant) -> bool { + if self.max_per_window == 0 { + return true; + } + let mut windows = self + .windows + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + + if windows.len() >= PRUNE_THRESHOLD { + windows.retain(|_, window| now.duration_since(window.started) < self.window); + } + + let window = windows.entry(sandbox_id.to_string()).or_insert(Window { + started: now, + count: 0, + }); + if now.duration_since(window.started) >= self.window { + window.started = now; + window.count = 0; + } + if window.count >= self.max_per_window { + return false; + } + window.count += 1; + true + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn allows_a_burst_then_refuses_within_the_window() { + let limiter = ExtensionMintLimiter::new(Duration::from_secs(60), 3); + let start = Instant::now(); + + for _ in 0..3 { + assert!(limiter.try_acquire_at("sandbox-a", start)); + } + assert!(!limiter.try_acquire_at("sandbox-a", start)); + } + + #[test] + fn window_rollover_restores_capacity() { + let limiter = ExtensionMintLimiter::new(Duration::from_secs(60), 1); + let start = Instant::now(); + + assert!(limiter.try_acquire_at("sandbox-a", start)); + assert!(!limiter.try_acquire_at("sandbox-a", start + Duration::from_secs(59))); + assert!(limiter.try_acquire_at("sandbox-a", start + Duration::from_secs(60))); + } + + #[test] + fn sandboxes_are_limited_independently() { + let limiter = ExtensionMintLimiter::new(Duration::from_secs(60), 1); + let start = Instant::now(); + + assert!(limiter.try_acquire_at("sandbox-a", start)); + assert!(!limiter.try_acquire_at("sandbox-a", start)); + // One noisy sandbox must not deny credentials to any other. + assert!(limiter.try_acquire_at("sandbox-b", start)); + } + + #[test] + fn legitimate_rotation_cadence_stays_well_inside_the_default_bound() { + let limiter = ExtensionMintLimiter::default(); + let start = Instant::now(); + + // Startup acquires once, then the poll loop rotates at ~80% of a + // 15-minute credential. Even compressed into a single window that is + // far below the bound. + for minute in 0..12 { + assert!(limiter.try_acquire_at("sandbox-a", start + Duration::from_secs(minute * 60))); + } + } + + #[test] + fn a_zero_bound_disables_limiting() { + let limiter = ExtensionMintLimiter::new(Duration::from_secs(60), 0); + let start = Instant::now(); + for _ in 0..1_000 { + assert!(limiter.try_acquire_at("sandbox-a", start)); + } + } +} diff --git a/crates/openshell-server/src/auth/http.rs b/crates/openshell-server/src/auth/http.rs index f0e7011658..df95f35fd7 100644 --- a/crates/openshell-server/src/auth/http.rs +++ b/crates/openshell-server/src/auth/http.rs @@ -18,7 +18,7 @@ use axum::{ Json, Router, extract::{Query, State}, - http::{HeaderMap, StatusCode}, + http::{HeaderMap, StatusCode, Uri}, response::{Html, IntoResponse}, routing::get, }; @@ -59,9 +59,104 @@ pub fn router(state: Arc) -> Router { Router::new() .route("/auth/connect", get(auth_connect)) .route("/auth/oidc-config", get(oidc_config_handler)) + .route("/.well-known/jwks.json", get(gateway_jwks_handler)) + .route( + "/.well-known/openid-configuration", + get(gateway_discovery_handler), + ) .with_state(state) } +/// Publish OIDC-shaped discovery metadata for extension services. +/// +/// This lets an extension be configured with only the trusted gateway URL: +/// it learns the exact expected `iss` and the `jwks_uri` from one document +/// instead of having both provisioned separately. +/// +/// Like the equivalent Kubernetes endpoint, this is OIDC-shaped rather than +/// OIDC-compliant: `issuer` is the gateway identity (`openshell-gateway:`), +/// not the URL this document is served from. Verifiers must compare `iss` +/// against that value, and must not infer trust from the document's location +/// alone. The serving TLS connection is what authenticates the gateway. +async fn gateway_discovery_handler( + State(state): State>, + headers: HeaderMap, + uri: Uri, +) -> impl IntoResponse { + gateway_discovery_response( + state.sandbox_jwt_authenticator.as_deref(), + &document_base_url(&headers, &uri), + ) +} + +/// Reconstruct the externally visible base URL for absolute discovery links. +/// +/// HTTP/1.1 carries `Host`; HTTP/2 carries `:authority`, which axum surfaces +/// on the request URI. A terminating proxy may report the original scheme in +/// `X-Forwarded-Proto`; otherwise assume TLS, since the extension contract +/// requires fetching this document over an authenticated connection. +fn document_base_url(headers: &HeaderMap, uri: &Uri) -> Option { + let authority = headers + .get(header::HOST) + .and_then(|value| value.to_str().ok()) + .filter(|host| !host.is_empty()) + .map(ToString::to_string) + .or_else(|| uri.authority().map(ToString::to_string))?; + let scheme = headers + .get("x-forwarded-proto") + .and_then(|value| value.to_str().ok()) + .and_then(|proto| proto.split(',').next()) + .map(str::trim) + .filter(|proto| !proto.is_empty()) + .unwrap_or("https"); + Some(format!("{scheme}://{authority}")) +} + +fn gateway_discovery_response( + authenticator: Option<&crate::auth::sandbox_jwt::SandboxJwtAuthenticator>, + base_url: &Option, +) -> axum::response::Response { + let Some(authenticator) = authenticator else { + return StatusCode::NOT_FOUND.into_response(); + }; + let Some(base_url) = base_url else { + // Without a usable authority the `jwks_uri` cannot be absolute, and a + // relative value would be worse than none: a verifier could resolve it + // against the wrong origin. + return StatusCode::BAD_REQUEST.into_response(); + }; + Json(serde_json::json!({ + "issuer": authenticator.issuer(), + "jwks_uri": format!("{base_url}/.well-known/jwks.json"), + "id_token_signing_alg_values_supported": ["EdDSA"], + "response_types_supported": ["id_token"], + "subject_types_supported": ["public"], + "scopes_supported": ["openid"], + "claims_supported": [ + "iss", "aud", "sub", "iat", "exp", "jti", "caller_kind", "sandbox_id" + ], + })) + .into_response() +} + +/// Publish the gateway's JWT verification key for extension services. +/// +/// Public keys are not secret. The HTTPS connection authenticates the +/// gateway from which an integration bootstraps this document; integrations +/// then cache keys by `kid` and refresh when an unfamiliar `kid` appears. +async fn gateway_jwks_handler(State(state): State>) -> impl IntoResponse { + gateway_jwks_response(state.sandbox_jwt_authenticator.as_deref()) +} + +fn gateway_jwks_response( + authenticator: Option<&crate::auth::sandbox_jwt::SandboxJwtAuthenticator>, +) -> axum::response::Response { + authenticator.map_or_else( + || StatusCode::NOT_FOUND.into_response(), + |authenticator| Json(authenticator.jwks()).into_response(), + ) +} + /// OIDC configuration discovery endpoint. /// /// Returns the OIDC issuer and audience when OIDC is configured on the server, @@ -474,6 +569,8 @@ fn render_waiting_page(callback_port: u16, code: &str) -> String { #[cfg(test)] mod tests { use super::*; + use axum::body::to_bytes; + use openshell_bootstrap::jwt::generate_jwt_key; #[test] fn extract_cookie_finds_value() { @@ -586,4 +683,109 @@ mod tests { assert_eq!(html_escape("a\"b"), "a"b"); assert_eq!(html_escape("a'b"), "a'b"); } + + #[test] + fn jwks_response_publishes_configured_gateway_key() { + let material = generate_jwt_key().expect("key"); + let authenticator = crate::auth::sandbox_jwt::SandboxJwtAuthenticator::from_pem( + material.public_key_pem.as_bytes(), + material.kid.clone(), + "gateway-a", + ) + .expect("authenticator"); + + let response = gateway_jwks_response(Some(&authenticator)); + assert_eq!(response.status(), StatusCode::OK); + let key = &authenticator.jwks().keys[0]; + assert_eq!(key.kid, material.kid); + assert_eq!(key.kty, "OKP"); + assert_eq!(key.crv, "Ed25519"); + assert_eq!(key.alg, "EdDSA"); + assert_eq!(key.key_use, "sig"); + } + + #[test] + fn jwks_response_is_not_found_without_gateway_key() { + assert_eq!(gateway_jwks_response(None).status(), StatusCode::NOT_FOUND); + } + + fn test_authenticator() -> crate::auth::sandbox_jwt::SandboxJwtAuthenticator { + let material = generate_jwt_key().expect("key"); + crate::auth::sandbox_jwt::SandboxJwtAuthenticator::from_pem( + material.public_key_pem.as_bytes(), + material.kid, + "gateway-a", + ) + .expect("authenticator") + } + + #[tokio::test] + async fn discovery_document_advertises_issuer_identity_and_absolute_jwks_uri() { + let authenticator = test_authenticator(); + let response = gateway_discovery_response( + Some(&authenticator), + &Some("https://gateway.example:8443".to_string()), + ); + assert_eq!(response.status(), StatusCode::OK); + + let body = to_bytes(response.into_body(), 64 * 1024) + .await + .expect("body"); + let document: serde_json::Value = serde_json::from_slice(&body).expect("json"); + + // The issuer is the gateway identity, not the serving URL. Extensions + // compare `iss` against this exact value. + assert_eq!(document["issuer"], "openshell-gateway:gateway-a"); + assert_eq!( + document["jwks_uri"], + "https://gateway.example:8443/.well-known/jwks.json" + ); + assert_eq!( + document["id_token_signing_alg_values_supported"][0], + "EdDSA" + ); + } + + #[test] + fn discovery_document_requires_a_key_and_a_resolvable_authority() { + assert_eq!( + gateway_discovery_response(None, &Some("https://gateway.example".to_string())).status(), + StatusCode::NOT_FOUND + ); + // A relative jwks_uri could be resolved against the wrong origin, so + // refuse to emit a document rather than emit an ambiguous one. + assert_eq!( + gateway_discovery_response(Some(&test_authenticator()), &None).status(), + StatusCode::BAD_REQUEST + ); + } + + #[test] + fn base_url_prefers_host_header_and_honours_forwarded_scheme() { + let mut headers = HeaderMap::new(); + headers.insert(header::HOST, "gateway.example:8443".parse().unwrap()); + assert_eq!( + document_base_url(&headers, &Uri::from_static("/")), + Some("https://gateway.example:8443".to_string()) + ); + + headers.insert("x-forwarded-proto", "http, https".parse().unwrap()); + assert_eq!( + document_base_url(&headers, &Uri::from_static("/")), + Some("http://gateway.example:8443".to_string()) + ); + + // HTTP/2 has no Host header; axum surfaces `:authority` on the URI. + assert_eq!( + document_base_url( + &HeaderMap::new(), + &Uri::from_static("https://h2.example/.well-known/openid-configuration") + ), + Some("https://h2.example".to_string()) + ); + assert_eq!( + document_base_url(&HeaderMap::new(), &Uri::from_static("/")), + None + ); + } } diff --git a/crates/openshell-server/src/auth/k8s_sa.rs b/crates/openshell-server/src/auth/k8s_sa.rs index eed0e5f083..32cb2e119c 100644 --- a/crates/openshell-server/src/auth/k8s_sa.rs +++ b/crates/openshell-server/src/auth/k8s_sa.rs @@ -26,6 +26,7 @@ use k8s_openapi::apimachinery::pkg::apis::meta::v1::ObjectMeta; use kube::Error as KubeError; use kube::api::{Api, ApiResource, PostParams}; use kube::core::{DynamicObject, gvk::GroupVersionKind}; +use openshell_driver_kubernetes::OperatorNamespaceAllowlist; use std::sync::Arc; use tonic::Status; use tracing::{debug, info, warn}; @@ -135,8 +136,32 @@ impl Authenticator for K8sServiceAccountAuthenticator { } } +/// Validates the namespace extracted from an SA token username against the +/// expected set for the active workspace mode. +#[derive(Debug, Clone)] +pub enum NamespaceValidator { + /// Shared mode: accept only the single configured namespace. + Exact(String), + /// Managed mode: accept any namespace with the managed prefix + /// (`openshell-{gateway_id}-`). + Prefix(String), + /// Operator mode: accept namespaces in the dynamic allowlist. + Allowlist(OperatorNamespaceAllowlist), +} + +impl NamespaceValidator { + pub fn accepts(&self, namespace: &str) -> bool { + match self { + Self::Exact(expected) => namespace == expected, + Self::Prefix(prefix) => namespace.starts_with(prefix.as_str()), + Self::Allowlist(al) => al.contains(namespace), + } + } +} + #[derive(Debug)] struct TokenReviewIdentity { + namespace: String, pod_name: String, pod_uid: String, } @@ -151,59 +176,53 @@ struct SandboxOwnerReference { /// Resolver backed by the apiserver's `TokenReview` API and `kube::Client` /// for the per-pod annotation lookup. pub struct LiveK8sResolver { + client: kube::Client, token_reviews_api: Api, - pods_api: Api, - sandboxes_api_v1beta1: Api, - sandboxes_api_v1alpha1: Api, expected_audience: String, - sandbox_namespace: String, + namespace_validator: NamespaceValidator, expected_service_account: String, } impl LiveK8sResolver { pub fn new( client: kube::Client, - namespace: &str, + namespace_validator: NamespaceValidator, expected_audience: String, expected_service_account: String, ) -> Self { let token_reviews_api: Api = Api::all(client.clone()); - let pods_api: Api = Api::namespaced(client.clone(), namespace); - let sandbox_gvk_v1beta1 = - GroupVersionKind::gvk(SANDBOX_API_GROUP, SANDBOX_API_VERSION_V1BETA1, SANDBOX_KIND); - let sandbox_resource_v1beta1 = ApiResource::from_gvk(&sandbox_gvk_v1beta1); - let sandbox_gvk_v1alpha1 = GroupVersionKind::gvk( - SANDBOX_API_GROUP, - SANDBOX_API_VERSION_V1ALPHA1, - SANDBOX_KIND, - ); - let sandbox_resource_v1alpha1 = ApiResource::from_gvk(&sandbox_gvk_v1alpha1); - let sandboxes_api_v1beta1: Api = - Api::namespaced_with(client.clone(), namespace, &sandbox_resource_v1beta1); - let sandboxes_api_v1alpha1: Api = - Api::namespaced_with(client, namespace, &sandbox_resource_v1alpha1); Self { + client, token_reviews_api, - pods_api, - sandboxes_api_v1beta1, - sandboxes_api_v1alpha1, expected_audience, - sandbox_namespace: namespace.to_string(), + namespace_validator, expected_service_account, } } + fn pods_api(&self, namespace: &str) -> Api { + Api::namespaced(self.client.clone(), namespace) + } + + fn sandboxes_api(&self, namespace: &str, api_version: &str) -> Api { + let gvk = GroupVersionKind::gvk(SANDBOX_API_GROUP, api_version, SANDBOX_KIND); + let resource = ApiResource::from_gvk(&gvk); + Api::namespaced_with(self.client.clone(), namespace, &resource) + } + async fn get_sandbox_cr_for_owner( &self, + namespace: &str, owner: &SandboxOwnerReference, ) -> Result, KubeError> { - let apis = if owner.api_version == SANDBOX_API_VERSION_FULL_V1ALPHA1 { - [&self.sandboxes_api_v1alpha1, &self.sandboxes_api_v1beta1] + let versions = if owner.api_version == SANDBOX_API_VERSION_FULL_V1ALPHA1 { + [SANDBOX_API_VERSION_V1ALPHA1, SANDBOX_API_VERSION_V1BETA1] } else { - [&self.sandboxes_api_v1beta1, &self.sandboxes_api_v1alpha1] + [SANDBOX_API_VERSION_V1BETA1, SANDBOX_API_VERSION_V1ALPHA1] }; - for api in apis { + for version in versions { + let api = self.sandboxes_api(namespace, version); match api.get_opt(&owner.name).await { Ok(Some(sandbox_cr)) => return Ok(Some(sandbox_cr)), Ok(None) => {} @@ -242,7 +261,7 @@ impl K8sIdentityResolver for LiveK8sResolver { let Some(identity) = token_review_identity( &status, &self.expected_audience, - &self.sandbox_namespace, + &self.namespace_validator, &self.expected_service_account, )? else { @@ -252,34 +271,30 @@ impl K8sIdentityResolver for LiveK8sResolver { info!( pod_name = %identity.pod_name, pod_uid = %identity.pod_uid, + namespace = %identity.namespace, service_account = %self.expected_service_account, "validated K8s SA token via TokenReview" ); - // Look up the pod and read its sandbox-id annotation. - let pod = self - .pods_api - .get_opt(&identity.pod_name) - .await - .map_err(|e| { - warn!( - pod = %identity.pod_name, - error = %e, - "failed to fetch sandbox pod for annotation lookup" - ); - Status::internal(format!("pod GET failed: {e}")) - })?; + let pods_api = self.pods_api(&identity.namespace); + let pod = pods_api.get_opt(&identity.pod_name).await.map_err(|e| { + warn!( + pod = %identity.pod_name, + namespace = %identity.namespace, + error = %e, + "failed to fetch sandbox pod for annotation lookup" + ); + Status::internal(format!("pod GET failed: {e}")) + })?; let Some(pod) = pod else { warn!( pod = %identity.pod_name, - "sandbox pod referenced by SA token not found in this namespace" + namespace = %identity.namespace, + "sandbox pod referenced by SA token not found" ); return Err(Status::not_found("sandbox pod not found")); }; - // Defense-in-depth: confirm the pod UID matches the SA token's - // `kubernetes.io.pod.uid`. Prevents a replayed token from a - // recreated pod with the same name. let actual_uid = pod.metadata.uid.as_deref().unwrap_or_default(); if actual_uid != identity.pod_uid { warn!( @@ -294,16 +309,19 @@ impl K8sIdentityResolver for LiveK8sResolver { let sandbox_id = pod_sandbox_id(&pod)?; let owner = sandbox_owner_reference(&pod)?; - let sandbox_cr = self.get_sandbox_cr_for_owner(&owner).await.map_err(|e| { - warn!( - pod = %identity.pod_name, - sandbox_owner = %owner.name, - sandbox_owner_api_version = %owner.api_version, - error = %e, - "failed to fetch owning Sandbox CR for pod identity validation" - ); - Status::internal(format!("sandbox GET failed: {e}")) - })?; + let sandbox_cr = self + .get_sandbox_cr_for_owner(&identity.namespace, &owner) + .await + .map_err(|e| { + warn!( + pod = %identity.pod_name, + sandbox_owner = %owner.name, + sandbox_owner_api_version = %owner.api_version, + error = %e, + "failed to fetch owning Sandbox CR for pod identity validation" + ); + Status::internal(format!("sandbox GET failed: {e}")) + })?; let Some(sandbox_cr) = sandbox_cr else { warn!( pod = %identity.pod_name, @@ -327,7 +345,7 @@ impl K8sIdentityResolver for LiveK8sResolver { fn token_review_identity( status: &TokenReviewStatus, expected_audience: &str, - sandbox_namespace: &str, + namespace_validator: &NamespaceValidator, expected_service_account: &str, ) -> Result, Status> { if status.authenticated != Some(true) { @@ -356,13 +374,20 @@ fn token_review_identity( .username .as_deref() .ok_or_else(|| Status::permission_denied("TokenReview response missing username"))?; - let expected_username = - format!("system:serviceaccount:{sandbox_namespace}:{expected_service_account}"); - if username != expected_username { + + let (namespace, sa_name) = parse_sa_username(username).ok_or_else(|| { warn!( username = %username, - sandbox_namespace = %sandbox_namespace, - service_account = %expected_service_account, + "K8s TokenReview username is not a service account" + ); + Status::permission_denied("SA token username format not recognized") + })?; + + if sa_name != expected_service_account { + warn!( + username = %username, + service_account = %sa_name, + expected = %expected_service_account, "K8s TokenReview principal is not the configured sandbox service account" ); return Err(Status::permission_denied( @@ -370,9 +395,33 @@ fn token_review_identity( )); } + if !namespace_validator.accepts(&namespace) { + warn!( + username = %username, + namespace = %namespace, + "K8s TokenReview SA namespace not accepted by workspace mode validator" + ); + return Err(Status::permission_denied( + "SA token is not from an accepted sandbox namespace", + )); + } + let pod_name = user_extra_one(user, POD_NAME_EXTRA)?; let pod_uid = user_extra_one(user, POD_UID_EXTRA)?; - Ok(Some(TokenReviewIdentity { pod_name, pod_uid })) + Ok(Some(TokenReviewIdentity { + namespace, + pod_name, + pod_uid, + })) +} + +fn parse_sa_username(username: &str) -> Option<(String, String)> { + let rest = username.strip_prefix("system:serviceaccount:")?; + let (namespace, sa_name) = rest.split_once(':')?; + if namespace.is_empty() || sa_name.is_empty() { + return None; + } + Some((namespace.to_string(), sa_name.to_string())) } #[allow(clippy::result_large_err)] @@ -664,6 +713,10 @@ mod tests { cr } + fn exact_validator(ns: &str) -> NamespaceValidator { + NamespaceValidator::Exact(ns.to_string()) + } + #[test] fn token_review_identity_extracts_pod_binding() { let status = token_review_status( @@ -676,10 +729,12 @@ mod tests { ], ); - let identity = token_review_identity(&status, "openshell-gateway", "openshell", "default") + let validator = exact_validator("openshell"); + let identity = token_review_identity(&status, "openshell-gateway", &validator, "default") .unwrap() .expect("authenticated token should resolve"); + assert_eq!(identity.namespace, "openshell"); assert_eq!(identity.pod_name, "openshell-sandbox-a"); assert_eq!(identity.pod_uid, "uid-a"); } @@ -691,9 +746,10 @@ mod tests { error: Some("invalid audience".to_string()), ..Default::default() }; + let validator = exact_validator("openshell"); assert!( - token_review_identity(&status, "openshell-gateway", "openshell", "default") + token_review_identity(&status, "openshell-gateway", &validator, "default") .unwrap() .is_none() ); @@ -710,8 +766,9 @@ mod tests { (POD_UID_EXTRA, "uid-a"), ], ); + let validator = exact_validator("openshell"); - let err = token_review_identity(&status, "openshell-gateway", "openshell", "default") + let err = token_review_identity(&status, "openshell-gateway", &validator, "default") .expect_err("wrong audience must fail closed"); assert_eq!(err.code(), tonic::Code::Unauthenticated); } @@ -727,8 +784,9 @@ mod tests { (POD_UID_EXTRA, "uid-a"), ], ); + let validator = exact_validator("openshell"); - let err = token_review_identity(&status, "openshell-gateway", "openshell", "default") + let err = token_review_identity(&status, "openshell-gateway", &validator, "default") .expect_err("other namespace must be rejected"); assert_eq!(err.code(), tonic::Code::PermissionDenied); } @@ -744,8 +802,9 @@ mod tests { (POD_UID_EXTRA, "uid-a"), ], ); + let validator = exact_validator("openshell"); - let err = token_review_identity(&status, "openshell-gateway", "openshell", "default") + let err = token_review_identity(&status, "openshell-gateway", &validator, "default") .expect_err("other service account must be rejected"); assert_eq!(err.code(), tonic::Code::PermissionDenied); } @@ -758,12 +817,71 @@ mod tests { "system:serviceaccount:openshell:default", vec![], ); + let validator = exact_validator("openshell"); - let err = token_review_identity(&status, "openshell-gateway", "openshell", "default") + let err = token_review_identity(&status, "openshell-gateway", &validator, "default") .expect_err("non pod-bound tokens must be rejected"); assert_eq!(err.code(), tonic::Code::PermissionDenied); } + #[test] + fn namespace_validator_exact_accepts_matching() { + let v = NamespaceValidator::Exact("openshell".to_string()); + assert!(v.accepts("openshell")); + assert!(!v.accepts("other")); + } + + #[test] + fn namespace_validator_prefix_accepts_managed_namespaces() { + let v = NamespaceValidator::Prefix("openshell-gw1-".to_string()); + assert!(v.accepts("openshell-gw1-workspace-a")); + assert!(v.accepts("openshell-gw1-default")); + assert!(!v.accepts("openshell-gw2-workspace-a")); + assert!(!v.accepts("other")); + } + + #[test] + fn namespace_validator_allowlist_accepts_known_namespaces() { + let al = OperatorNamespaceAllowlist::from_set(std::collections::BTreeSet::from([ + "ns-a".to_string(), + "ns-b".to_string(), + ])); + let v = NamespaceValidator::Allowlist(al); + assert!(v.accepts("ns-a")); + assert!(v.accepts("ns-b")); + assert!(!v.accepts("ns-c")); + } + + #[test] + fn token_review_identity_prefix_validator_accepts_managed_namespace() { + let status = token_review_status( + true, + vec!["openshell-gateway"], + "system:serviceaccount:openshell-gw1-workspace-a:default", + vec![ + (POD_NAME_EXTRA, "openshell-sandbox-a"), + (POD_UID_EXTRA, "uid-a"), + ], + ); + let validator = NamespaceValidator::Prefix("openshell-gw1-".to_string()); + + let identity = token_review_identity(&status, "openshell-gateway", &validator, "default") + .unwrap() + .expect("managed namespace token should resolve"); + assert_eq!(identity.namespace, "openshell-gw1-workspace-a"); + } + + #[test] + fn parse_sa_username_extracts_namespace_and_sa() { + let (ns, sa) = parse_sa_username("system:serviceaccount:openshell:default").unwrap(); + assert_eq!(ns, "openshell"); + assert_eq!(sa, "default"); + + assert!(parse_sa_username("system:node:nodename").is_none()); + assert!(parse_sa_username("system:serviceaccount::default").is_none()); + assert!(parse_sa_username("system:serviceaccount:ns:").is_none()); + } + #[test] fn pod_sandbox_id_requires_annotation() { assert_eq!( diff --git a/crates/openshell-server/src/auth/mod.rs b/crates/openshell-server/src/auth/mod.rs index c26fac08ad..bedbebe015 100644 --- a/crates/openshell-server/src/auth/mod.rs +++ b/crates/openshell-server/src/auth/mod.rs @@ -11,6 +11,7 @@ pub mod authenticator; pub mod authz; pub mod descriptor_authz; +pub mod extension_mint_limit; pub mod guard; mod http; pub mod identity; diff --git a/crates/openshell-server/src/auth/sandbox_jwt.rs b/crates/openshell-server/src/auth/sandbox_jwt.rs index 39f5982ca0..3d66824f20 100644 --- a/crates/openshell-server/src/auth/sandbox_jwt.rs +++ b/crates/openshell-server/src/auth/sandbox_jwt.rs @@ -18,13 +18,22 @@ use super::authenticator::Authenticator; use super::principal::{Principal, SandboxIdentitySource, SandboxPrincipal}; use async_trait::async_trait; +use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; use jsonwebtoken::{ Algorithm, DecodingKey, EncodingKey, Header, Validation, decode, decode_header, encode, }; +pub use openshell_extension_core::{ + EXTENSION_JWT_TYP, ExtensionAudience, ExtensionCallerKind, ExtensionJwtClaims, + MAX_EXTENSION_TOKEN_TTL, +}; use serde::{Deserialize, Serialize}; -use std::time::{Duration, SystemTime, UNIX_EPOCH}; +use std::{ + io::Cursor, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; use tonic::Status; use tracing::{debug, warn}; +use x509_parser::{oid_registry::OID_SIG_ED25519, prelude::FromDer, x509::SubjectPublicKeyInfo}; /// SPIFFE-shaped subject prefix. Embedded in the `sub` claim of every /// minted token so a future migration to per-sandbox certs or SPIRE can @@ -33,6 +42,24 @@ use tracing::{debug, warn}; const SPIFFE_SUBJECT_PREFIX: &str = "spiffe://openshell/sandbox/"; const SANDBOX_JWT_EXP_LEEWAY_SECS: i64 = 60; +/// Public JSON Web Key Set served by the gateway. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct GatewayJwks { + pub keys: Vec, +} + +/// Ed25519 public key entry in the gateway JWKS. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct GatewayJwk { + pub kty: &'static str, + pub crv: &'static str, + pub alg: &'static str, + #[serde(rename = "use")] + pub key_use: &'static str, + pub kid: String, + pub x: String, +} + /// JWT claim set serialized in every gateway-minted sandbox token. #[derive(Debug, Serialize, Deserialize)] pub struct SandboxJwtClaims { @@ -126,6 +153,75 @@ impl SandboxJwtIssuer { }) } + /// Mint a short-lived bearer token for one exact extension audience. + /// + /// `sandbox_id` is required for supervisor calls and forbidden for + /// gateway calls. The subject follows the existing SPIFFE-shaped sandbox + /// identity for supervisor calls; gateway calls use the issuer identity. + #[allow(clippy::result_large_err)] + pub fn mint_extension_token( + &self, + audience: &ExtensionAudience, + caller_kind: ExtensionCallerKind, + sandbox_id: Option<&str>, + ttl: Duration, + ) -> Result { + if audience.as_str() == self.audience { + return Err(Status::invalid_argument( + "extension audience must not equal the gateway sandbox audience", + )); + } + if ttl.is_zero() || ttl > MAX_EXTENSION_TOKEN_TTL { + return Err(Status::invalid_argument(format!( + "extension token TTL must be between 1 and {} seconds", + MAX_EXTENSION_TOKEN_TTL.as_secs() + ))); + } + + let (sub, sandbox_id) = match (caller_kind, sandbox_id) { + (ExtensionCallerKind::Gateway, None) => (self.issuer.clone(), None), + (ExtensionCallerKind::Supervisor, Some(id)) if !id.trim().is_empty() => { + (format!("{SPIFFE_SUBJECT_PREFIX}{id}"), Some(id.to_string())) + } + (ExtensionCallerKind::Gateway, Some(_)) => { + return Err(Status::invalid_argument( + "gateway extension tokens must not include a sandbox ID", + )); + } + (ExtensionCallerKind::Supervisor, _) => { + return Err(Status::invalid_argument( + "supervisor extension tokens require a sandbox ID", + )); + } + }; + + let now = now_secs(); + let exp = now.saturating_add(i64::try_from(ttl.as_secs()).unwrap_or(3_600)); + let claims = ExtensionJwtClaims { + iss: self.issuer.clone(), + aud: audience.as_str().to_string(), + sub, + iat: now, + exp, + jti: uuid::Uuid::new_v4().to_string(), + caller_kind, + sandbox_id, + }; + let mut header = Header::new(Algorithm::EdDSA); + header.kid = Some(self.kid.clone()); + // Explicit typing so an extension that requires this `typ` cannot be + // handed a sandbox-to-gateway bootstrap token signed by the same key. + header.typ = Some(EXTENSION_JWT_TYP.to_string()); + let token = encode(&header, &claims, &self.encoding_key).map_err(|e| { + warn!(error = %e, "failed to mint extension JWT"); + Status::internal("failed to mint extension token") + })?; + Ok(MintedToken { + token, + expires_at_ms: exp.saturating_mul(1000), + }) + } + pub fn ttl(&self) -> Duration { self.ttl } @@ -137,6 +233,7 @@ pub struct SandboxJwtAuthenticator { kid: String, issuer: String, audience: String, + jwks: GatewayJwks, } impl std::fmt::Debug for SandboxJwtAuthenticator { @@ -153,15 +250,30 @@ impl SandboxJwtAuthenticator { pub fn from_pem(public_key_pem: &[u8], kid: String, gateway_id: &str) -> Result { let decoding_key = DecodingKey::from_ed_pem(public_key_pem) .map_err(|e| format!("failed to parse Ed25519 public key PEM: {e}"))?; + let jwks = GatewayJwks::from_public_key_pem(public_key_pem, kid.clone())?; let identity = format!("openshell-gateway:{gateway_id}"); Ok(Self { decoding_key, kid, issuer: identity.clone(), audience: identity, + jwks, }) } + /// Return the public signing keys integrations use to verify extension + /// tokens. No private key material is retained by this type. + #[must_use] + pub const fn jwks(&self) -> &GatewayJwks { + &self.jwks + } + + /// The exact `iss` claim carried by every token this gateway mints. + #[must_use] + pub fn issuer(&self) -> &str { + &self.issuer + } + #[allow(clippy::result_large_err)] fn validate_bearer(&self, token: &str) -> Result, Status> { let header = decode_header(token).map_err(|e| { @@ -169,6 +281,16 @@ impl SandboxJwtAuthenticator { Status::unauthenticated("invalid token") })?; + // Extension credentials share this signing key during alpha, but are + // never valid sandbox admission credentials. Check the explicit type + // before `kid` fallthrough so another authenticator cannot accept one. + // Legacy and untyped sandbox JWTs remain valid for rolling upgrades. + if header.typ.as_deref() == Some(EXTENSION_JWT_TYP) { + return Err(Status::unauthenticated( + "extension tokens cannot authenticate to the gateway", + )); + } + // Fall through to other authenticators when the kid does not match — // OIDC issuers may share the Bearer slot. if header.kid.as_deref() != Some(self.kid.as_str()) { @@ -201,6 +323,36 @@ impl SandboxJwtAuthenticator { } } +impl GatewayJwks { + fn from_public_key_pem(public_key_pem: &[u8], kid: String) -> Result { + let item = rustls_pemfile::read_one(&mut Cursor::new(public_key_pem)) + .map_err(|e| format!("failed to parse Ed25519 public key PEM for JWKS: {e}"))?; + let Some(rustls_pemfile::Item::SubjectPublicKeyInfo(der)) = item else { + return Err("Ed25519 public key PEM does not contain a PUBLIC KEY block".into()); + }; + let (remainder, spki) = SubjectPublicKeyInfo::from_der(der.as_ref()) + .map_err(|e| format!("failed to parse SubjectPublicKeyInfo for JWKS: {e}"))?; + if !remainder.is_empty() || spki.algorithm.algorithm != OID_SIG_ED25519 { + return Err("public key is not an RFC 8410 Ed25519 SubjectPublicKeyInfo key".into()); + } + let raw_key = spki.subject_public_key.data.as_ref(); + if raw_key.len() != 32 { + return Err("Ed25519 public key must be 32 bytes".to_string()); + } + + Ok(Self { + keys: vec![GatewayJwk { + kty: "OKP", + crv: "Ed25519", + alg: "EdDSA", + key_use: "sig", + kid, + x: URL_SAFE_NO_PAD.encode(raw_key), + }], + }) + } +} + #[async_trait] impl Authenticator for SandboxJwtAuthenticator { async fn authenticate( @@ -278,6 +430,10 @@ mod tests { (issuer, auth) } + fn extension_audience(value: &str) -> ExtensionAudience { + ExtensionAudience::new(value).expect("valid extension audience") + } + #[tokio::test] async fn mint_and_validate_round_trip() { let (issuer, auth) = pair(); @@ -301,6 +457,54 @@ mod tests { } } + #[tokio::test] + async fn extension_token_cannot_authenticate_as_a_sandbox() { + let mat = generate_jwt_key().expect("jwt key"); + let issuer = SandboxJwtIssuer::from_pem( + mat.signing_key_pem.as_bytes(), + mat.kid.clone(), + "test-gateway", + Duration::from_secs(3600), + ) + .expect("issuer"); + let auth = SandboxJwtAuthenticator::from_pem( + mat.public_key_pem.as_bytes(), + mat.kid.clone(), + "test-gateway", + ) + .expect("authenticator"); + + // Build the token directly to model a credential minted before the + // reserved-audience guard was added. Its claims otherwise satisfy the + // sandbox authenticator's issuer, audience, subject, and expiry checks. + let sandbox_id = "sandbox-a"; + let now = now_secs(); + let claims = ExtensionJwtClaims { + iss: "openshell-gateway:test-gateway".to_string(), + aud: "openshell-gateway:test-gateway".to_string(), + sub: format!("{SPIFFE_SUBJECT_PREFIX}{sandbox_id}"), + iat: now, + exp: now + 300, + jti: uuid::Uuid::new_v4().to_string(), + caller_kind: ExtensionCallerKind::Supervisor, + sandbox_id: Some(sandbox_id.to_string()), + }; + let mut header = Header::new(Algorithm::EdDSA); + header.kid = Some(mat.kid); + header.typ = Some(EXTENSION_JWT_TYP.to_string()); + let token = encode(&header, &claims, &issuer.encoding_key).expect("extension token"); + + let error = auth + .authenticate(&header_map_with_bearer(&token), "/anything") + .await + .expect_err("extension token must not authenticate as a sandbox"); + assert_eq!(error.code(), tonic::Code::Unauthenticated); + assert_eq!( + error.message(), + "extension tokens cannot authenticate to the gateway" + ); + } + #[tokio::test] async fn ttl_zero_mints_non_expiring_token() { let (issuer, auth) = pair_with_ttl(Duration::ZERO); @@ -393,4 +597,195 @@ mod tests { .expect_err("expired token must reject"); assert_eq!(err.code(), tonic::Code::Unauthenticated); } + + #[test] + fn extension_tokens_have_exact_audience_and_caller_identity() { + let mat = generate_jwt_key().expect("jwt key"); + let issuer = SandboxJwtIssuer::from_pem( + mat.signing_key_pem.as_bytes(), + mat.kid.clone(), + "gateway-a", + Duration::ZERO, + ) + .expect("issuer"); + let decoding_key = DecodingKey::from_ed_pem(mat.public_key_pem.as_bytes()).unwrap(); + + let gateway = issuer + .mint_extension_token( + &extension_audience("urn:openshell:extension:middleware:scanner"), + ExtensionCallerKind::Gateway, + None, + Duration::from_secs(300), + ) + .expect("gateway token"); + let mut validation = Validation::new(Algorithm::EdDSA); + validation.set_issuer(&["openshell-gateway:gateway-a"]); + validation.set_audience(&["urn:openshell:extension:middleware:scanner"]); + validation.set_required_spec_claims(&["iss", "aud", "sub", "iat", "exp"]); + let claims = decode::(&gateway.token, &decoding_key, &validation) + .expect("valid extension token") + .claims; + assert_eq!(claims.sub, "openshell-gateway:gateway-a"); + assert_eq!(claims.caller_kind, ExtensionCallerKind::Gateway); + assert_eq!(claims.sandbox_id, None); + assert!(!claims.jti.is_empty()); + assert_eq!(gateway.expires_at_ms, claims.exp * 1000); + + let supervisor = issuer + .mint_extension_token( + &extension_audience("urn:openshell:extension:middleware:scanner"), + ExtensionCallerKind::Supervisor, + Some("sandbox-a"), + Duration::from_secs(300), + ) + .expect("supervisor token"); + let claims = decode::(&supervisor.token, &decoding_key, &validation) + .expect("valid supervisor extension token") + .claims; + assert_eq!(claims.sub, "spiffe://openshell/sandbox/sandbox-a"); + assert_eq!(claims.caller_kind, ExtensionCallerKind::Supervisor); + assert_eq!(claims.sandbox_id.as_deref(), Some("sandbox-a")); + } + + #[test] + fn extension_tokens_are_explicitly_typed_and_sandbox_tokens_are_not() { + let mat = generate_jwt_key().expect("jwt key"); + let issuer = SandboxJwtIssuer::from_pem( + mat.signing_key_pem.as_bytes(), + mat.kid.clone(), + "gateway-a", + Duration::from_secs(3600), + ) + .expect("issuer"); + + let extension = issuer + .mint_extension_token( + &extension_audience("urn:openshell:extension:middleware:scanner"), + ExtensionCallerKind::Gateway, + None, + Duration::from_secs(300), + ) + .expect("extension token"); + assert_eq!( + decode_header(&extension.token).unwrap().typ.as_deref(), + Some(EXTENSION_JWT_TYP) + ); + + // The discriminator is only useful if the sandbox bootstrap token does + // not carry it. A verifier requiring `openshell-ext+jwt` must reject a + // gateway admission credential even though both share a signing key. + let sandbox = issuer.mint("sandbox-a").expect("sandbox token"); + assert_ne!( + decode_header(&sandbox.token).unwrap().typ.as_deref(), + Some(EXTENSION_JWT_TYP) + ); + } + + #[test] + fn extension_token_rejects_wrong_audience() { + let mat = generate_jwt_key().expect("jwt key"); + let issuer = SandboxJwtIssuer::from_pem( + mat.signing_key_pem.as_bytes(), + mat.kid, + "gateway-a", + Duration::ZERO, + ) + .expect("issuer"); + let minted = issuer + .mint_extension_token( + &extension_audience("service-a"), + ExtensionCallerKind::Gateway, + None, + Duration::from_secs(60), + ) + .expect("token"); + let decoding_key = DecodingKey::from_ed_pem(mat.public_key_pem.as_bytes()).unwrap(); + let mut validation = Validation::new(Algorithm::EdDSA); + validation.set_issuer(&["openshell-gateway:gateway-a"]); + validation.set_audience(&["service-b"]); + assert!(decode::(&minted.token, &decoding_key, &validation).is_err()); + } + + #[test] + fn extension_token_rejects_gateway_sandbox_audience() { + let (issuer, _) = pair(); + let error = issuer + .mint_extension_token( + &extension_audience("openshell-gateway:test-gateway"), + ExtensionCallerKind::Supervisor, + Some("sandbox-a"), + Duration::from_secs(60), + ) + .expect_err("gateway sandbox audience must be reserved"); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + assert_eq!( + error.message(), + "extension audience must not equal the gateway sandbox audience" + ); + } + + #[test] + fn extension_token_enforces_positive_bounded_ttl_and_caller_shape() { + let (issuer, _) = pair_with_ttl(Duration::ZERO); + for ttl in [ + Duration::ZERO, + MAX_EXTENSION_TOKEN_TTL + Duration::from_secs(1), + ] { + let error = issuer + .mint_extension_token( + &extension_audience("service"), + ExtensionCallerKind::Gateway, + None, + ttl, + ) + .expect_err("invalid TTL"); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + } + assert!( + issuer + .mint_extension_token( + &extension_audience("service"), + ExtensionCallerKind::Supervisor, + None, + Duration::from_secs(60), + ) + .is_err() + ); + assert!( + issuer + .mint_extension_token( + &extension_audience("service"), + ExtensionCallerKind::Gateway, + Some("sandbox-a"), + Duration::from_secs(60), + ) + .is_err() + ); + assert!(ExtensionAudience::new(" ").is_err()); + } + + #[test] + fn jwks_contains_public_ed25519_key_without_pem_material() { + let mat = generate_jwt_key().expect("jwt key"); + let auth = SandboxJwtAuthenticator::from_pem( + mat.public_key_pem.as_bytes(), + mat.kid.clone(), + "gateway-a", + ) + .expect("authenticator"); + let jwks = auth.jwks(); + assert_eq!(jwks.keys.len(), 1); + let key = &jwks.keys[0]; + assert_eq!(key.kid, mat.kid); + assert_eq!(key.kty, "OKP"); + assert_eq!(key.crv, "Ed25519"); + assert_eq!(key.alg, "EdDSA"); + assert_eq!(key.key_use, "sig"); + assert_eq!(URL_SAFE_NO_PAD.decode(&key.x).unwrap().len(), 32); + + let json = serde_json::to_string(jwks).expect("JSON"); + assert!(!json.contains("BEGIN PUBLIC KEY")); + assert!(!json.contains("PRIVATE")); + assert!(json.contains(r#""use":"sig""#)); + } } diff --git a/crates/openshell-server/src/compute/mod.rs b/crates/openshell-server/src/compute/mod.rs index bc98670b89..e09b63de09 100644 --- a/crates/openshell-server/src/compute/mod.rs +++ b/crates/openshell-server/src/compute/mod.rs @@ -32,9 +32,10 @@ use futures::{Stream, StreamExt}; use hyper_util::rt::TokioIo; use openshell_core::ComputeDriverKind; use openshell_core::proto::compute::v1::{ - CreateSandboxRequest, DeleteSandboxRequest, DriverCondition, DriverPlatformEvent, - DriverResourceRequirements, DriverSandbox, DriverSandboxSpec, DriverSandboxStatus, - DriverSandboxTemplate, GatewayListenerRequirement as ProtoGatewayListenerRequirement, + CreateSandboxRequest, DeleteSandboxRequest, DeleteWorkspaceRequest, DeleteWorkspaceResponse, + DriverCondition, DriverPlatformEvent, DriverResourceRequirements, DriverSandbox, + DriverSandboxSpec, DriverSandboxStatus, DriverSandboxTemplate, EnsureWorkspaceRequest, + EnsureWorkspaceResponse, GatewayListenerRequirement as ProtoGatewayListenerRequirement, GetCapabilitiesRequest, GetGatewayListenerRequirementsRequest, GetGatewayListenerRequirementsResponse, GetSandboxRequest, GpuResourceRequirements as DriverGpuResourceRequirements, ListSandboxesRequest, @@ -53,6 +54,7 @@ use openshell_driver_docker::DockerComputeDriver; #[cfg(not(target_os = "windows"))] use openshell_driver_kubernetes::{ ComputeDriverService as KubernetesDriverService, KubernetesComputeDriver, + OperatorNamespaceAllowlist, }; #[cfg(not(target_os = "windows"))] use openshell_driver_podman::{ComputeDriverService as PodmanDriverService, PodmanComputeDriver}; @@ -566,6 +568,22 @@ impl ComputeDriver for RemoteComputeDriver { let stream = response.into_inner(); Ok(tonic::Response::new(Box::pin(stream))) } + + async fn ensure_workspace( + &self, + request: Request, + ) -> Result, Status> { + let mut client = self.client(); + client.ensure_workspace(request).await + } + + async fn delete_workspace( + &self, + request: Request, + ) -> Result, Status> { + let mut client = self.client(); + client.delete_workspace(request).await + } } #[derive(Clone)] @@ -775,12 +793,14 @@ impl ComputeRuntime { sandbox_watch_bus: SandboxWatchBus, tracing_log_bus: TracingLogBus, supervisor_sessions: Arc, - ) -> Result { - let driver = KubernetesComputeDriver::new(config) + shutdown_rx: watch::Receiver, + ) -> Result<(Self, Option), ComputeError> { + let driver = KubernetesComputeDriver::new(config, shutdown_rx) .await .map_err(|err| ComputeError::Message(err.to_string()))?; + let operator_allowlist_arc = driver.operator_allowlist().cloned(); let driver: SharedComputeDriver = Arc::new(KubernetesDriverService::new(driver)); - Self::from_driver( + let runtime = Self::from_driver( ComputeDriverKind::Kubernetes.as_str().to_string(), driver, None, @@ -792,7 +812,8 @@ impl ComputeRuntime { tracing_log_bus, supervisor_sessions, ) - .await + .await?; + Ok((runtime, operator_allowlist_arc)) } pub(crate) async fn new_remote_driver( @@ -867,6 +888,40 @@ impl ComputeRuntime { &self.gateway_listener_requirements } + pub(crate) async fn ensure_workspace(&self, workspace: &str) -> Result<(), Status> { + let workspace = workspace.to_string(); + match self + .driver + .call("driver.ensure_workspace", None, |driver| async move { + driver + .ensure_workspace(Request::new(EnsureWorkspaceRequest { workspace })) + .await + }) + .await + { + Ok(_) => Ok(()), + Err(status) if status.code() == Code::Unimplemented => Ok(()), + Err(status) => Err(status), + } + } + + pub(crate) async fn delete_workspace(&self, workspace: &str) -> Result<(), Status> { + let workspace = workspace.to_string(); + match self + .driver + .call("driver.delete_workspace", None, |driver| async move { + driver + .delete_workspace(Request::new(DeleteWorkspaceRequest { workspace })) + .await + }) + .await + { + Ok(_) => Ok(()), + Err(status) if status.code() == Code::Unimplemented => Ok(()), + Err(status) => Err(status), + } + } + pub async fn validate_sandbox_create(&self, sandbox: &Sandbox) -> Result<(), Status> { let driver_sandbox = driver_sandbox_from_public(sandbox, &self.driver_info.name) .map_err(|status| *status)?; @@ -3770,7 +3825,18 @@ fn is_terminal_failure_reason(reason: &str) -> bool { #[cfg(test)] #[derive(Debug, Default)] -pub struct NoopTestDriver; +pub struct NoopTestDriver { + workspace_delete_failures: std::sync::atomic::AtomicUsize, +} + +#[cfg(test)] +impl NoopTestDriver { + pub fn failing_workspace_deletes(count: usize) -> Self { + Self { + workspace_delete_failures: std::sync::atomic::AtomicUsize::new(count), + } + } +} #[cfg(test)] #[tonic::async_trait] @@ -3878,6 +3944,31 @@ impl ComputeDriver for NoopTestDriver { ) -> Result, Status> { Ok(tonic::Response::new(Box::pin(futures::stream::empty()))) } + + async fn ensure_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(tonic::Response::new(EnsureWorkspaceResponse {})) + } + + async fn delete_workspace( + &self, + _request: Request, + ) -> Result, Status> { + if self + .workspace_delete_failures + .fetch_update( + std::sync::atomic::Ordering::Relaxed, + std::sync::atomic::Ordering::Relaxed, + |remaining| remaining.checked_sub(1), + ) + .is_ok() + { + return Err(Status::unavailable("injected workspace cleanup failure")); + } + Ok(tonic::Response::new(DeleteWorkspaceResponse {})) + } } #[cfg(test)] @@ -3887,8 +3978,17 @@ pub async fn new_test_runtime(store: Arc) -> ComputeRuntime { #[cfg(test)] pub async fn new_test_runtime_for_driver(store: Arc, driver_name: &str) -> ComputeRuntime { + new_test_runtime_with_driver(store, driver_name, Arc::new(NoopTestDriver::default())).await +} + +#[cfg(test)] +pub async fn new_test_runtime_with_driver( + store: Arc, + driver_name: &str, + driver: Arc, +) -> ComputeRuntime { ComputeRuntime { - driver: TracedDriver::new(Arc::new(NoopTestDriver), "test".to_string()), + driver: TracedDriver::new(driver, "test".to_string()), driver_info: ComputeDriverInfoSnapshot { name: driver_name.to_string(), driver_name: driver_name.to_string(), @@ -4042,6 +4142,7 @@ mod tests { struct TestDriver { listed_sandboxes: Vec, current_sandboxes: Vec, + workspace_rpcs_unimplemented: bool, } #[tonic::async_trait] @@ -4155,6 +4256,38 @@ mod tests { ) -> Result, Status> { Ok(tonic::Response::new(Box::pin(stream::empty()))) } + + async fn ensure_workspace( + &self, + _request: Request, + ) -> Result, Status> { + if self.workspace_rpcs_unimplemented { + return Err(Status::unimplemented("workspace lifecycle is unsupported")); + } + Ok(tonic::Response::new(EnsureWorkspaceResponse {})) + } + + async fn delete_workspace( + &self, + _request: Request, + ) -> Result, Status> { + if self.workspace_rpcs_unimplemented { + return Err(Status::unimplemented("workspace lifecycle is unsupported")); + } + Ok(tonic::Response::new(DeleteWorkspaceResponse {})) + } + } + + #[tokio::test] + async fn workspace_lifecycle_allows_legacy_driver_without_workspace_rpcs() { + let runtime = test_runtime(Arc::new(TestDriver { + workspace_rpcs_unimplemented: true, + ..Default::default() + })) + .await; + + runtime.ensure_workspace("legacy").await.unwrap(); + runtime.delete_workspace("legacy").await.unwrap(); } #[derive(Clone)] @@ -4481,6 +4614,20 @@ mod tests { UnboundedReceiverStream::new(receiver), ))) } + + async fn ensure_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(tonic::Response::new(EnsureWorkspaceResponse {})) + } + + async fn delete_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(tonic::Response::new(DeleteWorkspaceResponse {})) + } } async fn test_runtime(driver: SharedComputeDriver) -> ComputeRuntime { @@ -5247,6 +5394,20 @@ mod tests { ) -> Result, Status> { self.0.watch_sandboxes(request).await } + + async fn ensure_workspace( + &self, + request: Request, + ) -> Result, Status> { + self.0.ensure_workspace(request).await + } + + async fn delete_workspace( + &self, + request: Request, + ) -> Result, Status> { + self.0.delete_workspace(request).await + } } let runtime = test_runtime(Arc::new(FailingDriver::default())).await; @@ -7487,6 +7648,7 @@ mod tests { #[tokio::test] async fn reconcile_store_with_backend_applies_driver_snapshot() { let runtime = test_runtime(Arc::new(TestDriver { + workspace_rpcs_unimplemented: false, listed_sandboxes: vec![DriverSandbox { id: "sb-1".to_string(), name: "sandbox-a".to_string(), @@ -7674,6 +7836,7 @@ mod tests { #[tokio::test] async fn reconcile_store_with_backend_does_not_recreate_missing_record_from_snapshot() { let runtime = test_runtime(Arc::new(TestDriver { + workspace_rpcs_unimplemented: false, listed_sandboxes: vec![DriverSandbox { id: "sb-1".to_string(), name: "sandbox-a".to_string(), diff --git a/crates/openshell-server/src/config_file.rs b/crates/openshell-server/src/config_file.rs index 39166333be..00b7a2f64d 100644 --- a/crates/openshell-server/src/config_file.rs +++ b/crates/openshell-server/src/config_file.rs @@ -21,9 +21,11 @@ //! values. use std::collections::BTreeMap; +use std::io::Cursor; use std::net::SocketAddr; use std::path::{Path, PathBuf}; +use base64::Engine as _; use openshell_core::config::ComputeDriverKind; use openshell_core::proto::SupervisorMiddlewareService; use openshell_core::{ @@ -220,24 +222,98 @@ pub struct SupervisorFileSection { pub struct MiddlewareServiceFileConfig { /// Operator-facing name used for diagnostics. pub name: String, - /// Plaintext gRPC endpoint reachable by the gateway and supervisors. + /// HTTP or HTTPS gRPC endpoint reachable by the gateway and supervisors. pub grpc_endpoint: String, - /// Operator-owned body limit for every binding exposed by this service. - pub max_body_bytes: u64, + /// Optional PEM trust-root bundle for an HTTPS endpoint. + #[serde(default)] + pub tls_ca_cert_path: Option, + /// Exact JWT audience for this service. Defaults to a kind-scoped value + /// derived from the registration name. + #[serde(default)] + pub audience: Option, + /// Opt out of extension authentication for this registration, permitting a + /// plaintext `http://` endpoint with no bearer credential. Development and + /// trusted-network deployments only. + #[serde(default)] + pub allow_insecure_transport: bool, + /// Operator-owned logical payload limit for every binding exposed by this + /// service, including HTTP bodies and complete WebSocket messages. + #[serde(alias = "max_body_bytes")] + pub max_payload_bytes: u64, /// Default RPC timeout using an integer with an `ms` or `s` suffix. #[serde(default)] pub timeout: Option, } -impl From<&MiddlewareServiceFileConfig> for SupervisorMiddlewareService { - fn from(config: &MiddlewareServiceFileConfig) -> Self { - Self { +impl TryFrom<&MiddlewareServiceFileConfig> for SupervisorMiddlewareService { + type Error = ConfigFileError; + + fn try_from(config: &MiddlewareServiceFileConfig) -> Result { + let tls_ca_cert_pem = match &config.tls_ca_cert_path { + Some(path) => { + let pem = + std::fs::read(path).map_err(|source| ConfigFileError::MiddlewareTlsCaRead { + name: config.name.clone(), + path: path.clone(), + source, + })?; + sanitize_ca_cert_pem(&config.name, path, &pem)? + } + None => Vec::new(), + }; + + Ok(Self { name: config.name.clone(), grpc_endpoint: config.grpc_endpoint.clone(), - max_body_bytes: config.max_body_bytes, + max_payload_bytes: config.max_payload_bytes, timeout: config.timeout.clone().unwrap_or_default(), + tls_ca_cert_pem, + audience: config + .audience + .as_deref() + .filter(|audience| !audience.is_empty()) + .map_or_else( + || format!("urn:openshell:extension:middleware:{}", config.name), + ToString::to_string, + ), + allow_insecure_transport: config.allow_insecure_transport, + }) + } +} + +fn sanitize_ca_cert_pem(name: &str, path: &Path, pem: &[u8]) -> Result, ConfigFileError> { + let mut sanitized = Vec::new(); + let mut certificate_count = 0; + for item in rustls_pemfile::read_all(&mut Cursor::new(pem)) { + let item = item.map_err(|source| ConfigFileError::MiddlewareTlsCaInvalid { + name: name.to_string(), + path: path.to_path_buf(), + message: source.to_string(), + })?; + let rustls_pemfile::Item::X509Certificate(certificate) = item else { + return Err(ConfigFileError::MiddlewareTlsCaInvalid { + name: name.to_string(), + path: path.to_path_buf(), + message: "PEM bundle contains a non-certificate block".to_string(), + }); + }; + certificate_count += 1; + sanitized.extend_from_slice(b"-----BEGIN CERTIFICATE-----\n"); + let encoded = base64::engine::general_purpose::STANDARD.encode(certificate.as_ref()); + for line in encoded.as_bytes().chunks(64) { + sanitized.extend_from_slice(line); + sanitized.push(b'\n'); } + sanitized.extend_from_slice(b"-----END CERTIFICATE-----\n"); } + if certificate_count == 0 { + return Err(ConfigFileError::MiddlewareTlsCaInvalid { + name: name.to_string(), + path: path.to_path_buf(), + message: "PEM bundle does not contain a certificate".to_string(), + }); + } + Ok(sanitized) } #[derive(Debug, thiserror::Error)] @@ -271,6 +347,25 @@ pub enum ConfigFileError { field: &'static str, message: &'static str, }, + #[error( + "failed to read TLS CA certificate for supervisor middleware '{name}' from '{}': {source}", + path.display() + )] + MiddlewareTlsCaRead { + name: String, + path: PathBuf, + #[source] + source: std::io::Error, + }, + #[error( + "invalid TLS CA certificate for supervisor middleware '{name}' at '{}': {message}", + path.display() + )] + MiddlewareTlsCaInvalid { + name: String, + path: PathBuf, + message: String, + }, } /// Load and validate a TOML config file. @@ -605,27 +700,175 @@ allow_unauthenticated_users = true #[test] fn parses_supervisor_middleware_registration() { + let certificate = rcgen::generate_simple_self_signed(vec!["localhost".to_string()]) + .expect("test certificate"); + let mut ca = tempfile::Builder::new() + .suffix(".pem") + .tempfile() + .expect("CA tempfile"); + ca.write_all(certificate.cert.pem().as_bytes()) + .expect("write CA"); let toml = r#" [[openshell.supervisor.middleware]] name = "local-guard" -grpc_endpoint = "http://127.0.0.1:50051" -max_body_bytes = 262144 +grpc_endpoint = "https://127.0.0.1:50051" +tls_ca_cert_path = "CA_PATH" +audience = "urn:openshell:middleware:local-guard" +max_payload_bytes = 262144 timeout = "2s" -"#; - let tmp = write_tmp(toml); +"# + .replace("CA_PATH", &ca.path().display().to_string()); + let tmp = write_tmp(&toml); let file = load(tmp.path()).expect("valid middleware registration parses"); assert_eq!( file.openshell.supervisor.middleware, vec![MiddlewareServiceFileConfig { name: "local-guard".into(), - grpc_endpoint: "http://127.0.0.1:50051".into(), - max_body_bytes: 262_144, + grpc_endpoint: "https://127.0.0.1:50051".into(), + tls_ca_cert_path: Some(ca.path().to_path_buf()), + audience: Some("urn:openshell:middleware:local-guard".into()), + allow_insecure_transport: false, + max_payload_bytes: 262_144, timeout: Some("2s".into()), }] ); let registration = - SupervisorMiddlewareService::from(&file.openshell.supervisor.middleware[0]); + SupervisorMiddlewareService::try_from(&file.openshell.supervisor.middleware[0]) + .expect("valid CA resolves"); assert_eq!(registration.timeout, "2s"); + assert_eq!( + registration.tls_ca_cert_pem, + certificate.cert.pem().as_bytes() + ); + assert_eq!( + registration.audience, + "urn:openshell:middleware:local-guard" + ); + } + + #[test] + fn middleware_registration_defaults_audience_to_name() { + let mut config = MiddlewareServiceFileConfig { + name: "local-guard".into(), + grpc_endpoint: "https://guard.example:50051".into(), + tls_ca_cert_path: None, + audience: None, + allow_insecure_transport: false, + max_payload_bytes: 262_144, + timeout: None, + }; + + let registration = SupervisorMiddlewareService::try_from(&config).unwrap(); + assert_eq!( + registration.audience, + "urn:openshell:extension:middleware:local-guard" + ); + assert!(registration.tls_ca_cert_pem.is_empty()); + + config.audience = Some(String::new()); + let registration = SupervisorMiddlewareService::try_from(&config).unwrap(); + assert_eq!( + registration.audience, + "urn:openshell:extension:middleware:local-guard" + ); + } + + #[test] + fn middleware_registration_rejects_invalid_ca_pem() { + let mut ca = tempfile::Builder::new() + .suffix(".pem") + .tempfile() + .expect("CA tempfile"); + ca.write_all(b"not a certificate").expect("write CA"); + let config = MiddlewareServiceFileConfig { + name: "local-guard".into(), + grpc_endpoint: "https://guard.example:50051".into(), + tls_ca_cert_path: Some(ca.path().to_path_buf()), + audience: None, + allow_insecure_transport: false, + max_payload_bytes: 262_144, + timeout: None, + }; + + let error = SupervisorMiddlewareService::try_from(&config) + .expect_err("invalid CA must fail before service connection"); + assert!(matches!( + error, + ConfigFileError::MiddlewareTlsCaInvalid { .. } + )); + } + + #[test] + fn middleware_registration_rejects_ca_bundle_with_private_key() { + use std::io::Write as _; + + let certificate = + rcgen::generate_simple_self_signed(vec!["localhost".into()]).expect("test certificate"); + let mut ca = tempfile::Builder::new() + .suffix(".pem") + .tempfile() + .expect("CA tempfile"); + ca.write_all(certificate.cert.pem().as_bytes()) + .expect("write certificate"); + ca.write_all(certificate.key_pair.serialize_pem().as_bytes()) + .expect("write private key"); + let config = MiddlewareServiceFileConfig { + name: "local-guard".into(), + grpc_endpoint: "https://guard.example:50051".into(), + tls_ca_cert_path: Some(ca.path().to_path_buf()), + audience: None, + allow_insecure_transport: false, + max_payload_bytes: 262_144, + timeout: None, + }; + + let error = SupervisorMiddlewareService::try_from(&config) + .expect_err("private key material must never be distributed to a sandbox"); + assert!(matches!( + error, + ConfigFileError::MiddlewareTlsCaInvalid { .. } + )); + assert!(error.to_string().contains("non-certificate block")); + } + + #[test] + fn parses_gateway_interceptor_tls_and_audience() { + let tmp = write_tmp( + r#" +[[openshell.gateway.interceptors]] +name = "quota" +grpc_endpoint = "https://quota.example:50051" +tls_ca_cert_path = "/etc/openshell/quota-ca.pem" +audience = "urn:openshell:interceptor:quota" +"#, + ); + + let file = load(tmp.path()).expect("valid interceptor config parses"); + let interceptor = &file.openshell.gateway.interceptors[0]; + assert_eq!( + interceptor.tls_ca_cert_path.as_deref(), + Some(Path::new("/etc/openshell/quota-ca.pem")) + ); + assert_eq!( + interceptor.resolved_audience(), + "urn:openshell:interceptor:quota" + ); + } + + #[test] + fn parses_legacy_supervisor_middleware_payload_limit() { + let toml = r#" +[[openshell.supervisor.middleware]] +name = "local-guard" +grpc_endpoint = "http://127.0.0.1:50051" +max_body_bytes = 262144 +"#; + let tmp = write_tmp(toml); + let file = load(tmp.path()).expect("legacy middleware registration parses"); + assert_eq!( + file.openshell.supervisor.middleware[0].max_payload_bytes, + 262_144 + ); } #[test] diff --git a/crates/openshell-server/src/grpc/auth_rpc.rs b/crates/openshell-server/src/grpc/auth_rpc.rs index 84ec9b97e4..dca563a715 100644 --- a/crates/openshell-server/src/grpc/auth_rpc.rs +++ b/crates/openshell-server/src/grpc/auth_rpc.rs @@ -16,10 +16,14 @@ use crate::ServerState; use crate::auth::identity::IdentityProvider; use crate::auth::principal::{Principal, SandboxIdentitySource}; use openshell_core::proto::{ - GetCurrentUserRequest, GetCurrentUserResponse, IssueSandboxTokenRequest, - IssueSandboxTokenResponse, RefreshSandboxTokenRequest, RefreshSandboxTokenResponse, Sandbox, + ExtensionServiceCredential, GetCurrentUserRequest, GetCurrentUserResponse, + GetSandboxConfigRequest, IssueSandboxTokenRequest, IssueSandboxTokenResponse, + RefreshSandboxTokenRequest, RefreshSandboxTokenResponse, Sandbox, }; +use openshell_extension_core::{ExtensionAudience, ExtensionCallerKind, MAX_EXTENSION_TOKEN_TTL}; +use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use std::time::Duration; use tonic::{Request, Response, Status}; use tracing::{debug, info, warn}; @@ -109,6 +113,7 @@ pub async fn handle_refresh_sandbox_token( state: &Arc, request: Request, ) -> Result, Status> { + let requested_extension_services = request.get_ref().extension_service_names.clone(); let principal = request .extensions() .get::() @@ -144,6 +149,41 @@ pub async fn handle_refresh_sandbox_token( ensure_sandbox_exists(state, &sandbox.sandbox_id).await?; let minted = issuer.mint(&sandbox.sandbox_id)?; + let extension_credentials = if requested_extension_services.is_empty() { + Vec::new() + } else if !state + .extension_mint_limiter + .try_acquire(&sandbox.sandbox_id) + { + // Minting resolves the sandbox's effective policy, so an unbounded + // caller could impose real gateway cost from inside a sandbox. The + // supervisor keeps its last-known-good slots on error and retries at + // its normal cadence, so refusing is safe. + warn!( + sandbox_id = %sandbox.sandbox_id, + "extension credential minting rate limit exceeded" + ); + return Err(Status::resource_exhausted( + "extension credential minting rate limit exceeded for this sandbox", + )); + } else { + let mut config_request = Request::new(GetSandboxConfigRequest { + sandbox_id: sandbox.sandbox_id.clone(), + }); + config_request + .extensions_mut() + .insert(Principal::Sandbox(sandbox.clone())); + let available = super::policy::handle_get_sandbox_config(state, config_request) + .await? + .into_inner() + .supervisor_middleware_services; + mint_extension_credentials( + issuer, + &sandbox.sandbox_id, + &requested_extension_services, + &available, + )? + }; info!( sandbox_id = %sandbox.sandbox_id, "renewed gateway sandbox JWT" @@ -152,9 +192,81 @@ pub async fn handle_refresh_sandbox_token( Ok(Response::new(RefreshSandboxTokenResponse { token: minted.token, expires_at_ms: minted.expires_at_ms, + extension_credentials, })) } +const MAX_EXTENSION_CREDENTIALS_PER_REFRESH: usize = 64; +const DEFAULT_EXTENSION_TOKEN_TTL: Duration = Duration::from_secs(15 * 60); + +#[allow(clippy::result_large_err)] +fn mint_extension_credentials( + issuer: &crate::auth::sandbox_jwt::SandboxJwtIssuer, + sandbox_id: &str, + requested_names: &[String], + available_services: &[openshell_core::proto::SupervisorMiddlewareService], +) -> Result, Status> { + if requested_names.len() > MAX_EXTENSION_CREDENTIALS_PER_REFRESH { + return Err(Status::invalid_argument(format!( + "at most {MAX_EXTENSION_CREDENTIALS_PER_REFRESH} extension credentials may be requested" + ))); + } + let mut unique = HashSet::with_capacity(requested_names.len()); + for name in requested_names { + if name.is_empty() { + return Err(Status::invalid_argument( + "extension service names must not be empty", + )); + } + if !unique.insert(name.as_str()) { + return Err(Status::invalid_argument(format!( + "duplicate extension service name '{name}'" + ))); + } + } + + let available: HashMap<&str, &openshell_core::proto::SupervisorMiddlewareService> = + available_services + .iter() + .map(|service| (service.name.as_str(), service)) + .collect(); + let ttl = if issuer.ttl().is_zero() { + DEFAULT_EXTENSION_TOKEN_TTL + } else { + issuer.ttl().min(MAX_EXTENSION_TOKEN_TTL) + }; + + requested_names + .iter() + .map(|name| { + let service = available.get(name.as_str()).ok_or_else(|| { + Status::permission_denied(format!( + "extension service '{name}' is not selected by the sandbox policy" + )) + })?; + if service.allow_insecure_transport { + return Err(Status::failed_precondition(format!( + "extension service '{name}' opted out of extension authentication; \ + no credential is minted for it" + ))); + } + let audience = ExtensionAudience::new(service.audience.clone()) + .map_err(|error| Status::failed_precondition(error.to_string()))?; + let minted = issuer.mint_extension_token( + &audience, + ExtensionCallerKind::Supervisor, + Some(sandbox_id), + ttl, + )?; + Ok(ExtensionServiceCredential { + service_name: name.clone(), + token: minted.token, + expires_at_ms: minted.expires_at_ms, + }) + }) + .collect() +} + async fn ensure_sandbox_exists(state: &Arc, sandbox_id: &str) -> Result<(), Status> { if sandbox_id.is_empty() { return Err(Status::invalid_argument("sandbox_id is required")); @@ -284,7 +396,9 @@ mod tests { #[tokio::test] async fn refresh_returns_new_token() { let state = state_with_issuer().await; - let mut req = Request::new(RefreshSandboxTokenRequest {}); + let mut req = Request::new(RefreshSandboxTokenRequest { + extension_service_names: Vec::new(), + }); req.extensions_mut().insert(sandbox_principal("sandbox-a")); let resp = handle_refresh_sandbox_token(&state, req) .await @@ -294,10 +408,99 @@ mod tests { assert!(resp.expires_at_ms > 0); } + #[tokio::test] + async fn extension_credentials_are_minted_only_for_selected_registration_names() { + let state = state_with_issuer().await; + let issuer = state.sandbox_jwt_issuer.as_deref().expect("issuer"); + let available = vec![openshell_core::proto::SupervisorMiddlewareService { + name: "content-guard".to_string(), + audience: "urn:example:content-guard".to_string(), + ..Default::default() + }]; + + let credentials = mint_extension_credentials( + issuer, + "sandbox-a", + &["content-guard".to_string()], + &available, + ) + .expect("selected service credential"); + assert_eq!(credentials.len(), 1); + assert_eq!(credentials[0].service_name, "content-guard"); + assert!(!credentials[0].token.is_empty()); + assert!(credentials[0].expires_at_ms > 0); + + let error = mint_extension_credentials( + issuer, + "sandbox-a", + &["attacker-chosen-audience".to_string()], + &available, + ) + .expect_err("unselected name must be rejected"); + assert_eq!(error.code(), tonic::Code::PermissionDenied); + } + + #[tokio::test] + async fn refresh_refuses_extension_credentials_past_the_per_sandbox_bound() { + let state = state_with_issuer().await; + // The gateway credential path is unaffected; only requests that carry + // extension service names consume the bound. + for _ in 0..10 { + assert!(state.extension_mint_limiter.try_acquire("sandbox-a")); + } + assert!(!state.extension_mint_limiter.try_acquire("sandbox-a")); + assert!(state.extension_mint_limiter.try_acquire("sandbox-b")); + } + + #[tokio::test] + async fn opted_out_registrations_never_receive_a_minted_credential() { + let state = state_with_issuer().await; + let issuer = state.sandbox_jwt_issuer.as_deref().expect("issuer"); + let available = vec![openshell_core::proto::SupervisorMiddlewareService { + name: "legacy-guard".to_string(), + audience: "urn:example:legacy-guard".to_string(), + allow_insecure_transport: true, + ..Default::default() + }]; + + // The registration is policy-selected, so authorization passes; the + // opt-out is what withholds the credential. A supervisor must not be + // able to obtain a bearer token it would then send over plaintext. + let error = mint_extension_credentials( + issuer, + "sandbox-a", + &["legacy-guard".to_string()], + &available, + ) + .expect_err("opted-out registration must not mint a credential"); + assert_eq!(error.code(), tonic::Code::FailedPrecondition); + } + + #[tokio::test] + async fn extension_credential_request_rejects_duplicate_names_atomically() { + let state = state_with_issuer().await; + let issuer = state.sandbox_jwt_issuer.as_deref().expect("issuer"); + let available = vec![openshell_core::proto::SupervisorMiddlewareService { + name: "content-guard".to_string(), + audience: "urn:example:content-guard".to_string(), + ..Default::default() + }]; + let error = mint_extension_credentials( + issuer, + "sandbox-a", + &["content-guard".to_string(), "content-guard".to_string()], + &available, + ) + .expect_err("duplicates must be rejected"); + assert_eq!(error.code(), tonic::Code::InvalidArgument); + } + #[tokio::test] async fn refresh_rejects_missing_sandbox() { let state = state_with_issuer().await; - let mut req = Request::new(RefreshSandboxTokenRequest {}); + let mut req = Request::new(RefreshSandboxTokenRequest { + extension_service_names: Vec::new(), + }); req.extensions_mut() .insert(sandbox_principal("sandbox-deleted")); let err = handle_refresh_sandbox_token(&state, req) @@ -354,7 +557,9 @@ mod tests { async fn refresh_rejects_user_principal() { use crate::auth::identity::{Identity, IdentityProvider}; let state = state_with_issuer().await; - let mut req = Request::new(RefreshSandboxTokenRequest {}); + let mut req = Request::new(RefreshSandboxTokenRequest { + extension_service_names: Vec::new(), + }); req.extensions_mut().insert(Principal::User(UserPrincipal { identity: Identity { subject: "alice".to_string(), @@ -377,7 +582,9 @@ mod tests { // gateway-minted JWT exists. use crate::auth::principal::SandboxIdentitySource; let state = state_with_issuer().await; - let mut req = Request::new(RefreshSandboxTokenRequest {}); + let mut req = Request::new(RefreshSandboxTokenRequest { + extension_service_names: Vec::new(), + }); req.extensions_mut() .insert(Principal::Sandbox(SandboxPrincipal { sandbox_id: "sandbox-a".to_string(), @@ -416,7 +623,9 @@ mod tests { None, )); insert_sandbox(&state, "sandbox-a").await; - let mut req = Request::new(RefreshSandboxTokenRequest {}); + let mut req = Request::new(RefreshSandboxTokenRequest { + extension_service_names: Vec::new(), + }); req.extensions_mut().insert(sandbox_principal("sandbox-a")); let err = handle_refresh_sandbox_token(&state, req) .await diff --git a/crates/openshell-server/src/grpc/mod.rs b/crates/openshell-server/src/grpc/mod.rs index a0ea195442..2c52acbe12 100644 --- a/crates/openshell-server/src/grpc/mod.rs +++ b/crates/openshell-server/src/grpc/mod.rs @@ -753,7 +753,9 @@ pub mod test_support { use crate::ServerState; use crate::auth::identity::{Identity, IdentityProvider}; use crate::auth::principal::{Principal, UserPrincipal}; - use crate::compute::{new_test_runtime, new_test_runtime_for_driver}; + use crate::compute::{ + NoopTestDriver, new_test_runtime, new_test_runtime_for_driver, new_test_runtime_with_driver, + }; use crate::persistence::Store; use crate::sandbox_index::SandboxIndex; use crate::sandbox_watch::SandboxWatchBus; @@ -813,6 +815,33 @@ pub mod test_support { None, )) } + + /// Build a test state whose compute driver fails the requested number of + /// workspace cleanup calls before succeeding. + pub async fn test_server_state_with_workspace_cleanup_failures( + failures: usize, + ) -> Arc { + let store = Arc::new( + Store::connect("sqlite::memory:?cache=shared") + .await + .unwrap(), + ); + crate::ensure_default_workspace(&store).await.unwrap(); + let driver = Arc::new(NoopTestDriver::failing_workspace_deletes(failures)); + let compute = new_test_runtime_with_driver(store.clone(), "test", driver).await; + Arc::new(ServerState::new( + Config::new(None) + .with_database_url("sqlite::memory:?cache=shared") + .with_credential_drivers(["test-static"]), + store, + compute, + SandboxIndex::new(), + SandboxWatchBus::new(), + TracingLogBus::new(), + Arc::new(SupervisorSessionRegistry::new()), + None, + )) + } } // --------------------------------------------------------------------------- diff --git a/crates/openshell-server/src/grpc/policy.rs b/crates/openshell-server/src/grpc/policy.rs index 9f8a43a992..3b841e66a5 100644 --- a/crates/openshell-server/src/grpc/policy.rs +++ b/crates/openshell-server/src/grpc/policy.rs @@ -1902,6 +1902,7 @@ pub(super) async fn handle_get_sandbox_config( policy_source, &supervisor_middleware_services, state.config.policy_validation_failure_mode, + state.sandbox_jwt_issuer.is_some(), ); let policy_credential_bindings = policy_static_credential_endpoint_bindings(policy.as_ref())?; if let Some(policy) = policy.as_ref() { @@ -1939,6 +1940,7 @@ pub(super) async fn handle_get_sandbox_config( .policy_validation_failure_mode .as_str() .to_string(), + extension_authentication_enabled: state.sandbox_jwt_issuer.is_some(), })) } @@ -4431,10 +4433,12 @@ fn compute_config_revision_with_validation_mode( policy_source: PolicySource, supervisor_middleware_services: &[openshell_core::proto::SupervisorMiddlewareService], policy_validation_failure_mode: openshell_core::PolicyValidationFailureMode, + extension_authentication_enabled: bool, ) -> u64 { let mut hasher = Sha256::new(); hasher.update((policy_source as i32).to_le_bytes()); hasher.update(policy_validation_failure_mode.as_str().as_bytes()); + hasher.update([u8::from(extension_authentication_enabled)]); if let Some(policy) = policy { hasher.update(deterministic_policy_hash(policy).as_bytes()); } @@ -4489,6 +4493,7 @@ fn compute_config_revision( policy_source, supervisor_middleware_services, openshell_core::PolicyValidationFailureMode::default(), + false, ) } @@ -13937,6 +13942,7 @@ mod tests { PolicySource::Sandbox, &[], openshell_core::PolicyValidationFailureMode::FailClosed, + false, ); let retain_last_valid = compute_config_revision_with_validation_mode( Some(&policy), @@ -13944,10 +13950,35 @@ mod tests { PolicySource::Sandbox, &[], openshell_core::PolicyValidationFailureMode::RetainLastValid, + false, ); assert_ne!(fail_closed, retain_last_valid); } + #[test] + fn config_revision_changes_when_extension_authentication_capability_changes() { + let policy = ProtoSandboxPolicy::default(); + let settings = HashMap::new(); + + let disabled = compute_config_revision_with_validation_mode( + Some(&policy), + &settings, + PolicySource::Sandbox, + &[], + openshell_core::PolicyValidationFailureMode::FailClosed, + false, + ); + let enabled = compute_config_revision_with_validation_mode( + Some(&policy), + &settings, + PolicySource::Sandbox, + &[], + openshell_core::PolicyValidationFailureMode::FailClosed, + true, + ); + assert_ne!(disabled, enabled); + } + #[test] fn config_revision_changes_when_supervisor_middleware_services_change() { let policy = ProtoSandboxPolicy::default(); @@ -13955,7 +13986,7 @@ mod tests { let service = openshell_core::proto::SupervisorMiddlewareService { name: "local-guard".into(), grpc_endpoint: "http://127.0.0.1:50051".into(), - max_body_bytes: 1024, + max_payload_bytes: 1024, ..Default::default() }; diff --git a/crates/openshell-server/src/grpc/provider.rs b/crates/openshell-server/src/grpc/provider.rs index 6dc4318a8a..4d67eee018 100644 --- a/crates/openshell-server/src/grpc/provider.rs +++ b/crates/openshell-server/src/grpc/provider.rs @@ -2078,6 +2078,9 @@ pub(super) async fn handle_create_provider( metadata.workspace.clone_from(&workspace); } let provider_type = provider.r#type.clone(); + if state.credentials.stores_provider_credentials() && !provider.credentials.is_empty() { + state.compute.ensure_workspace(&workspace).await?; + } let catalog = state .provider_profile_sources .snapshot_catalog(state.store.as_ref(), &workspace) @@ -3233,6 +3236,9 @@ pub(super) async fn handle_update_provider( provider .credential_expires_at_ms .extend(req.credential_expires_at_ms); + if state.credentials.stores_provider_credentials() && !provider.credentials.is_empty() { + state.compute.ensure_workspace(&workspace).await?; + } let catalog = state .provider_profile_sources .snapshot_catalog(state.store.as_ref(), &workspace) @@ -3648,6 +3654,7 @@ pub(super) async fn handle_rotate_provider_credential( state.store.as_ref(), &workspace, Some(&state.credentials), + Some(&state.compute), provider_name, credential_key, ) diff --git a/crates/openshell-server/src/grpc/workspace.rs b/crates/openshell-server/src/grpc/workspace.rs index a22a195226..d83ffab0e8 100644 --- a/crates/openshell-server/src/grpc/workspace.rs +++ b/crates/openshell-server/src/grpc/workspace.rs @@ -423,6 +423,15 @@ pub(super) async fn handle_delete_workspace( .await .map_err(|e| Status::internal(format!("delete workspace members failed: {e}")))?; + // Keep the terminating workspace durable until platform cleanup has been + // accepted. A failed cleanup can then be retried through this same path. + state.compute.delete_workspace(&name).await.map_err(|e| { + Status::new( + e.code(), + format!("delete workspace platform resources failed: {e}"), + ) + })?; + let deleted = state .store .delete_if(Workspace::object_type(), &ws_id, delete_version) @@ -616,7 +625,9 @@ mod tests { use openshell_core::proto::datamodel::v1::ObjectMeta; use tonic::{Code, Request}; - use crate::grpc::test_support::{authed_request, test_server_state}; + use crate::grpc::test_support::{ + authed_request, test_server_state, test_server_state_with_workspace_cleanup_failures, + }; #[tokio::test] async fn create_workspace_returns_metadata() { @@ -1322,6 +1333,62 @@ mod tests { assert!(resp.deleted); } + #[tokio::test] + async fn delete_workspace_retains_terminating_record_when_platform_cleanup_fails() { + let state = test_server_state_with_workspace_cleanup_failures(1).await; + + handle_create_workspace( + &state, + Request::new(CreateWorkspaceRequest { + name: "cleanup-retry".to_string(), + labels: HashMap::new(), + }), + ) + .await + .unwrap(); + + let err = handle_delete_workspace( + &state, + Request::new(DeleteWorkspaceRequest { + name: "cleanup-retry".to_string(), + }), + ) + .await + .unwrap_err(); + assert_eq!(err.code(), Code::Unavailable); + + let retained: Workspace = state + .store + .get_message_by_name("", "cleanup-retry") + .await + .unwrap() + .expect("workspace must remain durable after cleanup failure"); + assert_ne!( + retained.metadata.unwrap().deletion_timestamp_ms, + 0, + "retained workspace must remain terminating" + ); + + let retry = handle_delete_workspace( + &state, + Request::new(DeleteWorkspaceRequest { + name: "cleanup-retry".to_string(), + }), + ) + .await + .unwrap() + .into_inner(); + assert!(retry.deleted); + assert!( + state + .store + .get_message_by_name::("", "cleanup-retry") + .await + .unwrap() + .is_none() + ); + } + #[tokio::test] async fn create_workspace_persists_labels_for_selector() { let state = test_server_state().await; diff --git a/crates/openshell-server/src/lib.rs b/crates/openshell-server/src/lib.rs index 8ecf69a7a1..a6031a9bc6 100644 --- a/crates/openshell-server/src/lib.rs +++ b/crates/openshell-server/src/lib.rs @@ -60,14 +60,17 @@ mod ws_tunnel; use metrics_exporter_prometheus::PrometheusBuilder; use openshell_core::net::set_tcp_nodelay_best_effort; use openshell_core::{ComputeDriverKind, Config, Error, ObjectLabels, Result}; +use openshell_extension_core::{ + BearerTokenSlot, ExtensionAudience, ExtensionCallerKind, ExtensionKind, MAX_EXTENSION_TOKEN_TTL, +}; use openshell_supervisor_middleware::MiddlewareRegistry; -use std::collections::HashMap; +use std::collections::{BTreeMap, HashMap}; use std::io::ErrorKind; use std::net::SocketAddr; #[cfg(test)] use std::sync::LazyLock; use std::sync::{Arc, Mutex}; -use std::time::Duration; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::net::{TcpListener, TcpStream}; use tokio::sync::watch; use tracing::{debug, error, info, warn}; @@ -83,6 +86,158 @@ use compute::ComputeRuntime; use gateway_listener::{BoundGatewayListener, GatewayListenerScope, bind_gateway_listeners}; pub use grpc::OpenShellService; pub use http::{health_router, http_router, metrics_router, service_http_router}; + +/// Deriving `Debug` is safe here: `BearerTokenSlot` renders only its expiry, +/// and an extension audience is configuration rather than secret material. +#[derive(Debug)] +struct GatewayExtensionCredential { + name: String, + audience: ExtensionAudience, + slot: BearerTokenSlot, + ttl: Duration, +} + +fn extension_token_ttl(issuer: &auth::sandbox_jwt::SandboxJwtIssuer) -> Duration { + if issuer.ttl().is_zero() { + Duration::from_secs(15 * 60) + } else { + issuer.ttl().min(MAX_EXTENSION_TOKEN_TTL) + } +} + +/// Mint the gateway-caller credential for one extension registration. +/// +/// Returns `Ok(None)` when the operator has explicitly opted the registration +/// out of extension authentication. The opt-out is deliberately loud: it +/// downgrades a security boundary, so it is reported once per registration at +/// startup rather than being silently tolerated. +fn mint_gateway_extension_credential( + issuer: &Arc, + kind: ExtensionKind, + name: &str, + audience: &str, + endpoint: &str, + allow_insecure_transport: bool, +) -> Result> { + // A middleware endpoint must be reachable from sandbox supervisors, so a + // gateway-local Unix socket is only an option for interceptors. + let (accepted, supports_unix) = match kind { + ExtensionKind::Middleware => ("https://", false), + ExtensionKind::Interceptor => ("https:// or unix://", true), + _ => { + return Err(Error::config(format!( + "extension kind '{kind}' is not supported by gateway authentication" + ))); + } + }; + if allow_insecure_transport { + warn!( + extension = %name, + endpoint = %endpoint, + "extension authentication is DISABLED for this registration by \ + allow_insecure_transport; OpenShell attaches no caller credential \ + and the service cannot distinguish OpenShell from any other \ + network client. Use {accepted} with the opt-out removed outside \ + trusted-network development deployments." + ); + return Ok(None); + } + let transport_supported = + endpoint.starts_with("https://") || (supports_unix && endpoint.starts_with("unix://")); + if !transport_supported { + return Err(Error::config(format!( + "authenticated {kind} '{name}' must use {accepted}; set \ + allow_insecure_transport = true to opt this registration out of \ + extension authentication instead" + ))); + } + let audience = ExtensionAudience::new(audience.to_string()).map_err(|error| { + Error::config(format!( + "extension '{name}' has an invalid audience: {error}" + )) + })?; + let ttl = extension_token_ttl(issuer); + let minted = issuer + .mint_extension_token(&audience, ExtensionCallerKind::Gateway, None, ttl) + .map_err(|status| { + Error::config(format!( + "failed to mint credential for extension '{name}': {}", + status.message() + )) + })?; + let slot = BearerTokenSlot::new(&minted.token, minted.expires_at_ms).map_err(|error| { + Error::config(format!( + "failed to install credential for extension '{name}': {error}" + )) + })?; + Ok(Some(GatewayExtensionCredential { + name: name.to_string(), + audience, + slot, + ttl, + })) +} + +fn spawn_gateway_extension_token_refresh( + issuer: Arc, + credentials: Vec, +) { + if credentials.is_empty() { + return; + } + tokio::spawn(async move { + loop { + let now_ms = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |duration| { + i64::try_from(duration.as_millis()).unwrap_or(i64::MAX) + }); + let remaining_ms = credentials + .iter() + .filter_map(|credential| credential.slot.expires_at_ms()) + .min() + .map_or(60_000, |expiry_ms| expiry_ms.saturating_sub(now_ms)); + let refresh_delay = if remaining_ms <= 0 { + Duration::from_millis(100) + } else { + Duration::from_millis( + u64::try_from(remaining_ms) + .unwrap_or(u64::MAX) + .saturating_mul(4) + .checked_div(5) + .unwrap_or(100) + .max(100), + ) + }; + tokio::time::sleep(refresh_delay).await; + for credential in &credentials { + match issuer.mint_extension_token( + &credential.audience, + ExtensionCallerKind::Gateway, + None, + credential.ttl, + ) { + Ok(minted) => { + if let Err(error) = + credential.slot.update(&minted.token, minted.expires_at_ms) + { + warn!( + extension = %credential.name, + error = %error, + "failed to rotate gateway extension credential" + ); + } + } + Err(status) => warn!( + extension = %credential.name, + error = %status, + "failed to mint gateway extension credential" + ), + } + } + } + }); +} pub use multiplex::{MultiplexService, MultiplexedService}; pub use persistence::Store; use sandbox_index::SandboxIndex; @@ -167,6 +322,10 @@ pub struct ServerState { /// Gateway-wide gRPC request rate limiter shared by every multiplex path. pub(crate) grpc_rate_limiter: Option, + /// Per-sandbox bound on extension credential minting, which resolves the + /// caller's effective policy on every request. + pub(crate) extension_mint_limiter: auth::extension_mint_limit::ExtensionMintLimiter, + /// Immutable gateway interceptor execution plan. `None` when disabled. pub(crate) gateway_interceptors: Option, @@ -254,6 +413,7 @@ impl ServerState { ssh_connections_by_sandbox: Mutex::new(HashMap::new()), settings_mutex: tokio::sync::Mutex::new(()), supervisor_sessions, + extension_mint_limiter: auth::extension_mint_limit::ExtensionMintLimiter::default(), middleware_registry: Arc::new(MiddlewareRegistry::default()), oidc_cache, sandbox_jwt_issuer: None, @@ -284,6 +444,7 @@ pub(crate) async fn run_server( config_file, guest_tls, } = startup; + let (shutdown_tx, shutdown_rx) = watch::channel(false); auth::descriptor_authz::init() .map_err(|error| Error::config(format!("invalid gRPC authorization metadata: {error}")))?; @@ -293,6 +454,60 @@ pub(crate) async fn run_server( return Err(Error::config("database_url is required")); } + // Load signing material before connecting remote extensions so their + // startup Describe calls can authenticate with gateway-caller tokens. + let (sandbox_jwt_issuer, sandbox_jwt_authenticator) = if let Some(ref jwt) = config.gateway_jwt + { + let signing_pem = std::fs::read(&jwt.signing_key_path).map_err(|e| { + Error::config(format!( + "failed to read sandbox JWT signing key from {}: {e}", + jwt.signing_key_path.display() + )) + })?; + let public_pem = std::fs::read(&jwt.public_key_path).map_err(|e| { + Error::config(format!( + "failed to read sandbox JWT public key from {}: {e}", + jwt.public_key_path.display() + )) + })?; + let kid = std::fs::read_to_string(&jwt.kid_path) + .map_err(|e| { + Error::config(format!( + "failed to read sandbox JWT kid from {}: {e}", + jwt.kid_path.display() + )) + })? + .trim() + .to_string(); + if kid.is_empty() { + return Err(Error::config(format!( + "sandbox JWT kid file {} is empty", + jwt.kid_path.display() + ))); + } + let issuer = Arc::new( + auth::sandbox_jwt::SandboxJwtIssuer::from_pem( + &signing_pem, + kid.clone(), + &jwt.gateway_id, + Duration::from_secs(jwt.ttl_secs), + ) + .map_err(Error::config)?, + ); + let authenticator = Arc::new( + auth::sandbox_jwt::SandboxJwtAuthenticator::from_pem(&public_pem, kid, &jwt.gateway_id) + .map_err(Error::config)?, + ); + info!( + gateway_id = %jwt.gateway_id, + ttl_secs = jwt.ttl_secs, + "gateway-minted sandbox JWT enabled" + ); + (Some(issuer), Some(authenticator)) + } else { + (None, None) + }; + let middleware_registrations = config_file .as_ref() .map(|file| { @@ -300,16 +515,42 @@ pub(crate) async fn run_server( .supervisor .middleware .iter() - .map(Into::into) - .collect() + .map(openshell_core::proto::SupervisorMiddlewareService::try_from) + .collect::, _>>() }) + .transpose() + .map_err(|error| Error::config(format!("middleware registration failed: {error}")))? .unwrap_or_default(); + let mut gateway_extension_credentials = Vec::new(); let middleware_registry = Arc::new( - MiddlewareRegistry::connect_services( - openshell_supervisor_middleware_builtins::services(), - middleware_registrations, - ) - .await + if let Some(issuer) = sandbox_jwt_issuer.as_ref() { + let mut slots = HashMap::new(); + for registration in &middleware_registrations { + if let Some(credential) = mint_gateway_extension_credential( + issuer, + ExtensionKind::Middleware, + ®istration.name, + ®istration.audience, + ®istration.grpc_endpoint, + registration.allow_insecure_transport, + )? { + slots.insert(registration.name.clone(), credential.slot.clone()); + gateway_extension_credentials.push(credential); + } + } + MiddlewareRegistry::connect_services_authenticated( + openshell_supervisor_middleware_builtins::services(), + middleware_registrations, + &slots, + ) + .await + } else { + MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + middleware_registrations, + ) + .await + } .map_err(|error| Error::config(format!("middleware registration failed: {error}")))?, ); @@ -349,7 +590,7 @@ pub(crate) async fn run_server( gateway_tls_enabled: config.tls.is_some(), endpoint_overrides: &config.compute_driver_endpoints, }; - let compute = build_compute_runtime( + let (compute, operator_allowlist) = build_compute_runtime( &config, driver_startup, store.clone(), @@ -357,14 +598,34 @@ pub(crate) async fn run_server( sandbox_watch_bus.clone(), tracing_log_bus.clone(), supervisor_sessions.clone(), + shutdown_rx.clone(), ) .await?; - let gateway_interceptors = - openshell_gateway_interceptors::initialize(config.gateway_interceptors.clone()) - .await - .map_err(|e| { - Error::config(format!("gateway interceptor initialization failed: {e}")) - })?; + let gateway_interceptors = if let Some(issuer) = sandbox_jwt_issuer.as_ref() { + let mut slots = BTreeMap::new(); + for interceptor in &config.gateway_interceptors { + let audience = interceptor.resolved_audience(); + if let Some(credential) = mint_gateway_extension_credential( + issuer, + ExtensionKind::Interceptor, + &interceptor.name, + audience.as_ref(), + &interceptor.grpc_endpoint, + interceptor.allow_insecure_transport, + )? { + slots.insert(interceptor.name.clone(), credential.slot.clone()); + gateway_extension_credentials.push(credential); + } + } + openshell_gateway_interceptors::initialize_authenticated( + config.gateway_interceptors.clone(), + slots, + ) + .await + } else { + openshell_gateway_interceptors::initialize(config.gateway_interceptors.clone()).await + } + .map_err(|e| Error::config(format!("gateway interceptor initialization failed: {e}")))?; let provider_profile_sources = provider_profile_sources::ProviderProfileSources::from_config( &config.provider_profile_sources, gateway_interceptors.as_ref(), @@ -392,56 +653,10 @@ pub(crate) async fn run_server( state.middleware_registry = middleware_registry; state.gateway_interceptors = gateway_interceptors; state.provider_profile_sources = provider_profile_sources; - - // Load the gateway-minted sandbox JWT signing key when configured. - // Optional so single-driver dev deployments without certgen continue - // to start. The helm-deployed gateway and the RPM init script populate - // `gateway_jwt` once `certgen` has produced the on-disk material. - if let Some(ref jwt) = config.gateway_jwt { - let signing_pem = std::fs::read(&jwt.signing_key_path).map_err(|e| { - Error::config(format!( - "failed to read sandbox JWT signing key from {}: {e}", - jwt.signing_key_path.display() - )) - })?; - let public_pem = std::fs::read(&jwt.public_key_path).map_err(|e| { - Error::config(format!( - "failed to read sandbox JWT public key from {}: {e}", - jwt.public_key_path.display() - )) - })?; - let kid = std::fs::read_to_string(&jwt.kid_path) - .map_err(|e| { - Error::config(format!( - "failed to read sandbox JWT kid from {}: {e}", - jwt.kid_path.display() - )) - })? - .trim() - .to_string(); - if kid.is_empty() { - return Err(Error::config(format!( - "sandbox JWT kid file {} is empty", - jwt.kid_path.display() - ))); - } - let issuer = auth::sandbox_jwt::SandboxJwtIssuer::from_pem( - &signing_pem, - kid.clone(), - &jwt.gateway_id, - Duration::from_secs(jwt.ttl_secs), - ) - .map_err(Error::config)?; - let authenticator = - auth::sandbox_jwt::SandboxJwtAuthenticator::from_pem(&public_pem, kid, &jwt.gateway_id) - .map_err(Error::config)?; - info!( - gateway_id = %jwt.gateway_id, - ttl_secs = jwt.ttl_secs, - "gateway-minted sandbox JWT enabled" - ); - state.sandbox_jwt_issuer = Some(Arc::new(issuer)); - state.sandbox_jwt_authenticator = Some(Arc::new(authenticator)); + state.sandbox_jwt_issuer = sandbox_jwt_issuer.clone(); + state.sandbox_jwt_authenticator = sandbox_jwt_authenticator; + if let Some(issuer) = sandbox_jwt_issuer { + spawn_gateway_extension_token_refresh(issuer, gateway_extension_credentials); } // K8s ServiceAccount bootstrap authenticator. Only constructed when @@ -457,13 +672,29 @@ pub(crate) async fn run_server( compute::driver_config::builtin::kubernetes_config_for_k8s_sa_bootstrap( config_file.as_ref(), )?; - let sandbox_namespace = kubernetes_config.namespace; - let sandbox_service_account = kubernetes_config.service_account_name; + let sandbox_namespace = kubernetes_config.namespace.clone(); + let sandbox_service_account = kubernetes_config.service_account_name.clone(); + let namespace_validator = match kubernetes_config.workspace_mode { + openshell_driver_kubernetes::WorkspaceMode::Shared => { + auth::k8s_sa::NamespaceValidator::Exact(kubernetes_config.namespace) + } + openshell_driver_kubernetes::WorkspaceMode::Managed => { + auth::k8s_sa::NamespaceValidator::Prefix( + openshell_driver_kubernetes::managed_namespace_prefix( + &kubernetes_config.gateway_id, + ), + ) + } + openshell_driver_kubernetes::WorkspaceMode::Operator => { + let allowlist = operator_allowlist.clone().unwrap_or_default(); + auth::k8s_sa::NamespaceValidator::Allowlist(allowlist) + } + }; match kube::Client::try_default().await { Ok(client) => { let resolver = Arc::new(auth::k8s_sa::LiveK8sResolver::new( client, - &sandbox_namespace, + namespace_validator, "openshell-gateway".to_string(), sandbox_service_account.clone(), )); @@ -485,8 +716,6 @@ pub(crate) async fn run_server( let state = Arc::new(state); - let (shutdown_tx, shutdown_rx) = watch::channel(false); - // Start sandboxes that were stopped during the previous gateway // shutdown so the running compute state matches the persisted store. // Runs before watchers spawn so the watch loop sees the post-start @@ -853,6 +1082,9 @@ fn unsupported_builtin_compute_driver(driver: ComputeDriverKind) -> compute::Com // Internal wiring helper: each argument is a distinct piece of runtime state // that must be passed through, so the count is justified. +#[allow(clippy::too_many_arguments)] +type OperatorAllowlistArc = Option; + #[allow(clippy::too_many_arguments)] async fn build_compute_runtime( config: &Config, @@ -862,33 +1094,41 @@ async fn build_compute_runtime( sandbox_watch_bus: SandboxWatchBus, tracing_log_bus: TracingLogBus, supervisor_sessions: Arc, -) -> Result { + shutdown_rx: watch::Receiver, +) -> Result<(ComputeRuntime, OperatorAllowlistArc)> { let driver = configured_compute_driver(config, driver_startup)?; info!(driver = %driver.name(), "Using compute driver"); - let runtime = match driver { + let (runtime, operator_allowlist) = match driver { #[cfg(target_os = "windows")] - ConfiguredComputeDriver::Builtin(driver) => Err(unsupported_builtin_compute_driver(driver)), + ConfiguredComputeDriver::Builtin(driver) => { + return Err(Error::execution( + unsupported_builtin_compute_driver(driver).to_string(), + )); + } #[cfg(not(target_os = "windows"))] ConfiguredComputeDriver::Builtin(ComputeDriverKind::Kubernetes) => { warn_if_kubernetes_sandbox_jwt_expiry_disabled(config); let k8s_config = compute::driver_config::builtin::kubernetes_config_from_context(driver_startup)?; - ComputeRuntime::new_kubernetes( + let (rt, allowlist) = ComputeRuntime::new_kubernetes( k8s_config, store, sandbox_index, sandbox_watch_bus, tracing_log_bus, supervisor_sessions.clone(), + shutdown_rx, ) .await + .map_err(|e| Error::execution(format!("failed to create compute runtime: {e}")))?; + (rt, allowlist) } #[cfg(not(target_os = "windows"))] ConfiguredComputeDriver::Builtin(ComputeDriverKind::Docker) => { let docker_config = compute::driver_config::builtin::docker_config_from_context(driver_startup)?; - ComputeRuntime::new_docker( + let rt = ComputeRuntime::new_docker( config.clone(), docker_config, store, @@ -898,12 +1138,14 @@ async fn build_compute_runtime( supervisor_sessions, ) .await + .map_err(|e| Error::execution(format!("failed to create compute runtime: {e}")))?; + (rt, None) } #[cfg(not(target_os = "windows"))] ConfiguredComputeDriver::Builtin(ComputeDriverKind::Podman) => { let podman_config = compute::driver_config::builtin::podman_config_from_context(driver_startup)?; - ComputeRuntime::new_podman( + let rt = ComputeRuntime::new_podman( podman_config, store, sandbox_index, @@ -912,6 +1154,8 @@ async fn build_compute_runtime( supervisor_sessions, ) .await + .map_err(|e| Error::execution(format!("failed to create compute runtime: {e}")))?; + (rt, None) } #[cfg(not(target_os = "windows"))] ConfiguredComputeDriver::Builtin(ComputeDriverKind::Vm) => { @@ -921,7 +1165,7 @@ async fn build_compute_runtime( .file .and_then(|file| file.openshell.gateway.otlp.as_ref()); let endpoint = compute::vm::spawn(config, &vm_config, otlp_config).await?; - ComputeRuntime::new_remote_driver( + let rt = ComputeRuntime::new_remote_driver( endpoint, store, sandbox_index, @@ -930,6 +1174,8 @@ async fn build_compute_runtime( supervisor_sessions, ) .await + .map_err(|e| Error::execution(format!("failed to create compute runtime: {e}")))?; + (rt, None) } ConfiguredComputeDriver::Remote { name } => { let remote_config = @@ -942,7 +1188,7 @@ async fn build_compute_runtime( let endpoint = compute::connect_remote_compute_driver(name, &remote_config.socket_path) .await .map_err(|e| Error::execution(format!("failed to create compute runtime: {e}")))?; - ComputeRuntime::new_remote_driver( + let rt = ComputeRuntime::new_remote_driver( endpoint, store, sandbox_index, @@ -951,10 +1197,12 @@ async fn build_compute_runtime( supervisor_sessions, ) .await + .map_err(|e| Error::execution(format!("failed to create compute runtime: {e}")))?; + (rt, None) } }; - runtime.map_err(|e| Error::execution(format!("failed to create compute runtime: {e}"))) + Ok((runtime, operator_allowlist)) } #[derive(Debug, Clone)] @@ -1096,10 +1344,11 @@ pub(crate) async fn ensure_default_workspace(store: &Store) -> Result<()> { #[cfg(test)] mod tests { use super::{ - BoundGatewayListener, ConfiguredComputeDriver, ConnectionProtocol, GatewayListenerScope, - MultiplexService, ServerState, TlsAcceptor, allow_plaintext_service_http, - bind_gateway_listeners, classify_initial_bytes, configured_compute_driver, - is_benign_tls_handshake_failure, kubernetes_sandbox_jwt_expiry_disabled, + BoundGatewayListener, ConfiguredComputeDriver, ConnectionProtocol, ExtensionKind, + GatewayListenerScope, MultiplexService, ServerState, TlsAcceptor, + allow_plaintext_service_http, bind_gateway_listeners, classify_initial_bytes, + configured_compute_driver, is_benign_tls_handshake_failure, + kubernetes_sandbox_jwt_expiry_disabled, mint_gateway_extension_credential, serve_gateway_listener, }; use openshell_core::{ @@ -1124,6 +1373,94 @@ mod tests { tls_test_utils::{generate_test_certs_with_ca, install_rustls_provider}, }; + fn extension_test_issuer() -> Arc { + let material = openshell_bootstrap::jwt::generate_jwt_key().expect("jwt key"); + Arc::new( + crate::auth::sandbox_jwt::SandboxJwtIssuer::from_pem( + material.signing_key_pem.as_bytes(), + material.kid, + "gateway-a", + Duration::from_secs(900), + ) + .expect("issuer"), + ) + } + + #[test] + fn plaintext_extension_endpoint_is_rejected_unless_explicitly_opted_out() { + let issuer = extension_test_issuer(); + + // Default posture: a plaintext endpoint cannot carry a bearer + // credential, so startup fails and names the opt-out. + let error = mint_gateway_extension_credential( + &issuer, + ExtensionKind::Middleware, + "content-guard", + "urn:openshell:extension:middleware:content-guard", + "http://host.openshell.internal:50051", + false, + ) + .expect_err("plaintext endpoint must not silently downgrade"); + assert!(error.to_string().contains("allow_insecure_transport")); + + // Explicit opt-out starts the gateway with no credential attached. + assert!( + mint_gateway_extension_credential( + &issuer, + ExtensionKind::Middleware, + "content-guard", + "urn:openshell:extension:middleware:content-guard", + "http://host.openshell.internal:50051", + true, + ) + .expect("opt-out must be permitted") + .is_none() + ); + } + + #[test] + fn authenticated_extension_endpoints_mint_a_credential() { + let issuer = extension_test_issuer(); + let credential = mint_gateway_extension_credential( + &issuer, + ExtensionKind::Middleware, + "content-guard", + "urn:openshell:extension:middleware:content-guard", + "https://content-guard.example:50051", + false, + ) + .expect("credential") + .expect("authenticated endpoint mints a credential"); + assert_eq!(credential.name, "content-guard"); + assert!(credential.slot.expires_at_ms().is_some_and(|ms| ms > 0)); + + // Unix sockets are gateway-local, so only interceptors can use them. + // A middleware endpoint must also be reachable from every supervisor. + let error = mint_gateway_extension_credential( + &issuer, + ExtensionKind::Middleware, + "content-guard", + "urn:openshell:extension:middleware:content-guard", + "unix:///run/openshell/content-guard.sock", + false, + ) + .expect_err("middleware cannot be reached over a gateway-local socket"); + assert!(error.to_string().contains("must use https://")); + + assert!( + mint_gateway_extension_credential( + &issuer, + ExtensionKind::Interceptor, + "quota", + "urn:openshell:extension:interceptor:quota", + "unix:///run/openshell/interceptors/quota.sock", + false, + ) + .expect("credential") + .is_some() + ); + } + fn test_driver_startup<'a>( config: &'a Config, file: Option<&'a super::config_file::ConfigFile>, diff --git a/crates/openshell-server/src/multiplex.rs b/crates/openshell-server/src/multiplex.rs index 114201b982..7a7125dcc3 100644 --- a/crates/openshell-server/src/multiplex.rs +++ b/crates/openshell-server/src/multiplex.rs @@ -1466,6 +1466,7 @@ mod tests { failure_policy: "fail_open".to_string(), }], provider_profiles: false, + expected_audience: String::new(), })) } diff --git a/crates/openshell-server/src/provider_refresh.rs b/crates/openshell-server/src/provider_refresh.rs index 9a655babb4..dc039265f6 100644 --- a/crates/openshell-server/src/provider_refresh.rs +++ b/crates/openshell-server/src/provider_refresh.rs @@ -343,6 +343,7 @@ pub async fn refresh_provider_credential( store: &Store, workspace: &str, credentials: Option<&crate::credentials::CredentialRuntime>, + compute: Option<&crate::compute::ComputeRuntime>, provider_name: &str, credential_key: &str, ) -> Result { @@ -448,6 +449,7 @@ pub async fn refresh_provider_credential( store, workspace, credentials, + compute, &provider, credential_key, &minted, @@ -511,6 +513,7 @@ async fn apply_minted_credential( store: &Store, workspace: &str, credentials: Option<&crate::credentials::CredentialRuntime>, + compute: Option<&crate::compute::ComputeRuntime>, provider: &Provider, credential_key: &str, minted: &MintedCredential, @@ -520,6 +523,9 @@ async fn apply_minted_credential( let staged_handles = if let Some(credentials) = credentials && credentials.stores_provider_credentials() { + if let Some(compute) = compute { + compute.ensure_workspace(workspace).await?; + } let mut creds_to_store = HashMap::from([(credential_key.to_string(), minted.access_token.clone())]); for (key, value) in &minted.additional_credentials { @@ -1115,8 +1121,12 @@ pub fn spawn_refresh_worker(state: std::sync::Arc, interval: ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); loop { ticker.tick().await; - if let Err(err) = - run_refresh_worker_tick(state.store.as_ref(), Some(&state.credentials)).await + if let Err(err) = run_refresh_worker_tick( + state.store.as_ref(), + Some(&state.credentials), + Some(&state.compute), + ) + .await { warn!(error = %err, "provider credential refresh worker tick failed"); } @@ -1136,6 +1146,7 @@ pub fn spawn_refresh_worker(state: std::sync::Arc, interval: async fn run_refresh_worker_tick( store: &Store, credentials: Option<&crate::credentials::CredentialRuntime>, + compute: Option<&crate::compute::ComputeRuntime>, ) -> Result<(), Status> { let now_ms = current_time_ms(); let states = list_all_refresh_states(store).await.inspect_err(|_| { @@ -1200,6 +1211,7 @@ async fn run_refresh_worker_tick( store, state.object_workspace(), credentials, + compute, &state.provider_name, &state.credential_key, ) @@ -1328,6 +1340,7 @@ mod tests { &store, "default", None, + None, "my-graph", "MS_GRAPH_ACCESS_TOKEN", ) @@ -1398,6 +1411,7 @@ mod tests { &store, "default", Some(&credentials), + None, "my-stored-graph", "MS_GRAPH_ACCESS_TOKEN", ) @@ -1498,6 +1512,7 @@ mod tests { &store, "default", None, + None, "refreshing-graph", "MS_GRAPH_ACCESS_TOKEN", ) @@ -1578,6 +1593,7 @@ mod tests { &store, "default", None, + None, "my-delegated-graph", "MS_GRAPH_ACCESS_TOKEN", ) @@ -1672,6 +1688,7 @@ mod tests { &store, "default", None, + None, "my-drive", "GOOGLE_DRIVE_ACCESS_TOKEN", ) @@ -1715,7 +1732,7 @@ mod tests { .unwrap(); put_refresh_state(&store, &state).await.unwrap(); - run_refresh_worker_tick(&store, None).await.unwrap(); + run_refresh_worker_tick(&store, None, None).await.unwrap(); let stored_state = get_refresh_state( &store, @@ -1751,7 +1768,7 @@ mod tests { let store = test_store().await; let traced = test_exporter::install_traced(); - run_refresh_worker_tick(&store, None).await.unwrap(); + run_refresh_worker_tick(&store, None, None).await.unwrap(); let spans = traced.finished_spans(); let root = spans @@ -1873,6 +1890,7 @@ mod tests { &store, "default", None, + None, "aws-sts-test", "AWS_ACCESS_KEY_ID", ) @@ -1970,6 +1988,7 @@ mod tests { &store, "default", None, + None, "aws-sts-custom", "AWS_ACCESS_KEY_ID", ) @@ -2046,6 +2065,7 @@ mod tests { &store, "default", None, + None, "aws-sts-partial", "AWS_ACCESS_KEY_ID", ) @@ -2088,9 +2108,17 @@ mod tests { ]), }; - apply_minted_credential(&store, "default", None, &prov, "AWS_ACCESS_KEY_ID", &minted) - .await - .unwrap(); + apply_minted_credential( + &store, + "default", + None, + None, + &prov, + "AWS_ACCESS_KEY_ID", + &minted, + ) + .await + .unwrap(); let stored = store .get_message_by_name::("default", "aws-test") @@ -2163,6 +2191,7 @@ mod tests { &store, "default", Some(&credentials), + None, &prov, "AWS_ACCESS_KEY_ID", &minted, @@ -2266,6 +2295,7 @@ mod tests { &store, "default", Some(&credentials), + None, &refreshing_provider, "AWS_ACCESS_KEY_ID", &minted, @@ -2376,6 +2406,7 @@ mod tests { &store, "default", None, + None, "aws-sts-session", "AWS_ACCESS_KEY_ID", ) @@ -2444,6 +2475,7 @@ mod tests { &store, "default", None, + None, "aws-sts-lonesession", "AWS_ACCESS_KEY_ID", ) @@ -2526,8 +2558,14 @@ mod tests { .unwrap(); put_refresh_state(&store, &state).await.unwrap(); - let rotate = - refresh_provider_credential(&store, "default", None, "aws-race", "AWS_ACCESS_KEY_ID"); + let rotate = refresh_provider_credential( + &store, + "default", + None, + None, + "aws-race", + "AWS_ACCESS_KEY_ID", + ); let interfere = async { // Wait until the rotation is inside the STS call (its state read has // already happened), then delete the refresh and release STS. @@ -2645,6 +2683,7 @@ mod tests { &store, "default", None, + None, "aws-superseded", "AWS_ACCESS_KEY_ID", ); diff --git a/crates/openshell-server/src/test_support.rs b/crates/openshell-server/src/test_support.rs index 016e8d56af..f8124ded6c 100644 --- a/crates/openshell-server/src/test_support.rs +++ b/crates/openshell-server/src/test_support.rs @@ -8,13 +8,14 @@ use futures::{Stream, stream}; use openshell_core::proto::compute::v1::compute_driver_server::ComputeDriverServer; use openshell_core::proto::compute::v1::{ CreateSandboxRequest, CreateSandboxResponse, DeleteSandboxRequest, DeleteSandboxResponse, - DriverSandbox, GatewayListenerRequirement, GetCapabilitiesRequest, GetCapabilitiesResponse, - GetGatewayListenerRequirementsRequest, GetGatewayListenerRequirementsResponse, - GetSandboxRequest, GetSandboxResponse, ListSandboxesRequest, ListSandboxesResponse, - StartSandboxRequest, StartSandboxResponse, StopSandboxRequest, StopSandboxResponse, - ValidateSandboxCreateRequest, ValidateSandboxCreateResponse, WatchSandboxesEvent, - WatchSandboxesRequest, compute_driver_server::ComputeDriver, - gateway_listener_requirement::Selector, + DeleteWorkspaceRequest, DeleteWorkspaceResponse, DriverSandbox, EnsureWorkspaceRequest, + EnsureWorkspaceResponse, GatewayListenerRequirement, GetCapabilitiesRequest, + GetCapabilitiesResponse, GetGatewayListenerRequirementsRequest, + GetGatewayListenerRequirementsResponse, GetSandboxRequest, GetSandboxResponse, + ListSandboxesRequest, ListSandboxesResponse, StartSandboxRequest, StartSandboxResponse, + StopSandboxRequest, StopSandboxResponse, ValidateSandboxCreateRequest, + ValidateSandboxCreateResponse, WatchSandboxesEvent, WatchSandboxesRequest, + compute_driver_server::ComputeDriver, gateway_listener_requirement::Selector, }; use std::collections::HashMap; #[cfg(unix)] @@ -400,4 +401,18 @@ impl ComputeDriver for FakeComputeDriver { self.with_state(|state| state.calls.push(FakeComputeDriverCall::WatchSandboxes)); Ok(Response::new(Box::pin(stream::empty()))) } + + async fn ensure_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(EnsureWorkspaceResponse {})) + } + + async fn delete_workspace( + &self, + _request: Request, + ) -> Result, Status> { + Ok(Response::new(DeleteWorkspaceResponse {})) + } } diff --git a/crates/openshell-supervisor-middleware-builtins/Cargo.toml b/crates/openshell-supervisor-middleware-builtins/Cargo.toml index c888e698a1..8e38a05ad2 100644 --- a/crates/openshell-supervisor-middleware-builtins/Cargo.toml +++ b/crates/openshell-supervisor-middleware-builtins/Cargo.toml @@ -19,9 +19,9 @@ prost-types = { workspace = true } regex = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } - -[dev-dependencies] tokio = { workspace = true } +tokio-stream = { workspace = true } +tonic = { workspace = true, features = ["server"] } [lints] workspace = true diff --git a/crates/openshell-supervisor-middleware-builtins/src/lib.rs b/crates/openshell-supervisor-middleware-builtins/src/lib.rs index 120e6056c6..f87afafc3c 100644 --- a/crates/openshell-supervisor-middleware-builtins/src/lib.rs +++ b/crates/openshell-supervisor-middleware-builtins/src/lib.rs @@ -8,17 +8,24 @@ mod regex; use std::sync::Arc; use miette::{Result, miette}; -use openshell_core::middleware::{HttpRequestView, InProcessMiddleware}; -use openshell_core::proto::{HttpRequestResult, MiddlewareManifest}; +use openshell_core::middleware::{HttpRequestView, InProcessMiddleware, WebSocketResponseStream}; +use openshell_core::proto::{ + HttpRequestResult, MiddlewareManifest, SupervisorMiddlewarePhase, WebSocketPreflightAction, + WebSocketPreflightDecision, WebSocketSessionEvent, WebSocketSessionEventResult, + web_socket_message, web_socket_session_event, web_socket_session_event_result, +}; +use tokio_stream::{Stream, StreamExt}; +use tonic::Status; pub use regex::{NAME as BUILTIN_REGEX, RegexConfig, RegexMode}; -/// Return the first-party in-process services installed by the gateway and supervisor. +/// Return the first-party services that the gateway and supervisor install. pub fn services() -> Vec> { vec![Arc::new(BuiltinMiddlewareService)] } -/// Validate configuration for a first-party binding. +/// Resolve and validate a first-party config before the supervisor has selected +/// its service endpoint. pub fn validate_config(implementation: &str, config: &prost_types::Struct) -> Result<()> { match implementation { BUILTIN_REGEX => regex::validate_config(config), @@ -41,13 +48,151 @@ fn evaluate_http_request(request: HttpRequestView<'_>) -> Result(mut requests: S) -> WebSocketResponseStream + where + S: Stream> + + Send + + Unpin + + 'static, + { + let (responses_tx, responses_rx) = tokio::sync::mpsc::channel(4); + tokio::spawn(async move { + let mut config = None; + let mut started = false; + let mut sequence_lower_bound = Some(1u64); + + while let Some(request) = requests.next().await { + let request = match request { + Ok(request) => request, + Err(error) => { + let _ = responses_tx.send(Err(error)).await; + break; + } + }; + let response = match request.event { + Some(web_socket_session_event::Event::Preflight(preflight)) + if config.is_none() && !started => + { + if preflight.phase == SupervisorMiddlewarePhase::PreCredentials as i32 { + let selected_config = preflight.config.unwrap_or_default(); + match regex::validate_config(&selected_config) { + Ok(()) => { + config = Some(selected_config); + Ok(Some(WebSocketSessionEventResult { + result: Some( + web_socket_session_event_result::Result::PreflightDecision( + WebSocketPreflightDecision { + action: WebSocketPreflightAction::Inspect + as i32, + ..Default::default() + }, + ), + ), + })) + } + Err(error) => Err(Status::invalid_argument(error.to_string())), + } + } else { + Err(Status::invalid_argument( + "unsupported built-in WebSocket binding", + )) + } + } + Some(web_socket_session_event::Event::SessionStart(_)) + if config.is_some() && !started => + { + started = true; + Ok(None) + } + Some(web_socket_session_event::Event::Message(message)) if started => { + if let Err(error) = advance_sequence_lower_bound( + &mut sequence_lower_bound, + message.sequence, + ) { + Err(error) + } else { + match message.payload { + Some(web_socket_message::Payload::Text(payload)) => { + let selected_config = + config.as_ref().expect("started stream has config"); + match regex::evaluate_websocket_text( + message.sequence, + &payload, + selected_config, + ) { + Ok(result) => Ok(Some(WebSocketSessionEventResult { + result: Some( + web_socket_session_event_result::Result::MessageResult( + result, + ), + ), + })), + Err(error) => { + Err(Status::invalid_argument(error.to_string())) + } + } + } + Some(web_socket_message::Payload::Binary(_)) | None => { + Err(Status::invalid_argument( + "openshell/regex supports only client-to-upstream WebSocket text messages", + )) + } + } + } + } + Some(web_socket_session_event::Event::SessionEnd(_)) if config.is_some() => { + break; + } + _ => Err(Status::failed_precondition( + "invalid built-in WebSocket session lifecycle", + )), + }; + + match response { + Ok(Some(response)) => { + if responses_tx.send(Ok(response)).await.is_err() { + break; + } + } + Ok(None) => {} + Err(error) => { + let _ = responses_tx.send(Err(error)).await; + break; + } + } + } + }); + Box::pin(tokio_stream::wrappers::ReceiverStream::new(responses_rx)) + } +} + +fn advance_sequence_lower_bound( + lower_bound: &mut Option, + sequence: u64, +) -> std::result::Result<(), Status> { + let Some(current_lower_bound) = *lower_bound else { + return Err(Status::invalid_argument( + "WebSocket message sequence must be strictly increasing", + )); + }; + if sequence < current_lower_bound { + return Err(Status::invalid_argument( + "WebSocket message sequence must be strictly increasing", + )); + } + *lower_bound = sequence.checked_add(1); + Ok(()) +} + +#[tonic::async_trait] impl InProcessMiddleware for BuiltinMiddlewareService { async fn describe(&self) -> MiddlewareManifest { MiddlewareManifest { name: BUILTIN_REGEX.into(), service_version: env!("CARGO_PKG_VERSION").into(), - bindings: vec![regex::describe()], + bindings: regex::describe(), + expected_audience: String::new(), } } @@ -65,6 +210,15 @@ impl InProcessMiddleware for BuiltinMiddlewareService { ) -> Result { evaluate_http_request(request) } + + async fn open_websocket_session( + &self, + receiver: tokio::sync::mpsc::Receiver, + ) -> std::result::Result { + Ok(Self::websocket_stream( + tokio_stream::wrappers::ReceiverStream::new(receiver).map(Ok), + )) + } } #[cfg(test)] @@ -72,7 +226,7 @@ mod tests { use super::*; use openshell_core::proto::{ Decision, HttpRequestTarget, RequestContext, SupervisorMiddlewareOperation, - SupervisorMiddlewarePhase, + SupervisorMiddlewarePhase, WebSocketPreflight, }; fn string_config(key: &str, value: &str) -> prost_types::Struct { @@ -103,8 +257,8 @@ mod tests { #[tokio::test] async fn service_describes_regex_binding() { - let manifest = BuiltinMiddlewareService.describe().await; - assert_eq!(manifest.bindings.len(), 1); + let manifest = InProcessMiddleware::describe(&BuiltinMiddlewareService).await; + assert_eq!(manifest.bindings.len(), 2); assert_eq!( manifest.bindings[0].operation, SupervisorMiddlewareOperation::HttpRequest as i32 @@ -113,7 +267,16 @@ mod tests { manifest.bindings[0].phase, SupervisorMiddlewarePhase::PreCredentials as i32 ); - assert_eq!(manifest.bindings[0].max_body_bytes, 256 * 1024); + assert_eq!(manifest.bindings[0].max_payload_bytes, 256 * 1024); + assert_eq!( + manifest.bindings[1].operation, + SupervisorMiddlewareOperation::WebsocketMessage as i32 + ); + assert_eq!( + manifest.bindings[1].phase, + SupervisorMiddlewarePhase::PreCredentials as i32 + ); + assert_eq!(manifest.bindings[1].max_payload_bytes, 256 * 1024); } #[test] @@ -179,6 +342,44 @@ mod tests { ); } + #[tokio::test] + async fn service_validates_builtin_config() { + InProcessMiddleware::validate_config( + &BuiltinMiddlewareService, + BUILTIN_REGEX, + &prost_types::Struct::default(), + ) + .await + .expect("validate config"); + } + + #[tokio::test] + async fn websocket_preflight_does_not_dispatch_on_registration_name() { + let requests = tokio_stream::iter([Ok::<_, Status>(WebSocketSessionEvent { + event: Some(web_socket_session_event::Event::Preflight( + WebSocketPreflight { + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + middleware_name: "operator-assigned-name".into(), + config: Some(prost_types::Struct::default()), + ..Default::default() + }, + )), + })]); + let mut responses = BuiltinMiddlewareService::websocket_stream(requests); + let response = responses + .next() + .await + .expect("preflight response") + .expect("valid preflight"); + + assert!(matches!( + response.result, + Some(web_socket_session_event_result::Result::PreflightDecision( + WebSocketPreflightDecision { action, .. } + )) if action == WebSocketPreflightAction::Inspect as i32 + )); + } + #[test] fn regex_replacement_does_not_parse_keyword_assignments() { let body = concat!( @@ -194,6 +395,74 @@ mod tests { assert!(result.findings.is_empty()); } + #[test] + fn regex_websocket_text_reuses_findings_and_metadata_semantics() { + let payload = + r#"{"type":"response.create","input":"sk-ABCDEFGHIJKLMNOP sk-QRSTUVWXYZabcdef"}"#; + let result = regex::evaluate_websocket_text(7, payload, &prost_types::Struct::default()) + .expect("evaluate WebSocket text"); + + assert_eq!(result.sequence, 7); + assert_eq!(result.decision, Decision::Allow as i32); + assert_eq!( + result.replacement, + Some( + openshell_core::proto::web_socket_message_result::Replacement::Text( + r#"{"type":"response.create","input":"[REDACTED] [REDACTED]"}"#.into() + ) + ) + ); + assert_eq!(result.findings.len(), 1); + assert_eq!(result.findings[0].r#type, "regex.openai"); + assert_eq!(result.findings[0].count, 2); + assert_eq!( + result.metadata.get("regex_matches_replaced"), + Some(&"2".to_string()) + ); + } + + #[test] + fn regex_websocket_no_match_returns_no_replacement_or_findings() { + let result = regex::evaluate_websocket_text( + 1, + r#"{"type":"response.create","input":"public"}"#, + &prost_types::Struct::default(), + ) + .expect("evaluate WebSocket text"); + + assert!(result.replacement.is_none()); + assert!(result.findings.is_empty()); + assert!(result.metadata.is_empty()); + } + + #[test] + fn regex_websocket_rejects_oversize_messages() { + assert!( + regex::evaluate_websocket_text( + 1, + &"a".repeat(256 * 1024 + 1), + &prost_types::Struct::default(), + ) + .is_err() + ); + } + + #[test] + fn websocket_sequence_lower_bound_accepts_gaps_and_rejects_reuse() { + let mut lower_bound = Some(1); + advance_sequence_lower_bound(&mut lower_bound, 2).expect("first delivered sequence"); + assert_eq!(lower_bound, Some(3)); + assert!(advance_sequence_lower_bound(&mut lower_bound, 2).is_err()); + assert!(advance_sequence_lower_bound(&mut lower_bound, 1).is_err()); + + advance_sequence_lower_bound(&mut lower_bound, 7).expect("forward gap"); + assert_eq!(lower_bound, Some(8)); + + advance_sequence_lower_bound(&mut lower_bound, u64::MAX).expect("last sequence"); + assert_eq!(lower_bound, None); + assert!(advance_sequence_lower_bound(&mut lower_bound, u64::MAX).is_err()); + } + #[test] fn regex_rejects_non_utf8_borrowed_body() { let error = diff --git a/crates/openshell-supervisor-middleware-builtins/src/regex.rs b/crates/openshell-supervisor-middleware-builtins/src/regex.rs index 6d954ba1af..a5c2df882a 100644 --- a/crates/openshell-supervisor-middleware-builtins/src/regex.rs +++ b/crates/openshell-supervisor-middleware-builtins/src/regex.rs @@ -2,7 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 //! Example built-in middleware that applies a fixed set of regular-expression -//! replacements to UTF-8 request bodies. +//! replacements to UTF-8 HTTP request bodies and WebSocket text messages. //! //! This is intentionally a best-effort text transformation, not a secret //! scanner or a parser-aware redactor. It provides no guarantee that sensitive @@ -15,13 +15,13 @@ use std::sync::LazyLock; use miette::{Result, miette}; use openshell_core::proto::{ Decision, Finding, HttpRequestResult, MiddlewareBinding, SupervisorMiddlewareOperation, - SupervisorMiddlewarePhase, + SupervisorMiddlewarePhase, WebSocketMessageResult, web_socket_message_result, }; use regex::Regex; use serde::Deserialize; pub const NAME: &str = "openshell/regex"; -const MAX_BODY_BYTES: u64 = 256 * 1024; +const MAX_PAYLOAD_BYTES: u64 = 256 * 1024; #[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Deserialize)] #[serde(default, deny_unknown_fields)] @@ -48,14 +48,22 @@ impl RegexConfig { } } -/// Describe the HTTP request phase and body limit supported by the regex middleware. -pub fn describe() -> MiddlewareBinding { - MiddlewareBinding { - operation: SupervisorMiddlewareOperation::HttpRequest as i32, - phase: SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: MAX_BODY_BYTES, - timeout: String::new(), - } +/// Describe the HTTP request and WebSocket message bindings supported by the regex middleware. +pub fn describe() -> Vec { + vec![ + MiddlewareBinding { + operation: SupervisorMiddlewareOperation::HttpRequest as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_payload_bytes: MAX_PAYLOAD_BYTES, + timeout: String::new(), + }, + MiddlewareBinding { + operation: SupervisorMiddlewareOperation::WebsocketMessage as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_payload_bytes: MAX_PAYLOAD_BYTES, + timeout: String::new(), + }, + ] } struct ReplacementPattern { @@ -92,11 +100,9 @@ pub fn evaluate_http_request( let text = std::str::from_utf8(body).map_err(|_| miette!("{NAME} requires UTF-8 request bodies"))?; let (body, matches) = apply_replacements(text); - let total: u32 = matches - .iter() - .fold(0u32, |acc, (_, count)| acc.saturating_add(*count)); + let (findings, metadata) = findings_and_metadata(&matches); let has_body = !matches.is_empty(); - let mut result = HttpRequestResult { + let result = HttpRequestResult { decision: Decision::Allow as i32, reason: String::new(), body: match body { @@ -105,25 +111,62 @@ pub fn evaluate_http_request( }, has_body, header_mutations: Vec::new(), - findings: Vec::new(), - metadata: HashMap::new(), + findings, + metadata, reason_code: String::new(), }; - for (kind, count) in &matches { - result.findings.push(Finding { + Ok(result) +} + +pub fn evaluate_websocket_text( + sequence: u64, + payload: &str, + config: &prost_types::Struct, +) -> Result { + validate_config(config)?; + let payload_bytes = u64::try_from(payload.len()) + .map_err(|_| miette!("{NAME} WebSocket text message length is not representable"))?; + if payload_bytes > MAX_PAYLOAD_BYTES { + return Err(miette!( + "{NAME} WebSocket text message exceeds {MAX_PAYLOAD_BYTES} bytes" + )); + } + let (replacement, matches) = apply_replacements(payload); + let (findings, metadata) = findings_and_metadata(&matches); + let replacement = (!matches.is_empty()) + .then(|| web_socket_message_result::Replacement::Text(replacement.into_owned())); + Ok(WebSocketMessageResult { + sequence, + decision: Decision::Allow as i32, + replacement, + reason: String::new(), + findings, + metadata, + reason_code: String::new(), + }) +} + +fn findings_and_metadata( + matches: &[(&'static str, u32)], +) -> (Vec, HashMap) { + let findings = matches + .iter() + .map(|(kind, count)| Finding { r#type: format!("regex.{kind}"), label: format!("{kind} regex match"), count: *count, confidence: "medium".into(), severity: "medium".into(), - }); - } + }) + .collect(); + let mut metadata = HashMap::new(); if !matches.is_empty() { - result - .metadata - .insert("regex_matches_replaced".into(), total.to_string()); + let total = matches + .iter() + .fold(0u32, |acc, (_, count)| acc.saturating_add(*count)); + metadata.insert("regex_matches_replaced".into(), total.to_string()); } - Ok(result) + (findings, metadata) } fn apply_replacements(input: &str) -> (Cow<'_, str>, Vec<(&'static str, u32)>) { diff --git a/crates/openshell-supervisor-middleware/Cargo.toml b/crates/openshell-supervisor-middleware/Cargo.toml index 9cdc53febb..453520c3eb 100644 --- a/crates/openshell-supervisor-middleware/Cargo.toml +++ b/crates/openshell-supervisor-middleware/Cargo.toml @@ -12,11 +12,14 @@ rust-version.workspace = true [dependencies] openshell-core = { path = "../openshell-core", default-features = false } +openshell-extension-core = { path = "../openshell-extension-core" } miette = { workspace = true } +futures = { workspace = true } prost = { workspace = true } prost-types = { workspace = true } tokio = { workspace = true } +tokio-stream = { workspace = true } tonic = { workspace = true, features = ["channel", "server", "tls-native-roots"] } [dev-dependencies] diff --git a/crates/openshell-supervisor-middleware/src/lib.rs b/crates/openshell-supervisor-middleware/src/lib.rs index 0125f8e5a2..d9972223ee 100644 --- a/crates/openshell-supervisor-middleware/src/lib.rs +++ b/crates/openshell-supervisor-middleware/src/lib.rs @@ -5,10 +5,16 @@ mod headers; mod remote; +mod websocket; -#[cfg(test)] -use std::collections::HashMap; -use std::collections::{BTreeMap, HashSet}; +pub use websocket::{ + WebSocketCoverage, WebSocketCoverageState, WebSocketInvocation, WebSocketInvocationOutcome, + WebSocketMessageAdmission, WebSocketMessageOutcome, WebSocketMessageType, + WebSocketPreflightInput, WebSocketPreflightResult, WebSocketSession, + WebSocketSessionStartOutcome, +}; + +use std::collections::{BTreeMap, HashMap, HashSet}; use std::future::Future; use std::sync::Arc; use std::time::Duration; @@ -16,30 +22,252 @@ use std::time::Duration; use miette::{Result, miette}; use prost::Message; +use openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware; use openshell_core::proto::{ - Decision, Finding, HeaderMutation, HttpHeader, HttpRequestTarget, MiddlewareBinding, - MiddlewareManifest, NetworkMiddlewareConfig, RequestContext, SandboxPolicy, + Decision, Finding, HeaderMutation, HttpHeader, HttpRequestEvaluation, HttpRequestTarget, + MiddlewareBinding, MiddlewareManifest, NetworkMiddlewareConfig, RequestContext, SandboxPolicy, SupervisorMiddlewareOperation, SupervisorMiddlewarePhase, SupervisorMiddlewareService, - ValidateConfigResponse, + ValidateConfigRequest, ValidateConfigResponse, }; -use tokio::sync::OnceCell; +use tokio::sync::{OnceCell, OwnedSemaphorePermit, Semaphore}; +use tonic::{Request, Response as TonicResponse, Status as TonicStatus}; -#[cfg(test)] -use openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware; -#[cfg(test)] -use openshell_core::proto::{HttpRequestEvaluation, ValidateConfigRequest}; -#[cfg(test)] -use tonic::Request; +pub use openshell_core::middleware::{ + HttpRequestView, InProcessMiddleware, SupervisorMiddlewareEndpoint, WebSocketResponseStream, +}; +pub type MiddlewareService = + dyn SupervisorMiddleware; + +struct GeneratedMiddlewareEndpoint { + service: Arc, +} + +#[tonic::async_trait] +impl SupervisorMiddlewareEndpoint for GeneratedMiddlewareEndpoint { + async fn describe( + &self, + request: Request<()>, + ) -> std::result::Result, TonicStatus> { + self.service.describe(request).await + } + + async fn validate_config( + &self, + request: Request, + ) -> std::result::Result, TonicStatus> { + self.service.validate_config(request).await + } + + async fn evaluate_http_request( + &self, + request: Request, + ) -> std::result::Result, TonicStatus> + { + self.service.evaluate_http_request(request).await + } + + async fn open_websocket_session( + &self, + _receiver: tokio::sync::mpsc::Receiver, + ) -> std::result::Result { + Err(TonicStatus::unimplemented( + "middleware service does not expose an in-process WebSocket stream", + )) + } +} + +#[tonic::async_trait] +impl InProcessMiddleware for GeneratedMiddlewareEndpoint { + async fn describe(&self) -> MiddlewareManifest { + self.service + .describe(Request::new(())) + .await + .expect("generated in-process Describe failed") + .into_inner() + } + + async fn validate_config( + &self, + middleware_name: &str, + config: &prost_types::Struct, + ) -> Result<()> { + let response = self + .service + .validate_config(Request::new(ValidateConfigRequest { + config: Some(config.clone()), + middleware_name: middleware_name.to_string(), + })) + .await + .map_err(|error| miette!("{error}"))? + .into_inner(); + if response.valid { + Ok(()) + } else { + Err(miette!("{}", response.reason)) + } + } + + async fn evaluate_http_request( + &self, + request: HttpRequestView<'_>, + ) -> Result { + self.service + .evaluate_http_request(Request::new(request_view_to_evaluation(request))) + .await + .map(tonic::Response::into_inner) + .map_err(|error| miette!("{error}")) + } +} + +/// Adapt a generated HTTP-only service to the borrowed in-process contract. +/// +/// This compatibility adapter is intended for tests and downstream HTTP-only +/// implementations. First-party built-ins implement [`InProcessMiddleware`] +/// directly so their HTTP path remains allocation-free. +pub fn http_only_endpoint(service: Arc) -> Arc { + Arc::new(GeneratedMiddlewareEndpoint { service }) +} + +struct EndpointInProcessAdapter { + endpoint: Arc, +} + +#[tonic::async_trait] +impl InProcessMiddleware for EndpointInProcessAdapter { + async fn describe(&self) -> MiddlewareManifest { + self.endpoint + .describe(Request::new(())) + .await + .expect("in-process endpoint Describe failed") + .into_inner() + } + + async fn validate_config( + &self, + middleware_name: &str, + config: &prost_types::Struct, + ) -> Result<()> { + let response = self + .endpoint + .validate_config(Request::new(ValidateConfigRequest { + config: Some(config.clone()), + middleware_name: middleware_name.to_string(), + })) + .await + .map_err(|error| miette!("{error}"))? + .into_inner(); + if response.valid { + Ok(()) + } else { + Err(miette!("{}", response.reason)) + } + } + + async fn evaluate_http_request( + &self, + request: HttpRequestView<'_>, + ) -> Result { + self.endpoint + .evaluate_http_request(Request::new(request_view_to_evaluation(request))) + .await + .map(tonic::Response::into_inner) + .map_err(|error| miette!("{error}")) + } + + async fn open_websocket_session( + &self, + requests: tokio::sync::mpsc::Receiver, + ) -> std::result::Result { + self.endpoint.open_websocket_session(requests).await + } +} + +/// Adapt a transport-neutral endpoint to the in-process registry contract. +/// +/// Prefer implementing [`InProcessMiddleware`] directly. This compatibility +/// path materializes an owned HTTP request, but preserves direct WebSocket +/// streams for endpoint implementations that predate the borrowed contract. +pub fn in_process_endpoint( + endpoint: Arc, +) -> Arc { + Arc::new(EndpointInProcessAdapter { endpoint }) +} + +/// Maximum short-lived middleware work items allowed to wait for active +/// capacity. +/// +/// Waiters do not buffer request or message bodies, so the queue can absorb a +/// larger burst without increasing the active payload-memory bound. +pub const MAX_QUEUED_MIDDLEWARE_WORK: usize = MAX_CONCURRENT_MIDDLEWARE_WORK * 2; + +/// One slot in the shared middleware work budget. +/// +/// Callers that buffer request or message bodies acquire this guard first and +/// retain it through evaluation, bounding aggregate buffered middleware input. +#[derive(Debug)] +pub struct MiddlewareWorkAdmission { + _work: OwnedSemaphorePermit, + saturated: bool, +} + +impl MiddlewareWorkAdmission { + pub fn saturated(&self) -> bool { + self.saturated + } +} + +/// Result of attempting to enter the bounded middleware work queue. +/// +/// Active-capacity saturation is ordinary backpressure: callers that obtain a +/// waiter slot eventually receive [`Self::Admitted`]. [`Self::QueueExhausted`] +/// is immediate load shedding after both active capacity and the waiter queue +/// are full. +#[derive(Debug)] +pub enum MiddlewareWorkAdmissionOutcome { + Admitted(MiddlewareWorkAdmission), + QueueExhausted, +} + +impl MiddlewareWorkAdmissionOutcome { + /// Preserve the existing failure behavior for protocols whose outer layer + /// already translates middleware admission errors into a stable response + /// or typed termination. + pub fn into_admission(self) -> Result { + match self { + Self::Admitted(admission) => Ok(admission), + Self::QueueExhausted => Err(miette!( + "middleware admission queue is full; refusing additional buffered work" + )), + } + } +} + +/// One slot in the shared persistent middleware session budget. +/// +/// Protocol-specific session runners retain this guard while at least one +/// streaming stage remains active. Registry replacement preserves the shared +/// admission state so future streaming HTTP middleware can use the same +/// process-wide bound. +#[derive(Debug)] +struct MiddlewareSessionPermit { + _session: OwnedSemaphorePermit, +} + +enum MiddlewareSessionAdmission { + Admitted(MiddlewareSessionPermit), + AtCapacity, +} pub use openshell_core::middleware::{ - DEFAULT_MIDDLEWARE_TIMEOUT, HttpRequestView, InProcessMiddleware, - MAX_MIDDLEWARE_CHAIN_FINDINGS, MAX_MIDDLEWARE_CHAIN_STAGES, MAX_MIDDLEWARE_CONFIGS, - MAX_MIDDLEWARE_FINDINGS_PER_STAGE, MAX_MIDDLEWARE_SELECTOR_PATTERNS, MAX_MIDDLEWARE_TIMEOUT, - MIN_MIDDLEWARE_TIMEOUT, middleware_timeout_or_default, parse_middleware_timeout, + DEFAULT_MIDDLEWARE_TIMEOUT, MAX_CONCURRENT_MIDDLEWARE_SESSIONS, MAX_CONCURRENT_MIDDLEWARE_WORK, + MAX_MIDDLEWARE_CHAIN_FINDINGS, MAX_MIDDLEWARE_CHAIN_STAGES, MAX_MIDDLEWARE_CHAIN_TIMEOUT, + MAX_MIDDLEWARE_CONFIGS, MAX_MIDDLEWARE_FINDINGS_PER_STAGE, MAX_MIDDLEWARE_PREFLIGHT_TIMEOUT, + MAX_MIDDLEWARE_SELECTOR_PATTERNS, MAX_MIDDLEWARE_TIMEOUT, MIN_MIDDLEWARE_TIMEOUT, + middleware_timeout_or_default, parse_middleware_timeout, }; -/// Largest request or replacement body accepted by the middleware platform. -pub const MAX_MIDDLEWARE_BODY_BYTES: usize = 4 * 1024 * 1024; +/// Largest logical payload or replacement accepted by the middleware platform. +pub const MAX_MIDDLEWARE_PAYLOAD_BYTES: usize = 4 * 1024 * 1024; /// Largest encoded service-specific configuration attached to one evaluation. pub const MAX_MIDDLEWARE_CONFIG_BYTES: usize = 64 * 1024; /// Largest encoded request identity context attached to one evaluation. @@ -74,22 +302,23 @@ const MAX_MIDDLEWARE_RESPONSE_ENVELOPE_BYTES: usize = MAX_MIDDLEWARE_REASON_BYTE + MAX_MIDDLEWARE_FINDINGS_PER_STAGE * MAX_MIDDLEWARE_FINDING_BYTES + MAX_MIDDLEWARE_METADATA_BYTES + MAX_MIDDLEWARE_PROTOBUF_OVERHEAD_BYTES; -/// gRPC envelope headroom derived from every bounded non-body component. +/// gRPC envelope headroom derived from every bounded non-payload component. pub const MIDDLEWARE_GRPC_ENVELOPE_BYTES: usize = if MAX_MIDDLEWARE_REQUEST_ENVELOPE_BYTES > MAX_MIDDLEWARE_RESPONSE_ENVELOPE_BYTES { MAX_MIDDLEWARE_REQUEST_ENVELOPE_BYTES } else { MAX_MIDDLEWARE_RESPONSE_ENVELOPE_BYTES }; -/// gRPC message limit derived from the body and bounded protobuf components. +/// gRPC message limit derived from the payload and bounded protobuf components. pub const MIDDLEWARE_GRPC_MESSAGE_BYTES: usize = - MAX_MIDDLEWARE_BODY_BYTES + MIDDLEWARE_GRPC_ENVELOPE_BYTES; + MAX_MIDDLEWARE_PAYLOAD_BYTES + MIDDLEWARE_GRPC_ENVELOPE_BYTES; +const MAX_STABLE_IDENTIFIER_BYTES: usize = 128; +const EXTERNAL_FINDING_LABEL: &str = "External middleware finding"; +#[cfg(test)] const HTTP_REQUEST_OPERATION: SupervisorMiddlewareOperation = SupervisorMiddlewareOperation::HttpRequest; const PRE_CREDENTIALS_PHASE: SupervisorMiddlewarePhase = SupervisorMiddlewarePhase::PreCredentials; -const MAX_STABLE_IDENTIFIER_BYTES: usize = 128; -const EXTERNAL_FINDING_LABEL: &str = "External middleware finding"; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum OnError { FailClosed, @@ -141,20 +370,28 @@ impl TryFrom<(&str, &NetworkMiddlewareConfig)> for ChainEntry { } /// A policy-selected middleware config joined with metadata reported by its -/// service's `Describe` call. A missing binding is retained so `on_error` can -/// decide whether the request fails open or closed. +/// service's `Describe` call. +/// +/// An unregistered implementation is retained so `on_error` can decide whether +/// the request fails open or closed. A registered implementation without the +/// requested binding is not part of this chain. #[derive(Clone)] pub struct DescribedChainEntry { entry: ChainEntry, service: Option>, binding: Option, - max_body_bytes: usize, + max_payload_bytes: usize, timeout: Duration, } +struct DescribedChain { + entries: Vec, + unbound: Vec, +} + impl DescribedChainEntry { - pub fn max_body_bytes(&self) -> usize { - self.max_body_bytes + pub fn max_payload_bytes(&self) -> usize { + self.max_payload_bytes } pub fn on_error(&self) -> OnError { @@ -168,7 +405,7 @@ impl DescribedChainEntry { /// True when this entry resolved to a registered binding and will be /// evaluated. When false, the binding is absent from the current registry /// and the entry is handled entirely by its `on_error` policy, so it - /// imposes no body-buffering limit on the chain. + /// imposes no payload-buffering limit on the chain. pub fn is_resolved(&self) -> bool { self.binding.is_some() } @@ -298,19 +535,32 @@ fn apply_on_error( } } +fn request_view_to_evaluation(request: HttpRequestView<'_>) -> HttpRequestEvaluation { + HttpRequestEvaluation { + phase: request.phase() as i32, + context: Some(request.context().clone()), + config: Some(request.config().clone()), + target: Some(request.target().clone()), + headers: request.headers().to_vec(), + body: request.body().to_vec(), + middleware_name: request.middleware_name().to_string(), + } +} + #[derive(Clone)] pub struct ChainRunner { registry: Arc, } -enum MiddlewareService { +#[derive(Clone)] +enum MiddlewareDispatch { /// Built-ins borrow the current request state and never construct protobuf. InProcess(Arc), /// Operator services receive an owned protobuf through the gRPC adapter. Grpc(remote::GrpcMiddlewareService), } -impl MiddlewareService { +impl MiddlewareDispatch { async fn describe( &self, ) -> std::result::Result, tonic::Status> { @@ -356,6 +606,16 @@ impl MiddlewareService { Self::Grpc(service) => service.evaluate_http_request(request).await, } } + + async fn open_websocket_session( + &self, + receiver: tokio::sync::mpsc::Receiver, + ) -> std::result::Result { + match self { + Self::InProcess(service) => service.open_websocket_session(receiver).await, + Self::Grpc(service) => service.open_websocket_session(receiver).await, + } + } } struct MiddlewareServiceState { @@ -363,10 +623,10 @@ struct MiddlewareServiceState { /// single-service test constructor leaves this empty and uses the manifest /// name after Describe. attachment_name: Option, - service: MiddlewareService, + service: MiddlewareDispatch, manifest: OnceCell, diagnostic_policy: MiddlewareDiagnosticPolicy, - operator_max_body_bytes: Option, + operator_max_payload_bytes: Option, operator_timeout: Duration, } @@ -435,6 +695,9 @@ pub struct MiddlewareRegistry { services: Arc>>, registered_services: Arc>, middleware_names: Arc>, + work_admission: Arc, + work_admission_waiters: Arc, + session_admission: Arc, } impl std::fmt::Debug for MiddlewareRegistry { @@ -444,6 +707,14 @@ impl std::fmt::Debug for MiddlewareRegistry { .field("service_count", &self.services.len()) .field("registered_service_count", &self.registered_services.len()) .field("middleware_count", &self.middleware_names.len()) + .field( + "available_work_permits", + &self.work_admission.available_permits(), + ) + .field( + "available_session_permits", + &self.session_admission.available_permits(), + ) .finish() } } @@ -459,6 +730,9 @@ impl Default for MiddlewareRegistry { services: Arc::new(Vec::new()), registered_services: Arc::new(Vec::new()), middleware_names: Arc::new(HashSet::new()), + work_admission: Arc::new(Semaphore::new(MAX_CONCURRENT_MIDDLEWARE_WORK)), + work_admission_waiters: Arc::new(Semaphore::new(MAX_QUEUED_MIDDLEWARE_WORK)), + session_admission: Arc::new(Semaphore::new(MAX_CONCURRENT_MIDDLEWARE_SESSIONS)), } } } @@ -483,15 +757,9 @@ fn validate_registration(registration: &SupervisorMiddlewareService) -> Result MAX_MIDDLEWARE_BODY_BYTES as u64 { + if registration.max_payload_bytes > MAX_MIDDLEWARE_PAYLOAD_BYTES as u64 { return Err(miette!( - "middleware registration '{}' max_body_bytes exceeds the platform maximum of {MAX_MIDDLEWARE_BODY_BYTES}", + "middleware registration '{}' max_payload_bytes exceeds the platform maximum of {MAX_MIDDLEWARE_PAYLOAD_BYTES}", registration.name )); } @@ -537,23 +805,54 @@ fn middleware_denial_reason(config_name: &str, reason_code: Option<&str>) -> Str ) } -fn validate_body_limit(source: &str, binding: &MiddlewareBinding) -> Result { - if binding.max_body_bytes == 0 { - return Err(miette!("{source} must advertise a non-zero body limit")); +fn validate_payload_limit(source: &str, binding: &MiddlewareBinding) -> Result { + if binding.max_payload_bytes == 0 { + return Err(miette!("{source} must advertise a non-zero payload limit")); } - if binding.max_body_bytes > MAX_MIDDLEWARE_BODY_BYTES as u64 { + if binding.max_payload_bytes > MAX_MIDDLEWARE_PAYLOAD_BYTES as u64 { return Err(miette!( - "{source} body limit exceeds the platform maximum of {MAX_MIDDLEWARE_BODY_BYTES}" + "{source} payload limit exceeds the platform maximum of {MAX_MIDDLEWARE_PAYLOAD_BYTES}" )); } - usize::try_from(binding.max_body_bytes) - .map_err(|_| miette!("{source} reports a body limit too large for this platform")) + usize::try_from(binding.max_payload_bytes) + .map_err(|_| miette!("{source} reports a payload limit too large for this platform")) +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum SupportedBinding { + HttpPreCredentials, + WebSocketPreCredentials, +} + +fn supported_binding(source: &str, binding: &MiddlewareBinding) -> Result { + match ( + SupervisorMiddlewareOperation::try_from(binding.operation).ok(), + SupervisorMiddlewarePhase::try_from(binding.phase).ok(), + ) { + ( + Some(SupervisorMiddlewareOperation::HttpRequest), + Some(SupervisorMiddlewarePhase::PreCredentials), + ) => Ok(SupportedBinding::HttpPreCredentials), + ( + Some(SupervisorMiddlewareOperation::WebsocketMessage), + Some(SupervisorMiddlewarePhase::PreCredentials), + ) => Ok(SupportedBinding::WebSocketPreCredentials), + ( + Some(SupervisorMiddlewareOperation::WebsocketMessage), + Some(SupervisorMiddlewarePhase::PreReturn), + ) => Err(miette!( + "{source} advertises WEBSOCKET_MESSAGE/PRE_RETURN, which is reserved for PR 2" + )), + _ => Err(miette!( + "{source} advertises an unsupported middleware operation/phase pair" + )), + } } fn validate_manifest_bindings( source: &str, manifest: &MiddlewareManifest, - operator_max_body_bytes: Option, + operator_max_payload_bytes: Option, ) -> Result<()> { if manifest.bindings.is_empty() { return Err(miette!("{source} describes no bindings")); @@ -561,27 +860,26 @@ fn validate_manifest_bindings( let mut described_pairs = HashSet::with_capacity(manifest.bindings.len()); for binding in &manifest.bindings { - if binding.operation != HTTP_REQUEST_OPERATION as i32 - || binding.phase != PRE_CREDENTIALS_PHASE as i32 - { - return Err(miette!( - "{source} must support HTTP_REQUEST/PRE_CREDENTIALS" - )); - } + supported_binding(source, binding)?; if !described_pairs.insert((binding.operation, binding.phase)) { return Err(miette!( - "{source} describes more than one binding for HTTP_REQUEST/PRE_CREDENTIALS" + "{source} describes a duplicate middleware operation/phase pair" )); } - let advertised = validate_body_limit(source, binding)?; + let advertised = validate_payload_limit(source, binding)?; if !binding.timeout.trim().is_empty() { parse_middleware_timeout(&binding.timeout) .map_err(|reason| miette!("{source} has invalid timeout for binding: {reason}"))?; } - if operator_max_body_bytes.is_some_and(|limit| limit > advertised) { + if operator_max_payload_bytes.is_some_and(|limit| limit > advertised) { + return Err(miette!( + "{source} max_payload_bytes ({}) exceeds the binding capability ({advertised})", + operator_max_payload_bytes.expect("operator limit checked above") + )); + } + if operator_max_payload_bytes == Some(0) { return Err(miette!( - "{source} max_body_bytes ({}) exceeds the binding capability ({advertised})", - operator_max_body_bytes.expect("operator limit checked above") + "{source} must configure max_payload_bytes for every payload-bearing binding" )); } } @@ -591,15 +889,46 @@ fn validate_manifest_bindings( fn validate_external_manifest( registration: &SupervisorMiddlewareService, manifest: &MiddlewareManifest, - operator_max_body_bytes: usize, + operator_max_payload_bytes: usize, + authenticated: bool, ) -> Result<()> { validate_manifest_bindings( &format!("external middleware registration '{}'", registration.name), manifest, - Some(operator_max_body_bytes), + Some(operator_max_payload_bytes), + )?; + validate_expected_audience( + ®istration.name, + ®istration.audience, + &manifest.expected_audience, + authenticated && !registration.allow_insecure_transport, ) } +/// After authenticated Describe succeeds, reject a registration whose +/// configured audience differs from the one the service says it verifies. +/// +/// This is a post-authentication consistency assertion, not audience discovery: +/// a strict verifier may reject an incorrect audience before returning its +/// manifest. A service that does not advertise an audience is accepted unchanged. +fn validate_expected_audience( + registration_name: &str, + configured: &str, + advertised: &str, + authenticated: bool, +) -> Result<()> { + if !authenticated || advertised.is_empty() { + return Ok(()); + } + if advertised != configured { + return Err(miette!( + "middleware registration '{registration_name}' expects audience \ + '{advertised}' but OpenShell is configured to mint '{configured}'" + )); + } + Ok(()) +} + /// External diagnostic text is untrusted and may contain request data. Keep /// only values derived from the validated, operator-owned registration name /// and numeric finding counts; do not carry per-request free-form text into @@ -634,7 +963,7 @@ fn normalize_untrusted_diagnostics( } fn validate_request_view(request: HttpRequestView<'_>) -> std::result::Result<(), &'static str> { - if request.body().len() > MAX_MIDDLEWARE_BODY_BYTES { + if request.body().len() > MAX_MIDDLEWARE_PAYLOAD_BYTES { return Err("request_body_over_capacity"); } if request.config().encoded_len() > MAX_MIDDLEWARE_CONFIG_BYTES { @@ -661,7 +990,7 @@ fn validate_request_view(request: HttpRequestView<'_>) -> std::result::Result<() fn validate_response_envelope( result: &openshell_core::proto::HttpRequestResult, ) -> std::result::Result<(), &'static str> { - if result.body.len() > MAX_MIDDLEWARE_BODY_BYTES { + if result.body.len() > MAX_MIDDLEWARE_PAYLOAD_BYTES { return Err("response_body_over_capacity"); } if result.reason.len() > MAX_MIDDLEWARE_REASON_BYTES { @@ -713,13 +1042,32 @@ impl MiddlewareRegistry { pub async fn connect_services( in_process_services: Vec>, registrations: Vec, + ) -> Result { + Self::connect_services_inner(in_process_services, registrations, None).await + } + + /// Connect services with optional refreshable credentials keyed by + /// operator registration name. A configured credential is shared by all + /// generated client clones and can rotate without rebuilding the registry. + pub async fn connect_services_authenticated( + in_process_services: Vec>, + registrations: Vec, + credentials: &HashMap, + ) -> Result { + Self::connect_services_inner(in_process_services, registrations, Some(credentials)).await + } + + async fn connect_services_inner( + in_process_services: Vec>, + registrations: Vec, + credentials: Option<&HashMap>, ) -> Result { let mut services = Vec::with_capacity(in_process_services.len() + registrations.len()); let mut registered_services = Vec::with_capacity(registrations.len()); let mut middleware_names = HashSet::new(); for service in in_process_services { - let service = MiddlewareService::InProcess(service); + let service = MiddlewareDispatch::InProcess(service); let manifest = call_with_timeout(DEFAULT_MIDDLEWARE_TIMEOUT, "Describe", service.describe()) .await @@ -757,7 +1105,7 @@ impl MiddlewareRegistry { service, manifest: manifest_cell, diagnostic_policy: MiddlewareDiagnosticPolicy::Preserve, - operator_max_body_bytes: None, + operator_max_payload_bytes: None, operator_timeout: DEFAULT_MIDDLEWARE_TIMEOUT, })); } @@ -771,17 +1119,35 @@ impl MiddlewareRegistry { )); } - let operator_max_body_bytes = - usize::try_from(registration.max_body_bytes).map_err(|_| { + let operator_max_payload_bytes = usize::try_from(registration.max_payload_bytes) + .map_err(|_| { miette!( - "middleware registration '{}' body limit is too large for this platform", + "middleware registration '{}' payload limit is too large for this platform", registration.name ) })?; - let service = MiddlewareService::Grpc( + // A registration the operator opted out of extension + // authentication carries no credential by design. Every other + // registration must have one, or the connection fails closed + // rather than silently downgrading to an unauthenticated call. + let bearer = credentials + .filter(|_| !registration.allow_insecure_transport) + .map(|credentials| { + credentials.get(®istration.name).cloned().ok_or_else(|| { + miette!( + "middleware registration '{}' is missing its extension credential", + registration.name + ) + }) + }) + .transpose()?; + let authenticated = bearer.is_some(); + let service = MiddlewareDispatch::Grpc( remote::GrpcMiddlewareService::connect( ®istration.name, ®istration.grpc_endpoint, + ®istration.tls_ca_cert_pem, + bearer, ) .await?, ); @@ -795,7 +1161,12 @@ impl MiddlewareRegistry { safe_reason(&error.to_string()) ) })?; - validate_external_manifest(®istration, &manifest, operator_max_body_bytes)?; + validate_external_manifest( + ®istration, + &manifest, + operator_max_payload_bytes, + authenticated, + )?; let manifest_cell = OnceCell::new(); manifest_cell .set(manifest) @@ -805,7 +1176,7 @@ impl MiddlewareRegistry { service, manifest: manifest_cell, diagnostic_policy: MiddlewareDiagnosticPolicy::Normalize, - operator_max_body_bytes: Some(operator_max_body_bytes), + operator_max_payload_bytes: Some(operator_max_payload_bytes), operator_timeout, })); registered_services.push(RegisteredMiddlewareService { registration }); @@ -815,6 +1186,9 @@ impl MiddlewareRegistry { services: Arc::new(services), registered_services: Arc::new(registered_services), middleware_names: Arc::new(middleware_names), + work_admission: Arc::new(Semaphore::new(MAX_CONCURRENT_MIDDLEWARE_WORK)), + work_admission_waiters: Arc::new(Semaphore::new(MAX_QUEUED_MIDDLEWARE_WORK)), + session_admission: Arc::new(Semaphore::new(MAX_CONCURRENT_MIDDLEWARE_SESSIONS)), }) } @@ -886,10 +1260,16 @@ impl ChainRunner { /// Construct a runner around one in-process middleware implementation. #[must_use] pub fn new(service: Arc) -> Self { - Self::from_service(MiddlewareService::InProcess(service)) + Self::from_service(MiddlewareDispatch::InProcess(service)) + } + + /// Construct a runner around a legacy transport-neutral in-process endpoint. + #[must_use] + pub fn from_endpoint(endpoint: Arc) -> Self { + Self::new(in_process_endpoint(endpoint)) } - fn from_service(service: MiddlewareService) -> Self { + fn from_service(service: MiddlewareDispatch) -> Self { Self { registry: Arc::new(MiddlewareRegistry { services: Arc::new(vec![Arc::new(MiddlewareServiceState { @@ -897,19 +1277,24 @@ impl ChainRunner { service, manifest: OnceCell::new(), diagnostic_policy: MiddlewareDiagnosticPolicy::Preserve, - operator_max_body_bytes: None, + operator_max_payload_bytes: None, operator_timeout: DEFAULT_MIDDLEWARE_TIMEOUT, })]), registered_services: Arc::new(Vec::new()), middleware_names: Arc::new(HashSet::new()), + work_admission: Arc::new(Semaphore::new(MAX_CONCURRENT_MIDDLEWARE_WORK)), + work_admission_waiters: Arc::new(Semaphore::new(MAX_QUEUED_MIDDLEWARE_WORK)), + session_admission: Arc::new(Semaphore::new(MAX_CONCURRENT_MIDDLEWARE_SESSIONS)), }), } } #[cfg(test)] - fn new_protobuf_for_tests(service: Arc) -> Self { - Self::from_service(MiddlewareService::Grpc( - remote::GrpcMiddlewareService::from_service(service), + fn new_protobuf_for_tests(service: Arc) -> Self { + let endpoint: Arc = + Arc::new(GeneratedMiddlewareEndpoint { service }); + Self::from_service(MiddlewareDispatch::Grpc( + remote::GrpcMiddlewareService::from_service(endpoint), )) } @@ -919,6 +1304,67 @@ impl ChainRunner { } } + /// Build a runner for a replacement registry while preserving process-wide + /// admission budgets across registry generations. + #[must_use] + pub fn with_replacement_registry(&self, mut registry: MiddlewareRegistry) -> Self { + registry.work_admission = Arc::clone(&self.registry.work_admission); + registry.work_admission_waiters = Arc::clone(&self.registry.work_admission_waiters); + registry.session_admission = Arc::clone(&self.registry.session_admission); + Self::from_registry(registry) + } + + /// Reserve one unit of short-lived middleware work. + /// + /// The bounded waiter queue provides backpressure for work expected to + /// complete promptly, such as HTTP evaluations, WebSocket messages, and + /// streaming-session preflight. + pub async fn reserve_middleware_work(&self) -> Result { + if let Ok(permit) = Arc::clone(&self.registry.work_admission).try_acquire_owned() { + Ok(MiddlewareWorkAdmissionOutcome::Admitted( + MiddlewareWorkAdmission { + _work: permit, + saturated: false, + }, + )) + } else { + let Ok(waiter) = Arc::clone(&self.registry.work_admission_waiters).try_acquire_owned() + else { + return Ok(MiddlewareWorkAdmissionOutcome::QueueExhausted); + }; + let permit = Arc::clone(&self.registry.work_admission) + .acquire_owned() + .await + .map_err(|_| miette!("middleware admission semaphore closed"))?; + drop(waiter); + Ok(MiddlewareWorkAdmissionOutcome::Admitted( + MiddlewareWorkAdmission { + _work: permit, + saturated: true, + }, + )) + } + } + + /// Reserve middleware work for a caller whose established external + /// behavior treats queue exhaustion as a middleware processing failure. + pub async fn reserve_middleware_work_admission(&self) -> Result { + self.reserve_middleware_work().await?.into_admission() + } + + /// Attempt to reserve one persistent middleware session without waiting. + /// + /// Long-lived sessions have no useful queueing bound because their release + /// time is unrelated to middleware latency. Protocol-specific runners apply + /// their own `on_error` semantics when the shared session budget is full. + fn try_reserve_middleware_session(&self) -> MiddlewareSessionAdmission { + Arc::clone(&self.registry.session_admission) + .try_acquire_owned() + .map_or(MiddlewareSessionAdmission::AtCapacity, |permit| { + MiddlewareSessionAdmission::Admitted(MiddlewareSessionPermit { _session: permit }) + }) + } + async fn manifests(&self) -> Result, MiddlewareManifest)>> { let mut manifests = Vec::with_capacity(self.registry.services.len()); for state in self.registry.services.iter() { @@ -951,62 +1397,89 @@ impl ChainRunner { .unwrap_or(manifest.name.as_str()) } - fn http_pre_credentials_binding(manifest: &MiddlewareManifest) -> Option<&MiddlewareBinding> { - manifest.bindings.iter().find(|binding| { - binding.operation == HTTP_REQUEST_OPERATION as i32 - && binding.phase == PRE_CREDENTIALS_PHASE as i32 - }) + fn binding( + manifest: &MiddlewareManifest, + operation: SupervisorMiddlewareOperation, + phase: SupervisorMiddlewarePhase, + ) -> Option<&MiddlewareBinding> { + manifest + .bindings + .iter() + .find(|binding| binding.operation == operation as i32 && binding.phase == phase as i32) } pub async fn describe_chain(&self, entries: &[ChainEntry]) -> Result> { + Ok(self + .describe_chain_for( + entries, + SupervisorMiddlewareOperation::HttpRequest, + SupervisorMiddlewarePhase::PreCredentials, + ) + .await? + .entries) + } + + pub async fn describe_websocket_chain( + &self, + entries: &[ChainEntry], + ) -> Result> { + Ok(self + .describe_chain_for( + entries, + SupervisorMiddlewareOperation::WebsocketMessage, + SupervisorMiddlewarePhase::PreCredentials, + ) + .await? + .entries) + } + + async fn describe_chain_for( + &self, + entries: &[ChainEntry], + operation: SupervisorMiddlewareOperation, + phase: SupervisorMiddlewarePhase, + ) -> Result { ensure_chain_capacity(entries.len())?; let manifests = self.manifests().await?; let mut entries = entries.to_vec(); sort_chain_entries(&mut entries); - entries - .iter() - .map(|entry| { - let described = manifests - .iter() - .find(|(state, manifest)| { - Self::attachment_name(state, manifest) == entry.implementation - }) - .and_then(|(state, manifest)| { - Self::http_pre_credentials_binding(manifest) - .cloned() - .map(|binding| (Arc::clone(state), binding)) - }); - let (service, binding) = described.map_or((None, None), |(service, binding)| { - (Some(service), Some(binding)) + let mut described_entries = Vec::with_capacity(entries.len()); + let mut unbound = Vec::new(); + for entry in entries { + let Some((state, manifest)) = manifests.iter().find(|(state, manifest)| { + Self::attachment_name(state, manifest) == entry.implementation + }) else { + described_entries.push(DescribedChainEntry { + entry, + service: None, + binding: None, + max_payload_bytes: 0, + timeout: DEFAULT_MIDDLEWARE_TIMEOUT, }); - let max_body_bytes = binding - .as_ref() - .map(|binding| { - let advertised = validate_body_limit("middleware manifest", binding)?; - Ok::<_, miette::Report>( - service - .as_ref() - .and_then(|state| state.operator_max_body_bytes) - .unwrap_or(advertised), - ) - }) - .transpose()? - .unwrap_or(0); - let timeout = service - .as_ref() - .zip(binding.as_ref()) - .map(|(state, binding)| state.timeout_for_binding(binding)) - .transpose()? - .unwrap_or(DEFAULT_MIDDLEWARE_TIMEOUT); - Ok(DescribedChainEntry { - entry: entry.clone(), - service, - binding, - max_body_bytes, - timeout, - }) - }) - .collect() + continue; + }; + let Some(binding) = Self::binding(manifest, operation, phase).cloned() else { + // The config remains globally ordered, but it does not + // participate in this exact operation/phase chain. + unbound.push(entry); + continue; + }; + let timeout = state.timeout_for_binding(&binding)?; + let advertised = validate_payload_limit("middleware manifest", &binding)?; + let max_payload_bytes = state.operator_max_payload_bytes.unwrap_or(advertised); + described_entries.push(DescribedChainEntry { + entry, + service: Some(Arc::clone(state)), + binding: Some(binding), + max_payload_bytes, + timeout, + }); + } + ensure_chain_capacity(described_entries.len())?; + Ok(DescribedChain { + entries: described_entries, + unbound, + }) } pub async fn validate_config( @@ -1020,16 +1493,14 @@ impl ChainRunner { )); } let manifests = self.manifests().await?; - let Some((state, binding)) = manifests.iter().find_map(|(state, manifest)| { - (Self::attachment_name(state, manifest) == middleware_name) - .then(|| Self::http_pre_credentials_binding(manifest)) - .flatten() - .map(|binding| (state, binding)) - }) else { + let Some((state, _manifest)) = manifests + .iter() + .find(|(state, manifest)| Self::attachment_name(state, manifest) == middleware_name) + else { return Err(miette!("middleware '{middleware_name}' is not registered")); }; let response = call_with_timeout( - state.timeout_for_binding(binding)?, + state.operator_timeout, "ValidateConfig", state.service.validate_config(middleware_name, &config), ) @@ -1082,6 +1553,29 @@ impl ChainRunner { entries: &[DescribedChainEntry], input: HttpRequestInput, transformed_body_policy: TransformedBodyPolicy<'_>, + ) -> Result { + let admission = if entries.is_empty() { + None + } else { + Some(self.reserve_middleware_work_admission().await?) + }; + self.evaluate_described_with_policy_admitted( + entries, + input, + transformed_body_policy, + admission, + ) + .await + } + + /// Evaluate a chain using capacity reserved before its request body was + /// buffered. The guard is retained until the ordered chain completes. + pub async fn evaluate_described_with_policy_admitted( + &self, + entries: &[DescribedChainEntry], + input: HttpRequestInput, + transformed_body_policy: TransformedBodyPolicy<'_>, + admission: Option, ) -> Result { ensure_chain_capacity(entries.len())?; let HttpRequestInput { @@ -1122,6 +1616,8 @@ impl ChainRunner { let mut findings = Vec::new(); let mut metadata = BTreeMap::new(); let mut applied = Vec::new(); + let _admission = admission; + let chain_deadline = tokio::time::Instant::now() + MAX_MIDDLEWARE_CHAIN_TIMEOUT; for entry in entries { let Some(_binding) = entry.binding.as_ref() else { @@ -1141,7 +1637,7 @@ impl ChainRunner { } } }; - if body.len() > entry.max_body_bytes { + if body.len() > entry.max_payload_bytes { match apply_on_error(entry, "request_body_over_capacity", &mut applied) { OnErrorAction::FailOpen => continue, OnErrorAction::FailClosed(reason) => { @@ -1187,8 +1683,26 @@ impl ChainRunner { let Some(service) = entry.service.as_ref() else { unreachable!("described binding always has a service") }; + let remaining = chain_deadline.saturating_duration_since(tokio::time::Instant::now()); + if remaining.is_zero() { + match apply_on_error(entry, "middleware_chain_timeout", &mut applied) { + OnErrorAction::FailOpen => continue, + OnErrorAction::FailClosed(reason) => { + return Ok(ChainOutcome { + allowed: false, + reason, + body, + header_mutations, + findings, + metadata, + applied, + denial: None, + }); + } + } + } let mut result = match call_with_timeout( - entry.timeout, + entry.timeout.min(remaining), "EvaluateHttpRequest", service.service.evaluate_http_request(request), ) @@ -1303,7 +1817,7 @@ impl ChainRunner { }); } - if result.has_body && result.body.len() > entry.max_body_bytes { + if result.has_body && result.body.len() > entry.max_payload_bytes { match apply_on_error(entry, "response_body_over_capacity", &mut applied) { OnErrorAction::FailOpen => continue, OnErrorAction::FailClosed(reason) => { @@ -1468,15 +1982,43 @@ pub(crate) fn safe_reason(reason: &str) -> String { #[cfg(test)] mod tests { use super::*; + use futures::{FutureExt, Stream, StreamExt}; use openshell_core::proto::middleware::v1::supervisor_middleware_server::{ SupervisorMiddleware, SupervisorMiddlewareServer, }; use openshell_core::proto::{ExistingHeaderAction, header_mutation}; use openshell_supervisor_middleware_builtins::{BUILTIN_REGEX, services}; + use tokio_stream::wrappers::TcpListenerStream; - fn builtin_runner() -> ChainRunner { - ChainRunner::new( + #[test] + fn advertised_audience_mismatch_fails_registration() { + let configured = "urn:openshell:extension:middleware:content-guard"; + + // Matching and unadvertised audiences both pass. + validate_expected_audience("content-guard", configured, "", true) + .expect("unadvertised audience is accepted"); + validate_expected_audience("content-guard", configured, configured, true) + .expect("matching audience is accepted"); + + // Once authenticated Describe succeeds, reject a manifest that + // contradicts the operator-owned audience configuration. + let error = + validate_expected_audience("content-guard", configured, "urn:example:stale", true) + .expect_err("mismatched audience must fail closed"); + let message = error.to_string(); + assert!(message.contains("urn:example:stale")); + assert!(message.contains(configured)); + + // The check does not apply where no credential is attached at all, + // whether because the registration opted out or because the gateway + // has no signing key configured. + validate_expected_audience("content-guard", configured, "urn:example:stale", false) + .expect("an unauthenticated call has no audience to mismatch"); + } + + fn builtin_runner() -> ChainRunner { + ChainRunner::new( services() .into_iter() .next() @@ -1561,9 +2103,10 @@ mod tests { bindings: vec![MiddlewareBinding { operation: SupervisorMiddlewareOperation::HttpRequest as i32, phase: SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: 4096, + max_payload_bytes: 4096, timeout: String::new(), }], + expected_audience: String::new(), } } @@ -1696,9 +2239,10 @@ mod tests { bindings: vec![MiddlewareBinding { operation: SupervisorMiddlewareOperation::HttpRequest as i32, phase: SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: 4096, + max_payload_bytes: 4096, timeout: String::new(), }], + expected_audience: String::new(), } } @@ -1786,9 +2330,10 @@ mod tests { bindings: vec![MiddlewareBinding { operation: SupervisorMiddlewareOperation::HttpRequest as i32, phase: SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: 4096, + max_payload_bytes: 4096, timeout: "10ms".into(), }], + expected_audience: String::new(), } } @@ -2025,6 +2570,16 @@ mod tests { #[tonic::async_trait] impl SupervisorMiddleware for ScriptedService { + type EvaluateWebSocketSessionStream = WebSocketResponseStream; + + async fn evaluate_web_socket_session( + &self, + _request: Request>, + ) -> std::result::Result, tonic::Status> + { + Err(tonic::Status::unimplemented("HTTP-only test middleware")) + } + async fn describe( &self, _request: Request<()>, @@ -2035,9 +2590,10 @@ mod tests { bindings: vec![MiddlewareBinding { operation: SupervisorMiddlewareOperation::HttpRequest as i32, phase: SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: self.max_body_bytes, + max_payload_bytes: self.max_body_bytes, timeout: String::new(), }], + expected_audience: String::new(), })) } @@ -2069,6 +2625,16 @@ mod tests { #[tonic::async_trait] impl SupervisorMiddleware for SlowService { + type EvaluateWebSocketSessionStream = WebSocketResponseStream; + + async fn evaluate_web_socket_session( + &self, + _request: Request>, + ) -> std::result::Result, tonic::Status> + { + Err(tonic::Status::unimplemented("HTTP-only test middleware")) + } + async fn describe( &self, _request: Request<()>, @@ -2079,9 +2645,10 @@ mod tests { bindings: vec![MiddlewareBinding { operation: SupervisorMiddlewareOperation::HttpRequest as i32, phase: SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: 4096, + max_payload_bytes: 4096, timeout: self.binding_timeout.clone(), }], + expected_audience: String::new(), })) } @@ -2117,6 +2684,16 @@ mod tests { #[tonic::async_trait] impl SupervisorMiddleware for TwoStageService { + type EvaluateWebSocketSessionStream = WebSocketResponseStream; + + async fn evaluate_web_socket_session( + &self, + _request: Request>, + ) -> std::result::Result, tonic::Status> + { + Err(tonic::Status::unimplemented("HTTP-only test middleware")) + } + async fn describe( &self, _request: Request<()>, @@ -2127,9 +2704,10 @@ mod tests { bindings: vec![MiddlewareBinding { operation: SupervisorMiddlewareOperation::HttpRequest as i32, phase: SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: 256 * 1024, + max_payload_bytes: 256 * 1024, timeout: String::new(), }], + expected_audience: String::new(), })) } @@ -2176,7 +2754,7 @@ mod tests { // must stop there: the second stage never runs, so it never sees a // payload the policy would reject. let second_ran = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let service: Arc = Arc::new(TwoStageService { + let service: Arc = Arc::new(TwoStageService { second_ran: Arc::clone(&second_ran), }); let runner = ChainRunner::new_protobuf_for_tests(service); @@ -2238,7 +2816,7 @@ mod tests { // A validator that accepts every body lets both stages run; the second // stage sees the first stage's output. let second_ran = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let service: Arc = Arc::new(TwoStageService { + let service: Arc = Arc::new(TwoStageService { second_ran: Arc::clone(&second_ran), }); let runner = ChainRunner::new_protobuf_for_tests(service); @@ -2290,7 +2868,7 @@ mod tests { #[tokio::test] async fn per_stage_validator_error_becomes_structured_denial() { let second_ran = Arc::new(std::sync::atomic::AtomicBool::new(false)); - let service: Arc = Arc::new(TwoStageService { + let service: Arc = Arc::new(TwoStageService { second_ran: Arc::clone(&second_ran), }); let runner = ChainRunner::new_protobuf_for_tests(service); @@ -2376,6 +2954,16 @@ mod tests { #[tonic::async_trait] impl SupervisorMiddleware for RecordingService { + type EvaluateWebSocketSessionStream = WebSocketResponseStream; + + async fn evaluate_web_socket_session( + &self, + _request: Request>, + ) -> std::result::Result, tonic::Status> + { + Err(tonic::Status::unimplemented("HTTP-only test middleware")) + } + async fn describe( &self, _request: Request<()>, @@ -2386,9 +2974,10 @@ mod tests { bindings: vec![MiddlewareBinding { operation: SupervisorMiddlewareOperation::HttpRequest as i32, phase: SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: 4096, + max_payload_bytes: 4096, timeout: String::new(), }], + expected_audience: String::new(), })) } @@ -2430,6 +3019,16 @@ mod tests { #[tonic::async_trait] impl SupervisorMiddleware for HeaderChainService { + type EvaluateWebSocketSessionStream = WebSocketResponseStream; + + async fn evaluate_web_socket_session( + &self, + _request: Request>, + ) -> std::result::Result, tonic::Status> + { + Err(tonic::Status::unimplemented("HTTP-only test middleware")) + } + async fn describe( &self, _request: Request<()>, @@ -2440,9 +3039,10 @@ mod tests { bindings: vec![MiddlewareBinding { operation: SupervisorMiddlewareOperation::HttpRequest as i32, phase: SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: 4096, + max_payload_bytes: 4096, timeout: String::new(), }], + expected_audience: String::new(), })) } @@ -2550,7 +3150,7 @@ mod tests { validated: std::sync::Mutex::new(Vec::new()), received: std::sync::Mutex::new(Vec::new()), }); - let recorder: Arc = service.clone(); + let recorder: Arc = service.clone(); let runner = ChainRunner::new_protobuf_for_tests(recorder); let validation_config = prost_types::Struct { fields: std::iter::once(( @@ -2639,17 +3239,17 @@ mod tests { ); } - fn external_registration(max_body_bytes: u64) -> SupervisorMiddlewareService { + fn external_registration(max_payload_bytes: u64) -> SupervisorMiddlewareService { SupervisorMiddlewareService { name: "local-guard-service".into(), grpc_endpoint: "http://127.0.0.1:50051".into(), - max_body_bytes, + max_payload_bytes, ..Default::default() } } async fn registry_with_external( - service: Arc, + service: Arc, registration: SupervisorMiddlewareService, ) -> MiddlewareRegistry { let builtin_service = services() @@ -2670,9 +3270,9 @@ mod tests { .await .expect("describe test service") .into_inner(); - let operator_max_body_bytes = usize::try_from(registration.max_body_bytes).unwrap(); + let operator_max_payload_bytes = usize::try_from(registration.max_payload_bytes).unwrap(); let operator_timeout = validate_registration(®istration).expect("valid registration"); - validate_external_manifest(®istration, &manifest, operator_max_body_bytes) + validate_external_manifest(®istration, &manifest, operator_max_payload_bytes, false) .expect("valid external manifest"); let manifest_cell = OnceCell::new(); manifest_cell.set(manifest).expect("manifest cache"); @@ -2681,25 +3281,28 @@ mod tests { services: Arc::new(vec![ Arc::new(MiddlewareServiceState { attachment_name: Some(builtin_name.clone()), - service: MiddlewareService::InProcess(builtin_service), + service: MiddlewareDispatch::InProcess(builtin_service), manifest: builtin_manifest_cell, diagnostic_policy: MiddlewareDiagnosticPolicy::Preserve, - operator_max_body_bytes: None, + operator_max_payload_bytes: None, operator_timeout: DEFAULT_MIDDLEWARE_TIMEOUT, }), Arc::new(MiddlewareServiceState { attachment_name: Some(registration_name.clone()), - service: MiddlewareService::Grpc(remote::GrpcMiddlewareService::from_service( - service, + service: MiddlewareDispatch::Grpc(remote::GrpcMiddlewareService::from_service( + Arc::new(GeneratedMiddlewareEndpoint { service }), )), manifest: manifest_cell, diagnostic_policy: MiddlewareDiagnosticPolicy::Normalize, - operator_max_body_bytes: Some(operator_max_body_bytes), + operator_max_payload_bytes: Some(operator_max_payload_bytes), operator_timeout, }), ]), registered_services: Arc::new(vec![RegisteredMiddlewareService { registration }]), middleware_names: Arc::new(HashSet::from([builtin_name, registration_name])), + work_admission: Arc::new(Semaphore::new(MAX_CONCURRENT_MIDDLEWARE_WORK)), + work_admission_waiters: Arc::new(Semaphore::new(MAX_QUEUED_MIDDLEWARE_WORK)), + session_admission: Arc::new(Semaphore::new(MAX_CONCURRENT_MIDDLEWARE_SESSIONS)), } } @@ -2719,7 +3322,7 @@ mod tests { // The built-in resolves and reports its real limit; the missing binding // does not resolve and must not contribute a body limit. assert!(described[0].is_resolved()); - assert_eq!(described[0].max_body_bytes(), 256 * 1024); + assert_eq!(described[0].max_payload_bytes(), 256 * 1024); assert!(!described[1].is_resolved()); } @@ -2742,7 +3345,7 @@ mod tests { .describe_chain(std::slice::from_ref(&entry)) .await .expect("describe external middleware"); - assert_eq!(described[0].max_body_bytes(), 4096); + assert_eq!(described[0].max_payload_bytes(), 4096); assert_eq!( described[0] .binding @@ -2781,8 +3384,8 @@ mod tests { .describe_chain(&entries) .await .expect("describe chain"); - assert_eq!(described[0].max_body_bytes(), 256 * 1024); - assert_eq!(described[1].max_body_bytes(), 1024); + assert_eq!(described[0].max_payload_bytes(), 256 * 1024); + assert_eq!(described[1].max_payload_bytes(), 1024); let outcome = runner .evaluate_described(&described, input(r#"token="sk-ABCDEFGHIJKLMNOP""#)) @@ -2888,25 +3491,26 @@ mod tests { bindings: vec![MiddlewareBinding { operation: HTTP_REQUEST_OPERATION as i32, phase: PRE_CREDENTIALS_PHASE as i32, - max_body_bytes: 4096, + max_payload_bytes: 4096, timeout: String::new(), }], + expected_audience: String::new(), }; - let error = validate_external_manifest(®istration, &manifest, 4097) + let error = validate_external_manifest(®istration, &manifest, 4097, false) .expect_err("operator limit must fit capability"); assert!(error.to_string().contains("exceeds")); } #[test] - fn external_registration_rejects_body_limit_above_platform_maximum() { + fn external_registration_rejects_payload_limit_above_platform_maximum() { let registration = external_registration(u64::MAX); let error = validate_registration(®istration) - .expect_err("extreme body limit must be rejected before allocation"); + .expect_err("extreme payload limit must be rejected before allocation"); assert!(error.to_string().contains("platform maximum")); } #[test] - fn manifest_rejects_body_limit_above_platform_maximum() { + fn manifest_rejects_payload_limit_above_platform_maximum() { let registration = external_registration(4096); let manifest = MiddlewareManifest { name: "example/service".into(), @@ -2914,12 +3518,13 @@ mod tests { bindings: vec![MiddlewareBinding { operation: HTTP_REQUEST_OPERATION as i32, phase: PRE_CREDENTIALS_PHASE as i32, - max_body_bytes: u64::MAX, + max_payload_bytes: u64::MAX, timeout: String::new(), }], + expected_audience: String::new(), }; - let error = validate_external_manifest(®istration, &manifest, 4096) - .expect_err("extreme advertised body limit must be rejected"); + let error = validate_external_manifest(®istration, &manifest, 4096, false) + .expect_err("extreme advertised payload limit must be rejected"); assert!(error.to_string().contains("platform maximum")); } @@ -2929,24 +3534,92 @@ mod tests { let binding = || MiddlewareBinding { operation: HTTP_REQUEST_OPERATION as i32, phase: PRE_CREDENTIALS_PHASE as i32, - max_body_bytes: 4096, + max_payload_bytes: 4096, timeout: String::new(), }; let manifest = MiddlewareManifest { name: "example/service".into(), service_version: "test".into(), bindings: vec![binding(), binding()], + expected_audience: String::new(), }; - let error = validate_external_manifest(®istration, &manifest, 4096) + let error = validate_external_manifest(®istration, &manifest, 4096, false) .expect_err("one service cannot advertise two bindings for the same pair"); assert!( error .to_string() - .contains("more than one binding for HTTP_REQUEST/PRE_CREDENTIALS") + .contains("duplicate middleware operation/phase pair") ); } + #[test] + fn manifest_accepts_forward_websocket_binding_and_reserves_return_phase() { + let binding = |phase| MiddlewareBinding { + operation: SupervisorMiddlewareOperation::WebsocketMessage as i32, + phase: phase as i32, + max_payload_bytes: MAX_MIDDLEWARE_PAYLOAD_BYTES as u64, + timeout: "500ms".into(), + }; + let mut manifest = MiddlewareManifest { + name: "example/websocket".into(), + service_version: "test".into(), + bindings: vec![binding(SupervisorMiddlewarePhase::PreCredentials)], + expected_audience: String::new(), + }; + validate_manifest_bindings("test WebSocket service", &manifest, None) + .expect("forward WebSocket binding is supported"); + + manifest.bindings = vec![binding(SupervisorMiddlewarePhase::PreReturn)]; + let error = validate_manifest_bindings("test WebSocket service", &manifest, None) + .expect_err("return-path binding stays reserved for PR 2"); + assert!(error.to_string().contains("reserved for PR 2")); + } + + #[test] + fn external_websocket_binding_requires_operator_payload_limit() { + let registration = external_registration(0); + let manifest = MiddlewareManifest { + name: "example/websocket".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: SupervisorMiddlewareOperation::WebsocketMessage as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_payload_bytes: 4096, + timeout: String::new(), + }], + expected_audience: String::new(), + }; + + let error = validate_external_manifest(®istration, &manifest, 0, false) + .expect_err("WebSocket bindings require an operator payload ceiling"); + assert!( + error + .to_string() + .contains("must configure max_payload_bytes") + ); + } + + #[test] + fn external_websocket_binding_rejects_operator_limit_above_capability() { + let registration = external_registration(4097); + let manifest = MiddlewareManifest { + name: "example/websocket".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: SupervisorMiddlewareOperation::WebsocketMessage as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_payload_bytes: 4096, + timeout: String::new(), + }], + expected_audience: String::new(), + }; + + let error = validate_external_manifest(®istration, &manifest, 4097, false) + .expect_err("operator payload limit must fit WebSocket capability"); + assert!(error.to_string().contains("exceeds")); + } + #[test] fn external_registration_accepts_http_and_https_grpc_endpoints() { for grpc_endpoint in [ @@ -3010,11 +3683,12 @@ mod tests { bindings: vec![MiddlewareBinding { operation: HTTP_REQUEST_OPERATION as i32, phase: PRE_CREDENTIALS_PHASE as i32, - max_body_bytes: 4096, + max_payload_bytes: 4096, timeout: timeout.into(), }], + expected_audience: String::new(), }; - let error = validate_external_manifest(®istration, &manifest, 4096) + let error = validate_external_manifest(®istration, &manifest, 4096, false) .expect_err("out-of-bounds binding timeout must be rejected"); assert!(error.to_string().contains("invalid timeout")); } @@ -3249,11 +3923,11 @@ mod tests { .add_service( SupervisorMiddlewareServer::new(ScriptedService { manifest_name: "test/middleware".into(), - max_body_bytes: MAX_MIDDLEWARE_BODY_BYTES as u64, + max_body_bytes: MAX_MIDDLEWARE_PAYLOAD_BYTES as u64, result: openshell_core::proto::HttpRequestResult { reason: "r".repeat(MAX_MIDDLEWARE_REASON_BYTES - 128), reason_code: "r".repeat(MAX_MIDDLEWARE_REASON_CODE_BYTES), - body: vec![b'x'; MAX_MIDDLEWARE_BODY_BYTES], + body: vec![b'x'; MAX_MIDDLEWARE_PAYLOAD_BYTES], has_body: true, header_mutations: vec![write_header( "x-openshell-middleware-envelope", @@ -3277,7 +3951,7 @@ mod tests { }); let server_task = tokio::spawn(server); - let mut registration = external_registration(MAX_MIDDLEWARE_BODY_BYTES as u64); + let mut registration = external_registration(MAX_MIDDLEWARE_PAYLOAD_BYTES as u64); registration.grpc_endpoint = format!("http://{address}"); let registry = MiddlewareRegistry::connect_services(Vec::new(), vec![registration]) .await @@ -3301,7 +3975,7 @@ mod tests { "x-large-envelope".into(), "v".repeat(MAX_MIDDLEWARE_HEADER_BYTES - 256), )]; - request.body = vec![b'b'; MAX_MIDDLEWARE_BODY_BYTES]; + request.body = vec![b'b'; MAX_MIDDLEWARE_PAYLOAD_BYTES]; let outcome = ChainRunner::from_registry(registry) .evaluate( &[ChainEntry { @@ -3317,7 +3991,7 @@ mod tests { .expect("maximum bounded envelopes should fit configured transport limit"); assert!(outcome.allowed); - assert_eq!(outcome.body.len(), MAX_MIDDLEWARE_BODY_BYTES); + assert_eq!(outcome.body.len(), MAX_MIDDLEWARE_PAYLOAD_BYTES); assert_eq!(outcome.header_mutations.len(), 1); assert_eq!(outcome.findings.len(), MAX_MIDDLEWARE_FINDINGS_PER_STAGE); let _ = shutdown_tx.send(()); @@ -3332,7 +4006,7 @@ mod tests { assert_eq!(MIDDLEWARE_GRPC_ENVELOPE_BYTES, 292 * 1024 + 64); assert_eq!( MIDDLEWARE_GRPC_MESSAGE_BYTES, - MAX_MIDDLEWARE_BODY_BYTES + 292 * 1024 + 64 + MAX_MIDDLEWARE_PAYLOAD_BYTES + 292 * 1024 + 64 ); } @@ -3873,4 +4547,1322 @@ mod tests { ); assert!(outcome.applied[0].failed); } + + #[derive(Clone, Default)] + struct OpenAiRedactionService { + preflight: Arc>>, + manifest_name: String, + describe_calls: Arc, + skip: bool, + deny: bool, + preflight_reason: String, + preflight_reason_code: String, + preflight_findings: Vec, + preflight_metadata: HashMap, + close_on_first_message: bool, + messages: Arc, + session_ends: Option< + tokio::sync::mpsc::UnboundedSender, + >, + } + + impl OpenAiRedactionService { + fn websocket_stream(&self, mut requests: S) -> WebSocketResponseStream + where + S: Stream< + Item = std::result::Result< + openshell_core::proto::WebSocketSessionEvent, + tonic::Status, + >, + > + Send + + Unpin + + 'static, + { + use openshell_core::proto::{ + WebSocketMessageResult, WebSocketPreflightAction, WebSocketPreflightDecision, + WebSocketSessionEventResult, web_socket_message, web_socket_message_result, + web_socket_session_event, web_socket_session_event_result, + }; + + let preflight = Arc::clone(&self.preflight); + let skip = self.skip; + let deny = self.deny; + let preflight_reason = self.preflight_reason.clone(); + let preflight_reason_code = self.preflight_reason_code.clone(); + let preflight_findings = self.preflight_findings.clone(); + let preflight_metadata = self.preflight_metadata.clone(); + let close_on_first_message = self.close_on_first_message; + let messages = Arc::clone(&self.messages); + let session_ends = self.session_ends.clone(); + let (responses_tx, responses_rx) = tokio::sync::mpsc::channel(4); + tokio::spawn(async move { + while let Some(Ok(request)) = requests.next().await { + let response = match request.event { + Some(web_socket_session_event::Event::Preflight(value)) => { + *preflight.lock().expect("preflight lock") = Some(value); + Some(WebSocketSessionEventResult { + result: Some( + web_socket_session_event_result::Result::PreflightDecision( + WebSocketPreflightDecision { + action: if deny { + WebSocketPreflightAction::Deny as i32 + } else if skip { + WebSocketPreflightAction::Skip as i32 + } else { + WebSocketPreflightAction::Inspect as i32 + }, + reason: preflight_reason.clone(), + findings: preflight_findings.clone(), + metadata: preflight_metadata.clone(), + reason_code: preflight_reason_code.clone(), + }, + ), + ), + }) + } + Some(web_socket_session_event::Event::Message(value)) => { + messages.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if close_on_first_message { + break; + } + let web_socket_message::Payload::Text(payload) = + value.payload.expect("test OpenAI event payload") + else { + panic!("test OpenAI event must be text"); + }; + let payload = payload.replace("customer-secret", "[REDACTED]"); + Some(WebSocketSessionEventResult { + result: Some( + web_socket_session_event_result::Result::MessageResult( + WebSocketMessageResult { + sequence: value.sequence, + decision: Decision::Allow as i32, + replacement: Some( + web_socket_message_result::Replacement::Text( + payload, + ), + ), + reason_code: "redacted".into(), + ..Default::default() + }, + ), + ), + }) + } + Some(web_socket_session_event::Event::SessionStart(_)) | None => None, + Some(web_socket_session_event::Event::SessionEnd(end)) => { + if let Some(session_ends) = &session_ends + && let Ok(reason) = + openshell_core::proto::WebSocketSessionEndReason::try_from( + end.reason, + ) + { + let _ = session_ends.send(reason); + } + None + } + }; + if let Some(response) = response + && responses_tx.send(Ok(response)).await.is_err() + { + break; + } + } + }); + Box::pin(tokio_stream::wrappers::ReceiverStream::new(responses_rx)) + } + } + + fn websocket_preflight_input(session_id: impl Into) -> WebSocketPreflightInput { + WebSocketPreflightInput { + session_id: session_id.into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "wss".into(), + host: "api.openai.com".into(), + port: 443, + path: "/v1/responses".into(), + requested_subprotocols: Vec::new(), + } + } + + #[tonic::async_trait] + impl SupervisorMiddleware for OpenAiRedactionService { + type EvaluateWebSocketSessionStream = WebSocketResponseStream; + + async fn describe( + &self, + _request: Request<()>, + ) -> std::result::Result, tonic::Status> { + self.describe_calls + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + Ok(tonic::Response::new(MiddlewareManifest { + name: if self.manifest_name.is_empty() { + "test/openai-websocket-redactor".into() + } else { + self.manifest_name.clone() + }, + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: SupervisorMiddlewareOperation::WebsocketMessage as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_payload_bytes: MAX_MIDDLEWARE_PAYLOAD_BYTES as u64, + timeout: "1s".into(), + }], + expected_audience: String::new(), + })) + } + + async fn validate_config( + &self, + _request: Request, + ) -> std::result::Result, tonic::Status> { + Ok(tonic::Response::new(ValidateConfigResponse { + valid: true, + reason: String::new(), + })) + } + + async fn evaluate_http_request( + &self, + _request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Err(tonic::Status::unimplemented( + "WebSocket-only test middleware", + )) + } + + async fn evaluate_web_socket_session( + &self, + request: Request>, + ) -> std::result::Result, tonic::Status> + { + Ok(tonic::Response::new( + self.websocket_stream(request.into_inner()), + )) + } + } + + #[tonic::async_trait] + impl SupervisorMiddlewareEndpoint for OpenAiRedactionService { + async fn describe( + &self, + request: Request<()>, + ) -> std::result::Result, tonic::Status> { + SupervisorMiddleware::describe(self, request).await + } + + async fn validate_config( + &self, + request: Request, + ) -> std::result::Result, tonic::Status> { + SupervisorMiddleware::validate_config(self, request).await + } + + async fn evaluate_http_request( + &self, + request: Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + SupervisorMiddleware::evaluate_http_request(self, request).await + } + + async fn open_websocket_session( + &self, + receiver: tokio::sync::mpsc::Receiver, + ) -> std::result::Result { + Ok( + self.websocket_stream( + tokio_stream::wrappers::ReceiverStream::new(receiver).map(Ok), + ), + ) + } + } + + fn websocket_entry( + name: &str, + implementation: &str, + order: i32, + on_error: OnError, + ) -> ChainEntry { + ChainEntry { + name: name.into(), + implementation: implementation.into(), + order, + config: prost_types::Struct::default(), + on_error, + } + } + + #[tokio::test] + async fn empty_websocket_chain_skips_describe_and_preflight() { + let service = OpenAiRedactionService::default(); + let describe_calls = Arc::clone(&service.describe_calls); + let observed_preflight = Arc::clone(&service.preflight); + let runner = ChainRunner::from_endpoint(Arc::new(service)); + + let outcome = runner + .preflight_websocket(&[], websocket_preflight_input("empty-chain")) + .await + .expect("empty preflight"); + + assert!(outcome.allowed); + assert_eq!(outcome.terminal_reason, None); + assert!(outcome.session.is_none()); + assert!(outcome.invocations.is_empty()); + assert_eq!(describe_calls.load(std::sync::atomic::Ordering::SeqCst), 0); + assert!(observed_preflight.lock().expect("preflight lock").is_none()); + } + + #[tokio::test] + async fn http_only_attachments_are_reported_but_do_not_select_websocket_stages() { + for on_error in [OnError::FailClosed, OnError::FailOpen] { + let runner = ChainRunner::new_protobuf_for_tests(Arc::new(ScriptedService { + manifest_name: "test/http-only".into(), + max_body_bytes: 4096, + result: allow_result(), + })); + let chain = [ChainEntry { + name: "http-guard".into(), + implementation: "test/http-only".into(), + order: 0, + config: prost_types::Struct::default(), + on_error, + }]; + + let outcome = runner + .preflight_websocket( + &chain, + websocket_preflight_input(format!("http-only-{on_error:?}")), + ) + .await + .expect("HTTP-only attachment coverage"); + + assert!(outcome.allowed); + assert_eq!(outcome.terminal_reason, None); + assert!(outcome.session.is_none()); + assert!(outcome.invocations.is_empty()); + assert_eq!( + outcome.coverage, + [WebSocketCoverage { + config_name: "http-guard".into(), + implementation: "test/http-only".into(), + state: WebSocketCoverageState::BindingNotSelected, + sequence: None, + message_type: None, + original_size: 0, + }] + ); + } + } + + #[tokio::test] + async fn http_only_attachment_allows_33_requested_subprotocols() { + let runner = ChainRunner::new_protobuf_for_tests(Arc::new(ScriptedService { + manifest_name: "test/http-only".into(), + max_body_bytes: 4096, + result: allow_result(), + })); + let chain = [ChainEntry { + name: "http-guard".into(), + implementation: "test/http-only".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }]; + let mut input = websocket_preflight_input("http-only-many-subprotocols"); + input.requested_subprotocols = (0..33) + .map(|index| format!("subprotocol-{index}")) + .collect(); + + let outcome = runner + .preflight_websocket(&chain, input) + .await + .expect("HTTP-only attachment must not validate a WebSocket middleware envelope"); + + assert!(outcome.allowed); + assert_eq!(outcome.terminal_reason, None); + assert!(outcome.session.is_none()); + assert!(outcome.invocations.is_empty()); + assert_eq!( + outcome.coverage, + [WebSocketCoverage { + config_name: "http-guard".into(), + implementation: "test/http-only".into(), + state: WebSocketCoverageState::BindingNotSelected, + sequence: None, + message_type: None, + original_size: 0, + }] + ); + } + + #[tokio::test] + async fn unsupported_binary_messages_advance_sequence_without_applying_on_error() { + for on_error in [OnError::FailClosed, OnError::FailOpen] { + let runner = builtin_runner(); + let chain = [entry("regex-redactor", on_error)]; + let preflight = runner + .preflight_websocket( + &chain, + websocket_preflight_input(format!("binary-{on_error:?}")), + ) + .await + .expect("preflight"); + let mut session = preflight.session.expect("built-in inspects text"); + assert!(session.start("").await.allowed); + + let coverage = session.observe_unsupported_message(WebSocketMessageType::Binary, 23); + assert_eq!( + coverage, + [WebSocketCoverage { + config_name: "regex-redactor".into(), + implementation: BUILTIN_REGEX.into(), + state: WebSocketCoverageState::UnsupportedMessageType, + sequence: Some(1), + message_type: Some(WebSocketMessageType::Binary), + original_size: 23, + }] + ); + + let text = session.evaluate_text(r#"{"input":"safe"}"#.into()).await; + assert!(text.allowed); + assert_eq!(text.invocations[0].sequence, Some(2)); + assert!(!text.invocations[0].failed); + + session + .end(openshell_core::proto::WebSocketSessionEndReason::NormalClose) + .await; + } + } + + #[tokio::test] + async fn explicit_websocket_preflight_denial_is_authoritative_for_both_error_modes() { + use openshell_core::proto::WebSocketSessionEndReason; + + for on_error in [OnError::FailOpen, OnError::FailClosed] { + let (session_ends_tx, mut session_ends_rx) = tokio::sync::mpsc::unbounded_channel(); + let runner = ChainRunner::from_endpoint(Arc::new(OpenAiRedactionService { + deny: true, + preflight_reason: "contains sensitive request data".into(), + preflight_reason_code: "upgrade_blocked".into(), + preflight_findings: vec![Finding { + r#type: "content.sensitive".into(), + label: "Sensitive content".into(), + count: 1, + confidence: "high".into(), + severity: "high".into(), + }], + preflight_metadata: HashMap::from([("policy_version".into(), "1".into())]), + session_ends: Some(session_ends_tx), + ..Default::default() + })); + + let outcome = runner + .preflight_websocket( + &[websocket_entry( + "deny-upgrade", + "test/openai-websocket-redactor", + 0, + on_error, + )], + websocket_preflight_input("explicit-denial"), + ) + .await + .expect("denied preflight"); + + assert!(!outcome.allowed); + assert_eq!( + outcome.terminal_reason, + Some(WebSocketSessionEndReason::MiddlewareDenial) + ); + assert_eq!( + outcome.reason, + "middleware_denied:deny-upgrade:upgrade_blocked" + ); + assert_eq!( + outcome + .denial + .as_ref() + .map(|denial| denial.config_name.as_str()), + Some("deny-upgrade") + ); + assert_eq!( + outcome + .denial + .as_ref() + .and_then(|denial| denial.reason_code.as_deref()), + Some("upgrade_blocked") + ); + assert_eq!( + outcome.invocations[0].reason_code.as_deref(), + Some("upgrade_blocked") + ); + assert_eq!(outcome.findings.len(), 1); + assert_eq!(outcome.findings[0].middleware, "deny-upgrade"); + assert_eq!(outcome.findings[0].finding.r#type, "content.sensitive"); + assert_eq!(outcome.metadata["deny-upgrade"]["policy_version"], "1"); + assert!(!outcome.reason.contains("sensitive request data")); + assert!(outcome.session.is_none()); + assert_eq!(outcome.invocations.len(), 1); + assert_eq!( + outcome.invocations[0].outcome, + WebSocketInvocationOutcome::Deny + ); + assert!(!outcome.invocations[0].failed); + assert_eq!( + session_ends_rx.recv().await, + Some(WebSocketSessionEndReason::MiddlewareDenial) + ); + assert!( + session_ends_rx.try_recv().is_err(), + "each opened stream receives at most one session_end" + ); + } + } + + #[tokio::test] + async fn mixed_websocket_preflight_denial_ends_every_opened_stage() { + use openshell_core::proto::WebSocketSessionEndReason; + + let (first_end_tx, mut first_end_rx) = tokio::sync::mpsc::unbounded_channel(); + let (denier_end_tx, mut denier_end_rx) = tokio::sync::mpsc::unbounded_channel(); + let (last_end_tx, mut last_end_rx) = tokio::sync::mpsc::unbounded_channel(); + let endpoints: Vec> = vec![ + in_process_endpoint(Arc::new(OpenAiRedactionService { + manifest_name: "test/first-inspector".into(), + session_ends: Some(first_end_tx), + ..Default::default() + })), + in_process_endpoint(Arc::new(OpenAiRedactionService { + manifest_name: "test/denier".into(), + deny: true, + session_ends: Some(denier_end_tx), + ..Default::default() + })), + in_process_endpoint(Arc::new(OpenAiRedactionService { + manifest_name: "test/last-inspector".into(), + session_ends: Some(last_end_tx), + ..Default::default() + })), + ]; + let runner = ChainRunner::from_registry( + MiddlewareRegistry::connect_services(endpoints, Vec::new()) + .await + .expect("connect mixed middleware services"), + ); + let chain = [ + websocket_entry("first", "test/first-inspector", 0, OnError::FailClosed), + websocket_entry("deny", "test/denier", 1, OnError::FailOpen), + websocket_entry("last", "test/last-inspector", 2, OnError::FailClosed), + ]; + + let outcome = runner + .preflight_websocket(&chain, websocket_preflight_input("mixed-denial")) + .await + .expect("mixed preflight"); + + assert!(!outcome.allowed); + assert_eq!( + outcome.terminal_reason, + Some(WebSocketSessionEndReason::MiddlewareDenial) + ); + assert_eq!( + outcome + .invocations + .iter() + .map(|invocation| invocation.outcome) + .collect::>(), + vec![ + WebSocketInvocationOutcome::Inspect, + WebSocketInvocationOutcome::Deny, + WebSocketInvocationOutcome::Inspect, + ] + ); + for receiver in [&mut first_end_rx, &mut denier_end_rx, &mut last_end_rx] { + assert_eq!( + receiver.recv().await, + Some(WebSocketSessionEndReason::MiddlewareDenial) + ); + assert!( + receiver.try_recv().is_err(), + "each opened stream receives at most one session_end" + ); + } + assert_eq!( + runner.registry.session_admission.available_permits(), + MAX_CONCURRENT_MIDDLEWARE_SESSIONS + ); + } + + #[tokio::test] + async fn builtin_regex_redacts_ordered_websocket_text_messages() { + let runner = builtin_runner(); + let chain = [entry("regex-redactor", OnError::FailClosed)]; + let preflight = runner + .preflight_websocket( + &chain, + WebSocketPreflightInput { + session_id: "builtin-regex-session".into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "wss".into(), + host: "api.openai.com".into(), + port: 443, + path: "/v1/responses".into(), + requested_subprotocols: vec!["realtime".into()], + }, + ) + .await + .expect("preflight"); + assert!(preflight.allowed); + assert_eq!( + preflight.invocations[0].outcome, + WebSocketInvocationOutcome::Inspect + ); + let mut session = preflight.session.expect("built-in chose to inspect"); + assert!(session.start("realtime").await.allowed); + + let original = r#"{"type":"response.create","response":{"input":"sk-ABCDEFGHIJKLMNOP"}}"#; + let redacted = session.evaluate_text(original.into()).await; + assert!(redacted.allowed); + assert_eq!( + redacted.payload, + r#"{"type":"response.create","response":{"input":"[REDACTED]"}}"# + ); + assert_eq!(redacted.invocations[0].sequence, Some(1)); + assert!(redacted.invocations[0].transformed); + assert_eq!(redacted.findings.len(), 1); + assert_eq!(redacted.findings[0].middleware, "regex-redactor"); + assert_eq!(redacted.findings[0].finding.r#type, "regex.openai"); + assert_eq!( + redacted.metadata["regex-redactor"]["regex_matches_replaced"], + "1" + ); + + let unchanged = session + .evaluate_text(r#"{"type":"response.cancel"}"#.into()) + .await; + assert!(unchanged.allowed); + assert_eq!(unchanged.payload, r#"{"type":"response.cancel"}"#); + assert_eq!(unchanged.invocations[0].sequence, Some(2)); + assert!(!unchanged.invocations[0].transformed); + assert!(unchanged.findings.is_empty()); + assert!(unchanged.metadata.is_empty()); + + let oversized = session.evaluate_text("a".repeat(256 * 1024 + 1)).await; + assert!(!oversized.allowed); + assert_eq!( + oversized.reason, + "middleware_failed: request_message_over_capacity" + ); + session + .end(openshell_core::proto::WebSocketSessionEndReason::NormalClose) + .await; + } + + #[tokio::test] + async fn builtin_regex_redacts_after_fail_open_message_capacity_gap() { + let runner = builtin_runner(); + let chain = [entry("regex-redactor", OnError::FailOpen)]; + let preflight = runner + .preflight_websocket( + &chain, + WebSocketPreflightInput { + session_id: "builtin-regex-gap-session".into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "wss".into(), + host: "api.openai.com".into(), + port: 443, + path: "/v1/responses".into(), + requested_subprotocols: vec!["realtime".into()], + }, + ) + .await + .expect("preflight"); + assert!(preflight.allowed); + let mut session = preflight.session.expect("built-in chose to inspect"); + assert!(session.start("realtime").await.allowed); + + let oversized_payload = "a".repeat(256 * 1024 + 1); + let oversized = session.evaluate_text(oversized_payload.clone()).await; + assert!(oversized.allowed); + assert_eq!(oversized.payload, oversized_payload); + assert_eq!(oversized.invocations[0].sequence, Some(1)); + assert_eq!( + oversized.invocations[0].outcome, + WebSocketInvocationOutcome::FailOpen + ); + assert!(!oversized.invocations[0].stage_disabled); + + let original = r#"{"type":"response.create","response":{"input":"sk-ABCDEFGHIJKLMNOP"}}"#; + let redacted = session.evaluate_text(original.into()).await; + assert!(redacted.allowed); + assert_eq!( + redacted.payload, + r#"{"type":"response.create","response":{"input":"[REDACTED]"}}"# + ); + assert_eq!(redacted.invocations[0].sequence, Some(2)); + assert_eq!( + redacted.invocations[0].outcome, + WebSocketInvocationOutcome::Allow + ); + assert!(redacted.invocations[0].transformed); + assert!(!redacted.invocations[0].stage_disabled); + + session + .end(openshell_core::proto::WebSocketSessionEndReason::NormalClose) + .await; + } + + #[tokio::test] + async fn in_process_websocket_endpoint_redacts_openai_event() { + let service = OpenAiRedactionService::default(); + let runner = ChainRunner::from_endpoint(Arc::new(service)); + let chain = [ChainEntry { + name: "openai-redactor".into(), + implementation: "test/openai-websocket-redactor".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }]; + let preflight = runner + .preflight_websocket( + &chain, + WebSocketPreflightInput { + session_id: "in-process-session".into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "wss".into(), + host: "api.openai.com".into(), + port: 443, + path: "/v1/responses".into(), + requested_subprotocols: vec!["realtime".into()], + }, + ) + .await + .expect("preflight"); + assert!(preflight.allowed); + let mut session = preflight.session.expect("middleware chose to inspect"); + assert!(session.start("realtime").await.allowed); + + let original = r#"{"type":"response.create","response":{"input":"customer-secret"}}"#; + let outcome = session.evaluate_text(original.into()).await; + assert!(outcome.allowed); + assert_eq!( + outcome.payload, + r#"{"type":"response.create","response":{"input":"[REDACTED]"}}"# + ); + assert!(outcome.invocations[0].transformed); + session + .end(openshell_core::proto::WebSocketSessionEndReason::NormalClose) + .await; + } + + #[tokio::test] + async fn openai_websocket_event_is_introspected_and_redacted() { + let service = OpenAiRedactionService::default(); + let observed_preflight = Arc::clone(&service.preflight); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind WebSocket middleware"); + let address = listener.local_addr().expect("middleware address"); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tonic::transport::Server::builder() + .add_service(SupervisorMiddlewareServer::new(service)) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }); + let server_task = tokio::spawn(server); + + let mut registration = external_registration(1024); + registration.grpc_endpoint = format!("http://{address}"); + let registry = MiddlewareRegistry::connect_services(Vec::new(), vec![registration]) + .await + .expect("connect WebSocket middleware"); + let runner = ChainRunner::from_registry(registry); + let chain = [ChainEntry { + name: "openai-redactor".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }]; + let described = runner + .describe_websocket_chain(&chain) + .await + .expect("describe WebSocket chain"); + assert_eq!( + described[0].max_payload_bytes(), + 1024, + "operator max_payload_bytes must cap WebSocket messages" + ); + let preflight = runner + .preflight_websocket( + &chain, + WebSocketPreflightInput { + session_id: "ws-session".into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "wss".into(), + host: "api.openai.com".into(), + port: 443, + path: "/v1/responses".into(), + requested_subprotocols: vec!["realtime".into()], + }, + ) + .await + .expect("preflight"); + assert!(preflight.allowed); + let mut session = preflight.session.expect("middleware chose to inspect"); + assert!(session.start("realtime").await.allowed); + + let original = r#"{"type":"response.create","response":{"input":"customer-secret"}}"#; + let outcome = session.evaluate_text(original.into()).await; + assert!(outcome.allowed); + let transformed = outcome.payload; + assert!(transformed.contains("[REDACTED]")); + assert!(!transformed.contains("customer-secret")); + assert!(outcome.invocations[0].transformed); + + let observed = observed_preflight + .lock() + .expect("preflight lock") + .clone() + .expect("preflight observed"); + let target = observed.target.expect("preflight target"); + assert_eq!(target.scheme, "wss"); + assert_eq!(target.host, "api.openai.com"); + assert_eq!(target.port, 443); + assert_eq!(target.method, "GET"); + assert_eq!(target.path, "/v1/responses"); + assert!(target.query.is_empty()); + assert_eq!(observed.requested_subprotocols, ["realtime"]); + session + .end(openshell_core::proto::WebSocketSessionEndReason::NormalClose) + .await; + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join test middleware") + .expect("serve middleware"); + } + + #[tokio::test] + async fn fail_open_disables_broken_websocket_stage_for_later_messages() { + let service = OpenAiRedactionService { + close_on_first_message: true, + ..Default::default() + }; + let observed_preflight = Arc::clone(&service.preflight); + let message_count = Arc::clone(&service.messages); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind WebSocket middleware"); + let address = listener.local_addr().expect("middleware address"); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tonic::transport::Server::builder() + .add_service(SupervisorMiddlewareServer::new(service)) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }); + let server_task = tokio::spawn(server); + + let mut registration = external_registration(1024); + registration.grpc_endpoint = format!("http://{address}"); + let registry = MiddlewareRegistry::connect_services(Vec::new(), vec![registration]) + .await + .expect("connect WebSocket middleware"); + let runner = ChainRunner::from_registry(registry); + let chain = [ChainEntry { + name: "openai-redactor".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailOpen, + }]; + let preflight = runner + .preflight_websocket( + &chain, + WebSocketPreflightInput { + session_id: "ws-session".into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "ws".into(), + host: "api.openai.com".into(), + port: 80, + path: "/v1/responses".into(), + requested_subprotocols: Vec::new(), + }, + ) + .await + .expect("preflight"); + let mut session = preflight.session.expect("middleware chose to inspect"); + assert!(session.start("").await.allowed); + assert_eq!( + observed_preflight + .lock() + .expect("preflight lock") + .as_ref() + .expect("preflight observed") + .target + .as_ref() + .expect("preflight target") + .scheme, + "ws" + ); + + let first = session + .evaluate_text(r#"{"type":"response.create"}"#.into()) + .await; + assert!(first.allowed, "fail-open should bypass the broken stage"); + assert_eq!(first.invocations.len(), 1); + assert!(first.invocations[0].failed); + assert!(first.invocations[0].stage_disabled); + assert_eq!( + runner.registry.session_admission.available_permits(), + MAX_CONCURRENT_MIDDLEWARE_SESSIONS, + "the final disabled stage must release persistent session capacity" + ); + + let mut work = Vec::new(); + for _ in 0..MAX_CONCURRENT_MIDDLEWARE_WORK { + work.push( + runner + .reserve_middleware_work_admission() + .await + .expect("fill middleware work budget"), + ); + } + + let second = session + .evaluate_text(r#"{"type":"response.cancel"}"#.into()) + .now_or_never() + .expect("fully disabled session must bypass without waiting for work admission"); + assert!(second.allowed); + assert!( + second.invocations.is_empty(), + "disabled stage must not be called again in this session" + ); + assert_eq!(message_count.load(std::sync::atomic::Ordering::SeqCst), 1); + drop(work); + + session + .end(openshell_core::proto::WebSocketSessionEndReason::NormalClose) + .await; + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join test middleware") + .expect("serve middleware"); + } + + #[tokio::test] + async fn mixed_websocket_session_keeps_message_admission_while_one_stage_is_active() { + let broken = Arc::new(OpenAiRedactionService { + close_on_first_message: true, + ..Default::default() + }); + let mut endpoints = services(); + endpoints.push(in_process_endpoint(broken)); + let runner = ChainRunner::from_registry( + MiddlewareRegistry::connect_services(endpoints, Vec::new()) + .await + .expect("connect mixed middleware services"), + ); + let broken_entry = ChainEntry { + name: "best-effort-remote".into(), + implementation: "test/openai-websocket-redactor".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailOpen, + }; + let mut regex_entry = entry("required-regex", OnError::FailClosed); + regex_entry.order = 1; + let preflight = runner + .preflight_websocket( + &[broken_entry, regex_entry], + websocket_preflight_input("mixed-active"), + ) + .await + .expect("mixed preflight"); + let mut session = preflight.session.expect("both stages inspect"); + assert!(session.start("").await.allowed); + + let first = session + .evaluate_text(r#"{"input":"sk-ABCDEFGHIJKLMNOP"}"#.into()) + .await; + assert!(first.allowed); + assert!(first.invocations[0].stage_disabled); + assert_eq!( + first.invocations[1].outcome, + WebSocketInvocationOutcome::Allow + ); + + let mut work = Vec::new(); + for _ in 0..MAX_CONCURRENT_MIDDLEWARE_WORK { + work.push( + runner + .reserve_middleware_work_admission() + .await + .expect("fill middleware work budget"), + ); + } + assert!( + session.admit_message().now_or_never().is_none(), + "an active remaining stage must still wait for message work admission" + ); + drop(work); + + let second = session + .evaluate_text(r#"{"input":"sk-QRSTUVWXYZabcdef"}"#.into()) + .await; + assert!(second.allowed); + assert_eq!(second.invocations.len(), 1); + assert_eq!( + second.invocations[0].config_name, "required-regex", + "disabled stage must stay bypassed while the active stage continues" + ); + } + + #[tokio::test] + async fn websocket_admission_wait_queue_is_bounded() { + let runner = ChainRunner::default(); + let mut active = Vec::new(); + for _ in 0..MAX_CONCURRENT_MIDDLEWARE_WORK { + active.push( + runner + .reserve_middleware_work_admission() + .await + .expect("active admission"), + ); + } + + let mut waiters = Vec::new(); + for _ in 0..MAX_QUEUED_MIDDLEWARE_WORK { + let runner = runner.clone(); + waiters.push(tokio::spawn(async move { + runner.reserve_middleware_work().await + })); + } + while runner.registry.work_admission_waiters.available_permits() != 0 { + tokio::task::yield_now().await; + } + + let overflow = runner + .reserve_middleware_work() + .await + .expect("admission outcome"); + assert!(matches!( + overflow, + MiddlewareWorkAdmissionOutcome::QueueExhausted + )); + runner + .reserve_middleware_work_admission() + .await + .expect_err("WebSocket callers retain their existing failure path"); + + drop(active); + for waiter in waiters { + let admission = waiter + .await + .expect("waiter task") + .expect("queued admission after capacity is released"); + assert!(matches!( + admission, + MiddlewareWorkAdmissionOutcome::Admitted(_) + )); + } + assert_eq!( + runner.registry.work_admission.available_permits(), + MAX_CONCURRENT_MIDDLEWARE_WORK + ); + assert_eq!( + runner.registry.work_admission_waiters.available_permits(), + MAX_QUEUED_MIDDLEWARE_WORK + ); + + let mut recovered = Vec::new(); + for _ in 0..MAX_CONCURRENT_MIDDLEWARE_WORK { + recovered.push( + runner + .reserve_middleware_work_admission() + .await + .expect("recovered active admission"), + ); + } + assert_eq!(recovered.len(), MAX_CONCURRENT_MIDDLEWARE_WORK); + } + + #[tokio::test] + async fn websocket_queue_exhaustion_remains_a_protocol_failure() { + let runner = builtin_runner(); + let chain = [entry("regex-redactor", OnError::FailClosed)]; + let preflight = runner + .preflight_websocket(&chain, websocket_preflight_input("established")) + .await + .expect("initial preflight"); + let mut session = preflight.session.expect("built-in inspects session"); + assert!(session.start("").await.allowed); + + let mut active = Vec::new(); + for _ in 0..MAX_CONCURRENT_MIDDLEWARE_WORK { + active.push( + runner + .reserve_middleware_work_admission() + .await + .expect("fill active work"), + ); + } + let mut waiters = Vec::new(); + for _ in 0..MAX_QUEUED_MIDDLEWARE_WORK { + let runner = runner.clone(); + waiters.push(tokio::spawn(async move { + runner.reserve_middleware_work().await + })); + } + while runner.registry.work_admission_waiters.available_permits() != 0 { + tokio::task::yield_now().await; + } + + let preflight_overflow = runner + .preflight_websocket(&chain, websocket_preflight_input("preflight-overflow")) + .await; + assert!( + preflight_overflow.is_err(), + "preflight exhaustion remains an outer HTTP failure" + ); + session + .admit_message() + .await + .expect_err("established message exhaustion remains a typed termination input"); + + for waiter in waiters { + waiter.abort(); + } + drop(active); + } + + #[tokio::test] + async fn websocket_preflight_skip_removes_stage_without_message_calls() { + let (session_ends_tx, mut session_ends_rx) = tokio::sync::mpsc::unbounded_channel(); + let service = OpenAiRedactionService { + skip: true, + session_ends: Some(session_ends_tx), + ..Default::default() + }; + let message_count = Arc::clone(&service.messages); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind WebSocket middleware"); + let address = listener.local_addr().expect("middleware address"); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tonic::transport::Server::builder() + .add_service(SupervisorMiddlewareServer::new(service)) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }); + let server_task = tokio::spawn(server); + let mut registration = external_registration(1024); + registration.grpc_endpoint = format!("http://{address}"); + let runner = ChainRunner::from_registry( + MiddlewareRegistry::connect_services(Vec::new(), vec![registration]) + .await + .expect("connect middleware"), + ); + let result = runner + .preflight_websocket( + &[ChainEntry { + name: "scope".into(), + implementation: "local-guard-service".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }], + WebSocketPreflightInput { + session_id: "session".into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "wss".into(), + host: "api.openai.com".into(), + port: 443, + path: "/v1/responses".into(), + requested_subprotocols: Vec::new(), + }, + ) + .await + .expect("preflight"); + assert!(result.allowed); + assert!(result.session.is_none()); + assert_eq!( + result.invocations[0].outcome, + WebSocketInvocationOutcome::Skip + ); + assert_eq!(message_count.load(std::sync::atomic::Ordering::SeqCst), 0); + assert_eq!( + runner.registry.session_admission.available_permits(), + MAX_CONCURRENT_MIDDLEWARE_SESSIONS, + "all-skip preflight must not retain session capacity" + ); + assert_eq!( + session_ends_rx.recv().await, + Some(openshell_core::proto::WebSocketSessionEndReason::StageSkipped) + ); + assert!( + session_ends_rx.try_recv().is_err(), + "a skipped stage receives at most one session_end" + ); + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware") + .expect("serve middleware"); + } + + #[tokio::test] + async fn websocket_session_budget_caps_idle_inspecting_sessions_and_releases_on_end() { + let runner = builtin_runner(); + let chain = [entry("regex-redactor", OnError::FailClosed)]; + let mut sessions = Vec::new(); + for index in 0..MAX_CONCURRENT_MIDDLEWARE_SESSIONS { + let preflight = runner + .preflight_websocket( + &chain, + websocket_preflight_input(format!("session-{index}")), + ) + .await + .expect("admit inspecting session"); + assert!(preflight.allowed); + sessions.push(preflight.session.expect("built-in inspects session")); + } + assert_eq!(runner.registry.session_admission.available_permits(), 0); + + let overflow = runner + .preflight_websocket(&chain, websocket_preflight_input("overflow")) + .await + .expect("capacity exhaustion is a typed preflight outcome"); + assert!(!overflow.allowed); + assert!(overflow.session.is_none()); + assert!(overflow.session_capacity_exhausted); + assert_eq!( + overflow.invocations[0].outcome, + WebSocketInvocationOutcome::FailClosed + ); + + sessions + .pop() + .expect("retained session") + .end(openshell_core::proto::WebSocketSessionEndReason::NormalClose) + .await; + assert_eq!(runner.registry.session_admission.available_permits(), 1); + + let replacement = runner + .preflight_websocket(&chain, websocket_preflight_input("replacement")) + .await + .expect("released session capacity is reusable"); + assert!(replacement.allowed); + assert!(replacement.session.is_some()); + } + + #[tokio::test] + async fn websocket_session_budget_survives_registry_replacement() { + let runner = builtin_runner(); + let chain = [entry("regex-redactor", OnError::FailClosed)]; + let mut sessions = Vec::new(); + for index in 0..MAX_CONCURRENT_MIDDLEWARE_SESSIONS { + let preflight = runner + .preflight_websocket( + &chain, + websocket_preflight_input(format!("old-generation-{index}")), + ) + .await + .expect("admit old-generation session"); + sessions.push(preflight.session.expect("built-in inspects session")); + } + + let replacement_registry = MiddlewareRegistry::connect_services(services(), Vec::new()) + .await + .expect("connect replacement registry"); + let replacement = runner.with_replacement_registry(replacement_registry); + let overflow = replacement + .preflight_websocket(&chain, websocket_preflight_input("new-generation-overflow")) + .await + .expect("capacity exhaustion is a typed preflight outcome"); + assert!(!overflow.allowed); + assert!(overflow.session_capacity_exhausted); + + sessions + .pop() + .expect("retained old-generation session") + .end(openshell_core::proto::WebSocketSessionEndReason::PolicyReload) + .await; + let admitted = replacement + .preflight_websocket(&chain, websocket_preflight_input("new-generation-admitted")) + .await + .expect("released capacity is reusable after replacement"); + assert!(admitted.allowed); + assert!(admitted.session.is_some()); + } + + #[tokio::test] + async fn websocket_session_capacity_exhaustion_honors_mixed_on_error() { + let runner = builtin_runner(); + let mut held = Vec::new(); + for _ in 0..MAX_CONCURRENT_MIDDLEWARE_SESSIONS { + match runner.try_reserve_middleware_session() { + MiddlewareSessionAdmission::Admitted(admission) => held.push(admission), + MiddlewareSessionAdmission::AtCapacity => { + panic!("session budget exhausted before platform limit") + } + } + } + + let mut first = entry("best-effort-a", OnError::FailOpen); + first.order = 1; + let mut second = entry("best-effort-b", OnError::FailOpen); + second.order = 2; + let all_fail_open = runner + .preflight_websocket( + &[first.clone(), second.clone()], + websocket_preflight_input("all-fail-open"), + ) + .await + .expect("all-fail-open capacity outcome"); + assert!(all_fail_open.allowed); + assert!(all_fail_open.session.is_none()); + assert!(all_fail_open.session_capacity_exhausted); + assert!( + all_fail_open + .invocations + .iter() + .all(|invocation| invocation.outcome == WebSocketInvocationOutcome::FailOpen) + ); + + second.on_error = OnError::FailClosed; + let mixed = runner + .preflight_websocket(&[first, second], websocket_preflight_input("mixed")) + .await + .expect("mixed capacity outcome"); + assert!(!mixed.allowed); + assert!(mixed.session.is_none()); + assert!(mixed.session_capacity_exhausted); + assert_eq!( + mixed + .invocations + .iter() + .map(|invocation| invocation.outcome) + .collect::>(), + [ + WebSocketInvocationOutcome::FailOpen, + WebSocketInvocationOutcome::FailClosed, + ] + ); + drop(held); + } } diff --git a/crates/openshell-supervisor-middleware/src/remote.rs b/crates/openshell-supervisor-middleware/src/remote.rs index 25838c3361..edc1e8066c 100644 --- a/crates/openshell-supervisor-middleware/src/remote.rs +++ b/crates/openshell-supervisor-middleware/src/remote.rs @@ -1,46 +1,59 @@ // SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -use std::sync::Arc; -use std::time::Duration; - use miette::{IntoDiagnostic, Result, WrapErr}; -use openshell_core::middleware::HttpRequestView; +use openshell_core::middleware::{ + HttpRequestView, SupervisorMiddlewareEndpoint, WebSocketResponseStream, +}; use openshell_core::proto::middleware::v1::supervisor_middleware_client::SupervisorMiddlewareClient; -use openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware; use openshell_core::proto::{ HttpRequestEvaluation, HttpRequestResult, MiddlewareManifest, ValidateConfigRequest, - ValidateConfigResponse, + ValidateConfigResponse, WebSocketSessionEvent, }; -use tonic::transport::{Channel, ClientTlsConfig, Endpoint}; +use openshell_extension_core::{ + BearerTokenInterceptor, BearerTokenSlot, ExtensionChannelConfig, ExtensionServerTrust, + connect_channel, +}; +use std::sync::Arc; +use tonic::service::interceptor::InterceptedService; +use tonic::transport::Channel; use tonic::{Request, Response, Status}; use crate::MIDDLEWARE_GRPC_MESSAGE_BYTES; -const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); -const HTTP2_KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(10); -const HTTP2_KEEP_ALIVE_TIMEOUT: Duration = Duration::from_secs(20); +type ExtensionChannel = InterceptedService; /// Adapts the borrowed runtime request contract to the owned protobuf service /// contract only when dispatch crosses a gRPC-shaped boundary. #[derive(Clone)] pub struct GrpcMiddlewareService { - service: Arc, + service: Arc, } impl GrpcMiddlewareService { /// Connect an operator registration and wrap its generated gRPC client. - pub async fn connect(registration_name: &str, grpc_endpoint: &str) -> Result { + pub async fn connect( + registration_name: &str, + grpc_endpoint: &str, + tls_ca_cert_pem: &[u8], + bearer: Option, + ) -> Result { Ok(Self { service: Arc::new( - RemoteMiddlewareService::connect(registration_name, grpc_endpoint).await?, + RemoteMiddlewareService::connect( + registration_name, + grpc_endpoint, + tls_ca_cert_pem, + bearer, + ) + .await?, ), }) } /// Wrap a protobuf-shaped service used by transport-boundary tests. #[cfg(test)] - pub fn from_service(service: Arc) -> Self { + pub fn from_service(service: Arc) -> Self { Self { service } } @@ -80,39 +93,34 @@ impl GrpcMiddlewareService { })) .await } + + /// Open a remote WebSocket middleware stream through the gRPC adapter. + pub async fn open_websocket_session( + &self, + receiver: tokio::sync::mpsc::Receiver, + ) -> std::result::Result { + self.service.open_websocket_session(receiver).await + } } #[derive(Clone)] pub struct RemoteMiddlewareService { - client: SupervisorMiddlewareClient, + client: SupervisorMiddlewareClient, } impl RemoteMiddlewareService { - pub async fn connect(registration_name: &str, grpc_endpoint: &str) -> Result { - let mut endpoint = Endpoint::from_shared(grpc_endpoint.to_string()) - .into_diagnostic() - .wrap_err_with(|| { - format!( - "middleware registration '{registration_name}' has an invalid grpc_endpoint" - ) - })? - .http2_keep_alive_interval(HTTP2_KEEP_ALIVE_INTERVAL) - .keep_alive_while_idle(true) - .keep_alive_timeout(HTTP2_KEEP_ALIVE_TIMEOUT) - .http2_adaptive_window(true); - - if grpc_endpoint.starts_with("https://") { - endpoint = endpoint - .tls_config(ClientTlsConfig::new().with_enabled_roots()) - .into_diagnostic() - .wrap_err_with(|| { - format!("middleware registration '{registration_name}' could not configure TLS") - })?; + pub async fn connect( + registration_name: &str, + grpc_endpoint: &str, + tls_ca_cert_pem: &[u8], + bearer: Option, + ) -> Result { + let mut config = ExtensionChannelConfig::new(grpc_endpoint); + if !tls_ca_cert_pem.is_empty() { + config = config + .with_server_trust(ExtensionServerTrust::CustomCaPem(tls_ca_cert_pem.to_vec())); } - - let channel = endpoint - .connect_timeout(CONNECT_TIMEOUT) - .connect() + let channel = connect_channel(&config) .await .into_diagnostic() .wrap_err_with(|| { @@ -120,6 +128,9 @@ impl RemoteMiddlewareService { "middleware registration '{registration_name}' could not connect to {grpc_endpoint}" ) })?; + let interceptor = + bearer.map_or_else(BearerTokenInterceptor::disabled, |slot| slot.interceptor()); + let channel = InterceptedService::new(channel, interceptor); Ok(Self { client: SupervisorMiddlewareClient::new(channel) @@ -130,7 +141,7 @@ impl RemoteMiddlewareService { } #[tonic::async_trait] -impl SupervisorMiddleware for RemoteMiddlewareService { +impl SupervisorMiddlewareEndpoint for RemoteMiddlewareService { async fn describe( &self, request: Request<()>, @@ -154,4 +165,18 @@ impl SupervisorMiddleware for RemoteMiddlewareService { let mut client = self.client.clone(); client.evaluate_http_request(request).await } + + async fn open_websocket_session( + &self, + receiver: tokio::sync::mpsc::Receiver, + ) -> std::result::Result { + let mut client = self.client.clone(); + let responses = client + .evaluate_web_socket_session(Request::new(tokio_stream::wrappers::ReceiverStream::new( + receiver, + ))) + .await? + .into_inner(); + Ok(Box::pin(responses)) + } } diff --git a/crates/openshell-supervisor-middleware/src/websocket.rs b/crates/openshell-supervisor-middleware/src/websocket.rs new file mode 100644 index 0000000000..cea7addb0d --- /dev/null +++ b/crates/openshell-supervisor-middleware/src/websocket.rs @@ -0,0 +1,1408 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +//! Forward-direction WebSocket middleware session runner. + +use std::collections::BTreeMap; +use std::time::Duration; + +use futures::{StreamExt, future::join_all}; +use prost::Message as _; +use tokio::sync::mpsc; +use tokio::time::Instant; + +use openshell_core::proto::{ + Decision, HttpRequestTarget, RequestContext, SupervisorMiddlewarePhase, WebSocketMessage, + WebSocketMessageResult, WebSocketPreflight, WebSocketPreflightAction, + WebSocketPreflightDecision, WebSocketSessionEnd, WebSocketSessionEndReason, + WebSocketSessionEvent, WebSocketSessionStart, web_socket_message, web_socket_message_result, + web_socket_session_event, web_socket_session_event_result, +}; + +use super::{ + ChainEntry, ChainRunner, DescribedChainEntry, MAX_MIDDLEWARE_CHAIN_TIMEOUT, + MAX_MIDDLEWARE_CONFIG_BYTES, MAX_MIDDLEWARE_CONTEXT_BYTES, MAX_MIDDLEWARE_FINDING_BYTES, + MAX_MIDDLEWARE_FINDINGS_PER_STAGE, MAX_MIDDLEWARE_METADATA_BYTES, + MAX_MIDDLEWARE_METADATA_ENTRIES, MAX_MIDDLEWARE_PAYLOAD_BYTES, + MAX_MIDDLEWARE_PREFLIGHT_TIMEOUT, MAX_MIDDLEWARE_REASON_BYTES, MIDDLEWARE_GRPC_MESSAGE_BYTES, + MiddlewareDenial, MiddlewareSessionAdmission, MiddlewareSessionPermit, MiddlewareWorkAdmission, + NamespacedFinding, OnError, is_stable_reason_code, middleware_denial_reason, +}; + +const STREAM_CHANNEL_CAPACITY: usize = 4; +const MAX_REQUESTED_SUBPROTOCOLS: usize = 32; +const MAX_SUBPROTOCOL_BYTES: usize = 4 * 1024; +const MAX_SELECTED_SUBPROTOCOL_BYTES: usize = 256; +#[derive(Debug, Clone)] +pub struct WebSocketPreflightInput { + pub session_id: String, + pub request_id: String, + pub sandbox_id: String, + pub scheme: String, + pub host: String, + pub port: u16, + /// Raw request path without a query string. + pub path: String, + pub requested_subprotocols: Vec, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WebSocketInvocationOutcome { + Inspect, + Skip, + Allow, + Deny, + FailOpen, + FailClosed, +} + +#[derive(Debug, Clone)] +pub struct WebSocketInvocation { + pub config_name: String, + pub implementation: String, + pub outcome: WebSocketInvocationOutcome, + pub sequence: Option, + pub original_size: usize, + pub replacement_size: Option, + pub transformed: bool, + pub failed: bool, + /// The stage stream became unusable and will be bypassed for the rest of + /// this session when its policy is `fail_open`. + pub stage_disabled: bool, + pub reason_code: Option, +} + +/// Coverage of a selected policy attachment that did not result in a +/// WebSocket middleware invocation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WebSocketCoverageState { + /// The attached implementation did not advertise the exact + /// `WEBSOCKET_MESSAGE/PRE_CREDENTIALS` binding. + BindingNotSelected, + /// The binding was selected, but the V1 relay does not expose this message + /// class to middleware. + UnsupportedMessageType, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum WebSocketMessageType { + Text, + Binary, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WebSocketCoverage { + pub config_name: String, + pub implementation: String, + pub state: WebSocketCoverageState, + pub sequence: Option, + pub message_type: Option, + pub original_size: usize, +} + +pub struct WebSocketPreflightResult { + pub allowed: bool, + /// Typed terminal reason when preflight denied the upgrade. `None` means + /// the request may continue, including voluntary skip and fail-open. + pub terminal_reason: Option, + pub reason: String, + pub denial: Option, + pub session: Option, + pub findings: Vec, + pub metadata: BTreeMap>, + pub invocations: Vec, + pub coverage: Vec, + pub saturated: bool, + pub session_capacity_exhausted: bool, +} + +#[derive(Debug)] +pub struct WebSocketSessionStartOutcome { + pub allowed: bool, + /// Typed terminal reason when session start cannot continue. + pub terminal_reason: Option, + pub reason: String, + pub invocations: Vec, +} + +#[derive(Debug)] +pub struct WebSocketMessageOutcome { + pub allowed: bool, + pub reason: String, + pub payload: String, + pub findings: Vec, + pub metadata: BTreeMap>, + pub invocations: Vec, + pub denial: Option, + pub saturated: bool, + pub platform_oversize: bool, +} + +struct WebSocketStageTransport { + sender: mpsc::Sender, + responses: super::WebSocketResponseStream, +} + +struct WebSocketStage { + entry: DescribedChainEntry, + transport: Option, +} + +impl WebSocketStage { + fn is_active(&self) -> bool { + self.transport.is_some() + } + + async fn disable(&mut self) { + self.end(WebSocketSessionEndReason::MiddlewareFailure).await; + } + + async fn end(&mut self, reason: WebSocketSessionEndReason) { + if let Some(transport) = self.transport.take() { + let _ = tokio::time::timeout( + Duration::from_millis(10), + transport.sender.send(session_end_request(reason)), + ) + .await; + } + } +} + +pub struct WebSocketSession { + runner: ChainRunner, + stages: Vec, + next_sequence: u64, + session_admission: Option, +} + +/// Whether a WebSocket text message needs the shared short-lived work budget. +/// +/// A fully disabled fail-open session returns `Bypass` without touching the +/// work semaphore. Other parsed WebSocket features may continue processing the +/// original payload independently. +#[derive(Debug)] +pub enum WebSocketMessageAdmission { + Bypass, + Inspect(MiddlewareWorkAdmission), +} + +enum OpenStage { + Inspect(Box, PreflightStageOutcome), + Deny(Box, PreflightStageOutcome), + Skip(PreflightStageOutcome), + Failed(DescribedChainEntry, String), +} + +struct PreflightStageOutcome { + invocation: WebSocketInvocation, + findings: Vec, + metadata: Option<(String, BTreeMap)>, +} + +impl ChainRunner { + pub async fn preflight_websocket( + &self, + entries: &[ChainEntry], + input: WebSocketPreflightInput, + ) -> miette::Result { + if entries.is_empty() { + return Ok(empty_preflight_result()); + } + let description = self + .describe_chain_for( + entries, + openshell_core::proto::SupervisorMiddlewareOperation::WebsocketMessage, + SupervisorMiddlewarePhase::PreCredentials, + ) + .await?; + let coverage = description + .unbound + .iter() + .map(binding_not_selected_coverage) + .collect::>(); + let described = description.entries; + if described.is_empty() { + let mut result = empty_preflight_result(); + result.coverage = coverage; + return Ok(result); + } + validate_preflight_input(&input)?; + + // One permit covers the complete concurrent preflight fan-out. Permit + // wait is deliberate backpressure and is excluded from every deadline. + let preflight_work = self.reserve_middleware_work_admission().await?; + let saturated = preflight_work.saturated(); + let session_admission = match self.try_reserve_middleware_session() { + MiddlewareSessionAdmission::Admitted(admission) => admission, + MiddlewareSessionAdmission::AtCapacity => { + return Ok(session_capacity_exhausted(described, coverage, saturated)); + } + }; + let opened = join_all( + described + .into_iter() + .map(|entry| open_stage(entry, input.clone())), + ) + .await; + + let mut stages = Vec::new(); + let mut invocations = Vec::new(); + let mut findings = Vec::new(); + let mut metadata = BTreeMap::new(); + let mut denial = None; + let mut fail_closed_reason = None; + for result in opened { + match result { + OpenStage::Inspect(stage, outcome) => { + stages.push(*stage); + collect_preflight_outcome( + outcome, + &mut invocations, + &mut findings, + &mut metadata, + ); + } + OpenStage::Deny(stage, outcome) => { + denial.get_or_insert_with(|| MiddlewareDenial { + config_name: stage.entry.entry.name.clone(), + reason_code: outcome.invocation.reason_code.clone(), + }); + stages.push(*stage); + collect_preflight_outcome( + outcome, + &mut invocations, + &mut findings, + &mut metadata, + ); + } + OpenStage::Skip(outcome) => collect_preflight_outcome( + outcome, + &mut invocations, + &mut findings, + &mut metadata, + ), + OpenStage::Failed(entry, reason) => { + let invocation = failure_invocation(&entry, None, 0, &reason); + if entry.entry.on_error == OnError::FailClosed { + fail_closed_reason + .get_or_insert_with(|| format!("middleware_failed: {reason}")); + } + invocations.push(invocation); + } + } + } + + if let Some(denial) = denial { + end_stages(&mut stages, WebSocketSessionEndReason::MiddlewareDenial).await; + return Ok(WebSocketPreflightResult { + allowed: false, + terminal_reason: Some(WebSocketSessionEndReason::MiddlewareDenial), + reason: middleware_denial_reason( + &denial.config_name, + denial.reason_code.as_deref(), + ), + denial: Some(denial), + session: None, + findings, + metadata, + invocations, + coverage, + saturated, + session_capacity_exhausted: false, + }); + } + + if let Some(reason) = fail_closed_reason { + end_stages(&mut stages, WebSocketSessionEndReason::MiddlewareFailure).await; + return Ok(WebSocketPreflightResult { + allowed: false, + terminal_reason: Some(WebSocketSessionEndReason::MiddlewareFailure), + reason, + denial: None, + session: None, + findings, + metadata, + invocations, + coverage, + saturated, + session_capacity_exhausted: false, + }); + } + + if stages.is_empty() { + drop(session_admission); + return Ok(WebSocketPreflightResult { + allowed: true, + terminal_reason: None, + reason: String::new(), + denial: None, + session: None, + findings, + metadata, + invocations, + coverage, + saturated, + session_capacity_exhausted: false, + }); + } + + Ok(WebSocketPreflightResult { + allowed: true, + terminal_reason: None, + reason: String::new(), + denial: None, + session: Some(WebSocketSession { + runner: self.clone(), + stages, + next_sequence: 1, + session_admission: Some(session_admission), + }), + findings, + metadata, + invocations, + coverage, + saturated, + session_capacity_exhausted: false, + }) + } +} + +fn empty_preflight_result() -> WebSocketPreflightResult { + WebSocketPreflightResult { + allowed: true, + terminal_reason: None, + reason: String::new(), + denial: None, + session: None, + findings: Vec::new(), + metadata: BTreeMap::new(), + invocations: Vec::new(), + coverage: Vec::new(), + saturated: false, + session_capacity_exhausted: false, + } +} + +fn session_capacity_exhausted( + described: Vec, + coverage: Vec, + saturated: bool, +) -> WebSocketPreflightResult { + let reason = "middleware_session_capacity_exhausted"; + let mut fail_closed = false; + let invocations = described + .iter() + .map(|entry| { + fail_closed |= entry.entry.on_error == OnError::FailClosed; + failure_invocation(entry, None, 0, reason) + }) + .collect(); + WebSocketPreflightResult { + allowed: !fail_closed, + terminal_reason: fail_closed.then_some(WebSocketSessionEndReason::MiddlewareFailure), + reason: if fail_closed { + format!("middleware_failed: {reason}") + } else { + String::new() + }, + denial: None, + session: None, + findings: Vec::new(), + metadata: BTreeMap::new(), + invocations, + coverage, + saturated, + session_capacity_exhausted: true, + } +} + +impl WebSocketSession { + fn has_active_stages(&self) -> bool { + self.stages.iter().any(WebSocketStage::is_active) + } + + fn reconcile_lifecycle(&mut self) { + if !self.has_active_stages() { + self.session_admission.take(); + } + } + + pub async fn admit_message(&mut self) -> miette::Result { + self.reconcile_lifecycle(); + if !self.has_active_stages() { + return Ok(WebSocketMessageAdmission::Bypass); + } + self.runner + .reserve_middleware_work_admission() + .await + .map(WebSocketMessageAdmission::Inspect) + } + + pub async fn start(&mut self, selected_subprotocol: &str) -> WebSocketSessionStartOutcome { + if selected_subprotocol.len() > MAX_SELECTED_SUBPROTOCOL_BYTES { + return WebSocketSessionStartOutcome { + allowed: false, + terminal_reason: Some(WebSocketSessionEndReason::MiddlewareFailure), + reason: "middleware_failed: selected_subprotocol_over_capacity".to_string(), + invocations: Vec::new(), + }; + } + let mut invocations = Vec::new(); + let mut fail_closed = None; + for stage in &mut self.stages { + let Some(transport) = stage.transport.as_mut() else { + continue; + }; + let request = WebSocketSessionEvent { + event: Some(web_socket_session_event::Event::SessionStart( + WebSocketSessionStart { + selected_subprotocol: selected_subprotocol.to_string(), + }, + )), + }; + let sent = + tokio::time::timeout(stage.entry.timeout, transport.sender.send(request)).await; + if !matches!(sent, Ok(Ok(()))) { + stage.disable().await; + let reason = "session_start_send_failed"; + let mut invocation = failure_invocation(&stage.entry, None, 0, reason); + invocation.stage_disabled = true; + if stage.entry.entry.on_error == OnError::FailClosed { + fail_closed.get_or_insert_with(|| format!("middleware_failed: {reason}")); + } + invocations.push(invocation); + } + } + self.reconcile_lifecycle(); + WebSocketSessionStartOutcome { + allowed: fail_closed.is_none(), + terminal_reason: fail_closed + .as_ref() + .map(|_| WebSocketSessionEndReason::MiddlewareFailure), + reason: fail_closed.unwrap_or_default(), + invocations, + } + } + + /// Record one logical message whose type the selected V1 WebSocket binding + /// cannot inspect. This is a coverage state, not a middleware failure: + /// `on_error` is not applied and active stages remain available for later + /// text messages. + pub fn observe_unsupported_message( + &mut self, + message_type: WebSocketMessageType, + original_size: usize, + ) -> Vec { + self.reconcile_lifecycle(); + if !self.has_active_stages() { + return Vec::new(); + } + let sequence = self.next_sequence; + self.next_sequence = self.next_sequence.saturating_add(1); + self.stages + .iter() + .filter(|stage| stage.is_active()) + .map(|stage| WebSocketCoverage { + config_name: stage.entry.entry.name.clone(), + implementation: stage.entry.entry.implementation.clone(), + state: WebSocketCoverageState::UnsupportedMessageType, + sequence: Some(sequence), + message_type: Some(message_type), + original_size, + }) + .collect() + } + + pub async fn evaluate_text(&mut self, payload: String) -> WebSocketMessageOutcome { + if payload.len() > MAX_MIDDLEWARE_PAYLOAD_BYTES { + return platform_oversize_outcome(payload); + } + match self.admit_message().await { + Ok(WebSocketMessageAdmission::Bypass) => bypassed_message_outcome(payload), + Ok(WebSocketMessageAdmission::Inspect(admission)) => { + self.evaluate_text_admitted(payload, admission).await + } + Err(_) => admission_failure_outcome(payload), + } + } + + pub async fn evaluate_text_admitted( + &mut self, + payload: String, + admission: MiddlewareWorkAdmission, + ) -> WebSocketMessageOutcome { + let outcome = self.evaluate_text_admitted_inner(payload, admission).await; + self.reconcile_lifecycle(); + outcome + } + + async fn evaluate_text_admitted_inner( + &mut self, + payload: String, + admission: MiddlewareWorkAdmission, + ) -> WebSocketMessageOutcome { + if payload.len() > MAX_MIDDLEWARE_PAYLOAD_BYTES { + return platform_oversize_outcome(payload); + } + + let saturated = admission.saturated(); + let sequence = self.next_sequence; + self.next_sequence = self.next_sequence.saturating_add(1); + let chain_deadline = Instant::now() + MAX_MIDDLEWARE_CHAIN_TIMEOUT; + let mut current = payload; + let mut findings = Vec::new(); + let mut metadata = BTreeMap::new(); + let mut invocations = Vec::new(); + + for stage in &mut self.stages { + if !stage.is_active() { + continue; + } + let original_size = current.len(); + if original_size > stage.entry.max_payload_bytes { + let reason = "request_message_over_capacity"; + let invocation = + failure_invocation(&stage.entry, Some(sequence), original_size, reason); + let fail_closed = stage.entry.entry.on_error == OnError::FailClosed; + invocations.push(invocation); + if fail_closed { + return denied_message_outcome( + current, + findings, + metadata, + invocations, + format!("middleware_failed: {reason}"), + None, + saturated, + ); + } + continue; + } + + let remaining = chain_deadline.saturating_duration_since(Instant::now()); + if remaining.is_zero() { + let reason = "middleware_chain_timeout"; + let mut invocation = + failure_invocation(&stage.entry, Some(sequence), original_size, reason); + let fail_closed = stage.entry.entry.on_error == OnError::FailClosed; + stage.disable().await; + invocation.stage_disabled = true; + invocations.push(invocation); + if fail_closed { + return denied_message_outcome( + current, + findings, + metadata, + invocations, + format!("middleware_failed: {reason}"), + None, + saturated, + ); + } + continue; + } + let stage_timeout = stage.entry.timeout.min(remaining); + let request = WebSocketSessionEvent { + event: Some(web_socket_session_event::Event::Message(WebSocketMessage { + sequence, + payload: Some(web_socket_message::Payload::Text(current.clone())), + })), + }; + let response = { + let transport = stage + .transport + .as_mut() + .expect("active WebSocket stage has transport"); + tokio::time::timeout(stage_timeout, async { + transport + .sender + .send(request) + .await + .map_err(|_| tonic::Status::unavailable("request stream closed"))?; + transport.responses.next().await.transpose() + }) + .await + }; + let result = match response { + Ok(Ok(Some(response))) => match response.result { + Some(web_socket_session_event_result::Result::MessageResult(result)) => result, + Some(web_socket_session_event_result::Result::PreflightDecision(_)) | None => { + if let Some(outcome) = handle_stage_failure( + stage, + sequence, + original_size, + "unexpected_websocket_response", + ¤t, + &findings, + &metadata, + &mut invocations, + saturated, + ) + .await + { + return outcome; + } + continue; + } + }, + Ok(Ok(None)) => { + if let Some(outcome) = handle_stage_failure( + stage, + sequence, + original_size, + "missing_message_result", + ¤t, + &findings, + &metadata, + &mut invocations, + saturated, + ) + .await + { + return outcome; + } + continue; + } + Ok(Err(error)) => { + let reason = stage.entry.service.as_ref().map_or_else( + || "binding_not_described".to_string(), + |service| service.diagnostic_policy.error_reason(&error), + ); + if let Some(outcome) = handle_stage_failure( + stage, + sequence, + original_size, + &reason, + ¤t, + &findings, + &metadata, + &mut invocations, + saturated, + ) + .await + { + return outcome; + } + continue; + } + Err(_) => { + if let Some(outcome) = handle_stage_failure( + stage, + sequence, + original_size, + "middleware_timeout", + ¤t, + &findings, + &metadata, + &mut invocations, + saturated, + ) + .await + { + return outcome; + } + continue; + } + }; + + let result = match validate_message_result( + result, + sequence, + WebSocketMessageType::Text, + stage.entry.max_payload_bytes, + ) { + Ok(result) => result, + Err(reason) => { + if let Some(outcome) = handle_stage_failure( + stage, + sequence, + original_size, + reason, + ¤t, + &findings, + &metadata, + &mut invocations, + saturated, + ) + .await + { + return outcome; + } + continue; + } + }; + + let decision = Decision::try_from(result.decision).expect("validated decision"); + let reason_code = (!result.reason_code.is_empty()).then(|| result.reason_code.clone()); + for finding in result.findings { + findings.push(NamespacedFinding { + middleware: stage.entry.entry.name.clone(), + finding, + }); + } + if !result.metadata.is_empty() { + metadata.insert( + stage.entry.entry.name.clone(), + result.metadata.into_iter().collect(), + ); + } + if decision == Decision::Deny { + let denial = MiddlewareDenial { + config_name: stage.entry.entry.name.clone(), + reason_code, + }; + invocations.push(success_invocation( + &stage.entry, + WebSocketInvocationOutcome::Deny, + sequence, + original_size, + None, + false, + denial.reason_code.clone(), + )); + return denied_message_outcome( + current, + findings, + metadata, + invocations, + middleware_denial_reason(&denial.config_name, denial.reason_code.as_deref()), + Some(denial), + saturated, + ); + } + + let replacement_size = result.replacement.as_ref().map(websocket_replacement_len); + let transformed = result.replacement.is_some(); + if let Some(web_socket_message_result::Replacement::Text(replacement)) = + result.replacement + { + current = replacement; + } + invocations.push(success_invocation( + &stage.entry, + WebSocketInvocationOutcome::Allow, + sequence, + original_size, + replacement_size, + transformed, + reason_code, + )); + } + + WebSocketMessageOutcome { + allowed: true, + reason: String::new(), + payload: current, + findings, + metadata, + invocations, + denial: None, + saturated, + platform_oversize: false, + } + } + + pub async fn end(mut self, reason: WebSocketSessionEndReason) { + end_stages(&mut self.stages, reason).await; + self.reconcile_lifecycle(); + } +} + +impl Drop for WebSocketSession { + fn drop(&mut self) { + end_stages_now(&mut self.stages, WebSocketSessionEndReason::Cancellation); + self.reconcile_lifecycle(); + } +} + +fn platform_oversize_outcome(payload: String) -> WebSocketMessageOutcome { + WebSocketMessageOutcome { + allowed: false, + reason: "websocket_message_over_platform_capacity".to_string(), + payload, + findings: Vec::new(), + metadata: BTreeMap::new(), + invocations: Vec::new(), + denial: None, + saturated: false, + platform_oversize: true, + } +} + +fn admission_failure_outcome(payload: String) -> WebSocketMessageOutcome { + WebSocketMessageOutcome { + allowed: false, + reason: "middleware_admission_over_capacity".to_string(), + payload, + findings: Vec::new(), + metadata: BTreeMap::new(), + invocations: Vec::new(), + denial: None, + saturated: true, + platform_oversize: false, + } +} + +fn bypassed_message_outcome(payload: String) -> WebSocketMessageOutcome { + WebSocketMessageOutcome { + allowed: true, + reason: String::new(), + payload, + findings: Vec::new(), + metadata: BTreeMap::new(), + invocations: Vec::new(), + denial: None, + saturated: false, + platform_oversize: false, + } +} + +fn binding_not_selected_coverage(entry: &ChainEntry) -> WebSocketCoverage { + WebSocketCoverage { + config_name: entry.name.clone(), + implementation: entry.implementation.clone(), + state: WebSocketCoverageState::BindingNotSelected, + sequence: None, + message_type: None, + original_size: 0, + } +} + +fn preflight_stage_outcome( + entry: &DescribedChainEntry, + outcome: WebSocketInvocationOutcome, + decision: WebSocketPreflightDecision, +) -> PreflightStageOutcome { + let reason_code = (!decision.reason_code.is_empty()).then(|| decision.reason_code.clone()); + let findings = decision + .findings + .into_iter() + .map(|finding| NamespacedFinding { + middleware: entry.entry.name.clone(), + finding, + }) + .collect(); + let metadata = (!decision.metadata.is_empty()).then(|| { + ( + entry.entry.name.clone(), + decision.metadata.into_iter().collect(), + ) + }); + PreflightStageOutcome { + invocation: success_invocation(entry, outcome, 0, 0, None, false, reason_code), + findings, + metadata, + } +} + +fn collect_preflight_outcome( + outcome: PreflightStageOutcome, + invocations: &mut Vec, + findings: &mut Vec, + metadata: &mut BTreeMap>, +) { + invocations.push(outcome.invocation); + findings.extend(outcome.findings); + if let Some((middleware, values)) = outcome.metadata { + metadata.insert(middleware, values); + } +} + +async fn open_stage(entry: DescribedChainEntry, input: WebSocketPreflightInput) -> OpenStage { + let Some(service) = entry.service.as_ref() else { + return OpenStage::Failed(entry, "binding_not_described".into()); + }; + let dispatch = service.service.clone(); + let diagnostic_policy = service.diagnostic_policy; + let preflight = WebSocketPreflight { + session_id: input.session_id, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + context: Some(RequestContext { + request_id: input.request_id, + sandbox_id: input.sandbox_id, + originating_process: None, + }), + target: Some(HttpRequestTarget { + scheme: input.scheme, + host: input.host, + port: u32::from(input.port), + method: "GET".into(), + path: input.path, + query: String::new(), + }), + requested_subprotocols: input.requested_subprotocols, + middleware_name: entry.entry.implementation.clone(), + config: Some(entry.entry.config.clone()), + }; + if validate_preflight_envelope(&preflight).is_err() { + return OpenStage::Failed(entry, "preflight_envelope_over_capacity".into()); + } + + let timeout = entry.timeout.min(MAX_MIDDLEWARE_PREFLIGHT_TIMEOUT); + let opened = tokio::time::timeout(timeout, async { + let (sender, receiver) = mpsc::channel(STREAM_CHANNEL_CAPACITY); + sender + .send(WebSocketSessionEvent { + event: Some(web_socket_session_event::Event::Preflight(preflight)), + }) + .await + .map_err(|_| tonic::Status::unavailable("request stream closed"))?; + let mut responses = dispatch.open_websocket_session(receiver).await?; + let response = responses.next().await.transpose()?; + Ok::<_, tonic::Status>((sender, responses, response)) + }) + .await; + + let (sender, responses, response) = match opened { + Ok(Ok(opened)) => opened, + Ok(Err(error)) => { + return OpenStage::Failed(entry, diagnostic_policy.error_reason(&error)); + } + Err(_) => return OpenStage::Failed(entry, "middleware_timeout".into()), + }; + let Some(response) = response else { + let _ = sender.try_send(session_end_request( + WebSocketSessionEndReason::MiddlewareFailure, + )); + return OpenStage::Failed(entry, "missing_preflight_decision".into()); + }; + let Some(web_socket_session_event_result::Result::PreflightDecision(decision)) = + response.result + else { + let _ = sender.try_send(session_end_request( + WebSocketSessionEndReason::MiddlewareFailure, + )); + return OpenStage::Failed(entry, "invalid_preflight_decision".into()); + }; + let decision = match validate_preflight_decision(decision) { + Ok(decision) => decision, + Err(reason) => { + let _ = sender.try_send(session_end_request( + WebSocketSessionEndReason::MiddlewareFailure, + )); + return OpenStage::Failed(entry, reason.into()); + } + }; + let action = + WebSocketPreflightAction::try_from(decision.action).expect("validated preflight action"); + match action { + WebSocketPreflightAction::Inspect => { + let outcome = + preflight_stage_outcome(&entry, WebSocketInvocationOutcome::Inspect, decision); + OpenStage::Inspect( + Box::new(WebSocketStage { + entry, + transport: Some(WebSocketStageTransport { sender, responses }), + }), + outcome, + ) + } + WebSocketPreflightAction::Deny => { + let outcome = + preflight_stage_outcome(&entry, WebSocketInvocationOutcome::Deny, decision); + OpenStage::Deny( + Box::new(WebSocketStage { + entry, + transport: Some(WebSocketStageTransport { sender, responses }), + }), + outcome, + ) + } + WebSocketPreflightAction::Skip => { + let outcome = + preflight_stage_outcome(&entry, WebSocketInvocationOutcome::Skip, decision); + let _ = sender.try_send(session_end_request(WebSocketSessionEndReason::StageSkipped)); + OpenStage::Skip(outcome) + } + WebSocketPreflightAction::Unspecified => { + unreachable!("validated preflight action cannot be unspecified") + } + } +} + +fn validate_preflight_input(input: &WebSocketPreflightInput) -> miette::Result<()> { + if input.session_id.is_empty() || input.session_id.len() > 128 { + return Err(miette::miette!("invalid WebSocket middleware session id")); + } + if input.path.len() > super::MAX_MIDDLEWARE_TARGET_BYTES { + return Err(miette::miette!( + "WebSocket middleware preflight path exceeds platform capacity" + )); + } + if input.path.contains('?') { + return Err(miette::miette!( + "WebSocket middleware preflight path must not contain a query string" + )); + } + if input.requested_subprotocols.len() > MAX_REQUESTED_SUBPROTOCOLS + || input + .requested_subprotocols + .iter() + .map(String::len) + .sum::() + > MAX_SUBPROTOCOL_BYTES + { + return Err(miette::miette!( + "WebSocket middleware requested subprotocols exceed platform capacity" + )); + } + Ok(()) +} + +fn validate_preflight_envelope(preflight: &WebSocketPreflight) -> Result<(), &'static str> { + let Some(target) = preflight.target.as_ref() else { + return Err("preflight_target_missing"); + }; + if target.method != "GET" { + return Err("preflight_target_method_invalid"); + } + if !target.query.is_empty() || target.path.contains('?') { + return Err("preflight_target_query_present"); + } + if target.encoded_len() > super::MAX_MIDDLEWARE_TARGET_BYTES { + return Err("preflight_target_over_capacity"); + } + if preflight + .config + .as_ref() + .is_some_and(|config| config.encoded_len() > MAX_MIDDLEWARE_CONFIG_BYTES) + { + return Err("preflight_config_over_capacity"); + } + if preflight + .context + .as_ref() + .is_some_and(|context| context.encoded_len() > MAX_MIDDLEWARE_CONTEXT_BYTES) + { + return Err("preflight_context_over_capacity"); + } + if preflight.encoded_len() > MIDDLEWARE_GRPC_MESSAGE_BYTES { + return Err("preflight_envelope_over_capacity"); + } + Ok(()) +} + +fn validate_preflight_decision( + decision: WebSocketPreflightDecision, +) -> Result { + if !matches!( + WebSocketPreflightAction::try_from(decision.action), + Ok(WebSocketPreflightAction::Inspect + | WebSocketPreflightAction::Skip + | WebSocketPreflightAction::Deny) + ) { + return Err("invalid_preflight_decision"); + } + if decision.reason.len() > MAX_MIDDLEWARE_REASON_BYTES { + return Err("response_reason_over_capacity"); + } + if !decision.reason_code.is_empty() && !is_stable_reason_code(&decision.reason_code) { + return Err("response_reason_code_invalid"); + } + if decision.findings.len() > MAX_MIDDLEWARE_FINDINGS_PER_STAGE + || decision + .findings + .iter() + .any(|finding| finding.encoded_len() > MAX_MIDDLEWARE_FINDING_BYTES) + { + return Err("response_findings_over_capacity"); + } + if decision.metadata.len() > MAX_MIDDLEWARE_METADATA_ENTRIES { + return Err("response_metadata_count_over_capacity"); + } + let metadata_bytes = decision + .metadata + .iter() + .fold(0usize, |total, (key, value)| { + total.saturating_add(key.len()).saturating_add(value.len()) + }); + if metadata_bytes > MAX_MIDDLEWARE_METADATA_BYTES { + return Err("response_metadata_bytes_over_capacity"); + } + if decision.encoded_len() > MIDDLEWARE_GRPC_MESSAGE_BYTES { + return Err("response_envelope_over_capacity"); + } + Ok(decision) +} + +fn validate_message_result( + result: WebSocketMessageResult, + sequence: u64, + message_type: WebSocketMessageType, + stage_limit: usize, +) -> Result { + if result.sequence != sequence { + return Err("message_result_sequence_mismatch"); + } + if !matches!( + Decision::try_from(result.decision), + Ok(Decision::Allow | Decision::Deny) + ) { + return Err("invalid_response_decision"); + } + if result.reason.len() > MAX_MIDDLEWARE_REASON_BYTES { + return Err("response_reason_over_capacity"); + } + if !result.reason_code.is_empty() && !is_stable_reason_code(&result.reason_code) { + return Err("response_reason_code_invalid"); + } + if let Some(replacement) = &result.replacement { + if !matches!( + (message_type, replacement), + ( + WebSocketMessageType::Text, + web_socket_message_result::Replacement::Text(_) + ) | ( + WebSocketMessageType::Binary, + web_socket_message_result::Replacement::Binary(_) + ) + ) { + return Err("replacement_type_mismatch"); + } + let replacement_len = websocket_replacement_len(replacement); + if replacement_len > MAX_MIDDLEWARE_PAYLOAD_BYTES { + return Err("response_message_over_platform_capacity"); + } + if replacement_len > stage_limit { + return Err("response_message_over_capacity"); + } + } + if result.findings.len() > MAX_MIDDLEWARE_FINDINGS_PER_STAGE + || result + .findings + .iter() + .any(|finding| finding.encoded_len() > MAX_MIDDLEWARE_FINDING_BYTES) + { + return Err("response_findings_over_capacity"); + } + if result.metadata.len() > MAX_MIDDLEWARE_METADATA_ENTRIES { + return Err("response_metadata_count_over_capacity"); + } + let metadata_bytes = result.metadata.iter().fold(0usize, |total, (key, value)| { + total.saturating_add(key.len()).saturating_add(value.len()) + }); + if metadata_bytes > MAX_MIDDLEWARE_METADATA_BYTES { + return Err("response_metadata_bytes_over_capacity"); + } + if result.encoded_len() > MIDDLEWARE_GRPC_MESSAGE_BYTES { + return Err("response_envelope_over_capacity"); + } + Ok(result) +} + +fn websocket_replacement_len(replacement: &web_socket_message_result::Replacement) -> usize { + match replacement { + web_socket_message_result::Replacement::Text(text) => text.len(), + web_socket_message_result::Replacement::Binary(binary) => binary.len(), + } +} + +#[allow(clippy::too_many_arguments)] +async fn handle_stage_failure( + stage: &mut WebSocketStage, + sequence: u64, + original_size: usize, + reason: &str, + current: &str, + findings: &[NamespacedFinding], + metadata: &BTreeMap>, + invocations: &mut Vec, + saturated: bool, +) -> Option { + stage.disable().await; + let mut invocation = failure_invocation(&stage.entry, Some(sequence), original_size, reason); + invocation.stage_disabled = true; + invocations.push(invocation); + (stage.entry.entry.on_error == OnError::FailClosed).then(|| { + denied_message_outcome( + current.to_owned(), + findings.to_vec(), + metadata.clone(), + invocations.clone(), + format!("middleware_failed: {reason}"), + None, + saturated, + ) + }) +} + +fn denied_message_outcome( + payload: String, + findings: Vec, + metadata: BTreeMap>, + invocations: Vec, + reason: String, + denial: Option, + saturated: bool, +) -> WebSocketMessageOutcome { + WebSocketMessageOutcome { + allowed: false, + reason, + payload, + findings, + metadata, + invocations, + denial, + saturated, + platform_oversize: false, + } +} + +fn success_invocation( + entry: &DescribedChainEntry, + outcome: WebSocketInvocationOutcome, + sequence: u64, + original_size: usize, + replacement_size: Option, + transformed: bool, + reason_code: Option, +) -> WebSocketInvocation { + WebSocketInvocation { + config_name: entry.entry.name.clone(), + implementation: entry.entry.implementation.clone(), + outcome, + sequence: (sequence != 0).then_some(sequence), + original_size, + replacement_size, + transformed, + failed: false, + stage_disabled: false, + reason_code, + } +} + +fn failure_invocation( + entry: &DescribedChainEntry, + sequence: Option, + original_size: usize, + _reason: &str, +) -> WebSocketInvocation { + let outcome = match entry.entry.on_error { + OnError::FailOpen => WebSocketInvocationOutcome::FailOpen, + OnError::FailClosed => WebSocketInvocationOutcome::FailClosed, + }; + WebSocketInvocation { + config_name: entry.entry.name.clone(), + implementation: entry.entry.implementation.clone(), + outcome, + sequence, + original_size, + replacement_size: None, + transformed: false, + failed: true, + stage_disabled: false, + reason_code: None, + } +} + +async fn end_stages(stages: &mut [WebSocketStage], reason: WebSocketSessionEndReason) { + for stage in stages { + stage.end(reason).await; + } +} + +fn end_stages_now(stages: &mut [WebSocketStage], reason: WebSocketSessionEndReason) { + for stage in stages { + if let Some(transport) = stage.transport.take() { + let _ = transport.sender.try_send(session_end_request(reason)); + } + } +} + +fn session_end_request(reason: WebSocketSessionEndReason) -> WebSocketSessionEvent { + WebSocketSessionEvent { + event: Some(web_socket_session_event::Event::SessionEnd( + WebSocketSessionEnd { + reason: reason as i32, + }, + )), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn protobuf_rejects_invalid_utf8_text_payload() { + let encoded_text_with_invalid_utf8 = [0x12, 0x01, 0xff]; + assert!(WebSocketMessage::decode(encoded_text_with_invalid_utf8.as_slice()).is_err()); + } + + #[test] + fn replacement_presence_preserves_empty_text_and_rejects_type_changes() { + let empty_text = WebSocketMessageResult { + sequence: 7, + decision: Decision::Allow as i32, + replacement: Some(web_socket_message_result::Replacement::Text(String::new())), + ..Default::default() + }; + let validated = validate_message_result( + empty_text, + 7, + WebSocketMessageType::Text, + MAX_MIDDLEWARE_PAYLOAD_BYTES, + ) + .expect("empty text replacement must retain oneof presence"); + assert_eq!( + validated.replacement, + Some(web_socket_message_result::Replacement::Text(String::new())) + ); + + let binary_replacement = WebSocketMessageResult { + sequence: 7, + decision: Decision::Allow as i32, + replacement: Some(web_socket_message_result::Replacement::Binary(Vec::new())), + ..Default::default() + }; + assert_eq!( + validate_message_result( + binary_replacement, + 7, + WebSocketMessageType::Text, + MAX_MIDDLEWARE_PAYLOAD_BYTES, + ), + Err("replacement_type_mismatch") + ); + } + + #[tokio::test] + async fn disabling_stage_sends_middleware_failure_once() { + let (sender, mut requests) = mpsc::channel(1); + let mut stage = WebSocketStage { + entry: DescribedChainEntry { + entry: ChainEntry { + name: "best-effort".into(), + implementation: "test/middleware".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailOpen, + }, + service: None, + binding: None, + max_payload_bytes: 1024, + timeout: Duration::from_secs(1), + }, + transport: Some(WebSocketStageTransport { + sender, + responses: Box::pin(tokio_stream::empty()), + }), + }; + + stage.disable().await; + stage.disable().await; + + let event = requests.recv().await.expect("session end event"); + let Some(web_socket_session_event::Event::SessionEnd(end)) = event.event else { + panic!("disabled stage must receive session end"); + }; + assert_eq!( + WebSocketSessionEndReason::try_from(end.reason), + Ok(WebSocketSessionEndReason::MiddlewareFailure) + ); + assert!( + requests.try_recv().is_err(), + "disabled stage must receive at most one session end" + ); + } +} diff --git a/crates/openshell-supervisor-network/Cargo.toml b/crates/openshell-supervisor-network/Cargo.toml index 58360aa56c..ae36554be7 100644 --- a/crates/openshell-supervisor-network/Cargo.toml +++ b/crates/openshell-supervisor-network/Cargo.toml @@ -59,9 +59,11 @@ openshell-supervisor-middleware-builtins = { path = "../openshell-supervisor-mid tempfile = "3" tonic = { workspace = true } temp-env = "0.3" +tokio = { workspace = true, features = ["test-util"] } tokio-tungstenite = { workspace = true } futures = { workspace = true } tracing-subscriber = { workspace = true } +tokio-stream = { workspace = true, features = ["net"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/crates/openshell-supervisor-network/src/l7/middleware.rs b/crates/openshell-supervisor-network/src/l7/middleware.rs index 28f91c3bb7..b8c863f0cb 100644 --- a/crates/openshell-supervisor-network/src/l7/middleware.rs +++ b/crates/openshell-supervisor-network/src/l7/middleware.rs @@ -8,7 +8,8 @@ use crate::opa::PolicyGenerationGuard; use miette::{Result, miette}; use openshell_ocsf::{ ActionId, ActivityId, DetectionFindingBuilder, DispositionId, Endpoint, FindingInfo, - HttpActivityBuilder, HttpRequest, SeverityId, StatusId, Url as OcsfUrl, ocsf_emit, + HttpActivityBuilder, HttpRequest, NetworkActivityBuilder, SeverityId, StatusId, Url as OcsfUrl, + ocsf_emit, }; use std::path::PathBuf; use tokio::io::{AsyncRead, AsyncWrite}; @@ -18,6 +19,11 @@ pub enum MiddlewareApplyResult { Denied { denial: Option, }, + /// The platform's shared active-work and waiter capacities were both full. + /// + /// This is platform load shedding, not a selected middleware-stage failure, + /// so callers must not apply a stage's `on_error` policy. + AdmissionExhausted, } /// How traffic a middleware chain can never inspect (h2c, non-HTTP TCP, @@ -83,6 +89,321 @@ pub fn emit_middleware_uninspectable(ctx: &L7EvalContext, detail: &str, denied: ocsf_emit!(event); } +pub fn emit_websocket_preflight_events( + ctx: &L7EvalContext, + outcome: &openshell_supervisor_middleware::WebSocketPreflightResult, +) { + emit_websocket_invocations(ctx, &outcome.invocations); + emit_websocket_coverage(ctx, &outcome.coverage); + for event in websocket_preflight_finding_events(outcome) { + ocsf_emit!(event); + } + if outcome.saturated { + emit_websocket_saturation(ctx); + } + if outcome.session_capacity_exhausted { + emit_middleware_session_capacity_exhausted(ctx); + } +} + +pub(super) fn emit_websocket_coverage( + ctx: &L7EvalContext, + coverage: &[openshell_supervisor_middleware::WebSocketCoverage], +) { + for event in websocket_coverage_events(ctx, coverage) { + ocsf_emit!(event); + } +} + +/// Build coverage events separately from the tracing pipeline so tests can +/// assert exact coverage telemetry without process-global callsite cache races. +pub(super) fn websocket_coverage_events( + ctx: &L7EvalContext, + coverage: &[openshell_supervisor_middleware::WebSocketCoverage], +) -> Vec { + coverage + .iter() + .map(|coverage| { + use openshell_supervisor_middleware::WebSocketCoverageState as State; + + let state = match coverage.state { + State::BindingNotSelected => "binding_not_selected", + State::UnsupportedMessageType => "unsupported_message_type", + }; + let sequence = coverage + .sequence + .map_or_else(|| "-".to_string(), |sequence| sequence.to_string()); + let message_type = match coverage.message_type { + Some(openshell_supervisor_middleware::WebSocketMessageType::Text) => "text", + Some(openshell_supervisor_middleware::WebSocketMessageType::Binary) => "binary", + None => "-", + }; + NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Other) + .activity_name("WebSocket middleware coverage") + .action(ActionId::Allowed) + .disposition(DispositionId::Allowed) + .severity(SeverityId::Informational) + .status(StatusId::Success) + .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) + .firewall_rule(&ctx.policy_name, "supervisor-middleware") + .unmapped("middleware_config", coverage.config_name.as_str()) + .unmapped( + "middleware_implementation", + coverage.implementation.as_str(), + ) + .unmapped("coverage_state", state) + .unmapped("websocket_message_type", message_type) + .unmapped("websocket_sequence", sequence.as_str()) + .unmapped("input_bytes", coverage.original_size) + .message(format!( + "WEBSOCKET_MIDDLEWARE_COVERAGE state={state} config={} implementation={} sequence={sequence} message_type={message_type} input_bytes={}", + coverage.config_name, coverage.implementation, coverage.original_size, + )) + .build() + }) + .collect() +} + +pub(super) fn emit_websocket_session_start_events( + ctx: &L7EvalContext, + outcome: &openshell_supervisor_middleware::WebSocketSessionStartOutcome, +) { + emit_websocket_invocations(ctx, &outcome.invocations); +} + +pub(super) fn emit_websocket_message_events( + ctx: &L7EvalContext, + outcome: &openshell_supervisor_middleware::WebSocketMessageOutcome, +) { + emit_websocket_invocations(ctx, &outcome.invocations); + if outcome.saturated { + emit_websocket_saturation(ctx); + } + for event in websocket_message_finding_events(outcome) { + ocsf_emit!(event); + } +} + +pub(super) fn websocket_preflight_finding_events( + outcome: &openshell_supervisor_middleware::WebSocketPreflightResult, +) -> Vec { + middleware_finding_events(&outcome.findings) +} + +pub(super) fn websocket_message_finding_events( + outcome: &openshell_supervisor_middleware::WebSocketMessageOutcome, +) -> Vec { + middleware_finding_events(&outcome.findings) +} + +fn middleware_finding_events( + findings: &[openshell_supervisor_middleware::NamespacedFinding], +) -> Vec { + findings + .iter() + .take(openshell_supervisor_middleware::MAX_MIDDLEWARE_CHAIN_FINDINGS) + .map(|finding| { + DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(match finding.finding.severity.as_str() { + "high" => SeverityId::High, + "low" => SeverityId::Low, + _ => SeverityId::Medium, + }) + .finding_info(FindingInfo::new( + &finding.finding.r#type, + &finding.finding.label, + )) + .evidence_pairs(&[ + ("middleware", &finding.middleware), + ("count", &finding.finding.count.to_string()), + ]) + .unmapped("middleware", finding.middleware.as_str()) + .unmapped("count", finding.finding.count) + .message(format!( + "Middleware finding {} count={}", + finding.finding.r#type, finding.finding.count + )) + .build() + }) + .collect() +} + +fn emit_websocket_invocations( + ctx: &L7EvalContext, + invocations: &[openshell_supervisor_middleware::WebSocketInvocation], +) { + for invocation in invocations { + use openshell_supervisor_middleware::WebSocketInvocationOutcome as Outcome; + let (action, disposition, severity, status, outcome_name) = match invocation.outcome { + Outcome::Inspect => ( + ActionId::Other, + DispositionId::Allowed, + SeverityId::Informational, + StatusId::Success, + "inspect", + ), + Outcome::Skip => ( + ActionId::Other, + DispositionId::Other, + SeverityId::Informational, + StatusId::Success, + "voluntary_skip", + ), + Outcome::Allow => ( + ActionId::Allowed, + DispositionId::Allowed, + SeverityId::Informational, + StatusId::Success, + "allow", + ), + Outcome::Deny => ( + ActionId::Denied, + DispositionId::Blocked, + SeverityId::Medium, + StatusId::Failure, + "deny", + ), + Outcome::FailOpen => ( + ActionId::Other, + DispositionId::Allowed, + SeverityId::Medium, + StatusId::Failure, + "fail_open", + ), + Outcome::FailClosed => ( + ActionId::Denied, + DispositionId::Blocked, + SeverityId::High, + StatusId::Failure, + "fail_closed", + ), + }; + let sequence = invocation + .sequence + .map_or_else(|| "-".to_string(), |sequence| sequence.to_string()); + let replacement_size = invocation + .replacement_size + .map_or_else(|| "-".to_string(), |size| size.to_string()); + let reason_code = invocation.reason_code.as_deref().unwrap_or("-"); + let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Other) + .activity_name("WebSocket middleware") + .action(action) + .disposition(disposition) + .severity(severity) + .status(status) + .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) + .firewall_rule(&ctx.policy_name, "supervisor-middleware") + .message(format!( + "WEBSOCKET_MIDDLEWARE {outcome_name} config={} implementation={} sequence={sequence} input_bytes={} replacement_bytes={replacement_size} transformed={} reason_code={reason_code}", + invocation.config_name, + invocation.implementation, + invocation.original_size, + invocation.transformed, + )) + .build(); + ocsf_emit!(event); + if invocation.failed { + let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(if invocation.outcome == Outcome::FailClosed { + SeverityId::High + } else { + SeverityId::Medium + }) + .finding_info(FindingInfo::new( + "openshell.middleware.websocket_failure", + "WebSocket middleware processing failure", + )) + .evidence_pairs(&[ + ("policy", ctx.policy_name.as_str()), + ("host", ctx.host.as_str()), + ("config", invocation.config_name.as_str()), + ("implementation", invocation.implementation.as_str()), + ("disposition", outcome_name), + ]) + .message("WebSocket middleware stage failed") + .build(); + ocsf_emit!(event); + } + if invocation.stage_disabled { + let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(SeverityId::Medium) + .finding_info(FindingInfo::new( + "openshell.middleware.websocket_stage_disabled", + "WebSocket middleware stage disabled", + )) + .evidence_pairs(&[ + ("policy", ctx.policy_name.as_str()), + ("host", ctx.host.as_str()), + ("config", invocation.config_name.as_str()), + ("implementation", invocation.implementation.as_str()), + ("disposition", outcome_name), + ]) + .message( + "WebSocket middleware stage stream became unusable and was disabled for this session", + ) + .build(); + ocsf_emit!(event); + } + } +} + +fn emit_websocket_saturation(ctx: &L7EvalContext) { + let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(SeverityId::Medium) + .finding_info(FindingInfo::new( + "openshell.middleware.admission_saturated", + "Supervisor middleware admission saturated", + )) + .evidence_pairs(&[ + ("policy", ctx.policy_name.as_str()), + ("host", ctx.host.as_str()), + ("operation", "websocket_message"), + ]) + .message("WebSocket middleware work waited for admission capacity") + .build(); + ocsf_emit!(event); +} + +fn emit_middleware_session_capacity_exhausted(ctx: &L7EvalContext) { + let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(SeverityId::Medium) + .finding_info(FindingInfo::new( + "openshell.middleware.session_capacity_exhausted", + "Supervisor middleware session capacity exhausted", + )) + .evidence_pairs(&[ + ("policy", ctx.policy_name.as_str()), + ("host", ctx.host.as_str()), + ("operation", "websocket_message"), + ]) + .message("Persistent middleware session admission was refused at process capacity") + .build(); + ocsf_emit!(event); +} + +fn middleware_admission_exhausted_event(ctx: &L7EvalContext) -> openshell_ocsf::OcsfEvent { + DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) + .severity(SeverityId::Medium) + .finding_info(FindingInfo::new( + "openshell.middleware.admission_exhausted", + "Supervisor middleware admission exhausted", + )) + .evidence_pairs(&[ + ("policy", ctx.policy_name.as_str()), + ("host", ctx.host.as_str()), + ("operation", "http_request"), + ("disposition", "shed"), + ]) + .message("HTTP request shed because middleware work admission was exhausted") + .build() +} + +fn emit_middleware_admission_exhausted(ctx: &L7EvalContext) { + ocsf_emit!(middleware_admission_exhausted_event(ctx)); +} + /// Largest body-buffering limit across the entries that actually resolved to a /// registered binding. Buffering for the most capable stage lets every stage /// that can handle the body run; stages whose own limit is smaller are failed @@ -98,7 +419,7 @@ pub(super) fn middleware_chain_body_limit( chain .iter() .filter(|entry| entry.is_resolved()) - .map(openshell_supervisor_middleware::DescribedChainEntry::max_body_bytes) + .map(openshell_supervisor_middleware::DescribedChainEntry::max_payload_bytes) .max() } @@ -139,6 +460,20 @@ pub async fn apply_middleware_chain_for_scheme Some(admission), + openshell_supervisor_middleware::MiddlewareWorkAdmissionOutcome::QueueExhausted => { + emit_middleware_admission_exhausted(ctx); + return Ok(MiddlewareApplyResult::AdmissionExhausted); + } + } + }; let Some(max_body_bytes) = middleware_chain_body_limit(&chain) else { // No entry resolved to a registered binding, so nothing inspects the // body. Apply each entry's `on_error` policy without buffering (an @@ -153,7 +488,14 @@ pub async fn apply_middleware_chain_for_scheme( + req: &crate::l7::provider::L7Request, + client: &mut C, + ctx: &L7EvalContext, + redacted_target: &str, +) -> Result<()> { + crate::l7::rest::send_middleware_unavailable_response( + req, + &ctx.policy_name, + client, + Some(redacted_target), + Some(crate::l7::rest::DenyResponseContext::from_l7_context(ctx)), + ) + .await +} + pub(super) fn middleware_request_input( scheme: &str, req: &crate::l7::provider::L7Request, @@ -499,34 +868,7 @@ pub(super) fn middleware_events( // Each stage and the selected chain are independently bounded by the // runner. Keep the derived chain-wide emission bound as defense in depth // for manually constructed or future outcome producers. - for finding in outcome - .findings - .iter() - .take(openshell_supervisor_middleware::MAX_MIDDLEWARE_CHAIN_FINDINGS) - { - let event = DetectionFindingBuilder::new(openshell_ocsf::ctx::ctx()) - .severity(match finding.finding.severity.as_str() { - "high" => SeverityId::High, - "low" => SeverityId::Low, - _ => SeverityId::Medium, - }) - .finding_info(FindingInfo::new( - &finding.finding.r#type, - &finding.finding.label, - )) - .evidence_pairs(&[ - ("middleware", &finding.middleware), - ("count", &finding.finding.count.to_string()), - ]) - .unmapped("middleware", finding.middleware.as_str()) - .unmapped("count", finding.finding.count) - .message(format!( - "Middleware finding {} count={}", - finding.finding.r#type, finding.finding.count - )) - .build(); - events.push(event); - } + events.extend(middleware_finding_events(&outcome.findings)); events } @@ -544,10 +886,153 @@ fn emit_middleware_events( #[cfg(test)] mod tests { - use super::{safe_middleware_headers, send_middleware_rejection_response}; + use super::{ + middleware_admission_exhausted_event, safe_middleware_headers, + send_middleware_rejection_response, websocket_coverage_events, + websocket_message_finding_events, websocket_preflight_finding_events, + }; use crate::l7::relay::L7EvalContext; use tokio::io::AsyncReadExt; + #[test] + fn admission_exhaustion_event_contains_only_platform_context() { + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + policy_name: "api-policy".into(), + binary_path: "DO_NOT_LOG_BINARY".into(), + ..Default::default() + }; + + let serialized = serde_json::to_string(&middleware_admission_exhausted_event(&ctx)) + .expect("serialize admission event"); + assert!(serialized.contains("openshell.middleware.admission_exhausted")); + assert!(serialized.contains("api-policy")); + assert!(serialized.contains("api.example.test")); + assert!(serialized.contains("http_request")); + assert!(serialized.contains("shed")); + assert!(!serialized.contains("DO_NOT_LOG_BINARY")); + assert!(!serialized.contains("middleware_config")); + assert!(!serialized.contains("request_body")); + assert!(!serialized.contains("query")); + } + + #[test] + fn websocket_coverage_events_distinguish_selection_from_message_support() { + use openshell_ocsf::SeverityId; + use openshell_supervisor_middleware::{ + WebSocketCoverage, WebSocketCoverageState as State, WebSocketMessageType, + }; + + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 443, + policy_name: "api-policy".into(), + ..Default::default() + }; + let events = websocket_coverage_events( + &ctx, + &[ + WebSocketCoverage { + config_name: "http-guard".into(), + implementation: "example/http-only".into(), + state: State::BindingNotSelected, + sequence: None, + message_type: None, + original_size: 0, + }, + WebSocketCoverage { + config_name: "text-guard".into(), + implementation: "example/websocket-text".into(), + state: State::UnsupportedMessageType, + sequence: Some(7), + message_type: Some(WebSocketMessageType::Binary), + original_size: 23, + }, + ], + ); + + assert_eq!(events.len(), 2); + assert!(events.iter().all(|event| event.class_uid() == 4001)); + assert!( + events + .iter() + .all(|event| event.base().severity == SeverityId::Informational) + ); + let serialized = serde_json::to_string(&events).expect("serialize coverage events"); + assert!(serialized.contains("binding_not_selected")); + assert!(serialized.contains("unsupported_message_type")); + assert!(serialized.contains("\"websocket_message_type\":\"binary\"")); + assert!(serialized.contains("\"websocket_sequence\":\"7\"")); + assert!(serialized.contains("\"input_bytes\":23")); + assert!(!serialized.contains("fail_open")); + assert!(!serialized.contains("fail_closed")); + } + + #[test] + fn websocket_preflight_findings_match_http_mapping() { + let outcome = openshell_supervisor_middleware::WebSocketPreflightResult { + allowed: true, + terminal_reason: None, + reason: "allowed".into(), + denial: None, + session: None, + findings: vec![test_namespaced_finding()], + metadata: std::collections::BTreeMap::new(), + invocations: Vec::new(), + coverage: Vec::new(), + saturated: false, + session_capacity_exhausted: false, + }; + + assert_middleware_finding_mapping(websocket_preflight_finding_events(&outcome)); + } + + #[test] + fn websocket_message_findings_match_http_mapping() { + let outcome = openshell_supervisor_middleware::WebSocketMessageOutcome { + allowed: true, + reason: "allowed".into(), + payload: "hello".into(), + findings: vec![test_namespaced_finding()], + metadata: std::collections::BTreeMap::new(), + invocations: Vec::new(), + denial: None, + saturated: false, + platform_oversize: false, + }; + + assert_middleware_finding_mapping(websocket_message_finding_events(&outcome)); + } + + fn test_namespaced_finding() -> openshell_supervisor_middleware::NamespacedFinding { + openshell_supervisor_middleware::NamespacedFinding { + middleware: "content-guard".into(), + finding: openshell_core::proto::Finding { + r#type: "regex.api_key".into(), + label: "API key".into(), + count: 3, + confidence: "high".into(), + severity: "high".into(), + }, + } + } + + fn assert_middleware_finding_mapping(events: Vec) { + use openshell_ocsf::SeverityId; + + assert_eq!(events.len(), 1); + assert_eq!(events[0].class_uid(), 2004); + assert_eq!(events[0].base().severity, SeverityId::High); + let serialized = serde_json::to_string(&events[0]).expect("serialize finding event"); + assert!(serialized.contains("regex.api_key")); + assert!(serialized.contains("API key")); + assert!(serialized.contains("content-guard")); + assert!(serialized.contains("\"count\":3")); + assert!(serialized.contains("Middleware finding regex.api_key count=3")); + assert!(!serialized.contains("openshell.middleware.websocket_finding")); + } + #[tokio::test] async fn direct_denial_uses_middleware_response_without_service_text() { let ctx = L7EvalContext { diff --git a/crates/openshell-supervisor-network/src/l7/provider.rs b/crates/openshell-supervisor-network/src/l7/provider.rs index 864d94ad26..3a51bd1d8c 100644 --- a/crates/openshell-supervisor-network/src/l7/provider.rs +++ b/crates/openshell-supervisor-network/src/l7/provider.rs @@ -30,6 +30,7 @@ pub enum RelayOutcome { Upgraded { overflow: Vec, websocket_permessage_deflate: bool, + websocket_subprotocol: Option, }, } diff --git a/crates/openshell-supervisor-network/src/l7/relay.rs b/crates/openshell-supervisor-network/src/l7/relay.rs index aae3c042b9..6bd0a98476 100644 --- a/crates/openshell-supervisor-network/src/l7/relay.rs +++ b/crates/openshell-supervisor-network/src/l7/relay.rs @@ -312,13 +312,17 @@ where pub(crate) struct UpgradeRelayOptions<'a> { pub(crate) websocket_request: bool, pub(crate) websocket: WebSocketUpgradeBehavior, + pub(crate) assembly_budget: Option, pub(crate) secret_resolver: Option>, + pub(crate) generation_guard: Option<&'a PolicyGenerationGuard>, pub(crate) engine: Option<&'a TunnelPolicyEngine>, pub(crate) ctx: Option<&'a L7EvalContext>, pub(crate) enforcement: EnforcementMode, pub(crate) target: String, pub(crate) query_params: std::collections::HashMap>, pub(crate) policy_name: String, + pub(crate) middleware_session: Option, + pub(crate) selected_subprotocol: Option, } #[derive(Default)] @@ -701,12 +705,13 @@ where if allowed || (config.enforcement == EnforcementMode::Audit && !force_deny) { let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + let websocket_chain = websocket_request.then(|| chain.clone()); // Route selection resolved `config` per request, so re-check the // body against that protocol's policy after every transforming // stage (a no-op for REST and websocket, whose policy inputs the // chain cannot mutate). let validate = transformed_body_validator(config, &engine, ctx, &request_info); - let req = match apply_middleware_chain( + let middleware_result = apply_middleware_chain( req, client, ctx, @@ -715,8 +720,8 @@ where engine.generation_guard(), openshell_supervisor_middleware::TransformedBodyPolicy::Reevaluate(&validate), ) - .await? - { + .await; + let req = match middleware_result? { MiddlewareApplyResult::Allowed(request) => request, MiddlewareApplyResult::Denied { denial, .. } => { let denied_request = crate::l7::provider::L7Request { @@ -736,10 +741,60 @@ where .await?; return Ok(()); } + MiddlewareApplyResult::AdmissionExhausted => { + let unavailable_request = crate::l7::provider::L7Request { + action: request_info.action.clone(), + target: redacted_target.clone(), + query_params: request_info.query_params.clone(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + crate::l7::middleware::send_middleware_admission_exhausted_response( + &unavailable_request, + client, + ctx, + &redacted_target, + ) + .await?; + return Ok(()); + } }; let scoped_ctx = scoped_context_for_request(ctx, &req); let ctx = scoped_ctx.as_ref().unwrap_or(ctx); - let Some(outcome) = relay_http_request_with_credential_rejection( + let mut middleware_session = if let Some(chain) = websocket_chain.as_deref() { + let preflight = websocket_middleware_preflight( + &req, + chain, + engine.middleware_runner(), + ctx, + "wss", + ) + .await; + let preflight = match preflight { + Ok(preflight) => preflight, + Err(error) => { + warn!(error = %error, "WebSocket middleware preflight failed"); + write_bad_gateway_response(client).await?; + return Ok(()); + } + }; + crate::l7::middleware::emit_websocket_preflight_events(ctx, &preflight); + if preflight.terminal_reason.is_some() { + crate::l7::middleware::send_middleware_rejection_response( + &req, + client, + ctx, + preflight.denial.as_ref(), + &redacted_target, + ) + .await?; + return Ok(()); + } + preflight.session + } else { + None + }; + let outcome_result = relay_http_request_with_credential_rejection( &req, client, upstream, @@ -747,7 +802,10 @@ where resolver: ctx.secret_resolver.as_deref(), credential_generation: credential_generation_guard(ctx), generation_guard: Some(engine.generation_guard()), - websocket_extensions: websocket_extension_mode(config), + websocket_extensions: websocket_extension_mode( + config, + middleware_session.is_some(), + ), request_body_credential_rewrite: config.protocol == L7Protocol::Rest && config.request_body_credential_rewrite, credential_signing: config.credential_signing, @@ -758,16 +816,48 @@ where }, ctx, ) - .await? - else { - return Ok(()); + .await; + let outcome_result = match outcome_result { + Ok(Some(outcome)) => Ok(outcome), + Ok(None) => { + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::Cancellation) + .await; + } + return Ok(()); + } + Err(error) => Err(error), }; + let outcome = finalize_websocket_pre_upgrade( + &mut middleware_session, + engine.generation_guard(), + &ctx.host, + ctx.port, + &ctx.policy_name, + outcome_result, + ) + .await?; match outcome { - RelayOutcome::Reusable => {} - RelayOutcome::Consumed => return Ok(()), + RelayOutcome::Reusable => { + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::UpstreamRejected) + .await; + } + } + RelayOutcome::Consumed => { + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::UpstreamRejected) + .await; + } + return Ok(()); + } RelayOutcome::Upgraded { overflow, websocket_permessage_deflate, + websocket_subprotocol, } => { let mut options = upgrade_options( config, @@ -778,6 +868,8 @@ where Some(&engine), ); options.websocket.permessage_deflate = websocket_permessage_deflate; + options.middleware_session = middleware_session.take(); + options.selected_subprotocol = websocket_subprotocol; return handle_upgrade( client, upstream, overflow, &ctx.host, ctx.port, options, ) @@ -877,6 +969,37 @@ fn emit_activity(ctx: &L7EvalContext, denied: bool, deny_group: &'static str) { } } +pub(crate) async fn websocket_middleware_preflight( + req: &crate::l7::provider::L7Request, + chain: &[openshell_supervisor_middleware::ChainEntry], + runner: &openshell_supervisor_middleware::ChainRunner, + ctx: &L7EvalContext, + scheme: &str, +) -> Result { + let header_end = req + .raw_header + .windows(4) + .position(|window| window == b"\r\n\r\n") + .map_or(req.raw_header.len(), |position| position + 4); + let requested_subprotocols = + crate::l7::rest::websocket_requested_subprotocols(&req.raw_header[..header_end])?; + runner + .preflight_websocket( + chain, + openshell_supervisor_middleware::WebSocketPreflightInput { + session_id: uuid::Uuid::new_v4().to_string(), + request_id: uuid::Uuid::new_v4().to_string(), + sandbox_id: openshell_ocsf::ctx::ctx().sandbox_id.clone(), + scheme: scheme.to_string(), + host: ctx.host.clone(), + port: ctx.port, + path: req.target.clone(), + requested_subprotocols, + }, + ) + .await +} + /// Handle an upgraded connection (101 Switching Protocols). /// /// Forwards any overflow bytes from the upgrade response to the client, then @@ -888,16 +1011,37 @@ pub(crate) async fn handle_upgrade( overflow: Vec, host: &str, port: u16, - options: UpgradeRelayOptions<'_>, + mut options: UpgradeRelayOptions<'_>, ) -> Result<()> where C: AsyncRead + AsyncWrite + Unpin + Send, U: AsyncRead + AsyncWrite + Unpin + Send, { + ensure_upgrade_generation_current(client, upstream, host, port, &mut options).await?; + let start_terminal_reason = if let Some(session) = options.middleware_session.as_mut() { + let start = session + .start(options.selected_subprotocol.as_deref().unwrap_or_default()) + .await; + if let Some(ctx) = options.ctx { + crate::l7::middleware::emit_websocket_session_start_events(ctx, &start); + } + start.terminal_reason + } else { + None + }; + ensure_upgrade_generation_current(client, upstream, host, port, &mut options).await?; + if let Some(reason) = start_terminal_reason { + if let Some(session) = options.middleware_session.take() { + session.end(reason).await; + } + send_websocket_close(client, upstream, 1008).await; + return Ok(()); + } let use_websocket_relay = options.websocket_request && (options.websocket.message_policy.inspects_messages() || options.websocket.permessage_deflate - || options.websocket.credential_rewrite); + || options.websocket.credential_rewrite + || options.middleware_session.is_some()); let relay_mode = if use_websocket_relay { "websocket parsed relay" } else { @@ -916,6 +1060,7 @@ where .build() ); if use_websocket_relay { + let assembly_budget = options.assembly_budget.take().unwrap_or_default(); let resolver = if options.websocket.credential_rewrite { options.secret_resolver.as_deref() } else { @@ -953,13 +1098,17 @@ where port, crate::l7::websocket::RelayOptions { policy_name: &options.policy_name, + assembly_budget, resolver, + generation_guard: options.generation_guard, provider_credentials: options .ctx .and_then(|ctx| ctx.provider_credentials.as_ref()), target: &options.target, inspector, compression, + middleware_session: options.middleware_session.take(), + middleware_context: options.ctx, }, ) .await; @@ -974,6 +1123,45 @@ where Ok(()) } +async fn ensure_upgrade_generation_current( + client: &mut C, + upstream: &mut U, + host: &str, + port: u16, + options: &mut UpgradeRelayOptions<'_>, +) -> Result<()> +where + C: AsyncWrite + Unpin, + U: AsyncWrite + Unpin, +{ + let Some(guard) = options.generation_guard else { + return Ok(()); + }; + if let Err(error) = guard.ensure_current() { + emit_policy_reload(guard, host, port, &options.policy_name); + if let Some(session) = options.middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::PolicyReload) + .await; + } + send_websocket_close(client, upstream, 1012).await; + return Err(error); + } + Ok(()) +} + +async fn send_websocket_close(client: &mut C, upstream: &mut U, code: u16) +where + C: AsyncWrite + Unpin, + U: AsyncWrite + Unpin, +{ + let payload = code.to_be_bytes(); + let _ = crate::l7::websocket::write_unmasked_close(client, &payload).await; + let _ = crate::l7::websocket::write_masked_close(upstream, &payload).await; + let _ = client.shutdown().await; + let _ = upstream.shutdown().await; +} + pub(crate) fn upgrade_options<'a>( config: &L7EndpointConfig, ctx: &'a L7EvalContext, @@ -1001,22 +1189,30 @@ pub(crate) fn upgrade_options<'a>( message_policy: websocket_message_policy, permessage_deflate: false, }, + assembly_budget: engine.map(TunnelPolicyEngine::websocket_assembly_budget), secret_resolver: if websocket_credential_rewrite { ctx.secret_resolver.clone() } else { None }, + generation_guard: engine.map(TunnelPolicyEngine::generation_guard), engine, ctx: (engine.is_some() || websocket_credential_rewrite).then_some(ctx), enforcement: config.enforcement, target: target.to_string(), query_params: query_params.clone(), policy_name: ctx.policy_name.clone(), + middleware_session: None, + selected_subprotocol: None, } } -pub(crate) fn websocket_extension_mode(config: &L7EndpointConfig) -> WebSocketExtensionMode { - if config.protocol == L7Protocol::Websocket +pub(crate) fn websocket_extension_mode( + config: &L7EndpointConfig, + inspecting_middleware_session: bool, +) -> WebSocketExtensionMode { + if inspecting_middleware_session + || config.protocol == L7Protocol::Websocket || (config.protocol == L7Protocol::Rest && config.websocket_credential_rewrite) { WebSocketExtensionMode::PermessageDeflate @@ -1185,10 +1381,11 @@ where if allowed || config.enforcement == EnforcementMode::Audit { let chain = engine.query_middleware_chain(&middleware_network_input(ctx))?; + let websocket_chain = websocket_request.then(|| chain.clone()); // REST and websocket-upgrade policy evaluates only the method, // path, and query, which a middleware result cannot mutate, so no // per-stage body re-check is needed. - let req = match apply_middleware_chain( + let middleware_result = apply_middleware_chain( req, client, ctx, @@ -1197,8 +1394,8 @@ where engine.generation_guard(), openshell_supervisor_middleware::TransformedBodyPolicy::NotPolicyRelevant, ) - .await? - { + .await; + let req = match middleware_result? { MiddlewareApplyResult::Allowed(request) => request, MiddlewareApplyResult::Denied { denial, .. } => { let denied_request = crate::l7::provider::L7Request { @@ -1218,6 +1415,56 @@ where .await?; return Ok(()); } + MiddlewareApplyResult::AdmissionExhausted => { + let unavailable_request = crate::l7::provider::L7Request { + action: request_info.action.clone(), + target: redacted_target.clone(), + query_params: request_info.query_params.clone(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + crate::l7::middleware::send_middleware_admission_exhausted_response( + &unavailable_request, + client, + ctx, + &redacted_target, + ) + .await?; + return Ok(()); + } + }; + let mut middleware_session = if let Some(chain) = websocket_chain.as_deref() { + let preflight = websocket_middleware_preflight( + &req, + chain, + engine.middleware_runner(), + ctx, + "wss", + ) + .await; + let preflight = match preflight { + Ok(preflight) => preflight, + Err(error) => { + warn!(error = %error, "WebSocket middleware preflight failed"); + write_bad_gateway_response(client).await?; + return Ok(()); + } + }; + crate::l7::middleware::emit_websocket_preflight_events(ctx, &preflight); + if preflight.terminal_reason.is_some() { + crate::l7::middleware::send_middleware_rejection_response( + &req, + client, + ctx, + preflight.denial.as_ref(), + &redacted_target, + ) + .await?; + return Ok(()); + } + preflight.session + } else { + None }; let req_with_auth = match crate::l7::token_grant_injection::inject_if_needed(req, ctx).await { @@ -1237,7 +1484,7 @@ where let ctx = scoped_ctx.as_ref().unwrap_or(ctx); // Forward request to upstream and relay response - let Some(outcome) = relay_http_request_with_credential_rejection( + let outcome_result = relay_http_request_with_credential_rejection( &req_with_auth, client, upstream, @@ -1245,7 +1492,10 @@ where resolver: ctx.secret_resolver.as_deref(), credential_generation: credential_generation_guard(ctx), generation_guard: Some(engine.generation_guard()), - websocket_extensions: websocket_extension_mode(config), + websocket_extensions: websocket_extension_mode( + config, + middleware_session.is_some(), + ), request_body_credential_rewrite: config.protocol == L7Protocol::Rest && config.request_body_credential_rewrite, credential_signing: config.credential_signing, @@ -1256,13 +1506,42 @@ where }, ctx, ) - .await? - else { - return Ok(()); + .await; + let outcome_result = match outcome_result { + Ok(Some(outcome)) => Ok(outcome), + Ok(None) => { + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::Cancellation) + .await; + } + return Ok(()); + } + Err(error) => Err(error), }; + let outcome = finalize_websocket_pre_upgrade( + &mut middleware_session, + engine.generation_guard(), + &ctx.host, + ctx.port, + &ctx.policy_name, + outcome_result, + ) + .await?; match outcome { - RelayOutcome::Reusable => {} // continue loop + RelayOutcome::Reusable => { + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::UpstreamRejected) + .await; + } + } RelayOutcome::Consumed => { + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::UpstreamRejected) + .await; + } debug!( host = %ctx.host, port = ctx.port, @@ -1273,6 +1552,7 @@ where RelayOutcome::Upgraded { overflow, websocket_permessage_deflate, + websocket_subprotocol, } => { let mut options = upgrade_options( config, @@ -1283,6 +1563,8 @@ where Some(engine), ); options.websocket.permessage_deflate = websocket_permessage_deflate; + options.middleware_session = middleware_session.take(); + options.selected_subprotocol = websocket_subprotocol; return handle_upgrade( client, upstream, overflow, &ctx.host, ctx.port, options, ) @@ -1311,6 +1593,16 @@ fn close_if_stale(guard: &PolicyGenerationGuard, ctx: &L7EvalContext) -> bool { return false; } + emit_policy_reload(guard, &ctx.host, ctx.port, &ctx.policy_name); + true +} + +pub(crate) fn emit_policy_reload( + guard: &PolicyGenerationGuard, + host: &str, + port: u16, + policy_name: &str, +) { ocsf_emit!( NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Open) @@ -1318,18 +1610,55 @@ fn close_if_stale(guard: &PolicyGenerationGuard, ctx: &L7EvalContext) -> bool { .disposition(DispositionId::Blocked) .severity(SeverityId::Medium) .status(StatusId::Failure) - .dst_endpoint(Endpoint::from_domain(&ctx.host, ctx.port)) - .firewall_rule(&ctx.policy_name, "l7") + .dst_endpoint(Endpoint::from_domain(host, port)) + .firewall_rule(policy_name, "l7") .message(format!( "L7 tunnel closed after policy reload [host:{} port:{} captured_generation:{} current_generation:{}]", - ctx.host, - ctx.port, + host, + port, guard.captured_generation(), guard.current_generation(), )) .build() ); - true +} + +pub(crate) async fn finalize_websocket_pre_upgrade( + session: &mut Option, + guard: &PolicyGenerationGuard, + host: &str, + port: u16, + policy_name: &str, + result: Result, +) -> Result { + match result { + Ok(value @ RelayOutcome::Upgraded { .. }) => Ok(value), + Ok(value) => { + if let Err(error) = guard.ensure_current() { + emit_policy_reload(guard, host, port, policy_name); + if let Some(session) = session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::PolicyReload) + .await; + } + Err(error) + } else { + Ok(value) + } + } + Err(error) => { + let reason = if guard.is_stale() { + emit_policy_reload(guard, host, port, policy_name); + openshell_core::proto::WebSocketSessionEndReason::PolicyReload + } else { + openshell_core::proto::WebSocketSessionEndReason::UpstreamRejected + }; + if let Some(session) = session.take() { + session.end(reason).await; + } + Err(error) + } + } } async fn relay_jsonrpc( @@ -1499,6 +1828,23 @@ where .await?; return Ok(()); } + MiddlewareApplyResult::AdmissionExhausted => { + let unavailable_request = crate::l7::provider::L7Request { + action: request_info.action.clone(), + target: redacted_target.clone(), + query_params: request_info.query_params.clone(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + crate::l7::middleware::send_middleware_admission_exhausted_response( + &unavailable_request, + client, + ctx, + &redacted_target, + ) + .await?; + return Ok(()); + } }; let scoped_ctx = scoped_context_for_request(ctx, &req); let ctx = scoped_ctx.as_ref().unwrap_or(ctx); @@ -1722,6 +2068,23 @@ where .await?; return Ok(()); } + MiddlewareApplyResult::AdmissionExhausted => { + let unavailable_request = crate::l7::provider::L7Request { + action: request_info.action.clone(), + target: redacted_target.clone(), + query_params: request_info.query_params.clone(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + crate::l7::middleware::send_middleware_admission_exhausted_response( + &unavailable_request, + client, + ctx, + &redacted_target, + ) + .await?; + return Ok(()); + } }; let scoped_ctx = scoped_context_for_request(ctx, &req); let ctx = scoped_ctx.as_ref().unwrap_or(ctx); @@ -1754,8 +2117,12 @@ where RelayOutcome::Upgraded { overflow, websocket_permessage_deflate, + .. } => { let options = UpgradeRelayOptions { + assembly_budget: Some( + crate::l7::websocket::WebSocketAssemblyBudget::default(), + ), websocket: WebSocketUpgradeBehavior { permessage_deflate: websocket_permessage_deflate, ..Default::default() @@ -2323,6 +2690,23 @@ where .await?; return Ok(()); } + MiddlewareApplyResult::AdmissionExhausted => { + let unavailable_request = crate::l7::provider::L7Request { + action: "HTTP".into(), + target: redacted_target.clone(), + query_params: std::collections::HashMap::new(), + raw_header: Vec::new(), + body_length: crate::l7::provider::BodyLength::None, + }; + crate::l7::middleware::send_middleware_admission_exhausted_response( + &unavailable_request, + client, + ctx, + &redacted_target, + ) + .await?; + return Ok(()); + } } } else { req @@ -2755,6 +3139,35 @@ mod tests { assert!(body.get("agent_guidance").is_none()); } + fn assert_middleware_unavailable_response(response: &str, policy_name: &str) { + assert!( + response.starts_with("HTTP/1.1 503 Service Unavailable\r\n"), + "{response}" + ); + assert!(!response.contains("100 Continue"), "{response}"); + assert!(!response.to_ascii_lowercase().contains("retry-after")); + let (headers, body) = response.split_once("\r\n\r\n").expect("HTTP response"); + let content_length = headers + .lines() + .find_map(|line| { + line.strip_prefix("Content-Length: ") + .and_then(|value| value.parse::().ok()) + }) + .expect("Content-Length"); + assert_eq!(content_length, body.len()); + let body: serde_json::Value = serde_json::from_str(body).expect("JSON response"); + assert_eq!(body["error"], "middleware_failed"); + assert_eq!( + body["detail"], + "Request could not be processed by configured middleware" + ); + assert_eq!(body["policy"], policy_name); + assert!(body.get("middleware").is_none()); + assert!(body.get("reason_code").is_none()); + assert!(body.get("rule_missing").is_none()); + assert!(body.get("next_steps").is_none()); + } + fn rest_token_grant_relay_context( resolver_response: std::result::Result<&str, &str>, ) -> ( @@ -2935,6 +3348,304 @@ network_policies: (generation_guard, ctx, fixture) } + #[derive(Clone)] + struct ControllableWebSocketPreflight { + seen: tokio::sync::mpsc::UnboundedSender<()>, + release: Arc, + action: openshell_core::proto::WebSocketPreflightAction, + } + + #[tonic::async_trait] + impl openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddleware + for ControllableWebSocketPreflight + { + type EvaluateWebSocketSessionStream = + openshell_supervisor_middleware::WebSocketResponseStream; + + async fn describe( + &self, + _request: tonic::Request<()>, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::MiddlewareManifest { + name: "test/controllable-websocket-preflight".into(), + service_version: "test".into(), + bindings: vec![openshell_core::proto::MiddlewareBinding { + operation: + openshell_core::proto::SupervisorMiddlewareOperation::WebsocketMessage + as i32, + phase: openshell_core::proto::SupervisorMiddlewarePhase::PreCredentials + as i32, + max_payload_bytes: + openshell_supervisor_middleware::MAX_MIDDLEWARE_PAYLOAD_BYTES as u64, + timeout: "2s".into(), + }], + expected_audience: String::new(), + }, + )) + } + + async fn validate_config( + &self, + _request: tonic::Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + _request: tonic::Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Err(tonic::Status::unimplemented("WebSocket-only middleware")) + } + + async fn evaluate_web_socket_session( + &self, + request: tonic::Request>, + ) -> std::result::Result, tonic::Status> + { + use openshell_core::proto::{ + WebSocketPreflightDecision, WebSocketSessionEventResult, web_socket_session_event, + web_socket_session_event_result, + }; + use tokio_stream::wrappers::ReceiverStream; + + let mut requests = request.into_inner(); + let seen = self.seen.clone(); + let release = Arc::clone(&self.release); + let action = self.action; + let (responses_tx, responses_rx) = tokio::sync::mpsc::channel(4); + tokio::spawn(async move { + while let Ok(Some(request)) = requests.message().await { + if matches!( + request.event, + Some(web_socket_session_event::Event::Preflight(_)) + ) { + let _ = seen.send(()); + release.notified().await; + let _ = responses_tx + .send(Ok(WebSocketSessionEventResult { + result: Some( + web_socket_session_event_result::Result::PreflightDecision( + WebSocketPreflightDecision { + action: action as i32, + ..Default::default() + }, + ), + ), + })) + .await; + } + } + }); + Ok(tonic::Response::new(Box::pin(ReceiverStream::new( + responses_rx, + )))) + } + } + + async fn assert_websocket_preflight_precedes_token_grant( + action: openshell_core::proto::WebSocketPreflightAction, + admitted: bool, + ) { + use openshell_core::proto::SupervisorMiddlewareService; + use openshell_core::proto::middleware::v1::supervisor_middleware_server::SupervisorMiddlewareServer; + use openshell_supervisor_middleware::{ChainRunner, MiddlewareRegistry}; + use tokio_stream::wrappers::TcpListenerStream; + + let (seen_tx, mut seen_rx) = tokio::sync::mpsc::unbounded_channel(); + let release = Arc::new(tokio::sync::Notify::new()); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind middleware"); + let address = listener.local_addr().expect("middleware address"); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tonic::transport::Server::builder() + .add_service(SupervisorMiddlewareServer::new( + ControllableWebSocketPreflight { + seen: seen_tx, + release: Arc::clone(&release), + action, + }, + )) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }); + let server_task = tokio::spawn(server); + let registry = MiddlewareRegistry::connect_services( + Vec::new(), + vec![SupervisorMiddlewareService { + name: "preflight-service".into(), + grpc_endpoint: format!("http://{address}"), + max_payload_bytes: openshell_supervisor_middleware::MAX_MIDDLEWARE_PAYLOAD_BYTES + as u64, + timeout: "2s".into(), + tls_ca_cert_pem: Vec::new(), + audience: String::new(), + allow_insecure_transport: false, + }], + ) + .await + .expect("connect middleware"); + + let data = r#" +network_middlewares: + websocket-preflight: + middleware: preflight-service + on_error: fail_closed + endpoints: + include: ["api.example.test"] +network_policies: + rest_api: + name: rest_api + endpoints: + - host: api.example.test + port: 8080 + protocol: rest + enforcement: enforce + rules: + - allow: + method: GET + path: "/v1/**" + binaries: + - { path: /usr/bin/curl } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).expect("test policy"); + engine.set_middleware_runner_for_tests(ChainRunner::from_registry(registry)); + let input = NetworkInput { + host: "api.example.test".into(), + port: 8080, + binary_path: PathBuf::from("/usr/bin/curl"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint_config, generation) = engine + .query_endpoint_config_with_generation(&input) + .expect("endpoint config"); + let config = crate::l7::parse_l7_config(&endpoint_config.expect("configured endpoint")) + .expect("REST config"); + let tunnel_engine = engine + .clone_engine_for_tunnel(generation) + .expect("tunnel engine"); + let provider_key = "api.example.test\t8080\t/v1/**\tprovider:access_token"; + let fixture = + crate::l7::token_grant_injection::test_support::TokenGrantTestFixture::success( + provider_key, + "grant-token", + ); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 8080, + request_default_port: Some(8080), + policy_name: "rest_api".into(), + binary_path: "/usr/bin/curl".into(), + dynamic_credentials: Some(fixture.dynamic_credentials()), + token_grant_resolver: Some(fixture.resolver()), + ..Default::default() + }; + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_rest( + &config, + &tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + app.write_all( + b"GET /v1/ws HTTP/1.1\r\nHost: api.example.test\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n", + ) + .await + .expect("send upgrade request"); + seen_rx.recv().await.expect("preflight reached middleware"); + fixture.assert_no_requests(); + release.notify_one(); + + if admitted { + let mut forwarded = Vec::new(); + let mut buffer = [0u8; 512]; + while !forwarded.windows(4).any(|window| window == b"\r\n\r\n") { + let count = upstream.read(&mut buffer).await.expect("read upstream"); + assert!(count > 0, "upstream closed before request headers"); + forwarded.extend_from_slice(&buffer[..count]); + } + let forwarded = String::from_utf8_lossy(&forwarded); + assert!(forwarded.contains("Authorization: Bearer grant-token\r\n")); + upstream + .write_all( + b"HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n", + ) + .await + .expect("reject upgrade"); + let mut response = [0u8; 512]; + let count = app.read(&mut response).await.expect("read client response"); + assert!( + String::from_utf8_lossy(&response[..count]).contains("400 Bad Request"), + "unexpected client response" + ); + fixture.assert_one_request(provider_key); + } else { + let mut response = [0u8; 1024]; + let count = app.read(&mut response).await.expect("read client response"); + let response = String::from_utf8_lossy(&response[..count]); + assert!(response.contains("403 Forbidden"), "{response}"); + assert!(response.contains(r#""error":"middleware_denied""#)); + assert!(response.contains(r#""middleware":"websocket-preflight""#)); + let mut byte = [0u8; 1]; + let count = upstream.read(&mut byte).await.expect("upstream close"); + assert_eq!(count, 0, "denied preflight must not reach upstream"); + fixture.assert_no_requests(); + } + + drop(app); + relay + .await + .expect("join REST relay") + .expect("REST relay result"); + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware server") + .expect("middleware server"); + } + + #[tokio::test] + async fn denied_websocket_preflight_has_no_token_grant_side_effects() { + assert_websocket_preflight_precedes_token_grant( + openshell_core::proto::WebSocketPreflightAction::Deny, + false, + ) + .await; + } + + #[tokio::test] + async fn admitted_websocket_preflight_precedes_token_grant() { + assert_websocket_preflight_precedes_token_grant( + openshell_core::proto::WebSocketPreflightAction::Inspect, + true, + ) + .await; + } + fn jsonrpc_test_relay_context() -> (L7EndpointConfig, TunnelPolicyEngine, L7EvalContext) { jsonrpc_test_relay_context_with_path("/rpc") } @@ -3433,6 +4144,94 @@ network_policies: .unwrap(); } + #[tokio::test] + async fn l7_rest_exhausted_middleware_admission_returns_503_before_body_or_upstream() { + let (config, tunnel_engine, ctx) = middleware_relay_context("openshell/regex", "fail_open"); + let runner = tunnel_engine.middleware_runner().clone(); + + let mut active = Vec::new(); + for _ in 0..openshell_supervisor_middleware::MAX_CONCURRENT_MIDDLEWARE_WORK { + active.push( + runner + .reserve_middleware_work_admission() + .await + .expect("fill active middleware work"), + ); + } + let mut waiters = Vec::new(); + for _ in 0..openshell_supervisor_middleware::MAX_QUEUED_MIDDLEWARE_WORK { + let runner = runner.clone(); + waiters.push(Box::pin( + async move { runner.reserve_middleware_work().await }, + )); + } + for waiter in &mut waiters { + assert!( + futures::poll!(waiter.as_mut()).is_pending(), + "every bounded waiter slot must be occupied" + ); + } + + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_with_inspection( + &config, + tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + // The declared body is within the built-in regex HTTP capability, but + // the client intentionally withholds it behind Expect: 100-continue. + // Queue exhaustion must be answered before buffering begins. + app.write_all( + b"POST /v1/messages HTTP/1.1\r\nHost: api.example.test\r\nContent-Length: 32\r\nExpect: 100-continue\r\nConnection: close\r\n\r\n", + ) + .await + .expect("send headers without body"); + + tokio::time::timeout(std::time::Duration::from_secs(1), relay) + .await + .expect("relay should shed immediately") + .expect("join relay") + .expect("relay returns a complete HTTP response"); + + let mut response = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(1), + app.read_to_end(&mut response), + ) + .await + .expect("client should receive 503 without sending its body") + .expect("read client response"); + let response = String::from_utf8(response).expect("UTF-8 response"); + assert_middleware_unavailable_response(&response, "rest_api"); + + let mut upstream_bytes = Vec::new(); + tokio::time::timeout( + std::time::Duration::from_secs(1), + upstream.read_to_end(&mut upstream_bytes), + ) + .await + .expect("upstream side should close") + .expect("read upstream"); + assert!( + upstream_bytes.is_empty(), + "admission-exhausted request must not reach upstream" + ); + + drop(waiters); + drop(active); + runner + .reserve_middleware_work_admission() + .await + .expect("work capacity recovers after saturation fixture"); + } + #[tokio::test] async fn l7_rest_middleware_fail_closed_does_not_reach_upstream() { let (config, tunnel_engine, ctx) = @@ -4237,9 +5036,10 @@ network_policies: operation: openshell_core::proto::SupervisorMiddlewareOperation::HttpRequest as i32, phase: openshell_core::proto::SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: 8192, + max_payload_bytes: 8192, timeout: String::new(), }], + expected_audience: String::new(), } } @@ -4382,9 +5182,10 @@ network_policies: operation: openshell_core::proto::SupervisorMiddlewareOperation::HttpRequest as i32, phase: openshell_core::proto::SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: 8192, + max_payload_bytes: 8192, timeout: String::new(), }], + expected_audience: String::new(), } } @@ -4852,9 +5653,10 @@ network_policies: bindings: vec![MiddlewareBinding { operation: SupervisorMiddlewareOperation::HttpRequest as i32, phase: SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: self.max_body_bytes, + max_payload_bytes: self.max_body_bytes, timeout: String::new(), }], + expected_audience: String::new(), } } @@ -4969,6 +5771,9 @@ network_policies: MiddlewareApplyResult::Denied { .. } => { panic!("body within the largest stage limit must not fail the chain") } + MiddlewareApplyResult::AdmissionExhausted => { + panic!("test middleware work admission must be available") + } } } @@ -6084,6 +6889,106 @@ network_policies: .unwrap(); } + #[tokio::test] + async fn rest_websocket_middleware_inspects_compressed_wss_messages() { + let data = r#" +network_middlewares: + redact: + middleware: openshell/regex + on_error: fail_closed + endpoints: + include: ["api.example.test"] +network_policies: + rest_api: + name: rest_api + endpoints: + - host: api.example.test + port: 8080 + protocol: rest + enforcement: enforce + rules: + - allow: + method: GET + path: "/ws" + binaries: + - { path: /usr/bin/node } +"#; + let engine = OpaEngine::from_strings(TEST_POLICY, data).unwrap(); + install_builtin_middleware(&engine); + let input = NetworkInput { + host: "api.example.test".into(), + port: 8080, + binary_path: PathBuf::from("/usr/bin/node"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let (endpoint_config, generation) = engine + .query_endpoint_config_with_generation(&input) + .unwrap(); + let config = crate::l7::parse_l7_config(&endpoint_config.unwrap()).unwrap(); + let tunnel_engine = engine.clone_engine_for_tunnel(generation).unwrap(); + let ctx = L7EvalContext { + host: "api.example.test".into(), + port: 8080, + request_default_port: Some(8080), + policy_name: "rest_api".into(), + binary_path: "/usr/bin/node".into(), + ..Default::default() + }; + let (mut app, mut relay_client) = tokio::io::duplex(8192); + let (mut relay_upstream, mut upstream) = tokio::io::duplex(8192); + let relay = tokio::spawn(async move { + relay_rest( + &config, + &tunnel_engine, + &mut relay_client, + &mut relay_upstream, + &ctx, + ) + .await + }); + + let scenario = tokio::time::timeout(std::time::Duration::from_secs(60), async { + app.write_all( + b"GET /ws HTTP/1.1\r\nHost: api.example.test\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover\r\n\r\n", + ) + .await + .unwrap(); + + let upstream_headers = read_http_headers(&mut upstream).await; + let upstream_headers = String::from_utf8_lossy(&upstream_headers); + assert!(upstream_headers.contains( + "Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover\r\n" + )); + upstream + .write_all( + b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\nSec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover\r\n\r\n", + ) + .await + .unwrap(); + let response = read_http_headers(&mut app).await; + assert!(String::from_utf8_lossy(&response).contains("101 Switching Protocols")); + + app.write_all( + &crate::l7::websocket::compressed_masked_text_frame_for_test( + br#"{"token":"sk-1234567890abcdef"}"#, + ), + ) + .await + .unwrap(); + let frame = crate::l7::websocket::read_frame_for_test(&mut upstream).await; + assert_eq!( + crate::l7::websocket::decode_compressed_masked_text_frame_for_test(&frame), + r#"{"token":"[REDACTED]"}"# + ); + }) + .await; + relay.abort(); + let _ = relay.await; + scenario.expect("compressed WSS scenario should complete"); + } + #[tokio::test] async fn route_selected_websocket_upgrade_rejects_invalid_accept_without_forwarding_101() { let data = r#" @@ -6550,6 +7455,18 @@ network_policies: frame } + async fn read_http_headers(reader: &mut R) -> Vec { + let mut bytes = Vec::new(); + let mut byte = [0u8; 1]; + loop { + reader.read_exact(&mut byte).await.unwrap(); + bytes.push(byte[0]); + if bytes.ends_with(b"\r\n\r\n") { + return bytes; + } + } + } + async fn read_text_frame( reader: &mut R, ) -> std::io::Result<(bool, String)> { diff --git a/crates/openshell-supervisor-network/src/l7/rest.rs b/crates/openshell-supervisor-network/src/l7/rest.rs index 29377fdf85..f9aaaf18a9 100644 --- a/crates/openshell-supervisor-network/src/l7/rest.rs +++ b/crates/openshell-supervisor-network/src/l7/rest.rs @@ -45,7 +45,7 @@ async fn max_middleware_body_bytes() -> usize { }]) .await .expect("describe built-in middleware"); - chain[0].max_body_bytes() + chain[0].max_payload_bytes() } const RELAY_BUF_SIZE: usize = 8192; const HTTP_METHOD_PREFIXES: &[&[u8]] = &[ @@ -2187,6 +2187,12 @@ fn validate_websocket_upgrade_request(raw_header: &[u8]) -> Result { parse_websocket_upgrade_request(raw_header).map(|request| request.is_some()) } +pub(crate) fn websocket_requested_subprotocols(raw_header: &[u8]) -> Result> { + Ok(parse_websocket_upgrade_request(raw_header)? + .map(|request| request.subprotocols) + .unwrap_or_default()) +} + fn parse_websocket_upgrade_request(raw_header: &[u8]) -> Result> { let header_str = std::str::from_utf8(raw_header) .map_err(|_| miette!("HTTP headers contain invalid UTF-8"))?; @@ -2386,14 +2392,36 @@ pub(crate) async fn send_middleware_failure_response( send_forbidden_json(policy_name, body, client).await } +/// Send a platform-owned availability response when shared middleware work +/// admission is exhausted before the request body is buffered. +pub(crate) async fn send_middleware_unavailable_response( + req: &L7Request, + policy_name: &str, + client: &mut C, + redacted_target: Option<&str>, + context: Option>, +) -> Result<()> { + let body = middleware_failure_response_body(req, policy_name, redacted_target, context); + send_json_response(policy_name, body, client, "503 Service Unavailable").await +} + async fn send_forbidden_json( policy_name: &str, body: serde_json::Value, client: &mut C, +) -> Result<()> { + send_json_response(policy_name, body, client, "403 Forbidden").await +} + +async fn send_json_response( + policy_name: &str, + body: serde_json::Value, + client: &mut C, + status: &str, ) -> Result<()> { let body_bytes = body.to_string(); let response = format!( - "HTTP/1.1 403 Forbidden\r\n\ + "HTTP/1.1 {status}\r\n\ Content-Type: application/json\r\n\ Content-Length: {}\r\n\ X-OpenShell-Policy: {}\r\n\ @@ -2927,7 +2955,7 @@ where if !options.client_requested_upgrade { return Ok(RelayOutcome::Consumed); } - let websocket_permessage_deflate = validate_websocket_response( + let (websocket_permessage_deflate, websocket_subprotocol) = validate_websocket_response( &header_str, options.websocket_extensions, options.websocket.as_ref(), @@ -2946,6 +2974,7 @@ where return Ok(RelayOutcome::Upgraded { overflow, websocket_permessage_deflate, + websocket_subprotocol, }); } @@ -3075,9 +3104,10 @@ fn validate_websocket_response( headers: &str, mode: WebSocketExtensionMode, websocket: Option<&WebSocketResponseValidation>, -) -> Result { +) -> Result<(bool, Option)> { let Some(validation) = websocket else { - return validate_websocket_response_extensions_preserved(headers, mode); + return validate_websocket_response_extensions_preserved(headers, mode) + .map(|compressed| (compressed, None)); }; let mut upgrade_websocket = false; @@ -3137,11 +3167,11 @@ fn validate_websocket_response( "websocket upgrade response has multiple Sec-WebSocket-Protocol headers" )); } - if let Some(protocol) = selected_subprotocol + if let Some(ref protocol) = selected_subprotocol && !validation .offered_subprotocols .iter() - .any(|offered| offered == &protocol) + .any(|offered| offered == protocol) { return Err(miette!( "upstream selected WebSocket subprotocol that was not offered" @@ -3153,8 +3183,10 @@ fn validate_websocket_response( (None, Some(_)) => Err(miette!( "upstream negotiated WebSocket extension that was not offered" )), - (None | Some(_), None) => Ok(false), - (Some(expected), Some(actual)) if expected.eq_ignore_ascii_case(actual) => Ok(true), + (None | Some(_), None) => Ok((false, selected_subprotocol)), + (Some(expected), Some(actual)) if expected.eq_ignore_ascii_case(actual) => { + Ok((true, selected_subprotocol)) + } (Some(_), Some(_)) => Err(miette!( "upstream negotiated WebSocket extension that does not match the safe offer" )), @@ -3729,6 +3761,7 @@ mod tests { let RelayOutcome::Upgraded { overflow, websocket_permessage_deflate, + .. } = outcome else { panic!("expected upgraded relay outcome"); @@ -3742,6 +3775,7 @@ mod tests { 443, crate::l7::relay::UpgradeRelayOptions { websocket_request: true, + assembly_budget: Some(crate::l7::websocket::WebSocketAssemblyBudget::default()), websocket: crate::l7::relay::WebSocketUpgradeBehavior { credential_rewrite, permessage_deflate: websocket_permessage_deflate, @@ -4547,7 +4581,7 @@ mod tests { &mut client, &[], None, - Some(openshell_supervisor_middleware::MAX_MIDDLEWARE_BODY_BYTES), + Some(openshell_supervisor_middleware::MAX_MIDDLEWARE_PAYLOAD_BYTES), ) .await .expect("chunked body should decode"); @@ -4575,7 +4609,7 @@ mod tests { &req, &mut client, None, - openshell_supervisor_middleware::MAX_MIDDLEWARE_BODY_BYTES, + openshell_supervisor_middleware::MAX_MIDDLEWARE_PAYLOAD_BYTES, ) .await .expect("oversized body should produce a capacity result"); @@ -6309,7 +6343,7 @@ mod tests { offered_subprotocols: Vec::new(), }; - let negotiated = validate_websocket_response( + let (negotiated, subprotocol) = validate_websocket_response( "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\nSec-WebSocket-Extensions: permessage-deflate; server_no_context_takeover; client_no_context_takeover\r\n\r\n", WebSocketExtensionMode::PermessageDeflate, Some(&validation), @@ -6317,6 +6351,7 @@ mod tests { .expect("reordered safe extension params should canonicalize"); assert!(negotiated); + assert_eq!(subprotocol, None); } #[test] @@ -6339,7 +6374,7 @@ mod tests { #[test] fn preserve_mode_leaves_malformed_extension_response_raw() { - let negotiated = validate_websocket_response( + let (negotiated, subprotocol) = validate_websocket_response( "HTTP/1.1 101 Switching Protocols\r\nSec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover=\"true\"\r\n\r\n", WebSocketExtensionMode::Preserve, None, @@ -6347,6 +6382,7 @@ mod tests { .expect("preserve mode should not parse or reject raw extension negotiation"); assert!(!negotiated); + assert_eq!(subprotocol, None); } #[test] @@ -6370,7 +6406,7 @@ mod tests { offered_subprotocols: vec!["chat".to_string(), "superchat".to_string()], }; - let negotiated = validate_websocket_response( + let (negotiated, subprotocol) = validate_websocket_response( "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\nSec-WebSocket-Protocol: superchat\r\n\r\n", WebSocketExtensionMode::PermessageDeflate, Some(&validation), @@ -6378,6 +6414,7 @@ mod tests { .expect("offered subprotocol should validate"); assert!(!negotiated); + assert_eq!(subprotocol.as_deref(), Some("superchat")); } #[test] diff --git a/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs b/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs index 2ca25e6e81..ce6c581bc8 100644 --- a/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs +++ b/crates/openshell-supervisor-network/src/l7/token_grant_injection.rs @@ -419,6 +419,14 @@ pub mod test_support { self.resolver.clone() } + pub fn assert_no_requests(&self) { + let requests = self + .requests + .lock() + .expect("fake token grant requests lock poisoned"); + assert!(requests.is_empty(), "unexpected token grant requests"); + } + pub fn assert_one_request(&self, expected_provider_key: &str) { let requests = self .requests diff --git a/crates/openshell-supervisor-network/src/l7/websocket.rs b/crates/openshell-supervisor-network/src/l7/websocket.rs index cf7864e03f..7ba286b103 100644 --- a/crates/openshell-supervisor-network/src/l7/websocket.rs +++ b/crates/openshell-supervisor-network/src/l7/websocket.rs @@ -8,7 +8,7 @@ use crate::l7::relay::{L7EvalContext, evaluate_l7_request}; use crate::l7::{EnforcementMode, L7RequestInfo}; -use crate::opa::TunnelPolicyEngine; +use crate::opa::{PolicyGenerationGuard, TunnelPolicyEngine}; use flate2::{Compress, Compression, Decompress, FlushCompress, FlushDecompress, Status}; use miette::{IntoDiagnostic, Result, miette}; use openshell_core::provider_credentials::ProviderCredentialState; @@ -19,10 +19,19 @@ use openshell_ocsf::{ }; use std::collections::HashMap; use std::future::Future; +use std::sync::Arc; +use std::time::Duration as StdDuration; use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio::sync::{OwnedSemaphorePermit, Semaphore}; -const MAX_TEXT_MESSAGE_BYTES: usize = 1024 * 1024; +const MAX_TEXT_MESSAGE_BYTES: usize = openshell_supervisor_middleware::MAX_MIDDLEWARE_PAYLOAD_BYTES; +pub const MAX_CONCURRENT_WEBSOCKET_ASSEMBLIES: usize = 32; +pub const MAX_QUEUED_WEBSOCKET_ASSEMBLIES: usize = MAX_CONCURRENT_WEBSOCKET_ASSEMBLIES * 2; const MAX_RAW_FRAME_PAYLOAD_BYTES: u64 = 16 * 1024 * 1024; +const MAX_MESSAGE_FRAGMENTS: usize = 4096; +const TEXT_MESSAGE_ASSEMBLY_IDLE_TIMEOUT: StdDuration = StdDuration::from_secs(30); +const TEXT_MESSAGE_ASSEMBLY_TOTAL_TIMEOUT: StdDuration = StdDuration::from_secs(120); +const TEXT_MESSAGE_FORWARD_TOTAL_TIMEOUT: StdDuration = StdDuration::from_secs(120); const COPY_BUF_SIZE: usize = 8192; const OPCODE_CONTINUATION: u8 = 0x0; const OPCODE_TEXT: u8 = 0x1; @@ -32,6 +41,274 @@ const OPCODE_PING: u8 = 0x9; const OPCODE_PONG: u8 = 0xA; const CREDENTIAL_ENDPOINT_MISMATCH: &str = "websocket credential endpoint mismatch"; +#[derive(Clone, Debug)] +pub struct WebSocketAssemblyBudget { + active: Arc, + waiters: Arc, +} + +impl Default for WebSocketAssemblyBudget { + fn default() -> Self { + Self::new( + MAX_CONCURRENT_WEBSOCKET_ASSEMBLIES, + MAX_QUEUED_WEBSOCKET_ASSEMBLIES, + ) + } +} + +impl WebSocketAssemblyBudget { + pub fn new(active: usize, waiters: usize) -> Self { + Self { + active: Arc::new(Semaphore::new(active)), + waiters: Arc::new(Semaphore::new(waiters)), + } + } + + pub async fn reserve(&self) -> Result { + if let Ok(active) = Arc::clone(&self.active).try_acquire_owned() { + return Ok(WebSocketAssemblyAdmissionOutcome::Admitted( + WebSocketAssemblyAdmission { _active: active }, + )); + } + let Ok(waiter) = Arc::clone(&self.waiters).try_acquire_owned() else { + return Ok(WebSocketAssemblyAdmissionOutcome::QueueExhausted); + }; + let active = Arc::clone(&self.active) + .acquire_owned() + .await + .map_err(|_| miette!("websocket assembly admission semaphore closed"))?; + drop(waiter); + Ok(WebSocketAssemblyAdmissionOutcome::Admitted( + WebSocketAssemblyAdmission { _active: active }, + )) + } +} + +#[derive(Debug)] +pub struct WebSocketAssemblyAdmission { + _active: OwnedSemaphorePermit, +} + +#[derive(Debug)] +pub enum WebSocketAssemblyAdmissionOutcome { + Admitted(WebSocketAssemblyAdmission), + QueueExhausted, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum WebSocketTerminationCause { + PeerDisconnect, + PolicyReload, + CapacityExhausted, + MiddlewareDenial, + MiddlewareFailure, + PolicyDenial, + InvalidUtf8, + ProtocolError, + MessageTooBig, +} + +impl WebSocketTerminationCause { + fn close_code(self) -> Option { + match self { + Self::PeerDisconnect => None, + Self::PolicyReload => Some(1012), + Self::CapacityExhausted => Some(1013), + Self::MiddlewareDenial | Self::MiddlewareFailure | Self::PolicyDenial => Some(1008), + Self::InvalidUtf8 => Some(1007), + Self::ProtocolError => Some(1002), + Self::MessageTooBig => Some(1009), + } + } + + fn session_end_reason(self) -> openshell_core::proto::WebSocketSessionEndReason { + match self { + Self::PeerDisconnect => { + openshell_core::proto::WebSocketSessionEndReason::PeerDisconnect + } + Self::PolicyReload => openshell_core::proto::WebSocketSessionEndReason::PolicyReload, + Self::MiddlewareDenial => { + openshell_core::proto::WebSocketSessionEndReason::MiddlewareDenial + } + Self::PolicyDenial => openshell_core::proto::WebSocketSessionEndReason::PolicyDenial, + Self::CapacityExhausted | Self::MiddlewareFailure => { + openshell_core::proto::WebSocketSessionEndReason::MiddlewareFailure + } + Self::InvalidUtf8 | Self::ProtocolError | Self::MessageTooBig => { + openshell_core::proto::WebSocketSessionEndReason::ProtocolError + } + } + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum FrameFailureClass { + MessageAssemblyIdleTimeout, + MessageAssemblyTotalTimeout, + InvalidUtf8, + InvalidFragmentation, + InvalidCloseFrame, + InvalidControlFrame, + InvalidLength, + ReservedOpcode, + UnmaskedClientFrame, + RsvBits, + ProtocolError, +} + +impl FrameFailureClass { + fn as_str(self) -> &'static str { + match self { + Self::MessageAssemblyIdleTimeout => "message_assembly_idle_timeout", + Self::MessageAssemblyTotalTimeout => "message_assembly_total_timeout", + Self::InvalidUtf8 => "invalid_utf8", + Self::InvalidFragmentation => "invalid_fragmentation", + Self::InvalidCloseFrame => "invalid_close_frame", + Self::InvalidControlFrame => "invalid_control_frame", + Self::InvalidLength => "invalid_length", + Self::ReservedOpcode => "reserved_opcode", + Self::UnmaskedClientFrame => "unmasked_client_frame", + Self::RsvBits => "rsv_bits", + Self::ProtocolError => "protocol_error", + } + } +} + +#[derive(Debug)] +struct WebSocketTermination { + cause: WebSocketTerminationCause, + failure_class: Option, + error: miette::Report, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum AssemblyTimeoutKind { + Idle, + Total, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum FrameErrorKind { + PeerDisconnect, + Protocol(FrameFailureClass), + InvalidUtf8, + MessageTooBig, + AssemblyTimeout(AssemblyTimeoutKind), +} + +#[derive(Debug)] +struct FrameError { + kind: FrameErrorKind, + error: miette::Report, +} + +impl std::fmt::Display for FrameError { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + self.error.fmt(formatter) + } +} + +impl FrameError { + fn peer_io(context: &str, error: std::io::Error) -> Self { + Self { + kind: FrameErrorKind::PeerDisconnect, + error: miette!("{context}: {error}"), + } + } + + fn peer_disconnect(error: miette::Report) -> Self { + Self { + kind: FrameErrorKind::PeerDisconnect, + error, + } + } + + fn protocol(failure_class: FrameFailureClass, error: miette::Report) -> Self { + Self { + kind: FrameErrorKind::Protocol(failure_class), + error, + } + } + + fn invalid_utf8(error: miette::Report) -> Self { + Self { + kind: FrameErrorKind::InvalidUtf8, + error, + } + } + + fn message_too_big(error: miette::Report) -> Self { + Self { + kind: FrameErrorKind::MessageTooBig, + error, + } + } + + fn assembly_timeout(kind: AssemblyTimeoutKind) -> Self { + let error = match kind { + AssemblyTimeoutKind::Idle => { + miette!("websocket text message assembly idle timeout") + } + AssemblyTimeoutKind::Total => { + miette!("websocket text message assembly total timeout") + } + }; + Self { + kind: FrameErrorKind::AssemblyTimeout(kind), + error, + } + } +} + +impl From for WebSocketTermination { + fn from(frame_error: FrameError) -> Self { + let (cause, failure_class) = match frame_error.kind { + FrameErrorKind::PeerDisconnect => (WebSocketTerminationCause::PeerDisconnect, None), + FrameErrorKind::Protocol(failure_class) => ( + WebSocketTerminationCause::ProtocolError, + Some(failure_class), + ), + FrameErrorKind::InvalidUtf8 => ( + WebSocketTerminationCause::InvalidUtf8, + Some(FrameFailureClass::InvalidUtf8), + ), + FrameErrorKind::MessageTooBig => ( + WebSocketTerminationCause::MessageTooBig, + Some(FrameFailureClass::InvalidLength), + ), + FrameErrorKind::AssemblyTimeout(kind) => ( + WebSocketTerminationCause::ProtocolError, + Some(match kind { + AssemblyTimeoutKind::Idle => FrameFailureClass::MessageAssemblyIdleTimeout, + AssemblyTimeoutKind::Total => FrameFailureClass::MessageAssemblyTotalTimeout, + }), + ), + }; + Self { + cause, + failure_class, + error: frame_error.error, + } + } +} + +#[derive(Debug)] +enum WebSocketDecompressionError { + MessageTooBig(miette::Report), + Protocol(miette::Report), +} + +type WebSocketRelayResult = std::result::Result; +type FrameResult = std::result::Result; + +fn terminate(cause: WebSocketTerminationCause, error: miette::Report) -> WebSocketTermination { + WebSocketTermination { + cause, + failure_class: None, + error, + } +} + #[derive(Debug)] struct FrameHeader { fin: bool, @@ -46,8 +323,146 @@ struct FrameHeader { #[derive(Debug)] enum FragmentState { None, - Text { payload: Vec, compressed: bool }, - Binary, + Text(TextMessageAssembly), + Binary { + fragment_count: usize, + coverage: Vec, + }, +} + +/// One admitted client text message while its complete logical payload is +/// being assembled. +/// +/// Keeping the admission permit with the buffer and deadlines makes every +/// timeout and terminal parser error release shared middleware capacity through +/// ordinary ownership. The total deadline includes interleaved control frames; +/// the idle deadline resets only when a client read makes progress. +#[derive(Debug)] +struct TextMessageAssembly { + payload: Vec, + compressed: bool, + fragment_count: usize, + assembly_admission: WebSocketAssemblyAdmission, + admission: Option, + total_deadline: tokio::time::Instant, +} + +impl TextMessageAssembly { + fn new( + compressed: bool, + assembly_admission: WebSocketAssemblyAdmission, + admission: Option, + ) -> Self { + Self { + payload: Vec::new(), + compressed, + fragment_count: 1, + assembly_admission, + admission, + total_deadline: tokio::time::Instant::now() + TEXT_MESSAGE_ASSEMBLY_TOTAL_TIMEOUT, + } + } + + async fn read_some( + &self, + reader: &mut R, + buffer: &mut [u8], + ) -> FrameResult { + if buffer.is_empty() { + return Ok(0); + } + let idle_deadline = tokio::time::Instant::now() + TEXT_MESSAGE_ASSEMBLY_IDLE_TIMEOUT; + tokio::select! { + biased; + () = tokio::time::sleep_until(self.total_deadline) => { + Err(FrameError::assembly_timeout(AssemblyTimeoutKind::Total)) + } + () = tokio::time::sleep_until(idle_deadline) => { + Err(FrameError::assembly_timeout(AssemblyTimeoutKind::Idle)) + } + result = reader.read(buffer) => { + result.map_err(|error| FrameError::peer_io("websocket client read failed", error)) + }, + } + } + + async fn read_exact( + &self, + reader: &mut R, + buffer: &mut [u8], + ) -> FrameResult<()> { + let mut filled = 0; + while filled < buffer.len() { + let read = self.read_some(reader, &mut buffer[filled..]).await?; + if read == 0 { + return Err(FrameError::peer_disconnect(miette!( + "websocket payload ended before declared length" + ))); + } + filled += read; + } + Ok(()) + } + + async fn read_payload( + &mut self, + reader: &mut R, + frame: &FrameHeader, + ) -> FrameResult<()> { + let next = read_masked_payload(reader, frame, Some(self)).await?; + append_text_fragment(&mut self.payload, next) + } + + fn ensure_payload_fits(&self, frame: &FrameHeader) -> FrameResult<()> { + let frame_len = usize::try_from(frame.payload_len).map_err(|_| { + FrameError::message_too_big(miette!("websocket text frame is too large to buffer")) + })?; + let complete_len = self.payload.len().checked_add(frame_len).ok_or_else(|| { + FrameError::message_too_big(miette!("websocket text message length overflow")) + })?; + if complete_len > MAX_TEXT_MESSAGE_BYTES { + return Err(FrameError::message_too_big(miette!( + "websocket text message exceeds {MAX_TEXT_MESSAGE_BYTES} byte limit" + ))); + } + Ok(()) + } + + fn add_fragment(&mut self) -> FrameResult<()> { + self.fragment_count = self.fragment_count.saturating_add(1); + if self.fragment_count > MAX_MESSAGE_FRAGMENTS { + return Err(FrameError::protocol( + FrameFailureClass::InvalidFragmentation, + miette!("websocket message exceeds {MAX_MESSAGE_FRAGMENTS} fragment limit"), + )); + } + Ok(()) + } + + async fn within_total( + &self, + future: impl Future>, + ) -> FrameResult { + tokio::time::timeout_at(self.total_deadline, future) + .await + .map_err(|_| FrameError::assembly_timeout(AssemblyTimeoutKind::Total))? + } + + fn into_parts( + self, + ) -> ( + Vec, + bool, + WebSocketAssemblyAdmission, + Option, + ) { + ( + self.payload, + self.compressed, + self.assembly_admission, + self.admission, + ) + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -67,11 +482,15 @@ pub(super) struct InspectionOptions<'a> { pub(super) struct RelayOptions<'a> { pub(super) policy_name: &'a str, + pub(super) assembly_budget: WebSocketAssemblyBudget, pub(super) resolver: Option<&'a SecretResolver>, + pub(super) generation_guard: Option<&'a PolicyGenerationGuard>, pub(super) provider_credentials: Option<&'a ProviderCredentialState>, pub(super) target: &'a str, pub(super) inspector: Option>, pub(super) compression: WebSocketCompression, + pub(super) middleware_session: Option, + pub(super) middleware_context: Option<&'a L7EvalContext>, } /// Relay an upgraded WebSocket connection with optional client text inspection, @@ -82,7 +501,7 @@ pub(super) async fn relay_with_options( overflow: Vec, host: &str, port: u16, - options: RelayOptions<'_>, + mut options: RelayOptions<'_>, ) -> Result<()> where C: AsyncRead + AsyncWrite + Unpin + Send, @@ -96,30 +515,66 @@ where client_write.flush().await.into_diagnostic()?; } - let client_to_server = - relay_client_to_server(&mut client_read, &mut upstream_write, host, port, &options); + let client_to_server = relay_client_to_server( + &mut client_read, + &mut upstream_write, + host, + port, + &mut options, + ); let server_to_client = async { tokio::io::copy(&mut upstream_read, &mut client_write) .await - .into_diagnostic()?; - client_write.flush().await.into_diagnostic()?; - Ok::<(), miette::Report>(()) + .map_err(|error| { + terminate( + WebSocketTerminationCause::PeerDisconnect, + miette!("websocket upstream relay ended: {error}"), + ) + })?; + client_write.flush().await.map_err(|error| { + terminate( + WebSocketTerminationCause::PeerDisconnect, + miette!("websocket client relay ended: {error}"), + ) + })?; + Ok::<_, WebSocketTermination>( + openshell_core::proto::WebSocketSessionEndReason::PeerDisconnect, + ) }; let result = tokio::select! { result = client_to_server => result, result = server_to_client => result, }; - if result - .as_ref() - .is_err_and(|error| error.to_string().contains(CREDENTIAL_ENDPOINT_MISMATCH)) - { - emit_credential_endpoint_mismatch(host, port, options.policy_name); - write_policy_violation_close(&mut client_write).await?; + if let Err(termination) = &result { + observe_termination(host, port, options.policy_name, termination); + } + if let Err(termination) = &result { + let error = termination.error.to_string(); + if error.contains(CREDENTIAL_ENDPOINT_MISMATCH) { + emit_credential_endpoint_mismatch(host, port, options.policy_name); + let _ = write_policy_violation_close(&mut client_write).await; + } else if error.contains("credential") { + if let Some(code) = termination.cause.close_code() { + let payload = code.to_be_bytes(); + let _ = write_unmasked_close(&mut client_write, &payload).await; + } + } else if let Some(code) = termination.cause.close_code() { + let payload = code.to_be_bytes(); + let _ = write_masked_close(&mut upstream_write, &payload).await; + let _ = write_unmasked_close(&mut client_write, &payload).await; + } + } + if let Some(session) = options.middleware_session.take() { + let reason = match &result { + Ok(reason) => *reason, + Err(termination) => termination.cause.session_end_reason(), + }; + session.end(reason).await; } let _ = upstream_write.shutdown().await; let _ = client_write.shutdown().await; - result + result.map(|_| ()).map_err(|termination| termination.error) } async fn write_policy_violation_close(writer: &mut W) -> Result<()> { @@ -162,166 +617,242 @@ async fn relay_client_to_server( writer: &mut W, host: &str, port: u16, - options: &RelayOptions<'_>, -) -> Result<()> + options: &mut RelayOptions<'_>, +) -> WebSocketRelayResult where R: AsyncRead + Unpin, W: AsyncWrite + Unpin, { let mut fragments = FragmentState::None; let mut close_seen = false; - loop { - let Some(frame) = read_frame_header(reader).await.inspect_err(|e| { - emit_protocol_failure(host, port, options.policy_name, protocol_failure_class(e)); - })? + let assembly = match &fragments { + FragmentState::Text(assembly) => Some(assembly), + FragmentState::None | FragmentState::Binary { .. } => None, + }; + let Some(frame) = read_frame_header(reader, assembly) + .await + .map_err(WebSocketTermination::from)? else { - writer.shutdown().await.into_diagnostic()?; - return Ok(()); + let _ = writer.shutdown().await; + return Ok(if close_seen { + openshell_core::proto::WebSocketSessionEndReason::NormalClose + } else { + openshell_core::proto::WebSocketSessionEndReason::PeerDisconnect + }); }; if close_seen { - let e = miette!("websocket frame received after close frame"); - emit_protocol_failure(host, port, options.policy_name, protocol_failure_class(&e)); - return Err(e); + return Err(FrameError::protocol( + FrameFailureClass::InvalidCloseFrame, + miette!("websocket frame received after close frame"), + ) + .into()); } - if let Err(e) = validate_frame_header(&frame, &fragments, options.compression) { - emit_protocol_failure(host, port, options.policy_name, protocol_failure_class(&e)); - return Err(e); + validate_frame_header(&frame, &fragments, options.compression) + .map_err(WebSocketTermination::from)?; + + if matches!( + frame.opcode, + OPCODE_TEXT | OPCODE_BINARY | OPCODE_CONTINUATION + ) { + ensure_generation_current(host, port, options)?; } match frame.opcode { OPCODE_TEXT => { - let payload = read_masked_payload(reader, &frame).await.inspect_err(|e| { - emit_protocol_failure( - host, - port, - options.policy_name, - protocol_failure_class(e), - ); - })?; + if frame.payload_len > MAX_TEXT_MESSAGE_BYTES as u64 { + return Err(FrameError::message_too_big(miette!( + "websocket text message exceeds {MAX_TEXT_MESSAGE_BYTES} byte limit" + )) + .into()); + } + let assembly_outcome = + options.assembly_budget.reserve().await.map_err(|error| { + terminate(WebSocketTerminationCause::CapacityExhausted, error) + })?; + let assembly_admission = match assembly_outcome { + WebSocketAssemblyAdmissionOutcome::Admitted(admission) => admission, + WebSocketAssemblyAdmissionOutcome::QueueExhausted => { + return Err(terminate( + WebSocketTerminationCause::CapacityExhausted, + miette!( + "websocket assembly admission queue is full; refusing additional buffered work" + ), + )); + } + }; + ensure_generation_current(host, port, options)?; + let admission = if let Some(session) = options.middleware_session.as_mut() { + let message_admission = session.admit_message().await.map_err(|error| { + terminate(WebSocketTerminationCause::MiddlewareFailure, error) + })?; + match message_admission { + openshell_supervisor_middleware::WebSocketMessageAdmission::Bypass => { + options.middleware_session.take(); + None + } + openshell_supervisor_middleware::WebSocketMessageAdmission::Inspect( + admission, + ) => Some(admission), + } + } else { + None + }; + ensure_generation_current(host, port, options)?; let compressed = frame.rsv == 0x40; + let mut assembly = + TextMessageAssembly::new(compressed, assembly_admission, admission); + assembly + .read_payload(reader, &frame) + .await + .map_err(WebSocketTermination::from)?; + ensure_generation_current(host, port, options)?; if frame.fin { + let (payload, compressed, assembly_admission, admission) = + assembly.into_parts(); relay_text_payload( - writer, &frame, payload, false, compressed, host, port, options, - ) - .await - .inspect_err(|e| { - emit_protocol_failure( - host, - port, - options.policy_name, - protocol_failure_class(e), - ); - })?; - } else { - fragments = FragmentState::Text { + writer, + &frame, payload, + assembly_admission, + admission, + false, compressed, - }; + host, + port, + options, + ) + .await?; + } else { + fragments = FragmentState::Text(assembly); } } - OPCODE_CONTINUATION => match &mut fragments { - FragmentState::Text { - payload, - compressed, - } => { - let next = read_masked_payload(reader, &frame).await.inspect_err(|e| { - emit_protocol_failure( - host, - port, - options.policy_name, - protocol_failure_class(e), - ); - })?; - if let Err(e) = append_text_fragment(payload, next) { - emit_protocol_failure( - host, - port, - options.policy_name, - protocol_failure_class(&e), - ); - return Err(e); + OPCODE_CONTINUATION => { + if let FragmentState::Text(assembly) = &mut fragments { + assembly + .add_fragment() + .map_err(WebSocketTermination::from)?; + if frame.payload_len > MAX_TEXT_MESSAGE_BYTES as u64 { + return Err(FrameError::message_too_big(miette!( + "websocket text message exceeds {MAX_TEXT_MESSAGE_BYTES} byte limit" + )) + .into()); } + assembly + .ensure_payload_fits(&frame) + .map_err(WebSocketTermination::from)?; + assembly + .read_payload(reader, &frame) + .await + .map_err(WebSocketTermination::from)?; + ensure_generation_current(host, port, options)?; if frame.fin { - let complete = std::mem::take(payload); - let was_compressed = *compressed; - fragments = FragmentState::None; + let FragmentState::Text(assembly) = + std::mem::replace(&mut fragments, FragmentState::None) + else { + unreachable!("validated text continuation state") + }; + let (complete, was_compressed, assembly_admission, admission) = + assembly.into_parts(); relay_text_payload( writer, &frame, complete, + assembly_admission, + admission, true, was_compressed, host, port, options, ) - .await - .inspect_err(|e| { - emit_protocol_failure( - host, - port, - options.policy_name, - protocol_failure_class(e), - ); - })?; + .await?; + } + } else if let FragmentState::Binary { + fragment_count, + coverage, + } = &mut fragments + { + *fragment_count = fragment_count.saturating_add(1); + if *fragment_count > MAX_MESSAGE_FRAGMENTS { + return Err(FrameError::protocol( + FrameFailureClass::InvalidFragmentation, + miette!( + "websocket message exceeds {MAX_MESSAGE_FRAGMENTS} fragment limit" + ), + ) + .into()); } - } - FragmentState::Binary => { copy_raw_frame_payload(reader, writer, &frame) .await - .inspect_err(|e| { - emit_protocol_failure( - host, - port, - options.policy_name, - protocol_failure_class(e), - ); - })?; + .map_err(WebSocketTermination::from)?; + let fragment_size = usize::try_from(frame.payload_len).unwrap_or(usize::MAX); + for record in coverage.iter_mut() { + record.original_size = record.original_size.saturating_add(fragment_size); + } if frame.fin { - fragments = FragmentState::None; + let FragmentState::Binary { coverage, .. } = + std::mem::replace(&mut fragments, FragmentState::None) + else { + unreachable!("validated binary continuation state") + }; + if let Some(ctx) = options.middleware_context { + crate::l7::middleware::emit_websocket_coverage(ctx, &coverage); + } } + } else { + return Err(FrameError::protocol( + FrameFailureClass::InvalidFragmentation, + miette!("websocket continuation frame without active fragmented message"), + ) + .into()); } - FragmentState::None => { - let e = - miette!("websocket continuation frame without active fragmented message"); - emit_protocol_failure( - host, - port, - options.policy_name, - protocol_failure_class(&e), - ); - return Err(e); - } - }, + } OPCODE_BINARY => { - if !frame.fin { - fragments = FragmentState::Binary; - } + let initial_size = usize::try_from(frame.payload_len).unwrap_or(usize::MAX); + let coverage = options + .middleware_session + .as_mut() + .map(|session| { + session.observe_unsupported_message( + openshell_supervisor_middleware::WebSocketMessageType::Binary, + initial_size, + ) + }) + .unwrap_or_default(); copy_raw_frame_payload(reader, writer, &frame) .await - .inspect_err(|e| { - emit_protocol_failure( - host, - port, - options.policy_name, - protocol_failure_class(e), - ); - })?; + .map_err(WebSocketTermination::from)?; + if frame.fin + && let Some(ctx) = options.middleware_context + { + crate::l7::middleware::emit_websocket_coverage(ctx, &coverage); + } else if !frame.fin { + fragments = FragmentState::Binary { + fragment_count: 1, + coverage, + }; + } } OPCODE_CLOSE | OPCODE_PING | OPCODE_PONG => { - relay_control_frame(reader, writer, &frame) - .await - .inspect_err(|e| { - emit_protocol_failure( - host, - port, - options.policy_name, - protocol_failure_class(e), - ); - })?; + let control_result = match &fragments { + FragmentState::Text(assembly) => { + assembly + .within_total(relay_control_frame( + reader, + writer, + &frame, + Some(assembly), + )) + .await + } + FragmentState::None | FragmentState::Binary { .. } => { + relay_control_frame(reader, writer, &frame, None).await + } + }; + control_result.map_err(WebSocketTermination::from)?; if frame.opcode == OPCODE_CLOSE { close_seen = true; } @@ -331,25 +862,41 @@ where } } -async fn read_frame_header(reader: &mut R) -> Result> { - let first = match reader.read_u8().await { - Ok(byte) => byte, - Err(e) - if matches!( - e.kind(), - std::io::ErrorKind::UnexpectedEof - | std::io::ErrorKind::ConnectionReset - | std::io::ErrorKind::BrokenPipe - ) => - { - return Ok(None); - } - Err(e) => return Err(miette!("{e}")), +async fn read_exact_for_assembly( + reader: &mut R, + buffer: &mut [u8], + assembly: Option<&TextMessageAssembly>, +) -> FrameResult<()> { + match assembly { + Some(assembly) => assembly.read_exact(reader, buffer).await, + None => reader + .read_exact(buffer) + .await + .map(|_| ()) + .map_err(|error| FrameError::peer_io("websocket client read failed", error)), + } +} + +async fn read_frame_header( + reader: &mut R, + assembly: Option<&TextMessageAssembly>, +) -> FrameResult> { + let mut first = [0u8; 1]; + let first_read = match assembly { + Some(assembly) => assembly.read_some(reader, &mut first).await, + None => reader + .read(&mut first) + .await + .map_err(|error| FrameError::peer_io("websocket client read failed", error)), }; - let second = reader - .read_u8() - .await - .map_err(|e| miette!("malformed websocket frame header: {e}"))?; + let first = match first_read { + Ok(0) => return Ok(None), + Ok(_) => first[0], + Err(error) => return Err(error), + }; + let mut second = [0u8; 1]; + read_exact_for_assembly(reader, &mut second, assembly).await?; + let second = second[0]; let mut raw_header = vec![first, second]; let len_code = second & 0x7F; @@ -357,33 +904,32 @@ async fn read_frame_header(reader: &mut R) -> Result u64::from(len_code), 126 => { let mut bytes = [0u8; 2]; - reader - .read_exact(&mut bytes) - .await - .map_err(|e| miette!("malformed websocket extended length: {e}"))?; + read_exact_for_assembly(reader, &mut bytes, assembly).await?; raw_header.extend_from_slice(&bytes); let len = u64::from(u16::from_be_bytes(bytes)); if len < 126 { - return Err(miette!( - "websocket frame uses non-minimal 16-bit extended length" + return Err(FrameError::protocol( + FrameFailureClass::InvalidLength, + miette!("websocket frame uses non-minimal 16-bit extended length"), )); } len } 127 => { let mut bytes = [0u8; 8]; - reader - .read_exact(&mut bytes) - .await - .map_err(|e| miette!("malformed websocket extended length: {e}"))?; + read_exact_for_assembly(reader, &mut bytes, assembly).await?; if bytes[0] & 0x80 != 0 { - return Err(miette!("websocket frame uses non-canonical 64-bit length")); + return Err(FrameError::protocol( + FrameFailureClass::InvalidLength, + miette!("websocket frame uses non-canonical 64-bit length"), + )); } raw_header.extend_from_slice(&bytes); let len = u64::from_be_bytes(bytes); if u16::try_from(len).is_ok() { - return Err(miette!( - "websocket frame uses non-minimal 64-bit extended length" + return Err(FrameError::protocol( + FrameFailureClass::InvalidLength, + miette!("websocket frame uses non-minimal 64-bit extended length"), )); } len @@ -394,10 +940,7 @@ async fn read_frame_header(reader: &mut R) -> Result Result<()> { +) -> FrameResult<()> { if !valid_rsv_bits(frame, fragments, compression) { - return Err(miette!( - "websocket frame has unsupported RSV bits or extension state" + return Err(FrameError::protocol( + FrameFailureClass::RsvBits, + miette!("websocket frame has unsupported RSV bits or extension state"), )); } if !frame.masked { - return Err(miette!("websocket client frame is not masked")); + return Err(FrameError::protocol( + FrameFailureClass::UnmaskedClientFrame, + miette!("websocket client frame is not masked"), + )); } if !matches!( frame.opcode, @@ -437,34 +984,49 @@ fn validate_frame_header( | OPCODE_PING | OPCODE_PONG ) { - return Err(miette!("websocket frame uses reserved opcode")); + return Err(FrameError::protocol( + FrameFailureClass::ReservedOpcode, + miette!("websocket frame uses reserved opcode"), + )); } if matches!(frame.opcode, OPCODE_CLOSE | OPCODE_PING | OPCODE_PONG) { if !frame.fin { - return Err(miette!("websocket control frame is fragmented")); + return Err(FrameError::protocol( + FrameFailureClass::InvalidControlFrame, + miette!("websocket control frame is fragmented"), + )); } if frame.payload_len > 125 { - return Err(miette!("websocket control frame exceeds 125 bytes")); + return Err(FrameError::protocol( + FrameFailureClass::InvalidControlFrame, + miette!("websocket control frame exceeds 125 bytes"), + )); } } if matches!(frame.opcode, OPCODE_TEXT | OPCODE_BINARY) && !matches!(fragments, FragmentState::None) { - return Err(miette!( - "websocket data frame started before previous fragmented message completed" + return Err(FrameError::protocol( + FrameFailureClass::InvalidFragmentation, + miette!("websocket data frame started before previous fragmented message completed"), )); } if matches!(frame.opcode, OPCODE_CONTINUATION) && matches!(fragments, FragmentState::None) { - return Err(miette!( - "websocket continuation frame without active fragmented message" + return Err(FrameError::protocol( + FrameFailureClass::InvalidFragmentation, + miette!("websocket continuation frame without active fragmented message"), )); } if (frame.opcode == OPCODE_BINARY - || (frame.opcode == OPCODE_CONTINUATION && matches!(fragments, FragmentState::Binary))) + || (frame.opcode == OPCODE_CONTINUATION + && matches!(fragments, FragmentState::Binary { .. }))) && frame.payload_len > MAX_RAW_FRAME_PAYLOAD_BYTES { - return Err(miette!( - "websocket binary frame exceeds {MAX_RAW_FRAME_PAYLOAD_BYTES} byte relay limit" + return Err(FrameError::protocol( + FrameFailureClass::InvalidLength, + miette!( + "websocket binary frame exceeds {MAX_RAW_FRAME_PAYLOAD_BYTES} byte relay limit" + ), )); } Ok(()) @@ -487,55 +1049,83 @@ fn valid_rsv_bits( async fn read_masked_payload( reader: &mut R, frame: &FrameHeader, -) -> Result> { - let payload_len = usize::try_from(frame.payload_len) - .map_err(|_| miette!("websocket text frame is too large to buffer"))?; + assembly: Option<&TextMessageAssembly>, +) -> FrameResult> { + let payload_len = usize::try_from(frame.payload_len).map_err(|_| { + FrameError::message_too_big(miette!("websocket text frame is too large to buffer")) + })?; if payload_len > MAX_TEXT_MESSAGE_BYTES { - return Err(miette!( + return Err(FrameError::message_too_big(miette!( "websocket text message exceeds {MAX_TEXT_MESSAGE_BYTES} byte limit" - )); + ))); } let mut payload = vec![0u8; payload_len]; - reader - .read_exact(&mut payload) - .await - .map_err(|e| miette!("malformed websocket payload: {e}"))?; - let mask_key = frame - .mask_key - .ok_or_else(|| miette!("websocket client frame is not masked"))?; + read_exact_for_assembly(reader, &mut payload, assembly).await?; + let mask_key = frame.mask_key.ok_or_else(|| { + FrameError::protocol( + FrameFailureClass::UnmaskedClientFrame, + miette!("websocket client frame is not masked"), + ) + })?; apply_mask(&mut payload, mask_key); Ok(payload) } -fn append_text_fragment(buffer: &mut Vec, next: Vec) -> Result<()> { - let new_len = buffer - .len() - .checked_add(next.len()) - .ok_or_else(|| miette!("websocket text message length overflow"))?; +fn append_text_fragment(buffer: &mut Vec, next: Vec) -> FrameResult<()> { + let new_len = buffer.len().checked_add(next.len()).ok_or_else(|| { + FrameError::message_too_big(miette!("websocket text message length overflow")) + })?; if new_len > MAX_TEXT_MESSAGE_BYTES { - return Err(miette!( + return Err(FrameError::message_too_big(miette!( "websocket text message exceeds {MAX_TEXT_MESSAGE_BYTES} byte limit" - )); + ))); } buffer.extend_from_slice(&next); Ok(()) } -#[allow(clippy::too_many_arguments)] -async fn relay_text_payload( - writer: &mut W, - frame: &FrameHeader, - payload: Vec, - force_reframe: bool, - compressed: bool, +fn ensure_generation_current( host: &str, port: u16, options: &RelayOptions<'_>, -) -> Result<()> { +) -> WebSocketRelayResult<()> { + ensure_generation_guard_current(host, port, options.policy_name, options.generation_guard) +} + +fn ensure_generation_guard_current( + host: &str, + port: u16, + policy_name: &str, + generation_guard: Option<&PolicyGenerationGuard>, +) -> WebSocketRelayResult<()> { + let Some(guard) = generation_guard else { + return Ok(()); + }; + guard.ensure_current().map_err(|error| { + crate::l7::relay::emit_policy_reload(guard, host, port, policy_name); + terminate(WebSocketTerminationCause::PolicyReload, error) + }) +} + +#[allow(clippy::too_many_arguments)] +async fn relay_text_payload( + writer: &mut W, + frame: &FrameHeader, + payload: Vec, + assembly_admission: WebSocketAssemblyAdmission, + admission: Option, + force_reframe: bool, + compressed: bool, + host: &str, + port: u16, + options: &mut RelayOptions<'_>, +) -> WebSocketRelayResult<()> { relay_text_payload_with_before_credential_write( writer, frame, payload, + assembly_admission, + admission, force_reframe, compressed, host, @@ -551,24 +1141,88 @@ async fn relay_text_payload_with_before_credential_write( writer: &mut W, frame: &FrameHeader, payload: Vec, + _assembly_admission: WebSocketAssemblyAdmission, + admission: Option, force_reframe: bool, compressed: bool, host: &str, port: u16, - options: &RelayOptions<'_>, + options: &mut RelayOptions<'_>, before_credential_write: F, -) -> Result<()> +) -> WebSocketRelayResult<()> where W: AsyncWrite + Unpin, F: Future, { + ensure_generation_current(host, port, options)?; let message_payload = if compressed { - decompress_permessage_deflate(&payload)? + decompress_permessage_deflate(&payload).map_err(|error| match error { + WebSocketDecompressionError::MessageTooBig(error) => { + WebSocketTermination::from(FrameError::message_too_big(error)) + } + WebSocketDecompressionError::Protocol(error) => WebSocketTermination::from( + FrameError::protocol(FrameFailureClass::ProtocolError, error), + ), + })? } else { payload }; - let mut text = String::from_utf8(message_payload) - .map_err(|_| miette!("websocket text message is not valid UTF-8"))?; + let mut text = String::from_utf8(message_payload).map_err(|_| { + WebSocketTermination::from(FrameError::invalid_utf8(miette!( + "websocket text message is not valid UTF-8" + ))) + })?; + + // Built-in transport/GraphQL inspection sees the original unresolved + // message. External transformations run next, then policy is re-evaluated + // before credential material is introduced. + if let Some(inspector) = options.inspector.as_ref() { + inspect_websocket_text_message(host, port, options.policy_name, inspector, &text)?; + } + ensure_generation_current(host, port, options)?; + + let mut middleware_transformed = false; + if let Some(session) = options.middleware_session.as_mut() { + let admission = admission.ok_or_else(|| { + terminate( + WebSocketTerminationCause::MiddlewareFailure, + miette!("websocket middleware message missing work admission"), + ) + })?; + let outcome = session.evaluate_text_admitted(text, admission).await; + ensure_generation_current(host, port, options)?; + if let Some(ctx) = options.middleware_context { + crate::l7::middleware::emit_websocket_message_events(ctx, &outcome); + } + if !outcome.allowed { + if outcome.platform_oversize { + return Err(FrameError::message_too_big(miette!( + "websocket message over middleware platform capacity" + )) + .into()); + } + let cause = if outcome.denial.is_some() { + WebSocketTerminationCause::MiddlewareDenial + } else { + WebSocketTerminationCause::MiddlewareFailure + }; + return Err(terminate( + cause, + miette!("websocket middleware denied message: {}", outcome.reason), + )); + } + middleware_transformed = outcome + .invocations + .iter() + .any(|invocation| invocation.transformed); + text = outcome.payload; + } + + if middleware_transformed && let Some(inspector) = options.inspector.as_ref() { + inspect_websocket_text_message(host, port, options.policy_name, inspector, &text)?; + } + ensure_generation_current(host, port, options)?; + let live_resolver = options.provider_credentials.map(|credentials| { let (resolver, revision) = credentials.resolver_for_endpoint_with_revision(host, port, options.target); @@ -585,54 +1239,88 @@ where .rewrite_websocket_text_placeholders(&mut text) .map_err(|error| { if error.is_endpoint_mismatch() { - miette!(CREDENTIAL_ENDPOINT_MISMATCH) + terminate( + WebSocketTerminationCause::PolicyDenial, + miette!(CREDENTIAL_ENDPOINT_MISMATCH), + ) } else { - miette!("websocket credential placeholder resolution failed") + terminate( + WebSocketTerminationCause::MiddlewareFailure, + miette!("websocket credential placeholder resolution failed"), + ) } })? } else if contains_reserved_credential_marker(&text) { - return Err(miette!( - "websocket credential placeholder resolution failed" + return Err(terminate( + WebSocketTerminationCause::MiddlewareFailure, + miette!("websocket credential placeholder resolution failed"), )); } else { 0 }; + ensure_generation_current(host, port, options)?; - if let Some(inspector) = options.inspector.as_ref() { - inspect_websocket_text_message(host, port, options.policy_name, inspector, &text)?; - } - - if replacements == 0 && !force_reframe && !compressed { - writer - .write_all(&frame.raw_header) - .await - .into_diagnostic()?; + if replacements == 0 && !middleware_transformed && !force_reframe && !compressed { let mut payload = text.into_bytes(); - let mask_key = frame - .mask_key - .ok_or_else(|| miette!("websocket client frame is not masked"))?; + let mask_key = frame.mask_key.ok_or_else(|| { + WebSocketTermination::from(FrameError::protocol( + FrameFailureClass::UnmaskedClientFrame, + miette!("websocket client frame is not masked"), + )) + })?; apply_mask(&mut payload, mask_key); - writer.write_all(&payload).await.into_diagnostic()?; - writer.flush().await.into_diagnostic()?; - return Ok(()); + return write_text_frame_guarded( + writer, + &frame.raw_header, + &payload, + host, + port, + options.policy_name, + options.generation_guard, + ) + .await; } if replacements > 0 { emit_rewrite_event(host, port, options.policy_name, replacements); } - let (rsv, frame_payload) = if compressed { - (0x40, compress_permessage_deflate(text.as_bytes())?) - } else { - (0, text.into_bytes()) - }; - let rewritten_frame = masked_frame_bytes(OPCODE_TEXT, rsv, &frame_payload); if replacements > 0 { before_credential_write.await; if let Some((_, guard)) = live_resolver { - guard.ensure_current()?; + guard + .ensure_current() + .map_err(|error| terminate(WebSocketTerminationCause::PolicyDenial, error))?; } + ensure_generation_current(host, port, options)?; + } + if compressed { + let compressed_payload = compress_permessage_deflate(text.as_bytes()).map_err(|error| { + WebSocketTermination::from(FrameError::protocol( + FrameFailureClass::ProtocolError, + error, + )) + })?; + return write_masked_text_frame_guarded( + writer, + 0x40, + &compressed_payload, + host, + port, + options.policy_name, + options.generation_guard, + ) + .await; } - write_frame_bytes(writer, &rewritten_frame).await + write_masked_text_frame_guarded( + writer, + 0, + text.as_bytes(), + host, + port, + options.policy_name, + options.generation_guard, + ) + .await } fn inspect_websocket_text_message( @@ -641,7 +1329,7 @@ fn inspect_websocket_text_message( policy_name: &str, inspector: &InspectionOptions<'_>, text: &str, -) -> Result<()> { +) -> WebSocketRelayResult<()> { if inspector.graphql_policy { return inspect_graphql_websocket_message(host, port, policy_name, inspector, text); } @@ -653,7 +1341,8 @@ fn inspect_websocket_text_message( graphql: None, jsonrpc: None, }; - let (allowed, reason) = evaluate_l7_request(inspector.engine, inspector.ctx, &request_info)?; + let (allowed, reason) = evaluate_l7_request(inspector.engine, inspector.ctx, &request_info) + .map_err(|error| terminate(WebSocketTerminationCause::PolicyReload, error))?; let decision = match (allowed, inspector.enforcement) { (true, _) => "allow", (false, EnforcementMode::Audit) => "audit", @@ -669,7 +1358,10 @@ fn inspect_websocket_text_message( None, ); if !allowed && inspector.enforcement == EnforcementMode::Enforce { - return Err(miette!("websocket text message denied by policy")); + return Err(terminate( + WebSocketTerminationCause::PolicyDenial, + miette!("websocket text message denied by policy"), + )); } Ok(()) } @@ -680,7 +1372,7 @@ fn inspect_graphql_websocket_message( policy_name: &str, inspector: &InspectionOptions<'_>, text: &str, -) -> Result<()> { +) -> WebSocketRelayResult<()> { match classify_graphql_websocket_message(text) { GraphqlWebSocketMessage::Control { message_type } => { let request_info = L7RequestInfo { @@ -720,7 +1412,8 @@ fn inspect_graphql_websocket_message( let (allowed, reason) = if let Some(reason) = parse_error_reason { (false, reason) } else { - evaluate_l7_request(inspector.engine, inspector.ctx, &request_info)? + evaluate_l7_request(inspector.engine, inspector.ctx, &request_info) + .map_err(|error| terminate(WebSocketTerminationCause::PolicyReload, error))? }; let decision = match (allowed, inspector.enforcement) { (_, _) if force_deny => "deny", @@ -739,7 +1432,10 @@ fn inspect_graphql_websocket_message( Some(&graphql), ); if (!allowed && inspector.enforcement == EnforcementMode::Enforce) || force_deny { - return Err(miette!("websocket GraphQL message denied by policy")); + return Err(terminate( + WebSocketTerminationCause::PolicyDenial, + miette!("websocket GraphQL message denied by policy"), + )); } Ok(()) } @@ -834,24 +1530,29 @@ async fn relay_control_frame( reader: &mut R, writer: &mut W, frame: &FrameHeader, -) -> Result<()> + assembly: Option<&TextMessageAssembly>, +) -> FrameResult<()> where R: AsyncRead + Unpin, W: AsyncWrite + Unpin, { - let raw_payload_len = usize::try_from(frame.payload_len) - .map_err(|_| miette!("websocket control frame payload length overflow"))?; + let raw_payload_len = usize::try_from(frame.payload_len).map_err(|_| { + FrameError::protocol( + FrameFailureClass::InvalidControlFrame, + miette!("websocket control frame payload length overflow"), + ) + })?; let mut raw_payload = vec![0u8; raw_payload_len]; - reader - .read_exact(&mut raw_payload) - .await - .map_err(|e| miette!("malformed websocket control payload: {e}"))?; + read_exact_for_assembly(reader, &mut raw_payload, assembly).await?; if frame.opcode == OPCODE_CLOSE { let mut payload = raw_payload.clone(); - let mask_key = frame - .mask_key - .ok_or_else(|| miette!("websocket client frame is not masked"))?; + let mask_key = frame.mask_key.ok_or_else(|| { + FrameError::protocol( + FrameFailureClass::UnmaskedClientFrame, + miette!("websocket client frame is not masked"), + ) + })?; apply_mask(&mut payload, mask_key); validate_close_payload(&payload)?; } @@ -859,16 +1560,23 @@ where writer .write_all(&frame.raw_header) .await - .into_diagnostic()?; - writer.write_all(&raw_payload).await.into_diagnostic()?; - writer.flush().await.into_diagnostic()?; + .map_err(|error| FrameError::peer_io("websocket upstream write failed", error))?; + writer + .write_all(&raw_payload) + .await + .map_err(|error| FrameError::peer_io("websocket upstream write failed", error))?; + writer + .flush() + .await + .map_err(|error| FrameError::peer_io("websocket upstream flush failed", error))?; Ok(()) } -fn validate_close_payload(payload: &[u8]) -> Result<()> { +fn validate_close_payload(payload: &[u8]) -> FrameResult<()> { if payload.len() == 1 { - return Err(miette!( - "websocket close frame payload cannot be exactly one byte" + return Err(FrameError::protocol( + FrameFailureClass::InvalidCloseFrame, + miette!("websocket close frame payload cannot be exactly one byte"), )); } if payload.len() < 2 { @@ -877,10 +1585,15 @@ fn validate_close_payload(payload: &[u8]) -> Result<()> { let code = u16::from_be_bytes([payload[0], payload[1]]); if !valid_close_code(code) { - return Err(miette!("websocket close frame uses invalid close code")); + return Err(FrameError::protocol( + FrameFailureClass::InvalidCloseFrame, + miette!("websocket close frame uses invalid close code"), + )); } if std::str::from_utf8(&payload[2..]).is_err() { - return Err(miette!("websocket close frame reason is not valid UTF-8")); + return Err(FrameError::invalid_utf8(miette!( + "websocket close frame reason is not valid UTF-8" + ))); } Ok(()) } @@ -893,7 +1606,7 @@ async fn copy_raw_frame_payload( reader: &mut R, writer: &mut W, frame: &FrameHeader, -) -> Result<()> +) -> FrameResult<()> where R: AsyncRead + Unpin, W: AsyncWrite + Unpin, @@ -901,25 +1614,142 @@ where writer .write_all(&frame.raw_header) .await - .into_diagnostic()?; + .map_err(|error| FrameError::peer_io("websocket upstream write failed", error))?; let mut remaining = frame.payload_len; let mut buf = [0u8; COPY_BUF_SIZE]; while remaining > 0 { let to_read = usize::try_from(remaining) .unwrap_or(buf.len()) .min(buf.len()); - let n = reader.read(&mut buf[..to_read]).await.into_diagnostic()?; + let n = reader + .read(&mut buf[..to_read]) + .await + .map_err(|error| FrameError::peer_io("websocket client read failed", error))?; if n == 0 { - return Err(miette!("websocket payload ended before declared length")); + return Err(FrameError::peer_disconnect(miette!( + "websocket payload ended before declared length" + ))); } - writer.write_all(&buf[..n]).await.into_diagnostic()?; + writer + .write_all(&buf[..n]) + .await + .map_err(|error| FrameError::peer_io("websocket upstream write failed", error))?; remaining -= n as u64; } + writer + .flush() + .await + .map_err(|error| FrameError::peer_io("websocket upstream flush failed", error))?; + Ok(()) +} + +async fn write_masked_frame( + writer: &mut W, + opcode: u8, + payload: &[u8], +) -> Result<()> { + write_masked_frame_with_rsv(writer, opcode, 0, payload).await +} + +pub(super) async fn write_masked_close( + writer: &mut W, + payload: &[u8], +) -> Result<()> { + write_masked_frame(writer, OPCODE_CLOSE, payload).await +} + +pub(super) async fn write_unmasked_close( + writer: &mut W, + payload: &[u8], +) -> Result<()> { + let payload_len = u8::try_from(payload.len()) + .map_err(|_| miette!("websocket close payload exceeds 125 bytes"))?; + writer + .write_all(&[0x80 | OPCODE_CLOSE, payload_len]) + .await + .into_diagnostic()?; + writer.write_all(payload).await.into_diagnostic()?; + writer.flush().await.into_diagnostic()?; + Ok(()) +} + +async fn write_masked_frame_with_rsv( + writer: &mut W, + opcode: u8, + rsv: u8, + payload: &[u8], +) -> Result<()> { + let (header, masked) = masked_frame_parts(opcode, rsv, payload); + writer.write_all(&header).await.into_diagnostic()?; + writer.write_all(&masked).await.into_diagnostic()?; writer.flush().await.into_diagnostic()?; Ok(()) } -fn masked_frame_bytes(opcode: u8, rsv: u8, payload: &[u8]) -> Vec { +async fn write_masked_text_frame_guarded( + writer: &mut W, + rsv: u8, + payload: &[u8], + host: &str, + port: u16, + policy_name: &str, + generation_guard: Option<&PolicyGenerationGuard>, +) -> WebSocketRelayResult<()> { + let (header, masked) = masked_frame_parts(OPCODE_TEXT, rsv, payload); + write_text_frame_guarded( + writer, + &header, + &masked, + host, + port, + policy_name, + generation_guard, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn write_text_frame_guarded( + writer: &mut W, + header: &[u8], + payload: &[u8], + host: &str, + port: u16, + policy_name: &str, + generation_guard: Option<&PolicyGenerationGuard>, +) -> WebSocketRelayResult<()> { + ensure_generation_guard_current(host, port, policy_name, generation_guard)?; + tokio::time::timeout(TEXT_MESSAGE_FORWARD_TOTAL_TIMEOUT, async { + writer.write_all(header).await.map_err(|error| { + terminate( + WebSocketTerminationCause::PeerDisconnect, + miette!("websocket upstream write failed: {error}"), + ) + })?; + writer.write_all(payload).await.map_err(|error| { + terminate( + WebSocketTerminationCause::PeerDisconnect, + miette!("websocket upstream write failed: {error}"), + ) + })?; + writer.flush().await.map_err(|error| { + terminate( + WebSocketTerminationCause::PeerDisconnect, + miette!("websocket upstream flush failed: {error}"), + ) + }) + }) + .await + .map_err(|_| { + terminate( + WebSocketTerminationCause::PeerDisconnect, + miette!("websocket upstream forwarding total timeout"), + ) + })??; + ensure_generation_guard_current(host, port, policy_name, generation_guard) +} + +fn masked_frame_parts(opcode: u8, rsv: u8, payload: &[u8]) -> (Vec, Vec) { let mut header = Vec::with_capacity(14); header.push(0x80 | rsv | opcode); match payload.len() { @@ -942,17 +1772,12 @@ fn masked_frame_bytes(opcode: u8, rsv: u8, payload: &[u8]) -> Vec { let mut masked = payload.to_vec(); apply_mask(&mut masked, mask_key); - header.extend_from_slice(&masked); - header + (header, masked) } -async fn write_frame_bytes(writer: &mut W, frame: &[u8]) -> Result<()> { - writer.write_all(frame).await.into_diagnostic()?; - writer.flush().await.into_diagnostic()?; - Ok(()) -} - -fn decompress_permessage_deflate(payload: &[u8]) -> Result> { +fn decompress_permessage_deflate( + payload: &[u8], +) -> std::result::Result, WebSocketDecompressionError> { let mut decoder = Decompress::new(false); let mut input = Vec::with_capacity(payload.len() + 4); input.extend_from_slice(payload); @@ -965,18 +1790,30 @@ fn decompress_permessage_deflate(payload: &[u8]) -> Result> { let before_out = decoder.total_out(); let status = decoder .decompress(&input[input_pos..], &mut scratch, FlushDecompress::Sync) - .map_err(|e| miette!("websocket permessage-deflate decompression failed: {e}"))?; - let read = usize::try_from(decoder.total_in() - before_in) - .map_err(|_| miette!("websocket permessage-deflate input length overflow"))?; - let written = usize::try_from(decoder.total_out() - before_out) - .map_err(|_| miette!("websocket permessage-deflate output length overflow"))?; - input_pos = input_pos - .checked_add(read) - .ok_or_else(|| miette!("websocket permessage-deflate input length overflow"))?; + .map_err(|e| { + WebSocketDecompressionError::Protocol(miette!( + "websocket permessage-deflate decompression failed: {e}" + )) + })?; + let read = usize::try_from(decoder.total_in() - before_in).map_err(|_| { + WebSocketDecompressionError::Protocol(miette!( + "websocket permessage-deflate input length overflow" + )) + })?; + let written = usize::try_from(decoder.total_out() - before_out).map_err(|_| { + WebSocketDecompressionError::Protocol(miette!( + "websocket permessage-deflate output length overflow" + )) + })?; + input_pos = input_pos.checked_add(read).ok_or_else(|| { + WebSocketDecompressionError::Protocol(miette!( + "websocket permessage-deflate input length overflow" + )) + })?; if out.len().saturating_add(written) > MAX_TEXT_MESSAGE_BYTES { - return Err(miette!( + return Err(WebSocketDecompressionError::MessageTooBig(miette!( "websocket text message exceeds {MAX_TEXT_MESSAGE_BYTES} byte limit" - )); + ))); } out.extend_from_slice(&scratch[..written]); if matches!(status, Status::StreamEnd) { @@ -986,9 +1823,9 @@ fn decompress_permessage_deflate(payload: &[u8]) -> Result> { break; } if read == 0 && written == 0 { - return Err(miette!( + return Err(WebSocketDecompressionError::Protocol(miette!( "websocket permessage-deflate decompression did not make progress" - )); + ))); } } Ok(out) @@ -1037,6 +1874,99 @@ fn compress_permessage_deflate(payload: &[u8]) -> Result> { Ok(out) } +#[cfg(test)] +pub fn compressed_masked_text_frame_for_test(payload: &[u8]) -> Vec { + let compressed = compress_permessage_deflate(payload).expect("compress test WebSocket frame"); + let (mut frame, masked) = masked_frame_parts(OPCODE_TEXT, 0x40, &compressed); + frame.extend_from_slice(&masked); + frame +} + +#[cfg(test)] +pub fn decode_compressed_masked_text_frame_for_test(frame: &[u8]) -> String { + assert_eq!(frame[0] & 0x0f, OPCODE_TEXT); + assert_eq!(frame[0] & 0x40, 0x40); + let header = parse_test_frame_layout(frame); + assert!(header.masked, "client-to-upstream frame must be masked"); + let mut payload = + frame[header.payload_offset..header.payload_offset + header.payload_len].to_vec(); + apply_mask(&mut payload, header.mask_key.expect("masked test frame")); + String::from_utf8( + decompress_permessage_deflate(&payload).expect("decompress test WebSocket frame"), + ) + .expect("UTF-8 test WebSocket text") +} + +#[cfg(test)] +pub async fn read_frame_for_test(reader: &mut R) -> Vec { + let mut frame = vec![0u8; 2]; + reader + .read_exact(&mut frame) + .await + .expect("read test WebSocket frame header"); + let extended_len_bytes = match frame[1] & 0x7f { + 0..=125 => 0, + 126 => 2, + 127 => 8, + _ => unreachable!(), + }; + let header_len = extended_len_bytes + if frame[1] & 0x80 != 0 { 4 } else { 0 }; + frame.resize(2 + header_len, 0); + reader + .read_exact(&mut frame[2..]) + .await + .expect("read test WebSocket frame metadata"); + let payload_len = match frame[1] & 0x7f { + 0..=125 => usize::from(frame[1] & 0x7f), + 126 => usize::from(u16::from_be_bytes([frame[2], frame[3]])), + 127 => usize::try_from(u64::from_be_bytes(frame[2..10].try_into().unwrap())).unwrap(), + _ => unreachable!(), + }; + let frame_len = frame.len(); + frame.resize(frame_len + payload_len, 0); + reader + .read_exact(&mut frame[frame_len..]) + .await + .expect("read test WebSocket frame payload"); + frame +} + +#[cfg(test)] +struct TestFrameLayout { + masked: bool, + mask_key: Option<[u8; 4]>, + payload_offset: usize, + payload_len: usize, +} + +#[cfg(test)] +fn parse_test_frame_layout(frame: &[u8]) -> TestFrameLayout { + let masked = frame[1] & 0x80 != 0; + let len_code = frame[1] & 0x7f; + let (payload_len, mut payload_offset) = match len_code { + 0..=125 => (usize::from(len_code), 2), + 126 => (usize::from(u16::from_be_bytes([frame[2], frame[3]])), 4), + 127 => ( + usize::try_from(u64::from_be_bytes(frame[2..10].try_into().unwrap())).unwrap(), + 10, + ), + _ => unreachable!(), + }; + let mask_key = masked.then(|| { + let key = frame[payload_offset..payload_offset + 4] + .try_into() + .expect("test frame mask"); + payload_offset += 4; + key + }); + TestFrameLayout { + masked, + mask_key, + payload_offset, + payload_len, + } +} + fn new_mask_key() -> [u8; 4] { let bytes = uuid::Uuid::new_v4().into_bytes(); [bytes[0], bytes[1], bytes[2], bytes[3]] @@ -1120,44 +2050,60 @@ fn emit_websocket_l7_event( ocsf_emit!(event); } -fn protocol_failure_class(error: &miette::Report) -> &'static str { - let msg = error.to_string().to_ascii_lowercase(); - if msg.contains("credential") { - "credential_resolution_failed" - } else if msg.contains("utf-8") { - "invalid_utf8" - } else if msg.contains("close frame") || msg.contains("after close") { - "invalid_close_frame" - } else if msg.contains("control frame") { - "invalid_control_frame" - } else if msg.contains("length") - || msg.contains("too large") - || msg.contains("exceeds") - || msg.contains("overflow") - { - "invalid_length" - } else if msg.contains("continuation") || msg.contains("fragmented") { - "invalid_fragmentation" - } else if msg.contains("reserved opcode") { - "reserved_opcode" - } else if msg.contains("not masked") { - "unmasked_client_frame" - } else if msg.contains("rsv") { - "rsv_bits" - } else if msg.contains("malformed") { - "malformed_frame" - } else { - "protocol_error" +fn observe_termination( + host: &str, + port: u16, + policy_name: &str, + termination: &WebSocketTermination, +) { + if let Some(failure_class) = termination.failure_class { + emit_protocol_failure(host, port, policy_name, failure_class); + } + if termination.cause == WebSocketTerminationCause::CapacityExhausted { + ocsf_emit!( + NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Open) + .action(ActionId::Denied) + .disposition(DispositionId::Blocked) + .severity(SeverityId::Medium) + .status(StatusId::Failure) + .dst_endpoint(Endpoint::from_domain(host, port)) + .firewall_rule(policy_name, "l7-websocket") + .status_detail("assembly_capacity_exhausted") + .message(format!( + "WebSocket text assembly capacity exhausted [host:{host} port:{port}]" + )) + .build() + ); } } -fn emit_protocol_failure(host: &str, port: u16, policy_name: &str, failure_class: &str) { +fn emit_protocol_failure( + host: &str, + port: u16, + policy_name: &str, + failure_class: FrameFailureClass, +) { + ocsf_emit!(protocol_failure_event( + host, + port, + policy_name, + failure_class + )); +} + +fn protocol_failure_event( + host: &str, + port: u16, + policy_name: &str, + failure_class: FrameFailureClass, +) -> openshell_ocsf::OcsfEvent { let policy_name = if policy_name.is_empty() { "-" } else { policy_name }; - let event = NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) + NetworkActivityBuilder::new(openshell_ocsf::ctx::ctx()) .activity(ActivityId::Open) .action(ActionId::Denied) .disposition(DispositionId::Blocked) @@ -1166,9 +2112,8 @@ fn emit_protocol_failure(host: &str, port: u16, policy_name: &str, failure_class .dst_endpoint(Endpoint::from_domain(host, port)) .firewall_rule(policy_name, "l7-websocket") .message(protocol_failure_message(host, port)) - .status_detail(failure_class) - .build(); - ocsf_emit!(event); + .status_detail(failure_class.as_str()) + .build() } fn protocol_failure_message(host: &str, port: u16) -> String { @@ -1180,11 +2125,29 @@ mod tests { use super::*; use crate::l7::relay::L7EvalContext; use crate::opa::{NetworkInput, OpaEngine}; + use openshell_core::proto::middleware::v1::supervisor_middleware_server::{ + SupervisorMiddleware, SupervisorMiddlewareServer, + }; use openshell_core::proto::{StaticCredentialBinding, StaticCredentialEndpointBinding}; use openshell_core::provider_credentials::ProviderCredentialState; use openshell_core::secrets::SecretResolver; use std::path::PathBuf; use tokio::io::{AsyncReadExt, AsyncWriteExt}; + use tokio_stream::wrappers::{ReceiverStream, TcpListenerStream}; + use tonic::{Request, Response, Status}; + + async fn test_assembly_admission() -> WebSocketAssemblyAdmission { + match WebSocketAssemblyBudget::new(1, 0) + .reserve() + .await + .expect("reserve test assembly") + { + WebSocketAssemblyAdmissionOutcome::Admitted(admission) => admission, + WebSocketAssemblyAdmissionOutcome::QueueExhausted => { + panic!("fresh test assembly budget must admit") + } + } + } const TEST_POLICY: &str = include_str!("../../data/sandbox-policy.rego"); const GRAPHQL_WS_POLICY: &str = r#" @@ -1211,6 +2174,54 @@ network_policies: - { path: /usr/bin/node } "#; + #[test] + fn termination_causes_map_to_protocol_close_codes_and_session_reasons() { + use openshell_core::proto::WebSocketSessionEndReason as EndReason; + + assert_eq!( + WebSocketTerminationCause::InvalidUtf8.close_code(), + Some(1007) + ); + assert_eq!( + WebSocketTerminationCause::ProtocolError.close_code(), + Some(1002) + ); + assert_eq!( + WebSocketTerminationCause::MessageTooBig.close_code(), + Some(1009) + ); + assert_eq!( + WebSocketTerminationCause::MiddlewareDenial.close_code(), + Some(1008) + ); + assert_eq!( + WebSocketTerminationCause::PolicyReload.close_code(), + Some(1012) + ); + assert_eq!(WebSocketTerminationCause::PeerDisconnect.close_code(), None); + + assert_eq!( + WebSocketTerminationCause::InvalidUtf8.session_end_reason(), + EndReason::ProtocolError + ); + assert_eq!( + WebSocketTerminationCause::MiddlewareDenial.session_end_reason(), + EndReason::MiddlewareDenial + ); + assert_eq!( + WebSocketTerminationCause::PolicyDenial.session_end_reason(), + EndReason::PolicyDenial + ); + assert_eq!( + WebSocketTerminationCause::MiddlewareFailure.session_end_reason(), + EndReason::MiddlewareFailure + ); + assert_eq!( + WebSocketTerminationCause::PolicyReload.session_end_reason(), + EndReason::PolicyReload + ); + } + fn resolver() -> (HashMap, SecretResolver) { let (child_env, resolver) = SecretResolver::from_provider_env( std::iter::once(("DISCORD_BOT_TOKEN".to_string(), "real-token".to_string())).collect(), @@ -1282,42 +2293,335 @@ network_policies: frame } - fn close_payload(code: u16, reason: &[u8]) -> Vec { - let mut payload = Vec::with_capacity(2 + reason.len()); - payload.extend_from_slice(&code.to_be_bytes()); - payload.extend_from_slice(reason); - payload + fn test_frame_header(fin: bool, opcode: u8, payload_len: u64) -> FrameHeader { + FrameHeader { + fin, + rsv: 0, + opcode, + masked: true, + payload_len, + mask_key: Some([0x37, 0xfa, 0x21, 0x3d]), + raw_header: Vec::new(), + } } - async fn run_client_to_server(input: Vec) -> Result> { - let (_, resolver) = resolver(); - let (mut client_write, mut relay_read) = tokio::io::duplex(MAX_TEXT_MESSAGE_BYTES + 1024); - let (mut relay_write, mut upstream_read) = tokio::io::duplex(MAX_TEXT_MESSAGE_BYTES + 1024); + async fn wait_for_stalled_task(task: &tokio::task::JoinHandle) { + tokio::task::yield_now().await; + assert!(!task.is_finished(), "fixture task must be pending"); + } - client_write.write_all(&input).await.unwrap(); - drop(client_write); + struct ReloadAfterFirstWrite { + engine: Arc, + output: Vec, + writes: usize, + } - let options = RelayOptions { - policy_name: "test-policy", - resolver: Some(&resolver), - provider_credentials: None, - target: "/", + impl AsyncWrite for ReloadAfterFirstWrite { + fn poll_write( + self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + buffer: &[u8], + ) -> std::task::Poll> { + let this = self.get_mut(); + this.output.extend_from_slice(buffer); + this.writes += 1; + if this.writes == 1 { + this.engine + .replace_middleware_registry( + openshell_supervisor_middleware::MiddlewareRegistry::default(), + ) + .expect("invalidate generation after frame header"); + } + std::task::Poll::Ready(Ok(buffer.len())) + } + + fn poll_flush( + self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + _cx: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + } + + fn relay_options_with_budget(budget: WebSocketAssemblyBudget) -> RelayOptions<'static> { + RelayOptions { + policy_name: "test-policy", + assembly_budget: budget, + resolver: None, + generation_guard: None, + provider_credentials: None, + target: "/", + inspector: None, + compression: WebSocketCompression::None, + middleware_session: None, + middleware_context: None, + } + } + + fn close_payload(code: u16, reason: &[u8]) -> Vec { + let mut payload = Vec::with_capacity(2 + reason.len()); + payload.extend_from_slice(&code.to_be_bytes()); + payload.extend_from_slice(reason); + payload + } + + async fn run_client_to_server(input: Vec) -> Result> { + let (_, resolver) = resolver(); + let (mut client_write, mut relay_read) = tokio::io::duplex(MAX_TEXT_MESSAGE_BYTES + 1024); + let (mut relay_write, mut upstream_read) = tokio::io::duplex(MAX_TEXT_MESSAGE_BYTES + 1024); + + client_write.write_all(&input).await.unwrap(); + drop(client_write); + + let mut options = RelayOptions { + policy_name: "test-policy", + assembly_budget: WebSocketAssemblyBudget::default(), + resolver: Some(&resolver), + generation_guard: None, + provider_credentials: None, + target: "/", inspector: None, compression: WebSocketCompression::None, + middleware_session: None, + middleware_context: None, }; let result = relay_client_to_server( &mut relay_read, &mut relay_write, "gateway.example.test", 443, - &options, + &mut options, ) .await; drop(relay_write); let mut output = Vec::new(); upstream_read.read_to_end(&mut output).await.unwrap(); - result.map(|()| output) + result + .map(|_| output) + .map_err(|termination| termination.error) + } + + #[tokio::test] + async fn parsed_relays_share_assembly_budget_without_middleware() { + let budget = WebSocketAssemblyBudget::new(1, 0); + let held_frame = masked_frame(true, OPCODE_TEXT, b"held"); + let (mut first_client, mut first_reader) = tokio::io::duplex(64); + let (mut first_writer, _first_upstream) = tokio::io::duplex(64); + first_client + .write_all(&held_frame[..6]) + .await + .expect("send frame header without payload"); + let first_budget = budget.clone(); + let first = tokio::spawn(async move { + let mut options = relay_options_with_budget(first_budget); + relay_client_to_server( + &mut first_reader, + &mut first_writer, + "gateway.example.test", + 443, + &mut options, + ) + .await + }); + wait_for_stalled_task(&first).await; + + let rejected_frame = masked_frame(true, OPCODE_TEXT, b"rejected"); + let (mut second_client, mut second_reader) = tokio::io::duplex(64); + let (mut second_writer, mut second_upstream) = tokio::io::duplex(64); + second_client + .write_all(&rejected_frame) + .await + .expect("send rejected frame"); + drop(second_client); + let mut second_options = relay_options_with_budget(budget.clone()); + let rejected = relay_client_to_server( + &mut second_reader, + &mut second_writer, + "gateway.example.test", + 443, + &mut second_options, + ) + .await + .expect_err("full assembly budget must shed"); + assert_eq!(rejected.cause, WebSocketTerminationCause::CapacityExhausted); + drop(second_writer); + let mut rejected_output = Vec::new(); + second_upstream + .read_to_end(&mut rejected_output) + .await + .expect("read rejected upstream"); + assert!(rejected_output.is_empty()); + + drop(first_client); + first + .await + .expect("join held relay") + .expect_err("incomplete message must end on disconnect"); + + let admitted_frame = masked_frame(true, OPCODE_TEXT, b"admitted"); + let (mut third_client, mut third_reader) = tokio::io::duplex(64); + let (mut third_writer, mut third_upstream) = tokio::io::duplex(64); + third_client + .write_all(&admitted_frame) + .await + .expect("send admitted frame"); + drop(third_client); + let mut third_options = relay_options_with_budget(budget); + relay_client_to_server( + &mut third_reader, + &mut third_writer, + "gateway.example.test", + 443, + &mut third_options, + ) + .await + .expect("released assembly budget must admit"); + drop(third_writer); + let mut admitted_output = Vec::new(); + third_upstream + .read_to_end(&mut admitted_output) + .await + .expect("read admitted upstream"); + assert_eq!(admitted_output, admitted_frame); + } + + #[tokio::test] + async fn assembly_budget_bounds_waiters_and_recovers_capacity() { + let budget = WebSocketAssemblyBudget::new(1, 1); + let first = match budget.reserve().await.expect("reserve active assembly") { + WebSocketAssemblyAdmissionOutcome::Admitted(admission) => admission, + WebSocketAssemblyAdmissionOutcome::QueueExhausted => { + panic!("fresh budget must admit") + } + }; + let waiting_budget = budget.clone(); + let waiting = tokio::spawn(async move { waiting_budget.reserve().await }); + wait_for_stalled_task(&waiting).await; + assert!(matches!( + budget.reserve().await.expect("attempt shed admission"), + WebSocketAssemblyAdmissionOutcome::QueueExhausted + )); + drop(first); + assert!(matches!( + waiting + .await + .expect("join waiting admission") + .expect("waiting admission result"), + WebSocketAssemblyAdmissionOutcome::Admitted(_) + )); + } + + #[tokio::test(start_paused = true)] + async fn upstream_forwarding_timeout_releases_assembly_capacity() { + let budget = WebSocketAssemblyBudget::new(1, 0); + let assembly_admission = match budget.reserve().await.expect("reserve assembly") { + WebSocketAssemblyAdmissionOutcome::Admitted(admission) => admission, + WebSocketAssemblyAdmissionOutcome::QueueExhausted => { + panic!("fresh assembly budget must admit") + } + }; + let payload = vec![b'x'; 64]; + let frame_bytes = masked_frame(true, OPCODE_TEXT, &payload); + let mut frame = test_frame_header(true, OPCODE_TEXT, payload.len() as u64); + frame.raw_header = frame_bytes[..6].to_vec(); + let (mut writer, _non_reading_upstream) = tokio::io::duplex(1); + let forwarding = tokio::spawn(async move { + let mut options = relay_options_with_budget(WebSocketAssemblyBudget::new(1, 0)); + relay_text_payload( + &mut writer, + &frame, + payload, + assembly_admission, + None, + false, + false, + "gateway.example.test", + 443, + &mut options, + ) + .await + }); + wait_for_stalled_task(&forwarding).await; + assert!(matches!( + budget.reserve().await.expect("attempt shed admission"), + WebSocketAssemblyAdmissionOutcome::QueueExhausted + )); + + tokio::time::advance(TEXT_MESSAGE_FORWARD_TOTAL_TIMEOUT + StdDuration::from_millis(1)) + .await; + let error = forwarding + .await + .expect("join forwarding") + .expect_err("non-reading upstream must time out"); + assert_eq!(error.cause, WebSocketTerminationCause::PeerDisconnect); + assert!( + error + .error + .to_string() + .contains("upstream forwarding total timeout") + ); + assert!(matches!( + budget + .reserve() + .await + .expect("reserve after forwarding timeout"), + WebSocketAssemblyAdmissionOutcome::Admitted(_) + )); + } + + #[tokio::test] + async fn reload_after_frame_header_preserves_frame_boundary_before_close() { + let engine = Arc::new( + OpaEngine::from_strings(TEST_POLICY, "network_policies: {}\n").expect("test policy"), + ); + let generation_guard = engine + .generation_guard(engine.current_generation()) + .expect("generation guard"); + let payload = b"complete-frame"; + let (header, masked) = masked_frame_parts(OPCODE_TEXT, 0, payload); + let mut writer = ReloadAfterFirstWrite { + engine, + output: Vec::new(), + writes: 0, + }; + + let error = write_text_frame_guarded( + &mut writer, + &header, + &masked, + "gateway.example.test", + 443, + "test-policy", + Some(&generation_guard), + ) + .await + .expect_err("reload after header must close after completing the frame"); + assert_eq!(error.cause, WebSocketTerminationCause::PolicyReload); + + write_masked_close(&mut writer, &1012u16.to_be_bytes()) + .await + .expect("write typed close"); + let frame_len = header.len() + masked.len(); + assert_eq!(&writer.output[..header.len()], header); + assert_eq!(&writer.output[header.len()..frame_len], masked); + let close = &writer.output[frame_len..]; + assert_eq!(close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes( + decode_masked_payload(close)[..2] + .try_into() + .expect("close code"), + ), + 1012 + ); } fn bound_websocket_provider_state() -> ProviderCredentialState { @@ -1353,26 +2657,33 @@ network_policies: client_write.write_all(&input).await.unwrap(); drop(client_write); - let options = RelayOptions { + let mut options = RelayOptions { policy_name: "test-policy", + assembly_budget: WebSocketAssemblyBudget::default(), resolver: Some(fallback), + generation_guard: None, provider_credentials: Some(state), target: "/socket", inspector: None, compression: WebSocketCompression::None, + middleware_session: None, + middleware_context: None, }; let result = relay_client_to_server( &mut relay_read, &mut relay_write, "gateway.example.test", 443, - &options, + &mut options, ) .await; drop(relay_write); let mut output = Vec::new(); upstream_read.read_to_end(&mut output).await.unwrap(); - (result, output) + ( + result.map(|_| ()).map_err(|termination| termination.error), + output, + ) } #[tokio::test] @@ -1432,13 +2743,17 @@ network_policies: mask_key: Some([0x37, 0xfa, 0x21, 0x3d]), raw_header: Vec::new(), }; - let options = RelayOptions { + let mut options = RelayOptions { policy_name: "test-policy", + assembly_budget: WebSocketAssemblyBudget::default(), resolver: Some(fallback.as_ref()), + generation_guard: None, provider_credentials: Some(&state), target: "/socket", inspector: None, compression: WebSocketCompression::PermessageDeflate, + middleware_session: None, + middleware_context: None, }; let reached_write = tokio::sync::Barrier::new(2); let release_write = tokio::sync::Barrier::new(2); @@ -1448,11 +2763,13 @@ network_policies: &mut relay_write, &frame, compressed, + test_assembly_admission().await, + None, false, true, "gateway.example.test", 443, - &options, + &mut options, async { reached_write.wait().await; release_write.wait().await; @@ -1467,7 +2784,7 @@ network_policies: assert!( result .as_ref() - .is_err_and(|error| error.to_string().contains("generation changed")), + .is_err_and(|error| error.error.to_string().contains("generation changed")), "revoked credential generation must fail before the frame write: {result:?}" ); @@ -1517,9 +2834,11 @@ network_policies: client_write.write_all(&input).await.unwrap(); drop(client_write); - let options = RelayOptions { + let mut options = RelayOptions { policy_name: "graphql_ws", + assembly_budget: WebSocketAssemblyBudget::default(), resolver, + generation_guard: Some(tunnel_engine.generation_guard()), provider_credentials: None, target: "/graphql", inspector: Some(InspectionOptions { @@ -1531,20 +2850,24 @@ network_policies: graphql_policy: true, }), compression: WebSocketCompression::None, + middleware_session: None, + middleware_context: None, }; let result = relay_client_to_server( &mut relay_read, &mut relay_write, "realtime.graphql.test", 443, - &options, + &mut options, ) .await; drop(relay_write); let mut output = Vec::new(); upstream_read.read_to_end(&mut output).await.unwrap(); - result.map(|()| output) + result + .map(|_| output) + .map_err(|termination| termination.error) } async fn run_client_to_server_compressed(input: Vec) -> Result> { @@ -1555,27 +2878,33 @@ network_policies: client_write.write_all(&input).await.unwrap(); drop(client_write); - let options = RelayOptions { + let mut options = RelayOptions { policy_name: "test-policy", + assembly_budget: WebSocketAssemblyBudget::default(), resolver: Some(&resolver), + generation_guard: None, provider_credentials: None, target: "/", inspector: None, compression: WebSocketCompression::PermessageDeflate, + middleware_session: None, + middleware_context: None, }; let result = relay_client_to_server( &mut relay_read, &mut relay_write, "gateway.example.test", 443, - &options, + &mut options, ) .await; drop(relay_write); let mut output = Vec::new(); upstream_read.read_to_end(&mut output).await.unwrap(); - result.map(|()| output) + result + .map(|_| output) + .map_err(|termination| termination.error) } fn decode_masked_text_frame(frame: &[u8]) -> String { @@ -1651,6 +2980,202 @@ network_policies: frame } + #[tokio::test(start_paused = true)] + async fn stalled_initial_text_payload_releases_middleware_admission() { + let runner = openshell_supervisor_middleware::ChainRunner::default(); + let admission = runner + .reserve_middleware_work_admission() + .await + .expect("reserve middleware work"); + let (client, mut reader) = tokio::io::duplex(8); + let frame = test_frame_header(true, OPCODE_TEXT, 4); + let task = tokio::spawn(async move { + let mut assembly = + TextMessageAssembly::new(false, test_assembly_admission().await, Some(admission)); + assembly.read_payload(&mut reader, &frame).await + }); + + wait_for_stalled_task(&task).await; + tokio::time::advance(TEXT_MESSAGE_ASSEMBLY_IDLE_TIMEOUT + StdDuration::from_millis(1)) + .await; + let error = task + .await + .expect("join stalled assembly") + .expect_err("initial payload must time out"); + assert!(error.to_string().contains("assembly idle timeout")); + + runner + .reserve_middleware_work_admission() + .await + .expect("timed-out initial payload releases admission"); + drop(client); + } + + #[tokio::test(start_paused = true)] + async fn stalled_continuation_payload_releases_middleware_admission() { + let runner = openshell_supervisor_middleware::ChainRunner::default(); + let admission = runner + .reserve_middleware_work_admission() + .await + .expect("reserve middleware work"); + let (mut client, mut reader) = tokio::io::duplex(8); + client + .write_all(&[0x37]) + .await + .expect("send partial continuation payload"); + let frame = test_frame_header(true, OPCODE_CONTINUATION, 2); + let task = tokio::spawn(async move { + let mut assembly = + TextMessageAssembly::new(false, test_assembly_admission().await, Some(admission)); + assembly.payload.extend_from_slice(b"first"); + assembly.add_fragment().expect("continuation within limit"); + assembly.read_payload(&mut reader, &frame).await + }); + + wait_for_stalled_task(&task).await; + tokio::time::advance(TEXT_MESSAGE_ASSEMBLY_IDLE_TIMEOUT + StdDuration::from_millis(1)) + .await; + let error = task + .await + .expect("join stalled assembly") + .expect_err("continuation payload must time out"); + assert!(error.to_string().contains("assembly idle timeout")); + + runner + .reserve_middleware_work_admission() + .await + .expect("timed-out continuation releases admission"); + drop(client); + } + + #[tokio::test(start_paused = true)] + async fn missing_continuation_header_releases_middleware_admission() { + let runner = openshell_supervisor_middleware::ChainRunner::default(); + let admission = runner + .reserve_middleware_work_admission() + .await + .expect("reserve middleware work"); + let (client, mut reader) = tokio::io::duplex(8); + let task = tokio::spawn(async move { + let mut assembly = + TextMessageAssembly::new(false, test_assembly_admission().await, Some(admission)); + assembly.payload.extend_from_slice(b"first"); + let result = read_frame_header(&mut reader, Some(&assembly)).await; + drop(assembly); + result + }); + + wait_for_stalled_task(&task).await; + tokio::time::advance(TEXT_MESSAGE_ASSEMBLY_IDLE_TIMEOUT + StdDuration::from_millis(1)) + .await; + let error = task + .await + .expect("join stalled assembly") + .expect_err("missing continuation header must time out"); + assert!(error.to_string().contains("assembly idle timeout")); + + runner + .reserve_middleware_work_admission() + .await + .expect("missing continuation releases admission"); + drop(client); + } + + #[tokio::test(start_paused = true)] + async fn text_assembly_total_deadline_does_not_reset_on_input_progress() { + let runner = openshell_supervisor_middleware::ChainRunner::default(); + let admission = runner + .reserve_middleware_work_admission() + .await + .expect("reserve middleware work"); + let (mut client, mut reader) = tokio::io::duplex(8); + let frame = test_frame_header(true, OPCODE_TEXT, 1_024); + let task = tokio::spawn(async move { + let mut assembly = + TextMessageAssembly::new(false, test_assembly_admission().await, Some(admission)); + assembly.read_payload(&mut reader, &frame).await + }); + wait_for_stalled_task(&task).await; + + let progress_interval = TEXT_MESSAGE_ASSEMBLY_IDLE_TIMEOUT / 2; + let mut elapsed = StdDuration::ZERO; + while elapsed + progress_interval < TEXT_MESSAGE_ASSEMBLY_TOTAL_TIMEOUT { + tokio::time::advance(progress_interval).await; + elapsed += progress_interval; + client + .write_all(&[0x37]) + .await + .expect("make progress before idle timeout"); + tokio::task::yield_now().await; + assert!(!task.is_finished(), "idle deadline must reset on progress"); + } + let until_total_timeout = TEXT_MESSAGE_ASSEMBLY_TOTAL_TIMEOUT + .checked_sub(elapsed) + .expect("progress schedule stays within total timeout"); + tokio::time::advance(until_total_timeout + StdDuration::from_millis(1)).await; + let error = task + .await + .expect("join total assembly timeout") + .expect_err("total assembly deadline must not reset"); + assert!(error.to_string().contains("assembly total timeout")); + + runner + .reserve_middleware_work_admission() + .await + .expect("total timeout releases admission"); + } + + #[tokio::test(start_paused = true)] + async fn stalled_assemblies_release_the_saturated_shared_work_budget() { + let runner = openshell_supervisor_middleware::ChainRunner::default(); + let mut clients = Vec::new(); + let mut stalled = Vec::new(); + for _ in 0..openshell_supervisor_middleware::MAX_CONCURRENT_MIDDLEWARE_WORK { + let admission = runner + .reserve_middleware_work_admission() + .await + .expect("fill shared middleware work budget"); + let (client, mut reader) = tokio::io::duplex(8); + clients.push(client); + let frame = test_frame_header(true, OPCODE_TEXT, 4); + stalled.push(tokio::spawn(async move { + let mut assembly = TextMessageAssembly::new( + false, + test_assembly_admission().await, + Some(admission), + ); + assembly.read_payload(&mut reader, &frame).await + })); + } + tokio::task::yield_now().await; + assert!(stalled.iter().all(|task| !task.is_finished())); + + let later_runner = runner.clone(); + let later_work = + tokio::spawn(async move { later_runner.reserve_middleware_work_admission().await }); + wait_for_stalled_task(&later_work).await; + + tokio::time::advance(TEXT_MESSAGE_ASSEMBLY_IDLE_TIMEOUT + StdDuration::from_millis(1)) + .await; + for task in stalled { + let error = task + .await + .expect("join stalled assembly") + .expect_err("stalled assembly must time out"); + assert!(error.to_string().contains("assembly idle timeout")); + } + + let admission = later_work + .await + .expect("join later middleware work") + .expect("later middleware work acquires released capacity"); + assert!( + admission.saturated(), + "later work must have waited behind the saturated budget" + ); + drop(clients); + } + #[test] fn classifies_graphql_transport_ws_subscribe_operation() { let message = r#"{"type":"subscribe","id":"1","payload":{"query":"subscription NewMessages { messageAdded }"}}"#; @@ -1796,11 +3321,15 @@ network_policies: 443, RelayOptions { policy_name: "test-policy", + assembly_budget: WebSocketAssemblyBudget::default(), resolver: Some(&resolver), + generation_guard: None, provider_credentials: None, target: "/", inspector: None, compression: WebSocketCompression::None, + middleware_session: None, + middleware_context: None, }, ) .await @@ -1825,6 +3354,1490 @@ network_policies: let _ = tokio::time::timeout(std::time::Duration::from_secs(2), relay).await; } + #[derive(Debug)] + enum ObservedWebSocketRequest { + SessionStart, + Message { sequence: u64, payload: String }, + SessionEnd(openshell_core::proto::WebSocketSessionEndReason), + } + + #[derive(Clone, Default)] + struct OpenAiWebSocketRedactor { + observed: Option>, + close_on_first_message: bool, + message_received: Option>, + release_message: Option>, + } + + #[tonic::async_trait] + impl SupervisorMiddleware for OpenAiWebSocketRedactor { + type EvaluateWebSocketSessionStream = + openshell_supervisor_middleware::WebSocketResponseStream; + + async fn describe( + &self, + _request: Request<()>, + ) -> std::result::Result, Status> + { + use openshell_core::proto::{ + MiddlewareBinding, MiddlewareManifest, SupervisorMiddlewareOperation, + SupervisorMiddlewarePhase, + }; + Ok(Response::new(MiddlewareManifest { + name: "test/openai-websocket-redactor".into(), + service_version: "test".into(), + bindings: vec![MiddlewareBinding { + operation: SupervisorMiddlewareOperation::WebsocketMessage as i32, + phase: SupervisorMiddlewarePhase::PreCredentials as i32, + max_payload_bytes: openshell_supervisor_middleware::MAX_MIDDLEWARE_PAYLOAD_BYTES + as u64, + timeout: "1s".into(), + }], + expected_audience: String::new(), + })) + } + + async fn validate_config( + &self, + _request: Request, + ) -> std::result::Result, Status> + { + Ok(Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + _request: Request, + ) -> std::result::Result, Status> + { + Err(Status::unimplemented("WebSocket-only test middleware")) + } + + async fn evaluate_web_socket_session( + &self, + request: Request>, + ) -> std::result::Result, Status> { + use openshell_core::proto::{ + Decision, WebSocketMessageResult, WebSocketPreflightAction, + WebSocketPreflightDecision, WebSocketSessionEventResult, web_socket_message, + web_socket_message_result, web_socket_session_event, + web_socket_session_event_result, + }; + let mut requests = request.into_inner(); + let observed = self.observed.clone(); + let close_on_first_message = self.close_on_first_message; + let message_received = self.message_received.clone(); + let release_message = self.release_message.clone(); + let (responses_tx, responses_rx) = tokio::sync::mpsc::channel(4); + tokio::spawn(async move { + while let Ok(Some(request)) = requests.message().await { + let response = match request.event { + Some(web_socket_session_event::Event::Preflight(_)) => { + Some(WebSocketSessionEventResult { + result: Some( + web_socket_session_event_result::Result::PreflightDecision( + WebSocketPreflightDecision { + action: WebSocketPreflightAction::Inspect as i32, + ..Default::default() + }, + ), + ), + }) + } + Some(web_socket_session_event::Event::Message(message)) => { + let web_socket_message::Payload::Text(text) = + message.payload.expect("OpenAI event payload") + else { + panic!("OpenAI event must be text"); + }; + if let Some(observed) = &observed { + let _ = observed.send(ObservedWebSocketRequest::Message { + sequence: message.sequence, + payload: text.clone(), + }); + } + if close_on_first_message { + break; + } + if let Some(received) = &message_received { + received.notify_one(); + } + if let Some(release) = &release_message { + release.notified().await; + } + let deny = text.contains("deny-me"); + let replacement = text.replace("customer-secret", "[REDACTED]"); + Some(WebSocketSessionEventResult { + result: Some( + web_socket_session_event_result::Result::MessageResult( + WebSocketMessageResult { + sequence: message.sequence, + decision: if deny { + Decision::Deny as i32 + } else { + Decision::Allow as i32 + }, + replacement: (!deny).then_some( + web_socket_message_result::Replacement::Text( + replacement, + ), + ), + reason_code: if deny { + "blocked".into() + } else { + "redacted".into() + }, + ..Default::default() + }, + ), + ), + }) + } + Some(web_socket_session_event::Event::SessionStart(_)) => { + if let Some(observed) = &observed { + let _ = observed.send(ObservedWebSocketRequest::SessionStart); + } + None + } + Some(web_socket_session_event::Event::SessionEnd(end)) => { + if let Some(observed) = &observed + && let Ok(reason) = + openshell_core::proto::WebSocketSessionEndReason::try_from( + end.reason, + ) + { + let _ = observed.send(ObservedWebSocketRequest::SessionEnd(reason)); + } + None + } + _ => None, + }; + if let Some(response) = response + && responses_tx.send(Ok(response)).await.is_err() + { + break; + } + } + }); + Ok(Response::new(Box::pin(ReceiverStream::new(responses_rx)))) + } + } + + async fn recording_middleware_session( + scheme: &str, + ) -> ( + openshell_supervisor_middleware::WebSocketSession, + tokio::sync::mpsc::UnboundedReceiver, + tokio::sync::oneshot::Sender<()>, + tokio::task::JoinHandle>, + ) { + recording_middleware_session_with_controls(scheme, None, None).await + } + + async fn recording_middleware_session_with_controls( + scheme: &str, + message_received: Option>, + release_message: Option>, + ) -> ( + openshell_supervisor_middleware::WebSocketSession, + tokio::sync::mpsc::UnboundedReceiver, + tokio::sync::oneshot::Sender<()>, + tokio::task::JoinHandle>, + ) { + use openshell_core::proto::SupervisorMiddlewareService; + use openshell_supervisor_middleware::{ChainEntry, MiddlewareRegistry, OnError}; + + let (observed_tx, observed_rx) = tokio::sync::mpsc::unbounded_channel(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind WebSocket middleware"); + let address = listener.local_addr().expect("middleware address"); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tonic::transport::Server::builder() + .add_service(SupervisorMiddlewareServer::new(OpenAiWebSocketRedactor { + observed: Some(observed_tx), + message_received, + release_message, + ..Default::default() + })) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }); + let server_task = tokio::spawn(server); + let registry = MiddlewareRegistry::connect_services( + Vec::new(), + vec![SupervisorMiddlewareService { + name: "openai-redactor".into(), + grpc_endpoint: format!("http://{address}"), + max_payload_bytes: openshell_supervisor_middleware::MAX_MIDDLEWARE_PAYLOAD_BYTES + as u64, + timeout: "2s".into(), + tls_ca_cert_pem: Vec::new(), + audience: String::new(), + allow_insecure_transport: false, + }], + ) + .await + .expect("connect middleware"); + let runner = openshell_supervisor_middleware::ChainRunner::from_registry(registry); + let preflight = runner + .preflight_websocket( + &[ChainEntry { + name: "redact-openai".into(), + implementation: "openai-redactor".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }], + openshell_supervisor_middleware::WebSocketPreflightInput { + session_id: "session".into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: scheme.into(), + host: "api.openai.com".into(), + port: if scheme == "wss" { 443 } else { 80 }, + path: "/v1/responses".into(), + requested_subprotocols: Vec::new(), + }, + ) + .await + .expect("preflight"); + + ( + preflight.session.expect("middleware inspects session"), + observed_rx, + shutdown_tx, + server_task, + ) + } + + async fn assert_invalid_close_termination(payload: Vec, expected_close_code: u16) { + let (mut session, mut observed, shutdown_tx, server_task) = + recording_middleware_session("wss").await; + assert!(session.start("").await.allowed); + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionStart) + )); + + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + let relay = tokio::spawn(async move { + relay_with_options( + &mut relay_client, + &mut relay_upstream, + Vec::new(), + "api.openai.com", + 443, + RelayOptions { + policy_name: "rest-api", + assembly_budget: WebSocketAssemblyBudget::default(), + resolver: None, + generation_guard: None, + provider_credentials: None, + target: "/", + inspector: None, + compression: WebSocketCompression::None, + middleware_session: Some(session), + middleware_context: None, + }, + ) + .await + }); + + client_app + .write_all(&masked_frame(true, OPCODE_CLOSE, &payload)) + .await + .expect("send invalid close frame"); + client_app.flush().await.expect("flush invalid close frame"); + + let upstream_close = read_one_frame(&mut upstream_app).await; + assert_eq!(upstream_close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes( + decode_masked_payload(&upstream_close)[..2] + .try_into() + .expect("upstream close code"), + ), + expected_close_code + ); + let client_close = read_one_frame(&mut client_app).await; + assert_eq!(client_close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes(client_close[2..4].try_into().expect("client close code")), + expected_close_code + ); + + relay + .await + .expect("join relay") + .expect_err("invalid close frame must terminate relay"); + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionEnd( + openshell_core::proto::WebSocketSessionEndReason::ProtocolError, + )) + )); + assert!( + observed.try_recv().is_err(), + "control-frame failure must not invoke middleware" + ); + + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware server") + .expect("middleware server"); + } + + #[tokio::test] + async fn invalid_close_frames_close_both_peers_and_report_protocol_session_end() { + assert_invalid_close_termination(vec![0x03], 1002).await; + assert_invalid_close_termination(close_payload(1005, b""), 1002).await; + assert_invalid_close_termination(close_payload(1000, &[0xff]), 1007).await; + } + + #[test] + fn invalid_close_frames_have_stable_telemetry_classes() { + let cases = [ + ( + vec![0x03], + WebSocketTerminationCause::ProtocolError, + FrameFailureClass::InvalidCloseFrame, + 1002, + ), + ( + close_payload(1005, b""), + WebSocketTerminationCause::ProtocolError, + FrameFailureClass::InvalidCloseFrame, + 1002, + ), + ( + close_payload(1000, &[0xff]), + WebSocketTerminationCause::InvalidUtf8, + FrameFailureClass::InvalidUtf8, + 1007, + ), + ]; + + for (payload, expected_cause, expected_class, expected_close_code) in cases { + let frame_error = + validate_close_payload(&payload).expect_err("close payload must be invalid"); + let termination = WebSocketTermination::from(frame_error); + assert_eq!(termination.cause, expected_cause); + assert_eq!(termination.failure_class, Some(expected_class)); + assert_eq!(termination.cause.close_code(), Some(expected_close_code)); + + let event = + protocol_failure_event("gateway.example.test", 443, "test-policy", expected_class); + assert_eq!( + event.base().status_detail.as_deref(), + Some(expected_class.as_str()) + ); + } + } + + #[tokio::test] + async fn partial_control_payload_eof_is_peer_disconnect_without_generated_close() { + let (mut session, mut observed, shutdown_tx, server_task) = + recording_middleware_session("wss").await; + assert!(session.start("").await.allowed); + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionStart) + )); + + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + let relay = tokio::spawn(async move { + relay_with_options( + &mut relay_client, + &mut relay_upstream, + Vec::new(), + "api.openai.com", + 443, + RelayOptions { + policy_name: "rest-api", + assembly_budget: WebSocketAssemblyBudget::default(), + resolver: None, + generation_guard: None, + provider_credentials: None, + target: "/", + inspector: None, + compression: WebSocketCompression::None, + middleware_session: Some(session), + middleware_context: None, + }, + ) + .await + }); + + client_app + .write_all(&[0x80 | OPCODE_CLOSE, 0x80 | 2, 0x37, 0xfa, 0x21, 0x3d]) + .await + .expect("send truncated close frame"); + drop(client_app); + + let mut upstream_output = Vec::new(); + upstream_app + .read_to_end(&mut upstream_output) + .await + .expect("read upstream shutdown"); + assert!( + upstream_output.is_empty(), + "peer EOF must not generate an upstream close frame" + ); + relay + .await + .expect("join relay") + .expect_err("truncated payload must end relay"); + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionEnd( + openshell_core::proto::WebSocketSessionEndReason::PeerDisconnect, + )) + )); + + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware server") + .expect("middleware server"); + } + + #[tokio::test] + async fn denied_websocket_session_start_reports_middleware_failure_before_close() { + let (session, mut observed, shutdown_tx, server_task) = + recording_middleware_session("wss").await; + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + + crate::l7::relay::handle_upgrade( + &mut relay_client, + &mut relay_upstream, + Vec::new(), + "api.openai.com", + 443, + crate::l7::relay::UpgradeRelayOptions { + websocket_request: true, + assembly_budget: Some(WebSocketAssemblyBudget::default()), + middleware_session: Some(session), + selected_subprotocol: Some("x".repeat(257)), + ..Default::default() + }, + ) + .await + .expect("denied session start closes cleanly"); + + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionEnd( + openshell_core::proto::WebSocketSessionEndReason::MiddlewareFailure, + )) + )); + assert!( + observed.try_recv().is_err(), + "session start failure must send exactly one terminal event" + ); + + let client_close = read_one_frame(&mut client_app).await; + assert_eq!(client_close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes(client_close[2..4].try_into().expect("client close code")), + 1008 + ); + let upstream_close = read_one_frame(&mut upstream_app).await; + assert_eq!(upstream_close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes( + decode_masked_payload(&upstream_close)[..2] + .try_into() + .expect("upstream close code"), + ), + 1008 + ); + + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware server") + .expect("middleware server"); + } + + #[tokio::test] + async fn selected_middleware_reports_binary_gap_and_inspects_later_text_at_next_sequence() { + let (session, mut observed, shutdown_tx, server_task) = + recording_middleware_session("wss").await; + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + let relay = tokio::spawn(async move { + crate::l7::relay::handle_upgrade( + &mut relay_client, + &mut relay_upstream, + Vec::new(), + "api.openai.com", + 443, + crate::l7::relay::UpgradeRelayOptions { + websocket_request: true, + assembly_budget: Some(WebSocketAssemblyBudget::default()), + ctx: Some(&L7EvalContext { + host: "api.openai.com".into(), + port: 443, + policy_name: "rest-api".into(), + ..Default::default() + }), + policy_name: "rest-api".into(), + middleware_session: Some(session), + ..Default::default() + }, + ) + .await + }); + + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionStart) + )); + + let binary = masked_frame(true, OPCODE_BINARY, &[0, 1, 2, 3, 255]); + let text = masked_frame(true, OPCODE_TEXT, br#"{"type":"response.create"}"#); + client_app + .write_all(&binary) + .await + .expect("send binary message"); + client_app + .write_all(&text) + .await + .expect("send text message"); + + assert_eq!(read_one_frame(&mut upstream_app).await, binary); + assert_eq!( + decode_masked_text_frame(&read_one_frame(&mut upstream_app).await), + r#"{"type":"response.create"}"# + ); + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::Message { + sequence: 2, + payload, + }) if payload == r#"{"type":"response.create"}"# + )); + + drop(client_app); + drop(upstream_app); + tokio::time::timeout(std::time::Duration::from_secs(2), relay) + .await + .expect("relay should stop") + .expect("join relay") + .expect("relay result"); + + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware server") + .expect("middleware server"); + } + + async fn assert_middleware_only_relay_observes_reload(scheme: &str, fragmented: bool) { + use openshell_supervisor_middleware::MiddlewareRegistry; + + let (session, mut observed, shutdown_tx, server_task) = + recording_middleware_session(scheme).await; + let engine = Arc::new( + OpaEngine::from_strings(TEST_POLICY, "network_policies: {}\n").expect("test policy"), + ); + let generation_guard = engine + .generation_guard(engine.current_generation()) + .expect("generation guard"); + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + let port = if scheme == "wss" { 443 } else { 80 }; + let relay = tokio::spawn(async move { + crate::l7::relay::handle_upgrade( + &mut relay_client, + &mut relay_upstream, + Vec::new(), + "api.openai.com", + port, + crate::l7::relay::UpgradeRelayOptions { + websocket_request: true, + assembly_budget: Some(WebSocketAssemblyBudget::default()), + generation_guard: Some(&generation_guard), + ctx: Some(&L7EvalContext { + host: "api.openai.com".into(), + port, + policy_name: "rest-api".into(), + ..Default::default() + }), + policy_name: "rest-api".into(), + middleware_session: Some(session), + ..Default::default() + }, + ) + .await + }); + + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionStart) + )); + let stale_frame = if fragmented { + masked_frame(true, OPCODE_CONTINUATION, b"message") + } else { + masked_frame(true, OPCODE_TEXT, b"stale-message") + }; + if fragmented { + client_app + .write_all(&masked_frame(false, OPCODE_TEXT, b"stale-")) + .await + .expect("send initial fragment"); + } else { + client_app + .write_all(&stale_frame[..7]) + .await + .expect("send frame header and partial payload"); + } + + engine + .replace_middleware_registry(MiddlewareRegistry::default()) + .expect("invalidate generation"); + let stale_input = if fragmented { + &stale_frame[..6] + } else { + &stale_frame[7..] + }; + client_app + .write_all(stale_input) + .await + .expect("send stale data frame"); + + let upstream_close = read_one_frame(&mut upstream_app).await; + assert_eq!(upstream_close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes( + decode_masked_payload(&upstream_close)[..2] + .try_into() + .expect("upstream close code"), + ), + 1012 + ); + let client_close = read_one_frame(&mut client_app).await; + assert_eq!(client_close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes(client_close[2..4].try_into().expect("client close code")), + 1012 + ); + let error = relay + .await + .expect("join relay") + .expect_err("stale generation must terminate relay"); + assert!(error.to_string().contains("policy generation is stale")); + match observed.recv().await { + Some(ObservedWebSocketRequest::SessionEnd( + openshell_core::proto::WebSocketSessionEndReason::PolicyReload, + )) => {} + Some(ObservedWebSocketRequest::Message { payload, .. }) => { + panic!("stale message leaked {} bytes to middleware", payload.len()); + } + other => panic!("unexpected middleware lifecycle event: {other:?}"), + } + assert!( + observed.try_recv().is_err(), + "stale data must not reach middleware" + ); + + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware server") + .expect("middleware server"); + } + + #[tokio::test] + async fn middleware_only_rest_wss_relay_observes_policy_reload() { + assert_middleware_only_relay_observes_reload("wss", false).await; + } + + #[tokio::test] + async fn middleware_only_rest_ws_relay_stops_fragment_after_policy_reload() { + assert_middleware_only_relay_observes_reload("ws", true).await; + } + + #[tokio::test] + async fn reload_during_middleware_evaluation_blocks_credentials_and_payload() { + use openshell_supervisor_middleware::MiddlewareRegistry; + + let message_received = Arc::new(tokio::sync::Notify::new()); + let release_message = Arc::new(tokio::sync::Notify::new()); + let (session, mut observed, shutdown_tx, server_task) = + recording_middleware_session_with_controls( + "wss", + Some(Arc::clone(&message_received)), + Some(Arc::clone(&release_message)), + ) + .await; + let engine = Arc::new( + OpaEngine::from_strings(TEST_POLICY, "network_policies: {}\n").expect("test policy"), + ); + let generation_guard = engine + .generation_guard(engine.current_generation()) + .expect("generation guard"); + let assembly_budget = engine.websocket_assembly_budget(); + let (child_env, resolver) = resolver(); + let placeholder = child_env + .get("DISCORD_BOT_TOKEN") + .expect("credential placeholder") + .clone(); + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + let relay = tokio::spawn(async move { + crate::l7::relay::handle_upgrade( + &mut relay_client, + &mut relay_upstream, + Vec::new(), + "api.openai.com", + 443, + crate::l7::relay::UpgradeRelayOptions { + websocket_request: true, + websocket: crate::l7::relay::WebSocketUpgradeBehavior { + credential_rewrite: true, + ..Default::default() + }, + assembly_budget: Some(assembly_budget), + secret_resolver: Some(Arc::new(resolver)), + generation_guard: Some(&generation_guard), + policy_name: "rest-api".into(), + middleware_session: Some(session), + ..Default::default() + }, + ) + .await + }); + + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionStart) + )); + let payload = format!(r#"{{"authorization":"{placeholder}"}}"#); + client_app + .write_all(&masked_frame(true, OPCODE_TEXT, payload.as_bytes())) + .await + .expect("send credential-bearing message"); + message_received.notified().await; + + engine + .replace_middleware_registry(MiddlewareRegistry::default()) + .expect("invalidate generation"); + release_message.notify_one(); + + let upstream_close = read_one_frame(&mut upstream_app).await; + assert_eq!(upstream_close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes( + decode_masked_payload(&upstream_close)[..2] + .try_into() + .expect("upstream close code"), + ), + 1012 + ); + assert!( + !String::from_utf8_lossy(&upstream_close).contains("real-token"), + "resolved credential must not reach upstream" + ); + let error = relay + .await + .expect("join relay") + .expect_err("stale generation must terminate relay"); + assert!(error.to_string().contains("policy generation is stale")); + + let mut end_reason = None; + while let Some(event) = observed.recv().await { + if let ObservedWebSocketRequest::SessionEnd(reason) = event { + end_reason = Some(reason); + break; + } + } + assert_eq!( + end_reason, + Some(openshell_core::proto::WebSocketSessionEndReason::PolicyReload) + ); + + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware server") + .expect("middleware server"); + } + + #[tokio::test] + async fn pre_upgrade_reload_finalizes_session_as_policy_reload() { + use openshell_supervisor_middleware::MiddlewareRegistry; + + let (session, mut observed, shutdown_tx, server_task) = + recording_middleware_session("wss").await; + let engine = + OpaEngine::from_strings(TEST_POLICY, "network_policies: {}\n").expect("test policy"); + let generation_guard = engine + .generation_guard(engine.current_generation()) + .expect("generation guard"); + engine + .replace_middleware_registry(MiddlewareRegistry::default()) + .expect("invalidate generation"); + let mut session = Some(session); + + crate::l7::relay::finalize_websocket_pre_upgrade( + &mut session, + &generation_guard, + "api.openai.com", + 443, + "rest-api", + Ok(crate::l7::provider::RelayOutcome::Reusable), + ) + .await + .expect_err("reload before upgrade must terminate"); + assert!(session.is_none()); + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionEnd( + openshell_core::proto::WebSocketSessionEndReason::PolicyReload + )) + )); + + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware server") + .expect("middleware server"); + } + + #[tokio::test] + async fn reload_after_forwarded_upgrade_uses_typed_close_path() { + use openshell_supervisor_middleware::MiddlewareRegistry; + + let (session, mut observed, shutdown_tx, server_task) = + recording_middleware_session("wss").await; + let engine = + OpaEngine::from_strings(TEST_POLICY, "network_policies: {}\n").expect("test policy"); + let generation_guard = engine + .generation_guard(engine.current_generation()) + .expect("generation guard"); + engine + .replace_middleware_registry(MiddlewareRegistry::default()) + .expect("invalidate generation"); + let mut session = Some(session); + let upgrade_response = b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n"; + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + relay_client + .write_all(upgrade_response) + .await + .expect("forward upgrade response"); + + let outcome = crate::l7::relay::finalize_websocket_pre_upgrade( + &mut session, + &generation_guard, + "api.openai.com", + 443, + "rest-api", + Ok(crate::l7::provider::RelayOutcome::Upgraded { + overflow: Vec::new(), + websocket_permessage_deflate: false, + websocket_subprotocol: None, + }), + ) + .await + .expect("upgraded outcome must reach typed close path"); + let crate::l7::provider::RelayOutcome::Upgraded { + overflow, + websocket_permessage_deflate, + websocket_subprotocol, + } = outcome + else { + panic!("expected upgraded outcome") + }; + + let error = crate::l7::relay::handle_upgrade( + &mut relay_client, + &mut relay_upstream, + overflow, + "api.openai.com", + 443, + crate::l7::relay::UpgradeRelayOptions { + websocket_request: true, + websocket: crate::l7::relay::WebSocketUpgradeBehavior { + permessage_deflate: websocket_permessage_deflate, + ..Default::default() + }, + assembly_budget: Some(WebSocketAssemblyBudget::default()), + generation_guard: Some(&generation_guard), + policy_name: "rest-api".into(), + middleware_session: session.take(), + selected_subprotocol: websocket_subprotocol, + ..Default::default() + }, + ) + .await + .expect_err("stale upgraded connection must close"); + assert!(error.to_string().contains("policy generation is stale")); + + let mut client_output = Vec::new(); + client_app + .read_to_end(&mut client_output) + .await + .expect("read upgrade and close"); + assert_eq!(&client_output[..upgrade_response.len()], upgrade_response); + assert_eq!( + &client_output[upgrade_response.len()..], + &[0x88, 0x02, 0x03, 0xf4] + ); + let upstream_close = read_one_frame(&mut upstream_app).await; + assert_eq!(upstream_close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes( + decode_masked_payload(&upstream_close)[..2] + .try_into() + .expect("upstream close code"), + ), + 1012 + ); + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionEnd( + openshell_core::proto::WebSocketSessionEndReason::PolicyReload + )) + )); + + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware server") + .expect("middleware server"); + } + + #[tokio::test] + async fn graphql_policy_denial_reports_policy_denial_to_middleware() { + let (mut session, mut observed, shutdown_tx, server_task) = + recording_middleware_session("wss").await; + assert!(session.start("").await.allowed); + assert!(matches!( + observed.recv().await, + Some(ObservedWebSocketRequest::SessionStart) + )); + + let engine = OpaEngine::from_strings(TEST_POLICY, GRAPHQL_WS_POLICY) + .expect("GraphQL WebSocket policy should load"); + let network_input = NetworkInput { + host: "realtime.graphql.test".into(), + port: 443, + binary_path: PathBuf::from("/usr/bin/node"), + binary_sha256: "unused".into(), + ancestors: vec![], + cmdline_paths: vec![], + }; + let generation = engine + .evaluate_network_action_with_generation(&network_input) + .expect("network action should evaluate") + .1; + let tunnel_engine = engine + .clone_engine_for_tunnel(generation) + .expect("tunnel engine"); + let ctx = L7EvalContext { + host: "realtime.graphql.test".into(), + port: 443, + policy_name: "graphql_ws".into(), + binary_path: "/usr/bin/node".into(), + ..Default::default() + }; + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + let relay = tokio::spawn(async move { + relay_with_options( + &mut relay_client, + &mut relay_upstream, + Vec::new(), + "realtime.graphql.test", + 443, + RelayOptions { + policy_name: "graphql_ws", + assembly_budget: WebSocketAssemblyBudget::default(), + resolver: None, + generation_guard: Some(tunnel_engine.generation_guard()), + provider_credentials: None, + target: "/graphql", + inspector: Some(InspectionOptions { + engine: &tunnel_engine, + ctx: &ctx, + enforcement: EnforcementMode::Enforce, + target: "/graphql".into(), + query_params: HashMap::new(), + graphql_policy: true, + }), + compression: WebSocketCompression::None, + middleware_session: Some(session), + middleware_context: Some(&ctx), + }, + ) + .await + }); + + let payload = + br#"{"type":"subscribe","id":"1","payload":{"query":"query Admin { adminAuditLog }"}}"#; + client_app + .write_all(&masked_frame(true, OPCODE_TEXT, payload)) + .await + .expect("send policy-denied message"); + + let upstream_close = read_one_frame(&mut upstream_app).await; + assert_eq!( + u16::from_be_bytes( + decode_masked_payload(&upstream_close)[..2] + .try_into() + .expect("upstream close code"), + ), + 1008 + ); + let client_close = read_one_frame(&mut client_app).await; + assert_eq!( + u16::from_be_bytes(client_close[2..4].try_into().expect("client close code")), + 1008 + ); + let error = relay + .await + .expect("join relay") + .expect_err("policy denial must terminate relay"); + assert!( + error + .to_string() + .contains("websocket GraphQL message denied") + ); + match observed.recv().await { + Some(ObservedWebSocketRequest::SessionEnd( + openshell_core::proto::WebSocketSessionEndReason::PolicyDenial, + )) => {} + Some(ObservedWebSocketRequest::Message { payload, .. }) => { + panic!( + "built-in policy denial leaked {} bytes to middleware", + payload.len() + ); + } + other => panic!("unexpected middleware lifecycle event: {other:?}"), + } + + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware server") + .expect("middleware server"); + } + + #[tokio::test] + async fn parsed_relay_sends_redacted_openai_event_to_upstream() { + use openshell_core::proto::SupervisorMiddlewareService; + use openshell_supervisor_middleware::{ChainEntry, MiddlewareRegistry, OnError}; + + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind WebSocket middleware"); + let address = listener.local_addr().expect("middleware address"); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tonic::transport::Server::builder() + .add_service(SupervisorMiddlewareServer::new( + OpenAiWebSocketRedactor::default(), + )) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }); + let server_task = tokio::spawn(server); + let registry = MiddlewareRegistry::connect_services( + Vec::new(), + vec![SupervisorMiddlewareService { + name: "openai-redactor".into(), + grpc_endpoint: format!("http://{address}"), + max_payload_bytes: openshell_supervisor_middleware::MAX_MIDDLEWARE_PAYLOAD_BYTES + as u64, + timeout: "2s".into(), + tls_ca_cert_pem: Vec::new(), + audience: String::new(), + allow_insecure_transport: false, + }], + ) + .await + .expect("connect middleware"); + let runner = openshell_supervisor_middleware::ChainRunner::from_registry(registry); + let preflight = runner + .preflight_websocket( + &[ChainEntry { + name: "redact-openai".into(), + implementation: "openai-redactor".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }], + openshell_supervisor_middleware::WebSocketPreflightInput { + session_id: "session".into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "wss".into(), + host: "api.openai.com".into(), + port: 443, + path: "/v1/responses".into(), + requested_subprotocols: Vec::new(), + }, + ) + .await + .expect("preflight"); + let mut session = preflight.session.expect("middleware inspects session"); + assert!(session.start("").await.allowed); + + let original = br#"{"type":"response.create","response":{"input":"customer-secret"}}"#; + let client_frame = masked_frame(true, OPCODE_TEXT, original); + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + let relay = tokio::spawn(async move { + relay_with_options( + &mut relay_client, + &mut relay_upstream, + Vec::new(), + "api.openai.com", + 443, + RelayOptions { + policy_name: "openai", + assembly_budget: WebSocketAssemblyBudget::default(), + resolver: None, + generation_guard: None, + provider_credentials: None, + target: "/", + inspector: None, + compression: WebSocketCompression::None, + middleware_session: Some(session), + middleware_context: None, + }, + ) + .await + }); + + client_app + .write_all(&client_frame) + .await + .expect("send event"); + client_app.flush().await.expect("flush event"); + let upstream_frame = tokio::time::timeout( + std::time::Duration::from_secs(2), + read_one_frame(&mut upstream_app), + ) + .await + .expect("upstream receives event"); + let upstream_text = decode_masked_text_frame(&upstream_frame); + assert!(upstream_text.contains("[REDACTED]")); + assert!(!upstream_text.contains("customer-secret")); + + let denied = br#"{"type":"response.create","response":{"input":"deny-me"}}"#; + client_app + .write_all(&masked_frame(true, OPCODE_TEXT, denied)) + .await + .expect("send denied event"); + client_app.flush().await.expect("flush denied event"); + let upstream_close = tokio::time::timeout( + std::time::Duration::from_secs(2), + read_one_frame(&mut upstream_app), + ) + .await + .expect("upstream receives close"); + assert_eq!(upstream_close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes( + decode_masked_payload(&upstream_close)[..2] + .try_into() + .expect("close code"), + ), + 1008 + ); + let client_close = tokio::time::timeout( + std::time::Duration::from_secs(2), + read_one_frame(&mut client_app), + ) + .await + .expect("client receives close"); + assert_eq!(client_close[0] & 0x0f, OPCODE_CLOSE); + assert_eq!( + u16::from_be_bytes(client_close[2..4].try_into().expect("close code")), + 1008 + ); + + drop(client_app); + drop(upstream_app); + let _ = tokio::time::timeout(std::time::Duration::from_secs(2), relay).await; + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware") + .expect("serve middleware"); + } + + #[tokio::test] + async fn fully_disabled_session_bypasses_saturated_work_budget_without_rpc() { + use openshell_core::proto::SupervisorMiddlewareService; + use openshell_supervisor_middleware::{ChainEntry, MiddlewareRegistry, OnError}; + + let (observed_tx, mut observed_rx) = tokio::sync::mpsc::unbounded_channel(); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0") + .await + .expect("bind WebSocket middleware"); + let address = listener.local_addr().expect("middleware address"); + let (shutdown_tx, shutdown_rx) = tokio::sync::oneshot::channel(); + let server = tonic::transport::Server::builder() + .add_service(SupervisorMiddlewareServer::new(OpenAiWebSocketRedactor { + observed: Some(observed_tx), + close_on_first_message: true, + ..Default::default() + })) + .serve_with_incoming_shutdown(TcpListenerStream::new(listener), async { + let _ = shutdown_rx.await; + }); + let server_task = tokio::spawn(server); + let registry = MiddlewareRegistry::connect_services( + Vec::new(), + vec![SupervisorMiddlewareService { + name: "openai-redactor".into(), + grpc_endpoint: format!("http://{address}"), + max_payload_bytes: openshell_supervisor_middleware::MAX_MIDDLEWARE_PAYLOAD_BYTES + as u64, + timeout: "2s".into(), + tls_ca_cert_pem: Vec::new(), + audience: String::new(), + allow_insecure_transport: false, + }], + ) + .await + .expect("connect middleware"); + let runner = openshell_supervisor_middleware::ChainRunner::from_registry(registry); + let preflight = runner + .preflight_websocket( + &[ChainEntry { + name: "redact-openai".into(), + implementation: "openai-redactor".into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailOpen, + }], + openshell_supervisor_middleware::WebSocketPreflightInput { + session_id: "disabled-session".into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "wss".into(), + host: "api.openai.com".into(), + port: 443, + path: "/v1/responses".into(), + requested_subprotocols: Vec::new(), + }, + ) + .await + .expect("preflight"); + let mut session = preflight.session.expect("middleware inspects session"); + assert!(session.start("").await.allowed); + assert!(matches!( + observed_rx.recv().await, + Some(ObservedWebSocketRequest::SessionStart) + )); + + let failed = session + .evaluate_text(r#"{"type":"response.create"}"#.into()) + .await; + assert!(failed.allowed); + assert!(failed.invocations[0].stage_disabled); + assert!(matches!( + observed_rx.recv().await, + Some(ObservedWebSocketRequest::Message { .. }) + )); + + let mut occupied_work = Vec::new(); + for _ in 0..openshell_supervisor_middleware::MAX_CONCURRENT_MIDDLEWARE_WORK { + occupied_work.push( + runner + .reserve_middleware_work_admission() + .await + .expect("fill middleware work budget"), + ); + } + + let original = r#"{"type":"response.cancel","reason":"keep-original"}"#; + let client_frame = masked_frame(true, OPCODE_TEXT, original.as_bytes()); + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + let relay = tokio::spawn(async move { + relay_with_options( + &mut relay_client, + &mut relay_upstream, + Vec::new(), + "api.openai.com", + 443, + RelayOptions { + policy_name: "openai", + assembly_budget: WebSocketAssemblyBudget::default(), + resolver: None, + generation_guard: None, + provider_credentials: None, + target: "/", + inspector: None, + compression: WebSocketCompression::None, + middleware_session: Some(session), + middleware_context: None, + }, + ) + .await + }); + + client_app + .write_all(&client_frame) + .await + .expect("send bypassed event"); + client_app.flush().await.expect("flush bypassed event"); + let upstream_frame = tokio::time::timeout( + std::time::Duration::from_secs(2), + read_one_frame(&mut upstream_app), + ) + .await + .expect("fully disabled session bypasses saturated work"); + assert_eq!(decode_masked_text_frame(&upstream_frame), original); + assert!( + observed_rx.try_recv().is_err(), + "fully disabled session must not make another middleware RPC" + ); + + drop(occupied_work); + drop(client_app); + drop(upstream_app); + tokio::time::timeout(std::time::Duration::from_secs(2), relay) + .await + .expect("relay finishes after disconnect") + .expect("join relay") + .expect("relay"); + let _ = shutdown_tx.send(()); + server_task + .await + .expect("join middleware") + .expect("serve middleware"); + } + + #[tokio::test] + async fn parsed_relay_uses_builtin_regex_for_complete_client_text_messages() { + use openshell_supervisor_middleware::{ChainEntry, MiddlewareRegistry, OnError}; + + let registry = MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await + .expect("connect built-in middleware"); + let runner = openshell_supervisor_middleware::ChainRunner::from_registry(registry); + let preflight = runner + .preflight_websocket( + &[ChainEntry { + name: "regex-redactor".into(), + implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct::default(), + on_error: OnError::FailClosed, + }], + openshell_supervisor_middleware::WebSocketPreflightInput { + session_id: "builtin-regex-session".into(), + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "wss".into(), + host: "api.openai.com".into(), + port: 443, + path: "/v1/responses".into(), + requested_subprotocols: Vec::new(), + }, + ) + .await + .expect("preflight"); + let mut session = preflight.session.expect("built-in inspects session"); + assert!(session.start("").await.allowed); + + let original = br#"{"type":"response.create","response":{"input":"sk-ABCDEFGHIJKLMNOP"}}"#; + let (mut client_app, mut relay_client) = tokio::io::duplex(4096); + let (mut relay_upstream, mut upstream_app) = tokio::io::duplex(4096); + let relay = tokio::spawn(async move { + relay_with_options( + &mut relay_client, + &mut relay_upstream, + Vec::new(), + "api.openai.com", + 443, + RelayOptions { + policy_name: "openai", + assembly_budget: WebSocketAssemblyBudget::default(), + resolver: None, + generation_guard: None, + provider_credentials: None, + target: "/", + inspector: None, + compression: WebSocketCompression::None, + middleware_session: Some(session), + middleware_context: None, + }, + ) + .await + }); + + let split = original + .windows(b"sk-ABC".len()) + .position(|window| window == b"sk-ABC") + .expect("token prefix") + + b"sk-ABC".len(); + client_app + .write_all(&masked_frame(false, OPCODE_TEXT, &original[..split])) + .await + .expect("send initial event fragment"); + client_app + .write_all(&masked_frame(true, OPCODE_CONTINUATION, &original[split..])) + .await + .expect("send final event fragment"); + let upstream_frame = tokio::time::timeout( + std::time::Duration::from_secs(2), + read_one_frame(&mut upstream_app), + ) + .await + .expect("upstream receives event"); + let upstream_text = decode_masked_text_frame(&upstream_frame); + assert_eq!( + upstream_text, + r#"{"type":"response.create","response":{"input":"[REDACTED]"}}"# + ); + + drop(client_app); + drop(upstream_app); + tokio::time::timeout(std::time::Duration::from_secs(2), relay) + .await + .expect("relay finishes after disconnect") + .expect("join relay") + .expect("relay"); + } + + #[tokio::test] + #[ignore = "PR 2 adds return-path inspection and completes this full-duplex fixture"] + async fn pr2_full_duplex_external_middleware_vertical_slice() { + // PR 2 should extend the real relay fixture above with controllable + // server-to-client transforms plus slow, hanging, closed, duplicate, + // missing, out-of-order, and oversized middleware responses. + let deferred_faults = [ + "slow", + "hanging", + "closed", + "duplicate", + "missing", + "out-of-order", + "oversized", + ]; + assert_eq!(deferred_faults.len(), 7); + } + #[tokio::test] async fn graphql_websocket_policy_allows_subscription_operation() { let payload = r#"{"type":"subscribe","id":"1","payload":{"query":"subscription NewMessages { messageAdded }"}}"#; diff --git a/crates/openshell-supervisor-network/src/opa.rs b/crates/openshell-supervisor-network/src/opa.rs index bfbb807868..6dd92b40db 100644 --- a/crates/openshell-supervisor-network/src/opa.rs +++ b/crates/openshell-supervisor-network/src/opa.rs @@ -124,6 +124,7 @@ pub struct OpaEngine { engine: Mutex, generation: Arc, middleware_runner: RwLock, + websocket_assembly_budget: crate::l7::websocket::WebSocketAssemblyBudget, generation_tx: watch::Sender, fail_closed_reason: RwLock>, } @@ -198,6 +199,7 @@ pub struct TunnelPolicyEngine { engine: Mutex, generation_guard: PolicyGenerationGuard, middleware_runner: ChainRunner, + websocket_assembly_budget: crate::l7::websocket::WebSocketAssemblyBudget, } impl TunnelPolicyEngine { @@ -225,6 +227,12 @@ impl TunnelPolicyEngine { &self.middleware_runner } + pub(crate) fn websocket_assembly_budget( + &self, + ) -> crate::l7::websocket::WebSocketAssemblyBudget { + self.websocket_assembly_budget.clone() + } + /// Query the ordered middleware chain for a destination within this tunnel. pub fn query_middleware_chain(&self, input: &NetworkInput) -> Result> { let mut engine = self @@ -236,6 +244,12 @@ impl TunnelPolicyEngine { } impl OpaEngine { + pub(crate) fn websocket_assembly_budget( + &self, + ) -> crate::l7::websocket::WebSocketAssemblyBudget { + self.websocket_assembly_budget.clone() + } + fn with_engine(engine: regorus::Engine) -> Self { let generation = Arc::new(AtomicU64::new(0)); let (generation_tx, _) = watch::channel(0); @@ -243,6 +257,7 @@ impl OpaEngine { engine: Mutex::new(engine), generation, middleware_runner: RwLock::new(ChainRunner::default()), + websocket_assembly_budget: crate::l7::websocket::WebSocketAssemblyBudget::default(), generation_tx, fail_closed_reason: RwLock::new(None), } @@ -630,8 +645,6 @@ impl OpaEngine { .engine .into_inner() .map_err(|_| miette::miette!("lock poisoned on new engine"))?; - let new_runner = ChainRunner::from_registry(registry); - // Match clone_engine_for_tunnel's lock order (engine, then runner) so // readers can observe only the old pair or the new pair. let mut engine = self @@ -642,6 +655,7 @@ impl OpaEngine { .middleware_runner .write() .map_err(|_| miette::miette!("middleware runner lock poisoned"))?; + let new_runner = runner.with_replacement_registry(registry); *engine = new_engine; *runner = new_runner; *self @@ -711,7 +725,7 @@ impl OpaEngine { .middleware_runner .write() .map_err(|_| miette::miette!("middleware runner lock poisoned"))?; - *runner = ChainRunner::from_registry(registry); + *runner = runner.with_replacement_registry(registry); self.advance_generation(); Ok(()) } @@ -910,6 +924,7 @@ impl OpaEngine { generation_rx: self.generation_tx.subscribe(), }, middleware_runner: self.middleware_runner()?, + websocket_assembly_budget: self.websocket_assembly_budget(), }) } } @@ -7074,6 +7089,142 @@ network_policies: assert!(described[0].is_resolved()); } + #[tokio::test] + async fn middleware_session_budget_survives_atomic_registry_reload() { + let proto = test_proto(); + let engine = OpaEngine::from_proto(&proto).expect("initial load should succeed"); + let registry = MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await + .expect("built-in registry"); + engine + .replace_middleware_registry(registry) + .expect("install registry"); + let old_runner = engine.middleware_runner().expect("old runner"); + let entry = ChainEntry { + name: "regex".into(), + implementation: openshell_supervisor_middleware_builtins::BUILTIN_REGEX.into(), + order: 0, + config: prost_types::Struct { + fields: std::iter::once(( + "mode".into(), + prost_types::Value { + kind: Some(prost_types::value::Kind::StringValue("redact".into())), + }, + )) + .collect(), + }, + on_error: openshell_supervisor_middleware::OnError::FailClosed, + }; + let preflight_input = + |session_id: String| openshell_supervisor_middleware::WebSocketPreflightInput { + session_id, + request_id: "request".into(), + sandbox_id: "sandbox".into(), + scheme: "wss".into(), + host: "api.openai.com".into(), + port: 443, + path: "/v1/responses".into(), + requested_subprotocols: Vec::new(), + }; + let mut old_sessions = Vec::new(); + for index in 0..openshell_supervisor_middleware::MAX_CONCURRENT_MIDDLEWARE_SESSIONS { + let preflight = old_runner + .preflight_websocket( + std::slice::from_ref(&entry), + preflight_input(format!("old-generation-{index}")), + ) + .await + .expect("admit old-generation session"); + old_sessions.push(preflight.session.expect("built-in inspects session")); + } + + let replacement = MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await + .expect("replacement registry"); + engine + .reload_policy_and_middleware_from_proto_with_pid(&proto, 0, replacement) + .expect("atomic policy and registry reload"); + let current_runner = engine.middleware_runner().expect("current runner"); + let overflow = current_runner + .preflight_websocket( + std::slice::from_ref(&entry), + preflight_input("new-generation-overflow".into()), + ) + .await + .expect("capacity exhaustion is a typed preflight outcome"); + assert!(!overflow.allowed); + assert!(overflow.session_capacity_exhausted); + + old_sessions + .pop() + .expect("old-generation session") + .end(openshell_core::proto::WebSocketSessionEndReason::PolicyReload) + .await; + let admitted = current_runner + .preflight_websocket( + std::slice::from_ref(&entry), + preflight_input("new-generation-admitted".into()), + ) + .await + .expect("released capacity is reusable after reload"); + assert!(admitted.allowed); + assert!(admitted.session.is_some()); + } + + #[tokio::test] + async fn websocket_assembly_budget_survives_policy_reload() { + use crate::l7::websocket::{ + MAX_CONCURRENT_WEBSOCKET_ASSEMBLIES, WebSocketAssemblyAdmissionOutcome, + }; + + let proto = test_proto(); + let engine = OpaEngine::from_proto(&proto).expect("initial policy"); + let old_tunnel = engine + .clone_engine_for_tunnel(engine.current_generation()) + .expect("old tunnel"); + let old_budget = old_tunnel.websocket_assembly_budget(); + let mut old_admissions = Vec::new(); + for _ in 0..MAX_CONCURRENT_WEBSOCKET_ASSEMBLIES { + match old_budget.reserve().await.expect("reserve old assembly") { + WebSocketAssemblyAdmissionOutcome::Admitted(admission) => { + old_admissions.push(admission); + } + WebSocketAssemblyAdmissionOutcome::QueueExhausted => { + panic!("active assembly capacity exhausted too early") + } + } + } + + engine + .reload_from_proto_with_pid(&proto, 0) + .expect("policy reload"); + let new_tunnel = engine + .clone_engine_for_tunnel(engine.current_generation()) + .expect("new tunnel"); + let new_budget = new_tunnel.websocket_assembly_budget(); + let waiting = tokio::spawn(async move { new_budget.reserve().await }); + tokio::task::yield_now().await; + assert!( + !waiting.is_finished(), + "new generation must share old generation assembly capacity" + ); + + drop(old_admissions.pop()); + assert!(matches!( + waiting + .await + .expect("join waiting assembly") + .expect("waiting assembly result"), + WebSocketAssemblyAdmissionOutcome::Admitted(_) + )); + } + #[tokio::test] async fn policy_only_reload_keeps_connected_middleware_registry() { let proto = test_proto(); diff --git a/crates/openshell-supervisor-network/src/proxy.rs b/crates/openshell-supervisor-network/src/proxy.rs index 6104e0f66b..b4da286bf8 100644 --- a/crates/openshell-supervisor-network/src/proxy.rs +++ b/crates/openshell-supervisor-network/src/proxy.rs @@ -1616,7 +1616,7 @@ async fn handle_tcp_connection( relay::relay_http_stream(&mut tls_client, &mut tls_upstream, relay_context).await }; - if let Err(e) = tls_result.await { + if let Err(e) = Box::pin(tls_result).await { if is_benign_relay_error(&e) { debug!( host = %host_lc, @@ -4496,7 +4496,7 @@ async fn handle_forward_proxy( } forward_websocket_request = crate::l7::rest::request_is_websocket_upgrade(&forward_request_bytes); - websocket_extensions = crate::l7::relay::websocket_extension_mode(&l7_config.config); + websocket_extensions = crate::l7::relay::websocket_extension_mode(&l7_config.config, false); request_body_credential_rewrite = l7_config.config.protocol == crate::l7::L7Protocol::Rest && l7_config.config.request_body_credential_rewrite; forward_upgrade_config = Some(l7_config.config.clone()); @@ -4842,46 +4842,6 @@ async fn handle_forward_proxy( return Ok(()); } - // 6. Connect upstream. Plain-HTTP requests always dial the destination - // directly: only TLS (CONNECT) tunnels chain through the corporate - // proxy, since plain-HTTP forwarding would need absolute-form requests - // rather than a CONNECT tunnel. - let mut upstream = match connector.connect().await { - Ok(s) => s, - Err(e) => { - let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) - .activity(ActivityId::Fail) - .severity(SeverityId::Low) - .status(StatusId::Failure) - .http_request(HttpRequest::new( - method, - OcsfUrl::new("http", &host_lc, &telemetry_path, port), - )) - .dst_endpoint(Endpoint::from_domain(&host_lc, port)) - .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) - .actor_process( - Process::from_bypass(&binary_str, &pid_str, &ancestors_str) - .with_cmd_line(&cmdline_str), - ) - .message(format!( - "FORWARD upstream connect failed for {host_lc}:{port}: {e}" - )) - .build(); - ocsf_emit!(event); - respond( - client, - &build_json_error_response( - 502, - "Bad Gateway", - "upstream_unreachable", - &format!("connection to {host_lc}:{port} failed"), - ), - ) - .await?; - return Ok(()); - } - }; - let middleware_path = path.split_once('?').map_or(path.as_str(), |(path, _)| path); let middleware_input = crate::opa::NetworkInput { host: host_lc.clone(), @@ -4915,6 +4875,7 @@ async fn handle_forward_proxy( .await?; return Ok(()); } + let websocket_chain = forward_websocket_request.then(|| chain.clone()); if !chain.is_empty() { let middleware_runner = opa_engine.middleware_runner()?; let request = crate::l7::rest::request_from_buffered_http( @@ -4949,7 +4910,62 @@ async fn handle_forward_proxy( respond(client, &response).await?; return Ok(()); } + crate::l7::middleware::MiddlewareApplyResult::AdmissionExhausted => { + emit_activity_simple(activity_tx, true, "middleware"); + let response = build_middleware_unavailable_response(&l7_ctx.policy_name); + respond(client, &response).await?; + return Ok(()); + } + }; + } + let mut middleware_session = if let Some(chain) = websocket_chain.as_deref() { + let request = crate::l7::rest::request_from_buffered_http( + method, + middleware_path, + &upstream_target, + forward_request_bytes.clone(), + )?; + let middleware_runner = opa_engine.middleware_runner()?; + let preflight = crate::l7::relay::websocket_middleware_preflight( + &request, + chain, + &middleware_runner, + &l7_ctx, + "ws", + ) + .await; + let preflight = match preflight { + Ok(preflight) => preflight, + Err(error) => { + warn!(error = %error, "Plaintext WebSocket middleware preflight failed"); + respond( + client, + &build_json_error_response( + 502, + "Bad Gateway", + "middleware_failed", + "WebSocket middleware preflight failed", + ), + ) + .await?; + return Ok(()); + } }; + crate::l7::middleware::emit_websocket_preflight_events(&l7_ctx, &preflight); + if preflight.terminal_reason.is_some() { + let response = preflight.denial.as_ref().map_or_else( + || build_middleware_failure_response(&l7_ctx.policy_name), + |denial| build_middleware_deny_response(&l7_ctx.policy_name, denial), + ); + respond(client, &response).await?; + return Ok(()); + } + preflight.session + } else { + None + }; + if middleware_session.is_some() { + websocket_extensions = crate::l7::rest::WebSocketExtensionMode::PermessageDeflate; } forward_request_bytes = match inject_token_grant_for_forward_request( method, @@ -4967,6 +4983,11 @@ async fn handle_forward_proxy( error = %e, "token grant failed in forward proxy" ); + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::Cancellation) + .await; + } respond( client, &build_json_error_response( @@ -5022,6 +5043,11 @@ async fn handle_forward_proxy( error = %e, "credential injection failed in forward proxy" ); + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::Cancellation) + .await; + } if e.is_endpoint_mismatch() { emit_credential_endpoint_mismatch(&host_lc, port, policy_str); respond( @@ -5060,6 +5086,11 @@ async fn handle_forward_proxy( "Forward proxy rejected request because policy changed before relay" ); emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::PolicyReload) + .await; + } respond( client, &build_json_error_response( @@ -5072,6 +5103,81 @@ async fn handle_forward_proxy( .await?; return Ok(()); } + // Plain-HTTP requests dial the destination directly: only TLS (CONNECT) + // tunnels chain through the corporate proxy, since plain-HTTP forwarding + // would need absolute-form requests rather than a CONNECT tunnel. Dial + // only after every local authorization and transformation step so a + // rejected WebSocket preflight cannot contact the destination. + let dial_result = connector.connect().await; + let mut upstream = match dial_result { + Ok(s) => s, + Err(e) => { + let event = HttpActivityBuilder::new(openshell_ocsf::ctx::ctx()) + .activity(ActivityId::Fail) + .severity(SeverityId::Low) + .status(StatusId::Failure) + .http_request(HttpRequest::new( + method, + OcsfUrl::new("http", &host_lc, &path, port), + )) + .dst_endpoint(Endpoint::from_domain(&host_lc, port)) + .src_endpoint(Endpoint::from_ip(workload_addr.ip(), workload_addr.port())) + .actor_process( + Process::from_bypass(&binary_str, &pid_str, &ancestors_str) + .with_cmd_line(&cmdline_str), + ) + .message(format!( + "FORWARD upstream connect failed for {host_lc}:{port}: {e}" + )) + .build(); + ocsf_emit!(event); + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::UpstreamRejected) + .await; + } + respond( + client, + &build_json_error_response( + 502, + "Bad Gateway", + "upstream_unreachable", + &format!("connection to {host_lc}:{port} failed"), + ), + ) + .await?; + return Ok(()); + } + }; + + if let Err(e) = forward_generation_guard.ensure_current() { + warn!( + host = %host_lc, + port, + captured_generation = forward_generation_guard.captured_generation(), + current_generation = forward_generation_guard.current_generation(), + error = %e, + "Forward proxy rejected request because policy changed during upstream connect" + ); + emit_l7_tunnel_close_after_policy_change(&host_lc, port, e); + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::PolicyReload) + .await; + } + respond( + client, + &build_json_error_response( + 403, + "Forbidden", + "policy_denied", + &format!("{method} {host_lc}:{port}{path} not permitted by policy"), + ), + ) + .await?; + return Ok(()); + } + let credential_signing = forward_upgrade_config .as_ref() .map_or(crate::l7::CredentialSigning::None, |config| { @@ -5083,7 +5189,7 @@ async fn handle_forward_proxy( let signing_region = forward_upgrade_config .as_ref() .map_or("", |config| config.signing_region.as_str()); - let outcome = match relay_rewritten_forward_request( + let outcome_result = relay_rewritten_forward_request( method, &upstream_target, rewritten, @@ -5102,17 +5208,31 @@ async fn handle_forward_proxy( port, }, ) - .await - { - Ok(outcome) => outcome, + .await; + let outcome_result = match outcome_result { Err(report) => { if let Some(error) = report.downcast_ref::() { + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::Cancellation) + .await; + } crate::l7::relay::reject_credential_resolution(client, &l7_ctx, error).await?; return Ok(()); } - return Err(report); + Err(report) } + outcome => outcome, }; + let outcome = crate::l7::relay::finalize_websocket_pre_upgrade( + &mut middleware_session, + &forward_generation_guard, + &host_lc, + port, + policy_str, + outcome_result, + ) + .await?; // The request has now survived middleware, token grant, credential // rewriting, generation checks, and the HTTP relay. Only now record the @@ -5131,39 +5251,55 @@ async fn handle_forward_proxy( )); emit_forward_success_activity(activity_tx, l7_activity_pending); - if let crate::l7::provider::RelayOutcome::Upgraded { - overflow, - websocket_permessage_deflate, - } = outcome - { - let mut upgrade_options = if let (Some(config), Some(engine)) = ( - forward_upgrade_config.as_ref(), - forward_tunnel_engine.as_ref(), - ) { - crate::l7::relay::upgrade_options( - config, - &l7_ctx, - forward_websocket_request, - &forward_upgrade_target, - &forward_upgrade_query_params, - Some(engine), - ) - } else { - crate::l7::relay::UpgradeRelayOptions { - websocket_request: forward_websocket_request, - ..Default::default() + match outcome { + crate::l7::provider::RelayOutcome::Reusable + | crate::l7::provider::RelayOutcome::Consumed => { + if let Some(session) = middleware_session.take() { + session + .end(openshell_core::proto::WebSocketSessionEndReason::UpstreamRejected) + .await; } - }; - upgrade_options.websocket.permessage_deflate = websocket_permessage_deflate; - crate::l7::relay::handle_upgrade( - client, - &mut upstream, + } + crate::l7::provider::RelayOutcome::Upgraded { overflow, - &host_lc, - port, - upgrade_options, - ) - .await?; + websocket_permessage_deflate, + websocket_subprotocol, + } => { + let mut upgrade_options = if let (Some(config), Some(engine)) = ( + forward_upgrade_config.as_ref(), + forward_tunnel_engine.as_ref(), + ) { + crate::l7::relay::upgrade_options( + config, + &l7_ctx, + forward_websocket_request, + &forward_upgrade_target, + &forward_upgrade_query_params, + Some(engine), + ) + } else { + crate::l7::relay::UpgradeRelayOptions { + websocket_request: forward_websocket_request, + ctx: Some(&l7_ctx), + policy_name: l7_ctx.policy_name.clone(), + ..Default::default() + } + }; + upgrade_options.generation_guard = Some(&forward_generation_guard); + upgrade_options.assembly_budget = Some(opa_engine.websocket_assembly_budget()); + upgrade_options.websocket.permessage_deflate = websocket_permessage_deflate; + upgrade_options.middleware_session = middleware_session.take(); + upgrade_options.selected_subprotocol = websocket_subprotocol; + crate::l7::relay::handle_upgrade( + client, + &mut upstream, + overflow, + &host_lc, + port, + upgrade_options, + ) + .await?; + } } Ok(()) @@ -5285,6 +5421,14 @@ fn build_middleware_deny_response( } fn build_middleware_failure_response(policy_name: &str) -> Vec { + build_middleware_platform_response(policy_name, "403 Forbidden") +} + +fn build_middleware_unavailable_response(policy_name: &str) -> Vec { + build_middleware_platform_response(policy_name, "503 Service Unavailable") +} + +fn build_middleware_platform_response(policy_name: &str, status: &str) -> Vec { let body = serde_json::json!({ "error": "middleware_failed", "detail": "Request could not be processed by configured middleware", @@ -5292,7 +5436,7 @@ fn build_middleware_failure_response(policy_name: &str) -> Vec { }); let body_str = body.to_string(); format!( - "HTTP/1.1 403 Forbidden\r\n\ + "HTTP/1.1 {status}\r\n\ Content-Type: application/json\r\n\ Content-Length: {}\r\n\ Connection: close\r\n\ @@ -5382,6 +5526,96 @@ mod tests { use tokio::io::{AsyncRead, AsyncReadExt, AsyncWriteExt}; use tokio::net::{TcpListener, TcpStream}; + struct DenyWebSocketPreflight; + + #[tonic::async_trait] + impl openshell_core::middleware::SupervisorMiddlewareEndpoint for DenyWebSocketPreflight { + async fn describe( + &self, + _request: tonic::Request<()>, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::MiddlewareManifest { + name: "test/deny-websocket".into(), + service_version: "test".into(), + bindings: vec![openshell_core::proto::MiddlewareBinding { + operation: + openshell_core::proto::SupervisorMiddlewareOperation::WebsocketMessage + as i32, + phase: openshell_core::proto::SupervisorMiddlewarePhase::PreCredentials + as i32, + max_payload_bytes: 1024, + timeout: "1s".into(), + }], + expected_audience: String::new(), + }, + )) + } + + async fn validate_config( + &self, + _request: tonic::Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Ok(tonic::Response::new( + openshell_core::proto::ValidateConfigResponse { + valid: true, + reason: String::new(), + }, + )) + } + + async fn evaluate_http_request( + &self, + _request: tonic::Request, + ) -> std::result::Result< + tonic::Response, + tonic::Status, + > { + Err(tonic::Status::unimplemented("WebSocket-only test service")) + } + + async fn open_websocket_session( + &self, + mut receiver: mpsc::Receiver, + ) -> std::result::Result + { + let (responses, response_stream) = mpsc::channel(1); + tokio::spawn(async move { + while let Some(event) = receiver.recv().await { + if matches!( + event.event, + Some(openshell_core::proto::web_socket_session_event::Event::Preflight(_)) + ) { + let _ = responses + .send(Ok(openshell_core::proto::WebSocketSessionEventResult { + result: Some( + openshell_core::proto::web_socket_session_event_result::Result::PreflightDecision( + openshell_core::proto::WebSocketPreflightDecision { + action: openshell_core::proto::WebSocketPreflightAction::Deny as i32, + reason: "test denial".into(), + reason_code: "test_denial".into(), + ..Default::default() + }, + ), + ), + })) + .await; + break; + } + } + }); + Ok(Box::pin(tokio_stream::wrappers::ReceiverStream::new( + response_stream, + ))) + } + } + struct BlockingForwardMiddleware { entered: Arc, release: Arc, @@ -5397,9 +5631,10 @@ mod tests { operation: openshell_core::proto::SupervisorMiddlewareOperation::HttpRequest as i32, phase: openshell_core::proto::SupervisorMiddlewarePhase::PreCredentials as i32, - max_body_bytes: 8192, + max_payload_bytes: 8192, timeout: String::new(), }], + expected_audience: String::new(), } } @@ -5424,6 +5659,15 @@ mod tests { } } + fn non_loopback_test_ipv4() -> Option { + let socket = std::net::UdpSocket::bind("0.0.0.0:0").ok()?; + socket.connect("192.0.2.1:9").ok()?; + match socket.local_addr().ok()?.ip() { + IpAddr::V4(ip) if !ip.is_loopback() && !ip.is_unspecified() => Some(ip), + _ => None, + } + } + async fn drive_raw_request_through_handler(raw: Vec) -> Vec { let policy = include_str!("../data/sandbox-policy.rego"); let data = r#" @@ -5483,6 +5727,254 @@ network_policies: {} } } + #[tokio::test] + async fn plaintext_websocket_preflight_denial_does_not_connect_upstream() { + if !cfg!(target_os = "linux") { + eprintln!("skipping: handler identity binding requires /proc (Linux)"); + return; + } + let Some(upstream_ip) = non_loopback_test_ipv4() else { + eprintln!("skipping: no routable non-loopback IPv4 test address"); + return; + }; + + let upstream_listener = TcpListener::bind((upstream_ip, 0)) + .await + .expect("bind upstream listener"); + let upstream_port = upstream_listener.local_addr().unwrap().port(); + let executable = std::env::current_exe().expect("current executable"); + let data = format!( + r#" +network_middlewares: + deny-upgrade: + middleware: test/deny-websocket + on_error: fail_closed + endpoints: + include: ["{upstream_ip}"] +network_policies: + allow-upstream: + name: allow-upstream + endpoints: + - host: "{upstream_ip}" + port: {upstream_port} + binaries: + - {{ path: "{executable}" }} +"#, + executable = executable.display(), + ); + let engine = Arc::new( + OpaEngine::from_strings(include_str!("../data/sandbox-policy.rego"), &data) + .expect("load policy"), + ); + let registry = openshell_supervisor_middleware::MiddlewareRegistry::connect_services( + vec![openshell_supervisor_middleware::in_process_endpoint( + Arc::new(DenyWebSocketPreflight), + )], + Vec::new(), + ) + .await + .expect("connect test middleware"); + engine + .replace_middleware_registry(registry) + .expect("install test middleware"); + + let proxy_listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind proxy listener"); + let proxy_address = proxy_listener.local_addr().unwrap(); + let target = format!("http://{upstream_ip}:{upstream_port}/ws"); + let request = format!( + "GET {target} HTTP/1.1\r\nHost: {upstream_ip}:{upstream_port}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n\r\n" + ); + let client = tokio::spawn(async move { + let mut socket = TcpStream::connect(proxy_address) + .await + .expect("connect proxy"); + let mut response = Vec::new(); + socket + .read_to_end(&mut response) + .await + .expect("read proxy response"); + response + }); + let (mut proxy_connection, _) = proxy_listener.accept().await.unwrap(); + + tokio::time::timeout( + std::time::Duration::from_secs(30), + handle_forward_proxy( + "GET", + &target, + request.as_bytes(), + request.len(), + &mut proxy_connection, + engine, + Arc::new(BinaryIdentityCache::new()), + Arc::new(AtomicU32::new(std::process::id())), + None, + AgentProposals::default(), + Arc::new(None), + None, + None, + None, + None, + None, + ), + ) + .await + .expect("denied preflight must complete without an upstream response") + .expect("handle denied plaintext WebSocket upgrade"); + drop(proxy_connection); + + let response = String::from_utf8(client.await.unwrap()).expect("UTF-8 response"); + assert!( + response.contains("\"error\":\"middleware_denied\""), + "preflight must deny the upgrade: {response}" + ); + assert!( + tokio::time::timeout( + std::time::Duration::from_millis(100), + upstream_listener.accept() + ) + .await + .is_err(), + "denied preflight must not establish an upstream connection" + ); + } + + #[tokio::test] + async fn plaintext_websocket_middleware_inspects_compressed_ws_messages() { + if !cfg!(target_os = "linux") { + eprintln!("skipping: handler identity binding requires /proc (Linux)"); + return; + } + let Some(upstream_ip) = non_loopback_test_ipv4() else { + eprintln!("skipping: no routable non-loopback IPv4 test address"); + return; + }; + + let upstream_listener = TcpListener::bind((upstream_ip, 0)) + .await + .expect("bind upstream listener"); + let upstream_port = upstream_listener.local_addr().unwrap().port(); + let executable = std::env::current_exe().expect("current executable"); + let data = format!( + r#" +network_middlewares: + redact: + middleware: openshell/regex + on_error: fail_closed + endpoints: + include: ["{upstream_ip}"] +network_policies: + allow-upstream: + name: allow-upstream + endpoints: + - host: "{upstream_ip}" + port: {upstream_port} + binaries: + - {{ path: "{executable}" }} +"#, + executable = executable.display(), + ); + let engine = Arc::new( + OpaEngine::from_strings(include_str!("../data/sandbox-policy.rego"), &data) + .expect("load policy"), + ); + let registry = openshell_supervisor_middleware::MiddlewareRegistry::connect_services( + openshell_supervisor_middleware_builtins::services(), + Vec::new(), + ) + .await + .expect("connect built-in middleware"); + engine + .replace_middleware_registry(registry) + .expect("install built-in middleware"); + + let upstream = tokio::spawn(async move { + let (mut socket, _) = upstream_listener.accept().await.unwrap(); + let request = read_http_headers_unbounded(&mut socket).await; + let request = String::from_utf8_lossy(&request); + assert!(request.starts_with("GET /ws HTTP/1.1\r\n")); + assert!(request.contains( + "Sec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover\r\n" + )); + socket + .write_all( + b"HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=\r\nSec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover\r\n\r\n", + ) + .await + .unwrap(); + let frame = crate::l7::websocket::read_frame_for_test(&mut socket).await; + crate::l7::websocket::decode_compressed_masked_text_frame_for_test(&frame) + }); + + let proxy_listener = TcpListener::bind("127.0.0.1:0") + .await + .expect("bind proxy listener"); + let proxy_address = proxy_listener.local_addr().unwrap(); + let target = format!("http://{upstream_ip}:{upstream_port}/ws"); + let request = format!( + "GET {target} HTTP/1.1\r\nHost: {upstream_ip}:{upstream_port}\r\nConnection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\nSec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Extensions: permessage-deflate; client_no_context_takeover\r\n\r\n" + ); + let client = tokio::spawn(async move { + let mut socket = TcpStream::connect(proxy_address) + .await + .expect("connect proxy"); + let response = read_http_headers_unbounded(&mut socket).await; + assert!(String::from_utf8_lossy(&response).contains("101 Switching Protocols")); + socket + .write_all( + &crate::l7::websocket::compressed_masked_text_frame_for_test( + br#"{"token":"sk-1234567890abcdef"}"#, + ), + ) + .await + .unwrap(); + }); + let (mut proxy_connection, _) = proxy_listener.accept().await.unwrap(); + + let handler = tokio::spawn(async move { + handle_forward_proxy( + "GET", + &target, + request.as_bytes(), + request.len(), + &mut proxy_connection, + engine, + Arc::new(BinaryIdentityCache::new()), + Arc::new(AtomicU32::new(std::process::id())), + None, + AgentProposals::default(), + Arc::new(None), + None, + None, + None, + None, + None, + ) + .await + }); + let scenario = tokio::time::timeout(std::time::Duration::from_secs(60), async { + let (client, upstream) = tokio::join!(client, upstream); + client.expect("join plaintext WebSocket client"); + assert_eq!( + upstream.expect("join plaintext WebSocket upstream"), + r#"{"token":"[REDACTED]"}"# + ); + }) + .await; + if handler.is_finished() { + handler + .await + .expect("join plaintext WebSocket handler") + .expect("handle compressed plaintext WebSocket upgrade"); + } else { + handler.abort(); + let _ = handler.await; + } + scenario.expect("compressed plaintext WebSocket scenario should complete"); + } + #[tokio::test] async fn malformed_request_lines_are_rejected_before_connect_or_forward_dispatch() { for host in ["api.example.com", "unmatched.example.com"] { @@ -5548,6 +6040,28 @@ network_policies: {} assert!(body.get("agent_guidance").is_none()); } + #[test] + fn middleware_unavailable_response_is_complete_and_has_no_retry_hint() { + let response = build_middleware_unavailable_response("api-policy"); + let response = String::from_utf8(response).expect("UTF-8 error response"); + assert!(response.starts_with("HTTP/1.1 503 Service Unavailable\r\n")); + assert!(!response.to_ascii_lowercase().contains("retry-after")); + let (headers, body) = response.split_once("\r\n\r\n").expect("HTTP response"); + let content_length = headers + .lines() + .find_map(|line| { + line.strip_prefix("Content-Length: ") + .and_then(|value| value.parse::().ok()) + }) + .expect("Content-Length"); + assert_eq!(content_length, body.len()); + let body: serde_json::Value = serde_json::from_str(body).expect("JSON response"); + assert_eq!(body["error"], "middleware_failed"); + assert_eq!(body["policy"], "api-policy"); + assert!(body.get("middleware").is_none()); + assert!(body.get("reason_code").is_none()); + } + #[test] fn policy_deny_response_includes_reason() { let response = build_json_error_response_with_reason( @@ -6116,6 +6630,9 @@ network_policies: crate::l7::middleware::MiddlewareApplyResult::Allowed(_) => { panic!("policy-invalid transformed request must be denied") } + crate::l7::middleware::MiddlewareApplyResult::AdmissionExhausted => { + panic!("test middleware work admission must be available") + } } } @@ -6204,6 +6721,9 @@ network_policies: crate::l7::middleware::MiddlewareApplyResult::Denied { .. } => { panic!("blocking middleware should allow after release") } + crate::l7::middleware::MiddlewareApplyResult::AdmissionExhausted => { + panic!("blocking middleware should already hold admission") + } }; let credentials = endpoint_credentials_for_request( @@ -6499,14 +7019,36 @@ network_policies: } async fn read_http_headers(reader: &mut R) -> Vec { + read_http_headers_with_timeout(reader, std::time::Duration::from_secs(1)).await + } + + async fn read_http_headers_with_timeout( + reader: &mut R, + timeout: std::time::Duration, + ) -> Vec { let mut bytes = Vec::new(); let mut chunk = [0u8; 256]; loop { - let n = - tokio::time::timeout(std::time::Duration::from_secs(1), reader.read(&mut chunk)) - .await - .expect("HTTP headers should arrive") - .expect("header read should succeed"); + let n = tokio::time::timeout(timeout, reader.read(&mut chunk)) + .await + .expect("HTTP headers should arrive") + .expect("header read should succeed"); + assert!(n > 0, "stream closed before HTTP headers"); + bytes.extend_from_slice(&chunk[..n]); + if bytes.windows(4).any(|w| w == b"\r\n\r\n") { + return bytes; + } + } + } + + async fn read_http_headers_unbounded(reader: &mut R) -> Vec { + let mut bytes = Vec::new(); + let mut chunk = [0u8; 256]; + loop { + let n = reader + .read(&mut chunk) + .await + .expect("header read should succeed"); assert!(n > 0, "stream closed before HTTP headers"); bytes.extend_from_slice(&chunk[..n]); if bytes.windows(4).any(|w| w == b"\r\n\r\n") { @@ -6533,6 +7075,14 @@ network_policies: frame } + fn masked_close_code(frame: &[u8]) -> u16 { + assert_eq!(frame[0] & 0x0f, 0x08, "expected a close frame"); + assert_eq!(frame[1] & 0x7f, 2, "expected a two-byte close code"); + assert_ne!(frame[1] & 0x80, 0, "client-to-upstream close is masked"); + let decoded = [frame[6] ^ frame[2], frame[7] ^ frame[3]]; + u16::from_be_bytes(decoded) + } + async fn forward_websocket_denied_after_upgrade( config: crate::l7::L7EndpointConfig, tunnel_engine: crate::opa::TunnelPolicyEngine, @@ -6559,7 +7109,7 @@ network_policies: false, ) .expect("forward websocket request should rewrite to origin form"); - let websocket_extensions = crate::l7::relay::websocket_extension_mode(&config); + let websocket_extensions = crate::l7::relay::websocket_extension_mode(&config, false); let target = path.to_string(); let query_params = std::collections::HashMap::new(); let (mut proxy_to_upstream, mut upstream) = tokio::io::duplex(8192); @@ -6590,6 +7140,7 @@ network_policies: if let crate::l7::provider::RelayOutcome::Upgraded { overflow, websocket_permessage_deflate, + .. } = outcome { let mut options = crate::l7::relay::upgrade_options( @@ -6677,10 +7228,10 @@ network_policies: }; let query_params = std::collections::HashMap::new(); - let extensions = crate::l7::relay::websocket_extension_mode(&websocket_l7_config( - crate::l7::L7Protocol::Websocket, - true, - )); + let extensions = crate::l7::relay::websocket_extension_mode( + &websocket_l7_config(crate::l7::L7Protocol::Websocket, true), + false, + ); let options = crate::l7::relay::upgrade_options( &websocket_l7_config(crate::l7::L7Protocol::Websocket, true), &ctx, @@ -6696,6 +7247,7 @@ network_policies: ); assert!(options.websocket.credential_rewrite); assert!(options.secret_resolver.is_some()); + assert!(options.generation_guard.is_some()); assert!(options.engine.is_some()); assert!(options.ctx.is_some()); assert!(matches!( @@ -6719,7 +7271,7 @@ network_policies: }; let query_params = std::collections::HashMap::new(); let config = websocket_l7_config(crate::l7::L7Protocol::Rest, false); - let extensions = crate::l7::relay::websocket_extension_mode(&config); + let extensions = crate::l7::relay::websocket_extension_mode(&config, false); let options = crate::l7::relay::upgrade_options(&config, &ctx, true, "/ws", &query_params, None); @@ -6737,6 +7289,41 @@ network_policies: )); } + #[test] + fn rest_websocket_upgrade_carries_guard_without_message_inspector() { + let engine = OpaEngine::from_strings( + include_str!("../data/sandbox-policy.rego"), + "network_policies: {}\n", + ) + .expect("test policy"); + let tunnel_engine = engine + .clone_engine_for_tunnel(engine.current_generation()) + .expect("tunnel engine"); + let ctx = crate::l7::relay::L7EvalContext { + host: "gateway.example.test".into(), + port: 443, + policy_name: "rest_api".into(), + binary_path: "/usr/bin/node".into(), + ..Default::default() + }; + let config = websocket_l7_config(crate::l7::L7Protocol::Rest, false); + let options = crate::l7::relay::upgrade_options( + &config, + &ctx, + true, + "/ws", + &std::collections::HashMap::new(), + Some(&tunnel_engine), + ); + + assert!(matches!( + options.websocket.message_policy, + crate::l7::relay::WebSocketMessagePolicy::None + )); + assert!(options.generation_guard.is_some()); + assert!(options.engine.is_some()); + } + #[tokio::test] async fn forward_websocket_upgrade_blocks_text_frame_by_policy() { let data = r#" @@ -6775,9 +7362,10 @@ network_policies: .await; assert!(err.to_string().contains("websocket text message denied")); - assert!( - leaked.is_empty(), - "denied forward-proxy WebSocket text frames must not reach upstream" + assert_eq!( + masked_close_code(&leaked), + 1008, + "only a policy close, not the denied text frame, may reach upstream" ); } @@ -6828,9 +7416,10 @@ network_policies: .await; assert!(err.to_string().contains("websocket GraphQL message denied")); - assert!( - leaked.is_empty(), - "denied forward-proxy GraphQL WebSocket operations must not reach upstream" + assert_eq!( + masked_close_code(&leaked), + 1008, + "only a policy close, not the denied GraphQL operation, may reach upstream" ); } diff --git a/crates/openshell-supervisor-process/src/debug_rpc.rs b/crates/openshell-supervisor-process/src/debug_rpc.rs index f583d54dcd..6f885a69db 100644 --- a/crates/openshell-supervisor-process/src/debug_rpc.rs +++ b/crates/openshell-supervisor-process/src/debug_rpc.rs @@ -105,7 +105,9 @@ async fn run_get_sandbox_config(args: &[String]) -> Result { async fn run_refresh() -> Result { let mut client = open_client().await?; let resp = client - .refresh_sandbox_token(RefreshSandboxTokenRequest {}) + .refresh_sandbox_token(RefreshSandboxTokenRequest { + extension_service_names: Vec::new(), + }) .await; match resp { Ok(r) => { diff --git a/deploy/helm/openshell/README.md b/deploy/helm/openshell/README.md index 8752b863d9..93dab354b6 100644 --- a/deploy/helm/openshell/README.md +++ b/deploy/helm/openshell/README.md @@ -177,7 +177,7 @@ add `ci/values-spire.yaml` to the OpenShell release values files. | image.tag | string | `""` | Gateway image tag. Defaults to the chart appVersion when empty. | | imagePullSecrets | list | `[]` | Image pull secrets attached to gateway and helper pods. | | nameOverride | string | `"openshell"` | Override the chart name used in generated resource names. | -| networkPolicy.enabled | bool | `true` | Create a NetworkPolicy restricting SSH ingress on sandbox pods to the gateway. | +| networkPolicy.enabled | bool | `true` | Restrict SSH ingress on sandbox pods to the gateway. In managed mode, the driver applies the equivalent policy to each workspace namespace. | | nodeSelector | object | `{}` | Node selector for the gateway pod. | | openshiftRoute.annotations | object | `{}` | Extra annotations on the Route (e.g. haproxy.router.openshift.io/*). | | openshiftRoute.enabled | bool | `false` | Create an OpenShift Route with TLS passthrough. | @@ -229,6 +229,9 @@ add `ci/values-spire.yaml` to the OpenShell release values files. | server.dbUrl | string | `"sqlite:/var/openshell/openshell.db"` | Gateway database URL (used for the default SQLite backend). | | server.defaultRuntimeClassName | string | `""` | Default Kubernetes runtimeClassName for sandbox pods. Applied when a CreateSandbox request does not specify one. Empty (default) = omit the field, using the cluster's default RuntimeClass. Set to a RuntimeClass name (e.g. "kata-containers", "nvidia") to apply it to all sandboxes that don't explicitly override it. | | server.disableTls | bool | `false` | Disable TLS entirely - the server listens on plaintext HTTP. Set to true when a reverse proxy / tunnel terminates TLS at the edge. | +| server.drivers.kubernetes.operatorNamespaceFile | string | `""` | Path to a JSON file containing an array of namespace names allowed in operator mode. Hot-reloaded on change. | +| server.drivers.kubernetes.operatorNamespaceLabel | string | `""` | K8s label selector for namespace discovery in operator mode. The driver watches namespaces matching this label. | +| server.drivers.kubernetes.workspaceMode | string | `"shared"` | How workspaces map to Kubernetes namespaces. "shared" (default): all sandboxes in a single namespace. "managed": auto-creates per-workspace namespaces. "operator": uses pre-provisioned namespaces. | | server.enableLoopbackServiceHttp | bool | `true` | Enable plaintext HTTP routing for loopback sandbox service URLs on TLS-enabled gateways. | | server.enableUserNamespaces | bool | `false` | Enable Kubernetes user namespace isolation (hostUsers: false) for sandbox pods. Requires Kubernetes 1.33+ with user namespace support available (beta through 1.35, GA in 1.36+), plus a supporting container runtime and Linux 5.12+. When enabled, container UID 0 maps to an unprivileged host UID and capabilities become namespaced. | | server.externalDbSecret | string | `""` | Name of a pre-existing Opaque Secret containing a PostgreSQL connection URI (key: uri). When set, the gateway reads OPENSHELL_DB_URL from this Secret instead of using dbUrl. The Secret must contain a `uri` key, e.g. postgresql://user:pass@host:5432/dbname. | diff --git a/deploy/helm/openshell/ci/values-workspace-managed.yaml b/deploy/helm/openshell/ci/values-workspace-managed.yaml new file mode 100644 index 0000000000..e9f88846c4 --- /dev/null +++ b/deploy/helm/openshell/ci/values-workspace-managed.yaml @@ -0,0 +1,11 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# E2E overlay: deploy the gateway in managed workspace mode. +# Sandbox namespaces are auto-created as openshell-{gateway_id}-{workspace}. +server: + sandboxImagePullSecrets: + - name: e2e-regcred + drivers: + kubernetes: + workspaceMode: "managed" diff --git a/deploy/helm/openshell/ci/values-workspace-operator.yaml b/deploy/helm/openshell/ci/values-workspace-operator.yaml new file mode 100644 index 0000000000..8d895e4e98 --- /dev/null +++ b/deploy/helm/openshell/ci/values-workspace-operator.yaml @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# E2E overlay: deploy the gateway in operator workspace mode. +# Namespaces must be pre-provisioned and labeled before sandbox creation. +server: + drivers: + kubernetes: + workspaceMode: "operator" + operatorNamespaceLabel: "openshell.ai/e2e-operator-workspace=true" diff --git a/deploy/helm/openshell/templates/_helpers.tpl b/deploy/helm/openshell/templates/_helpers.tpl index 3764fa6d7a..548418abc6 100644 --- a/deploy/helm/openshell/templates/_helpers.tpl +++ b/deploy/helm/openshell/templates/_helpers.tpl @@ -247,6 +247,10 @@ Validate chart values that Helm would otherwise accept silently. {{- if and (eq $workloadKind "statefulset") (gt $replicaCount 1) (not (get $workload "allowMultiReplicaStatefulSet" | default false)) -}} {{- fail "replicaCount > 1 with workload.kind=statefulset requires workload.allowMultiReplicaStatefulSet=true; use workload.kind=deployment for external database-backed multi-replica gateways." -}} {{- end -}} +{{- $workspaceMode := .Values.server.drivers.kubernetes.workspaceMode | default "shared" -}} +{{- if not (has $workspaceMode (list "shared" "managed" "operator")) -}} +{{- fail "server.drivers.kubernetes.workspaceMode must be one of: shared, managed, operator." -}} +{{- end -}} {{- $credentialDrivers := list -}} {{- if .Values.server.credentialDrivers.kubernetesSecrets.enabled -}} {{- $credentialDrivers = append $credentialDrivers "kubernetes-secrets" -}} diff --git a/deploy/helm/openshell/templates/cert-manager-pki.yaml b/deploy/helm/openshell/templates/cert-manager-pki.yaml index 2cd8aeabbf..838534e62e 100644 --- a/deploy/helm/openshell/templates/cert-manager-pki.yaml +++ b/deploy/helm/openshell/templates/cert-manager-pki.yaml @@ -1,7 +1,6 @@ +{{- if .Values.certManager.enabled }} # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 - -{{- if .Values.certManager.enabled }} apiVersion: cert-manager.io/v1 kind: Issuer metadata: diff --git a/deploy/helm/openshell/templates/clusterrole.yaml b/deploy/helm/openshell/templates/clusterrole.yaml index 073c8835ec..eb1ed8e1d0 100644 --- a/deploy/helm/openshell/templates/clusterrole.yaml +++ b/deploy/helm/openshell/templates/clusterrole.yaml @@ -1,6 +1,7 @@ # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 +{{- $workspaceMode := .Values.server.drivers.kubernetes.workspaceMode | default "shared" }} apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: @@ -25,9 +26,124 @@ rules: - list - watch # Read namespace annotations for OpenShift SCC UID/GID range resolution. + # Managed/operator modes additionally need list+watch for cluster-wide + # namespace discovery. Managed mode needs create+delete for namespace + # lifecycle. - apiGroups: - "" resources: - namespaces verbs: - get + {{- if ne $workspaceMode "shared" }} + - list + - watch + {{- end }} + {{- if eq $workspaceMode "managed" }} + - create + - delete + {{- end }} + {{- if ne $workspaceMode "shared" }} + # Cluster-wide sandbox CRD access for managed/operator workspace modes. + - apiGroups: + - agents.x-k8s.io + resources: + - sandboxes + - sandboxes/status + verbs: + - create + - delete + - get + - list + - patch + - update + - watch + - apiGroups: + - "" + resources: + - events + verbs: + - get + - list + - watch + - apiGroups: + - "" + resources: + - pods + verbs: + - get + {{- end }} + {{- $copiedSecretNames := list }} + {{- if and (ne $workspaceMode "shared") (not .Values.server.disableTls) }} + {{- $copiedSecretNames = append $copiedSecretNames .Values.server.tls.clientTlsSecretName }} + {{- end }} + {{- if eq $workspaceMode "managed" }} + {{- range .Values.server.sandboxImagePullSecrets }} + {{- if .name }} + {{- $copiedSecretNames = append $copiedSecretNames .name }} + {{- end }} + {{- end }} + {{- end }} + {{- $copiedSecretNames = uniq $copiedSecretNames }} + {{- if $copiedSecretNames }} + # Copy only explicitly configured TLS and image-pull Secrets into workspace + # namespaces. Server-side apply authorizes these requests as patch operations. + - apiGroups: + - "" + resources: + - secrets + resourceNames: + {{- range $copiedSecretNames }} + - {{ . | quote }} + {{- end }} + verbs: + - get + - patch + # Server-side apply uses PATCH for an existing Secret, but the API server + # additionally authorizes CREATE when the named Secret does not exist yet. + # Kubernetes RBAC cannot restrict CREATE by resourceNames because create + # authorization happens before the object name is available to RBAC. Keep + # reads and mutations name-restricted above; this broader grant is required + # only to create the initial copy in a gateway-owned managed namespace. + - apiGroups: + - "" + resources: + - secrets + verbs: + - create + {{- end }} + {{- if and (ne $workspaceMode "shared") .Values.server.credentialDrivers.kubernetesSecrets.enabled }} + # The kubernetes-secrets credential driver uses dynamic hashed names in + # workspace namespaces, so Kubernetes RBAC cannot restrict resourceNames. + - apiGroups: + - "" + resources: + - secrets + verbs: + - get + - create + - patch + - delete + {{- end }} + {{- if eq $workspaceMode "managed" }} + # ServiceAccount creation in managed namespaces. + - apiGroups: + - "" + resources: + - serviceaccounts + verbs: + - create + - get + {{- if .Values.networkPolicy.enabled }} + # Apply gateway-only SSH ingress isolation in managed namespaces. + - apiGroups: + - networking.k8s.io + resources: + - networkpolicies + verbs: + - get + - create + - patch + - update + {{- end }} + {{- end }} diff --git a/deploy/helm/openshell/templates/credential-secrets-role.yaml b/deploy/helm/openshell/templates/credential-secrets-role.yaml index 72f0528cb2..f6187c9acb 100644 --- a/deploy/helm/openshell/templates/credential-secrets-role.yaml +++ b/deploy/helm/openshell/templates/credential-secrets-role.yaml @@ -1,7 +1,6 @@ +{{- if and .Values.server.credentialDrivers.kubernetesSecrets.enabled .Values.server.credentialDrivers.kubernetesSecrets.rbac.create }} # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 - -{{- if and .Values.server.credentialDrivers.kubernetesSecrets.enabled .Values.server.credentialDrivers.kubernetesSecrets.rbac.create }} apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: diff --git a/deploy/helm/openshell/templates/credential-secrets-rolebinding.yaml b/deploy/helm/openshell/templates/credential-secrets-rolebinding.yaml index 4274fa6e1a..3a9ee0bddc 100644 --- a/deploy/helm/openshell/templates/credential-secrets-rolebinding.yaml +++ b/deploy/helm/openshell/templates/credential-secrets-rolebinding.yaml @@ -1,7 +1,6 @@ +{{- if and .Values.server.credentialDrivers.kubernetesSecrets.enabled .Values.server.credentialDrivers.kubernetesSecrets.rbac.create }} # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 - -{{- if and .Values.server.credentialDrivers.kubernetesSecrets.enabled .Values.server.credentialDrivers.kubernetesSecrets.rbac.create }} apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: diff --git a/deploy/helm/openshell/templates/deployment.yaml b/deploy/helm/openshell/templates/deployment.yaml index e937979370..f94900b136 100644 --- a/deploy/helm/openshell/templates/deployment.yaml +++ b/deploy/helm/openshell/templates/deployment.yaml @@ -1,7 +1,7 @@ -# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -# SPDX-License-Identifier: Apache-2.0 {{- include "openshell.validateValues" . }} {{- if eq (include "openshell.workloadKind" .) "deployment" }} +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 apiVersion: apps/v1 kind: Deployment metadata: diff --git a/deploy/helm/openshell/templates/gateway-config.yaml b/deploy/helm/openshell/templates/gateway-config.yaml index 40f5748df4..9d24dbd917 100644 --- a/deploy/helm/openshell/templates/gateway-config.yaml +++ b/deploy/helm/openshell/templates/gateway-config.yaml @@ -135,8 +135,16 @@ data: {{- end }} [openshell.drivers.kubernetes] + workspace_mode = {{ .Values.server.drivers.kubernetes.workspaceMode | default "shared" | quote }} + gateway_id = {{ .Values.server.sandboxJwt.gatewayId | default (include "openshell.fullname" .) | quote }} grpc_endpoint = {{ include "openshell.grpcEndpoint" . | quote }} service_account_name = {{ include "openshell.sandboxServiceAccountName" . | quote }} + {{- if .Values.server.drivers.kubernetes.operatorNamespaceLabel }} + operator_namespace_label = {{ .Values.server.drivers.kubernetes.operatorNamespaceLabel | quote }} + {{- end }} + {{- if .Values.server.drivers.kubernetes.operatorNamespaceFile }} + operator_namespace_file = {{ .Values.server.drivers.kubernetes.operatorNamespaceFile | quote }} + {{- end }} supervisor_sideload_method = {{ include "openshell.supervisorSideloadMethod" . | quote }} topology = {{ .Values.supervisor.topology | default "combined" | quote }} sa_token_ttl_secs = {{ .Values.server.sandboxJwt.k8sSaTokenTtlSecs | default 3600 }} @@ -189,6 +197,11 @@ data: supervisor_image_pull_policy = {{ .Values.supervisor.image.pullPolicy | quote }} {{- end }} + [openshell.drivers.kubernetes.managed_ssh_ingress] + enabled = {{ .Values.networkPolicy.enabled }} + gateway_namespace = {{ .Release.Namespace | quote }} + gateway_pod_selector = { "app.kubernetes.io/name" = {{ include "openshell.name" . | quote }}, "app.kubernetes.io/instance" = {{ .Release.Name | quote }} } + [openshell.drivers.kubernetes.sidecar] proxy_uid = {{ .Values.supervisor.sidecar.proxyUid | default 1337 }} process_binary_aware_network_policy = {{ .Values.supervisor.sidecar.processBinaryAwareNetworkPolicy }} @@ -204,6 +217,8 @@ data: [openshell.credential_drivers.kubernetes-secrets] namespace = {{ include "openshell.credentialKubernetesSecretsNamespace" . | quote }} allow_reference_namespace = {{ .Values.server.credentialDrivers.kubernetesSecrets.allowReferenceNamespace }} + workspace_mode = {{ .Values.server.drivers.kubernetes.workspaceMode | default "shared" | quote }} + gateway_id = {{ .Values.server.sandboxJwt.gatewayId | default (include "openshell.fullname" .) | quote }} {{- end }} {{- if .Values.server.credentialDrivers.vault.enabled }} diff --git a/deploy/helm/openshell/templates/gateway.yaml b/deploy/helm/openshell/templates/gateway.yaml index f431ffbbd1..2b78595053 100644 --- a/deploy/helm/openshell/templates/gateway.yaml +++ b/deploy/helm/openshell/templates/gateway.yaml @@ -1,7 +1,6 @@ +{{- if and .Values.grpcRoute.enabled .Values.grpcRoute.gateway.create }} # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 - -{{- if and .Values.grpcRoute.enabled .Values.grpcRoute.gateway.create }} apiVersion: gateway.networking.k8s.io/v1 kind: Gateway metadata: diff --git a/deploy/helm/openshell/templates/grpcroute.yaml b/deploy/helm/openshell/templates/grpcroute.yaml index 8fde5458cd..362067fda3 100644 --- a/deploy/helm/openshell/templates/grpcroute.yaml +++ b/deploy/helm/openshell/templates/grpcroute.yaml @@ -1,7 +1,6 @@ +{{- if .Values.grpcRoute.enabled }} # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 - -{{- if .Values.grpcRoute.enabled }} apiVersion: gateway.networking.k8s.io/v1 kind: GRPCRoute metadata: diff --git a/deploy/helm/openshell/templates/role.yaml b/deploy/helm/openshell/templates/role.yaml index 5ecc4428ad..af80989072 100644 --- a/deploy/helm/openshell/templates/role.yaml +++ b/deploy/helm/openshell/templates/role.yaml @@ -1,6 +1,7 @@ +{{- $workspaceMode := .Values.server.drivers.kubernetes.workspaceMode | default "shared" -}} +{{- if eq $workspaceMode "shared" }} # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 - apiVersion: rbac.authorization.k8s.io/v1 kind: Role metadata: @@ -42,3 +43,4 @@ rules: - pods verbs: - get +{{- end }} diff --git a/deploy/helm/openshell/templates/rolebinding.yaml b/deploy/helm/openshell/templates/rolebinding.yaml index e5233f753c..381473a58b 100644 --- a/deploy/helm/openshell/templates/rolebinding.yaml +++ b/deploy/helm/openshell/templates/rolebinding.yaml @@ -1,6 +1,7 @@ +{{- $workspaceMode := .Values.server.drivers.kubernetes.workspaceMode | default "shared" -}} +{{- if eq $workspaceMode "shared" }} # SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # SPDX-License-Identifier: Apache-2.0 - apiVersion: rbac.authorization.k8s.io/v1 kind: RoleBinding metadata: @@ -16,3 +17,4 @@ subjects: - kind: ServiceAccount name: {{ include "openshell.serviceAccountName" . }} namespace: {{ .Release.Namespace }} +{{- end }} diff --git a/deploy/helm/openshell/tests/clusterrole_test.yaml b/deploy/helm/openshell/tests/clusterrole_test.yaml new file mode 100644 index 0000000000..afecada9b6 --- /dev/null +++ b/deploy/helm/openshell/tests/clusterrole_test.yaml @@ -0,0 +1,124 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +suite: ClusterRole RBAC +templates: + - templates/clusterrole.yaml +release: + name: openshell + namespace: my-namespace + +tests: + - it: grants managed namespace NetworkPolicy apply permissions + set: + server.drivers.kubernetes.workspaceMode: managed + asserts: + - contains: + path: rules + content: + apiGroups: ["networking.k8s.io"] + resources: ["networkpolicies"] + verbs: ["get", "create", "patch", "update"] + + - it: omits managed NetworkPolicy permissions when isolation is disabled + set: + server.drivers.kubernetes.workspaceMode: managed + networkPolicy.enabled: false + asserts: + - notContains: + path: rules + content: + apiGroups: ["networking.k8s.io"] + resources: ["networkpolicies"] + any: true + + - it: grants broad secret access when credential driver is enabled (operator) + set: + server.drivers.kubernetes.workspaceMode: operator + server.credentialDrivers.kubernetesSecrets.enabled: true + asserts: + - contains: + path: rules + content: + apiGroups: [""] + resources: ["secrets"] + verbs: ["get", "create", "patch", "delete"] + + - it: restricts operator TLS sync to the configured secret + set: + server.drivers.kubernetes.workspaceMode: operator + server.tls.clientTlsSecretName: custom-client-tls + asserts: + - contains: + path: rules + content: + apiGroups: [""] + resources: ["secrets"] + resourceNames: ["custom-client-tls"] + verbs: ["get", "patch"] + + - it: omits operator secret access when TLS and credential storage are disabled + set: + server.drivers.kubernetes.workspaceMode: operator + server.disableTls: true + asserts: + - notContains: + path: rules + content: + apiGroups: [""] + resources: ["secrets"] + any: true + + - it: restricts managed copies to TLS and configured image-pull secrets + set: + server.drivers.kubernetes.workspaceMode: managed + server.tls.clientTlsSecretName: custom-client-tls + server.sandboxImagePullSecrets: + - name: registry-one + - name: registry-two + asserts: + - contains: + path: rules + content: + apiGroups: [""] + resources: ["secrets"] + resourceNames: ["custom-client-tls", "registry-one", "registry-two"] + verbs: ["get", "patch"] + - contains: + path: rules + content: + apiGroups: [""] + resources: ["secrets"] + verbs: ["create"] + + - it: restricts managed copies to image-pull secrets when TLS is disabled + set: + server.drivers.kubernetes.workspaceMode: managed + server.disableTls: true + server.sandboxImagePullSecrets: + - name: registry-one + asserts: + - contains: + path: rules + content: + apiGroups: [""] + resources: ["secrets"] + resourceNames: ["registry-one"] + verbs: ["get", "patch"] + - contains: + path: rules + content: + apiGroups: [""] + resources: ["secrets"] + verbs: ["create"] + + - it: omits secrets rule entirely in shared mode + set: + server.drivers.kubernetes.workspaceMode: shared + asserts: + - notContains: + path: rules + content: + apiGroups: [""] + resources: ["secrets"] + any: true diff --git a/deploy/helm/openshell/tests/gateway_config_test.yaml b/deploy/helm/openshell/tests/gateway_config_test.yaml index 784180fcb3..afacd01eb4 100644 --- a/deploy/helm/openshell/tests/gateway_config_test.yaml +++ b/deploy/helm/openshell/tests/gateway_config_test.yaml @@ -208,6 +208,13 @@ tests: path: data["gateway.toml"] pattern: '(?ms)\[openshell\.drivers\.kubernetes\.sidecar\].*?process_binary_aware_network_policy\s*=\s*false' + - it: configures managed SSH isolation with the gateway peer + template: templates/gateway-config.yaml + asserts: + - matchRegex: + path: data["gateway.toml"] + pattern: '(?ms)\[openshell\.drivers\.kubernetes\.managed_ssh_ingress\].*?enabled\s*=\s*true.*?gateway_namespace\s*=\s*"my-namespace".*?gateway_pod_selector\s*=.*?app\.kubernetes\.io/name.*?openshell' + - it: renders sandbox image pull secrets under [openshell.drivers.kubernetes] template: templates/gateway-config.yaml set: diff --git a/deploy/helm/openshell/values.yaml b/deploy/helm/openshell/values.yaml index 4fbbf4915c..33337c768e 100644 --- a/deploy/helm/openshell/values.yaml +++ b/deploy/helm/openshell/values.yaml @@ -243,6 +243,20 @@ server: # the field, "RuntimeDefault" to force the runtime default profile, or # "Localhost/profile-name" for an operator-managed localhost profile. appArmorProfile: "Unconfined" + # Kubernetes compute driver settings. + drivers: + kubernetes: + # -- How workspaces map to Kubernetes namespaces. + # "shared" (default): all sandboxes in a single namespace. + # "managed": auto-creates per-workspace namespaces. + # "operator": uses pre-provisioned namespaces. + workspaceMode: "shared" + # -- K8s label selector for namespace discovery in operator mode. + # The driver watches namespaces matching this label. + operatorNamespaceLabel: "" + # -- Path to a JSON file containing an array of namespace names + # allowed in operator mode. Hot-reloaded on change. + operatorNamespaceFile: "" # -- Disable TLS entirely - the server listens on plaintext HTTP. # Set to true when a reverse proxy / tunnel terminates TLS at the edge. disableTls: false @@ -389,7 +403,8 @@ server: # NetworkPolicy restricting SSH ingress on sandbox pods to the gateway only. networkPolicy: - # -- Create a NetworkPolicy restricting SSH ingress on sandbox pods to the gateway. + # -- Restrict SSH ingress on sandbox pods to the gateway. In managed mode, + # the driver applies the equivalent policy to each workspace namespace. enabled: true # Built-in TLS PKI bootstrap via a pre-install/pre-upgrade hook Job. diff --git a/docs/extensibility/gateway-interceptors.mdx b/docs/extensibility/gateway-interceptors.mdx index 9fe50ef5a7..bf9656a5ed 100644 --- a/docs/extensibility/gateway-interceptors.mdx +++ b/docs/extensibility/gateway-interceptors.mdx @@ -73,7 +73,9 @@ Start the interceptor before the gateway, then register it in gateway TOML: ```toml [[openshell.gateway.interceptors]] name = "policy-governance" -grpc_endpoint = "http://127.0.0.1:18081" +grpc_endpoint = "https://governance.example:18081" +tls_ca_cert_path = "/etc/openshell/governance-ca.pem" +audience = "urn:example:governance" order = 10 failure_policy = "fail_closed" binding_policy = "allowlist" @@ -90,7 +92,15 @@ rpc = "openshell.v1.OpenShell/UpdateConfig" phases = ["validate"] ``` -The gateway supports `http://`, `https://`, and `unix://` interceptor endpoints. It calls `Describe` and builds an immutable execution plan during startup. An unavailable service, invalid manifest, or unauthorized configured binding prevents the gateway from starting. +The gateway supports `http://`, `https://`, and `unix://` interceptor endpoints. When gateway JWT signing is configured, authenticated network interceptors use `https://`; Unix sockets remain available for local integrations. HTTPS uses platform trust roots unless `tls_ca_cert_path` supplies a private CA, and normal hostname verification remains enabled. The gateway calls `Describe` and builds an immutable execution plan during startup. An unavailable service, invalid manifest, missing credential, or unauthorized configured binding prevents the gateway from starting. + +The gateway attaches a short-lived EdDSA bearer token to `Describe`, `Evaluate`, and provider-profile snapshot calls. The token uses the configured `audience` (defaulting to `urn:openshell:extension:interceptor:`) and `caller_kind: gateway`. + +Return your expected audience in the `expected_audience` field of your `Describe` manifest. After authenticated `Describe` succeeds, the gateway compares the advertised value with its operator-configured audience and refuses to start when they differ. This is a post-authentication consistency assertion, not audience discovery: a strict verifier may reject an incorrect audience before returning the manifest, in which case startup reports an authentication failure. Leave the field empty to skip the consistency check. + +Provision the trusted gateway URL, expected gateway ID, and public key or JWKS through the deployment. This operator-provisioned key material is the authoritative cold-start trust anchor. The expected issuer is exactly `openshell-gateway:`; fetching JWKS does not establish that identity by itself. After initial trust is established, `GET /.well-known/openid-configuration` and its `jwks_uri` provide steady-state key refresh and operational convenience. The document is OIDC-shaped rather than OIDC-compliant because `issuer` is the gateway identity rather than the serving URL; compare `iss` against the configured value and fetch updates only over authenticated TLS at the trusted gateway URL. Pin `alg` to `EdDSA`, require `typ` to be exactly `openshell-ext+jwt`, and validate `kid`, signature, expected issuer, exact audience, positive expiry, and caller kind. + +Set `allow_insecure_transport = true` on an interceptor to keep a plaintext `http://` endpoint working with no credential attached. The gateway logs a warning naming the interceptor at every startup, and the service cannot distinguish the gateway from any other client that can reach it. Registration is static. Restart the gateway after adding, removing, or changing an interceptor. See [Gateway Configuration](/reference/gateway-config#gateway-interceptors) for the complete field reference. @@ -163,5 +173,6 @@ The gateway emits structured evaluation logs containing the interceptor name, bi - Only explicitly allowlisted unary write RPCs are interceptable. New gateway RPCs are non-interceptable until added to the allowlist. - `current_state` is available only in the `validate` contract. The gateway does not yet populate it with method-specific state. - Registration changes require a gateway restart. -- Custom TLS roots, client authentication, service health checks, and runtime registration are not available. +- mTLS client authentication, service health checks, runtime registration, and overlapping signing-key rotation are not available. +- Extension tokens and sandbox-to-gateway tokens are signed by the same key, separated by audience and `typ`. The extension credential path cannot yet be rotated or revoked independently of sandbox admission. - Interceptors cannot receive or mutate protobuf fields marked secret. diff --git a/docs/extensibility/supervisor-middleware.mdx b/docs/extensibility/supervisor-middleware.mdx index f3bdcac9bb..42beedeff9 100644 --- a/docs/extensibility/supervisor-middleware.mdx +++ b/docs/extensibility/supervisor-middleware.mdx @@ -3,11 +3,11 @@ # SPDX-License-Identifier: Apache-2.0 title: "Supervisor Middleware" sidebar-title: "Supervisor Middleware" -description: "Configure and operate built-in and operator-run middleware for sandbox HTTP requests." +description: "Configure and operate built-in and operator-run middleware for sandbox HTTP requests and WebSocket messages." keywords: "Generative AI, Cybersecurity, AI Agents, Supervisor Middleware, Extensibility, Request Filtering" --- -Supervisor middleware adds ordered request-processing stages to allowed HTTP egress. Middleware runs after network and L7 policy admit a request and before OpenShell injects provider credentials. A stage can allow or deny the request, replace its body, add approved headers, and report audit-safe findings. +Supervisor middleware adds ordered processing stages to allowed HTTP and WebSocket egress. Middleware runs after network and L7 policy admit traffic and before OpenShell injects provider credentials. A stage can allow or deny an HTTP request or client WebSocket text message, replace its payload, add approved HTTP headers, and report audit-safe findings. Middleware selection is independent of the network policy rule that admitted the request. OpenShell matches middleware by destination host, so the same middleware applies consistently across broad, specific, user-authored, and provider-derived network policies. @@ -22,6 +22,19 @@ For each inspected HTTP request, the supervisor: 5. Re-checks body-aware protocol policy (GraphQL, JSON-RPC, MCP) after each stage that replaces the body. Every middleware receives a payload the policy admits, and a transformation cannot smuggle a denied or unparseable operation to a later stage or the upstream. 6. Applies allowed transformations, injects provider credentials, and forwards the request. +For an RFC 6455 upgrade over `ws://` or `wss://`, the supervisor first finds every host-matched attachment, then selects only implementations that advertise `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. It opens one ordered, phase-specific `EvaluateWebSocketSession` stream per selected stage. OpenShell sends `WebSocketSessionEvent` values, while the service returns `WebSocketSessionEventResult` values only for preflight and message events; session start and end are notifications. Future upstream-to-client inspection uses the same RPC with `PRE_RETURN`; an implementation that advertises both phases receives two independent streams for the WebSocket session. An attachment without the selected binding can still inspect the HTTP upgrade request when it advertises the HTTP binding, but it is not a failed WebSocket stage. OpenShell allows post-upgrade traffic and emits an informational `binding_not_selected` coverage event for that attachment. + +1. A preflight before the upgrade is sent upstream. The stage chooses `INSPECT`, voluntary `SKIP`, or authoritative `DENY` and may return a bounded diagnostic reason, stable reason code, findings, and metadata. OpenShell runs selected preflights concurrently; any `DENY` rejects the upgrade regardless of `on_error`. +2. A session-start event after the upstream accepts the upgrade, including the negotiated subprotocol. +3. Complete client-to-upstream text messages in sequence order. OpenShell reassembles fragmented messages and decompresses negotiated `permessage-deflate` messages before evaluation. +4. A best-effort session-end event when the stage stream remains writable. OpenShell attempts at most one terminal event for each opened stream, including streams opened during a preflight that rejects the upgrade before session start. + +The protobuf represents each logical message with a `text` or `binary` payload variant. Text uses the protobuf `string` type, so invalid UTF-8 cannot enter the middleware contract. Results use an optional matching replacement variant: absence preserves the input, while presence represents a replacement even when its content is empty. OpenShell rejects attempts to change the message type. Allowed replacements are re-framed, re-compressed when required, and forwarded. Binary messages, control frames, and upstream-to-client traffic remain uninspected. Binary messages pass through under both `on_error` modes. For each active selected stage, OpenShell emits an informational `unsupported_message_type` coverage event and advances the session-global sequence; the next text message can therefore reach the stage with a valid sequence gap. + +The network supervisor reserves process-wide assembly capacity before buffering every parsed WebSocket text message, even when no middleware is selected. At most 32 assemblies run while 64 additional callers wait without buffering payload bytes. When both bounds are full, OpenShell closes the WebSocket with code `1013` before reading the new message payload. A text message may contain at most 4,096 fragments, must make input progress within 30 seconds, and must finish assembly within 2 minutes. Forwarding the completed text frame must finish within another 2 minutes. The assembly budget lasts for the supervisor process lifetime, so policy reloads do not reset its capacity. + +Active middleware sessions additionally reserve shared middleware capacity before buffering WebSocket text, and HTTP middleware reserves the same capacity before buffering request bodies; at most 32 evaluations run and 64 additional unbuffered callers wait for capacity. When both middleware bounds are full, OpenShell sheds an HTTP request with `503 Service Unavailable` before reading its body. Persistent middleware streams use a separate process-wide budget of 32 sessions. WebSocket session admission does not wait: if the budget is full, OpenShell applies each selected config's `on_error` behavior before opening a stream. + Because each transformed body is re-checked before the next stage runs, a middleware hook always receives a request that satisfies the sandbox policy. A stage whose output the policy rejects stops the chain; under `enforcement: audit` the rejection is logged and the request proceeds. If post-transformation policy evaluation itself fails, OpenShell denies the request and emits a high-severity detection finding. This failure is separate from middleware `on_error` because the middleware completed successfully; the sandbox policy could not validate its output. @@ -30,14 +43,14 @@ Middleware receives the request before credential injection. Operator-run servic ## Choose a Middleware Type -| Type | Registration | Body limit | Deployment | +| Type | Registration | Payload limit | Deployment | | --- | --- | --- | --- | | Built-in | None | Defined by OpenShell | Runs inside the supervisor | | Operator-run service | Required in gateway TOML | Set by the operator, up to the service capability | Runs as a separate service reachable by the gateway and supervisors | -`openshell/regex` is an example built-in middleware. It replaces only simple, self-contained token patterns in UTF-8 request bodies; the initial pattern recognizes `sk-` tokens. It does not infer values from keyword assignments such as JSON `password` fields. This best-effort text transformation is not parser-aware and does not guarantee that it will detect or fully remove sensitive values. Its `config` accepts one field, `mode: redact`, which is also the default when the field is omitted. Unknown config fields and non-string values are rejected at policy validation. Custom expressions are not configurable yet. +`openshell/regex` is an example built-in middleware. It replaces only simple, self-contained token patterns in UTF-8 HTTP bodies and client WebSocket text messages; the initial pattern recognizes `sk-` tokens. It does not infer values from keyword assignments such as JSON `password` fields. This best-effort text transformation is not parser-aware and does not guarantee that it will detect or fully remove sensitive values. Its `config` accepts one field, `mode: redact`, which is also the default when the field is omitted. Unknown config fields and non-string values are rejected at policy validation. Custom expressions are not configurable yet. -Operator-run services expose bindings for supported operation and phase pairs. A binding is identified by its operation and phase; V1 supports only `HttpRequest/pre_credentials`. Policies attach the complete middleware by its operator-owned gateway registration name. +Operator-run services expose bindings for supported operation and phase pairs. A binding is identified by its operation and phase. V1 supports `HttpRequest/pre_credentials` and `WebSocketMessage/pre_credentials`; a service may expose either or both. Policies attach the complete middleware by its operator-owned gateway registration name. ## Register a Middleware Service @@ -46,24 +59,54 @@ Start an operator-run service before starting the gateway, then add a registrati ```toml [[openshell.supervisor.middleware]] name = "local-content-guard" -grpc_endpoint = "http://host.openshell.internal:50051" -max_body_bytes = 262144 +grpc_endpoint = "https://content-guard.example:50051" +tls_ca_cert_path = "/etc/openshell/content-guard-ca.pem" +audience = "urn:example:content-guard" +max_payload_bytes = 262144 timeout = "500ms" ``` | Field | Description | | --- | --- | | `name` | Operator-owned registration name used by policy attachments and diagnostics. Names must be unique, and `openshell/` is reserved for built-ins. | -| `grpc_endpoint` | Service address reachable from both the gateway and sandbox supervisors. Supports plaintext `http://` and TLS `https://` with platform trust roots. | -| `max_body_bytes` | Operator limit applied to every binding exposed by the service, up to the 4 MiB platform maximum. | +| `grpc_endpoint` | Service address reachable from both the gateway and sandbox supervisors. Authenticated extensions use TLS `https://`. | +| `tls_ca_cert_path` | Optional PEM trust roots for a private HTTPS service. Custom roots replace platform roots and retain hostname verification. | +| `audience` | Exact audience expected by the service. Defaults to `urn:openshell:extension:middleware:`. | +| `allow_insecure_transport` | Opt this registration out of extension authentication, permitting a plaintext `http://` endpoint with no bearer credential. Defaults to `false`. Development and trusted-network deployments only. | +| `max_payload_bytes` | Shared operator limit applied to inspectable logical payloads across every binding exposed by the service, up to the 4 MiB platform maximum. It caps HTTP bodies and complete WebSocket text messages. | | `timeout` | Optional service-wide RPC timeout using an integer with an `ms` or `s` suffix. Defaults to `500ms`; valid values range from `10ms` through `30s`. | -Each binding returned by `Describe` may advertise a shorter `timeout` using the same syntax and bounds. The operator-configured service timeout is a ceiling: OpenShell uses the smaller of the binding and service values. An omitted binding timeout inherits the service setting, and an omitted service setting uses the 500 ms platform default. OpenShell rejects an invalid timeout before accepting the manifest. The service timeout applies to `Describe`, while the effective binding timeout applies to `ValidateConfig` and `EvaluateHttpRequest`. +Each binding returned by `Describe` may advertise a shorter `timeout` using the same syntax and bounds. The operator-configured service timeout is a ceiling: OpenShell uses the smaller of the binding and service values. An omitted binding timeout inherits the service setting, and an omitted service setting uses the 500 ms platform default. OpenShell rejects an invalid timeout before accepting the manifest. The operator-configured service timeout applies to `Describe` and `ValidateConfig`. The effective binding timeout applies only to `EvaluateHttpRequest`, WebSocket preflight, and each WebSocket message. WebSocket streams have no connection-wide deadline. The gateway connects to every registered service and verifies its capabilities before accepting traffic. Gateway startup fails when a service is unavailable, reports an invalid capability, or exposes more than one binding for the same operation and phase. The manifest `name` is diagnostic metadata and does not need to match the operator registration name. Operator-run registration names cannot claim the reserved `openshell/` namespace. Registration is static. Restart the gateway after adding, removing, or changing a service. See [Gateway Configuration](/reference/gateway-config#supervisor-middleware-services) for the complete gateway TOML context. +### Authenticate OpenShell Callers + +When gateway JWT signing is configured, OpenShell attaches a short-lived EdDSA bearer token to every remote middleware RPC. Gateway calls use `caller_kind: gateway`; sandbox supervisor calls use `caller_kind: supervisor` and include the sandbox ID. Supervisors request credentials by registration name through `RefreshSandboxToken`. The gateway derives the audience from operator-owned configuration and authorizes each name against the sandbox's effective policy. + +Return your expected audience in the `expected_audience` field of your `Describe` manifest. After authenticated `Describe` succeeds, OpenShell compares the advertised value with its operator-configured audience and refuses to start when they differ. This is a post-authentication consistency assertion, not audience discovery: a strict verifier may reject an incorrect audience before returning the manifest, in which case startup reports an authentication failure. Leave the field empty to skip the consistency check. + +Provision the trusted gateway URL, expected gateway ID, and public key or JWKS through the deployment. This operator-provisioned key material is the authoritative cold-start trust anchor. The expected issuer is exactly `openshell-gateway:`; fetching JWKS does not establish that identity by itself. After initial trust is established, `GET /.well-known/openid-configuration` and its `jwks_uri` provide steady-state key refresh and operational convenience. The document is OIDC-shaped rather than OIDC-compliant: `issuer` is the gateway identity, not the URL serving the document, so compare `iss` against the configured value and fetch updates only over authenticated TLS at the trusted gateway URL. + +Cache keys by `kid`. Validate, at minimum: + +- `typ` is exactly `openshell-ext+jwt`. Extension tokens and sandbox-to-gateway bootstrap tokens share a signing key and differ only in audience; this header is a second, independent discriminator. +- `alg` is pinned to `EdDSA`. Never select the algorithm from the token. +- Signature, expected issuer, exact audience, and positive expiry. +- `caller_kind`, and the sandbox identity when your service scopes behavior per sandbox. + +A sandbox-to-gateway JWT is not an extension credential even though both token types use the same signing key. + +Each token carries a unique `jti` that identifies that token instance for correlation and future explicit revocation. OpenShell reuses a token across calls until rotation and does not track `jti`, so rejecting a repeated `jti` would reject legitimate requests. Per-request replay resistance requires a request nonce or signature, channel binding, or another proof-of-possession mechanism. + +### Run Without Extension Authentication + +Set `allow_insecure_transport = true` on a registration to keep a plaintext `http://` endpoint working. OpenShell then attaches no credential to that service, supervisors do not request one, and the gateway refuses to mint one if asked. The gateway logs a warning naming the registration at every startup. + +The service cannot distinguish OpenShell from any other client that can reach it. Use this only where the network already provides that guarantee, and prefer `https://` everywhere else. + ## Apply Middleware with Policy Add middleware configs to the top-level `network_middlewares` map. Each key is the policy-local config name: @@ -92,16 +135,18 @@ See [Policy Schema](/reference/policy-schema#network-middleware) for the complet ## Configure Failure Behavior -`on_error` controls what happens when middleware is unavailable, rejects its configuration, returns an invalid result, or exceeds a body limit. +`on_error` controls what happens after an operation binding is selected and middleware is unavailable, rejects its configuration, returns an invalid result, or exceeds the selected binding's payload limit. It does not turn an unadvertised operation or an unsupported WebSocket message class into a middleware failure. | Value | Behavior | | --- | --- | -| `fail_closed` | Denies the request when the middleware stage fails. This is the default. | -| `fail_open` | Skips the failed stage and continues the request through the remaining chain. | +| `fail_closed` | Denies the HTTP request or closes the WebSocket when the stage fails. This is the default. | +| `fail_open` | Skips the failed HTTP stage. For a broken WebSocket stage stream, disables that stage for the rest of the connection and continues the remaining chain. | -Use `fail_open` only when bypassing the middleware preserves the intended security policy. OpenShell emits a detection finding when a failed stage is bypassed. +Use `fail_open` only when bypassing the middleware preserves the intended security policy. OpenShell emits a detection finding when a failed stage is bypassed and a separate state-change finding when a WebSocket stage is disabled for the session. -An explicit deny decision always stops the chain and denies the request, regardless of `on_error`. The HTTP response uses `error: middleware_denied`, identifies the policy-local middleware config, and omits policy-advisor remediation because the network and L7 allow rules already matched. OpenShell never copies the free-form middleware `reason` into the response or security logs. A service can instead return an optional stable `reason_code`: 1–64 bytes, starting with a lowercase ASCII letter and containing only lowercase ASCII letters, digits, and underscores. Invalid codes make the result a middleware failure governed by `on_error`. +Capability coverage is separate from failure handling. A host-matched HTTP-only attachment does not join the WebSocket chain, regardless of `on_error`. Binary messages are outside the V1 text-message binding and pass through even when a selected stage is `fail_closed`. OpenShell records both states as informational coverage events so operators do not mistake pass-through traffic for inspected traffic. If a deployment requires all WebSocket message classes to be inspected, V1 cannot express that requirement. + +An explicit deny decision always stops the chain and denies the request or WebSocket upgrade, regardless of `on_error`. A WebSocket preflight `DENY` is a successful policy decision, not a middleware failure; OpenShell rejects the upgrade before upstream contact and ends each still-writable stream opened by a successful preflight decision with `MIDDLEWARE_DENIAL`. The HTTP response uses `error: middleware_denied`, identifies the policy-local middleware config, and omits policy-advisor remediation because the network and L7 allow rules already matched. OpenShell never copies the free-form middleware `reason` into the response or security logs. HTTP results, WebSocket preflight decisions, and WebSocket message results can instead return an optional stable `reason_code`: 1–64 bytes, starting with a lowercase ASCII letter and containing only lowercase ASCII letters, digits, and underscores. Invalid codes make the result a middleware failure governed by `on_error`. Preflight findings and metadata use the same bounds and audit-safe handling as message results. ```json { @@ -117,19 +162,21 @@ A failed `fail_closed` stage uses `error: middleware_failed` and a platform-owne Middleware decisions are enforced regardless of the endpoint's `enforcement` mode. `enforcement: audit` applies to an endpoint's network and L7 policy rules and does not bypass middleware: a middleware deny, or a failed `fail_closed` stage, blocks the request even on an audit endpoint. A middleware service that needs to observe traffic without blocking should return an allow decision with findings, which OpenShell emits as detection findings. -## Set Body Limits +## Set Payload Limits -Every middleware binding declares the largest request or replacement body it supports. +Every middleware binding declares the largest logical payload or replacement it supports through `max_payload_bytes`. For `HTTP_REQUEST`, that payload is one request body. For `WEBSOCKET_MESSAGE`, it is one complete message rather than the whole session. - Built-in middleware uses its OpenShell-defined limit. -- Each operator-run registration sets `max_body_bytes` no higher than the service capability. +- Each operator-run registration sets one `max_payload_bytes` ceiling no higher than any binding's advertised `max_payload_bytes` capability. - A selected chain buffers using its largest stage limit, so every stage that can process the body receives it. - The same per-stage limit applies to request bodies and replacement bodies. -The gateway rejects a registration whose operator limit exceeds the service capability or the 4 MiB platform maximum instead of silently clamping it. OpenShell also bounds the non-body protobuf components: 64 KiB for service config, 4 KiB for request context, 32 KiB for the target, and 128 request header lines totaling at most 64 KiB encoded. Results allow a 4 KiB discarded free-form reason, a 64-byte validated reason code, 64 header mutations totaling at most 64 KiB encoded, 32 findings of at most 4 KiB encoded each, and 64 metadata entries totaling at most 32 KiB. Middleware gRPC servers should configure request and response message limits to at least 4 MiB plus 293 KiB so every platform-valid envelope fits. +The gateway rejects a registration whose operator limit exceeds the service capability or the 4 MiB platform maximum instead of silently clamping it. OpenShell also bounds the non-payload protobuf components: 64 KiB for service config, 4 KiB for request context, 32 KiB for the target, and 128 request header lines totaling at most 64 KiB encoded. Results allow a 4 KiB discarded free-form reason, a 64-byte validated reason code, 64 header mutations totaling at most 64 KiB encoded, 32 findings of at most 4 KiB encoded each, and 64 metadata entries totaling at most 32 KiB. Middleware gRPC servers should configure request and response message limits to at least 4 MiB plus 293 KiB so every platform-valid envelope fits. At request time, exceeding a selected stage's limit is a middleware failure for that stage alone and follows that config's `on_error` behavior; other stages in the chain still run against their own limits. OpenShell can apply `fail_open` to an oversized `Content-Length` before consuming body bytes. A chunked body can cross the limit only after bytes have been consumed, so OpenShell denies that request because it cannot safely resume the original stream. +For a WebSocket binding, `max_payload_bytes` covers complete client text messages and replacements. Exceeding a selected stage's effective text-message limit follows that stage's `on_error`. The 4 MiB parsed-text platform cap and other protocol-safety limits are independent of middleware failure policy. Binary messages are not delivered to middleware, so the operator ceiling does not become a binary relay limit; individual raw binary frames retain the 16 MiB relay-safety bound. Oversized parsed text closes the connection with code `1009`; invalid UTF-8 uses `1007`; protocol errors use `1002`; middleware or policy denials use `1008`; and policy reload uses `1012`. + ## Mutate Request Headers A middleware result can return ordered header mutations before OpenShell injects credentials. A `write` mutation adds a value when the case-insensitive header name is absent and selects one behavior when it is already present: @@ -164,6 +211,8 @@ Middleware activity is emitted through OpenShell's OCSF logging: - A denied invocation records a platform-owned reason derived from the policy-local config name and optional validated reason code. OpenShell does not record service-provided free-form reason text. - A bypass under `fail_open` emits a detection finding. - A required stage that fails closed emits a high-severity detection finding. +- A host-matched attachment without a WebSocket binding emits an informational `binding_not_selected` coverage event. +- A binary message encountered by an active WebSocket stage emits an informational `unsupported_message_type` coverage event with message type, sequence, and byte count. It is not reported as an invocation or failure. - Built-in findings include their type, label, and aggregate count. Operator-run findings use the operator-owned registration name and a platform label plus the aggregate count; OpenShell does not log service-provided finding text or diagnostic metadata. A stage can return at most 32 findings. Exceeding the per-stage cap is an invalid response handled through `on_error`. A maximum 10-stage chain retains and emits up to 320 findings without silently dropping findings from later stages. - Registry reload success and failure are emitted as configuration state changes. @@ -171,9 +220,13 @@ See [Logging](/observability/logging) for log access and [OCSF JSON Export](/obs ## Current Limitations -- Middleware applies only to HTTP requests parsed by the supervisor. Traffic the supervisor cannot inspect, such as HTTP/2 prior knowledge or non-HTTP TCP protocols, is denied on hosts matched by a fail-closed middleware, and relayed with a detection finding when every matching middleware is `fail_open`. -- The typed operation and phase are `HTTP_REQUEST/PRE_CREDENTIALS`. +- Middleware applies only through operation bindings advertised by each implementation. For protocols that have no supported middleware operation at all, such as HTTP/2 prior knowledge or non-HTTP TCP, the existing uninspectable-traffic gate denies a host match containing `fail_closed` and relays an all-`fail_open` match with a detection finding. +- The typed operation and phase pairs are `HTTP_REQUEST/PRE_CREDENTIALS` and `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. +- A host match does not imply every advertised operation: an HTTP-only attachment can inspect the upgrade GET, then post-upgrade traffic passes with `binding_not_selected` coverage. +- The V1 WebSocket binding inspects complete client text messages only. Binary messages pass with `unsupported_message_type` coverage for active stages; control frames and upstream-to-client messages remain outside the middleware operation. - Selection uses destination host include and exclude patterns. - A fail-closed middleware cannot cover `tls: skip` endpoints because OpenShell cannot inspect that traffic. An all-`fail_open` match may cover the endpoint; OpenShell bypasses the middleware and emits a detection finding. -- Operator-run services support plaintext `http://` and TLS `https://` endpoints. HTTPS certificates must chain to a CA in the platform trust store. -- Custom trust roots, client authentication, health checks, and runtime registration are not available. +- Operator-run services use TLS `https://` when gateway JWT signing is enabled, unless the registration sets `allow_insecure_transport`. Certificates must chain to the configured custom CA or platform roots, and the endpoint hostname must match. +- Extension tokens and sandbox-to-gateway tokens are signed by the same key. They are separated by audience and by `typ`, but the extension credential path cannot yet be rotated or revoked independently of sandbox admission. +- OpenShell does not track or revoke `jti`; bearer tokens can be replayed until expiry. Per-request replay resistance requires proof of possession or request binding. +- mTLS client authentication, health checks, runtime registration, and overlapping signing-key rotation are not available. diff --git a/docs/observability/logging.mdx b/docs/observability/logging.mdx index 1ab0b5bfed..c3998629e5 100644 --- a/docs/observability/logging.mdx +++ b/docs/observability/logging.mdx @@ -137,6 +137,21 @@ OCSF HTTP:POST [INFO] ALLOWED POST http://httpbin.org:443/anything [policy:httpb OCSF FINDING:CREATE [MED] "configured content matched" [type:content_guard.match count:1 middleware:prototype-content-guard] ``` +WebSocket middleware emits one safe event per preflight, session-start, or client text-message decision. The event includes the policy-local config, registered implementation, sequence, byte counts, transformation flag, and validated reason code. It never includes the message payload or service-provided free-form reason: + +```text +OCSF NET:OTHER [INFO] WEBSOCKET_MIDDLEWARE allow config=api-redactor implementation=openshell/regex sequence=3 input_bytes=128 replacement_bytes=96 transformed=true reason_code=- +``` + +Coverage events are separate from invocation decisions. `binding_not_selected` means a host-matched attachment did not advertise the WebSocket operation. `unsupported_message_type` means an active WebSocket stage encountered a binary message, which V1 passes through without inspection. Both are informational, do not apply `on_error`, and never claim the traffic was inspected: + +```text +OCSF NET:OTHER [INFO] WEBSOCKET_MIDDLEWARE_COVERAGE state=binding_not_selected config=http-dlp implementation=example/http-dlp sequence=- message_type=- input_bytes=0 +OCSF NET:OTHER [INFO] WEBSOCKET_MIDDLEWARE_COVERAGE state=unsupported_message_type config=api-redactor implementation=openshell/regex sequence=4 message_type=binary input_bytes=512 +``` + +A fail-open stream error emits both a middleware failure and `openshell.middleware.websocket_stage_disabled`. The latter records that OpenShell will bypass that stage for later messages on the same connection. Waiting for saturated admission capacity also emits a detection finding without payload content. When both active capacity and the bounded wait queue are full, HTTP work is rejected before its payload is buffered, returns `503 Service Unavailable`, and emits `openshell.middleware.admission_exhausted`. + Proxy and SSH servers ready: ```text @@ -167,7 +182,7 @@ OCSF CONFIG:LOADED [INFO] Policy reloaded successfully [policy_hash:0cc0c2b52557 Denied `NET:` and `HTTP:` events carry a `[reason:...]` suffix that surfaces the decision detail from the event's `status_detail` field. The reason helps distinguish between policy misses, SSRF hardening, and L7 enforcement without inspecting the full OCSF JSONL record. -For supervisor middleware denials, `status_detail` contains a platform-owned reason derived from the policy-local middleware config name and optional validated reason code. Middleware failure details also use platform-owned error codes. OpenShell does not copy per-request service text into logs. +For supervisor middleware denials, `status_detail` contains a platform-owned reason derived from the policy-local middleware config name and optional validated reason code. Middleware failure details also use platform-owned error codes. OpenShell does not copy per-request service text or WebSocket message content into logs. Common reason phrases emitted by the sandbox include: diff --git a/docs/reference/gateway-config.mdx b/docs/reference/gateway-config.mdx index 230ae77cee..85e965a357 100644 --- a/docs/reference/gateway-config.mdx +++ b/docs/reference/gateway-config.mdx @@ -130,8 +130,10 @@ provider_profile_sources = [ # both the gateway and sandbox supervisors. [[openshell.supervisor.middleware]] name = "local-content-guard" -grpc_endpoint = "http://host.openshell.internal:50051" -max_body_bytes = 262144 +grpc_endpoint = "https://host.openshell.internal:50051" +tls_ca_cert_path = "/etc/openshell/certs/content-guard-ca.pem" +audience = "urn:openshell:middleware:local-content-guard" +max_payload_bytes = 262144 timeout = "500ms" # Gateway listener TLS (distinct from the per-driver guest_tls_*). @@ -176,6 +178,7 @@ scopes_claim = "" [[openshell.gateway.interceptors]] name = "quota" grpc_endpoint = "unix:///run/openshell/interceptors/quota.sock" +audience = "urn:openshell:interceptor:quota" order = 10 failure_policy = "fail_closed" binding_policy = "allowlist" @@ -261,27 +264,44 @@ Register operator-run supervisor middleware services with one or more `[[openshe ```toml [[openshell.supervisor.middleware]] name = "local-content-guard" -grpc_endpoint = "http://host.openshell.internal:50051" -max_body_bytes = 262144 +grpc_endpoint = "https://host.openshell.internal:50051" +tls_ca_cert_path = "/etc/openshell/certs/content-guard-ca.pem" +audience = "urn:openshell:middleware:local-content-guard" +max_payload_bytes = 262144 timeout = "500ms" ``` -Each service implements the supervisor middleware gRPC contract and exposes bindings through `Describe`. Policies reference the operator-owned registration `name`, attaching the complete middleware and all of its bindings. Bindings are identified by operation and phase. A manifest may expose at most one binding for each operation and phase pair; V1 supports only `HttpRequest/pre_credentials`, so a service currently exposes one binding. Registration names must be unique, and operator-run registrations cannot claim the reserved `openshell/` namespace. The service-reported manifest name is diagnostic metadata and does not need to match the registration name. +Each service implements the supervisor middleware gRPC contract and exposes bindings through `Describe`. Policies reference the operator-owned registration `name`, attaching the complete middleware and all of its bindings. Bindings are identified by operation and phase. A manifest may expose at most one binding for each operation and phase pair. V1 supports `HttpRequest/pre_credentials` and `WebSocketMessage/pre_credentials`, so a service can inspect HTTP, WebSocket, or both. Registration names must be unique, and operator-run registrations cannot claim the reserved `openshell/` namespace. The service-reported manifest name is diagnostic metadata and does not need to match the registration name. The gateway connects to every registered service and validates `Describe` before it starts. The service must therefore be running before the gateway. Policy creation and full policy updates call `ValidateConfig`; an unavailable service or invalid middleware configuration rejects the policy before persistence. -`max_body_bytes` is the operator limit for every binding exposed by the service. It must be greater than zero, no larger than each binding's advertised limit, and no larger than the 4 MiB platform maximum. OpenShell rejects an oversized value instead of silently clamping it. Middleware gRPC servers should allow messages of at least 4 MiB plus 293 KiB so a maximum-size body and its protobuf envelope fit on the transport. +`max_payload_bytes` is the shared operator limit for inspectable logical payloads across every binding exposed by the service. It caps HTTP request and replacement bodies as well as complete WebSocket text messages and replacements. The value must be greater than zero, no larger than each binding's advertised `max_payload_bytes` capability, and no larger than the 4 MiB platform maximum. OpenShell rejects oversized values instead of silently clamping them. Binary WebSocket messages are not exposed to V1 middleware, so this field does not limit binary pass-through. Middleware gRPC servers should allow messages of at least 4 MiB plus 293 KiB so a maximum-size payload and its protobuf envelope fit on the transport. -`timeout` is the operator-configured service-wide RPC timeout. It accepts the same compact duration syntax as gateway interceptors: an integer followed by `ms` or `s`, such as `500ms` or `2s`. Values must be between `10ms` and `30s`, inclusive. Omit the field to use the 500 ms platform default. A binding may advertise a shorter `timeout` in the `Describe` manifest, but it cannot extend the operator-configured deadline; OpenShell uses the smaller value. OpenShell validates both levels before accepting the service. The effective timeout covers `ValidateConfig` and `EvaluateHttpRequest`; `Describe` uses the service timeout because binding metadata is not available yet. +`timeout` is the operator-configured service-wide RPC timeout. It accepts the same compact duration syntax as gateway interceptors: an integer followed by `ms` or `s`, such as `500ms` or `2s`. Values must be between `10ms` and `30s`, inclusive. Omit the field to use the 500 ms platform default. A binding may advertise a shorter `timeout` in the `Describe` manifest, but it cannot extend the operator-configured deadline; OpenShell uses the smaller value. OpenShell validates both levels before accepting the service. The operator-configured service timeout applies to `Describe` and `ValidateConfig`. The effective binding timeout applies only to `EvaluateHttpRequest`, WebSocket preflight, and each WebSocket message. An accepted WebSocket stream has no connection-wide RPC deadline. -The service `grpc_endpoint` currently supports plaintext `http://` and TLS `https://` using the platform trust store. Custom trust roots, client authentication, health checks, and runtime registration are not currently supported. The endpoint must be reachable from both the gateway and sandbox supervisors; use `host.openshell.internal` or another shared address that can be resolved in both places. +The service `grpc_endpoint` supports plaintext `http://` and TLS `https://`. HTTPS uses the platform trust store unless `tls_ca_cert_path` names a certificate-only PEM bundle. OpenShell rejects bundles containing private keys, loads the certificates at gateway startup, and distributes only public certificates to sandbox supervisors; normal TLS hostname verification still applies. `audience` sets the exact audience for gateway-minted service tokens and defaults to `urn:openshell:extension:middleware:`. After authenticated `Describe` succeeds, OpenShell treats a non-empty manifest `expected_audience` as a consistency assertion and refuses to start when it differs from the configured audience. A strict verifier may reject an incorrect audience before returning the manifest. -See [Supervisor Middleware](/extensibility/supervisor-middleware) for selection, failure, body-limit, and operational guidance. +When `gateway_jwt` is configured, OpenShell attaches short-lived bearer credentials to gateway and supervisor calls and requires `https://`. A middleware endpoint must be reachable from sandbox supervisors, so Unix sockets are not an option here. Set `allow_insecure_transport = true` on a registration to keep a plaintext `http://` endpoint: OpenShell then attaches no credential, supervisors do not request one, and the gateway logs a warning naming the registration at every startup. mTLS client authentication, health checks, and runtime registration are not currently supported. The endpoint must be reachable from both the gateway and sandbox supervisors; use `host.openshell.internal` or another shared address that can be resolved in both places. + +See [Supervisor Middleware](/extensibility/supervisor-middleware) for selection, failure, payload-limit, and operational guidance. ## Gateway Interceptors `[[openshell.gateway.interceptors]]` configures gateway-side interceptor services. The gateway calls each service's `Describe` RPC at startup, validates its declared OpenShell RPC bindings against the compiled service descriptor, and applies matching phases from a central gRPC middleware path. Interceptors can target only methods in the gateway's built-in allowlist of unary mutation RPCs. New RPCs are non-interceptable until they are deliberately added to that allowlist; adding one does not require handler-specific interceptor code. Request bodies are exposed as protobuf JSON objects. Fields marked secret in the protobuf schema are recursively omitted from requests and post-commit responses. Interceptors cannot patch an omitted field or a containing object. +HTTPS interceptor endpoints use the platform trust store by default. Set `tls_ca_cert_path` to a PEM certificate bundle for a private CA; normal TLS hostname verification still applies. `audience` sets the exact audience for gateway-minted service tokens and defaults to `urn:openshell:extension:interceptor:`. After authenticated `Describe` succeeds, the gateway treats a non-empty manifest `expected_audience` as a consistency assertion and refuses to start when it differs from the configured audience. A strict verifier may reject an incorrect audience before returning the manifest. When `gateway_jwt` is configured, network interceptors must use HTTPS and receive short-lived gateway-caller bearer credentials; local Unix sockets are also supported. Set `allow_insecure_transport = true` to keep a plaintext `http://` interceptor endpoint with no credential attached and a startup warning. + +### Extension Token Verification Endpoints + +When `gateway_jwt` is configured the gateway publishes two unauthenticated documents that extension services use to verify OpenShell callers: + +| Path | Contents | +| --- | --- | +| `/.well-known/jwks.json` | Single-key JWKS holding the Ed25519 public key and its `kid`. | +| `/.well-known/openid-configuration` | OIDC-shaped discovery metadata: the exact expected `iss`, an absolute `jwks_uri`, and `EdDSA` as the only supported signing algorithm. | + +The discovery document is OIDC-shaped rather than OIDC-compliant: `issuer` is the gateway identity (`openshell-gateway:`), not the URL the document is served from. Verifiers compare `iss` against that value and must not infer trust from the document's location; the serving TLS connection is what authenticates the gateway. Both endpoints return `404` when `gateway_jwt` is not configured. + `binding_policy` controls how the manifest and operator binding configuration combine: - `dynamic` enables valid manifest bindings and treats configured entries as optional narrowing overrides. This is the compatibility default. The gateway logs a startup warning because the interceptor controls its non-secret RPC authority. @@ -423,6 +443,14 @@ client_ca_path = "/etc/openshell-tls/client-ca/ca.crt" # external_server_names = ["gateway.example.com"] [openshell.drivers.kubernetes] +# Workspace isolation mode. "shared" renders all sandboxes into a single +# namespace. "managed" auto-creates a K8s namespace per workspace +# (openshell-{gateway_id}-{workspace}). "operator" maps each workspace to a +# pre-provisioned namespace discovered via label selector or drop-in file. +workspace_mode = "shared" +# Gateway identity used in managed-mode namespace naming. Defaults to the +# gateway JWT gateway_id. Must be a DNS-1123 label. +# gateway_id = "openshell" namespace = "agents" service_account_name = "openshell-sandbox" default_image = "ghcr.io/nvidia/openshell/sandbox:latest" @@ -431,6 +459,7 @@ image_pull_secrets = ["regcred"] # Defaults to the gateway version; override to pin a specific build. # supervisor_image = "ghcr.io/nvidia/openshell/supervisor:" supervisor_image_pull_policy = "IfNotPresent" + # Use the image volume on Kubernetes >= 1.35 (GA in 1.36); switch to "init-container" # on older clusters or where the ImageVolume feature gate is off. supervisor_sideload_method = "image-volume" @@ -491,6 +520,18 @@ provider_spiffe_workload_api_socket_path = "/spiffe-workload-api/spire-agent.soc # back to 1000 on non-OpenShift clusters. # sandbox_uid = 1500 # sandbox_gid = 1500 +# Operator-mode namespace discovery. At least one must be set when +# workspace_mode = "operator". Both can be combined. +# operator_namespace_label discovers namespaces matching a K8s label selector. +# operator_namespace_label = "openshell.ai/workspace=true" +# operator_namespace_file reads allowed namespaces from a JSON/YAML file +# (hot-reloaded on change, e.g. via ConfigMap volume mount). +# operator_namespace_file = "/etc/openshell/workspace-namespaces.json" + +[openshell.drivers.kubernetes.managed_ssh_ingress] +enabled = true +gateway_namespace = "openshell" +gateway_pod_selector = { "app.kubernetes.io/name" = "openshell", "app.kubernetes.io/instance" = "openshell" } [openshell.drivers.kubernetes.sidecar] # UID used by relaxed long-running network sidecars. Strict process/binary-aware @@ -505,6 +546,11 @@ proxy_uid = 1337 process_binary_aware_network_policy = true ``` +In managed workspace mode, the Kubernetes driver copies each explicitly named +`image_pull_secrets` Secret from `namespace` into the managed workspace +namespace on sandbox creation. Shared and operator modes require the Secret to +already exist in the sandbox namespace. + ### Docker Sandboxes run as containers on a local bridge network. The supervisor binary is bind-mounted from the host (no in-cluster image pull required); guest mTLS material is supplied as host paths. diff --git a/docs/reference/policy-schema.mdx b/docs/reference/policy-schema.mdx index ab9aed8574..e6dcf12a01 100644 --- a/docs/reference/policy-schema.mdx +++ b/docs/reference/policy-schema.mdx @@ -30,7 +30,7 @@ network_middlewares: { ... } | `landlock` | object | No | Static | Configures Landlock LSM enforcement behavior. | | `process` | object | No | Static | Sets the user and group the agent process runs as. | | `network_policies` | map | No | Dynamic | Declares which binaries can reach which network endpoints. | -| `network_middlewares` | map | No | Dynamic | Selects ordered HTTP request middleware by destination host. | +| `network_middlewares` | map | No | Dynamic | Attaches ordered middleware by destination host; each implementation's manifest selects its supported HTTP and WebSocket operations. | Static fields are set at sandbox creation time. Changing them requires destroying and recreating the sandbox. Dynamic fields can be updated on a running sandbox with `openshell policy update` for incremental merges or `openshell policy set` for full replacement, and take effect without restarting. @@ -525,7 +525,7 @@ Identifies an executable that is permitted to use the associated endpoints. **Category:** Dynamic -A map of up to 10 middleware configs selected after network and L7 policy admit an HTTP request. Each map key is the stable policy-local config identity. Middleware selection is independent of the network policy entry that admitted the request. Every matching config runs once by ascending `order` before provider credential injection. Order values must be unique across the policy, and runtime selection also enforces the 10-stage maximum. +A map of up to 10 middleware configs selected after network and L7 policy admit an HTTP request or WebSocket upgrade. Each map key is the stable policy-local config identity. Middleware selection is independent of the network policy entry that admitted the traffic. Every matching config runs once by ascending `order` before provider credential injection. WebSocket-capable bindings continue on client text messages after the upgrade. Order values must be unique across the policy, and runtime selection also enforces the 10-stage maximum. ```yaml showLineNumbers={false} network_middlewares: @@ -547,10 +547,10 @@ network_middlewares: | `middleware` | string | Yes | Built-in middleware name or operator-owned registration name. `openshell/` is reserved for built-ins. | | `order` | integer | No | Execution priority. Lower values run first, and values must be unique across the policy. Defaults to `0`; therefore, policies with multiple configs normally specify it explicitly. | | `config` | object | No | Implementation-owned configuration validated by the selected middleware. | -| `on_error` | string | No | `fail_closed` denies the request when the stage fails; `fail_open` skips the failed stage. Defaults to `fail_closed`. | +| `on_error` | string | No | Applies only after an advertised operation binding is selected. `fail_closed` denies the HTTP request or closes the WebSocket when that stage fails; `fail_open` skips a failed HTTP stage or disables a broken WebSocket stage for the rest of that connection. Defaults to `fail_closed`. | | `endpoints` | object | Yes | Host selector with required non-empty `include` and optional `exclude` lists, limited to 32 combined patterns. Exclusions take precedence. | -Host selectors use the same case-insensitive exact and DNS glob semantics as network endpoints: `*` matches exactly one DNS label and `**` matches one or more labels, so `**.example.com` covers subdomains but not `example.com` itself. Brace alternates are rejected at validation. Middleware runs only on HTTP requests the supervisor parses. A fail-closed selector that can cover a `tls: skip` endpoint is rejected because OpenShell cannot inspect that traffic. An all-`fail_open` match may cover the endpoint; the supervisor bypasses the middleware and emits a detection finding. +Host selectors use the same case-insensitive exact and DNS glob semantics as network endpoints: `*` matches exactly one DNS label and `**` matches one or more labels, so `**.example.com` covers subdomains but not `example.com` itself. Brace alternates are rejected at validation. A matching attachment joins only the operation chains its implementation advertises. An HTTP-only attachment may inspect a WebSocket upgrade GET without joining the post-upgrade chain; OpenShell permits the messages and records `binding_not_selected` coverage regardless of `on_error`. WebSocket bindings inspect complete client text messages. Binary messages pass with `unsupported_message_type` coverage for active stages. A fail-closed selector that can cover a `tls: skip` endpoint is rejected because OpenShell cannot inspect that traffic through any operation. An all-`fail_open` match may cover the endpoint; the supervisor bypasses the middleware and emits a detection finding. See [Supervisor Middleware](/extensibility/supervisor-middleware) for registration, failure behavior, body limits, and operational guidance. diff --git a/docs/reference/sandbox-compute-drivers.mdx b/docs/reference/sandbox-compute-drivers.mdx index 189f685ff3..897e780c39 100644 --- a/docs/reference/sandbox-compute-drivers.mdx +++ b/docs/reference/sandbox-compute-drivers.mdx @@ -328,6 +328,17 @@ On hosts with restrictive firewalls (e.g. firewalld), the host firewall may addi Kubernetes-backed sandboxes run as pods in the configured sandbox namespace. Use Kubernetes for shared clusters, remote compute, GPU scheduling, and operator-managed environments. + +Kubernetes workspace namespaces are an administrative trust boundary. In +shared and managed modes, only the OpenShell gateway and its trusted Agent +Sandbox controller may administer Sandbox CRs, sandbox pods, or the configured +sandbox ServiceAccount in those namespaces. In operator mode, allowlist only +namespaces where the platform operator preserves that exclusive control. +Untrusted principals must not be able to create sandbox pods with fabricated +owner references or use the sandbox ServiceAccount. The operator namespace +allowlist is a trust grant, not a tenant isolation mechanism. + + Helm deployments set Kubernetes driver values through the chart. For maintainer-level implementation details, refer to the [Kubernetes driver README](https://github.com/NVIDIA/OpenShell/blob/main/crates/openshell-driver-kubernetes/README.md). @@ -339,7 +350,8 @@ For maintainer-level implementation details, refer to the [Kubernetes driver REA | `service_account_name` | `sandboxServiceAccount.name` | Set the Kubernetes service account assigned to sandbox pods and accepted by the gateway TokenReview bootstrap path. The Helm chart creates a dedicated sandbox service account by default. | | `default_image` | `server.sandboxImage` | Set the default sandbox image. | | `image_pull_policy` | `server.sandboxImagePullPolicy` | Set the Kubernetes image pull policy for sandbox pods. | -| `image_pull_secrets` | `server.sandboxImagePullSecrets` | Attach Kubernetes image pull secrets to sandbox pods. Referenced Secrets must exist in the sandbox namespace. | +| `image_pull_secrets` | `server.sandboxImagePullSecrets` | Attach Kubernetes image-pull Secrets to sandbox pods. Managed mode copies these explicitly named Secrets from the configured source namespace into each workspace namespace. In shared and operator modes, the Secrets must already exist in the sandbox namespace. | +| `[managed_ssh_ingress]` | `networkPolicy.enabled` | In managed mode, create an SSH ingress policy in every workspace namespace. Helm configures the gateway namespace and pod selector automatically. Operator mode leaves namespace policy management to the platform operator. | | `grpc_endpoint` | `server.grpcEndpoint` | Set the gateway callback endpoint reachable from sandbox pods. | | `client_tls_secret_name` | `server.tls.clientTlsSecretName` | Mount sandbox client TLS materials from a Kubernetes secret. | | `supervisor_image` | `supervisor.image.repository` / `supervisor.image.tag` | Override the supervisor image that provides the `openshell-sandbox` binary. The default repository with an empty tag uses the version-pinned image built into the gateway. Changing the repository uses the effective gateway image tag, while setting a tag pins that version explicitly. | @@ -359,6 +371,13 @@ For maintainer-level implementation details, refer to the [Kubernetes driver REA | `workspace_storage_class` | `server.workspaceStorageClass` | Set the `StorageClass` for the workspace PVC. Empty (default) omits `storageClassName` and uses the cluster's default `StorageClass`. Set this on clusters with no default `StorageClass`, otherwise the workspace PVC stays `Pending` and the sandbox never starts. | | `sa_token_ttl_secs` | `server.sandboxJwt.k8sSaTokenTtlSecs` | Set the projected ServiceAccount token TTL used for the bootstrap token exchange. | +Managed-mode Secret copying requires the gateway ServiceAccount to create +Secrets. Kubernetes RBAC cannot restrict Secret `create` by resource name, so +the Helm chart grants cluster-wide Secret `create`; Secret `get` and `patch` +remain limited to the explicitly configured TLS and image-pull Secret names. +The driver creates copies only in gateway-owned managed namespaces. Do not +reuse the gateway ServiceAccount for unrelated workloads. + In `combined` topology, the agent container carries the Linux capabilities needed by the supervisor for network namespace setup, Landlock filesystem policy, process privilege changes, and network policy enforcement. In `sidecar` diff --git a/docs/sandboxes/policies.mdx b/docs/sandboxes/policies.mdx index 206c7d64c9..f57a21fc3f 100644 --- a/docs/sandboxes/policies.mdx +++ b/docs/sandboxes/policies.mdx @@ -62,7 +62,7 @@ network_middlewares: Static sections are locked at sandbox creation. Changing them requires destroying and recreating the sandbox. Dynamic sections can be updated on a running sandbox with `openshell policy update` for incremental merges or `openshell policy set` for full replacement, and take effect without restarting. -When a hot reload changes rules, the supervisor publishes a new policy generation and closes connections pinned to the previous generation. This includes HTTP keep-alive tunnels, `tls: skip`, non-HTTP payloads, HTTP upgrades such as WebSocket, and long-lived response streams such as SSE. Most clients reconnect automatically, and the next connection or request is evaluated against the current policy. Use `protocol: websocket` when policy should stay attached to the RFC 6455 upgrade and client text messages after the allowed upgrade. Add `websocket_credential_rewrite: true` only when the relay should rewrite credential placeholders in client-to-server WebSocket text messages. Add `request_body_credential_rewrite: true` only on inspected REST endpoints that need OpenShell to rewrite placeholders in supported text request bodies. +When a hot reload changes rules, the supervisor publishes a new policy generation and closes connections pinned to the previous generation. This includes HTTP keep-alive tunnels, `tls: skip`, non-HTTP payloads, HTTP upgrades such as WebSocket, and long-lived response streams such as SSE. Most clients reconnect automatically, and the next connection or request is evaluated against the current policy. A parsed WebSocket relay closes with code `1012` when its attached policy generation becomes stale. Use `protocol: websocket` when policy should stay attached to the RFC 6455 upgrade and client text messages after the allowed upgrade. Add `websocket_credential_rewrite: true` only when the relay should rewrite credential placeholders in client-to-server WebSocket text messages. Add `request_body_credential_rewrite: true` only on inspected REST endpoints that need OpenShell to rewrite placeholders in supported text request bodies. | Section | Type | Description | |---|---|---| @@ -70,11 +70,11 @@ When a hot reload changes rules, the supervisor publishes a new policy generatio | `landlock` | Static | Configures Landlock LSM enforcement behavior. Set `compatibility` to `best_effort` (skip individual inaccessible paths while applying remaining rules) or `hard_requirement` (fail if any path is inaccessible or the required kernel ABI is unavailable). Refer to the [Policy Schema Reference](/reference/policy-schema#landlock) for the full behavior table. | | `process` | Static | Optionally overrides the OS-level identity for the agent process. Explicit values must be `sandbox` or numeric UID/GID values in the allowed sandbox range. Docker and Podman may use named identities or non-root system IDs only through per-field OCI `USER` fallback; Kubernetes uses its platform-selected numeric identity. Root identities are always rejected. The agent also runs with seccomp filters that block dangerous system calls. | | `network_policies` | Dynamic | Controls network access for ordinary outbound traffic from the sandbox. Each block has a name, a list of endpoints (host, port, protocol, and optional rules), and a list of binaries allowed to use those endpoints.
Every outbound connection except `https://inference.local` goes through the proxy, which queries the [policy engine](/about/how-it-works#core-components) with the destination and calling binary. A connection is allowed only when both match an entry in the same policy block.
For endpoints with `protocol: rest`, the proxy auto-detects TLS and terminates it so each HTTP request can be checked against that endpoint's `rules` (method and path). For endpoints with `protocol: websocket`, the proxy validates the RFC 6455 upgrade and evaluates `GET` rules for the handshake plus either `WEBSOCKET_TEXT` rules for raw client text messages or GraphQL operation rules for GraphQL-over-WebSocket messages. Set `websocket_credential_rewrite: true` only when a WebSocket or REST compatibility endpoint must keep placeholder credentials in sandbox-owned text frames and resolve them at the OpenShell relay boundary.
Endpoints without `protocol` allow the TCP stream through without inspecting payloads.
If no endpoint matches, the connection is denied. Configure managed inference separately through [Inference Routing](/sandboxes/inference-routing). | -| `network_middlewares` | Dynamic | Declares keyed HTTP request middleware configs. After network and L7 policy admit a request, OpenShell matches each config's host selectors independently and runs matching entries by their unique ascending `order` before credential injection. | +| `network_middlewares` | Dynamic | Declares keyed HTTP and WebSocket middleware configs. After network and L7 policy admit a request or upgrade, OpenShell matches each config's host selectors independently and runs matching entries by their unique ascending `order` before credential injection. WebSocket-capable entries continue on complete client text messages. | ## Supervisor Middleware -Supervisor middleware can inspect, deny, or replace admitted HTTP request bodies before provider credentials are injected. Middleware selection is independent of the `network_policies` rule that admitted the request: each keyed `network_middlewares` entry matches the destination host through `endpoints.include` and `endpoints.exclude`. +Supervisor middleware can inspect, deny, or replace admitted HTTP request bodies and client WebSocket text messages before provider credentials are injected. Middleware selection is independent of the `network_policies` rule that admitted the traffic: each keyed `network_middlewares` entry matches the destination host through `endpoints.include` and `endpoints.exclude`. ```yaml network_middlewares: @@ -92,9 +92,9 @@ network_middlewares: Matching entries run once each by ascending `order`; lower values run first, and duplicate order values are rejected. The default order is `0`, so policies with multiple entries normally set it explicitly. Map keys are structurally unique. An optional `name` provides a human-readable label, defaults to the map key, and does not change the key used as the config identity. Different keys may use the same implementation and run as distinct stages. `exclude` takes precedence over `include`. -`openshell/regex` is an example built into the supervisor. It applies fixed regular expressions as a best-effort UTF-8 text transformation, without guarantees that sensitive values will be detected or fully removed. Custom expressions are not configurable yet. Operator-run middleware must be registered by name before a policy can reference it. The gateway validates implementation-owned config before accepting the policy. +`openshell/regex` is an example built into the supervisor. It applies fixed regular expressions to UTF-8 HTTP request bodies and complete client-to-upstream WebSocket text messages before credential injection. The initial pattern recognizes `sk-` tokens. This is a best-effort text transformation without guarantees that sensitive values will be detected or fully removed; it does not inspect binary or upstream-to-client WebSocket messages. Custom expressions are not configurable yet. Operator-run middleware must be registered by name before a policy can reference it. The gateway validates implementation-owned config before accepting the policy. -`on_error` defaults to `fail_closed`. Use `fail_open` only when skipping a failed middleware is acceptable. Middleware applies only to HTTP traffic the supervisor can parse and inspect. Policy validation rejects a fail-closed selector that can cover a `tls: skip` endpoint. An all-`fail_open` match may cover the endpoint; the supervisor bypasses the middleware and emits a detection finding. +`on_error` defaults to `fail_closed`. Use `fail_open` only when skipping a selected stage that fails is acceptable. For WebSocket streams, a broken fail-open stage is disabled for the rest of that connection and OpenShell emits a state-change finding. A host-matched attachment joins only operation chains advertised by its implementation. An HTTP-only attachment may inspect the WebSocket upgrade GET, but post-upgrade messages pass with informational `binding_not_selected` coverage under either error mode. Binary messages also pass without middleware inspection and produce `unsupported_message_type` coverage for active WebSocket stages. Upstream-to-client messages remain uninspected. Policy validation rejects a fail-closed selector that can cover a `tls: skip` endpoint. An all-`fail_open` match may cover the endpoint; the supervisor bypasses the middleware and emits a detection finding. See [Supervisor Middleware](/extensibility/supervisor-middleware) for registration, chain ordering, body limits, failure behavior, and operations. diff --git a/e2e/rust/Cargo.toml b/e2e/rust/Cargo.toml index e2bc94d81d..9ff52c73ab 100644 --- a/e2e/rust/Cargo.toml +++ b/e2e/rust/Cargo.toml @@ -29,6 +29,8 @@ e2e-gpu = ["e2e"] e2e-docker-gpu = ["e2e-docker", "e2e-gpu"] e2e-kubernetes = ["e2e"] e2e-kubernetes-credential-drivers = ["e2e-kubernetes"] +e2e-kubernetes-workspace-managed = ["e2e-kubernetes"] +e2e-kubernetes-workspace-operator = ["e2e-kubernetes"] e2e-podman = ["e2e", "e2e-host-gateway", "e2e-local-container-driver"] e2e-podman-gpu = ["e2e-podman", "e2e-gpu"] e2e-oidc-pkce = [] @@ -139,6 +141,16 @@ name = "proxy_egress_pipeline" path = "tests/proxy_egress_pipeline.rs" required-features = ["e2e-host-gateway"] +[[test]] +name = "workspace_namespace_managed" +path = "tests/workspace_namespace_managed.rs" +required-features = ["e2e-kubernetes-workspace-managed"] + +[[test]] +name = "workspace_namespace_operator" +path = "tests/workspace_namespace_operator.rs" +required-features = ["e2e-kubernetes-workspace-operator"] + [[test]] name = "gpu" path = "tests/gpu.rs" diff --git a/e2e/rust/tests/workspace_namespace_managed.rs b/e2e/rust/tests/workspace_namespace_managed.rs new file mode 100644 index 0000000000..38de1da6a3 --- /dev/null +++ b/e2e/rust/tests/workspace_namespace_managed.rs @@ -0,0 +1,815 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#![cfg(feature = "e2e-kubernetes-workspace-managed")] + +//! E2E tests for managed workspace mode. +//! +//! The gateway is deployed with `workspace_mode = "managed"`, which +//! auto-creates a K8s namespace per workspace (`openshell-{gateway_id}-{ws}`) +//! and deletes it when the last sandbox is removed. +//! +//! Namespace cleanup after sandbox deletion is best-effort and depends on +//! controller finalization timing. These tests focus on verifiable behavior: +//! namespace creation, labels, ServiceAccount and SSH NetworkPolicy +//! provisioning, and sandbox CR placement in the correct namespace. + +use std::process::Stdio; +use std::time::Duration; + +use openshell_e2e::harness::binary::{openshell_bin, openshell_cmd}; +use openshell_e2e::harness::output::strip_ansi; + +fn kube_context() -> String { + std::env::var("OPENSHELL_E2E_KUBE_CONTEXT_ACTIVE") + .expect("OPENSHELL_E2E_KUBE_CONTEXT_ACTIVE must be set") +} + +async fn kubectl(args: &[&str]) -> (bool, String) { + let context = kube_context(); + let output = tokio::process::Command::new("kubectl") + .arg("--context") + .arg(&context) + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .await + .expect("failed to spawn kubectl"); + + let combined = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + (output.status.success(), combined) +} + +fn managed_namespace(workspace: &str) -> String { + format!("openshell-openshell-{workspace}") +} + +async fn run_cli(args: &[&str]) -> (bool, String) { + let mut cmd = openshell_cmd(); + cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped()); + let output = cmd.output().await.expect("failed to spawn openshell"); + let combined = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + (output.status.success(), strip_ansi(&combined)) +} + +fn unique_workspace(prefix: &str) -> String { + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + % 100_000; + format!("{prefix}-{ts}") +} + +async fn wait_sandbox_gone(workspace: &str, sandbox: &str) { + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let (ok, out) = run_cli(&["sandbox", "list", "--workspace", workspace]).await; + if ok && !out.contains(sandbox) { + return; + } + if tokio::time::Instant::now() >= deadline { + panic!( + "sandbox {sandbox} still listed in workspace {workspace} 30s after delete: {out}" + ); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } +} + +struct ManagedCleanup { + workspace: String, + sandboxes: Vec, +} + +impl Drop for ManagedCleanup { + fn drop(&mut self) { + let bin = openshell_bin(); + for sb in &self.sandboxes { + let _ = std::process::Command::new(&bin) + .args(["sandbox", "delete", sb, "--workspace", &self.workspace]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + let _ = std::process::Command::new(&bin) + .args(["workspace", "delete", &self.workspace]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + let context = std::env::var("OPENSHELL_E2E_KUBE_CONTEXT_ACTIVE").unwrap_or_default(); + if !context.is_empty() { + let ns = managed_namespace(&self.workspace); + let _ = std::process::Command::new("kubectl") + .args([ + "--context", + &context, + "delete", + "namespace", + &ns, + "--ignore-not-found", + "--wait=false", + ]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + } +} + +#[tokio::test] +async fn managed_creates_namespace_with_labels() { + let ws = unique_workspace("mgd"); + let ns = managed_namespace(&ws); + let _cleanup = ManagedCleanup { + workspace: ws.clone(), + sandboxes: vec!["mgd-sb".into()], + }; + + let (ok, out) = run_cli(&["workspace", "create", "--name", &ws]).await; + assert!(ok, "workspace create failed: {out}"); + + // Create a sandbox — this triggers namespace creation. + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "mgd-sb", + "--", + "echo", + "managed-ok", + ]) + .await; + assert!(ok, "sandbox create failed: {out}"); + assert!( + out.contains("managed-ok"), + "sandbox output missing expected string: {out}" + ); + + // Verify the managed namespace was created. + let (ok, out) = kubectl(&["get", "namespace", &ns]).await; + assert!(ok, "managed namespace {ns} should exist: {out}"); + + // Verify labels on the namespace. + let (ok, label_out) = + kubectl(&["get", "namespace", &ns, "-o", "jsonpath={.metadata.labels}"]).await; + assert!(ok, "failed to read namespace labels: {label_out}"); + assert!( + label_out.contains("openshell.ai/managed-by"), + "namespace missing managed-by label: {label_out}" + ); + assert!( + label_out.contains("openshell.ai/gateway-id"), + "namespace missing gateway-id label: {label_out}" + ); + + // Verify the ServiceAccount was created in the managed namespace. + let (ok, _) = kubectl(&["get", "serviceaccount", "openshell-sandbox", "-n", &ns]).await; + assert!(ok, "ServiceAccount openshell-sandbox should exist in {ns}"); + + // The managed driver copies only explicitly configured image-pull Secrets + // from the gateway namespace into the workspace namespace. + let (ok, copied_secret) = kubectl(&[ + "get", + "secret", + "e2e-regcred", + "-n", + &ns, + "-o", + "jsonpath={.type}", + ]) + .await; + assert!( + ok && copied_secret.contains("kubernetes.io/dockerconfigjson"), + "configured image-pull Secret should be copied into {ns}: {copied_secret}" + ); + + // Verify SSH ingress is restricted to the gateway peer. Because Kubernetes + // NetworkPolicies are allowlists, the absence of a sandbox peer here + // denies sandbox-to-sandbox TCP 2222 traffic. + let (ok, policy) = kubectl(&[ + "get", + "networkpolicy", + "openshell-sandbox-ssh", + "-n", + &ns, + "-o", + "json", + ]) + .await; + assert!( + ok, + "managed SSH NetworkPolicy should exist in {ns}: {policy}" + ); + let policy: serde_json::Value = + serde_json::from_str(&policy).expect("managed SSH NetworkPolicy should be valid JSON"); + assert_eq!( + policy["spec"]["podSelector"]["matchLabels"]["openshell.ai/managed-by"], + "openshell" + ); + assert_eq!(policy["spec"]["ingress"][0]["ports"][0]["port"], 2222); + assert_eq!( + policy["spec"]["ingress"][0]["from"][0]["namespaceSelector"]["matchLabels"]["kubernetes.io/metadata.name"], + "openshell" + ); + assert!( + policy["spec"]["ingress"][0]["from"][0]["podSelector"]["matchLabels"] + ["app.kubernetes.io/name"] + .is_string(), + "SSH ingress peer must select gateway pods: {policy}" + ); + + // Verify sandbox CR is in the managed namespace (not the gateway namespace). + let (ok, out) = kubectl(&["get", "sandbox.agents.x-k8s.io", "-n", &ns, "-o", "name"]).await; + assert!(ok, "sandbox CR should exist in namespace {ns}: {out}"); + assert!(out.contains("mgd-sb"), "sandbox CR name mismatch: {out}"); + + // Verify the sandbox is resolvable through the OpenShell control plane. + let (ok, out) = run_cli(&["sandbox", "list", "--workspace", &ws]).await; + assert!(ok, "sandbox list failed: {out}"); + assert!( + out.contains("mgd-sb"), + "sandbox list should find mgd-sb via control plane: {out}" + ); + + let (ok, out) = run_cli(&["sandbox", "get", "mgd-sb", "--workspace", &ws]).await; + assert!(ok, "sandbox get failed: {out}"); + assert!( + out.contains("mgd-sb"), + "sandbox get should resolve mgd-sb via control plane: {out}" + ); + + // Verify sandbox delete works through the control plane (uses sandbox_lookup_selector). + let (ok, out) = run_cli(&["sandbox", "delete", "mgd-sb", "--workspace", &ws]).await; + assert!(ok, "sandbox delete failed: {out}"); + + // Wait for the sandbox CR to be fully removed (deletion is asynchronous). + wait_sandbox_gone(&ws, "mgd-sb").await; +} + +#[tokio::test] +async fn managed_namespace_survives_with_remaining_sandboxes() { + let ws = unique_workspace("mgd2"); + let ns = managed_namespace(&ws); + let _cleanup = ManagedCleanup { + workspace: ws.clone(), + sandboxes: vec!["sb-a".into(), "sb-b".into()], + }; + + let (ok, out) = run_cli(&["workspace", "create", "--name", &ws]).await; + assert!(ok, "workspace create failed: {out}"); + + // Create two sandboxes. + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "sb-a", + "--", + "echo", + "a", + ]) + .await; + assert!(ok, "sandbox sb-a create failed: {out}"); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "sb-b", + "--", + "echo", + "b", + ]) + .await; + assert!(ok, "sandbox sb-b create failed: {out}"); + + // Delete first sandbox — namespace should survive because sb-b still exists. + let (ok, out) = run_cli(&["sandbox", "delete", "sb-a", "--workspace", &ws]).await; + assert!(ok, "sandbox sb-a delete failed: {out}"); + + // Wait for sb-a to be fully removed before checking namespace state. + wait_sandbox_gone(&ws, "sb-a").await; + + let (ok, _) = kubectl(&["get", "namespace", &ns]).await; + assert!(ok, "managed namespace {ns} should still exist with sb-b"); + + // Verify sb-b's CR is still in the managed namespace. + let (ok, out) = kubectl(&["get", "sandbox.agents.x-k8s.io", "-n", &ns, "-o", "name"]).await; + assert!(ok, "sandbox CRs should still exist in {ns}: {out}"); + assert!( + out.contains("sb-b"), + "sb-b CR should still be present: {out}" + ); + + // Verify sb-b is still resolvable through the OpenShell control plane. + let (ok, out) = run_cli(&["sandbox", "list", "--workspace", &ws]).await; + assert!(ok, "sandbox list failed: {out}"); + assert!( + out.contains("sb-b"), + "sandbox list should find sb-b via control plane: {out}" + ); +} + +#[tokio::test] +async fn managed_isolates_workspaces_into_separate_namespaces() { + let ws_a = unique_workspace("iso-a"); + let ws_b = unique_workspace("iso-b"); + let ns_a = managed_namespace(&ws_a); + let ns_b = managed_namespace(&ws_b); + let _cleanup_a = ManagedCleanup { + workspace: ws_a.clone(), + sandboxes: vec!["sb-iso-a".into()], + }; + let _cleanup_b = ManagedCleanup { + workspace: ws_b.clone(), + sandboxes: vec!["sb-iso-b".into()], + }; + + // Create two workspaces with sandboxes. + let (ok, out) = run_cli(&["workspace", "create", "--name", &ws_a]).await; + assert!(ok, "workspace A create failed: {out}"); + let (ok, out) = run_cli(&["workspace", "create", "--name", &ws_b]).await; + assert!(ok, "workspace B create failed: {out}"); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws_a, + "--name", + "sb-iso-a", + "--", + "echo", + "a", + ]) + .await; + assert!(ok, "sandbox A create failed: {out}"); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws_b, + "--name", + "sb-iso-b", + "--", + "echo", + "b", + ]) + .await; + assert!(ok, "sandbox B create failed: {out}"); + + // Verify each workspace has its own namespace. + assert_ne!(ns_a, ns_b, "namespaces should differ"); + + let (ok, _) = kubectl(&["get", "namespace", &ns_a]).await; + assert!(ok, "namespace {ns_a} should exist"); + let (ok, _) = kubectl(&["get", "namespace", &ns_b]).await; + assert!(ok, "namespace {ns_b} should exist"); + + // Verify sandbox CRs are in the correct namespaces (no cross-contamination). + let (ok, out) = kubectl(&["get", "sandbox.agents.x-k8s.io", "-n", &ns_a, "-o", "name"]).await; + assert!(ok, "failed to list CRs in {ns_a}: {out}"); + assert!(out.contains("sb-iso-a"), "sb-iso-a should be in {ns_a}"); + assert!( + !out.contains("sb-iso-b"), + "sb-iso-b should NOT be in {ns_a}" + ); + + let (ok, out) = kubectl(&["get", "sandbox.agents.x-k8s.io", "-n", &ns_b, "-o", "name"]).await; + assert!(ok, "failed to list CRs in {ns_b}: {out}"); + assert!(out.contains("sb-iso-b"), "sb-iso-b should be in {ns_b}"); + assert!( + !out.contains("sb-iso-a"), + "sb-iso-a should NOT be in {ns_b}" + ); + + // Verify workspace isolation through the OpenShell control plane. + let (ok, out) = run_cli(&["sandbox", "list", "--workspace", &ws_a]).await; + assert!(ok, "sandbox list ws_a failed: {out}"); + assert!( + out.contains("sb-iso-a"), + "sandbox list ws_a should find sb-iso-a: {out}" + ); + assert!( + !out.contains("sb-iso-b"), + "sandbox list ws_a should NOT find sb-iso-b: {out}" + ); + + let (ok, out) = run_cli(&["sandbox", "list", "--workspace", &ws_b]).await; + assert!(ok, "sandbox list ws_b failed: {out}"); + assert!( + out.contains("sb-iso-b"), + "sandbox list ws_b should find sb-iso-b: {out}" + ); + assert!( + !out.contains("sb-iso-a"), + "sandbox list ws_b should NOT find sb-iso-a: {out}" + ); +} + +#[tokio::test] +async fn managed_workspace_delete_removes_namespace() { + let ws = unique_workspace("mgddel"); + let ns = managed_namespace(&ws); + let _cleanup = ManagedCleanup { + workspace: ws.clone(), + sandboxes: vec!["del-sb".into()], + }; + + let (ok, out) = run_cli(&["workspace", "create", "--name", &ws]).await; + assert!(ok, "workspace create failed: {out}"); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "del-sb", + "--", + "echo", + "del-ok", + ]) + .await; + assert!(ok, "sandbox create failed: {out}"); + assert!( + out.contains("del-ok"), + "sandbox output missing expected string: {out}" + ); + + let (ok, _) = kubectl(&["get", "namespace", &ns]).await; + assert!( + ok, + "managed namespace {ns} should exist after sandbox create" + ); + + let (ok, out) = run_cli(&["sandbox", "delete", "del-sb", "--workspace", &ws]).await; + assert!(ok, "sandbox delete failed: {out}"); + + wait_sandbox_gone(&ws, "del-sb").await; + + let (ok, out) = run_cli(&["workspace", "delete", &ws]).await; + assert!(ok, "workspace delete failed: {out}"); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let (exists, _) = kubectl(&["get", "namespace", &ns]).await; + if !exists { + break; + } + if tokio::time::Instant::now() >= deadline { + panic!("managed namespace {ns} still exists 30s after workspace delete"); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } +} + +#[tokio::test] +async fn managed_tls_secret_copied_to_namespace() { + let (ok, config_out) = kubectl(&[ + "get", + "configmap", + "openshell-config", + "-n", + "openshell", + "-o", + "jsonpath={.data.gateway\\.toml}", + ]) + .await; + if !ok || !config_out.contains("client_tls_secret_name") { + eprintln!("SKIP: client_tls_secret_name not configured; TLS secret copying disabled"); + return; + } + + let ws = unique_workspace("mgdtls"); + let ns = managed_namespace(&ws); + let _cleanup = ManagedCleanup { + workspace: ws.clone(), + sandboxes: vec!["tls-sb".into()], + }; + + let (ok, out) = run_cli(&["workspace", "create", "--name", &ws]).await; + assert!(ok, "workspace create failed: {out}"); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "tls-sb", + "--", + "echo", + "tls-ok", + ]) + .await; + assert!(ok, "sandbox create failed: {out}"); + assert!( + out.contains("tls-ok"), + "sandbox output missing expected string: {out}" + ); + + let (ok, out) = kubectl(&["get", "secret", "openshell-client-tls", "-n", &ns]).await; + assert!( + ok, + "TLS secret openshell-client-tls should be copied to managed namespace {ns}: {out}" + ); + + let (ok, label_out) = kubectl(&[ + "get", + "secret", + "openshell-client-tls", + "-n", + &ns, + "-o", + "jsonpath={.metadata.labels}", + ]) + .await; + assert!(ok, "failed to read TLS secret labels: {label_out}"); + assert!( + label_out.contains("openshell.ai/managed-by"), + "copied TLS secret missing managed-by label: {label_out}" + ); +} + +#[tokio::test] +async fn managed_rejects_namespace_owned_by_different_gateway() { + let ws = unique_workspace("mgdown"); + let ns = managed_namespace(&ws); + let _cleanup = ManagedCleanup { + workspace: ws.clone(), + sandboxes: vec![], + }; + + let (ok, out) = kubectl(&["create", "namespace", &ns]).await; + assert!(ok, "failed to pre-create namespace {ns}: {out}"); + + let (ok, out) = kubectl(&[ + "label", + "namespace", + &ns, + "openshell.ai/managed-by=openshell", + "openshell.ai/gateway-id=wrong-gateway", + ]) + .await; + assert!(ok, "failed to label namespace: {out}"); + + let (ok, out) = run_cli(&["workspace", "create", "--name", &ws]).await; + assert!(ok, "workspace create failed: {out}"); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "conflict-sb", + "--", + "echo", + "nope", + ]) + .await; + assert!( + !ok, + "sandbox create should fail for namespace owned by different gateway, but succeeded: {out}" + ); +} + +#[tokio::test] +async fn managed_full_lifecycle_with_multiple_sandboxes() { + let ws = unique_workspace("mgdlc"); + let ns = managed_namespace(&ws); + let _cleanup = ManagedCleanup { + workspace: ws.clone(), + sandboxes: vec!["lc-a".into(), "lc-b".into()], + }; + + let (ok, out) = run_cli(&["workspace", "create", "--name", &ws]).await; + assert!(ok, "workspace create failed: {out}"); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "lc-a", + "--", + "echo", + "a", + ]) + .await; + assert!(ok, "sandbox lc-a create failed: {out}"); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "lc-b", + "--", + "echo", + "b", + ]) + .await; + assert!(ok, "sandbox lc-b create failed: {out}"); + + let (ok, _) = kubectl(&["get", "namespace", &ns]).await; + assert!(ok, "managed namespace {ns} should exist"); + + let (ok, out) = run_cli(&["sandbox", "delete", "lc-a", "--workspace", &ws]).await; + assert!(ok, "sandbox lc-a delete failed: {out}"); + + wait_sandbox_gone(&ws, "lc-a").await; + + let (ok, _) = kubectl(&["get", "namespace", &ns]).await; + assert!( + ok, + "managed namespace {ns} should still exist with lc-b remaining" + ); + + let (ok, out) = run_cli(&["sandbox", "delete", "lc-b", "--workspace", &ws]).await; + assert!(ok, "sandbox lc-b delete failed: {out}"); + + wait_sandbox_gone(&ws, "lc-b").await; + + let (ok, out) = run_cli(&["workspace", "delete", &ws]).await; + assert!(ok, "workspace delete failed: {out}"); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let (exists, _) = kubectl(&["get", "namespace", &ns]).await; + if !exists { + break; + } + if tokio::time::Instant::now() >= deadline { + panic!("managed namespace {ns} still exists 30s after full lifecycle cleanup"); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } +} + +#[tokio::test] +async fn managed_stop_waits_for_workspace_pod_to_disappear() { + let (ok, sandbox_api_version) = kubectl(&[ + "get", + "crd", + "sandboxes.agents.x-k8s.io", + "-o", + "jsonpath={.spec.versions[?(@.storage==true)].name}", + ]) + .await; + assert!( + ok, + "failed to resolve Sandbox API version: {sandbox_api_version}" + ); + if sandbox_api_version.trim() != "v1alpha1" { + eprintln!("SKIP: legacy pod-disappearance fallback applies only to Sandbox API v1alpha1"); + return; + } + + let ws = unique_workspace("mgdstop"); + let ns = managed_namespace(&ws); + let sandbox = "stop-sb"; + let _cleanup = ManagedCleanup { + workspace: ws.clone(), + sandboxes: vec![sandbox.into()], + }; + + let (ok, out) = run_cli(&["workspace", "create", "--name", &ws]).await; + assert!(ok, "workspace create failed: {out}"); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + sandbox, + "--", + "echo", + "ready", + ]) + .await; + assert!(ok, "sandbox create failed: {out}"); + + let (ok, pod_name) = kubectl(&[ + "get", + "sandbox", + sandbox, + "-n", + &ns, + "-o", + "jsonpath={.metadata.annotations.agents\\.x-k8s\\.io/pod-name}", + ]) + .await; + assert!(ok, "failed to resolve sandbox pod name: {pod_name}"); + let pod_name = pod_name.trim(); + assert!(!pod_name.is_empty(), "sandbox pod annotation was empty"); + + let (ok, out) = run_cli(&["sandbox", "stop", sandbox, "--workspace", &ws]).await; + assert!(ok, "sandbox stop failed: {out}"); + + let (exists, out) = kubectl(&["get", "pod", pod_name, "-n", &ns]).await; + assert!( + !exists, + "sandbox stop returned before workspace pod {pod_name} disappeared: {out}" + ); +} + +#[tokio::test] +async fn managed_rejects_invalid_dns1123_sandbox_name() { + let ws = unique_workspace("mgddns"); + let _cleanup = ManagedCleanup { + workspace: ws.clone(), + sandboxes: vec![], + }; + + let (ok, out) = run_cli(&["workspace", "create", "--name", &ws]).await; + assert!(ok, "workspace create failed: {out}"); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "my_bad_name", + "--", + "echo", + "nope", + ]) + .await; + assert!( + !ok, + "sandbox with underscore name should be rejected: {out}" + ); + assert!( + out.contains("lowercase alphanumeric"), + "error should mention character constraint: {out}" + ); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "MyBadName", + "--", + "echo", + "nope", + ]) + .await; + assert!(!ok, "sandbox with uppercase name should be rejected: {out}"); + assert!( + out.contains("lowercase alphanumeric"), + "error should mention character constraint: {out}" + ); + + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ws, + "--name", + "trailing-", + "--", + "echo", + "nope", + ]) + .await; + assert!( + !ok, + "sandbox with trailing hyphen should be rejected: {out}" + ); + let normalized: String = out + .chars() + .filter(|c| *c != '│') + .collect::() + .split_whitespace() + .collect::>() + .join(" "); + assert!( + normalized.contains("must not start or end with a hyphen"), + "error should mention hyphen constraint: {out}" + ); +} diff --git a/e2e/rust/tests/workspace_namespace_operator.rs b/e2e/rust/tests/workspace_namespace_operator.rs new file mode 100644 index 0000000000..f421aa6ada --- /dev/null +++ b/e2e/rust/tests/workspace_namespace_operator.rs @@ -0,0 +1,450 @@ +// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +#![cfg(feature = "e2e-kubernetes-workspace-operator")] + +//! E2E tests for operator workspace mode. +//! +//! The gateway is deployed with `workspace_mode = "operator"` and +//! `operator_namespace_label = "openshell.ai/e2e-operator-workspace=true"`. +//! Namespaces must be pre-provisioned and labeled before sandbox creation. +//! The gateway discovers valid namespaces via the label selector. + +use std::process::Stdio; +use std::time::Duration; + +use openshell_e2e::harness::binary::{openshell_bin, openshell_cmd}; +use openshell_e2e::harness::output::strip_ansi; + +const OPERATOR_LABEL: &str = "openshell.ai/e2e-operator-workspace=true"; +const SA_NAME: &str = "openshell-sandbox"; + +fn kube_context() -> String { + std::env::var("OPENSHELL_E2E_KUBE_CONTEXT_ACTIVE") + .expect("OPENSHELL_E2E_KUBE_CONTEXT_ACTIVE must be set") +} + +async fn kubectl(args: &[&str]) -> (bool, String) { + let context = kube_context(); + let output = tokio::process::Command::new("kubectl") + .arg("--context") + .arg(&context) + .args(args) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .output() + .await + .expect("failed to spawn kubectl"); + + let combined = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + (output.status.success(), combined) +} + +async fn run_cli(args: &[&str]) -> (bool, String) { + let mut cmd = openshell_cmd(); + cmd.args(args).stdout(Stdio::piped()).stderr(Stdio::piped()); + let output = cmd.output().await.expect("failed to spawn openshell"); + let combined = format!( + "{}{}", + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ); + (output.status.success(), strip_ansi(&combined)) +} + +fn unique_namespace(prefix: &str) -> String { + let ts = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap_or_default() + .as_millis() + % 100_000; + format!("{prefix}-{ts}") +} + +async fn wait_sandbox_gone(workspace: &str, sandbox: &str) { + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let (ok, out) = run_cli(&["sandbox", "list", "--workspace", workspace]).await; + if ok && !out.contains(sandbox) { + return; + } + if tokio::time::Instant::now() >= deadline { + panic!( + "sandbox {sandbox} still listed in workspace {workspace} 30s after delete: {out}" + ); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } +} + +async fn provision_operator_namespace(name: &str) { + let (ok, out) = kubectl(&["create", "namespace", name]).await; + assert!(ok, "failed to create namespace {name}: {out}"); + + let (ok, out) = kubectl(&["label", "namespace", name, OPERATOR_LABEL]).await; + assert!(ok, "failed to label namespace {name}: {out}"); + + let (ok, out) = kubectl(&["create", "serviceaccount", SA_NAME, "-n", name]).await; + assert!(ok, "failed to create SA in {name}: {out}"); +} + +async fn delete_namespace(name: &str) { + let _ = kubectl(&[ + "delete", + "namespace", + name, + "--ignore-not-found", + "--wait=false", + ]) + .await; +} + +struct OperatorCleanup { + workspace: String, + namespace: String, + sandboxes: Vec, +} + +impl Drop for OperatorCleanup { + fn drop(&mut self) { + let bin = openshell_bin(); + for sb in &self.sandboxes { + let _ = std::process::Command::new(&bin) + .args(["sandbox", "delete", sb, "--workspace", &self.workspace]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + let _ = std::process::Command::new(&bin) + .args(["workspace", "delete", &self.workspace]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + let context = std::env::var("OPENSHELL_E2E_KUBE_CONTEXT_ACTIVE").unwrap_or_default(); + if !context.is_empty() { + let _ = std::process::Command::new("kubectl") + .args([ + "--context", + &context, + "delete", + "namespace", + &self.namespace, + "--ignore-not-found", + "--wait=false", + ]) + .stdout(Stdio::null()) + .stderr(Stdio::null()) + .status(); + } + } +} + +#[tokio::test] +async fn operator_sandbox_in_labeled_namespace() { + let ns = unique_namespace("op"); + let _cleanup = OperatorCleanup { + workspace: ns.clone(), + namespace: ns.clone(), + sandboxes: vec!["op-sb".into()], + }; + + // Pre-provision the namespace with the operator label and ServiceAccount. + provision_operator_namespace(&ns).await; + + // Create a workspace matching the namespace name (operator mode: 1:1 mapping). + let (ok, out) = run_cli(&["workspace", "create", "--name", &ns]).await; + assert!(ok, "workspace create failed: {out}"); + + // Poll until the gateway's namespace watcher discovers the labeled namespace + // and sandbox creation succeeds (up to 30s). + let mut sandbox_out = String::new(); + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ns, + "--name", + "op-sb", + "--", + "echo", + "operator-ok", + ]) + .await; + if ok { + sandbox_out = out; + break; + } + if tokio::time::Instant::now() >= deadline { + panic!("sandbox create did not succeed within 30s: {out}"); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + assert!( + sandbox_out.contains("operator-ok"), + "sandbox output missing expected string: {sandbox_out}" + ); + + // Verify the sandbox CR lives in the pre-provisioned namespace. + let (ok, out) = kubectl(&["get", "sandbox.agents.x-k8s.io", "-n", &ns, "-o", "name"]).await; + assert!(ok, "sandbox CR should exist in namespace {ns}: {out}"); + assert!( + out.contains("op-sb"), + "sandbox CR name should be bare 'op-sb', got: {out}" + ); + + // Verify sandbox is resolvable through the OpenShell control plane. + let (ok, out) = run_cli(&["sandbox", "list", "--workspace", &ns]).await; + assert!(ok, "sandbox list failed: {out}"); + assert!( + out.contains("op-sb"), + "sandbox list should find op-sb via control plane: {out}" + ); + + let (ok, out) = run_cli(&["sandbox", "get", "op-sb", "--workspace", &ns]).await; + assert!(ok, "sandbox get failed: {out}"); + assert!( + out.contains("op-sb"), + "sandbox get should resolve op-sb via control plane: {out}" + ); + + // Verify sandbox delete works through the control plane. + let (ok, out) = run_cli(&["sandbox", "delete", "op-sb", "--workspace", &ns]).await; + assert!(ok, "sandbox delete failed: {out}"); + + // Wait for the sandbox CR to be fully removed (deletion is asynchronous). + wait_sandbox_gone(&ns, "op-sb").await; + + let (ok, out) = run_cli(&["workspace", "delete", &ns]).await; + assert!(ok, "workspace delete failed: {out}"); + + delete_namespace(&ns).await; +} + +#[tokio::test] +async fn operator_rejects_unlabeled_namespace() { + let ns = unique_namespace("opun"); + let _cleanup = OperatorCleanup { + workspace: ns.clone(), + namespace: ns.clone(), + sandboxes: vec![], + }; + + // Create namespace WITHOUT the operator label. + let (ok, out) = kubectl(&["create", "namespace", &ns]).await; + assert!(ok, "failed to create namespace: {out}"); + + // Create the ServiceAccount (not the label — that's the point). + let (ok, _) = kubectl(&["create", "serviceaccount", SA_NAME, "-n", &ns]).await; + assert!(ok, "failed to create SA"); + + // Create workspace. + let (ok, out) = run_cli(&["workspace", "create", "--name", &ns]).await; + assert!(ok, "workspace create failed: {out}"); + + // Attempt sandbox creation — should fail because namespace is not in the allowlist. + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ns, + "--name", + "should-fail", + "--", + "echo", + "nope", + ]) + .await; + assert!( + !ok, + "sandbox create should fail for unlabeled namespace, but succeeded: {out}" + ); + + // Clean up. + let _ = run_cli(&["workspace", "delete", &ns]).await; + delete_namespace(&ns).await; +} + +#[tokio::test] +async fn operator_rejects_nonexistent_namespace() { + let ns = unique_namespace("opne"); + let _cleanup = OperatorCleanup { + workspace: ns.clone(), + namespace: ns.clone(), + sandboxes: vec![], + }; + + // Create workspace with no matching namespace at all. + let (ok, out) = run_cli(&["workspace", "create", "--name", &ns]).await; + assert!(ok, "workspace create failed: {out}"); + + // Attempt sandbox creation — should fail. + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ns, + "--name", + "should-fail", + "--", + "echo", + "nope", + ]) + .await; + assert!( + !ok, + "sandbox create should fail for nonexistent namespace, but succeeded: {out}" + ); + + // Clean up. + let _ = run_cli(&["workspace", "delete", &ns]).await; +} + +#[tokio::test] +async fn operator_workspace_delete_preserves_namespace() { + let ns = unique_namespace("opdel"); + let _cleanup = OperatorCleanup { + workspace: ns.clone(), + namespace: ns.clone(), + sandboxes: vec!["opdel-sb".into()], + }; + + provision_operator_namespace(&ns).await; + + let (ok, out) = run_cli(&["workspace", "create", "--name", &ns]).await; + assert!(ok, "workspace create failed: {out}"); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ns, + "--name", + "opdel-sb", + "--", + "echo", + "opdel-ok", + ]) + .await; + if ok { + break; + } + if tokio::time::Instant::now() >= deadline { + panic!("sandbox create did not succeed within 30s: {out}"); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + + let (ok, out) = run_cli(&["sandbox", "delete", "opdel-sb", "--workspace", &ns]).await; + assert!(ok, "sandbox delete failed: {out}"); + + wait_sandbox_gone(&ns, "opdel-sb").await; + + let (ok, out) = run_cli(&["workspace", "delete", &ns]).await; + assert!(ok, "workspace delete failed: {out}"); + + let (ok, out) = kubectl(&["get", "namespace", &ns]).await; + assert!( + ok, + "operator namespace {ns} should still exist after workspace delete: {out}" + ); + + let (ok, label_out) = + kubectl(&["get", "namespace", &ns, "-o", "jsonpath={.metadata.labels}"]).await; + assert!(ok, "failed to read namespace labels: {label_out}"); + assert!( + label_out.contains("openshell.ai/e2e-operator-workspace"), + "operator label should be intact after workspace delete: {label_out}" + ); + + delete_namespace(&ns).await; +} + +#[tokio::test] +async fn operator_label_removal_blocks_sandbox_creation() { + let ns = unique_namespace("oplbl"); + let _cleanup = OperatorCleanup { + workspace: ns.clone(), + namespace: ns.clone(), + sandboxes: vec!["lbl-sb1".into()], + }; + + provision_operator_namespace(&ns).await; + + let (ok, out) = run_cli(&["workspace", "create", "--name", &ns]).await; + assert!(ok, "workspace create failed: {out}"); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let (ok, out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ns, + "--name", + "lbl-sb1", + "--", + "echo", + "lbl-ok", + ]) + .await; + if ok { + break; + } + if tokio::time::Instant::now() >= deadline { + panic!("sandbox create did not succeed within 30s: {out}"); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + + let (ok, out) = run_cli(&["sandbox", "delete", "lbl-sb1", "--workspace", &ns]).await; + assert!(ok, "sandbox lbl-sb1 delete failed: {out}"); + + wait_sandbox_gone(&ns, "lbl-sb1").await; + + let (ok, out) = kubectl(&[ + "label", + "namespace", + &ns, + "openshell.ai/e2e-operator-workspace-", + ]) + .await; + assert!(ok, "failed to remove operator label: {out}"); + + let deadline = tokio::time::Instant::now() + Duration::from_secs(30); + loop { + let (ok, _out) = run_cli(&[ + "sandbox", + "create", + "--workspace", + &ns, + "--name", + "lbl-sb2", + "--", + "echo", + "should-fail", + ]) + .await; + if !ok { + break; + } + // Sandbox was created despite label removal — clean it up and retry. + let _ = run_cli(&["sandbox", "delete", "lbl-sb2", "--workspace", &ns]).await; + if tokio::time::Instant::now() >= deadline { + panic!( + "sandbox creation still succeeds 30s after operator label removal; \ + watcher did not remove namespace from allowlist" + ); + } + tokio::time::sleep(Duration::from_secs(2)).await; + } + + delete_namespace(&ns).await; +} diff --git a/e2e/with-kube-gateway.sh b/e2e/with-kube-gateway.sh index cfc886ffcd..f6d0efc4ec 100755 --- a/e2e/with-kube-gateway.sh +++ b/e2e/with-kube-gateway.sh @@ -277,6 +277,22 @@ cleanup() { --ignore-not-found >/dev/null 2>&1 || true fi + # Sweep managed-mode and operator-mode workspace namespaces before + # uninstalling the Helm release (ClusterRole still needed for deletion). + if command -v kubectl >/dev/null 2>&1 && [ -n "${KUBE_CONTEXT}" ]; then + for label in "openshell.ai/managed-by=openshell" \ + "openshell.ai/e2e-operator-workspace=true"; do + ns_list="$(kctl get namespaces -l "${label}" -o name 2>/dev/null || true)" + if [ -n "${ns_list}" ]; then + echo "Cleaning up namespaces with label ${label}..." + echo "${ns_list}" | while read -r ns_ref; do + kctl delete "${ns_ref}" --wait=false --ignore-not-found \ + 2>/dev/null || true + done + fi + done + fi + if [ "${HELM_INSTALLED}" = "1" ] && [ -n "${KUBE_CONTEXT}" ] && [ -n "${NAMESPACE}" ]; then if command -v helm >/dev/null 2>&1; then helmctl uninstall "${RELEASE_NAME}" --namespace "${NAMESPACE}" --wait \ @@ -798,6 +814,14 @@ else --wait --timeout 5m HELM_INSTALLED=1 + if [ -n "${OPENSHELL_E2E_KUBE_IMAGE_PULL_SECRET:-}" ]; then + kctl -n "${NAMESPACE}" create secret docker-registry \ + "${OPENSHELL_E2E_KUBE_IMAGE_PULL_SECRET}" \ + --docker-server=registry.example.test \ + --docker-username=e2e-user \ + --docker-password=e2e-password + fi + LOCAL_PORT="$(e2e_pick_port)" echo "Starting kubectl port-forward svc/openshell ${LOCAL_PORT}:8080..." kctl -n "${NAMESPACE}" port-forward "svc/openshell" \ diff --git a/examples/governance-interceptor/Cargo.lock b/examples/governance-interceptor/Cargo.lock index 1aa370096f..02aaefe8a7 100644 --- a/examples/governance-interceptor/Cargo.lock +++ b/examples/governance-interceptor/Cargo.lock @@ -55,15 +55,6 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" -[[package]] -name = "autotools" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef941527c41b0fc0dd48511a8154cd5fc7e29200a0ff8b7203c5d777dbc795cf" -dependencies = [ - "cc", -] - [[package]] name = "axum" version = "0.8.9" @@ -180,6 +171,12 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + [[package]] name = "core-foundation" version = "0.10.1" @@ -811,6 +808,18 @@ version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084" +[[package]] +name = "nix" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "num-bigint" version = "0.4.6" @@ -864,17 +873,21 @@ checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" name = "openshell-core" version = "0.0.0" dependencies = [ + "async-trait", "base64", "glob", "ipnet", "miette", + "nix", + "openshell-extension-core", "prost", "prost-types", - "protobuf-src", + "protoc-bin-vendored", "serde", "serde_json", "thiserror", "tokio", + "tokio-stream", "tonic", "tonic-prost", "tonic-prost-build", @@ -882,6 +895,18 @@ dependencies = [ "url", ] +[[package]] +name = "openshell-extension-core" +version = "0.0.0" +dependencies = [ + "hyper-util", + "serde", + "thiserror", + "tokio", + "tonic", + "tower", +] + [[package]] name = "openshell-governance-interceptor-example" version = "0.0.0" @@ -920,6 +945,7 @@ version = "0.0.0" dependencies = [ "glob", "openshell-core", + "openshell-policy", "serde", "serde_json", "serde_yml", @@ -1125,14 +1151,69 @@ dependencies = [ ] [[package]] -name = "protobuf-src" -version = "1.1.0+21.5" +name = "protoc-bin-vendored" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7ac8852baeb3cc6fb83b93646fb93c0ffe5d14bf138c945ceb4b9948ee0e3c1" +checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa" dependencies = [ - "autotools", + "protoc-bin-vendored-linux-aarch_64", + "protoc-bin-vendored-linux-ppcle_64", + "protoc-bin-vendored-linux-s390_64", + "protoc-bin-vendored-linux-x86_32", + "protoc-bin-vendored-linux-x86_64", + "protoc-bin-vendored-macos-aarch_64", + "protoc-bin-vendored-macos-x86_64", + "protoc-bin-vendored-win32", ] +[[package]] +name = "protoc-bin-vendored-linux-aarch_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c" + +[[package]] +name = "protoc-bin-vendored-linux-ppcle_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c" + +[[package]] +name = "protoc-bin-vendored-linux-s390_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0" + +[[package]] +name = "protoc-bin-vendored-linux-x86_32" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5" + +[[package]] +name = "protoc-bin-vendored-linux-x86_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78" + +[[package]] +name = "protoc-bin-vendored-macos-aarch_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092" + +[[package]] +name = "protoc-bin-vendored-macos-x86_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756" + +[[package]] +name = "protoc-bin-vendored-win32" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" + [[package]] name = "pulldown-cmark" version = "0.13.4" @@ -1260,6 +1341,7 @@ checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f" dependencies = [ "log", "once_cell", + "ring", "rustls-pki-types", "rustls-webpki", "subtle", diff --git a/examples/governance-interceptor/src/main.rs b/examples/governance-interceptor/src/main.rs index 5ad8c12266..4e9b38f409 100644 --- a/examples/governance-interceptor/src/main.rs +++ b/examples/governance-interceptor/src/main.rs @@ -336,6 +336,7 @@ impl GovernanceInterceptorService { &[GatewayInterceptorPhase::Validate], ), ], + expected_audience: String::new(), } } diff --git a/examples/supervisor-middleware-content-guard/Cargo.lock b/examples/supervisor-middleware-content-guard/Cargo.lock index f397d82dee..9bb8d1feee 100644 --- a/examples/supervisor-middleware-content-guard/Cargo.lock +++ b/examples/supervisor-middleware-content-guard/Cargo.lock @@ -99,15 +99,6 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" -[[package]] -name = "autotools" -version = "0.2.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef941527c41b0fc0dd48511a8154cd5fc7e29200a0ff8b7203c5d777dbc795cf" -dependencies = [ - "cc", -] - [[package]] name = "axum" version = "0.8.9" @@ -852,18 +843,21 @@ checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" name = "openshell-core" version = "0.0.0" dependencies = [ + "async-trait", "base64", "glob", "ipnet", "miette", "nix", + "openshell-extension-core", "prost", "prost-types", - "protobuf-src", + "protoc-bin-vendored", "serde", "serde_json", "thiserror", "tokio", + "tokio-stream", "tonic", "tonic-prost", "tonic-prost-build", @@ -871,6 +865,18 @@ dependencies = [ "url", ] +[[package]] +name = "openshell-extension-core" +version = "0.0.0" +dependencies = [ + "hyper-util", + "serde", + "thiserror", + "tokio", + "tonic", + "tower", +] + [[package]] name = "openshell-supervisor-middleware-content-guard" version = "0.0.0" @@ -879,6 +885,7 @@ dependencies = [ "openshell-core", "prost-types", "tokio", + "tokio-stream", "tonic", ] @@ -1042,14 +1049,69 @@ dependencies = [ ] [[package]] -name = "protobuf-src" -version = "1.1.0+21.5" +name = "protoc-bin-vendored" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c7ac8852baeb3cc6fb83b93646fb93c0ffe5d14bf138c945ceb4b9948ee0e3c1" +checksum = "d1c381df33c98266b5f08186583660090a4ffa0889e76c7e9a5e175f645a67fa" dependencies = [ - "autotools", + "protoc-bin-vendored-linux-aarch_64", + "protoc-bin-vendored-linux-ppcle_64", + "protoc-bin-vendored-linux-s390_64", + "protoc-bin-vendored-linux-x86_32", + "protoc-bin-vendored-linux-x86_64", + "protoc-bin-vendored-macos-aarch_64", + "protoc-bin-vendored-macos-x86_64", + "protoc-bin-vendored-win32", ] +[[package]] +name = "protoc-bin-vendored-linux-aarch_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c350df4d49b5b9e3ca79f7e646fde2377b199e13cfa87320308397e1f37e1a4c" + +[[package]] +name = "protoc-bin-vendored-linux-ppcle_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a55a63e6c7244f19b5c6393f025017eb5d793fd5467823a099740a7a4222440c" + +[[package]] +name = "protoc-bin-vendored-linux-s390_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dba5565db4288e935d5330a07c264a4ee8e4a5b4a4e6f4e83fad824cc32f3b0" + +[[package]] +name = "protoc-bin-vendored-linux-x86_32" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8854774b24ee28b7868cd71dccaae8e02a2365e67a4a87a6cd11ee6cdbdf9cf5" + +[[package]] +name = "protoc-bin-vendored-linux-x86_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b38b07546580df720fa464ce124c4b03630a6fb83e05c336fea2a241df7e5d78" + +[[package]] +name = "protoc-bin-vendored-macos-aarch_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89278a9926ce312e51f1d999fee8825d324d603213344a9a706daa009f1d8092" + +[[package]] +name = "protoc-bin-vendored-macos-x86_64" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81745feda7ccfb9471d7a4de888f0652e806d5795b61480605d4943176299756" + +[[package]] +name = "protoc-bin-vendored-win32" +version = "3.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95067976aca6421a523e491fce939a3e65249bac4b977adee0ee9771568e8aa3" + [[package]] name = "pulldown-cmark" version = "0.13.4" @@ -1164,6 +1226,7 @@ checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f" dependencies = [ "log", "once_cell", + "ring", "rustls-pki-types", "rustls-webpki", "subtle", diff --git a/examples/supervisor-middleware-content-guard/Cargo.toml b/examples/supervisor-middleware-content-guard/Cargo.toml index eceaeac509..ef0d1f47c3 100644 --- a/examples/supervisor-middleware-content-guard/Cargo.toml +++ b/examples/supervisor-middleware-content-guard/Cargo.toml @@ -17,6 +17,7 @@ clap = { version = "4.5", features = ["derive"] } openshell-core = { path = "../../crates/openshell-core", default-features = false } prost-types = "0.14" tokio = { version = "1.43", features = ["macros", "rt-multi-thread"] } +tokio-stream = "0.1" tonic = { version = "0.14", features = ["transport"] } [[bin]] diff --git a/examples/supervisor-middleware-content-guard/README.md b/examples/supervisor-middleware-content-guard/README.md index 10f76effa7..53eda94210 100644 --- a/examples/supervisor-middleware-content-guard/README.md +++ b/examples/supervisor-middleware-content-guard/README.md @@ -8,10 +8,10 @@ SPDX-License-Identifier: Apache-2.0 > [!WARNING] > Supervisor middleware is a research preview. Its policy and service contracts may change without compatibility guarantees. Use it only to prototype and evaluate middleware integrations. -This example implements an operator-run supervisor middleware service. It scans UTF-8 HTTP request bodies for configured literal strings, then either replaces every match or denies the request. Findings report only aggregate counts and never include configured terms or request content. +This example implements an operator-run supervisor middleware service. It scans UTF-8 HTTP request bodies and complete client-to-upstream WebSocket text messages for configured literal strings, then either replaces every match or denies the request or message. Findings report only aggregate counts and never include configured terms or inspected content. > [!WARNING] -> This intentionally simple implementation demonstrates the supervisor middleware service contract. It is not a complete or reliable content guard and must not be used as a security control. It handles only UTF-8 request bodies and case-sensitive literal terms, merges overlapping literal match ranges before redaction, and does not address the encodings, transformations, normalization, streaming, or adversarial inputs that a production content guard must handle. +> This intentionally simple implementation demonstrates the supervisor middleware service contract. It is not a complete or reliable content guard and must not be used as a security control. It handles only UTF-8 HTTP request bodies and WebSocket text messages with case-sensitive literal terms, merges overlapping literal match ranges before redaction, and does not address encodings, transformations, normalization, binary WebSocket messages, upstream-to-client messages, or adversarial inputs that a production content guard must handle. ## Prerequisites @@ -54,7 +54,7 @@ Add the service registration to your local gateway TOML: [[openshell.supervisor.middleware]] name = "content-guard-example" grpc_endpoint = "http://host.openshell.internal:50051" -max_body_bytes = 262144 +max_payload_bytes = 262144 timeout = "500ms" ``` @@ -84,6 +84,12 @@ curl -sS https://httpbin.org/anything \ The echoed JSON body contains `[FILTERED]` instead of the configured term. +## WebSocket behavior + +For a selected WebSocket upgrade, the service accepts preflight, waits for the session-start notification, and evaluates each complete client-to-upstream text message. Redact mode returns a replacement message, while deny mode returns `content_match` and OpenShell closes the session according to middleware policy. Session-start and session-end events are notifications and do not produce results. + +The service advertises a 256 KiB limit for complete WebSocket text messages. OpenShell does not send binary messages, control frames, or upstream-to-client messages to this binding. The smoke script exercises the HTTP path; the example's unit tests cover the WebSocket lifecycle and both redact and deny results. + ## Configuration | Field | Required | Description | @@ -101,4 +107,4 @@ config: - prototype-secret ``` -The implementation supports only `HttpRequest/pre_credentials`, advertises a 256 KiB body limit, and inherits the service-wide RPC timeout. The gateway registration may set a smaller body limit. A binding can advertise a shorter timeout, but it cannot extend the operator-configured timeout. +The implementation supports `HTTP_REQUEST/PRE_CREDENTIALS` and `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`, advertises a 256 KiB limit for each operation, and inherits the service-wide RPC timeout. The gateway registration's `max_payload_bytes` may set a smaller shared limit. A binding can advertise a shorter timeout, but it cannot extend the operator-configured timeout. diff --git a/examples/supervisor-middleware-content-guard/smoke.sh b/examples/supervisor-middleware-content-guard/smoke.sh index aab026e983..509ffd403d 100755 --- a/examples/supervisor-middleware-content-guard/smoke.sh +++ b/examples/supervisor-middleware-content-guard/smoke.sh @@ -214,7 +214,7 @@ ttl_secs = 0 [[openshell.supervisor.middleware]] name = "content-guard-example" grpc_endpoint = "http://$SERVICE_HOST:$MIDDLEWARE_PORT" -max_body_bytes = 262144 +max_payload_bytes = 262144 timeout = "500ms" EOF } diff --git a/examples/supervisor-middleware-content-guard/src/main.rs b/examples/supervisor-middleware-content-guard/src/main.rs index cf36a4cb0c..c527537e74 100644 --- a/examples/supervisor-middleware-content-guard/src/main.rs +++ b/examples/supervisor-middleware-content-guard/src/main.rs @@ -6,23 +6,27 @@ use std::net::SocketAddr; use std::ops::Range; use clap::Parser; +use openshell_core::middleware::WebSocketResponseStream; use openshell_core::proto::middleware::v1::supervisor_middleware_server::{ SupervisorMiddleware, SupervisorMiddlewareServer, }; use openshell_core::proto::{ Decision, Finding, HttpRequestEvaluation, HttpRequestResult, MiddlewareBinding, MiddlewareManifest, SupervisorMiddlewareOperation, SupervisorMiddlewarePhase, - ValidateConfigRequest, ValidateConfigResponse, + ValidateConfigRequest, ValidateConfigResponse, WebSocketMessage, WebSocketMessageResult, + WebSocketPreflightAction, WebSocketPreflightDecision, WebSocketSessionEvent, + WebSocketSessionEventResult, web_socket_message, web_socket_message_result, + web_socket_session_event, web_socket_session_event_result, }; use prost_types::Struct; use prost_types::value::Kind; +use tokio_stream::{Stream, StreamExt}; use tonic::transport::Server; use tonic::{Request, Response, Status}; const MANIFEST_NAME: &str = "example/content-guard-service"; -const OPERATION: SupervisorMiddlewareOperation = SupervisorMiddlewareOperation::HttpRequest; const PHASE: SupervisorMiddlewarePhase = SupervisorMiddlewarePhase::PreCredentials; -const MAX_BODY_BYTES: u64 = 256 * 1024; +const MAX_PAYLOAD_BYTES: u64 = 256 * 1024; const DEFAULT_REPLACEMENT: &str = "[REDACTED]"; #[derive(Debug, Parser)] @@ -113,8 +117,107 @@ fn optional_string_field<'a>(config: &'a Struct, name: &str) -> Result(mut events: S) -> WebSocketResponseStream + where + S: Stream> + Send + Unpin + 'static, + { + let (results_tx, results_rx) = tokio::sync::mpsc::channel(4); + tokio::spawn(async move { + let mut config = None; + let mut started = false; + let mut sequence_lower_bound = Some(1_u64); + + while let Some(event) = events.next().await { + let event = match event { + Ok(event) => event, + Err(error) => { + let _ = results_tx.send(Err(error)).await; + break; + } + }; + let result = match event.event { + Some(web_socket_session_event::Event::Preflight(preflight)) + if config.is_none() && !started => + { + if let Err(error) = validate_phase(preflight.phase) { + Err(Status::invalid_argument(error)) + } else { + match GuardConfig::parse(preflight.config.as_ref()) { + Ok(selected_config) => { + config = Some(selected_config); + Ok(Some(WebSocketSessionEventResult { + result: Some( + web_socket_session_event_result::Result::PreflightDecision( + WebSocketPreflightDecision { + action: WebSocketPreflightAction::Inspect + as i32, + ..Default::default() + }, + ), + ), + })) + } + Err(error) => Err(Status::invalid_argument(error)), + } + } + } + Some(web_socket_session_event::Event::SessionStart(_)) + if config.is_some() && !started => + { + started = true; + Ok(None) + } + Some(web_socket_session_event::Event::Message(message)) if started => { + if let Err(error) = advance_sequence_lower_bound( + &mut sequence_lower_bound, + message.sequence, + ) { + Err(error) + } else { + let selected_config = + config.as_ref().expect("started stream has config"); + evaluate_websocket_message(selected_config, &message).map(|result| { + Some(WebSocketSessionEventResult { + result: Some( + web_socket_session_event_result::Result::MessageResult( + result, + ), + ), + }) + }) + } + } + Some(web_socket_session_event::Event::SessionEnd(_)) if config.is_some() => { + break; + } + _ => Err(Status::failed_precondition( + "invalid content guard WebSocket session lifecycle", + )), + }; + + match result { + Ok(Some(result)) => { + if results_tx.send(Ok(result)).await.is_err() { + break; + } + } + Ok(None) => {} + Err(error) => { + let _ = results_tx.send(Err(error)).await; + break; + } + } + } + }); + Box::pin(tokio_stream::wrappers::ReceiverStream::new(results_rx)) + } +} + #[tonic::async_trait] impl SupervisorMiddleware for ContentGuard { + type EvaluateWebSocketSessionStream = WebSocketResponseStream; + async fn describe( &self, _request: Request<()>, @@ -122,12 +225,21 @@ impl SupervisorMiddleware for ContentGuard { Ok(Response::new(MiddlewareManifest { name: MANIFEST_NAME.into(), service_version: env!("CARGO_PKG_VERSION").into(), - bindings: vec![MiddlewareBinding { - operation: OPERATION as i32, - phase: PHASE as i32, - max_body_bytes: MAX_BODY_BYTES, - timeout: String::new(), - }], + bindings: vec![ + MiddlewareBinding { + operation: SupervisorMiddlewareOperation::HttpRequest as i32, + phase: PHASE as i32, + max_payload_bytes: MAX_PAYLOAD_BYTES, + timeout: String::new(), + }, + MiddlewareBinding { + operation: SupervisorMiddlewareOperation::WebsocketMessage as i32, + phase: PHASE as i32, + max_payload_bytes: MAX_PAYLOAD_BYTES, + timeout: String::new(), + }, + ], + expected_audience: String::new(), })) } @@ -161,6 +273,13 @@ impl SupervisorMiddleware for ContentGuard { .map_err(|_| Status::invalid_argument("content guard requires a UTF-8 body"))?; Ok(Response::new(evaluate(&config, &body))) } + + async fn evaluate_web_socket_session( + &self, + request: Request>, + ) -> Result, Status> { + Ok(Response::new(Self::websocket_stream(request.into_inner()))) + } } fn validate_phase(phase: i32) -> Result<(), String> { @@ -209,7 +328,7 @@ fn evaluate(config: &GuardConfig, body: &str) -> HttpRequestResult { }, Mode::Deny => HttpRequestResult { decision: Decision::Deny as i32, - reason: "request body matched configured content".into(), + reason: "payload matched configured content".into(), body: Vec::new(), has_body: false, header_mutations: Vec::new(), @@ -220,6 +339,61 @@ fn evaluate(config: &GuardConfig, body: &str) -> HttpRequestResult { } } +fn evaluate_websocket_message( + config: &GuardConfig, + message: &WebSocketMessage, +) -> Result { + let Some(web_socket_message::Payload::Text(payload)) = message.payload.as_ref() else { + return Err(Status::invalid_argument( + "content guard supports only WebSocket text messages", + )); + }; + let payload_bytes = u64::try_from(payload.len()).map_err(|_| { + Status::invalid_argument("WebSocket text message length is not representable") + })?; + if payload_bytes > MAX_PAYLOAD_BYTES { + return Err(Status::invalid_argument(format!( + "WebSocket text message exceeds {MAX_PAYLOAD_BYTES} bytes" + ))); + } + let result = evaluate(config, payload); + let replacement = if result.has_body { + Some(web_socket_message_result::Replacement::Text( + String::from_utf8(result.body) + .expect("content guard replacements are constructed from UTF-8 text"), + )) + } else { + None + }; + Ok(WebSocketMessageResult { + sequence: message.sequence, + decision: result.decision, + replacement, + reason: result.reason, + findings: result.findings, + metadata: result.metadata, + reason_code: result.reason_code, + }) +} + +fn advance_sequence_lower_bound( + lower_bound: &mut Option, + sequence: u64, +) -> Result<(), Status> { + let Some(current_lower_bound) = *lower_bound else { + return Err(Status::invalid_argument( + "WebSocket message sequence must be strictly increasing", + )); + }; + if sequence < current_lower_bound { + return Err(Status::invalid_argument( + "WebSocket message sequence must be strictly increasing", + )); + } + *lower_bound = sequence.checked_add(1); + Ok(()) +} + fn find_match_ranges(body: &str, terms: &[String]) -> (Vec>, u32, u32) { let mut ranges = Vec::new(); let mut match_count = 0_u32; @@ -304,6 +478,7 @@ async fn main() -> Result<(), Box> { #[cfg(test)] mod tests { use super::*; + use openshell_core::proto::{WebSocketPreflight, WebSocketSessionEnd, WebSocketSessionStart}; use prost_types::{ListValue, Value}; use std::collections::BTreeMap; @@ -331,6 +506,109 @@ mod tests { Struct { fields } } + fn event(event: web_socket_session_event::Event) -> Result { + Ok(WebSocketSessionEvent { event: Some(event) }) + } + + #[tokio::test] + async fn manifest_advertises_http_and_websocket_bindings() { + let manifest = SupervisorMiddleware::describe(&ContentGuard, Request::new(())) + .await + .expect("describe") + .into_inner(); + + assert_eq!(manifest.bindings.len(), 2); + assert_eq!( + manifest.bindings[0].operation, + SupervisorMiddlewareOperation::HttpRequest as i32 + ); + assert_eq!(manifest.bindings[0].max_payload_bytes, MAX_PAYLOAD_BYTES); + assert_eq!( + manifest.bindings[1].operation, + SupervisorMiddlewareOperation::WebsocketMessage as i32 + ); + assert_eq!(manifest.bindings[1].max_payload_bytes, MAX_PAYLOAD_BYTES); + } + + #[tokio::test] + async fn websocket_stream_redacts_text_messages() { + let events = tokio_stream::iter([ + event(web_socket_session_event::Event::Preflight( + WebSocketPreflight { + phase: PHASE as i32, + config: Some(config("redact", &["prototype-secret"], Some("[FILTERED]"))), + ..Default::default() + }, + )), + event(web_socket_session_event::Event::SessionStart( + WebSocketSessionStart::default(), + )), + event(web_socket_session_event::Event::Message(WebSocketMessage { + sequence: 1, + payload: Some(web_socket_message::Payload::Text( + "contains prototype-secret".into(), + )), + })), + event(web_socket_session_event::Event::SessionEnd( + WebSocketSessionEnd::default(), + )), + ]); + let mut results = ContentGuard::websocket_stream(events); + + let preflight = results + .next() + .await + .expect("preflight result") + .expect("valid preflight result"); + assert!(matches!( + preflight.result, + Some(web_socket_session_event_result::Result::PreflightDecision( + WebSocketPreflightDecision { action, .. } + )) if action == WebSocketPreflightAction::Inspect as i32 + )); + + let message = results + .next() + .await + .expect("message result") + .expect("valid message result"); + let Some(web_socket_session_event_result::Result::MessageResult(message)) = message.result + else { + panic!("expected message result"); + }; + assert_eq!(message.decision, Decision::Allow as i32); + assert_eq!( + message.replacement, + Some(web_socket_message_result::Replacement::Text( + "contains [FILTERED]".into() + )) + ); + assert_eq!(message.findings[0].count, 1); + assert!(results.next().await.is_none()); + } + + #[test] + fn websocket_deny_preserves_safe_diagnostics() { + let config = GuardConfig::parse(Some(&config("deny", &["prototype-secret"], None))) + .expect("valid config"); + let result = evaluate_websocket_message( + &config, + &WebSocketMessage { + sequence: 7, + payload: Some(web_socket_message::Payload::Text( + "contains prototype-secret".into(), + )), + }, + ) + .expect("message result"); + + assert_eq!(result.sequence, 7); + assert_eq!(result.decision, Decision::Deny as i32); + assert_eq!(result.reason_code, "content_match"); + assert!(!result.reason.contains("prototype-secret")); + assert!(result.replacement.is_none()); + } + #[test] fn redact_replaces_every_configured_match() { let config = GuardConfig::parse(Some(&config( diff --git a/flake.nix b/flake.nix index 9409af1785..f8dca42d91 100644 --- a/flake.nix +++ b/flake.nix @@ -55,7 +55,7 @@ llvmPackages.libclang # system dependency for openshell-prover z3 - # Bazel + # Bazel bazel_9 buildifier # Coverage diff --git a/proto/compute_driver.proto b/proto/compute_driver.proto index 3a0b7609ab..0ce4f61539 100644 --- a/proto/compute_driver.proto +++ b/proto/compute_driver.proto @@ -51,6 +51,13 @@ service ComputeDriver { // Stream sandbox observations from the platform. rpc WatchSandboxes(WatchSandboxesRequest) returns (stream WatchSandboxesEvent); + + // Ensure platform resources for a workspace exist (e.g. namespace). + // Idempotent: succeeds if resources already exist. + rpc EnsureWorkspace(EnsureWorkspaceRequest) returns (EnsureWorkspaceResponse); + + // Tear down platform resources for a workspace. + rpc DeleteWorkspace(DeleteWorkspaceRequest) returns (DeleteWorkspaceResponse); } message GetCapabilitiesRequest {} @@ -339,3 +346,17 @@ message WatchSandboxesEvent { WatchSandboxesPlatformEvent platform_event = 3; } } + +message EnsureWorkspaceRequest { + // Workspace identifier used by the gateway. + string workspace = 1; +} + +message EnsureWorkspaceResponse {} + +message DeleteWorkspaceRequest { + // Workspace identifier used by the gateway. + string workspace = 1; +} + +message DeleteWorkspaceResponse {} diff --git a/proto/gateway_interceptor.proto b/proto/gateway_interceptor.proto index f6b4a19210..72fec90197 100644 --- a/proto/gateway_interceptor.proto +++ b/proto/gateway_interceptor.proto @@ -100,6 +100,12 @@ message InterceptorManifest { string failure_policy = 3; // True when this interceptor implements SnapshotProviderProfiles. bool provider_profiles = 4; + // Exact JWT audience this service verifies on inbound OpenShell calls. + // After authenticated Describe succeeds, the gateway refuses to start unless + // this matches the operator-configured audience. A strict verifier may reject + // an incorrect audience before returning this manifest. Empty skips this + // post-authentication consistency check. + string expected_audience = 5; } message ProviderProfileSnapshot { diff --git a/proto/openshell.proto b/proto/openshell.proto index 5f3b660ae4..a30852664c 100644 --- a/proto/openshell.proto +++ b/proto/openshell.proto @@ -682,10 +682,16 @@ message IssueSandboxTokenResponse { int64 expires_at_ms = 2; } -// RefreshSandboxToken request. Empty body; the calling principal must -// already be a sandbox principal (i.e. the request carries a still-valid -// gateway-minted JWT in its Authorization header). -message RefreshSandboxTokenRequest {} +// RefreshSandboxToken request. The calling principal must already be a +// sandbox principal (i.e. the request carries a still-valid gateway-minted +// JWT in its Authorization header). Extension service names are resolved +// against server-owned registrations and the sandbox's effective policy; +// callers never choose token audiences directly. +message RefreshSandboxTokenRequest { + // Operator registration names for extension services selected by the + // sandbox's effective policy. + repeated string extension_service_names = 1; +} // RefreshSandboxToken response. The new token replaces the supervisor's // in-memory bearer credential. @@ -695,8 +701,12 @@ message RefreshSandboxTokenResponse { // Absolute expiry of the new token, milliseconds since the epoch. 0 means // the token is non-expiring. int64 expires_at_ms = 2; + // Fresh credentials for the requested, policy-authorized extension + // services. These remain in supervisor memory and are never persisted. + repeated ExtensionServiceCredential extension_credentials = 3; } + // Health check request. message HealthRequest {} @@ -2663,3 +2673,16 @@ message ListWorkspaceMembersRequest { message ListWorkspaceMembersResponse { repeated WorkspaceMember members = 1; } + +// Short-lived credential for one policy-authorized extension service. +// Kept at the end of the file so adding it does not renumber existing +// generated message descriptors. +message ExtensionServiceCredential { + // Operator registration name used to correlate the credential with the + // stable service registration delivered by GetSandboxConfig. + string service_name = 1; + // Gateway-minted JWT with an audience derived from the registration. + string token = 2 [(openshell.options.v1.secret) = true]; + // Absolute expiry of the token, milliseconds since the epoch. + int64 expires_at_ms = 3; +} diff --git a/proto/sandbox.proto b/proto/sandbox.proto index af90032dd2..23cbbbae55 100644 --- a/proto/sandbox.proto +++ b/proto/sandbox.proto @@ -382,6 +382,10 @@ message GetSandboxConfigResponse { // are "fail_closed" and "retain_last_valid". Unknown or empty values must // be treated as fail_closed by the supervisor. string policy_validation_failure_mode = 11; + // Whether this gateway can mint authenticated extension credentials. + // False also covers older gateways that do not advertise this capability; + // supervisors preserve their legacy unauthenticated connection behavior. + bool extension_authentication_enabled = 12; } // Connection details for one operator-registered supervisor middleware service. @@ -391,10 +395,23 @@ message SupervisorMiddlewareService { string name = 1; // gRPC endpoint reachable from the sandbox supervisor. string grpc_endpoint = 2; - // Operator-owned body limit applied to every binding exposed by the service. - uint64 max_body_bytes = 3; + // Operator-owned logical payload limit applied to every binding exposed by + // the service. This caps HTTP bodies and complete WebSocket messages. + uint64 max_payload_bytes = 3; // Default RPC timeout for this service. Empty uses the platform default of // 500ms. Values use an integer with an `ms` or `s` suffix and must be // between 10ms and 30s. string timeout = 4; + // PEM-encoded trust roots loaded by the gateway from the operator-configured + // tls_ca_cert_path. Empty uses the platform trust store. + bytes tls_ca_cert_pem = 5; + // Exact JWT audience for this service. The gateway resolves an omitted + // operator value to a kind-scoped audience derived from the registration + // name before sending sandbox config. + string audience = 6; + // Operator opt-out from extension authentication for this registration. + // When true the service may use a plaintext endpoint and OpenShell attaches + // no bearer credential; supervisors must not request one. Intended only for + // trusted-network development deployments. + bool allow_insecure_transport = 7; } diff --git a/proto/supervisor_middleware.proto b/proto/supervisor_middleware.proto index dbde411c9f..2c7c63c11d 100644 --- a/proto/supervisor_middleware.proto +++ b/proto/supervisor_middleware.proto @@ -9,7 +9,8 @@ import "google/protobuf/empty.proto"; import "google/protobuf/struct.proto"; // SupervisorMiddleware lets an operator-run service inspect and transform -// sandbox HTTP egress before OpenShell injects credentials. +// sandbox HTTP requests and client WebSocket text messages before OpenShell +// injects credentials. service SupervisorMiddleware { // Describe returns the service manifest and declared bindings. rpc Describe(google.protobuf.Empty) returns (MiddlewareManifest); @@ -20,6 +21,16 @@ service SupervisorMiddleware { // EvaluateHttpRequest returns an allow, deny, or mutation decision for one // buffered HTTP request. rpc EvaluateHttpRequest(HttpRequestEvaluation) returns (HttpRequestResult); + + // EvaluateWebSocketSession opens one ordered, phase-specific stream for a + // single middleware stage and WebSocket upgrade attempt. The current + // implementation supports client-to-upstream text messages at + // PRE_CREDENTIALS; PRE_RETURN is reserved for upstream-to-client messages. + // A request may go unanswered when the session terminates. For every opened + // stage stream, OpenShell attempts at most one session_end before closing the + // stream when its transport is still writable. + rpc EvaluateWebSocketSession(stream WebSocketSessionEvent) + returns (stream WebSocketSessionEventResult); } // MiddlewareManifest describes one middleware service and the bindings it @@ -34,16 +45,26 @@ message MiddlewareManifest { string service_version = 2; // Bindings exposed by this middleware service. repeated MiddlewareBinding bindings = 3; + // Exact JWT audience this service verifies on inbound OpenShell calls. + // After authenticated Describe succeeds, OpenShell rejects the registration + // unless this matches the operator-configured audience. A strict verifier may + // reject an incorrect audience before returning this manifest. Empty skips + // this post-authentication consistency check. + string expected_audience = 4; } // MiddlewareBinding declares one operation and phase supported by a service. message MiddlewareBinding { - // Supported operation. V1 supports HTTP_REQUEST. + // Supported operation. SupervisorMiddlewareOperation operation = 1; - // Supported evaluation phase. V1 supports PRE_CREDENTIALS. + // Supported evaluation phase. PR 1 supports PRE_CREDENTIALS. PRE_RETURN is + // reserved for the return-path follow-up and is rejected by current + // manifest validation. SupervisorMiddlewarePhase phase = 2; - // Maximum request or replacement body this binding can process. - uint64 max_body_bytes = 3; + // Maximum logical payload or replacement this binding can process. For + // HTTP_REQUEST this is the request body; for WEBSOCKET_MESSAGE this is one + // complete message. Required for every payload-bearing operation. + uint64 max_payload_bytes = 3; // Optional binding-specific RPC timeout. Empty uses the operator-configured // service timeout, or the 500ms platform default when that is also omitted. // A non-empty value may shorten but cannot extend the operator timeout. @@ -104,12 +125,151 @@ message HttpHeader { enum SupervisorMiddlewareOperation { SUPERVISOR_MIDDLEWARE_OPERATION_UNSPECIFIED = 0; SUPERVISOR_MIDDLEWARE_OPERATION_HTTP_REQUEST = 1; + SUPERVISOR_MIDDLEWARE_OPERATION_WEBSOCKET_MESSAGE = 2; } // Ordered phase within a supervisor operation. enum SupervisorMiddlewarePhase { SUPERVISOR_MIDDLEWARE_PHASE_UNSPECIFIED = 0; SUPERVISOR_MIDDLEWARE_PHASE_PRE_CREDENTIALS = 1; + SUPERVISOR_MIDDLEWARE_PHASE_PRE_RETURN = 2; +} + +// Why OpenShell is ending a middleware stream. +enum WebSocketSessionEndReason { + WEB_SOCKET_SESSION_END_REASON_UNSPECIFIED = 0; + WEB_SOCKET_SESSION_END_REASON_NORMAL_CLOSE = 1; + WEB_SOCKET_SESSION_END_REASON_PEER_DISCONNECT = 2; + WEB_SOCKET_SESSION_END_REASON_POLICY_RELOAD = 3; + WEB_SOCKET_SESSION_END_REASON_MIDDLEWARE_DENIAL = 4; + WEB_SOCKET_SESSION_END_REASON_MIDDLEWARE_FAILURE = 5; + WEB_SOCKET_SESSION_END_REASON_PROTOCOL_ERROR = 6; + WEB_SOCKET_SESSION_END_REASON_CANCELLATION = 7; + WEB_SOCKET_SESSION_END_REASON_UPSTREAM_REJECTED = 8; + WEB_SOCKET_SESSION_END_REASON_POLICY_DENIAL = 9; + // The middleware stage voluntarily declined inspection during preflight. + // This is a successful stage-local outcome, not a cancellation or denial of + // the WebSocket upgrade. + WEB_SOCKET_SESSION_END_REASON_STAGE_SKIPPED = 10; +} + +// WebSocketSessionEvent is one ordered event in a stage-local stream. +// Message sequence numbers identify logical messages session-wide. A stage +// receives a strictly increasing subset of those numbers; gaps are valid when +// session messages are not delivered to that stage. +message WebSocketSessionEvent { + oneof event { + WebSocketPreflight preflight = 1; + WebSocketSessionStart session_start = 2; + WebSocketMessage message = 3; + WebSocketSessionEnd session_end = 4; + } +} + +// WebSocketPreflight lets a service decline this upgrade before OpenShell +// contacts upstream. It deliberately excludes query data, arbitrary request +// headers, and message payloads. +message WebSocketPreflight { + string session_id = 1; + SupervisorMiddlewarePhase phase = 2; + RequestContext context = 3; + // Admitted HTTP WebSocket-upgrade target. The method is GET, query is always + // empty, and path never includes a query string. + HttpRequestTarget target = 4; + repeated string requested_subprotocols = 5; + // Built-in middleware name or operator-owned registration name. + string middleware_name = 6; + google.protobuf.Struct config = 7; +} + +// WebSocketSessionStart reports bounded metadata known only after the +// upstream 101 response validates. Empty selected_subprotocol means none. +message WebSocketSessionStart { + string selected_subprotocol = 1; +} + +// WebSocketMessage contains one complete reconstructed logical message. +message WebSocketMessage { + // Session-global sequence starting at 1. Values delivered to one stage must + // strictly increase but need not be contiguous. Reject zero, duplicates, and + // regressions; accept gaps. + uint64 sequence = 1; + // One complete logical payload. Protobuf string decoding enforces UTF-8 for + // text messages. Raw frame mechanics are never exposed. Limited to 4 MiB by + // the platform and the binding-specific cap. + oneof payload { + string text = 2; + bytes binary = 3; + } +} + +// WebSocketSessionEnd is OpenShell's best-effort terminal notification for one +// opened stage stream. A stage receives at most one such notification. +message WebSocketSessionEnd { + WebSocketSessionEndReason reason = 1; +} + +// WebSocketPreflightAction is the service's one-time scoping decision. +enum WebSocketPreflightAction { + // Invalid response value handled according to the policy failure mode. + WEB_SOCKET_PREFLIGHT_ACTION_UNSPECIFIED = 0; + // Inspect this session after the upstream accepts the upgrade. + WEB_SOCKET_PREFLIGHT_ACTION_INSPECT = 1; + // Voluntarily decline inspection without denying the upgrade. This is a + // successful decision and does not engage on_error. + WEB_SOCKET_PREFLIGHT_ACTION_SKIP = 2; + // Authoritatively deny the upgrade before upstream contact. This is a + // successful decision and is enforced regardless of on_error. + WEB_SOCKET_PREFLIGHT_ACTION_DENY = 3; +} + +message WebSocketPreflightDecision { + WebSocketPreflightAction action = 1; + // Free-form service diagnostic. OpenShell never exposes this to the + // workload or security logs. Limited to 4 KiB before discarding. + string reason = 2; + // Optional stable machine-readable code for a deny decision. Because + // preflight runs before the HTTP upgrade completes, OpenShell may return + // this code to the requester. Codes follow the same format and 64-byte + // maximum as HttpRequestResult.reason_code. + string reason_code = 3; + // Audit-safe findings produced during preflight. At most 32 findings of at + // most 4 KiB encoded each are accepted. + repeated Finding findings = 4; + // Non-secret service-defined metadata included in diagnostics. At most 64 + // entries and 32 KiB of combined key/value data are accepted. + map metadata = 5; +} + +// WebSocketMessageResult contains the decision and optional replacement for +// one message. A replacement must use the same variant as the input payload. +message WebSocketMessageResult { + // Must exactly match the sequence of the corresponding WebSocketMessage. + uint64 sequence = 1; + Decision decision = 2; + // Absence preserves the input unchanged. Oneof presence distinguishes an + // empty replacement from no replacement, and string decoding enforces UTF-8. + oneof replacement { + string text = 3; + bytes binary = 4; + } + // Free-form service diagnostic. OpenShell never exposes this to the + // workload or security logs. Limited to 4 KiB before discarding. + string reason = 5; + // Optional stable machine-readable code for OCSF only. Unlike the HTTP + // reason_code, this value is never put in a WebSocket close frame. + string reason_code = 6; + repeated Finding findings = 7; + map metadata = 8; +} + +// WebSocketSessionEventResult is an evaluation result for a preflight or message +// event. Session start and end events do not produce results. +message WebSocketSessionEventResult { + oneof result { + WebSocketPreflightDecision preflight_decision = 1; + WebSocketMessageResult message_result = 2; + } } // RequestContext identifies the sandbox request being evaluated. @@ -124,7 +284,7 @@ message RequestContext { // HttpRequestTarget describes the admitted HTTP destination and request target. message HttpRequestTarget { - // Request scheme, such as "http" or "https". + // Request scheme, such as "http", "https", "ws", or "wss". string scheme = 1; // Destination hostname selected by network policy. string host = 2; @@ -148,13 +308,16 @@ message Process { repeated string ancestors = 3; } -// Decision controls whether OpenShell continues processing the request. +// Decision controls whether OpenShell continues processing the current +// evaluation unit. enum Decision { // Invalid response value handled according to the policy failure mode. DECISION_UNSPECIFIED = 0; - // Continue processing the request and apply any returned mutations. + // Continue processing the current request or message and apply any returned + // mutations. DECISION_ALLOW = 1; - // Deny the request before credentials are injected or data is sent upstream. + // Reject the current request or message. The operation-specific result + // defines the enclosing protocol behavior. DECISION_DENY = 2; } diff --git a/rfc/0009-supervisor-middleware/README.md b/rfc/0009-supervisor-middleware/README.md index f43e05ed79..1f6eacde7b 100644 --- a/rfc/0009-supervisor-middleware/README.md +++ b/rfc/0009-supervisor-middleware/README.md @@ -13,6 +13,13 @@ links: # RFC 0009 - Supervisor Middleware +## Revision history + +| Date | References | Change | +|------|------------|--------| +| 2026-07-17 | [#2010](https://github.com/NVIDIA/OpenShell/issues/2010) | Added unary HTTP request middleware with built-in and operator-run services. | +| 2026-07-28 | [#2428](https://github.com/NVIDIA/OpenShell/issues/2428) | Added WebSocket preflight and text-message evaluation, and aligned the middleware API names, limits, and diagnostics. | + ## Summary This RFC proposes the introduction of supervisor middleware: a supervisor-side extension system for hooks that can inspect, transform, block, and annotate supervisor-managed operations at specific operation phases. The first hook family is supervisor egress middleware for outbound sandbox HTTP requests, but the framework is intentionally named and shaped so later supervisor hooks can cover other protocols or supervisor operations without renaming the feature. @@ -134,21 +141,26 @@ This ordering is deliberate: The hook operates on a parsed HTTP request, so it runs wherever OpenShell can parse one. The supervisor proxy TLS-terminates and HTTP-parses every egress connection that is not marked `tls: skip` and is not opaque, non-HTTP traffic, so the hook fires on those requests regardless of whether the endpoint also declares a `protocol`. Declaring a `protocol` additionally subjects the request to L7 Rego policy; an endpoint without one is still terminated and parsed and the middleware hook runs on it. The only traffic the hook cannot inspect is traffic OpenShell never parses: `tls: skip` endpoints and opaque TCP or TLS passthrough. Policy validation rejects any middleware selector whose possible hosts overlap an endpoint configured with `tls: skip`, so selector-based middleware cannot be silently bypassed by an unparsed path. -If matching middleware exists but a request becomes uninspectable at runtime, OpenShell examines the whole matching chain. If any stage is `fail_closed`, the request is denied. If every matching stage is `fail_open`, OpenShell relays the request and emits a bypass `DetectionFinding`. This chain-level rule prevents one permissive stage from overriding a required stage. +> **Update in PR #2477 - WebSocket middleware:** The following text extends the original HTTP-only scope. It adds operation-specific selection, client WebSocket text-message inspection, and explicit coverage for traffic that an attached middleware cannot inspect. + +If a selected operation chain becomes uninspectable at runtime, OpenShell examines that chain. If any selected stage is `fail_closed`, the request is denied. If every selected stage is `fail_open`, OpenShell relays the request and emits a bypass `DetectionFinding`. This chain-level rule prevents one permissive selected stage from overriding a required stage. -WebSocket sits on this boundary. The upgrade request is a normal HTTP/1.1 request that the hook can inspect, allow, or deny, but the frames exchanged after the connection upgrades are out of scope for v1 (a later `message.*` hook may cover them). To keep the v1 boundary unambiguous: +Attachment and operation selection are separate. A destination host selector attaches a policy config, then the implementation manifest decides whether that config participates in `HTTP_REQUEST/PRE_CREDENTIALS`, `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`, or both. The absence of an operation binding is a declared capability boundary rather than a middleware failure, so `on_error` does not apply. OpenShell records informational coverage when an attached config does not join the WebSocket chain. + +WebSocket sits on this boundary. The upgrade request is a normal HTTP/1.1 request that an HTTP binding can inspect, allow, or deny. A separate V1 operation covers complete client-to-upstream text messages after upgrade. Binary messages, control frames, and upstream-to-client messages remain outside that operation. To keep the v1 boundary unambiguous: **In scope for v1:** - Inspectable HTTP/1.x requests that OpenShell terminates and parses, after L4 and SSRF admit them (and L7 policy too, where the endpoint declares a `protocol`). - WebSocket upgrade (handshake) requests - the HTTP request that initiates the upgrade. +- Complete client-to-upstream WebSocket text messages for implementations that advertise `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. - Bounded request bodies: a `Content-Length` or bounded chunked body OpenShell can buffer within the applicable chain cap. - Safe metadata output for later routing or audit. **Out of scope for v1:** - HTTP/2 and HTTP/3. The proxy's TLS termination pins ALPN to `http/1.1` today, so these are not introspected. -- Post-upgrade WebSocket frames, and response-body scanning. +- Binary and control WebSocket messages, upstream-to-client WebSocket messages, and response-body scanning. - Opaque TCP streams and endpoints with `tls: skip`. - Unbounded streaming uploads or full-duplex request processing. - Multipart or compressed body semantics, unless a selected service's manifest and policy explicitly support them within the size limits. @@ -191,7 +203,7 @@ message MiddlewareBinding { string id = 1; // service-owned stable ID SupervisorMiddlewareOperation operation = 2; SupervisorMiddlewarePhase phase = 3; - uint64 max_body_bytes = 4; + uint64 max_payload_bytes = 4; // one logical request or message payload string timeout = 5; // optional binding-specific RPC timeout } @@ -276,9 +288,15 @@ The evaluation and result are shaped so middleware composes cleanly in a chain. Headers use a repeated representation so duplicate lines and wire order survive evaluation and chaining. Before an external call, OpenShell omits credential-bearing, routing, framing, hop-by-hop, and `Connection`-nominated headers. A result may return ordered writes and removals. Writes support append, overwrite, and skip modes but may target only the `x-openshell-middleware-*` namespace. Removals may target other headers visible to middleware, except credential-bearing, routing, framing, hop-by-hop, and `Connection`-nominated headers. Header values containing control characters are invalid. OpenShell validates and applies a stage's mutations atomically. If any mutation is invalid, none are applied and the stage follows its configured `on_error` behavior. -The interface is gRPC. The protobuf package `openshell.middleware.v1` is the protocol version boundary, so manifests and evaluation messages do not repeat an API-version string. The hot-path v1 RPC is unary: the supervisor buffers the bounded body, sends one `HttpRequestEvaluation`, and receives one `HttpRequestResult`. Streaming is deliberately not baked into `EvaluateHttpRequest`; if OpenShell later needs chunked or incremental processing, it should add a separate operation-specific method rather than changing the v1 method cardinality. Possible extensions are collected in the [protocol-extensions appendix](appendices/protocol-extensions.md). Built-in middleware uses the same logical contract in-process with no network hop. +> **Update in PR #2477 - WebSocket middleware:** The following contract text adds the bidirectional `EvaluateWebSocketSession` RPC, WebSocket preflight, message limits, and the WebSocket binding for the built-in regex middleware. The unary HTTP contract does not change. + +The interface is gRPC. The protobuf package `openshell.middleware.v1` is the protocol version boundary, so manifests and evaluation messages do not repeat an API-version string. HTTP evaluation remains unary: the supervisor buffers the bounded body, sends one `HttpRequestEvaluation`, and receives one `HttpRequestResult`. Complete client-to-upstream WebSocket text messages use the separate bidirectional-streaming `EvaluateWebSocketSession` RPC. The supervisor sends `WebSocketSessionEvent` values; the service returns `WebSocketSessionEventResult` values for preflight and message events, while session start and end are notifications without corresponding results. Streaming is not baked into `EvaluateHttpRequest`; future chunked HTTP transport should add another operation-specific method rather than changing the existing method's cardinality. Possible extensions are collected in the [protocol-extensions appendix](appendices/protocol-extensions.md). Built-in middleware uses the same logical contracts in-process; the `openshell/regex` built-in advertises both V1 operations. + +V1 applies explicit public envelope limits before invoking a service or accepting its result: 64 KiB for encoded config, 4 KiB for request context, 32 KiB for the target, 128 header lines and 64 KiB of encoded headers, 4 MiB for the logical payload, 4 KiB for a reason, 64 header mutations with at most 32 KiB of validated name/value data and 64 KiB encoded, 32 findings per stage with each finding at most 4 KiB encoded, and 64 metadata entries totaling at most 32 KiB. A chain has at most 10 stages and therefore at most 320 findings. Middleware gRPC servers configure request and response message limits to cover the 4 MiB payload plus at least 292 KiB for the remaining envelope. -V1 applies explicit public envelope limits before invoking a service or accepting its result: 64 KiB for encoded config, 4 KiB for request context, 32 KiB for the target, 128 header lines and 64 KiB of encoded headers, 4 MiB for the body, 4 KiB for a reason, 64 header mutations with at most 32 KiB of validated name/value data and 64 KiB encoded, 32 findings per stage with each finding at most 4 KiB encoded, and 64 metadata entries totaling at most 32 KiB. A chain has at most 10 stages and therefore at most 320 findings. Middleware gRPC servers configure request and response message limits to cover the 4 MiB body plus at least 292 KiB for the remaining envelope. +For WebSocket traffic, a service advertises `WEBSOCKET_MESSAGE/PRE_CREDENTIALS` with `max_payload_bytes`, which limits one complete message or replacement rather than the whole session. HTTP bindings use the same field for one request body or replacement. An attached service without that exact binding does not join the chain, does not apply `on_error`, and produces internal `binding_not_selected` coverage. OpenShell opens one phase-specific `EvaluateWebSocketSession` stream per selected stage and upgrade attempt. Future upstream-to-client inspection uses the same RPC with `PRE_RETURN`; a service selected for both phases receives two independent streams for the WebSocket session. A bounded preflight exposes only the admitted destination through `HttpRequestTarget`, with its path separated from query data, requested subprotocols, sandbox context, the attached API middleware name, and validated implementation config. Policy-local config identity remains internal for audit and denial metadata. OpenShell evaluates selected preflights concurrently. Each stage returns `inspect`, voluntary `skip`, or authoritative `deny` before upstream contact, plus optional bounded reason, reason code, findings, and metadata. `deny` is a successful decision enforced independently of `on_error` and takes precedence over concurrent failures; failures alone follow each stage's `on_error`. OpenShell sends the terminal reason to every still-writable stream whose preflight opened successfully, at most once per stage. Inspecting stages that continue receive `session_start`, then complete logical text messages with monotonic sequence numbers. Stages run in global policy order and each sees the prior stage's accepted replacement. Binary logical messages pass through without middleware inspection under both error modes, consume a session-global sequence, and emit `unsupported_message_type` coverage for active stages; a later text RPC may therefore contain a valid sequence gap. `PRE_RETURN` and upstream-to-client inspection are reserved for a later implementation. + +Inspectable WebSocket text input and replacements share the 4 MiB platform cap. The operator's `max_payload_bytes` is the shared HTTP-body and WebSocket-text ceiling, further constrained by each operation binding's capability. It does not bound binary pass-through, which retains a separate raw-frame safety limit. Logical messages use a protobuf `oneof` with `string text` and `bytes binary` variants; results use an optional matching replacement `oneof`, whose presence also represents an empty replacement without a separate boolean. Protobuf decoding enforces UTF-8 for text, and OpenShell rejects replacement variants that would change the message type. A complete text message holds one process-wide admission permit for its entire chain; preflight fan-out holds one permit until every stage resolves. Permit waiting is backpressure and does not consume the per-message deadline. Per-stage timeouts are also bounded by a 30-second total chain budget, which applies to HTTP chains too. This bound controls concurrency and peak buffered inspection memory; it is not rate limiting. The `originating_process` is the same identity OpenShell resolves on the egress path - the binary, pid, and ancestor chain it uses for binary-scoped network policy and OCSF audit. It is per-connection rather than strictly per-request and is optional. Middleware must treat missing process data as unavailable rather than as an authorization failure. The initial implementation leaves this field unset until reliable propagation is available. @@ -310,7 +328,7 @@ The protobuf package is the wire-version handshake. `Describe` reports a diagnos ### Registration and delivery -The operator registers available external middleware services in gateway configuration under `openshell.supervisor.middleware`. The namespace identifies the subsystem whose behavior is extended, not the process that reads the configuration. The gateway still loads, validates, and distributes these registrations to supervisors. Each entry has a diagnostic name, gRPC endpoint, maximum body size, optional RPC timeout, and transport settings. The diagnostic name identifies the configured connection in logs but is not a policy key. Policy authors select stable binding IDs returned by `Describe`, so they cannot point traffic at an arbitrary endpoint and do not depend on an operator-local registration name. +The operator registers available external middleware services in gateway configuration under `openshell.supervisor.middleware`. The namespace identifies the subsystem whose behavior is extended, not the process that reads the configuration. The gateway still loads, validates, and distributes these registrations to supervisors. Each entry has a diagnostic name, gRPC endpoint, maximum logical payload size, optional RPC timeout, and transport settings. The diagnostic name identifies the configured connection in logs but is not a policy key. Policy authors select stable binding IDs returned by `Describe`, so they cannot point traffic at an arbitrary endpoint and do not depend on an operator-local registration name. The v1 transport is gRPC over a network endpoint reachable from every supervisor across Docker, Podman, VM, and Kubernetes drivers. In local single-player deployments, a loopback endpoint such as `127.0.0.1:1234` may be translated to `host.openshell.internal` so a supervisor can reach a service running on the local host. That loopback shorthand is not an HA deployment model: Kubernetes and other shared deployments should register a routable service DNS name or address that every supervisor can reach directly. Other deployment shapes are deferred until OpenShell has a universal way to make those endpoints reachable from the relevant supervisor environments. @@ -318,19 +336,19 @@ The v1 transport is gRPC over a network endpoint reachable from every supervisor [[openshell.supervisor.middleware]] name = "anonymizer" grpc_endpoint = "http://127.0.0.1:1234" -max_body_bytes = 4194304 +max_payload_bytes = 4194304 timeout = "500ms" allow_insecure = true [[openshell.supervisor.middleware]] name = "agent-traces-exporter" grpc_endpoint = "https://middleware.example.internal:443" -max_body_bytes = 1048576 +max_payload_bytes = 1048576 ``` The stable transport requirement is confidentiality plus authentication of the intended middleware service. Phase 1 may temporarily accept a plaintext `http://` endpoint only when the same entry explicitly sets `allow_insecure = true`. OpenShell rejects plaintext without that opt-in, warns prominently, and records the insecure registration as auditable configuration state. This escape hatch is limited to trusted local development and isolated research environments. Phase 2 removes plaintext support and the `allow_insecure` field, requiring authenticated encrypted transport. That removal is an intentional research-preview breaking change with no long-term compatibility obligation. The exact phase 2 mechanism, such as mTLS or TLS plus explicit caller authentication, is follow-up protocol work (see [appendices/protocol-extensions.md](appendices/protocol-extensions.md#middleware-authentication)). -For each binding, the operator's `max_body_bytes` must not exceed the binding capability returned by `Describe` or the 4 MiB platform maximum. The gateway rejects an invalid registration rather than silently clamping it. The resulting operator limit applies to every binding exposed by that registration. +For each binding, the operator's `max_payload_bytes` must not exceed the binding capability returned by `Describe` or the 4 MiB platform maximum. The gateway rejects an invalid registration rather than silently clamping it. The resulting operator limit applies to every binding exposed by that registration. RPC timeouts use an integer with an `ms` or `s` suffix, range from 10 ms through 30 s, and default to 500 ms. A binding may advertise its own timeout through `Describe`; that value overrides the service registration timeout. The service timeout applies to `Describe`, while the effective binding timeout applies to `ValidateConfig` and `EvaluateHttpRequest`. @@ -424,8 +442,11 @@ The namespace is the policy-local middleware config map key, not the optional hu A middleware decision is observable sandbox behavior, so it is recorded as an OCSF event, consistent with how the supervisor already logs network and L7 enforcement. This RFC commits to the event categories and the safety rules; exact field mappings are an implementation detail. +> **Update in PR #2477 - WebSocket middleware:** The coverage-boundary event below is new. It distinguishes an unsupported operation or message type from a middleware invocation or failure. + - **Per-invocation decisions** are `HttpActivity` events, since middleware is an L7 enforcement point. Each stage records the policy-local config key, validated binding ID, decision, transformation state, latency, and policy and endpoint context. Allowed requests are `Informational`; denials are `Medium`. - **Enforcement failures and bypasses** also emit `DetectionFinding` events. Required-stage failures, invalid responses, uninspectable traffic with a required stage, and body-aware policy evaluation failures are `High`. A `fail_open` bypass and uninspectable traffic allowed because every matching stage is `fail_open` are still findings so operators can alert on reduced enforcement. +- **Coverage boundaries** emit informational `NetworkActivity` events separately from invocations and failures. `binding_not_selected` records an attached config whose manifest lacks the WebSocket binding. `unsupported_message_type` records binary pass-through for an active stage with its internal config identity, logical sequence, message class, and size. - **Configuration events** are `ConfigStateChange` events: middleware registration validation, registry reload success or failure, and policy validation outcome. These events must never leak the content they describe. The OCSF JSONL may be shipped to external systems, so: @@ -440,7 +461,9 @@ This mirrors the middleware response contract, which already forbids the service Supervisor egress middleware stays opt-in throughout: until a policy declares a matching middleware config, no sandbox invokes one and the proxy hot path is unchanged. The initial usable slice proves built-in and external execution together; the phase boundary is transport hardening, not whether external middleware exists. -**Phase 1 - research-preview contract and execution.** Define `openshell.middleware.v1` with `Describe`, `ValidateConfig`, and `EvaluateHttpRequest`; ship the example `openshell/regex` built-in; and support statically registered operator-run services. Policy uses a top-level selector-based `network_middlewares` map with stable config keys, unique numeric `order`, per-stage `on_error`, bounded bodies, bounded RPC timeouts, atomic header mutations, post-transformation policy re-evaluation, and OCSF observability. Gateway startup validates external manifests, policy writes validate implementation-owned config, effective sandbox config carries only required external registrations, and supervisors install policy plus registry as one last-known-good runtime generation. Phase 1 requires encrypted authenticated transport for normal use but temporarily permits plaintext `http://` only with explicit `allow_insecure = true` for trusted local development or isolated research. OpenShell warns and emits auditable configuration state whenever that exception is used. +> **Update in PR #2477 - WebSocket middleware:** Phase 1 now also includes the forward-text WebSocket operation, bounded WebSocket messages, and the WebSocket binding for the built-in regex middleware. + +**Phase 1 - research-preview contract and execution.** Define `openshell.middleware.v1` with `Describe`, `ValidateConfig`, unary `EvaluateHttpRequest`, and forward-text `EvaluateWebSocketSession`; ship the example `openshell/regex` built-in; and support statically registered operator-run services. Policy uses a top-level selector-based `network_middlewares` map with stable config keys, unique numeric `order`, per-stage `on_error`, bounded bodies and messages, bounded RPC timeouts, atomic header mutations, post-transformation policy re-evaluation, and OCSF observability. Gateway startup validates external manifests, policy writes validate implementation-owned config, effective sandbox config carries only required external registrations, and supervisors install policy plus registry as one last-known-good runtime generation. Phase 1 requires encrypted authenticated transport for normal use but temporarily permits plaintext `http://` only with explicit `allow_insecure = true` for trusted local development or isolated research. OpenShell warns and emits auditable configuration state whenever that exception is used. **Phase 2 - mandatory authenticated encryption.** Remove plaintext middleware transport and remove `allow_insecure`. Every external connection must provide transport confidentiality and authenticate the intended service, with the final mechanism and credential delivery model defined by follow-up protocol work. Because phase 1 is explicitly a research preview, removing its insecure escape hatch is an intentional breaking change and does not create a long-term compatibility obligation. Operator-run service deployment otherwise keeps the same binding, policy, validation, delivery, reload, and invocation model. @@ -456,10 +479,12 @@ The first release is a research preview. The contract, policy surface, and scope Adding a synchronous, content-aware hook to the egress path has real costs. The most significant: +> **Update in PR #2477 - WebSocket middleware:** OpenShell now bounds concurrent middleware work and buffered memory. It does not add request-rate limiting. The updated rate-limit risk below keeps that distinction explicit. + - **Hot-path latency and a new per-request dependency.** Each selected external stage makes a synchronous call and blocks on its reply, so middleware latency becomes request latency and the service becomes a new failure surface on the data plane. This is bounded by opt-in host selectors, per-middleware timeouts, and built-ins running in-process with no network hop, but for matching traffic the tax is unavoidable. - **Fail-closed breaks workloads.** Denying traffic when a required middleware is unavailable, times out, or returns a malformed response is the safe default, but it converts a middleware outage into a sandbox outage. The opposite default leaks the very content the middleware exists to control. There is no choice that is both safe and always available; `on_error` makes the tradeoff explicit per middleware, but operators can still pick a default that surprises them. - **Body buffering and size limits.** Inspecting content means buffering a bounded request body instead of streaming it, which adds memory cost and interacts badly with growing payloads (for example inference requests whose context expands each turn until it exceeds the cap). An over-cap request is treated as an `on_error` event for the middleware that needs the body, so it follows the same `fail_closed` default: it is denied unless the operator has explicitly set `on_error: fail_open` for that middleware. Passing an over-cap request through unprocessed is therefore never the default - it is an opt-in choice made per middleware, and one a security-critical middleware would deliberately leave off so that oversized content is denied rather than silently egressed. -- **No OpenShell-side rate limiting.** OpenShell does not throttle calls to a middleware. A middleware that is slow, overloaded, or unavailable is handled only by its timeout and `on_error`, so operators must size, scale, and protect the service themselves; a struggling middleware degrades every request routed through it. +- **No OpenShell-side rate limiting.** OpenShell bounds concurrent middleware work and buffered memory, but does not throttle fast calls. A middleware that is slow, overloaded, or unavailable is handled by admission backpressure, its timeout, and `on_error`, so operators must still size, scale, and protect the service. - **Trusting an unsandboxed service with raw content.** Middleware receives raw request payloads, and OpenShell does not sandbox it, verify its behavior, or prevent it from mishandling or exfiltrating what it inspects. A buggy or malicious middleware is a direct data-exposure path. Trust in the middleware is the operator's responsibility, the same as trust in a sandbox image, but the blast radius here is in-flight request content. - **A false sense of coverage.** The hook runs only on traffic OpenShell terminates and parses. Opaque TCP or TLS passthrough, encrypted or otherwise opaque bodies, endpoints outside every selector, and content the middleware fails to detect can still leave without effective inspection. Policy validation rejects selector overlap with `tls: skip`, and runtime uninspectability follows the matching chain's failure policy, but detection correctness and traffic outside the selected host set remain inherent limitations. - **Phase 1 plaintext is risky.** The research-preview exception permits plaintext gRPC only with explicit `allow_insecure = true`. Because middleware can allow, deny, or transform egress, an impersonated or eavesdropped service is a policy-enforcement bypass, not just an observability gap. The exception is unsuitable for shared or untrusted networks, produces an explicit warning and audit event, and is removed in phase 2. See [appendices/protocol-extensions.md](appendices/protocol-extensions.md#middleware-authentication). @@ -491,10 +516,12 @@ This section closes the current review themes. ### Decisions +> **Update in PR #2477 - WebSocket middleware:** The operation-scope and failure-behavior decisions below now include WebSocket bindings, client text messages, binary pass-through, and capability coverage. + - **Middleware naming.** Use the feature name "supervisor middleware." The first operation family is egress middleware, but the higher-level feature name stays extensible for future supervisor hooks. The service can inspect, transform, deny, and annotate, so narrower names such as "transformer" or "request processor" describe only part of the contract. - **Middleware binding IDs.** Services own stable binding IDs and policy selects them through the `middleware` field. Gateway registration names are diagnostic only. Binding IDs use `/` for namespaces, `openshell/` is reserved for built-ins, and empty path segments are invalid. - **Operation naming.** Use typed operation and phase enums such as `HTTP_REQUEST/PRE_CREDENTIALS`. The operation describes the middleware API payload, and the phase describes the proxy position. Later protocols can add typed operations such as WebSocket message or TCP connect without renaming the v1 hook. -- **HTTP scope of v1.** `HTTP_REQUEST/PRE_CREDENTIALS` applies to every HTTP/1.x request that OpenShell terminates and parses, whether or not the endpoint declares a `protocol`. WebSocket upgrade requests are included; post-upgrade frames, HTTP/2, HTTP/3, opaque TCP, and `tls: skip` traffic are excluded. +- **Operation scope of v1.** `HTTP_REQUEST/PRE_CREDENTIALS` applies to every HTTP/1.x request that OpenShell terminates and parses, whether or not the endpoint declares a `protocol`; WebSocket upgrade requests are included. `WEBSOCKET_MESSAGE/PRE_CREDENTIALS` applies only to complete client-to-upstream text messages for attachments whose manifest advertises it. Binary and return-path messages, HTTP/2, HTTP/3, opaque TCP, and `tls: skip` traffic are excluded from those operation bindings. - **Route selection and forwarding.** V1 has no `forward_to` decision. Middleware never makes the upstream call. Future route-selection hooks may choose among OpenShell-managed destinations, such as model routes, but must not become arbitrary external endpoint rewrites. - **SigV4/request signing.** AWS SigV4 belongs to a restricted built-in `HttpRequest/post_credentials` hook, not external `HttpRequest/pre_credentials` middleware. The middleware can be configured by policy, but it must run in-process with supervisor host capabilities so it can strip placeholder signatures and sign with real supervisor-resolved credentials without exposing those credentials over the external middleware contract. - **Composability and ordering.** Middleware is chainable and ordered by ascending numeric `order`. Order values must be unique across the policy. A stage receives the previous stage's transformed body and header mutations; `deny` short-circuits the chain; and different config map keys may invoke the same binding as separate stages. @@ -503,7 +530,7 @@ This section closes the current review themes. - **Actor data.** Actor process data is optional and per-connection. Middleware must treat it as context, not a reliable per-request identity or authorization input. - **Metadata namespacing.** Metadata is stored under the policy-local middleware config map key rather than the optional human-readable name. This prevents collisions without a central key registry and lets two configs using the same implementation emit independent metadata. - **Selector-only placement.** V1 uses only config-level `endpoints.include` and `endpoints.exclude` selectors. Policy-level and endpoint-level attachment lists are not part of the schema. Selection is independent of the network rule that admitted the request and therefore remains stable after effective-policy composition. -- **Failure behavior.** Middleware errors, timeouts, malformed responses, and over-cap bodies use `on_error`; `fail_closed` is the default. Passing unprocessed content through is only possible when the operator explicitly sets `on_error: fail_open`. +- **Failure behavior.** Middleware errors, timeouts, malformed responses, and over-cap inspectable payloads use `on_error` after an operation binding is selected; `fail_closed` is the default. An absent operation binding and binary WebSocket messages are capability coverage states, not failures, and pass with informational telemetry under both error modes. - **Limits.** V1 caps policies at 10 middleware configs, selectors at 32 combined patterns per config, bodies at 4 MiB, findings at 32 per stage, and all non-body request and result fields at the public envelope limits in the contract section. - **Delivery and reload.** `GetSandboxConfig` delivers only external registrations required by the effective policy. Built-ins are installed locally. Supervisors prepare candidate policy and registry state off-path, swap them as one generation, reuse connections for policy-only changes, and preserve the complete last-known-good runtime on failure. - **Chunked and compressed bodies.** V1 operates on bounded bytes OpenShell can buffer safely. Known over-cap content length may fail open before consumption when every affected stage permits it. Chunked overflow after consumption is denied because the raw stream cannot be resumed. Compressed bodies remain opaque unless a binding explicitly supports them. diff --git a/rfc/0009-supervisor-middleware/appendices/extension-authentication.md b/rfc/0009-supervisor-middleware/appendices/extension-authentication.md new file mode 100644 index 0000000000..d73a7aa9bf --- /dev/null +++ b/rfc/0009-supervisor-middleware/appendices/extension-authentication.md @@ -0,0 +1,66 @@ +# Appendix: Extension Authentication (Alpha) + +> This is an appendix to the [RFC](../README.md). Please familiarize yourself with the RFC before reading this. + +The RFC body left the authenticated-transport mechanism as follow-up protocol work: it required confidentiality plus authentication of the intended middleware service, described a phase 1 `allow_insecure` escape hatch, and deferred the phase 2 choice between mTLS, TLS plus explicit caller authentication, or an equivalent. This appendix records the mechanism that was actually built for alpha. It supersedes the body's transport-authentication and `allow_insecure` paragraphs; the rest of the body is unchanged. + +Related: [protocol-extensions.md](protocol-extensions.md#middleware-authentication). + +## What ships in alpha + +Transport is HTTPS with either platform trust roots or an operator-provided CA bundle, with normal certificate and endpoint-hostname verification. A middleware endpoint must be reachable from every sandbox supervisor as well as the gateway, so a gateway-local Unix socket is not an option for this mechanism. + +Caller identity is a short-lived Ed25519 JWT minted by the gateway's existing sandbox signing authority. The gateway attaches one to its own `Describe` and `ValidateConfig` calls; sandbox supervisors attach one to `Describe` and `EvaluateHttpRequest`. Both directions of the RFC's stated requirement are covered: TLS and the configured trust roots authenticate the middleware service to OpenShell, and the exact-audience JWT proves to the middleware that a gateway or a policy-authorized sandbox supervisor made the call. + +## Claim contract + +| Claim | Meaning | +|---|---| +| `iss` | Exactly `openshell-gateway:`. | +| `aud` | The exact audience for one registration. Never a list. | +| `sub` | Gateway identity for gateway callers; `spiffe://openshell/sandbox/` for supervisor callers. | +| `caller_kind` | `gateway` or `supervisor`. | +| `sandbox_id` | Present only for supervisor callers. | +| `jti` | Unique per token. OpenShell does not track it. | +| `iat`, `exp` | Bounded lifetime, at most one hour. | + +The JOSE header carries `alg: EdDSA`, the signing `kid`, and `typ: openshell-ext+jwt`. + +Explicit typing exists because extension tokens and sandbox-to-gateway admission tokens are signed by the same key and would otherwise be separated by audience alone. A verifier that requires this `typ` cannot accept a sandbox bootstrap credential even if it neglects to check `aud`. This is defense in depth for the most likely verifier mistake, not a replacement for audience validation. + +## Authorization and distribution + +Supervisors request credentials by operator registration name through the existing `RefreshSandboxToken` RPC, which already authenticates a sandbox principal. The gateway resolves each requested name against server-owned registration metadata and the sandbox's effective policy before minting; unknown, unselected, or duplicated names are rejected. Callers never choose an audience. + +Because that resolution runs the full effective-policy composition, two bounds apply. Supervisors rotate only when a credential is missing or has passed four fifths of its lifetime rather than on every configuration poll, and the gateway caps how many minting requests a single sandbox may make per minute. + +## Audience agreement + +The audience is operator configuration on the OpenShell side and service configuration on the middleware side. A strict verifier rejects a mismatched token before dispatching `Describe`, so OpenShell may observe only an authentication failure. + +A service may advertise the audience it verifies in the `expected_audience` field of its `Describe` manifest. After authenticated `Describe` succeeds, OpenShell compares that value against the configured one and rejects the registration on a mismatch. This is a post-authentication consistency assertion, not audience discovery. An empty field means the service does not advertise an audience and the check is skipped, so this is additive for existing services. + +## Verification key distribution + +The operator-provisioned public key or JWKS is the authoritative cold-start trust anchor. Deploy it alongside the extension service through the same trusted configuration path used for the gateway URL, expected gateway ID, and private CA. This lets a service verify its first authenticated call without trusting key material learned from that call's peer. + +The gateway also publishes its public signing key as a single-key JWKS at `/.well-known/jwks.json`, and OIDC-shaped discovery metadata at `/.well-known/openid-configuration` carrying the expected `iss`, an absolute `jwks_uri`, and `EdDSA` as the only supported algorithm. After initial trust is established, extensions may use these endpoints for steady-state key refresh and operational convenience. + +The discovery document is OIDC-shaped rather than OIDC-compliant, in the same way and for the same reason as the equivalent Kubernetes endpoint: `issuer` is the gateway identity, not the URL the document is served from. Verifiers compare `iss` against that value. Fetching the document does not establish gateway identity; the preconfigured gateway identity and authenticated TLS connection do. The well-known endpoints are therefore not a replacement for operator-provisioned first-contact trust. + +## Compatibility + +A registration may set `allow_insecure_transport = true`, which replaces the body's `allow_insecure` field with a clearer name and a wider meaning: it opts the registration out of extension authentication entirely. OpenShell attaches no credential, supervisors do not request one, the gateway refuses to mint one if asked, and a warning naming the registration is logged at every gateway startup. + +This keeps plaintext registrations working for trusted local development and isolated research environments, and preserves compatibility for deployments configured before extension authentication existed. The body's intent that this be a temporary, auditable, prominently-warned escape hatch is retained. + +## Residual risks + +- **Bearer replay within the token lifetime.** Anything that obtains a token can use it until expiry. Short bounded lifetimes limit the window. `jti` identifies a token instance for correlation or future explicit revocation, but OpenShell reuses tokens across calls and does not track or revoke it. Per-request replay resistance requires request binding or proof of possession. +- **Shared signing key across two trust domains.** Extension credentials and sandbox admission credentials come from one key and one `kid`. They are separated by audience and `typ`, but extension-token issuance cannot be rotated or revoked independently of sandbox admission. A separate extension signing key is the natural next step and the `kid`-based design does not preclude it. +- **Single-key JWKS.** There is no overlap window, so key rotation is not yet a zero-downtime operation. +- **No channel binding.** mTLS or another proof-of-possession mechanism remains deferred hardening. + +## Deferred + +mTLS client authentication, multi-key rotation with an overlap window, replay resistance beyond short expiry, and per-runtime secret delivery are all out of scope for alpha and remain follow-up work. diff --git a/rfc/0009-supervisor-middleware/appendices/protocol-extensions.md b/rfc/0009-supervisor-middleware/appendices/protocol-extensions.md index 924c7bd699..63115d9e52 100644 --- a/rfc/0009-supervisor-middleware/appendices/protocol-extensions.md +++ b/rfc/0009-supervisor-middleware/appendices/protocol-extensions.md @@ -2,7 +2,9 @@ > This is an appendix to the [RFC](../README.md). Please familiarize yourself with the RFC before reading this. -The v1 contract is intentionally minimal: one HTTP request hook, buffered unary calls, an `allow`/`deny` decision plus optional transformed content, findings, and metadata. This appendix records extensions the proto should not preclude, so v1 stays small without painting future work into a corner. None of these are committed; they exist to validate that the v1 shape is forward-compatible. +**Update in PR #2477 - WebSocket middleware:** V1 now includes a forward-text WebSocket operation. The updated text below separates this implemented operation from future HTTP streaming and WebSocket return-path operations. + +The v1 contract is intentionally minimal: one buffered unary HTTP request hook and one forward-text WebSocket message hook, each with an `allow`/`deny` decision plus optional transformed content, findings, and metadata. This appendix records extensions the proto should not preclude, so v1 stays small without painting future work into a corner. None of these are committed; they exist to validate that the v1 shape is forward-compatible. ## Streaming @@ -42,16 +44,19 @@ A cleaner phased design using a `oneof` over `context` and `body_chunk`, in the ## Additional operation phases -V1 defines a single typed operation, `HTTP_REQUEST/PRE_CREDENTIALS`, which runs after network and L7 policy admit a request and before credential injection. The same service interface can host more operations, each advertised through the `Describe` manifest and invoked through an operation-specific method such as `EvaluateHttpRequest`. Each operation and phase pair encodes a different position in the proxy flow: +> **Update in PR #2477 - WebSocket middleware:** This section now records `WEBSOCKET_MESSAGE/PRE_CREDENTIALS` as implemented. It keeps `WEBSOCKET_MESSAGE/PRE_RETURN` as a reserved future operation. + +V1 supports `HTTP_REQUEST/PRE_CREDENTIALS` and forward-text `WEBSOCKET_MESSAGE/PRE_CREDENTIALS`. The same service interface can host more operations, each advertised through the `Describe` manifest and invoked through an operation-specific method. Each operation and phase pair encodes a different position in the proxy flow: - `Connection/before_policy` / `HttpRequest/before_policy` - *before* network/L7 policy admits the request, for earlier classification. Riskier, because request content reaches a service before policy has allowed the request. - `HTTP_REQUEST/PRE_CREDENTIALS` (v1) - after policy admits the request, before credential injection. - `HttpRequest/post_credentials` - after credential injection, immediately before the relay writes the request upstream. This hook is credential-visible, so it is built-in-only: OpenShell marks it as a restricted hook and rejects any externally registered middleware that advertises it during manifest validation. The motivating use is request signing that must run after credentials are injected - for example a built-in `openshell/sigv4` that strips placeholder-signed AWS headers and signs the finalized request with supervisor-resolved credentials just before it is sent upstream. - `HttpResponse/completed` - after an upstream request completes, emit metadata such as status, content length, selected route, selected model, and model usage if available. This is notification-only: no body, no transformation, and no allow/deny verdict. It would let reservation-style budget middleware reconcile a pre-dispatch decision without introducing response-body inspection. - `HttpResponse/before_return` - on the return path, after the upstream responds and before the response reaches the sandbox; inspect or redact upstream responses. -- `WebSocketMessage/before_forward` / `WebSocketMessage/before_return` - after a WebSocket or streaming protocol upgrade, on each forwarded or returned message, well past the one-shot request path. +- `WEBSOCKET_MESSAGE/PRE_CREDENTIALS` (v1 forward text) - after a WebSocket upgrade, on each complete client text message before credential placeholder rewriting. Before upstream contact, a concurrent preflight lets each selected stage inspect, voluntarily skip, or authoritatively deny the upgrade. Explicit denial takes precedence over failures and is enforced independently of `on_error`; OpenShell best-effort ends every still-writable opened stage stream with the typed terminal reason. An attached implementation without this binding is not selected and records coverage rather than applying `on_error`. Binary messages pass without inspection, consume a logical sequence, and record unsupported-message coverage for active stages. +- `WEBSOCKET_MESSAGE/PRE_RETURN` - on complete upstream messages before they return to the workload. The enum value is reserved, but manifests advertising it are rejected until return-path inspection is implemented. -Pre-policy phases run earliest, the two request phases bracket credential injection, response notifications and response phases run after the upstream call, and message phases run later, sometimes on a different path entirely. Of these, only `HTTP_REQUEST/PRE_CREDENTIALS` is part of v1. `HttpRequest/post_credentials` is the nearest planned request-path follow-up and is kept built-in-only because it sees injected credentials; `HttpResponse/completed` is a separate future notification hook for metadata-only post-call reconciliation. +Pre-policy phases run earliest, the two request phases bracket credential injection, response notifications and response phases run after the upstream call, and message phases run later on the parsed relay. V1 implements only the two pre-credentials pairs above. `HttpRequest/post_credentials` is the nearest planned request-path follow-up and is kept built-in-only because it sees injected credentials; `HttpResponse/completed` is a separate future notification hook for metadata-only post-call reconciliation. ## Semantic context @@ -83,4 +88,6 @@ Phase 2 removes plaintext endpoint support and removes `allow_insecure`. Every e The exact phase 2 mechanism is deferred. Follow-up protocol work should choose and specify mTLS, TLS plus explicit caller authentication, or an equivalent design, including trust roots, client identity, credential delivery, certificate or key rotation, middleware identity binding, and how supervisors receive authentication material. +The alpha mechanism that was subsequently built - TLS with optional operator-provided trust roots plus short-lived, exact-audience gateway-signed JWTs - is recorded in [extension-authentication.md](extension-authentication.md). It supersedes this section's `allow_insecure` design with `allow_insecure_transport` and narrows, but does not close, the phase 2 question: mTLS and overlapping key rotation remain deferred. + Even during the phase 1 plaintext exception, the hook stays before provider credential injection, and OpenShell does not forward original `Authorization`, `Cookie`, or other protected headers to middleware. This preserves the separation between content inspection and upstream credential injection while authenticated transport is completed. diff --git a/rfc/0010-gateway-interceptors/appendices/extension-authentication.md b/rfc/0010-gateway-interceptors/appendices/extension-authentication.md new file mode 100644 index 0000000000..e2abff31ff --- /dev/null +++ b/rfc/0010-gateway-interceptors/appendices/extension-authentication.md @@ -0,0 +1,31 @@ +# Appendix: Extension Authentication (Alpha) + +> This is an appendix to the [RFC](../README.md). Please familiarize yourself with the RFC before reading this. + +The RFC body states that all gateway interceptor connections require authentication, leaves the model out of scope, and suggests implementations should support mTLS and bearer-token authentication. This appendix records the mechanism that was actually built for alpha. It supersedes that paragraph; the rest of the body is unchanged. + +Gateway interceptors and supervisor middleware share one implementation. The full claim contract, authorization model, key distribution, and residual risks are documented once in [RFC 0009's appendix](../../0009-supervisor-middleware/appendices/extension-authentication.md). This appendix records only what differs for interceptors. + +## What ships in alpha + +The bearer-token half of the body's suggestion, not the mTLS half. The gateway attaches a short-lived, exact-audience Ed25519 JWT to `Describe`, `Evaluate`, and provider-profile snapshot calls. mTLS remains deferred hardening. + +Interceptors are called only by the gateway, so every token carries `caller_kind: gateway` and no `sandbox_id`. There is no supervisor-side distribution path and no policy-based authorization step: the gateway mints its own credentials at startup from configuration and rotates them in place. + +## Transport + +Unlike middleware, interceptors keep the body's Unix domain socket option. A gateway-local socket is reachable by the only caller that exists, so both `https://` and `unix://` are accepted when gateway JWT signing is configured. HTTPS endpoints may pin an operator-provided CA bundle and retain normal hostname verification. + +## Audience agreement + +The audience defaults to `urn:openshell:extension:interceptor:` and may be set explicitly per interceptor. An interceptor may advertise the audience it verifies in the `expected_audience` field of its `Describe` manifest. After authenticated `Describe` succeeds, the gateway treats that value as a consistency assertion and refuses to start when it differs from the configured audience. A strict verifier may reject an incorrect audience before returning the manifest, so this does not provide audience discovery. + +Because the body already makes an unavailable service, invalid manifest, or unauthorized binding a startup failure, this fits the existing posture: interceptor configuration problems surface before the gateway serves traffic. + +## Compatibility + +An interceptor may set `allow_insecure_transport = true` to keep a plaintext `http://` endpoint with no credential attached. The gateway logs a warning naming the interceptor at every startup. This exists for local development and for deployments configured before extension authentication existed. + +## Deferred + +mTLS client authentication, multi-key rotation with an overlap window, and replay resistance beyond short expiry remain follow-up work, as recorded in RFC 0009's appendix. diff --git a/sdk/go/proto/openshellv1/openshell.pb.go b/sdk/go/proto/openshellv1/openshell.pb.go index fdbcadea97..ecff3a1e17 100644 --- a/sdk/go/proto/openshellv1/openshell.pb.go +++ b/sdk/go/proto/openshellv1/openshell.pb.go @@ -485,13 +485,18 @@ func (x *IssueSandboxTokenResponse) GetExpiresAtMs() int64 { return 0 } -// RefreshSandboxToken request. Empty body; the calling principal must -// already be a sandbox principal (i.e. the request carries a still-valid -// gateway-minted JWT in its Authorization header). +// RefreshSandboxToken request. The calling principal must already be a +// sandbox principal (i.e. the request carries a still-valid gateway-minted +// JWT in its Authorization header). Extension service names are resolved +// against server-owned registrations and the sandbox's effective policy; +// callers never choose token audiences directly. type RefreshSandboxTokenRequest struct { - state protoimpl.MessageState `protogen:"open.v1"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + // Operator registration names for extension services selected by the + // sandbox's effective policy. + ExtensionServiceNames []string `protobuf:"bytes,1,rep,name=extension_service_names,json=extensionServiceNames,proto3" json:"extension_service_names,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RefreshSandboxTokenRequest) Reset() { @@ -524,6 +529,13 @@ func (*RefreshSandboxTokenRequest) Descriptor() ([]byte, []int) { return file_openshell_proto_rawDescGZIP(), []int{2} } +func (x *RefreshSandboxTokenRequest) GetExtensionServiceNames() []string { + if x != nil { + return x.ExtensionServiceNames + } + return nil +} + // RefreshSandboxToken response. The new token replaces the supervisor's // in-memory bearer credential. type RefreshSandboxTokenResponse struct { @@ -532,9 +544,12 @@ type RefreshSandboxTokenResponse struct { Token string `protobuf:"bytes,1,opt,name=token,proto3" json:"token,omitempty"` // Absolute expiry of the new token, milliseconds since the epoch. 0 means // the token is non-expiring. - ExpiresAtMs int64 `protobuf:"varint,2,opt,name=expires_at_ms,json=expiresAtMs,proto3" json:"expires_at_ms,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + ExpiresAtMs int64 `protobuf:"varint,2,opt,name=expires_at_ms,json=expiresAtMs,proto3" json:"expires_at_ms,omitempty"` + // Fresh credentials for the requested, policy-authorized extension + // services. These remain in supervisor memory and are never persisted. + ExtensionCredentials []*ExtensionServiceCredential `protobuf:"bytes,3,rep,name=extension_credentials,json=extensionCredentials,proto3" json:"extension_credentials,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RefreshSandboxTokenResponse) Reset() { @@ -581,6 +596,13 @@ func (x *RefreshSandboxTokenResponse) GetExpiresAtMs() int64 { return 0 } +func (x *RefreshSandboxTokenResponse) GetExtensionCredentials() []*ExtensionServiceCredential { + if x != nil { + return x.ExtensionCredentials + } + return nil +} + // Health check request. type HealthRequest struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -12980,6 +13002,73 @@ func (x *ListWorkspaceMembersResponse) GetMembers() []*WorkspaceMember { return nil } +// Short-lived credential for one policy-authorized extension service. +// Kept at the end of the file so adding it does not renumber existing +// generated message descriptors. +type ExtensionServiceCredential struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Operator registration name used to correlate the credential with the + // stable service registration delivered by GetSandboxConfig. + ServiceName string `protobuf:"bytes,1,opt,name=service_name,json=serviceName,proto3" json:"service_name,omitempty"` + // Gateway-minted JWT with an audience derived from the registration. + Token string `protobuf:"bytes,2,opt,name=token,proto3" json:"token,omitempty"` + // Absolute expiry of the token, milliseconds since the epoch. + ExpiresAtMs int64 `protobuf:"varint,3,opt,name=expires_at_ms,json=expiresAtMs,proto3" json:"expires_at_ms,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExtensionServiceCredential) Reset() { + *x = ExtensionServiceCredential{} + mi := &file_openshell_proto_msgTypes[184] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExtensionServiceCredential) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExtensionServiceCredential) ProtoMessage() {} + +func (x *ExtensionServiceCredential) ProtoReflect() protoreflect.Message { + mi := &file_openshell_proto_msgTypes[184] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ExtensionServiceCredential.ProtoReflect.Descriptor instead. +func (*ExtensionServiceCredential) Descriptor() ([]byte, []int) { + return file_openshell_proto_rawDescGZIP(), []int{184} +} + +func (x *ExtensionServiceCredential) GetServiceName() string { + if x != nil { + return x.ServiceName + } + return "" +} + +func (x *ExtensionServiceCredential) GetToken() string { + if x != nil { + return x.Token + } + return "" +} + +func (x *ExtensionServiceCredential) GetExpiresAtMs() int64 { + if x != nil { + return x.ExpiresAtMs + } + return 0 +} + var File_openshell_proto protoreflect.FileDescriptor const file_openshell_proto_rawDesc = "" + @@ -12988,11 +13077,13 @@ const file_openshell_proto_rawDesc = "" + "\x18IssueSandboxTokenRequest\"[\n" + "\x19IssueSandboxTokenResponse\x12\x1a\n" + "\x05token\x18\x01 \x01(\tB\x04\x88\xb5\x18\x01R\x05token\x12\"\n" + - "\rexpires_at_ms\x18\x02 \x01(\x03R\vexpiresAtMs\"\x1c\n" + - "\x1aRefreshSandboxTokenRequest\"]\n" + + "\rexpires_at_ms\x18\x02 \x01(\x03R\vexpiresAtMs\"T\n" + + "\x1aRefreshSandboxTokenRequest\x126\n" + + "\x17extension_service_names\x18\x01 \x03(\tR\x15extensionServiceNames\"\xbc\x01\n" + "\x1bRefreshSandboxTokenResponse\x12\x1a\n" + "\x05token\x18\x01 \x01(\tB\x04\x88\xb5\x18\x01R\x05token\x12\"\n" + - "\rexpires_at_ms\x18\x02 \x01(\x03R\vexpiresAtMs\"\x0f\n" + + "\rexpires_at_ms\x18\x02 \x01(\x03R\vexpiresAtMs\x12]\n" + + "\x15extension_credentials\x18\x03 \x03(\v2(.openshell.v1.ExtensionServiceCredentialR\x14extensionCredentials\"\x0f\n" + "\rHealthRequest\"_\n" + "\x0eHealthResponse\x123\n" + "\x06status\x18\x01 \x01(\x0e2\x1b.openshell.v1.ServiceStatusR\x06status\x12\x18\n" + @@ -13971,7 +14062,11 @@ const file_openshell_proto_rawDesc = "" + "\x05limit\x18\x02 \x01(\rR\x05limit\x12\x16\n" + "\x06offset\x18\x03 \x01(\rR\x06offset\"W\n" + "\x1cListWorkspaceMembersResponse\x127\n" + - "\amembers\x18\x01 \x03(\v2\x1d.openshell.v1.WorkspaceMemberR\amembers*\x89\x02\n" + + "\amembers\x18\x01 \x03(\v2\x1d.openshell.v1.WorkspaceMemberR\amembers\"\x7f\n" + + "\x1aExtensionServiceCredential\x12!\n" + + "\fservice_name\x18\x01 \x01(\tR\vserviceName\x12\x1a\n" + + "\x05token\x18\x02 \x01(\tB\x04\x88\xb5\x18\x01R\x05token\x12\"\n" + + "\rexpires_at_ms\x18\x03 \x01(\x03R\vexpiresAtMs*\x89\x02\n" + "\fSandboxPhase\x12\x1d\n" + "\x19SANDBOX_PHASE_UNSPECIFIED\x10\x00\x12\x1e\n" + "\x1aSANDBOX_PHASE_PROVISIONING\x10\x01\x12\x17\n" + @@ -14164,7 +14259,7 @@ func file_openshell_proto_rawDescGZIP() []byte { } var file_openshell_proto_enumTypes = make([]protoimpl.EnumInfo, 6) -var file_openshell_proto_msgTypes = make([]protoimpl.MessageInfo, 208) +var file_openshell_proto_msgTypes = make([]protoimpl.MessageInfo, 209) var file_openshell_proto_goTypes = []any{ (SandboxPhase)(0), // 0: openshell.v1.SandboxPhase (ProviderCredentialRefreshStrategy)(0), // 1: openshell.v1.ProviderCredentialRefreshStrategy @@ -14356,334 +14451,336 @@ var file_openshell_proto_goTypes = []any{ (*RemoveWorkspaceMemberResponse)(nil), // 187: openshell.v1.RemoveWorkspaceMemberResponse (*ListWorkspaceMembersRequest)(nil), // 188: openshell.v1.ListWorkspaceMembersRequest (*ListWorkspaceMembersResponse)(nil), // 189: openshell.v1.ListWorkspaceMembersResponse - nil, // 190: openshell.v1.SandboxSpec.EnvironmentEntry - nil, // 191: openshell.v1.SandboxTemplate.LabelsEntry - nil, // 192: openshell.v1.SandboxTemplate.AnnotationsEntry - nil, // 193: openshell.v1.SandboxTemplate.EnvironmentEntry - nil, // 194: openshell.v1.PlatformEvent.MetadataEntry - nil, // 195: openshell.v1.CreateSandboxRequest.LabelsEntry - nil, // 196: openshell.v1.CreateSandboxRequest.AnnotationsEntry - nil, // 197: openshell.v1.ExecSandboxRequest.EnvironmentEntry - nil, // 198: openshell.v1.SandboxLogLine.FieldsEntry - nil, // 199: openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry - nil, // 200: openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry - nil, // 201: openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry - nil, // 202: openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry - nil, // 203: openshell.v1.ProviderProfile.AnnotationsEntry - nil, // 204: openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry - nil, // 205: openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry - nil, // 206: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry - nil, // 207: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry - nil, // 208: openshell.v1.UpdateConfigRequest.AnnotationsEntry - nil, // 209: openshell.v1.UpdateConfigResponse.AnnotationsEntry - nil, // 210: openshell.v1.SandboxPolicyRevision.ProvenanceEntry - nil, // 211: openshell.v1.PolicyRevisionPayload.ProvenanceEntry - nil, // 212: openshell.v1.StoredPolicyRevision.ProvenanceEntry - nil, // 213: openshell.v1.CreateWorkspaceRequest.LabelsEntry - (*datamodelv1.ObjectMeta)(nil), // 214: openshell.datamodel.v1.ObjectMeta - (*sandboxv1.SandboxPolicy)(nil), // 215: openshell.sandbox.v1.SandboxPolicy - (*structpb.Struct)(nil), // 216: google.protobuf.Struct - (*datamodelv1.Provider)(nil), // 217: openshell.datamodel.v1.Provider - (*sandboxv1.NetworkEndpoint)(nil), // 218: openshell.sandbox.v1.NetworkEndpoint - (*sandboxv1.NetworkBinary)(nil), // 219: openshell.sandbox.v1.NetworkBinary - (*sandboxv1.SettingValue)(nil), // 220: openshell.sandbox.v1.SettingValue - (*sandboxv1.NetworkPolicyRule)(nil), // 221: openshell.sandbox.v1.NetworkPolicyRule - (*sandboxv1.L7DenyRule)(nil), // 222: openshell.sandbox.v1.L7DenyRule - (*sandboxv1.L7Rule)(nil), // 223: openshell.sandbox.v1.L7Rule - (*datamodelv1.Workspace)(nil), // 224: openshell.datamodel.v1.Workspace - (*sandboxv1.GetSandboxConfigRequest)(nil), // 225: openshell.sandbox.v1.GetSandboxConfigRequest - (*sandboxv1.GetGatewayConfigRequest)(nil), // 226: openshell.sandbox.v1.GetGatewayConfigRequest - (*sandboxv1.GetSandboxConfigResponse)(nil), // 227: openshell.sandbox.v1.GetSandboxConfigResponse - (*sandboxv1.GetGatewayConfigResponse)(nil), // 228: openshell.sandbox.v1.GetGatewayConfigResponse + (*ExtensionServiceCredential)(nil), // 190: openshell.v1.ExtensionServiceCredential + nil, // 191: openshell.v1.SandboxSpec.EnvironmentEntry + nil, // 192: openshell.v1.SandboxTemplate.LabelsEntry + nil, // 193: openshell.v1.SandboxTemplate.AnnotationsEntry + nil, // 194: openshell.v1.SandboxTemplate.EnvironmentEntry + nil, // 195: openshell.v1.PlatformEvent.MetadataEntry + nil, // 196: openshell.v1.CreateSandboxRequest.LabelsEntry + nil, // 197: openshell.v1.CreateSandboxRequest.AnnotationsEntry + nil, // 198: openshell.v1.ExecSandboxRequest.EnvironmentEntry + nil, // 199: openshell.v1.SandboxLogLine.FieldsEntry + nil, // 200: openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry + nil, // 201: openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry + nil, // 202: openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry + nil, // 203: openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry + nil, // 204: openshell.v1.ProviderProfile.AnnotationsEntry + nil, // 205: openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry + nil, // 206: openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry + nil, // 207: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry + nil, // 208: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry + nil, // 209: openshell.v1.UpdateConfigRequest.AnnotationsEntry + nil, // 210: openshell.v1.UpdateConfigResponse.AnnotationsEntry + nil, // 211: openshell.v1.SandboxPolicyRevision.ProvenanceEntry + nil, // 212: openshell.v1.PolicyRevisionPayload.ProvenanceEntry + nil, // 213: openshell.v1.StoredPolicyRevision.ProvenanceEntry + nil, // 214: openshell.v1.CreateWorkspaceRequest.LabelsEntry + (*datamodelv1.ObjectMeta)(nil), // 215: openshell.datamodel.v1.ObjectMeta + (*sandboxv1.SandboxPolicy)(nil), // 216: openshell.sandbox.v1.SandboxPolicy + (*structpb.Struct)(nil), // 217: google.protobuf.Struct + (*datamodelv1.Provider)(nil), // 218: openshell.datamodel.v1.Provider + (*sandboxv1.NetworkEndpoint)(nil), // 219: openshell.sandbox.v1.NetworkEndpoint + (*sandboxv1.NetworkBinary)(nil), // 220: openshell.sandbox.v1.NetworkBinary + (*sandboxv1.SettingValue)(nil), // 221: openshell.sandbox.v1.SettingValue + (*sandboxv1.NetworkPolicyRule)(nil), // 222: openshell.sandbox.v1.NetworkPolicyRule + (*sandboxv1.L7DenyRule)(nil), // 223: openshell.sandbox.v1.L7DenyRule + (*sandboxv1.L7Rule)(nil), // 224: openshell.sandbox.v1.L7Rule + (*datamodelv1.Workspace)(nil), // 225: openshell.datamodel.v1.Workspace + (*sandboxv1.GetSandboxConfigRequest)(nil), // 226: openshell.sandbox.v1.GetSandboxConfigRequest + (*sandboxv1.GetGatewayConfigRequest)(nil), // 227: openshell.sandbox.v1.GetGatewayConfigRequest + (*sandboxv1.GetSandboxConfigResponse)(nil), // 228: openshell.sandbox.v1.GetSandboxConfigResponse + (*sandboxv1.GetGatewayConfigResponse)(nil), // 229: openshell.sandbox.v1.GetGatewayConfigResponse } var file_openshell_proto_depIdxs = []int32{ - 4, // 0: openshell.v1.HealthResponse.status:type_name -> openshell.v1.ServiceStatus - 4, // 1: openshell.v1.GetGatewayInfoResponse.status:type_name -> openshell.v1.ServiceStatus - 16, // 2: openshell.v1.GetGatewayInfoResponse.compute_drivers:type_name -> openshell.v1.ComputeDriverInfo - 17, // 3: openshell.v1.ComputeDriverInfo.capabilities:type_name -> openshell.v1.ComputeDriverCapabilities - 214, // 4: openshell.v1.Sandbox.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 19, // 5: openshell.v1.Sandbox.spec:type_name -> openshell.v1.SandboxSpec - 23, // 6: openshell.v1.Sandbox.status:type_name -> openshell.v1.SandboxStatus - 190, // 7: openshell.v1.SandboxSpec.environment:type_name -> openshell.v1.SandboxSpec.EnvironmentEntry - 22, // 8: openshell.v1.SandboxSpec.template:type_name -> openshell.v1.SandboxTemplate - 215, // 9: openshell.v1.SandboxSpec.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 20, // 10: openshell.v1.SandboxSpec.resource_requirements:type_name -> openshell.v1.ResourceRequirements - 21, // 11: openshell.v1.ResourceRequirements.gpu:type_name -> openshell.v1.GpuResourceRequirements - 191, // 12: openshell.v1.SandboxTemplate.labels:type_name -> openshell.v1.SandboxTemplate.LabelsEntry - 192, // 13: openshell.v1.SandboxTemplate.annotations:type_name -> openshell.v1.SandboxTemplate.AnnotationsEntry - 193, // 14: openshell.v1.SandboxTemplate.environment:type_name -> openshell.v1.SandboxTemplate.EnvironmentEntry - 216, // 15: openshell.v1.SandboxTemplate.resources:type_name -> google.protobuf.Struct - 216, // 16: openshell.v1.SandboxTemplate.driver_config:type_name -> google.protobuf.Struct - 24, // 17: openshell.v1.SandboxStatus.conditions:type_name -> openshell.v1.SandboxCondition - 0, // 18: openshell.v1.SandboxStatus.phase:type_name -> openshell.v1.SandboxPhase - 194, // 19: openshell.v1.PlatformEvent.metadata:type_name -> openshell.v1.PlatformEvent.MetadataEntry - 19, // 20: openshell.v1.CreateSandboxRequest.spec:type_name -> openshell.v1.SandboxSpec - 195, // 21: openshell.v1.CreateSandboxRequest.labels:type_name -> openshell.v1.CreateSandboxRequest.LabelsEntry - 196, // 22: openshell.v1.CreateSandboxRequest.annotations:type_name -> openshell.v1.CreateSandboxRequest.AnnotationsEntry - 18, // 23: openshell.v1.SandboxResponse.sandbox:type_name -> openshell.v1.Sandbox - 18, // 24: openshell.v1.ListSandboxesResponse.sandboxes:type_name -> openshell.v1.Sandbox - 217, // 25: openshell.v1.ListSandboxProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider - 18, // 26: openshell.v1.AttachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox - 18, // 27: openshell.v1.DetachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox - 50, // 28: openshell.v1.ListServicesResponse.services:type_name -> openshell.v1.ServiceEndpointResponse - 214, // 29: openshell.v1.ServiceEndpoint.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 49, // 30: openshell.v1.ServiceEndpointResponse.endpoint:type_name -> openshell.v1.ServiceEndpoint - 197, // 31: openshell.v1.ExecSandboxRequest.environment:type_name -> openshell.v1.ExecSandboxRequest.EnvironmentEntry - 54, // 32: openshell.v1.ExecSandboxEvent.stdout:type_name -> openshell.v1.ExecSandboxStdout - 55, // 33: openshell.v1.ExecSandboxEvent.stderr:type_name -> openshell.v1.ExecSandboxStderr - 56, // 34: openshell.v1.ExecSandboxEvent.exit:type_name -> openshell.v1.ExecSandboxExit - 140, // 35: openshell.v1.TcpForwardInit.ssh:type_name -> openshell.v1.SshRelayTarget - 141, // 36: openshell.v1.TcpForwardInit.tcp:type_name -> openshell.v1.TcpRelayTarget - 58, // 37: openshell.v1.TcpForwardFrame.init:type_name -> openshell.v1.TcpForwardInit - 53, // 38: openshell.v1.ExecSandboxInput.start:type_name -> openshell.v1.ExecSandboxRequest - 61, // 39: openshell.v1.ExecSandboxInput.resize:type_name -> openshell.v1.ExecSandboxWindowResize - 214, // 40: openshell.v1.SshSession.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 18, // 41: openshell.v1.SandboxStreamEvent.sandbox:type_name -> openshell.v1.Sandbox - 65, // 42: openshell.v1.SandboxStreamEvent.log:type_name -> openshell.v1.SandboxLogLine - 25, // 43: openshell.v1.SandboxStreamEvent.event:type_name -> openshell.v1.PlatformEvent - 66, // 44: openshell.v1.SandboxStreamEvent.warning:type_name -> openshell.v1.SandboxStreamWarning - 151, // 45: openshell.v1.SandboxStreamEvent.draft_policy_update:type_name -> openshell.v1.DraftPolicyUpdate - 198, // 46: openshell.v1.SandboxLogLine.fields:type_name -> openshell.v1.SandboxLogLine.FieldsEntry - 217, // 47: openshell.v1.CreateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider - 217, // 48: openshell.v1.UpdateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider - 199, // 49: openshell.v1.UpdateProviderRequest.credential_expires_at_ms:type_name -> openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry - 217, // 50: openshell.v1.ProviderResponse.provider:type_name -> openshell.datamodel.v1.Provider - 217, // 51: openshell.v1.ListProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider - 95, // 52: openshell.v1.ProviderProfileImportItem.profile:type_name -> openshell.v1.ProviderProfile - 78, // 53: openshell.v1.ProviderCredentialTokenGrant.audience_overrides:type_name -> openshell.v1.ProviderCredentialTokenGrantAudienceOverride - 83, // 54: openshell.v1.ProviderProfileCredential.refresh:type_name -> openshell.v1.ProviderCredentialRefresh - 79, // 55: openshell.v1.ProviderProfileCredential.token_grant:type_name -> openshell.v1.ProviderCredentialTokenGrant - 1, // 56: openshell.v1.ProviderCredentialRefresh.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 81, // 57: openshell.v1.ProviderCredentialRefresh.material:type_name -> openshell.v1.ProviderCredentialRefreshMaterial - 82, // 58: openshell.v1.ProviderCredentialRefresh.additional_outputs:type_name -> openshell.v1.ProviderCredentialRefreshOutput - 1, // 59: openshell.v1.ProviderCredentialRefreshStatus.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 214, // 60: openshell.v1.StoredProviderCredentialRefreshState.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 1, // 61: openshell.v1.StoredProviderCredentialRefreshState.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 200, // 62: openshell.v1.StoredProviderCredentialRefreshState.material:type_name -> openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry - 201, // 63: openshell.v1.StoredProviderCredentialRefreshState.additional_output_keys:type_name -> openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry - 84, // 64: openshell.v1.GetProviderRefreshStatusResponse.credentials:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 1, // 65: openshell.v1.ConfigureProviderRefreshRequest.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy - 202, // 66: openshell.v1.ConfigureProviderRefreshRequest.material:type_name -> openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry - 84, // 67: openshell.v1.ConfigureProviderRefreshResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 84, // 68: openshell.v1.RotateProviderCredentialResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus - 2, // 69: openshell.v1.ProviderProfile.category:type_name -> openshell.v1.ProviderProfileCategory - 80, // 70: openshell.v1.ProviderProfile.credentials:type_name -> openshell.v1.ProviderProfileCredential - 218, // 71: openshell.v1.ProviderProfile.endpoints:type_name -> openshell.sandbox.v1.NetworkEndpoint - 219, // 72: openshell.v1.ProviderProfile.binaries:type_name -> openshell.sandbox.v1.NetworkBinary - 85, // 73: openshell.v1.ProviderProfile.discovery:type_name -> openshell.v1.ProviderProfileDiscovery - 203, // 74: openshell.v1.ProviderProfile.annotations:type_name -> openshell.v1.ProviderProfile.AnnotationsEntry - 214, // 75: openshell.v1.StoredProviderProfile.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 95, // 76: openshell.v1.StoredProviderProfile.profile:type_name -> openshell.v1.ProviderProfile - 95, // 77: openshell.v1.ProviderProfileResponse.profile:type_name -> openshell.v1.ProviderProfile - 95, // 78: openshell.v1.ListProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile - 76, // 79: openshell.v1.ImportProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem - 77, // 80: openshell.v1.ImportProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 95, // 81: openshell.v1.ImportProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile - 76, // 82: openshell.v1.UpdateProviderProfilesRequest.profile:type_name -> openshell.v1.ProviderProfileImportItem - 77, // 83: openshell.v1.UpdateProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 95, // 84: openshell.v1.UpdateProviderProfilesResponse.profile:type_name -> openshell.v1.ProviderProfile - 76, // 85: openshell.v1.LintProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem - 77, // 86: openshell.v1.LintProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic - 109, // 87: openshell.v1.StaticCredentialBinding.endpoints:type_name -> openshell.v1.StaticCredentialEndpointBinding - 204, // 88: openshell.v1.GetSandboxProviderEnvironmentResponse.environment:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry - 205, // 89: openshell.v1.GetSandboxProviderEnvironmentResponse.credential_expires_at_ms:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry - 206, // 90: openshell.v1.GetSandboxProviderEnvironmentResponse.dynamic_credentials:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry - 207, // 91: openshell.v1.GetSandboxProviderEnvironmentResponse.static_credential_bindings:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry - 215, // 92: openshell.v1.UpdateConfigRequest.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 220, // 93: openshell.v1.UpdateConfigRequest.setting_value:type_name -> openshell.sandbox.v1.SettingValue - 113, // 94: openshell.v1.UpdateConfigRequest.merge_operations:type_name -> openshell.v1.PolicyMergeOperation - 208, // 95: openshell.v1.UpdateConfigRequest.annotations:type_name -> openshell.v1.UpdateConfigRequest.AnnotationsEntry - 114, // 96: openshell.v1.PolicyMergeOperation.add_rule:type_name -> openshell.v1.AddNetworkRule - 115, // 97: openshell.v1.PolicyMergeOperation.remove_endpoint:type_name -> openshell.v1.RemoveNetworkEndpoint - 116, // 98: openshell.v1.PolicyMergeOperation.remove_rule:type_name -> openshell.v1.RemoveNetworkRule - 117, // 99: openshell.v1.PolicyMergeOperation.add_deny_rules:type_name -> openshell.v1.AddDenyRules - 118, // 100: openshell.v1.PolicyMergeOperation.add_allow_rules:type_name -> openshell.v1.AddAllowRules - 119, // 101: openshell.v1.PolicyMergeOperation.remove_binary:type_name -> openshell.v1.RemoveNetworkBinary - 221, // 102: openshell.v1.AddNetworkRule.rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 222, // 103: openshell.v1.AddDenyRules.deny_rules:type_name -> openshell.sandbox.v1.L7DenyRule - 223, // 104: openshell.v1.AddAllowRules.rules:type_name -> openshell.sandbox.v1.L7Rule - 209, // 105: openshell.v1.UpdateConfigResponse.annotations:type_name -> openshell.v1.UpdateConfigResponse.AnnotationsEntry - 127, // 106: openshell.v1.GetSandboxPolicyStatusResponse.revision:type_name -> openshell.v1.SandboxPolicyRevision - 127, // 107: openshell.v1.ListSandboxPoliciesResponse.revisions:type_name -> openshell.v1.SandboxPolicyRevision - 3, // 108: openshell.v1.ReportPolicyStatusRequest.status:type_name -> openshell.v1.PolicyStatus - 3, // 109: openshell.v1.SandboxPolicyRevision.status:type_name -> openshell.v1.PolicyStatus - 215, // 110: openshell.v1.SandboxPolicyRevision.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 210, // 111: openshell.v1.SandboxPolicyRevision.provenance:type_name -> openshell.v1.SandboxPolicyRevision.ProvenanceEntry - 65, // 112: openshell.v1.PushSandboxLogsRequest.logs:type_name -> openshell.v1.SandboxLogLine - 65, // 113: openshell.v1.GetSandboxLogsResponse.logs:type_name -> openshell.v1.SandboxLogLine - 134, // 114: openshell.v1.SupervisorMessage.hello:type_name -> openshell.v1.SupervisorHello - 137, // 115: openshell.v1.SupervisorMessage.heartbeat:type_name -> openshell.v1.SupervisorHeartbeat - 144, // 116: openshell.v1.SupervisorMessage.relay_open_result:type_name -> openshell.v1.RelayOpenResult - 145, // 117: openshell.v1.SupervisorMessage.relay_close:type_name -> openshell.v1.RelayClose - 135, // 118: openshell.v1.GatewayMessage.session_accepted:type_name -> openshell.v1.SessionAccepted - 136, // 119: openshell.v1.GatewayMessage.session_rejected:type_name -> openshell.v1.SessionRejected - 138, // 120: openshell.v1.GatewayMessage.heartbeat:type_name -> openshell.v1.GatewayHeartbeat - 139, // 121: openshell.v1.GatewayMessage.relay_open:type_name -> openshell.v1.RelayOpen - 145, // 122: openshell.v1.GatewayMessage.relay_close:type_name -> openshell.v1.RelayClose - 140, // 123: openshell.v1.RelayOpen.ssh:type_name -> openshell.v1.SshRelayTarget - 141, // 124: openshell.v1.RelayOpen.tcp:type_name -> openshell.v1.TcpRelayTarget - 142, // 125: openshell.v1.RelayFrame.init:type_name -> openshell.v1.RelayInit - 146, // 126: openshell.v1.DenialSummary.l7_request_samples:type_name -> openshell.v1.L7RequestSample - 148, // 127: openshell.v1.NetworkActivitySummary.denials_by_group:type_name -> openshell.v1.DenialGroupCount - 221, // 128: openshell.v1.PolicyChunk.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 147, // 129: openshell.v1.SubmitPolicyAnalysisRequest.summaries:type_name -> openshell.v1.DenialSummary - 150, // 130: openshell.v1.SubmitPolicyAnalysisRequest.proposed_chunks:type_name -> openshell.v1.PolicyChunk - 149, // 131: openshell.v1.SubmitPolicyAnalysisRequest.network_activity_summaries:type_name -> openshell.v1.NetworkActivitySummary - 150, // 132: openshell.v1.GetDraftPolicyResponse.chunks:type_name -> openshell.v1.PolicyChunk - 221, // 133: openshell.v1.EditDraftChunkRequest.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 169, // 134: openshell.v1.GetDraftHistoryResponse.entries:type_name -> openshell.v1.DraftHistoryEntry - 215, // 135: openshell.v1.PolicyRevisionPayload.policy:type_name -> openshell.sandbox.v1.SandboxPolicy - 211, // 136: openshell.v1.PolicyRevisionPayload.provenance:type_name -> openshell.v1.PolicyRevisionPayload.ProvenanceEntry - 221, // 137: openshell.v1.DraftChunkPayload.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule - 212, // 138: openshell.v1.StoredPolicyRevision.provenance:type_name -> openshell.v1.StoredPolicyRevision.ProvenanceEntry - 213, // 139: openshell.v1.CreateWorkspaceRequest.labels:type_name -> openshell.v1.CreateWorkspaceRequest.LabelsEntry - 224, // 140: openshell.v1.CreateWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace - 224, // 141: openshell.v1.GetWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace - 224, // 142: openshell.v1.ListWorkspacesResponse.workspaces:type_name -> openshell.datamodel.v1.Workspace - 214, // 143: openshell.v1.WorkspaceMember.metadata:type_name -> openshell.datamodel.v1.ObjectMeta - 5, // 144: openshell.v1.WorkspaceMember.role:type_name -> openshell.v1.WorkspaceRole - 5, // 145: openshell.v1.AddWorkspaceMemberRequest.role:type_name -> openshell.v1.WorkspaceRole - 183, // 146: openshell.v1.AddWorkspaceMemberResponse.member:type_name -> openshell.v1.WorkspaceMember - 183, // 147: openshell.v1.ListWorkspaceMembersResponse.members:type_name -> openshell.v1.WorkspaceMember - 80, // 148: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry.value:type_name -> openshell.v1.ProviderProfileCredential - 110, // 149: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry.value:type_name -> openshell.v1.StaticCredentialBinding - 10, // 150: openshell.v1.OpenShell.Health:input_type -> openshell.v1.HealthRequest - 12, // 151: openshell.v1.OpenShell.GetCurrentUser:input_type -> openshell.v1.GetCurrentUserRequest - 14, // 152: openshell.v1.OpenShell.GetGatewayInfo:input_type -> openshell.v1.GetGatewayInfoRequest - 26, // 153: openshell.v1.OpenShell.CreateSandbox:input_type -> openshell.v1.CreateSandboxRequest - 27, // 154: openshell.v1.OpenShell.GetSandbox:input_type -> openshell.v1.GetSandboxRequest - 28, // 155: openshell.v1.OpenShell.ListSandboxes:input_type -> openshell.v1.ListSandboxesRequest - 29, // 156: openshell.v1.OpenShell.ListSandboxProviders:input_type -> openshell.v1.ListSandboxProvidersRequest - 30, // 157: openshell.v1.OpenShell.AttachSandboxProvider:input_type -> openshell.v1.AttachSandboxProviderRequest - 31, // 158: openshell.v1.OpenShell.DetachSandboxProvider:input_type -> openshell.v1.DetachSandboxProviderRequest - 32, // 159: openshell.v1.OpenShell.DeleteSandbox:input_type -> openshell.v1.DeleteSandboxRequest - 33, // 160: openshell.v1.OpenShell.StopSandbox:input_type -> openshell.v1.StopSandboxRequest - 34, // 161: openshell.v1.OpenShell.StartSandbox:input_type -> openshell.v1.StartSandboxRequest - 41, // 162: openshell.v1.OpenShell.CreateSshSession:input_type -> openshell.v1.CreateSshSessionRequest - 43, // 163: openshell.v1.OpenShell.ExposeService:input_type -> openshell.v1.ExposeServiceRequest - 44, // 164: openshell.v1.OpenShell.GetService:input_type -> openshell.v1.GetServiceRequest - 45, // 165: openshell.v1.OpenShell.ListServices:input_type -> openshell.v1.ListServicesRequest - 47, // 166: openshell.v1.OpenShell.DeleteService:input_type -> openshell.v1.DeleteServiceRequest - 51, // 167: openshell.v1.OpenShell.RevokeSshSession:input_type -> openshell.v1.RevokeSshSessionRequest - 53, // 168: openshell.v1.OpenShell.ExecSandbox:input_type -> openshell.v1.ExecSandboxRequest - 59, // 169: openshell.v1.OpenShell.ForwardTcp:input_type -> openshell.v1.TcpForwardFrame - 60, // 170: openshell.v1.OpenShell.ExecSandboxInteractive:input_type -> openshell.v1.ExecSandboxInput - 67, // 171: openshell.v1.OpenShell.CreateProvider:input_type -> openshell.v1.CreateProviderRequest - 68, // 172: openshell.v1.OpenShell.GetProvider:input_type -> openshell.v1.GetProviderRequest - 69, // 173: openshell.v1.OpenShell.ListProviders:input_type -> openshell.v1.ListProvidersRequest - 74, // 174: openshell.v1.OpenShell.ListProviderProfiles:input_type -> openshell.v1.ListProviderProfilesRequest - 75, // 175: openshell.v1.OpenShell.GetProviderProfile:input_type -> openshell.v1.GetProviderProfileRequest - 99, // 176: openshell.v1.OpenShell.ImportProviderProfiles:input_type -> openshell.v1.ImportProviderProfilesRequest - 101, // 177: openshell.v1.OpenShell.UpdateProviderProfiles:input_type -> openshell.v1.UpdateProviderProfilesRequest - 103, // 178: openshell.v1.OpenShell.LintProviderProfiles:input_type -> openshell.v1.LintProviderProfilesRequest - 70, // 179: openshell.v1.OpenShell.UpdateProvider:input_type -> openshell.v1.UpdateProviderRequest - 87, // 180: openshell.v1.OpenShell.GetProviderRefreshStatus:input_type -> openshell.v1.GetProviderRefreshStatusRequest - 89, // 181: openshell.v1.OpenShell.ConfigureProviderRefresh:input_type -> openshell.v1.ConfigureProviderRefreshRequest - 91, // 182: openshell.v1.OpenShell.RotateProviderCredential:input_type -> openshell.v1.RotateProviderCredentialRequest - 93, // 183: openshell.v1.OpenShell.DeleteProviderRefresh:input_type -> openshell.v1.DeleteProviderRefreshRequest - 71, // 184: openshell.v1.OpenShell.DeleteProvider:input_type -> openshell.v1.DeleteProviderRequest - 106, // 185: openshell.v1.OpenShell.DeleteProviderProfile:input_type -> openshell.v1.DeleteProviderProfileRequest - 225, // 186: openshell.v1.OpenShell.GetSandboxConfig:input_type -> openshell.sandbox.v1.GetSandboxConfigRequest - 226, // 187: openshell.v1.OpenShell.GetGatewayConfig:input_type -> openshell.sandbox.v1.GetGatewayConfigRequest - 112, // 188: openshell.v1.OpenShell.UpdateConfig:input_type -> openshell.v1.UpdateConfigRequest - 121, // 189: openshell.v1.OpenShell.GetSandboxPolicyStatus:input_type -> openshell.v1.GetSandboxPolicyStatusRequest - 123, // 190: openshell.v1.OpenShell.ListSandboxPolicies:input_type -> openshell.v1.ListSandboxPoliciesRequest - 125, // 191: openshell.v1.OpenShell.ReportPolicyStatus:input_type -> openshell.v1.ReportPolicyStatusRequest - 108, // 192: openshell.v1.OpenShell.GetSandboxProviderEnvironment:input_type -> openshell.v1.GetSandboxProviderEnvironmentRequest - 128, // 193: openshell.v1.OpenShell.GetSandboxLogs:input_type -> openshell.v1.GetSandboxLogsRequest - 129, // 194: openshell.v1.OpenShell.PushSandboxLogs:input_type -> openshell.v1.PushSandboxLogsRequest - 132, // 195: openshell.v1.OpenShell.ConnectSupervisor:input_type -> openshell.v1.SupervisorMessage - 143, // 196: openshell.v1.OpenShell.RelayStream:input_type -> openshell.v1.RelayFrame - 63, // 197: openshell.v1.OpenShell.WatchSandbox:input_type -> openshell.v1.WatchSandboxRequest - 152, // 198: openshell.v1.OpenShell.SubmitPolicyAnalysis:input_type -> openshell.v1.SubmitPolicyAnalysisRequest - 154, // 199: openshell.v1.OpenShell.GetDraftPolicy:input_type -> openshell.v1.GetDraftPolicyRequest - 156, // 200: openshell.v1.OpenShell.ApproveDraftChunk:input_type -> openshell.v1.ApproveDraftChunkRequest - 158, // 201: openshell.v1.OpenShell.RejectDraftChunk:input_type -> openshell.v1.RejectDraftChunkRequest - 160, // 202: openshell.v1.OpenShell.ApproveAllDraftChunks:input_type -> openshell.v1.ApproveAllDraftChunksRequest - 162, // 203: openshell.v1.OpenShell.EditDraftChunk:input_type -> openshell.v1.EditDraftChunkRequest - 164, // 204: openshell.v1.OpenShell.UndoDraftChunk:input_type -> openshell.v1.UndoDraftChunkRequest - 166, // 205: openshell.v1.OpenShell.ClearDraftChunks:input_type -> openshell.v1.ClearDraftChunksRequest - 168, // 206: openshell.v1.OpenShell.GetDraftHistory:input_type -> openshell.v1.GetDraftHistoryRequest - 6, // 207: openshell.v1.OpenShell.IssueSandboxToken:input_type -> openshell.v1.IssueSandboxTokenRequest - 8, // 208: openshell.v1.OpenShell.RefreshSandboxToken:input_type -> openshell.v1.RefreshSandboxTokenRequest - 175, // 209: openshell.v1.OpenShell.CreateWorkspace:input_type -> openshell.v1.CreateWorkspaceRequest - 177, // 210: openshell.v1.OpenShell.GetWorkspace:input_type -> openshell.v1.GetWorkspaceRequest - 179, // 211: openshell.v1.OpenShell.ListWorkspaces:input_type -> openshell.v1.ListWorkspacesRequest - 181, // 212: openshell.v1.OpenShell.DeleteWorkspace:input_type -> openshell.v1.DeleteWorkspaceRequest - 184, // 213: openshell.v1.OpenShell.AddWorkspaceMember:input_type -> openshell.v1.AddWorkspaceMemberRequest - 186, // 214: openshell.v1.OpenShell.RemoveWorkspaceMember:input_type -> openshell.v1.RemoveWorkspaceMemberRequest - 188, // 215: openshell.v1.OpenShell.ListWorkspaceMembers:input_type -> openshell.v1.ListWorkspaceMembersRequest - 11, // 216: openshell.v1.OpenShell.Health:output_type -> openshell.v1.HealthResponse - 13, // 217: openshell.v1.OpenShell.GetCurrentUser:output_type -> openshell.v1.GetCurrentUserResponse - 15, // 218: openshell.v1.OpenShell.GetGatewayInfo:output_type -> openshell.v1.GetGatewayInfoResponse - 35, // 219: openshell.v1.OpenShell.CreateSandbox:output_type -> openshell.v1.SandboxResponse - 35, // 220: openshell.v1.OpenShell.GetSandbox:output_type -> openshell.v1.SandboxResponse - 36, // 221: openshell.v1.OpenShell.ListSandboxes:output_type -> openshell.v1.ListSandboxesResponse - 37, // 222: openshell.v1.OpenShell.ListSandboxProviders:output_type -> openshell.v1.ListSandboxProvidersResponse - 38, // 223: openshell.v1.OpenShell.AttachSandboxProvider:output_type -> openshell.v1.AttachSandboxProviderResponse - 39, // 224: openshell.v1.OpenShell.DetachSandboxProvider:output_type -> openshell.v1.DetachSandboxProviderResponse - 40, // 225: openshell.v1.OpenShell.DeleteSandbox:output_type -> openshell.v1.DeleteSandboxResponse - 35, // 226: openshell.v1.OpenShell.StopSandbox:output_type -> openshell.v1.SandboxResponse - 35, // 227: openshell.v1.OpenShell.StartSandbox:output_type -> openshell.v1.SandboxResponse - 42, // 228: openshell.v1.OpenShell.CreateSshSession:output_type -> openshell.v1.CreateSshSessionResponse - 50, // 229: openshell.v1.OpenShell.ExposeService:output_type -> openshell.v1.ServiceEndpointResponse - 50, // 230: openshell.v1.OpenShell.GetService:output_type -> openshell.v1.ServiceEndpointResponse - 46, // 231: openshell.v1.OpenShell.ListServices:output_type -> openshell.v1.ListServicesResponse - 48, // 232: openshell.v1.OpenShell.DeleteService:output_type -> openshell.v1.DeleteServiceResponse - 52, // 233: openshell.v1.OpenShell.RevokeSshSession:output_type -> openshell.v1.RevokeSshSessionResponse - 57, // 234: openshell.v1.OpenShell.ExecSandbox:output_type -> openshell.v1.ExecSandboxEvent - 59, // 235: openshell.v1.OpenShell.ForwardTcp:output_type -> openshell.v1.TcpForwardFrame - 57, // 236: openshell.v1.OpenShell.ExecSandboxInteractive:output_type -> openshell.v1.ExecSandboxEvent - 72, // 237: openshell.v1.OpenShell.CreateProvider:output_type -> openshell.v1.ProviderResponse - 72, // 238: openshell.v1.OpenShell.GetProvider:output_type -> openshell.v1.ProviderResponse - 73, // 239: openshell.v1.OpenShell.ListProviders:output_type -> openshell.v1.ListProvidersResponse - 98, // 240: openshell.v1.OpenShell.ListProviderProfiles:output_type -> openshell.v1.ListProviderProfilesResponse - 97, // 241: openshell.v1.OpenShell.GetProviderProfile:output_type -> openshell.v1.ProviderProfileResponse - 100, // 242: openshell.v1.OpenShell.ImportProviderProfiles:output_type -> openshell.v1.ImportProviderProfilesResponse - 102, // 243: openshell.v1.OpenShell.UpdateProviderProfiles:output_type -> openshell.v1.UpdateProviderProfilesResponse - 104, // 244: openshell.v1.OpenShell.LintProviderProfiles:output_type -> openshell.v1.LintProviderProfilesResponse - 72, // 245: openshell.v1.OpenShell.UpdateProvider:output_type -> openshell.v1.ProviderResponse - 88, // 246: openshell.v1.OpenShell.GetProviderRefreshStatus:output_type -> openshell.v1.GetProviderRefreshStatusResponse - 90, // 247: openshell.v1.OpenShell.ConfigureProviderRefresh:output_type -> openshell.v1.ConfigureProviderRefreshResponse - 92, // 248: openshell.v1.OpenShell.RotateProviderCredential:output_type -> openshell.v1.RotateProviderCredentialResponse - 94, // 249: openshell.v1.OpenShell.DeleteProviderRefresh:output_type -> openshell.v1.DeleteProviderRefreshResponse - 105, // 250: openshell.v1.OpenShell.DeleteProvider:output_type -> openshell.v1.DeleteProviderResponse - 107, // 251: openshell.v1.OpenShell.DeleteProviderProfile:output_type -> openshell.v1.DeleteProviderProfileResponse - 227, // 252: openshell.v1.OpenShell.GetSandboxConfig:output_type -> openshell.sandbox.v1.GetSandboxConfigResponse - 228, // 253: openshell.v1.OpenShell.GetGatewayConfig:output_type -> openshell.sandbox.v1.GetGatewayConfigResponse - 120, // 254: openshell.v1.OpenShell.UpdateConfig:output_type -> openshell.v1.UpdateConfigResponse - 122, // 255: openshell.v1.OpenShell.GetSandboxPolicyStatus:output_type -> openshell.v1.GetSandboxPolicyStatusResponse - 124, // 256: openshell.v1.OpenShell.ListSandboxPolicies:output_type -> openshell.v1.ListSandboxPoliciesResponse - 126, // 257: openshell.v1.OpenShell.ReportPolicyStatus:output_type -> openshell.v1.ReportPolicyStatusResponse - 111, // 258: openshell.v1.OpenShell.GetSandboxProviderEnvironment:output_type -> openshell.v1.GetSandboxProviderEnvironmentResponse - 131, // 259: openshell.v1.OpenShell.GetSandboxLogs:output_type -> openshell.v1.GetSandboxLogsResponse - 130, // 260: openshell.v1.OpenShell.PushSandboxLogs:output_type -> openshell.v1.PushSandboxLogsResponse - 133, // 261: openshell.v1.OpenShell.ConnectSupervisor:output_type -> openshell.v1.GatewayMessage - 143, // 262: openshell.v1.OpenShell.RelayStream:output_type -> openshell.v1.RelayFrame - 64, // 263: openshell.v1.OpenShell.WatchSandbox:output_type -> openshell.v1.SandboxStreamEvent - 153, // 264: openshell.v1.OpenShell.SubmitPolicyAnalysis:output_type -> openshell.v1.SubmitPolicyAnalysisResponse - 155, // 265: openshell.v1.OpenShell.GetDraftPolicy:output_type -> openshell.v1.GetDraftPolicyResponse - 157, // 266: openshell.v1.OpenShell.ApproveDraftChunk:output_type -> openshell.v1.ApproveDraftChunkResponse - 159, // 267: openshell.v1.OpenShell.RejectDraftChunk:output_type -> openshell.v1.RejectDraftChunkResponse - 161, // 268: openshell.v1.OpenShell.ApproveAllDraftChunks:output_type -> openshell.v1.ApproveAllDraftChunksResponse - 163, // 269: openshell.v1.OpenShell.EditDraftChunk:output_type -> openshell.v1.EditDraftChunkResponse - 165, // 270: openshell.v1.OpenShell.UndoDraftChunk:output_type -> openshell.v1.UndoDraftChunkResponse - 167, // 271: openshell.v1.OpenShell.ClearDraftChunks:output_type -> openshell.v1.ClearDraftChunksResponse - 170, // 272: openshell.v1.OpenShell.GetDraftHistory:output_type -> openshell.v1.GetDraftHistoryResponse - 7, // 273: openshell.v1.OpenShell.IssueSandboxToken:output_type -> openshell.v1.IssueSandboxTokenResponse - 9, // 274: openshell.v1.OpenShell.RefreshSandboxToken:output_type -> openshell.v1.RefreshSandboxTokenResponse - 176, // 275: openshell.v1.OpenShell.CreateWorkspace:output_type -> openshell.v1.CreateWorkspaceResponse - 178, // 276: openshell.v1.OpenShell.GetWorkspace:output_type -> openshell.v1.GetWorkspaceResponse - 180, // 277: openshell.v1.OpenShell.ListWorkspaces:output_type -> openshell.v1.ListWorkspacesResponse - 182, // 278: openshell.v1.OpenShell.DeleteWorkspace:output_type -> openshell.v1.DeleteWorkspaceResponse - 185, // 279: openshell.v1.OpenShell.AddWorkspaceMember:output_type -> openshell.v1.AddWorkspaceMemberResponse - 187, // 280: openshell.v1.OpenShell.RemoveWorkspaceMember:output_type -> openshell.v1.RemoveWorkspaceMemberResponse - 189, // 281: openshell.v1.OpenShell.ListWorkspaceMembers:output_type -> openshell.v1.ListWorkspaceMembersResponse - 216, // [216:282] is the sub-list for method output_type - 150, // [150:216] is the sub-list for method input_type - 150, // [150:150] is the sub-list for extension type_name - 150, // [150:150] is the sub-list for extension extendee - 0, // [0:150] is the sub-list for field type_name + 190, // 0: openshell.v1.RefreshSandboxTokenResponse.extension_credentials:type_name -> openshell.v1.ExtensionServiceCredential + 4, // 1: openshell.v1.HealthResponse.status:type_name -> openshell.v1.ServiceStatus + 4, // 2: openshell.v1.GetGatewayInfoResponse.status:type_name -> openshell.v1.ServiceStatus + 16, // 3: openshell.v1.GetGatewayInfoResponse.compute_drivers:type_name -> openshell.v1.ComputeDriverInfo + 17, // 4: openshell.v1.ComputeDriverInfo.capabilities:type_name -> openshell.v1.ComputeDriverCapabilities + 215, // 5: openshell.v1.Sandbox.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 19, // 6: openshell.v1.Sandbox.spec:type_name -> openshell.v1.SandboxSpec + 23, // 7: openshell.v1.Sandbox.status:type_name -> openshell.v1.SandboxStatus + 191, // 8: openshell.v1.SandboxSpec.environment:type_name -> openshell.v1.SandboxSpec.EnvironmentEntry + 22, // 9: openshell.v1.SandboxSpec.template:type_name -> openshell.v1.SandboxTemplate + 216, // 10: openshell.v1.SandboxSpec.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 20, // 11: openshell.v1.SandboxSpec.resource_requirements:type_name -> openshell.v1.ResourceRequirements + 21, // 12: openshell.v1.ResourceRequirements.gpu:type_name -> openshell.v1.GpuResourceRequirements + 192, // 13: openshell.v1.SandboxTemplate.labels:type_name -> openshell.v1.SandboxTemplate.LabelsEntry + 193, // 14: openshell.v1.SandboxTemplate.annotations:type_name -> openshell.v1.SandboxTemplate.AnnotationsEntry + 194, // 15: openshell.v1.SandboxTemplate.environment:type_name -> openshell.v1.SandboxTemplate.EnvironmentEntry + 217, // 16: openshell.v1.SandboxTemplate.resources:type_name -> google.protobuf.Struct + 217, // 17: openshell.v1.SandboxTemplate.driver_config:type_name -> google.protobuf.Struct + 24, // 18: openshell.v1.SandboxStatus.conditions:type_name -> openshell.v1.SandboxCondition + 0, // 19: openshell.v1.SandboxStatus.phase:type_name -> openshell.v1.SandboxPhase + 195, // 20: openshell.v1.PlatformEvent.metadata:type_name -> openshell.v1.PlatformEvent.MetadataEntry + 19, // 21: openshell.v1.CreateSandboxRequest.spec:type_name -> openshell.v1.SandboxSpec + 196, // 22: openshell.v1.CreateSandboxRequest.labels:type_name -> openshell.v1.CreateSandboxRequest.LabelsEntry + 197, // 23: openshell.v1.CreateSandboxRequest.annotations:type_name -> openshell.v1.CreateSandboxRequest.AnnotationsEntry + 18, // 24: openshell.v1.SandboxResponse.sandbox:type_name -> openshell.v1.Sandbox + 18, // 25: openshell.v1.ListSandboxesResponse.sandboxes:type_name -> openshell.v1.Sandbox + 218, // 26: openshell.v1.ListSandboxProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider + 18, // 27: openshell.v1.AttachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox + 18, // 28: openshell.v1.DetachSandboxProviderResponse.sandbox:type_name -> openshell.v1.Sandbox + 50, // 29: openshell.v1.ListServicesResponse.services:type_name -> openshell.v1.ServiceEndpointResponse + 215, // 30: openshell.v1.ServiceEndpoint.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 49, // 31: openshell.v1.ServiceEndpointResponse.endpoint:type_name -> openshell.v1.ServiceEndpoint + 198, // 32: openshell.v1.ExecSandboxRequest.environment:type_name -> openshell.v1.ExecSandboxRequest.EnvironmentEntry + 54, // 33: openshell.v1.ExecSandboxEvent.stdout:type_name -> openshell.v1.ExecSandboxStdout + 55, // 34: openshell.v1.ExecSandboxEvent.stderr:type_name -> openshell.v1.ExecSandboxStderr + 56, // 35: openshell.v1.ExecSandboxEvent.exit:type_name -> openshell.v1.ExecSandboxExit + 140, // 36: openshell.v1.TcpForwardInit.ssh:type_name -> openshell.v1.SshRelayTarget + 141, // 37: openshell.v1.TcpForwardInit.tcp:type_name -> openshell.v1.TcpRelayTarget + 58, // 38: openshell.v1.TcpForwardFrame.init:type_name -> openshell.v1.TcpForwardInit + 53, // 39: openshell.v1.ExecSandboxInput.start:type_name -> openshell.v1.ExecSandboxRequest + 61, // 40: openshell.v1.ExecSandboxInput.resize:type_name -> openshell.v1.ExecSandboxWindowResize + 215, // 41: openshell.v1.SshSession.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 18, // 42: openshell.v1.SandboxStreamEvent.sandbox:type_name -> openshell.v1.Sandbox + 65, // 43: openshell.v1.SandboxStreamEvent.log:type_name -> openshell.v1.SandboxLogLine + 25, // 44: openshell.v1.SandboxStreamEvent.event:type_name -> openshell.v1.PlatformEvent + 66, // 45: openshell.v1.SandboxStreamEvent.warning:type_name -> openshell.v1.SandboxStreamWarning + 151, // 46: openshell.v1.SandboxStreamEvent.draft_policy_update:type_name -> openshell.v1.DraftPolicyUpdate + 199, // 47: openshell.v1.SandboxLogLine.fields:type_name -> openshell.v1.SandboxLogLine.FieldsEntry + 218, // 48: openshell.v1.CreateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider + 218, // 49: openshell.v1.UpdateProviderRequest.provider:type_name -> openshell.datamodel.v1.Provider + 200, // 50: openshell.v1.UpdateProviderRequest.credential_expires_at_ms:type_name -> openshell.v1.UpdateProviderRequest.CredentialExpiresAtMsEntry + 218, // 51: openshell.v1.ProviderResponse.provider:type_name -> openshell.datamodel.v1.Provider + 218, // 52: openshell.v1.ListProvidersResponse.providers:type_name -> openshell.datamodel.v1.Provider + 95, // 53: openshell.v1.ProviderProfileImportItem.profile:type_name -> openshell.v1.ProviderProfile + 78, // 54: openshell.v1.ProviderCredentialTokenGrant.audience_overrides:type_name -> openshell.v1.ProviderCredentialTokenGrantAudienceOverride + 83, // 55: openshell.v1.ProviderProfileCredential.refresh:type_name -> openshell.v1.ProviderCredentialRefresh + 79, // 56: openshell.v1.ProviderProfileCredential.token_grant:type_name -> openshell.v1.ProviderCredentialTokenGrant + 1, // 57: openshell.v1.ProviderCredentialRefresh.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 81, // 58: openshell.v1.ProviderCredentialRefresh.material:type_name -> openshell.v1.ProviderCredentialRefreshMaterial + 82, // 59: openshell.v1.ProviderCredentialRefresh.additional_outputs:type_name -> openshell.v1.ProviderCredentialRefreshOutput + 1, // 60: openshell.v1.ProviderCredentialRefreshStatus.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 215, // 61: openshell.v1.StoredProviderCredentialRefreshState.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 1, // 62: openshell.v1.StoredProviderCredentialRefreshState.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 201, // 63: openshell.v1.StoredProviderCredentialRefreshState.material:type_name -> openshell.v1.StoredProviderCredentialRefreshState.MaterialEntry + 202, // 64: openshell.v1.StoredProviderCredentialRefreshState.additional_output_keys:type_name -> openshell.v1.StoredProviderCredentialRefreshState.AdditionalOutputKeysEntry + 84, // 65: openshell.v1.GetProviderRefreshStatusResponse.credentials:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 1, // 66: openshell.v1.ConfigureProviderRefreshRequest.strategy:type_name -> openshell.v1.ProviderCredentialRefreshStrategy + 203, // 67: openshell.v1.ConfigureProviderRefreshRequest.material:type_name -> openshell.v1.ConfigureProviderRefreshRequest.MaterialEntry + 84, // 68: openshell.v1.ConfigureProviderRefreshResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 84, // 69: openshell.v1.RotateProviderCredentialResponse.status:type_name -> openshell.v1.ProviderCredentialRefreshStatus + 2, // 70: openshell.v1.ProviderProfile.category:type_name -> openshell.v1.ProviderProfileCategory + 80, // 71: openshell.v1.ProviderProfile.credentials:type_name -> openshell.v1.ProviderProfileCredential + 219, // 72: openshell.v1.ProviderProfile.endpoints:type_name -> openshell.sandbox.v1.NetworkEndpoint + 220, // 73: openshell.v1.ProviderProfile.binaries:type_name -> openshell.sandbox.v1.NetworkBinary + 85, // 74: openshell.v1.ProviderProfile.discovery:type_name -> openshell.v1.ProviderProfileDiscovery + 204, // 75: openshell.v1.ProviderProfile.annotations:type_name -> openshell.v1.ProviderProfile.AnnotationsEntry + 215, // 76: openshell.v1.StoredProviderProfile.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 95, // 77: openshell.v1.StoredProviderProfile.profile:type_name -> openshell.v1.ProviderProfile + 95, // 78: openshell.v1.ProviderProfileResponse.profile:type_name -> openshell.v1.ProviderProfile + 95, // 79: openshell.v1.ListProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile + 76, // 80: openshell.v1.ImportProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem + 77, // 81: openshell.v1.ImportProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 95, // 82: openshell.v1.ImportProviderProfilesResponse.profiles:type_name -> openshell.v1.ProviderProfile + 76, // 83: openshell.v1.UpdateProviderProfilesRequest.profile:type_name -> openshell.v1.ProviderProfileImportItem + 77, // 84: openshell.v1.UpdateProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 95, // 85: openshell.v1.UpdateProviderProfilesResponse.profile:type_name -> openshell.v1.ProviderProfile + 76, // 86: openshell.v1.LintProviderProfilesRequest.profiles:type_name -> openshell.v1.ProviderProfileImportItem + 77, // 87: openshell.v1.LintProviderProfilesResponse.diagnostics:type_name -> openshell.v1.ProviderProfileDiagnostic + 109, // 88: openshell.v1.StaticCredentialBinding.endpoints:type_name -> openshell.v1.StaticCredentialEndpointBinding + 205, // 89: openshell.v1.GetSandboxProviderEnvironmentResponse.environment:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.EnvironmentEntry + 206, // 90: openshell.v1.GetSandboxProviderEnvironmentResponse.credential_expires_at_ms:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.CredentialExpiresAtMsEntry + 207, // 91: openshell.v1.GetSandboxProviderEnvironmentResponse.dynamic_credentials:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry + 208, // 92: openshell.v1.GetSandboxProviderEnvironmentResponse.static_credential_bindings:type_name -> openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry + 216, // 93: openshell.v1.UpdateConfigRequest.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 221, // 94: openshell.v1.UpdateConfigRequest.setting_value:type_name -> openshell.sandbox.v1.SettingValue + 113, // 95: openshell.v1.UpdateConfigRequest.merge_operations:type_name -> openshell.v1.PolicyMergeOperation + 209, // 96: openshell.v1.UpdateConfigRequest.annotations:type_name -> openshell.v1.UpdateConfigRequest.AnnotationsEntry + 114, // 97: openshell.v1.PolicyMergeOperation.add_rule:type_name -> openshell.v1.AddNetworkRule + 115, // 98: openshell.v1.PolicyMergeOperation.remove_endpoint:type_name -> openshell.v1.RemoveNetworkEndpoint + 116, // 99: openshell.v1.PolicyMergeOperation.remove_rule:type_name -> openshell.v1.RemoveNetworkRule + 117, // 100: openshell.v1.PolicyMergeOperation.add_deny_rules:type_name -> openshell.v1.AddDenyRules + 118, // 101: openshell.v1.PolicyMergeOperation.add_allow_rules:type_name -> openshell.v1.AddAllowRules + 119, // 102: openshell.v1.PolicyMergeOperation.remove_binary:type_name -> openshell.v1.RemoveNetworkBinary + 222, // 103: openshell.v1.AddNetworkRule.rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 223, // 104: openshell.v1.AddDenyRules.deny_rules:type_name -> openshell.sandbox.v1.L7DenyRule + 224, // 105: openshell.v1.AddAllowRules.rules:type_name -> openshell.sandbox.v1.L7Rule + 210, // 106: openshell.v1.UpdateConfigResponse.annotations:type_name -> openshell.v1.UpdateConfigResponse.AnnotationsEntry + 127, // 107: openshell.v1.GetSandboxPolicyStatusResponse.revision:type_name -> openshell.v1.SandboxPolicyRevision + 127, // 108: openshell.v1.ListSandboxPoliciesResponse.revisions:type_name -> openshell.v1.SandboxPolicyRevision + 3, // 109: openshell.v1.ReportPolicyStatusRequest.status:type_name -> openshell.v1.PolicyStatus + 3, // 110: openshell.v1.SandboxPolicyRevision.status:type_name -> openshell.v1.PolicyStatus + 216, // 111: openshell.v1.SandboxPolicyRevision.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 211, // 112: openshell.v1.SandboxPolicyRevision.provenance:type_name -> openshell.v1.SandboxPolicyRevision.ProvenanceEntry + 65, // 113: openshell.v1.PushSandboxLogsRequest.logs:type_name -> openshell.v1.SandboxLogLine + 65, // 114: openshell.v1.GetSandboxLogsResponse.logs:type_name -> openshell.v1.SandboxLogLine + 134, // 115: openshell.v1.SupervisorMessage.hello:type_name -> openshell.v1.SupervisorHello + 137, // 116: openshell.v1.SupervisorMessage.heartbeat:type_name -> openshell.v1.SupervisorHeartbeat + 144, // 117: openshell.v1.SupervisorMessage.relay_open_result:type_name -> openshell.v1.RelayOpenResult + 145, // 118: openshell.v1.SupervisorMessage.relay_close:type_name -> openshell.v1.RelayClose + 135, // 119: openshell.v1.GatewayMessage.session_accepted:type_name -> openshell.v1.SessionAccepted + 136, // 120: openshell.v1.GatewayMessage.session_rejected:type_name -> openshell.v1.SessionRejected + 138, // 121: openshell.v1.GatewayMessage.heartbeat:type_name -> openshell.v1.GatewayHeartbeat + 139, // 122: openshell.v1.GatewayMessage.relay_open:type_name -> openshell.v1.RelayOpen + 145, // 123: openshell.v1.GatewayMessage.relay_close:type_name -> openshell.v1.RelayClose + 140, // 124: openshell.v1.RelayOpen.ssh:type_name -> openshell.v1.SshRelayTarget + 141, // 125: openshell.v1.RelayOpen.tcp:type_name -> openshell.v1.TcpRelayTarget + 142, // 126: openshell.v1.RelayFrame.init:type_name -> openshell.v1.RelayInit + 146, // 127: openshell.v1.DenialSummary.l7_request_samples:type_name -> openshell.v1.L7RequestSample + 148, // 128: openshell.v1.NetworkActivitySummary.denials_by_group:type_name -> openshell.v1.DenialGroupCount + 222, // 129: openshell.v1.PolicyChunk.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 147, // 130: openshell.v1.SubmitPolicyAnalysisRequest.summaries:type_name -> openshell.v1.DenialSummary + 150, // 131: openshell.v1.SubmitPolicyAnalysisRequest.proposed_chunks:type_name -> openshell.v1.PolicyChunk + 149, // 132: openshell.v1.SubmitPolicyAnalysisRequest.network_activity_summaries:type_name -> openshell.v1.NetworkActivitySummary + 150, // 133: openshell.v1.GetDraftPolicyResponse.chunks:type_name -> openshell.v1.PolicyChunk + 222, // 134: openshell.v1.EditDraftChunkRequest.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 169, // 135: openshell.v1.GetDraftHistoryResponse.entries:type_name -> openshell.v1.DraftHistoryEntry + 216, // 136: openshell.v1.PolicyRevisionPayload.policy:type_name -> openshell.sandbox.v1.SandboxPolicy + 212, // 137: openshell.v1.PolicyRevisionPayload.provenance:type_name -> openshell.v1.PolicyRevisionPayload.ProvenanceEntry + 222, // 138: openshell.v1.DraftChunkPayload.proposed_rule:type_name -> openshell.sandbox.v1.NetworkPolicyRule + 213, // 139: openshell.v1.StoredPolicyRevision.provenance:type_name -> openshell.v1.StoredPolicyRevision.ProvenanceEntry + 214, // 140: openshell.v1.CreateWorkspaceRequest.labels:type_name -> openshell.v1.CreateWorkspaceRequest.LabelsEntry + 225, // 141: openshell.v1.CreateWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace + 225, // 142: openshell.v1.GetWorkspaceResponse.workspace:type_name -> openshell.datamodel.v1.Workspace + 225, // 143: openshell.v1.ListWorkspacesResponse.workspaces:type_name -> openshell.datamodel.v1.Workspace + 215, // 144: openshell.v1.WorkspaceMember.metadata:type_name -> openshell.datamodel.v1.ObjectMeta + 5, // 145: openshell.v1.WorkspaceMember.role:type_name -> openshell.v1.WorkspaceRole + 5, // 146: openshell.v1.AddWorkspaceMemberRequest.role:type_name -> openshell.v1.WorkspaceRole + 183, // 147: openshell.v1.AddWorkspaceMemberResponse.member:type_name -> openshell.v1.WorkspaceMember + 183, // 148: openshell.v1.ListWorkspaceMembersResponse.members:type_name -> openshell.v1.WorkspaceMember + 80, // 149: openshell.v1.GetSandboxProviderEnvironmentResponse.DynamicCredentialsEntry.value:type_name -> openshell.v1.ProviderProfileCredential + 110, // 150: openshell.v1.GetSandboxProviderEnvironmentResponse.StaticCredentialBindingsEntry.value:type_name -> openshell.v1.StaticCredentialBinding + 10, // 151: openshell.v1.OpenShell.Health:input_type -> openshell.v1.HealthRequest + 12, // 152: openshell.v1.OpenShell.GetCurrentUser:input_type -> openshell.v1.GetCurrentUserRequest + 14, // 153: openshell.v1.OpenShell.GetGatewayInfo:input_type -> openshell.v1.GetGatewayInfoRequest + 26, // 154: openshell.v1.OpenShell.CreateSandbox:input_type -> openshell.v1.CreateSandboxRequest + 27, // 155: openshell.v1.OpenShell.GetSandbox:input_type -> openshell.v1.GetSandboxRequest + 28, // 156: openshell.v1.OpenShell.ListSandboxes:input_type -> openshell.v1.ListSandboxesRequest + 29, // 157: openshell.v1.OpenShell.ListSandboxProviders:input_type -> openshell.v1.ListSandboxProvidersRequest + 30, // 158: openshell.v1.OpenShell.AttachSandboxProvider:input_type -> openshell.v1.AttachSandboxProviderRequest + 31, // 159: openshell.v1.OpenShell.DetachSandboxProvider:input_type -> openshell.v1.DetachSandboxProviderRequest + 32, // 160: openshell.v1.OpenShell.DeleteSandbox:input_type -> openshell.v1.DeleteSandboxRequest + 33, // 161: openshell.v1.OpenShell.StopSandbox:input_type -> openshell.v1.StopSandboxRequest + 34, // 162: openshell.v1.OpenShell.StartSandbox:input_type -> openshell.v1.StartSandboxRequest + 41, // 163: openshell.v1.OpenShell.CreateSshSession:input_type -> openshell.v1.CreateSshSessionRequest + 43, // 164: openshell.v1.OpenShell.ExposeService:input_type -> openshell.v1.ExposeServiceRequest + 44, // 165: openshell.v1.OpenShell.GetService:input_type -> openshell.v1.GetServiceRequest + 45, // 166: openshell.v1.OpenShell.ListServices:input_type -> openshell.v1.ListServicesRequest + 47, // 167: openshell.v1.OpenShell.DeleteService:input_type -> openshell.v1.DeleteServiceRequest + 51, // 168: openshell.v1.OpenShell.RevokeSshSession:input_type -> openshell.v1.RevokeSshSessionRequest + 53, // 169: openshell.v1.OpenShell.ExecSandbox:input_type -> openshell.v1.ExecSandboxRequest + 59, // 170: openshell.v1.OpenShell.ForwardTcp:input_type -> openshell.v1.TcpForwardFrame + 60, // 171: openshell.v1.OpenShell.ExecSandboxInteractive:input_type -> openshell.v1.ExecSandboxInput + 67, // 172: openshell.v1.OpenShell.CreateProvider:input_type -> openshell.v1.CreateProviderRequest + 68, // 173: openshell.v1.OpenShell.GetProvider:input_type -> openshell.v1.GetProviderRequest + 69, // 174: openshell.v1.OpenShell.ListProviders:input_type -> openshell.v1.ListProvidersRequest + 74, // 175: openshell.v1.OpenShell.ListProviderProfiles:input_type -> openshell.v1.ListProviderProfilesRequest + 75, // 176: openshell.v1.OpenShell.GetProviderProfile:input_type -> openshell.v1.GetProviderProfileRequest + 99, // 177: openshell.v1.OpenShell.ImportProviderProfiles:input_type -> openshell.v1.ImportProviderProfilesRequest + 101, // 178: openshell.v1.OpenShell.UpdateProviderProfiles:input_type -> openshell.v1.UpdateProviderProfilesRequest + 103, // 179: openshell.v1.OpenShell.LintProviderProfiles:input_type -> openshell.v1.LintProviderProfilesRequest + 70, // 180: openshell.v1.OpenShell.UpdateProvider:input_type -> openshell.v1.UpdateProviderRequest + 87, // 181: openshell.v1.OpenShell.GetProviderRefreshStatus:input_type -> openshell.v1.GetProviderRefreshStatusRequest + 89, // 182: openshell.v1.OpenShell.ConfigureProviderRefresh:input_type -> openshell.v1.ConfigureProviderRefreshRequest + 91, // 183: openshell.v1.OpenShell.RotateProviderCredential:input_type -> openshell.v1.RotateProviderCredentialRequest + 93, // 184: openshell.v1.OpenShell.DeleteProviderRefresh:input_type -> openshell.v1.DeleteProviderRefreshRequest + 71, // 185: openshell.v1.OpenShell.DeleteProvider:input_type -> openshell.v1.DeleteProviderRequest + 106, // 186: openshell.v1.OpenShell.DeleteProviderProfile:input_type -> openshell.v1.DeleteProviderProfileRequest + 226, // 187: openshell.v1.OpenShell.GetSandboxConfig:input_type -> openshell.sandbox.v1.GetSandboxConfigRequest + 227, // 188: openshell.v1.OpenShell.GetGatewayConfig:input_type -> openshell.sandbox.v1.GetGatewayConfigRequest + 112, // 189: openshell.v1.OpenShell.UpdateConfig:input_type -> openshell.v1.UpdateConfigRequest + 121, // 190: openshell.v1.OpenShell.GetSandboxPolicyStatus:input_type -> openshell.v1.GetSandboxPolicyStatusRequest + 123, // 191: openshell.v1.OpenShell.ListSandboxPolicies:input_type -> openshell.v1.ListSandboxPoliciesRequest + 125, // 192: openshell.v1.OpenShell.ReportPolicyStatus:input_type -> openshell.v1.ReportPolicyStatusRequest + 108, // 193: openshell.v1.OpenShell.GetSandboxProviderEnvironment:input_type -> openshell.v1.GetSandboxProviderEnvironmentRequest + 128, // 194: openshell.v1.OpenShell.GetSandboxLogs:input_type -> openshell.v1.GetSandboxLogsRequest + 129, // 195: openshell.v1.OpenShell.PushSandboxLogs:input_type -> openshell.v1.PushSandboxLogsRequest + 132, // 196: openshell.v1.OpenShell.ConnectSupervisor:input_type -> openshell.v1.SupervisorMessage + 143, // 197: openshell.v1.OpenShell.RelayStream:input_type -> openshell.v1.RelayFrame + 63, // 198: openshell.v1.OpenShell.WatchSandbox:input_type -> openshell.v1.WatchSandboxRequest + 152, // 199: openshell.v1.OpenShell.SubmitPolicyAnalysis:input_type -> openshell.v1.SubmitPolicyAnalysisRequest + 154, // 200: openshell.v1.OpenShell.GetDraftPolicy:input_type -> openshell.v1.GetDraftPolicyRequest + 156, // 201: openshell.v1.OpenShell.ApproveDraftChunk:input_type -> openshell.v1.ApproveDraftChunkRequest + 158, // 202: openshell.v1.OpenShell.RejectDraftChunk:input_type -> openshell.v1.RejectDraftChunkRequest + 160, // 203: openshell.v1.OpenShell.ApproveAllDraftChunks:input_type -> openshell.v1.ApproveAllDraftChunksRequest + 162, // 204: openshell.v1.OpenShell.EditDraftChunk:input_type -> openshell.v1.EditDraftChunkRequest + 164, // 205: openshell.v1.OpenShell.UndoDraftChunk:input_type -> openshell.v1.UndoDraftChunkRequest + 166, // 206: openshell.v1.OpenShell.ClearDraftChunks:input_type -> openshell.v1.ClearDraftChunksRequest + 168, // 207: openshell.v1.OpenShell.GetDraftHistory:input_type -> openshell.v1.GetDraftHistoryRequest + 6, // 208: openshell.v1.OpenShell.IssueSandboxToken:input_type -> openshell.v1.IssueSandboxTokenRequest + 8, // 209: openshell.v1.OpenShell.RefreshSandboxToken:input_type -> openshell.v1.RefreshSandboxTokenRequest + 175, // 210: openshell.v1.OpenShell.CreateWorkspace:input_type -> openshell.v1.CreateWorkspaceRequest + 177, // 211: openshell.v1.OpenShell.GetWorkspace:input_type -> openshell.v1.GetWorkspaceRequest + 179, // 212: openshell.v1.OpenShell.ListWorkspaces:input_type -> openshell.v1.ListWorkspacesRequest + 181, // 213: openshell.v1.OpenShell.DeleteWorkspace:input_type -> openshell.v1.DeleteWorkspaceRequest + 184, // 214: openshell.v1.OpenShell.AddWorkspaceMember:input_type -> openshell.v1.AddWorkspaceMemberRequest + 186, // 215: openshell.v1.OpenShell.RemoveWorkspaceMember:input_type -> openshell.v1.RemoveWorkspaceMemberRequest + 188, // 216: openshell.v1.OpenShell.ListWorkspaceMembers:input_type -> openshell.v1.ListWorkspaceMembersRequest + 11, // 217: openshell.v1.OpenShell.Health:output_type -> openshell.v1.HealthResponse + 13, // 218: openshell.v1.OpenShell.GetCurrentUser:output_type -> openshell.v1.GetCurrentUserResponse + 15, // 219: openshell.v1.OpenShell.GetGatewayInfo:output_type -> openshell.v1.GetGatewayInfoResponse + 35, // 220: openshell.v1.OpenShell.CreateSandbox:output_type -> openshell.v1.SandboxResponse + 35, // 221: openshell.v1.OpenShell.GetSandbox:output_type -> openshell.v1.SandboxResponse + 36, // 222: openshell.v1.OpenShell.ListSandboxes:output_type -> openshell.v1.ListSandboxesResponse + 37, // 223: openshell.v1.OpenShell.ListSandboxProviders:output_type -> openshell.v1.ListSandboxProvidersResponse + 38, // 224: openshell.v1.OpenShell.AttachSandboxProvider:output_type -> openshell.v1.AttachSandboxProviderResponse + 39, // 225: openshell.v1.OpenShell.DetachSandboxProvider:output_type -> openshell.v1.DetachSandboxProviderResponse + 40, // 226: openshell.v1.OpenShell.DeleteSandbox:output_type -> openshell.v1.DeleteSandboxResponse + 35, // 227: openshell.v1.OpenShell.StopSandbox:output_type -> openshell.v1.SandboxResponse + 35, // 228: openshell.v1.OpenShell.StartSandbox:output_type -> openshell.v1.SandboxResponse + 42, // 229: openshell.v1.OpenShell.CreateSshSession:output_type -> openshell.v1.CreateSshSessionResponse + 50, // 230: openshell.v1.OpenShell.ExposeService:output_type -> openshell.v1.ServiceEndpointResponse + 50, // 231: openshell.v1.OpenShell.GetService:output_type -> openshell.v1.ServiceEndpointResponse + 46, // 232: openshell.v1.OpenShell.ListServices:output_type -> openshell.v1.ListServicesResponse + 48, // 233: openshell.v1.OpenShell.DeleteService:output_type -> openshell.v1.DeleteServiceResponse + 52, // 234: openshell.v1.OpenShell.RevokeSshSession:output_type -> openshell.v1.RevokeSshSessionResponse + 57, // 235: openshell.v1.OpenShell.ExecSandbox:output_type -> openshell.v1.ExecSandboxEvent + 59, // 236: openshell.v1.OpenShell.ForwardTcp:output_type -> openshell.v1.TcpForwardFrame + 57, // 237: openshell.v1.OpenShell.ExecSandboxInteractive:output_type -> openshell.v1.ExecSandboxEvent + 72, // 238: openshell.v1.OpenShell.CreateProvider:output_type -> openshell.v1.ProviderResponse + 72, // 239: openshell.v1.OpenShell.GetProvider:output_type -> openshell.v1.ProviderResponse + 73, // 240: openshell.v1.OpenShell.ListProviders:output_type -> openshell.v1.ListProvidersResponse + 98, // 241: openshell.v1.OpenShell.ListProviderProfiles:output_type -> openshell.v1.ListProviderProfilesResponse + 97, // 242: openshell.v1.OpenShell.GetProviderProfile:output_type -> openshell.v1.ProviderProfileResponse + 100, // 243: openshell.v1.OpenShell.ImportProviderProfiles:output_type -> openshell.v1.ImportProviderProfilesResponse + 102, // 244: openshell.v1.OpenShell.UpdateProviderProfiles:output_type -> openshell.v1.UpdateProviderProfilesResponse + 104, // 245: openshell.v1.OpenShell.LintProviderProfiles:output_type -> openshell.v1.LintProviderProfilesResponse + 72, // 246: openshell.v1.OpenShell.UpdateProvider:output_type -> openshell.v1.ProviderResponse + 88, // 247: openshell.v1.OpenShell.GetProviderRefreshStatus:output_type -> openshell.v1.GetProviderRefreshStatusResponse + 90, // 248: openshell.v1.OpenShell.ConfigureProviderRefresh:output_type -> openshell.v1.ConfigureProviderRefreshResponse + 92, // 249: openshell.v1.OpenShell.RotateProviderCredential:output_type -> openshell.v1.RotateProviderCredentialResponse + 94, // 250: openshell.v1.OpenShell.DeleteProviderRefresh:output_type -> openshell.v1.DeleteProviderRefreshResponse + 105, // 251: openshell.v1.OpenShell.DeleteProvider:output_type -> openshell.v1.DeleteProviderResponse + 107, // 252: openshell.v1.OpenShell.DeleteProviderProfile:output_type -> openshell.v1.DeleteProviderProfileResponse + 228, // 253: openshell.v1.OpenShell.GetSandboxConfig:output_type -> openshell.sandbox.v1.GetSandboxConfigResponse + 229, // 254: openshell.v1.OpenShell.GetGatewayConfig:output_type -> openshell.sandbox.v1.GetGatewayConfigResponse + 120, // 255: openshell.v1.OpenShell.UpdateConfig:output_type -> openshell.v1.UpdateConfigResponse + 122, // 256: openshell.v1.OpenShell.GetSandboxPolicyStatus:output_type -> openshell.v1.GetSandboxPolicyStatusResponse + 124, // 257: openshell.v1.OpenShell.ListSandboxPolicies:output_type -> openshell.v1.ListSandboxPoliciesResponse + 126, // 258: openshell.v1.OpenShell.ReportPolicyStatus:output_type -> openshell.v1.ReportPolicyStatusResponse + 111, // 259: openshell.v1.OpenShell.GetSandboxProviderEnvironment:output_type -> openshell.v1.GetSandboxProviderEnvironmentResponse + 131, // 260: openshell.v1.OpenShell.GetSandboxLogs:output_type -> openshell.v1.GetSandboxLogsResponse + 130, // 261: openshell.v1.OpenShell.PushSandboxLogs:output_type -> openshell.v1.PushSandboxLogsResponse + 133, // 262: openshell.v1.OpenShell.ConnectSupervisor:output_type -> openshell.v1.GatewayMessage + 143, // 263: openshell.v1.OpenShell.RelayStream:output_type -> openshell.v1.RelayFrame + 64, // 264: openshell.v1.OpenShell.WatchSandbox:output_type -> openshell.v1.SandboxStreamEvent + 153, // 265: openshell.v1.OpenShell.SubmitPolicyAnalysis:output_type -> openshell.v1.SubmitPolicyAnalysisResponse + 155, // 266: openshell.v1.OpenShell.GetDraftPolicy:output_type -> openshell.v1.GetDraftPolicyResponse + 157, // 267: openshell.v1.OpenShell.ApproveDraftChunk:output_type -> openshell.v1.ApproveDraftChunkResponse + 159, // 268: openshell.v1.OpenShell.RejectDraftChunk:output_type -> openshell.v1.RejectDraftChunkResponse + 161, // 269: openshell.v1.OpenShell.ApproveAllDraftChunks:output_type -> openshell.v1.ApproveAllDraftChunksResponse + 163, // 270: openshell.v1.OpenShell.EditDraftChunk:output_type -> openshell.v1.EditDraftChunkResponse + 165, // 271: openshell.v1.OpenShell.UndoDraftChunk:output_type -> openshell.v1.UndoDraftChunkResponse + 167, // 272: openshell.v1.OpenShell.ClearDraftChunks:output_type -> openshell.v1.ClearDraftChunksResponse + 170, // 273: openshell.v1.OpenShell.GetDraftHistory:output_type -> openshell.v1.GetDraftHistoryResponse + 7, // 274: openshell.v1.OpenShell.IssueSandboxToken:output_type -> openshell.v1.IssueSandboxTokenResponse + 9, // 275: openshell.v1.OpenShell.RefreshSandboxToken:output_type -> openshell.v1.RefreshSandboxTokenResponse + 176, // 276: openshell.v1.OpenShell.CreateWorkspace:output_type -> openshell.v1.CreateWorkspaceResponse + 178, // 277: openshell.v1.OpenShell.GetWorkspace:output_type -> openshell.v1.GetWorkspaceResponse + 180, // 278: openshell.v1.OpenShell.ListWorkspaces:output_type -> openshell.v1.ListWorkspacesResponse + 182, // 279: openshell.v1.OpenShell.DeleteWorkspace:output_type -> openshell.v1.DeleteWorkspaceResponse + 185, // 280: openshell.v1.OpenShell.AddWorkspaceMember:output_type -> openshell.v1.AddWorkspaceMemberResponse + 187, // 281: openshell.v1.OpenShell.RemoveWorkspaceMember:output_type -> openshell.v1.RemoveWorkspaceMemberResponse + 189, // 282: openshell.v1.OpenShell.ListWorkspaceMembers:output_type -> openshell.v1.ListWorkspaceMembersResponse + 217, // [217:283] is the sub-list for method output_type + 151, // [151:217] is the sub-list for method input_type + 151, // [151:151] is the sub-list for extension type_name + 151, // [151:151] is the sub-list for extension extendee + 0, // [0:151] is the sub-list for field type_name } func init() { file_openshell_proto_init() } @@ -14756,7 +14853,7 @@ func file_openshell_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_openshell_proto_rawDesc), len(file_openshell_proto_rawDesc)), NumEnums: 6, - NumMessages: 208, + NumMessages: 209, NumExtensions: 0, NumServices: 1, }, diff --git a/sdk/go/proto/sandboxv1/sandbox.pb.go b/sdk/go/proto/sandboxv1/sandbox.pb.go index 0a4a0a7370..48250ccc72 100644 --- a/sdk/go/proto/sandboxv1/sandbox.pb.go +++ b/sdk/go/proto/sandboxv1/sandbox.pb.go @@ -1800,8 +1800,12 @@ type GetSandboxConfigResponse struct { // are "fail_closed" and "retain_last_valid". Unknown or empty values must // be treated as fail_closed by the supervisor. PolicyValidationFailureMode string `protobuf:"bytes,11,opt,name=policy_validation_failure_mode,json=policyValidationFailureMode,proto3" json:"policy_validation_failure_mode,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Whether this gateway can mint authenticated extension credentials. + // False also covers older gateways that do not advertise this capability; + // supervisors preserve their legacy unauthenticated connection behavior. + ExtensionAuthenticationEnabled bool `protobuf:"varint,12,opt,name=extension_authentication_enabled,json=extensionAuthenticationEnabled,proto3" json:"extension_authentication_enabled,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *GetSandboxConfigResponse) Reset() { @@ -1911,6 +1915,13 @@ func (x *GetSandboxConfigResponse) GetPolicyValidationFailureMode() string { return "" } +func (x *GetSandboxConfigResponse) GetExtensionAuthenticationEnabled() bool { + if x != nil { + return x.ExtensionAuthenticationEnabled + } + return false +} + // Connection details for one operator-registered supervisor middleware service. // V1 supports plaintext and server-authenticated TLS gRPC. type SupervisorMiddlewareService struct { @@ -1919,14 +1930,27 @@ type SupervisorMiddlewareService struct { Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // gRPC endpoint reachable from the sandbox supervisor. GrpcEndpoint string `protobuf:"bytes,2,opt,name=grpc_endpoint,json=grpcEndpoint,proto3" json:"grpc_endpoint,omitempty"` - // Operator-owned body limit applied to every binding exposed by the service. - MaxBodyBytes uint64 `protobuf:"varint,3,opt,name=max_body_bytes,json=maxBodyBytes,proto3" json:"max_body_bytes,omitempty"` + // Operator-owned logical payload limit applied to every binding exposed by + // the service. This caps HTTP bodies and complete WebSocket messages. + MaxPayloadBytes uint64 `protobuf:"varint,3,opt,name=max_payload_bytes,json=maxPayloadBytes,proto3" json:"max_payload_bytes,omitempty"` // Default RPC timeout for this service. Empty uses the platform default of // 500ms. Values use an integer with an `ms` or `s` suffix and must be // between 10ms and 30s. - Timeout string `protobuf:"bytes,4,opt,name=timeout,proto3" json:"timeout,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + Timeout string `protobuf:"bytes,4,opt,name=timeout,proto3" json:"timeout,omitempty"` + // PEM-encoded trust roots loaded by the gateway from the operator-configured + // tls_ca_cert_path. Empty uses the platform trust store. + TlsCaCertPem []byte `protobuf:"bytes,5,opt,name=tls_ca_cert_pem,json=tlsCaCertPem,proto3" json:"tls_ca_cert_pem,omitempty"` + // Exact JWT audience for this service. The gateway resolves an omitted + // operator value to a kind-scoped audience derived from the registration + // name before sending sandbox config. + Audience string `protobuf:"bytes,6,opt,name=audience,proto3" json:"audience,omitempty"` + // Operator opt-out from extension authentication for this registration. + // When true the service may use a plaintext endpoint and OpenShell attaches + // no bearer credential; supervisors must not request one. Intended only for + // trusted-network development deployments. + AllowInsecureTransport bool `protobuf:"varint,7,opt,name=allow_insecure_transport,json=allowInsecureTransport,proto3" json:"allow_insecure_transport,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *SupervisorMiddlewareService) Reset() { @@ -1973,9 +1997,9 @@ func (x *SupervisorMiddlewareService) GetGrpcEndpoint() string { return "" } -func (x *SupervisorMiddlewareService) GetMaxBodyBytes() uint64 { +func (x *SupervisorMiddlewareService) GetMaxPayloadBytes() uint64 { if x != nil { - return x.MaxBodyBytes + return x.MaxPayloadBytes } return 0 } @@ -1987,6 +2011,27 @@ func (x *SupervisorMiddlewareService) GetTimeout() string { return "" } +func (x *SupervisorMiddlewareService) GetTlsCaCertPem() []byte { + if x != nil { + return x.TlsCaCertPem + } + return nil +} + +func (x *SupervisorMiddlewareService) GetAudience() string { + if x != nil { + return x.Audience + } + return "" +} + +func (x *SupervisorMiddlewareService) GetAllowInsecureTransport() bool { + if x != nil { + return x.AllowInsecureTransport + } + return false +} + var File_sandbox_proto protoreflect.FileDescriptor const file_sandbox_proto_rawDesc = "" + @@ -2138,7 +2183,7 @@ const file_sandbox_proto_rawDesc = "" + "\x05value\"\x86\x01\n" + "\x10EffectiveSetting\x128\n" + "\x05value\x18\x01 \x01(\v2\".openshell.sandbox.v1.SettingValueR\x05value\x128\n" + - "\x05scope\x18\x02 \x01(\x0e2\".openshell.sandbox.v1.SettingScopeR\x05scope\"\x87\x06\n" + + "\x05scope\x18\x02 \x01(\x0e2\".openshell.sandbox.v1.SettingScopeR\x05scope\"\xd1\x06\n" + "\x18GetSandboxConfigResponse\x12;\n" + "\x06policy\x18\x01 \x01(\v2#.openshell.sandbox.v1.SandboxPolicyR\x06policy\x12\x18\n" + "\aversion\x18\x02 \x01(\rR\aversion\x12\x1f\n" + @@ -2152,15 +2197,19 @@ const file_sandbox_proto_rawDesc = "" + "\x1esupervisor_middleware_services\x18\t \x03(\v21.openshell.sandbox.v1.SupervisorMiddlewareServiceR\x1csupervisorMiddlewareServices\x12\x1c\n" + "\tworkspace\x18\n" + " \x01(\tR\tworkspace\x12C\n" + - "\x1epolicy_validation_failure_mode\x18\v \x01(\tR\x1bpolicyValidationFailureMode\x1ac\n" + + "\x1epolicy_validation_failure_mode\x18\v \x01(\tR\x1bpolicyValidationFailureMode\x12H\n" + + " extension_authentication_enabled\x18\f \x01(\bR\x1eextensionAuthenticationEnabled\x1ac\n" + "\rSettingsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12<\n" + - "\x05value\x18\x02 \x01(\v2&.openshell.sandbox.v1.EffectiveSettingR\x05value:\x028\x01\"\x96\x01\n" + + "\x05value\x18\x02 \x01(\v2&.openshell.sandbox.v1.EffectiveSettingR\x05value:\x028\x01\"\x99\x02\n" + "\x1bSupervisorMiddlewareService\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12#\n" + - "\rgrpc_endpoint\x18\x02 \x01(\tR\fgrpcEndpoint\x12$\n" + - "\x0emax_body_bytes\x18\x03 \x01(\x04R\fmaxBodyBytes\x12\x18\n" + - "\atimeout\x18\x04 \x01(\tR\atimeout*b\n" + + "\rgrpc_endpoint\x18\x02 \x01(\tR\fgrpcEndpoint\x12*\n" + + "\x11max_payload_bytes\x18\x03 \x01(\x04R\x0fmaxPayloadBytes\x12\x18\n" + + "\atimeout\x18\x04 \x01(\tR\atimeout\x12%\n" + + "\x0ftls_ca_cert_pem\x18\x05 \x01(\fR\ftlsCaCertPem\x12\x1a\n" + + "\baudience\x18\x06 \x01(\tR\baudience\x128\n" + + "\x18allow_insecure_transport\x18\a \x01(\bR\x16allowInsecureTransport*b\n" + "\fSettingScope\x12\x1d\n" + "\x19SETTING_SCOPE_UNSPECIFIED\x10\x00\x12\x19\n" + "\x15SETTING_SCOPE_SANDBOX\x10\x01\x12\x18\n" + diff --git a/tasks/rust.toml b/tasks/rust.toml index 8ca47d7efe..854c2ac939 100644 --- a/tasks/rust.toml +++ b/tasks/rust.toml @@ -14,6 +14,7 @@ description = "Lint Rust code with Clippy (deny warnings)" run = [ "cargo clippy --workspace --all-targets -- -D warnings", "cargo clippy --manifest-path e2e/rust/Cargo.toml --all-targets -- -D warnings", + "cargo check --manifest-path examples/governance-interceptor/Cargo.toml --all-targets", ] run_windows = "powershell -NoProfile -ExecutionPolicy Bypass -File tasks/scripts/windows-msvc.ps1 lint native" hide = true @@ -23,6 +24,7 @@ description = "Format Rust code" run = [ "cargo fmt --all", "cargo fmt --manifest-path e2e/rust/Cargo.toml --all", + "cargo fmt --manifest-path examples/governance-interceptor/Cargo.toml --all", ] hide = true @@ -31,6 +33,7 @@ description = "Check Rust formatting" run = [ "cargo fmt --all -- --check", "cargo fmt --manifest-path e2e/rust/Cargo.toml --all -- --check", + "cargo fmt --manifest-path examples/governance-interceptor/Cargo.toml --all -- --check", ] hide = true diff --git a/tasks/scripts/gateway.sh b/tasks/scripts/gateway.sh index 69a487e00d..51eb1d0eee 100644 --- a/tasks/scripts/gateway.sh +++ b/tasks/scripts/gateway.sh @@ -35,6 +35,8 @@ Options: Environment: OPENSHELL_DRIVERS Driver override used by openshell-gateway. OPENSHELL_GATEWAY_NAME Gateway name for generic podman/kubernetes runs. + OPENSHELL_BIND_ADDRESS Gateway listener address. Defaults to 127.0.0.1, + or ::1 for Podman Machine on macOS. OPENSHELL_SERVER_PORT Gateway port. Defaults to 8080 for Kubernetes, 18080 for Podman/Docker, and 18081 for VM. OPENSHELL_SUPERVISOR_IMAGE @@ -300,13 +302,16 @@ SANDBOX_IMAGE="${OPENSHELL_SANDBOX_IMAGE:-ghcr.io/nvidia/openshell-community/san SANDBOX_IMAGE_PULL_POLICY="${OPENSHELL_SANDBOX_IMAGE_PULL_POLICY:-IfNotPresent}" GRPC_ENDPOINT="${OPENSHELL_GRPC_ENDPOINT:-}" LOG_LEVEL="${OPENSHELL_LOG_LEVEL:-info}" -PRIMARY_BIND_IP="127.0.0.1" +PRIMARY_BIND_IP="${OPENSHELL_BIND_ADDRESS:-127.0.0.1}" CLI_ENDPOINT_HOST="127.0.0.1" -if [[ "${DRIVER}" == "podman" && "$(uname -s)" == "Darwin" ]]; then +if [[ -z "${OPENSHELL_BIND_ADDRESS:-}" \ + && "${DRIVER}" == "podman" \ + && "$(uname -s)" == "Darwin" ]]; then # Podman Machine reserves IPv4 loopback for its callback-only listener. # Keep the primary listener distinct while using a hostname that resolves - # to IPv6 loopback for local CLI connections. + # to IPv6 loopback for local CLI connections. An explicit bind address + # overrides this platform default. PRIMARY_BIND_IP="::1" CLI_ENDPOINT_HOST="localhost" fi @@ -437,6 +442,7 @@ register_gateway_metadata "${GATEWAY_NAME}" "${GATEWAY_ENDPOINT}" "${PORT}" echo "Starting standalone ${DRIVER} gateway..." echo " gateway: ${GATEWAY_NAME}" echo " endpoint: ${GATEWAY_ENDPOINT}" +echo " bind: ${PRIMARY_BIND_IP}:${PORT}" echo " namespace: ${SANDBOX_NAMESPACE}" echo " state dir: ${STATE_DIR}" if [[ "${DRIVER}" == "podman" ]]; then diff --git a/tasks/scripts/helm-k3s-local.sh b/tasks/scripts/helm-k3s-local.sh index f9ac186f52..82b8d5cfc8 100755 --- a/tasks/scripts/helm-k3s-local.sh +++ b/tasks/scripts/helm-k3s-local.sh @@ -230,11 +230,13 @@ preload_sandbox_image() { docker pull --platform "${platform}" "${PRELOAD_SANDBOX_IMAGE}" fi + # Save without --platform: the platform-specific pull already constrained the + # local image, and --platform fails on OCI index (multi-arch) manifests. tmp="$(mktemp "${TMPDIR:-/tmp}/openshell-sandbox-image.XXXXXX")" - if ! docker image save --platform "${platform}" -o "${tmp}" "${PRELOAD_SANDBOX_IMAGE}"; then + if ! docker image save -o "${tmp}" "${PRELOAD_SANDBOX_IMAGE}"; then echo "Pulling sandbox image for ${platform}..." docker pull --platform "${platform}" "${PRELOAD_SANDBOX_IMAGE}" - docker image save --platform "${platform}" -o "${tmp}" "${PRELOAD_SANDBOX_IMAGE}" + docker image save -o "${tmp}" "${PRELOAD_SANDBOX_IMAGE}" fi if ! k3d image import "${tmp}" --cluster "${CLUSTER_NAME}"; then diff --git a/tasks/test.toml b/tasks/test.toml index d50750e9cb..bef8baf2b5 100644 --- a/tasks/test.toml +++ b/tasks/test.toml @@ -170,6 +170,16 @@ description = "Run Kubernetes e2e for provider credential storage backed by Kube env = { OPENSHELL_E2E_CREDENTIAL_DRIVERS = "1", OPENSHELL_E2E_KUBE_TEST = "credential_drivers", OPENSHELL_E2E_KUBERNETES_FEATURES = "e2e,e2e-kubernetes,e2e-kubernetes-credential-drivers" } run = "e2e/rust/e2e-kubernetes.sh" +["e2e:kubernetes:workspace-managed"] +description = "Run Kubernetes e2e with managed workspace mode (auto-created per-workspace namespaces)" +env = { OPENSHELL_E2E_KUBE_EXTRA_VALUES = "deploy/helm/openshell/ci/values-workspace-managed.yaml", OPENSHELL_E2E_KUBE_IMAGE_PULL_SECRET = "e2e-regcred", OPENSHELL_E2E_KUBE_TEST = "workspace_namespace_managed", OPENSHELL_E2E_KUBERNETES_FEATURES = "e2e,e2e-kubernetes,e2e-kubernetes-workspace-managed" } +run = "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" } +run = "e2e/rust/e2e-kubernetes.sh" + ["e2e:vm"] description = "Start openshell-gateway with the VM compute driver and run VM e2e tests" run = "e2e/rust/e2e-vm.sh"