diff --git a/.changeset/deploy-image-override-multi-tenant-warning.md b/.changeset/deploy-image-override-multi-tenant-warning.md new file mode 100644 index 00000000000..0fed0552c36 --- /dev/null +++ b/.changeset/deploy-image-override-multi-tenant-warning.md @@ -0,0 +1,7 @@ +--- +"trigger.dev": minor +--- + +webapp: clarify DEPLOY_IMAGE_OVERRIDE is single-tenant only + +The `DEPLOY_IMAGE_OVERRIDE` env var forces every deployment finalized by the webapp to use the configured image, ignoring the registry config / per-deployment image computation. Useful for self-hosted single-tenant installs where CI builds one canonical tasks image; dangerous on cloud / multi-tenant where deployments come from untrusted user code. No behavior change — just adds a strong warning docstring to `apps/webapp/app/env.server.ts` calling out the multi-tenant foot-gun. diff --git a/.github/workflows/changesets-pr.yml b/.github/workflows/changesets-pr.yml index 851c5341dbf..ee9547832d5 100644 --- a/.github/workflows/changesets-pr.yml +++ b/.github/workflows/changesets-pr.yml @@ -18,7 +18,7 @@ concurrency: jobs: release-pr: name: Create Release PR - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: write pull-requests: write diff --git a/.github/workflows/check-review-md.yml b/.github/workflows/check-review-md.yml index 06f0d2d82c4..fa69c55b3fc 100644 --- a/.github/workflows/check-review-md.yml +++ b/.github/workflows/check-review-md.yml @@ -20,7 +20,7 @@ jobs: vars.ENABLE_CLAUDE_CODE != 'false' && github.event.pull_request.draft == false && github.event.pull_request.head.repo.full_name == github.repository - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: read pull-requests: write diff --git a/.github/workflows/claude-md-audit.yml b/.github/workflows/claude-md-audit.yml index aa62444c9df..fb5c581b616 100644 --- a/.github/workflows/claude-md-audit.yml +++ b/.github/workflows/claude-md-audit.yml @@ -21,7 +21,7 @@ jobs: vars.ENABLE_CLAUDE_CODE != 'false' && github.event.pull_request.draft == false && github.event.pull_request.head.repo.full_name == github.repository - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: read pull-requests: write diff --git a/.github/workflows/claude.yml b/.github/workflows/claude.yml index 7a278672a24..8b0c019e632 100644 --- a/.github/workflows/claude.yml +++ b/.github/workflows/claude.yml @@ -22,7 +22,7 @@ jobs: (github.event_name == 'pull_request_review' && contains(github.event.review.body, '@claude')) || (github.event_name == 'issues' && (contains(github.event.issue.body, '@claude') || contains(github.event.issue.title, '@claude'))) ) - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: write pull-requests: write diff --git a/.github/workflows/code-quality.yml b/.github/workflows/code-quality.yml index 48575827b39..1d488dd67ba 100644 --- a/.github/workflows/code-quality.yml +++ b/.github/workflows/code-quality.yml @@ -8,7 +8,7 @@ permissions: jobs: code-quality: - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo diff --git a/.github/workflows/dependabot-critical-alerts.yml b/.github/workflows/dependabot-critical-alerts.yml index 62d68c30023..9a61387324d 100644 --- a/.github/workflows/dependabot-critical-alerts.yml +++ b/.github/workflows/dependabot-critical-alerts.yml @@ -29,7 +29,7 @@ jobs: # the Dependabot alert/summary notifiers — e.g. forks/mirrors that lack the # DEPENDABOT_ALERTS_TOKEN / SLACK_BOT_TOKEN secrets. Defaults to enabled. if: ${{ vars.ENABLE_DEPENDABOT_ALERTS != 'false' }} - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest environment: dependabot-summary env: SEVERITY: ${{ inputs.severity || 'critical' }} diff --git a/.github/workflows/dependabot-weekly-summary.yml b/.github/workflows/dependabot-weekly-summary.yml index fc9eaebcb94..d7b489d55da 100644 --- a/.github/workflows/dependabot-weekly-summary.yml +++ b/.github/workflows/dependabot-weekly-summary.yml @@ -23,7 +23,7 @@ jobs: # the Dependabot alert/summary notifiers — e.g. forks/mirrors that lack the # DEPENDABOT_ALERTS_TOKEN / SLACK_BOT_TOKEN secrets. Defaults to enabled. if: ${{ vars.ENABLE_DEPENDABOT_ALERTS != 'false' }} - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest environment: dependabot-summary env: # Severities surface in the actions list when their remaining TTR drops diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml index 460a21c2021..9e7309d5f98 100644 --- a/.github/workflows/docs.yml +++ b/.github/workflows/docs.yml @@ -20,7 +20,7 @@ permissions: jobs: check-broken-links: - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest defaults: run: working-directory: ./docs diff --git a/.github/workflows/e2e-webapp-auth-full.yml b/.github/workflows/e2e-webapp-auth-full.yml index e88429a3443..d467dbe65fc 100644 --- a/.github/workflows/e2e-webapp-auth-full.yml +++ b/.github/workflows/e2e-webapp-auth-full.yml @@ -37,7 +37,7 @@ on: jobs: e2eAuthFull: name: "🛡️ E2E Auth Tests (full)" - runs-on: warp-ubuntu-latest-x64-8x + runs-on: ubuntu-latest timeout-minutes: 30 env: DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} diff --git a/.github/workflows/e2e-webapp.yml b/.github/workflows/e2e-webapp.yml index 1931cfdd336..ca21dce0023 100644 --- a/.github/workflows/e2e-webapp.yml +++ b/.github/workflows/e2e-webapp.yml @@ -14,7 +14,7 @@ on: jobs: e2eTests: name: "🧪 E2E Tests: Webapp" - runs-on: warp-ubuntu-latest-x64-16x + runs-on: ubuntu-latest timeout-minutes: 20 env: DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 4584ea69c13..9f3367ffc1d 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -20,7 +20,7 @@ jobs: strategy: fail-fast: false matrix: - os: [warp-ubuntu-latest-x64-4x, warp-windows-latest-x64-8x] + os: [ubuntu-latest, windows-latest] package-manager: ["npm", "pnpm"] steps: - name: ⬇️ Checkout repo diff --git a/.github/workflows/helm-prerelease.yml b/.github/workflows/helm-prerelease.yml index 7d49868eeaf..40b18c03c80 100644 --- a/.github/workflows/helm-prerelease.yml +++ b/.github/workflows/helm-prerelease.yml @@ -24,11 +24,14 @@ concurrency: env: REGISTRY: ghcr.io - CHART_NAME: trigger + # Published OCI chart name. Distinct from upstream `trigger` so the + # GovSignals fork's vendored chart doesn't collide with the upstream + # package under ghcr.io/govsignals/charts/trigger. + CHART_NAME: vendored-upstream-trigger jobs: lint-and-test: - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: read steps: @@ -79,7 +82,7 @@ jobs: ((github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository) || github.event_name == 'push' || github.event_name == 'workflow_dispatch') - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: read packages: write @@ -90,6 +93,12 @@ jobs: with: persist-credentials: false + - name: Resolve repo owner (lowercase) + id: owner + run: | + OWNER="${{ github.repository_owner }}" + echo "lc=${OWNER,,}" >> "$GITHUB_OUTPUT" + - name: Set up Helm uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5.0.1 with: @@ -132,9 +141,10 @@ jobs: echo "version=$PRERELEASE_VERSION" >> "$GITHUB_OUTPUT" echo "Prerelease version: $PRERELEASE_VERSION" - - name: Update Chart.yaml with prerelease version + - name: Update Chart.yaml with prerelease version and rename chart run: | sed -i "s/^version:.*/version: ${STEPS_VERSION_OUTPUTS_VERSION}/" ./hosting/k8s/helm/Chart.yaml + sed -i "s/^name:.*/name: ${{ env.CHART_NAME }}/" ./hosting/k8s/helm/Chart.yaml env: STEPS_VERSION_OUTPUTS_VERSION: ${{ steps.version.outputs.version }} @@ -155,7 +165,7 @@ jobs: CHART_PACKAGE="/tmp/${{ env.CHART_NAME }}-${VERSION}.tgz" # Push to GHCR OCI registry - helm push "$CHART_PACKAGE" "oci://${{ env.REGISTRY }}/${{ github.repository_owner }}/charts" + helm push "$CHART_PACKAGE" "oci://${{ env.REGISTRY }}/${{ steps.owner.outputs.lc }}/charts" env: STEPS_VERSION_OUTPUTS_VERSION: ${{ steps.version.outputs.version }} @@ -169,7 +179,7 @@ jobs: echo "**Install:**" echo '```bash' echo "helm upgrade --install trigger \\" - echo " oci://${{ env.REGISTRY }}/${{ github.repository_owner }}/charts/${{ env.CHART_NAME }} \\" + echo " oci://${{ env.REGISTRY }}/${{ steps.owner.outputs.lc }}/charts/${{ env.CHART_NAME }} \\" echo " --version \"${STEPS_VERSION_OUTPUTS_VERSION}\"" echo '```' } >> "$GITHUB_STEP_SUMMARY" @@ -199,7 +209,7 @@ jobs: **Install:** ```bash helm upgrade --install trigger \ - oci://ghcr.io/${{ github.repository_owner }}/charts/trigger \ + oci://ghcr.io/${{ steps.owner.outputs.lc }}/charts/${{ env.CHART_NAME }} \ --version "${{ steps.version.outputs.version }}" ``` diff --git a/.github/workflows/pr_checks.yml b/.github/workflows/pr_checks.yml index b0fbd6ac040..0e705f74e05 100644 --- a/.github/workflows/pr_checks.yml +++ b/.github/workflows/pr_checks.yml @@ -15,7 +15,7 @@ permissions: jobs: changes: name: Detect changes - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest outputs: code: ${{ steps.code_filter.outputs.code }} typecheck_self: ${{ steps.filter.outputs.typecheck_self }} @@ -175,7 +175,7 @@ jobs: - e2e - sdk-compat if: always() - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest steps: - name: Verify all checks run: | diff --git a/.github/workflows/preview-dispatch.yml b/.github/workflows/preview-dispatch.yml index ac0decfafa8..3f26c66cf33 100644 --- a/.github/workflows/preview-dispatch.yml +++ b/.github/workflows/preview-dispatch.yml @@ -20,7 +20,7 @@ permissions: {} jobs: dispatch: name: Dispatch preview-deploy to cloud - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest # label added -> create # new commit while labeled -> update # label removed / PR closed -> destroy diff --git a/.github/workflows/preview-packages.yml b/.github/workflows/preview-packages.yml index b5bdbb31347..dcc25d04475 100644 --- a/.github/workflows/preview-packages.yml +++ b/.github/workflows/preview-packages.yml @@ -42,7 +42,7 @@ permissions: jobs: publish: name: Build and publish previews - runs-on: warp-ubuntu-latest-x64-8x + runs-on: ubuntu-latest if: github.repository == 'triggerdotdev/trigger.dev' steps: - name: ⬇️ Checkout repo diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml index f664a9a2fd4..8a457c77dc4 100644 --- a/.github/workflows/publish-docs.yml +++ b/.github/workflows/publish-docs.yml @@ -15,7 +15,7 @@ concurrency: jobs: publish: - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest steps: - name: 📥 Checkout tagged commit uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 diff --git a/.github/workflows/publish-webapp.yml b/.github/workflows/publish-webapp.yml index 497cdfb8ed6..8d6dfe63a33 100644 --- a/.github/workflows/publish-webapp.yml +++ b/.github/workflows/publish-webapp.yml @@ -38,7 +38,7 @@ on: jobs: publish: - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest env: PRISMA_ENGINES_CHECKSUM_IGNORE_MISSING: 1 outputs: diff --git a/.github/workflows/publish-worker-v4.yml b/.github/workflows/publish-worker-v4.yml index 2dba27013b7..5595a1fd41b 100644 --- a/.github/workflows/publish-worker-v4.yml +++ b/.github/workflows/publish-worker-v4.yml @@ -32,7 +32,7 @@ permissions: jobs: # check-branch: - # runs-on: warp-ubuntu-latest-x64-2x + # runs-on: ubuntu-latest # steps: # - name: Fail if re2-prod-* is pushed from a non-main branch # if: startsWith(github.ref_name, 're2-prod-') && github.base_ref != 'main' @@ -44,7 +44,7 @@ jobs: strategy: matrix: package: [supervisor] - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest # Single-entry matrix, so these job outputs are unambiguous (consumed by the # scan-supervisor job in publish.yml). outputs: diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1b9e55c3b34..49d8f847faa 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -123,7 +123,7 @@ jobs: name: 📣 Dispatch main image needs: [publish-webapp] if: github.repository == (vars.MAIN_IMAGE_DISPATCH_REPO || 'triggerdotdev/trigger.dev') && github.event_name == 'push' && startsWith(github.ref_name, vars.MAIN_IMAGE_DISPATCH_REF_PREFIX || 'main') - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: {} steps: - name: Build dispatch payload diff --git a/.github/workflows/release-helm.yml b/.github/workflows/release-helm.yml index 0ce968ebc47..a81089041e8 100644 --- a/.github/workflows/release-helm.yml +++ b/.github/workflows/release-helm.yml @@ -19,11 +19,14 @@ on: env: REGISTRY: ghcr.io - CHART_NAME: trigger + # Published OCI chart name. Distinct from upstream `trigger` so the + # GovSignals fork's vendored chart doesn't collide with the upstream + # package under ghcr.io/govsignals/charts/trigger. + CHART_NAME: vendored-upstream-trigger jobs: lint-and-test: - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: read steps: @@ -70,7 +73,7 @@ jobs: # on the owner's charts namespace. Defaults to enabled; the lint-and-test # job above always runs regardless. if: ${{ vars.ENABLE_HELM_PRERELEASE != 'false' }} - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: write # for gh-release packages: write @@ -80,6 +83,12 @@ jobs: with: persist-credentials: false + - name: Resolve repo owner (lowercase) + id: owner + run: | + OWNER="${{ github.repository_owner }}" + echo "lc=${OWNER,,}" >> "$GITHUB_OUTPUT" + - name: Set up Helm uses: azure/setup-helm@9bc31f4ebc9c6b171d7bfbaa5d006ae7abdb4310 # v5.0.1 with: @@ -128,6 +137,10 @@ jobs: env: STEPS_VERSION_OUTPUTS_VERSION: ${{ steps.version.outputs.version }} + - name: Rename chart for vendored-upstream OCI publish + run: | + sed -i "s/^name:.*/name: ${{ env.CHART_NAME }}/" ./hosting/k8s/helm/Chart.yaml + - name: Package Helm Chart run: | helm package ./hosting/k8s/helm/ --destination /tmp/ @@ -138,7 +151,7 @@ jobs: CHART_PACKAGE="/tmp/${{ env.CHART_NAME }}-${VERSION}.tgz" # Push to GHCR OCI registry - helm push "$CHART_PACKAGE" "oci://${{ env.REGISTRY }}/${{ github.repository_owner }}/charts" + helm push "$CHART_PACKAGE" "oci://${{ env.REGISTRY }}/${{ steps.owner.outputs.lc }}/charts" env: STEPS_VERSION_OUTPUTS_VERSION: ${{ steps.version.outputs.version }} @@ -152,7 +165,7 @@ jobs: ### Installation ```bash helm upgrade --install trigger \ - oci://${{ env.REGISTRY }}/${{ github.repository_owner }}/charts/${{ env.CHART_NAME }} \ + oci://${{ env.REGISTRY }}/${{ steps.owner.outputs.lc }}/charts/${{ env.CHART_NAME }} \ --version "${{ steps.version.outputs.version }}" ``` diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5292903562e..809063722fd 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -226,7 +226,7 @@ jobs: name: 🔗 Update release Docker link needs: [release, publish-docker] if: needs.release.outputs.published == 'true' - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: write packages: read @@ -268,7 +268,7 @@ jobs: name: 📝 Dispatch changelog PR needs: [release, update-release] if: needs.release.outputs.published == 'true' && needs.release.outputs.is_prerelease != 'true' - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: {} steps: - uses: peter-evans/repository-dispatch@28959ce8df70de7be546dd1250a005dd32156697 # v4.0.1 diff --git a/.github/workflows/runops-guard.yml b/.github/workflows/runops-guard.yml index e496db2a93d..f35115b1da5 100644 --- a/.github/workflows/runops-guard.yml +++ b/.github/workflows/runops-guard.yml @@ -8,7 +8,7 @@ permissions: jobs: runops-guard: - runs-on: warp-ubuntu-latest-x64-16x + runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo diff --git a/.github/workflows/sdk-compat.yml b/.github/workflows/sdk-compat.yml index ddfb4731db1..c2468262ae4 100644 --- a/.github/workflows/sdk-compat.yml +++ b/.github/workflows/sdk-compat.yml @@ -13,7 +13,7 @@ jobs: strategy: fail-fast: false matrix: - os: [warp-ubuntu-latest-x64-4x] + os: [ubuntu-latest] node: ["20.20", "22.23", "24.18", "26.4"] steps: @@ -54,7 +54,7 @@ jobs: bun-compat: name: "Bun Runtime" - runs-on: warp-ubuntu-latest-x64-4x + runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 @@ -96,7 +96,7 @@ jobs: deno-compat: name: "Deno Runtime" - runs-on: warp-ubuntu-latest-x64-4x + runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 @@ -142,7 +142,7 @@ jobs: cloudflare-compat: name: "Cloudflare Workers" - runs-on: warp-ubuntu-latest-x64-4x + runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 diff --git a/.github/workflows/trivy-image.yml b/.github/workflows/trivy-image.yml index 4c85823f0d4..76140518ac6 100644 --- a/.github/workflows/trivy-image.yml +++ b/.github/workflows/trivy-image.yml @@ -33,7 +33,7 @@ concurrency: jobs: scan: name: Scan - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: read packages: read # pull the image from GHCR diff --git a/.github/workflows/typecheck.yml b/.github/workflows/typecheck.yml index d8521f3936a..8ac14dd6d4f 100644 --- a/.github/workflows/typecheck.yml +++ b/.github/workflows/typecheck.yml @@ -8,7 +8,7 @@ permissions: jobs: typecheck: - runs-on: warp-ubuntu-latest-x64-16x + runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo diff --git a/.github/workflows/unit-tests-internal.yml b/.github/workflows/unit-tests-internal.yml index 1a398af9c44..5095eaf8a4e 100644 --- a/.github/workflows/unit-tests-internal.yml +++ b/.github/workflows/unit-tests-internal.yml @@ -18,7 +18,7 @@ jobs: # (fileParallelism: false) and container-wait-bound, so 12 in-machine shard processes # fit comfortably in 32 vCPUs while paying the setup cost (install, prisma generate, # image pulls) once instead of 12 times. - runs-on: warp-ubuntu-latest-x64-32x + runs-on: ubuntu-latest env: DOCKERHUB_USERNAME: ${{ secrets.DOCKERHUB_USERNAME }} SHARD_TOTAL: 12 diff --git a/.github/workflows/unit-tests-packages.yml b/.github/workflows/unit-tests-packages.yml index 465174fb95d..9a1e65537f4 100644 --- a/.github/workflows/unit-tests-packages.yml +++ b/.github/workflows/unit-tests-packages.yml @@ -14,7 +14,7 @@ on: jobs: unitTests: name: "🧪 Unit Tests: Packages" - runs-on: warp-ubuntu-latest-x64-4x + runs-on: ubuntu-latest strategy: # one flaky shard shouldn't cancel its siblings - lets us re-run only the failed shard fail-fast: false @@ -130,7 +130,7 @@ jobs: name: "📊 Merge Reports" if: ${{ !cancelled() }} needs: [unitTests] - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 diff --git a/.github/workflows/unit-tests-webapp.yml b/.github/workflows/unit-tests-webapp.yml index 680eafd9aa1..4082d1484b1 100644 --- a/.github/workflows/unit-tests-webapp.yml +++ b/.github/workflows/unit-tests-webapp.yml @@ -19,7 +19,7 @@ jobs: # spin-up), so many machines beats few big ones - fewer/bigger (3x32) measured # SLOWER than 10x8. The 16x (vs 8x) gives the fork pool the CPU headroom the 8x # runners lacked. Setup overhead per machine is ~1 min on warm runners. - runs-on: warp-ubuntu-latest-x64-16x + runs-on: ubuntu-latest strategy: # one flaky shard shouldn't cancel its siblings - lets us re-run only the failed shard fail-fast: false @@ -144,7 +144,7 @@ jobs: name: "📊 Merge Reports" if: ${{ !cancelled() }} needs: [unitTests] - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest steps: - name: ⬇️ Checkout repo uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 diff --git a/.github/workflows/vouch-check-pr.yml b/.github/workflows/vouch-check-pr.yml index fab876451b6..d854b1e0ce6 100644 --- a/.github/workflows/vouch-check-pr.yml +++ b/.github/workflows/vouch-check-pr.yml @@ -8,7 +8,7 @@ permissions: {} jobs: check-vouch: - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: read pull-requests: write # auto-close unvouched PRs @@ -34,7 +34,7 @@ jobs: github.event.pull_request.user.login != 'devin-ai-integration[bot]' && github.event.pull_request.user.login != 'dependabot[bot]' && github.event.pull_request.user.login != 'github-actions[bot]' - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest steps: - name: Close non-draft PR env: diff --git a/.github/workflows/vouch-manage-by-issue.yml b/.github/workflows/vouch-manage-by-issue.yml index 29d9584cabd..51bce367b3e 100644 --- a/.github/workflows/vouch-manage-by-issue.yml +++ b/.github/workflows/vouch-manage-by-issue.yml @@ -10,7 +10,7 @@ permissions: jobs: manage: - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest if: >- contains(github.event.comment.body, 'vouch') || contains(github.event.comment.body, 'denounce') || diff --git a/.github/workflows/workflow-checks.yml b/.github/workflows/workflow-checks.yml index 40843deb2ea..cce1381c673 100644 --- a/.github/workflows/workflow-checks.yml +++ b/.github/workflows/workflow-checks.yml @@ -24,7 +24,7 @@ concurrency: jobs: actionlint: name: Actionlint - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: contents: read steps: @@ -43,7 +43,7 @@ jobs: # variable to 'false' to skip this job where code scanning isn't available; # leave it unset (the default) to run the scan. if: ${{ vars.ENABLE_WORKFLOW_SECURITY_SCAN != 'false' }} - runs-on: warp-ubuntu-latest-x64-2x + runs-on: ubuntu-latest permissions: security-events: write # Upload SARIF to GitHub Security tab contents: read # Read workflow files for analysis diff --git a/apps/supervisor/src/env.test.ts b/apps/supervisor/src/env.test.ts index b02d117513c..a106b8a76c4 100644 --- a/apps/supervisor/src/env.test.ts +++ b/apps/supervisor/src/env.test.ts @@ -62,3 +62,89 @@ describe("Env superRefine - backpressure source awareness", () => { ).toThrow(); }); }); + +describe("Env superRefine - worker volumes", () => { + const volumes = JSON.stringify([{ name: "extra-ca", configMap: { name: "my-ca-bundle" } }]); + const mounts = JSON.stringify([ + { name: "extra-ca", mountPath: "/etc/ssl/extra-ca", readOnly: true }, + ]); + + const issueMessages = (input: Record) => { + const result = Env.safeParse({ ...base, ...input }); + return result.success ? [] : result.error.issues.map((issue) => issue.message); + }; + + it("defaults both lists to empty", () => { + const parsed = Env.parse(base); + expect(parsed.KUBERNETES_WORKER_VOLUMES).toEqual([]); + expect(parsed.KUBERNETES_WORKER_VOLUME_MOUNTS).toEqual([]); + }); + + it("accepts mounts that name a configured volume", () => { + const parsed = Env.parse({ + ...base, + KUBERNETES_WORKER_VOLUMES: volumes, + KUBERNETES_WORKER_VOLUME_MOUNTS: mounts, + }); + expect(parsed.KUBERNETES_WORKER_VOLUMES).toEqual(JSON.parse(volumes)); + expect(parsed.KUBERNETES_WORKER_VOLUME_MOUNTS).toEqual(JSON.parse(mounts)); + }); + + it("refuses to start when a mount names a volume that is not configured", () => { + expect(issueMessages({ KUBERNETES_WORKER_VOLUME_MOUNTS: mounts })).toEqual([ + 'KUBERNETES_WORKER_VOLUME_MOUNTS mounts volume "extra-ca", which is not defined in KUBERNETES_WORKER_VOLUMES', + ]); + }); + + it("refuses to start when two volumes share a name", () => { + const duplicated = JSON.stringify([ + { name: "extra-ca", configMap: { name: "a" } }, + { name: "extra-ca", configMap: { name: "b" } }, + ]); + expect(issueMessages({ KUBERNETES_WORKER_VOLUMES: duplicated })).toEqual([ + 'KUBERNETES_WORKER_VOLUMES has more than one volume named "extra-ca"', + ]); + }); + + it("refuses to start on a misspelled volume source, naming the env var and the key", () => { + const messages = issueMessages({ + KUBERNETES_WORKER_VOLUMES: '[{"name":"extra-ca","configmap":{"name":"my-ca-bundle"}}]', + }); + expect(messages).toHaveLength(1); + expect(messages[0]).toMatch(/^KUBERNETES_WORKER_VOLUMES has invalid item\(s\): /); + expect(messages[0]).toContain('[0.configmap] unknown key "configmap" (not a V1Volume field)'); + }); + + it("refuses to start when two mounts share a mountPath", () => { + expect( + issueMessages({ + KUBERNETES_WORKER_VOLUMES: volumes, + KUBERNETES_WORKER_VOLUME_MOUNTS: JSON.stringify([ + { name: "extra-ca", mountPath: "/etc/ssl/extra-ca" }, + { name: "extra-ca", mountPath: "/etc/ssl/extra-ca", readOnly: true }, + ]), + }) + ).toEqual([ + 'KUBERNETES_WORKER_VOLUME_MOUNTS has more than one mount at path "/etc/ssl/extra-ca"', + ]); + }); + + it("treats blank values as empty lists", () => { + const parsed = Env.parse({ + ...base, + KUBERNETES_WORKER_VOLUMES: "", + KUBERNETES_WORKER_VOLUME_MOUNTS: " ", + }); + expect(parsed.KUBERNETES_WORKER_VOLUMES).toEqual([]); + expect(parsed.KUBERNETES_WORKER_VOLUME_MOUNTS).toEqual([]); + }); + + it("refuses to start when a mount has no mountPath, reporting only the parse error", () => { + const messages = issueMessages({ + KUBERNETES_WORKER_VOLUMES: volumes, + KUBERNETES_WORKER_VOLUME_MOUNTS: '[{"name":"extra-ca"}]', + }); + expect(messages).toHaveLength(1); + expect(messages[0]).toMatch(/^KUBERNETES_WORKER_VOLUME_MOUNTS has invalid item/); + }); +}); diff --git a/apps/supervisor/src/env.ts b/apps/supervisor/src/env.ts index 6c954b4e76a..74d5982508c 100644 --- a/apps/supervisor/src/env.ts +++ b/apps/supervisor/src/env.ts @@ -1,7 +1,12 @@ import { randomUUID } from "crypto"; import { env as stdEnv } from "std-env"; import { z } from "zod"; -import { AdditionalEnvVars, BoolEnv } from "./envUtil.js"; +import { AdditionalEnvVars, BoolEnv, JsonAny, JsonArrayEnv, JsonObjectEnv } from "./envUtil.js"; +import { + WorkerVolumeMountSchema, + WorkerVolumeSchema, + findWorkerVolumeConfigErrors, +} from "./workloadManager/kubernetesPodSpec.js"; export const Env = z .object({ @@ -173,6 +178,70 @@ export const Env = z KUBERNETES_FORCE_ENABLED: BoolEnv.default(false), KUBERNETES_NAMESPACE: z.string().default("default"), KUBERNETES_WORKER_NODETYPE_LABEL: z.string().default("v4-worker"), + KUBERNETES_WORKER_SERVICE_ACCOUNT: z.string().optional(), // Service account for worker pods + KUBERNETES_WORKER_AUTOMOUNT_SERVICE_ACCOUNT_TOKEN: BoolEnv.default(false), // Whether to mount SA token + // Extra annotations to apply to every worker pod (e.g. for service mesh + // sidecar injection, certificate injection, scheduling hints). K8s + // annotation values are always strings (`map[string]string` per the API + // spec) — and `kubernetes.ts` spreads this parsed object straight into + // the pod's `metadata.annotations` without any conversion. So each + // value here must be a string. The explicit validator documents that + // Kubernetes requirement; accepting nested objects would get rejected + // by the K8s API with + // "Pod in version v1 cannot be handled as a Pod: json: cannot + // unmarshal object into Go struct field + // ObjectMeta.metadata.annotations of type string" + // (Real failure mode hit on FedStart with + // `{"com.palantir.rubix.service/pod-cert": {}}`.) + KUBERNETES_WORKER_POD_ANNOTATIONS: JsonObjectEnv("KUBERNETES_WORKER_POD_ANNOTATIONS", { + valueValidator: z.string(), + }), + // Pod-level securityContext applied to every worker pod (V1PodSecurityContext shape). + // Default is empty `{}`, preserving the upstream behavior of not setting + // a pod-level securityContext. Provide a JSON object to enforce e.g. + // `{"runAsNonRoot": true, "runAsUser": 1000, "fsGroup": 1000}`. + // OpenShift and other clusters with arbitrary-UID SCCs typically want + // to leave this empty and let the SCC inject values. + KUBERNETES_WORKER_POD_SECURITY_CONTEXT: JsonObjectEnv( + "KUBERNETES_WORKER_POD_SECURITY_CONTEXT", + { + valueValidator: JsonAny, + } + ), + // Container-level securityContext applied to the worker container of every + // worker pod (V1SecurityContext shape). Default is empty `{}` (matches + // upstream's previous behavior of not setting a container securityContext). + // Provide a JSON object to enforce e.g. + // `{"runAsNonRoot": true, "runAsUser": 1000, "allowPrivilegeEscalation": false, + // "capabilities": {"drop": ["ALL"]}, "seccompProfile": {"type": "RuntimeDefault"}}`. + KUBERNETES_WORKER_CONTAINER_SECURITY_CONTEXT: JsonObjectEnv( + "KUBERNETES_WORKER_CONTAINER_SECURITY_CONTEXT", + { valueValidator: JsonAny } + ), + // Name of a Kubernetes Secret to envFrom-mount into every worker pod's + // container. Pulls every key/value pair in the secret as env vars on + // the worker. Resolved by the kubelet at pod creation time; the + // supervisor never reads the secret values, so this needs no extra + // RBAC. Use case: keep task-time secrets (DB URLs, API keys) in + // Kubernetes rather than syncing them through the trigger.dev webapp. + KUBERNETES_WORKER_ENV_FROM_SECRET: z.string().optional(), + // Extra volumes added to every worker pod (array of V1Volume objects), e.g. + // `[{"name":"extra-ca","configMap":{"name":"my-ca-bundle"}}]`. Default is + // empty `[]`, which leaves the pod spec unchanged. Each entry needs a unique + // `name`, exactly one volume source, and no keys outside V1Volume (the + // Kubernetes client would silently drop them). + KUBERNETES_WORKER_VOLUMES: JsonArrayEnv("KUBERNETES_WORKER_VOLUMES", { + itemValidator: WorkerVolumeSchema, + }), + // Mounts added to the run-controller container of every worker pod (array + // of V1VolumeMount objects), e.g. + // `[{"name":"extra-ca","mountPath":"/etc/ssl/extra-ca","readOnly":true}]`. + // Default is empty `[]`. Every `name` must match a volume in + // KUBERNETES_WORKER_VOLUMES, mount paths must be unique, and keys outside + // V1VolumeMount are rejected; the supervisor refuses to start otherwise. + KUBERNETES_WORKER_VOLUME_MOUNTS: JsonArrayEnv("KUBERNETES_WORKER_VOLUME_MOUNTS", { + itemValidator: WorkerVolumeMountSchema, + }), KUBERNETES_IMAGE_PULL_SECRETS: z.string().optional(), // csv KUBERNETES_EPHEMERAL_STORAGE_SIZE_LIMIT: z.string().default("10Gi"), KUBERNETES_EPHEMERAL_STORAGE_SIZE_REQUEST: z.string().default("2Gi"), @@ -348,6 +417,22 @@ export const Env = z TRIGGER_WIDE_EVENTS_NOISY_ROUTES: BoolEnv.default(false), }) .superRefine((data, ctx) => { + // Only cross-check once both lists parsed; a parse failure is already reported. + if ( + Array.isArray(data.KUBERNETES_WORKER_VOLUMES) && + Array.isArray(data.KUBERNETES_WORKER_VOLUME_MOUNTS) + ) { + for (const error of findWorkerVolumeConfigErrors( + data.KUBERNETES_WORKER_VOLUMES, + data.KUBERNETES_WORKER_VOLUME_MOUNTS + )) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: error.message, + path: [error.envVar], + }); + } + } if ( data.TRIGGER_DEQUEUE_BACKPRESSURE_POD_COUNT_ENABLED && data.TRIGGER_DEQUEUE_BACKPRESSURE_POD_COUNT_RELEASE >= diff --git a/apps/supervisor/src/envUtil.test.ts b/apps/supervisor/src/envUtil.test.ts index c3d35758f16..d59b9fef423 100644 --- a/apps/supervisor/src/envUtil.test.ts +++ b/apps/supervisor/src/envUtil.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect } from "vitest"; -import { BoolEnv, AdditionalEnvVars } from "./envUtil.js"; +import { z } from "zod"; +import { BoolEnv, AdditionalEnvVars, JsonObjectEnv, JsonAny, JsonArrayEnv } from "./envUtil.js"; describe("BoolEnv", () => { it("should parse string 'true' as true", () => { @@ -78,3 +79,187 @@ describe("AdditionalEnvVars", () => { }); }); }); + +describe("JsonObjectEnv (string-valued)", () => { + const schema = JsonObjectEnv("TEST_ENV"); + + it("returns empty object for default (no value)", () => { + expect(schema.parse(undefined)).toEqual({}); + }); + + it("parses a simple string-valued JSON object", () => { + expect(schema.parse('{"a":"1","b":"2"}')).toEqual({ a: "1", b: "2" }); + }); + + it("parses an empty JSON object", () => { + expect(schema.parse("{}")).toEqual({}); + }); + + it("rejects non-JSON input", () => { + expect(() => schema.parse("not json")).toThrowError(/not valid JSON/); + }); + + it("rejects JSON arrays", () => { + expect(() => schema.parse("[]")).toThrowError(/must be a JSON object \(got array\)/); + }); + + it("rejects JSON primitives", () => { + expect(() => schema.parse('"foo"')).toThrowError(/must be a JSON object \(got string\)/); + expect(() => schema.parse("42")).toThrowError(/must be a JSON object \(got number\)/); + expect(() => schema.parse("null")).toThrowError(/must be a JSON object \(got object\)/); + }); + + it("rejects values that are not strings (with default validator)", () => { + expect(() => schema.parse('{"a": 1}')).toThrowError(/has invalid value/); + expect(() => schema.parse('{"a": true}')).toThrowError(/has invalid value/); + }); +}); + +describe("JsonObjectEnv (arbitrary-value)", () => { + const schema = JsonObjectEnv("TEST_ANY", { valueValidator: JsonAny }); + + it("accepts nested objects", () => { + expect( + schema.parse( + JSON.stringify({ + runAsNonRoot: true, + runAsUser: 1000, + capabilities: { drop: ["ALL"] }, + }) + ) + ).toEqual({ + runAsNonRoot: true, + runAsUser: 1000, + capabilities: { drop: ["ALL"] }, + }); + }); + + it("accepts mixed value types", () => { + expect(schema.parse('{"s":"x","n":1,"b":true,"a":[1,2],"o":{"k":"v"}}')).toEqual({ + s: "x", + n: 1, + b: true, + a: [1, 2], + o: { k: "v" }, + }); + }); + + it("still rejects non-object roots", () => { + expect(() => schema.parse('"x"')).toThrowError(/must be a JSON object/); + expect(() => schema.parse("[1,2,3]")).toThrowError(/must be a JSON object/); + }); + + it("includes the env var name in error messages", () => { + const named = JsonObjectEnv("KUBERNETES_WORKER_POD_SECURITY_CONTEXT"); + expect(() => named.parse("{notjson")).toThrowError(/KUBERNETES_WORKER_POD_SECURITY_CONTEXT/); + }); +}); + +describe("JsonObjectEnv (flat string values, K8s-annotation shape)", () => { + // Regression test for a real production incident on FedStart: passing + // KUBERNETES_WORKER_POD_ANNOTATIONS with a nested-map value silently + // passed zod validation under the default JsonStringMap validator + // (because `{}` is a valid empty `Record`), but then + // got spread directly into a K8s Pod's metadata.annotations and + // rejected by the apiserver: + // + // "Pod in version v1 cannot be handled as a Pod: json: cannot + // unmarshal object into Go struct field + // ObjectMeta.metadata.annotations of type string" + // + // K8s annotations are flat `map[string]string` per the API spec, so + // KUBERNETES_WORKER_POD_ANNOTATIONS must validate values as `z.string()`, + // not as a nested string map. + const schema = JsonObjectEnv("KUBERNETES_WORKER_POD_ANNOTATIONS", { + valueValidator: z.string(), + }); + + it("accepts the Rubix pod-cert annotation as a string value", () => { + // Rubix's `com.palantir.rubix.service/pod-cert` annotation expects + // its VALUE to be the 2-char string "{}" (which Rubix internally + // parses as JSON to determine cert minting config). The env var + // input is itself JSON-stringified, so the value here is the + // 4-char string `"{}"` — two quotes around two braces. + expect(schema.parse('{"com.palantir.rubix.service/pod-cert":"{}"}')).toEqual({ + "com.palantir.rubix.service/pod-cert": "{}", + }); + }); + + it("accepts multiple flat string annotations", () => { + expect( + schema.parse('{"com.palantir.rubix.service/pod-cert":"{}","trigger.dev/owner":"supervisor"}') + ).toEqual({ + "com.palantir.rubix.service/pod-cert": "{}", + "trigger.dev/owner": "supervisor", + }); + }); + + it("rejects object values (annotations must be flat strings)", () => { + // The pre-fix bug: this would have passed zod with the default + // JsonStringMap validator, then crashed at K8s apiserver. Schema + // must reject before the value ever reaches K8s. + expect(() => schema.parse('{"com.palantir.rubix.service/pod-cert":{}}')).toThrowError( + /has invalid value/ + ); + }); + + it("rejects nested string maps as values", () => { + expect(() => schema.parse('{"some/annotation":{"nested":"value"}}')).toThrowError( + /has invalid value/ + ); + }); + + it("rejects numeric and boolean values", () => { + expect(() => schema.parse('{"some/annotation":42}')).toThrowError(/has invalid value/); + expect(() => schema.parse('{"some/annotation":true}')).toThrowError(/has invalid value/); + }); +}); + +describe("JsonArrayEnv", () => { + const schema = JsonArrayEnv("TEST_ARRAY", { + itemValidator: z.object({ name: z.string().min(1) }).catchall(JsonAny), + }); + + it("returns empty array for default (no value)", () => { + expect(schema.parse(undefined)).toEqual([]); + }); + + it("parses an empty JSON array", () => { + expect(schema.parse("[]")).toEqual([]); + }); + + it("treats an empty or whitespace-only value as an empty array", () => { + expect(schema.parse("")).toEqual([]); + expect(schema.parse(" ")).toEqual([]); + expect(schema.parse("\n\t ")).toEqual([]); + }); + + it("parses an array of objects, keeping nested fields", () => { + expect( + schema.parse('[{"name":"a","configMap":{"name":"cm","items":[{"key":"k","path":"p"}]}}]') + ).toEqual([{ name: "a", configMap: { name: "cm", items: [{ key: "k", path: "p" }] } }]); + }); + + it("rejects non-JSON input", () => { + expect(() => schema.parse("not json")).toThrowError(/TEST_ARRAY is not valid JSON/); + }); + + it("rejects JSON objects", () => { + expect(() => schema.parse('{"name":"a"}')).toThrowError( + /TEST_ARRAY must be a JSON array \(got object\)/ + ); + }); + + it("rejects JSON primitives and null", () => { + expect(() => schema.parse('"foo"')).toThrowError(/must be a JSON array \(got string\)/); + expect(() => schema.parse("42")).toThrowError(/must be a JSON array \(got number\)/); + expect(() => schema.parse("null")).toThrowError(/must be a JSON array \(got null\)/); + }); + + it("rejects items that fail the item validator", () => { + expect(() => schema.parse('["a"]')).toThrowError(/TEST_ARRAY has invalid item/); + expect(() => schema.parse("[{}]")).toThrowError(/TEST_ARRAY has invalid item/); + expect(() => schema.parse('[{"name":""}]')).toThrowError(/TEST_ARRAY has invalid item/); + expect(() => schema.parse('[{"name":1}]')).toThrowError(/TEST_ARRAY has invalid item/); + }); +}); diff --git a/apps/supervisor/src/envUtil.ts b/apps/supervisor/src/envUtil.ts index 917f984cc37..27ba8a3c61b 100644 --- a/apps/supervisor/src/envUtil.ts +++ b/apps/supervisor/src/envUtil.ts @@ -45,3 +45,150 @@ export const AdditionalEnvVars = z.preprocess((val) => { return undefined; } }, z.record(z.string(), z.string()).optional()); + +/** + * Factory for env vars that hold a JSON object. The default is the empty object, + * so callers can spread the parsed result into Kubernetes manifests without + * branching on undefined. + * + * `valueValidator` constrains the shape of the parsed values: + * - `z.string()` for `Record` (e.g. annotations, labels) + * - `JsonAny` for arbitrary nested objects (e.g. `securityContext`) + * + * @example + * KUBERNETES_WORKER_POD_ANNOTATIONS: JsonObjectEnv("KUBERNETES_WORKER_POD_ANNOTATIONS", { + * valueValidator: z.string(), + * }), + */ +export const JsonStringMap = z.record(z.string(), z.string()); +const JsonStringValue = z.string(); +export const JsonAny: z.ZodTypeAny = z.lazy(() => + z.union([ + z.string(), + z.number(), + z.boolean(), + z.null(), + z.array(JsonAny), + z.record(z.string(), JsonAny), + ]) +); + +type JsonObjectEnvOpts = { + /** + * Schema applied to each *value* in the parsed object. Defaults to + * `z.string()`. + */ + valueValidator?: TSchema; +}; + +export const JsonObjectEnv = ( + envName: string, + opts: JsonObjectEnvOpts = {} +) => { + const valueValidator = (opts.valueValidator ?? JsonStringValue) as TSchema; + + return z + .string() + .default("{}") + .transform((raw, ctx) => { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (e) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `${envName} is not valid JSON: ${e instanceof Error ? e.message : String(e)}`, + }); + return z.NEVER; + } + + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `${envName} must be a JSON object (got ${ + Array.isArray(parsed) ? "array" : typeof parsed + })`, + }); + return z.NEVER; + } + + const validated = z.record(z.string(), valueValidator).safeParse(parsed); + if (!validated.success) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `${envName} has invalid value(s): ${validated.error.message}`, + }); + return z.NEVER; + } + + return validated.data as z.infer extends z.ZodTypeAny + ? Record> + : Record; + }); +}; + +type JsonArrayEnvOpts = { + /** + * Schema applied to each *item* in the parsed array. + */ + itemValidator: TSchema; +}; + +/** + * Factory for env vars that hold a JSON array. Unset, empty and whitespace-only + * values all parse to the empty array, so callers can check `.length` and + * spread the parsed result into Kubernetes manifests without branching on + * undefined. + * + * @example + * KUBERNETES_WORKER_VOLUMES: JsonArrayEnv("KUBERNETES_WORKER_VOLUMES", { + * itemValidator: z.object({ name: z.string().min(1) }).catchall(JsonAny), + * }), + */ +export const JsonArrayEnv = ( + envName: string, + opts: JsonArrayEnvOpts +) => { + return z + .string() + .default("[]") + .transform((raw, ctx): z.infer[] => { + if (raw.trim() === "") { + return []; + } + + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (e) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `${envName} is not valid JSON: ${e instanceof Error ? e.message : String(e)}`, + }); + return z.NEVER; + } + + if (!Array.isArray(parsed)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `${envName} must be a JSON array (got ${ + parsed === null ? "null" : typeof parsed + })`, + }); + return z.NEVER; + } + + const validated = z.array(opts.itemValidator).safeParse(parsed); + if (!validated.success) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `${envName} has invalid item(s): ${validated.error.issues + .map((issue) => `[${issue.path.join(".")}] ${issue.message}`) + .join("; ")}`, + }); + return z.NEVER; + } + + return validated.data; + }); +}; diff --git a/apps/supervisor/src/workloadManager/kubernetes.test.ts b/apps/supervisor/src/workloadManager/kubernetes.test.ts index 85ad3cbebff..64ae292c389 100644 --- a/apps/supervisor/src/workloadManager/kubernetes.test.ts +++ b/apps/supervisor/src/workloadManager/kubernetes.test.ts @@ -1,7 +1,12 @@ import { describe, expect, it } from "vitest"; import { BLOCK_IO_URING_SECCOMP_PROFILE, + findWorkerVolumeConfigErrors, withBlockIoUringSeccompProfile, + withWorkerVolumeMounts, + withWorkerVolumes, + WorkerVolumeMountSchema, + WorkerVolumeSchema, } from "./kubernetesPodSpec.js"; const basePodSpec = { @@ -38,3 +43,195 @@ describe("withBlockIoUringSeccompProfile", () => { } }); }); + +const caVolume = { name: "extra-ca", configMap: { name: "my-ca-bundle" } }; +const caMount = { name: "extra-ca", mountPath: "/etc/ssl/extra-ca", readOnly: true }; + +describe("withWorkerVolumes", () => { + it("leaves the pod spec exactly as it was when no volumes are configured", () => { + const podSpec = withWorkerVolumes(basePodSpec, []); + + expect(podSpec).toBe(basePodSpec); + expect(podSpec).not.toHaveProperty("volumes"); + }); + + it("adds the configured volumes to a pod spec that has none", () => { + expect(withWorkerVolumes(basePodSpec, [caVolume])).toEqual({ + ...basePodSpec, + volumes: [caVolume], + }); + }); + + it("appends to volumes already on the pod spec instead of replacing them", () => { + const existing = { name: "scratch", emptyDir: {} }; + const podSpec = { ...basePodSpec, volumes: [existing] }; + + expect(withWorkerVolumes(podSpec, [caVolume]).volumes).toEqual([existing, caVolume]); + expect(podSpec.volumes).toEqual([existing]); + }); +}); + +describe("withWorkerVolumeMounts", () => { + const runController = { name: "run-controller", image: "task:latest" }; + const sidecar = { name: "sidecar", image: "sidecar:latest" }; + + it("leaves the containers exactly as they were when no mounts are configured", () => { + const containers = [runController]; + const result = withWorkerVolumeMounts([], containers); + + expect(result).toBe(containers); + expect(result[0]).not.toHaveProperty("volumeMounts"); + }); + + it("adds the configured mounts to the run-controller container", () => { + expect(withWorkerVolumeMounts([caMount], [runController])).toEqual([ + { ...runController, volumeMounts: [caMount] }, + ]); + }); + + it("appends to mounts already on the container instead of replacing them", () => { + const existing = { name: "scratch", mountPath: "/scratch" }; + const withExisting = { ...runController, volumeMounts: [existing] }; + + expect(withWorkerVolumeMounts([caMount], [withExisting])[0]?.volumeMounts).toEqual([ + existing, + caMount, + ]); + expect(withExisting.volumeMounts).toEqual([existing]); + }); + + it("does not mount into containers other than run-controller", () => { + expect(withWorkerVolumeMounts([caMount], [sidecar, runController])).toEqual([ + sidecar, + { ...runController, volumeMounts: [caMount] }, + ]); + }); +}); + +describe("findWorkerVolumeConfigErrors", () => { + it("accepts empty lists", () => { + expect(findWorkerVolumeConfigErrors([], [])).toEqual([]); + }); + + it("accepts mounts that all name a configured volume, and volumes with no mount", () => { + expect( + findWorkerVolumeConfigErrors([caVolume, { name: "unused", emptyDir: {} }], [caMount]) + ).toEqual([]); + }); + + it("reports a mount naming a volume that is not configured, naming the env var", () => { + expect(findWorkerVolumeConfigErrors([], [caMount])).toEqual([ + { + envVar: "KUBERNETES_WORKER_VOLUME_MOUNTS", + message: + 'KUBERNETES_WORKER_VOLUME_MOUNTS mounts volume "extra-ca", which is not defined in KUBERNETES_WORKER_VOLUMES', + }, + ]); + }); + + it("reports two mounts at the same path once, naming the env var", () => { + const other = { name: "other", emptyDir: {} }; + const clash = { name: "other", mountPath: caMount.mountPath }; + expect(findWorkerVolumeConfigErrors([caVolume, other], [caMount, clash, { ...clash }])).toEqual( + [ + { + envVar: "KUBERNETES_WORKER_VOLUME_MOUNTS", + message: + 'KUBERNETES_WORKER_VOLUME_MOUNTS has more than one mount at path "/etc/ssl/extra-ca"', + }, + ] + ); + }); + + it("accepts two mounts of the same volume at different paths", () => { + expect( + findWorkerVolumeConfigErrors( + [caVolume], + [caMount, { name: "extra-ca", mountPath: "/etc/ssl/certs/extra" }] + ) + ).toEqual([]); + }); + + it("reports two volumes sharing a name once, naming the env var", () => { + expect(findWorkerVolumeConfigErrors([caVolume, caVolume, caVolume], [caMount])).toEqual([ + { + envVar: "KUBERNETES_WORKER_VOLUMES", + message: 'KUBERNETES_WORKER_VOLUMES has more than one volume named "extra-ca"', + }, + ]); + }); +}); + +const issueMessages = (result: { success: boolean; error?: { issues: { message: string }[] } }) => + result.success ? [] : (result.error?.issues.map((issue) => issue.message) ?? []); + +describe("WorkerVolumeSchema", () => { + it("accepts a volume with one known source", () => { + expect(WorkerVolumeSchema.parse(caVolume)).toEqual(caVolume); + expect(WorkerVolumeSchema.parse({ name: "scratch", emptyDir: {} })).toEqual({ + name: "scratch", + emptyDir: {}, + }); + }); + + it.each([ + ["projected", { sources: [{ configMap: { name: "my-ca-bundle" } }] }], + ["csi", { driver: "secrets-store.csi.k8s.io" }], + ["ephemeral", { volumeClaimTemplate: { spec: {} } }], + ["downwardAPI", { items: [] }], + ["secret", { secretName: "my-secret" }], + ])("accepts a %s volume source", (source, value) => { + const volume = { name: "extra", [source]: value }; + expect(WorkerVolumeSchema.parse(volume)).toEqual(volume); + }); + + it("rejects an unknown top-level key such as a lowercase configmap, naming the key", () => { + expect( + issueMessages( + WorkerVolumeSchema.safeParse({ name: "extra-ca", configmap: { name: "my-ca-bundle" } }) + ) + ).toEqual([ + 'unknown key "configmap" (not a V1Volume field)', + 'volume "extra-ca" must have exactly one volume source (got none)', + ]); + }); + + it("rejects a volume with no source", () => { + expect(issueMessages(WorkerVolumeSchema.safeParse({ name: "extra-ca" }))).toEqual([ + 'volume "extra-ca" must have exactly one volume source (got none)', + ]); + }); + + it("rejects a volume with two sources", () => { + expect( + issueMessages( + WorkerVolumeSchema.safeParse({ + name: "extra-ca", + configMap: { name: "my-ca-bundle" }, + secret: { secretName: "my-ca-secret" }, + }) + ) + ).toEqual(['volume "extra-ca" must have exactly one volume source (got configMap, secret)']); + }); + + it("rejects a source whose value is not a JSON object", () => { + for (const value of ["my-ca-bundle", 1, true, null, [{ name: "my-ca-bundle" }]]) { + expect( + issueMessages(WorkerVolumeSchema.safeParse({ name: "extra-ca", configMap: value })) + ).toEqual(['volume source "configMap" must be a JSON object']); + } + }); +}); + +describe("WorkerVolumeMountSchema", () => { + it("accepts a mount using only V1VolumeMount fields", () => { + const mount = { ...caMount, subPath: "ca.pem", mountPropagation: "None" }; + expect(WorkerVolumeMountSchema.parse(mount)).toEqual(mount); + }); + + it("rejects an unknown top-level key, naming the key", () => { + expect( + issueMessages(WorkerVolumeMountSchema.safeParse({ ...caMount, readonly: true })) + ).toEqual(['unknown key "readonly" (not a V1VolumeMount field)']); + }); +}); diff --git a/apps/supervisor/src/workloadManager/kubernetes.ts b/apps/supervisor/src/workloadManager/kubernetes.ts index 0263b229e13..7c0b19f7c9d 100644 --- a/apps/supervisor/src/workloadManager/kubernetes.ts +++ b/apps/supervisor/src/workloadManager/kubernetes.ts @@ -14,7 +14,11 @@ import { PlacementTagProcessor } from "@trigger.dev/core/v3/serverOnly"; import { env } from "../env.js"; import { type K8sApi, createK8sApi, type k8s } from "../clients/kubernetes.js"; import { getRunnerId } from "../util.js"; -import { withBlockIoUringSeccompProfile } from "./kubernetesPodSpec.js"; +import { + withBlockIoUringSeccompProfile, + withWorkerVolumeMounts, + withWorkerVolumes, +} from "./kubernetesPodSpec.js"; type ResourceQuantities = { [K in "cpu" | "memory" | "ephemeral-storage"]?: string; @@ -106,7 +110,10 @@ export class KubernetesWorkloadManager implements WorkloadManager { const runnerId = getRunnerId(opts.runFriendlyId, opts.nextAttemptNumber); try { - const basePodSpec = this.addPlacementTags(this.#defaultPodSpec, opts.placementTags); + const basePodSpec = withWorkerVolumes( + this.addPlacementTags(this.#defaultPodSpec, opts.placementTags), + env.KUBERNETES_WORKER_VOLUMES + ); const podSpec = this.opts.checkpointsEnabled ? withBlockIoUringSeccompProfile(basePodSpec, opts.runtime) : basePodSpec; @@ -123,13 +130,20 @@ export class KubernetesWorkloadManager implements WorkloadManager { "app.kubernetes.io/part-of": "trigger-worker", "app.kubernetes.io/component": "create", }, + ...(Object.keys(env.KUBERNETES_WORKER_POD_ANNOTATIONS).length > 0 + ? { + annotations: { + ...env.KUBERNETES_WORKER_POD_ANNOTATIONS, + } as Record, + } + : {}), }, spec: { ...podSpec, affinity: this.#getAffinity(opts), tolerations: this.#getScheduleTolerations(this.#isScheduledRun(opts)), terminationGracePeriodSeconds: 60 * 60, - containers: [ + containers: withWorkerVolumeMounts(env.KUBERNETES_WORKER_VOLUME_MOUNTS, [ { name: "run-controller", image: this.stripImageDigest(opts.image), @@ -139,6 +153,14 @@ export class KubernetesWorkloadManager implements WorkloadManager { }, ], resources: this.#getResourcesForMachine(opts.machine), + ...(Object.keys(env.KUBERNETES_WORKER_CONTAINER_SECURITY_CONTEXT).length > 0 + ? { securityContext: env.KUBERNETES_WORKER_CONTAINER_SECURITY_CONTEXT } + : {}), + ...(env.KUBERNETES_WORKER_ENV_FROM_SECRET + ? { + envFrom: [{ secretRef: { name: env.KUBERNETES_WORKER_ENV_FROM_SECRET } }], + } + : {}), env: [ { name: "TRIGGER_DEQUEUED_AT_MS", @@ -269,7 +291,7 @@ export class KubernetesWorkloadManager implements WorkloadManager { : []), ], }, - ], + ]), }, }, }); @@ -322,13 +344,21 @@ export class KubernetesWorkloadManager implements WorkloadManager { get #defaultPodSpec(): Omit { return { restartPolicy: "Never", - automountServiceAccountToken: false, + // Explicit control over service account token mounting (defaults to false for security) + automountServiceAccountToken: env.KUBERNETES_WORKER_AUTOMOUNT_SERVICE_ACCOUNT_TOKEN, imagePullSecrets: this.getImagePullSecrets(), ...(env.KUBERNETES_SCHEDULER_NAME ? { schedulerName: env.KUBERNETES_SCHEDULER_NAME, } : {}), + // Optionally specify a service account for the worker pods + ...(env.KUBERNETES_WORKER_SERVICE_ACCOUNT + ? { serviceAccountName: env.KUBERNETES_WORKER_SERVICE_ACCOUNT } + : {}), + ...(Object.keys(env.KUBERNETES_WORKER_POD_SECURITY_CONTEXT).length > 0 + ? { securityContext: env.KUBERNETES_WORKER_POD_SECURITY_CONTEXT } + : {}), ...(env.KUBERNETES_WORKER_NODETYPE_LABEL ? { nodeSelector: { diff --git a/apps/supervisor/src/workloadManager/kubernetesPodSpec.ts b/apps/supervisor/src/workloadManager/kubernetesPodSpec.ts index 32c4410ca43..8fe8c4b2553 100644 --- a/apps/supervisor/src/workloadManager/kubernetesPodSpec.ts +++ b/apps/supervisor/src/workloadManager/kubernetesPodSpec.ts @@ -1,4 +1,7 @@ +import { V1Volume, V1VolumeMount } from "@kubernetes/client-node"; +import { z } from "zod"; import type { k8s } from "../clients/kubernetes.js"; +import { JsonAny } from "../envUtil.js"; /** * Relative path (kubelet seccomp root) of the profile blocking only io_uring @@ -31,3 +34,174 @@ export function withBlockIoUringSeccompProfile( }, }; } + +/** + * Appends operator-supplied volumes (KUBERNETES_WORKER_VOLUMES) to a worker pod + * spec, keeping any volumes already on it. An empty list returns the spec + * untouched, so pods look exactly as they did before the option existed. + */ +export function withWorkerVolumes( + podSpec: Omit, + volumes: k8s.V1Volume[] +): Omit { + if (volumes.length === 0) { + return podSpec; + } + + return { + ...podSpec, + volumes: [...(podSpec.volumes ?? []), ...volumes], + }; +} + +/** Name of the worker pod container that runs the task. */ +export const RUN_CONTROLLER_CONTAINER_NAME = "run-controller"; + +/** + * Appends operator-supplied mounts (KUBERNETES_WORKER_VOLUME_MOUNTS) to the + * run-controller container, keeping any mounts already on it. Other containers + * are left alone. An empty list returns the containers untouched. The + * containers come last so the call site can wrap the container list inline. + */ +export function withWorkerVolumeMounts( + volumeMounts: k8s.V1VolumeMount[], + containers: k8s.V1Container[] +): k8s.V1Container[] { + if (volumeMounts.length === 0) { + return containers; + } + + return containers.map((container) => + container.name === RUN_CONTROLLER_CONTAINER_NAME + ? { ...container, volumeMounts: [...(container.volumeMounts ?? []), ...volumeMounts] } + : container + ); +} + +// The Kubernetes client serializes only the fields it knows and silently drops +// the rest, so a misspelled key (e.g. `configmap`) would reach the API server +// as a bare `{name}` volume, which it defaults to an emptyDir. Reject unknown +// top-level keys instead. Nested objects are passed through unchecked. +const V1_VOLUME_FIELDS = new Set(V1Volume.getAttributeTypeMap().map((attr) => attr.name)); +const V1_VOLUME_MOUNT_FIELDS = new Set( + V1VolumeMount.getAttributeTypeMap().map((attr) => attr.name) +); + +/** + * Item schema for KUBERNETES_WORKER_VOLUMES: a V1Volume with a non-empty name, + * no fields outside V1Volume, and exactly one volume source whose value is a + * JSON object. + */ +export const WorkerVolumeSchema = z + .object({ name: z.string().min(1) }) + .catchall(JsonAny) + .superRefine((volume, ctx) => { + const sources: string[] = []; + + for (const [key, value] of Object.entries(volume)) { + if (key === "name") { + continue; + } + + if (!V1_VOLUME_FIELDS.has(key)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `unknown key "${key}" (not a V1Volume field)`, + path: [key], + }); + continue; + } + + sources.push(key); + + if (typeof value !== "object" || value === null || Array.isArray(value)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `volume source "${key}" must be a JSON object`, + path: [key], + }); + } + } + + if (sources.length !== 1) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `volume "${volume.name}" must have exactly one volume source (got ${ + sources.length === 0 ? "none" : sources.join(", ") + })`, + }); + } + }); + +/** + * Item schema for KUBERNETES_WORKER_VOLUME_MOUNTS: a V1VolumeMount with a + * non-empty name and mountPath and no fields outside V1VolumeMount. + */ +export const WorkerVolumeMountSchema = z + .object({ name: z.string().min(1), mountPath: z.string().min(1) }) + .catchall(JsonAny) + .superRefine((mount, ctx) => { + for (const key of Object.keys(mount)) { + if (!V1_VOLUME_MOUNT_FIELDS.has(key)) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + message: `unknown key "${key}" (not a V1VolumeMount field)`, + path: [key], + }); + } + } + }); + +export type WorkerVolumeConfigError = { + envVar: "KUBERNETES_WORKER_VOLUMES" | "KUBERNETES_WORKER_VOLUME_MOUNTS"; + message: string; +}; + +/** + * Cross-checks KUBERNETES_WORKER_VOLUMES against KUBERNETES_WORKER_VOLUME_MOUNTS: + * unique volume names, unique mount paths, and every mount naming a volume. + * The Kubernetes API would reject every worker pod built from a config that + * fails these checks, so the supervisor runs them once at startup instead. + */ +export function findWorkerVolumeConfigErrors( + volumes: k8s.V1Volume[], + volumeMounts: k8s.V1VolumeMount[] +): WorkerVolumeConfigError[] { + const errors: WorkerVolumeConfigError[] = []; + const seen = new Set(); + const reported = new Set(); + + for (const { name } of volumes) { + if (seen.has(name) && !reported.has(name)) { + reported.add(name); + errors.push({ + envVar: "KUBERNETES_WORKER_VOLUMES", + message: `KUBERNETES_WORKER_VOLUMES has more than one volume named "${name}"`, + }); + } + seen.add(name); + } + + const seenPaths = new Set(); + const reportedPaths = new Set(); + + for (const { name, mountPath } of volumeMounts) { + if (!seen.has(name)) { + errors.push({ + envVar: "KUBERNETES_WORKER_VOLUME_MOUNTS", + message: `KUBERNETES_WORKER_VOLUME_MOUNTS mounts volume "${name}", which is not defined in KUBERNETES_WORKER_VOLUMES`, + }); + } + + if (seenPaths.has(mountPath) && !reportedPaths.has(mountPath)) { + reportedPaths.add(mountPath); + errors.push({ + envVar: "KUBERNETES_WORKER_VOLUME_MOUNTS", + message: `KUBERNETES_WORKER_VOLUME_MOUNTS has more than one mount at path "${mountPath}"`, + }); + } + seenPaths.add(mountPath); + } + + return errors; +} diff --git a/apps/webapp/app/env.server.ts b/apps/webapp/app/env.server.ts index 53b5edf0a46..49dd6f959e6 100644 --- a/apps/webapp/app/env.server.ts +++ b/apps/webapp/app/env.server.ts @@ -659,6 +659,38 @@ const EnvironmentSchema = z ), DEPLOY_IMAGE_PLATFORM: z.string().default("linux/amd64"), + /** + * DEPLOY_IMAGE_OVERRIDE — full image reference override; bypasses + * auto-generation of image tags. When set, every deployment finalized + * by this webapp instance uses this exact image reference instead of + * being routed through `getDeploymentImageRef` (ECR repo creation, + * per-project tagging, isEcr/repoCreated detection, etc). + * + * ⚠️ WARNING: SINGLE-TENANT ONLY. ⚠️ + * + * When set, every deployment finalized by this webapp instance will be + * wired to this image, regardless of which org / project triggered it. + * This is a foot-gun for any multi-tenant trigger.dev install + * (including Cloud) where deployments come from untrusted user code: + * one operator-set value silently overrides every tenant's per-project + * image. Only enable when BOTH of the following hold: + * - You control the build pipeline producing the image (e.g. your CI + * builds + pushes a single canonical tasks image per release), AND + * - The install serves only your own org's projects (self-hosted, + * single-tenant). + * + * For cloud / multi-tenant: leave unset. The deployment image is + * normally computed per-deployment from the registry config and the + * deploy version, which keeps tenants isolated. + * + * Empty string is treated as unset. + * + * Example: `myregistry.com/myorg/myapp:1.0.5` + */ + DEPLOY_IMAGE_OVERRIDE: z + .string() + .optional() + .transform((v) => (v && v.length > 0 ? v : undefined)), DEPLOY_TIMEOUT_MS: z.coerce .number() .int() @@ -683,6 +715,8 @@ const EnvironmentSchema = z OBJECT_STORE_SECRET_ACCESS_KEY: z.string().optional(), OBJECT_STORE_REGION: z.string().optional(), OBJECT_STORE_SERVICE: z.string().default("s3"), + // IAM mode only. Set false for endpoints that reject path-style requests (AWS FIPS endpoints). + OBJECT_STORE_FORCE_PATH_STYLE: BoolEnv.default(true), // Protocol to use for new uploads (e.g., "s3", "r2"). Data without protocol uses default provider above. // If specified, you must configure the corresponding provider using OBJECT_STORE_{PROTOCOL}_* env vars. diff --git a/apps/webapp/app/v3/objectStore.server.ts b/apps/webapp/app/v3/objectStore.server.ts index 159f2f41c6f..57b3ceded3b 100644 --- a/apps/webapp/app/v3/objectStore.server.ts +++ b/apps/webapp/app/v3/objectStore.server.ts @@ -5,6 +5,7 @@ import { type AuthenticatedEnvironment } from "~/services/apiAuth.server"; import { logger } from "~/services/logger.server"; import { ServiceValidationError } from "~/v3/services/common.server"; import { singleton } from "~/utils/singleton"; +import { BoolEnv } from "~/utils/boolEnv"; import { normalizeObjectStoreLogicalKeyPathname, ObjectStoreClient, @@ -182,6 +183,9 @@ function getObjectStoreConfig(protocol?: string): ObjectStoreClientConfig | unde secretAccessKey: process.env[`${prefix}SECRET_ACCESS_KEY`] || undefined, region: process.env[`${prefix}REGION`] || undefined, service: process.env[`${prefix}SERVICE`] || undefined, + forcePathStyle: BoolEnv.optional().parse( + process.env[`${prefix}FORCE_PATH_STYLE`] || undefined + ), }; } @@ -197,6 +201,7 @@ function getObjectStoreConfig(protocol?: string): ObjectStoreClientConfig | unde secretAccessKey: env.OBJECT_STORE_SECRET_ACCESS_KEY || undefined, region: env.OBJECT_STORE_REGION || undefined, service: env.OBJECT_STORE_SERVICE || undefined, + forcePathStyle: env.OBJECT_STORE_FORCE_PATH_STYLE, }; } diff --git a/apps/webapp/app/v3/objectStoreClient.server.ts b/apps/webapp/app/v3/objectStoreClient.server.ts index 790530de352..0082c7f393b 100644 --- a/apps/webapp/app/v3/objectStoreClient.server.ts +++ b/apps/webapp/app/v3/objectStoreClient.server.ts @@ -87,6 +87,7 @@ type AwsSdkConfig = { bucket: string; baseUrl: string; region?: string; + forcePathStyle: boolean; }; class AwsSdkClient implements IObjectStoreClient { @@ -95,7 +96,7 @@ class AwsSdkClient implements IObjectStoreClient { constructor(private readonly config: AwsSdkConfig) { this.s3Client = new S3Client({ endpoint: config.baseUrl, - forcePathStyle: true, + forcePathStyle: config.forcePathStyle, ...(config.region ? { region: config.region } : {}), }); } @@ -164,6 +165,12 @@ export type ObjectStoreClientConfig = { secretAccessKey?: string; region?: string; service?: string; + /** + * IAM mode only: address objects as `//` (true, the default) or + * `./` (false). AWS FIPS endpoints such as + * `s3-fips.us-gov-west-1.amazonaws.com` only accept the virtual-hosted form. + */ + forcePathStyle?: boolean; }; export class ObjectStoreClient implements IObjectStoreClient { @@ -199,6 +206,7 @@ export class ObjectStoreClient implements IObjectStoreClient { bucket: config.bucket, baseUrl: config.baseUrl, region: config.region, + forcePathStyle: config.forcePathStyle ?? true, }), config.bucket ); diff --git a/apps/webapp/app/v3/services/initializeDeployment.server.ts b/apps/webapp/app/v3/services/initializeDeployment.server.ts index abb99082dd6..4b5bca71f21 100644 --- a/apps/webapp/app/v3/services/initializeDeployment.server.ts +++ b/apps/webapp/app/v3/services/initializeDeployment.server.ts @@ -16,6 +16,10 @@ import { tryCatch } from "@trigger.dev/core"; import { getRegistryConfig } from "../registryConfig.server"; import { DeploymentService } from "./deployment.server"; import { createDeploymentWithNextVersion } from "./initializeDeployment/createDeploymentWithNextVersion.server"; +import { + ImageReferenceMismatchError, + resolveOverrideImageRef, +} from "./initializeDeployment/resolveDeploymentImageRef"; import { errAsync } from "neverthrow"; const nanoid = customAlphabet("1234567890abcdefghijklmnopqrstuvwxyz", 8); @@ -198,13 +202,39 @@ export class InitializeDeploymentService extends BaseService { environment.id, async (nextVersion) => { const [imageRefError, imageRefResult] = await tryCatch( - getDeploymentImageRef({ - registry: registryConfig, - projectRef: environment.project.externalRef, - nextVersion, - environmentType: environment.type, - deploymentShortCode, - }) + (async () => { + if (env.DEPLOY_IMAGE_OVERRIDE) { + // The override is the opt-in switch for the pre-built-image + // flow. When the caller supplies its own canonical + // imageReference (constrained to the override's + // registry/repository), honor it so the stamped image is + // deterministic instead of a function of this pod's boot-time + // override snapshot. + try { + return { + imageRef: resolveOverrideImageRef({ + override: env.DEPLOY_IMAGE_OVERRIDE, + clientImageReference: payload.imageReference, + }), + isEcr: false, + repoCreated: false, + }; + } catch (error) { + if (error instanceof ImageReferenceMismatchError) { + throw new ServiceValidationError(error.message); + } + throw error; + } + } + + return getDeploymentImageRef({ + registry: registryConfig, + projectRef: environment.project.externalRef, + nextVersion, + environmentType: environment.type, + deploymentShortCode, + }); + })() ); if (imageRefError) { @@ -216,6 +246,12 @@ export class InitializeDeploymentService extends BaseService { type: payload.type, cause: imageRefError.message, }); + // Surface a deliberate validation failure (e.g. a client + // imageReference that doesn't match the override repository) with + // its specific message rather than the generic fallback. + if (imageRefError instanceof ServiceValidationError) { + throw imageRefError; + } throw new ServiceValidationError("Failed to get deployment image ref"); } diff --git a/apps/webapp/app/v3/services/initializeDeployment/resolveDeploymentImageRef.ts b/apps/webapp/app/v3/services/initializeDeployment/resolveDeploymentImageRef.ts new file mode 100644 index 00000000000..12a6613c74b --- /dev/null +++ b/apps/webapp/app/v3/services/initializeDeployment/resolveDeploymentImageRef.ts @@ -0,0 +1,93 @@ +/** + * Pure resolution of the deployment image reference for single-tenant installs + * that set `DEPLOY_IMAGE_OVERRIDE`. Kept free of env/DB imports so it can be + * unit-tested directly (mirrors the `createDeploymentWithNextVersion` helper). + * + * Background: the override is the opt-in switch for the "pre-built canonical + * image" flow. When a caller (e.g. a self-hosted deploy hook that has already + * built and pushed the image) supplies its own `imageReference`, we honor it + * instead of the webapp pod's boot-time override snapshot so the stamped image + * is deterministic and not a function of pod rollout timing. To bound the + * supply-chain surface, the caller-supplied reference must share the override's + * registry + repository; the tag (version) and/or digest may differ. + */ + +export class ImageReferenceMismatchError extends Error { + readonly name = "ImageReferenceMismatchError"; + readonly clientRepository: string; + readonly overrideRepository: string; + + constructor(args: { clientRepository: string; overrideRepository: string }) { + super( + `Client imageReference repository "${args.clientRepository}" does not match the configured DEPLOY_IMAGE_OVERRIDE repository "${args.overrideRepository}"` + ); + this.clientRepository = args.clientRepository; + this.overrideRepository = args.overrideRepository; + } +} + +/** + * Split an image reference into its repository (registry host + path) and its + * tag/digest. Tolerates a `registry:port` host (the tag is only the segment + * after the last `:` that follows the last `/`) and a trailing `@sha256:...` + * digest. + */ +export function parseImageRef(imageRef: string): { + repository: string; + tag?: string; + digest?: string; +} { + let rest = imageRef; + let digest: string | undefined; + + const atIndex = rest.indexOf("@"); + if (atIndex !== -1) { + digest = rest.slice(atIndex + 1); + rest = rest.slice(0, atIndex); + } + + const lastSlash = rest.lastIndexOf("/"); + const lastColon = rest.lastIndexOf(":"); + + // A colon denotes a tag only when it comes after the last path separator; + // otherwise it is the `registry:port` host separator and there is no tag. + if (lastColon > lastSlash) { + return { + repository: rest.slice(0, lastColon), + tag: rest.slice(lastColon + 1), + digest, + }; + } + + return { repository: rest, digest }; +} + +/** + * Resolve the image reference to stamp on a deployment when + * `DEPLOY_IMAGE_OVERRIDE` is set. + * + * - No caller-supplied reference -> use the override verbatim (prior behavior). + * - Caller-supplied reference -> require the same registry/repository as the + * override and use it (so the tag/digest can move ahead deterministically). + * + * Throws {@link ImageReferenceMismatchError} when the repositories differ. + */ +export function resolveOverrideImageRef(args: { + override: string; + clientImageReference?: string; +}): string { + const { override, clientImageReference } = args; + + if (!clientImageReference) { + return override; + } + + const overrideRepository = parseImageRef(override).repository; + const clientRepository = parseImageRef(clientImageReference).repository; + + if (overrideRepository !== clientRepository) { + throw new ImageReferenceMismatchError({ clientRepository, overrideRepository }); + } + + return clientImageReference; +} diff --git a/apps/webapp/test/objectStoreClient.test.ts b/apps/webapp/test/objectStoreClient.test.ts new file mode 100644 index 00000000000..077774f1fba --- /dev/null +++ b/apps/webapp/test/objectStoreClient.test.ts @@ -0,0 +1,53 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { ObjectStoreClient } from "~/v3/objectStoreClient.server"; + +// Presigning is local SigV4 signing, so these tests need no network or containers. +// Static env credentials stand in for the IAM credential chain the client resolves at sign time. +const FIPS_ENDPOINT = "https://s3-fips.us-gov-west-1.amazonaws.com"; +const BUCKET = "trigger-bucket"; +const KEY = `${BUCKET}/packets/proj_123/run_456/payload.json`; + +function iamClient(forcePathStyle?: boolean) { + return ObjectStoreClient.create({ + baseUrl: FIPS_ENDPOINT, + bucket: BUCKET, + region: "us-gov-west-1", + ...(forcePathStyle === undefined ? {} : { forcePathStyle }), + }); +} + +describe("ObjectStoreClient IAM-mode addressing", () => { + beforeEach(() => { + vi.stubEnv("AWS_ACCESS_KEY_ID", "AKIAIOSFODNN7EXAMPLE"); + vi.stubEnv("AWS_SECRET_ACCESS_KEY", "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"); + vi.stubEnv("AWS_SESSION_TOKEN", undefined); + vi.stubEnv("AWS_PROFILE", undefined); + }); + + afterEach(() => { + vi.unstubAllEnvs(); + }); + + it("keeps path-style URLs when forcePathStyle is not set", async () => { + const url = new URL(await iamClient().presign(KEY, "PUT", 300)); + + expect(url.host).toBe("s3-fips.us-gov-west-1.amazonaws.com"); + expect(url.pathname).toBe(`/${KEY}`); + }); + + it("uses virtual-hosted URLs when forcePathStyle is false", async () => { + const url = new URL(await iamClient(false).presign(KEY, "PUT", 300)); + + expect(url.host).toBe(`${BUCKET}.s3-fips.us-gov-west-1.amazonaws.com`); + expect(url.pathname).toBe("/packets/proj_123/run_456/payload.json"); + expect(url.searchParams.get("X-Amz-Algorithm")).toBe("AWS4-HMAC-SHA256"); + expect(url.searchParams.get("X-Amz-Expires")).toBe("300"); + }); + + it("applies the same addressing to GET presigns", async () => { + const url = new URL(await iamClient(false).presign(KEY, "GET", 300)); + + expect(url.host).toBe(`${BUCKET}.s3-fips.us-gov-west-1.amazonaws.com`); + expect(url.pathname).toBe("/packets/proj_123/run_456/payload.json"); + }); +}); diff --git a/apps/webapp/test/resolveDeploymentImageRef.test.ts b/apps/webapp/test/resolveDeploymentImageRef.test.ts new file mode 100644 index 00000000000..4e5ff049ca4 --- /dev/null +++ b/apps/webapp/test/resolveDeploymentImageRef.test.ts @@ -0,0 +1,81 @@ +import { describe, expect, it } from "vitest"; +import { + ImageReferenceMismatchError, + parseImageRef, + resolveOverrideImageRef, +} from "../app/v3/services/initializeDeployment/resolveDeploymentImageRef"; + +describe("parseImageRef", () => { + it("splits registry/repository and tag", () => { + expect(parseImageRef("registry.example.com/acme/tasks:0.0.106")).toEqual({ + repository: "registry.example.com/acme/tasks", + tag: "0.0.106", + digest: undefined, + }); + }); + + it("treats a registry:port host as part of the repository, not a tag", () => { + expect(parseImageRef("localhost:5001/tasks")).toEqual({ + repository: "localhost:5001/tasks", + tag: undefined, + digest: undefined, + }); + }); + + it("handles registry:port host with a tag", () => { + expect(parseImageRef("localhost:5001/tasks:0.0.106")).toEqual({ + repository: "localhost:5001/tasks", + tag: "0.0.106", + digest: undefined, + }); + }); + + it("strips a trailing @sha256 digest", () => { + expect( + parseImageRef( + "123456789012.dkr.ecr.us-east-1.amazonaws.com/acme/tasks:0.0.107@sha256:" + "a".repeat(64) + ) + ).toEqual({ + repository: "123456789012.dkr.ecr.us-east-1.amazonaws.com/acme/tasks", + tag: "0.0.107", + digest: "sha256:" + "a".repeat(64), + }); + }); +}); + +describe("resolveOverrideImageRef", () => { + const override = "registry.example.com/acme/tasks:0.0.104"; + + it("returns the override verbatim when no client imageReference is supplied", () => { + expect(resolveOverrideImageRef({ override })).toBe(override); + }); + + it("returns the client imageReference when it shares the override registry/repository", () => { + const clientImageReference = "registry.example.com/acme/tasks:0.0.106"; + expect(resolveOverrideImageRef({ override, clientImageReference })).toBe(clientImageReference); + }); + + it("allows the client imageReference to add a digest to the same tag", () => { + const clientImageReference = "registry.example.com/acme/tasks:0.0.104@sha256:" + "b".repeat(64); + expect(resolveOverrideImageRef({ override, clientImageReference })).toBe(clientImageReference); + }); + + it("allows the client imageReference to differ by both tag and digest", () => { + const clientImageReference = "registry.example.com/acme/tasks:0.0.106@sha256:" + "c".repeat(64); + expect(resolveOverrideImageRef({ override, clientImageReference })).toBe(clientImageReference); + }); + + it("throws when the client imageReference repository differs from the override", () => { + const clientImageReference = "evil.example.com/attacker/image:latest"; + expect(() => resolveOverrideImageRef({ override, clientImageReference })).toThrow( + ImageReferenceMismatchError + ); + }); + + it("throws when only the registry host differs (same path)", () => { + const clientImageReference = "evil.example.com/acme/tasks:0.0.106"; + expect(() => resolveOverrideImageRef({ override, clientImageReference })).toThrow( + ImageReferenceMismatchError + ); + }); +}); diff --git a/docker/scripts/entrypoint.sh b/docker/scripts/entrypoint.sh index 1e5c7c7cab0..265859b777b 100755 --- a/docker/scripts/entrypoint.sh +++ b/docker/scripts/entrypoint.sh @@ -1,6 +1,11 @@ #!/bin/sh set -xe +if [ "$1" = "migrate" ]; then + echo "Running migrations only (entrypoint.sh migrate mode)" + SKIP_POSTGRES_MIGRATIONS=0 +fi + if [ -n "$DATABASE_HOST" ]; then scripts/wait-for-it.sh ${DATABASE_HOST} -- echo "database is up" fi @@ -85,6 +90,11 @@ else fi set -x +if [ "$1" = "migrate" ]; then + echo "Migrations complete, exiting." + exit 0 +fi + # Copy over required prisma files cp internal-packages/database/prisma/schema.prisma apps/webapp/prisma/ cp node_modules/@prisma/engines/*.node apps/webapp/prisma/ diff --git a/docs/self-hosting/env/webapp.mdx b/docs/self-hosting/env/webapp.mdx index 09416f0f38f..ac558242765 100644 --- a/docs/self-hosting/env/webapp.mdx +++ b/docs/self-hosting/env/webapp.mdx @@ -88,12 +88,14 @@ mode: "wide" | `OBJECT_STORE_SECRET_ACCESS_KEY` | No | — | Object store secret key (default provider). | | `OBJECT_STORE_REGION` | No | — | Object store region (default provider). | | `OBJECT_STORE_SERVICE` | No | s3 | Object store service (default provider). | +| `OBJECT_STORE_FORCE_PATH_STYLE` | No | true | IAM mode only (no access keys). Set `false` for virtual-hosted addressing, which AWS FIPS endpoints require. | | `OBJECT_STORE_DEFAULT_PROTOCOL` | No | — | Protocol for new uploads (e.g. `s3`, `r2`). Enables protocol-prefixed storage. See migration guide below. | | `OBJECT_STORE_{PROTOCOL}_BASE_URL` | No | — | Named provider base URL (replace `{PROTOCOL}`, e.g. `OBJECT_STORE_S3_BASE_URL`). | | `OBJECT_STORE_{PROTOCOL}_ACCESS_KEY_ID` | No | — | Named provider access key. | | `OBJECT_STORE_{PROTOCOL}_SECRET_ACCESS_KEY` | No | — | Named provider secret key. | | `OBJECT_STORE_{PROTOCOL}_REGION` | No | — | Named provider region. | | `OBJECT_STORE_{PROTOCOL}_SERVICE` | No | — | Named provider service. | +| `OBJECT_STORE_{PROTOCOL}_FORCE_PATH_STYLE` | No | true | Named provider path-style addressing (IAM mode only). | | `ARTIFACTS_OBJECT_STORE_BUCKET` | No | — | Optional separate bucket for artifacts. If not set, uses main object store. | | `ARTIFACTS_OBJECT_STORE_BASE_URL` | No | — | Optional artifacts store base URL. | | `ARTIFACTS_OBJECT_STORE_ACCESS_KEY_ID` | No | — | Optional artifacts store access key. | diff --git a/hosting/k8s/helm/Chart.yaml b/hosting/k8s/helm/Chart.yaml index e40b51845c3..e860553631a 100644 --- a/hosting/k8s/helm/Chart.yaml +++ b/hosting/k8s/helm/Chart.yaml @@ -2,7 +2,7 @@ apiVersion: v2 name: trigger description: The official Trigger.dev Helm chart type: application -version: 4.5.7 +version: 4.5.7-plt663.12 appVersion: v4.5.7 home: https://trigger.dev sources: diff --git a/hosting/k8s/helm/README.md b/hosting/k8s/helm/README.md index 79c49138215..97ac89fcfdc 100644 --- a/hosting/k8s/helm/README.md +++ b/hosting/k8s/helm/README.md @@ -225,6 +225,110 @@ postgres: memory: 2Gi ``` +### CA bundle injection (webapp + supervisor) + +For environments where the webapp or supervisor needs to validate TLS against an internal/private CA (e.g. a corporate proxy, an enterprise image registry, an internal trigger.dev API endpoint), mount the CA bundle into the pod via `extraVolumes` / `extraVolumeMounts` and point Node at it with `NODE_EXTRA_CA_CERTS`: + +```yaml +webapp: + extraVolumes: + - name: ca-bundle + configMap: + name: enterprise-ca-bundle + extraVolumeMounts: + - name: ca-bundle + mountPath: /etc/ssl/enterprise-ca + readOnly: true + extraEnvVars: + - name: NODE_EXTRA_CA_CERTS + value: /etc/ssl/enterprise-ca/ca.crt + +supervisor: + extraVolumes: + - name: ca-bundle + configMap: + name: enterprise-ca-bundle + extraVolumeMounts: + - name: ca-bundle + mountPath: /etc/ssl/enterprise-ca + readOnly: true + extraEnvVars: + - name: NODE_EXTRA_CA_CERTS + value: /etc/ssl/enterprise-ca/ca.crt +``` + +The supervisor `extraVolumes` / `extraVolumeMounts` keys behave identically to the webapp ones. Both render unconditionally — they don't require any other feature toggle. + +### Supervisor init containers + +`supervisor.extraInitContainers` prepends init containers to the supervisor pod. It accepts a list, or a string that is `tpl`-rendered in chart scope (the same contract as `webapp.extraContainers`), so entries can use helpers such as `trigger-v4.fullname`. + +The supervisor makes one connect call to the webapp when it boots and exits 1 if that call fails; Kubernetes then restarts it with backoff. If your webapp is a single replica that runs migrations at boot, a node drain that reschedules both pods leaves the supervisor crash-looping until the webapp is back. Gating on the webapp health endpoint avoids the restarts: + +```yaml +supervisor: + extraInitContainers: | + - name: wait-for-webapp + image: curlimages/curl:8.5.0 + command: ["/bin/sh", "-c"] + args: + - | + until curl -sf http://{{ include "trigger-v4.fullname" . }}-webapp:{{ .Values.webapp.service.port }}/healthcheck; do + echo "webapp not ready"; sleep 5 + done +``` + +The pod sits in `Init:0/1` (no restart counter) until the webapp answers, then the supervisor starts and connects normally. + +### Worker pod security context + +By default the supervisor doesn't set a `securityContext` on the worker pods it schedules — it lets the cluster's PodSecurity admission / SCC apply whatever defaults are configured. If you need to enforce explicit pod- or container-level security, set: + +```yaml +supervisor: + extraEnvVars: + - name: KUBERNETES_WORKER_POD_SECURITY_CONTEXT + value: '{"runAsNonRoot":true,"runAsUser":1000,"fsGroup":1000}' + - name: KUBERNETES_WORKER_CONTAINER_SECURITY_CONTEXT + value: '{"runAsNonRoot":true,"runAsUser":1000,"allowPrivilegeEscalation":false,"capabilities":{"drop":["ALL"]},"seccompProfile":{"type":"RuntimeDefault"}}' +``` + +These map directly to Kubernetes `V1PodSecurityContext` and `V1SecurityContext`. Don't set `runAsUser` on OpenShift — leave both env vars unset and let the namespace SCC inject the UID range. + +To pass extra annotations (e.g. for service-mesh sidecar injection) onto every worker pod: + +```yaml +supervisor: + extraEnvVars: + - name: KUBERNETES_WORKER_POD_ANNOTATIONS + value: '{"sidecar.istio.io/inject":"false"}' +``` + +### Worker pod volumes + +`supervisor.config.kubernetes.workerVolumes` and `workerVolumeMounts` add volumes to every worker (task run) pod the supervisor creates, and mount them into its `run-controller` container. Both take plain Kubernetes `V1Volume` / `V1VolumeMount` objects and default to `[]`, which leaves worker pods unchanged. + +A common use is giving task code a private CA bundle so it can call internal HTTPS endpoints. Mount the bundle, then point Node in the worker pods at it by adding `NODE_EXTRA_CA_CERTS` to the supervisor's `RUNNER_ADDITIONAL_ENV_VARS` (a comma-separated `KEY=value` list the supervisor copies into every worker pod): + +```yaml +supervisor: + config: + kubernetes: + workerVolumes: + - name: extra-ca + configMap: + name: my-ca-bundle + workerVolumeMounts: + - name: extra-ca + mountPath: /etc/ssl/extra-ca + readOnly: true + extraEnvVars: + - name: RUNNER_ADDITIONAL_ENV_VARS + value: NODE_EXTRA_CA_CERTS=/etc/ssl/extra-ca/ca.pem +``` + +The volumes are added to the pod spec alongside anything the supervisor already sets. Each mount must name a volume in `workerVolumes`, volume names and mount paths must be unique, each volume needs exactly one source, and top-level keys outside `V1Volume` / `V1VolumeMount` (such as a misspelled `configmap`) are rejected; the supervisor checks all of this at startup and exits with an error naming `KUBERNETES_WORKER_VOLUMES` or `KUBERNETES_WORKER_VOLUME_MOUNTS` if anything is wrong. Fields nested inside a volume source are passed through unchecked, and the Kubernetes client drops any it doesn't recognise, so check spelling there by hand. The volume source (for example the configmap) must exist in the namespace the worker pods run in, otherwise every worker pod stays in `ContainerCreating` and runs hang until they time out. + ## Deployment Modes ### Testing/Development diff --git a/hosting/k8s/helm/templates/_helpers.tpl b/hosting/k8s/helm/templates/_helpers.tpl index 0ecc17b9893..aa5a82bf49e 100644 --- a/hosting/k8s/helm/templates/_helpers.tpl +++ b/hosting/k8s/helm/templates/_helpers.tpl @@ -422,11 +422,14 @@ ClickHouse hostname {{/* ClickHouse URL for application (with secure parameter) -Note on the external+existingSecret branch: the password is expanded via +Note on `$(CLICKHOUSE_PASSWORD)`: the password is expanded via Kubernetes' `$(VAR)` syntax, not shell `${VAR}`. Kubelet substitutes `$(CLICKHOUSE_PASSWORD)` at container-creation time from the CLICKHOUSE_PASSWORD env var declared just before CLICKHOUSE_URL in -webapp.yaml. Shell-style `${...}` does not work here because +webapp.yaml. Both the `deploy: true` and external+existingSecret +branches use this placeholder so that the chart never bakes the +password literal into a rendered URL string. Shell-style `${...}` +does not work here because `docker/scripts/entrypoint.sh` assigns CLICKHOUSE_URL to GOOSE_DBSTRING with a single-pass expansion (`export GOOSE_DBSTRING="$CLICKHOUSE_URL"`), so any inner `${...}` reaches goose verbatim and fails URL parsing. diff --git a/hosting/k8s/helm/templates/electric.yaml b/hosting/k8s/helm/templates/electric.yaml index 5bb1964a0e9..836048e7611 100644 --- a/hosting/k8s/helm/templates/electric.yaml +++ b/hosting/k8s/helm/templates/electric.yaml @@ -15,7 +15,7 @@ spec: metadata: {{- with .Values.electric.podAnnotations }} annotations: - {{- toYaml . | nindent 8 }} + {{- tpl (toYaml .) $ | nindent 8 }} {{- end }} labels: {{- include "trigger-v4.componentSelectorLabels" (dict "Chart" .Chart "Release" .Release "Values" .Values "component" $component) | nindent 8 }} @@ -59,7 +59,7 @@ spec: - name: ELECTRIC_USAGE_REPORTING value: {{ .Values.electric.config.usageReporting | quote }} {{- with .Values.electric.extraEnvVars }} - {{- toYaml . | nindent 12 }} + {{- tpl (toYaml .) $ | nindent 12 }} {{- end }} {{- if .Values.electric.livenessProbe.enabled }} livenessProbe: @@ -96,6 +96,14 @@ spec: {{- end }} resources: {{- toYaml .Values.electric.resources | nindent 12 }} + {{- with .Values.electric.extraVolumeMounts }} + volumeMounts: + {{- tpl (toYaml .) $ | nindent 12 }} + {{- end }} + {{- with .Values.electric.extraVolumes }} + volumes: + {{- tpl (toYaml .) $ | nindent 8 }} + {{- end }} --- apiVersion: v1 kind: Service diff --git a/hosting/k8s/helm/templates/supervisor.yaml b/hosting/k8s/helm/templates/supervisor.yaml index 11fd7a7f6d9..e1276f9d5e0 100644 --- a/hosting/k8s/helm/templates/supervisor.yaml +++ b/hosting/k8s/helm/templates/supervisor.yaml @@ -67,7 +67,7 @@ spec: {{- include "trigger-v4.componentSelectorLabels" (dict "Chart" .Chart "Release" .Release "Values" .Values "component" $component) | nindent 8 }} {{- with .Values.supervisor.podAnnotations }} annotations: - {{- toYaml . | nindent 8 }} + {{- tpl (toYaml .) $ | nindent 8 }} {{- end }} spec: serviceAccountName: {{ include "trigger-v4.supervisorServiceAccountName" . }} @@ -76,8 +76,23 @@ spec: {{- with .Values.supervisor.podSecurityContext }} {{- toYaml . | nindent 8 }} {{- end }} - {{- if not .Values.webapp.bootstrap.enabled }} + {{- /* + extraInitContainers is tpl-rendered into a variable first (string or + list, same contract as webapp.extraContainers) so `initContainers:` is + only emitted when something actually renders — a template string that + evaluates to nothing would otherwise leave a null list behind. + */}} + {{- $extraInitContainers := "" }} + {{- with .Values.supervisor.extraInitContainers }} + {{- if kindIs "string" . }} + {{- $extraInitContainers = tpl . $ | trim }} + {{- else }} + {{- $extraInitContainers = tpl (toYaml .) $ | trim }} + {{- end }} + {{- end }} + {{- if or (not .Values.webapp.bootstrap.enabled) $extraInitContainers }} initContainers: + {{- if not .Values.webapp.bootstrap.enabled }} - name: init-shared image: busybox:1.35 command: ['sh', '-c', 'mkdir -p /home/node/shared'] @@ -86,6 +101,10 @@ spec: volumeMounts: - name: shared mountPath: /home/node/shared + {{- end }} + {{- with $extraInitContainers }} + {{- . | nindent 8 }} + {{- end }} {{- end }} containers: - name: supervisor @@ -136,7 +155,12 @@ spec: env: # Core configuration - name: TRIGGER_API_URL + {{- if and .Values.nginx.enabled .Values.nginx.tls.enabled }} + # Use internal TLS service (bypasses oauth2-proxy, still encrypted) + value: "https://{{ include "trigger-v4.fullname" . }}-webapp-internal.{{ .Release.Namespace }}.svc.cluster.local:{{ .Values.nginx.internalPort | default 3031 }}" + {{- else }} value: "http://{{ include "trigger-v4.fullname" . }}-webapp:{{ .Values.webapp.service.port }}" + {{- end }} - name: TRIGGER_WORKER_TOKEN {{- if .Values.webapp.bootstrap.enabled }} valueFrom: @@ -170,6 +194,30 @@ spec: value: {{ .Values.supervisor.config.kubernetes.forceEnabled | quote }} - name: KUBERNETES_WORKER_NODETYPE_LABEL value: {{ .Values.supervisor.config.kubernetes.workerNodetypeLabel | quote }} + - name: KUBERNETES_WORKER_SERVICE_ACCOUNT + value: {{ .Values.supervisor.config.kubernetes.workerServiceAccount | quote }} + - name: KUBERNETES_WORKER_AUTOMOUNT_SERVICE_ACCOUNT_TOKEN + value: {{ .Values.supervisor.config.kubernetes.workerAutomountServiceAccountToken | quote }} + {{- if .Values.supervisor.config.kubernetes.workerPodSecurityContext }} + - name: KUBERNETES_WORKER_POD_SECURITY_CONTEXT + value: {{ .Values.supervisor.config.kubernetes.workerPodSecurityContext | toJson | quote }} + {{- end }} + {{- if .Values.supervisor.config.kubernetes.workerContainerSecurityContext }} + - name: KUBERNETES_WORKER_CONTAINER_SECURITY_CONTEXT + value: {{ .Values.supervisor.config.kubernetes.workerContainerSecurityContext | toJson | quote }} + {{- end }} + {{- if .Values.supervisor.config.kubernetes.workerPodAnnotations }} + - name: KUBERNETES_WORKER_POD_ANNOTATIONS + value: {{ .Values.supervisor.config.kubernetes.workerPodAnnotations | toJson | quote }} + {{- end }} + {{- if .Values.supervisor.config.kubernetes.workerVolumes }} + - name: KUBERNETES_WORKER_VOLUMES + value: {{ .Values.supervisor.config.kubernetes.workerVolumes | toJson | quote }} + {{- end }} + {{- if .Values.supervisor.config.kubernetes.workerVolumeMounts }} + - name: KUBERNETES_WORKER_VOLUME_MOUNTS + value: {{ .Values.supervisor.config.kubernetes.workerVolumeMounts | toJson | quote }} + {{- end }} {{- $registryAuthEnabled := false }} {{- if .Values.registry.deploy }} {{- $registryAuthEnabled = .Values.registry.auth.enabled }} @@ -237,21 +285,31 @@ spec: value: {{ .Values.supervisor.config.debug | quote }} # OTEL - name: OTEL_EXPORTER_OTLP_ENDPOINT + {{- if and .Values.nginx.enabled .Values.nginx.tls.enabled }} + value: "https://{{ include "trigger-v4.fullname" . }}-webapp-internal.{{ .Release.Namespace }}.svc.cluster.local:{{ .Values.nginx.internalPort | default 3031 }}/otel" + {{- else }} value: "http://{{ include "trigger-v4.fullname" . }}-webapp.{{ .Release.Namespace }}.svc.cluster.local:{{ .Values.webapp.service.port }}/otel" + {{- end }} {{- with .Values.supervisor.extraEnvVars }} - {{- toYaml . | nindent 12 }} + {{- tpl (toYaml .) $ | nindent 12 }} {{- end }} - {{- if not .Values.webapp.bootstrap.enabled }} + {{- if or (not .Values.webapp.bootstrap.enabled) .Values.supervisor.extraVolumeMounts }} volumeMounts: + {{- if not .Values.webapp.bootstrap.enabled }} - name: shared mountPath: /home/node/shared + {{- end }} + {{- with .Values.supervisor.extraVolumeMounts }} + {{- tpl (toYaml .) $ | nindent 12 }} + {{- end }} {{- end }} {{- with .Values.supervisor.securityContext }} securityContext: {{- toYaml . | nindent 12 }} {{- end }} - {{- if not .Values.webapp.bootstrap.enabled }} + {{- if or (not .Values.webapp.bootstrap.enabled) .Values.supervisor.extraVolumes }} volumes: + {{- if not .Values.webapp.bootstrap.enabled }} - name: shared {{- if .Values.persistence.shared.enabled }} persistentVolumeClaim: @@ -259,6 +317,10 @@ spec: {{- else }} emptyDir: {} {{- end }} + {{- end }} + {{- with .Values.supervisor.extraVolumes }} + {{- tpl (toYaml .) $ | nindent 8 }} + {{- end }} {{- end }} {{- with .Values.supervisor.nodeSelector }} nodeSelector: diff --git a/hosting/k8s/helm/templates/webapp.yaml b/hosting/k8s/helm/templates/webapp.yaml index 49acee98f4a..1b8a5b2e2d4 100644 --- a/hosting/k8s/helm/templates/webapp.yaml +++ b/hosting/k8s/helm/templates/webapp.yaml @@ -49,6 +49,10 @@ metadata: {{- include "trigger-v4.componentLabels" (dict "Chart" .Chart "Release" .Release "Values" .Values "component" $component) | nindent 4 }} spec: replicas: {{ .Values.webapp.replicaCount }} + {{- with .Values.webapp.strategy }} + strategy: + {{- toYaml . | nindent 4 }} + {{- end }} selector: matchLabels: {{- include "trigger-v4.componentSelectorLabels" (dict "Chart" .Chart "Release" .Release "Values" .Values "component" $component) | nindent 6 }} @@ -57,7 +61,7 @@ spec: annotations: kubectl.kubernetes.io/default-container: webapp {{- with .Values.webapp.podAnnotations }} - {{- toYaml . | nindent 8 }} + {{- tpl (toYaml .) $ | nindent 8 }} {{- end }} labels: {{- include "trigger-v4.componentSelectorLabels" (dict "Chart" .Chart "Release" .Release "Values" .Values "component" $component) | nindent 8 }} @@ -77,18 +81,31 @@ spec: image: {{ include "trigger-v4.webapp.volumePermissions.image" . }} imagePullPolicy: {{ .Values.webapp.volumePermissions.image.pullPolicy }} command: ['sh', '-c', 'mkdir -p /home/node/shared'] + {{- with .Values.webapp.initContainers.securityContext }} + securityContext: + {{- toYaml . | nindent 12 }} + {{- else }} securityContext: runAsUser: 1000 + {{- end }} volumeMounts: - name: shared mountPath: /home/node/shared + {{- with .Values.webapp.extraInitContainers }} + {{- toYaml . | nindent 8 }} + {{- end }} containers: - name: token-syncer image: {{ include "trigger-v4.webapp.tokenSyncer.image" . }} imagePullPolicy: {{ .Values.webapp.tokenSyncer.image.pullPolicy }} + {{- with .Values.webapp.sidecarContainers.securityContext }} + securityContext: + {{- toYaml . | nindent 12 }} + {{- else }} securityContext: runAsUser: 1000 runAsNonRoot: true + {{- end }} command: - /bin/bash - -c @@ -328,6 +345,24 @@ spec: secretKeyRef: name: {{ include "trigger-v4.secretsName" . }} key: MANAGED_WORKER_SECRET + {{- end }} + {{- /* + Object-store credentials are scoped independently of the four + session secrets above. Three branches: + 1. s3.deploy → mount from the chart's internal MinIO + creds (s3.auth.existingSecret or the + chart-managed s3-auth-* keys). + 2. s3.external.useIam → skip entirely. IRSA / Workload + Identity provides credentials to the + SDK; mounting OBJECT_STORE_* would + force static-key mode. + 3. external static keys → s3.external.existingSecret, OR + s3.external.accessKeyId when the + chart is provisioning its own + secret (requires secrets.enabled + so secrets.yaml actually writes + s3-access-key-id). + */}} {{- if .Values.s3.deploy }} {{- if .Values.s3.auth.existingSecret }} - name: OBJECT_STORE_ACCESS_KEY_ID @@ -352,7 +387,7 @@ spec: name: {{ include "trigger-v4.secretsName" . }} key: s3-auth-secret-access-key {{- end }} - {{- else }} + {{- else if not .Values.s3.external.useIam }} {{- if .Values.s3.external.existingSecret }} - name: OBJECT_STORE_ACCESS_KEY_ID valueFrom: @@ -364,7 +399,7 @@ spec: secretKeyRef: name: {{ include "trigger-v4.s3.external.secretName" . }} key: {{ include "trigger-v4.s3.external.secretAccessKeyKey" . }} - {{- else if .Values.s3.external.accessKeyId }} + {{- else if and .Values.secrets.enabled .Values.s3.external.accessKeyId }} - name: OBJECT_STORE_ACCESS_KEY_ID valueFrom: secretKeyRef: @@ -377,7 +412,6 @@ spec: key: s3-secret-access-key {{- end }} {{- end }} - {{- end }} {{- if .Values.webapp.observability }} {{- if .Values.webapp.observability.tracing.exporterUrl }} - name: INTERNAL_OTEL_TRACE_EXPORTER_URL @@ -412,7 +446,7 @@ spec: - name: INTERNAL_OTEL_METRIC_EXPORTER_INTERVAL_MS value: {{ .Values.webapp.observability.metrics.exporterIntervalMs | quote }} {{- end }} - {{- if and .Values.clickhouse.external.host .Values.clickhouse.external.existingSecret }} + {{- if and (not .Values.clickhouse.deploy) .Values.clickhouse.external.host .Values.clickhouse.external.existingSecret }} - name: CLICKHOUSE_PASSWORD valueFrom: secretKeyRef: @@ -440,14 +474,21 @@ spec: value: "1" {{- end }} {{- with .Values.webapp.extraEnvVars }} - {{- toYaml . | nindent 12 }} + {{- tpl (toYaml .) $ | nindent 12 }} {{- end }} volumeMounts: - name: shared mountPath: /home/node/shared {{- with .Values.webapp.extraVolumeMounts }} - {{- toYaml . | nindent 12 }} + {{- tpl (toYaml .) $ | nindent 12 }} {{- end }} + {{- with .Values.webapp.extraContainers }} + {{- if kindIs "string" . }} + {{- tpl . $ | nindent 8 }} + {{- else }} + {{- tpl (toYaml .) $ | nindent 8 }} + {{- end }} + {{- end }} volumes: - name: shared {{- if .Values.persistence.shared.enabled }} @@ -457,7 +498,11 @@ spec: emptyDir: {} {{- end }} {{- with .Values.webapp.extraVolumes }} - {{- toYaml . | nindent 8 }} + {{- if kindIs "string" . }} + {{- tpl . $ | nindent 8 }} + {{- else }} + {{- tpl (toYaml .) $ | nindent 8 }} + {{- end }} {{- end }} {{- with .Values.webapp.nodeSelector }} nodeSelector: @@ -483,13 +528,17 @@ metadata: labels: {{- $component := "webapp" }} {{- include "trigger-v4.componentLabels" (dict "Chart" .Chart "Release" .Release "Values" .Values "component" $component) | nindent 4 }} + {{- with .Values.webapp.service.annotations }} + annotations: + {{- toYaml . | nindent 4 }} + {{- end }} spec: type: {{ .Values.webapp.service.type }} ports: - port: {{ .Values.webapp.service.port }} - targetPort: http + targetPort: {{ .Values.webapp.service.servicePortTargetPort | default .Values.webapp.service.targetPort | default "http" }} protocol: TCP - name: http + name: {{ .Values.webapp.service.name | default "http" }} selector: {{- include "trigger-v4.componentSelectorLabels" (dict "Chart" .Chart "Release" .Release "Values" .Values "component" $component) | nindent 4 }} --- diff --git a/hosting/k8s/helm/values.yaml b/hosting/k8s/helm/values.yaml index e76a921279c..83f3c90f665 100644 --- a/hosting/k8s/helm/values.yaml +++ b/hosting/k8s/helm/values.yaml @@ -76,6 +76,13 @@ webapp: replicaCount: 1 + # Deployment update strategy. Empty keeps the Kubernetes default (RollingUpdate). + # Set `type: Recreate` when the webapp mounts a ReadWriteOnce volume (e.g. + # `persistence.shared` with the default access mode): a rolling update starts + # the new pod before the old one stops, and the new pod cannot attach the + # volume while the old pod still holds it. + strategy: {} + service: type: ClusterIP port: 3030 @@ -177,6 +184,44 @@ webapp: # mountPath: /etc/ssl/certs # readOnly: true + # Extra containers added to the webapp pod (sidecars). Useful for + # in-pod TLS (nginx, envoy), log shippers, audit agents, etc. + extraContainers: + [] + # - name: nginx-tls + # image: nginx:alpine + # ports: + # - name: https-internal + # containerPort: 3031 + # volumeMounts: + # - name: nginx-config + # mountPath: /etc/nginx/conf.d + # - name: nginx-tls-certs + # mountPath: /etc/nginx/tls + + # Extra init containers added to the webapp pod, scheduled after the + # built-in `volume-permissions` init. + extraInitContainers: + [] + # - name: wait-for-secrets + # image: busybox + # command: [...] + + # Container-level securityContext applied to the built-in + # `volume-permissions` init container. When unset, defaults to + # `runAsUser: 1000`. Set this to enforce stricter pod-security + # admission (e.g. FIPS / FedRAMP / Pod Security Standards "restricted": + # `runAsNonRoot: true`, `allowPrivilegeEscalation: false`, + # `capabilities.drop: [ALL]`, `seccompProfile.type: RuntimeDefault`). + initContainers: + securityContext: {} + + # Container-level securityContext applied to the built-in `token-syncer` + # sidecar. Same shape + intent as `webapp.initContainers.securityContext`. + # Defaults to `{ runAsUser: 1000, runAsNonRoot: true }` when unset. + sidecarContainers: + securityContext: {} + # ServiceMonitor for Prometheus monitoring serviceMonitor: enabled: false @@ -296,6 +341,26 @@ supervisor: forceEnabled: true namespace: "" # Default: uses release namespace workerNodetypeLabel: "" # When set, runs will only be scheduled on nodes with "nodetype=