From 783a9f8781ce01a57918f1781745690da56c9ff1 Mon Sep 17 00:00:00 2001 From: JamesVictor-O Date: Fri, 20 Nov 2026 22:47:18 +0100 Subject: [PATCH 1/4] ci: pin all GitHub Actions to commit SHAs with Dependabot automation Every third-party action in .github/workflows (199 references, 25 actions) now uses a full commit SHA with the release as a trailing comment, so a moved tag or branch can no longer change what runs in CI. dtolnay/rust-toolchain picks the toolchain from its ref, so the pinned steps now pass toolchain: stable/nightly explicitly. Dependabot gains a github-actions entry that bumps SHA and comment together, grouping minor and patch updates. The top-level security-updates block is removed: it is not a Dependabot v2 key and made GitHub reject the entire config, so no update entry applied. scripts/workflow-pins.test.mjs fails make test-tooling on any unpinned reference, a missing version comment, one release pinned to two SHAs, a pinned rust-toolchain without a toolchain input, or an invalid Dependabot config. The CI tooling filter now also runs on any workflow or dependabot.yml change. CONTRIBUTING documents the policy. Closes #1468 --- .github/dependabot.yml | 55 +++---- .github/workflows/auto-merge.yml | 2 +- .github/workflows/autoscaling.yml | 6 +- .github/workflows/backup.yml | 8 +- .github/workflows/benchmarks.yml | 10 +- .github/workflows/blue-green-deploy.yml | 4 +- .github/workflows/canary-deployment.yml | 4 +- .github/workflows/canary.yml | 6 +- .github/workflows/ci.yml | 39 ++--- .github/workflows/commitlint.yml | 4 +- .github/workflows/config-validation.yml | 4 +- .github/workflows/contracts-evm.yml | 12 +- .github/workflows/cost-monitor.yml | 10 +- .github/workflows/coverage.yml | 6 +- .github/workflows/devcontainer.yml | 6 +- .github/workflows/docker-build.yml | 8 +- .github/workflows/e2e.yml | 22 +-- .github/workflows/formal-verification.yml | 12 +- .github/workflows/fuzz-testing.yml | 33 ++-- .github/workflows/gas-checks.yml | 10 +- .github/workflows/generate-docs.yml | 8 +- .github/workflows/integration.yml | 12 +- .github/workflows/k6-load-test.yml | 6 +- .github/workflows/migrations.yml | 4 +- .github/workflows/performance-monitoring.yml | 16 +- .github/workflows/platform-services.yml | 16 +- .github/workflows/release.yml | 8 +- .github/workflows/sdk-docs.yml | 10 +- .github/workflows/sdk-generation.yml | 32 ++-- .github/workflows/security-audit-pipeline.yml | 42 ++--- .github/workflows/security-audit.yml | 37 ++--- .github/workflows/size-limit.yml | 6 +- .github/workflows/tenant-isolation.yml | 4 +- .github/workflows/types-contract.yml | 4 +- CONTRIBUTING.md | 19 +++ scripts/workflow-pins.test.mjs | 152 ++++++++++++++++++ 36 files changed, 407 insertions(+), 230 deletions(-) create mode 100644 scripts/workflow-pins.test.mjs diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 924492e7..f42a9902 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -74,38 +74,35 @@ updates: - "root" versioning-strategy: "increase" -# Enable security updates -security-updates: - - package-ecosystem: "npm" - directory: "/backend" + # GitHub Actions (#1468). Every workflow pins each action to a full commit + # SHA with the release tag as a trailing comment, e.g. + # uses: actions/checkout@<40-char sha> # v4.4.0 + # Dependabot bumps the SHA and the comment together. Minor and patch bumps + # arrive as one grouped PR; a major bump gets its own PR so its changelog + # can be reviewed. scripts/workflow-pins.test.mjs fails CI on any unpinned + # `uses:` reference. + - package-ecosystem: "github-actions" + directory: "/" schedule: - interval: "daily" - open-pull-requests-limit: 10 - reviewers: - - "mmesolove" - assignees: - - "mmesolove" + interval: "weekly" + day: "monday" + time: "09:00" + open-pull-requests-limit: 5 commit-message: - prefix: "security" + prefix: "ci" include: "scope" labels: - - "security" - "dependencies" - - "backend" + - "github-actions" + groups: + github-actions-minor-and-patch: + patterns: + - "*" + update-types: + - "minor" + - "patch" - - package-ecosystem: "npm" - directory: "/frontend" - schedule: - interval: "daily" - open-pull-requests-limit: 10 - reviewers: - - "mmesolove" - assignees: - - "mmesolove" - commit-message: - prefix: "security" - include: "scope" - labels: - - "security" - - "dependencies" - - "frontend" +# Security updates are not configured in this file: Dependabot v2 rejects +# unknown top-level keys, and the former `security-updates:` block made the +# whole config invalid. Enable "Dependabot security updates" under +# Settings > Code security instead; they then cover every ecosystem above. diff --git a/.github/workflows/auto-merge.yml b/.github/workflows/auto-merge.yml index e3aaa0d9..cb8eddbd 100644 --- a/.github/workflows/auto-merge.yml +++ b/.github/workflows/auto-merge.yml @@ -15,7 +15,7 @@ jobs: runs-on: ubuntu-latest steps: - name: Auto-merge PR if no conflicts - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 with: script: | const pr = context.payload.pull_request; diff --git a/.github/workflows/autoscaling.yml b/.github/workflows/autoscaling.yml index 40aef1bb..7929c320 100644 --- a/.github/workflows/autoscaling.yml +++ b/.github/workflows/autoscaling.yml @@ -140,7 +140,7 @@ jobs: cat scaling-manifest.json - name: Upload scaling manifest - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: scaling-manifest-${{ github.run_number }} path: scaling-manifest.json @@ -158,10 +158,10 @@ jobs: matrix: shard: [1, 2, 3, 4] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 20 cache: npm diff --git a/.github/workflows/backup.yml b/.github/workflows/backup.yml index acdf4153..d0fb0722 100644 --- a/.github/workflows/backup.yml +++ b/.github/workflows/backup.yml @@ -44,10 +44,10 @@ jobs: - 5432:5432 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@v4 + uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 with: aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }} aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }} @@ -96,7 +96,7 @@ jobs: PGPASSWORD: postgres - name: Upload backup artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: database-backup-${{ github.run_id }} path: ${{ env.BACKUP_DIR }} @@ -104,7 +104,7 @@ jobs: - name: Notify on failure if: failure() - uses: slackapi/slack-github-action@v2.1.0 + uses: slackapi/slack-github-action@b0fa283ad8fea605de13dc3f449259339835fc52 # v2.1.0 with: webhook: ${{ secrets.SLACK_WEBHOOK_URL }} webhook-type: incoming-webhook diff --git a/.github/workflows/benchmarks.yml b/.github/workflows/benchmarks.yml index d9faaeda..8be09124 100644 --- a/.github/workflows/benchmarks.yml +++ b/.github/workflows/benchmarks.yml @@ -26,10 +26,10 @@ jobs: run: working-directory: backend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '22' cache: npm @@ -51,7 +51,7 @@ jobs: - name: Upload benchmark artifacts if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: api-benchmarks path: | @@ -83,10 +83,10 @@ jobs: run: working-directory: backend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '22' cache: npm diff --git a/.github/workflows/blue-green-deploy.yml b/.github/workflows/blue-green-deploy.yml index d9b0e19b..e1681148 100644 --- a/.github/workflows/blue-green-deploy.yml +++ b/.github/workflows/blue-green-deploy.yml @@ -24,7 +24,7 @@ jobs: validate: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Validate deployment script run: | bash -n scripts/blue-green-deploy.sh @@ -35,7 +35,7 @@ jobs: runs-on: ubuntu-latest environment: production steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Configure Kubernetes credentials env: KUBE_CONFIG_B64: ${{ secrets.KUBE_CONFIG_B64 }} diff --git a/.github/workflows/canary-deployment.yml b/.github/workflows/canary-deployment.yml index 6d3e4585..88032feb 100644 --- a/.github/workflows/canary-deployment.yml +++ b/.github/workflows/canary-deployment.yml @@ -47,10 +47,10 @@ jobs: steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Configure AWS credentials - uses: aws-actions/configure-aws-credentials@v4 + uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4.3.1 with: role-to-assume: ${{ secrets.AWS_ROLE_ARN }} aws-region: ${{ secrets.AWS_REGION }} diff --git a/.github/workflows/canary.yml b/.github/workflows/canary.yml index c6767696..f1e9e03d 100644 --- a/.github/workflows/canary.yml +++ b/.github/workflows/canary.yml @@ -11,7 +11,7 @@ jobs: runs-on: ubuntu-latest environment: canary-10 # Links to the environment steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Deploy 10% run: bash scripts/deploy_canary.sh ${{ github.sha }} 10 - name: Automated Health Check @@ -23,7 +23,7 @@ jobs: runs-on: ubuntu-latest environment: canary-50 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Deploy 50% run: bash scripts/deploy_canary.sh ${{ github.sha }} 50 - name: Automated Health Check @@ -36,7 +36,7 @@ jobs: # This environment has "Required Reviewers" set in GitHub UI environment: production steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Deploy 100% run: bash scripts/deploy_canary.sh ${{ github.sha }} 100 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 047a00f9..8dc10506 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,8 +44,8 @@ jobs: contracts: ${{ steps.filter.outputs.contracts }} tooling: ${{ steps.filter.outputs.tooling }} steps: - - uses: actions/checkout@v4 - - uses: dorny/paths-filter@v3 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: dorny/paths-filter@0e4a8c6effa4802afeda77dc8d303f8176d7dfad # v3.0.4 id: filter with: filters: | @@ -66,9 +66,11 @@ jobs: - '.husky/**' - '.releaserc.json' - '.github/CODEOWNERS' - - '.github/workflows/release.yml' + # Any workflow or Dependabot change re-runs the action-pin + # policy in scripts/workflow-pins.test.mjs (#1468). + - '.github/workflows/**' + - '.github/dependabot.yml' - 'infra/sentry/**' - - '.github/workflows/ci.yml' # ── Backend ─────────────────────────────────────────────────────────────── backend: @@ -94,10 +96,10 @@ jobs: run: working-directory: backend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ matrix.node-version }} cache: npm @@ -106,7 +108,7 @@ jobs: # Cache the installed node_modules between runs with the same lock file. # This shaves ~30s off each run after the first on a given branch. - name: Cache node_modules - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: backend/node_modules key: ${{ runner.os }}-backend-modules-node${{ matrix.node-version }}-${{ hashFiles('backend/package-lock.json') }} @@ -146,7 +148,7 @@ jobs: # Local fallback for turbo's cache when the remote cache is not configured. - name: Cache turbo artifacts - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: node_modules/.cache/turbo key: ${{ runner.os }}-turbo-backend-node${{ matrix.node-version }}-${{ github.sha }} @@ -206,17 +208,17 @@ jobs: run: working-directory: frontend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js ${{ matrix.node-version }} - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ matrix.node-version }} cache: npm cache-dependency-path: frontend/package-lock.json - name: Cache node_modules - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: frontend/node_modules key: ${{ runner.os }}-frontend-modules-node${{ matrix.node-version }}-${{ hashFiles('frontend/package-lock.json') }} @@ -225,7 +227,7 @@ jobs: # Next.js build cache (incremental compilation) - name: Cache Next.js build - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: ${{ github.workspace }}/frontend/.next/cache key: ${{ runner.os }}-nextjs-node${{ matrix.node-version }}-${{ hashFiles('frontend/package-lock.json') }}-${{ hashFiles('frontend/src/**') }} @@ -265,7 +267,7 @@ jobs: fi - name: Cache turbo artifacts - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: node_modules/.cache/turbo key: ${{ runner.os }}-turbo-frontend-node${{ matrix.node-version }}-${{ github.sha }} @@ -294,15 +296,16 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: + toolchain: stable targets: wasm32-unknown-unknown - name: Rust Cache - uses: Swatinem/rust-cache@v2 + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: "contracts -> target" @@ -321,10 +324,10 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm diff --git a/.github/workflows/commitlint.yml b/.github/workflows/commitlint.yml index 8979eb75..f3946ee3 100644 --- a/.github/workflows/commitlint.yml +++ b/.github/workflows/commitlint.yml @@ -22,9 +22,9 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm diff --git a/.github/workflows/config-validation.yml b/.github/workflows/config-validation.yml index 3c210ae0..ab765f21 100644 --- a/.github/workflows/config-validation.yml +++ b/.github/workflows/config-validation.yml @@ -24,9 +24,9 @@ jobs: run: working-directory: backend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '20' cache: 'npm' diff --git a/.github/workflows/contracts-evm.yml b/.github/workflows/contracts-evm.yml index 343a3c25..709f0c0f 100644 --- a/.github/workflows/contracts-evm.yml +++ b/.github/workflows/contracts-evm.yml @@ -18,8 +18,8 @@ jobs: outputs: evm: ${{ steps.filter.outputs.evm }} steps: - - uses: actions/checkout@v4 - - uses: dorny/paths-filter@v3 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: dorny/paths-filter@0e4a8c6effa4802afeda77dc8d303f8176d7dfad # v3.0.4 id: filter with: filters: | @@ -37,17 +37,17 @@ jobs: run: working-directory: contracts/evm steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm cache-dependency-path: contracts/evm/package-lock.json - name: Cache node_modules - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: contracts/evm/node_modules key: ${{ runner.os }}-evm-modules-${{ hashFiles('contracts/evm/package-lock.json') }} @@ -76,7 +76,7 @@ jobs: - name: Upload coverage artifact if: ${{ !cancelled() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: evm-coverage path: contracts/evm/coverage diff --git a/.github/workflows/cost-monitor.yml b/.github/workflows/cost-monitor.yml index 46bd8a2f..acead9ee 100644 --- a/.github/workflows/cost-monitor.yml +++ b/.github/workflows/cost-monitor.yml @@ -54,7 +54,7 @@ jobs: build_date: ${{ steps.tag.outputs.build_date }} commit_short: ${{ steps.tag.outputs.commit_short }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Generate resource tags id: tag @@ -88,7 +88,7 @@ jobs: cat resource-tags.json - name: Upload resource tag manifest - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: resource-tags-${{ github.run_number }} path: resource-tags.json @@ -179,10 +179,10 @@ jobs: frontend_size_kb: ${{ steps.sizes.outputs.frontend_size_kb }} size_alert: ${{ steps.sizes.outputs.size_alert }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 20 cache: npm @@ -265,7 +265,7 @@ jobs: EOF - name: Upload bundle size baseline - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: bundle-sizes-${{ github.run_number }} path: bundle-sizes.json diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index a9235d03..75f548c9 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -17,9 +17,9 @@ jobs: run: working-directory: frontend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '20' cache: 'npm' @@ -34,7 +34,7 @@ jobs: NEXT_TELEMETRY_DISABLED: '1' - name: Upload coverage to Codecov - uses: codecov/codecov-action@v4 + uses: codecov/codecov-action@b9fd7d16f6d7d1b5d2bec1a2887e65ceed900238 # v4.6.0 with: token: ${{ secrets.CODECOV_TOKEN }} directory: coverage diff --git a/.github/workflows/devcontainer.yml b/.github/workflows/devcontainer.yml index 2c77d083..ee8344be 100644 --- a/.github/workflows/devcontainer.yml +++ b/.github/workflows/devcontainer.yml @@ -25,10 +25,10 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Build devcontainer image - uses: devcontainers/ci@v0.3 + uses: devcontainers/ci@513af61f4de4f75d37e4438f184ba4358f0fc1ca # v0.3.1900000450 with: runCmd: echo "Devcontainer image built successfully" configFile: .devcontainer/devcontainer.json @@ -40,7 +40,7 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Validate root compose file run: docker compose -f docker-compose.yml config diff --git a/.github/workflows/docker-build.yml b/.github/workflows/docker-build.yml index df4ad7e6..fdd0a233 100644 --- a/.github/workflows/docker-build.yml +++ b/.github/workflows/docker-build.yml @@ -12,14 +12,14 @@ jobs: build: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Set up QEMU - uses: docker/setup-qemu-action@v2 + uses: docker/setup-qemu-action@2b82ce82d56a2a04d2637cd93a637ae1b359c0a7 # v2.2.0 - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v2 + uses: docker/setup-buildx-action@885d1462b80bc1c1c7f0b00334ad271f09369c55 # v2.10.0 - name: Login to Docker Hub if: false - uses: docker/login-action@v2 + uses: docker/login-action@465a07811f14bebb1938fbed4728c6a1ff8901fc # v2.2.0 with: username: ${{ secrets.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index a162fcbe..c867f631 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -29,8 +29,8 @@ jobs: outputs: frontend: ${{ steps.filter.outputs.frontend }} steps: - - uses: actions/checkout@v4 - - uses: dorny/paths-filter@v3 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: dorny/paths-filter@0e4a8c6effa4802afeda77dc8d303f8176d7dfad # v3.0.4 id: filter with: filters: | @@ -52,10 +52,10 @@ jobs: run: working-directory: frontend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm @@ -81,7 +81,7 @@ jobs: - name: Cache Playwright browsers id: pw-cache - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: ~/.cache/ms-playwright key: ${{ runner.os }}-playwright-${{ steps.pw-version.outputs.version }} @@ -96,7 +96,7 @@ jobs: - name: Upload HTML report if: ${{ !cancelled() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: playwright-report-${{ matrix.project }} path: frontend/playwright-report @@ -104,7 +104,7 @@ jobs: - name: Upload traces & videos if: failure() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: playwright-trace-${{ matrix.project }} path: frontend/test-results @@ -125,10 +125,10 @@ jobs: image: mcr.microsoft.com/playwright:v1.59.1-noble options: --ipc=host steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Cache npm - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: ~/.npm key: ${{ runner.os }}-visual-npm-${{ hashFiles('frontend/package-lock.json', 'package-lock.json') }} @@ -162,7 +162,7 @@ jobs: - name: Upload report if: ${{ !cancelled() }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: visual-report path: frontend/playwright-report/visual @@ -170,7 +170,7 @@ jobs: - name: Upload re-recorded baselines if: ${{ inputs.update_visual_snapshots }} - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: visual-baselines path: frontend/tests/e2e/visual/__screenshots__ diff --git a/.github/workflows/formal-verification.yml b/.github/workflows/formal-verification.yml index 224b357f..ff8b0be3 100644 --- a/.github/workflows/formal-verification.yml +++ b/.github/workflows/formal-verification.yml @@ -25,10 +25,10 @@ jobs: env: CERTORAKEY: ${{ secrets.CERTORAKEY }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Python - uses: actions/setup-python@v5 + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: '3.11' @@ -54,13 +54,15 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable + with: + toolchain: stable - name: Cache cargo - uses: Swatinem/rust-cache@v2 + uses: Swatinem/rust-cache@d1527c8f67ef9af357290475d4af4b0fab8f12e0 # v2.9.3 with: workspaces: contracts diff --git a/.github/workflows/fuzz-testing.yml b/.github/workflows/fuzz-testing.yml index a9d3f22a..9de7246c 100644 --- a/.github/workflows/fuzz-testing.yml +++ b/.github/workflows/fuzz-testing.yml @@ -14,11 +14,12 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: + toolchain: stable targets: wasm32-unknown-unknown components: rustfmt, clippy @@ -66,7 +67,7 @@ jobs: --shrinkLimit 1000 - name: Upload Echidna Results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 if: always() with: name: echidna-results @@ -89,11 +90,12 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Install Rust - uses: dtolnay/rust-toolchain@nightly + uses: dtolnay/rust-toolchain@6a52aad76a94a5fbc50d567bb5be24419801c1fb # nightly with: + toolchain: nightly targets: wasm32-unknown-unknown components: rustfmt, clippy @@ -118,7 +120,7 @@ jobs: timeout 300 cargo +nightly fuzz run authorization_consistency || true - name: Upload Fuzz Artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 if: always() with: name: haloria-fuzz-artifacts @@ -128,11 +130,12 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Install Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: + toolchain: stable components: rustfmt, clippy, llvm-tools - name: Install grcov @@ -156,7 +159,7 @@ jobs: --output-path coverage.lcov - name: Upload Coverage to Codecov - uses: codecov/codecov-action@v4 + uses: codecov/codecov-action@b9fd7d16f6d7d1b5d2bec1a2887e65ceed900238 # v4.6.0 with: file: contracts/coverage.lcov flags: fuzz-testing @@ -176,7 +179,7 @@ jobs: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Install Slither run: | @@ -190,7 +193,7 @@ jobs: slither . --json slither-results.json --filter medium,high || true - name: Upload Slither Results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 if: always() with: name: slither-results @@ -216,10 +219,10 @@ jobs: if: always() steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Download Artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: path: artifacts/ @@ -270,14 +273,14 @@ jobs: echo "- Security scan: Available in artifacts/slither-results/" >> fuzz-test-report.md - name: Upload Report - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: fuzz-test-report path: fuzz-test-report.md - name: Comment PR if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 with: script: | const fs = require('fs'); diff --git a/.github/workflows/gas-checks.yml b/.github/workflows/gas-checks.yml index dbc73acc..eda0030f 100644 --- a/.github/workflows/gas-checks.yml +++ b/.github/workflows/gas-checks.yml @@ -20,16 +20,16 @@ jobs: name: Gas Regression Check runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Install Rust toolchain - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: toolchain: ${{ env.RUST_TOOLCHAIN }} targets: wasm32-unknown-unknown - name: Cache Cargo dependencies - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: | ~/.cargo/registry @@ -97,14 +97,14 @@ jobs: shell: bash - name: Upload gas results - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: gas-benchmark-results path: /tmp/gas-results.txt retention-days: 30 - name: Upload gas baseline - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: gas-baseline path: contracts/gas-baseline.json diff --git a/.github/workflows/generate-docs.yml b/.github/workflows/generate-docs.yml index 1db0197b..00cb91e2 100644 --- a/.github/workflows/generate-docs.yml +++ b/.github/workflows/generate-docs.yml @@ -23,10 +23,10 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '20' cache: npm @@ -47,7 +47,7 @@ jobs: node -e "const s=require('./docs/api/openapi/openapi.json'); if(!s.paths||!s.components) process.exit(1)" - name: Install Python for documentation - uses: actions/setup-python@v5 + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: '3.11' @@ -286,7 +286,7 @@ jobs: find ${{ env.API_DOCS_DIR }} -type f -name "*.json" -o -name "*.yaml" -o -name "*.md" | head -20 - name: Upload artifacts - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: api-documentation path: ${{ env.API_DOCS_DIR }}/ diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml index 18e551c0..3a52bb94 100644 --- a/.github/workflows/integration.yml +++ b/.github/workflows/integration.yml @@ -16,8 +16,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ env.NODE_VERSION }} cache: npm @@ -31,8 +31,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 20 steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ env.NODE_VERSION }} cache: npm @@ -44,8 +44,8 @@ jobs: if: ${{ vars.PRODUCTION_SMOKE_URL != '' }} runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ env.NODE_VERSION }} - run: npm run test:smoke diff --git a/.github/workflows/k6-load-test.yml b/.github/workflows/k6-load-test.yml index dd995df1..09b36d4c 100644 --- a/.github/workflows/k6-load-test.yml +++ b/.github/workflows/k6-load-test.yml @@ -21,8 +21,8 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 15 steps: - - uses: actions/checkout@v4 - - uses: grafana/setup-k6-action@v1 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: grafana/setup-k6-action@c47136d33d365efbeb9ae7266908b5dcf98cdece # v1.3.0 - name: Run health smoke test env: BASE_URL: ${{ inputs.base_url }} @@ -34,7 +34,7 @@ jobs: run: k6 run --summary-export=k6-summary.json tests/load/k6/payment-flow.js - name: Upload load-test summary if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: k6-summary path: k6-summary.json diff --git a/.github/workflows/migrations.yml b/.github/workflows/migrations.yml index 198703f8..1ee59849 100644 --- a/.github/workflows/migrations.yml +++ b/.github/workflows/migrations.yml @@ -43,9 +43,9 @@ jobs: DATABASE_URL: postgresql://postgres:postgres@localhost:5432/agenticpay steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm diff --git a/.github/workflows/performance-monitoring.yml b/.github/workflows/performance-monitoring.yml index 6b2d74fa..9359f9d2 100644 --- a/.github/workflows/performance-monitoring.yml +++ b/.github/workflows/performance-monitoring.yml @@ -14,11 +14,11 @@ jobs: timeout-minutes: 30 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '20' cache: 'npm' @@ -170,7 +170,7 @@ jobs: - name: Upload performance artifacts if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: performance-reports path: reports/ @@ -178,7 +178,7 @@ jobs: - name: Comment PR with performance summary if: github.event_name == 'pull_request' - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 with: script: | const fs = require('fs'); @@ -197,10 +197,10 @@ jobs: timeout-minutes: 15 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Run Lighthouse CI - uses: treosh/lighthouse-ci-action@v10 + uses: treosh/lighthouse-ci-action@03becbfc543944dd6e7534f7ff768abb8a296826 # v10 with: configPath: './lighthouse/lighthouse.config.json' uploadArtifacts: true @@ -212,9 +212,9 @@ jobs: timeout-minutes: 10 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '20' cache: 'npm' diff --git a/.github/workflows/platform-services.yml b/.github/workflows/platform-services.yml index 6f70202d..54bb1c5b 100644 --- a/.github/workflows/platform-services.yml +++ b/.github/workflows/platform-services.yml @@ -15,9 +15,9 @@ jobs: run: working-directory: backend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm @@ -49,9 +49,9 @@ jobs: run: working-directory: frontend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm @@ -74,9 +74,9 @@ jobs: run: working-directory: frontend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 @@ -102,9 +102,9 @@ jobs: run: working-directory: contracts/evm steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b2d314b0..343efb4c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -27,12 +27,12 @@ jobs: published: ${{ steps.version.outputs.published }} version: ${{ steps.version.outputs.version }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 0 persist-credentials: false - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ env.NODE_VERSION }} cache: 'npm' @@ -85,7 +85,7 @@ jobs: echo "configured=true" >> "$GITHUB_OUTPUT" fi - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 if: steps.sentry.outputs.configured == 'true' with: ref: v${{ needs.release.outputs.version }} @@ -93,7 +93,7 @@ jobs: fetch-depth: 0 persist-credentials: false - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 if: steps.sentry.outputs.configured == 'true' with: node-version: ${{ env.NODE_VERSION }} diff --git a/.github/workflows/sdk-docs.yml b/.github/workflows/sdk-docs.yml index 78965d23..4323f17a 100644 --- a/.github/workflows/sdk-docs.yml +++ b/.github/workflows/sdk-docs.yml @@ -19,8 +19,8 @@ jobs: matrix: package: [sdk, types] steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm @@ -39,7 +39,7 @@ jobs: run: npm run docs - name: Upload docs artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: typedoc-${{ matrix.package }} path: packages/${{ matrix.package }}/docs/api @@ -50,8 +50,8 @@ jobs: run: working-directory: packages/sdk steps: - - uses: actions/checkout@v4 - - uses: actions/setup-node@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 - run: npm install diff --git a/.github/workflows/sdk-generation.yml b/.github/workflows/sdk-generation.yml index 53b0896a..96e11246 100644 --- a/.github/workflows/sdk-generation.yml +++ b/.github/workflows/sdk-generation.yml @@ -33,10 +33,10 @@ jobs: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '22' cache: 'npm' @@ -58,7 +58,7 @@ jobs: run: npm run openapi:validate - name: Upload OpenAPI spec - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: openapi-spec path: backend/docs/api/openapi/openapi.json @@ -70,10 +70,10 @@ jobs: needs: generate-openapi steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Download OpenAPI spec - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: openapi-spec path: backend/docs/api/openapi/ @@ -115,7 +115,7 @@ jobs: - name: Comment breaking changes on PR if: github.event_name == 'pull_request' && steps.diff.outputs.BREAKING_CHANGES == 'true' - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 with: script: | const fs = require('fs'); @@ -136,10 +136,10 @@ jobs: language: [typescript, python, go] steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '22' cache: 'npm' @@ -150,7 +150,7 @@ jobs: run: npm ci - name: Download OpenAPI spec - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: openapi-spec path: backend/docs/api/openapi/ @@ -160,7 +160,7 @@ jobs: run: npm run sdk:generate:${{ matrix.language }} - name: Upload ${{ matrix.language }} SDK - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: sdk-${{ matrix.language }} path: packages/sdk/generated/${{ matrix.language }} @@ -173,16 +173,16 @@ jobs: if: github.event_name == 'push' && github.ref == 'refs/heads/main' steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '22' registry-url: 'https://registry.npmjs.org' - name: Download TypeScript SDK - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: name: sdk-typescript path: packages/sdk/generated/typescript @@ -212,10 +212,10 @@ jobs: needs: [generate-openapi, breaking-change-detection] steps: - name: Checkout code - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '22' @@ -228,7 +228,7 @@ jobs: echo "API Changelog generated" - name: Upload changelog - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: changelog path: CHANGELOG.md diff --git a/.github/workflows/security-audit-pipeline.yml b/.github/workflows/security-audit-pipeline.yml index e5a6e949..74f353ff 100644 --- a/.github/workflows/security-audit-pipeline.yml +++ b/.github/workflows/security-audit-pipeline.yml @@ -48,12 +48,12 @@ jobs: if: ${{ github.event.inputs.scan_type == 'all' || github.event.inputs.scan_type == 'sast' || github.event_name != 'workflow_dispatch' }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ env.NODE_VERSION }} cache: npm @@ -85,7 +85,7 @@ jobs: || true - name: Run Semgrep SAST - uses: semgrep/semgrep-action@v1 + uses: semgrep/semgrep-action@713efdd345f3035192eaa63f56867b88e63e4e5d # v1 continue-on-error: true with: config: >- @@ -99,7 +99,7 @@ jobs: - name: Upload Semgrep SARIF if: ${{ always() && hashFiles('security-reports/semgrep.sarif') != '' }} - uses: github/codeql-action/upload-sarif@v3 + uses: github/codeql-action/upload-sarif@d2aacf54c2fbc910db8d7ec338fdb54ea48c692d # v3.39.4 with: sarif_file: ${{ env.SECURITY_REPORT_DIR }}/semgrep.sarif category: semgrep-sast @@ -119,7 +119,7 @@ jobs: - name: Upload SAST artifacts if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: sast-reports path: ${{ env.SECURITY_REPORT_DIR }}/ @@ -136,10 +136,10 @@ jobs: if: ${{ github.event.inputs.scan_type == 'all' || github.event.inputs.scan_type == 'dependencies' || github.event_name != 'workflow_dispatch' }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ env.NODE_VERSION }} @@ -161,7 +161,7 @@ jobs: npm audit --audit-level=high 2>&1 | tee ../${{ env.SECURITY_REPORT_DIR }}/npm-audit-frontend.txt || true - name: Snyk dependency scan - uses: snyk/actions/node@master + uses: snyk/actions/node@11b673cfb4b0dc0d860a1323caa199d54950dcce # master continue-on-error: true env: SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} @@ -173,7 +173,7 @@ jobs: - name: Upload Snyk SARIF if: ${{ always() && hashFiles('security-reports/snyk.sarif') != '' }} - uses: github/codeql-action/upload-sarif@v3 + uses: github/codeql-action/upload-sarif@d2aacf54c2fbc910db8d7ec338fdb54ea48c692d # v3.39.4 with: sarif_file: ${{ env.SECURITY_REPORT_DIR }}/snyk.sarif category: snyk-dependencies @@ -208,7 +208,7 @@ jobs: - name: Upload dependency scan artifacts if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: dependency-scan-reports path: ${{ env.SECURITY_REPORT_DIR }}/ @@ -236,10 +236,10 @@ jobs: && (github.event.inputs.scan_type == 'all' || github.event.inputs.scan_type == 'dast' || github.event_name != 'workflow_dispatch') }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Setup Node.js - uses: actions/setup-node@v4 + uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ env.NODE_VERSION }} @@ -255,7 +255,7 @@ jobs: OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY || 'sk-test-placeholder' }} - name: OWASP ZAP Baseline Scan - uses: zaproxy/action-baseline@v0.10.0 + uses: zaproxy/action-baseline@1e1871e84428617b969d4a1f981a8255630d54b0 # v0.10.0 continue-on-error: true with: target: "http://localhost:3001" @@ -265,7 +265,7 @@ jobs: - name: Upload DAST artifacts if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: dast-reports path: | @@ -287,11 +287,11 @@ jobs: ${{ github.event.inputs.scan_type == 'all' || github.event_name != 'workflow_dispatch' }} steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Detect contract changes id: changes - uses: dorny/paths-filter@v3 + uses: dorny/paths-filter@0e4a8c6effa4802afeda77dc8d303f8176d7dfad # v3.0.4 with: filters: | solidity: @@ -302,7 +302,7 @@ jobs: - name: Setup Python for Slither if: steps.changes.outputs.solidity == 'true' - uses: actions/setup-python@v5 + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.11" @@ -332,7 +332,7 @@ jobs: - name: Upload contract scan artifacts if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: smart-contract-reports path: ${{ env.SECURITY_REPORT_DIR }}/ @@ -359,10 +359,10 @@ jobs: timeout-minutes: 10 steps: - name: Checkout - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Download all artifacts - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: path: all-reports continue-on-error: true @@ -382,7 +382,7 @@ jobs: - name: Comment on PR if: github.event_name == 'pull_request' - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 with: script: | github.rest.issues.createComment({ diff --git a/.github/workflows/security-audit.yml b/.github/workflows/security-audit.yml index 55fa3300..9fa1d76b 100644 --- a/.github/workflows/security-audit.yml +++ b/.github/workflows/security-audit.yml @@ -27,8 +27,8 @@ jobs: outputs: contracts: ${{ steps.filter.outputs.contracts }} steps: - - uses: actions/checkout@v4 - - uses: dorny/paths-filter@v3 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - uses: dorny/paths-filter@0e4a8c6effa4802afeda77dc8d303f8176d7dfad # v3.0.4 id: filter with: filters: | @@ -46,10 +46,10 @@ jobs: contents: read security-events: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: '3.11' @@ -106,7 +106,7 @@ jobs: - name: Upload Slither Artifacts if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: slither-reports path: ${{ env.SECURITY_REPORT_DIR }}/ @@ -129,10 +129,10 @@ jobs: contents: read security-events: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Set up Python - uses: actions/setup-python@v5 + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: '3.11' @@ -187,7 +187,7 @@ jobs: - name: Upload Mythril Artifacts if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: mythril-reports path: ${{ env.SECURITY_REPORT_DIR }}/ @@ -201,18 +201,19 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Set up Rust - uses: dtolnay/rust-toolchain@stable + uses: dtolnay/rust-toolchain@39008827e6b4319a349e9a42dfc90579dd25f1ca # stable with: + toolchain: stable components: rustfmt, clippy - name: Install Soroban system dependencies run: sudo apt-get update && sudo apt-get install -y pkg-config libdbus-1-dev libudev-dev - name: Cache cargo registry - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: ~/.cargo/registry key: ${{ runner.os }}-cargo-registry-${{ hashFiles('contracts/Cargo.lock') }} @@ -220,7 +221,7 @@ jobs: ${{ runner.os }}-cargo-registry- - name: Cache cargo index - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: ~/.cargo/git key: ${{ runner.os }}-cargo-git-${{ hashFiles('contracts/Cargo.lock') }} @@ -228,7 +229,7 @@ jobs: ${{ runner.os }}-cargo-git- - name: Cache cargo build - uses: actions/cache@v4 + uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: contracts/target key: ${{ runner.os }}-cargo-build-target-${{ hashFiles('contracts/Cargo.lock') }} @@ -265,7 +266,7 @@ jobs: - name: Upload Property Test Artifacts if: always() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: property-test-reports path: ${{ env.SECURITY_REPORT_DIR }}/ @@ -281,10 +282,10 @@ jobs: contents: read security-events: write steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - name: Download all reports - uses: actions/download-artifact@v4 + uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0 with: path: all-reports @@ -335,7 +336,7 @@ jobs: cat ${{ env.SECURITY_REPORT_DIR }}/SECURITY_SUMMARY.md >> $GITHUB_STEP_SUMMARY - name: Upload Security Report - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: name: security-audit-report path: ${{ env.SECURITY_REPORT_DIR }}/ @@ -350,7 +351,7 @@ jobs: steps: - name: Create GitHub Issue for Security Findings if: github.event_name == 'push' && github.ref == 'refs/heads/main' - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 with: script: | github.rest.issues.create({ diff --git a/.github/workflows/size-limit.yml b/.github/workflows/size-limit.yml index cd5e280f..7a01eaf4 100644 --- a/.github/workflows/size-limit.yml +++ b/.github/workflows/size-limit.yml @@ -26,9 +26,9 @@ jobs: run: working-directory: frontend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '20' cache: 'npm' @@ -47,7 +47,7 @@ jobs: - name: Report size regressions on pull requests if: github.event_name == 'pull_request' - uses: andresz1/size-limit-action@v1 + uses: andresz1/size-limit-action@e7493a72a44b113341c0cf6186ab49c17c4b65c1 # v1.6.1 with: github_token: ${{ secrets.GITHUB_TOKEN }} directory: frontend diff --git a/.github/workflows/tenant-isolation.yml b/.github/workflows/tenant-isolation.yml index 364f0091..c9d6ccc3 100644 --- a/.github/workflows/tenant-isolation.yml +++ b/.github/workflows/tenant-isolation.yml @@ -15,9 +15,9 @@ jobs: run: working-directory: backend steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: '20' cache: 'npm' diff --git a/.github/workflows/types-contract.yml b/.github/workflows/types-contract.yml index 7089c874..899648dc 100644 --- a/.github/workflows/types-contract.yml +++ b/.github/workflows/types-contract.yml @@ -6,10 +6,10 @@ jobs: shared-types: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: fetch-depth: 0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: 22 cache: npm diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index ab34a883..4fb3c070 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -125,6 +125,25 @@ Preview what the next release would contain with - screenshots or recordings for UI changes, if applicable 6. Respond to review feedback with follow-up commits unless a maintainer asks for a squash or rebase. +### GitHub Actions workflows + +Every third-party action is pinned to a full 40-character commit SHA, with the +release it corresponds to as a trailing comment. A tag or branch can be moved +to different code after review; a commit SHA cannot. + +```yaml +- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 +``` + +To add or change an action, look up the commit for the release +(`gh api repos/OWNER/REPO/commits/vX.Y.Z --jq .sha`) and pin that, reusing the +SHA already used elsewhere for the same release. `dtolnay/rust-toolchain` +selects the toolchain by its ref, so once pinned it needs +`with: toolchain: stable` (or `nightly`). Dependabot's `github-actions` entry +in `.github/dependabot.yml` bumps the SHA and the comment together each week. +`scripts/workflow-pins.test.mjs` (run by `make test-tooling` in CI) fails on any +unpinned reference. + ## Testing Requirements Every contribution should be verified before review. diff --git a/scripts/workflow-pins.test.mjs b/scripts/workflow-pins.test.mjs new file mode 100644 index 00000000..772486e4 --- /dev/null +++ b/scripts/workflow-pins.test.mjs @@ -0,0 +1,152 @@ +// Pins the GitHub Actions supply-chain policy (#1468): +// +// - every `uses:` in .github/workflows references an action by a full +// 40-character commit SHA, never a movable tag or branch, and carries the +// release it corresponds to as a trailing `# ` comment so humans +// and Dependabot can read and bump it; +// - dtolnay/rust-toolchain, whose ref *is* the toolchain name, passes the +// toolchain explicitly once its ref is a SHA; +// - .github/dependabot.yml keeps those pins current and stays a valid v2 +// config (unknown top-level keys make GitHub reject the whole file). +// +// Run by `make test-tooling` in the CI "Repo tooling" job. +import assert from 'node:assert/strict'; +import { readFileSync, readdirSync } from 'node:fs'; +import { dirname, join, resolve } from 'node:path'; +import test, { describe } from 'node:test'; +import { fileURLToPath } from 'node:url'; + +const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..'); +const workflowsDir = join(repositoryRoot, '.github', 'workflows'); + +const USES = /^\s*(?:-\s+)?uses:\s*['"]?([^'"\s#]+)['"]?\s*(#.*)?$/; +const PINNED = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_./-]+)?@[0-9a-f]{40}$/; +const DOCKER_DIGEST = /^docker:\/\/[^@\s]+@sha256:[0-9a-f]{64}$/; + +/** Every `uses:` line of every workflow, with its file and line number. */ +export function collectUses(dir = workflowsDir) { + const found = []; + for (const name of readdirSync(dir).filter((f) => /\.ya?ml$/.test(f)).sort()) { + const lines = readFileSync(join(dir, name), 'utf8').split('\n'); + lines.forEach((line, index) => { + const match = USES.exec(line); + if (match) { + found.push({ file: name, line: index + 1, ref: match[1], comment: match[2] ?? '', lines, index }); + } + }); + } + return found; +} + +/** Why `ref`/`comment` violates the pinning policy, or null when it complies. */ +export function pinViolation(ref, comment) { + if (ref.startsWith('./')) return null; // local action: versioned with this repo + if (ref.startsWith('docker://')) { + return DOCKER_DIGEST.test(ref) ? null : 'docker image must be pinned by @sha256 digest'; + } + if (!ref.includes('@')) return 'missing @'; + if (!PINNED.test(ref)) { + return `pinned to "${ref.split('@')[1]}"; use the full 40-character commit SHA`; + } + if (!/^#\s*\S+/.test(comment)) return 'missing trailing "# " comment for the pinned SHA'; + return null; +} + +const uses = collectUses(); +const remote = uses.filter(({ ref }) => !ref.startsWith('./')); + +describe('pinViolation', () => { + const sha = 'a'.repeat(40); + + test('accepts a SHA pin with a version comment, local actions and digest-pinned images', () => { + assert.equal(pinViolation(`actions/checkout@${sha}`, '# v4.4.0'), null); + assert.equal(pinViolation(`github/codeql-action/upload-sarif@${sha}`, '# v3.39.4'), null); + assert.equal(pinViolation('./.github/actions/setup', ''), null); + assert.equal(pinViolation(`docker://alpine@sha256:${'b'.repeat(64)}`, ''), null); + }); + + test('rejects tags, branches, short SHAs and missing refs', () => { + assert.match(pinViolation('actions/checkout@v4', '# v4'), /full 40-character commit SHA/); + assert.match(pinViolation('snyk/actions/node@master', ''), /full 40-character commit SHA/); + assert.match(pinViolation('actions/checkout@11d5960', '# v4'), /full 40-character commit SHA/); + assert.match(pinViolation(`actions/checkout@${'A'.repeat(40)}`, '# v4'), /full 40-character commit SHA/); + assert.match(pinViolation('actions/checkout', ''), /missing @/); + assert.match(pinViolation('docker://alpine:3.20', ''), /sha256 digest/); + }); + + test('rejects a SHA pin without a version comment', () => { + assert.match(pinViolation(`actions/checkout@${sha}`, ''), /version/); + assert.match(pinViolation(`actions/checkout@${sha}`, '#'), /version/); + }); +}); + +describe('workflow action references', () => { + test('the workflows directory has action references to check', () => { + assert.ok(remote.length > 0, 'expected at least one remote action reference'); + }); + + test('every action is pinned to a full commit SHA with a version comment', () => { + const violations = uses + .map((use) => ({ ...use, problem: pinViolation(use.ref, use.comment) })) + .filter(({ problem }) => problem) + .map(({ file, line, ref, problem }) => `.github/workflows/${file}:${line} ${ref}: ${problem}`); + assert.deepEqual(violations, [], `unpinned actions:\n${violations.join('\n')}`); + }); + + test('one action release resolves to one SHA across all workflows', () => { + // Keyed by action and version comment: rust-toolchain legitimately pins + // two refs (stable, nightly), but "actions/checkout # v4.4.0" must never + // point at two different commits. + const byAction = new Map(); + for (const { ref, comment, file, line } of remote) { + const [action, sha] = ref.split('@'); + const key = `${action} ${comment.trim()}`; + if (!byAction.has(key)) byAction.set(key, new Map()); + byAction.get(key).set(sha, `${file}:${line}`); + } + const drift = [...byAction] + .filter(([, shas]) => shas.size > 1) + .map(([action, shas]) => `${action}: ${[...shas].map(([s, where]) => `${s.slice(0, 7)} (${where})`).join(', ')}`); + assert.deepEqual(drift, [], `the same action is pinned to different SHAs:\n${drift.join('\n')}`); + }); + + test('dtolnay/rust-toolchain passes the toolchain explicitly once pinned', () => { + const missing = remote + .filter(({ ref }) => ref.startsWith('dtolnay/rust-toolchain@')) + .filter(({ lines, index }) => { + const indent = lines[index].search(/\S/) + (lines[index].trimStart().startsWith('- ') ? 2 : 0); + for (let i = index + 1; i < lines.length; i++) { + const text = lines[i]; + if (!text.trim()) continue; + const col = text.search(/\S/); + if (col < indent || (col === indent && !text.trim().startsWith('with:'))) break; + if (/^\s*toolchain:\s*\S/.test(text)) return false; + } + return true; + }) + .map(({ file, line }) => `.github/workflows/${file}:${line}`); + assert.deepEqual(missing, [], `rust-toolchain steps without a toolchain input:\n${missing.join('\n')}`); + }); +}); + +describe('.github/dependabot.yml', () => { + const config = readFileSync(join(repositoryRoot, '.github', 'dependabot.yml'), 'utf8'); + const topLevelKeys = config + .split('\n') + .filter((line) => /^[A-Za-z][\w-]*:/.test(line)) + .map((line) => line.split(':')[0]); + + test('only uses top-level keys Dependabot v2 accepts', () => { + const allowed = new Set(['version', 'updates', 'registries', 'enable-beta-ecosystems', 'multi-ecosystem-groups']); + assert.deepEqual(topLevelKeys.filter((key) => !allowed.has(key)), []); + assert.match(config, /^version:\s*2\s*$/m); + }); + + test('keeps GitHub Actions pins up to date from the repository root', () => { + const entries = config.split(/\n(?=\s*- package-ecosystem:)/); + const actions = entries.find((entry) => /package-ecosystem:\s*["']?github-actions["']?/.test(entry)); + assert.ok(actions, 'missing a github-actions update entry'); + assert.match(actions, /directory:\s*["']?\/["']?\s*$/m); + assert.match(actions, /interval:\s*["']?(daily|weekly|monthly)["']?/); + }); +}); From 91aab3565ade7b75548d7bfb857efe80d787054a Mon Sep 17 00:00:00 2001 From: JamesVictor-O Date: Fri, 20 Nov 2026 22:52:29 +0100 Subject: [PATCH 2/4] perf(webhooks): shard the delivery queue by destination domain The delivery worker sent every due webhook one at a time in a single global pass and skipped whole ticks while a pass was in flight, so one slow or hanging endpoint (up to the 8s attempt timeout) delayed every merchant's deliveries. Due deliveries are now grouped by destination host and each host drains on its own lane (services/webhooks/shard-dispatcher.ts): - one request at a time per host, oldest first; - up to WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS hosts in parallel (default 8), oldest-waiting hosts first when lanes are saturated; - a host still draining is skipped instead of started twice, which keeps the no-double-send guarantee the old global lock provided; - at most WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD deliveries per run (default 25) so one backlog cannot monopolise a lane. Invalid settings fail at worker start with the variable named. Observability: queue-wait (due to send) and lane-run percentiles, backlog, busy skips, saturation and deliver errors, served by GET /api/v1/webhooks/dispatch-stats, plus a once-a-minute saturation warning and per-shard error logs. Documented in docs/WEBHOOK_RETRY_STRATEGY.md and ENV_VARS.md. Closes #1462 --- ENV_VARS.md | 2 + backend/src/routes/webhooks.ts | 10 + backend/src/services/webhooks.test.ts | 125 +++++++ backend/src/services/webhooks.ts | 86 +++-- .../__tests__/shard-dispatcher.test.ts | 238 ++++++++++++++ .../src/services/webhooks/shard-dispatcher.ts | 307 ++++++++++++++++++ docs/WEBHOOK_RETRY_STRATEGY.md | 46 +++ 7 files changed, 794 insertions(+), 20 deletions(-) create mode 100644 backend/src/services/webhooks/__tests__/shard-dispatcher.test.ts create mode 100644 backend/src/services/webhooks/shard-dispatcher.ts diff --git a/ENV_VARS.md b/ENV_VARS.md index 57c3766b..f2acbc78 100644 --- a/ENV_VARS.md +++ b/ENV_VARS.md @@ -37,6 +37,8 @@ | WOOCOMMERCE_WEBHOOK_SECRET | Secret used to verify `X-WC-Webhook-Signature` | - | No | | WEBHOOK_EGRESS_ALLOWED_HOSTS | Hosts webhook deliveries may be sent to. Exact hostnames or `*.suffix` wildcards, comma-separated. Empty denies every delivery (fail closed). Private, loopback and link-local addresses are always denied. See [WEBHOOK_VERIFICATION.md](./WEBHOOK_VERIFICATION.md#outbound-egress-policy) | - | **Yes** for webhooks | | WEBHOOK_EGRESS_ALLOWED_PORTS | Ports webhook deliveries may use, comma-separated. Applies to HTTPS only | 443 | No | +| WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS | Destination hosts whose webhook deliveries may drain at the same time (1 to 256). Each host gets one request at a time. See [WEBHOOK_RETRY_STRATEGY.md](./docs/WEBHOOK_RETRY_STRATEGY.md#domain-sharded-dispatch) | 8 | No | +| WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD | Deliveries one host drains per run before yielding its lane (1 to 1000) | 25 | No | | SALESFORCE_INSTANCE_URL | Salesforce instance URL (e.g. `https://acme.my.salesforce.com`) | - | No | | SALESFORCE_ACCESS_TOKEN | Salesforce OAuth access token | - | No | | SALESFORCE_API_VERSION | Salesforce REST API version | 59.0 | No | diff --git a/backend/src/routes/webhooks.ts b/backend/src/routes/webhooks.ts index b4ab6a99..2e503b1b 100644 --- a/backend/src/routes/webhooks.ts +++ b/backend/src/routes/webhooks.ts @@ -19,6 +19,7 @@ import { getWebhookAuditLog } from '../services/webhooks/audit.js'; import { enqueueWebhookEvent, getWebhookDelivery, + getWebhookDispatchStats, listDeadLetterQueue, listWebhookConfigs, listWebhookDeliveries, @@ -230,4 +231,13 @@ webhooksRouter.get( asyncHandler(async (_req, res) => { res.json({ data: listDeadLetterQueue() }); }) +); + +// Domain-sharded dispatch health (#1462): active shards, backlog, skips, +// saturation and queue-wait percentiles. +webhooksRouter.get( + '/dispatch-stats', + asyncHandler(async (_req, res) => { + res.json(getWebhookDispatchStats()); + }) ); \ No newline at end of file diff --git a/backend/src/services/webhooks.test.ts b/backend/src/services/webhooks.test.ts index 3edc8c5b..f71e5d4a 100644 --- a/backend/src/services/webhooks.test.ts +++ b/backend/src/services/webhooks.test.ts @@ -5,6 +5,9 @@ import { startWebhookWorker, stopWebhookWorker, getWebhookDelivery, + drainWebhookDeliveries, + getActiveWebhookShards, + getWebhookDispatchStats, } from './webhooks.js'; describe('webhook worker', () => { @@ -56,3 +59,125 @@ describe('webhook worker', () => { expect(getWebhookDelivery(delivery!.id)?.status).toBe('delivered'); }); }); + +describe('domain-sharded webhook dispatch (#1462)', () => { + afterEach(() => { + stopWebhookWorker(); + vi.useRealTimers(); + vi.unstubAllGlobals(); + }); + + /** fetch stub: URLs containing `hang` stay pending until released; others answer 200. */ + function stubFetch() { + const calls: string[] = []; + const releases: Array<() => void> = []; + const fetchMock = vi.fn((url: string) => { + calls.push(url); + if (url.includes('hang')) { + return new Promise((resolve) => { + releases.push(() => resolve({ ok: true, status: 200, text: async () => '{}' } as Response)); + }); + } + return Promise.resolve({ ok: true, status: 200, text: async () => '{}' } as Response); + }); + vi.stubGlobal('fetch', fetchMock); + return { fetchMock, calls, releaseAll: () => releases.splice(0).forEach((r) => r()) }; + } + + function merchant(id: string, url: string) { + upsertWebhookConfig({ merchantId: id, url, secret: 'a_very_secret_value' }); + return (type = 'payment.completed') => + enqueueWebhookEvent({ merchantId: id, type, payload: { id } }).delivery!; + } + + it('delivers to healthy hosts while another host hangs', async () => { + vi.useFakeTimers(); + const { calls, releaseAll } = stubFetch(); + const slow = merchant('m_hang', 'https://hang.slow-merchant.example/hook'); + const fast = merchant('m_fast', 'https://fast-merchant.example/hook'); + + const slowDelivery = slow(); + const fastDeliveries = [fast(), fast(), fast()]; + + startWebhookWorker(); + await vi.advanceTimersByTimeAsync(1_000); + + // The hanging host holds only its own lane; the healthy host drains fully. + for (const d of fastDeliveries) expect(getWebhookDelivery(d.id)?.status).toBe('delivered'); + expect(getWebhookDelivery(slowDelivery.id)?.status).toBe('processing'); + expect(getActiveWebhookShards()).toEqual(['hang.slow-merchant.example']); + + // A delivery enqueued for the healthy host later is not stuck behind the hang either. + const late = fast('payment.refunded'); + await vi.advanceTimersByTimeAsync(1_000); + expect(getWebhookDelivery(late.id)?.status).toBe('delivered'); + + // The hanging host was sent exactly one request across all those ticks. + expect(calls.filter((url) => url.includes('hang'))).toHaveLength(1); + + releaseAll(); + await vi.advanceTimersByTimeAsync(0); + expect(getWebhookDelivery(slowDelivery.id)?.status).toBe('delivered'); + expect(getActiveWebhookShards()).toEqual([]); + }); + + it('sends one request at a time to the same host, in order', async () => { + const order: string[] = []; + let inFlight = 0; + let maxInFlight = 0; + vi.stubGlobal( + 'fetch', + vi.fn(async (_url: string, init: RequestInit) => { + inFlight += 1; + maxInFlight = Math.max(maxInFlight, inFlight); + order.push(JSON.parse(String(init.body)).type); + await new Promise((r) => setTimeout(r, 5)); + inFlight -= 1; + return { ok: true, status: 200, text: async () => '{}' } as Response; + }), + ); + const send = merchant('m_serial', 'https://serial-merchant.example/hook'); + const deliveries = ['a', 'b', 'c'].map((t) => send(`evt.${t}`)); + + await drainWebhookDeliveries(); + + expect(maxInFlight).toBe(1); + expect(order).toEqual(['evt.a', 'evt.b', 'evt.c']); + for (const d of deliveries) expect(getWebhookDelivery(d.id)?.status).toBe('delivered'); + }); + + it('still retries failures on their own host without blocking others', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => + url.includes('broken') + ? ({ ok: false, status: 503, text: async () => 'down' } as Response) + : ({ ok: true, status: 200, text: async () => '{}' } as Response), + ), + ); + const broken = merchant('m_broken', 'https://broken-merchant.example/hook')(); + const healthy = merchant('m_healthy', 'https://healthy-merchant.example/hook')(); + + await drainWebhookDeliveries(); + + expect(getWebhookDelivery(healthy.id)?.status).toBe('delivered'); + const failed = getWebhookDelivery(broken.id)!; + expect(failed.status).toBe('retrying'); + expect(failed.attempt).toBe(1); + expect(failed.lastError).toBe('HTTP 503'); + }); + + it('exposes dispatch stats with queue-wait percentiles and the active config', async () => { + stubFetch(); + merchant('m_stats', 'https://stats-merchant.example/hook')(); + + await drainWebhookDeliveries(); + + const stats = getWebhookDispatchStats(); + expect(stats.config).toEqual({ maxConcurrentShards: 8, maxBatchPerShard: 25 }); + expect(stats.passes).toBeGreaterThan(0); + expect(stats.deliveriesStarted).toBeGreaterThan(0); + expect(stats.queueWaitMs.samples).toBeGreaterThan(0); + expect(stats.activeShards).toBe(0); + }); +}); diff --git a/backend/src/services/webhooks.ts b/backend/src/services/webhooks.ts index fd9b697c..d2cf4a85 100644 --- a/backend/src/services/webhooks.ts +++ b/backend/src/services/webhooks.ts @@ -1,4 +1,13 @@ import { createHmac, randomUUID } from 'node:crypto'; +import { logger } from '../utils/logger.js'; +import { + ShardedDispatcher, + readShardDispatcherOptions, + shardKeyForUrl, + UNPARSEABLE_URL_SHARD, + type DispatchPassResult, + type DispatchStatsSnapshot, +} from './webhooks/shard-dispatcher.js'; export type WebhookDeliveryStatus = | 'pending' @@ -48,8 +57,6 @@ export interface WebhookDeliveryLog { type WorkerState = { timer?: NodeJS.Timeout; running: boolean; - /** True while a pass over due deliveries is in flight, so the 1s ticker never overlaps itself. */ - processing: boolean; }; const MAX_ATTEMPTS = 5; @@ -62,7 +69,7 @@ const deliveries = new Map(); const idempotencyIndex = new Map(); const deadLetterQueue: WebhookDeliveryLog[] = []; -const worker: WorkerState = { running: false, processing: false }; +const worker: WorkerState = { running: false }; function nowIso(): string { return new Date().toISOString(); @@ -239,33 +246,73 @@ async function deliverOne(delivery: WebhookDeliveryLog): Promise { } } -async function processDueDeliveries(): Promise { - const now = Date.now(); - const due = Array.from(deliveries.values()).filter((d) => { +/** The shard (destination host) a delivery is sent to (#1462). */ +function deliveryShardKey(delivery: WebhookDeliveryLog): string { + const config = webhookConfigs.get(delivery.configId); + return config ? shardKeyForUrl(config.url) : UNPARSEABLE_URL_SHARD; +} + +let dispatcher: ShardedDispatcher | undefined; + +/** + * Deliveries are sharded by destination host so one slow or hanging endpoint + * only delays its own deliveries instead of every merchant's (#1462). See + * `webhooks/shard-dispatcher.ts`. Created lazily so configuration is read + * when the worker starts, and a bad value fails there. + */ +function getDispatcher(): ShardedDispatcher { + dispatcher ??= new ShardedDispatcher(readShardDispatcherOptions(), { + shardKey: deliveryShardKey, + dueAt: (delivery) => (delivery.nextAttemptAt ? Date.parse(delivery.nextAttemptAt) : undefined), + deliver: deliverOne, + logger, + }); + return dispatcher; +} + +function dueDeliveries(now = Date.now()): WebhookDeliveryLog[] { + return Array.from(deliveries.values()).filter((d) => { if (d.status !== 'pending' && d.status !== 'retrying') return false; if (!d.nextAttemptAt) return false; return new Date(d.nextAttemptAt).getTime() <= now; }); +} - for (const delivery of due) { - await deliverOne(delivery); - } +/** + * Starts a run for every idle shard with due deliveries. A shard still + * draining from an earlier pass is skipped, which is what keeps a delivery + * from being sent twice: overlapping ticks can no longer pick up the same + * still-"pending"/"retrying" delivery, yet other hosts keep flowing. + */ +function processDueDeliveries(): DispatchPassResult { + return getDispatcher().dispatch(dueDeliveries()); +} + +/** + * Dispatches every due delivery and waits until all shards are idle. Used by + * tests and by operational tooling that needs a synchronous drain. + */ +export async function drainWebhookDeliveries(): Promise { + await processDueDeliveries().settled; + await getDispatcher().idle(); +} + +/** Destination hosts whose deliveries are currently draining. */ +export function getActiveWebhookShards(): string[] { + return dispatcher?.activeShards() ?? []; +} + +/** Dispatcher counters and queue-wait percentiles, served by GET /webhooks/dispatch-stats. */ +export function getWebhookDispatchStats(): DispatchStatsSnapshot & { config: ReturnType } { + return { ...getDispatcher().stats(), config: readShardDispatcherOptions() }; } export function startWebhookWorker(): void { if (worker.running) return; + getDispatcher(); worker.running = true; worker.timer = setInterval(() => { - // A pass that is still in flight (e.g. a slow endpoint, or a backlog bigger - // than one tick can clear) must finish before another one starts. Without - // this guard, the next 1s tick starts a second, overlapping pass that can - // pick up and deliver the same still-"pending"/"retrying" delivery a - // second time before the first pass has marked it "processing". - if (worker.processing) return; - worker.processing = true; - void processDueDeliveries().finally(() => { - worker.processing = false; - }); + processDueDeliveries(); }, 1_000); } @@ -273,7 +320,6 @@ export function stopWebhookWorker(): void { if (worker.timer) clearInterval(worker.timer); worker.timer = undefined; worker.running = false; - worker.processing = false; } export function listWebhookDeliveries(): WebhookDeliveryLog[] { diff --git a/backend/src/services/webhooks/__tests__/shard-dispatcher.test.ts b/backend/src/services/webhooks/__tests__/shard-dispatcher.test.ts new file mode 100644 index 00000000..0e37c327 --- /dev/null +++ b/backend/src/services/webhooks/__tests__/shard-dispatcher.test.ts @@ -0,0 +1,238 @@ +import { describe, it, expect, vi } from 'vitest'; +import { + DEFAULT_SHARD_DISPATCHER_OPTIONS, + ShardedDispatcher, + UNPARSEABLE_URL_SHARD, + readShardDispatcherOptions, + shardKeyForUrl, +} from '../shard-dispatcher.js'; + +interface Job { + id: string; + host: string; + dueAt: number; +} + +/** A deliver() whose calls stay pending until released, per job id. */ +function controllableDeliver() { + const pending = new Map void>(); + const started: string[] = []; + const deliver = vi.fn( + (job: Job) => + new Promise((resolve) => { + started.push(job.id); + pending.set(job.id, resolve); + }), + ); + const release = async (id: string) => { + pending.get(id)?.(); + pending.delete(id); + // Let the shard loop advance to its next item. + for (let i = 0; i < 5; i++) await Promise.resolve(); + }; + return { deliver, started, release, pending }; +} + +function dispatcherFor( + deliver: (job: Job) => Promise, + options = DEFAULT_SHARD_DISPATCHER_OPTIONS, + extra: { now?: () => number; logger?: { warn: (...a: unknown[]) => void; error: (...a: unknown[]) => void } } = {}, +) { + return new ShardedDispatcher(options, { + shardKey: (job) => job.host, + dueAt: (job) => job.dueAt, + deliver, + ...extra, + }); +} + +const job = (id: string, host: string, dueAt = 0): Job => ({ id, host, dueAt }); + +describe('shardKeyForUrl', () => { + it('shards by lowercased host, ignoring scheme, port, path and a trailing dot', () => { + expect(shardKeyForUrl('https://API.Example.com/hooks')).toBe('api.example.com'); + expect(shardKeyForUrl('https://api.example.com:8443/x')).toBe('api.example.com'); + expect(shardKeyForUrl('http://api.example.com./x')).toBe('api.example.com'); + }); + + it('keeps different hosts, including subdomains, on different shards', () => { + expect(shardKeyForUrl('https://a.example.com/')).not.toBe(shardKeyForUrl('https://b.example.com/')); + }); + + it('strips IPv6 brackets', () => { + expect(shardKeyForUrl('https://[2001:db8::1]:9000/hook')).toBe('2001:db8::1'); + }); + + it('puts unparseable URLs on a dedicated shard', () => { + expect(shardKeyForUrl('not a url')).toBe(UNPARSEABLE_URL_SHARD); + }); +}); + +describe('readShardDispatcherOptions', () => { + it('uses the defaults when unset or blank', () => { + expect(readShardDispatcherOptions({})).toEqual(DEFAULT_SHARD_DISPATCHER_OPTIONS); + expect( + readShardDispatcherOptions({ WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS: ' ', WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD: '' }), + ).toEqual(DEFAULT_SHARD_DISPATCHER_OPTIONS); + }); + + it('reads valid overrides', () => { + expect( + readShardDispatcherOptions({ WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS: '32', WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD: '5' }), + ).toEqual({ maxConcurrentShards: 32, maxBatchPerShard: 5 }); + }); + + it.each(['0', '-1', '1.5', 'eight', '257'])('rejects WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS=%s', (value) => { + expect(() => readShardDispatcherOptions({ WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS: value })).toThrow( + /WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS must be an integer between 1 and 256/, + ); + }); + + it('rejects an out-of-range batch size', () => { + expect(() => readShardDispatcherOptions({ WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD: '1001' })).toThrow( + /WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD/, + ); + }); +}); + +describe('ShardedDispatcher', () => { + it('a slow host does not delay deliveries to other hosts', async () => { + const { deliver, started, release } = controllableDeliver(); + const dispatcher = dispatcherFor(deliver); + + dispatcher.dispatch([job('slow-1', 'slow.example'), job('fast-1', 'fast.example'), job('fast-2', 'fast.example')]); + + // Both hosts start immediately; the slow one is still pending. + expect(started).toEqual(['slow-1', 'fast-1']); + await release('fast-1'); + expect(started).toEqual(['slow-1', 'fast-1', 'fast-2']); + await release('fast-2'); + expect(dispatcher.activeShards()).toEqual(['slow.example']); + + await release('slow-1'); + await dispatcher.idle(); + expect(dispatcher.activeShards()).toEqual([]); + }); + + it('sends at most one request at a time to a host, oldest first', async () => { + const { deliver, started, release } = controllableDeliver(); + const dispatcher = dispatcherFor(deliver); + + dispatcher.dispatch([job('c', 'h.example', 30), job('a', 'h.example', 10), job('b', 'h.example', 20)]); + expect(started).toEqual(['a']); + await release('a'); + expect(started).toEqual(['a', 'b']); + await release('b'); + await release('c'); + expect(started).toEqual(['a', 'b', 'c']); + }); + + it('skips a host that is still draining instead of sending its deliveries twice', async () => { + const { deliver, started, release } = controllableDeliver(); + const dispatcher = dispatcherFor(deliver); + const items = [job('x1', 'h.example')]; + + const first = dispatcher.dispatch(items); + const second = dispatcher.dispatch(items); + + expect(first).toMatchObject({ started: 1, busy: 0 }); + expect(second).toMatchObject({ started: 0, busy: 1 }); + expect(deliver).toHaveBeenCalledTimes(1); + await release('x1'); + await first.settled; + expect(dispatcher.stats().busyShardSkips).toBe(1); + }); + + it('caps concurrently draining hosts and starts the oldest-waiting hosts first', async () => { + const { deliver, started, release } = controllableDeliver(); + const dispatcher = dispatcherFor(deliver, { maxConcurrentShards: 2, maxBatchPerShard: 25 }); + + const pass = dispatcher.dispatch([ + job('new', 'new.example', 300), + job('old', 'old.example', 100), + job('mid', 'mid.example', 200), + ]); + + expect(pass).toMatchObject({ shards: 3, started: 2, deferred: 1 }); + expect(started).toEqual(['old', 'mid']); + + await release('old'); + const next = dispatcher.dispatch([job('new', 'new.example', 300)]); + expect(next.started).toBe(1); + expect(started).toContain('new'); + await release('mid'); + await release('new'); + await dispatcher.idle(); + }); + + it('drains at most maxBatchPerShard deliveries per run, leaving the rest for a later pass', async () => { + const deliver = vi.fn(async () => {}); + const dispatcher = dispatcherFor(deliver, { maxConcurrentShards: 8, maxBatchPerShard: 2 }); + + const pass = dispatcher.dispatch([job('1', 'h', 1), job('2', 'h', 2), job('3', 'h', 3)]); + await pass.settled; + + expect(deliver.mock.calls.map(([j]) => (j as Job).id)).toEqual(['1', '2']); + }); + + it('keeps draining a host after one delivery throws, and logs it', async () => { + const logger = { warn: vi.fn(), error: vi.fn() }; + const deliver = vi.fn(async (j: Job) => { + if (j.id === 'bad') throw new Error('boom'); + }); + const dispatcher = dispatcherFor(deliver, DEFAULT_SHARD_DISPATCHER_OPTIONS, { logger }); + + await dispatcher.dispatch([job('bad', 'h', 1), job('good', 'h', 2)]).settled; + + expect(deliver).toHaveBeenCalledTimes(2); + expect(dispatcher.activeShards()).toEqual([]); + expect(dispatcher.stats().deliverErrors).toBe(1); + expect(logger.error).toHaveBeenCalledWith('webhook shard delivery threw', { shard: 'h', error: 'boom' }); + }); + + it('records queue wait from the due time and shard run time', async () => { + let now = 1_000; + const deliver = vi.fn(async () => { + now += 50; + }); + const dispatcher = dispatcherFor(deliver, DEFAULT_SHARD_DISPATCHER_OPTIONS, { now: () => now }); + + await dispatcher.dispatch([job('a', 'h', 400), job('b', 'h', 900)]).settled; + + const stats = dispatcher.stats(); + // a waited 1000-400=600ms; b started after a's 50ms send: 1050-900=150ms. + expect(stats.queueWaitMs).toMatchObject({ samples: 2, max: 600, p50: 150 }); + expect(stats.shardRunMs).toMatchObject({ samples: 1, max: 100 }); + expect(stats).toMatchObject({ passes: 1, shardRuns: 1, deliveriesStarted: 2, dueBacklog: 2, activeShards: 0 }); + }); + + it('warns once per minute while saturated', async () => { + let now = 0; + const logger = { warn: vi.fn(), error: vi.fn() }; + const { deliver, release } = controllableDeliver(); + const dispatcher = dispatcherFor(deliver, { maxConcurrentShards: 1, maxBatchPerShard: 25 }, { logger, now: () => now }); + + const items = [job('a', 'a.example', 1), job('b', 'b.example', 2)]; + dispatcher.dispatch(items); + dispatcher.dispatch(items); + expect(logger.warn).toHaveBeenCalledTimes(1); + expect(logger.warn.mock.calls[0][1]).toMatchObject({ deferredShards: 1, maxConcurrentShards: 1 }); + + now += 60_000; + dispatcher.dispatch(items); + expect(logger.warn).toHaveBeenCalledTimes(2); + expect(dispatcher.stats().deferredShards).toBe(3); + await release('a'); + await dispatcher.idle(); + }); + + it('reports an empty pass without starting anything', async () => { + const deliver = vi.fn(async () => {}); + const dispatcher = dispatcherFor(deliver); + const pass = dispatcher.dispatch([]); + await pass.settled; + expect(pass).toMatchObject({ due: 0, shards: 0, started: 0, busy: 0, deferred: 0 }); + expect(deliver).not.toHaveBeenCalled(); + expect(dispatcher.stats().queueWaitMs).toEqual({ samples: 0, p50: 0, p95: 0, p99: 0, max: 0 }); + }); +}); diff --git a/backend/src/services/webhooks/shard-dispatcher.ts b/backend/src/services/webhooks/shard-dispatcher.ts new file mode 100644 index 00000000..d13b83e8 --- /dev/null +++ b/backend/src/services/webhooks/shard-dispatcher.ts @@ -0,0 +1,307 @@ +/** + * Domain-sharded webhook dispatch (#1462). + * + * The delivery worker used to send every due webhook one at a time in a + * single global pass, and skipped whole ticks while a pass was running. One + * slow or hanging endpoint (up to the per-attempt timeout) therefore delayed + * every other merchant's deliveries: head-of-line blocking that showed up as + * tail latency for everyone. + * + * Due deliveries are now grouped by destination host ("shard"). Each shard + * drains on its own lane: + * + * - Within a shard, deliveries run one at a time, oldest first, so a + * merchant's endpoint never sees more than one concurrent request from us. + * - Different shards run concurrently, up to `maxConcurrentShards`. + * - A shard still draining is skipped on later ticks rather than started + * twice, so a delivery is never in flight twice. Other shards keep + * flowing, so a slow host only delays its own deliveries. + * - A shard drains at most `maxBatchPerShard` deliveries per run, so a large + * backlog for one host yields its lane instead of monopolising it. + * + * The dispatcher is generic over the delivery type so it can be tested + * without the HTTP layer; `services/webhooks.ts` wires it to real deliveries. + */ + +export interface ShardDispatcherOptions { + /** Shards (destination hosts) that may drain at the same time. */ + maxConcurrentShards: number; + /** Deliveries a shard drains per run before giving its lane back. */ + maxBatchPerShard: number; +} + +export const DEFAULT_SHARD_DISPATCHER_OPTIONS: ShardDispatcherOptions = { + maxConcurrentShards: 8, + maxBatchPerShard: 25, +}; + +const LIMITS = { + maxConcurrentShards: { min: 1, max: 256 }, + maxBatchPerShard: { min: 1, max: 1_000 }, +} as const; + +/** + * Reads `WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS` and + * `WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD`. A missing value uses the default; + * an invalid one (not an integer, or out of range) throws so a typo surfaces + * at startup instead of silently changing throughput. + */ +export function readShardDispatcherOptions(env: NodeJS.ProcessEnv = process.env): ShardDispatcherOptions { + const read = (name: string, key: keyof ShardDispatcherOptions): number => { + const raw = env[name]; + if (raw === undefined || raw.trim() === '') return DEFAULT_SHARD_DISPATCHER_OPTIONS[key]; + const value = Number(raw); + const { min, max } = LIMITS[key]; + if (!Number.isInteger(value) || value < min || value > max) { + throw new Error(`${name} must be an integer between ${min} and ${max} (got "${raw}")`); + } + return value; + }; + return { + maxConcurrentShards: read('WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS', 'maxConcurrentShards'), + maxBatchPerShard: read('WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD', 'maxBatchPerShard'), + }; +} + +/** Shard for deliveries whose URL cannot be parsed; they still drain, just together. */ +export const UNPARSEABLE_URL_SHARD = 'invalid-url'; + +/** + * The shard a webhook URL belongs to: its lowercased host without a trailing + * dot or IPv6 brackets. The port is ignored, so `api.example.com:8443` and + * `api.example.com` share a lane, because they are usually the same server. + */ +export function shardKeyForUrl(url: string): string { + try { + const host = new URL(url).hostname.toLowerCase().replace(/\.$/, '').replace(/^\[|\]$/g, ''); + return host || UNPARSEABLE_URL_SHARD; + } catch { + return UNPARSEABLE_URL_SHARD; + } +} + +/** Percentiles over the most recent samples of a duration, in ms. */ +export interface LatencySummary { + samples: number; + p50: number; + p95: number; + p99: number; + max: number; +} + +export interface DispatchStatsSnapshot { + /** Shards (destination hosts) draining right now. */ + activeShards: number; + /** Due deliveries seen by the most recent pass. */ + dueBacklog: number; + passes: number; + shardRuns: number; + deliveriesStarted: number; + /** Times a pass found a shard still draining and left it alone. */ + busyShardSkips: number; + /** Times a shard had to wait because `maxConcurrentShards` lanes were busy. */ + deferredShards: number; + /** deliver() calls that threw (outcomes are normally recorded by deliver itself). */ + deliverErrors: number; + /** Time from a delivery becoming due to its send starting: the tail-latency signal. */ + queueWaitMs: LatencySummary; + /** Wall time of one shard run. */ + shardRunMs: LatencySummary; +} + +/** Recent-window size for latency percentiles. */ +const LATENCY_WINDOW = 1_024; + +class LatencyWindow { + private readonly values: number[] = []; + private next = 0; + + record(value: number): void { + if (this.values.length < LATENCY_WINDOW) this.values.push(value); + else this.values[this.next] = value; + this.next = (this.next + 1) % LATENCY_WINDOW; + } + + summary(): LatencySummary { + if (this.values.length === 0) return { samples: 0, p50: 0, p95: 0, p99: 0, max: 0 }; + const sorted = [...this.values].sort((a, b) => a - b); + const at = (q: number) => sorted[Math.min(sorted.length - 1, Math.ceil(q * sorted.length) - 1)]; + return { samples: sorted.length, p50: at(0.5), p95: at(0.95), p99: at(0.99), max: sorted[sorted.length - 1] }; + } +} + +export interface DispatchLogger { + warn(...args: unknown[]): void; + error(...args: unknown[]): void; +} + +export interface ShardDispatcherDeps { + /** Shard (destination host) of a delivery. */ + shardKey(item: T): string; + /** When the delivery became due, in epoch ms, to measure queue wait. */ + dueAt(item: T): number | undefined; + /** Delivers one item. Expected to record its own outcome; a throw is logged and the shard moves on. */ + deliver(item: T): Promise; + logger?: DispatchLogger; + now?: () => number; +} + +/** At most one saturation warning per this interval, so a busy minute logs once. */ +const SATURATION_WARN_INTERVAL_MS = 60_000; + +export interface DispatchPassResult { + /** Due deliveries handed to this pass. */ + due: number; + /** Shards that had due deliveries. */ + shards: number; + /** Shards started by this pass. */ + started: number; + /** Shards skipped because they were still draining from an earlier pass. */ + busy: number; + /** Shards left for a later tick because the concurrency cap was reached. */ + deferred: number; + /** Resolves once every shard started by this pass has finished its run. */ + settled: Promise; +} + +export class ShardedDispatcher { + private readonly active = new Map>(); + private readonly now: () => number; + private readonly counters = { + dueBacklog: 0, + passes: 0, + shardRuns: 0, + deliveriesStarted: 0, + busyShardSkips: 0, + deferredShards: 0, + deliverErrors: 0, + }; + private readonly queueWait = new LatencyWindow(); + private readonly shardRun = new LatencyWindow(); + private lastSaturationWarnAt = Number.NEGATIVE_INFINITY; + + constructor( + private readonly options: ShardDispatcherOptions, + private readonly deps: ShardDispatcherDeps, + ) { + this.now = deps.now ?? Date.now; + } + + /** Shards currently draining. */ + activeShards(): string[] { + return [...this.active.keys()]; + } + + /** Counters and latency percentiles since this dispatcher was created. */ + stats(): DispatchStatsSnapshot { + return { + activeShards: this.active.size, + ...this.counters, + queueWaitMs: this.queueWait.summary(), + shardRunMs: this.shardRun.summary(), + }; + } + + /** Resolves once every shard that is currently draining has finished. */ + async idle(): Promise { + while (this.active.size > 0) { + await Promise.all(this.active.values()); + } + } + + /** + * Starts a run for every idle shard with due deliveries, oldest shard + * first, until the concurrency cap is reached. Never waits for deliveries; + * use `settled` (or `idle()`) to wait for the started runs. + */ + dispatch(due: readonly T[]): DispatchPassResult { + const groups = new Map(); + for (const item of due) { + const key = this.deps.shardKey(item); + const group = groups.get(key); + if (group) group.push(item); + else groups.set(key, [item]); + } + + // Oldest-due shard first, so a lane freed by the cap goes to the shard + // that has been waiting longest. + const ordered = [...groups.entries()] + .map(([key, items]) => { + const sorted = [...items].sort((a, b) => (this.deps.dueAt(a) ?? 0) - (this.deps.dueAt(b) ?? 0)); + return { key, items: sorted, oldest: this.deps.dueAt(sorted[0]) ?? 0 }; + }) + .sort((a, b) => a.oldest - b.oldest); + + let started = 0; + let busy = 0; + let deferred = 0; + const runs: Promise[] = []; + for (const { key, items } of ordered) { + if (this.active.has(key)) { + busy += 1; + continue; + } + if (this.active.size >= this.options.maxConcurrentShards) { + deferred += 1; + continue; + } + const run = this.runShard(key, items.slice(0, this.options.maxBatchPerShard)); + this.active.set(key, run); + runs.push(run); + started += 1; + } + + this.counters.passes += 1; + this.counters.dueBacklog = due.length; + this.counters.busyShardSkips += busy; + this.counters.deferredShards += deferred; + if (deferred > 0) this.warnSaturated(deferred); + + return { + due: due.length, + shards: groups.size, + started, + busy, + deferred, + settled: Promise.all(runs).then(() => undefined), + }; + } + + private warnSaturated(deferred: number): void { + const now = this.now(); + if (now - this.lastSaturationWarnAt < SATURATION_WARN_INTERVAL_MS) return; + this.lastSaturationWarnAt = now; + this.deps.logger?.warn('webhook dispatch saturated: shards are waiting for a free lane', { + deferredShards: deferred, + activeShards: this.active.size, + maxConcurrentShards: this.options.maxConcurrentShards, + hint: 'raise WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS if this persists', + }); + } + + private async runShard(key: string, items: T[]): Promise { + const startedAt = this.now(); + this.counters.shardRuns += 1; + try { + for (const item of items) { + const dueAt = this.deps.dueAt(item); + if (dueAt !== undefined) this.queueWait.record(Math.max(0, this.now() - dueAt)); + this.counters.deliveriesStarted += 1; + try { + await this.deps.deliver(item); + } catch (err) { + // deliver() records outcomes itself; a throw here is a bug in that + // path. Keep draining the shard so one bad delivery cannot stall it. + this.counters.deliverErrors += 1; + this.deps.logger?.error('webhook shard delivery threw', { + shard: key, + error: err instanceof Error ? err.message : String(err), + }); + } + } + } finally { + this.active.delete(key); + this.shardRun.record(this.now() - startedAt); + } + } +} diff --git a/docs/WEBHOOK_RETRY_STRATEGY.md b/docs/WEBHOOK_RETRY_STRATEGY.md index c11ecfe1..4336bf90 100644 --- a/docs/WEBHOOK_RETRY_STRATEGY.md +++ b/docs/WEBHOOK_RETRY_STRATEGY.md @@ -140,6 +140,51 @@ const signature = crypto - Timestamps older than 5 minutes are rejected - Duplicate event IDs within 24 hours are rejected +## Domain-Sharded Dispatch + +The delivery worker (`backend/src/services/webhooks.ts`) ticks every second and +hands due deliveries to a sharded dispatcher +(`backend/src/services/webhooks/shard-dispatcher.ts`). Deliveries are grouped by +the destination host of the merchant's webhook URL. Each group (a shard) drains +on its own lane: + +- **One request at a time per host, oldest first.** A merchant endpoint never + receives concurrent requests from us. +- **Hosts drain in parallel.** Up to `WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS` + hosts (default 8) are served at once, so a slow or hanging endpoint holds only + its own lane until its attempt times out. Previously every delivery shared one + sequential pass, and a single slow host delayed all merchants. +- **No double sends.** A host whose lane is still busy is skipped on later + ticks, and its deliveries are picked up once the lane frees. +- **Bounded runs.** A lane drains at most `WEBHOOK_DISPATCH_MAX_BATCH_PER_SHARD` + deliveries (default 25) before giving the lane back, so a large backlog for + one host cannot monopolise it. When every lane is busy, the hosts that have + waited longest get the next free lanes. + +The shard key is the lowercased hostname; the port and path are ignored. +Retries, backoff and dead-lettering are unchanged and stay per delivery. + +### Dispatch stats + +`GET /api/v1/webhooks/dispatch-stats` returns: + +| Field | Meaning | +|-------|---------| +| `activeShards` | Hosts draining right now | +| `dueBacklog` | Due deliveries seen by the last pass | +| `queueWaitMs` | `p50`/`p95`/`p99`/`max` time from due to send start, over the last 1,024 deliveries. This is the tail-latency signal | +| `shardRunMs` | Percentiles of one lane run | +| `busyShardSkips` | Ticks that found a host still draining | +| `deferredShards` | Times a host waited because every lane was busy | +| `deliverErrors` | Unexpected throws while delivering (each is logged with its shard) | +| `config` | The active concurrency and batch limits | + +A rising `deferredShards` with a high `queueWaitMs.p99` means the lanes are +saturated. The worker also logs `webhook dispatch saturated` (at most once a +minute). Raise `WEBHOOK_DISPATCH_MAX_CONCURRENT_SHARDS` if this persists. +Invalid values for either setting stop the worker at startup with a message +naming the variable. + ## Monitoring and Debugging ### Webhook Logs @@ -286,6 +331,7 @@ await sdk.webhooks.updateConfig({ ## Changelog - **2024-10-17**: Initial webhook retry strategy documentation (Issue #1158) +- Domain-sharded dispatch and `GET /webhooks/dispatch-stats` (Issue #1462) ## Related Documentation From a5fbc2eab821c9c59bca4d17ae1a57961135b438 Mon Sep 17 00:00:00 2001 From: JamesVictor-O Date: Fri, 20 Nov 2026 22:55:26 +0100 Subject: [PATCH 3/4] perf(auth): prefetch workspace scopes once per request in the auth middleware Every requirePermission/requireRole check rescanned the whole workspace membership store for the same user, so a route with several checks paid for several scans. The auth middleware now loads the principal's memberships once after a strategy succeeds and attaches them as req.workspaceScopes ({ userId, roles }); RBAC reads the role from there. - Decisions are unchanged: the prefetched role is what getMemberRole returns, and a missing workspace is still a 403. - Scopes are bound to their user: another user falls back to a direct lookup, and scopes present before authentication are cleared. - A loader failure never blocks authentication; it is logged and RBAC falls back to per-check lookups. - createAuthMiddleware takes an optional loadWorkspaceScopes (custom loader, or false to disable); getScopePrefetchStats() reports counts, failures and timing. Also fixes two latent bugs in the touched files: requireRole loaded getMemberRole with a runtime require(), which fails under Vitest's ESM loader (now a static import), and the API-key strategy imported lookupApiKeyRecord, which was renamed to lookupApiKey in #979 and made every x-api-key request throw a TypeError. Closes #1464 --- .../__tests__/auth-scope-prefetch.test.ts | 205 ++++++++++++++++++ backend/src/middleware/auth.ts | 96 +++++++- backend/src/middleware/rbac.ts | 28 ++- backend/src/services/workspaces.ts | 19 ++ docs/security/request-hardening.md | 25 +++ 5 files changed, 365 insertions(+), 8 deletions(-) create mode 100644 backend/src/middleware/__tests__/auth-scope-prefetch.test.ts diff --git a/backend/src/middleware/__tests__/auth-scope-prefetch.test.ts b/backend/src/middleware/__tests__/auth-scope-prefetch.test.ts new file mode 100644 index 00000000..91e61bb4 --- /dev/null +++ b/backend/src/middleware/__tests__/auth-scope-prefetch.test.ts @@ -0,0 +1,205 @@ +/** + * Workspace scope prefetch in the auth middleware (#1464). + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import type { NextFunction, Request, Response } from 'express'; + +// Count every per-check role lookup RBAC makes, while keeping the real store. +vi.mock('../../services/workspaces.js', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, getMemberRole: vi.fn(actual.getMemberRole), getWorkspaceScopes: vi.fn(actual.getWorkspaceScopes) }; +}); + +import { + createAuthMiddleware, + getScopePrefetchStats, + resetScopePrefetchStatsForTests, + type AuthPrincipal, + type AuthStrategy, +} from '../auth.js'; +import { requirePermission, requireRole } from '../rbac.js'; +import * as workspaces from '../../services/workspaces.js'; + +const getMemberRole = vi.mocked(workspaces.getMemberRole); +const getWorkspaceScopes = vi.mocked(workspaces.getWorkspaceScopes); + +function strategy(principal: Partial & { id: string }, opts: { fail?: boolean } = {}): AuthStrategy { + return { + name: 'token', + applies: () => true, + authenticate: async () => { + if (opts.fail) throw new Error('bad credentials'); + return { tenantId: 't1', role: 'user', method: 'token', ...principal }; + }, + }; +} + +function makeReq(extra: Record = {}): Request { + return { headers: {}, params: {}, query: {}, body: {}, ...extra } as unknown as Request; +} + +async function run(mw: (req: Request, res: Response, next: NextFunction) => unknown, req: Request) { + const next = vi.fn(); + await mw(req, {} as Response, next); + return next; +} + +/** Runs a synchronous RBAC middleware and returns what it passed to next(). */ +function check(mw: (req: Request, res: Response, next: NextFunction) => void, req: Request) { + const next = vi.fn(); + mw(req, {} as Response, next); + return next.mock.calls[0]?.[0]; +} + +describe('auth middleware workspace scope prefetch', () => { + let alphaId: string; + let betaId: string; + + beforeEach(() => { + workspaces.resetForTests(); + resetScopePrefetchStatsForTests(); + vi.clearAllMocks(); + alphaId = workspaces.createWorkspace({ name: 'Alpha', ownerId: 'owner-a' }).id; + betaId = workspaces.createWorkspace({ name: 'Beta', ownerId: 'owner-b' }).id; + workspaces.addMember(alphaId, 'alice', 'admin'); + workspaces.addMember(betaId, 'alice', 'viewer'); + }); + + it('attaches every workspace role of the principal after authenticating', async () => { + const req = makeReq(); + const next = await run(createAuthMiddleware([strategy({ id: 'alice' })]), req); + + expect(next).toHaveBeenCalledWith(); + expect(req.workspaceScopes?.userId).toBe('alice'); + expect(Object.fromEntries(req.workspaceScopes!.roles)).toEqual({ [alphaId]: 'admin', [betaId]: 'viewer' }); + expect(getWorkspaceScopes).toHaveBeenCalledTimes(1); + }); + + it('attaches an empty scope set for a principal with no memberships', async () => { + const req = makeReq(); + await run(createAuthMiddleware([strategy({ id: 'nobody' })]), req); + expect(req.workspaceScopes).toEqual({ userId: 'nobody', roles: new Map() }); + }); + + it('serves every RBAC check on the request from the prefetched scopes', async () => { + const req = makeReq({ params: { workspaceId: alphaId } }); + await run(createAuthMiddleware([strategy({ id: 'alice' })]), req); + + expect(check(requirePermission('payment:read'), req)).toBeUndefined(); + expect(check(requirePermission('payment:refund'), req)).toBeUndefined(); + expect(check(requireRole('admin'), req)).toBeUndefined(); + expect(check(requirePermission('workspace:delete'), req)).toMatchObject({ statusCode: 403 }); + expect(check(requireRole('owner'), req)).toMatchObject({ statusCode: 403 }); + + // Five checks, zero per-check lookups: the single prefetch covered them. + expect(getMemberRole).not.toHaveBeenCalled(); + expect(getWorkspaceScopes).toHaveBeenCalledTimes(1); + }); + + it('denies a workspace the principal does not belong to, from the scopes alone', async () => { + const outsider = workspaces.createWorkspace({ name: 'Gamma', ownerId: 'owner-c' }).id; + const req = makeReq({ params: { workspaceId: outsider } }); + await run(createAuthMiddleware([strategy({ id: 'alice' })]), req); + + expect(check(requirePermission('payment:read'), req)).toMatchObject({ statusCode: 403 }); + expect(check(requireRole('admin'), req)).toMatchObject({ statusCode: 403, message: 'Not a member of this workspace' }); + expect(getMemberRole).not.toHaveBeenCalled(); + }); + + it('matches the direct lookup for every role and action', async () => { + const actions = ['workspace:delete', 'payment:refund', 'payment:approve_refund', 'audit:read', 'webhook:create'] as const; + const roles = ['owner', 'admin', 'member', 'viewer'] as const; + for (const role of roles) { + const userId = `user-${role}`; + if (role !== 'owner') workspaces.addMember(alphaId, userId, role); + const principalId = role === 'owner' ? 'owner-a' : userId; + const req = makeReq({ params: { workspaceId: alphaId } }); + await run(createAuthMiddleware([strategy({ id: principalId })]), req); + for (const action of actions) { + const allowed = check(requirePermission(action), req) === undefined; + expect(allowed, `${role} ${action}`).toBe(workspaces.hasPermission(alphaId, principalId, action)); + } + } + }); + + it('falls back to a direct lookup when the request has no prefetched scopes', () => { + const req = makeReq({ params: { workspaceId: alphaId }, userId: 'alice' }); + expect(check(requirePermission('payment:refund'), req)).toBeUndefined(); + expect(getMemberRole).toHaveBeenCalledWith(alphaId, 'alice'); + }); + + it('never uses scopes that belong to a different user', async () => { + const req = makeReq({ params: { workspaceId: alphaId } }); + await run(createAuthMiddleware([strategy({ id: 'alice' })]), req); + // A later middleware switched the acting user; alice's scopes must not apply. + (req as unknown as { user: AuthPrincipal }).user = { id: 'mallory', tenantId: 't1', role: 'user', method: 'token' }; + + expect(check(requirePermission('payment:read'), req)).toMatchObject({ statusCode: 403 }); + expect(getMemberRole).toHaveBeenCalledWith(alphaId, 'mallory'); + }); + + it('clears scopes supplied before authentication instead of trusting them', async () => { + const forged = { userId: 'alice', roles: new Map([[alphaId, 'owner' as const]]) }; + const req = makeReq({ workspaceScopes: forged }); + const next = await run(createAuthMiddleware([strategy({ id: 'alice' }, { fail: true })]), req); + + expect(next).toHaveBeenCalledWith(expect.any(Error)); + expect(req.workspaceScopes).toBeUndefined(); + }); + + it('does not prefetch when authentication fails', async () => { + const req = makeReq(); + await run(createAuthMiddleware([strategy({ id: 'alice' }, { fail: true })]), req); + expect(getWorkspaceScopes).not.toHaveBeenCalled(); + expect(getScopePrefetchStats().prefetches).toBe(0); + }); + + it('still authenticates when the scope loader fails, and RBAC falls back', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const req = makeReq({ params: { workspaceId: alphaId } }); + const next = await run( + createAuthMiddleware([strategy({ id: 'alice' })], { + loadWorkspaceScopes: () => { + throw new Error('membership store unavailable'); + }, + }), + req, + ); + + expect(next).toHaveBeenCalledWith(); + expect(req.user?.id).toBe('alice'); + expect(req.workspaceScopes).toBeUndefined(); + expect(check(requirePermission('payment:refund'), req)).toBeUndefined(); + expect(getMemberRole).toHaveBeenCalledTimes(1); + expect(getScopePrefetchStats()).toMatchObject({ failures: 1, prefetches: 0 }); + expect(String(warn.mock.calls[0]?.[0])).toContain('workspace scope prefetch failed'); + warn.mockRestore(); + }); + + it('awaits an asynchronous scope loader before continuing', async () => { + const req = makeReq(); + await run( + createAuthMiddleware([strategy({ id: 'alice' })], { + loadWorkspaceScopes: async () => new Map([[alphaId, 'member' as const]]), + }), + req, + ); + expect(req.workspaceScopes?.roles.get(alphaId)).toBe('member'); + }); + + it('can disable prefetching', async () => { + const req = makeReq(); + await run(createAuthMiddleware([strategy({ id: 'alice' })], { loadWorkspaceScopes: false }), req); + expect(req.workspaceScopes).toBeUndefined(); + expect(getWorkspaceScopes).not.toHaveBeenCalled(); + }); + + it('records prefetch counts and timing', async () => { + const mw = createAuthMiddleware([strategy({ id: 'alice' })]); + await run(mw, makeReq()); + await run(mw, makeReq()); + const stats = getScopePrefetchStats(); + expect(stats).toMatchObject({ prefetches: 2, failures: 0 }); + expect(stats.averageDurationMs).toBeGreaterThanOrEqual(0); + }); +}); diff --git a/backend/src/middleware/auth.ts b/backend/src/middleware/auth.ts index d405d941..7e38f086 100644 --- a/backend/src/middleware/auth.ts +++ b/backend/src/middleware/auth.ts @@ -25,9 +25,11 @@ import { AppError } from './errorHandler.js'; import { hmacAuthMiddleware, HEADER_SIGNATURE } from './hmac-auth.js'; import { tokenAuthMiddleware } from './token-auth.js'; import { getSession } from '../services/session.js'; -import { lookupApiKeyRecord } from '../services/api-key-registry.js'; +import { lookupApiKey } from '../services/api-key-registry.js'; import type { AccessTokenClaims } from '../auth/jwt.js'; import { mergeLogContext } from '../logging/context.js'; +import { getWorkspaceScopes, type WorkspaceRole } from '../services/workspaces.js'; +import { logger } from '../utils/logger.js'; export type AuthMethod = 'session' | 'hmac' | 'token' | 'apiKey'; @@ -38,6 +40,80 @@ export interface AuthPrincipal { method: AuthMethod; } +/** + * The principal's workspace memberships (workspace id → role), loaded once + * per request right after authentication (#1464). `userId` records whose + * scopes these are, so a check for a different user never reads them. + */ +export interface WorkspaceScopes { + userId: string; + roles: ReadonlyMap; +} + +export type WorkspaceScopeLoader = ( + principal: AuthPrincipal, +) => ReadonlyMap | Promise>; + +export const defaultWorkspaceScopeLoader: WorkspaceScopeLoader = (principal) => getWorkspaceScopes(principal.id); + +export interface AuthMiddlewareOptions { + /** Loads the principal's workspace scopes; pass `false` to skip prefetching. */ + loadWorkspaceScopes?: WorkspaceScopeLoader | false; +} + +export interface ScopePrefetchStats { + prefetches: number; + failures: number; + lastDurationMs: number; + averageDurationMs: number; +} + +const prefetchStats = { prefetches: 0, failures: 0, lastDurationMs: 0, totalDurationMs: 0 }; + +/** Scope prefetch counters and timing since process start (or the last reset). */ +export function getScopePrefetchStats(): ScopePrefetchStats { + return { + prefetches: prefetchStats.prefetches, + failures: prefetchStats.failures, + lastDurationMs: prefetchStats.lastDurationMs, + averageDurationMs: + prefetchStats.prefetches === 0 ? 0 : prefetchStats.totalDurationMs / prefetchStats.prefetches, + }; +} + +export function resetScopePrefetchStatsForTests(): void { + prefetchStats.prefetches = 0; + prefetchStats.failures = 0; + prefetchStats.lastDurationMs = 0; + prefetchStats.totalDurationMs = 0; +} + +/** + * Attaches the principal's workspace scopes to the request. A loader failure + * never fails authentication: the request continues without prefetched + * scopes, and RBAC falls back to looking the role up directly, so access + * decisions stay correct. + */ +async function prefetchWorkspaceScopes(req: Request, principal: AuthPrincipal, load: WorkspaceScopeLoader): Promise { + const started = performance.now(); + try { + const roles = await load(principal); + req.workspaceScopes = { userId: principal.id, roles }; + const duration = performance.now() - started; + prefetchStats.prefetches += 1; + prefetchStats.lastDurationMs = duration; + prefetchStats.totalDurationMs += duration; + } catch (err) { + prefetchStats.failures += 1; + req.workspaceScopes = undefined; + logger.warn('workspace scope prefetch failed; RBAC will look roles up per check', { + principalId: principal.id, + method: principal.method, + error: err instanceof Error ? err.message : String(err), + }); + } +} + // `req.user` is read throughout the codebase (errorHandler, BaseController, // responseFormatter, ...) but was never declared on Express's Request type. declare global { @@ -48,6 +124,8 @@ declare global { accessToken?: string; /** Verified JWT claims, set by `tokenAuthMiddleware`. */ accessTokenClaims?: AccessTokenClaims; + /** Workspace memberships prefetched by the auth middleware (#1464). */ + workspaceScopes?: WorkspaceScopes; } } } @@ -137,7 +215,8 @@ export const apiKeyStrategy: AuthStrategy = { applies: (req) => Boolean(getHeader(req, 'x-api-key')), async authenticate(req) { const key = getHeader(req, 'x-api-key')!; - const record = await lookupApiKeyRecord(key); + // Renamed from lookupApiKeyRecord in #979; the stale import made this strategy throw. + const record = lookupApiKey(key); if (!record) throw new AppError(401, 'Invalid API key', 'API_KEY_INVALID'); return { id: record.key, @@ -157,9 +236,19 @@ export const DEFAULT_AUTH_STRATEGIES: AuthStrategy[] = [sessionStrategy, hmacStr * `req.user`. If none of the applicable strategies succeed, the last * failure is forwarded to the error handler; if no strategy's credential is * present at all, responds 401 "Authentication required". + * + * After a successful authentication the principal's workspace scopes are + * loaded once and attached as `req.workspaceScopes`, so downstream RBAC + * checks (`middleware/rbac.ts`) do not each repeat the membership lookup. */ -export function createAuthMiddleware(strategies: AuthStrategy[] = DEFAULT_AUTH_STRATEGIES): RequestHandler { +export function createAuthMiddleware( + strategies: AuthStrategy[] = DEFAULT_AUTH_STRATEGIES, + options: AuthMiddlewareOptions = {}, +): RequestHandler { + const loadScopes = options.loadWorkspaceScopes ?? defaultWorkspaceScopeLoader; return async function authMiddleware(req: Request, res: Response, next: NextFunction): Promise { + // Never let scopes from an earlier middleware run (or a spoofed object) leak in. + req.workspaceScopes = undefined; const applicable = strategies.filter((s) => s.applies(req)); if (applicable.length === 0) { next(new AppError(401, 'Authentication required', 'AUTH_REQUIRED')); @@ -171,6 +260,7 @@ export function createAuthMiddleware(strategies: AuthStrategy[] = DEFAULT_AUTH_S const principal = await applicable[i].authenticate(req, res); req.user = principal; mergeLogContext({ tenantId: principal.tenantId }); + if (loadScopes) await prefetchWorkspaceScopes(req, principal, loadScopes); next(); return; } catch (err) { diff --git a/backend/src/middleware/rbac.ts b/backend/src/middleware/rbac.ts index 20bed040..c75993d7 100644 --- a/backend/src/middleware/rbac.ts +++ b/backend/src/middleware/rbac.ts @@ -1,6 +1,25 @@ import { Request, Response, NextFunction } from 'express'; import { AppError } from './errorHandler.js'; -import { hasPermission, ResourceAction } from '../services/workspaces.js'; +import { + getMemberRole, + roleHasPermission, + type ResourceAction, + type WorkspaceRole, +} from '../services/workspaces.js'; + +/** + * The user's role in a workspace. Uses the scopes the auth middleware + * prefetched for this request when they belong to the same user (#1464); + * otherwise falls back to a direct lookup, e.g. on routes that set + * `req.userId` without going through `authMiddleware`. + */ +function resolveRole(req: Request, workspaceId: string, userId: string): WorkspaceRole | undefined { + const scopes = req.workspaceScopes; + if (scopes && scopes.userId === userId) { + return scopes.roles.get(workspaceId); + } + return getMemberRole(workspaceId, userId); +} /** * Middleware factory that checks if the authenticated user has the required @@ -24,7 +43,8 @@ export function requirePermission(action: ResourceAction, getWorkspaceId?: (req: return; } - if (!hasPermission(workspaceId, userId, action)) { + const role = resolveRole(req, workspaceId, userId); + if (!role || !roleHasPermission(role, action)) { next(new AppError(403, 'Insufficient permissions for this action', 'FORBIDDEN')); return; } @@ -80,9 +100,7 @@ export function requireRole(minimumRole: 'admin' | 'owner') { return; } - // Import dynamically to avoid circular deps - const { getMemberRole } = require('../services/workspaces.js'); - const role = getMemberRole(workspaceId, userId); + const role = resolveRole(req, workspaceId, userId); if (!role) { next(new AppError(403, 'Not a member of this workspace', 'FORBIDDEN')); diff --git a/backend/src/services/workspaces.ts b/backend/src/services/workspaces.ts index 4eac8ee8..eeefa987 100644 --- a/backend/src/services/workspaces.ts +++ b/backend/src/services/workspaces.ts @@ -473,6 +473,25 @@ export function requirePermission( } } +/** Whether `role` grants `action`. */ +export function roleHasPermission(role: WorkspaceRole, action: ResourceAction): boolean { + return ROLE_PERMISSIONS[role].includes(action); +} + +/** + * Every workspace `userId` belongs to, with their role, collected in a single + * pass over the member store. The auth middleware calls this once per request + * so RBAC checks on that request read the result instead of each rescanning + * the store (#1464). + */ +export function getWorkspaceScopes(userId: string): Map { + const scopes = new Map(); + for (const member of memberStore.values()) { + if (member.userId === userId) scopes.set(member.workspaceId, member.role); + } + return scopes; +} + export function getRolePermissions(role: WorkspaceRole): ResourceAction[] { return [...ROLE_PERMISSIONS[role]]; } diff --git a/docs/security/request-hardening.md b/docs/security/request-hardening.md index 2d7bb041..7b6c8505 100644 --- a/docs/security/request-hardening.md +++ b/docs/security/request-hardening.md @@ -142,6 +142,31 @@ A link can be used by anyone who holds it until it expires, so keep the lifetime **Breaking change:** `GET /api/v1/receipts/:tokenId/pdf` without a valid grant now returns 401. No code in this repository called the endpoint directly. External callers must first call `download-url`. +## 5. Workspace scopes prefetched at authentication (#1464) + +`authMiddleware` (`backend/src/middleware/auth.ts`) loads the principal's +workspace memberships once, right after a strategy succeeds, and attaches them +as `req.workspaceScopes`: `{ userId, roles: Map }`. +`requirePermission` and `requireRole` (`backend/src/middleware/rbac.ts`) read +the role from there. Before, every check rescanned the whole membership store, +so a route with several checks paid for several scans. + +- **Same decisions.** The prefetched role is the one `getMemberRole` would + return; a workspace missing from the map means "not a member" (403). +- **Bound to one user.** Scopes are used only when `userId` matches the user + being checked. Any other user falls back to a direct lookup, and scopes + present on the request before authentication are cleared, never trusted. +- **Fails open on lookup, never on access.** If loading scopes throws, the + request is still authenticated, a `workspace scope prefetch failed` warning is + logged, and RBAC falls back to per-check lookups. +- **Routes without `authMiddleware`** (those that set `req.userId` themselves) + keep the direct lookup. + +`createAuthMiddleware(strategies, { loadWorkspaceScopes })` accepts a custom +loader (for example a database query) or `false` to turn prefetching off. +`getScopePrefetchStats()` reports prefetch count, failures, and last and +average duration. + ## Rollout notes - Set `RECEIPT_DOWNLOAD_SECRET` in every environment before deploying. From 271cabaebdec28aeea93ec6987d8071ce8f4d2ac Mon Sep 17 00:00:00 2001 From: JamesVictor-O Date: Fri, 20 Nov 2026 23:15:42 +0100 Subject: [PATCH 4/4] feat(frontend): enforce a strict per-request nonce CSP for the dashboard middleware.ts now creates a fresh 128-bit nonce for every document request and sends a policy built by lib/csp.ts: script-src 'self' 'nonce-' 'strict-dynamic'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; ... The nonce and policy are set on the forwarded request (next-intl copies request headers into its response) so Next.js stamps the nonce on every script it renders, and on the response so the browser enforces it. Injected scripts and inline handlers no longer run. Development adds 'unsafe-eval' and local HMR origins only under next dev. - The root layout calls connection() so pages render per request; a nonce cannot be added to statically prerendered HTML. - connect-src allows https:/wss: for wallet RPCs and WalletConnect, plus the configured API and realtime origins; styles keep 'unsafe-inline' because React/Radix/Web3Modal set inline style attributes. - /forms/embed/:id stays frameable by merchant sites; every other page sends frame-ancestors 'none' and X-Frame-Options: DENY. - CSP_REPORT_ONLY=true rolls the policy out as Report-Only; reports go to CSP_REPORT_URI or Sentry's security endpoint for the DSN, via report-uri, report-to and Reporting-Endpoints. - next.config.ts adds nosniff and Referrer-Policy headers. Verified on a production build: every