diff --git a/.github/actions/cleanup/action.yml b/.github/actions/cleanup/action.yml new file mode 100644 index 0000000..6c4eec8 --- /dev/null +++ b/.github/actions/cleanup/action.yml @@ -0,0 +1,36 @@ +name: Run and validate cleanup dry-run +description: Exercise the pinned Cleanup Action with zero target mutations and validate its published event. +inputs: + attempt: + description: first or repeat; records must match across both invocations + required: true +runs: + using: composite + steps: + - name: Execute cleanup dry-run + id: action + continue-on-error: true + uses: commercekit-tools/ccv2-build-cleanup@4ab51d33ded51a360e8223e686bb46918cf7863f + with: + token-endpoint: ${{ env.CCV2_TOKEN_ENDPOINT }} + client-id: ${{ env.CCV2_CLIENT_ID }} + client-secret: ${{ env.CCV2_CLIENT_SECRET }} + resource: ${{ env.CCV2_RESOURCE }} + subscription-code: '131762872233634f29fdeb7d50983aa4' + application-code: commerce + api-base-url: https://ccv2.sandbox.commercekit.tools + retention-days: '30' + keep-latest: '10' + max-deletions: '20' + exclude-build-codes: cleanup-006 + dry-run: 'true' + timeout-minutes: '2' + continue-on-delete-error: 'false' + - name: Validate cleanup outputs, event and observed mutation count + if: ${{ always() }} + shell: bash + run: node scripts/runner.mjs record-cleanup + env: + CLEANUP_ATTEMPT: ${{ inputs.attempt }} + OUTPUTS_JSON: ${{ toJSON(steps.action.outputs) }} + ACTION_OUTCOME: ${{ steps.action.outcome }} diff --git a/.github/workflows/build-approve-deploy.yml b/.github/workflows/build-approve-deploy.yml new file mode 100644 index 0000000..ebc5ea8 --- /dev/null +++ b/.github/workflows/build-approve-deploy.yml @@ -0,0 +1,140 @@ +name: Build, check and approve Sandbox deploy +on: + workflow_dispatch: + inputs: + confirmation: + description: Type RUN-COMMERCEKIT-SANDBOX-TESTS to create disposable Sandbox runs + type: string + required: true +permissions: + contents: read + packages: read +concurrency: + group: commercekit-action-integration + cancel-in-progress: false +jobs: + repository-build: + if: >- + github.repository == 'commercekit-tools/action-integration-tests' && + github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && + inputs.confirmation == 'RUN-COMMERCEKIT-SANDBOX-TESTS' + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + packages: read + actions: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 + with: + node-version-file: .node-version + registry-url: https://npm.pkg.github.com + scope: '@commercekit-tools' + - run: corepack enable + - run: pnpm install --frozen-lockfile + env: + NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Build and validate the integration repository + run: pnpm quality + - name: Verify deployment approval is configured before any Sandbox run + run: node scripts/approval.mjs verify-environment + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + commerce-check: + needs: repository-build + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + - name: Install verified CommerceKit CLI + uses: commercekit-tools/setup-commercekit@7f650f3162ab027bfd784cf879832f44d3248584 + with: + version: '0.1.0-preview.2' + - name: Check the supported synthetic Commerce files + run: commercekit check fixtures/commerce --format github + cloud-build: + needs: commerce-check + runs-on: ubuntu-24.04 + timeout-minutes: 10 + outputs: + build-code: ${{ steps.handoff.outputs.build-code }} + env: + SCENARIO: rolling-success + PROVIDER: none + CONFIRMATION: ${{ inputs.confirmation }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + - name: Set private state directory for this job + run: printf 'STATE_DIRECTORY=%s/commercekit-integration\n' "$RUNNER_TEMP" >> "$GITHUB_ENV" + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 + with: + node-version-file: .node-version + registry-url: https://npm.pkg.github.com + scope: '@commercekit-tools' + - run: corepack enable + - run: pnpm install --frozen-lockfile + env: + NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Create disposable Sandbox build run + id: prepare + run: node scripts/runner.mjs prepare + - name: Execute and validate CCv2 Build Action + if: steps.prepare.outcome == 'success' + uses: ./.github/actions/build + - name: Export only the validated build identifier + id: handoff + run: node scripts/runner.mjs handoff-build + - name: Delete the completed build run and verify cleanup + if: ${{ always() }} + run: node scripts/runner.mjs cleanup + env: + STATE_DIRECTORY: ${{ runner.temp }}/commercekit-integration + deploy: + needs: cloud-build + runs-on: ubuntu-24.04 + timeout-minutes: 10 + environment: sandbox-deploy-approval + permissions: + contents: read + packages: read + actions: read + env: + SCENARIO: rolling-success + PROVIDER: none + CONFIRMATION: ${{ inputs.confirmation }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + - name: Set private state directory for this approved job + run: printf 'STATE_DIRECTORY=%s/commercekit-integration\n' "$RUNNER_TEMP" >> "$GITHUB_ENV" + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 + with: + node-version-file: .node-version + registry-url: https://npm.pkg.github.com + scope: '@commercekit-tools' + - run: corepack enable + - run: pnpm install --frozen-lockfile + env: + NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Recheck approval protection before creating the deployment run + run: node scripts/approval.mjs verify-environment + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Recreate the approved synthetic build in a fresh isolated run + id: prepare + run: node scripts/runner.mjs prepare-approved-deploy + env: + BUILT_BUILD_CODE: ${{ needs.cloud-build.outputs.build-code }} + - name: Deploy the approved synthetic build + if: steps.prepare.outcome == 'success' + uses: ./.github/actions/deploy + with: + phase: initial + - name: Assert approved deployment, its real result and event + if: ${{ always() && steps.prepare.outcome == 'success' }} + run: node scripts/runner.mjs assert-approved-deployment + - name: Delete the approved deployment run and verify cleanup + if: ${{ always() }} + run: node scripts/runner.mjs cleanup + env: + STATE_DIRECTORY: ${{ runner.temp }}/commercekit-integration diff --git a/.github/workflows/cleanup.yml b/.github/workflows/cleanup.yml new file mode 100644 index 0000000..d9ab75e --- /dev/null +++ b/.github/workflows/cleanup.yml @@ -0,0 +1,61 @@ +name: Manual cleanup dry-run integration +on: + workflow_dispatch: + inputs: + confirmation: + description: Type RUN-COMMERCEKIT-SANDBOX-TESTS to create a disposable cleanup fixture + type: string + required: true +permissions: + contents: read + packages: read +concurrency: + group: commercekit-sandbox-cleanup + cancel-in-progress: false +jobs: + cleanup: + if: >- + github.repository == 'commercekit-tools/action-integration-tests' && + github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && + inputs.confirmation == 'RUN-COMMERCEKIT-SANDBOX-TESTS' + runs-on: ubuntu-24.04 + timeout-minutes: 15 + environment: sandbox-e2e + env: + SCENARIO: cleanup-dry-run + PROVIDER: none + CONFIRMATION: ${{ inputs.confirmation }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + - name: Set private state directory for this job + run: printf 'STATE_DIRECTORY=%s/commercekit-cleanup-integration\n' "$RUNNER_TEMP" >> "$GITHUB_ENV" + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 + with: + node-version-file: .node-version + registry-url: https://npm.pkg.github.com + scope: '@commercekit-tools' + - run: corepack enable + - run: pnpm install --frozen-lockfile + env: + NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + - name: Create and seed one isolated cleanup fixture + id: prepare + run: node scripts/runner.mjs prepare + - name: Validate initial cleanup dry-run + if: steps.prepare.outcome == 'success' + uses: ./.github/actions/cleanup + with: + attempt: first + - name: Validate repeated cleanup dry-run + if: steps.prepare.outcome == 'success' + uses: ./.github/actions/cleanup + with: + attempt: repeat + - name: Assert unchanged inventory and zero target API mutations + if: ${{ always() && steps.prepare.outcome == 'success' }} + run: node scripts/runner.mjs assert-cleanup + - name: Delete disposable run and verify cleanup + if: ${{ always() }} + run: node scripts/runner.mjs cleanup + env: + STATE_DIRECTORY: ${{ runner.temp }}/commercekit-cleanup-integration diff --git a/README.md b/README.md index 0c03e4f..28b3bbe 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # CommerceKit Action Integration Tests Integration coverage for the CommerceKit Build → Deploy → Notify flow against the -public CCv2 Sandbox. This repository executes the actual, SHA-pinned Actions and +public CCv2 Sandbox, including an approval-gated synthetic deploy and cleanup dry-run. This repository executes the actual, SHA-pinned Actions and uses their real outputs; it does not replace them with test implementations. Each scenario creates one disposable Sandbox run, runs the Build Action, passes @@ -24,6 +24,31 @@ Start with [setup and dispatch](docs/SETUP.md). The [scenario reference](docs/SC defines expected negative outcomes and required assertions. Passing offline CI is not evidence that live Sandbox scenarios or provider delivery have passed. +## Additional manual workflows + +| Workflow | Order and effect | +| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| [build-approve-deploy.yml](.github/workflows/build-approve-deploy.yml) | Repository quality gate → CommerceKit check of three synthetic files → actual CCv2 Build Action → required approval → recreate the validated build in a fresh Sandbox run → actual Deploy Action | +| [cleanup.yml](.github/workflows/cleanup.yml) | Create an isolated 105-build fixture → actual Cleanup Action in hardcoded dry-run → repeat and compare → verify zero target mutations → remove the run | + +Both require a deliberate main-branch dispatch and +`RUN-COMMERCEKIT-SANDBOX-TESTS`. They have no schedule, real SAP credentials, +provider sends, publication or release steps. The approval environment is +`sandbox-deploy-approval`: reviewer `anilkreddy`, own-run approval allowed, main +only, administrator bypass disabled. Its settings are verified before the build +and again before preparing the approved deployment run. + +The repository stage runs this JavaScript harness's existing `pnpm quality` gate; +it does not compile a customer Commerce application. CommerceKit CLI +`0.1.0-preview.2` checks real supported fixture files. Only a validated build code +crosses jobs; source-run credentials are never exported or uploaded. Approval +starts a fresh synthetic run, with the source code mapped to an `approved-...` +fixture identifier because the Sandbox fixture API does not accept dots in keys. + +See [workflow setup, dispatch and limits](docs/WORKFLOWS.md). In particular, +merged Sandbox source does not prove that the hosted `/cleanup-fixture` endpoint +is deployed. Live workflow results are recorded separately from offline tests. + ## Development Use Node 24 and pnpm 12.6.0, then configure local GitHub Packages read access as @@ -37,9 +62,10 @@ pnpm quality Shared schema validation and CCv2 HTTP/authentication come from the existing `@commercekit-tools/notification-contract` and `@commercekit-tools/ccv2-client` -packages, pinned to `0.0.3`. These package versions are separate from Action -versions. Actual Action pins live once each in the composite wrappers under -`.github/actions/`. +packages, pinned to `0.0.4` and `0.0.3` respectively. These package versions are separate from Action +versions. Action revisions are catalogued in `action-refs.json`. Producer pins live in +the composite wrappers under `.github/actions/`; CLI setup is pinned in the +build/approval workflow. See [Contributing](CONTRIBUTING.md), [agent guidance](AGENTS.md), and the [security policy](SECURITY.md) before changing the harness. diff --git a/action-refs.json b/action-refs.json index 1965ded..9174717 100644 --- a/action-refs.json +++ b/action-refs.json @@ -3,5 +3,7 @@ "actions/setup-node": "949feb2413d6458794dcd2491c4babbbce0c15c1", "commercekit-tools/ccv2-build": "923535d589bd8cebece4f3cbf479608f9535c4c3", "commercekit-tools/ccv2-deploy": "e2b3f4cb7e03bfbcbba22eaf84545829b5629557", - "commercekit-tools/notify": "8242af6a4aaafd7917c93f0db27f1794266efeee" + "commercekit-tools/notify": "8242af6a4aaafd7917c93f0db27f1794266efeee", + "commercekit-tools/ccv2-build-cleanup": "4ab51d33ded51a360e8223e686bb46918cf7863f", + "commercekit-tools/setup-commercekit": "7f650f3162ab027bfd784cf879832f44d3248584" } diff --git a/docs/SCENARIOS.md b/docs/SCENARIOS.md index 5adef0e..cbe4d45 100644 --- a/docs/SCENARIOS.md +++ b/docs/SCENARIOS.md @@ -93,3 +93,25 @@ The provider suite additionally verifies webhook acceptance of actual producer events. Representative Slack/Teams visual inspection and a separate owner decision are still required before releasing the Actions. Initial repository creation alone is not evidence that any live suite ran. + +## Standalone cleanup fixture + +The separate manual `cleanup.yml` workflow uses `cleanup-dry-run`; it does not +extend the existing 16-entry full suite or send provider messages. Its shared +catalog seeds 105 builds (two listing pages) and three current/active deployment +references. It includes old/recent completions, latest-count protection, a +start-time tie, deployed/snapshot/excluded/active/unknown/deletion-marked builds, +a missing timestamp and an old completion with recent internal modification. + +The current production-shaped cleanup adapter cannot verify SAP four-hour +eligibility. Expected result: `blocked`, `dryRun=true`, 105 scanned/skipped, +13 protected dispositions, zero eligible/planned/requested/failed/unknown/deferred. +Every exact per-build reason set and the shared cleanup notification are checked; +reason categories overlap. `blocked` in dry-run is a handled successful Action +execution with a shared failure-status notification, not a deletion. + +A second invocation must preserve counts/decisions. Observed target API counters +must contain only supported reads/authentication, and listing counters must prove +both pages across both discovery passes for each invocation. Fixture creation and +run removal are control-plane operations, counted separately from target API +mutations. The final always-run step removes the disposable run and verifies404. diff --git a/docs/SETUP.md b/docs/SETUP.md index e09b065..9be6d7f 100644 --- a/docs/SETUP.md +++ b/docs/SETUP.md @@ -13,8 +13,8 @@ commits. This setup does not deploy the Sandbox or release any Action. 3. Allow the declared `contents: read` and `packages: read` job permissions. The workflows need no contents-write, release, or package-publish permission. 4. In each shared package's **Manage Actions access**, grant this repository - **Read** access to `notification-contract` and `ccv2-client`. Both are pinned - exactly to `0.0.3`. A successful install with an owner's local credential does + **Read** access to `notification-contract` and `ccv2-client`. The contract is pinned + exactly to `0.0.4` and the client to `0.0.3`. A successful install with an owner's local credential does not prove the repository's workflow token has package access. 5. Create/configure the environments below before the first live dispatch. @@ -186,3 +186,11 @@ This repository has no Marketplace, Action-tagging, GitHub Release, or package publication workflow. Its token permissions are read-only. Passing tests here does not release Notify, Build, or Deploy; release remains a separate decision in their owning repositories. + +## Approval-gated build/deploy and cleanup + +The additional `build-approve-deploy.yml` and `cleanup.yml` workflows are manual, +main-only Sandbox integrations. Their exact order, native approval environment, +synthetic handoff, cleanup expectations and dispatch commands are in +[WORKFLOWS.md](WORKFLOWS.md). No permanent SAP or Sandbox secrets are required. +The existing smoke/full/provider suites and their environments remain unchanged. diff --git a/docs/VALIDATION.md b/docs/VALIDATION.md new file mode 100644 index 0000000..3545091 --- /dev/null +++ b/docs/VALIDATION.md @@ -0,0 +1,130 @@ +# Workflow implementation validation — 2026-11-14 + +This record distinguishes offline/local validation from hosted manual workflow +execution. No hosted Sandbox run, provider send, real SAP operation, release, +tag, package publication or Sandbox Worker deployment was performed. + +## Source and dependencies + +- Integration repository base: `a7c06fceadfd50d4f74c15b1d568b9c39b093f91`. +- Existing Build, Deploy, Notify and third-party Action pins are preserved. + Added setup-commercekit `7f650f3162ab027bfd784cf879832f44d3248584` and + cleanup `4ab51d33ded51a360e8223e686bb46918cf7863f`. Full pins live in + [action-refs.json](../action-refs.json) and are enforced by policy tests. +- Existing `@commercekit-tools/ccv2-client@0.0.3` still owns OAuth and Management + API transport. The actual published `notification-contract@0.0.4` owns shared + cleanup event creation/validation; the registry lockfile was regenerated. +- Contract registry integrity: + `sha512-y1kTB/s049V0DGLoQZd4s+vlFscShG5wS5g2H4WH6t6rRSOuJrKiCy42dcNlx5wC7NAy6hQuYoTFOQVQ1+PVoA==`. +- Node 24.21.0 and pnpm 12.6.0; existing dependencies/test stack retained. No copied + Action, OAuth, generic transport, notification schema or provider delivery. + +## Executed checks + +| Command/check | Status | Evidence | +| ------------------------------------------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Baseline `pnpm install --frozen-lockfile` and `pnpm quality` | PASS | 33 pre-change offline tests, all existing checks and audit passed | +| Registry query for `notification-contract@0.0.4` | PASS | Exact published version/integrity verified with authorized read access | +| Updated `pnpm install --frozen-lockfile` | PASS | Registry-only reproducible lockfile, no local links or fake versions | +| Updated `pnpm quality` | PASS | Formatting, ESLint, 62 offline tests, workflow policy, public scan and dependency audit | +| `actionlint .github/workflows/*.yml` | PASS | Existing and new workflows linted with actionlint 1.7.12 | +| `git diff --check` | PASS | No whitespace errors | +| Published CLI check of actual fixture files | PASS | CLI 0.1.0-preview.2; three supported files, zero findings | +| Actual Cleanup bundle against local Sandbox | PASS | Exact consumer fixture and actual assertion function, two runs, matching decisions/counts, zero target mutations | +| Actual Deploy bundle against local Sandbox | PASS | Recreated mapped build fixture, successful actual result/event, one scoped deployment creation, zero Build API calls | +| Configured environment read-back | PASS | Required reviewer/main-only/no-bypass settings verified independently | +| Hosted ordinary PR CI on the implementation head | PASS | [Run 43632346842](https://github.com/commercekit-tools/action-integration-tests/actions/runs/43632346842) on `2563fd12ad4d8588a002a7e3dd0f8ee22b69cffd`; 62 tests, frozen job-token install and audit passed | +| Hosted manual build/check/approval/deploy or cleanup workflow | NOT RUN | No dispatch or hosted Sandbox fixture operations authorized/performed | + +Final offline suite: **62 passed, zero failed/cancelled/skipped**. All existing +16 scenario definitions and smoke/full/provider matrices remain unchanged. +New tests cover native-gate configuration failures, branch/tag restrictions, +read-only fixed GitHub API calls and bounds, CLI fixtures, public-only build +handoff, fresh credentials/private files, forbidden producer fabrication, +mismatched results/state, scoped mutation counters, partial preparation/final +cleanup, 105-build retention reasons, repeated decisions, valid shared events, +zero target mutations and malicious workflow policy changes. + +During dependency replacement, pnpm initially rejected the old 0.0.3 lock entry +after its exact age exception was removed. Regeneration temporarily retained the +already-reviewed old exception; the final manifest/lockfile and age exceptions +contain only client 0.0.3 and contract 0.0.4. Final frozen verification passed. +No release-age policy, audit level or existing test expectation was weakened. + +## Actual CLI evidence + +The public immutable release `cli-v0.1.0-preview.2` was inspected. Its native +Darwin ARM64 archive was downloaded to a private temporary directory and verified +against the GitHub asset digest, published SHA256SUMS and release manifest before +execution. No global installation was made. + +- Release build ID: `bceb04d3246ba74ce96bae27f5407862a11e04eb`. +- Archive size: 32126202 bytes; SHA256: + `264c476c3a6ae0174ec2659f1e1c90b30b0942b78ae2a1e2e970465ec0b1c6eb`. +- Extracted binary SHA256: + `2e955ba4b800a21cc910669dd7485b87371f98b03f78176b3ee1f5001ce037ea`. +- `commercekit --version` returned 0.1.0-preview.2. +- `commercekit check fixtures/commerce --format github` exited 0 with no findings. +- `commercekit check fixtures/commerce --json` returned success with three files: + one each for ImpEx, Properties and Manifest; zero errors/warnings/infos. + +The manual workflow's Ubuntu setup/check execution remains NOT RUN. Availability +of its release assets and passing setup-Action checks do not substitute for that +workflow's execution. + +## Actual local bundle evidence + +Temporary scripts were run with Node 24 first on PATH: + +```sh +node /private/tmp/consumer-local-fixture-check.mjs +node /private/tmp/consumer-approved-deploy-fixture-check.mjs +``` + +They started isolated local HTTPS Sandbox workers from the existing reviewed +checkout equivalent to merged Sandbox `4af998a4783ffa54dd5d7835bfc0dcc4dd382e14`. +The cleanup script imported the exact `getCleanupFixture` and `assertCleanupRecord` +from this repository and executed the real normal bundle twice. All expected +105-build counts/reason sets and actual 0.0.4 events passed; listing counters +proved multiple pages/passes and zero target mutations. Repeat decisions matched. + +The Deploy script used the exact existing pinned Deploy bundle with the mapped +`approved-...` fixture. Actual output/event validation passed, observing one +`createDeployment:d1`, no `createBuild` call, and successful server detail. +This exposed an initial fixture/assertion mismatch using an empty counter key. +The controller and existing ambiguous-create assertion now use the actual scoped +counter contract; regressions reject wrong/extra scopes, invalid counts and +aggregate overflow. This was a real contract correction, not relaxed validation. + +Bundle SHA256: + +- Cleanup: `be0faed210885aad0eabacf2525befd32c5fa6b378d4cd9825f35506c214c4b4`. +- Deploy: `dc9c95ff34749d0fd9c475702b820f608a6f60fef1cf97dde0ee85ae401405ba`. + +Both scripts removed their runs in finally blocks (DELETE 204 then GET 404) and +stopped local workers. These temporary scripts are local validation evidence, +not permanent CI entry points. Production workflow destinations remain fixed to +the hosted Sandbox; no arbitrary destination input was added. + +## Environment and remaining gates + +The owner selected the `sandbox-deploy-approval` environment settings. Separate +API read-backs confirmed required User reviewer `anilkreddy`/5541121, +prevent_self_review=false, can_admins_bypass=false, and exactly one `main` branch +policy, with no tag or wildcard rule. No permanent secrets were added. The native +gate and the two read-only configuration preflights are documented in +[WORKFLOWS.md](WORKFLOWS.md). + +A read-only GET of the public hosted `/openapi/sandbox.json` advertises +`/sandbox/v1/runs/{runId}/cleanup-fixture` (OpenAPI 3.1.0/version 1.0.0). No hosted +run was created to execute that handler. The web reader initially could not open +this metadata URL; a bounded HTTPS curl read succeeded. Repository job-token package access is proven by the successful ordinary PR CI +frozen install. Actual hosted fixture behavior, the new manual jobs' approval +metadata access, Linux CLI execution, native approval, +new hosted flow assertions and final hosted run cleanup remain **NOT RUN** until +an explicitly authorized main-branch manual dispatch after review/merge. + +No real SAP credentials are needed or permitted in these workflows. The cleanup +Action's unresolved production eligibility/operational evidence and owner release +approval gates remain unchanged. No automatic schedule, deletion-enable variable, +force-delete option or credential/artifact handoff was introduced. diff --git a/docs/WORKFLOWS.md b/docs/WORKFLOWS.md new file mode 100644 index 0000000..b8f81c1 --- /dev/null +++ b/docs/WORKFLOWS.md @@ -0,0 +1,133 @@ +# Manual build approval and cleanup workflows + +These workflows exercise SHA-pinned CommerceKit Actions against the fixed +`https://ccv2.sandbox.commercekit.tools` origin. They never target SAP and do not +publish packages, tag releases, deploy the Sandbox Worker or enable real deletion. +Both run only after a deliberate `workflow_dispatch` on this repository's main +branch with exact confirmation `RUN-COMMERCEKIT-SANDBOX-TESTS`. + +## Build → check → cloud build → approval → synthetic deploy + +`build-approve-deploy.yml` has four ordered jobs: + +1. `repository-build`: install frozen dependencies and run the existing offline + `pnpm quality` gate. This JavaScript integration harness has no application + compiler or customer source. Verify the configured approval environment using + read-only GitHub API calls before creating any Sandbox run. +2. `commerce-check`: install the exact published CommerceKit CLI + `0.1.0-preview.2` with the pinned setup Action, then run + `commercekit check fixtures/commerce --format github`. Three committed files + exercise Manifest, Properties and ImpEx checking; an empty directory is not + used as evidence of validation. +3. `cloud-build`: create a disposable isolated run, execute the actual Build + Action, validate its returned result/event and successful build code, then + export only that public identifier. Always remove and verify absence of the + source run. Cleanup failure prevents the dependent deploy job. +4. `deploy`: wait for native GitHub environment approval. After approval, recheck + environment protections, create a fresh isolated run, and seed a new completed + build fixture from the validated public source identifier. Run the actual + Deploy Action with `d1`, `ROLLING_UPDATE`, and database mode `NONE`; validate + its real result/event plus server detail and observed mutation counts. Always + remove this run and verify absence. + +This is explicitly a **recreated synthetic build handoff**, selected by the +owner. It does not preserve or deploy the original resource/run. The supported +Sandbox fixture API disallows dots in fixture keys, so `20261114.1` becomes +`approved-20261114-1`. The summary shows both identities. No Build Action result +or notification is fabricated for the recreated fixture. No generated control +or OAuth credential, raw run file, or private path crosses jobs or becomes an +artifact. Each Sandbox job obtains and masks fresh credentials in private runner-temp +files (`0600`, directory `0700`). + +### Configured approval environment + +On 2026-11-14 the owner selected and the API read-back verified: + +| Setting | Value | +| ---------------------- | ---------------------------------------------- | +| Environment | `sandbox-deploy-approval` | +| Required reviewer | `anilkreddy`, user ID 5541121 | +| Own-run approval | Allowed (`prevent_self_review=false`) | +| Administrator bypass | Disabled (`can_admins_bypass=false`) | +| Allowed deployment ref | Exact `main` branch; no tag or wildcard policy | +| Permanent secrets | None | + +The helper fails closed if the environment is missing, unavailable, has a wrong +reviewer/ref, permits administrator bypass, or returns malformed/oversized data. +The native environment remains the actual approval gate; YAML naming alone does +not configure protection. `actions: read` is granted only to the two jobs that +read environment metadata. All other permissions remain `contents: read` and +`packages: read`; no workflow token receives write access. + +Inspect the live settings if they change: + +```sh +gh api repos/commercekit-tools/action-integration-tests/environments/sandbox-deploy-approval +gh api repos/commercekit-tools/action-integration-tests/environments/sandbox-deploy-approval/deployment-branch-policies +``` + +After this workflow is reviewed and merged, dispatch deliberately: + +```sh +gh workflow run build-approve-deploy.yml \ + --repo commercekit-tools/action-integration-tests --ref main \ + -f confirmation=RUN-COMMERCEKIT-SANDBOX-TESTS +``` + +Wait for the build result, open the run, select **Review deployments**, and approve +`sandbox-deploy-approval`. Rejecting or leaving it unapproved prevents the deploy +job from starting. The source run has already been cleaned before the wait. Job +execution timeouts are 5–10 minutes; GitHub's environment wait is separate. The +workflow uses repository-local concurrency without automatically cancelling an +active run. It is not a distributed lock or a production deployment workflow. + +## Cleanup dry-run + +`cleanup.yml` creates one isolated 105-build fixture using the existing shared +runner and catalog, then executes the actual pinned Cleanup Action twice. Inputs +are fixed to subscription `131762872233634f29fdeb7d50983aa4`, application `commerce`, +retention 30 days, keep-latest 10, cap 20, exclusion `cleanup-006`, timeout 2 minutes, +continue-on-delete-error=false, and **dry-run=true**. There is no apply input or +schedule. `sandbox-e2e` main-only protection remains in use. + +The expected production-shaped result is blocked because eligibility evidence is +unverified. Assertions require exact counts/reasons, valid contract 0.0.4 cleanup +events, matching repeat-run decisions and zero target API mutations. They also +check listing counters to establish multi-page discovery. Fixture/control-plane +operations do not count as target DELETE requests. The run is removed in an +always-run final step, including partial preparation and assertion failures. + +After review/merge and hosted fixture capability verification: + +```sh +gh workflow run cleanup.yml \ + --repo commercekit-tools/action-integration-tests --ref main \ + -f confirmation=RUN-COMMERCEKIT-SANDBOX-TESTS +``` + +No SAP secrets, webhook credentials, Cloudflare credentials, subscription +variables or deletion-enable variables are needed for these Sandbox workflows. +Do not add production credentials to this public test repository. + +## Validation and remaining setup + +Offline CI injects network behavior and never creates hosted Sandbox runs or +sends notifications. It verifies the ordered jobs, native gate and preflights, +read-only permissions, exact Action/CLI pins, fixed origin, private lifecycle, +credential-free handoff, actual shared event validation and zero-mutation cleanup +assertions. See [VALIDATION.md](VALIDATION.md) for commands actually run. + +The hosted Sandbox must support `PUT /sandbox/v1/runs/{id}/cleanup-fixture`, which +is present in the reviewed merged Sandbox source. A read-only check of the hosted public control OpenAPI also advertises this +operation. That metadata read does not execute the fixture handler, and the +Sandbox Worker was not deployed by this task. Hosted capability and end-to-end workflow execution are separate +validation gates. Until a deliberately authorized run succeeds, do not claim +that the hosted approval/deploy or cleanup integrations have passed. The first +manual runs should be inspected for package-read access, fixture API support, +actual approval behavior, Action assertions and successful final run removal. + +The original Build/Deploy/Notify suites remain available through `integration.yml`. +Live provider messages still require their separate confirmation and webhook +setup; these two new workflows send no provider messages. Hard runner termination +can prevent final cleanup; the Sandbox's 24-hour expiry remains a fallback. None +of this clears the cleanup Action's real-SAP eligibility/release gates. diff --git a/fixtures/commerce/languages.impex b/fixtures/commerce/languages.impex new file mode 100644 index 0000000..8a55f88 --- /dev/null +++ b/fixtures/commerce/languages.impex @@ -0,0 +1,2 @@ +INSERT_UPDATE Language;isocode[unique=true];name[lang=en] +;en;English diff --git a/fixtures/commerce/local.properties b/fixtures/commerce/local.properties new file mode 100644 index 0000000..95986d8 --- /dev/null +++ b/fixtures/commerce/local.properties @@ -0,0 +1 @@ +commercekit.integration.mode=synthetic diff --git a/fixtures/commerce/manifest.json b/fixtures/commerce/manifest.json new file mode 100644 index 0000000..efd3e0f --- /dev/null +++ b/fixtures/commerce/manifest.json @@ -0,0 +1,4 @@ +{ + "commerceSuiteVersion": "2211", + "extensions": [] +} diff --git a/package.json b/package.json index 1e710bf..4568341 100644 --- a/package.json +++ b/package.json @@ -22,7 +22,7 @@ "dependencies": { "@actions/core": "3.0.1", "@commercekit-tools/ccv2-client": "0.0.3", - "@commercekit-tools/notification-contract": "0.0.3" + "@commercekit-tools/notification-contract": "0.0.4" }, "devDependencies": { "@eslint/js": "10.0.1", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 082a5d1..db3c5ca 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -176,8 +176,8 @@ importers: specifier: 0.0.3 version: 0.0.3 '@commercekit-tools/notification-contract': - specifier: 0.0.3 - version: 0.0.3 + specifier: 0.0.4 + version: 0.0.4 devDependencies: '@eslint/js': specifier: 10.0.1 @@ -219,8 +219,8 @@ packages: resolution: {integrity: sha512-AkGkMm0KPWsvq34/EHYIYQBgnNfS7eXby3O5z5Gpw6sLTGaoLQReA65UubYsEE+3KKg7dwLtRNknuZfhKDa4Wg==, tarball: https://npm.pkg.github.com/download/@commercekit-tools/ccv2-client/0.0.3/897df8bd5b1dce9a5f3b33ee6f98913b8f7c2ee8} engines: {node: '>=24.21.0'} - '@commercekit-tools/notification-contract@0.0.3': - resolution: {integrity: sha512-+TPMHceFbOTxFetmIfBa7s4y+JrBW+0ZpgnOHce7n6vldeRF2sVeNuDa/9jTYmh1q2R1oNSFiOLAIC6ODUIAQg==, tarball: https://npm.pkg.github.com/download/@commercekit-tools/notification-contract/0.0.3/10e37c57e0325438702d5c93df5563696f056210} + '@commercekit-tools/notification-contract@0.0.4': + resolution: {integrity: sha512-y1kTB/s049V0DGLoQZd4s+vlFscShG5wS5g2H4WH6t6rRSOuJrKiCy42dcNlx5wC7NAy6hQuYoTFOQVQ1+PVoA==, tarball: https://npm.pkg.github.com/download/@commercekit-tools/notification-contract/0.0.4/ea3bb209c62d42cc78865055de3efb193db46876} engines: {node: '>=24.21.0'} '@eslint-community/eslint-utils@4.10.1': @@ -606,7 +606,7 @@ snapshots: '@commercekit-tools/ccv2-client@0.0.3': {} - '@commercekit-tools/notification-contract@0.0.3': + '@commercekit-tools/notification-contract@0.0.4': dependencies: ajv: 8.20.0 ajv-formats: 3.0.1(ajv@8.20.0) diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 9448c7c..73c7f72 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -1,5 +1,5 @@ minimumReleaseAgeExclude: - '@commercekit-tools/ccv2-client@0.0.3' - - '@commercekit-tools/notification-contract@0.0.3' + - '@commercekit-tools/notification-contract@0.0.4' overrides: minimatch: 11.0.1 diff --git a/scripts/approval.mjs b/scripts/approval.mjs new file mode 100644 index 0000000..ace116f --- /dev/null +++ b/scripts/approval.mjs @@ -0,0 +1,149 @@ +import * as core from '@actions/core'; +import { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const environmentName = 'sandbox-deploy-approval'; +const environmentUrl = + 'https://api.github.com/repos/commercekit-tools/action-integration-tests/environments/' + + environmentName; +const errorMessage = 'Deployment approval configuration is missing, unavailable or invalid.'; +const maxJsonBytes = 32768; + +function requireApproval(condition) { + if (!condition) throw new Error(errorMessage); +} + +/** Public handoff value only; no credentials or arbitrary path/shell fragments. */ +export function validateApprovedBuildCode(value) { + if (typeof value !== 'string' || value.length > 64 || !/^\d{8}\.\d+$/.test(value)) + throw new Error('Approved build identifier is invalid.'); + return value; +} + +/** The existing Sandbox fixture keys accept hyphens but not a CCv2 code's dot. */ +export function approvedFixtureBuildCode(value) { + return `approved-${validateApprovedBuildCode(value).replace('.', '-')}`; +} + +/** A new synthetic build, not a fabricated Build Action result or notification. */ +export function createApprovedBuildFixture(buildCode, now = Date.now()) { + const code = approvedFixtureBuildCode(buildCode); + if (!Number.isSafeInteger(now) || now < 60000 || now > 253402300799999) + throw new Error('Approved build fixture clock is invalid.'); + const completedAt = new Date(now).toISOString(); + return { + builds: [ + { + code, + response: { + code, + subscriptionCode: '131762872233634f29fdeb7d50983aa4', + applicationCode: 'commerce', + status: 'SUCCESS', + buildStartTimestamp: new Date(now - 60000).toISOString(), + buildEndTimestamp: completedAt, + deployed: false, + hasSnapshot: false, + }, + modifiedAt: completedAt, + }, + ], + deployments: [], + }; +} + +async function readApprovalJson(url, token, fetcher) { + const response = await fetcher(url, { + method: 'GET', + redirect: 'error', + signal: AbortSignal.timeout(15000), + headers: { + Accept: 'application/vnd.github+json', + Authorization: `Bearer ${token}`, + 'User-Agent': 'CommerceKit-Integration-Tests/1.0', + }, + }); + requireApproval(response.status === 200); + requireApproval((response.headers.get('content-type') ?? '').includes('json')); + const reader = response.body?.getReader(); + requireApproval(reader); + const chunks = []; + let bytes = 0; + try { + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + bytes += value.byteLength; + requireApproval(bytes <= maxJsonBytes); + chunks.push(value); + } + } finally { + await reader.cancel(); + } + return JSON.parse(Buffer.concat(chunks).toString('utf8')); +} + +/** Read-only fail-closed preflight; the native environment remains the actual gate. */ +export async function verifyApprovalEnvironment({ token, fetcher = fetch } = {}) { + try { + requireApproval( + typeof token === 'string' && token.length > 0 && token.length <= 1000 && !/\s/.test(token), + ); + const environment = await readApprovalJson(environmentUrl, token, fetcher); + requireApproval(environment?.name === environmentName); + requireApproval(environment.can_admins_bypass === false); + requireApproval(Array.isArray(environment.protection_rules)); + const reviewerRules = environment.protection_rules.filter( + (rule) => rule?.type === 'required_reviewers', + ); + requireApproval(reviewerRules.length === 1); + const rule = reviewerRules[0]; + requireApproval(rule.prevent_self_review === false); + requireApproval(Array.isArray(rule.reviewers) && rule.reviewers.length === 1); + const reviewer = rule.reviewers[0]; + requireApproval( + reviewer?.type === 'User' && + reviewer.reviewer?.id === 5541121 && + reviewer.reviewer?.login === 'anilkreddy', + ); + requireApproval( + environment.deployment_branch_policy?.protected_branches === false && + environment.deployment_branch_policy?.custom_branch_policies === true, + ); + const branches = await readApprovalJson( + `${environmentUrl}/deployment-branch-policies?per_page=100`, + token, + fetcher, + ); + requireApproval(branches?.total_count === 1); + requireApproval( + Array.isArray(branches.branch_policies) && branches.branch_policies.length === 1, + ); + requireApproval( + branches.branch_policies[0]?.name === 'main' && + branches.branch_policies[0]?.type === 'branch', + ); + return Object.freeze({ + environment: environmentName, + reviewer: 'anilkreddy', + reviewerId: 5541121, + branch: 'main', + administratorBypass: false, + allowSelfApproval: true, + }); + } catch { + throw new Error(errorMessage); + } +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const token = process.env.GITHUB_TOKEN; + if (typeof token === 'string' && token) core.setSecret(token); + try { + requireApproval(process.argv[2] === 'verify-environment'); + await verifyApprovalEnvironment({ token }); + core.info('Required reviewer and main-only deployment approval protection verified.'); + } catch { + core.setFailed(errorMessage); + } +} diff --git a/scripts/check-policy.mjs b/scripts/check-policy.mjs index 83fbc55..b19eb5e 100644 --- a/scripts/check-policy.mjs +++ b/scripts/check-policy.mjs @@ -8,8 +8,10 @@ const workflowPaths = [ '.github/workflows/ci.yml', '.github/workflows/integration.yml', '.github/workflows/_scenario.yml', + '.github/workflows/cleanup.yml', + '.github/workflows/build-approve-deploy.yml', ]; -const compositePaths = ['build', 'deploy', 'notify'].map( +const compositePaths = ['build', 'deploy', 'notify', 'cleanup'].map( (name) => `.github/actions/${name}/action.yml`, ); const compact = (value) => String(value).replace(/\s+/g, ''); @@ -27,7 +29,7 @@ export function validatePolicy(files) { const workflows = Object.keys(files).filter((path) => path.startsWith('.github/workflows/')); assert.deepEqual([...workflows].sort(), [...workflowPaths].sort(), 'Unreviewed workflow.'); const pins = JSON.parse(files['action-refs.json']); - assert.equal(Object.keys(pins).length, 5, 'Unexpected Action dependency.'); + assert.equal(Object.keys(pins).length, 7, 'Unexpected Action dependency.'); for (const sha of Object.values(pins)) assert.match(sha, /^[a-f0-9]{40}$/); const docs = Object.fromEntries( [...workflowPaths, ...compositePaths].map((path) => [path, parse(files[path])]), @@ -38,7 +40,7 @@ export function validatePolicy(files) { if (value.permissions) { assert.equal(typeof value.permissions, 'object', 'Only explicit read permissions allowed.'); for (const [permission, access] of Object.entries(value.permissions)) { - assert(['contents', 'packages'].includes(permission), 'Unreviewed permission.'); + assert(['contents', 'packages', 'actions'].includes(permission), 'Unreviewed permission.'); assert.equal(access, 'read', 'Write permissions and release automation are disabled.'); } } @@ -55,6 +57,7 @@ export function validatePolicy(files) { './.github/actions/build', './.github/actions/deploy', './.github/actions/notify', + './.github/actions/cleanup', ].includes(value.uses), 'Unreviewed local Action.', ); @@ -75,7 +78,7 @@ export function validatePolicy(files) { assert( path.startsWith('.github/actions/') && value.id === 'action' && - /^commercekit-tools\/ccv2-(build|deploy)@/.test(value.uses ?? ''), + /^commercekit-tools\/ccv2-(build|deploy|build-cleanup)@/.test(value.uses ?? ''), 'Only producer execution may defer failure to explicit assertions.', ); } @@ -146,6 +149,128 @@ export function validatePolicy(files) { assert.equal(producer.runs.steps.at(-1).run, 'node scripts/runner.mjs record'); assert(compact(producer.runs.steps.at(-1).if).includes('always()')); } + const cleanupEntry = docs['.github/workflows/cleanup.yml']; + assert.deepEqual(Object.keys(cleanupEntry.on), ['workflow_dispatch']); + assert.deepEqual(Object.keys(cleanupEntry.on.workflow_dispatch.inputs), ['confirmation']); + assert.equal(cleanupEntry.on.workflow_dispatch.inputs.confirmation.required, true); + assert.equal(cleanupEntry.concurrency['cancel-in-progress'], false); + const cleanupJob = cleanupEntry.jobs.cleanup; + assert.equal( + compact(cleanupJob.if), + compact( + "github.repository == 'commercekit-tools/action-integration-tests' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && inputs.confirmation == 'RUN-COMMERCEKIT-SANDBOX-TESTS'", + ), + ); + assert.equal(cleanupJob.environment, 'sandbox-e2e'); + assert.equal(cleanupJob['timeout-minutes'], 15); + assert.equal(cleanupJob.env.SCENARIO, 'cleanup-dry-run'); + assert.equal(cleanupJob.env.PROVIDER, 'none'); + assert.equal(cleanupJob.env.NOTIFICATION_WEBHOOK, undefined); + const cleanupLast = cleanupJob.steps.at(-1); + assert.equal(cleanupLast.run, 'node scripts/runner.mjs cleanup'); + assert.equal(compact(cleanupLast.if), '${{always()}}'); + assert( + cleanupJob.steps.some( + (step) => + step.run === 'node scripts/runner.mjs assert-cleanup' && + compact(step.if).includes('always()'), + ), + ); + assert.deepEqual( + cleanupJob.steps + .filter((step) => step.uses === './.github/actions/cleanup') + .map((step) => step.with.attempt), + ['first', 'repeat'], + ); + const cleanupComposite = docs['.github/actions/cleanup/action.yml']; + const cleanupAction = cleanupComposite.runs.steps.find((step) => step.id === 'action'); + assert.equal(cleanupAction.with['api-base-url'], 'https://ccv2.sandbox.commercekit.tools'); + assert.equal(cleanupAction.with['subscription-code'], '131762872233634f29fdeb7d50983aa4'); + assert.equal(cleanupAction.with['dry-run'], 'true'); + assert.equal(cleanupAction.with['retention-days'], '30'); + assert.equal(cleanupAction.with['keep-latest'], '10'); + assert.equal(cleanupAction.with['max-deletions'], '20'); + assert.equal(cleanupAction.with['timeout-minutes'], '2'); + assert.equal(cleanupComposite.runs.steps.at(-1).run, 'node scripts/runner.mjs record-cleanup'); + assert(compact(cleanupComposite.runs.steps.at(-1).if).includes('always()')); + const approvedEntry = docs['.github/workflows/build-approve-deploy.yml']; + assert.deepEqual(Object.keys(approvedEntry.on), ['workflow_dispatch']); + assert.deepEqual(Object.keys(approvedEntry.on.workflow_dispatch.inputs), ['confirmation']); + assert.equal(approvedEntry.on.workflow_dispatch.inputs.confirmation.required, true); + assert.equal(approvedEntry.concurrency['cancel-in-progress'], false); + assert.equal(approvedEntry.concurrency.group, 'commercekit-action-integration'); + const approvedJobs = approvedEntry.jobs; + assert.deepEqual(Object.keys(approvedJobs), [ + 'repository-build', + 'commerce-check', + 'cloud-build', + 'deploy', + ]); + assert.equal(compact(approvedJobs['repository-build'].if), compact(cleanupJob.if)); + assert.equal(approvedJobs['commerce-check'].needs, 'repository-build'); + assert.equal(approvedJobs['cloud-build'].needs, 'commerce-check'); + assert.equal(approvedJobs.deploy.needs, 'cloud-build'); + assert.equal(approvedJobs.deploy.environment, 'sandbox-deploy-approval'); + for (const job of Object.values(approvedJobs)) { + assert(job['timeout-minutes'] > 0 && job['timeout-minutes'] <= 10); + assert.equal(job.env?.GITHUB_TOKEN, undefined); + } + const repository = approvedJobs['repository-build']; + assert.equal(repository.permissions.actions, 'read'); + const repositoryCommands = repository.steps.map((step) => step.run); + assert(repositoryCommands.includes('pnpm quality')); + assert( + repositoryCommands.indexOf('pnpm quality') < + repositoryCommands.indexOf('node scripts/approval.mjs verify-environment'), + ); + const checkSteps = approvedJobs['commerce-check'].steps; + const setup = checkSteps.find((step) => + step.uses?.startsWith('commercekit-tools/setup-commercekit@'), + ); + assert.equal(setup.with.version, '0.1.0-preview.2'); + assert( + checkSteps.some((step) => step.run === 'commercekit check fixtures/commerce --format github'), + ); + const cloud = approvedJobs['cloud-build']; + assert.deepEqual(cloud.outputs, { 'build-code': '${{ steps.handoff.outputs.build-code }}' }); + const handoff = cloud.steps.find((step) => step.id === 'handoff'); + assert.equal(handoff.run, 'node scripts/runner.mjs handoff-build'); + assert(cloud.steps.some((step) => step.uses === './.github/actions/build')); + const approved = approvedJobs.deploy; + assert.equal(approved.outputs, undefined, 'No credential or private state handoff.'); + assert.equal(approved.permissions.actions, 'read'); + const approvedPrepare = approved.steps.find((step) => step.id === 'prepare'); + assert.equal(approvedPrepare.run, 'node scripts/runner.mjs prepare-approved-deploy'); + assert.equal(approvedPrepare.env.BUILT_BUILD_CODE, '${{ needs.cloud-build.outputs.build-code }}'); + assert( + approved.steps.some( + (step) => step.uses === './.github/actions/deploy' && step.with.phase === 'initial', + ), + ); + assert( + approved.steps.some( + (step) => + step.run === 'node scripts/runner.mjs assert-approved-deployment' && + compact(step.if).includes('always()'), + ), + ); + for (const job of [cloud, approved]) { + assert.equal(job.env.SCENARIO, 'rolling-success'); + assert.equal(job.env.PROVIDER, 'none'); + assert.equal(job.env.CONFIRMATION, '${{ inputs.confirmation }}'); + const last = job.steps.at(-1); + assert.equal(last.run, 'node scripts/runner.mjs cleanup'); + assert.equal(compact(last.if), '${{always()}}'); + } + for (const job of [repository, approved]) { + const verification = job.steps.find( + (step) => step.run === 'node scripts/approval.mjs verify-environment', + ); + assert(verification); + assert.equal(verification.env.GITHUB_TOKEN, '${{ secrets.GITHUB_TOKEN }}'); + const prepareIndex = job.steps.findIndex((step) => step.id === 'prepare'); + assert(prepareIndex < 0 || job.steps.indexOf(verification) < prepareIndex); + } const notify = docs['.github/actions/notify/action.yml'].runs.steps.find( (step) => step.id === 'action', ); diff --git a/scripts/runner.mjs b/scripts/runner.mjs index 5121661..d74a222 100644 --- a/scripts/runner.mjs +++ b/scripts/runner.mjs @@ -6,6 +6,6 @@ try { await runCommand(command, process.env, core); } catch { core.setFailed( - `Integration ${['prepare', 'deploy-inputs', 'record', 'notify-inputs', 'record-notify', 'assert', 'cleanup'].includes(command) ? command : 'command'} failed. No raw provider response or credential is logged.`, + `Integration ${['prepare', 'prepare-approved-deploy', 'handoff-build', 'assert-approved-deployment', 'deploy-inputs', 'record', 'notify-inputs', 'record-notify', 'assert', 'cleanup', 'record-cleanup', 'assert-cleanup'].includes(command) ? command : 'command'} failed. No raw provider response or credential is logged.`, ); } diff --git a/scripts/runtime.mjs b/scripts/runtime.mjs index 2f4323c..0e5af5c 100644 --- a/scripts/runtime.mjs +++ b/scripts/runtime.mjs @@ -3,7 +3,21 @@ import { chmod, lstat, mkdir, readFile, rm, writeFile } from 'node:fs/promises'; import { isAbsolute, join } from 'node:path'; import { TechnicalUserTokenManager, createCcv2Client } from '@commercekit-tools/ccv2-client'; import { parseNotificationEventJson } from '@commercekit-tools/notification-contract'; -import { getScenario, phases, providers } from './scenarios.mjs'; +import { + approvedFixtureBuildCode, + createApprovedBuildFixture, + validateApprovedBuildCode, +} from './approval.mjs'; +import { + cleanupBuildCode, + cleanupPolicy, + cleanupScenarioId, + getCleanupExpectations, + getCleanupFixture, + getScenario, + phases, + providers, +} from './scenarios.mjs'; export const origin = 'https://ccv2.sandbox.commercekit.tools'; export const subscription = '131762872233634f29fdeb7d50983aa4'; @@ -27,7 +41,7 @@ export function assertLiveAuthorization(env) { typeof env.NOTIFICATION_WEBHOOK === 'string' && env.NOTIFICATION_WEBHOOK.length > 0, ); } - getScenario(env.SCENARIO); + if (getScenario(env.SCENARIO).cleanup) requireValue(env.PROVIDER === 'none'); } export async function controlRequest( @@ -36,7 +50,7 @@ export async function controlRequest( ) { requireValue( path === '/sandbox/v1/runs' || - /^\/sandbox\/v1\/runs\/run_[a-f0-9]{32}(?:\/(?:scenario|state))?$/.test(path), + /^\/sandbox\/v1\/runs\/run_[a-f0-9]{32}(?:\/(?:scenario|state|cleanup-fixture))?$/.test(path), ); const response = await fetcher(`${origin}${path}`, { method, @@ -145,6 +159,22 @@ async function managementRead(client, path) { return response.body.value; } +function observedOperationCalls(state, operation) { + requireValue( + state.faultCounters && + typeof state.faultCounters === 'object' && + !Array.isArray(state.faultCounters), + ); + let total = 0; + for (const [key, count] of Object.entries(state.faultCounters)) { + if (!key.startsWith(`${operation}:`)) continue; + requireValue(Number.isSafeInteger(count) && count >= 0); + total += count; + requireValue(Number.isSafeInteger(total)); + } + return total; +} + function phaseFrom(env) { requireValue(phases.includes(env.PHASE)); return env.PHASE; @@ -289,13 +319,126 @@ export function nextDeployInputs(scenarioId, phase, records) { }; } +/** Validate the actual bundled cleanup producer and observed target API calls. */ +export function assertCleanupRecord({ outputs, outcome, run, state }) { + requireValue(outputs && typeof outputs['result-json'] === 'string'); + requireValue(typeof outputs['notification-event'] === 'string'); + for (const name of ['result-json', 'notification-event']) { + requireValue(Buffer.byteLength(outputs[name]) <= 65536); + for (const secret of secrets(run)) requireValue(!outputs[name].includes(secret)); + } + const result = JSON.parse(outputs['result-json']); + const event = parseNotificationEventJson(outputs['notification-event'], { maxBytes: 65536 }); + assert.equal(outcome, 'success'); + assert.equal(result.schemaVersion, 1); + assert.equal(result.status, 'blocked'); + assert.equal(result.dryRun, true); + assert.equal(result.error, undefined); + assert.deepEqual(result.scope, { subscriptionCode: subscription, applicationCode: 'commerce' }); + assert.deepEqual(result.policy, cleanupPolicy); + assert.deepEqual(result.completeness, { inventory: true, protection: false, eligibility: false }); + assert.deepEqual(result.truncation, { omittedDecisions: 0 }); + requireValue(Number.isSafeInteger(result.durationMs) && result.durationMs >= 0); + requireValue( + typeof result.runStartedAt === 'string' && Number.isFinite(Date.parse(result.runStartedAt)), + ); + const expected = getCleanupExpectations(); + assert.deepEqual(result.counts, expected.counts); + assert.equal(outputs['cleanup-status'], result.status); + assert.equal(outputs['dry-run'], 'true'); + assert.equal(outputs['duration-ms'], String(result.durationMs)); + for (const [output, count] of Object.entries({ + 'scanned-count': 'scanned', + 'eligible-count': 'eligible', + 'planned-count': 'planned', + 'deletion-requested-count': 'deletionRequested', + 'skipped-count': 'skipped', + 'failed-count': 'failed', + 'unknown-count': 'unknown', + })) + assert.equal(outputs[output], String(result.counts[count])); + const codes = Array.from({ length: 105 }, (_, index) => cleanupBuildCode(index)); + assert.deepEqual( + result.decisions.map((decision) => decision.code), + codes, + ); + for (const decision of result.decisions) { + assert.equal(decision.applicationCode, 'commerce'); + assert.equal( + decision.disposition, + expected.protectedCodes.includes(decision.code) ? 'protected' : 'blocked', + ); + const reasons = ['eligibility-unverified']; + for (const [reason, indexes] of Object.entries(expected.reasons)) + if (indexes.some((index) => cleanupBuildCode(index) === decision.code)) reasons.push(reason); + assert.deepEqual(decision.reasons.toSorted(), reasons.toSorted()); + } + for (const [reason, indexes] of Object.entries(expected.reasons)) + assert.deepEqual( + result.decisions + .filter((decision) => decision.reasons.includes(reason)) + .map((decision) => decision.code), + indexes.map(cleanupBuildCode), + ); + assert.equal(event.eventType, 'ccv2.build-cleanup.completed'); + assert.equal(event.status, 'failure'); + assert.equal(event.source.component, 'ccv2-build-cleanup'); + assert.equal(event.occurredAt, result.runStartedAt); + assert.equal(event.data.mode, 'dry-run'); + assert.equal(event.data.cleanupStatus, result.status); + assert.equal(event.data.subscriptionCode, subscription); + assert.equal(event.data.applicationCode, 'commerce'); + assert.equal(event.data.retentionDays, cleanupPolicy.retentionDays); + assert.equal(event.data.keepLatest, cleanupPolicy.keepLatest); + assert.equal(event.data.durationMs, result.durationMs); + assert.equal(event.data.error, undefined); + for (const [eventCount, resultCount] of Object.entries({ + scannedCount: 'scanned', + eligibleCount: 'eligible', + plannedCount: 'planned', + deletionRequestedCount: 'deletionRequested', + skippedCount: 'skipped', + failedCount: 'failed', + unknownCount: 'unknown', + deferredCount: 'deferred', + })) + assert.equal(event.data[eventCount], result.counts[resultCount]); + assert.equal(event.context?.repository, 'commercekit-tools/action-integration-tests'); + assert.equal(event.context?.ref, 'refs/heads/main'); + assert.equal(state.counts.builds, 105); + assert.equal(state.counts.deployments, 3); + const readOperations = new Set([ + 'issueToken', + 'getBuilds', + 'getBuild', + 'getDeployments', + 'getEnvironments', + 'getDatabackups', + ]); + requireValue(state.faultCounters && typeof state.faultCounters === 'object'); + for (const [key, count] of Object.entries(state.faultCounters)) { + requireValue(Number.isSafeInteger(count) && count >= 0); + // Target mutations are distinct from control-plane fixture/run operations. + requireValue(readOperations.has(key.split(':')[0]) || count === 0); + } + requireValue(state.faultCounters['getBuilds:'] >= 4); + return { result, event, outputs, outcome, targetApiMutationCount: 0 }; +} + export async function runCommand(command, env, core, dependencies = {}) { const directory = privateDirectory(env); const fetcher = dependencies.fetcher ?? fetch; const request = (path, options) => controlRequest(path, { ...options, fetcher }); const scenario = getScenario(env.SCENARIO); - if (command === 'prepare') { + if (command === 'prepare' || command === 'prepare-approved-deploy') { assertLiveAuthorization(env); + const approved = command === 'prepare-approved-deploy'; + let sourceBuildCode; + if (approved) { + requireValue(env.SCENARIO === 'rolling-success' && env.PROVIDER === 'none'); + // Validate before creating any run; this is the only cross-job handoff value. + sourceBuildCode = validateApprovedBuildCode(env.BUILT_BUILD_CODE); + } await mkdir(directory, { mode: 0o700 }); await chmod(directory, 0o700); const run = validateControlRun( @@ -312,6 +455,27 @@ export async function runCommand(command, env, core, dependencies = {}) { token: run.controlToken, body: scenario.configuration, }); + if (scenario.cleanup) { + const fixture = getCleanupFixture(dependencies.now?.() ?? Date.now()); + await request(`/sandbox/v1/runs/${run.runId}/cleanup-fixture`, { + method: 'PUT', + token: run.controlToken, + body: fixture, + }); + } + if (approved) { + await request(`/sandbox/v1/runs/${run.runId}/cleanup-fixture`, { + method: 'PUT', + token: run.controlToken, + body: createApprovedBuildFixture(sourceBuildCode, dependencies.now?.() ?? Date.now()), + }); + // This is provenance for a recreated fixture, never a fabricated producer record. + await writePrivate(directory, 'approved-build.json', { + sourceBuildCode, + buildCode: approvedFixtureBuildCode(sourceBuildCode), + }); + core.info('Approved build recreated as a new synthetic Sandbox fixture.'); + } for (const [name, value] of Object.entries({ CCV2_TOKEN_ENDPOINT: run.credentials.tokenUrl, CCV2_CLIENT_ID: run.credentials.clientId, @@ -348,17 +512,93 @@ export async function runCommand(command, env, core, dependencies = {}) { } validateRun(run); for (const secret of secrets(run)) core.setSecret(secret); + if (command === 'record-cleanup') { + requireValue(env.SCENARIO === cleanupScenarioId && env.PROVIDER === 'none'); + requireValue(['first', 'repeat'].includes(env.CLEANUP_ATTEMPT)); + const state = await request(`/sandbox/v1/runs/${run.runId}/state`, { token: run.controlToken }); + const record = assertCleanupRecord({ + outputs: JSON.parse(env.OUTPUTS_JSON ?? ''), + outcome: env.ACTION_OUTCOME, + run, + state, + }); + if (env.CLEANUP_ATTEMPT === 'repeat') { + const first = await readPrivate(directory, 'first-cleanup.json'); + assert.deepEqual(record.result.decisions, first.result.decisions); + assert.deepEqual(record.result.counts, first.result.counts); + } + await writePrivate(directory, `${env.CLEANUP_ATTEMPT}-cleanup.json`, record); + core.info( + `Expected ${env.CLEANUP_ATTEMPT} cleanup result/event verified; zero target API mutations.`, + ); + return; + } + if (command === 'assert-cleanup') { + requireValue(env.SCENARIO === cleanupScenarioId && env.PROVIDER === 'none'); + const state = await request(`/sandbox/v1/runs/${run.runId}/state`, { token: run.controlToken }); + for (const attempt of ['first', 'repeat']) { + const record = await readPrivate(directory, `${attempt}-cleanup.json`); + assertCleanupRecord({ ...record, run, state }); + } + requireValue(state.faultCounters['getBuilds:'] >= 8); + await core.summary + ?.addRaw( + '### Sandbox cleanup dry-run\n\n105 builds; two inventory pages per pass; repeated run verified. Zero target API mutations. Cleanup remains blocked by unverified production eligibility; no deletion was requested.\n', + ) + .write(); + core.info('Cleanup dry-run and repeat-run assertions passed; zero target API mutations.'); + return; + } const records = {}; for (const phase of phases) if (await exists(directory, `${phase}.json`)) records[phase] = await readPrivate(directory, `${phase}.json`); + let approved; + if (await exists(directory, 'approved-build.json')) { + requireValue(env.SCENARIO === 'rolling-success' && env.PROVIDER === 'none'); + requireValue(!records.build && !records.followup && !records.final); + approved = await readPrivate(directory, 'approved-build.json'); + validateApprovedBuildCode(approved.sourceBuildCode); + assert.equal(approved.buildCode, approvedFixtureBuildCode(approved.sourceBuildCode)); + } + if (command === 'handoff-build') { + requireValue(env.SCENARIO === 'rolling-success' && env.PROVIDER === 'none' && !approved); + requireValue(records.build && Object.keys(records).length === 1); + const record = assertActionRecord({ + scenarioId: env.SCENARIO, + phase: 'build', + outputs: records.build.outputs, + outcome: records.build.outcome, + run, + }); + const code = validateApprovedBuildCode(record.result.buildCode); + const state = await request(`/sandbox/v1/runs/${run.runId}/state`, { token: run.controlToken }); + assert.equal(state.counts.builds, 1); + assert.equal(state.counts.deployments, 0); + assert.equal(observedOperationCalls(state, 'createBuild'), 1); + assert.equal(observedOperationCalls(state, 'createDeployment'), 0); + core.setOutput('build-code', code); + await core.summary + ?.addRaw( + `### Sandbox build ready for approval\n\nValidated build: \`${code}\`. The source run is removed before approval. After approval, a fresh run will deploy recreated fixture \`${approvedFixtureBuildCode(code)}\`; no credentials cross jobs.\n`, + ) + .write(); + return; + } if (command === 'deploy-inputs') { - const values = nextDeployInputs(env.SCENARIO, phaseFrom(env), records); + const phase = phaseFrom(env); + if (approved) requireValue(phase === 'initial'); + // nextDeployInputs needs only a validated build projection, not a producer event. + const inputRecords = approved + ? { build: { result: { outcome: 'success', buildCode: approved.buildCode } } } + : records; + const values = nextDeployInputs(env.SCENARIO, phase, inputRecords); for (const [name, value] of Object.entries(values)) core.setOutput(name, value); return; } if (command === 'record') { const phase = phaseFrom(env); + if (approved) requireValue(phase === 'initial'); const record = assertActionRecord({ scenarioId: env.SCENARIO, phase, @@ -367,7 +607,9 @@ export async function runCommand(command, env, core, dependencies = {}) { run, }); if (phase !== 'build') { - requireValue(record.result.buildCode === records.build?.result.buildCode); + requireValue( + record.result.buildCode === (approved?.buildCode ?? records.build?.result.buildCode), + ); if (phase !== 'initial') requireValue( record.result.originalDeploymentCode === @@ -405,6 +647,35 @@ export async function runCommand(command, env, core, dependencies = {}) { core.info(`Expected ${phase} provider delivery verified.`); return; } + if (command === 'assert-approved-deployment') { + requireValue(approved && Object.keys(records).length === 1 && records.initial); + const record = assertActionRecord({ + scenarioId: env.SCENARIO, + phase: 'initial', + outputs: records.initial.outputs, + outcome: records.initial.outcome, + run, + }); + assert.equal(record.result.buildCode, approved.buildCode); + const state = await request(`/sandbox/v1/runs/${run.runId}/state`, { token: run.controlToken }); + assert.equal(state.counts.builds, 1); + assert.equal(state.counts.deployments, 1); + assert.equal(observedOperationCalls(state, 'createBuild'), 0); + assert.equal(state.faultCounters['createDeployment:d1'], 1); + assert.equal(observedOperationCalls(state, 'createDeployment'), 1); + const client = + dependencies.client ?? managementClient(run, { fetcher, maskSecret: core.setSecret }); + const detail = await managementRead(client, `/deployments/${record.result.deploymentCode}`); + assert.equal(detail.buildCode, approved.buildCode); + assert.equal(detail.status, 'DEPLOYED'); + await core.summary + ?.addRaw( + `### Approved synthetic Sandbox deployment\n\nSource build: \`${approved.sourceBuildCode}\`. Recreated fixture: \`${approved.buildCode}\`. Deployment: \`${record.result.deploymentCode}\`. The actual Deploy Action result and notification were validated; no Build Action event was fabricated for this fixture.\n`, + ) + .write(); + core.info('Approved recreated fixture deployment result and event verified.'); + return; + } if (command === 'assert') { const required = [ 'build', @@ -435,7 +706,7 @@ export async function runCommand(command, env, core, dependencies = {}) { ); if (env.SCENARIO === 'build-create-error') assert.equal(state.faultCounters['createBuild:'], 1); if (env.SCENARIO === 'deploy-create-error') - assert.equal(state.faultCounters['createDeployment:'], 1); + assert.equal(state.faultCounters['createDeployment:d1'], 1); if (scenario.deploy && env.SCENARIO !== 'deploy-create-error') { const finalPhase = required.at(-1); const client = diff --git a/scripts/scenarios.mjs b/scripts/scenarios.mjs index e5de245..eb55b8c 100644 --- a/scripts/scenarios.mjs +++ b/scripts/scenarios.mjs @@ -53,8 +53,93 @@ const definitions = { export const scenarioIds = Object.freeze(Object.keys(definitions)); export const providers = Object.freeze(['none', 'slack', 'teams-workflow']); export const phases = Object.freeze(['build', 'initial', 'followup', 'final']); +export const cleanupScenarioId = 'cleanup-dry-run'; +export const cleanupPolicy = Object.freeze({ retentionDays: 30, keepLatest: 10, maxDeletions: 20 }); +export const cleanupBuildCode = (index) => `cleanup-${String(index).padStart(3, '0')}`; + +/** Standalone cleanup fixture; deliberately excluded from the existing sixteen-flow suite. */ +export function getCleanupFixture(now = Date.now()) { + if (!Number.isFinite(now)) throw new Error('Invalid cleanup fixture clock.'); + const old = now - 365 * 86400000; + const builds = Array.from({ length: 105 }, (_, index) => ({ + code: cleanupBuildCode(index), + response: { + code: cleanupBuildCode(index), + subscriptionCode: '131762872233634f29fdeb7d50983aa4', + applicationCode: 'commerce', + status: 'SUCCESS', + buildStartTimestamp: new Date(old + Math.min(index, 103) * 60000).toISOString(), + buildEndTimestamp: new Date(old + (60 + index) * 60000).toISOString(), + deployed: false, + hasSnapshot: false, + }, + modifiedAt: new Date(old).toISOString(), + })); + builds[0].response.deployed = true; + builds[1].response.hasSnapshot = true; + builds[2].response.status = 'BUILDING'; + builds[3].response.status = 'UNKNOWN'; + builds[4].response.status = 'DELETED'; + builds[5].response.buildEndTimestamp = new Date(now - 86400000).toISOString(); + builds[9].response.status = 'FAIL'; + delete builds[10].response.buildEndTimestamp; + delete builds[11].response.hasSnapshot; + builds[12].response.status = 'FAIL'; + // Simulator metadata is not a SAP last-modification field or enforcement guarantee. + builds[13].modifiedAt = new Date(now - 3600000).toISOString(); + const deployments = [ + ['scheduled', 7, 'd1', 'SCHEDULED'], + ['current', 8, 's1', 'DEPLOYED'], + ['historical', 9, 'p1', 'FAIL'], + ].map(([code, index, environmentCode, status]) => ({ + code, + response: { + code, + subscriptionCode: '131762872233634f29fdeb7d50983aa4', + buildCode: cleanupBuildCode(index), + environmentCode, + status, + strategy: 'ROLLING_UPDATE', + isCanaryAvailable: false, + createdTimestamp: new Date(old).toISOString(), + }, + })); + return { builds, deployments }; +} + +export function getCleanupExpectations() { + return { + counts: { + scanned: 105, + eligible: 0, + planned: 0, + deletionRequested: 0, + skipped: 105, + failed: 0, + unknown: 0, + protected: 13, + deferred: 0, + }, + protectedCodes: [4, 5, 10, ...Array.from({ length: 10 }, (_, index) => 95 + index)].map( + cleanupBuildCode, + ), + reasons: { + deployed: [0], + 'snapshot-or-backup-reference': [1], + 'active-build': [2, 3], + 'already-marked-for-deletion': [4], + 'retained-age': [5], + 'explicitly-excluded': [6], + 'active-deployment-reference': [7, 8], + 'missing-timestamp': [10], + 'retained-latest': Array.from({ length: 10 }, (_, index) => 95 + index), + }, + }; +} export function getScenario(id) { + if (id === cleanupScenarioId) + return { id, configuration: structuredClone(base), cleanup: true, deploy: false }; if (!Object.hasOwn(definitions, id)) throw new Error('Unknown integration scenario.'); const definition = definitions[id]; const configuration = structuredClone(base); diff --git a/tests/approval.test.mjs b/tests/approval.test.mjs new file mode 100644 index 0000000..e8a1223 --- /dev/null +++ b/tests/approval.test.mjs @@ -0,0 +1,300 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { encodeCcv2PathSegment } from '@commercekit-tools/ccv2-client'; +import { + approvedFixtureBuildCode, + createApprovedBuildFixture, + validateApprovedBuildCode, + verifyApprovalEnvironment, +} from '../scripts/approval.mjs'; + +const token = 'synthetic_readonly_github_token'; +const environmentUrl = + 'https://api.github.com/repos/commercekit-tools/action-integration-tests/environments/sandbox-deploy-approval'; +const failure = /^Deployment approval configuration is missing, unavailable or invalid\.$/; + +function environment() { + return { + name: 'sandbox-deploy-approval', + can_admins_bypass: false, + protection_rules: [ + { + type: 'required_reviewers', + prevent_self_review: false, + reviewers: [{ type: 'User', reviewer: { id: 5541121, login: 'anilkreddy' } }], + }, + ], + deployment_branch_policy: { protected_branches: false, custom_branch_policies: true }, + }; +} + +function branches() { + return { total_count: 1, branch_policies: [{ name: 'main', type: 'branch' }] }; +} + +function fetchFixture(env = environment(), policies = branches()) { + const calls = []; + const fetcher = async (url, init) => { + calls.push({ url, init }); + const value = calls.length === 1 ? env : policies; + return Response.json(value); + }; + return { calls, fetcher }; +} + +test('approval preflight requires the exact native gate with read-only bounded fixed-origin requests', async () => { + const { fetcher, calls } = fetchFixture(); + const result = await verifyApprovalEnvironment({ token, fetcher }); + assert.deepEqual(result, { + environment: 'sandbox-deploy-approval', + reviewer: 'anilkreddy', + reviewerId: 5541121, + branch: 'main', + administratorBypass: false, + allowSelfApproval: true, + }); + assert(!JSON.stringify(result).includes(token)); + assert.deepEqual( + calls.map(({ url }) => url), + [environmentUrl, `${environmentUrl}/deployment-branch-policies?per_page=100`], + ); + for (const { init } of calls) { + assert.equal(init.method, 'GET'); + assert.equal(init.redirect, 'error'); + assert.equal(init.headers.Authorization, `Bearer ${token}`); + assert.equal(init.headers.Accept, 'application/vnd.github+json'); + assert.equal(init.body, undefined); + assert(init.signal instanceof AbortSignal); + assert.equal(init.signal.aborted, false); + } +}); + +test('missing, unprotected, bypassable and mismatched reviewer gates fail before branch reads', async () => { + const mutations = [ + () => null, + () => ({}), + (value) => ({ ...value, name: 'other-environment' }), + (value) => ({ ...value, can_admins_bypass: true }), + (value) => { + delete value.can_admins_bypass; + return value; + }, + (value) => ({ ...value, protection_rules: [] }), + (value) => ({ ...value, protection_rules: {} }), + (value) => ({ ...value, protection_rules: [null] }), + (value) => ({ + ...value, + protection_rules: [...value.protection_rules, ...value.protection_rules], + }), + (value) => { + value.protection_rules[0].prevent_self_review = true; + return value; + }, + (value) => { + delete value.protection_rules[0].prevent_self_review; + return value; + }, + (value) => { + value.protection_rules[0].reviewers = []; + return value; + }, + (value) => { + value.protection_rules[0].reviewers = null; + return value; + }, + (value) => { + value.protection_rules[0].reviewers.push({ + type: 'User', + reviewer: { id: 1, login: 'other' }, + }); + return value; + }, + (value) => { + value.protection_rules[0].reviewers[0].type = 'Team'; + return value; + }, + (value) => { + value.protection_rules[0].reviewers[0].reviewer.id = 1; + return value; + }, + (value) => { + value.protection_rules[0].reviewers[0].reviewer.login = 'other'; + return value; + }, + (value) => { + value.protection_rules[0].reviewers[0].reviewer = null; + return value; + }, + (value) => ({ ...value, deployment_branch_policy: null }), + (value) => ({ + ...value, + deployment_branch_policy: { protected_branches: true, custom_branch_policies: false }, + }), + (value) => ({ + ...value, + deployment_branch_policy: { protected_branches: false }, + }), + ]; + for (const mutate of mutations) { + const { fetcher, calls } = fetchFixture(mutate(environment())); + await assert.rejects(verifyApprovalEnvironment({ token, fetcher }), { message: failure }); + assert.equal(calls.length, 1); + } +}); + +test('branch restrictions require exactly the main branch and cannot admit tags or broad patterns', async () => { + for (const policies of [ + null, + {}, + { total_count: 0, branch_policies: [] }, + { total_count: '1', branch_policies: [{ name: 'main', type: 'branch' }] }, + { total_count: 1, branch_policies: [] }, + { total_count: 1, branch_policies: [null] }, + { total_count: 1, branch_policies: [{ name: '*', type: 'branch' }] }, + { total_count: 1, branch_policies: [{ name: 'main', type: 'tag' }] }, + { total_count: 1, branch_policies: [{ name: 'main' }] }, + { total_count: 2, branch_policies: [{ name: 'main', type: 'branch' }] }, + { + total_count: 1, + branch_policies: [ + { name: 'main', type: 'branch' }, + { name: 'dev', type: 'branch' }, + ], + }, + ]) { + const { fetcher, calls } = fetchFixture(environment(), policies); + await assert.rejects(verifyApprovalEnvironment({ token, fetcher }), { message: failure }); + assert.equal(calls.length, 2); + } +}); + +test('missing and malformed GitHub tokens cause no network request', async () => { + for (const value of [undefined, null, '', ' ', 'secret\nheader', 'x'.repeat(1001), 123]) { + let called = false; + await assert.rejects( + verifyApprovalEnvironment({ + token: value, + fetcher: async () => { + called = true; + throw new Error('Must not request.'); + }, + }), + { message: failure }, + ); + assert.equal(called, false); + } +}); + +test('permission, malformed, oversized, redirected and lost responses fail without logging secrets', async () => { + const responses = [ + () => new Response('synthetic_secret_response', { status: 403 }), + () => new Response('', { status: 404 }), + () => new Response('', { status: 302 }), + () => new Response('synthetic_secret_response', { status: 200 }), + () => + new Response('{synthetic_secret_response', { + headers: { 'Content-Type': 'application/json' }, + }), + () => Response.json({ ...environment(), extra: 'synthetic_secret_response'.repeat(2000) }), + () => ({ status: 200, headers: new Headers({ 'Content-Type': 'application/json' }) }), + () => { + throw new Error(`Lost response includes ${token} and synthetic_secret_response`); + }, + ]; + for (const respond of responses) + for (const failAt of [1, 2]) { + let calls = 0; + await assert.rejects( + verifyApprovalEnvironment({ + token, + fetcher: async () => (++calls === failAt ? respond() : Response.json(environment())), + }), + (error) => { + assert.match(error.message, failure); + assert(!String(error).includes(token)); + assert(!String(error).includes('synthetic_secret_response')); + return true; + }, + ); + assert.equal(calls, failAt); + } +}); + +test('public build handoff accepts only bounded actual Build Action identifiers', () => { + assert.equal(validateApprovedBuildCode('20261114.1'), '20261114.1'); + const longest = `20261114.${'1'.repeat(55)}`; + assert.equal(longest.length, 64); + assert.equal(validateApprovedBuildCode(longest), longest); + for (const value of [ + undefined, + null, + 20261114, + '', + '20261114', + '20261114.', + '.1', + '../20261114.1', + '20261114.1\n', + '20261114.1; echo unsafe', + '20261114.$(unsafe)', + '20261114.1/other', + `20261114.${'1'.repeat(56)}`, + ]) { + assert.throws(() => validateApprovedBuildCode(value), /Approved build identifier is invalid/); + assert.throws(() => approvedFixtureBuildCode(value), /Approved build identifier is invalid/); + assert.throws(() => createApprovedBuildFixture(value), /Approved build identifier is invalid/); + } +}); + +test('approved build recreation uses supported fixture keys and faithful synthetic SAP fields', () => { + const source = '20261114.1'; + const now = Date.parse('2026-11-14T12:00:00Z'); + const fixture = createApprovedBuildFixture(source, now); + assert.equal(approvedFixtureBuildCode(source), 'approved-20261114-1'); + assert.deepEqual(fixture, { + builds: [ + { + code: 'approved-20261114-1', + response: { + code: 'approved-20261114-1', + subscriptionCode: '131762872233634f29fdeb7d50983aa4', + applicationCode: 'commerce', + status: 'SUCCESS', + buildStartTimestamp: '2026-11-14T11:59:00.000Z', + buildEndTimestamp: '2026-11-14T12:00:00.000Z', + deployed: false, + hasSnapshot: false, + }, + modifiedAt: '2026-11-14T12:00:00.000Z', + }, + ], + deployments: [], + }); + const longest = approvedFixtureBuildCode(`20261114.${'1'.repeat(55)}`); + for (const code of [fixture.builds[0].code, longest]) { + assert.match(code, /^[A-Za-z0-9_-]{1,100}$/); + assert.equal(encodeCcv2PathSegment(code), code); + } + assert(!JSON.stringify(fixture).includes('notification-event')); + assert(!JSON.stringify(fixture).includes('result-json')); + const next = createApprovedBuildFixture(source, now); + fixture.builds[0].response.status = 'FAIL'; + assert.equal(next.builds[0].response.status, 'SUCCESS'); + for (const value of [NaN, Infinity, -1, 0, 60000.5, Number.MAX_SAFE_INTEGER, 'now']) + assert.throws(() => createApprovedBuildFixture(source, value), /fixture clock is invalid/); +}); + +test('CommerceKit check targets three actual supported synthetic file types', async () => { + const directory = new URL('../fixtures/commerce/', import.meta.url); + const manifest = JSON.parse(await readFile(new URL('manifest.json', directory), 'utf8')); + assert.deepEqual(manifest, { commerceSuiteVersion: '2211', extensions: [] }); + assert.match( + await readFile(new URL('languages.impex', directory), 'utf8'), + /^INSERT_UPDATE Language;isocode\[unique=true\];name\[lang=en\]\n;en;English\n$/, + ); + assert.equal( + await readFile(new URL('local.properties', directory), 'utf8'), + 'commercekit.integration.mode=synthetic\n', + ); +}); diff --git a/tests/approved-runtime.test.mjs b/tests/approved-runtime.test.mjs new file mode 100644 index 0000000..617b8c3 --- /dev/null +++ b/tests/approved-runtime.test.mjs @@ -0,0 +1,557 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { lstat, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { + createBuildEvent, + createDeploymentEvent, + parseNotificationEventJson, +} from '@commercekit-tools/notification-contract'; +import { origin, runCommand, subscription } from '../scripts/runtime.mjs'; + +const sourceBuildCode = '20261114.7'; +const fixtureBuildCode = 'approved-20261114-7'; +const now = Date.parse('2026-11-14T12:00:00.000Z'); +function syntheticRun(letter) { + return { + runId: `run_${letter.repeat(32)}`, + controlToken: `synthetic-control-${letter.repeat(16)}`, + credentials: { + tokenUrl: `${origin}/oauth2/token`, + clientId: `synthetic-client-${letter.repeat(16)}`, + clientSecret: `synthetic-secret-${letter.repeat(16)}`, + resource: `urn:synthetic-resource:${letter.repeat(16)}`, + }, + }; +} +const envFor = (directory) => ({ + STATE_DIRECTORY: directory, + SCENARIO: 'rolling-success', + PROVIDER: 'none', + CONFIRMATION: 'RUN-COMMERCEKIT-SANDBOX-TESTS', + GITHUB_EVENT_NAME: 'workflow_dispatch', + GITHUB_REPOSITORY: 'commercekit-tools/action-integration-tests', + GITHUB_REF: 'refs/heads/main', + GITHUB_RUN_ID: '123', + GITHUB_RUN_ATTEMPT: '1', +}); +function coreHarness() { + const outputs = []; + const exported = {}; + const masked = []; + const logs = []; + return { + outputs, + exported, + masked, + logs, + setOutput: (name, value) => { + outputs.push([name, value]); + }, + exportVariable: (name, value) => { + exported[name] = value; + }, + setSecret: (value) => { + masked.push(value); + }, + info: (message) => { + logs.push(message); + }, + summary: { + addRaw: (message) => ({ + write: async () => { + logs.push(message); + }, + }), + }, + }; +} +function buildOutputs(code = sourceBuildCode) { + const result = { + schemaVersion: 1, + outcome: 'success', + durationMs: 1000, + pollCount: 1, + buildCode: code, + buildStatus: 'SUCCESS', + }; + return { + 'result-json': JSON.stringify(result), + 'notification-event': JSON.stringify( + createBuildEvent({ status: 'success', data: result, env: {} }), + ), + 'build-code': code, + 'build-status': 'SUCCESS', + 'duration-ms': '1000', + 'poll-count': '1', + }; +} +function deployOutputs(code = fixtureBuildCode) { + const result = { + schemaVersion: 1, + outcome: 'success', + durationMs: 1000, + pollCount: 1, + operation: 'deploy', + buildCode: code, + deploymentCode: '700007', + originalDeploymentCode: '700007', + deploymentStatus: 'DEPLOYED', + actionRequired: false, + }; + return { + 'result-json': JSON.stringify(result), + 'notification-event': JSON.stringify( + createDeploymentEvent({ status: 'success', data: result, env: {} }), + ), + 'build-code': code, + 'deployment-code': '700007', + 'deployment-status': 'DEPLOYED', + 'action-required': 'false', + operation: 'deploy', + 'duration-ms': '1000', + 'poll-count': '1', + }; +} +function controlHarness(run, { approved = false, seedFailure = false } = {}) { + const calls = []; + const state = { + counts: { builds: 1, deployments: approved ? 1 : 0 }, + faultCounters: { 'createBuild:': approved ? 0 : 1, 'createDeployment:d1': approved ? 1 : 0 }, + }; + const fetcher = async (url, init) => { + calls.push({ url, init }); + assert.equal(new URL(url).origin, origin); + assert.equal(init.redirect, 'error'); + const path = new URL(url).pathname; + if (init.method === 'POST') { + assert.equal(path, '/sandbox/v1/runs'); + return Response.json(run, { status: 201 }); + } + assert(path.startsWith(`/sandbox/v1/runs/${run.runId}`)); + assert.equal(init.headers.Authorization, `Bearer ${run.controlToken}`); + if (init.method === 'PUT') { + if (path.endsWith('/cleanup-fixture') && seedFailure) + return Response.json({}, { status: 500 }); + return Response.json({}); + } + if (path.endsWith('/state')) return Response.json(state); + if (init.method === 'DELETE') return new Response(null, { status: 204 }); + return Response.json({}, { status: 404 }); + }; + return { calls, state, fetcher }; +} +const record = (env, phase, outputs, core, dependencies) => + runCommand( + 'record', + { ...env, PHASE: phase, OUTPUTS_JSON: JSON.stringify(outputs), ACTION_OUTCOME: 'success' }, + core, + dependencies, + ); +function clientHarness(detail = { buildCode: fixtureBuildCode, status: 'DEPLOYED' }) { + const reads = []; + return { + reads, + request: async (path, options) => { + reads.push({ path, options }); + assert.equal(path, `/v2/subscriptions/${subscription}/deployments/700007`); + assert.equal(options.policy, 'safe-read'); + assert.equal(options.refreshOn401, true); + assert.equal(options.timeoutMs, 30000); + return { status: 200, body: { kind: 'json', value: detail } }; + }, + }; +} +async function withApproved(action) { + const base = await mkdtemp(join(tmpdir(), 'approved-runtime-')); + const env = { ...envFor(join(base, 'state')), BUILT_BUILD_CODE: sourceBuildCode }; + const run = syntheticRun('b'); + const core = coreHarness(); + const control = controlHarness(run, { approved: true }); + try { + await runCommand('prepare-approved-deploy', env, core, { + fetcher: control.fetcher, + now: () => now, + }); + await action({ env, run, core, control }); + } finally { + await runCommand('cleanup', env, core, { fetcher: control.fetcher }); + await rm(base, { recursive: true, force: true }); + } +} + +test('validated Build handoff, source cleanup and independent approved Deploy preserve only public provenance', async () => { + const base = await mkdtemp(join(tmpdir(), 'approved-handoff-')); + const source = syntheticRun('a'); + const sourceEnv = envFor(join(base, 'source')); + const sourceCore = coreHarness(); + const sourceControl = controlHarness(source); + const approved = syntheticRun('b'); + const approvedEnv = { ...envFor(join(base, 'approved')), BUILT_BUILD_CODE: sourceBuildCode }; + const approvedCore = coreHarness(); + const approvedControl = controlHarness(approved, { approved: true }); + try { + await runCommand('prepare', sourceEnv, sourceCore, { fetcher: sourceControl.fetcher }); + await record(sourceEnv, 'build', buildOutputs(), sourceCore, { + fetcher: sourceControl.fetcher, + }); + const before = sourceCore.outputs.length; + await runCommand('handoff-build', sourceEnv, sourceCore, { fetcher: sourceControl.fetcher }); + assert.deepEqual(sourceCore.outputs.slice(before), [['build-code', sourceBuildCode]]); + await runCommand('cleanup', sourceEnv, sourceCore, { fetcher: sourceControl.fetcher }); + await assert.rejects(lstat(sourceEnv.STATE_DIRECTORY), { code: 'ENOENT' }); + await runCommand('prepare-approved-deploy', approvedEnv, approvedCore, { + fetcher: approvedControl.fetcher, + now: () => now, + }); + assert.notEqual(source.runId, approved.runId); + assert.notEqual(source.credentials.clientSecret, approved.credentials.clientSecret); + assert.equal((await lstat(approvedEnv.STATE_DIRECTORY)).mode & 0o777, 0o700); + for (const name of ['run.json', 'approved-build.json']) + assert.equal((await lstat(join(approvedEnv.STATE_DIRECTORY, name))).mode & 0o777, 0o600); + const projection = JSON.parse( + await readFile(join(approvedEnv.STATE_DIRECTORY, 'approved-build.json'), 'utf8'), + ); + assert.deepEqual(projection, { sourceBuildCode, buildCode: fixtureBuildCode }); + await assert.rejects(lstat(join(approvedEnv.STATE_DIRECTORY, 'build.json')), { + code: 'ENOENT', + }); + await assert.rejects(lstat(join(approvedEnv.STATE_DIRECTORY, 'build-event.json')), { + code: 'ENOENT', + }); + const seed = approvedControl.calls.find(({ url }) => url.endsWith('/cleanup-fixture')); + const fixture = JSON.parse(seed.init.body); + assert.equal(fixture.builds.length, 1); + assert.equal(fixture.builds[0].code, fixtureBuildCode); + assert.equal(fixture.builds[0].response.code, fixtureBuildCode); + assert.equal(fixture.builds[0].response.status, 'SUCCESS'); + assert.deepEqual(fixture.deployments, []); + const outputStart = approvedCore.outputs.length; + await runCommand('deploy-inputs', { ...approvedEnv, PHASE: 'initial' }, approvedCore, { + fetcher: approvedControl.fetcher, + }); + assert.equal( + Object.fromEntries(approvedCore.outputs.slice(outputStart))['build-code'], + fixtureBuildCode, + ); + const outputs = deployOutputs(); + await record(approvedEnv, 'initial', outputs, approvedCore, { + fetcher: approvedControl.fetcher, + }); + const event = parseNotificationEventJson( + await readFile(join(approvedEnv.STATE_DIRECTORY, 'initial-event.json'), 'utf8'), + ); + assert.equal(event.eventType, 'ccv2.deployment.completed'); + assert.equal(event.data.buildCode, fixtureBuildCode); + const client = clientHarness(); + await runCommand('assert-approved-deployment', approvedEnv, approvedCore, { + fetcher: approvedControl.fetcher, + client, + }); + assert.equal(client.reads.length, 1); + for (const [run, core] of [ + [source, sourceCore], + [approved, approvedCore], + ]) { + for (const secret of [run.controlToken, ...Object.values(run.credentials)]) { + assert(core.masked.includes(secret)); + assert(!JSON.stringify(core.outputs).includes(secret)); + assert(!core.logs.join('\n').includes(secret)); + } + assert.equal(core.exported.CCV2_CLIENT_SECRET, run.credentials.clientSecret); + } + assert(approvedCore.logs.some((message) => message.includes('Recreated fixture'))); + await runCommand('cleanup', approvedEnv, approvedCore, { fetcher: approvedControl.fetcher }); + await assert.rejects(lstat(approvedEnv.STATE_DIRECTORY), { code: 'ENOENT' }); + assert.equal(sourceControl.calls.filter(({ init }) => init.method === 'DELETE').length, 1); + assert.equal(approvedControl.calls.filter(({ init }) => init.method === 'DELETE').length, 1); + } finally { + await rm(base, { recursive: true, force: true }); + } +}); + +test('invalid approved source or unauthorized context fails before creating a run', async () => { + const base = await mkdtemp(join(tmpdir(), 'approved-before-create-')); + const env = { ...envFor(join(base, 'state')), BUILT_BUILD_CODE: sourceBuildCode }; + try { + const variants = [ + ...[ + undefined, + '', + 123, + '20261114/7', + 'approved-20261114-7', + '20261114.7\n', + '1'.repeat(65), + ].map((BUILT_BUILD_CODE) => ({ BUILT_BUILD_CODE })), + { CONFIRMATION: '' }, + { GITHUB_EVENT_NAME: 'push' }, + { GITHUB_REF: 'refs/heads/feature' }, + { GITHUB_REPOSITORY: 'someone/fork' }, + { SCENARIO: 'build-failure' }, + { + PROVIDER: 'slack', + PROVIDER_CONFIRMATION: 'SEND-COMMERCEKIT-TEST-NOTIFICATION', + NOTIFICATION_WEBHOOK: 'synthetic-webhook', + }, + ]; + for (const change of variants) { + let called = false; + await assert.rejects( + runCommand('prepare-approved-deploy', { ...env, ...change }, coreHarness(), { + fetcher: async () => { + called = true; + throw Error('Must not fetch'); + }, + }), + ); + assert.equal(called, false); + await assert.rejects(lstat(env.STATE_DIRECTORY), { code: 'ENOENT' }); + } + } finally { + await rm(base, { recursive: true, force: true }); + } +}); + +test('partial approved fixture failure preserves cleanup identity without public credentials or fabricated records', async () => { + const base = await mkdtemp(join(tmpdir(), 'approved-partial-')); + const env = { ...envFor(join(base, 'state')), BUILT_BUILD_CODE: sourceBuildCode }; + const core = coreHarness(); + const control = controlHarness(syntheticRun('b'), { approved: true, seedFailure: true }); + try { + await assert.rejects( + runCommand('prepare-approved-deploy', env, core, { fetcher: control.fetcher }), + ); + assert.equal((await lstat(join(env.STATE_DIRECTORY, 'run.json'))).mode & 0o777, 0o600); + for (const name of ['approved-build.json', 'build.json', 'build-event.json']) + await assert.rejects(lstat(join(env.STATE_DIRECTORY, name)), { code: 'ENOENT' }); + assert.deepEqual(core.outputs, []); + assert.deepEqual(core.exported, {}); + await runCommand('cleanup', env, core, { fetcher: control.fetcher }); + assert.equal(control.calls.filter(({ init }) => init.method === 'DELETE').length, 1); + } finally { + await rm(base, { recursive: true, force: true }); + } +}); + +test('handoff requires the validated source Build record and exact source-state counts', async () => { + const base = await mkdtemp(join(tmpdir(), 'approved-source-state-')); + const env = envFor(join(base, 'state')); + const core = coreHarness(); + const control = controlHarness(syntheticRun('a')); + try { + await runCommand('prepare', env, core, { fetcher: control.fetcher }); + await assert.rejects(runCommand('handoff-build', env, core, { fetcher: control.fetcher })); + await record(env, 'build', buildOutputs(), core, { fetcher: control.fetcher }); + for (const change of [ + (state) => { + state.counts.builds = 2; + }, + (state) => { + state.counts.deployments = 1; + }, + (state) => { + state.faultCounters['createBuild:'] = 0; + }, + (state) => { + state.faultCounters['createDeployment:d1'] = 1; + }, + (state) => { + state.faultCounters['createDeployment:d2'] = 1; + }, + (state) => { + state.faultCounters['createBuild:'] = -1; + }, + (state) => { + state.faultCounters['createDeployment:d2'] = -1; + }, + (state) => { + state.faultCounters['createBuild:'] = '1'; + }, + (state) => { + state.faultCounters['createBuild:other'] = Number.MAX_SAFE_INTEGER; + }, + ]) { + control.state.counts = { builds: 1, deployments: 0 }; + control.state.faultCounters = { 'createBuild:': 1, 'createDeployment:d1': 0 }; + change(control.state); + const count = core.outputs.length; + await assert.rejects(runCommand('handoff-build', env, core, { fetcher: control.fetcher })); + assert.equal(core.outputs.length, count); + } + await writeFile(join(env.STATE_DIRECTORY, 'initial.json'), '{}', { mode: 0o600 }); + await assert.rejects(runCommand('handoff-build', env, core, { fetcher: control.fetcher })); + } finally { + await runCommand('cleanup', env, core, { fetcher: control.fetcher }); + await rm(base, { recursive: true, force: true }); + } +}); + +test('wrong source or mapped projection cannot produce deployment inputs', async () => { + await withApproved(async ({ env, core, control }) => { + for (const value of [ + { sourceBuildCode: 'wrong', buildCode: fixtureBuildCode }, + { sourceBuildCode: '20261114.8', buildCode: fixtureBuildCode }, + { sourceBuildCode, buildCode: 'approved-20261114-8' }, + ]) { + await writeFile(join(env.STATE_DIRECTORY, 'approved-build.json'), JSON.stringify(value), { + mode: 0o600, + }); + const count = core.outputs.length; + await assert.rejects( + runCommand('deploy-inputs', { ...env, PHASE: 'initial' }, core, { + fetcher: control.fetcher, + }), + ); + assert.equal(core.outputs.length, count); + } + }); +}); + +test('approved runs forbid build records and stale/follow-up phases', async () => { + await withApproved(async ({ env, core, control }) => { + await assert.rejects(record(env, 'build', buildOutputs(), core, { fetcher: control.fetcher })); + await assert.rejects(lstat(join(env.STATE_DIRECTORY, 'build.json')), { code: 'ENOENT' }); + await assert.rejects(lstat(join(env.STATE_DIRECTORY, 'build-event.json')), { code: 'ENOENT' }); + for (const phase of ['followup', 'final']) + await assert.rejects( + runCommand('deploy-inputs', { ...env, PHASE: phase }, core, { fetcher: control.fetcher }), + ); + for (const phase of ['build', 'followup', 'final']) { + const path = join(env.STATE_DIRECTORY, `${phase}.json`); + await writeFile(path, '{}', { mode: 0o600 }); + await assert.rejects( + runCommand('deploy-inputs', { ...env, PHASE: 'initial' }, core, { + fetcher: control.fetcher, + }), + ); + await rm(path); + } + }); +}); + +test('approved Deploy records must match the mapped fixture and real producer outcome', async () => { + await withApproved(async ({ env, core, control }) => { + for (const outputs of [deployOutputs(sourceBuildCode), deployOutputs('approved-20261114-99')]) { + await assert.rejects(record(env, 'initial', outputs, core, { fetcher: control.fetcher })); + await assert.rejects(lstat(join(env.STATE_DIRECTORY, 'initial.json')), { code: 'ENOENT' }); + } + const outputs = deployOutputs(); + await assert.rejects( + runCommand( + 'record', + { + ...env, + PHASE: 'initial', + OUTPUTS_JSON: JSON.stringify(outputs), + ACTION_OUTCOME: 'failure', + }, + core, + { fetcher: control.fetcher }, + ), + ); + await assert.rejects( + runCommand('assert-approved-deployment', env, core, { + fetcher: control.fetcher, + client: clientHarness(), + }), + ); + }); +}); + +test('approved final assertion rejects changed counts and mismatched authoritative deployment detail', async () => { + await withApproved(async ({ env, core, control }) => { + await record(env, 'initial', deployOutputs(), core, { fetcher: control.fetcher }); + for (const change of [ + (state) => { + state.counts.builds = 2; + }, + (state) => { + state.counts.deployments = 0; + }, + (state) => { + state.faultCounters['createBuild:'] = 1; + }, + (state) => { + state.faultCounters['createDeployment:d1'] = 2; + }, + (state) => { + state.faultCounters['createDeployment:d2'] = 1; + }, + (state) => { + state.faultCounters = { 'createDeployment:d2': 1 }; + }, + (state) => { + state.faultCounters['createDeployment:'] = 1; + }, + (state) => { + state.faultCounters = { 'createDeployment:': 1 }; + }, + (state) => { + state.faultCounters['createBuild:unexpected'] = 1; + }, + (state) => { + state.faultCounters['createBuild:'] = -1; + }, + (state) => { + state.faultCounters['createDeployment:d2'] = -1; + }, + (state) => { + state.faultCounters['createDeployment:d2'] = '0'; + }, + (state) => { + state.faultCounters['createDeployment:d2'] = 0.5; + }, + ]) { + control.state.counts = { builds: 1, deployments: 1 }; + control.state.faultCounters = { 'createBuild:': 0, 'createDeployment:d1': 1 }; + change(control.state); + const client = clientHarness(); + await assert.rejects( + runCommand('assert-approved-deployment', env, core, { fetcher: control.fetcher, client }), + ); + assert.equal(client.reads.length, 0); + } + control.state.counts = { builds: 1, deployments: 1 }; + control.state.faultCounters = { 'createDeployment:d1': 1 }; + for (const detail of [ + { buildCode: sourceBuildCode, status: 'DEPLOYED' }, + { buildCode: fixtureBuildCode, status: 'DEPLOYING' }, + ]) + await assert.rejects( + runCommand('assert-approved-deployment', env, core, { + fetcher: control.fetcher, + client: clientHarness(detail), + }), + ); + await runCommand('assert-approved-deployment', env, core, { + fetcher: control.fetcher, + client: clientHarness(), + }); + }); +}); + +test('approved commands fail without a handoff/projection and never invent a Build record', async () => { + const base = await mkdtemp(join(tmpdir(), 'approved-no-handoff-')); + const env = envFor(join(base, 'state')); + const core = coreHarness(); + const control = controlHarness(syntheticRun('a')); + try { + await runCommand('prepare', env, core, { fetcher: control.fetcher }); + await assert.rejects( + runCommand('deploy-inputs', { ...env, PHASE: 'initial' }, core, { fetcher: control.fetcher }), + ); + await assert.rejects( + runCommand('assert-approved-deployment', env, core, { + fetcher: control.fetcher, + client: clientHarness(), + }), + ); + await assert.rejects(lstat(join(env.STATE_DIRECTORY, 'build.json')), { code: 'ENOENT' }); + assert.equal(control.calls.filter(({ url }) => url.endsWith('/cleanup-fixture')).length, 0); + } finally { + await runCommand('cleanup', env, core, { fetcher: control.fetcher }); + await rm(base, { recursive: true, force: true }); + } +}); diff --git a/tests/cleanup-runtime.test.mjs b/tests/cleanup-runtime.test.mjs new file mode 100644 index 0000000..183847e --- /dev/null +++ b/tests/cleanup-runtime.test.mjs @@ -0,0 +1,526 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; +import { lstat, mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { createRequire } from 'node:module'; +import { + createBuildCleanupEvent, + parseNotificationEventJson, +} from '@commercekit-tools/notification-contract'; +import { + cleanupScenarioId, + getCleanupExpectations, + getCleanupFixture, + getScenario, + makePlan, +} from '../scripts/scenarios.mjs'; +import { + assertCleanupRecord, + assertLiveAuthorization, + controlRequest, + origin, + runCommand, + subscription, +} from '../scripts/runtime.mjs'; + +const metadata = createRequire(import.meta.url)( + '@commercekit-tools/notification-contract/package.json', +); + +const now = Date.parse('2026-11-14T00:00:00.000Z'); +const run = { + runId: `run_${'c'.repeat(32)}`, + controlToken: 'synthetic-cleanup-control', + credentials: { + clientId: 'synthetic-cleanup-client', + clientSecret: 'synthetic-cleanup-secret', + resource: 'urn:synthetic-cleanup-resource', + tokenUrl: `${origin}/oauth2/token`, + }, +}; +const envFor = (directory) => ({ + STATE_DIRECTORY: directory, + SCENARIO: cleanupScenarioId, + PROVIDER: 'none', + CONFIRMATION: 'RUN-COMMERCEKIT-SANDBOX-TESTS', + GITHUB_EVENT_NAME: 'workflow_dispatch', + GITHUB_REPOSITORY: 'commercekit-tools/action-integration-tests', + GITHUB_REF: 'refs/heads/main', +}); +function coreHarness() { + const outputs = {}; + const exported = {}; + const masked = []; + const logs = []; + return { + outputs, + exported, + masked, + logs, + setOutput: (name, value) => { + outputs[name] = value; + }, + exportVariable: (name, value) => { + exported[name] = value; + }, + setSecret: (value) => { + masked.push(value); + }, + info: (message) => { + logs.push(message); + }, + summary: { + addRaw: (message) => ({ + write: async () => { + logs.push(message); + }, + }), + }, + }; +} +function observedState() { + return { + counts: { builds: 105, deployments: 3, resources: 106, events: 2 }, + faultCounters: { + 'issueToken:': 2, + 'getBuilds:': 8, + 'getDeployments:': 2, + 'getEnvironments:': 2, + 'getDatabackups:': 6, + }, + }; +} +function producerRecord() { + // Independent accepted-output fixture, not the retention implementation under test. + const reasons = new Map([ + [0, 'deployed'], + [1, 'snapshot-or-backup-reference'], + [2, 'active-build'], + [3, 'active-build'], + [4, 'already-marked-for-deletion'], + [5, 'retained-age'], + [6, 'explicitly-excluded'], + [7, 'active-deployment-reference'], + [8, 'active-deployment-reference'], + [10, 'missing-timestamp'], + ]); + const protectedIndexes = new Set([4, 5, 10, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104]); + const result = { + schemaVersion: 1, + runStartedAt: new Date(now).toISOString(), + durationMs: 1000, + status: 'blocked', + dryRun: true, + scope: { subscriptionCode: subscription, applicationCode: 'commerce' }, + policy: { retentionDays: 30, keepLatest: 10, maxDeletions: 20 }, + completeness: { inventory: true, protection: false, eligibility: false }, + counts: { + scanned: 105, + eligible: 0, + planned: 0, + deletionRequested: 0, + skipped: 105, + failed: 0, + unknown: 0, + protected: 13, + deferred: 0, + }, + decisions: Array.from({ length: 105 }, (_, index) => ({ + code: `cleanup-${String(index).padStart(3, '0')}`, + applicationCode: 'commerce', + reasons: [ + ...(reasons.has(index) ? [reasons.get(index)] : []), + ...(index >= 95 ? ['retained-latest'] : []), + 'eligibility-unverified', + ], + disposition: protectedIndexes.has(index) ? 'protected' : 'blocked', + })), + truncation: { omittedDecisions: 0 }, + }; + const event = createBuildCleanupEvent({ + status: 'failure', + occurredAt: result.runStartedAt, + env: { + GITHUB_REPOSITORY: 'commercekit-tools/action-integration-tests', + GITHUB_REF: 'refs/heads/main', + }, + data: { + mode: 'dry-run', + subscriptionCode: subscription, + applicationCode: 'commerce', + retentionDays: 30, + keepLatest: 10, + cleanupStatus: 'blocked', + durationMs: 1000, + scannedCount: 105, + eligibleCount: 0, + plannedCount: 0, + deletionRequestedCount: 0, + skippedCount: 105, + failedCount: 0, + unknownCount: 0, + deferredCount: 0, + }, + }); + const outputs = { + 'result-json': JSON.stringify(result), + 'notification-event': JSON.stringify(event), + 'cleanup-status': 'blocked', + 'dry-run': 'true', + 'duration-ms': '1000', + 'scanned-count': '105', + 'eligible-count': '0', + 'planned-count': '0', + 'deletion-requested-count': '0', + 'skipped-count': '105', + 'failed-count': '0', + 'unknown-count': '0', + }; + return { result, event, outputs, outcome: 'success', run, state: observedState() }; +} +function fakeControl(calls, { seedFailure = false, state = observedState() } = {}) { + return async (url, init) => { + calls.push({ url, init }); + assert.equal(new URL(url).origin, origin); + assert.equal(init.redirect, 'error'); + const path = new URL(url).pathname; + if (init.method === 'POST') return Response.json(run, { status: 201 }); + assert.equal(init.headers.Authorization, `Bearer ${run.controlToken}`); + if (init.method === 'PUT') { + if (path.endsWith('/cleanup-fixture')) { + assert.equal(JSON.parse(init.body).builds.length, 105); + if (seedFailure) return Response.json({}, { status: 500 }); + } + return Response.json({}); + } + if (path.endsWith('/state')) return Response.json(state); + if (init.method === 'DELETE') return new Response(null, { status: 204 }); + return Response.json({}, { status: 404 }); + }; +} + +test('cleanup catalog is isolated, multipage, mixed and leaves existing suites unchanged', () => { + const fixture = getCleanupFixture(now); + assert.equal(getScenario(cleanupScenarioId).cleanup, true); + assert.equal(makePlan('full').include.length, 16); + assert(!makePlan('full').include.some(({ scenario }) => scenario === cleanupScenarioId)); + assert.equal(fixture.builds.length, 105); + assert.equal(new Set(fixture.builds.map(({ code }) => code)).size, 105); + assert.equal(fixture.builds[0].response.deployed, true); + assert.equal(fixture.builds[1].response.hasSnapshot, true); + assert.equal(fixture.builds[2].response.status, 'BUILDING'); + assert.equal(fixture.builds[3].response.status, 'UNKNOWN'); + assert.equal(fixture.builds[4].response.status, 'DELETED'); + assert.equal(fixture.builds[9].response.status, 'FAIL'); + assert(!Object.hasOwn(fixture.builds[10].response, 'buildEndTimestamp')); + assert(!Object.hasOwn(fixture.builds[11].response, 'hasSnapshot')); + assert.equal(Date.parse(fixture.builds[13].modifiedAt), now - 3600000); + assert(Date.parse(fixture.builds[13].response.buildEndTimestamp) < now - 30 * 86400000); + assert.equal( + fixture.builds[103].response.buildStartTimestamp, + fixture.builds[104].response.buildStartTimestamp, + ); + assert.deepEqual( + fixture.deployments.map(({ response }) => response.status), + ['SCHEDULED', 'DEPLOYED', 'FAIL'], + ); + assert.equal(getCleanupExpectations().counts.protected, 13); + fixture.builds[0].response.status = 'unsafe alteration'; + assert.equal(getCleanupFixture(now).builds[0].response.status, 'SUCCESS'); + assert.throws(() => getCleanupFixture(NaN)); +}); + +test('cleanup producer uses actual published shared factory/parser with accurate blocked dry-run counts', () => { + assert.equal(metadata.version, '0.0.4'); + const record = producerRecord(); + const actual = assertCleanupRecord(record); + assert.equal(actual.targetApiMutationCount, 0); + assert.equal(actual.event.eventType, 'ccv2.build-cleanup.completed'); + assert.equal(actual.result.counts.scanned, 105); + assert.equal(actual.result.counts.skipped, 105); + assert.equal(parseNotificationEventJson(record.outputs['notification-event']).status, 'failure'); +}); + +test('shared lifecycle seeds only isolated control plane, validates repeat output, masks secrets and cleans private state', async () => { + const base = await mkdtemp(join(tmpdir(), 'cleanup-integration-')); + const env = envFor(join(base, 'state')); + const core = coreHarness(); + const calls = []; + const fetcher = fakeControl(calls); + try { + await runCommand('prepare', env, core, { fetcher, now: () => now }); + assert.equal((await lstat(env.STATE_DIRECTORY)).mode & 0o777, 0o700); + assert.equal((await lstat(join(env.STATE_DIRECTORY, 'run.json'))).mode & 0o777, 0o600); + assert.equal(core.exported.CCV2_CLIENT_SECRET, run.credentials.clientSecret); + for (const secret of [run.controlToken, ...Object.values(run.credentials)]) + assert(core.masked.includes(secret)); + assert(calls.some(({ url }) => url.endsWith('/cleanup-fixture'))); + for (const attempt of ['first', 'repeat']) { + const record = producerRecord(); + await runCommand( + 'record-cleanup', + { + ...env, + CLEANUP_ATTEMPT: attempt, + OUTPUTS_JSON: JSON.stringify(record.outputs), + ACTION_OUTCOME: record.outcome, + }, + core, + { fetcher }, + ); + assert.equal( + (await lstat(join(env.STATE_DIRECTORY, `${attempt}-cleanup.json`))).mode & 0o777, + 0o600, + ); + } + await runCommand('assert-cleanup', env, core, { fetcher }); + assert(core.logs.some((message) => message.includes('zero target API mutations'))); + assert.equal(calls.filter(({ init }) => init.method === 'POST').length, 1); + assert.equal(calls.filter(({ init }) => init.method === 'PUT').length, 2); + assert(calls.every(({ url }) => new URL(url).pathname.startsWith('/sandbox/v1/runs'))); + for (const secret of [run.controlToken, ...Object.values(run.credentials)]) + assert(!core.logs.join('\n').includes(secret)); + await runCommand('cleanup', env, core, { fetcher }); + await assert.rejects(lstat(env.STATE_DIRECTORY), { code: 'ENOENT' }); + await runCommand('cleanup', env, core, { fetcher }); + assert.equal(calls.filter(({ init }) => init.method === 'DELETE').length, 1); + } finally { + await rm(base, { recursive: true, force: true }); + } +}); + +test('new fixture seed failure retains private cleanup identity and never exports credentials', async () => { + const base = await mkdtemp(join(tmpdir(), 'cleanup-partial-')); + const env = envFor(join(base, 'state')); + const core = coreHarness(); + const calls = []; + const fetcher = fakeControl(calls, { seedFailure: true }); + try { + await assert.rejects(runCommand('prepare', env, core, { fetcher })); + assert.equal((await lstat(join(env.STATE_DIRECTORY, 'run.json'))).mode & 0o777, 0o600); + assert.deepEqual(core.exported, {}); + await runCommand('cleanup', env, core, { fetcher }); + assert(calls.some(({ init }) => init.method === 'DELETE')); + } finally { + await rm(base, { recursive: true, force: true }); + } +}); + +test('cleanup live guard rejects invalid context and providers before creating fixtures', async () => { + const base = await mkdtemp(join(tmpdir(), 'cleanup-guard-')); + const env = envFor(join(base, 'state')); + try { + for (const patch of [ + { CONFIRMATION: '' }, + { GITHUB_EVENT_NAME: 'schedule' }, + { GITHUB_REPOSITORY: 'someone/fork' }, + { GITHUB_REF: 'refs/heads/feature' }, + { + PROVIDER: 'slack', + PROVIDER_CONFIRMATION: 'SEND-COMMERCEKIT-TEST-NOTIFICATION', + NOTIFICATION_WEBHOOK: 'synthetic-webhook', + }, + ]) { + assert.throws(() => assertLiveAuthorization({ ...env, ...patch })); + let called = false; + await assert.rejects( + runCommand('prepare', { ...env, ...patch }, coreHarness(), { + fetcher: async () => { + called = true; + throw Error('Network prohibited'); + }, + }), + ); + assert.equal(called, false); + } + } finally { + await rm(base, { recursive: true, force: true }); + } +}); + +test('cleanup output validation rejects apply, failure, incorrect scope, counts, reasons and truncation', () => { + const resultChanges = [ + (result) => { + result.dryRun = false; + }, + (result) => { + result.status = 'success'; + }, + (result) => { + result.completeness.eligibility = true; + }, + (result) => { + result.scope.applicationCode = 'different'; + }, + (result) => { + result.counts.deletionRequested = 1; + }, + (result) => { + result.durationMs = -1; + }, + (result) => { + result.decisions[0].reasons = ['eligibility-unverified']; + }, + (result) => { + result.decisions[9].reasons.push('active-deployment-reference'); + }, + (result) => { + result.decisions[13].reasons = []; + }, + (result) => { + result.decisions[14].reasons.push('unverified-unexpected-reason'); + }, + (result) => { + result.decisions[14].reasons.push('eligibility-unverified'); + }, + (result) => { + result.decisions.pop(); + }, + (result) => { + result.truncation.omittedDecisions = 1; + }, + (result) => { + result.leaked = run.credentials.clientSecret; + }, + ]; + for (const change of resultChanges) { + const record = producerRecord(); + change(record.result); + record.outputs['result-json'] = JSON.stringify(record.result); + assert.throws(() => assertCleanupRecord(record)); + } + for (const patch of [{ outcome: 'failure' }, { outputs: {} }]) + assert.throws(() => assertCleanupRecord({ ...producerRecord(), ...patch })); + const wrongCounter = producerRecord(); + wrongCounter.outputs['scanned-count'] = '104'; + assert.throws(() => assertCleanupRecord(wrongCounter)); +}); + +test('cleanup notifications reject malformed, mismatched, leaking and oversized data', () => { + for (const change of [ + (event) => { + event.data.scannedCount = 104; + }, + (event) => { + event.data.mode = 'apply'; + }, + (event) => { + event.context.ref = 'refs/heads/feature'; + }, + (event) => { + event.data.error = { code: 'synthetic', message: run.controlToken }; + }, + ]) { + const record = producerRecord(); + change(record.event); + record.outputs['notification-event'] = JSON.stringify(record.event); + assert.throws(() => assertCleanupRecord(record)); + } + for (const value of ['', '{}', 'x'.repeat(65537)]) { + const record = producerRecord(); + record.outputs['notification-event'] = value; + assert.throws(() => assertCleanupRecord(record)); + } +}); + +test('target mutation counters are checked separately from fixture/control events and read pagination', () => { + for (const patch of [ + { 'deleteBuild:cleanup-014': 1 }, + { 'createBuild:': 1 }, + { 'createDeployment:': 1 }, + { 'unexpectedMutation:': 1 }, + { 'getBuilds:': 3 }, + { 'getBuilds:': -1 }, + { 'getBuilds:': 4.5 }, + ]) { + const record = producerRecord(); + Object.assign(record.state.faultCounters, patch); + assert.throws(() => assertCleanupRecord(record)); + } + const record = producerRecord(); + record.state.counts.events = 23; // Control-plane events are not target mutations. + assert.doesNotThrow(() => assertCleanupRecord(record)); + record.state.counts.builds = 104; + assert.throws(() => assertCleanupRecord(record)); +}); + +test('missing or failed records cannot pass final assertions; duplicate first record cannot overwrite', async () => { + const base = await mkdtemp(join(tmpdir(), 'cleanup-record-')); + const env = envFor(join(base, 'state')); + const core = coreHarness(); + const calls = []; + const fetcher = fakeControl(calls); + try { + await runCommand('prepare', env, core, { fetcher }); + await assert.rejects(runCommand('assert-cleanup', env, core, { fetcher })); + const record = producerRecord(); + const recordEnv = { + ...env, + CLEANUP_ATTEMPT: 'repeat', + OUTPUTS_JSON: JSON.stringify(record.outputs), + ACTION_OUTCOME: 'success', + }; + await assert.rejects(runCommand('record-cleanup', recordEnv, core, { fetcher })); + await assert.rejects(lstat(join(env.STATE_DIRECTORY, 'repeat-cleanup.json')), { + code: 'ENOENT', + }); + await assert.rejects( + runCommand('record-cleanup', { ...recordEnv, CLEANUP_ATTEMPT: '../escape' }, core, { + fetcher, + }), + ); + await assert.rejects( + runCommand( + 'record-cleanup', + { ...recordEnv, CLEANUP_ATTEMPT: 'first', ACTION_OUTCOME: 'failure' }, + core, + { fetcher }, + ), + ); + await assert.rejects(lstat(join(env.STATE_DIRECTORY, 'first-cleanup.json')), { + code: 'ENOENT', + }); + await runCommand('record-cleanup', { ...recordEnv, CLEANUP_ATTEMPT: 'first' }, core, { + fetcher, + }); + const first = await readFile(join(env.STATE_DIRECTORY, 'first-cleanup.json'), 'utf8'); + await assert.rejects( + runCommand('record-cleanup', { ...recordEnv, CLEANUP_ATTEMPT: 'first' }, core, { fetcher }), + { code: 'EEXIST' }, + ); + assert.equal(await readFile(join(env.STATE_DIRECTORY, 'first-cleanup.json'), 'utf8'), first); + await assert.rejects(runCommand('prepare', env, core, { fetcher }), { code: 'EEXIST' }); + assert.equal(calls.filter(({ init }) => init.method === 'POST').length, 1); + await runCommand('cleanup', env, core, { fetcher }); + } finally { + await rm(base, { recursive: true, force: true }); + } +}); + +test('cleanup control whitelist permits only the supported run-scoped fixture path', async () => { + let calls = 0; + await controlRequest(`/sandbox/v1/runs/${run.runId}/cleanup-fixture`, { + method: 'PUT', + token: run.controlToken, + body: getCleanupFixture(now), + fetcher: async () => { + calls += 1; + return Response.json({}); + }, + }); + assert.equal(calls, 1); + for (const path of [ + '/sandbox/v1/runs/../cleanup-fixture', + `/sandbox/v1/runs/${run.runId}/cleanup-fixture/extra`, + '/v2/subscriptions/escape/builds', + `https://unsafe.invalid/sandbox/v1/runs/${run.runId}/cleanup-fixture`, + ]) + await assert.rejects( + controlRequest(path, { + fetcher: async () => { + throw Error('Must not fetch'); + }, + }), + ); +}); diff --git a/tests/runtime.test.mjs b/tests/runtime.test.mjs index 55ae94e..6a628ae 100644 --- a/tests/runtime.test.mjs +++ b/tests/runtime.test.mjs @@ -165,7 +165,7 @@ function fakeControl(id, calls, extra = {}) { builds: id === 'build-create-error' ? 0 : 1, deployments: scenario.deploy && id !== 'deploy-create-error' ? 1 : 0, }, - faultCounters: { 'createBuild:': 1, 'createDeployment:': 1 }, + faultCounters: { 'createBuild:': 1, 'createDeployment:d1': 1 }, }); return Response.json({ error: 'deleted' }, { status: 404 }); }; diff --git a/tests/workflow-policy.test.mjs b/tests/workflow-policy.test.mjs index 267c1d8..6b1920e 100644 --- a/tests/workflow-policy.test.mjs +++ b/tests/workflow-policy.test.mjs @@ -63,3 +63,96 @@ test('automatic live runs, missing cleanup and disabled final assertions are rej ]) assert.throws(() => validatePolicy(mutation('.github/workflows/_scenario.yml', change))); }); + +test('cleanup stays manual, dry-run, fixed to Sandbox and always cleaned', () => { + for (const change of [ + (doc) => { + doc.on.schedule = [{ cron: '17 3 * * 0' }]; + }, + (doc) => { + doc.on.workflow_dispatch.inputs['dry-run'] = { type: 'boolean', default: false }; + }, + (doc) => { + doc.jobs.cleanup.if = 'true'; + }, + (doc) => { + doc.jobs.cleanup.steps.at(-1).if = 'success()'; + }, + (doc) => { + doc.jobs.cleanup.env.PROVIDER = 'slack'; + }, + (doc) => { + doc.jobs.cleanup.steps = doc.jobs.cleanup.steps.filter( + (step) => step.run !== 'node scripts/runner.mjs assert-cleanup', + ); + }, + ]) + assert.throws(() => validatePolicy(mutation('.github/workflows/cleanup.yml', change))); + for (const change of [ + (doc) => { + doc.runs.steps[0].with['dry-run'] = 'false'; + }, + (doc) => { + doc.runs.steps[0].with['api-base-url'] = 'https://invalid.example.test'; + }, + (doc) => { + doc.runs.steps[0].with['max-deletions'] = '100'; + }, + (doc) => { + doc.runs.steps.at(-1).if = 'success()'; + }, + ]) + assert.throws(() => validatePolicy(mutation('.github/actions/cleanup/action.yml', change))); +}); + +test('approved deploy requires ordered checks, a protected environment and public-code-only handoff', () => { + for (const change of [ + (doc) => { + doc.on.push = { branches: ['main'] }; + }, + (doc) => { + doc.jobs['repository-build'].if = 'true'; + }, + (doc) => { + doc.jobs['commerce-check'].needs = 'repository-build-typo'; + }, + (doc) => { + doc.jobs['cloud-build'].needs = 'repository-build'; + }, + (doc) => { + doc.jobs.deploy.needs = 'commerce-check'; + }, + (doc) => { + delete doc.jobs.deploy.environment; + }, + (doc) => { + doc.jobs.deploy.environment = 'sandbox-e2e'; + }, + (doc) => { + doc.jobs['cloud-build'].outputs.credentials = '${{ steps.prepare.outputs.credentials }}'; + }, + (doc) => { + doc.jobs.deploy.steps.find((step) => step.id === 'prepare').env.BUILT_BUILD_CODE = + '${{ inputs.build-code }}'; + }, + (doc) => { + doc.jobs.deploy.steps.at(-1).if = 'success()'; + }, + (doc) => { + doc.jobs['cloud-build'].steps.at(-1).if = 'success()'; + }, + (doc) => { + doc.jobs.deploy.steps = doc.jobs.deploy.steps.filter( + (step) => step.run !== 'node scripts/approval.mjs verify-environment', + ); + }, + (doc) => { + doc.jobs['commerce-check'].steps.find((step) => + step.uses?.startsWith('commercekit-tools/setup-commercekit@'), + ).with.version = 'latest'; + }, + ]) + assert.throws(() => + validatePolicy(mutation('.github/workflows/build-approve-deploy.yml', change)), + ); +});