diff --git a/.github/workflows/test-helm-chart.yml b/.github/workflows/test-helm-chart.yml index 3bf0943..8a34cc8 100644 --- a/.github/workflows/test-helm-chart.yml +++ b/.github/workflows/test-helm-chart.yml @@ -26,6 +26,7 @@ jobs: - name: Run unit tests run: | python3 -m unittest discover -s tests -p 'test_*.py' + node --test tests/test_loop_runtime_tls.cjs helm unittest braintrust lint-test: diff --git a/README.md b/README.md index 68009db..47e732c 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,17 @@ See the [Braintrust Helm Chart](./braintrust/README.md) for more details. GKE Autopilot is the preferred solution for new Braintrust deployments. GKE Standard is supported when customer requirements prevent Autopilot use. +## Loop Runtime + +On GKE, set `enable_loop_runtime = true` in the +[public GCP Terraform module](https://github.com/braintrustdata/terraform-google-braintrust-data-plane#loop-runtime). +Its infrastructure apply installs isolated workers and generates persistent TLS +in Secret Manager. Pass the `loop_runtime_helm_values_yaml` output after your +existing Helm values. The runtime reads its client bundle through Workload +Identity; no setup module, worker provider aliases or certificate files are +required. The GKE app module consumes the same configuration automatically. +See the [Loop setup guide](braintrust/examples/gke-loop-runtime). + ## GKE Standard node pool changes The [Standard example](braintrust/examples/google-standard/values.yaml) uses stable workload selectors and enables optional API and Brainstore disruption budgets. diff --git a/braintrust/examples/gke-loop-runtime/README.md b/braintrust/examples/gke-loop-runtime/README.md index 5a509c2..8ce061c 100644 --- a/braintrust/examples/gke-loop-runtime/README.md +++ b/braintrust/examples/gke-loop-runtime/README.md @@ -1,8 +1,59 @@ # Loop Runtime on GKE -Loop Runtime runs in the primary GKE cluster. Its sandboxes run on Sandbox -Service workers in a separate isolated cluster. Both clusters come from the -GCP Terraform module with: +Set `enable_loop_runtime = true` in the +[GCP data-plane module](https://github.com/braintrustdata/terraform-google-braintrust-data-plane#loop-runtime-infrastructure) +and apply infrastructure first. Loop Runtime stays in the primary cluster; +Sandbox Service workers run in a separate isolated cluster. The primary keeps +its existing Autopilot or Standard mode. + +## Helm-managed primary release + +The infrastructure apply installs workers, generates separate server and client +CAs, and retains their bundles in Secret Manager. It waits for worker installation +to succeed. Later applies reuse the bundles. Export the resulting configuration +and pass it after your existing Helm values: + +```sh +terraform output -raw loop_runtime_helm_values_yaml > loop-values.yaml +helm upgrade --install braintrust oci://public.ecr.aws/braintrust/helm/braintrust \ + --namespace braintrust --create-namespace --version \ + --reset-then-reuse-values --values \ + --values loop-values.yaml --wait +``` + +Use a chart that supports `loopRuntime.sandbox.clientTlsSecret`. The overlay +contains a secret reference, runtime identity, worker version and connection +settings. Generated TLS keys are absent from Terraform state and Helm values. +At Pod startup, an init container uses Workload Identity to fetch only the client +bundle and writes it into an in-memory volume mounted read-only by the runtime. +The identity has no access to the server bundle or CA private keys. +No separate setup Terraform root, worker provider aliases or TLS generation is +required. Set worker sizing, version and Helm overrides through infrastructure's +optional `loop_runtime_options`. + +Deploy compatible API, Brainstore and routed AI Gateway versions first. Keep the +generated runtime/worker version compatible with those services. For a Standard +primary cluster, retain your `loopRuntime.nodeSelector` override for its services +pool. Explicit values after `--reset-then-reuse-values` replace retained settings. + +## Terraform-managed primary release + +The [GKE app module](https://github.com/braintrustdata/terraform-google-braintrust-gke-app#managed-loop-runtime) +passes the same configuration to its primary Helm release automatically: + +```hcl +loop_runtime = try(data.terraform_remote_state.infra.outputs.loop_runtime, null) +``` + +Apply infrastructure, then the app root. There is no separate app enable flag. +See its [remote-state example](https://github.com/braintrustdata/terraform-google-braintrust-gke-app/tree/main/examples/remote-state-app-root). +The full app module is optional for Helm installations. + +## Custom worker installations + +These optional steps are for installations that manage the worker release and +TLS themselves. Ordinary Terraform and Helm deployments use the automatic path +above. Provision standalone workers with the GCP infrastructure module: ```hcl gke_isolated_workers = { @@ -59,9 +110,9 @@ or at those limits. ## Filesystem retention -Retention is off unless the overlay is applied. Keep the worker chart, worker image -and Loop Runtime image compatible. Terraform selects the worker package from -`loopRuntime.sandboxServiceChart` in the chosen Braintrust Helm release. +The automatic infrastructure bootstrap enables filesystem retention and supplies +the checkpoint store. The following overlay steps apply only to custom worker +installations. Keep the worker chart, worker image and Loop Runtime compatible. Apply the GCP checkpoint-storage update first, then copy `gke_isolated_workers.checkpoint_store` into `sandbox-service-retention.yaml`. diff --git a/braintrust/files/loop-runtime-tls.js b/braintrust/files/loop-runtime-tls.js new file mode 100644 index 0000000..7216c06 --- /dev/null +++ b/braintrust/files/loop-runtime-tls.js @@ -0,0 +1,55 @@ +const fs = require('node:fs'); +const path = require('node:path'); +const { randomUUID } = require('node:crypto'); + +async function request(fetchImpl, url, options) { + for (let attempt = 0; attempt < 12; attempt++) { + const response = await fetchImpl(url, { ...options, signal: AbortSignal.timeout(10000) }); + if (response.ok) return response; + if (![401, 403, 429, 500, 502, 503, 504].includes(response.status) || attempt === 11) { + throw new Error(`TLS credential request failed (${response.status})`); + } + await new Promise(resolve => setTimeout(resolve, Math.min(1000 * 2 ** attempt, 10000))); + } +} + +async function installTls(secret, directory, fetchImpl = fetch) { + if (typeof secret !== 'string' || !/^projects\/[A-Za-z0-9.:-]+\/secrets\/[A-Za-z0-9_-]+\/versions\/(latest|[0-9]+)$/.test(secret)) { + throw new Error('Invalid sandbox TLS secret reference'); + } + const metadata = await request(fetchImpl, + 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token', + { headers: { 'Metadata-Flavor': 'Google' } }); + let token; + try { token = (await metadata.json()).access_token; } catch { throw new Error('Invalid Workload Identity response'); } + if (typeof token !== 'string' || !token) throw new Error('Invalid Workload Identity response'); + const response = await request(fetchImpl, `https://secretmanager.googleapis.com/v1/${secret}:access`, + { headers: { Authorization: `Bearer ${token}` } }); + let bundle; + try { + const payload = await response.json(); + bundle = JSON.parse(Buffer.from(payload.payload.data, 'base64').toString('utf8')); + } catch { throw new Error('Invalid sandbox TLS bundle'); } + if (!bundle || typeof bundle !== 'object' || Array.isArray(bundle) || + !['cert', 'key', 'ca_cert'].every(key => typeof bundle[key] === 'string' && bundle[key].trim())) { + throw new Error('Invalid sandbox TLS bundle'); + } + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + for (const [file, field] of Object.entries({ 'client.pem': 'cert', 'client.key': 'key', 'server-ca.pem': 'ca_cert' })) { + const temporary = path.join(directory, `.${file}.${randomUUID()}`); + try { + fs.writeFileSync(temporary, bundle[field], { mode: 0o400 }); + fs.renameSync(temporary, path.join(directory, file)); + } finally { + if (fs.existsSync(temporary)) fs.unlinkSync(temporary); + } + } +} + +module.exports = { installTls }; +if (process.env.SANDBOX_TLS_BOOTSTRAP === '1') { + installTls(process.env.SANDBOX_TLS_SECRET, '/etc/sandbox-tls').catch(() => { + console.error('Sandbox TLS initialization failed; check Workload Identity and the referenced Secret Manager version'); + process.exitCode = 1; + }); +} diff --git a/braintrust/templates/_helpers.tpl b/braintrust/templates/_helpers.tpl index 6b35d51..458e4a6 100644 --- a/braintrust/templates/_helpers.tpl +++ b/braintrust/templates/_helpers.tpl @@ -184,6 +184,13 @@ predates Loop Runtime have no loopRuntime map, which means disabled. {{- fail (printf "loopRuntime.sandbox.%s must be a positive integer" $field) -}} {{- end -}} {{- end -}} +{{- $secret := index $sandbox "clientTlsSecret" -}} +{{- if and (not (kindIs "invalid" $secret)) (not (kindIs "string" $secret)) -}} +{{- fail "loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty" -}} +{{- end -}} +{{- if and $secret (not (regexMatch "^projects/[A-Za-z0-9.:-]+/secrets/[A-Za-z0-9_-]+/versions/(latest|[0-9]+)$" $secret)) -}} +{{- fail "loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty" -}} +{{- end -}} {{- $egress := $sandbox.egressGateway | default dict -}} {{- $_ := required "objectStorage.google.brainstoreBucket is required" .Values.objectStorage.google.brainstoreBucket -}} {{- $_ := required "objectStorage.google.apiBucket is required" .Values.objectStorage.google.apiBucket -}} diff --git a/braintrust/templates/loop-runtime-deployment.yaml b/braintrust/templates/loop-runtime-deployment.yaml index 659ad4c..b05af3e 100644 --- a/braintrust/templates/loop-runtime-deployment.yaml +++ b/braintrust/templates/loop-runtime-deployment.yaml @@ -68,10 +68,41 @@ spec: affinity: {{- toYaml . | nindent 8 }} {{- end }} - {{- if $ordering.enabled }} + {{- if or $ordering.enabled .Values.loopRuntime.sandbox.clientTlsSecret }} initContainers: + {{- if $ordering.enabled }} {{- include "braintrust.migrations.initContainer" . | nindent 8 }} {{- include "braintrust.brainstoreStartupGate.initContainer" (dict "root" . "api" .Values.api) | nindent 8 }} + {{- end }} + {{- with .Values.loopRuntime.sandbox.clientTlsSecret }} + - name: sandbox-tls-init + image: "{{ $.Values.loopRuntime.image.repository }}:{{ $.Values.loopRuntime.image.tag }}" + imagePullPolicy: {{ $.Values.loopRuntime.image.pullPolicy }} + command: ["node"] + args: + - -e + - | + {{- $.Files.Get "files/loop-runtime-tls.js" | nindent 14 }} + env: + - name: SANDBOX_TLS_BOOTSTRAP + value: "1" + - name: SANDBOX_TLS_SECRET + value: {{ . | quote }} + resources: + requests: + cpu: 25m + memory: 32Mi + limits: + cpu: 100m + memory: 128Mi + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: ["ALL"] + volumeMounts: + - name: sandbox-tls + mountPath: /etc/sandbox-tls + {{- end }} {{- end }} containers: - name: loop-runtime @@ -169,10 +200,15 @@ spec: - name: cache emptyDir: sizeLimit: 6Gi - # Created by examples/gke-loop-runtime/create-sandbox-tls.sh. - name: sandbox-tls + {{- if .Values.loopRuntime.sandbox.clientTlsSecret }} + emptyDir: + medium: Memory + sizeLimit: 1Mi + {{- else }} secret: secretName: sandbox-client-tls + {{- end }} {{- with .Values.loopRuntime.extraVolumes }} {{- toYaml . | nindent 8 }} {{- end }} diff --git a/braintrust/tests/loop-runtime-secret-reference-ordering_test.yaml b/braintrust/tests/loop-runtime-secret-reference-ordering_test.yaml new file mode 100644 index 0000000..e2fbc9c --- /dev/null +++ b/braintrust/tests/loop-runtime-secret-reference-ordering_test.yaml @@ -0,0 +1,17 @@ +suite: Native TLS loading with startup ordering +tests: + - it: loads credentials after the existing migration and Brainstore checks + template: loop-runtime-deployment.yaml + values: + - __fixtures__/base-values.yaml + - __fixtures__/loop-runtime-values.yaml + set: + deploymentOrdering.enabled: true + loopRuntime.sandbox.clientTlsSecret: projects/test-project/secrets/loop-client-tls/versions/17 + asserts: + - equal: + path: spec.template.spec.initContainers[2].name + value: sandbox-tls-init + - equal: + path: spec.template.spec.initContainers[2].env[1].value + value: projects/test-project/secrets/loop-client-tls/versions/17 diff --git a/braintrust/tests/loop-runtime-secret-reference-validation_test.yaml b/braintrust/tests/loop-runtime-secret-reference-validation_test.yaml new file mode 100644 index 0000000..f3163b1 --- /dev/null +++ b/braintrust/tests/loop-runtime-secret-reference-validation_test.yaml @@ -0,0 +1,77 @@ +suite: Loop secret reference validation +templates: + - loop-runtime-configmap.yaml +tests: + - it: rejects a secret reference containing integer + template: loop-runtime-configmap.yaml + values: &values + - __fixtures__/base-values.yaml + - __fixtures__/loop-runtime-values.yaml + set: + loopRuntime.sandbox.clientTlsSecret: 0 + asserts: + - failedTemplate: + errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty + + - it: rejects a secret reference containing boolean + template: loop-runtime-configmap.yaml + values: *values + set: + loopRuntime.sandbox.clientTlsSecret: false + asserts: + - failedTemplate: + errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty + + - it: rejects a secret reference containing map + template: loop-runtime-configmap.yaml + values: *values + set: + loopRuntime.sandbox.clientTlsSecret: {} + asserts: + - failedTemplate: + errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty + + - it: rejects a secret reference containing list + template: loop-runtime-configmap.yaml + values: *values + set: + loopRuntime.sandbox.clientTlsSecret: [] + asserts: + - failedTemplate: + errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty + + - it: rejects a secret reference containing URL + template: loop-runtime-configmap.yaml + values: *values + set: + loopRuntime.sandbox.clientTlsSecret: https://example.com/tls + asserts: + - failedTemplate: + errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty + + - it: rejects a secret reference containing path traversal + template: loop-runtime-configmap.yaml + values: *values + set: + loopRuntime.sandbox.clientTlsSecret: projects/p/secrets/s/versions/../other + asserts: + - failedTemplate: + errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty + + - it: rejects a secret reference containing missing version + template: loop-runtime-configmap.yaml + values: *values + set: + loopRuntime.sandbox.clientTlsSecret: projects/p/secrets/s + asserts: + - failedTemplate: + errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty + + - it: rejects a secret reference containing query string + template: loop-runtime-configmap.yaml + values: *values + set: + loopRuntime.sandbox.clientTlsSecret: projects/p/secrets/s/versions/latest?token=value + asserts: + - failedTemplate: + errorMessage: loopRuntime.sandbox.clientTlsSecret must be a Secret Manager version reference or empty diff --git a/braintrust/tests/loop-runtime-secret-reference_test.yaml b/braintrust/tests/loop-runtime-secret-reference_test.yaml new file mode 100644 index 0000000..62ca2d7 --- /dev/null +++ b/braintrust/tests/loop-runtime-secret-reference_test.yaml @@ -0,0 +1,253 @@ +suite: Loop TLS Secret Manager references +templates: + - loop-runtime-deployment.yaml + - loop-runtime-configmap.yaml +tests: + - it: loads native secret credentials into memory without a primary Kubernetes Secret + template: loop-runtime-deployment.yaml + values: &values + - __fixtures__/base-values.yaml + - __fixtures__/loop-runtime-values.yaml + set: &native + deploymentOrdering.enabled: false + loopRuntime.sandbox.clientTlsSecret: projects/test-project/secrets/loop-client-tls/versions/latest + asserts: + - equal: + path: spec.template.spec.initContainers[0].name + value: sandbox-tls-init + - equal: + path: spec.template.spec.initContainers[0].image + value: test/loop-runtime:v1.0.0 + - equal: + path: spec.template.spec.initContainers[0].command + value: [node] + - equal: + path: spec.template.spec.initContainers[0].env[1] + value: + name: SANDBOX_TLS_SECRET + value: projects/test-project/secrets/loop-client-tls/versions/latest + - matchRegex: + path: spec.template.spec.initContainers[0].args[1] + pattern: metadata.google.internal + - matchRegex: + path: spec.template.spec.initContainers[0].args[1] + pattern: secretmanager.googleapis.com + - contains: + path: spec.template.spec.volumes + content: + name: sandbox-tls + emptyDir: + medium: Memory + sizeLimit: 1Mi + - contains: + path: spec.template.spec.containers[0].volumeMounts + content: + name: sandbox-tls + mountPath: /etc/sandbox-tls + readOnly: true + + - it: retains an external Kubernetes Secret when the reference is missing + template: loop-runtime-deployment.yaml + values: *values + set: + deploymentOrdering.enabled: false + asserts: &external + - notExists: + path: spec.template.spec.initContainers + - contains: + path: spec.template.spec.volumes + content: + name: sandbox-tls + secret: + secretName: sandbox-client-tls + + - it: retains external TLS with a empty secret reference + template: loop-runtime-deployment.yaml + values: *values + set: + deploymentOrdering.enabled: false + loopRuntime.sandbox.clientTlsSecret: "" + asserts: *external + + - it: retains external TLS with a null secret reference + template: loop-runtime-deployment.yaml + values: *values + set: + deploymentOrdering.enabled: false + loopRuntime.sandbox.clientTlsSecret: null + asserts: *external + + - it: ignores secret loading when Loop is disabled on google + template: loop-runtime-deployment.yaml + values: *values + set: + cloud: google + loopRuntime.enabled: false + loopRuntime.sandbox.clientTlsSecret: projects/test-project/secrets/loop-client-tls/versions/latest + asserts: + - hasDocuments: + count: 0 + + - it: ignores secret loading when Loop is disabled on aws + template: loop-runtime-deployment.yaml + values: *values + set: + cloud: aws + loopRuntime.enabled: false + loopRuntime.sandbox.clientTlsSecret: projects/test-project/secrets/loop-client-tls/versions/latest + asserts: + - hasDocuments: + count: 0 + + - it: ignores secret loading when Loop is disabled on azure + template: loop-runtime-deployment.yaml + values: *values + set: + cloud: azure + loopRuntime.enabled: false + loopRuntime.sandbox.clientTlsSecret: projects/test-project/secrets/loop-client-tls/versions/latest + asserts: + - hasDocuments: + count: 0 + + - it: uses the selected runtime image for credential loading with tag v2.24.0 + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.image.tag: "v2.24.0" + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: test/loop-runtime:v2.24.0 + - equal: + path: spec.template.spec.containers[0].image + value: test/loop-runtime:v2.24.0 + + - it: uses the selected runtime image for credential loading with tag 2.24.0 + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.image.tag: "2.24.0" + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: test/loop-runtime:2.24.0 + - equal: + path: spec.template.spec.containers[0].image + value: test/loop-runtime:2.24.0 + + - it: uses the selected runtime image for credential loading with tag abcdef0123456789abcdef0123456789abcdef0123 + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.image.tag: "abcdef0123456789abcdef0123456789abcdef0123" + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: test/loop-runtime:abcdef0123456789abcdef0123456789abcdef0123 + - equal: + path: spec.template.spec.containers[0].image + value: test/loop-runtime:abcdef0123456789abcdef0123456789abcdef0123 + + - it: uses the selected runtime image for credential loading with tag abc1234 + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.image.tag: "abc1234" + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: test/loop-runtime:abc1234 + - equal: + path: spec.template.spec.containers[0].image + value: test/loop-runtime:abc1234 + + - it: uses the selected runtime image for credential loading with tag 1234567 + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.image.tag: "1234567" + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: test/loop-runtime:1234567 + - equal: + path: spec.template.spec.containers[0].image + value: test/loop-runtime:1234567 + + - it: uses the selected runtime image for credential loading with tag v2.24.0-rc.1 + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.image.tag: "v2.24.0-rc.1" + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: test/loop-runtime:v2.24.0-rc.1 + - equal: + path: spec.template.spec.containers[0].image + value: test/loop-runtime:v2.24.0-rc.1 + + - it: uses the selected runtime image for credential loading with tag custom-build + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.image.tag: "custom-build" + asserts: + - equal: + path: spec.template.spec.initContainers[0].image + value: test/loop-runtime:custom-build + - equal: + path: spec.template.spec.containers[0].image + value: test/loop-runtime:custom-build + + - it: preserves null replicas with native TLS loading + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.replicas: null + asserts: + - equal: + path: spec.replicas + value: 1 + + - it: preserves empty replicas with native TLS loading + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.replicas: "" + asserts: + - equal: + path: spec.replicas + value: 1 + + - it: preserves zero replicas with native TLS loading + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.replicas: 0 + asserts: + - equal: + path: spec.replicas + value: 0 + + - it: supports a pinned numeric secret version + template: loop-runtime-deployment.yaml + values: *values + set: + <<: *native + loopRuntime.sandbox.clientTlsSecret: projects/123456789012/secrets/loop-client-tls/versions/1 + asserts: + - equal: + path: spec.template.spec.initContainers[0].env[1].value + value: projects/123456789012/secrets/loop-client-tls/versions/1 diff --git a/braintrust/values.yaml b/braintrust/values.yaml index 9d55d3d..70a181a 100644 --- a/braintrust/values.yaml +++ b/braintrust/values.yaml @@ -289,8 +289,9 @@ api: extraContainers: [] extraVolumes: [] -# Loop Runtime (optional, cloud: google only). Sandboxes run on Sandbox Service -# workers in a separate GKE cluster; see examples/gke-loop-runtime. +# Loop Runtime (optional, cloud: google only). The public GCP Terraform + GKE app +# modules manage workers, TLS, and these connection values when enable_loop_runtime +# is true. See examples/gke-loop-runtime; direct Helm setup is documented there too. loopRuntime: enabled: false # Allow Braintrust staff sysadmins to inspect and terminate sandboxes. @@ -357,6 +358,9 @@ loopRuntime: successThreshold: 1 # Values come from Terraform output gke_isolated_workers. sandbox: + # Secret Manager version populated by the automatic infrastructure bootstrap. + # Empty uses an existing sandbox-client-tls Kubernetes Secret. + clientTlsSecret: "" # discovery.endpoint dnsUrl: "" # loop_egress.address, loop_egress.source_ranges, and loop_egress.url diff --git a/test.sh b/test.sh index 75159a6..e4f297f 100755 --- a/test.sh +++ b/test.sh @@ -15,6 +15,7 @@ CHART_DIR="braintrust" # The init-container helper deliberately uses only the Python standard library. python3 -m unittest discover -s tests -p 'test_*.py' +node --test tests/test_loop_runtime_tls.cjs # Check if helm is installed if ! command -v helm &> /dev/null; then diff --git a/tests/test_loop_runtime_tls.cjs b/tests/test_loop_runtime_tls.cjs new file mode 100644 index 0000000..5f37996 --- /dev/null +++ b/tests/test_loop_runtime_tls.cjs @@ -0,0 +1,66 @@ +const { test } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { installTls } = require('../braintrust/files/loop-runtime-tls.js'); +const reference = 'projects/test-project/secrets/loop-client-tls/versions/latest'; +const valid = { cert: 'test-client-cert', key: 'test-client-key', ca_cert: 'test-server-ca' }; +function responses(bundle, calls = []) { + return async (url, options) => { + calls.push({ url, options }); + if (url.startsWith('http://metadata.google.internal/')) return { ok: true, json: async () => ({ access_token: 'test-token' }) }; + return { ok: true, json: async () => ({ payload: { data: Buffer.from(JSON.stringify(bundle)).toString('base64') } }) }; + }; +} +function directory(t) { + const result = fs.mkdtempSync(path.join(os.tmpdir(), 'loop-tls-test-')); + t.after(() => fs.rmSync(result, { recursive: true, force: true })); + return result; +} +test('loads only the referenced client bundle using Workload Identity', async t => { + const root = directory(t), calls = []; + await installTls(reference, root, responses(valid, calls)); + assert.equal(calls.length, 2); + assert.equal(calls[0].options.headers['Metadata-Flavor'], 'Google'); + assert.equal(calls[1].url, `https://secretmanager.googleapis.com/v1/${reference}:access`); + assert.equal(calls[1].options.headers.Authorization, 'Bearer test-token'); + for (const [file, field] of Object.entries({ 'client.pem': 'cert', 'client.key': 'key', 'server-ca.pem': 'ca_cert' })) { + assert.equal(fs.readFileSync(path.join(root, file), 'utf8'), valid[field]); + assert.equal(fs.statSync(path.join(root, file)).mode & 0o777, 0o400); + } + assert.deepEqual(fs.readdirSync(root).sort(), ['client.key', 'client.pem', 'server-ca.pem']); +}); +test('can rerun after read-only credential files were created', async t => { + const root = directory(t); + await installTls(reference, root, responses(valid)); + await installTls(reference, root, responses({ ...valid, key: 'replacement-client-key' })); + assert.equal(fs.readFileSync(path.join(root, 'client.key'), 'utf8'), 'replacement-client-key'); + assert.equal(fs.statSync(path.join(root, 'client.key')).mode & 0o777, 0o400); +}); +test('invalid references make no credential requests', async t => { + const root = directory(t); + for (const ref of [undefined, '', 'https://example.com/secret', 'projects/p/secrets/s/versions/../other', 'projects/p/secrets/s/versions/latest?x=1']) { + await assert.rejects(installTls(ref, root, () => { throw new Error('must not fetch'); }), /Invalid sandbox TLS secret reference/); + } +}); +test('malformed bundles cannot create partial credential files', async t => { + const root = directory(t); + for (const bad of [null, [], {}, { ...valid, cert: '' }, { ...valid, key: null }, { ...valid, ca_cert: 123 }, { ...valid, key: ' ' }]) { + await assert.rejects(installTls(reference, root, responses(bad)), /Invalid sandbox TLS bundle/); + assert.deepEqual(fs.readdirSync(root), []); + } +}); +test('retries IAM propagation and fails without exposing payloads', async t => { + const root = directory(t); + t.mock.method(globalThis, 'setTimeout', callback => { queueMicrotask(callback); return {}; }); + let attempts = 0; + const fetchImpl = async url => { + if (url.startsWith('http://metadata.')) return { ok: true, json: async () => ({ access_token: 'test-token' }) }; + attempts++; + return { ok: false, status: 403, json: async () => ({ private: 'must not appear' }) }; + }; + await assert.rejects(installTls(reference, root, fetchImpl), { message: 'TLS credential request failed (403)' }); + assert.equal(attempts, 12); + assert.deepEqual(fs.readdirSync(root), []); +});