diff --git a/deploy/helm/scope/CONFIGURATION.md b/deploy/helm/scope/CONFIGURATION.md index bb4842c60..aa3fedd0f 100644 --- a/deploy/helm/scope/CONFIGURATION.md +++ b/deploy/helm/scope/CONFIGURATION.md @@ -8,7 +8,9 @@ steps, see the [README](./README.md). Port-forward the Portal if it isn't already running (see README "Verify"): ```bash -kubectl -n scope port-forward svc/scope-portal 5100:80 +# Use global.namespace from your values file (scope unless customized). +NAMESPACE=scope +kubectl -n "$NAMESPACE" port-forward svc/scope-portal 5100:80 ``` Then, at : @@ -48,6 +50,35 @@ workers use this (they pull from ACR, not GHCR), as does `jobs.dbMigrate` (which needs a separate `:builder`-tagged image — see `templates/jobs/db-migrate.yaml`). +`image.digest`, when set for a service image, takes precedence over its tag +and `global.imageTag`. The MCP sidecars use this to pin the verified +`0.4.7-stdio` multi-architecture image. To change their release, update the +digest too; changing only `image.tag` leaves the pinned image unchanged. + +## Namespace and workload identity + +All chart resources use `global.namespace`. It must match both Bicep +federated-identity subjects: + +- `workloadIdentityServiceAccountNamespace` for the backend identity. +- `workerWorkloadIdentityServiceAccountNamespace` for the worker identity, + when provisioned. + +For example, to deploy into `scope-benchmarks`, provision **both** Bicep +namespace parameters as `scope-benchmarks` and keep the generated +`global.namespace: "scope-benchmarks"`. Use `--namespace scope-benchmarks` +with Helm and `scripts/bootstrap-workers.sh`, and `-n scope-benchmarks` +with `kubectl`. Always pass the same values file to worker bootstrap. +Changing only Helm's release namespace does not change `global.namespace` +or reconfigure Azure federation. + +The generator requires the backend namespace output. Worker identity +outputs may all be absent for a backend-only deployment; if any are +present, the client ID, service-account name, and namespace must all be +present and their namespace must equal the backend's. Older deployments +missing namespace outputs must be re-deployed with the updated Bicep +outputs before generating values. + ## Image registry strategy By default, the six core services (api, portal, judge, token-manager, @@ -59,7 +90,8 @@ No registry build step is required for these. If you publish your own fork's images, override the registry: ```bash -helm install scope deploy/helm/scope -n scope \ +NAMESPACE=scope # Must match global.namespace in my-values.yaml. +helm install scope deploy/helm/scope -n "$NAMESPACE" \ -f my-values.yaml \ --set global.imageRegistry=ghcr.io/ ``` diff --git a/deploy/helm/scope/README.md b/deploy/helm/scope/README.md index a5d3baf96..b718fdb0e 100644 --- a/deploy/helm/scope/README.md +++ b/deploy/helm/scope/README.md @@ -17,6 +17,8 @@ This README covers phases 2 and 3. Provider CSI driver + workload identity, Key Vault, Storage, Cosmos DB, Redis, ACR). - `helm` and `kubectl`, configured against the target cluster. +- ACP workers require the Kubernetes `SidecarContainers` feature (enabled + by default since 1.29, stable since 1.33). ## Phase 2: Deploy the core app @@ -28,11 +30,25 @@ This README covers phases 2 and 3. Otherwise, hand-author `my-values.yaml` — see [Configuration](./CONFIGURATION.md). +The generated `global.namespace` comes from +`workloadIdentityServiceAccountNamespace`. If worker identity outputs are +present, their namespace must match: this chart uses a single namespace. +Missing required namespace outputs or mismatched identities stop generation +before the values file is written. Re-deploy the Bicep template with +matching namespace parameters rather than guessing a namespace. + **2. Install the chart:** +Use the **same namespace** for `global.namespace`, the Helm release, and +all later `kubectl`/worker-bootstrap commands. `--create-namespace` creates +the Helm release namespace, not a different `global.namespace`. + ```bash +# Replace scope with global.namespace from my-values.yaml if customized. +NAMESPACE=scope + helm upgrade --install scope deploy/helm/scope \ - --namespace scope --create-namespace \ + --namespace "$NAMESPACE" --create-namespace \ -f my-values.yaml \ --wait --timeout 5m ``` @@ -46,7 +62,8 @@ Bicep doesn't provision — see ACP coding-agent workers are disabled by default: ```bash -./scripts/bootstrap-workers.sh --acr +./scripts/bootstrap-workers.sh --acr \ + --namespace "$NAMESPACE" --values-file my-values.yaml ``` Builds + pushes both worker images, enables their Deployments, and @@ -57,17 +74,30 @@ API key they need yourself via the Portal's **Secrets** tab (or ## Verify ```bash -kubectl get pods -n scope +kubectl get pods -n "$NAMESPACE" # No ingress yet — reach services via port-forward. -kubectl -n scope port-forward svc/api 18080:80 & -kubectl -n scope port-forward svc/scope-portal 5100:80 & +kubectl -n "$NAMESPACE" port-forward svc/api 18080:80 & +kubectl -n "$NAMESPACE" port-forward svc/scope-portal 5100:80 & scope agent list --url http://localhost:18080 # or open http://localhost:5100 ``` Then try an end-to-end run — see [Run a sample scenario](./SAMPLE-SCENARIO.md). +## Chart regression checks + +With Helm 3 and `jq` on `PATH`, run: + +```bash +pnpm exec vitest run scripts/helm-scope.test.ts scripts/generate-values-from-bicep.test.ts +``` + +These render the actual chart and run the generator against mocked Azure +outputs, including custom and mismatched namespaces. No cluster or Azure +credentials are used. The rendering suite is explicitly skipped when +Helm is not installed. + ## Learn more - [Configuration reference](./CONFIGURATION.md) — values.yaml conventions, diff --git a/deploy/helm/scope/SAMPLE-SCENARIO.md b/deploy/helm/scope/SAMPLE-SCENARIO.md index c63964669..8163485bc 100644 --- a/deploy/helm/scope/SAMPLE-SCENARIO.md +++ b/deploy/helm/scope/SAMPLE-SCENARIO.md @@ -24,7 +24,9 @@ projects — so run it yourself, once. ## Steps ```bash -kubectl -n scope port-forward svc/api 18080:80 & +# Use the same global.namespace as the Helm release and worker bootstrap. +NAMESPACE=scope +kubectl -n "$NAMESPACE" port-forward svc/api 18080:80 & # Find the project to seed into: the "Initial Project" created by # db-migrate on first install, or one of your own. diff --git a/deploy/helm/scope/WORKERS.md b/deploy/helm/scope/WORKERS.md index 3294298b9..2a57a84d4 100644 --- a/deploy/helm/scope/WORKERS.md +++ b/deploy/helm/scope/WORKERS.md @@ -9,7 +9,10 @@ templated yet (see the intended production pattern). Bring them online with one command: ```bash -./scripts/bootstrap-workers.sh --acr +# Use global.namespace from the original install's values file. +NAMESPACE=scope +./scripts/bootstrap-workers.sh --acr \ + --namespace "$NAMESPACE" --values-file my-values.yaml ``` This: @@ -30,6 +33,12 @@ Run `./scripts/bootstrap-workers.sh --help` for all flags, including `--skip-agent-registration`, and custom `--namespace`/`--release`/`--chart`/`--image-tag`. +`--namespace` must match both the Helm release namespace and +`global.namespace` in your values file. For a custom namespace, provision +both backend and worker Bicep namespace parameters to that same value +before generating values; the chart cannot deploy the identities into +different namespaces. + > Pass `--values-file ` so the upgrade re-merges your original values > override file against the chart's current defaults, instead of freezing a > historical `--reuse-values` snapshot (which silently drops any default key @@ -76,18 +85,37 @@ sidecar (`workers..mcpGateway`, enabled by default) that aggregates MCP servers for the worker, mirroring docker-compose's `mcp-gateway-copilot`/`mcp-gateway-claude-code` services: +- Uses the **0.4.7 stdio image pinned by multi-architecture digest** in + `values.yaml`, retaining Node.js/`npx`, `uvx`, and remote HTTP/SSE MCP + support. That release's + [`start --host` flag](https://github.com/mcpjungle/MCPJungle/blob/974e2fabe4694d3b613d281e6e4e8d2fa3f6da74/cmd/start.go) + binds the listener to `127.0.0.1:8080`. Development-mode registration is + unauthenticated, so it must not listen on the Pod IP; omitting a Service + does not prevent other pods from reaching a Pod IP. - Templated as a **native sidecar** (`initContainers` entry with - `restartPolicy: Always`, GA since Kubernetes 1.29) rather than a regular - container, so kubelet starts it first and holds the Pod at `NotReady` - until its `/health` readiness probe passes — the worker's first task - never races a gateway that isn't listening yet. + `restartPolicy: Always`; stable since Kubernetes 1.33, enabled by default + since 1.29). Its **startup probe** gates the initial start of the worker + queue consumer until `/health` succeeds, retrying every two seconds for + up to approximately two minutes before restarting the sidecar. + A readiness probe alone only controls Pod readiness, not worker startup. + See the [Kubernetes lifecycle contract](https://kubernetes.io/docs/concepts/workloads/pods/sidecar-containers/#sidecar-containers-and-pod-lifecycle). +- Both probes execute the image's `curl` inside the container against + `http://127.0.0.1:8080/health`, with a two-second request timeout. + Kubelet HTTP probes use the Pod IP and cannot reach this loopback-only + listener. - Shares an `emptyDir` volume mounted at `/workspace` with the worker container (compose's `copilot_workspace`/`claude_workspace` volumes). -- The worker reaches it at `http://localhost:8080` (same Pod — no +- The worker reaches it at `http://127.0.0.1:8080` (same Pod — no `Service` object needed). Set `workers..mcpGateway.enabled: false` only if your scenarios never -configure MCP servers. +configure MCP servers. If overriding the image, update its `digest` as +well as its `tag` (`digest` takes precedence), and verify that the image +supports the binding flags, `curl` probes, and your MCP transports. + +Loopback binding excludes other pods, not containers or benchmark code +inside this worker Pod. It does not resolve the trusted-processor versus +untrusted-executor limitation described below. ## Worker identity isolation @@ -104,8 +132,12 @@ need their own mount to receive it. `scripts/generate-values-from-bicep.sh` picks up the worker identity's outputs automatically if your Bicep deployment provisioned one; otherwise -those two values stay blank and are only required once you set -`workers..enabled: true`. +worker identity defaults remain unchanged and a client ID is only required +once you set `workers..enabled: true`. A provisioned worker identity +must expose its client ID, service-account name, and namespace together. +Its namespace must equal the backend identity's namespace, which the +generator writes as `global.namespace`; missing or incompatible namespace +outputs are errors, not a fallback to `scope`. **Known limitation**: full isolation needs worker code changes this chart can't make alone. `coder-acp-copilot`/`coder-acp-claude-code` are a single diff --git a/deploy/helm/scope/templates/_helpers.tpl b/deploy/helm/scope/templates/_helpers.tpl index a3635c7f6..d96a0186f 100644 --- a/deploy/helm/scope/templates/_helpers.tpl +++ b/deploy/helm/scope/templates/_helpers.tpl @@ -47,14 +47,19 @@ GHCR) wins; otherwise falls back to `global.imageRegistry` (the default distribution point for the core app services, conventionally ghcr.io//scope). Falls back to `global.imageTag` when `.image.tag` is unset, and to a bare (unregistered) name when no registry applies at all. +An optional `.image.digest` takes precedence over tags. */}} {{- define "scope.image" -}} {{- $tag := .image.tag | default .context.Values.global.imageTag -}} +{{- $version := printf ":%s" $tag -}} +{{- if .image.digest -}} +{{- $version = printf "@%s" .image.digest -}} +{{- end -}} {{- $registry := .image.registry | default .context.Values.global.imageRegistry -}} {{- if $registry -}} -{{- printf "%s/%s:%s" $registry .image.repository $tag -}} +{{- printf "%s/%s%s" $registry .image.repository $version -}} {{- else -}} -{{- printf "%s:%s" .image.repository $tag -}} +{{- printf "%s%s" .image.repository $version -}} {{- end -}} {{- end -}} diff --git a/deploy/helm/scope/templates/workers/coder-acp-claude-code/deployment.yaml b/deploy/helm/scope/templates/workers/coder-acp-claude-code/deployment.yaml index 60512ee54..c42e294a1 100644 --- a/deploy/helm/scope/templates/workers/coder-acp-claude-code/deployment.yaml +++ b/deploy/helm/scope/templates/workers/coder-acp-claude-code/deployment.yaml @@ -28,31 +28,34 @@ spec: {{- toYaml . | nindent 8 }} {{- end }} {{- if .Values.workers.coderAcpClaudeCode.mcpGateway.enabled }} - # Native sidecar (GA since K8s 1.29): kubelet starts this before the - # main container and holds the Pod at NotReady until its readiness - # probe passes, so the worker's first task never races an MCP-gateway - # that isn't listening yet. Mirrors compose's - # mcp-gateway-claude-code `depends_on: service_healthy`. + # Native sidecar (stable in K8s 1.33, enabled by default since 1.29). + # Its startup probe gates the queue consumer, not just Pod readiness. + # The unauthenticated registry must only listen on pod loopback. initContainers: - name: mcp-gateway restartPolicy: Always image: {{ include "scope.image" (dict "image" .Values.workers.coderAcpClaudeCode.mcpGateway.image "context" .) }} imagePullPolicy: {{ .Values.global.imagePullPolicy }} - # Suppress MCPJungle's ASCII-art banner (written to stderr). - command: ["/bin/sh", "-c"] - args: ["/mcpjungle start 2>&1 | grep --line-buffered -v '[█═╗╚║╔╝]' >&2"] + command: ["/mcpjungle"] + args: ["start", "--host", "127.0.0.1", "--port", "8080"] env: - name: SESSION_IDLE_TIMEOUT_SEC value: "0" volumeMounts: - name: workspace mountPath: /workspace + startupProbe: + exec: + command: ["curl", "--fail", "--silent", "--show-error", "--max-time", "2", "http://127.0.0.1:8080/health"] + timeoutSeconds: 3 + periodSeconds: 2 + failureThreshold: 60 readinessProbe: - httpGet: - path: /health - port: 8080 - initialDelaySeconds: 10 - periodSeconds: 60 + exec: + command: ["curl", "--fail", "--silent", "--show-error", "--max-time", "2", "http://127.0.0.1:8080/health"] + timeoutSeconds: 3 + periodSeconds: 10 + failureThreshold: 3 resources: {{- toYaml .Values.workers.coderAcpClaudeCode.mcpGateway.resources | nindent 12 }} {{- end }} @@ -100,7 +103,7 @@ spec: # Same Pod, so the sidecar is reachable over loopback — no # Service object needed. - name: MCP_GATEWAY_URL - value: http://localhost:8080 + value: http://127.0.0.1:8080 {{- end }} {{- if .Values.workers.coderAcpClaudeCode.mcpGateway.enabled }} volumeMounts: diff --git a/deploy/helm/scope/templates/workers/coder-acp-copilot/deployment.yaml b/deploy/helm/scope/templates/workers/coder-acp-copilot/deployment.yaml index c99c4d3d7..6a5fe7f70 100644 --- a/deploy/helm/scope/templates/workers/coder-acp-copilot/deployment.yaml +++ b/deploy/helm/scope/templates/workers/coder-acp-copilot/deployment.yaml @@ -28,31 +28,34 @@ spec: {{- toYaml . | nindent 8 }} {{- end }} {{- if .Values.workers.coderAcpCopilot.mcpGateway.enabled }} - # Native sidecar (GA since K8s 1.29): kubelet starts this before the - # main container and holds the Pod at NotReady until its readiness - # probe passes, so the worker's first task never races an MCP-gateway - # that isn't listening yet. Mirrors compose's - # mcp-gateway-copilot `depends_on: service_healthy`. + # Native sidecar (stable in K8s 1.33, enabled by default since 1.29). + # Its startup probe gates the queue consumer, not just Pod readiness. + # The unauthenticated registry must only listen on pod loopback. initContainers: - name: mcp-gateway restartPolicy: Always image: {{ include "scope.image" (dict "image" .Values.workers.coderAcpCopilot.mcpGateway.image "context" .) }} imagePullPolicy: {{ .Values.global.imagePullPolicy }} - # Suppress MCPJungle's ASCII-art banner (written to stderr). - command: ["/bin/sh", "-c"] - args: ["/mcpjungle start 2>&1 | grep --line-buffered -v '[█═╗╚║╔╝]' >&2"] + command: ["/mcpjungle"] + args: ["start", "--host", "127.0.0.1", "--port", "8080"] env: - name: SESSION_IDLE_TIMEOUT_SEC value: "0" volumeMounts: - name: workspace mountPath: /workspace + startupProbe: + exec: + command: ["curl", "--fail", "--silent", "--show-error", "--max-time", "2", "http://127.0.0.1:8080/health"] + timeoutSeconds: 3 + periodSeconds: 2 + failureThreshold: 60 readinessProbe: - httpGet: - path: /health - port: 8080 - initialDelaySeconds: 10 - periodSeconds: 60 + exec: + command: ["curl", "--fail", "--silent", "--show-error", "--max-time", "2", "http://127.0.0.1:8080/health"] + timeoutSeconds: 3 + periodSeconds: 10 + failureThreshold: 3 resources: {{- toYaml .Values.workers.coderAcpCopilot.mcpGateway.resources | nindent 12 }} {{- end }} @@ -99,7 +102,7 @@ spec: # Same Pod, so the sidecar is reachable over loopback — no # Service object needed. - name: MCP_GATEWAY_URL - value: http://localhost:8080 + value: http://127.0.0.1:8080 {{- end }} {{- if .Values.workers.coderAcpCopilot.mcpGateway.enabled }} volumeMounts: diff --git a/deploy/helm/scope/values.yaml b/deploy/helm/scope/values.yaml index f2d359eaa..3d0b40bb6 100644 --- a/deploy/helm/scope/values.yaml +++ b/deploy/helm/scope/values.yaml @@ -19,6 +19,8 @@ # azure.storageAccountName <- output storageAccountName # azure.redisHostName <- output redisHostName # azure.redisPort <- output redisPort +# global.namespace <- output workloadIdentityServiceAccountNamespace +# Must also match workerWorkloadIdentityServiceAccountNamespace when present. # azure.workerWorkloadIdentityClientId <- output workerWorkloadIdentityClientId # azure.workerServiceAccountName <- output workerWorkloadIdentityServiceAccountName # @@ -251,16 +253,18 @@ workers: limits: { cpu: "1", memory: 1Gi } # MCPJungle sidecar (MCP-server aggregation) — mirrors docker-compose's # mcp-gateway-copilot service. Templated as a native sidecar - # (initContainer with restartPolicy: Always, GA since K8s 1.29) so - # kubelet holds the Pod at NotReady until the gateway's health check - # passes, instead of racing the worker's first task. Disable only if + # (initContainer with restartPolicy: Always, stable in K8s 1.33, + # enabled by default since 1.29). An in-container loopback startup + # probe gates the worker until the gateway listens. Disable only if # your scenarios never configure MCP servers. mcpGateway: enabled: true image: registry: ghcr.io repository: mcpjungle/mcpjungle - tag: latest-stdio + # Verified 0.4.7 stdio release: supports --host and curl exec probes. + tag: "0.4.7-stdio" + digest: sha256:4eae32ecba23e2970413a320ae1f0457f9f7dac1ee39c2b3f34f48753e918e33 resources: requests: { cpu: 250m, memory: 256Mi } limits: { cpu: "500m", memory: 512Mi } @@ -284,7 +288,8 @@ workers: image: registry: ghcr.io repository: mcpjungle/mcpjungle - tag: latest-stdio + tag: "0.4.7-stdio" + digest: sha256:4eae32ecba23e2970413a320ae1f0457f9f7dac1ee39c2b3f34f48753e918e33 resources: requests: { cpu: 250m, memory: 256Mi } limits: { cpu: "500m", memory: 512Mi } diff --git a/scripts/generate-values-from-bicep.sh b/scripts/generate-values-from-bicep.sh index 120284fca..34b3bc366 100755 --- a/scripts/generate-values-from-bicep.sh +++ b/scripts/generate-values-from-bicep.sh @@ -36,12 +36,11 @@ # -h, --help Show this help. # # If the deployment also has worker-identity outputs -# (workerWorkloadIdentityClientId/workerWorkloadIdentityServiceAccountName — -# only present if you provisioned the ACP worker identity), those are -# written too. Missing is not an error: older deployments, or ones that -# never provisioned worker identity, just won't get the worker.* keys, and -# the chart falls back to its defaults (empty client ID, required only once -# you enable a worker — see WORKERS.md). +# (workerWorkloadIdentityClientId/workerWorkloadIdentityServiceAccountName/ +# workerWorkloadIdentityServiceAccountNamespace), those are written too. +# All three may be absent if no worker identity was provisioned, but a +# partial set is an error. Both identities must be federated to the same +# namespace: this chart deploys all resources into global.namespace. # # Requires: az (logged in, correct subscription active), jq. set -euo pipefail @@ -113,6 +112,7 @@ KEY_VAULT_NAME="$(get_output keyVaultName)" KEY_VAULT_URI="$(get_output keyVaultUri)" WORKLOAD_IDENTITY_CLIENT_ID="$(get_output workloadIdentityClientId)" SERVICE_ACCOUNT_NAME="$(get_output workloadIdentityServiceAccountName)" +SERVICE_ACCOUNT_NAMESPACE="$(get_output workloadIdentityServiceAccountNamespace)" STORAGE_ACCOUNT_NAME="$(get_output storageAccountName)" REDIS_HOST_NAME="$(get_output redisHostName)" REDIS_PORT="$(get_output redisPort)" @@ -120,6 +120,7 @@ REDIS_PORT="$(get_output redisPort)" # identity. Not required below — see WORKERS.md. WORKER_WORKLOAD_IDENTITY_CLIENT_ID="$(get_output workerWorkloadIdentityClientId)" WORKER_SERVICE_ACCOUNT_NAME="$(get_output workerWorkloadIdentityServiceAccountName)" +WORKER_SERVICE_ACCOUNT_NAMESPACE="$(get_output workerWorkloadIdentityServiceAccountNamespace)" for pair in \ "tenantId:$TENANT_ID" \ @@ -127,6 +128,7 @@ for pair in \ "keyVaultUri:$KEY_VAULT_URI" \ "workloadIdentityClientId:$WORKLOAD_IDENTITY_CLIENT_ID" \ "workloadIdentityServiceAccountName:$SERVICE_ACCOUNT_NAME" \ + "workloadIdentityServiceAccountNamespace:$SERVICE_ACCOUNT_NAMESPACE" \ "storageAccountName:$STORAGE_ACCOUNT_NAME" \ "redisHostName:$REDIS_HOST_NAME" \ "redisPort:$REDIS_PORT" @@ -139,20 +141,38 @@ do fi done -if [[ -z "$WORKER_WORKLOAD_IDENTITY_CLIENT_ID" || -z "$WORKER_SERVICE_ACCOUNT_NAME" ]]; then +if [[ -n "$WORKER_WORKLOAD_IDENTITY_CLIENT_ID" || -n "$WORKER_SERVICE_ACCOUNT_NAME" || -n "$WORKER_SERVICE_ACCOUNT_NAMESPACE" ]]; then + for pair in \ + "workerWorkloadIdentityClientId:$WORKER_WORKLOAD_IDENTITY_CLIENT_ID" \ + "workerWorkloadIdentityServiceAccountName:$WORKER_SERVICE_ACCOUNT_NAME" \ + "workerWorkloadIdentityServiceAccountNamespace:$WORKER_SERVICE_ACCOUNT_NAMESPACE" + do + key="${pair%%:*}" + val="${pair#*:}" + if [[ -z "$val" ]]; then + echo "ERROR: value for '$key' was empty in an incomplete worker identity. Re-provision with all worker-identity outputs before generating values." >&2 + exit 1 + fi + done + if [[ "$WORKER_SERVICE_ACCOUNT_NAMESPACE" != "$SERVICE_ACCOUNT_NAMESPACE" ]]; then + echo "ERROR: the chart uses a single namespace, but the backend identity is federated to '$SERVICE_ACCOUNT_NAMESPACE' and the worker identity to '$WORKER_SERVICE_ACCOUNT_NAMESPACE'. Re-provision both identities in the same namespace." >&2 + exit 1 + fi +else echo " Note: worker-identity outputs not found on this deployment — skipping worker.* values. Bring the ACP workers online only after re-provisioning with that identity (see WORKERS.md)." fi echo "==> Writing $VALUES_FILE" { - if [[ -n "$IMAGE_REGISTRY" ]]; then - cat <; + +const { parse }: { parse: (source: string) => GeneratedValues } = + createRequire(resolve("packages/shared/package.json"))("yaml"); +const directories: string[] = []; +const script = resolve("scripts/generate-values-from-bicep.sh"); +const workerOutputs = [ + "workerWorkloadIdentityClientId", + "workerWorkloadIdentityServiceAccountName", + "workerWorkloadIdentityServiceAccountNamespace", +]; +const outputs: BicepOutputs = { + keyVaultName: { value: "test-vault" }, + keyVaultUri: { value: "https://test-vault.vault.azure.net/" }, + workloadIdentityClientId: { value: "backend-client" }, + workloadIdentityServiceAccountName: { value: "backend-account" }, + workloadIdentityServiceAccountNamespace: { value: "scope-benchmarks" }, + storageAccountName: { value: "teststorage" }, + redisHostName: { value: "redis.example.test" }, + redisPort: { value: 10000 }, + workerWorkloadIdentityClientId: { value: "worker-client" }, + workerWorkloadIdentityServiceAccountName: { value: "worker-account" }, + workerWorkloadIdentityServiceAccountNamespace: { value: "scope-benchmarks" }, +}; + +function generate(values: BicepOutputs, args: string[] = [], existingValues?: string) { + const directory = mkdtempSync(join(tmpdir(), "scope-bicep-values-")); + directories.push(directory); + const bin = join(directory, "bin"); + mkdirSync(bin); + const outputsFile = join(directory, "outputs.json"); + const valuesFile = join(directory, "values.yaml"); + writeFileSync(outputsFile, JSON.stringify(values)); + if (existingValues !== undefined) writeFileSync(valuesFile, existingValues); + writeFileSync(join(bin, "az"), `#!/bin/sh +set -eu +case "$*" in + "deployment group show "*) cat "$TEST_BICEP_OUTPUTS" ;; + "account show "*) printf 'test-tenant\\n' ;; + *) echo "Unexpected Azure call: $*" >&2; exit 99 ;; +esac +`, { mode: 0o755 }); + const result = spawnSync("bash", [ + script, "--resource-group", "test-rg", "--deployment-name", "test-deployment", + "--values-file", valuesFile, ...args, + ], { + encoding: "utf8", + env: { ...process.env, PATH: `${bin}:${process.env.PATH ?? ""}`, TEST_BICEP_OUTPUTS: outputsFile }, + }); + return { ...result, valuesFile }; +} + +afterEach(() => { + for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true }); +}); + +describe("generate-values-from-bicep.sh namespaces", () => { + it.each(["scope", "scope-benchmarks"])("propagates the federated namespace %s with both identities", (namespace) => { + const result = generate({ + ...outputs, + workloadIdentityServiceAccountNamespace: { value: namespace }, + workerWorkloadIdentityServiceAccountNamespace: { value: namespace }, + }); + expect(result.status, result.stderr).toBe(0); + const values = parse(readFileSync(result.valuesFile, "utf8")); + expect(values.global).toEqual({ namespace }); + expect(values.azure).toMatchObject({ + serviceAccountName: "backend-account", + workerWorkloadIdentityClientId: "worker-client", + workerServiceAccountName: "worker-account", + }); + }); + + it("merges an image registry override into the same global mapping", () => { + const result = generate(outputs, ["--image-registry", "test.azurecr.io"]); + expect(result.status, result.stderr).toBe(0); + expect(parse(readFileSync(result.valuesFile, "utf8")).global).toEqual({ + namespace: "scope-benchmarks", imageRegistry: "test.azurecr.io", + }); + }); + + it("requires the backend namespace instead of silently using the chart default", () => { + const withoutNamespace = { ...outputs }; + delete withoutNamespace.workloadIdentityServiceAccountNamespace; + const result = generate(withoutNamespace); + expect(result.status).toBe(1); + expect(result.stderr).toContain("workloadIdentityServiceAccountNamespace"); + expect(existsSync(result.valuesFile)).toBe(false); + }); + + it("rejects differing backend/worker namespaces without overwriting an existing file", () => { + const original = "global:\n namespace: keep-me\n"; + const result = generate({ + ...outputs, workerWorkloadIdentityServiceAccountNamespace: { value: "other-namespace" }, + }, ["--force"], original); + expect(result.status).toBe(1); + expect(result.stderr).toContain("single namespace"); + expect(result.stderr).toContain("scope-benchmarks"); + expect(result.stderr).toContain("other-namespace"); + expect(readFileSync(result.valuesFile, "utf8")).toBe(original); + }); + + it.each(workerOutputs)("rejects an incomplete worker identity missing %s", (key) => { + const incomplete = { ...outputs }; + delete incomplete[key]; + const result = generate(incomplete); + expect(result.status).toBe(1); + expect(result.stderr).toContain(key); + expect(existsSync(result.valuesFile)).toBe(false); + }); + + it("still supports deployments that did not provision any worker identity", () => { + const withoutWorker = { ...outputs }; + for (const key of workerOutputs) delete withoutWorker[key]; + const result = generate(withoutWorker); + expect(result.status, result.stderr).toBe(0); + const values = parse(readFileSync(result.valuesFile, "utf8")); + expect(values.global.namespace).toBe("scope-benchmarks"); + expect(values.azure).not.toHaveProperty("workerWorkloadIdentityClientId"); + expect(values.azure).not.toHaveProperty("workerServiceAccountName"); + }); +}); diff --git a/scripts/helm-scope.test.ts b/scripts/helm-scope.test.ts new file mode 100644 index 000000000..e617076fe --- /dev/null +++ b/scripts/helm-scope.test.ts @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +import { spawnSync } from "node:child_process"; +import { createRequire } from "node:module"; +import { resolve } from "node:path"; +import { beforeAll, describe, expect, it } from "vitest"; + +interface Probe { + exec?: { command: string[] }; + timeoutSeconds: number; + periodSeconds: number; + failureThreshold: number; +} + +interface Container { + name: string; + image: string; + command?: string[]; + args?: string[]; + restartPolicy?: string; + env?: { name: string; value: string }[]; + volumeMounts?: { name: string; mountPath: string }[]; + startupProbe?: Probe; + readinessProbe?: Probe; +} + +interface PodSpec { + serviceAccountName: string; + initContainers?: Container[]; + containers: Container[]; + volumes?: { name: string; emptyDir?: object; csi?: object }[]; +} + +interface Manifest { + kind: string; + metadata: { name: string; namespace: string }; + spec?: { template?: { spec: PodSpec } }; +} + +const { parseAllDocuments }: { + parseAllDocuments: (source: string) => { toJSON: () => Manifest }[]; +} = createRequire(resolve("packages/shared/package.json"))("yaml"); + +const helmVersion = spawnSync("helm", ["version", "--short"], { encoding: "utf8" }); +const helmMissing = Boolean( + helmVersion.error && "code" in helmVersion.error && helmVersion.error.code === "ENOENT", +); +if (!helmMissing && helmVersion.status !== 0) { + throw helmVersion.error ?? new Error(helmVersion.stderr); +} + +function render(...overrides: string[]): Manifest[] { + const result = spawnSync("helm", [ + "template", "scope", "deploy/helm/scope", "--namespace", "scope-benchmarks", + "--set", "global.namespace=scope-benchmarks", + "--set", "global.imageTag=app-revision", + "--set", "azure.workloadIdentityClientId=test-backend", + "--set", "azure.workerWorkloadIdentityClientId=test-worker", + "--set", "azure.keyVaultName=test-vault", + "--set", "azure.keyVaultUri=https://test-vault.vault.azure.net/", + "--set", "azure.redisHostName=redis.example.test", + "--set", "azure.tenantId=test-tenant", + "--set", "workers.coderAcpCopilot.enabled=true", + "--set", "workers.coderAcpClaudeCode.enabled=true", + ...overrides, + ], { encoding: "utf8" }); + expect(result.error).toBeUndefined(); + expect(result.status, result.stderr).toBe(0); + return parseAllDocuments(result.stdout).map((document) => document.toJSON()); +} + +function pod(manifests: Manifest[], component: string): PodSpec { + const spec = manifests.find((manifest) => + manifest.kind === "Deployment" && manifest.metadata.name === `scope-${component}`, + )?.spec?.template?.spec; + if (!spec) throw new Error(`Missing Deployment for ${component}`); + return spec; +} + +describe.skipIf(helmMissing)("Scope Helm worker sidecars (requires helm on PATH)", () => { + let manifests: Manifest[]; + beforeAll(() => { manifests = render(); }); + + it("keeps all resources in the custom namespace without changing application image tags", () => { + expect(manifests.every((manifest) => manifest.metadata.namespace === "scope-benchmarks")).toBe(true); + expect(pod(manifests, "api").containers[0].image).toBe("ghcr.io/microsoft/scope-api:app-revision"); + }); + + for (const [component, key] of [ + ["coder-acp-copilot", "coderAcpCopilot"], + ["coder-acp-claude-code", "coderAcpClaudeCode"], + ]) { + it(`${component} binds the digest-pinned stdio gateway only to pod loopback`, () => { + const spec = pod(manifests, component); + const gateway = spec.initContainers?.find((container) => container.name === "mcp-gateway"); + expect(gateway?.image).toMatch(/^ghcr\.io\/mcpjungle\/mcpjungle@sha256:[a-f0-9]{64}$/); + expect(gateway?.command).toEqual(["/mcpjungle"]); + expect(gateway?.args).toEqual(["start", "--host", "127.0.0.1", "--port", "8080"]); + expect(spec.containers[0].env).toContainEqual({ + name: "MCP_GATEWAY_URL", value: "http://127.0.0.1:8080", + }); + expect(spec.serviceAccountName).toBe("scope-worker-workload-identity"); + expect(spec.volumes).toEqual([{ name: "workspace", emptyDir: {} }]); + for (const container of [gateway, spec.containers[0]]) { + expect(container?.volumeMounts).toEqual([{ name: "workspace", mountPath: "/workspace" }]); + } + }); + + it(`${component} gates native-sidecar startup on an in-container loopback health probe`, () => { + const gateway = pod(manifests, component).initContainers?.[0]; + expect(gateway?.restartPolicy).toBe("Always"); + expect(gateway?.startupProbe).toBeDefined(); + expect(gateway?.readinessProbe).toBeDefined(); + for (const probe of [gateway?.startupProbe, gateway?.readinessProbe]) { + expect(probe?.exec?.command).toEqual([ + "curl", "--fail", "--silent", "--show-error", "--max-time", "2", + "http://127.0.0.1:8080/health", + ]); + expect(probe).not.toHaveProperty("httpGet"); + expect(probe).not.toHaveProperty("tcpSocket"); + expect(probe?.timeoutSeconds).toBeGreaterThan(2); + expect(probe?.periodSeconds).toBeGreaterThan(0); + expect(probe?.failureThreshold).toBeGreaterThan(1); + } + }); + + it(`${component} still supports disabling the MCP sidecar`, () => { + const spec = pod(render("--set", `workers.${key}.mcpGateway.enabled=false`), component); + expect(spec.initContainers).toBeUndefined(); + expect(spec.containers[0].env?.some((entry) => entry.name === "MCP_GATEWAY_URL")).toBe(false); + }); + } +});