From fd7e8c7b3640aeb7caad11aa9d72d2ca22a05971 Mon Sep 17 00:00:00 2001 From: Garry Tan Date: Wed, 25 Nov 2026 16:09:24 -0500 Subject: [PATCH] Remove the /cso test files, CI workflows and docs ahead of removing /cso (GST-3920) (#4837) Deletes the tests, test fixtures, CI workflows, scripts and docs that exist only for /cso. Nothing changes for anyone using gstack. Why: this is the first half of removing /cso. The whole removal is too big to review in one pull request, so #4833 removes the skill and its helper code next. Nothing to do: #4833 lands right after this one. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- .github/workflows/cso-runtime-images.yml | 376 ----- .github/workflows/cso-runtime-promote.yml | 187 --- .../workflows/cso-runtime-qualification.yml | 162 -- .github/workflows/cso-scanner-images.yml | 375 ----- .github/workflows/free-tests.yml | 122 +- changelog.d/remove-cso-tests.md | 3 + docs/TEST_PORTFOLIO.md | 4 +- docs/cso-release-qualification.md | 392 ----- docs/cso-scanners.md | 123 -- docs/standalone-binaries.md | 16 - lib/docs-only.ts | 1 - package.json | 3 - scripts/cso-attestation-evidence.ts | 29 - scripts/cso-eval.ts | 984 ------------ scripts/cso-native-evidence.ts | 131 -- scripts/cso-public-ghcr.ts | 262 ---- scripts/cso-sbom-packages-check.jq | 7 - scripts/cso-sbom-packages.jq | 8 - scripts/cso-scanner-catalog.ts | 173 --- scripts/cso-scanner-matrix.ts | 134 -- scripts/cso-staging-run.ts | 124 -- scripts/cso-verify-runtime-base.ts | 117 -- scripts/free-test-durations-windows.json | 27 - scripts/free-test-durations.json | 62 - .../scripts/test-pr-profile.ts.json | 2 +- scripts/lib/windows-curation.ts | 35 - scripts/test-pr-profile.ts | 4 - scripts/typecheck-test-baseline.json | 8 - test/build-cso-nonfatal.test.ts | 76 - test/build-cso-result-record.test.ts | 129 -- test/ci-history-read.test.ts | 2 - test/cso-audit-paths.test.ts | 348 ----- test/cso-bounded-file.test.ts | 17 - test/cso-cache.test.ts | 280 ---- test/cso-cli-lifecycle.test.ts | 96 -- test/cso-cli-recheck.test.ts | 54 - test/cso-cli.test.ts | 216 --- test/cso-contracts.test.ts | 327 ---- test/cso-distribution.test.ts | 758 --------- test/cso-docker-argv0.test.ts | 173 --- test/cso-docker-integration.test.ts | 96 -- test/cso-docker-mounts.test.ts | 205 --- test/cso-docker-policy.test.ts | 29 - test/cso-docker-socket-realpath.test.ts | 118 -- test/cso-e2e-report-contract.test.ts | 68 - test/cso-eval.test.ts | 1371 ----------------- test/cso-file-ceiling.test.ts | 276 ---- test/cso-git-global-config.test.ts | 56 - test/cso-git-hardening.test.ts | 169 -- test/cso-history.test.ts | 64 - test/cso-image-provisioning.test.ts | 175 --- test/cso-json-redaction.test.ts | 141 -- test/cso-launcher-generation.test.ts | 53 - test/cso-lease-identity.test.ts | 332 ---- test/cso-macos-launcher.test.ts | 83 - test/cso-native-evidence.test.ts | 103 -- test/cso-node-lifecycle-integration.test.ts | 324 ---- test/cso-ntfs-fixture.test.ts | 78 - test/cso-ordinary-repos.test.ts | 520 ------- test/cso-postgresql-policy.test.ts | 20 - test/cso-preparation-adversarial.test.ts | 228 --- test/cso-preparation-container.test.ts | 96 -- test/cso-preparation-executor.test.ts | 551 ------- test/cso-preparation-java.test.ts | 62 - test/cso-preparation.test.ts | 357 ----- test/cso-preserved.test.ts | 107 -- test/cso-public-ghcr.test.ts | 145 -- test/cso-python-runner-shadow.test.ts | 76 - test/cso-rails-verification.test.ts | 59 - test/cso-recall.test.ts | 194 --- test/cso-registry-socket.test.ts | 122 -- test/cso-runtime-promotion.test.ts | 297 ---- test/cso-scanner-cli.test.ts | 81 - test/cso-scanner-docker-integration.test.ts | 122 -- test/cso-scanner-executor.test.ts | 227 --- test/cso-scanner-release.test.ts | 177 --- test/cso-scanners.test.ts | 440 ------ test/cso-snapshot-disappearance-race.test.ts | 84 - test/cso-snapshot-identity.test.ts | 35 - test/cso-snapshot-state.test.ts | 300 ---- test/cso-spec-taxonomy-alignment.test.ts | 48 - test/cso-stack-cold-integration.test.ts | 202 --- test/cso-staging-run.test.ts | 164 -- test/cso-unreadable-secret-file.test.ts | 111 -- test/cso-verification-cleanup.test.ts | 41 - test/cso-verifier.test.ts | 89 -- test/cso-watchdog.test.ts | 21 - test/cso-windows-build-contract.test.ts | 70 - test/cso-windows-docker.test.ts | 94 -- test/cso-windows-launcher.test.ts | 504 ------ test/cso-witness.test.ts | 117 -- test/docs-only-workflow.test.ts | 2 +- .../cso-e2e/diff-mode-45216872389-sub1.json | 183 --- .../cso-e2e/diff-mode-45216872389-sub2.json | 136 -- test/fixtures/cso-eval/README.md | 301 ---- test/fixtures/cso-eval/manifest.json | 686 --------- test/fixtures/cso-eval/materialize.ts | 383 ----- .../cso-eval/rails-lock-provenance.json | 488 ------ test/fixtures/cso-eval/rails.Gemfile.lock | 210 --- test/fixtures/cso-http-smoke.c | 41 - test/fixtures/cso-sarif/semgrep-1.179.0.sarif | 103 -- test/fixtures/cso-sarif/trivy-0.75.0-fs.sarif | 134 -- .../cso-sarif/trivy-0.75.0-repo-url.sarif | 134 -- test/helpers/cso-eval-oracles.ts | 102 -- test/helpers/cso-ntfs-fixture.ts | 34 - test/helpers/cso-qualified-cli.ts | 51 - test/helpers/free-fixtures-data.ts | 4 - test/retired-skills.test.ts | 25 + test/setup-cso-degrade.test.ts | 147 -- test/setup-cso-windows-probe.test.ts | 73 - test/test-free-shards.test.ts | 16 - test/test-of-test-ratchet.test.ts | 2 - test/workflow-gh-token.test.ts | 4 +- 113 files changed, 47 insertions(+), 19061 deletions(-) delete mode 100644 .github/workflows/cso-runtime-images.yml delete mode 100644 .github/workflows/cso-runtime-promote.yml delete mode 100644 .github/workflows/cso-runtime-qualification.yml delete mode 100644 .github/workflows/cso-scanner-images.yml create mode 100644 changelog.d/remove-cso-tests.md delete mode 100644 docs/cso-release-qualification.md delete mode 100644 docs/cso-scanners.md delete mode 100644 scripts/cso-attestation-evidence.ts delete mode 100644 scripts/cso-eval.ts delete mode 100644 scripts/cso-native-evidence.ts delete mode 100644 scripts/cso-public-ghcr.ts delete mode 100644 scripts/cso-sbom-packages-check.jq delete mode 100644 scripts/cso-sbom-packages.jq delete mode 100644 scripts/cso-scanner-catalog.ts delete mode 100644 scripts/cso-scanner-matrix.ts delete mode 100644 scripts/cso-staging-run.ts delete mode 100644 scripts/cso-verify-runtime-base.ts delete mode 100644 test/build-cso-nonfatal.test.ts delete mode 100644 test/build-cso-result-record.test.ts delete mode 100644 test/cso-audit-paths.test.ts delete mode 100644 test/cso-bounded-file.test.ts delete mode 100644 test/cso-cache.test.ts delete mode 100644 test/cso-cli-lifecycle.test.ts delete mode 100644 test/cso-cli-recheck.test.ts delete mode 100644 test/cso-cli.test.ts delete mode 100644 test/cso-contracts.test.ts delete mode 100644 test/cso-distribution.test.ts delete mode 100644 test/cso-docker-argv0.test.ts delete mode 100644 test/cso-docker-integration.test.ts delete mode 100644 test/cso-docker-mounts.test.ts delete mode 100644 test/cso-docker-policy.test.ts delete mode 100644 test/cso-docker-socket-realpath.test.ts delete mode 100644 test/cso-e2e-report-contract.test.ts delete mode 100644 test/cso-eval.test.ts delete mode 100644 test/cso-file-ceiling.test.ts delete mode 100644 test/cso-git-global-config.test.ts delete mode 100644 test/cso-git-hardening.test.ts delete mode 100644 test/cso-history.test.ts delete mode 100644 test/cso-image-provisioning.test.ts delete mode 100644 test/cso-json-redaction.test.ts delete mode 100644 test/cso-launcher-generation.test.ts delete mode 100644 test/cso-lease-identity.test.ts delete mode 100644 test/cso-macos-launcher.test.ts delete mode 100644 test/cso-native-evidence.test.ts delete mode 100644 test/cso-node-lifecycle-integration.test.ts delete mode 100644 test/cso-ntfs-fixture.test.ts delete mode 100644 test/cso-ordinary-repos.test.ts delete mode 100644 test/cso-postgresql-policy.test.ts delete mode 100644 test/cso-preparation-adversarial.test.ts delete mode 100644 test/cso-preparation-container.test.ts delete mode 100644 test/cso-preparation-executor.test.ts delete mode 100644 test/cso-preparation-java.test.ts delete mode 100644 test/cso-preparation.test.ts delete mode 100644 test/cso-preserved.test.ts delete mode 100644 test/cso-public-ghcr.test.ts delete mode 100644 test/cso-python-runner-shadow.test.ts delete mode 100644 test/cso-rails-verification.test.ts delete mode 100644 test/cso-recall.test.ts delete mode 100644 test/cso-registry-socket.test.ts delete mode 100644 test/cso-runtime-promotion.test.ts delete mode 100644 test/cso-scanner-cli.test.ts delete mode 100644 test/cso-scanner-docker-integration.test.ts delete mode 100644 test/cso-scanner-executor.test.ts delete mode 100644 test/cso-scanner-release.test.ts delete mode 100644 test/cso-scanners.test.ts delete mode 100644 test/cso-snapshot-disappearance-race.test.ts delete mode 100644 test/cso-snapshot-identity.test.ts delete mode 100644 test/cso-snapshot-state.test.ts delete mode 100644 test/cso-spec-taxonomy-alignment.test.ts delete mode 100644 test/cso-stack-cold-integration.test.ts delete mode 100644 test/cso-staging-run.test.ts delete mode 100644 test/cso-unreadable-secret-file.test.ts delete mode 100644 test/cso-verification-cleanup.test.ts delete mode 100644 test/cso-verifier.test.ts delete mode 100644 test/cso-watchdog.test.ts delete mode 100644 test/cso-windows-build-contract.test.ts delete mode 100644 test/cso-windows-docker.test.ts delete mode 100644 test/cso-windows-launcher.test.ts delete mode 100644 test/cso-witness.test.ts delete mode 100644 test/fixtures/cso-e2e/diff-mode-45216872389-sub1.json delete mode 100644 test/fixtures/cso-e2e/diff-mode-45216872389-sub2.json delete mode 100644 test/fixtures/cso-eval/README.md delete mode 100644 test/fixtures/cso-eval/manifest.json delete mode 100644 test/fixtures/cso-eval/materialize.ts delete mode 100644 test/fixtures/cso-eval/rails-lock-provenance.json delete mode 100644 test/fixtures/cso-eval/rails.Gemfile.lock delete mode 100644 test/fixtures/cso-http-smoke.c delete mode 100644 test/fixtures/cso-sarif/semgrep-1.179.0.sarif delete mode 100644 test/fixtures/cso-sarif/trivy-0.75.0-fs.sarif delete mode 100644 test/fixtures/cso-sarif/trivy-0.75.0-repo-url.sarif delete mode 100644 test/helpers/cso-eval-oracles.ts delete mode 100644 test/helpers/cso-ntfs-fixture.ts delete mode 100644 test/helpers/cso-qualified-cli.ts delete mode 100644 test/setup-cso-degrade.test.ts delete mode 100644 test/setup-cso-windows-probe.test.ts diff --git a/.github/workflows/cso-runtime-images.yml b/.github/workflows/cso-runtime-images.yml deleted file mode 100644 index fd9e4d425..000000000 --- a/.github/workflows/cso-runtime-images.yml +++ /dev/null @@ -1,376 +0,0 @@ -name: Stage CSO Runtime Images - -# Pull requests build every reviewed input on its native architecture without -# publishing. The cso-runtime-release environment must require a maintainer -# reviewer and permit deployments from protected main only. Staging digests -# never enter the execution catalog automatically. -on: - pull_request: - paths: - - '.github/workflows/cso-runtime-images.yml' - - 'lib/cso/**' - - 'scripts/cso-image-matrix.ts' - - 'scripts/cso-verify-runtime-base.ts' - - 'scripts/cso-runtime-promotion.ts' - - 'scripts/cso-requalification.ts' - - 'scripts/cso-public-ghcr.ts' - - 'test/cso-*.test.ts' - workflow_dispatch: - -permissions: - contents: read - -concurrency: - group: cso-runtime-images-${{ github.event.pull_request.number || 'release' }} - cancel-in-progress: false - -jobs: - reviewed-inputs: - if: github.event_name == 'pull_request' || (github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch') - runs-on: ubuntu-24.04 - outputs: - matrix: ${{ steps.inputs.outputs.matrix }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 - - name: Validate committed image digests and complete platform matrix - id: inputs - run: | - set -eu - matrix="$(bun run scripts/cso-image-matrix.ts)" - printf 'matrix=%s\n' "$matrix" >> "$GITHUB_OUTPUT" - - name: Record the requalification trigger inputs of this source commit - run: bun run scripts/cso-requalification.ts triggers > requalification.json - - if: github.event_name == 'workflow_dispatch' - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: cso-requalification-triggers - path: requalification.json - if-no-files-found: error - retention-days: 30 - - validate-native: - needs: reviewed-inputs - if: github.event_name == 'pull_request' - strategy: - fail-fast: false - matrix: ${{ fromJSON(needs.reviewed-inputs.outputs.matrix) }} - runs-on: ${{ matrix.runner }} - timeout-minutes: 35 - permissions: - contents: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 - with: - bun-version: 1.4.2 - - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - name: Require native Docker and verify reviewed source manifests - env: - CSO_ARCH: ${{ matrix.arch }} - CSO_PLATFORM: ${{ matrix.platform }} - CSO_STACK: ${{ matrix.stack }} - run: | - set -eu - case "$CSO_ARCH:$(uname -m)" in - amd64:x86_64|arm64:aarch64) ;; - *) echo 'Native architecture mismatch; emulation cannot validate a runtime.' >&2; exit 1 ;; - esac - bun run scripts/cso-verify-runtime-base.ts - - name: Compile native trusted image helpers - run: | - bun build --compile \ - --no-compile-autoload-dotenv \ - --no-compile-autoload-bunfig \ - --no-compile-autoload-tsconfig \ - --no-compile-autoload-package-json \ - lib/cso/verifier.ts --outfile lib/cso/images/gstack-cso-verifier - bun build --compile \ - --no-compile-autoload-dotenv \ - --no-compile-autoload-bunfig \ - --no-compile-autoload-tsconfig \ - --no-compile-autoload-package-json \ - lib/cso/preparation-container.ts --outfile lib/cso/images/gstack-cso-preparation - - name: Build the reviewed runtime without publishing - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 - with: - context: lib/cso/images - file: lib/cso/images/${{ matrix.stack }}.Dockerfile - platforms: ${{ matrix.platform }} - build-args: | - BASE_IMAGE=${{ matrix.baseImage }} - UV_IMAGE=${{ matrix.uvImage }} - tags: localhost/gstack-cso-pr-${{ matrix.stack }}:${{ github.sha }}-${{ matrix.arch }} - load: true - push: false - provenance: false - sbom: false - - name: Check the built image identity and fail-closed entrypoint - env: - CSO_IMAGE: localhost/gstack-cso-pr-${{ matrix.stack }}:${{ github.sha }}-${{ matrix.arch }} - run: | - set -eu - test "$(docker image inspect "$CSO_IMAGE" --format '{{.Config.User}}')" = "10001:10001" - test "$(docker image inspect "$CSO_IMAGE" --format '{{json .Config.Entrypoint}}')" = '["/opt/cso/entrypoint"]' - docker run --rm --pull never --network none --read-only --cap-drop ALL \ - --security-opt no-new-privileges --entrypoint /opt/cso/entrypoint \ - "$CSO_IMAGE" /bin/true - docker image rm "$CSO_IMAGE" - - stage: - needs: reviewed-inputs - if: github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' - environment: cso-runtime-release - strategy: - fail-fast: false - matrix: ${{ fromJSON(needs.reviewed-inputs.outputs.matrix) }} - runs-on: ${{ matrix.runner }} - timeout-minutes: 40 - permissions: - contents: read - packages: write - id-token: write - attestations: write - artifact-metadata: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 - - name: Require the declared native architecture and Docker daemon - env: - CSO_ARCH: ${{ matrix.arch }} - run: | - set -eu - case "$CSO_ARCH:$(uname -m)" in - amd64:x86_64|arm64:aarch64) ;; - *) echo 'Native architecture mismatch; emulation cannot qualify a runtime.' >&2; exit 1 ;; - esac - docker --host unix:///var/run/docker.sock info - - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - name: Verify reviewed source manifests and exact base versions - env: - CSO_PLATFORM: ${{ matrix.platform }} - CSO_STACK: ${{ matrix.stack }} - run: bun run scripts/cso-verify-runtime-base.ts - - name: Compile native trusted HTTP verifier for the runtime image - run: | - bun build --compile \ - --no-compile-autoload-dotenv \ - --no-compile-autoload-bunfig \ - --no-compile-autoload-tsconfig \ - --no-compile-autoload-package-json \ - lib/cso/verifier.ts --outfile lib/cso/images/gstack-cso-verifier - bun build --compile \ - --no-compile-autoload-dotenv \ - --no-compile-autoload-bunfig \ - --no-compile-autoload-tsconfig \ - --no-compile-autoload-package-json \ - lib/cso/preparation-container.ts --outfile lib/cso/images/gstack-cso-preparation - - name: Prepare immutable staging tag - id: image - env: - CSO_STACK: ${{ matrix.stack }} - CSO_ARCH: ${{ matrix.arch }} - run: | - set -eu - image="ghcr.io/${GITHUB_REPOSITORY,,}/cso-staging/$CSO_STACK-$CSO_ARCH" - printf 'name=%s\n' "$image" >> "$GITHUB_OUTPUT" - printf 'tag=%s:%s-%s\n' "$image" "$GITHUB_SHA" "$GITHUB_RUN_ID" >> "$GITHUB_OUTPUT" - - name: Build native staging image with SBOM and provenance - id: build - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 - with: - context: lib/cso/images - file: lib/cso/images/${{ matrix.stack }}.Dockerfile - platforms: ${{ matrix.platform }} - build-args: | - BASE_IMAGE=${{ matrix.baseImage }} - UV_IMAGE=${{ matrix.uvImage }} - tags: ${{ steps.image.outputs.tag }} - push: true - provenance: mode=max - attests: type=sbom,generator=${{ matrix.sbomGeneratorImage }} - - name: Extract the immutable image SBOM - env: - CSO_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - run: | - set -eu - docker buildx imagetools inspect "$CSO_IMAGE" --format '{{ json .SBOM.SPDX }}' > sbom.full.spdx.json - jq -c -f scripts/cso-sbom-packages.jq sbom.full.spdx.json > sbom.spdx.json - jq -e -f scripts/cso-sbom-packages-check.jq sbom.spdx.json >/dev/null - - name: Sign build provenance - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 - with: - subject-name: ${{ steps.image.outputs.name }} - subject-digest: ${{ steps.build.outputs.digest }} - push-to-registry: true - - name: Sign the image SBOM - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 - with: - subject-name: ${{ steps.image.outputs.name }} - subject-digest: ${{ steps.build.outputs.digest }} - sbom-path: sbom.spdx.json - push-to-registry: true - - name: Verify provenance and SBOM signer identities - env: - GH_TOKEN: ${{ github.token }} - CSO_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - run: | - set -eu - signer="https://github.com/$GITHUB_REPOSITORY/.github/workflows/cso-runtime-images.yml@refs/heads/main" - gh attestation verify "oci://$CSO_IMAGE" --repo "$GITHUB_REPOSITORY" --cert-identity "$signer" --source-ref refs/heads/main --source-digest "$GITHUB_SHA" --deny-self-hosted-runners --predicate-type https://slsa.dev/provenance/v1 --format json > provenance-verification.json - gh attestation verify "oci://$CSO_IMAGE" --repo "$GITHUB_REPOSITORY" --cert-identity "$signer" --source-ref refs/heads/main --source-digest "$GITHUB_SHA" --deny-self-hosted-runners --predicate-type https://spdx.dev/Document/v2.3 --format json > sbom-verification.json - - name: Require a public package and anonymously load the exact staged digest - env: - GH_TOKEN: ${{ github.token }} - CSO_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - CSO_PLATFORM: ${{ matrix.platform }} - run: | - set -euo pipefail - bun run scripts/cso-public-ghcr.ts verify \ - --image "$CSO_IMAGE" --platform "$CSO_PLATFORM" \ - --repository "$GITHUB_REPOSITORY" --output public-image.json - - name: Install helper dependencies and compile trusted tools - run: | - bun install --frozen-lockfile --ignore-scripts - bun run build:cso - - name: Exercise containment against the staged digest - env: - GSTACK_CSO_DOCKER_TESTS: "1" - GSTACK_CSO_TEST_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - GSTACK_CSO_TEST_PLATFORM: ${{ matrix.platform }} - GSTACK_CSO_TEST_STACK: ${{ matrix.stack }} - GSTACK_CSO_EXPECTED_VERSIONS: ${{ toJSON(matrix.versions) }} - DOCKER_HOST: unix:///var/run/docker.sock - run: bun test --max-concurrency 1 test/cso-docker-integration.test.ts - - name: Record staging evidence without promoting the catalog - env: - CSO_BUILD_REVISION: ${{ matrix.inputRevision }} - CSO_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - CSO_PLATFORM: ${{ matrix.platform }} - CSO_RUNTIME_ID: ${{ matrix.runtimeId }} - CSO_STACK: ${{ matrix.stack }} - CSO_VERSIONS: ${{ toJSON(matrix.versions) }} - run: | - set -eu - sha256sum public-image.json sbom.spdx.json provenance-verification.json sbom-verification.json > evidence.sha256 - sbom_digest="sha256:$(sha256sum sbom.spdx.json | cut -d ' ' -f 1)" - provenance_digest="sha256:$(sha256sum provenance-verification.json | cut -d ' ' -f 1)" - workflow="https://github.com/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" - jq -n --arg buildRevision "$CSO_BUILD_REVISION" --arg runtimeId "$CSO_RUNTIME_ID" \ - --arg image "$CSO_IMAGE" --arg platform "$CSO_PLATFORM" --arg stack "$CSO_STACK" \ - --arg commit "$GITHUB_SHA" --arg workflow "$workflow" --arg sbom "$sbom_digest" \ - --arg provenance "$provenance_digest" --argjson versions "$CSO_VERSIONS" \ - '{schemaVersion:1,helperAbi:3,state:"staged",buildRevision:$buildRevision,runtimeId:$runtimeId,image:$image,platform:$platform,stack:$stack,versions:$versions,sourceCommit:$commit,workflow:$workflow,sbomDigest:$sbom,provenanceDigest:$provenance,verifiedProvenance:true,qualification:"pending native and private release gates; no automatic promotion"}' > staged-image.json - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: cso-staged-${{ matrix.stack }}-${{ matrix.arch }} - path: | - staged-image.json - public-image.json - sbom.spdx.json - provenance-verification.json - sbom-verification.json - evidence.sha256 - if-no-files-found: error - retention-days: 30 - - qualify-native: - name: qualify-native ${{ matrix.runtimeId }} - needs: [reviewed-inputs, stage] - if: github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' - environment: cso-runtime-release - strategy: - fail-fast: false - matrix: ${{ fromJSON(needs.reviewed-inputs.outputs.matrix) }} - runs-on: ${{ matrix.runner }} - timeout-minutes: 40 - permissions: - contents: read - packages: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: cso-staged-${{ matrix.stack }}-${{ matrix.arch }} - path: staged-application - - if: matrix.stack == 'rails' - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: cso-staged-postgresql-${{ matrix.arch }} - path: staged-postgresql - - name: Require native Docker and anonymously load the signed staged inputs - env: - GH_TOKEN: ${{ github.token }} - CSO_ARCH: ${{ matrix.arch }} - CSO_PLATFORM: ${{ matrix.platform }} - CSO_STACK: ${{ matrix.stack }} - run: | - set -eu - case "$CSO_ARCH:$(uname -m)" in amd64:x86_64|arm64:aarch64) ;; *) exit 1 ;; esac - docker --host unix:///var/run/docker.sock info - (cd staged-application && sha256sum --check evidence.sha256) - if test "$CSO_STACK" = rails; then - (cd staged-postgresql && sha256sum --check evidence.sha256) - fi - app="$(jq -er --arg platform "$CSO_PLATFORM" --arg stack "$CSO_STACK" 'select(.state == "staged" and .platform == $platform and .stack == $stack) | .image' staged-application/staged-image.json)" - bun run scripts/cso-public-ghcr.ts verify \ - --image "$app" --platform "$CSO_PLATFORM" \ - --repository "$GITHUB_REPOSITORY" --output application-public-image.json - printf 'GSTACK_CSO_TEST_IMAGE=%s\n' "$app" >> "$GITHUB_ENV" - printf 'GSTACK_CSO_EXPECTED_VERSIONS=%s\n' "$(jq -c '.versions' staged-application/staged-image.json)" >> "$GITHUB_ENV" - if test "$CSO_STACK" = rails; then - pg="$(jq -er --arg platform "$CSO_PLATFORM" 'select(.state == "staged" and .platform == $platform and .stack == "postgresql") | .image' staged-postgresql/staged-image.json)" - bun run scripts/cso-public-ghcr.ts verify \ - --image "$pg" --platform "$CSO_PLATFORM" \ - --repository "$GITHUB_REPOSITORY" --output postgresql-public-image.json - printf 'GSTACK_CSO_TEST_POSTGRES_IMAGE=%s\n' "$pg" >> "$GITHUB_ENV" - printf 'GSTACK_CSO_TEST_POSTGRES_VERSION=%s\n' "$(jq -er '.versions.postgresql' staged-postgresql/staged-image.json)" >> "$GITHUB_ENV" - fi - - name: Compile trusted helpers and run the matching staged cold-start journey - env: - GSTACK_CSO_DOCKER_TESTS: "1" - GSTACK_CSO_TEST_PLATFORM: ${{ matrix.platform }} - GSTACK_CSO_TEST_STACK: ${{ matrix.stack }} - DOCKER_HOST: unix:///var/run/docker.sock - run: | - set -eu - bun install --frozen-lockfile --ignore-scripts - bun run build:cso - bun run test:cso:docker --reporter=junit --reporter-outfile=native-tests.junit.xml - - name: Derive native gate evidence from the executed test report - env: - CSO_STACK: ${{ matrix.stack }} - CSO_PLATFORM: ${{ matrix.platform }} - run: | - set -eu - bun run scripts/cso-native-evidence.ts --stack "$CSO_STACK" --platform "$CSO_PLATFORM" \ - --junit native-tests.junit.xml --staged staged-application/staged-image.json \ - --output qualification-evidence.json - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: cso-qualification-gates-${{ matrix.stack }}-${{ matrix.arch }} - path: | - qualification-evidence.json - native-tests.junit.xml - if-no-files-found: error - retention-days: 30 diff --git a/.github/workflows/cso-runtime-promote.yml b/.github/workflows/cso-runtime-promote.yml deleted file mode 100644 index 2acac8864..000000000 --- a/.github/workflows/cso-runtime-promote.yml +++ /dev/null @@ -1,187 +0,0 @@ -name: Propose CSO Runtime Catalog Promotion - -# This workflow never deploys a catalog. It converts authenticated -# same-repository qualification artifacts into an attested candidate, verifies -# those exact bytes, and opens a normal source-review PR from a protected job. -# Pushes and PRs made with GITHUB_TOKEN start no workflows, so the job -# dispatches the required free-tests check on the pushed branch head; a -# workflow_dispatch is the documented exception to that rule. -on: - workflow_dispatch: - inputs: - qualification_run_id: - description: Successful protected-main run containing cso-qualified-runtime-statements - required: true - type: string - -permissions: - contents: read - actions: read - -concurrency: - group: cso-runtime-catalog-promotion - cancel-in-progress: false - -jobs: - propose: - if: github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' - runs-on: ubuntu-24.04 - timeout-minutes: 40 - environment: cso-runtime-release - permissions: - contents: write - pull-requests: write - actions: write - packages: read - id-token: write - attestations: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - with: - persist-credentials: true - fetch-depth: 0 - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 - with: - bun-version: 1.4.2 - - name: Authenticate the completed qualification run - env: - GH_TOKEN: ${{ github.token }} - CSO_QUALIFICATION_RUN: ${{ inputs.qualification_run_id }} - run: | - set -euo pipefail - case "$CSO_QUALIFICATION_RUN" in - ''|*[!0-9]*) echo 'qualification_run_id must be numeric' >&2; exit 1 ;; - esac - gh api "repos/$GITHUB_REPOSITORY/actions/runs/$CSO_QUALIFICATION_RUN" > qualification-run.json - jq -e ' - .status == "completed" and .conclusion == "success" and - .head_branch == "main" and .event == "repository_dispatch" and - .path == ".github/workflows/cso-runtime-qualification.yml" and - (.head_sha | test("^[a-f0-9]{40}$")) - ' qualification-run.json - mkdir qualification-evidence - gh run download "$CSO_QUALIFICATION_RUN" --repo "$GITHUB_REPOSITORY" \ - --name cso-qualified-runtime-statements --dir qualification-evidence - - name: Generate a fail-closed catalog candidate - env: - GH_TOKEN: ${{ github.token }} - CSO_QUALIFICATION_RUN: ${{ inputs.qualification_run_id }} - run: | - set -euo pipefail - bun run scripts/cso-runtime-promotion.ts \ - --evidence-root qualification-evidence \ - --output runtime-catalog.candidate.json - source_commit="$(jq -er '.promotion.sourceCommit' runtime-catalog.candidate.json)" - workflow="$(jq -er '.promotion.workflow' runtime-catalog.candidate.json)" - test "$workflow" = "https://github.com/$GITHUB_REPOSITORY/actions/runs/$CSO_QUALIFICATION_RUN" - qualification_head="$(jq -er '.head_sha' qualification-run.json)" - gh api "repos/$GITHUB_REPOSITORY/compare/$source_commit...$qualification_head" > source-ancestry.json - jq -e '.status == "ahead" or .status == "identical"' source-ancestry.json - bun -e ' - import candidate from "./runtime-catalog.candidate.json"; - import {validateRuntimeCatalog} from "./lib/cso/runtime-catalog"; - validateRuntimeCatalog(candidate); - ' - bun run scripts/cso-runtime-promotion.ts validate-transition \ - lib/cso/runtime-catalog.json runtime-catalog.candidate.json - - name: Prove the promotion and catalog contracts before signing - run: | - set -euo pipefail - bun install --frozen-lockfile --ignore-scripts - bun test --max-concurrency 1 test/cso-runtime-promotion.test.ts test/cso-distribution.test.ts - - name: Recheck public visibility and anonymous pulls before promotion - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - mkdir public-image-evidence - jq -c '.runtimes[]' runtime-catalog.candidate.json | while IFS= read -r runtime; do - runtime_id="$(printf '%s' "$runtime" | jq -er '.id | select(test("^[a-z0-9][a-z0-9._-]{0,100}$"))')" - image="$(printf '%s' "$runtime" | jq -er '.image')" - platform="$(printf '%s' "$runtime" | jq -er '.platform | select(. == "linux/amd64" or . == "linux/arm64")')" - bun run scripts/cso-public-ghcr.ts verify \ - --image "$image" --platform "$platform" --repository "$GITHUB_REPOSITORY" \ - --output "public-image-evidence/$runtime_id.json" --remove-after - done - - name: Attest the exact review candidate - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 - with: - subject-path: runtime-catalog.candidate.json - - name: Verify and record the exact candidate attestation - env: - GH_TOKEN: ${{ github.token }} - CSO_QUALIFICATION_RUN: ${{ inputs.qualification_run_id }} - run: | - set -euo pipefail - candidate_sha256="sha256:$(sha256sum runtime-catalog.candidate.json | cut -d ' ' -f 1)" - subject_sha256="${candidate_sha256#sha256:}" - signer="https://github.com/$GITHUB_REPOSITORY/.github/workflows/cso-runtime-promote.yml@refs/heads/main" - verified=0 - for attempt in 1 2 3; do - if gh attestation verify runtime-catalog.candidate.json --repo "$GITHUB_REPOSITORY" \ - --cert-identity "$signer" --source-ref refs/heads/main --source-digest "$GITHUB_SHA" \ - --deny-self-hosted-runners --predicate-type https://slsa.dev/provenance/v1 \ - --format json > candidate-attestation-verification.tmp; then - mv candidate-attestation-verification.tmp candidate-attestation-verification.json - verified=1 - break - fi - rm -f candidate-attestation-verification.tmp - if test "$attempt" -lt 3; then sleep "$((attempt * 5))"; fi - done - test "$verified" -eq 1 - statement_set_digest="$(bun run scripts/cso-attestation-evidence.ts digest \ - candidate-attestation-verification.json https://slsa.dev/provenance/v1 "$subject_sha256")" - test "$candidate_sha256" = "sha256:$(sha256sum runtime-catalog.candidate.json | cut -d ' ' -f 1)" - jq -n --arg candidateSha256 "$candidate_sha256" \ - --arg statementSetDigest "$statement_set_digest" --arg signer "$signer" \ - --arg sourceCommit "$GITHUB_SHA" --arg qualificationRun "$CSO_QUALIFICATION_RUN" \ - '{schemaVersion:1,candidateSha256:$candidateSha256,verifiedStatementSetDigest:$statementSetDigest,signer:$signer,sourceCommit:$sourceCommit,qualificationRun:$qualificationRun}' \ - > candidate-attestation-evidence.json - - name: Commit the exact verified candidate and open its review PR - env: - GH_TOKEN: ${{ github.token }} - CSO_QUALIFICATION_RUN: ${{ inputs.qualification_run_id }} - run: | - set -euo pipefail - expected_candidate_sha256="$(jq -er '.candidateSha256 | select(test("^sha256:[a-f0-9]{64}$"))' candidate-attestation-evidence.json)" - test "$expected_candidate_sha256" = "sha256:$(sha256sum runtime-catalog.candidate.json | cut -d ' ' -f 1)" - bun run scripts/cso-runtime-promotion.ts validate-transition \ - lib/cso/runtime-catalog.json runtime-catalog.candidate.json - cp runtime-catalog.candidate.json lib/cso/runtime-catalog.json - cmp runtime-catalog.candidate.json lib/cso/runtime-catalog.json - bun -e ' - import candidate from "./lib/cso/runtime-catalog.json"; - import {validateRuntimeCatalog} from "./lib/cso/runtime-catalog"; - validateRuntimeCatalog(candidate); - ' - bun run build:cso - branch="cso-runtime-catalog-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" - git switch -c "$branch" - git config user.name github-actions[bot] - git config user.email 41898282+github-actions[bot]@users.noreply.github.com - git add lib/cso/runtime-catalog.json - git commit -m "Promote qualified CSO runtime catalog" - git show HEAD:lib/cso/runtime-catalog.json > committed-runtime-catalog.json - cmp runtime-catalog.candidate.json committed-runtime-catalog.json - test "$expected_candidate_sha256" = "sha256:$(sha256sum committed-runtime-catalog.json | cut -d ' ' -f 1)" - git push --set-upstream origin "$branch" - gh workflow run free-tests.yml --repo "$GITHUB_REPOSITORY" --ref "$branch" - cat > pr-body.md <> "$GITHUB_STEP_SUMMARY" - - qualify: - needs: dispatch-summary - if: github.ref == 'refs/heads/main' && github.event_name == 'repository_dispatch' - runs-on: ubuntu-24.04 - timeout-minutes: 40 - environment: cso-runtime-release - permissions: - contents: read - packages: read - attestations: read - actions: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - with: - persist-credentials: false - fetch-depth: 0 - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 - with: - bun-version: 1.4.2 - - name: Require the configured private-evaluator actor - env: - CSO_QUALIFICATION_ACTOR: ${{ vars.CSO_QUALIFICATION_ACTOR }} - run: | - set -euo pipefail - test -n "$CSO_QUALIFICATION_ACTOR" - test "$GITHUB_ACTOR" = "$CSO_QUALIFICATION_ACTOR" - - name: Recheck public visibility and anonymous pulls for every qualified digest - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - mkdir public-image-evidence - jq -c '.client_payload.statements[]' "$GITHUB_EVENT_PATH" | while IFS= read -r statement; do - runtime_id="$(printf '%s' "$statement" | jq -er '.runtimeId | select(test("^[a-z0-9][a-z0-9._-]{0,100}$"))')" - image="$(printf '%s' "$statement" | jq -er '.image | select(test("^ghcr\\.io/garrytan/gstack/cso-staging/[a-z0-9-]+-(amd64|arm64)@sha256:[a-f0-9]{64}$"))')" - platform="$(printf '%s' "$statement" | jq -er '.platform | select(. == "linux/amd64" or . == "linux/arm64")')" - bun run scripts/cso-public-ghcr.ts verify \ - --image "$image" --platform "$platform" --repository "$GITHUB_REPOSITORY" \ - --output "public-image-evidence/$runtime_id.json" --remove-after - done - - name: Verify each staged image attestation and normalize qualification statements - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - signer="https://github.com/$GITHUB_REPOSITORY/.github/workflows/cso-runtime-images.yml@refs/heads/main" - workflow="https://github.com/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" - qualified_at="$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" - mkdir qualification-evidence - jq -c '.client_payload.statements[]' "$GITHUB_EVENT_PATH" | while IFS= read -r statement; do - runtime_id="$(printf '%s' "$statement" | jq -er '.runtimeId | select(test("^[a-z0-9][a-z0-9._-]{0,100}$"))')" - image="$(printf '%s' "$statement" | jq -er '.image | select(test("^ghcr\\.io/garrytan/gstack/cso-staging/[a-z0-9-]+-(amd64|arm64)@sha256:[a-f0-9]{64}$"))')" - source_commit="$(printf '%s' "$statement" | jq -er '.sourceCommit | select(test("^[a-f0-9]{40}$"))')" - output="qualification-evidence/$runtime_id" - mkdir "$output" - gh attestation verify "oci://$image" --repo "$GITHUB_REPOSITORY" \ - --cert-identity "$signer" --source-ref refs/heads/main --source-digest "$source_commit" \ - --deny-self-hosted-runners --predicate-type https://slsa.dev/provenance/v1 \ - --format json > "$output/provenance-verification.json" - gh attestation verify "oci://$image" --repo "$GITHUB_REPOSITORY" \ - --cert-identity "$signer" --source-ref refs/heads/main --source-digest "$source_commit" \ - --deny-self-hosted-runners --predicate-type https://spdx.dev/Document/v2.3 \ - --format json > "$output/sbom-verification.json" - provenance_digest="sha256:$(sha256sum "$output/provenance-verification.json" | cut -d ' ' -f 1)" - sbom_digest="sha256:$(sha256sum "$output/sbom-verification.json" | cut -d ' ' -f 1)" - printf '%s' "$statement" | jq \ - --arg workflow "$workflow" --arg qualifiedAt "$qualified_at" \ - --arg provenanceDigest "$provenance_digest" --arg sbomDigest "$sbom_digest" \ - '{ - schemaVersion:.schemaVersion,helperAbi:.helperAbi,state:.state, - buildRevision:.buildRevision,runtimeId:.runtimeId,stack:.stack, - platform:.platform,image:.image,versions:.versions,sourceCommit:.sourceCommit, - checks:.checks,workflow:$workflow,qualifiedAt:$qualifiedAt, - provenanceDigest:$provenanceDigest,sbomDigest:$sbomDigest - }' \ - > "$output/qualified-runtime.json" - done - - name: Require one successful protected-main staging run with every native gate passed - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - mkdir staging-run-evidence - run_id="$(bun run scripts/cso-staging-run.ts run-id --repository "$GITHUB_REPOSITORY" \ - qualification-evidence/*/provenance-verification.json)" - gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id" > staging-run-evidence/run.json - gh api --paginate --slurp "repos/$GITHUB_REPOSITORY/actions/runs/$run_id/jobs?filter=latest&per_page=100" \ - > staging-run-evidence/jobs.json - bun run scripts/cso-staging-run.ts verify --repository "$GITHUB_REPOSITORY" --run-id "$run_id" \ - --event "$GITHUB_EVENT_PATH" --run staging-run-evidence/run.json --jobs staging-run-evidence/jobs.json - gh run download "$run_id" --repo "$GITHUB_REPOSITORY" \ - --name cso-requalification-triggers --dir requalification-download - mv requalification-download/requalification.json qualification-evidence/requalification.json - rmdir requalification-download - - name: Enforce the complete release contract before retaining evidence - run: | - set -euo pipefail - bun run scripts/cso-runtime-promotion.ts \ - --evidence-root qualification-evidence \ - --output runtime-catalog.proof.json - rm runtime-catalog.proof.json - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 - with: - name: cso-qualified-runtime-statements - path: | - qualification-evidence - public-image-evidence - staging-run-evidence - if-no-files-found: error - retention-days: 30 diff --git a/.github/workflows/cso-scanner-images.yml b/.github/workflows/cso-scanner-images.yml deleted file mode 100644 index 48b872d38..000000000 --- a/.github/workflows/cso-scanner-images.yml +++ /dev/null @@ -1,375 +0,0 @@ -name: Qualify CSO Scanner Images - -# Branch dispatches may validate reviewed inputs. Only protected main and the -# cso-scanner-release environment may publish or qualify scanner images. An -# explicit promotion input may then propose a catalog. -on: - workflow_dispatch: - inputs: - promote_catalog: - description: Open a reviewed scanner catalog promotion PR after every gate passes - required: false - default: false - type: boolean - -permissions: - contents: read - -concurrency: - group: cso-scanner-images-${{ github.ref }} - cancel-in-progress: false - -jobs: - reviewed-inputs: - runs-on: ubuntu-24.04 - outputs: - matrix: ${{ steps.inputs.outputs.matrix }} - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 - - name: Prove scanner normalization and fail-closed behavior - run: | - set -eu - bun install --frozen-lockfile --ignore-scripts - bun test --max-concurrency 1 test/cso-scanners.test.ts test/cso-scanner-executor.test.ts test/cso-scanner-release.test.ts - - name: Validate complete reviewed scanner inputs - id: inputs - run: | - set -eu - matrix="$(bun run scripts/cso-scanner-matrix.ts)" - printf 'matrix=%s\n' "$matrix" >> "$GITHUB_OUTPUT" - - stage-and-qualify: - needs: reviewed-inputs - if: github.ref == 'refs/heads/main' && github.event_name == 'workflow_dispatch' - environment: cso-scanner-release - strategy: - fail-fast: false - matrix: ${{ fromJSON(needs.reviewed-inputs.outputs.matrix) }} - runs-on: ${{ matrix.runner }} - timeout-minutes: 45 - permissions: - contents: read - packages: write - id-token: write - attestations: write - artifact-metadata: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 - - name: Require native Docker and the declared architecture - env: - CSO_ARCH: ${{ matrix.arch }} - run: | - set -eu - case "$CSO_ARCH:$(uname -m)" in - amd64:x86_64|arm64:aarch64) ;; - *) echo 'Native architecture mismatch; emulation cannot qualify a scanner.' >&2; exit 1 ;; - esac - docker --host unix:///var/run/docker.sock info - - uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 - - uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4 - with: - registry: ghcr.io - username: ${{ github.actor }} - password: ${{ secrets.GITHUB_TOKEN }} - - name: Verify reviewed upstream and SBOM-generator attestations - env: - GH_TOKEN: ${{ github.token }} - CSO_BASE_ATTESTATION: ${{ toJSON(matrix.baseAttestation) }} - CSO_SBOM_GENERATOR: ${{ toJSON(matrix.sbomGenerator) }} - run: | - set -eu - verify_reviewed_image() { - declaration="$1" - label="$2" - printf '%s\n' "$declaration" > "$label-declaration.json" - image="$(jq -r '.image' "$label-declaration.json")" - repository="$(jq -r '.repository' "$label-declaration.json")" - repository="${repository#https://github.com/}" - source_commit="$(jq -r '.sourceCommit' "$label-declaration.json")" - signer_workflow="$(jq -r '.signerWorkflow' "$label-declaration.json")" - signer_digest="$(jq -r '.signerDigest' "$label-declaration.json")" - subject_sha256="${image##*@sha256:}" - gh attestation verify "oci://$image" --repo "$repository" --signer-workflow "$signer_workflow" --signer-digest "$signer_digest" --source-digest "$source_commit" --deny-self-hosted-runners --predicate-type https://slsa.dev/provenance/v1 --format json > "$label-provenance-verification.json" - actual_provenance="$(bun run scripts/cso-attestation-evidence.ts digest "$label-provenance-verification.json" https://slsa.dev/provenance/v1 "$subject_sha256")" - test "$actual_provenance" = "$(jq -r '.provenanceStatementDigest' "$label-declaration.json")" - gh attestation verify "oci://$image" --repo "$repository" --signer-workflow "$signer_workflow" --signer-digest "$signer_digest" --source-digest "$source_commit" --deny-self-hosted-runners --predicate-type https://spdx.dev/Document/v2.3 --format json > "$label-sbom-verification.json" - actual_sbom="$(bun run scripts/cso-attestation-evidence.ts digest "$label-sbom-verification.json" https://spdx.dev/Document/v2.3 "$subject_sha256")" - test "$actual_sbom" = "$(jq -r '.sbomStatementDigest' "$label-declaration.json")" - } - verify_reviewed_image "$CSO_BASE_ATTESTATION" upstream-base - verify_reviewed_image "$CSO_SBOM_GENERATOR" sbom-generator - - name: Compile the trusted loopback assertion verifier - run: | - bun build --compile \ - --no-compile-autoload-dotenv \ - --no-compile-autoload-bunfig \ - --no-compile-autoload-tsconfig \ - --no-compile-autoload-package-json \ - lib/cso/verifier.ts --outfile lib/cso/images/gstack-cso-verifier - - name: Choose the immutable scanner repository - id: image - env: - CSO_SCANNER: ${{ matrix.scanner }} - CSO_ARCH: ${{ matrix.arch }} - run: | - set -eu - name="ghcr.io/${GITHUB_REPOSITORY,,}/cso-scanners/$CSO_SCANNER-$CSO_ARCH" - printf 'name=%s\n' "$name" >> "$GITHUB_OUTPUT" - printf 'tag=%s:%s-%s\n' "$name" "$GITHUB_SHA" "$GITHUB_RUN_ID" >> "$GITHUB_OUTPUT" - - name: Build native scanner wrapper with SBOM and provenance - id: build - uses: docker/build-push-action@c3c9e263c25d99ce0380d002d59b67737d91b0dc # v7.4.0 - with: - context: lib/cso - file: lib/cso/scanner-images/scanner.Dockerfile - platforms: ${{ matrix.platform }} - build-args: | - BASE_IMAGE=${{ matrix.baseImage }} - SCANNER_EXECUTABLE=${{ matrix.scannerExecutable }} - tags: ${{ steps.image.outputs.tag }} - push: true - provenance: mode=max - attests: type=sbom,generator=${{ matrix.sbomGenerator.image }} - - name: Extract and validate the wrapper SBOM - env: - CSO_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - run: | - set -eu - docker buildx imagetools inspect "$CSO_IMAGE" --format '{{ json .SBOM.SPDX }}' > sbom.full.spdx.json - jq -c -f scripts/cso-sbom-packages.jq sbom.full.spdx.json > sbom.spdx.json - jq -e -f scripts/cso-sbom-packages-check.jq sbom.spdx.json >/dev/null - - name: Sign build provenance - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 - with: - subject-name: ${{ steps.image.outputs.name }} - subject-digest: ${{ steps.build.outputs.digest }} - push-to-registry: true - - name: Sign the image SBOM - uses: actions/attest@1e69f48acb82d1966a394da916b4c1698aa569d6 # v4.2.2 - with: - subject-name: ${{ steps.image.outputs.name }} - subject-digest: ${{ steps.build.outputs.digest }} - sbom-path: sbom.spdx.json - push-to-registry: true - - name: Verify branch-bound provenance and SBOM identities - env: - GH_TOKEN: ${{ github.token }} - CSO_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - run: | - set -eu - signer="https://github.com/$GITHUB_REPOSITORY/.github/workflows/cso-scanner-images.yml@$GITHUB_REF" - gh attestation verify "oci://$CSO_IMAGE" --repo "$GITHUB_REPOSITORY" --cert-identity "$signer" --source-ref "$GITHUB_REF" --source-digest "$GITHUB_SHA" --deny-self-hosted-runners --predicate-type https://slsa.dev/provenance/v1 --format json > provenance-verification.json - gh attestation verify "oci://$CSO_IMAGE" --repo "$GITHUB_REPOSITORY" --cert-identity "$signer" --source-ref "$GITHUB_REF" --source-digest "$GITHUB_SHA" --deny-self-hosted-runners --predicate-type https://spdx.dev/Document/v2.3 --format json > sbom-verification.json - - name: Require a public package and anonymously load the verified immutable image - env: - GH_TOKEN: ${{ github.token }} - CSO_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - CSO_PLATFORM: ${{ matrix.platform }} - run: | - set -euo pipefail - bun run scripts/cso-public-ghcr.ts verify \ - --image "$CSO_IMAGE" --platform "$CSO_PLATFORM" \ - --repository "$GITHUB_REPOSITORY" --output public-image.json - - name: Recompute immutable rule or database content - env: - CSO_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - CSO_ASSETS: ${{ toJSON(matrix.assets) }} - run: | - set -eu - printf '%s\n' "$CSO_ASSETS" > declared-assets.json - asset_path="$(jq -r '.semgrepRules.path // .advisoryDatabase.path // empty' declared-assets.json)" - expected="$(jq -r '.semgrepRules.sha256 // .advisoryDatabase.contentSha256 // empty' declared-assets.json)" - if test -n "$asset_path"; then - case "$asset_path" in /policy/catalog/*|/opt/cso/scanner-data/*) ;; *) exit 1 ;; esac - container="$(docker --host unix:///var/run/docker.sock create --pull=never "$CSO_IMAGE" /bin/true)" - trap 'docker --host unix:///var/run/docker.sock rm --force "$container" >/dev/null 2>&1 || true' EXIT - docker --host unix:///var/run/docker.sock cp "$container:$asset_path" scanner-asset - actual="$(bun run scripts/cso-scanner-catalog.ts hash-asset scanner-asset)" - test "$actual" = "$expected" - docker --host unix:///var/run/docker.sock rm --force "$container" >/dev/null - trap - EXIT - else - test "$CSO_ASSETS" = null - fi - - name: Compile the helper and bind the staged profile - env: - CSO_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - CSO_SCANNER: ${{ matrix.scanner }} - CSO_PLATFORM: ${{ matrix.platform }} - CSO_VERSION: ${{ matrix.version }} - CSO_CAPABILITIES: ${{ toJSON(matrix.capabilities) }} - CSO_ASSETS: ${{ toJSON(matrix.assets) }} - CSO_APPLICATION_EXECUTABLE: ${{ matrix.applicationExecutable }} - run: | - set -eu - bun install --frozen-lockfile --ignore-scripts - bun run build:cso - policy_hash="$(bun -e "import {ISOLATION_POLICY_HASH} from './lib/cso/docker'; process.stdout.write(ISOLATION_POLICY_HASH)")" - jq -n --arg scanner "$CSO_SCANNER" --arg image "$CSO_IMAGE" --arg platform "$CSO_PLATFORM" --arg version "$CSO_VERSION" --arg policy "$policy_hash" --arg app "$CSO_APPLICATION_EXECUTABLE" --argjson capabilities "$CSO_CAPABILITIES" --argjson assets "$CSO_ASSETS" '{scanner:$scanner,image:$image,platform:$platform,version:$version,isolationPolicyHash:$policy,capabilities:$capabilities,assets:$assets,applicationExecutable:$app}' > staged-profile.json - - name: Exercise common containment and the real scanner adapter - env: - GSTACK_CSO_DOCKER_TESTS: "1" - GSTACK_CSO_SCANNER_DOCKER_TESTS: "1" - GSTACK_CSO_SCANNER_PROFILE: ${{ github.workspace }}/staged-profile.json - GSTACK_CSO_SCANNER_VERSION_HASH: ${{ github.workspace }}/version.sha256 - DOCKER_HOST: unix:///var/run/docker.sock - run: | - set -eu - bun test --max-concurrency 1 test/cso-docker-integration.test.ts - bun test --max-concurrency 1 test/cso-scanner-docker-integration.test.ts - - name: Emit one immutable qualified profile - env: - CSO_IMAGE: ${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }} - CSO_SCANNER: ${{ matrix.scanner }} - CSO_ARCH: ${{ matrix.arch }} - CSO_PLATFORM: ${{ matrix.platform }} - CSO_VERSION: ${{ matrix.version }} - CSO_CAPABILITIES: ${{ toJSON(matrix.capabilities) }} - CSO_ASSETS: ${{ toJSON(matrix.assets) }} - CSO_UPSTREAM: ${{ toJSON(matrix.baseAttestation) }} - CSO_SBOM_GENERATOR: ${{ toJSON(matrix.sbomGenerator) }} - run: | - set -eu - policy_hash="$(jq -r '.isolationPolicyHash' staged-profile.json)" - version_hash="$(cat version.sha256)" - sbom_digest="sha256:$(sha256sum sbom.spdx.json | cut -d' ' -f1)" - provenance_digest="sha256:$(sha256sum provenance-verification.json | cut -d' ' -f1)" - qualified_at="$(date -u +%Y-%m-%dT%H:%M:%S.000Z)" - workflow="https://github.com/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" - version_id="$(printf '%s' "$CSO_VERSION" | tr '[:upper:]+' '[:lower:]-' | tr -cd 'a-z0-9._-')" - profile_id="$CSO_SCANNER-$version_id-$CSO_ARCH" - output="$CSO_SCANNER-$CSO_ARCH.json" - jq -n --arg id "$profile_id" --arg scanner "$CSO_SCANNER" --arg platform "$CSO_PLATFORM" --arg image "$CSO_IMAGE" --arg version "$CSO_VERSION" --arg versionHash "$version_hash" --arg policy "$policy_hash" --arg qualifiedAt "$qualified_at" --arg sourceCommit "$GITHUB_SHA" --arg workflow "$workflow" --arg sbomDigest "$sbom_digest" --arg provenanceDigest "$provenance_digest" --argjson capabilities "$CSO_CAPABILITIES" --argjson assets "$CSO_ASSETS" '{id:$id,scanner:$scanner,state:"qualified",platform:$platform,image:$image,entrypoint:"/opt/cso/entrypoint",executable:"/opt/cso/bin/scanner",version:$version,versionOutputSha256:$versionHash,helperAbi:3,isolationPolicyHash:$policy,capabilities:$capabilities} + (if $assets == null then {} else {assets:$assets} end) + {qualifiedAt:$qualifiedAt,qualification:{sourceCommit:$sourceCommit,workflow:$workflow,sbomDigest:$sbomDigest,provenanceDigest:$provenanceDigest,verifiedProvenance:true,containmentPassed:true,adapterContractPassed:true,offlineAssetsPassed:true}}' > "$output" - printf '%s\n' "$CSO_UPSTREAM" > upstream-evidence.json - printf '%s\n' "$CSO_SBOM_GENERATOR" > sbom-generator-evidence.json - sha256sum "$output" staged-profile.json version.sha256 declared-assets.json public-image.json sbom.spdx.json provenance-verification.json sbom-verification.json upstream-evidence.json sbom-generator-evidence.json upstream-base-*-verification.json sbom-generator-*-verification.json > evidence.sha256 - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: cso-scanner-profile-${{ matrix.scanner }}-${{ matrix.arch }} - path: | - ${{ matrix.scanner }}-${{ matrix.arch }}.json - staged-profile.json - version.sha256 - declared-assets.json - public-image.json - sbom.spdx.json - provenance-verification.json - sbom-verification.json - upstream-evidence.json - sbom-generator-evidence.json - upstream-base-declaration.json - upstream-base-provenance-verification.json - upstream-base-sbom-verification.json - sbom-generator-declaration.json - sbom-generator-provenance-verification.json - sbom-generator-sbom-verification.json - evidence.sha256 - if-no-files-found: error - retention-days: 30 - - catalog-proposal: - needs: [reviewed-inputs, stage-and-qualify] - runs-on: ubuntu-24.04 - permissions: - contents: read - actions: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - pattern: cso-scanner-profile-* - path: qualified-artifacts - - name: Assemble and validate the complete catalog proposal - run: | - set -eu - mkdir qualified-fragments - find qualified-artifacts -mindepth 2 -maxdepth 2 -type f \( -name '*-amd64.json' -o -name '*-arm64.json' \) | sort | while IFS= read -r file; do cp "$file" qualified-fragments/; done - test "$(find qualified-fragments -type f -name '*.json' | wc -l | tr -d ' ')" -eq 12 - revision="cso-scanners-$(printf '%s' "$GITHUB_SHA" | cut -c1-12)-$GITHUB_RUN_ID" - workflow="https://github.com/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID" - image_prefix="ghcr.io/${GITHUB_REPOSITORY,,}/cso-scanners/" - bun run scripts/cso-scanner-catalog.ts assemble qualified-fragments lib/cso/scanner-images/catalog.json catalog-proposal.json --revision "$revision" --source-commit "$GITHUB_SHA" --workflow "$workflow" --image-prefix "$image_prefix" - bun run scripts/cso-scanner-catalog.ts validate catalog-proposal.json - - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: cso-scanner-catalog-proposal - path: catalog-proposal.json - if-no-files-found: error - retention-days: 30 - - promote-catalog: - needs: catalog-proposal - if: github.ref == 'refs/heads/main' && inputs.promote_catalog == true - environment: cso-scanner-release - runs-on: ubuntu-24.04 - permissions: - contents: write - pull-requests: write - actions: write - packages: read - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - ref: main - persist-credentials: true - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 - - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8 - with: - name: cso-scanner-catalog-proposal - path: promotion - - name: Recheck public visibility and anonymous pulls before promotion - env: - GH_TOKEN: ${{ github.token }} - run: | - set -euo pipefail - mkdir public-image-evidence - jq -c '.scanners[]' promotion/catalog-proposal.json | while IFS= read -r profile; do - profile_id="$(printf '%s' "$profile" | jq -er '.id | select(test("^[a-z0-9][a-z0-9._-]{0,100}$"))')" - image="$(printf '%s' "$profile" | jq -er '.image')" - platform="$(printf '%s' "$profile" | jq -er '.platform | select(. == "linux/amd64" or . == "linux/arm64")')" - bun run scripts/cso-public-ghcr.ts verify \ - --image "$image" --platform "$platform" --repository "$GITHUB_REPOSITORY" \ - --output "public-image-evidence/$profile_id.json" --remove-after - done - - name: Revalidate and open the reviewable source catalog PR - env: - GH_TOKEN: ${{ github.token }} - run: | - set -eu - bun run scripts/cso-scanner-catalog.ts validate promotion/catalog-proposal.json - bun run scripts/cso-scanner-catalog.ts validate-transition lib/cso/scanner-images/catalog.json promotion/catalog-proposal.json - cp promotion/catalog-proposal.json lib/cso/scanner-images/catalog.json - bun install --frozen-lockfile --ignore-scripts - bun test test/cso-scanners.test.ts test/cso-scanner-executor.test.ts test/cso-scanner-release.test.ts - bun run build:cso - branch="cso-scanner-catalog-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT" - git switch -c "$branch" - git config user.name github-actions[bot] - git config user.email 41898282+github-actions[bot]@users.noreply.github.com - git add lib/cso/scanner-images/catalog.json - git commit -m "Promote qualified CSO scanner catalog" - git push --set-upstream origin "$branch" - gh workflow run free-tests.yml --repo "$GITHUB_REPOSITORY" --ref "$branch" - cat > pr-body.md <<'EOF' - Promotes the complete scanner catalog produced by native amd64/arm64 qualification for all six CSO scanners. Each profile binds its immutable image, exact version-output hash, offline asset hash when required, containment and adapter gates, SBOM, provenance, source commit, and workflow run. - - Validation: scanner catalog contract tests and compiled CSO helper build. - EOF - gh pr create --base main --head "$branch" --title "Promote qualified CSO scanner catalog" --body-file pr-body.md diff --git a/.github/workflows/free-tests.yml b/.github/workflows/free-tests.yml index 861e69d96..7a96c642b 100644 --- a/.github/workflows/free-tests.yml +++ b/.github/workflows/free-tests.yml @@ -273,52 +273,19 @@ jobs: path: ${{ runner.temp }}/free-plan.json if-no-files-found: error - cso-macos-launcher: - needs: [reuse, docs-scope] - if: ${{ !cancelled() && (needs.reuse.result != 'success' || needs.reuse.outputs.reused != 'true') && !(needs.docs-scope.result == 'success' && needs.docs-scope.outputs.docs_only == 'true') }} - runs-on: macos-latest - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 - - name: Install helper dependencies - run: bun install --frozen-lockfile --ignore-scripts - - name: Build and sign the native macOS startup boundary - run: bun run build:cso - - name: Exercise hardened-runtime startup and environment scrubbing - run: bun run test:cso:macos - env: - GSTACK_CSO_MACOS_TESTS: "1" - - name: Build browser lifecycle prerequisites - env: - GSTACK_STRICT_BUILD: '1' - run: | - bunx playwright install chromium - bun run build - - name: Exercise native agent ownership and linked settings - env: - TMPDIR: /tmp - run: | - files=(browse/test/terminal-agent-lifecycle.test.ts browse/test/terminal-agent-native-observation.test.ts browse/test/terminal-agent-watchdog.test.ts browse/test/server-embedder-terminal-port.test.ts browse/test/server-factory.test.ts test/gstack-settings-hook-symlink.test.ts test/gstack-settings-hook-schema-aware.test.ts) - for file in "${files[@]}"; do test -f "$file"; done - bun test "${files[@]}" - # Named regressions that only reproduce on macOS's default temp root: # $TMPDIR sits under /var/folders and /var is a symlink to /private/var, so # code that compares a realpath with an unresolved path passes on Linux's # /tmp and fails here (#2982). TMPDIR is deliberately left at the runner's # default, and the job fails if that layout is not symlinked. It also sources - # the Codex probe from zsh, macOS's default shell (#3024; no paid call), and - # runs ubi-runner under macOS's bsdtar and one-true-awk (#3680, #3679). + # the Codex probe from zsh, macOS's default shell (#3024; no paid call), runs + # ubi-runner under macOS's bsdtar and one-true-awk (#3680, #3679), and runs + # the native terminal-agent ownership and linked-settings tests. macos-named-regressions: needs: [reuse, docs-scope] if: ${{ !cancelled() && (needs.reuse.result != 'success' || needs.reuse.outputs.reused != 'true') && !(needs.docs-scope.result == 'success' && needs.docs-scope.outputs.docs_only == 'true') }} runs-on: macos-latest - timeout-minutes: 20 + timeout-minutes: 25 steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: @@ -329,8 +296,6 @@ jobs: - name: Install dependencies run: bun install --frozen-lockfile --ignore-scripts - name: Build browser prerequisites - env: - GSTACK_STRICT_BUILD: '1' run: | bunx playwright install chromium bun run build @@ -356,71 +321,16 @@ jobs: resolved="$(realpath "$tmp")" echo "temp root: $tmp -> $resolved" test "$resolved" != "${tmp%/}" - files=(test/gstack-design-detect.test.ts browse/test/chromium-profile-isolation.test.ts test/cso-git-hardening.test.ts test/plan-count-file-permission.test.ts test/spec-quality-gate-secret-sink.test.ts test/gstack-memory-ingest.test.ts test/regression-issue3024-zsh-sourced-helpers.test.ts test/codex-probe-subcommands.test.ts browse/test/proxy-env-daemon.test.ts browse/test/proxy-direct-launch-args.test.ts test/regression-issue3680-ubicloud-bsd-userland.test.ts) + files=(test/gstack-design-detect.test.ts browse/test/chromium-profile-isolation.test.ts test/plan-count-file-permission.test.ts test/spec-quality-gate-secret-sink.test.ts test/gstack-memory-ingest.test.ts test/regression-issue3024-zsh-sourced-helpers.test.ts test/codex-probe-subcommands.test.ts browse/test/proxy-env-daemon.test.ts browse/test/proxy-direct-launch-args.test.ts test/regression-issue3680-ubicloud-bsd-userland.test.ts) for file in "${files[@]}"; do test -f "$file"; done bun test --timeout=30000 "${files[@]}" - - cso-windows-launcher: - needs: [reuse, docs-scope] - if: ${{ !cancelled() && (needs.reuse.result != 'success' || needs.reuse.outputs.reused != 'true') && !(needs.docs-scope.result == 'success' && needs.docs-scope.outputs.docs_only == 'true') }} - runs-on: windows-latest - timeout-minutes: 15 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 - - name: Install helper dependencies - run: bun install --frozen-lockfile --ignore-scripts - - name: Build the native Windows startup boundary from Git Bash - shell: bash - run: bun run build:cso - - name: Exercise native startup, environment, and argument forwarding - run: bun run test:cso:windows + - name: Exercise native agent ownership and linked settings env: - GSTACK_CSO_WINDOWS_TESTS: "1" - - name: Upload #2894 lease diagnostics - if: failure() - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 - with: - name: cso-lease-diagnostics-a${{ github.run_attempt }} - path: ${{ runner.temp }}/cso-lease-diagnostics - if-no-files-found: ignore - retention-days: 14 - - cso-docker-integration: - needs: [reuse, docs-scope] - if: ${{ !cancelled() && (needs.reuse.result != 'success' || needs.reuse.outputs.reused != 'true') && !(needs.docs-scope.result == 'success' && needs.docs-scope.outputs.docs_only == 'true') }} - runs-on: ubuntu-24.04 - timeout-minutes: 20 - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 - with: - persist-credentials: false - - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 - with: - bun-version: 1.4.2 - - name: Require local Docker containment prerequisites - # A missing daemon is a failed gate, never a skipped integration test. + TMPDIR: /tmp run: | - command -v docker - docker --host unix:///var/run/docker.sock info - command -v cc - - name: Install helper dependencies - run: bun install --frozen-lockfile --ignore-scripts - - name: Compile trusted CSO helper and watchdog - run: bun run build:cso - # Only the file that can run here: the node-lifecycle and stack-cold - # files need GSTACK_CSO_TEST_STACK images and run in the CSO runtime - # workflows (test:cso:docker), so in this job they always skipped. - - name: Run CSO Docker integration gate - run: | - bun test --max-concurrency 1 test/cso-docker-integration.test.ts - env: - GSTACK_CSO_DOCKER_TESTS: "1" - DOCKER_HOST: unix:///var/run/docker.sock + files=(browse/test/terminal-agent-lifecycle.test.ts browse/test/terminal-agent-native-observation.test.ts browse/test/terminal-agent-watchdog.test.ts browse/test/server-embedder-terminal-port.test.ts browse/test/server-factory.test.ts test/gstack-settings-hook-symlink.test.ts test/gstack-settings-hook-schema-aware.test.ts) + for file in "${files[@]}"; do test -f "$file"; done + bun test "${files[@]}" typecheck: needs: [reuse, docs-scope] @@ -905,14 +815,14 @@ jobs: if-no-files-found: ignore # Branch protection already requires the `free-tests` context. Keep that - # stable name as an always-running aggregate so every platform-specific CSO + # stable name as an always-running aggregate so every platform-specific # gate is merge-blocking without a separate branch-protection migration. # Its first step picks one of two exclusive paths before any download: a # verified reuse (main pushes and pull requests) links the reused run and passes; anything # else takes the strict path below unchanged, which alone uploads tested-tree. free-tests: if: always() - needs: [reuse, docs-scope, docs-lane, free-suite, typecheck, quick-bun-default, cso-macos-launcher, macos-named-regressions, cso-windows-launcher, cso-docker-integration] + needs: [reuse, docs-scope, docs-lane, free-suite, typecheck, quick-bun-default, macos-named-regressions] runs-on: ubuntu-24.04 timeout-minutes: 5 steps: @@ -952,25 +862,19 @@ jobs: echo "Reused $REUSE_RUN_URL, which passed on tree $REUSE_TREE; this push ran no suite of its own." >> "$GITHUB_STEP_SUMMARY" echo 'reused=true' >> "$GITHUB_OUTPUT" echo 'skip=true' >> "$GITHUB_OUTPUT" - - name: Require the free suite, typecheck, the quick tier on the default Bun, macOS regressions, and every CSO platform gate + - name: Require the free suite, typecheck, the quick tier on the default Bun, and the macOS regressions if: steps.route.outputs.skip != 'true' env: FREE_SUITE_RESULT: ${{ needs.free-suite.result }} TYPECHECK_RESULT: ${{ needs.typecheck.result }} QUICK_BUN_DEFAULT_RESULT: ${{ needs.quick-bun-default.result }} - CSO_MACOS_RESULT: ${{ needs.cso-macos-launcher.result }} MACOS_REGRESSIONS_RESULT: ${{ needs.macos-named-regressions.result }} - CSO_WINDOWS_RESULT: ${{ needs.cso-windows-launcher.result }} - CSO_DOCKER_RESULT: ${{ needs.cso-docker-integration.result }} run: | set -eu test "$FREE_SUITE_RESULT" = success test "$TYPECHECK_RESULT" = success test "$QUICK_BUN_DEFAULT_RESULT" = success - test "$CSO_MACOS_RESULT" = success test "$MACOS_REGRESSIONS_RESULT" = success - test "$CSO_WINDOWS_RESULT" = success - test "$CSO_DOCKER_RESULT" = success - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 if: steps.route.outputs.skip != 'true' with: diff --git a/changelog.d/remove-cso-tests.md b/changelog.d/remove-cso-tests.md new file mode 100644 index 000000000..9b656504d --- /dev/null +++ b/changelog.d/remove-cso-tests.md @@ -0,0 +1,3 @@ +### Removed + +- **The /cso tests, CI jobs and docs pages are gone, ahead of /cso itself.** The tests, test fixtures, CI workflows, scripts and docs that exist only for the /cso skill are removed, along with the `bun run test:cso:docker`, `test:cso:macos` and `test:cso:windows` scripts. The /cso skill still works until the next change removes it. Nothing changes for anyone using gstack. diff --git a/docs/TEST_PORTFOLIO.md b/docs/TEST_PORTFOLIO.md index d5de31d9b..d11a0cf69 100644 --- a/docs/TEST_PORTFOLIO.md +++ b/docs/TEST_PORTFOLIO.md @@ -225,8 +225,8 @@ test/eng-test-plan-edit-approval.test.ts The quoted-frame selector was folded into `test/plan-count-file-permission.test.ts` in the 2026-09 audit. -The publication/watchdog pair is `test/autoplan-publication-guard.test.ts` and -`test/cso-watchdog.test.ts`. The live pair is +The publication/watchdog pair was `test/autoplan-publication-guard.test.ts` and +a watchdog test since deleted with the skill it covered. The live pair is `test/skill-e2e-auq-consistency.test.ts` and `test/skill-e2e-auq-verbose-vs-carved-ab.test.ts`, using the default three consistency samples plus the two A/B captures. diff --git a/docs/cso-release-qualification.md b/docs/cso-release-qualification.md deleted file mode 100644 index e8efdbc84..000000000 --- a/docs/cso-release-qualification.md +++ /dev/null @@ -1,392 +0,0 @@ -# Building and qualifying CSO runtimes - -`bun run build:cso` compiles the trusted launcher, helper, and independent -watchdog. Bun must support all four `--no-compile-autoload-*` switches. macOS and -Linux also require a C compiler (`cc`, Clang, or GCC). Linux links the launcher -statically; macOS signs it with the hardened runtime. `bun run build` includes -this step and remains a strict release/developer build. Setup feature-probes the -four Bun switches and the host native toolchain before building. If either is -unavailable, it builds the rest of gstack, removes any stale CSO helpers, and -reports `/cso` unavailable; the skill then reports `not assessed` and never -substitutes repository tooling. Re-run setup after installing the prerequisite. -When the probe succeeds, setup keeps the strict failure behavior and checks the -artifacts for freshness. The generated -`bin/gstack-cso-launcher` is the setup-built direct command; the compiled core -is not the entrypoint. The core's direct-invocation marker catches accidental -misuse; it does not authenticate a process against the trusted same-user host. -The native launcher is the pre-runtime boundary that strips Bun, Node, and -loader injection variables. CSO is not exposed as an npm package bin: its native -launcher, compiled core, watchdog, and hidden `.gstack-cso-generation` manifest -must be built and installed together for the current host. Windows also requires -the empty `.gstack-cso-generation.lock` file from that same publication. Windows -builds the native launcher with Visual Studio 2022 Build Tools (Desktop -development with C++), discovered from Git Bash through the installed Developer -PowerShell script; only the core is compiled with Bun. -The dedicated Windows CI job checks startup, argument forwarding, and runtime -injection separately from static audit and private-state support. POSIX -watchdog execution remains unavailable there. - -Both catalogs are qualified. The scanner catalog -(`lib/cso/scanner-images/catalog.json`) lists twelve scanner images: six -scanners, each on linux/amd64 and linux/arm64. The runtime catalog -(`lib/cso/runtime-catalog.json`) lists ten runtime images: Node, Bun, Python, -Rails and PostgreSQL, each on both platforms. The private evaluator qualified -them, and `cso-runtime-promote.yml` promoted them (described below). - -Every successful fresh install or upgrade asks the trusted launcher to preload -the current host platform's qualified runtime and scanner images. This is the -only automatic image acquisition path. It first validates the committed -catalogs, pins a local Unix-socket Docker endpoint, rejects remote TCP/SSH -contexts, and uses a new empty Docker configuration so pulls are anonymous. -Only fully qualified `registry/repository@sha256:...` catalog entries are -requested. Missing Docker or public registry access is a visible, nonfatal -prerequisite: static audits remain available and a later `./setup` retries. -The preload stage reserves 30 seconds for endpoint admission and gives each -declared image a separate 30-second inspection/download window. Set -`GSTACK_CSO_IMAGE_PULL_TIMEOUT_SECONDS=120` when registry speed requires a -longer per-image window (accepted range: 5–300 seconds). The helper derives an aggregate deadline from the -catalog size and caps the complete stage at one hour. A per-image timeout leaves -that digest unavailable and continues with the next entry; reaching the hard -aggregate deadline stops all remaining work. When a registry prerequisite stops -further downloads, setup still checks later catalog entries locally and reports -every already-present digest. A later setup resumes from exact local digests. -Application, verifier, and scanner execution still use `--pull=never` with no -egress. `gstack-cso doctor --repo PATH` never downloads; it reports a qualified -profile unavailable until that exact digest and platform are already present -in the local daemon. - -The ordinary free suite exercises contracts without requiring Docker. The free -lane's `cso-docker-integration` job sets `GSTACK_CSO_DOCKER_TESTS=1` and runs -`test/cso-docker-integration.test.ts`; unavailable Docker or missing containment -prerequisites fail that job. The node-lifecycle and stack-cold files need a -staged stack image, so they run in the CSO runtime workflows through -`test:cso:docker`. Run all three locally with a working local daemon: - -```bash -bun run build:cso -GSTACK_CSO_DOCKER_TESTS=1 bun run test:cso:docker -``` - -When the staged-image workflow supplies `GSTACK_CSO_TEST_IMAGE`, platform, -stack, and exact tool versions, the same command also runs stack-specific -qualification journeys. A second native qualification job waits for every -same-architecture staging job, so Rails receives both its application digest -and the staged PostgreSQL digest; a missing matching artifact fails the gate. -The Node journey starts with an empty public archive -cache, acquires an integrity-pinned dependency through the registry-restricted -broker, installs and executes it offline, reproduces a producer-visible fixture -defect, and verifies a patch bound to its recorded closure and preparation -proofs. The helper issues a `runtime_tested` `RepairBundle` only when its -out-of-process witness authenticates the external assertions. Canonical project -tests run in a target-controlled process, so their completion remains -`self_reported`: target code can forge reporter output or terminate the runner. -Recorded command, count, exit, and output hashes are diagnostic evidence; they -do not establish target-independent test completion. The `tested` state remains -reserved for a future target-independent witness and is not emitted today. -Until the runtime-tested bundle, replay, and current-source recheck journey -passes, the held-out repair gate remains pending and catalog -promotion is prohibited. The candidate journey also asserts that no run-owned -containers, preparation call directories, archive staging directories, or -verification work directories remain. A skipped staged-image journey is not a -passing cold-start or private held-out-repair result. Bun and Python have cold acquisition, offline install, -boot, control, and project-test journeys. Rails runs those checks twice against -the same cold public-gem inputs: once with two disposable SQLite connections -and once with two databases in a fresh staged PostgreSQL sidecar. The Rails -fixture builds the source-platform `sqlite3` and `pg` native gems only in the -offline execution phase. - -Preparation output leaves its containers through `docker cp`, which cannot read -a tmpfs mount. The acquisition `/archives` directory and the offline `/work` -directory are therefore Docker local volumes backed by bounded tmpfs, created -per container with private mode, the runtime uid/gid, `nosuid`, and `nodev` -(`/archives` is also `noexec`; `/work` must stay executable for virtualenv and -binstub launchers). The runner inspects each container and refuses to start it -if Docker did not preserve those options. npm's user and global configs point -at two different empty files, because npm refuses to load one file in both -roles. Rails application and test containers hold on `sleep` after `run-app` -copies the source; `db:prepare` starts only once that copy has finished. -Changes to `/opt/cso/preparation` or an image recipe need a new staging run -before native qualification can pass. - -Each supervised command has a 300-second ceiling (`COMMAND_TIMEOUT_MS` in -`lib/cso/process.ts`). Only the dependency fetch and install commands of the -acquisition and offline preparation phases get `PREPARATION_COMMAND_TIMEOUT_MS`, -900 seconds. A Rails lockfile that lists only the `ruby` platform compiles -nokogiri, sqlite3 and pg offline, which takes about 385 seconds at the app -role's 0.85 CPU share. Both ceilings are cut to the time left before the -journey's aggregate deadline, so the longer ceiling never extends a journey. -Helper probes, exports, application starts, `db:prepare` and project tests keep -the 300-second ceiling. A free test in `test/cso-docker-mounts.test.ts` pins -which calls may request the longer ceiling. The CPU share is unchanged, so -`ISOLATION_POLICY_HASH` and the profiles bound to it are unaffected. - -When the in-image helper refuses to export a prepared tree, preparation fails -with error code `PREPARED_EXPORT_REJECTED` instead of the generic -`TOOL_FAILED`. The message carries the helper's exit status and its fixed -reason, such as `prepared tree contains a hard-linked file`, or the filesystem -errno and syscall. It never includes target paths. Nothing retries. Treat a -recurrence as evidence for a defect, not as a flake to rerun. - -The Rails offline install runs `bundle install --jobs 1`. Ruby's -`File.umask` getter sets the process umask to 0 for an instant, and RubyGems -calls it for every file it extracts. With two Bundler install threads, a -directory created by one thread during that instant comes out 0777, and the -export refuses the tree with `prepared tree contains a publicly writable -directory`. That refusal is correct, so the install runs on one thread rather -than the gate being relaxed. At the app role's 0.85 CPU share the second thread -saved no measurable time. - -For hashed Python requirements resolved by pip, the broker records the requested -index URL, allowed contacted hosts, and verified wheel hash. Pip's internal -`files.pythonhosted.org` response URL is opaque to that TLS boundary, so -`resolvedUrl` remains `null`; `registryResponseSha256` identifies the acquired -archive bytes, not a verified response URL. - -Image publication starts with the committed -[`build-inputs.json`](../lib/cso/images/build-inputs.json). Its reviewed revision -pins distinct native manifests for every stack and the SBOM generator. Each -profile records the inspected source tag and immutable index for provenance. -Every source tag (each base, Python's uv and the SBOM generator) must name an exact release (`..`, or -`.` for PostgreSQL); a floating major or minor tag, `latest` or -another alias fails matrix generation with `FLOATING__SOURCE`. Each profile then records -`baseImages` keyed by `linux/amd64` and `linux/arm64`; Python additionally -records native uv manifests. CI fails if a source tag no longer resolves to the -reviewed index, a platform manifest is absent from that index, its image -configuration names another architecture, or an executable reports a different -runtime or package-manager version. Bun does not declare a Node version because -its container's `node` path is a Bun-backed fallback rather than a Node release. -A Bun project with a Node engine constraint therefore receives an explicit -prerequisite instead of a fabricated compatibility result. - -Configure the repository's `cso-runtime-release` GitHub environment with required -maintainer review and deployments restricted to protected `main`. The -[`cso-runtime-images.yml`](../.github/workflows/cso-runtime-images.yml) workflow -runs a build-only native matrix on pull requests. Its manual publication jobs -only accept `main`. They build on native amd64 and arm64 runners, publish to -the `cso-staging` namespace, signs provenance and SBOM attestations, and verifies -the workflow identity and source commit. It then pulls that exact digest into -the local daemon for tests that prohibit implicit pulls. The per-image smoke test executes -the embedded verifier against a loopback service with both a passing control -and an intentionally failing control, alongside the containment suite. After -all staging rows finish, native qualification jobs run the matching cold-start -journey described above. The Node row additionally runs the complete lifecycle -journey. Each native job is named `qualify-native ` and runs the -Docker suites with Bun's JUnit reporter -(`--reporter=junit --reporter-outfile=native-tests.junit.xml`). -[`cso-native-evidence.ts`](../scripts/cso-native-evidence.ts) maps every native -check key to the named tests that prove it for that stack and records the key -true only when the report has no failed testcase and each named test appears -once, passed, and made at least one assertion. A test that the environment -skips, such as the staged-runtime smoke test without `GSTACK_CSO_TEST_IMAGE`, -reports as skipped and leaves its checks false; any false native check fails the -job. The pending private checks are the stack's required release gates from -`cso-runtime-promotion.ts` minus its native keys: `secretCanaryPassed` and -`watchdogCleanupPassed` for PostgreSQL, plus `heldOutRepairPassed` and -`accuracyGatesPassed` for application stacks. The job uploads the JUnit report -beside `qualification-evidence.json`, which records its digest. -Registry publication is staging, not runtime qualification. - -GitHub Container Registry creates new packages private. Before a staging digest -can enter native or private qualification, a package administrator must make -its package public in GitHub's package settings. This is an explicit bootstrap -step because GitHub documents the visibility change as irreversible and does -not provide a supported workflow API for it. The release jobs use their scoped -workflow token to require `visibility: public` from GitHub's package REST -endpoint, then pull the exact platform digest with `docker --config` pointing -at a new directory whose `config.json` contains only an empty `auths` object. -The GitHub token, Docker credentials, contexts, certificate paths, and -credential helpers are absent from that Docker client. A private package, -metadata mismatch, failed anonymous pull, or different returned digest stops -staging, qualification, and promotion. Both -runtime and scanner promotion repeat this anonymous pull check on fresh hosted -runners before opening a catalog PR. - -The first protected-main staging run therefore stops at the public-package -check by design: its push creates the ten `cso-staging` packages as private. A -package administrator makes those ten packages public, then dispatches the -staging workflow again. Later runs publish new digests into the same public -packages. - -Review the retained staging artifacts together with all checks in -[`qualification.json`](../lib/cso/images/qualification.json). Cold-start fixtures, -held-out repair evaluations, precision/recall thresholds, crash cleanup, and all -secret-canary checks must pass before a reviewed catalog change can make a -digest executable. A successful protected-main qualification run packages one -`qualified-runtime.json` statement for each stack and architecture under the -`cso-qualified-runtime-statements` artifact. All ten statements bind the same -source commit and workflow run. The protected -[`cso-runtime-promote.yml`](../.github/workflows/cso-runtime-promote.yml) workflow -authenticates that run through the Actions API, checks every statement against -the committed build profiles, and emits an attested -`runtime-catalog.candidate.json`. The protected job immediately verifies the -candidate attestation against its workflow identity, protected-main source ref, -source commit, and exact file digest. It then compares `previousRevision` with -the source catalog, commits those same bytes to a fresh branch, and opens a -normal review PR. Pushes and pull requests made with the workflow's -`GITHUB_TOKEN` start no workflows, so after pushing the branch the job dispatches -[`free-tests.yml`](../.github/workflows/free-tests.yml) on it with -`gh workflow run free-tests.yml --ref ` (its `actions: write` grant). -That run reports the required `free-tests` check on the branch head the PR -proposes. Opening the PR also requires the repository setting **Allow GitHub -Actions to create and approve pull requests** (Settings → Actions → General → -Workflow permissions). Without it `gh pr create` fails after the push and the -dispatch, and a maintainer opens the PR from the pushed branch. A concurrent -catalog promotion fails the compare-and-swap or -produces a merge conflict instead of silently replacing the newer matrix. -The catalog stores a separately recomputable digest of the retained runtime -matrix and the digest of the complete external qualification statements. The -helper rejects a post-generation image or qualification mutation even if the -statement digest field was left unchanged. -Rollback retains the prior compatible catalog revision. - -The public qualification ingress is -[`cso-runtime-qualification.yml`](../.github/workflows/cso-runtime-qualification.yml). -Set the protected environment variable `CSO_QUALIFICATION_ACTOR` to the GitHub -service account used by the private evaluator. After its held-out assertions and -accuracy run pass, that account sends a `repository_dispatch` event of type -`cso-runtime-qualified`. The payload has the key `statements` and, optionally, -`evaluationRef`; no other key is accepted. `statements` contains ten objects -with `schemaVersion`, `helperAbi`, `state`, `buildRevision`, `runtimeId`, -`stack`, `platform`, immutable `image`, exact `versions`, `sourceCommit`, and -the true-valued `checks` accepted by `cso-runtime-promotion.ts`. All ten name -one `sourceCommit`. `evaluationRef` is an opaque `sha256:<64 hex>` reference -that lets the approver match the dispatch to the private evaluator's verdict. -An unprotected `dispatch-summary` job with no token permissions validates the -payload shape and writes `evaluationRef`, the source commit, and each -`runtimeId` and `image` pair to the run's job summary. The reviewer reads it -there before approving the protected `qualify` job. `evaluationRef` never enters -the normalized statements, the uploaded evidence, or the catalog. - -The protected job checks the actor, re-verifies both OCI attestations against -the protected staging workflow and source commit, and replaces the workflow, -time, SBOM digest, and provenance digest with values it observed. Attestations -are signed in the staging job, before native qualification runs, so a valid -attestation alone does not show that native gates passed. -[`cso-staging-run.ts`](../scripts/cso-staging-run.ts) therefore resolves the -staging run from each verified SLSA provenance statement: the predicate's -`runDetails.metadata.invocationId` must equal the signing certificate's -`runInvocationURI`, and all ten images must resolve to the same run of this -repository. Through the Actions API (`actions: read`) the ingress then requires -that run to be `.github/workflows/cso-runtime-images.yml`, started by -`workflow_dispatch` on `main` in this repository, completed with conclusion -`success`, and built from the statements' `sourceCommit`. The latest attempt's -`qualify-native ` jobs, read across every page of the jobs API, must -be exactly one per committed matrix row (ten) and all `success`. The run and job -records are retained as `staging-run-evidence`. The catalog generator runs last -as the final schema gate, and the ingress uploads the statements only after that -gate passes. The payload carries no held-out assertion, application source, -finding, or repair bundle. - -A qualification stays valid only while the inputs it was measured under are -unchanged. [`cso-requalification.ts`](../scripts/cso-requalification.ts) defines -four requalification triggers: the helper ABI (`CSO_HELPER_ABI`), the isolation -policy (`ISOLATION_POLICY_HASH`, which covers the `cso-isolation-v1` policy -version and every limit), `preparationSha256` (a digest of every source byte -compiled or copied into a runtime image: the import closure of the image's -verifier and preparation helpers plus the image build context), and the -`build-inputs.json` revision. Each helper entrypoint's leading `#!` line is -hashed as absent: it is compiled into the binary as an unused string and never -runs inside the image. Every other byte of the helpers counts, and so does -every byte of every other file, shebang lines included. The staging run's `reviewed-inputs` job records -these values for its source commit as the `cso-requalification-triggers` -artifact. The ingress downloads that artifact from the verified staging run -into the evidence, and the promotion generator writes it into -`promotion.requalification`. When a recorded `preparationSha256` differs from -the promoting checkout's, generation re-measures it at the staged commit from -the checkout's git history. The record must match that commit under either the -current rule or the earlier rule that also hashed the helpers' `#!` lines, and -the current-rule value is what gets compared and recorded. Generation refuses -triggers that differ from the promoting checkout, so a trigger that changed between staging and promotion -requires a new staging run. The free suite's -[`cso-requalification.test.ts`](../test/cso-requalification.test.ts) compares -the committed catalog's recorded triggers with the current source and fails -when any differs. A change to a trigger therefore either lands with a -requalified catalog or withdraws the catalog's runtimes in the same pull -request. Independently, the helper refuses to select a runtime recorded under -another isolation policy. - -The daily precision gate (`dailyPrecision95` in -[`cso-eval.ts`](../scripts/cso-eval.ts)) divides true positives by reported -findings. Hypotheses count in neither term. A finding the evaluator marks -`instrumentation` also counts in neither term: it targets the evaluator's -declared fixture instrumentation, such as the canary overlay files or the egress -probe route. The seeded issue adds one true positive per cell, however many -times it is restated. A finding the evaluator marks `incidental` is a different -issue that a unanimous judge panel confirmed is real in that source. It adds one -true positive per distinct `incidentalKey` in its cell, never counts toward -recall, and needs no seeded match. Recall still measures only the seeded issue, -and the thresholds are unchanged. - -The falsely-tested gate (`zeroFalselyTestedRepairs`) counts every finding the -producer claimed was tested that trusted evidence does not certify. A claim on -the seeded issue is certified only by the judge's own held-out repair -verification. A claim on an `incidental` finding is certified only when the -evaluator replayed the helper's signed repair bundle for that finding against -the trusted source and the replay passed: the evaluator records -`trustedReplay: { result: "passed", replayEvidenceHash }`. A `failed` replay or a -`missing` bundle leaves the claim falsely tested. A claim on an -`instrumentation` finding counts in neither direction, the same way precision -leaves it out. Neither a replay nor an instrumentation claim ever counts toward -recall, repair or held-out rates, which need the seeded issue. - -The judge observes held-out attacks in one boot: a `VerificationRequest`'s -`security` field is either one assertion or an array of up to eight assertions -with distinct names, judged in a single before/after pair. The before phase is -`intended_failure` only when every assertion shows its vulnerable expectation, -and the after phase passes only when every assertion passes its fixed -expectation. A single assertion keeps its original hashes. The verifier is -compiled into the runtime images, so array requests need images staged from a -commit that includes it. - -### Evaluation-only helper builds - -The private evaluator drives the real helper against staged digests before -any gate is measured. It never edits the committed catalog. Instead, -`bun scripts/cso-runtime-promotion.ts evaluation-candidate --staged-root ---output ` converts one staging run's ten `staged-image.json` records -into an evaluation-only catalog. Its revision is `cso-eval--`, it -carries an `evaluation` record instead of `promotion`, and every runtime is an -`evaluation_candidate` whose qualification has `kind: "evaluation"` and no -release-gate field. Each runtime's `qualifiedAt` is the current time unless -`--created-at ` names it. An evaluation that builds one unit per -platform must pass the same `--created-at` to every build: the scorer requires -both platforms' producers to embed identical catalog bytes. Then - -```bash -bun run build:cso -- --evaluation-candidate --output -``` - -compiles the helper core and `cso-eval-producer` from a private copy of the -source with that catalog embedded, adds the native launcher and watchdog, and -writes the five-artifact producer unit to a new directory outside the checkout. -Beside the unchanged `.gstack-cso-generation` manifest, it writes -`.gstack-cso-evaluation`, which marks the unit evaluation-only and records the -catalog revision, catalog SHA-256, and core SHA-256. The helper reports -`"evaluationOnly": true` from `--version`, labels its catalog evaluation-only -in runtime readiness, and refuses `provision-images --setup-summary`. -Distribution refuses it at every step. A normal `build:cso` stops when -`lib/cso/runtime-catalog.json` carries a `cso-eval-` revision. Setup fails when -`bin/` holds an `.gstack-cso-evaluation` manifest or a launcher that reports -`evaluationOnly`. Catalog promotion and transitions reject evaluation catalogs, -and the runtime catalog validator rejects an evaluation catalog that carries -`promotion`, release-gate fields, or a revision that does not name its staging -run and source commit. - -The current reviewed profiles and unpromoted catalog establish this release -process; they do not claim published gstack images, passed containment, or -measured security accuracy. -Private held-out find-to-repair evaluations remain mandatory release gates for -Node, Bun, Python, and Rails. The producer-visible Node lifecycle fixture and the -other cold-start journeys do not satisfy those gates. Qualification artifacts -therefore record private checks as `"pending"` and `qualified: false` until all -four private evaluations and the accuracy thresholds pass. The remaining -external prerequisite is one successful protected-main run that uploads all ten -authenticated statements. This sandbox cannot create that evidence because it -has neither a native arm64 runner nor the private held-out assertions. - -Attestation behavior follows [Docker's SBOM documentation](https://docs.docker.com/build/metadata/attestations/sbom/) -and [GitHub CLI's verification policy](https://cli.github.com/manual/gh_attestation_verify). -Public-package behavior follows [GitHub's package permissions documentation](https://docs.github.com/en/packages/learn-github-packages/about-permissions-for-github-packages), -[GitHub's package REST endpoint](https://docs.github.com/en/rest/packages/packages#get-a-package-for-a-user), -and [Docker's client configuration documentation](https://docs.docker.com/reference/cli/docker/), -inspected on September 11, 2026. diff --git a/docs/cso-scanners.md b/docs/cso-scanners.md deleted file mode 100644 index f1a904c7d..000000000 --- a/docs/cso-scanners.md +++ /dev/null @@ -1,123 +0,0 @@ -# Running CSO scanners - -`gstack-cso scan RUN SCANNER [REQUEST.json]` collects candidate evidence through -the trusted helper when a matching qualified scanner catalog profile exists. -Recognized IDs are `gitleaks`, `osv`, `semgrep`, `zizmor`, `trivy`, and -`schemathesis`. Without a qualified profile, the command records a specific -prerequisite; static assessment and importing existing CodeQL or other SARIF -with `gstack-cso import-sarif RUN REPORT.sarif` remain available. -The returned immutable artifact can be read later with -`gstack-cso scanner-outcome RUN ARTIFACT_ID`; callers never need to open private -state files directly. - -The source-controlled catalog in -[`scanner-images/catalog.json`](../lib/cso/scanner-images/catalog.json) is empty -until every release gate produces real evidence. Without a reviewed profile, -the command records a specific `not_assessed` prerequisite. Installing a -scanner on the host does not enable execution. Each profile binds a Linux -platform, immutable image digest, fixed entrypoint, absolute scanner executable, -version-probe hash, required adapter capabilities, helper ABI, and the exact -isolation-policy hash. The helper validates that catalog when it starts and has -no executable fallback. -Setup preloads the current platform's qualified scanner digests through the -trusted installation helper using anonymous public-registry access. A failed -preload or a bounded per-image/setup deadline is a nonfatal prerequisite and -never causes an audit to pull. The default is 30 seconds per declared image; -`GSTACK_CSO_IMAGE_PULL_TIMEOUT_SECONDS=120` selects a longer allowance (accepted -range: 5–300 seconds) while the complete preload remains capped at one hour. Doctor is -read-only and reports each scanner unavailable unless its exact catalog digest -is already present locally. - -All scanner processes use Docker containment with a watchdog, shared admission -limits, read-only source, bounded output, and an isolated network namespace. -Static scanners have no network access, including when the audit omits -`--offline`. Semgrep rules and OSV/Trivy databases must be baked into the reviewed -image. Their content hashes, scope, and freshness accompany the result. Database -refresh is a separately reviewed image acquisition/release operation; scans -never download missing assets or switch to unrestricted registry networking. - -`REQUEST.json` can select an exact scanner `profile`. Schemathesis additionally -requires comprehensive mode and an `api` object; `gstack-cso schema` describes -its fields. The API harness supplies a bounded OpenAPI 3.0/3.1 JSON document, -1–20 unique path operation IDs, a qualified application runtime, an absolute -start command, a numeric loopback port, a legitimate HTTP control, and the -source files defining the security boundary. Internal schema references are -allowed. Server overrides, remote references/examples, hooks, callbacks, and -webhooks are rejected. The application must boot and pass the control before -the scanner starts. Application and scanner share only the admitted loopback -namespace. An API failure is a candidate, never a reproduced vulnerability or -certified repair. Sources needing dependency preparation report that prerequisite -until a prepared offline closure is available to the API runner. - -Each execution probes the scanner version before scanning and validates the -retained source both before and after collection. Unknown output, failed -diagnostics, a timeout, changed source, or incomplete cleanup cannot become an -empty clean result. The helper retains valid partial candidates when the -adapter can distinguish them from failed coverage. Scanner output is redacted -in place: each located sensitive span becomes a `` marker, so an -advisory URL or version string that resembles a phone number or IP address does -not discard the whole report. Output that cannot be redacted, including a span -split across stdout and stderr, is withheld. - -Scanner and SARIF collection hold the run's mutation lock and reject finished -or interrupted reports. Every outcome is written exclusively under a unique -`scanner-outcomes/` name before its coverage record enters the report. The -returned `artifact` path is relative to the run directory. Model submissions -cannot replace `scanner:*` coverage or certify the imported candidates. The -free scanner tests use injected runners and catalogs to verify dispatch and -failure handling; they do not claim real image qualification. The opt-in Docker -qualification test runs the production adapter, image, watchdog, and isolation -policy. It emits the version-output hash only after a representative scan -completes without a coverage gap. - -The reviewed release inputs in -[`build-inputs.json`](../lib/cso/scanner-images/build-inputs.json) cover all six -scanners on both native platforms. The inputs require immutable base and SBOM-generator image digests, exact source -commits and versions, signer workflow identities and digests, and reviewed -canonical SLSA/SPDX statement-set digests. The workflow cryptographically -re-verifies each image with those repository, source, signer, and predicate -constraints before use. Semgrep additionally requires a reviewed local rules bundle. OSV and -Trivy require complete offline database bundles with recorded content hashes, -freshness, and ecosystem coverage. The release workflow does not invent or -silently replace them. None of the upstream scanner images publish GitHub -artifact attestations, so the reviewed bases come from -[`garrytan/gstack-cso-scanner-bases`](https://github.com/garrytan/gstack-cso-scanner-bases). -That repository re-publishes each pinned upstream digest with the offline assets -added and signs provenance and an SPDX SBOM with its own workflow. Each tagged -release attaches a `pending` `build-inputs.json` candidate; a reviewer -independently re-verifies the identities and hashes before the state here -changes to `reviewed`. - -[`cso-scanner-images.yml`](../.github/workflows/cso-scanner-images.yml) lets a -dispatched branch run read-only input and contract validation. Image publishing, -native amd64/arm64 qualification, attestation verification, embedded-asset hash -checks, containment, real-adapter execution, and catalog-proposal generation run -only from protected `main` through the `cso-scanner-release` environment. Before -enabling qualification or promotion, configure the repository's -`cso-scanner-release` GitHub environment with required maintainer reviewers and -deployments restricted to protected `main`. GitHub otherwise creates a referenced -missing environment without protection rules. Promotion requires an explicit -dispatch from `main` and approval through that configured environment. It opens a pull request -containing only the proposed source catalog, so code review remains the final -authorization step. Pushes and pull requests made with the workflow's -`GITHUB_TOKEN` start no workflows, so after pushing the promotion branch the job -dispatches [`free-tests.yml`](../.github/workflows/free-tests.yml) on it -(`actions: write`); that run reports the required `free-tests` check on the -branch head. Opening the PR also requires the repository setting **Allow GitHub -Actions to create and approve pull requests** (Settings → Actions → General → -Workflow permissions); without it `gh pr create` fails after the push and the -dispatch, and a maintainer opens the PR from the pushed branch. -`previousRevision` records the prior compatible catalog for -rollback and must still equal the current `main` catalog when promotion runs. - -Scanner flags follow the primary documentation linked in -[`scanners.ts`](../lib/cso/scanners.ts). Offline qualification must exercise -the exact chosen version: OSV's maintainers documented a cache-location -regression in 2.5.0, which demonstrates why a version string alone is insufficient. -[OSV issue #2983](https://github.com/google/osv-scanner/issues/2983). -Trivy uses an explicit memory scan cache alongside read-only baked databases -and a baked misconfiguration checks bundle. Schemathesis 4.26 and later repeat -fuzzing until `--max-time` is spent, so the adapter sets that budget to three -quarters of the scanner deadline and treats a `max_time` stop as complete only -when every selected operation was exercised. -[Trivy filesystem reference](https://trivy.dev/docs/v0.68/guide/references/configuration/cli/trivy_filesystem/). diff --git a/docs/standalone-binaries.md b/docs/standalone-binaries.md index 44ef443f3..4038ebed7 100644 --- a/docs/standalone-binaries.md +++ b/docs/standalone-binaries.md @@ -26,19 +26,3 @@ Beyond the slash-command skills, gstack ships standalone CLIs for workflows that | `gstack-ios-qa-daemon` | **iOS QA daemon** — Mac-side broker between an agent and a connected iPhone or iPad over USB CoreDevice. Loopback by default; `--tailnet` opens a Tailscale-facing listener with identity-gated capability tiers. Single-instance via flock on `~/.gstack/ios-qa-daemon.pid`. See [docs/howto-ios-testing-with-gstack.md](howto-ios-testing-with-gstack.md). | | `gstack-ios-qa-mint` | **iOS allowlist manager** — owner-grant CLI for the tailnet allowlist. `grant`/`revoke`/`list` against `~/.gstack/ios-qa-allowlist.json` (mode 0600). Remote agents never auto-allowlist; this is the explicit-intent path. | | `gstack-ios-qa-regen` | **iOS bridge regenerator** — deterministically installs the canonical DebugBridge package, generates typed state accessors, and records the installed gstack version. Safe to rerun after source changes or upgrades. | - -The private paid CSO evaluation producer is a packaging contract, not an ordinary `bun run build` artifact. On macOS or Linux, a release operator compiles `cso-eval-producer` with the documented hardened Bun flags in the same clean build session as `bun run build:cso`, then installs it beside `gstack-cso-launcher`, `gstack-cso-core`, `gstack-cso-watchdog`, and the hidden `.gstack-cso-generation` manifest as one root-owned, nonwritable five-artifact unit. The producer rejects root execution, writable/symlinked/incomplete installations, and unreviewed provider CLI versions; each receipt binds all five artifact hashes, and collection rejects receipts from different unit identities. See the [clean producer procedure](../test/fixtures/cso-eval/README.md#trusted-five-artifact-producer-unit). Paid producer evaluation remains unavailable on Windows because the detached watchdog has no Windows build. - -Each producer gets a curated one-cell source copy with directories sealed to `0555` and files to `0444`, plus pre/post content, Git, and mode checks. Claude receives no source add-directory, because an add-directory is a sandbox write root where Claude Code's bubblewrap leaves an empty `.mcp.json` mount point. Its Bash runs inside Claude Code's sandbox with one exception: the exact absolute launcher path that `--allowed-tools` names, which runs outside it as it does for users. The launcher is the boundary there. It replaces its environment with a fixed allowlist, uses only the local Docker Unix socket, and runs every target in hardened containers. The producer passes that policy through `--settings` (sandbox enabled, fail if unavailable, no unsandboxed fallback, no auto-allow, and `excludedCommands` naming only the launcher). It refuses to start the agent (`CLAUDE_PRODUCER_SANDBOX_POLICY_MISMATCH`) unless the generated arguments and environment carry exactly that policy. `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` stays unset, because it would force the launcher back into the sandbox. Every other Bash command is denied by `--allowed-tools`, and Write is confined to the provider work directory and `cso-home`. Gemini receives no source working directory or include-directory. Codex technically receives read-only filesystem access to the exact curated source root because the trusted helper inherits the Codex permission profile; its private provider work directory and exact `cso-home` artifact directory are the only write roots, every other root path remains denied, and the producer prompt requires source access through the helper. This is evaluation containment for an immutable public fixture, not a claim that Codex cannot directly read that fixture. - -Copy each completed cell's receipt together with `state/cso-home/security/cso/` to the trusted adjudication host. Receipt entries are sorted paths relative to that directory and bind every retained file's size and SHA-256 plus an aggregate inventory hash. Provider homes, settings, sessions, and credentials live under separate disposable directories and are removed after the cell; they are never part of the retained artifact tree. The adjudicator must re-hash the transported tree against the receipt before trusting reports or repair bundles. - -Paid producer qualification uses this explicit host matrix: - -| Producer host | Daily/static cells | Comprehensive target execution | -|---|---|---| -| Codex CLI 0.153.4 | Supported under the custom permission profile | Fails closed because Docker/socket access is not granted to the model command sandbox; report the setup gap as partial | -| Claude Code 2.1.263 | Supported under restricted safe mode | Fails closed when the restricted launcher child cannot reach Docker; report the setup gap as partial | -| Gemini CLI 0.59.0 | Supported with isolated home/settings | Private release qualification host: the exact `run_shell_command()` policy can run the trusted helper without exposing a general shell | - -Every setup-blocked comprehensive cell remains a miss in release-gate denominators. The evaluator does not silently count a host or workflow as supported when its containment policy prevents required setup. diff --git a/lib/docs-only.ts b/lib/docs-only.ts index 3503b172e..3849049c3 100644 --- a/lib/docs-only.ts +++ b/lib/docs-only.ts @@ -52,7 +52,6 @@ export const DOCS_READER_EXEMPT: Readonly> = { 'test/bash32-case-in-substitution.test.ts': 'skips .md files', 'test/aside-artifacts.test.ts': 'lists generated SKILL.md and sections only', 'test/branch-slug-hygiene.test.ts': 'lists SKILL.md and sections only', - 'test/cso-cli.test.ts': 'lists a fixture repository', 'test/free-fixtures.test.ts': 'reads test/fixtures only', 'test/helpers/docsync-repo.ts': 'lists a fixture repository', }; diff --git a/package.json b/package.json index 8ae0ab20d..68bc11a28 100644 --- a/package.json +++ b/package.json @@ -15,9 +15,6 @@ "format:cso:check": "prettier --check 'lib/cso/*.ts'", "typecheck": "tsc -p tsconfig.json", "typecheck:test": "bun run scripts/typecheck-test.ts", - "test:cso:docker": "bun test --max-concurrency 1 test/cso-docker-integration.test.ts test/cso-node-lifecycle-integration.test.ts test/cso-stack-cold-integration.test.ts", - "test:cso:macos": "bun test test/cso-macos-launcher.test.ts test/cso-registry-socket.test.ts", - "test:cso:windows": "bun test test/cso-windows-launcher.test.ts", "vendor:xterm": "mkdir -p extension/lib && cp node_modules/xterm/lib/xterm.js extension/lib/xterm.js && cp node_modules/xterm/css/xterm.css extension/lib/xterm.css && cp node_modules/xterm-addon-fit/lib/xterm-addon-fit.js extension/lib/xterm-addon-fit.js", "dev:make-pdf": "bun run make-pdf/src/cli.ts", "dev:design": "bun run design/src/cli.ts", diff --git a/scripts/cso-attestation-evidence.ts b/scripts/cso-attestation-evidence.ts deleted file mode 100644 index b777eb23e..000000000 --- a/scripts/cso-attestation-evidence.ts +++ /dev/null @@ -1,29 +0,0 @@ -#!/usr/bin/env -S bun --no-env-file --config=/dev/null -/** Bind cryptographically verified `gh attestation verify --format json` output to reviewed statements. */ -import * as fs from 'node:fs'; -import { resolve } from 'node:path'; -import { canonical, sha256 } from '../lib/cso/contracts'; - -const HASH=/^[a-f0-9]{64}$/,MAX_BYTES=4*1024*1024; - -export function verifiedStatementSetDigest(value:unknown,predicateType:string,subjectSha256:string):string{ - if(!Array.isArray(value)||!value.length||typeof predicateType!=='string'||!/^https:\/\/[A-Za-z0-9./_-]+$/.test(predicateType)||!HASH.test(subjectSha256))throw new Error('INVALID_VERIFIED_ATTESTATION_SET'); - const statements:string[]=[]; - for(const item of value){ - if(!item||typeof item!=='object'||Array.isArray(item))throw new Error('INVALID_VERIFIED_ATTESTATION_SET'); - const result=(item as any).verificationResult,statement=result?.statement; - if(!statement||typeof statement!=='object'||Array.isArray(statement)||statement.predicateType!==predicateType||!Array.isArray(statement.subject)|| - !statement.subject.some((subject:any)=>subject&&typeof subject==='object'&&subject.digest?.sha256===subjectSha256))throw new Error('VERIFIED_ATTESTATION_IDENTITY_MISMATCH'); - statements.push(canonical(statement)); - } - statements.sort();return`sha256:${sha256(canonical(statements))}`; -} - -if(import.meta.main){ - try{ - const args=process.argv.slice(2),command=args.shift(),file=args.shift(),predicate=args.shift(),subject=args.shift(); - if(command!=='digest'||!file||!predicate||!subject||args.length)throw new Error('Usage: cso-attestation-evidence digest VERIFIED.json PREDICATE SUBJECT_SHA256'); - const path=resolve(file),stat=fs.lstatSync(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.nlink!==1||stat.size<=0||stat.size>MAX_BYTES)throw new Error('UNSAFE_VERIFIED_ATTESTATION_FILE'); - process.stdout.write(verifiedStatementSetDigest(JSON.parse(fs.readFileSync(path,'utf8')),predicate,subject)+'\n'); - }catch(error){process.stderr.write((error instanceof Error?error.message:'ATTESTATION_EVIDENCE_ERROR')+'\n');process.exitCode=1;} -} diff --git a/scripts/cso-eval.ts b/scripts/cso-eval.ts deleted file mode 100644 index 9d66b28c7..000000000 --- a/scripts/cso-eval.ts +++ /dev/null @@ -1,984 +0,0 @@ -#!/usr/bin/env -S bun --no-env-file --config=/dev/null -/** Trusted corpus preparation, producer receipt collection, and objective result accounting. */ -import { createHash } from 'node:crypto'; -import { execFileSync } from 'node:child_process'; -import { existsSync, lstatSync, mkdirSync, readdirSync, realpathSync } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; -import { readBoundedStable } from '../lib/cso/bounded-file'; -import { canonical } from '../lib/cso/contracts'; -import { validateRuntimeCatalog, type RuntimeCatalog } from '../lib/cso/runtime-catalog'; -import { EMPTY_GLOBAL_GIT_CONFIG, executable } from '../lib/cso/process'; -import { atomicWriteSync } from '../lib/fs-atomic'; -import { loadCorpusManifest, materializeCase, publicCorpus, STACKS, validateCorpusManifest, type CorpusManifest, type EvalCorpus, type EvalStack, type EvalVariant } from '../test/fixtures/cso-eval/materialize'; -import { - PRODUCER_PLATFORMS, - producerArtifactInventoryHash, - producerExecution, - producerInputHash, - producerInstallationIdentityHash, - producerProviderIdentityHash, - producerReceiptHash, - sha256, - type ProducerCell, - type ProducerArtifactInventory, - type ProducerHost, - type ProducerInput, - type ProducerInstallationIdentity, - type ProducerPlatform, - type ProducerProviderIdentity, - type ProducerReceipt, - type ProducerReceiptIndex, - type ProducerSourceEntry, -} from './cso-eval-protocol'; - -export type EvalVersion = 'v2' | 'v3'; -export type EvalMode = 'daily' | 'comprehensive'; -export type Outcome = 'passed' | 'failed' | 'blocked' | 'not_attempted'; -/** - * full: matched v2/v3 × 3 repetitions on one producer installation. - * release: v3 only, 1 repetition, each cell pinned to a native platform. - * baseline: v2 comprehensive only, 1 repetition; scored into a reusable EvalBaseline. - */ -export type EvalProfile = 'full' | 'release' | 'baseline'; -export type EvalPlatform = ProducerPlatform; -type EvalCorpusManifest = CorpusManifest; -export interface EvalCell extends ProducerCell { - id: string; caseId: string; stack: EvalStack; variant: EvalVariant; version: EvalVersion; mode: EvalMode; - repetition: 1 | 2 | 3; model: string; host: ProducerHost; budgetSeconds: number; sourceHash: string; skillHash: string; platform?: EvalPlatform; -} -interface EvalMatrixBase { - schemaVersion: 1; corpusVersion: string; corpusHash: string; model: string; host: ProducerHost; - budgets: { daily: number; comprehensive: number }; cells: EvalCell[]; -} -export interface FullEvalMatrix extends EvalMatrixBase { profile?: undefined; skillHashes: { v2: string; v3: string }; repetitions: 3 } -export interface ReleaseEvalMatrix extends EvalMatrixBase { - profile: 'release'; skillHashes: { v3: string }; repetitions: 1; - /** Daily cells run on one platform; each comprehensive case is fixed to one platform. */ - platforms: { daily: EvalPlatform; comprehensive: Record }; - /** Pre-registered external v2 baseline, or null when the regression gate stays unmeasured. */ - baselineHash: string | null; -} -export interface BaselineEvalMatrix extends EvalMatrixBase { - profile: 'baseline'; skillHashes: { v2: string }; repetitions: 1; - platforms: { comprehensive: Record }; -} -export type EvalMatrix = FullEvalMatrix | ReleaseEvalMatrix | BaselineEvalMatrix; -interface EvalMatrixCommonOptions { model: string; host: ProducerHost; budgets?: { daily: number; comprehensive: number } } -export interface FullEvalMatrixOptions extends EvalMatrixCommonOptions { profile?: 'full'; skillHashes: { v2: string; v3: string } } -export interface ReleaseEvalMatrixOptions extends EvalMatrixCommonOptions { profile: 'release'; skillHashes: { v3: string }; platforms: ReleaseEvalMatrix['platforms']; baseline?: EvalBaseline } -export interface BaselineEvalMatrixOptions extends EvalMatrixCommonOptions { profile: 'baseline'; skillHashes: { v2: string }; platforms: BaselineEvalMatrix['platforms'] } -export type EvalMatrixOptions = FullEvalMatrixOptions | ReleaseEvalMatrixOptions | BaselineEvalMatrixOptions; -/** - * A scored v2 comprehensive run, reused by release matrices while every bound - * input is unchanged. Release matrices pin its hash before results exist. - */ -export interface EvalBaseline { - schemaVersion: 1; version: 'v2'; - corpusVersion: string; corpusHash: string; model: string; host: ProducerHost; budgetSeconds: number; skillHash: string; - platforms: Record; - matrixHash: string; producerBatchHash: string; modelUsed: string; - provider: { family: ProducerProviderIdentity['family']; policyRevision: string; version: string }; - /** One entry per corpus case, in manifest order: whether the vulnerable cell found the seeded issue. */ - cases: Array<{ caseId: string; found: boolean }>; - baselineHash: string; -} -export interface PortableSkillFile { - path: string; - contents: string; -} -export interface PortableSkillFileIdentity { - path: string; - sha256: string; - bytes: number; -} -export interface PortableSkillPayloadIdentity { - schemaVersion: 1; - version: EvalVersion; - files: PortableSkillFileIdentity[]; -} -export interface EvalFinding { - id: string; evidence: 'supported' | 'hypothesis' | 'legacy_review'; claimedTested: boolean; - /** - * Written only by the independent evaluator after reviewing the reported trace. `correct`: the seeded issue. - * `incidental`: a different issue a unanimous judge panel confirmed is real in this source; a precision true - * positive, never recall. `instrumentation`: it targets the evaluator's declared fixture instrumentation - * (canary overlay files, egress probe), so precision leaves it out of both terms. - */ - judgment: 'correct' | 'incidental' | 'instrumentation' | 'incorrect' | 'unadjudicated'; matchedCaseId?: string; - /** `incidental` only: the evaluator's opaque key for the confirmed issue, so restatements count once per cell. */ - incidentalKey?: string; - /** - * Written only by the independent evaluator. A producer's tested claim is - * valid only when this finding, rather than merely another finding in the - * same corpus cell, owns the trusted repair and recheck observations. - */ - trustedVerification?: { - repair: Outcome; - repairEvidenceHash?: string; - recheck: Outcome; - recheckEvidenceHash?: string; - }; - /** - * Written only by the independent evaluator, for a tested claim on an `incidental` finding: the result of - * replaying the helper's signed repair bundle for that finding against the trusted source. `passed` (with the - * replay's evidence hash) certifies the claim; `failed` or `missing` (no bound bundle) leaves it falsely tested. - * It never counts toward recall, repair or held-out rates, which need the seeded issue. - */ - trustedReplay?: { result: 'passed' | 'failed' | 'missing'; replayEvidenceHash?: string }; -} -export interface EvalResult { - cellId: string; sourceHash: string; skillHash: string; model: string; host: string; budgetSeconds: number; - /** - * `reportFinished`: the helper report's status is `finished`; its findings and runtime outcomes count whatever its - * completeness, and the report gates require it. `reportComplete`: it is also `complete` (no gap, every domain - * assessed), measured as its own ungated rate because the corpus fixtures carry gaps by design. - */ - reportPresent: boolean; reportFinished: boolean; reportComplete: boolean; findings: EvalFinding[]; - setup: Outcome; reproduction: Outcome; repair: Outcome; recheck: Outcome; - /** Hash of trusted private observations; never a producer's claimed verification status. */ - oracleEvidenceHash?: string; - oracleVersion?: string; - heldOutAssertionsPassed: boolean; - currentSourceHash?: string; - recheckEvidenceHash?: string; - freshRecheck: boolean; - latencyMs: number; - firstUsefulResultMs: number | null; - /** Required by the release scorer; omitted only by isolated accounting tests. */ - producerReceiptHash?: string; - usage?: { source: 'host'; tokens?: number; costUSD?: number }; - prerequisite?: string; -} -export interface Rate { numerator: number; denominator: number; value: number | null } -export interface ReleaseQualification { - containment: Record; -} -export interface PreparedEvalSchedule { - schemaVersion: 1; - matrixHash: string; - scheduledCells: number; - preparedCells: number; - jobs: Array<{ cellId: string; relativePath: string; inputHash: string }>; -} -export interface ProducerGroupSummary { - version: EvalVersion; - mode: EvalMode; - scheduled: number; - submitted: number; - missing: number; - succeeded: number; - failed: number; - latency: { samples: number; denominator: number; p95Ms: number | null }; - firstUsefulResult: { samples: 0; denominator: number; p95Ms: null }; - modelTokens: { measured: number; denominator: number; total: number | null }; - estimatedCost: { measured: number; denominator: number; totalUSD: number | null; source: 'pricing-table-estimate' }; -} -export interface ProducerBatch { - schemaVersion: 1; - matrixHash: string; - scheduleHash: string; - receipts: ProducerReceiptIndex[]; - summary: { - scheduled: number; - prepared: number; - submitted: number; - missing: number; - matchedPairsExpected: number; - matchedPairsSubmitted: number; - modelMismatches: Array<{ pair: string; v2: string; v3: string }>; - groups: ProducerGroupSummary[]; - note: string; - }; - /** Present only when platforms embedded catalogs that differ in qualification time alone; see assertPlatformIdentities. */ - embeddedCatalogs?: RuntimeCatalog[]; - batchHash: string; -} -export const REQUIRED_CONTAINMENT = [ - 'hostile-startup-configuration', 'environment-canary', 'remote-docker-context', 'ipv4-egress', 'ipv6-egress', 'dns-egress', - 'archive-traversal-and-poisoning', 'symlink-traversal', 'split-output-secrets', 'concurrent-admission', 'expired-snapshot-replay', - 'watchdog-survival', 'failed-report-writes', 'held-out-oracle-visibility', -] as const; -const digest = (value: string) => createHash('sha256').update(value).digest('hex'); -const HEX = /^[a-f0-9]{64}$/; -const rate = (numerator: number, denominator: number): Rate => ({ numerator, denominator, value: denominator ? numerator / denominator : null }); -const validNumber = (value: unknown) => typeof value === 'number' && Number.isFinite(value) && value >= 0; -const PORTABLE_PAYLOAD_HEADER = '\n'; -const PORTABLE_FILE_END = '\n<<>>\n'; -const PORTABLE_FILE_LIMIT = 2 * 1024 * 1024; -const PORTABLE_PAYLOAD_LIMIT = 4 * 1024 * 1024; - -function portablePayloadPreamble(version: EvalVersion): string { - return `# Complete portable CSO evaluation instructions (${version})\n\nThis package is the sole CSO instruction input for this evaluation cell. Apply the embedded SKILL.md and every embedded manifest-listed section. Resolve any SKILL.md reference to cso/sections/ or sections/ from the matching embedded file below. Do not read an installed, user-home, repository, or other-version CSO skill or section. The file bodies are exact generated bytes; package markers are transport metadata.\n\n`; -} - -function portableFileOpen(identity: PortableSkillFileIdentity): string { - return `<<>>\n`; -} - -function parsePortableManifest(contents: string): { files: string[] } { - let manifest: any; - try { manifest = JSON.parse(contents); } catch { throw new Error('INVALID_CSO_EVAL_PAYLOAD_MANIFEST'); } - if (!manifest || manifest.skill !== 'cso' || manifest.version !== 1 || !Array.isArray(manifest.sections) || manifest.sections.length === 0) throw new Error('INVALID_CSO_EVAL_PAYLOAD_MANIFEST'); - const files: string[] = []; - const ids = new Set(); - for (const section of manifest.sections) { - if (!section || typeof section.id !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(section.id) || ids.has(section.id) || typeof section.file !== 'string' || !/^[a-z0-9]+(?:-[a-z0-9]+)*\.md$/.test(section.file) || files.includes(section.file) || typeof section.title !== 'string' || !section.title.trim() || typeof section.trigger !== 'string' || !section.trigger.trim()) throw new Error('INVALID_CSO_EVAL_PAYLOAD_MANIFEST'); - ids.add(section.id); files.push(section.file); - } - return { files }; -} - -function validatePortableSkillFiles(version: EvalVersion, files: PortableSkillFile[]): PortableSkillFile[] { - if (!['v2', 'v3'].includes(version) || !Array.isArray(files)) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - const byPath = new Map(); - for (const file of files) { - if (!file || typeof file.path !== 'string' || typeof file.contents !== 'string' || byPath.has(file.path) || Buffer.byteLength(file.contents) > PORTABLE_FILE_LIMIT || file.contents.includes(PORTABLE_FILE_END.trim())) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - byPath.set(file.path, file.contents); - } - const root = byPath.get('SKILL.md'), manifest = byPath.get('sections/manifest.json'); - if (root === undefined || manifest === undefined) throw new Error('INCOMPLETE_CSO_EVAL_PAYLOAD'); - const frontmatter = root.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/)?.[1]; - const versionMatch = frontmatter?.match(/^version:\s*([0-9]+)(?:\.[0-9]+){0,2}\s*$/m); - if (!versionMatch || Number(versionMatch[1]) !== Number(version.slice(1))) throw new Error('CSO_EVAL_PAYLOAD_VERSION_MISMATCH'); - const sectionFiles = parsePortableManifest(manifest).files; - const expectedPaths = ['SKILL.md', 'sections/manifest.json', ...sectionFiles.map(file => `sections/${file}`)]; - if (byPath.size !== expectedPaths.length || expectedPaths.some(path => !byPath.has(path))) throw new Error('INCOMPLETE_CSO_EVAL_PAYLOAD'); - return expectedPaths.map(path => ({ path, contents: byPath.get(path)! })); -} - -/** Render the only portable instruction format accepted by matrix preparation. */ -export function createPortableSkillPayload(version: EvalVersion, inputFiles: PortableSkillFile[]): string { - const files = validatePortableSkillFiles(version, inputFiles); - const identities = files.map(file => ({ path: file.path, sha256: sha256(file.contents), bytes: Buffer.byteLength(file.contents) })); - const identity: PortableSkillPayloadIdentity = { schemaVersion: 1, version, files: identities }; - let payload = `${PORTABLE_PAYLOAD_HEADER}${JSON.stringify(identity)}${PORTABLE_PAYLOAD_HEADER_END}${portablePayloadPreamble(version)}`; - for (let index = 0; index < files.length; index++) payload += `${portableFileOpen(identities[index])}${files[index].contents}${PORTABLE_FILE_END}`; - if (Buffer.byteLength(payload) > PORTABLE_PAYLOAD_LIMIT) throw new Error('CSO_EVAL_PAYLOAD_TOO_LARGE'); - return payload; -} - -/** Validate canonical serialization and return the identities bound by its hash. */ -export function validatePortableSkillPayload(payload: string, expectedVersion?: EvalVersion): PortableSkillPayloadIdentity { - if (typeof payload !== 'string' || Buffer.byteLength(payload) > PORTABLE_PAYLOAD_LIMIT || !payload.startsWith(PORTABLE_PAYLOAD_HEADER)) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - const headerEnd = payload.indexOf(PORTABLE_PAYLOAD_HEADER_END, PORTABLE_PAYLOAD_HEADER.length); - if (headerEnd < 0) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - let identity: PortableSkillPayloadIdentity; - try { identity = JSON.parse(payload.slice(PORTABLE_PAYLOAD_HEADER.length, headerEnd)); } catch { throw new Error('INVALID_CSO_EVAL_PAYLOAD'); } - if (identity?.schemaVersion !== 1 || !['v2', 'v3'].includes(identity.version) || (expectedVersion && identity.version !== expectedVersion) || !Array.isArray(identity.files)) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - let cursor = headerEnd + PORTABLE_PAYLOAD_HEADER_END.length; - const preamble = portablePayloadPreamble(identity.version); - if (payload.slice(cursor, cursor + preamble.length) !== preamble) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - cursor += preamble.length; - const files: PortableSkillFile[] = []; - for (const file of identity.files) { - if (!file || typeof file.path !== 'string' || !HEX.test(file.sha256) || !Number.isSafeInteger(file.bytes) || file.bytes < 0 || file.bytes > PORTABLE_FILE_LIMIT) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - const open = portableFileOpen(file); - if (payload.slice(cursor, cursor + open.length) !== open) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - cursor += open.length; - const end = payload.indexOf(PORTABLE_FILE_END, cursor); - if (end < 0) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - const contents = payload.slice(cursor, end); - if (Buffer.byteLength(contents) !== file.bytes || sha256(contents) !== file.sha256) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - files.push({ path: file.path, contents }); cursor = end + PORTABLE_FILE_END.length; - } - if (cursor !== payload.length || createPortableSkillPayload(identity.version, files) !== payload) throw new Error('INVALID_CSO_EVAL_PAYLOAD'); - return identity; -} - -/** Read one generated CSO skill tree and package every manifest-listed section. */ -export function loadPortableSkillPayload(version: EvalVersion, skillDirectory: string): string { - const root = resolve(skillDirectory), stat = lstatSync(root); - if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(root) !== root) throw new Error('UNSAFE_CSO_EVAL_SKILL_DIRECTORY'); - const read = (relativePath: string) => { - const bytes = readBoundedStable(join(root, ...relativePath.split('/')), PORTABLE_FILE_LIMIT, `CSO ${version} ${relativePath}`); - const contents = bytes.toString('utf8'); - if (!Buffer.from(contents).equals(bytes)) throw new Error('INVALID_CSO_EVAL_PAYLOAD_ENCODING'); - return contents; - }; - const rootSkill = read('SKILL.md'), manifest = read('sections/manifest.json'); - const sectionFiles = parsePortableManifest(manifest).files; - const sectionsRoot = join(root, 'sections'), sectionStat = lstatSync(sectionsRoot); - if (!sectionStat.isDirectory() || sectionStat.isSymbolicLink() || realpathSync(sectionsRoot) !== sectionsRoot) throw new Error('UNSAFE_CSO_EVAL_SKILL_DIRECTORY'); - const listed = new Set(sectionFiles); - const inventory = () => readdirSync(sectionsRoot, { withFileTypes: true }).filter(entry => entry.name.endsWith('.md')).map(entry => { - if (!entry.isFile() || entry.isSymbolicLink() || !listed.has(entry.name)) throw new Error('UNLISTED_CSO_EVAL_SECTION'); - return entry.name; - }).sort(); - const firstInventory = inventory(); - const files = [ - { path: 'SKILL.md', contents: rootSkill }, - { path: 'sections/manifest.json', contents: manifest }, - ...sectionFiles.map(file => ({ path: `sections/${file}`, contents: read(`sections/${file}`) })), - ]; - if (JSON.stringify(inventory()) !== JSON.stringify(firstInventory) || files.some(file => read(file.path) !== file.contents)) throw new Error('CSO_EVAL_SKILL_CHANGED_DURING_PACKAGING'); - return createPortableSkillPayload(version, files); -} - -function matrixHash(matrix: EvalMatrix): string { return digest(JSON.stringify(matrix)); } - -function safeWriteNew(path: string, value: unknown): void { - const target = resolve(path), parent = dirname(target), stat = lstatSync(parent); - if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(parent) !== parent) throw new Error('UNSAFE_EVAL_DESTINATION'); - atomicWriteSync(target, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, noReplace: true }); -} - -function readJsonBounded(path: string, max: number, label: string): any { - try { return JSON.parse(readBoundedStable(resolve(path), max, label).toString('utf8')); } - catch (error) { if (error instanceof SyntaxError) throw new Error(`INVALID_${label.toUpperCase().replaceAll(' ', '_')}`); throw error; } -} - -function initializeFixtureRepository(path: string): void { - const nullPath = process.platform === 'win32' ? 'NUL' : '/dev/null'; - const env = { - PATH: process.env.PATH ?? '', LANG: 'C', LC_ALL: 'C', - GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: EMPTY_GLOBAL_GIT_CONFIG, GIT_ATTR_NOSYSTEM: '1', - GIT_AUTHOR_NAME: 'CSO Eval', GIT_AUTHOR_EMAIL: 'cso-eval@invalid', - GIT_COMMITTER_NAME: 'CSO Eval', GIT_COMMITTER_EMAIL: 'cso-eval@invalid', - }; - const git = executable('git'); - // Prepared sources are copied immediately. A detached auto-maintenance child - // can remove .git/objects/maintenance.lock while that copy is in progress. - const safe = ['-c', 'maintenance.auto=false', '-c', 'gc.auto=0', - '-c', `core.hooksPath=${nullPath}`, '-c', `core.attributesFile=${nullPath}`, '-c', `core.excludesFile=${nullPath}`]; - execFileSync(git, [...safe, 'init', '--quiet', '--initial-branch=main'], { cwd: path, env, stdio: 'ignore' }); - execFileSync(git, [...safe, 'add', '--all'], { cwd: path, env, stdio: 'ignore' }); - execFileSync(git, [...safe, 'commit', '--quiet', '-m', 'immutable evaluation fixture'], { cwd: path, env, stdio: 'ignore' }); -} - -function sourceEntries(corpus: EvalCorpus, caseId: string, variant: EvalVariant): ProducerSourceEntry[] { - return Object.entries(corpus.sourceFiles(caseId, variant)).sort(([left], [right]) => left < right ? -1 : left > right ? 1 : 0).map(([path, contents]) => ({ path, sha256: sha256(contents), bytes: Buffer.byteLength(contents) })); -} - -/** - * Prepare independent one-cell jobs. The returned schedule is trusted - * evaluator metadata; transfer one job at a time and never give the schedule - * or sibling jobs to the producing agent. - */ -export function prepareEvalJobs(matrix: EvalMatrix, payloads: Partial>, destination: string, selectedCellIds?: string[], corpus: EvalCorpus = publicCorpus()): PreparedEvalSchedule { - validateMatrix(matrix, corpus.manifest); - const skillHashes: Partial> = matrix.skillHashes; - const versions = (['v2', 'v3'] as const).filter(version => skillHashes[version] !== undefined); - if (!payloads || Object.keys(payloads).sort().join(',') !== versions.join(',')) throw new Error('EVAL_SKILL_HASH_MISMATCH'); - for (const version of versions) { - validatePortableSkillPayload(payloads[version]!, version); - if (sha256(payloads[version]!) !== skillHashes[version]) throw new Error('EVAL_SKILL_HASH_MISMATCH'); - } - const root = resolve(destination); - if (existsSync(root)) throw new Error('EVAL_DESTINATION_EXISTS'); - const parent = dirname(root); - if (realpathSync(parent) !== parent || !lstatSync(parent).isDirectory()) throw new Error('UNSAFE_EVAL_DESTINATION'); - const selected = selectedCellIds === undefined ? matrix.cells : selectedCellIds.map(id => { - const cell = matrix.cells.find(item => item.id === id); - if (!cell) throw new Error('UNKNOWN_EVAL_CELL'); - return cell; - }); - if (new Set(selected.map(cell => cell.id)).size !== selected.length) throw new Error('DUPLICATE_EVAL_CELL'); - mkdirSync(root, { mode: 0o700 }); - const jobsRoot = join(root, 'jobs'); mkdirSync(jobsRoot, { mode: 0o700 }); - const jobs: PreparedEvalSchedule['jobs'] = []; - for (const cell of selected) { - const jobRoot = join(jobsRoot, cell.id); mkdirSync(jobRoot, { mode: 0o700 }); - const source = materializeCase(cell.caseId, cell.variant, join(jobRoot, 'source'), corpus); - if (source.sourceHash !== cell.sourceHash) throw new Error('CORPUS_INTEGRITY_MISMATCH'); - initializeFixtureRepository(source.path); - const input: ProducerInput = { schemaVersion: 2, cellRef: cell.id, skill: payloads[cell.version]!, source: sourceEntries(corpus, cell.caseId, cell.variant), execution: producerExecution(cell) }; - const inputHash = producerInputHash(input); - safeWriteNew(join(jobRoot, 'producer-input.json'), input); - jobs.push({ cellId: cell.id, relativePath: `jobs/${cell.id}`, inputHash }); - } - const schedule: PreparedEvalSchedule = { schemaVersion: 1, matrixHash: matrixHash(matrix), scheduledCells: matrix.cells.length, preparedCells: jobs.length, jobs }; - safeWriteNew(join(root, 'schedule.json'), schedule); - return schedule; -} - -function validateSchedule(matrix: EvalMatrix, schedule: PreparedEvalSchedule): void { - if (schedule?.schemaVersion !== 1 || schedule.matrixHash !== matrixHash(matrix) || schedule.scheduledCells !== matrix.cells.length || !Array.isArray(schedule.jobs) || schedule.preparedCells !== schedule.jobs.length) throw new Error('INVALID_EVAL_SCHEDULE'); - const known = new Set(matrix.cells.map(cell => cell.id)); - const seen = new Set(); - for (const job of schedule.jobs) { - if (!job || !known.has(job.cellId) || seen.has(job.cellId) || job.relativePath !== `jobs/${job.cellId}` || !HEX.test(job.inputHash)) throw new Error('INVALID_EVAL_SCHEDULE'); - seen.add(job.cellId); - } -} - -function validateReceipt(receipt: ProducerReceipt, cell: EvalCell, inputHash: string): void { - if (receipt?.schemaVersion !== 2 || receipt.cellRef !== cell.id || 'cell' in receipt || receipt.inputHash !== inputHash || receipt.requestedModel !== cell.model || !['succeeded', 'failed'].includes(receipt.status) || typeof receipt.modelUsed !== 'string' || !receipt.modelUsed || !['provider_reported', 'requested_pin'].includes(receipt.modelIdentitySource) || (receipt.modelIdentitySource === 'requested_pin' && receipt.modelUsed !== receipt.requestedModel) || (receipt.modelIdentitySource === 'provider_reported' && receipt.modelUsed === receipt.requestedModel) || !validNumber(receipt.durationMs) || receipt.firstUsefulResultMs !== null || !Number.isSafeInteger(receipt.toolCalls) || receipt.toolCalls < 0 || typeof receipt.output !== 'string' || receipt.outputHash !== sha256(receipt.output) || !HEX.test(receipt.receiptHash)) throw new Error('INVALID_PRODUCER_RECEIPT'); - const { receiptHash, ...withoutHash } = receipt; - if (producerReceiptHash(withoutHash) !== receiptHash) throw new Error('INVALID_PRODUCER_RECEIPT'); - const started = Date.parse(receipt.startedAt), finished = Date.parse(receipt.finishedAt); - if (!Number.isFinite(started) || !Number.isFinite(finished) || finished < started) throw new Error('INVALID_PRODUCER_RECEIPT'); - if (!receipt.usage || !['inputTokens', 'outputTokens', 'cachedTokens', 'estimatedCostUSD'].every(field => receipt.usage[field as keyof typeof receipt.usage] === null || validNumber(receipt.usage[field as keyof typeof receipt.usage]))) throw new Error('INVALID_PRODUCER_RECEIPT'); - const hasError = !!receipt.error; - if ((receipt.status === 'failed') !== hasError || (hasError && (!receipt.error!.code || typeof receipt.error!.reason !== 'string'))) throw new Error('INVALID_PRODUCER_RECEIPT'); - validateInstallationIdentity(receipt.installationIdentity, 'INVALID_PRODUCER_RECEIPT'); - validateProviderIdentity(receipt.providerIdentity, cell.host === 'codex' ? 'gpt' : cell.host, 'INVALID_PRODUCER_RECEIPT'); - validateArtifactInventory(receipt.artifacts, 'INVALID_PRODUCER_RECEIPT'); - const timeline = receipt.toolTimeline; - if (timeline !== undefined && (!Array.isArray(timeline) || timeline.length > 4096 || timeline.some(entry => !entry || !Number.isSafeInteger(entry.atMs) || entry.atMs < 0 || (entry.endMs !== undefined && (!Number.isSafeInteger(entry.endMs) || entry.endMs < entry.atMs)) || typeof entry.tool !== 'string' || !/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(entry.tool) || !['main', 'subagent'].includes(entry.agent) || Object.keys(entry).some(key => !['atMs', 'endMs', 'tool', 'agent'].includes(key))))) throw new Error('INVALID_PRODUCER_RECEIPT'); -} - -function validateInstallationIdentity(identity: ProducerInstallationIdentity, error: string): void { - const artifact = (value: any) => value && HEX.test(value.sha256) && Number.isSafeInteger(value.bytes) && value.bytes > 0; - if (!identity || identity.schemaVersion !== 1 || !artifact(identity.producer) || !artifact(identity.launcher) || !artifact(identity.core) || !artifact(identity.watchdog) || - !identity.embeddedCatalogs || !identity.embeddedCatalogs.runtimeRevision || !identity.embeddedCatalogs.runtimeBuildRevision || !HEX.test(identity.embeddedCatalogs.runtimeSha256) || - !identity.embeddedCatalogs.scannerRevision || !HEX.test(identity.embeddedCatalogs.scannerSha256) || !HEX.test(identity.identityHash)) throw new Error(error); - const { identityHash, ...withoutHash } = identity; - if (producerInstallationIdentityHash(withoutHash) !== identityHash) throw new Error(error); -} - -function validateProviderIdentity(identity: ProducerProviderIdentity, family: 'claude' | 'gpt' | 'gemini', error: string): void { - if (!identity || identity.schemaVersion !== 1 || identity.family !== family || !identity.policyRevision || !identity.version || - !identity.executable || !HEX.test(identity.executable.sha256) || !Number.isSafeInteger(identity.executable.bytes) || identity.executable.bytes <= 0 || - !Array.isArray(identity.argsPrefix) || identity.argsPrefix.some(value => typeof value !== 'string' || value.includes('\0')) || !HEX.test(identity.identityHash)) throw new Error(error); - const { identityHash, ...withoutHash } = identity; - if (producerProviderIdentityHash(withoutHash) !== identityHash) throw new Error(error); -} - -/** Paths are unique; their order is whatever the producer bound into identityHash (1.91.75 producers sorted by locale). */ -function validateArtifactInventory(inventory: ProducerArtifactInventory, error: string): void { - if (!inventory || inventory.schemaVersion !== 1 || inventory.root !== 'security/cso' || !Array.isArray(inventory.entries) || inventory.entries.length > 4096 || - !Number.isSafeInteger(inventory.totalBytes) || inventory.totalBytes < 0 || inventory.totalBytes > 128 * 1024 * 1024 || !HEX.test(inventory.identityHash)) throw new Error(error); - const paths = new Set(); - let total = 0; - for (const entry of inventory.entries) { - if (!entry || typeof entry.path !== 'string' || entry.path.length > 1024 || !/^[A-Za-z0-9._/-]+$/.test(entry.path) || entry.path.split('/').some(part => !part || part === '.' || part === '..') || - paths.has(entry.path) || !HEX.test(entry.sha256) || !Number.isSafeInteger(entry.bytes) || entry.bytes < 0 || entry.bytes > 32 * 1024 * 1024) throw new Error(error); - paths.add(entry.path); total += entry.bytes; - } - if (total !== inventory.totalBytes) throw new Error(error); - const { identityHash, ...withoutHash } = inventory; - if (producerArtifactInventoryHash(withoutHash) !== identityHash) throw new Error(error); -} - -function validateReceiptIndex(receipt: ProducerReceiptIndex, cell: EvalCell): void { - if (!receipt || receipt.schemaVersion !== 2 || receipt.cellRef !== cell.id || JSON.stringify(receipt.cell) !== JSON.stringify(cell) || !HEX.test(receipt.inputHash) || receipt.requestedModel !== cell.model || !receipt.modelUsed || !['provider_reported', 'requested_pin'].includes(receipt.modelIdentitySource) || (receipt.modelIdentitySource === 'requested_pin' && receipt.modelUsed !== receipt.requestedModel) || (receipt.modelIdentitySource === 'provider_reported' && receipt.modelUsed === receipt.requestedModel) || !['succeeded', 'failed'].includes(receipt.status) || !HEX.test(receipt.outputHash) || !HEX.test(receipt.receiptHash) || !validNumber(receipt.durationMs) || receipt.firstUsefulResultMs !== null || !Number.isSafeInteger(receipt.toolCalls) || receipt.toolCalls < 0 || !receipt.usage) throw new Error('INVALID_PRODUCER_BATCH'); - const started = Date.parse(receipt.startedAt), finished = Date.parse(receipt.finishedAt); - if (!Number.isFinite(started) || !Number.isFinite(finished) || finished < started || !['inputTokens', 'outputTokens', 'cachedTokens', 'estimatedCostUSD'].every(field => receipt.usage[field as keyof typeof receipt.usage] === null || validNumber(receipt.usage[field as keyof typeof receipt.usage])) || ((receipt.status === 'failed') !== !!receipt.error) || (receipt.error && !receipt.error.code)) throw new Error('INVALID_PRODUCER_BATCH'); - validateInstallationIdentity(receipt.installationIdentity, 'INVALID_PRODUCER_BATCH'); - validateProviderIdentity(receipt.providerIdentity, cell.host === 'codex' ? 'gpt' : cell.host, 'INVALID_PRODUCER_BATCH'); - validateArtifactInventory(receipt.artifacts, 'INVALID_PRODUCER_BATCH'); -} - -const matchedPairKey = (cell: EvalCell): string => [cell.caseId, cell.variant, cell.mode, cell.repetition, cell.model, cell.host, cell.budgetSeconds, cell.sourceHash].join('|'); -const PROFILE_GROUPS: Record> = { - full: [['v2', 'daily'], ['v2', 'comprehensive'], ['v3', 'daily'], ['v3', 'comprehensive']], - release: [['v3', 'daily'], ['v3', 'comprehensive']], - baseline: [['v2', 'comprehensive']], -}; -const profileOf = (matrix: EvalMatrix): EvalProfile => matrix.profile ?? 'full'; -const expectedMatchedPairs = (matrix: EvalMatrix): number => profileOf(matrix) === 'full' ? matrix.cells.length / 2 : 0; - -type IdentityBearing = Pick; -/** - * Each platform has exactly one producer installation and provider binary. - * Platforms differ only in native binaries: the embedded catalogs and the - * reviewed provider policy must be identical across them. Evaluation units that - * generated their catalog once per platform embed copies differing only in each - * runtime's `qualifiedAt` and the evidence digest over it; `bodies`, the catalogs - * as embedded, prove that, each hashing to its platform's runtimeSha256. - */ -function assertPlatformIdentities(receipts: IdentityBearing[], bodies: RuntimeCatalog[] = []): void { - const byPlatform = new Map(); - for (const receipt of receipts) { - const key = receipt.cell.platform ?? 'unpinned', list = byPlatform.get(key) ?? []; - list.push(receipt); byPlatform.set(key, list); - } - for (const list of byPlatform.values()) { - if (new Set(list.map(receipt => receipt.installationIdentity.identityHash)).size > 1) throw new Error('UNMATCHED_PRODUCER_INSTALLATIONS'); - if (new Set(list.map(receipt => receipt.providerIdentity.identityHash)).size > 1) throw new Error('UNMATCHED_PRODUCER_PROVIDERS'); - } - const representatives = [...byPlatform.values()].map(list => list[0]); - if (representatives.length < 2) return; - if (new Set(representatives.map(receipt => receipt.installationIdentity.identityHash)).size !== representatives.length) throw new Error('UNMATCHED_PRODUCER_PLATFORMS'); - const catalogs = (receipt: IdentityBearing) => JSON.stringify(receipt.installationIdentity.embeddedCatalogs); - const policy = ({ providerIdentity: { family, policyRevision, version, argsPrefix } }: IdentityBearing) => JSON.stringify({ family, policyRevision, version, argsPrefix }); - if (new Set(representatives.map(catalogs)).size !== 1 && !catalogsDifferOnlyInQualificationTime(representatives, bodies)) throw new Error('UNMATCHED_PRODUCER_INSTALLATIONS'); - if (new Set(representatives.map(policy)).size !== 1) throw new Error('UNMATCHED_PRODUCER_PROVIDERS'); -} - -function catalogsDifferOnlyInQualificationTime(representatives: IdentityBearing[], bodies: RuntimeCatalog[]): boolean { - if (!Array.isArray(bodies) || bodies.length !== representatives.length) return false; - const timeless = (body: RuntimeCatalog) => canonical({ ...body, evaluation: { ...body.evaluation, evidenceDigest: null }, runtimes: body.runtimes.map(({ qualifiedAt: _qualifiedAt, ...runtime }) => runtime) }); - const shared = ({ runtimeSha256: _runtimeSha256, ...rest }: ProducerInstallationIdentity['embeddedCatalogs']) => JSON.stringify(rest); - const matched = representatives.map(receipt => bodies.find(body => sha256(JSON.stringify(body)) === receipt.installationIdentity.embeddedCatalogs.runtimeSha256)); - if (matched.some(body => !body) || new Set(matched).size !== bodies.length) return false; - try { for (const body of bodies) validateRuntimeCatalog(body); } catch { return false; } - return new Set(representatives.map(receipt => shared(receipt.installationIdentity.embeddedCatalogs))).size === 1 && new Set(bodies.map(timeless)).size === 1 && - bodies.every(body => body.revision === representatives[0].installationIdentity.embeddedCatalogs.runtimeRevision && body.evaluation); -} - -/** `embeddedCatalogs`: the runtime catalog each platform's producer unit embedded, required only when those differ (see assertPlatformIdentities). */ -export function collectProducerReceipts(matrix: EvalMatrix, schedule: PreparedEvalSchedule, receipts: ProducerReceipt[], corpus: EvalCorpusManifest = loadCorpusManifest(), embeddedCatalogs: RuntimeCatalog[] = []): ProducerBatch { - validateMatrix(matrix, corpus); validateSchedule(matrix, schedule); - if (!Array.isArray(receipts)) throw new Error('INVALID_PRODUCER_RECEIPTS'); - const cells = new Map(matrix.cells.map(cell => [cell.id, cell])); - const jobs = new Map(schedule.jobs.map(job => [job.cellId, job])); - const seen = new Set(); - for (const receipt of receipts) { - const cell = cells.get(receipt?.cellRef), job = jobs.get(receipt?.cellRef); - if (!cell || !job || seen.has(cell.id)) throw new Error('UNKNOWN_OR_DUPLICATE_PRODUCER_RECEIPT'); - validateReceipt(receipt, cell, job.inputHash); seen.add(cell.id); - } - // Receipts name only the opaque cellRef; the trusted matrix supplies the cell. - const bound = receipts.map(receipt => ({ ...receipt, cell: cells.get(receipt.cellRef)! })); - assertPlatformIdentities(bound, embeddedCatalogs); - const platformCatalogs = new Set(bound.map(receipt => receipt.installationIdentity.embeddedCatalogs.runtimeSha256)).size > 1 ? embeddedCatalogs : undefined; - const pairs = new Map>>(); - if (profileOf(matrix) === 'full') for (const receipt of bound) { - const key = matchedPairKey(receipt.cell as EvalCell); - const pair = pairs.get(key) ?? {}; pair[receipt.cell.version] = receipt; pairs.set(key, pair); - } - else if (new Set(bound.map(receipt => receipt.modelUsed)).size > 1) throw new Error('UNMATCHED_EFFECTIVE_MODELS: single-version cells used different normalized model identities'); - const completePairs = [...pairs.entries()].filter(([, pair]) => pair.v2 && pair.v3) as Array<[string, { v2: (typeof bound)[number]; v3: (typeof bound)[number] }]>; - const modelMismatches = completePairs.filter(([, pair]) => pair.v2.modelUsed !== pair.v3.modelUsed).map(([pair, value]) => ({ pair: digest(pair), v2: value.v2.modelUsed, v3: value.v3.modelUsed })); - if (modelMismatches.length) throw new Error(`UNMATCHED_EFFECTIVE_MODELS: ${modelMismatches.length} matched v2/v3 pair(s) used different normalized model identities`); - const groups: ProducerGroupSummary[] = []; - for (const [version, mode] of PROFILE_GROUPS[profileOf(matrix)]) { - const expected = matrix.cells.filter(cell => cell.version === version && cell.mode === mode); - const submitted = bound.filter(receipt => receipt.cell.version === version && receipt.cell.mode === mode); - const tokens = submitted.flatMap(receipt => receipt.usage.inputTokens === null || receipt.usage.outputTokens === null ? [] : [receipt.usage.inputTokens + receipt.usage.outputTokens]); - const costs = submitted.flatMap(receipt => receipt.usage.estimatedCostUSD === null ? [] : [receipt.usage.estimatedCostUSD]); - groups.push({ version, mode, scheduled: expected.length, submitted: submitted.length, missing: expected.length - submitted.length, succeeded: submitted.filter(receipt => receipt.status === 'succeeded').length, failed: submitted.filter(receipt => receipt.status === 'failed').length, - latency: { samples: submitted.length, denominator: expected.length, p95Ms: quantile(submitted.map(receipt => receipt.durationMs), 0.95) }, - firstUsefulResult: { samples: 0, denominator: expected.length, p95Ms: null }, - modelTokens: { measured: tokens.length, denominator: expected.length, total: tokens.length ? tokens.reduce((sum, value) => sum + value, 0) : null }, - estimatedCost: { measured: costs.length, denominator: expected.length, totalUSD: costs.length ? costs.reduce((sum, value) => sum + value, 0) : null, source: 'pricing-table-estimate' }, - }); - } - const indexes: ProducerReceiptIndex[] = bound.map(({ output: _output, toolTimeline: _toolTimeline, error, ...receipt }) => ({ ...receipt, ...(error ? { error: { code: error.code } } : {}) })); - const base = { schemaVersion: 1 as const, matrixHash: matrixHash(matrix), scheduleHash: digest(JSON.stringify(schedule)), receipts: indexes.sort((left, right) => left.cell.id.localeCompare(right.cell.id)), summary: { - scheduled: matrix.cells.length, prepared: schedule.preparedCells, submitted: bound.length, missing: matrix.cells.length - bound.length, - matchedPairsExpected: expectedMatchedPairs(matrix), matchedPairsSubmitted: completePairs.length, modelMismatches, groups, - note: 'Costs are pricing-table estimates. First-useful timing is unmeasured because the reused provider adapters return completed runs. Trusted findings and runtime outcomes require separate oracle adjudication.', - }, ...(platformCatalogs ? { embeddedCatalogs: platformCatalogs } : {}) }; - return { ...base, batchHash: digest(JSON.stringify(base)) }; -} - -function normalizedPlatforms(corpus: EvalCorpusManifest, value: unknown): Record { - const assignment = value as Record; - if (!assignment || typeof assignment !== 'object' || Array.isArray(assignment) || Object.keys(assignment).length !== corpus.cases.length || - corpus.cases.some(fixture => !PRODUCER_PLATFORMS.includes(assignment[fixture.id]))) throw new Error('INVALID_EVAL_PLATFORMS'); - return Object.fromEntries(corpus.cases.map(fixture => [fixture.id, assignment[fixture.id]])); -} - -function buildEvalMatrix(options: EvalMatrixOptions, corpus: EvalCorpusManifest, baselineHash: string | null): EvalMatrix { - const profile = options.profile ?? 'full'; - const skillHashes: Partial> = options.skillHashes ?? {}; - const versions = profile === 'full' ? ['v2', 'v3'] : profile === 'release' ? ['v3'] : ['v2']; - if (!options.model?.trim() || !['claude', 'codex', 'gemini'].includes(options.host) || !['full', 'release', 'baseline'].includes(profile) || - Object.keys(skillHashes).sort().join(',') !== versions.join(',') || versions.some(version => !HEX.test(skillHashes[version as EvalVersion] ?? '')) || - (profile === 'full' && skillHashes.v2 === skillHashes.v3)) throw new Error('INVALID_MATCHED_EVAL_INPUT'); - const budgets = options.budgets ?? { daily: 600, comprehensive: 1800 }; - if (![budgets.daily, budgets.comprehensive].every(value => Number.isInteger(value) && value > 60 && value <= 3600)) throw new Error('INVALID_EVAL_BUDGET'); - const corpusHash = digest(JSON.stringify(corpus)); - const cells: EvalCell[] = []; - if (options.profile === undefined || options.profile === 'full') { - for (const fixture of corpus.cases) for (const variant of ['vulnerable', 'fixed'] as const) for (const mode of ['daily', 'comprehensive'] as const) for (const repetition of [1, 2, 3] as const) for (const version of ['v2', 'v3'] as const) { - const cell = { caseId: fixture.id, stack: fixture.stack, variant, version, mode, repetition, model: options.model, host: options.host, budgetSeconds: budgets[mode], sourceHash: fixture.filesHash[variant], skillHash: options.skillHashes[version] }; - cells.push({ id: digest(JSON.stringify(cell)), ...cell }); - } - return { schemaVersion: 1, corpusVersion: corpus.version, corpusHash, model: options.model, host: options.host, budgets, skillHashes: options.skillHashes, repetitions: 3, cells }; - } - const pinned = options as ReleaseEvalMatrixOptions | BaselineEvalMatrixOptions; - const platformKeys = pinned.profile === 'release' ? 'comprehensive,daily' : 'comprehensive'; - if (!pinned.platforms || Object.keys(pinned.platforms).sort().join(',') !== platformKeys) throw new Error('INVALID_EVAL_PLATFORMS'); - const comprehensive = normalizedPlatforms(corpus, pinned.platforms.comprehensive); - const daily = pinned.profile === 'release' ? pinned.platforms.daily : undefined; - if (pinned.profile === 'release' && !PRODUCER_PLATFORMS.includes(daily!)) throw new Error('INVALID_EVAL_PLATFORMS'); - const version: EvalVersion = pinned.profile === 'release' ? 'v3' : 'v2'; - const modes = pinned.profile === 'release' ? ['daily', 'comprehensive'] as const : ['comprehensive'] as const; - for (const fixture of corpus.cases) for (const variant of ['vulnerable', 'fixed'] as const) for (const mode of modes) { - const cell = { caseId: fixture.id, stack: fixture.stack, variant, version, mode, repetition: 1 as const, model: pinned.model, host: pinned.host, budgetSeconds: budgets[mode], sourceHash: fixture.filesHash[variant], skillHash: skillHashes[version]!, platform: mode === 'daily' ? daily! : comprehensive[fixture.id] }; - cells.push({ id: digest(JSON.stringify(cell)), ...cell }); - } - const common = { schemaVersion: 1 as const, corpusVersion: corpus.version, corpusHash, model: pinned.model, host: pinned.host, budgets }; - if (pinned.profile === 'release') { - if (baselineHash !== null && !HEX.test(baselineHash)) throw new Error('UNBOUND_EVAL_BASELINE'); - return { ...common, profile: 'release', skillHashes: { v3: pinned.skillHashes.v3 }, repetitions: 1, platforms: { daily: daily!, comprehensive }, baselineHash, cells }; - } - return { ...common, profile: 'baseline', skillHashes: { v2: pinned.skillHashes.v2 }, repetitions: 1, platforms: { comprehensive }, cells }; -} - -const BASELINE_FIELDS = 'baselineHash,budgetSeconds,cases,corpusHash,corpusVersion,host,matrixHash,model,modelUsed,platforms,producerBatchHash,provider,schemaVersion,skillHash,version'; -/** Check that a baseline was measured under the same corpus, model, host, budget and platform assignment. */ -function assertBaselineBinding(baseline: EvalBaseline, target: { corpus: EvalCorpusManifest; model: string; host: ProducerHost; budgetSeconds: number; platforms: Record }): void { - if (!baseline || typeof baseline !== 'object' || Object.keys(baseline).sort().join(',') !== BASELINE_FIELDS) throw new Error('UNBOUND_EVAL_BASELINE'); - const { baselineHash, ...record } = baseline; - const provider = baseline.provider as unknown as Record; - if (baseline.schemaVersion !== 1 || baseline.version !== 'v2' || !HEX.test(baselineHash) || digest(JSON.stringify(record)) !== baselineHash || - baseline.corpusVersion !== target.corpus.version || baseline.corpusHash !== digest(JSON.stringify(target.corpus)) || - baseline.model !== target.model || baseline.host !== target.host || baseline.budgetSeconds !== target.budgetSeconds || - JSON.stringify(baseline.platforms) !== JSON.stringify(target.platforms) || !HEX.test(baseline.skillHash) || !HEX.test(baseline.matrixHash) || - !HEX.test(baseline.producerBatchHash) || typeof baseline.modelUsed !== 'string' || !baseline.modelUsed || - !provider || typeof provider !== 'object' || Object.keys(provider).sort().join(',') !== 'family,policyRevision,version' || - !['claude', 'gpt', 'gemini'].includes(String(provider.family)) || typeof provider.policyRevision !== 'string' || !provider.policyRevision || - typeof provider.version !== 'string' || !provider.version || !Array.isArray(baseline.cases) || baseline.cases.length !== target.corpus.cases.length || - baseline.cases.some((entry, index) => !entry || Object.keys(entry).sort().join(',') !== 'caseId,found' || entry.caseId !== target.corpus.cases[index].id || typeof entry.found !== 'boolean')) - throw new Error('UNBOUND_EVAL_BASELINE'); -} - -export function createEvalMatrix(options: FullEvalMatrixOptions, corpus?: EvalCorpusManifest): FullEvalMatrix; -export function createEvalMatrix(options: ReleaseEvalMatrixOptions, corpus?: EvalCorpusManifest): ReleaseEvalMatrix; -export function createEvalMatrix(options: BaselineEvalMatrixOptions, corpus?: EvalCorpusManifest): BaselineEvalMatrix; -export function createEvalMatrix(options: EvalMatrixOptions, corpus: EvalCorpusManifest = loadCorpusManifest()): EvalMatrix { - let baselineHash: string | null = null; - if (options.profile === 'release' && options.baseline !== undefined) { - assertBaselineBinding(options.baseline, { corpus, model: options.model, host: options.host, budgetSeconds: (options.budgets ?? { comprehensive: 1800 }).comprehensive, platforms: normalizedPlatforms(corpus, options.platforms?.comprehensive) }); - baselineHash = options.baseline.baselineHash; - } - return buildEvalMatrix(options, corpus, baselineHash); -} - -export function validateMatrix(matrix: EvalMatrix, corpus: EvalCorpusManifest = loadCorpusManifest()): void { - if (!matrix || typeof matrix !== 'object') throw new Error('UNMATCHED_OR_INCOMPLETE_EVAL_MATRIX'); - const common = { model: matrix.model, host: matrix.host, budgets: matrix.budgets }; - let expected: EvalMatrix; - try { - expected = matrix.profile === 'release' ? buildEvalMatrix({ ...common, profile: 'release', skillHashes: matrix.skillHashes, platforms: matrix.platforms }, corpus, matrix.baselineHash) - : matrix.profile === 'baseline' ? buildEvalMatrix({ ...common, profile: 'baseline', skillHashes: matrix.skillHashes, platforms: matrix.platforms }, corpus, null) - : buildEvalMatrix({ ...common, skillHashes: matrix.skillHashes }, corpus, null); - } catch { throw new Error('UNMATCHED_OR_INCOMPLETE_EVAL_MATRIX'); } - if (JSON.stringify(matrix) !== JSON.stringify(expected)) throw new Error('UNMATCHED_OR_INCOMPLETE_EVAL_MATRIX'); -} -function validateResult(result: EvalResult, cell: EvalCell, corpus: EvalCorpusManifest): void { - if (result.sourceHash !== cell.sourceHash || result.skillHash !== cell.skillHash || result.model !== cell.model || result.host !== cell.host || result.budgetSeconds !== cell.budgetSeconds) throw new Error('UNMATCHED_EVAL_RESULT'); - for (const field of ['setup', 'reproduction', 'repair', 'recheck'] as const) if (!['passed', 'failed', 'blocked', 'not_attempted'].includes(result[field])) throw new Error('INVALID_EVAL_OUTCOME'); - for (const field of ['reportPresent', 'reportFinished', 'reportComplete', 'heldOutAssertionsPassed', 'freshRecheck'] as const) if (typeof result[field] !== 'boolean') throw new Error('INVALID_EVAL_RESULT'); - if (!Array.isArray(result.findings) || !validNumber(result.latencyMs) || (result.firstUsefulResultMs !== null && (!validNumber(result.firstUsefulResultMs) || result.firstUsefulResultMs > result.latencyMs))) throw new Error('INVALID_EVAL_RESULT'); - if ((result.reportComplete && !result.reportFinished) || (result.reportFinished && !result.reportPresent)) throw new Error('MISSING_EVAL_REPORT'); - if (!result.reportPresent && result.findings.length) throw new Error('FINDINGS_WITHOUT_REPORT'); - if (result.setup === 'blocked' && !result.prerequisite?.trim()) throw new Error('MISSING_SETUP_PREREQUISITE'); - if (result.oracleEvidenceHash !== undefined && (!HEX.test(result.oracleEvidenceHash) || result.oracleVersion !== corpus.version)) throw new Error('INVALID_ORACLE_PROVENANCE'); - if (result.currentSourceHash !== undefined && !HEX.test(result.currentSourceHash)) throw new Error('INVALID_RECHECK_SOURCE'); - if (result.recheckEvidenceHash !== undefined && !HEX.test(result.recheckEvidenceHash)) throw new Error('INVALID_RECHECK_EVIDENCE'); - if (result.usage && (result.usage.source !== 'host' || (result.usage.tokens !== undefined && !validNumber(result.usage.tokens)) || (result.usage.costUSD !== undefined && !validNumber(result.usage.costUSD)))) throw new Error('INVALID_EVAL_USAGE'); - if (result.producerReceiptHash !== undefined && !HEX.test(result.producerReceiptHash)) throw new Error('INVALID_PRODUCER_RECEIPT_PROVENANCE'); - const ids = new Set(), repairEvidence = new Set(), recheckEvidence = new Set(), replayEvidence = new Set(); - for (const finding of result.findings) { - if (!finding.id || ids.has(finding.id) || !['supported', 'hypothesis', 'legacy_review'].includes(finding.evidence) || !['correct', 'incidental', 'instrumentation', 'incorrect', 'unadjudicated'].includes(finding.judgment) || typeof finding.claimedTested !== 'boolean') throw new Error('INVALID_FINDING_JUDGMENT'); - ids.add(finding.id); - if (finding.judgment === 'correct' && (cell.variant !== 'vulnerable' || finding.matchedCaseId !== cell.caseId)) throw new Error('INVALID_ORACLE_MATCH'); - if ((finding.judgment === 'incidental' || finding.judgment === 'instrumentation') && (finding.evidence === 'hypothesis' || finding.matchedCaseId !== undefined)) throw new Error('INVALID_FINDING_JUDGMENT'); - if ((finding.judgment === 'incidental') !== (finding.incidentalKey !== undefined) || (finding.incidentalKey !== undefined && !HEX.test(finding.incidentalKey))) throw new Error('INVALID_FINDING_JUDGMENT'); - if (finding.trustedVerification !== undefined) { - const verification = finding.trustedVerification as Record, allowed = new Set(['repair', 'repairEvidenceHash', 'recheck', 'recheckEvidenceHash']); - if (!verification || typeof verification !== 'object' || Array.isArray(verification) || Object.keys(verification).some(key => !allowed.has(key)) || - !['passed', 'failed', 'blocked', 'not_attempted'].includes(String(verification.repair)) || - !['passed', 'failed', 'blocked', 'not_attempted'].includes(String(verification.recheck)) || !finding.claimedTested || cell.version !== 'v3' || cell.mode !== 'comprehensive') - throw new Error('INVALID_TRUSTED_FINDING_VERIFICATION'); - const repairHash = verification.repairEvidenceHash, recheckHash = verification.recheckEvidenceHash; - if (!(repairHash === undefined || (typeof repairHash === 'string' && HEX.test(repairHash))) || - !(recheckHash === undefined || (typeof recheckHash === 'string' && HEX.test(recheckHash))) || - (verification.repair === 'passed') !== (repairHash !== undefined) || - (verification.recheck === 'passed') !== (recheckHash !== undefined) || - (verification.recheck === 'passed' && verification.repair !== 'passed')) - throw new Error('INVALID_TRUSTED_FINDING_VERIFICATION'); - if (typeof repairHash === 'string') { - if (repairEvidence.has(repairHash)) throw new Error('DUPLICATE_TRUSTED_REPAIR_BINDING'); - repairEvidence.add(repairHash); - } - if (typeof recheckHash === 'string') { - if (recheckEvidence.has(recheckHash)) throw new Error('DUPLICATE_TRUSTED_RECHECK_BINDING'); - recheckEvidence.add(recheckHash); - } - } - if (finding.trustedReplay !== undefined) { - const replay = finding.trustedReplay as Record, hash = replay?.replayEvidenceHash; - if (!replay || typeof replay !== 'object' || Array.isArray(replay) || Object.keys(replay).some(key => key !== 'result' && key !== 'replayEvidenceHash') || - !['passed', 'failed', 'missing'].includes(String(replay.result)) || finding.judgment !== 'incidental' || !finding.claimedTested || - (replay.result === 'passed') !== (typeof hash === 'string' && HEX.test(hash)) || (replay.result !== 'passed' && hash !== undefined)) - throw new Error('INVALID_TRUSTED_REPLAY'); - if (typeof hash === 'string') { - if (replayEvidence.has(hash)) throw new Error('DUPLICATE_TRUSTED_REPLAY_BINDING'); - replayEvidence.add(hash); - } - } - } - if (cell.mode === 'daily' && [result.setup, result.reproduction, result.repair, result.recheck].some(value => value !== 'not_attempted')) throw new Error('DAILY_EVAL_EXECUTED_APPLICATION'); -} -function quantile(values: number[], fraction: number): number | null { - if (!values.length) return null; - return [...values].sort((left, right) => left - right)[Math.ceil(values.length * fraction) - 1]; -} -function measuredRate(cells: EvalCell[], results: Map, field: 'setup' | 'reproduction' | 'repair' | 'recheck', corpus: EvalCorpusManifest): Rate { - return rate(cells.filter(cell => { - const result = results.get(cell.id); - if (!result?.reportFinished || result[field] !== 'passed') return false; - if (field === 'setup') return true; - if (!result.oracleEvidenceHash || result.oracleVersion !== corpus.version || result.setup !== 'passed') return false; - if (field === 'reproduction') return true; - if (result.reproduction !== 'passed' || result.repair !== 'passed' || !result.heldOutAssertionsPassed) return false; - if (cell.version === 'v3' && !result.findings.some(finding => trustedFindingVerification(cell, result, finding, 'repair', corpus))) return false; - if (field === 'repair') return true; - // Correct alternative patches need not match the reference fix byte-for-byte. - // Closure needs a fresh source and a separate trusted current-source observation. - return result.freshRecheck && !!result.currentSourceHash && result.currentSourceHash !== cell.sourceHash && - !!result.recheckEvidenceHash && result.recheckEvidenceHash !== result.oracleEvidenceHash && - (cell.version !== 'v3' || result.findings.some(finding => trustedFindingVerification(cell, result, finding, 'recheck', corpus))); - }).length, cells.length); -} - -function trustedFindingVerification(cell: EvalCell, result: EvalResult, finding: EvalFinding, stage: 'repair' | 'recheck', corpus: EvalCorpusManifest): boolean { - const verification = finding.trustedVerification; - if (!result.reportFinished || cell.version !== 'v3' || cell.mode !== 'comprehensive' || cell.variant !== 'vulnerable' || finding.evidence !== 'supported' || - finding.judgment !== 'correct' || finding.matchedCaseId !== cell.caseId || !finding.claimedTested || !verification || - result.setup !== 'passed' || result.reproduction !== 'passed' || result.repair !== 'passed' || !result.heldOutAssertionsPassed || - verification.repair !== 'passed' || verification.repairEvidenceHash !== result.oracleEvidenceHash || result.oracleVersion !== corpus.version) - return false; - if (stage === 'repair') return true; - return result.recheck === 'passed' && verification.recheck === 'passed' && verification.recheckEvidenceHash === result.recheckEvidenceHash && - result.freshRecheck && !!result.currentSourceHash && result.currentSourceHash !== cell.sourceHash && - !!result.recheckEvidenceHash && result.recheckEvidenceHash !== result.oracleEvidenceHash; -} - -function validatedResults(matrix: EvalMatrix, observations: EvalResult[], corpus: EvalCorpusManifest): Map { - if (!Array.isArray(observations)) throw new Error('INVALID_EVAL_RESULTS'); - const cells = new Map(matrix.cells.map(cell => [cell.id, cell])); - const results = new Map(); - for (const result of observations) { - const cell = cells.get(result.cellId); - if (!cell || results.has(result.cellId)) throw new Error('UNKNOWN_OR_DUPLICATE_EVAL_RESULT'); - validateResult(result, cell, corpus); results.set(result.cellId, result); - } - return results; -} -const eligibleFinding = (cell: EvalCell, finding: EvalFinding) => finding.evidence === 'supported' || (cell.version === 'v2' && finding.evidence === 'legacy_review'); -const foundSeededIssue = (cell: EvalCell, result: EvalResult | undefined) => result?.reportFinished === true && - result.findings.some(finding => eligibleFinding(cell, finding) && finding.judgment === 'correct'); -/** - * A tested claim is false unless trusted evidence certifies it: the seeded repair's held-out verification, or, for an - * `incidental` finding, a passing replay of the helper's signed bundle. Claims on declared instrumentation count in - * neither direction (Garry, 2026-10-18, option 1), the same way precision leaves them out. - */ -const falselyTested = (cell: EvalCell, result: EvalResult, finding: EvalFinding, corpus: EvalCorpusManifest) => - finding.claimedTested && finding.judgment !== 'instrumentation' && !trustedFindingVerification(cell, result, finding, 'repair', corpus) && - !(finding.judgment === 'incidental' && finding.trustedReplay?.result === 'passed'); -const isHighCritical = (corpus: EvalCorpusManifest, caseId: string) => ['critical', 'high'].includes(corpus.cases.find(fixture => fixture.id === caseId)!.severity); - -/** High/critical recall of a pre-registered external baseline, after proving it binds to this release matrix. */ -function externalBaselineRecall(matrix: ReleaseEvalMatrix, baseline: EvalBaseline, corpus: EvalCorpusManifest): Rate { - if (matrix.baselineHash === null || baseline?.baselineHash !== matrix.baselineHash) throw new Error('UNBOUND_EVAL_BASELINE'); - assertBaselineBinding(baseline, { corpus, model: matrix.model, host: matrix.host, budgetSeconds: matrix.budgets.comprehensive, platforms: matrix.platforms.comprehensive }); - const highCritical = baseline.cases.filter(entry => isHighCritical(corpus, entry.caseId)); - return rate(highCritical.filter(entry => entry.found).length, highCritical.length); -} - -export function scoreEval(matrix: EvalMatrix, observations: EvalResult[], qualification: ReleaseQualification = { containment: {} }, corpus: EvalCorpusManifest = loadCorpusManifest(), baseline?: EvalBaseline) { - validateMatrix(matrix, corpus); - const profile = profileOf(matrix); - if (profile === 'baseline') throw new Error('BASELINE_PROFILE_NOT_QUALIFIABLE: use createEvalBaseline'); - if (profile !== 'release' && baseline !== undefined) throw new Error('UNBOUND_EVAL_BASELINE'); - const results = validatedResults(matrix, observations, corpus); - const found = (cell: EvalCell) => foundSeededIssue(cell, results.get(cell.id)); - const groups: any[] = []; - for (const [version, mode] of PROFILE_GROUPS[profile]) { - const selected = matrix.cells.filter(cell => cell.version === version && cell.mode === mode); - const completed = selected.map(cell => results.get(cell.id)).filter((result): result is EvalResult => !!result); - const expected = selected.filter(cell => cell.variant === 'vulnerable'); - const highCritical = expected.filter(cell => isHighCritical(corpus, cell.caseId)); - let correct = 0, reported = 0, unadjudicated = 0; - for (const cell of selected) { - const result = results.get(cell.id); - const findings = result?.reportFinished ? result.findings.filter(finding => finding.evidence !== 'hypothesis' && finding.judgment !== 'instrumentation') : []; - reported += findings.length; - unadjudicated += findings.filter(finding => finding.judgment === 'unadjudicated').length; - correct += Number(findings.some(finding => eligibleFinding(cell, finding) && finding.judgment === 'correct')); // Duplicate reports do not increase true positives. - correct += new Set(findings.filter(finding => eligibleFinding(cell, finding) && finding.judgment === 'incidental').map(finding => finding.incidentalKey)).size; - } - const firstUseful = completed.flatMap(result => result.firstUsefulResultMs === null ? [] : [result.firstUsefulResultMs]); - const costs = completed.flatMap(result => result.usage?.costUSD === undefined ? [] : [result.usage.costUSD]); - const tokens = completed.flatMap(result => result.usage?.tokens === undefined ? [] : [result.usage.tokens]); - const falseTested = selected.reduce((count, cell) => { - const result = results.get(cell.id); if (!result) return count; - return count + result.findings.filter(finding => falselyTested(cell, result, finding, corpus)).length; - }, 0); - groups.push({ version, mode, cells: selected.length, submitted: completed.length, missing: selected.length - completed.length, - reports: rate(completed.filter(result => result.reportPresent && result.reportComplete).length, selected.length), finishedReports: rate(completed.filter(result => result.reportFinished).length, selected.length), precision: rate(correct, reported), recall: rate(expected.filter(found).length, expected.length), highCriticalRecall: rate(highCritical.filter(found).length, highCritical.length), - unadjudicated, falseTested, setup: mode === 'comprehensive' ? measuredRate(selected, results, 'setup', corpus) : null, - reproduction: mode === 'comprehensive' ? measuredRate(expected, results, 'reproduction', corpus) : null, - repair: mode === 'comprehensive' ? measuredRate(expected, results, 'repair', corpus) : null, - recheck: mode === 'comprehensive' ? measuredRate(expected, results, 'recheck', corpus) : null, - setupBlocked: completed.filter(result => result.setup === 'blocked').length, - firstUsefulResult: { samples: firstUseful.length, denominator: selected.length, medianMs: quantile(firstUseful, 0.5), p95Ms: quantile(firstUseful, 0.95) }, - latency: { samples: completed.length, p95Ms: quantile(completed.map(result => result.latencyMs), 0.95) }, - cost: { measured: costs.length, denominator: selected.length, totalUSD: costs.length ? costs.reduce((sum, cost) => sum + cost, 0) : null }, - modelTokens: { measured: tokens.length, denominator: selected.length, total: tokens.length ? tokens.reduce((sum, count) => sum + count, 0) : null }, - }); - } - const daily = groups.find(group => group.version === 'v3' && group.mode === 'daily'); - const comprehensive = groups.find(group => group.version === 'v3' && group.mode === 'comprehensive'); - const inBatchBaseline = groups.find(group => group.version === 'v2' && group.mode === 'comprehensive'); - const external = matrix.profile === 'release' && baseline !== undefined ? externalBaselineRecall(matrix, baseline, corpus) : null; - const perStack = Object.fromEntries(STACKS.map(stack => { - const eligible = matrix.cells.filter(cell => cell.version === 'v3' && cell.mode === 'comprehensive' && cell.variant === 'vulnerable' && cell.stack === stack); - // A repaired oracle case demonstrates the full find-to-repair workflow only - // when the producer also reported the matching supported finding. - const successful = new Set(eligible.filter(cell => { - const result = results.get(cell.id); - return result?.findings.some(finding => trustedFindingVerification(cell, result, finding, 'repair', corpus)); - }).map(cell => cell.caseId)); - return [stack, { correctHeldOutRepairs: successful.size, denominator: new Set(eligible.map(cell => cell.caseId)).size }]; - })); - const assessedAll = observations.length === matrix.cells.length && observations.every(result => result.reportFinished) && groups.every(group => !group.unadjudicated); - const gate = (condition: boolean | null, hasData: boolean): 'pass' | 'fail' | 'unmeasured' => !hasData || condition === null ? 'unmeasured' : condition ? 'pass' : 'fail'; - const containmentValues = REQUIRED_CONTAINMENT.map(name => qualification.containment?.[name]); - if (containmentValues.some(value => value !== undefined && !['passed', 'failed', 'not_run'].includes(value))) throw new Error('INVALID_CONTAINMENT_RESULT'); - const gates = { - matchedCompleteMatrix: gate(assessedAll, observations.length > 0), - mandatoryReports: gate(groups.every(group => group.finishedReports.numerator === group.finishedReports.denominator), observations.length === matrix.cells.length), - dailyPrecision95: gate(daily.precision.value === null ? null : daily.precision.value >= 0.95, daily.submitted === daily.cells && !daily.unadjudicated), - comprehensiveHighCriticalRecall80: gate(comprehensive.highCriticalRecall.value >= 0.8, comprehensive.submitted === comprehensive.cells && !comprehensive.unadjudicated), - noHighCriticalRecallRegression: profile === 'full' - ? gate(comprehensive.highCriticalRecall.value >= inBatchBaseline.highCriticalRecall.value, comprehensive.submitted === comprehensive.cells && inBatchBaseline.submitted === inBatchBaseline.cells && !comprehensive.unadjudicated && !inBatchBaseline.unadjudicated) - : gate(external === null ? null : comprehensive.highCriticalRecall.value >= external.value!, comprehensive.submitted === comprehensive.cells && !comprehensive.unadjudicated && external !== null), - allCoreColdStarts: gate(comprehensive.setup.numerator === comprehensive.setup.denominator, comprehensive.submitted === comprehensive.cells), - zeroFalselyTestedRepairs: gate(comprehensive.falseTested === 0 && daily.falseTested === 0, comprehensive.submitted === comprehensive.cells && daily.submitted === daily.cells), - heldOutRepairEachStack: gate(Object.values(perStack).every(value => value.correctHeldOutRepairs >= 1), comprehensive.submitted === comprehensive.cells), - containmentAndCanaries: containmentValues.includes('failed') ? 'fail' as const : containmentValues.every(value => value === 'passed') ? 'pass' as const : 'unmeasured' as const, - }; - return { schemaVersion: 1, corpusVersion: corpus.version, model: matrix.model, host: matrix.host, - ...(profile === 'release' ? { profile, baseline: external === null ? null : { baselineHash: baseline!.baselineHash, highCriticalRecall: external } } : {}), - status: Object.values(gates).every(value => value === 'pass') ? 'qualified' : observations.length ? 'partial' : 'unmeasured', groups, perStack, gates, - notes: ['Missing and setup-blocked supported scenarios remain in recall and workflow denominators.', 'Costs and tokens come only from host-reported usage; wall-clock budgets are not model-spend caps.', 'Oracle judgments and qualification receipts must come from the trusted evaluator, never producing agents.'] }; -} - -/** Bind a complete collected batch and every trusted judgment to the matrix's producer receipts. */ -/** Validate the batch against its judgments; a failed producer receipt's report counts nothing, whatever the judge read. */ -function validateCollectedBatch(matrix: EvalMatrix, batch: ProducerBatch, observations: EvalResult[]): EvalResult[] { - if (!Array.isArray(observations)) throw new Error('INVALID_EVAL_RESULTS'); - if (!batch || batch.schemaVersion !== 1 || batch.matrixHash !== matrixHash(matrix) || !HEX.test(batch.scheduleHash) || !HEX.test(batch.batchHash)) throw new Error('INVALID_PRODUCER_BATCH'); - const { batchHash, ...withoutHash } = batch; - const pairs = expectedMatchedPairs(matrix); - if (digest(JSON.stringify(withoutHash)) !== batchHash || !Array.isArray(batch.receipts) || batch.receipts.length !== matrix.cells.length || batch.summary.scheduled !== matrix.cells.length || batch.summary.prepared !== matrix.cells.length || batch.summary.submitted !== matrix.cells.length || batch.summary.missing !== 0 || batch.summary.matchedPairsExpected !== pairs || batch.summary.matchedPairsSubmitted !== pairs || batch.summary.modelMismatches.length !== 0) throw new Error('INCOMPLETE_PRODUCER_BATCH'); - const cells = new Map(matrix.cells.map(cell => [cell.id, cell])); - const receipts = new Map(); - for (const receipt of batch.receipts) { - const cell = cells.get(receipt?.cellRef); - if (!cell || receipts.has(cell.id)) throw new Error('INVALID_PRODUCER_BATCH'); - validateReceiptIndex(receipt, cell); receipts.set(cell.id, receipt); - } - assertPlatformIdentities(batch.receipts, batch.embeddedCatalogs); - if (profileOf(matrix) === 'full') { - const actualModels = new Map>>(); - for (const receipt of batch.receipts) { - const key = matchedPairKey(receipt.cell as EvalCell), pair = actualModels.get(key) ?? {}; - pair[receipt.cell.version] = receipt.modelUsed; actualModels.set(key, pair); - } - if (actualModels.size !== pairs || [...actualModels.values()].some(pair => !pair.v2 || !pair.v3 || pair.v2 !== pair.v3)) throw new Error('UNMATCHED_EFFECTIVE_MODELS'); - } else if (new Set(batch.receipts.map(receipt => receipt.modelUsed)).size !== 1) throw new Error('UNMATCHED_EFFECTIVE_MODELS'); - for (const result of observations) { - const receipt = receipts.get(result.cellId); - if (!receipt || result.producerReceiptHash !== receipt.receiptHash) throw new Error('UNBOUND_EVAL_RESULT'); - } - return observations.map(result => receipts.get(result.cellId)!.status === 'failed' ? { ...result, reportFinished: false, reportComplete: false } : result); -} - -/** Release scoring path: every trusted judgment must bind to a collected producer receipt. */ -export function scoreCollectedEval(matrix: EvalMatrix, batch: ProducerBatch, observations: EvalResult[], qualification: ReleaseQualification = { containment: {} }, corpus: EvalCorpusManifest = loadCorpusManifest(), baseline?: EvalBaseline) { - validateMatrix(matrix, corpus); - if (profileOf(matrix) === 'baseline') throw new Error('BASELINE_PROFILE_NOT_QUALIFIABLE: use createEvalBaseline'); - const counted = validateCollectedBatch(matrix, batch, observations); - if (baseline !== undefined) { - const { modelUsed, providerIdentity: { family, policyRevision, version } } = batch.receipts[0]; - if (baseline?.modelUsed !== modelUsed || JSON.stringify(baseline?.provider) !== JSON.stringify({ family, policyRevision, version })) throw new Error('UNBOUND_EVAL_BASELINE'); - } - const score = scoreEval(matrix, counted, qualification, corpus, baseline); - return { ...score, producerBatchHash: batch.batchHash }; -} - -/** - * Turn a complete, fully adjudicated v2 baseline run into a reusable record. - * Missing reports, and reports behind a failed producer receipt, count as misses; an incomplete or unadjudicated run is refused. - */ -export function createEvalBaseline(matrix: BaselineEvalMatrix, batch: ProducerBatch, observations: EvalResult[], corpus: EvalCorpusManifest = loadCorpusManifest()): EvalBaseline { - if (matrix?.profile !== 'baseline') throw new Error('INVALID_EVAL_BASELINE_MATRIX'); - validateMatrix(matrix, corpus); - const results = validatedResults(matrix, validateCollectedBatch(matrix, batch, observations), corpus); - if (results.size !== matrix.cells.length) throw new Error('INCOMPLETE_EVAL_BASELINE'); - if ([...results.values()].some(result => result.reportFinished && result.findings.some(finding => finding.evidence !== 'hypothesis' && finding.judgment === 'unadjudicated'))) throw new Error('UNADJUDICATED_EVAL_BASELINE'); - const vulnerable = new Map(matrix.cells.filter(cell => cell.variant === 'vulnerable').map(cell => [cell.caseId, cell])); - const { modelUsed, providerIdentity: { family, policyRevision, version } } = batch.receipts[0]; - const record: Omit = { - schemaVersion: 1, version: 'v2', corpusVersion: corpus.version, corpusHash: matrix.corpusHash, model: matrix.model, host: matrix.host, - budgetSeconds: matrix.budgets.comprehensive, skillHash: matrix.skillHashes.v2, platforms: matrix.platforms.comprehensive, - matrixHash: matrixHash(matrix), producerBatchHash: batch.batchHash, modelUsed, provider: { family, policyRevision, version }, - cases: corpus.cases.map(fixture => ({ caseId: fixture.id, found: foundSeededIssue(vulnerable.get(fixture.id)!, results.get(vulnerable.get(fixture.id)!.id)) })), - }; - return { ...record, baselineHash: digest(JSON.stringify(record)) }; -} - -function splitFlags(args: string[], allowed: string[]): { positional: string[]; flags: Record } { - const positional: string[] = [], flags: Record = {}; - for (let index = 0; index < args.length; index++) { - if (!args[index].startsWith('--')) { positional.push(args[index]); continue; } - if (!allowed.includes(args[index]) || !args[index + 1] || flags[args[index]]) throw new Error(`Unsupported or repeated flag: ${args[index]}`); - flags[args[index]] = args[++index]; - } - return { positional, flags }; -} - -function cli(args: string[]): void { - const [command, ...rest] = args; - if (command === 'payload') { - if (rest.length !== 6 || rest[0] !== '--version' || !['v2', 'v3'].includes(rest[1]) || rest[2] !== '--skill-dir' || rest[4] !== '--output') throw new Error('Usage: cso-eval payload --version --skill-dir --output '); - const payload = loadPortableSkillPayload(rest[1] as EvalVersion, rest[3]); - const target = resolve(rest[5]), parent = dirname(target), stat = lstatSync(parent); - if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(parent) !== parent) throw new Error('UNSAFE_EVAL_DESTINATION'); - atomicWriteSync(target, payload, { mode: 0o600, noReplace: true }); - console.log(JSON.stringify({ version: rest[1], files: validatePortableSkillPayload(payload).files.length, sha256: sha256(payload), output: target, paidCalls: 0 })); return; - } - if (command === 'materialize') { - if (rest.length !== 3 || !['vulnerable', 'fixed'].includes(rest[1])) throw new Error('Usage: cso-eval materialize '); - console.log(JSON.stringify(materializeCase(rest[0], rest[1] as EvalVariant, rest[2]), null, 2)); return; - } - if (command === 'matrix') { - const values: Record = {}; - for (let index = 0; index < rest.length; index += 2) { - if (!['--model', '--host', '--v2-payload', '--v3-payload', '--output'].includes(rest[index]) || !rest[index + 1] || values[rest[index]]) throw new Error('Usage: cso-eval matrix --model --host --v2-payload --v3-payload --output '); - values[rest[index]] = rest[index + 1]; - } - if (Object.keys(values).length !== 5) throw new Error('All matrix flags are required; exact portable skill payloads and model identity must be pinned.'); - const payloads = { v2: readBoundedStable(resolve(values['--v2-payload']), PORTABLE_PAYLOAD_LIMIT, 'v2 portable skill payload').toString('utf8'), v3: readBoundedStable(resolve(values['--v3-payload']), PORTABLE_PAYLOAD_LIMIT, 'v3 portable skill payload').toString('utf8') }; - validatePortableSkillPayload(payloads.v2, 'v2'); validatePortableSkillPayload(payloads.v3, 'v3'); - const matrix = createEvalMatrix({ model: values['--model'], host: values['--host'] as ProducerHost, skillHashes: { v2: digest(payloads.v2), v3: digest(payloads.v3) } }); - safeWriteNew(values['--output'], matrix); console.log(JSON.stringify({ cells: matrix.cells.length, output: values['--output'], paidCalls: 0 })); return; - } - if (command === 'prepare') { - if (rest.length !== 7 || rest[1] !== '--v2-payload' || rest[3] !== '--v3-payload' || rest[5] !== '--output') throw new Error('Usage: cso-eval prepare --v2-payload --v3-payload --output '); - const matrix = readJsonBounded(rest[0], 16 * 1024 * 1024, 'evaluation matrix') as EvalMatrix; - const schedule = prepareEvalJobs(matrix, { v2: readBoundedStable(resolve(rest[2]), PORTABLE_PAYLOAD_LIMIT, 'v2 portable skill payload').toString('utf8'), v3: readBoundedStable(resolve(rest[4]), PORTABLE_PAYLOAD_LIMIT, 'v3 portable skill payload').toString('utf8') }, rest[6]); - console.log(JSON.stringify({ scheduled: schedule.scheduledCells, prepared: schedule.preparedCells, output: resolve(rest[6]), paidCalls: 0 })); return; - } - const { positional, flags } = splitFlags(rest, ['--corpus-manifest', '--baseline']); - const corpus = flags['--corpus-manifest'] ? validateCorpusManifest(readJsonBounded(flags['--corpus-manifest'], 16 * 1024 * 1024, 'corpus manifest')) : loadCorpusManifest(); - if (command === 'collect') { - if (positional.length !== 4 || flags['--baseline']) throw new Error('Usage: cso-eval collect [--corpus-manifest ]'); - const [matrixPath, schedulePath, receiptDirectory, output] = positional; - const matrix = readJsonBounded(matrixPath, 16 * 1024 * 1024, 'evaluation matrix') as EvalMatrix; - const schedule = readJsonBounded(schedulePath, 16 * 1024 * 1024, 'evaluation schedule') as PreparedEvalSchedule; - const receiptRoot = resolve(receiptDirectory), stat = lstatSync(receiptRoot); - if (!stat.isDirectory() || stat.isSymbolicLink() || realpathSync(receiptRoot) !== receiptRoot) throw new Error('UNSAFE_RECEIPT_DIRECTORY'); - const receipts: ProducerReceipt[] = []; - for (const entry of readdirSync(receiptRoot, { withFileTypes: true })) { - if (!entry.isFile() || entry.isSymbolicLink() || !/^[a-f0-9]{64}\.json$/.test(entry.name)) throw new Error('UNSAFE_RECEIPT_DIRECTORY'); - receipts.push(readJsonBounded(join(receiptRoot, entry.name), 40 * 1024 * 1024, 'producer receipt')); - } - const batch = collectProducerReceipts(matrix, schedule, receipts, corpus); - safeWriteNew(resolve(output), batch); - console.log(JSON.stringify({ output: resolve(output), submitted: batch.summary.submitted, missing: batch.summary.missing, modelMismatches: batch.summary.modelMismatches.length, paidCalls: 0 })); return; - } - if (command === 'score') { - if (positional.length < 3 || positional.length > 4) throw new Error('Usage: cso-eval score [qualification.json] [--corpus-manifest ] [--baseline ]'); - const baseline = flags['--baseline'] ? readJsonBounded(flags['--baseline'], 4 * 1024 * 1024, 'evaluation baseline') as EvalBaseline : undefined; - console.log(JSON.stringify(scoreCollectedEval(readJsonBounded(positional[0], 16 * 1024 * 1024, 'evaluation matrix'), readJsonBounded(positional[1], 16 * 1024 * 1024, 'producer batch'), readJsonBounded(positional[2], 64 * 1024 * 1024, 'trusted results'), positional[3] ? readJsonBounded(positional[3], 4 * 1024 * 1024, 'qualification') : undefined, corpus, baseline), null, 2)); return; - } - if (command === 'baseline') { - if (positional.length !== 4 || flags['--baseline']) throw new Error('Usage: cso-eval baseline [--corpus-manifest ]'); - const baseline = createEvalBaseline(readJsonBounded(positional[0], 16 * 1024 * 1024, 'evaluation matrix'), readJsonBounded(positional[1], 16 * 1024 * 1024, 'producer batch'), readJsonBounded(positional[2], 64 * 1024 * 1024, 'trusted results'), corpus); - safeWriteNew(resolve(positional[3]), baseline); - console.log(JSON.stringify({ output: resolve(positional[3]), baselineHash: baseline.baselineHash, paidCalls: 0 })); return; - } - throw new Error('Usage: cso-eval '); -} -if (import.meta.main) { try { cli(process.argv.slice(2)); } catch (error) { console.error(error instanceof Error ? error.message : 'CSO evaluation failed'); process.exitCode = 1; } } diff --git a/scripts/cso-native-evidence.ts b/scripts/cso-native-evidence.ts deleted file mode 100644 index d7c0f67e0..000000000 --- a/scripts/cso-native-evidence.ts +++ /dev/null @@ -1,131 +0,0 @@ -#!/usr/bin/env -S bun --no-env-file --config=/dev/null -/** Derive native runtime gate evidence from the named Docker tests that actually executed and passed. */ -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import { sha256 } from '../lib/cso/contracts'; -import type { ImageBuildRow } from './cso-image-matrix'; -import { requiredChecks } from './cso-runtime-promotion'; - -type Stack = ImageBuildRow['stack']; -export interface TestRef { file: string; name: string } -export interface JUnitCase extends TestRef { status: 'passed' | 'failed' | 'skipped'; assertions: number } - -const MAX_REPORT_BYTES = 4 * 1024 * 1024; -const DOCKER = 'test/cso-docker-integration.test.ts'; -const CONTAINMENT: TestRef[] = [ - { file: DOCKER, name: 'hard fails when local daemon enforcement prerequisites are absent' }, - { file: DOCKER, name: 'rejects image-declared writable volumes before container creation' }, - { file: DOCKER, name: 'shares only loopback while denying egress, privileges, and daemon logs, and reads private source/policy mounts' }, - { file: DOCKER, name: 'machine-wide admission allows only two groups per endpoint' }, -]; -const STAGED: TestRef = { file: DOCKER, name: 'staged runtime executes its trusted verifier and checks every declared tool version' }; -const NODE_LIFECYCLE: TestRef = { - file: 'test/cso-node-lifecycle-integration.test.ts', - name: 'finds, reproduces, bundles, replays, and closes against current source through the command dispatcher', -}; -const COLD_JOURNEY: TestRef = { - file: 'test/cso-stack-cold-integration.test.ts', - name: 'acquires, prepares, boots, controls, and tests the requested staged stack with no target egress', -}; - -/** Each native check key names the tests whose execution proves it for one stack. */ -export function nativeTestRequirements(stack: Stack): Record { - if (stack === 'postgresql') return { - containmentPassed: [...CONTAINMENT, STAGED], - coldStartPassed: [STAGED], - multiDatabasePassed: [STAGED], - readinessPassed: [STAGED], - }; - const journey = stack === 'node' ? NODE_LIFECYCLE : COLD_JOURNEY; - const application = { - containmentPassed: [...CONTAINMENT, STAGED], - coldStartPassed: [journey], - positiveNegativeAssertionsPassed: [STAGED], - acquisitionPublicOnlyPassed: [journey], - offlineLifecyclePassed: [journey], - }; - return stack === 'rails' - ? { ...application, railsSqlitePassed: [COLD_JOURNEY], railsPostgresqlPassed: [COLD_JOURNEY], nativeExtensionsPassed: [COLD_JOURNEY] } - : application; -} - -function decode(value: string): string { - return value.replace(/&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);/g, (_, entity: string) => { - if (entity.startsWith('#x')) return String.fromCodePoint(Number.parseInt(entity.slice(2), 16)); - if (entity.startsWith('#')) return String.fromCodePoint(Number.parseInt(entity.slice(1), 10)); - return { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" }[entity]!; - }); -} - -/** Parse the testcases of Bun's `--reporter=junit` output. */ -export function parseJUnit(xml: string): JUnitCase[] { - if (!/^<\?xml[^>]*\?>\s*]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g)) { - const attributes = Object.fromEntries([...match[1].matchAll(/([A-Za-z_:][\w:.-]*)="([^"]*)"/g)].map(([, key, value]) => [key, decode(value)])); - const body = match[2] ?? ''; - const status = /<(?:failure|error)\b/.test(body) ? 'failed' : / { - const clean = cases.some(item => item.status === 'passed') && !cases.some(item => item.status === 'failed'); - const passed = (ref: TestRef) => { - const matches = cases.filter(item => item.file === ref.file && item.name === ref.name); - return matches.length === 1 && matches[0].status === 'passed' && matches[0].assertions > 0; - }; - return Object.fromEntries(Object.entries(nativeTestRequirements(stack)) - .map(([key, refs]) => [key, clean && refs.every(passed)])); -} - -/** Native evidence for one staged row; private checks are every required release gate the native job cannot prove. */ -export function nativeEvidence(staged: unknown, stack: Stack, platform: string, report: string): Record { - const record = staged as Record; - if (!record || typeof record !== 'object' || record.state !== 'staged' || record.stack !== stack || record.platform !== platform) { - throw new Error('STAGED_EVIDENCE_MISMATCH'); - } - const required = requiredChecks(stack); - const nativeChecks = deriveNativeChecks(stack, parseJUnit(report)); - const failed = Object.entries(nativeChecks).filter(([key, value]) => !value || !required.includes(key)).map(([key]) => key); - if (failed.length) throw new Error(`NATIVE_GATE_NOT_PASSED: ${failed.sort().join(', ')}`); - return { - ...record, - state: 'native-gates-passed', - nativeChecks, - nativeTestReport: `sha256:${sha256(report)}`, - privateChecks: Object.fromEntries(required.filter(key => !(key in nativeChecks)).map(key => [key, 'pending'])), - qualified: false, - promotion: 'prohibited until authenticated private qualification evidence completes every release gate', - }; -} - -function readFile(file: string): string { - const stat = fs.lstatSync(path.resolve(file)); - if (!stat.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > MAX_REPORT_BYTES) throw new Error('UNSAFE_NATIVE_EVIDENCE_INPUT'); - return fs.readFileSync(path.resolve(file), 'utf8'); -} - -if (import.meta.main) { - try { - const args = process.argv.slice(2); - const names = ['--stack', '--platform', '--junit', '--staged', '--output']; - if (args.length !== names.length * 2 || names.some((name, index) => args[index * 2] !== name)) { - throw new Error('Usage: cso-native-evidence.ts --stack STACK --platform PLATFORM --junit REPORT.xml --staged staged-image.json --output EVIDENCE.json'); - } - const [stack, platform, junit, staged, output] = names.map((_, index) => args[index * 2 + 1]); - if (!['node', 'bun', 'python', 'rails', 'postgresql'].includes(stack)) throw new Error('INVALID_STACK'); - const evidence = nativeEvidence(JSON.parse(readFile(staged)), stack as Stack, platform, readFile(junit)); - fs.writeFileSync(path.resolve(output), JSON.stringify(evidence, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); - } catch (error) { - process.stderr.write((error instanceof Error ? error.message : 'NATIVE_EVIDENCE_FAILED') + '\n'); - process.exitCode = 1; - } -} diff --git a/scripts/cso-public-ghcr.ts b/scripts/cso-public-ghcr.ts deleted file mode 100644 index 14ac022d8..000000000 --- a/scripts/cso-public-ghcr.ts +++ /dev/null @@ -1,262 +0,0 @@ -#!/usr/bin/env -S bun --no-env-file --config=/dev/null -/** Release-only proof that a CSO image is public and anonymously pullable. */ -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; - -const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; -const DIGEST = /^sha256:[a-f0-9]{64}$/; -const PLATFORM = /^linux\/(amd64|arm64)$/; -const RUNTIME = /^(node|bun|python|rails|postgresql)-(amd64|arm64)$/; -const SCANNER = /^(gitleaks|osv|semgrep|zizmor|trivy|schemathesis)-(amd64|arm64)$/; -const MAX_HTTP_BYTES = 64 * 1024; -const MAX_DOCKER_OUTPUT = 64 * 1024; -const DOCKER_TIMEOUT_MS = 10 * 60 * 1000; - -export interface PublicGhcrTarget { - image: string; - owner: string; - repository: string; - packageName: string; - digest: string; - platform: 'linux/amd64' | 'linux/arm64'; -} - -export interface PublicImageProof { - schemaVersion: 1; - image: string; - platform: 'linux/amd64' | 'linux/arm64'; - packageName: string; - packageVisibility: 'public'; - packageApiUrl: string; - anonymousPull: 'passed'; - dockerConfig: 'isolated-empty-auths'; - verifiedAt: string; -} - -interface CommandResult { exitCode: number; stdout: string; stderr: string } -export interface PublicGhcrDependencies { - fetch: typeof globalThis.fetch; - githubToken: string; - dockerPath: string; - runDocker: (args: string[], env: Record) => Promise; - now: () => string; - sleep: (ms: number) => Promise; -} - -function fail(message: string): never { throw new Error(message); } - -export function parsePublicGhcrTarget(image: string, platform: string, githubRepository: string): PublicGhcrTarget { - if (!REPOSITORY.test(githubRepository)) fail('INVALID_GITHUB_REPOSITORY'); - const platformMatch = PLATFORM.exec(platform); - if (!platformMatch) fail('INVALID_PUBLIC_IMAGE_PLATFORM'); - const normalizedRepository = githubRepository.toLowerCase(); - const prefix = `ghcr.io/${normalizedRepository}/`; - if (!image.startsWith(prefix)) fail('PUBLIC_IMAGE_REPOSITORY_MISMATCH'); - const at = image.lastIndexOf('@'); - if (at < prefix.length || image.indexOf('@') !== at) fail('PUBLIC_IMAGE_MUST_BE_DIGEST_PINNED'); - const suffix = image.slice(prefix.length, at), digest = image.slice(at + 1); - if (!DIGEST.test(digest)) fail('PUBLIC_IMAGE_MUST_BE_DIGEST_PINNED'); - const [namespace, name, extra] = suffix.split('/'); - if (extra || !name || !['cso-staging', 'cso-scanners'].includes(namespace)) fail('INVALID_PUBLIC_IMAGE_PACKAGE'); - const nameMatch = namespace === 'cso-staging' ? RUNTIME.exec(name) : SCANNER.exec(name); - if (!nameMatch || nameMatch[2] !== platformMatch[1]) fail('PUBLIC_IMAGE_PLATFORM_MISMATCH'); - const [owner, repository] = normalizedRepository.split('/'); - return { - image, - owner, - repository, - packageName: `${repository}/${namespace}/${name}`, - digest, - platform: platform as PublicGhcrTarget['platform'], - }; -} - -async function responseJson(response: Response, label: string): Promise> { - const body = await response.text(); - if (body.length > MAX_HTTP_BYTES) fail(`${label}_RESPONSE_TOO_LARGE`); - let parsed: unknown; - try { parsed = JSON.parse(body); } catch { fail(`${label}_INVALID_RESPONSE`); } - if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) fail(`${label}_INVALID_RESPONSE`); - return parsed as Record; -} - -function publicHeaders(githubToken: string): Record { - return { - Accept: 'application/vnd.github+json', - Authorization: `Bearer ${githubToken}`, - 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': 'gstack-cso-public-image-verifier', - }; -} - -export function assertPublicPackageMetadata(value: Record, target: PublicGhcrTarget): void { - const owner = value.owner; - if (value.name !== target.packageName || value.package_type !== 'container' || value.visibility !== 'public' || - !owner || typeof owner !== 'object' || Array.isArray(owner) || - typeof (owner as Record).login !== 'string' || - ((owner as Record).login as string).toLowerCase() !== target.owner) { - fail('GHCR_PACKAGE_IS_NOT_PUBLIC'); - } -} - -async function publicPackageApi(target: PublicGhcrTarget, deps: PublicGhcrDependencies): Promise { - const ownerUrl = `https://api.github.com/users/${encodeURIComponent(target.owner)}`; - const ownerResponse = await deps.fetch(ownerUrl, { headers: publicHeaders(deps.githubToken), redirect: 'error', signal: AbortSignal.timeout(15_000) }); - if (ownerResponse.status !== 200) fail(`PUBLIC_OWNER_LOOKUP_FAILED: HTTP ${ownerResponse.status}`); - const owner = await responseJson(ownerResponse, 'PUBLIC_OWNER_LOOKUP'); - if (typeof owner.login !== 'string' || owner.login.toLowerCase() !== target.owner || !['User', 'Organization'].includes(String(owner.type))) { - fail('PUBLIC_OWNER_LOOKUP_IDENTITY_MISMATCH'); - } - const collection = owner.type === 'Organization' ? 'orgs' : 'users'; - const packageUrl = `https://api.github.com/${collection}/${encodeURIComponent(target.owner)}/packages/container/${encodeURIComponent(target.packageName)}`; - let lastStatus = 0; - for (let attempt = 1; attempt <= 6; attempt++) { - const response = await deps.fetch(packageUrl, { headers: publicHeaders(deps.githubToken), redirect: 'error', signal: AbortSignal.timeout(15_000) }); - lastStatus = response.status; - if (response.status === 200) { - assertPublicPackageMetadata(await responseJson(response, 'PUBLIC_PACKAGE_LOOKUP'), target); - return packageUrl; - } - await response.body?.cancel(); - if (attempt < 6 && [404, 429, 500, 502, 503, 504].includes(response.status)) await deps.sleep(attempt * 2_000); - else break; - } - fail(`GHCR_PACKAGE_IS_NOT_PUBLIC: authenticated GitHub Packages metadata lookup returned HTTP ${lastStatus}`); -} - -function cleanDockerEnvironment(configRoot: string, dockerHost: string): Record { - return { - HOME: configRoot, - DOCKER_CONFIG: configRoot, - DOCKER_HOST: dockerHost, - LANG: 'C.UTF-8', - LC_ALL: 'C.UTF-8', - PATH: '/usr/local/bin:/usr/bin:/bin', - TMPDIR: configRoot, - }; -} - -async function defaultRunDocker(dockerPath: string, args: string[], env: Record): Promise { - const process = Bun.spawn([dockerPath, ...args], { env, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' }); - const timeout = setTimeout(() => process.kill(), DOCKER_TIMEOUT_MS); - const boundedText = async (stream: ReadableStream): Promise => { - const reader = stream.getReader(), chunks: Uint8Array[] = []; - let bytes = 0; - try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - bytes += value.byteLength; - if (bytes > MAX_DOCKER_OUTPUT) { - process.kill(); - await reader.cancel(); - fail('ANONYMOUS_DOCKER_OUTPUT_LIMIT'); - } - chunks.push(value); - } - return Buffer.concat(chunks.map(chunk => Buffer.from(chunk))).toString('utf8'); - } finally { reader.releaseLock(); } - }; - try { - const [stdout, stderr, exitCode] = await Promise.all([ - boundedText(process.stdout), - boundedText(process.stderr), - process.exited, - ]); - return { exitCode, stdout, stderr }; - } finally { clearTimeout(timeout); } -} - -function dockerError(label: string, result: CommandResult): never { - const detail = result.stderr.trim().slice(0, 2048); - fail(`${label}${detail ? `: ${detail}` : ''}`); -} - -export async function verifyPublicGhcrImage( - options: { image: string; platform: string; githubRepository: string; dockerHost?: string; removeAfter?: boolean }, - dependencies?: Partial, -): Promise { - const target = parsePublicGhcrTarget(options.image, options.platform, options.githubRepository); - const dockerHost = options.dockerHost ?? 'unix:///var/run/docker.sock'; - if (dockerHost !== 'unix:///var/run/docker.sock') fail('UNTRUSTED_PUBLIC_IMAGE_DOCKER_HOST'); - const dockerPath = dependencies?.dockerPath ?? Bun.which('docker') ?? ''; - if (!path.isAbsolute(dockerPath)) fail('DOCKER_UNAVAILABLE'); - const githubToken = dependencies?.githubToken ?? process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN ?? ''; - if (!githubToken || githubToken.length > 2048 || /[\r\n]/.test(githubToken)) fail('GITHUB_PACKAGE_METADATA_TOKEN_REQUIRED'); - const deps: PublicGhcrDependencies = { - fetch: dependencies?.fetch ?? globalThis.fetch, - githubToken, - dockerPath, - runDocker: dependencies?.runDocker ?? ((args, env) => defaultRunDocker(dockerPath, args, env)), - now: dependencies?.now ?? (() => new Date().toISOString()), - sleep: dependencies?.sleep ?? (ms => Bun.sleep(ms)), - }; - const packageApiUrl = await publicPackageApi(target, deps); - const configRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-cso-anonymous-docker-')); - fs.chmodSync(configRoot, 0o700); - fs.writeFileSync(path.join(configRoot, 'config.json'), '{"auths":{}}\n', { flag: 'wx', mode: 0o600 }); - const env = cleanDockerEnvironment(configRoot, dockerHost); - let pulled = false; - try { - const pull = await deps.runDocker([ - '--config', configRoot, '--host', dockerHost, 'image', 'pull', '--quiet', '--platform', target.platform, target.image, - ], env); - if (pull.exitCode !== 0) dockerError('ANONYMOUS_IMAGE_PULL_FAILED', pull); - pulled = true; - const inspect = await deps.runDocker([ - '--config', configRoot, '--host', dockerHost, 'image', 'inspect', target.image, '--format', '{{json .RepoDigests}}', - ], env); - if (inspect.exitCode !== 0) dockerError('ANONYMOUS_IMAGE_INSPECT_FAILED', inspect); - let repoDigests: unknown; - try { repoDigests = JSON.parse(inspect.stdout.trim()); } catch { fail('ANONYMOUS_IMAGE_INSPECT_INVALID'); } - if (!Array.isArray(repoDigests) || !repoDigests.includes(target.image)) fail('ANONYMOUS_IMAGE_DIGEST_MISMATCH'); - return { - schemaVersion: 1, - image: target.image, - platform: target.platform, - packageName: target.packageName, - packageVisibility: 'public', - packageApiUrl, - anonymousPull: 'passed', - dockerConfig: 'isolated-empty-auths', - verifiedAt: deps.now(), - }; - } finally { - if (pulled && options.removeAfter) { - const remove = await deps.runDocker([ - '--config', configRoot, '--host', dockerHost, 'image', 'rm', '--force', target.image, - ], env); - if (remove.exitCode !== 0) dockerError('ANONYMOUS_IMAGE_CLEANUP_FAILED', remove); - } - fs.rmSync(configRoot, { recursive: true, force: true }); - } -} - -function option(args: string[], name: string): string | undefined { - const index = args.indexOf(name); - if (index < 0) return undefined; - const value = args[index + 1]; - if (!value || value.startsWith('--')) fail(`MISSING_${name.slice(2).toUpperCase().replaceAll('-', '_')}`); - args.splice(index, 2); - return value; -} - -if (import.meta.main) { - try { - const args = process.argv.slice(2), command = args.shift(); - const image = option(args, '--image'), platform = option(args, '--platform'), repository = option(args, '--repository'); - const output = option(args, '--output'), dockerHost = option(args, '--docker-host'); - const removeAt = args.indexOf('--remove-after'), removeAfter = removeAt >= 0; - if (removeAfter) args.splice(removeAt, 1); - if (command !== 'verify' || !image || !platform || !repository || !output || args.length) { - fail('Usage: cso-public-ghcr.ts verify --image IMAGE@sha256:DIGEST --platform linux/ARCH --repository OWNER/REPO --output PROOF.json [--docker-host unix:///var/run/docker.sock] [--remove-after]'); - } - const proof = await verifyPublicGhcrImage({ image, platform, githubRepository: repository, dockerHost, removeAfter }); - fs.writeFileSync(path.resolve(output), JSON.stringify(proof, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); - process.stdout.write(`ANONYMOUS PULL VERIFIED ${proof.image}\n`); - } catch (error) { - process.stderr.write((error instanceof Error ? error.message : 'PUBLIC_IMAGE_VERIFICATION_FAILED') + '\n'); - process.exitCode = 1; - } -} diff --git a/scripts/cso-sbom-packages-check.jq b/scripts/cso-sbom-packages-check.jq deleted file mode 100644 index ef5ec58c3..000000000 --- a/scripts/cso-sbom-packages-check.jq +++ /dev/null @@ -1,7 +0,0 @@ -# Accept only a package-level SPDX 2.3 document whose relationships name known elements. -.spdxVersion == "SPDX-2.3" -and (.packages | type == "array" and length > 0) -and (has("files") | not) -and (([.SPDXID, .packages[].SPDXID] | map({key: ., value: true}) | from_entries) as $known - | all(.relationships[]; ($known[.spdxElementId] // false) - and (($known[.relatedSpdxElement] // false) or (.relatedSpdxElement | test("^(NONE|NOASSERTION)$|^DocumentRef-"))))) diff --git a/scripts/cso-sbom-packages.jq b/scripts/cso-sbom-packages.jq deleted file mode 100644 index cd0ce2266..000000000 --- a/scripts/cso-sbom-packages.jq +++ /dev/null @@ -1,8 +0,0 @@ -# Reduce a BuildKit SPDX 2.3 SBOM to its package inventory before signing it. -# File entries (tens of thousands for Ruby or Python images) push the signed -# statement past actions/attest's 16 MiB limit; packages, their versions and -# package relationships are what CSO's release evidence relies on. -((.files // []) | map({key: .SPDXID, value: true}) | from_entries) as $files -| del(.files) -| .packages |= map(del(.hasFiles)) -| .relationships |= map(select(($files[.spdxElementId] // false | not) and ($files[.relatedSpdxElement] // false | not))) diff --git a/scripts/cso-scanner-catalog.ts b/scripts/cso-scanner-catalog.ts deleted file mode 100644 index 47fe4aeea..000000000 --- a/scripts/cso-scanner-catalog.ts +++ /dev/null @@ -1,173 +0,0 @@ -#!/usr/bin/env -S bun --no-env-file --config=/dev/null -/** Assemble and validate a complete source-controlled scanner catalog proposal. */ -import * as fs from 'node:fs'; -import { createHash } from 'node:crypto'; -import { basename, join, relative, resolve, sep } from 'node:path'; -import { canonical, sha256 } from '../lib/cso/contracts'; -import { QualifiedScanner, ScannerCatalog, scannerVersionHash, validateQualifiedScanner, validateScannerCatalog } from '../lib/cso/scanner-catalog'; -import { SCANNER_IDS, scannerPlans } from '../lib/cso/scanners'; - -const PLATFORMS = ['linux/amd64', 'linux/arm64'] as const; -const REVISION = /^[a-z0-9][a-z0-9._-]{0,100}$/; -const WORKFLOW = /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/actions\/runs\/[0-9]+$/; -const MAX_ARTIFACT = 1_048_576; -const MAX_TREE_BYTES = 10 * 1024 * 1024 * 1024; -const MAX_TREE_ENTRIES = 100_000; - -function sameFile(left: fs.Stats, right: fs.Stats): boolean { - return left.dev === right.dev && left.ino === right.ino && left.mode === right.mode && left.nlink === right.nlink && left.size === right.size; -} -function hashRegularFile(path: string, expected: fs.Stats): string { - const hash = createHash('sha256'), fd = fs.openSync(path, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0)); - try { - const before = fs.fstatSync(fd); - if (!before.isFile() || before.nlink !== 1 || !sameFile(expected, before)) throw new Error('UNSAFE_SCANNER_ASSET'); - const buffer = Buffer.alloc(1024 * 1024); let count = 0, bytes = 0; - while ((count = fs.readSync(fd, buffer, 0, buffer.length, null)) > 0) { - bytes += count; - if (bytes > expected.size || bytes > MAX_TREE_BYTES) throw new Error('SCANNER_ASSET_LIMIT'); - hash.update(buffer.subarray(0, count)); - } - const after = fs.fstatSync(fd), pathname = fs.lstatSync(path); - if (bytes !== expected.size || !sameFile(before, after) || !sameFile(after, pathname)) throw new Error('UNSAFE_SCANNER_ASSET'); - return hash.digest('hex'); - } finally { fs.closeSync(fd); } -} - -function sameStrings(left: string[], right: string[]): boolean { - return canonical([...left].sort()) === canonical([...right].sort()); -} -function exactKeys(value: Record, allowed: string[], label: string): void { - if (Object.keys(value).some(key => !allowed.includes(key))) throw new Error(`UNEXPECTED_${label.toUpperCase()}_FIELD`); -} -function strictProfile(value: unknown): QualifiedScanner { - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error('INVALID_SCANNER_FRAGMENT'); - const profile = value as QualifiedScanner & Record; - exactKeys(profile, ['id', 'scanner', 'state', 'platform', 'image', 'entrypoint', 'executable', 'version', 'versionOutputSha256', 'helperAbi', 'isolationPolicyHash', 'capabilities', 'assets', 'qualifiedAt', 'qualification'], 'scanner_profile'); - if (!profile.qualification || typeof profile.qualification !== 'object' || Array.isArray(profile.qualification)) throw new Error('INVALID_SCANNER_QUALIFICATION'); - exactKeys(profile.qualification as unknown as Record, ['sourceCommit', 'workflow', 'sbomDigest', 'provenanceDigest', 'verifiedProvenance', 'containmentPassed', 'adapterContractPassed', 'offlineAssetsPassed'], 'scanner_qualification'); - if (profile.assets !== undefined) { - if (!profile.assets || typeof profile.assets !== 'object' || Array.isArray(profile.assets)) throw new Error('INVALID_SCANNER_ASSETS'); - exactKeys(profile.assets as unknown as Record, ['semgrepRules', 'advisoryDatabase'], 'scanner_assets'); - for (const [name, asset] of Object.entries(profile.assets)) { - if (!asset || typeof asset !== 'object' || Array.isArray(asset)) throw new Error('INVALID_SCANNER_ASSETS'); - exactKeys(asset as unknown as Record, name === 'semgrepRules' ? ['path', 'sha256'] : ['path', 'contentSha256', 'updatedAt', 'ecosystems'], 'scanner_asset'); - } - } - validateQualifiedScanner(profile); - const required = scannerPlans({ snapshotRoot: '/source', offline: true, selected: [profile.scanner] })[0].requiredFeatures; - if (!sameStrings(profile.capabilities, required)) throw new Error(`CAPABILITY_CONTRACT_MISMATCH: ${profile.scanner}`); - return profile; -} - -export function scannerCatalogProposal(current: ScannerCatalog, fragments: unknown[], revision: string, expected: { sourceCommit: string; workflow: string; imagePrefix: string }): ScannerCatalog { - validateScannerCatalog(current); - if (!REVISION.test(revision) || revision === current.revision) throw new Error('INVALID_SCANNER_CATALOG_REVISION'); - if (!expected || !/^[a-f0-9]{40}$/.test(expected.sourceCommit)) throw new Error('INVALID_EXPECTED_SOURCE_COMMIT'); - if (!WORKFLOW.test(expected.workflow) || !expected.workflow.startsWith('https://github.com/garrytan/gstack/actions/runs/')) throw new Error('INVALID_EXPECTED_WORKFLOW'); - if (expected.imagePrefix !== 'ghcr.io/garrytan/gstack/cso-scanners/') throw new Error('INVALID_EXPECTED_IMAGE_PREFIX'); - const scanners = fragments.map(strictProfile), identities = new Set(); - if (scanners.length !== SCANNER_IDS.length * PLATFORMS.length) throw new Error('INCOMPLETE_SCANNER_CATALOG_MATRIX'); - for (const profile of scanners) { - const identity = `${profile.scanner}:${profile.platform}`; - if (identities.has(identity)) throw new Error(`DUPLICATE_SCANNER_CATALOG_PROFILE: ${identity}`); - identities.add(identity); - if (profile.qualification.sourceCommit !== expected.sourceCommit) throw new Error(`SOURCE_COMMIT_MISMATCH: ${identity}`); - if (profile.qualification.workflow !== expected.workflow) throw new Error(`WORKFLOW_IDENTITY_MISMATCH: ${identity}`); - if (!profile.image.startsWith(expected.imagePrefix)) throw new Error(`IMAGE_REPOSITORY_MISMATCH: ${identity}`); - } - for (const scanner of SCANNER_IDS) for (const platform of PLATFORMS) if (!identities.has(`${scanner}:${platform}`)) throw new Error(`MISSING_SCANNER_CATALOG_PROFILE: ${scanner}:${platform}`); - scanners.sort((a, b) => a.scanner.localeCompare(b.scanner) || a.platform.localeCompare(b.platform)); - const proposal: ScannerCatalog = { - schemaVersion: 1, - revision, - previousRevision: current.revision, - helperAbi: 3, - promotion: { sourceCommit: expected.sourceCommit, workflow: expected.workflow, evidenceDigest: `sha256:${sha256(canonical(scanners))}` }, - scanners, - }; - validateScannerCatalog(proposal); - return proposal; -} - -/** Promotion is a compare-and-swap against the catalog revision reviewed by qualification. */ -export function validateScannerCatalogTransition(current: ScannerCatalog, proposed: ScannerCatalog): void { - validateScannerCatalog(current); validateScannerCatalog(proposed); - if (proposed.revision === current.revision || proposed.previousRevision !== current.revision) - throw new Error('SCANNER_CATALOG_BASE_REVISION_MISMATCH'); -} - -function readJson(path: string): unknown { - const stat = fs.lstatSync(path); - if (stat.isSymbolicLink() || !stat.isFile() || stat.nlink !== 1 || stat.size > MAX_ARTIFACT) throw new Error(`UNSAFE_CATALOG_ARTIFACT: ${basename(path)}`); - return JSON.parse(fs.readFileSync(path, 'utf8')); -} -function fragments(directory: string): unknown[] { - const root = fs.realpathSync(directory), values: unknown[] = []; - for (const name of fs.readdirSync(root).sort()) { - if (!/^[a-z0-9._-]+\.json$/.test(name)) throw new Error(`UNSAFE_FRAGMENT_NAME: ${name}`); - values.push(readJson(join(root, name))); - } - return values; -} - -/** A file hashes as its bytes; a directory hashes a canonical regular-file inventory. */ -export function scannerAssetHash(path: string): string { - const supplied = fs.lstatSync(path); - if (supplied.isSymbolicLink()) throw new Error('UNSAFE_SCANNER_ASSET'); - const root = fs.realpathSync(path), initial = fs.lstatSync(root); - if (initial.isFile()) { - if (initial.nlink !== 1 || initial.size > MAX_TREE_BYTES) throw new Error('UNSAFE_SCANNER_ASSET'); - return hashRegularFile(root, initial); - } - if (!initial.isDirectory()) throw new Error('UNSAFE_SCANNER_ASSET'); - const entries: Array<[string, number, string]> = [], pending = [root]; let bytes = 0, objects = 0; - while (pending.length) { - const directory = pending.pop()!; - for (const item of fs.readdirSync(directory).sort()) { - const full = join(directory, item), stat = fs.lstatSync(full), rel = relative(root, full).split(sep).join('/'); - if (!rel || rel.startsWith('../') || stat.isSymbolicLink() || ++objects > MAX_TREE_ENTRIES) throw new Error('UNSAFE_SCANNER_ASSET'); - if (stat.isDirectory()) { pending.push(full); continue; } - if (!stat.isFile() || stat.nlink !== 1) throw new Error('UNSAFE_SCANNER_ASSET'); - bytes += stat.size; - if (bytes > MAX_TREE_BYTES) throw new Error('SCANNER_ASSET_LIMIT'); - entries.push([rel, stat.size, hashRegularFile(full, stat)]); - } - } - if (!entries.length) throw new Error('EMPTY_SCANNER_ASSET'); - entries.sort(([left], [right]) => left.localeCompare(right)); - return sha256(canonical(entries)); -} - -function option(args: string[], name: string): string | undefined { - const at = args.indexOf(name); if (at < 0) return undefined; - const value = args[at + 1]; if (!value || value.startsWith('--')) throw new Error(`MISSING_${name.slice(2).toUpperCase().replaceAll('-', '_')}`); - args.splice(at, 2); return value; -} - -if (import.meta.main) { - try { - const args = process.argv.slice(2), command = args.shift(); - if (command === 'validate') { - const path = args.shift(); if (!path || args.length) throw new Error('Usage: validate CATALOG.json'); - const value = readJson(resolve(path)); validateScannerCatalog(value); process.stdout.write('VALID\n'); - } else if (command === 'validate-transition') { - const current = args.shift(), proposed = args.shift(); if (!current || !proposed || args.length) throw new Error('Usage: validate-transition CURRENT.json PROPOSED.json'); - validateScannerCatalogTransition(readJson(resolve(current)) as ScannerCatalog, readJson(resolve(proposed)) as ScannerCatalog); process.stdout.write('VALID TRANSITION\n'); - } else if (command === 'assemble') { - const directory = args.shift(), currentPath = args.shift(), output = args.shift(), revision = option(args, '--revision'), sourceCommit = option(args, '--source-commit'), workflow = option(args, '--workflow'), imagePrefix = option(args, '--image-prefix'); - if (!directory || !currentPath || !output || !revision || !sourceCommit || !workflow || !imagePrefix || args.length) throw new Error('Usage: assemble FRAGMENTS CURRENT OUTPUT --revision ID --source-commit SHA --workflow URL --image-prefix PREFIX'); - const proposal = scannerCatalogProposal(readJson(resolve(currentPath)) as ScannerCatalog, fragments(resolve(directory)), revision, { sourceCommit, workflow, imagePrefix }); - fs.writeFileSync(resolve(output), JSON.stringify(proposal, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); - process.stdout.write(`${proposal.scanners.length} QUALIFIED PROFILES\n`); - } else if (command === 'hash-asset') { - const path = args.shift(); if (!path || args.length) throw new Error('Usage: hash-asset PATH'); process.stdout.write(scannerAssetHash(resolve(path)) + '\n'); - } else if (command === 'version-hash') { - const stdout = args.shift(), stderr = args.shift(); if (!stdout || !stderr || args.length) throw new Error('Usage: version-hash STDOUT STDERR'); - const read = (path: string) => { const stat = fs.lstatSync(path); if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > 8192) throw new Error('UNSAFE_VERSION_OUTPUT'); return fs.readFileSync(path, 'utf8'); }; - process.stdout.write(scannerVersionHash(read(resolve(stdout)), read(resolve(stderr))) + '\n'); - } else throw new Error('Usage: cso-scanner-catalog ...'); - } catch (error) { - process.stderr.write((error instanceof Error ? error.message : 'SCANNER_CATALOG_ERROR') + '\n'); process.exitCode = 1; - } -} diff --git a/scripts/cso-scanner-matrix.ts b/scripts/cso-scanner-matrix.ts deleted file mode 100644 index 3a3184555..000000000 --- a/scripts/cso-scanner-matrix.ts +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env -S bun --no-env-file --config=/dev/null -/** Validate reviewed scanner inputs before any image is built or published. */ -import { readFileSync } from 'node:fs'; -import { resolve } from 'node:path'; -import { SCANNER_IDS, ScannerId, scannerPlans } from '../lib/cso/scanners'; - -const PLATFORMS = ['linux/amd64', 'linux/arm64'] as const; -const IMAGE = /^(?:[a-z0-9.-]+(?::[0-9]+)?\/)?[a-z0-9][a-z0-9._/-]*@sha256:[a-f0-9]{64}$/; -const DIGEST = /^sha256:[a-f0-9]{64}$/; -const HASH = /^[a-f0-9]{64}$/; -const VERSION = /^[0-9][A-Za-z0-9.+_-]{0,100}$/; -const EXECUTABLE = /^\/(?:[A-Za-z0-9._+-]+\/)*[A-Za-z0-9._+-]+$/; -const REPOSITORY = /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; -const ID = /^[A-Za-z0-9][A-Za-z0-9._+/-]{0,100}$/; -const SIGNER_WORKFLOW = /^(?:github\.com\/)?[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/\.github\/workflows\/[A-Za-z0-9_.\/-]+\.ya?ml$/; - -type Platform = typeof PLATFORMS[number]; -type AssetDeclaration = { - semgrepRules?: { path: string; sha256: string }; - advisoryDatabase?: { path: string; contentSha256: string; updatedAt: string; ecosystems: string[] }; -}; -export type ReviewedAttestedImage = { - image: string; - repository: string; - sourceCommit: string; - release: string; - signerWorkflow: string; - signerDigest: string; - provenanceStatementDigest: string; - sbomStatementDigest: string; -}; -export interface ScannerBuildRow { - scanner: ScannerId; - platform: Platform; - arch: 'amd64' | 'arm64'; - runner: 'ubuntu-24.04' | 'ubuntu-24.04-arm'; - baseImage: string; - scannerExecutable: string; - version: string; - capabilities: string[]; - assets: AssetDeclaration | null; - applicationExecutable: string; - sbomGenerator: ReviewedAttestedImage; - baseAttestation: ReviewedAttestedImage; -} - -function object(value: unknown, code: string): Record { - if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(code); - return value as Record; -} -function exact(value: Record, allowed: string[], code: string): void { - if (Object.keys(value).some(key => !allowed.includes(key))) throw new Error(code); -} -function safePath(value: unknown, prefix: string, code: string): string { - if (typeof value !== 'string' || !EXECUTABLE.test(value) || !value.startsWith(prefix) || value.split('/').includes('..')) throw new Error(code); - return value; -} -function digest(value: unknown, code: string): string { - if (typeof value !== 'string' || !DIGEST.test(value)) throw new Error(code); - return value; -} -function attestedImage(value:unknown,code:string):ReviewedAttestedImage{ - const raw=object(value,code);exact(raw,['image','repository','sourceCommit','release','signerWorkflow','signerDigest','provenanceStatementDigest','sbomStatementDigest'],code); - if(typeof raw.image!=='string'||!IMAGE.test(raw.image)||typeof raw.repository!=='string'||!REPOSITORY.test(raw.repository)|| - typeof raw.sourceCommit!=='string'||!/^[a-f0-9]{40}$/.test(raw.sourceCommit)||typeof raw.release!=='string'||!ID.test(raw.release)|| - typeof raw.signerWorkflow!=='string'||!SIGNER_WORKFLOW.test(raw.signerWorkflow)||typeof raw.signerDigest!=='string'||!/^[a-f0-9]{40}$/.test(raw.signerDigest))throw new Error(code); - return{image:raw.image,repository:raw.repository,sourceCommit:raw.sourceCommit,release:raw.release,signerWorkflow:raw.signerWorkflow,signerDigest:raw.signerDigest, - provenanceStatementDigest:digest(raw.provenanceStatementDigest,code),sbomStatementDigest:digest(raw.sbomStatementDigest,code)}; -} -function assets(value: unknown, scanner: ScannerId): AssetDeclaration | null { - if (value === undefined || value === null) { - if (['semgrep', 'osv', 'trivy'].includes(scanner)) throw new Error(`MISSING_OFFLINE_ASSET: ${scanner}`); - return null; - } - const raw = object(value, 'INVALID_SCANNER_ASSET'); exact(raw, ['semgrepRules', 'advisoryDatabase'], 'INVALID_SCANNER_ASSET'); - if (scanner === 'semgrep') { - const rules = object(raw.semgrepRules, 'MISSING_SEMGREP_RULES'); exact(rules, ['path', 'sha256'], 'INVALID_SEMGREP_RULES'); - if (raw.advisoryDatabase !== undefined) throw new Error('INVALID_SEMGREP_RULES'); - const path = safePath(rules.path, '/policy/catalog/', 'INVALID_SEMGREP_RULES'); - if (typeof rules.sha256 !== 'string' || !HASH.test(rules.sha256)) throw new Error('INVALID_SEMGREP_RULES'); - return { semgrepRules: { path, sha256: rules.sha256 } }; - } - if (scanner === 'osv' || scanner === 'trivy') { - const db = object(raw.advisoryDatabase, 'MISSING_ADVISORY_DATABASE'); exact(db, ['path', 'contentSha256', 'updatedAt', 'ecosystems'], 'INVALID_ADVISORY_DATABASE'); - if (raw.semgrepRules !== undefined) throw new Error('INVALID_ADVISORY_DATABASE'); - const path = safePath(db.path, '/opt/cso/scanner-data/', 'INVALID_ADVISORY_DATABASE'); - if (typeof db.contentSha256 !== 'string' || !HASH.test(db.contentSha256) || typeof db.updatedAt !== 'string' || !Number.isFinite(Date.parse(db.updatedAt)) || !Array.isArray(db.ecosystems) || !db.ecosystems.length || new Set(db.ecosystems).size !== db.ecosystems.length || db.ecosystems.some(item => typeof item !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9.+_-]{0,63}$/.test(item))) throw new Error('INVALID_ADVISORY_DATABASE'); - return { advisoryDatabase: { path, contentSha256: db.contentSha256, updatedAt: new Date(db.updatedAt).toISOString(), ecosystems: (db.ecosystems as string[]).slice().sort() } }; - } - throw new Error(`UNEXPECTED_OFFLINE_ASSET: ${scanner}`); -} - -/** Every scanner must have both native platforms; partial matrices cannot publish. */ -export function scannerBuildMatrix(input: unknown): { include: ScannerBuildRow[] } { - const data = object(input, 'INVALID_SCANNER_BUILD_INPUTS'); - exact(data, ['schemaVersion', 'helperAbi', 'state', 'sbomGenerator', 'profiles', 'instructions'], 'INVALID_SCANNER_BUILD_INPUTS'); - if (data.schemaVersion !== 1 || data.helperAbi !== 3) throw new Error('INCOMPATIBLE_SCANNER_BUILD_INPUTS'); - if (data.state !== 'reviewed') throw new Error('MISSING_REVIEWED_SCANNER_INPUTS: review immutable images, assets, versions, SBOMs, and provenance before staging.'); - const sbomGenerator=attestedImage(data.sbomGenerator,'UNVERIFIED_SBOM_GENERATOR'); - if (!Array.isArray(data.profiles) || data.profiles.length !== SCANNER_IDS.length) throw new Error('INCOMPLETE_SCANNER_MATRIX'); - const rows: ScannerBuildRow[] = [], seen = new Set(); - for (const value of data.profiles) { - const profile = object(value, 'INVALID_SCANNER_PROFILE'); - exact(profile, ['scanner', 'version', 'baseImages', 'executable', 'assets', 'applicationExecutable'], 'INVALID_SCANNER_PROFILE'); - const scanner = profile.scanner as ScannerId; - if (!SCANNER_IDS.includes(scanner) || seen.has(scanner)) throw new Error('INVALID_OR_DUPLICATE_SCANNER'); - seen.add(scanner); - if (typeof profile.version !== 'string' || !VERSION.test(profile.version)) throw new Error(`UNPINNED_SCANNER_VERSION: ${scanner}`); - if (typeof profile.executable !== 'string' || !EXECUTABLE.test(profile.executable)) throw new Error(`INVALID_SCANNER_EXECUTABLE: ${scanner}`); - const baseImages = object(profile.baseImages, `MISSING_SCANNER_IMAGES: ${scanner}`); - exact(baseImages, [...PLATFORMS], `INVALID_SCANNER_IMAGES: ${scanner}`); - const declaredAssets = assets(profile.assets, scanner); - const applicationExecutable = scanner === 'schemathesis' ? safePath(profile.applicationExecutable, '/', 'MISSING_SCHEMATHESIS_FIXTURE_RUNTIME') : ''; - if (scanner !== 'schemathesis' && profile.applicationExecutable !== undefined) throw new Error(`UNEXPECTED_APPLICATION_EXECUTABLE: ${scanner}`); - const capabilities = scannerPlans({ snapshotRoot: '/source', offline: true, selected: [scanner] })[0].requiredFeatures.slice().sort(); - for (const platform of PLATFORMS) { - const baseAttestation=attestedImage(baseImages[platform],`INVALID_UPSTREAM_EVIDENCE: ${scanner} ${platform}`),baseImage=baseAttestation.image; - const arch = platform === 'linux/amd64' ? 'amd64' : 'arm64'; - rows.push({ scanner, platform, arch, runner: arch === 'amd64' ? 'ubuntu-24.04' : 'ubuntu-24.04-arm', baseImage, scannerExecutable: profile.executable, version: profile.version, capabilities, assets: declaredAssets, applicationExecutable, sbomGenerator, baseAttestation }); - } - } - return { include: rows }; -} - -if (import.meta.main) { - try { - if (process.argv.length !== 2) throw new Error('No arguments accepted; scanner inputs come from the reviewed repository file.'); - const file = resolve(import.meta.dir, '../lib/cso/scanner-images/build-inputs.json'); - process.stdout.write(JSON.stringify(scannerBuildMatrix(JSON.parse(readFileSync(file, 'utf8')))) + '\n'); - } catch (error) { - process.stderr.write((error instanceof Error ? error.message : 'INVALID_SCANNER_BUILD_INPUTS') + '\n'); - process.exitCode = 1; - } -} diff --git a/scripts/cso-staging-run.ts b/scripts/cso-staging-run.ts deleted file mode 100644 index 19451ca63..000000000 --- a/scripts/cso-staging-run.ts +++ /dev/null @@ -1,124 +0,0 @@ -#!/usr/bin/env -S bun --no-env-file --config=/dev/null -/** Bind a qualification dispatch to the one successful protected-main staging run that signed its images. */ -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import { canonical } from '../lib/cso/contracts'; -import { committedImageBuildMatrix } from './cso-image-matrix'; - -export const STAGING_WORKFLOW_PATH = '.github/workflows/cso-runtime-images.yml'; -export const NATIVE_JOB = 'qualify-native'; -const SLSA_PROVENANCE = 'https://slsa.dev/provenance/v1'; -const REPOSITORY = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/; -const INVOCATION = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+)\/actions\/runs\/([1-9][0-9]*)\/attempts\/[1-9][0-9]*$/; -const MAX_FILE_BYTES = 4 * 1024 * 1024; - -export interface StagingRunEvidence { - repository: string; - runId: string; - sourceCommit: string; - runtimeIds: string[]; - run: unknown; - jobPages: unknown; -} - -/** - * Resolve the staging run from verified SLSA provenance. The predicate's - * invocation and the Fulcio certificate's run URI must agree, and every - * verified statement for every image must name the same run. - */ -export function stagingRunId(repository: string, verifications: unknown[]): string { - if (!REPOSITORY.test(repository) || verifications.length === 0) throw new Error('INVALID_STAGING_PROVENANCE'); - const runs = new Set(); - for (const verification of verifications) { - if (!Array.isArray(verification) || verification.length === 0) throw new Error('INVALID_STAGING_PROVENANCE'); - for (const item of verification) { - const result = (item as any)?.verificationResult; - if (result?.statement?.predicateType !== SLSA_PROVENANCE) throw new Error('INVALID_STAGING_PROVENANCE'); - const invocation = result.statement.predicate?.runDetails?.metadata?.invocationId; - const match = typeof invocation === 'string' ? INVOCATION.exec(invocation) : null; - if (!match || match[1] !== repository || result.signature?.certificate?.runInvocationURI !== invocation) { - throw new Error('STAGING_INVOCATION_MISMATCH'); - } - runs.add(match[2]); - } - } - if (runs.size !== 1) throw new Error('STAGING_RUN_NOT_UNIQUE'); - return [...runs][0]; -} - -/** Every statement in one qualification dispatch names the same staged source commit. */ -export function dispatchSourceCommit(event: unknown): string { - const statements = (event as any)?.client_payload?.statements; - if (!Array.isArray(statements) || statements.length === 0) throw new Error('INVALID_QUALIFICATION_DISPATCH'); - const commits = new Set(statements.map((statement: any) => statement?.sourceCommit)); - const [commit] = [...commits]; - if (commits.size !== 1 || typeof commit !== 'string' || !/^[a-f0-9]{40}$/.test(commit)) throw new Error('STAGING_SOURCE_COMMIT_MISMATCH'); - return commit; -} - -/** The resolved run must be the protected-main staging dispatch at the statements' commit, with every native gate passed. */ -export function verifyStagingRun(evidence: StagingRunEvidence): void { - const { repository, runId, sourceCommit, runtimeIds } = evidence; - const run = evidence.run as any; - if (!run || typeof run !== 'object' || String(run.id) !== runId) throw new Error('STAGING_RUN_ID_MISMATCH'); - if (run.path !== STAGING_WORKFLOW_PATH) throw new Error('STAGING_WORKFLOW_MISMATCH'); - if (run.repository?.full_name !== repository || run.head_repository?.full_name !== repository) throw new Error('STAGING_REPOSITORY_MISMATCH'); - if (run.event !== 'workflow_dispatch' || run.head_branch !== 'main') throw new Error('STAGING_RUN_NOT_PROTECTED_MAIN_DISPATCH'); - if (run.status !== 'completed' || run.conclusion !== 'success') throw new Error('STAGING_RUN_NOT_SUCCESSFUL'); - if (run.head_sha !== sourceCommit) throw new Error('STAGING_SOURCE_COMMIT_MISMATCH'); - - const pages = evidence.jobPages; - if (!Array.isArray(pages) || pages.length === 0) throw new Error('INVALID_STAGING_JOBS'); - const totals = new Set(pages.map((page: any) => page?.total_count)); - if (pages.some((page: any) => !Array.isArray(page?.jobs)) || totals.size !== 1) throw new Error('INVALID_STAGING_JOBS'); - const jobs = pages.flatMap((page: any) => page.jobs); - if (jobs.length !== [...totals][0]) throw new Error('INCOMPLETE_STAGING_JOBS'); - - const native = jobs.filter((job: any) => typeof job?.name === 'string' && job.name.startsWith(NATIVE_JOB)); - const expected = runtimeIds.map(id => `${NATIVE_JOB} ${id}`).sort(); - if (runtimeIds.length === 0 || canonical(native.map((job: any) => job.name).sort()) !== canonical(expected)) { - throw new Error('STAGING_NATIVE_JOBS_MISMATCH'); - } - if (native.some((job: any) => String(job.run_id) !== runId || job.status !== 'completed' || job.conclusion !== 'success')) { - throw new Error('STAGING_NATIVE_GATE_NOT_PASSED'); - } -} - -function readJson(file: string): unknown { - const absolute = path.resolve(file); - const stat = fs.lstatSync(absolute); - if (!stat.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > MAX_FILE_BYTES) throw new Error('UNSAFE_STAGING_EVIDENCE_FILE'); - try { return JSON.parse(fs.readFileSync(absolute, 'utf8')); } catch { throw new Error('INVALID_STAGING_EVIDENCE_FILE'); } -} - -function option(args: string[], name: string): string { - const index = args.indexOf(name); - const value = index >= 0 ? args[index + 1] : undefined; - if (!value || value.startsWith('--')) throw new Error(`Missing ${name}`); - return value; -} - -if (import.meta.main) { - try { - const [command, ...args] = process.argv.slice(2); - if (command === 'run-id' && args[0] === '--repository' && args.length >= 3) { - process.stdout.write(`${stagingRunId(args[1], args.slice(2).map(readJson))}\n`); - } else if (command === 'verify' && args.length === 10) { - const event = readJson(option(args, '--event')); - verifyStagingRun({ - repository: option(args, '--repository'), - runId: option(args, '--run-id'), - sourceCommit: dispatchSourceCommit(event), - runtimeIds: committedImageBuildMatrix().include.map(row => row.runtimeId), - run: readJson(option(args, '--run')), - jobPages: readJson(option(args, '--jobs')), - }); - process.stdout.write('STAGING RUN VERIFIED\n'); - } else { - throw new Error('Usage: cso-staging-run.ts run-id --repository OWNER/REPO PROVENANCE.json... | verify --repository OWNER/REPO --run-id ID --event EVENT.json --run RUN.json --jobs JOB-PAGES.json'); - } - } catch (error) { - process.stderr.write((error instanceof Error ? error.message : 'STAGING_RUN_VERIFICATION_FAILED') + '\n'); - process.exitCode = 1; - } -} diff --git a/scripts/cso-verify-runtime-base.ts b/scripts/cso-verify-runtime-base.ts deleted file mode 100644 index 19867e553..000000000 --- a/scripts/cso-verify-runtime-base.ts +++ /dev/null @@ -1,117 +0,0 @@ -#!/usr/bin/env -S bun --no-env-file --config=/dev/null -/** Native trusted-CI verification for reviewed OCI build inputs. */ -import { spawnSync } from '../lib/spawn-sync'; -import { committedImageBuildMatrix, type ImageBuildRow } from './cso-image-matrix'; - -const MAX_OUTPUT = 1024 * 1024; -const TIMEOUT = 120_000; - -interface VersionProbe { - image: string; - executable: string; - args: string[]; - version: string; - name: string; -} - -export function assertVersionOutput(name: string, expected: string, output: string): void { - if (Buffer.byteLength(output) > 64 * 1024) throw new Error(`VERSION_OUTPUT_TOO_LARGE: ${name}`); - const first = output.match(/(? = { PATH: process.env.PATH ?? '/usr/bin:/bin' }; - if (process.env.HOME) env.HOME = process.env.HOME; - if (process.env.DOCKER_CONFIG) env.DOCKER_CONFIG = process.env.DOCKER_CONFIG; - const result = spawnSync(docker, args, { encoding: 'utf8', timeout, maxBuffer: MAX_OUTPUT, env }); - if (result.error || result.status !== 0) { - const message = [result.error?.message, result.stderr, result.stdout].filter(Boolean).join('\n').slice(0, 4096); - throw new Error(`DOCKER_INPUT_VERIFICATION_FAILED: ${args[0]} ${message}`); - } - if (Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr) > MAX_OUTPUT) throw new Error('DOCKER_INPUT_VERIFICATION_OUTPUT_TOO_LARGE'); - return result.stdout; -} - -function inspectManifest(docker: string, image: string): any { - const raw = command(docker, ['buildx', 'imagetools', 'inspect', image, '--format', '{{json .Manifest}}']); - try { return JSON.parse(raw); } catch { throw new Error(`INVALID_OCI_MANIFEST: ${image}`); } -} - -function inspectImage(docker: string, image: string): any { - const raw = command(docker, ['buildx', 'imagetools', 'inspect', image, '--format', '{{json .Image}}']); - try { return JSON.parse(raw); } catch { throw new Error(`INVALID_OCI_IMAGE_CONFIG: ${image}`); } -} - -function digestOf(image: string): string { - return image.slice(image.lastIndexOf('@') + 1); -} - -function assertSourceIndex(docker: string, source: string, indexImage: string, platformImage: string, row: ImageBuildRow): void { - const sourceManifest = inspectManifest(docker, source); - if (sourceManifest?.digest !== digestOf(indexImage)) throw new Error(`SOURCE_TAG_MOVED: ${source}`); - const indexManifest = inspectManifest(docker, indexImage); - const platformDigest = digestOf(platformImage); - const match = indexManifest?.manifests?.find((manifest: any) => - manifest?.digest === platformDigest && manifest?.platform?.os === 'linux' && manifest?.platform?.architecture === row.arch); - if (!match) throw new Error(`PLATFORM_MANIFEST_NOT_IN_INDEX: ${platformImage}`); - const config = inspectImage(docker, platformImage); - if (config?.os !== 'linux' || config?.architecture !== row.arch) throw new Error(`PLATFORM_CONFIG_MISMATCH: ${platformImage}`); -} - -export function verifyRuntimeBuildRow(row: ImageBuildRow, docker = Bun.which('docker')): void { - if (!docker || !docker.startsWith('/')) throw new Error('TRUSTED_DOCKER_NOT_FOUND'); - command(docker, ['--host', 'unix:///var/run/docker.sock', 'info'], 30_000); - assertSourceIndex(docker, row.baseSource, row.baseIndexImage, row.baseImage, row); - assertSourceIndex(docker, row.sbomGeneratorSource, row.sbomGeneratorIndexImage, row.sbomGeneratorImage, row); - if (row.stack === 'python') assertSourceIndex(docker, row.uvSource, row.uvIndexImage, row.uvImage, row); - const images = [...new Set(probesForBuildRow(row).map(probe => probe.image))]; - for (const image of images) command(docker, ['--host', 'unix:///var/run/docker.sock', 'pull', '--platform', row.platform, image], 5 * 60_000); - for (const probe of probesForBuildRow(row)) { - const output = command(docker, [ - '--host', 'unix:///var/run/docker.sock', 'run', '--rm', '--pull', 'never', '--network', 'none', - '--entrypoint', probe.executable, probe.image, ...probe.args, - ], 30_000); - assertVersionOutput(probe.name, probe.version, output); - } -} - -if (import.meta.main) { - try { - if (process.argv.length !== 2) throw new Error('No arguments accepted; the selected row comes from committed inputs and trusted CI environment.'); - const stack = process.env.CSO_STACK; - const platform = process.env.CSO_PLATFORM; - const rows = committedImageBuildMatrix().include.filter(row => row.stack === stack && row.platform === platform); - if (rows.length !== 1) throw new Error('INVALID_RUNTIME_BUILD_ROW'); - verifyRuntimeBuildRow(rows[0]); - process.stdout.write(`verified ${rows[0].runtimeId} base manifests and versions\n`); - } catch (error) { - process.stderr.write((error instanceof Error ? error.message : 'RUNTIME_BASE_VERIFICATION_FAILED') + '\n'); - process.exitCode = 1; - } -} diff --git a/scripts/free-test-durations-windows.json b/scripts/free-test-durations-windows.json index c3c1f7d21..7706ef5c7 100644 --- a/scripts/free-test-durations-windows.json +++ b/scripts/free-test-durations-windows.json @@ -337,33 +337,7 @@ "test/cost-known.test.ts": 349, "test/coverage-audit.test.ts": 8774, "test/crew-move-layout.test.ts": 60, - "test/cso-bounded-file.test.ts": 57, - "test/cso-docker-policy.test.ts": 219, - "test/cso-docker-socket-realpath.test.ts": 68, - "test/cso-git-global-config.test.ts": 125, - "test/cso-git-hardening.test.ts": 75, - "test/cso-history.test.ts": 46, - "test/cso-image-provisioning.test.ts": 280, - "test/cso-lease-identity.test.ts": 396, - "test/cso-native-evidence.test.ts": 99, - "test/cso-node-lifecycle-integration.test.ts": 110, - "test/cso-ntfs-fixture.test.ts": 592, - "test/cso-postgresql-policy.test.ts": 66, - "test/cso-preparation-java.test.ts": 62, - "test/cso-preparation.test.ts": 179, - "test/cso-preserved.test.ts": 55, - "test/cso-public-ghcr.test.ts": 58, "test/cso-requalification.test.ts": 160, - "test/cso-runtime-promotion.test.ts": 344, - "test/cso-scanner-docker-integration.test.ts": 95, - "test/cso-scanners.test.ts": 240, - "test/cso-snapshot-disappearance-race.test.ts": 65, - "test/cso-spec-taxonomy-alignment.test.ts": 45, - "test/cso-staging-run.test.ts": 191, - "test/cso-unreadable-secret-file.test.ts": 1252, - "test/cso-verifier.test.ts": 94, - "test/cso-windows-build-contract.test.ts": 62, - "test/cso-windows-docker.test.ts": 65, "test/declared-annotation.test.ts": 58, "test/defensive-review-framing.test.ts": 50, "test/dependency-security.test.ts": 154, @@ -809,7 +783,6 @@ "test/setup-codex-design-pdf-runtime.test.ts": 56, "test/setup-codex-model.test.ts": 54, "test/setup-codex-scope-review-boundaries.test.ts": 124, - "test/setup-cso-windows-probe.test.ts": 49, "test/setup-cursor-legacy-skills.test.ts": 119, "test/setup-deploy-key-presence.test.ts": 96, "test/setup-deploy-not-deployed.test.ts": 45, diff --git a/scripts/free-test-durations.json b/scripts/free-test-durations.json index f994005cd..fe6ebb023 100644 --- a/scripts/free-test-durations.json +++ b/scripts/free-test-durations.json @@ -397,8 +397,6 @@ "test/brain-sync.test.ts": 174893, "test/branch-slug-hygiene.test.ts": 623, "test/build-check-skill-eval.test.ts": 5280, - "test/build-cso-nonfatal.test.ts": 51, - "test/build-cso-result-record.test.ts": 392, "test/build-gbrain-env.test.ts": 58, "test/build-script-shell-compat.test.ts": 13, "test/builder-profile.test.ts": 3445, @@ -524,65 +522,7 @@ "test/credential-rejection.test.ts": 283, "test/crew-move-layout.test.ts": 15, "test/crew-skills-on-capy.test.ts": 1042, - "test/cso-audit-paths.test.ts": 21523, - "test/cso-bounded-file.test.ts": 22, - "test/cso-cache.test.ts": 183, - "test/cso-cli-lifecycle.test.ts": 6272, - "test/cso-cli-recheck.test.ts": 20977, - "test/cso-cli.test.ts": 41566, - "test/cso-contracts.test.ts": 298, - "test/cso-distribution.test.ts": 2597, - "test/cso-docker-argv0.test.ts": 947, - "test/cso-docker-integration.test.ts": 24, - "test/cso-docker-mounts.test.ts": 46, - "test/cso-docker-policy.test.ts": 27, - "test/cso-docker-socket-realpath.test.ts": 35, - "test/cso-eval.test.ts": 10505, - "test/cso-file-ceiling.test.ts": 36092, - "test/cso-git-global-config.test.ts": 32, - "test/cso-git-hardening.test.ts": 447, - "test/cso-history.test.ts": 14, - "test/cso-image-provisioning.test.ts": 300, - "test/cso-json-redaction.test.ts": 285, - "test/cso-launcher-generation.test.ts": 1624, - "test/cso-lease-identity.test.ts": 541, - "test/cso-macos-launcher.test.ts": 20, - "test/cso-native-evidence.test.ts": 109, - "test/cso-node-lifecycle-integration.test.ts": 48, - "test/cso-ntfs-fixture.test.ts": 92, - "test/cso-ordinary-repos.test.ts": 6367, - "test/cso-postgresql-policy.test.ts": 28, - "test/cso-preparation-adversarial.test.ts": 86, - "test/cso-preparation-container.test.ts": 84, - "test/cso-preparation-executor.test.ts": 864, - "test/cso-preparation-java.test.ts": 30, - "test/cso-preparation.test.ts": 122, - "test/cso-preserved.test.ts": 19, - "test/cso-public-ghcr.test.ts": 44, - "test/cso-python-runner-shadow.test.ts": 3263, - "test/cso-rails-verification.test.ts": 43, - "test/cso-registry-socket.test.ts": 3827, "test/cso-requalification.test.ts": 2885, - "test/cso-runtime-promotion.test.ts": 2784, - "test/cso-scanner-cli.test.ts": 8609, - "test/cso-scanner-docker-integration.test.ts": 36, - "test/cso-scanner-executor.test.ts": 145, - "test/cso-scanner-release.test.ts": 75, - "test/cso-scanners.test.ts": 146, - "test/cso-snapshot-disappearance-race.test.ts": 146, - "test/cso-snapshot-identity.test.ts": 444, - "test/cso-snapshot-state.test.ts": 4244, - "test/cso-spec-taxonomy-alignment.test.ts": 15, - "test/cso-stack-cold-integration.test.ts": 35, - "test/cso-staging-run.test.ts": 94, - "test/cso-unreadable-secret-file.test.ts": 263, - "test/cso-verification-cleanup.test.ts": 1109, - "test/cso-verifier.test.ts": 43, - "test/cso-watchdog.test.ts": 7691, - "test/cso-windows-build-contract.test.ts": 22, - "test/cso-windows-docker.test.ts": 21, - "test/cso-windows-launcher.test.ts": 21, - "test/cso-witness.test.ts": 1069, "test/decision-trail.test.ts": 554, "test/declared-annotation.test.ts": 17, "test/default-base.test.ts": 4360, @@ -1466,8 +1406,6 @@ "test/setup-conductor-auq-hook.test.ts": 19030, "test/setup-conductor-worktree.test.ts": 32, "test/setup-crlf-repair.test.ts": 167, - "test/setup-cso-degrade.test.ts": 140, - "test/setup-cso-windows-probe.test.ts": 46, "test/setup-cursor-legacy-skills.test.ts": 5159, "test/setup-deploy-key-presence.test.ts": 16, "test/setup-deploy-not-deployed.test.ts": 13, diff --git a/scripts/harness-pins/scripts/test-pr-profile.ts.json b/scripts/harness-pins/scripts/test-pr-profile.ts.json index 762520890..c5cfcec4a 100644 --- a/scripts/harness-pins/scripts/test-pr-profile.ts.json +++ b/scripts/harness-pins/scripts/test-pr-profile.ts.json @@ -1 +1 @@ -{"blob":"9384e521785e31e99eae4c0f126f67bb2d174260","since":8} +{"blob":"10f92d323fc94589f184ad00fd1228f1372b5470","since":8,"nonBehavioral":"Removes the four deleted /cso workflows from the PR-profile path list; no remaining case's selection, trials or verdict changes"} diff --git a/scripts/lib/windows-curation.ts b/scripts/lib/windows-curation.ts index d76b50664..728283347 100644 --- a/scripts/lib/windows-curation.ts +++ b/scripts/lib/windows-curation.ts @@ -230,30 +230,6 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> file: 'browse/test/security-audit-r2.test.ts', reason: 'symlink-attack fixtures (evil-link) need Developer Mode CI runners lack; expect(toThrow) fires unhandled on Windows', }, - // CSO comprehensive execution is qualified only for Linux containers behind - // the POSIX watchdog and Unix-domain registry broker. Keep the portable - // static/parser contracts in the Windows lane while leaving these exact - // containment suites to the Linux and macOS gates. - { - file: 'test/cso-preparation-adversarial.test.ts', - reason: 'exercises POSIX prepared-tree and archive-cache containment for qualified Linux Docker execution, which Windows does not admit', - }, - { - file: 'test/cso-preparation-container.test.ts', - reason: 'asserts POSIX permission and symlink semantics for inert exports consumed by qualified Linux Docker execution', - }, - { - file: 'test/cso-preparation-executor.test.ts', - reason: 'executes the Linux Docker acquisition path and its Unix-domain registry broker; comprehensive execution is unavailable on Windows', - }, - { - file: 'test/cso-verification-cleanup.test.ts', - reason: 'spawns the POSIX detached watchdog used by contained repair verification, which Windows intentionally leaves unavailable', - }, - { - file: 'test/cso-witness.test.ts', - reason: 'tests the contained repair witness with POSIX private-directory and compiled-helper assumptions; comprehensive execution is unavailable on Windows', - }, { file: 'test/shard-engine-equivalence.test.ts', reason: 'its classification golden was recorded from the POSIX runners (process-group wall kill); the win32 engine path is pinned by the mocked-platform case in shard-engine.test.ts', @@ -286,10 +262,6 @@ export const KNOWN_WINDOWS_INCOMPATIBLE: Array<{ file: string; reason: string }> file: 'test/setup-codex-scope-runtime-links.test.ts', reason: 'every case runs the real ./setup under describe.skipIf(win32); its bin/ spawns live in test/helpers/install-fixture.ts and test/helpers/setup-codex-scope-cyclic.ts, so the source scan misses them', }, - { - file: 'test/cso-scanner-cli.test.ts', - reason: 'drives the prebuilt POSIX CSO launcher with /usr/bin/git and a POSIX-only PATH; native Windows launcher behavior is covered by the dedicated cso-windows-launcher gate', - }, // C-stamp (ship policy, restamp, tree receipt, evidence bundle, ship receipt): // every case spawns bin/ shebang scripts and a #!/bin/sh `gh` shim through // test/helpers/restamp-fixture.ts, so the source scan misses them. @@ -543,7 +515,6 @@ export const KNOWN_WINDOWS_SAFE: Array<{ file: string; reason: string }> = [ // the curated lane even if a future edit trips a content pattern. { file: 'browse/test/cli-chain-stdin.test.ts', reason: 'piped-stdin browse chain against a stub daemon, and no-flow usage errors before any daemon boots; spawns the CLI through Bun argv' }, { file: 'browse/test/runtime-root-server-bundle.test.ts', reason: 'a runtime root copy without node_modules resolves the checkout bundle via .source-path and refuses on version skew; os.tmpdir layouts only' }, - { file: 'test/cso-windows-docker.test.ts', reason: '/cso docker.exe discovery under known-folder roots (real path, no reparse points) and the native-transport-unsupported outcome; pure win32 path logic' }, { file: 'test/copilot-windows-bash.test.ts', reason: 'the Copilot glossary line that runs bash blocks in Git for Windows Bash; reads host config only' }, { file: 'test/ship-hook-windows-paths.test.ts', reason: 'runs bin/ helpers through explicit bash and Bun argv with forward-slash paths; never executes a shebang; the path-spelling simulation is skipIf win32' }, { file: 'test/review-scope-windows-launch.test.ts', reason: '#3541: runs gstack-review-scope through lib/script-invocation.ts, which must reach the bash gstack-review-read through Git Bash (red at main: windows-free-shard 3, run 41228091417); os.tmpdir state only' }, @@ -600,12 +571,6 @@ export const KNOWN_WINDOWS_SAFE: Array<{ file: string; reason: string }> = [ // and never launches a shebang. Keep the native delimiter cases in CI. reason: 'replays the registered SDK callback with fixture-only bin paths; covers native Windows PATH composition', }, - { - file: 'test/cso-windows-build-contract.test.ts', - // bin is a temporary staging directory. The adapter injects spawnSync; - // real PowerShell/native execution remains in cso-windows-launcher. - reason: 'replays the native build callbacks with an injected subprocess; bin paths are staging fixtures, not shebang launches', - }, { file: 'test/setup-windows-rerun-refresh.test.ts', // Trips the "spawns bin/ shebang script" pattern via path.join(..., 'bin', diff --git a/scripts/test-pr-profile.ts b/scripts/test-pr-profile.ts index 9384e5217..10f92d323 100644 --- a/scripts/test-pr-profile.ts +++ b/scripts/test-pr-profile.ts @@ -270,10 +270,6 @@ export const FREE_ONLY_PR_FILES = [ '.github/workflows/arm-setup-smoke.yml', '.github/workflows/ci-image.yml', '.github/workflows/codex-hooks.yml', // Installs the pinned Codex CLI and runs the free test/codex-hooks-real-codex.test.ts; no paid case reads it. - '.github/workflows/cso-runtime-images.yml', - '.github/workflows/cso-runtime-promote.yml', - '.github/workflows/cso-runtime-qualification.yml', - '.github/workflows/cso-scanner-images.yml', '.github/workflows/dependency-review.yml', '.github/workflows/free-durations-record.yml', '.github/workflows/free-tests.yml', diff --git a/scripts/typecheck-test-baseline.json b/scripts/typecheck-test-baseline.json index 6835d28e4..5fd763614 100644 --- a/scripts/typecheck-test-baseline.json +++ b/scripts/typecheck-test-baseline.json @@ -120,14 +120,6 @@ "test/claude-code-runner.test.ts\tTS7006\tParameter 'callback' implicitly has an 'any' type.": 1, "test/claude-code-runner.test.ts\tTS7006\tParameter 'delay' implicitly has an 'any' type.": 1, "test/claude-code-runner.test.ts\tTS7019\tRest parameter 'args' implicitly has an 'any[]' type.": 1, - "test/cso-eval.test.ts\tTS2345\tArgument of type '(command: string, args: readonly string[] | undefined, options: any) => string' is not assignable to parameter of type '{ (file: string): NonSharedBuffer; (file: string, options: ExecFileSyncOptionsWithStringEncoding): string; (file: string, options: ExecFileSyncOptionsWithBufferEncoding): NonSharedBuffer; (file: string, options?: ExecFileSyncOptions | undefined): string | NonSharedBuffer; (file: string, args: readonly string[]): Non...'. Target signature provides too few arguments. Expected 3 or more, but got 1.": 1, - "test/cso-eval.test.ts\tTS2790\tThe operand of a 'delete' operator must be optional.": 1, - "test/cso-eval.test.ts\tTS7005\tVariable 'receipts' implicitly has an 'any[]' type.": 1, - "test/cso-eval.test.ts\tTS7034\tVariable 'receipts' implicitly has type 'any[]' in some locations where its type cannot be determined.": 1, - "test/cso-lease-identity.test.ts\tTS2365\tOperator '*' cannot be applied to types 'number' and 'bigint'.": 1, - "test/cso-ntfs-fixture.test.ts\tTS2769\tNo overload matches this call. The last overload gave the following error. Argument of type 'bigint | undefined' is not assignable to parameter of type 'bigint'. Type 'undefined' is not assignable to type 'bigint'.": 1, - "test/cso-preparation-executor.test.ts\tTS2339\tProperty 'sidecar' does not exist on type 'PreparedDatabaseContract'. Property 'sidecar' does not exist on type '{ adapter: \"sqlite\"; connections: string[]; }'.": 1, - "test/cso-public-ghcr.test.ts\tTS2352\tConversion of type '() => Promise' to type 'typeof fetch' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property 'preconnect' is missing in type '() => Promise' but required in type 'typeof fetch'.": 1, "test/design-catalog.test.ts\tTS2769\tNo overload matches this call. The last overload gave the following error. Argument of type 'string' is not assignable to parameter of type '\"quality\" | \"slop\"'.": 1, "test/design-completion-handoff-scored.test.ts\tTS2352\tConversion of type '({ answered: boolean; answeredAt: string; answers: { ...; }; failed: boolean; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; sessionId: string; toolUseId: string; unansweredQuestionIndices: never[]; } | ... 10 more ... | { ...; })[]' to type 'NativePlanQuestionCall[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type '{ answered: boolean; answeredAt: string; answers: { ...; }; failed: boolean; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; sessionId: string; toolUseId: string; unansweredQuestionIndices: never[]; } | ... 10 more ... | { ...; }' is not comparable to type 'NativePlanQuestionCall'. Type '{ sessionId: string; toolUseId: string; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; answered: boolean; failed: boolean; answers: { \"Pass 1 (Info Architecture) \\u2014 7/10. The plan has DOM order and heading structure, but no scan path ...' is not comparable to type 'NativePlanQuestionCall'. Types of property 'answers' are incompatible. Type '{ \"Pass 1 (Info Architecture) \\u2014 7/10. The plan has DOM order and heading structure, but no scan path specification: what does the user's eye land on first, second, third? The Visual Hierarchy gap identifies that Save is indistinguishable from other buttons, but names it as a styling problem rather than an IA pr...' is not comparable to type 'Record'. Property '\"Pass 1 (Info Architecture) \\u2014 7/10. The plan has DOM order and heading structure, but no scan path specification: what does the user's eye land on first, second, third? The Visual Hierarchy gap identifies that Save is indistinguishable from other buttons, but names it as a styling problem rather than an IA problem \\u2014 the primary action is missing from the visual hierarchy. Should I add a scan path description to the plan? \"' is incompatible with index signature. Type 'undefined' is not comparable to type 'string'.": 1, "test/design-completion-handoff-scored.test.ts\tTS2352\tConversion of type '({ answered: boolean; answeredAt: string; answers: { ...; }; failed: boolean; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; sessionId: string; toolUseId: string; unansweredQuestionIndices: never[]; } | ... 4 more ... | { ...; })[]' to type 'NativePlanQuestionCall[]' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Type '{ answered: boolean; answeredAt: string; answers: { ...; }; failed: boolean; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; sessionId: string; toolUseId: string; unansweredQuestionIndices: never[]; } | ... 4 more ... | { ...; }' is not comparable to type 'NativePlanQuestionCall'. Type '{ sessionId: string; toolUseId: string; questions: { header: string; multiSelect: boolean; options: { description: string; label: string; }[]; question: string; }[]; answered: boolean; failed: boolean; answers: { \"Pass 1 \\u2014 Visual Hierarchy: The plan lists this gap but has no fix. The Save button renders with th...' is not comparable to type 'NativePlanQuestionCall'. Types of property 'answers' are incompatible. Type '{ \"Pass 1 \\u2014 Visual Hierarchy: The plan lists this gap but has no fix. The Save button renders with the same size, weight, and color as Reset, Cancel, and Export. DESIGN.md already specifies the remedy: Save gets #1d4ed8 fill with white text; the other three are ghost neutral buttons. Should I add this fix speci...' is not comparable to type 'Record'. Property '\"Pass 1 \\u2014 Visual Hierarchy: The plan lists this gap but has no fix. The Save button renders with the same size, weight, and color as Reset, Cancel, and Export. DESIGN.md already specifies the remedy: Save gets #1d4ed8 fill with white text; the other three are ghost neutral buttons. Should I add this fix specification to the plan? \"' is incompatible with index signature. Type 'undefined' is not comparable to type 'string'.": 1, diff --git a/test/build-cso-nonfatal.test.ts b/test/build-cso-nonfatal.test.ts deleted file mode 100644 index ceeea31fe..000000000 --- a/test/build-cso-nonfatal.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { runBashScript } from './helpers/bash-script'; - -// #3071: CSO is optional, so a failed CSO build or publish must not abort -// scripts/build.sh before the browse server bundle and the completion stamp. -// GSTACK_STRICT_BUILD=1 (CI) keeps it fatal. Runs build.sh's real CSO block -// with scripts/build-cso.sh replaced by a stub that fails at a chosen stage. -const ROOT = path.resolve(import.meta.dir, '..'); -const BUILD = fs.readFileSync(path.join(ROOT, 'scripts/build.sh'), 'utf8'); -const START = 'if [ "${GSTACK_SETUP_RUNNING:-0}" = "1" ] && [ "${GSTACK_SETUP_SKIP_CSO_BUILD:-0}" = "1" ]; then'; -const END = '\nbash browse/scripts/build-node-server.sh'; -const block = BUILD.slice(BUILD.indexOf(START), BUILD.indexOf(END)); -const tmps: string[] = []; -afterEach(() => { for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true, force: true }); }); - -function run(strict: string | undefined, status = 1) { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-build-cso-nonfatal-')); - tmps.push(dir); - fs.mkdirSync(path.join(dir, 'bin')); - fs.mkdirSync(path.join(dir, 'scripts')); - fs.writeFileSync(path.join(dir, 'scripts/build-cso.sh'), [ - 'echo "stub CSO output (log=$GSTACK_CSO_BUILD_LOG)"', - 'echo "Staged CSO core is not one executable regular file." >&2', - "printf 'result=failed\\nstage=publish\\n' > bin/.gstack-cso-build-result", - `exit ${status}`, '', - ].join('\n')); - const env: Record = { PATH: process.env.PATH ?? '' }; - if (strict !== undefined) env.GSTACK_STRICT_BUILD = strict; - const r = runBashScript(`set -e\nROOT=${JSON.stringify(dir)}\nBUN_CMD=bun\n${block}\necho BUILD-CONTINUED`, { cwd: dir, env, timeout: 15_000 }); - return { ...r, dir, log: path.join(dir, 'bin/.gstack-cso-build.log') }; -} - -// The block runs under any bash; Windows paths in the messages would only add -// quoting noise, and the Windows lane covers this in windows-setup-e2e. -describe.skipIf(process.platform === 'win32')('scripts/build.sh: CSO failure is non-fatal unless GSTACK_STRICT_BUILD=1 (#3071)', () => { - test('a CSO publish failure is reported with its stage, log and retry, and the build continues', () => { - const r = run(undefined); - expect(r.status).toBe(0); - expect(r.stdout).toContain('BUILD-CONTINUED'); - expect(r.stderr).toContain('CSO unavailable: the publish step failed; the rest of the build continues.'); - expect(r.stderr).toContain(`Log: ${r.log}`); - expect(r.stderr).toContain(`Retry: cd ${r.dir} && bun run build:cso`); - const log = fs.readFileSync(r.log, 'utf8'); - expect(log).toContain(`stub CSO output (log=${r.log})`); - expect(log).toContain('Staged CSO core is not one executable regular file.'); - }); - - test('GSTACK_STRICT_BUILD=0 is the same non-fatal path', () => { - expect(run('0').status).toBe(0); - }); - - test('GSTACK_STRICT_BUILD=1 makes the same failure fatal', () => { - const r = run('1'); - expect(r.status).toBe(1); - expect(r.stdout).not.toContain('BUILD-CONTINUED'); - expect(r.stderr).toContain('CSO publish failed and GSTACK_STRICT_BUILD=1 makes it fatal.'); - }); - - test('a successful CSO build prints no unavailable line', () => { - const r = run('1', 0); - expect(r.status).toBe(0); - expect(r.stderr).not.toContain('CSO unavailable'); - }); - -}); - -describe('scripts/build.sh: CSO step order (#3071)', () => { - test('the server bundle and stamp still come after the CSO step', () => { - const cso = BUILD.indexOf('bash scripts/build-cso.sh'); - expect(BUILD.indexOf('bash browse/scripts/build-node-server.sh')).toBeGreaterThan(cso); - expect(BUILD.indexOf('mv -f "$BUILD_STAMP_TMP" "$BUILD_STAMP"')).toBeGreaterThan(cso); - }); -}); diff --git a/test/build-cso-result-record.test.ts b/test/build-cso-result-record.test.ts deleted file mode 100644 index 86a81821b..000000000 --- a/test/build-cso-result-record.test.ts +++ /dev/null @@ -1,129 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { dirname, join, resolve } from 'node:path'; -import { runBashScript } from './helpers/bash-script'; - -// #3071: scripts/build-cso.sh records each run's outcome in -// bin/.gstack-cso-build-result for setup's summary and gstack-doctor, and the -// parent clears its EXIT trap before exec'ing the native publisher so only the -// locked child cleans the stage. The real script runs; only compilation and -// the publisher lock are substituted (same seam as test/cso-distribution.test.ts). -const ROOT = resolve(import.meta.dir, '..'); -const temps: string[] = []; -afterEach(() => { for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true }); }); -const quote = (s: string) => "'" + s.replaceAll("'", "'\\''") + "'"; - -function fixture() { - const dir = mkdtempSync(join(tmpdir(), 'gstack-cso-result-')); temps.push(dir); - for (const sub of ['scripts', 'bin', 'lib/cso']) mkdirSync(join(dir, sub), { recursive: true }); - copyFileSync(join(ROOT, 'scripts/build-cso.sh'), join(dir, 'scripts/build-cso.sh')); - writeFileSync(join(dir, 'VERSION'), '9.9.9.9\n'); - writeFileSync(join(dir, 'publish lock'), '#!/bin/sh\nset -eu\nshift\nexport GSTACK_CSO_PUBLISH_LOCKED=1\nexec "$@"\n'); - chmodSync(join(dir, 'publish lock'), 0o755); - const compiler = [ - '#!/bin/sh', 'set -eu', - 'count_file="$CSO_FIXTURE/compiler.count"; count=0', - '[ ! -f "$count_file" ] || count=$(cat "$count_file")', - 'count=$((count+1)); printf "%s\\n" "$count" > "$count_file"', - 'if [ "${CSO_FAIL_COMPILER_N:-0}" = "$count" ]; then echo "fixture compiler failed" >&2; exit 42; fi', - 'output=""', - 'while [ "$#" -gt 0 ]; do case "$1" in --outfile|-o) shift; output="$1" ;; esac; shift; done', - 'if [ -n "$output" ]; then', - ' case "$output" in', - ' *gstack-cso-publish-lock*) cp "$CSO_FIXTURE/publish lock" "$output" ;;', - ' *) printf "#!/bin/sh\\nprintf NEW\\\\n\\n" > "$output" ;;', - ' esac', - ' chmod +x "$output"', - 'fi', '', - ].join('\n'); - writeFileSync(join(dir, 'compiler'), compiler); chmodSync(join(dir, 'compiler'), 0o755); - return dir; -} - -function seedOld(dir: string, installed = '9.9.9.8 (0123456789ab)') { - for (const name of ['gstack-cso-launcher', 'gstack-cso-core', 'gstack-cso-watchdog']) { - writeFileSync(join(dir, 'bin', name), '#!/bin/sh\nprintf OLD\\\\n\n'); chmodSync(join(dir, 'bin', name), 0o755); - } - writeFileSync(join(dir, 'bin', '.gstack-cso-generation'), '0'.repeat(64) + '\n'); - writeFileSync(join(dir, 'bin', '.gstack-cso-build-result'), `result=ok\nstage=publish\nreason=committed\nrevision=${installed}\ninstalled=${installed}\nlauncher=yes\ndiagnostic=old\n`); -} - -function build(dir: string, env = '') { - return runBashScript(`${env} GIT_CEILING_DIRECTORIES=${quote(dirname(dir))} CSO_FIXTURE=${quote(dir)} BUN_CMD=${quote(join(dir, 'compiler'))} CSO_CC=${quote(join(dir, 'compiler'))} bash ${quote(join(dir, 'scripts/build-cso.sh'))}`, { timeout: 15_000 }); -} - -function record(dir: string): Record { - const out: Record = {}; - for (const line of readFileSync(join(dir, 'bin', '.gstack-cso-build-result'), 'utf8').trim().split('\n')) { - const at = line.indexOf('='); - out[line.slice(0, at)] = line.slice(at + 1); - } - return out; -} -const stages = (dir: string) => readdirSync(join(dir, 'bin')).filter(name => name.startsWith('.gstack-cso-stage.')); -const launcherOutput = (dir: string) => readFileSync(join(dir, 'bin', 'gstack-cso-launcher'), 'utf8'); - -describe.skipIf(process.platform === 'win32')('build-cso.sh build-result record (#3071)', () => { - test('a successful build records ok with this revision installed', () => { - const dir = fixture(); - const r = build(dir, `GSTACK_CSO_BUILD_LOG=${quote(join(dir, 'cso.log'))}`); - expect(r.status, r.stderr).toBe(0); - expect(record(dir)).toMatchObject({ result: 'ok', stage: 'publish', revision: '9.9.9.9', installed: '9.9.9.9', launcher: 'yes', diagnostic: join(dir, 'cso.log') }); - expect(stages(dir)).toEqual([]); - }); - - test('a fresh build failure records the build stage with no usable launcher', () => { - const dir = fixture(); - const r = build(dir, 'CSO_FAIL_COMPILER_N=1'); - expect(r.status).toBe(42); - expect(record(dir)).toMatchObject({ result: 'failed', stage: 'build', reason: 'exit 42', installed: '', launcher: 'no' }); - expect(stages(dir)).toEqual([]); - }); - - test('a failed upgrade keeps the previous generation and names its revision', () => { - const dir = fixture(); seedOld(dir); - const r = build(dir, 'GSTACK_CSO_BUILD_TESTING=1 GSTACK_CSO_BUILD_TEST_FAIL_AFTER=publish-core'); - expect(r.status).toBe(86); - expect(launcherOutput(dir)).toContain('OLD'); - expect(record(dir)).toMatchObject({ result: 'failed', stage: 'publish', reason: 'exit 86', revision: '9.9.9.9', installed: '9.9.9.8 (0123456789ab)', launcher: 'yes' }); - expect(stages(dir)).toEqual([]); - }); - - test('a publish killed mid-flight leaves an interrupted publish record', () => { - const dir = fixture(); seedOld(dir); - const r = build(dir, 'GSTACK_CSO_BUILD_TESTING=1 GSTACK_CSO_BUILD_TEST_KILL_AFTER=publish-core'); - expect(r.status).not.toBe(0); - expect(record(dir)).toMatchObject({ result: 'failed', stage: 'publish', reason: 'interrupted' }); - expect(existsSync(join(dir, 'bin', 'gstack-cso-launcher'))).toBe(false); - }); - - test('a missing publisher at exec time cleans the stage and keeps the old generation', () => { - const dir = fixture(); seedOld(dir); - const r = build(dir, 'GSTACK_CSO_BUILD_TESTING=1 GSTACK_CSO_BUILD_TEST_REMOVE_LOCKER_AFTER=before-exec'); - expect(r.status).toBe(127); - expect(r.stderr).toContain('CSO publication could not start'); - expect(stages(dir)).toEqual([]); - expect(launcherOutput(dir)).toContain('OLD'); - expect(record(dir)).toMatchObject({ result: 'failed', stage: 'publish', reason: 'exit 127', installed: '9.9.9.8 (0123456789ab)', launcher: 'yes' }); - }); -}); - -describe('build-cso.sh publisher handoff (#3071)', () => { - const source = readFileSync(join(ROOT, 'scripts/build-cso.sh'), 'utf8'); - test('the parent checks the publisher, then clears its EXIT trap, then execs', () => { - const exec = source.indexOf('exec "$CSO_STAGE_LOCKER"'); - const clear = source.lastIndexOf('trap - EXIT', exec); - const check = source.lastIndexOf('cso_valid_artifact "$CSO_STAGE_LOCKER"', clear); - expect(exec).toBeGreaterThan(0); - expect(clear).toBeGreaterThan(check); - expect(check).toBeGreaterThan(0); - expect(source.slice(check, exec)).toContain('shopt -s execfail'); - expect(source.slice(exec)).toContain('cso_cleanup "$cso_exec_status"'); - }); - - test('the Windows build prefers PowerShell 7 and falls back to Windows PowerShell', () => { - expect(source).toContain('CSO_POWERSHELL="$(command -v pwsh 2>/dev/null || command -v powershell.exe 2>/dev/null || true)"'); - expect(source).not.toMatch(/^\s*powershell\.exe /m); - }); -}); diff --git a/test/ci-history-read.test.ts b/test/ci-history-read.test.ts index 179414e46..5b59a4b3e 100644 --- a/test/ci-history-read.test.ts +++ b/test/ci-history-read.test.ts @@ -35,8 +35,6 @@ afterAll(() => { /** Workflows that keep full clones, by file name, each with its reason. */ const FULL_CLONE_WORKFLOWS: Record = { 'weekly-release.yml': 'release: cuts and tags from main; off the PR and train path and not yet dispatched once blobless', - 'cso-runtime-promote.yml': 'CSO image promotion; off the PR and train path and not yet dispatched once blobless', - 'cso-runtime-qualification.yml': 'CSO runtime qualification; off the PR and train path and not yet dispatched once blobless', 'evals-periodic.yml': 'periodic evals; off the PR and train path and not yet dispatched once blobless', 'evals-marathon.yml': 'marathon evals; off the PR and train path and not yet dispatched once blobless', 'eval-sweep.yml': 'eval sweep; off the PR and train path and not yet dispatched once blobless', diff --git a/test/cso-audit-paths.test.ts b/test/cso-audit-paths.test.ts deleted file mode 100644 index 33dba7464..000000000 --- a/test/cso-audit-paths.test.ts +++ /dev/null @@ -1,348 +0,0 @@ -// /cso --paths audit scope (field list 2, item 12): a repository over the source -// cap can be audited by naming the subtree to read, and every skipped path stays -// in the manifest unread and is reported as a snapshot-inputs gap. -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { OUTSIDE_AUDIT_PATHS, capture, snapshotManifestCapMessage, sourceCapMessage } from '../lib/cso/snapshot'; -import { newRun, readJson, saveReport } from '../lib/cso/state'; -import { MAX_OUTPUT, canonical, sha256, type VerificationObservation } from '../lib/cso/contracts'; -import { ISOLATION_POLICY_HASH } from '../lib/cso/docker'; -import { canonicalStartPlan, canonicalTestPlan, patchHash, verifyRepair } from '../lib/cso/verification'; -import { replayRuntimeRejection } from './helpers/cso-runtime-catalog'; - -const ROOT = path.resolve(import.meta.dir, '..'); -const launcher = path.join(ROOT, 'bin', process.platform === 'win32' ? 'gstack-cso-launcher.exe' : 'gstack-cso-launcher'); -const MIB = 1024 * 1024; -let root = ''; -let state = ''; -const originalHome = process.env.GSTACK_HOME; - -function git(repo: string, ...args: string[]): string { - const result = spawnSync('/usr/bin/git', ['-C', repo, ...args], { encoding: 'utf8', env: { HOME: root, PATH: '/usr/bin:/bin' }, timeout: 60_000 }); - if (result.status) throw new Error(result.stderr); - return result.stdout; -} -function cso(repo: string, args: string[], home = state) { - return spawnSync(launcher, args, { cwd: repo, encoding: 'utf8', env: { HOME: root, GSTACK_HOME: home, PATH: '/usr/bin:/bin' }, timeout: 120_000, maxBuffer: 64 * MIB }); -} -function makeRepo(name: string, files: Record): string { - const repo = path.join(root, name); - fs.mkdirSync(repo); - git(repo, 'init', '-q'); - git(repo, 'config', 'user.email', 'fixture@example.test'); - git(repo, 'config', 'user.name', 'Fixture'); - for (const [file, body] of Object.entries(files)) { - fs.mkdirSync(path.dirname(path.join(repo, file)), { recursive: true }); - fs.writeFileSync(path.join(repo, file), body); - } - git(repo, 'add', '-A'); - git(repo, 'commit', '-qm', 'fixture'); - return repo; -} -function runDir(run: { repoId: string; runId: string }): string { - return path.join(state, 'security', 'cso', run.repoId, run.runId); -} -function listFiles(dir: string): string[] { - if (!fs.existsSync(dir)) return []; - return fs.readdirSync(dir, { recursive: true, withFileTypes: true }).filter((item) => item.isFile()).map((item) => path.relative(dir, path.join(item.parentPath, item.name)).split(path.sep).join('/')).sort(); -} -function runDirs(home: string): string[] { - const base = path.join(home, 'security', 'cso'); - if (!fs.existsSync(base)) return []; - return fs.readdirSync(base, { withFileTypes: true }).filter((repo) => repo.isDirectory()).flatMap((repo) => fs.readdirSync(path.join(base, repo.name), { withFileTypes: true }).filter((run) => run.isDirectory()).map((run) => `${repo.name}/${run.name}`)).sort(); -} -function error(result: ReturnType) { - expect(result.status).not.toBe(0); - expect(result.stdout).toBe(''); - return JSON.parse(result.stderr).error; -} -const USERS = 'export const tenantQuery = (id:string) => db.user.findUnique({where:{id}})\n'; -const application = { actors: ['tenant user'], assets: ['tenant records'], entrypoints: ['GET /users/:id'], tenantBoundaries: ['tenant id'], sensitiveOperations: ['record read'], invariants: ['tenant isolation'] }; -const finding = { title: 'Cross-tenant user read', rootCause: 'Tenant query omits caller tenant predicate', location: { path: 'src/core/users.ts', line: 1, symbol: 'tenantQuery' }, advisoryIds: [], severity: 'high', confidence: 'high', confidenceRationale: 'The caller-to-query trace and missing tenant predicate directly support the finding', evidence: 'supported', attackerControl: 'Authenticated caller chooses the record ID', impact: 'Another tenant record is returned', scenario: 'A tenant supplies a known record ID owned by another tenant and receives that record', trace: ['GET /users/:id', 'tenantQuery', 'findUnique by id'], references: ['src/core/users.ts:1', 'OWASP API1:2023'], recommendation: 'Bind the lookup predicate to the authenticated tenant identifier', challenge: { reviewer: 'independent-2', independent: true, mode: 'independent_agent', callers: 'Authenticated route forwards the ID', controls: 'Authentication does not bind tenant', counterevidence: 'Opaque IDs reduce guessing but do not authorize', conclusion: 'The authorization invariant is absent' } }; - -beforeAll(() => { - root = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-paths-')); - state = path.join(root, 'state'); - process.env.GSTACK_HOME = state; -}); -afterAll(() => { - if (originalHome === undefined) delete process.env.GSTACK_HOME; - else process.env.GSTACK_HOME = originalHome; - fs.rmSync(root, { recursive: true, force: true }); -}); - -describe('CSO --paths audit scope', () => { - test('only the source cap advises --paths; the manifest cap and entry limit, which still count skipped paths, do not', async () => { - const source = sourceCapMessage(346_199_207, 7_561); - expect(source).toContain('rerun with --paths'); - expect(source).toContain('counts every skipped path'); - expect(source).not.toContain('smaller checkout'); - const manifest = snapshotManifestCapMessage(61_234, 17_000_000); - expect(manifest).not.toContain('--paths'); - expect(manifest).toContain('No supported workaround raises this cap'); - - const repo = makeRepo('entry-limit-scoped', { 'src/core/users.ts': USERS, 'a.txt': 'a\n', 'b.txt': 'b\n' }); - const refused = await capture(repo, newRun(repo).dir, undefined, undefined, { maxEntries: 2 }, ['src/core']).then( - () => undefined, - (error) => error, - ); - expect(refused?.code).toBe('MISSING_INPUT'); - expect(refused?.message).toBe('Source tree exceeds the 2-entry snapshot admission limit'); - }); - - test('a repository over the source cap is admitted with --paths, and every skipped path is disclosed unread', () => { - const repo = makeRepo('over-cap-scoped', { - 'src/core/users.ts': USERS, - 'src/mcp/server.ts': 'export const serve = () => 1\n', - 'assets/a.bin': Buffer.alloc(40 * MIB, 1), - 'assets/b.bin': Buffer.alloc(25 * MIB, 1), - 'README.md': '# fixture\n', - 'src/core-utils/x.ts': 'export const lookalike = 1\n', - }); - const capped = error(cso(repo, ['start', '--repo', repo, '--offline'])).message; - expect(capped).toStartWith('64 MiB source cap exceeded:'); - expect(capped).toContain('rerun with --paths'); - - const started = cso(repo, ['start', '--repo', repo, '--offline', '--paths', 'src/mcp,src/core/,src/core']); - expect(started.stderr).toBe(''); - expect(started.status).toBe(0); - const run = JSON.parse(started.stdout), - dir = runDir(run), - report = readJson(path.join(dir, 'report.json')), - manifest = readJson(path.join(dir, 'snapshot.json'), 16 * MIB); - expect(report.policy.paths).toEqual(['src/core', 'src/mcp']); - - const skipped = ['README.md', 'assets/a.bin', 'assets/b.bin', 'src/core-utils/x.ts']; - for (const file of skipped) { - const entry = manifest.entries.find((item: any) => item.path === file); - expect(entry).toMatchObject({ originalHash: 'not-read', transformation: OUTSIDE_AUDIT_PATHS, bytes: fs.statSync(path.join(repo, file)).size }); - expect(entry.executionHash).toBeUndefined(); - } - expect(OUTSIDE_AUDIT_PATHS).toStartWith('withheld:'); - expect(listFiles(path.join(dir, 'snapshot'))).toEqual(['src/core/users.ts', 'src/mcp/server.ts']); - expect(listFiles(path.join(dir, 'readable'))).toEqual(['src/core/users.ts', 'src/mcp/server.ts']); - - const coverage = report.coverage.find((item: any) => item.domain === 'snapshot-inputs'); - expect(coverage.status).toBe('partial'); - expect(coverage.gaps).toEqual(skipped.map((file) => `${file}: outside the --paths audit scope; payload was not captured or assessed`)); - expect(coverage.evidence).toEqual(['2 sanitized execution inputs captured; 0 explicit non-executable exclusions; 0 unread in-scope inputs; 0 tracked deletions; audit limited by --paths to src/core, src/mcp, so 4 source files were skipped']); - expect(report.source.transformations).toEqual([]); - const history = fs.readFileSync(path.join(dir, 'history.txt'), 'utf8'); - expect(history).toContain('src/core/users.ts'); - expect(history).not.toContain('assets/a.bin'); - expect(history).not.toContain('src/core-utils/x.ts'); - const historyCoverage = report.coverage.find((item: any) => item.domain === 'history-inputs'); - expect(historyCoverage.evidence[0]).toContain('limited to --paths src/core, src/mcp'); - expect(historyCoverage).toMatchObject({ status: 'partial', gaps: ['History outside the --paths audit scope (src/core, src/mcp) was not retained or assessed'] }); - expect(cso(repo, ['history', run.runId, 'src/core/users.ts']).stdout).toContain('src/core/users.ts'); - expect(error(cso(repo, ['history', run.runId, 'assets/a.bin']))).toEqual({ code: 'INVALID_ARGUMENT', message: 'History path is outside the --paths audit scope (src/core, src/mcp); its history was not retained' }); - - const based = cso(repo, ['start', '--repo', repo, '--offline', '--base', 'HEAD', '--paths', 'src/core,src/mcp']); - expect(based.stderr).toBe(''); - expect(readJson(path.join(runDir(JSON.parse(based.stdout)), 'snapshot.json'), 16 * MIB).changedPaths).toEqual([]); - - fs.rmSync(path.join(repo, 'README.md')); - const deleted = cso(repo, ['start', '--repo', repo, '--offline', '--paths', 'src/core,src/mcp']); - expect(deleted.stderr).toBe(''); - const deletedReport = readJson(path.join(runDir(JSON.parse(deleted.stdout)), 'report.json')), - deletedCoverage = deletedReport.coverage.find((item: any) => item.domain === 'snapshot-inputs'); - expect(deletedReport.source.transformations).toEqual([]); - expect(deletedCoverage.gaps).toEqual([...skipped.slice(1), 'README.md'].map((file) => `${file}: outside the --paths audit scope; payload was not captured or assessed`)); - expect(deletedCoverage.evidence[0]).toContain('0 tracked deletions; audit limited by --paths to src/core, src/mcp, so 4 source files were skipped'); - }, 180_000); - - test('in-scope gaps are listed before skipped paths, so the bounded list never hides them', () => { - const files: Record = { 'z/app.ts': USERS, 'z/blob.dat': Buffer.from('a\0b') }; - for (let i = 0; i < 3000; i++) files[`a/long-out-of-scope-directory-name/file_number_${i}.ts`] = `export const v${i} = ${i};\n`; - const repo = makeRepo('gap-order', files), - started = cso(repo, ['start', '--repo', repo, '--offline', '--paths', 'z']); - expect(started.status).toBe(0); - const coverage = readJson(path.join(runDir(JSON.parse(started.stdout)), 'report.json')).coverage.find((item: any) => item.domain === 'snapshot-inputs'); - expect(coverage.gaps[0]).toBe('z/blob.dat: in-scope source payload was unread and withheld from static and runtime assessment'); - expect(coverage.gaps.at(-1)).toMatch(/^\d+ more unread, deleted or out-of-scope inputs are not listed/); - expect(coverage.evidence[0]).toContain('1 unread in-scope input;'); - expect(coverage.evidence[0]).toContain('so 3000 source files were skipped'); - }, 180_000); - - test('a comparison base hashes out-of-scope files in bounded chunks', async () => { - const repo = makeRepo('bounded-hash', { 'src/core/users.ts': USERS, 'assets/big.bin': Buffer.alloc(8 * MIB, 0x61) }); - const realAlloc = Buffer.alloc; - let largest = 0; - (Buffer as any).alloc = (size: number, ...rest: any[]) => { - largest = Math.max(largest, size); - return (realAlloc as any).call(Buffer, size, ...rest); - }; - try { - expect((await capture(repo, newRun(repo).dir, 'HEAD', undefined, {}, ['src/core'])).changedPaths).toEqual([]); - expect(largest).toBeLessThanOrEqual(MAX_OUTPUT); - fs.appendFileSync(path.join(repo, 'assets', 'big.bin'), 'x'); - expect((await capture(repo, newRun(repo).dir, 'HEAD', undefined, {}, ['src/core'])).changedPaths).toEqual(['assets/big.bin']); - } finally { - (Buffer as any).alloc = realAlloc; - } - }, 120_000); - - test.skipIf(process.platform === 'win32' || process.getuid?.() === 0)('capture never opens an out-of-scope payload when there is no comparison base', async () => { - const repo = makeRepo('unreadable-outside', { 'src/core/users.ts': USERS, 'secret/blob.txt': 'outside the audit\n' }); - fs.chmodSync(path.join(repo, 'secret', 'blob.txt'), 0o000); - try { - await expect(capture(repo, newRun(repo).dir)).rejects.toThrow('Source could not be opened as a regular file: secret/blob.txt'); - const run = newRun(repo), - manifest = await capture(repo, run.dir, undefined, undefined, {}, ['src/core']); - expect(manifest.entries.find((entry) => entry.path === 'secret/blob.txt')).toMatchObject({ originalHash: 'not-read', transformation: OUTSIDE_AUDIT_PATHS, bytes: 18 }); - expect(listFiles(path.join(run.dir, 'snapshot'))).toEqual(['src/core/users.ts']); - await expect(capture(repo, newRun(repo).dir, 'HEAD', undefined, {}, ['src/core'])).rejects.toThrow('Source could not be opened as a regular file: secret/blob.txt'); - } finally { - fs.chmodSync(path.join(repo, 'secret', 'blob.txt'), 0o644); - } - }); - - test('invalid --paths values are refused and leave no run', () => { - const repo = makeRepo('invalid-paths', { 'src/core/users.ts': USERS }); - const home = path.join(root, 'invalid-state'), - many = Array.from({ length: 33 }, (_, i) => `src/p${i}`).join(','); - for (const value of ['', ',', '../src', 'src/../x', '/src', '-src', 'src//core', 'src/./core', 'src\\core', 'src\ncore', many, 'a'.repeat(257), 'src,'.repeat(260)]) { - const refused = error(cso(repo, ['start', '--repo', repo, '--offline', '--paths', value], home)); - expect(refused.code).toBe('INVALID_ARGUMENT'); - } - const unmatched = error(cso(repo, ['start', '--repo', repo, '--offline', '--paths', 'src/core,src/typo'], home)); - expect(unmatched).toEqual({ code: 'INVALID_ARGUMENT', message: '--paths entry matches no source file: src/typo' }); - expect(error(cso(repo, ['start', '--repo', repo, '--paths'], home)).message).toBe('--paths requires a value'); - expect(error(cso(repo, ['start', '--repo', repo, '--offline', '--paths', 'rootfs/home/user/app'], home))).toEqual({ code: 'INVALID_ARGUMENT', message: '--paths entry would be altered by report redaction; choose a shorter or broader prefix' }); - expect(error(cso(repo, ['start', '--repo', repo, '--offline', '--paths', 'mirror/actions/runs/42'], home)).message).toBe('--paths entry would be altered by report redaction; choose a shorter or broader prefix'); - expect(runDirs(home)).toEqual([]); - }, 120_000); - - test('--diff refuses changed paths outside --paths and compares unchanged ones without reporting them', () => { - const repo = makeRepo('diff-scope', { 'src/core/users.ts': USERS, 'src/other/a.ts': 'export const a = 1\n', 'docs/b.md': 'b\n', 'AGENTS.md': '# agents\n', 'node_modules/dep/index.js': 'module.exports = 1\n' }), - base = git(repo, 'rev-parse', 'HEAD').trim(), - home = path.join(root, 'diff-state'), - start = () => cso(repo, ['start', '--repo', repo, '--offline', '--diff', '--base', base, '--paths', 'src/core'], home); - - fs.writeFileSync(path.join(repo, 'src/core/users.ts'), USERS + '// changed\n'); - fs.writeFileSync(path.join(repo, 'node_modules/dep/index.js'), 'module.exports = 2\n'); - const accepted = start(); - expect(accepted.stderr).toBe(''); - expect(accepted.status).toBe(0); - const run = JSON.parse(accepted.stdout), - manifest = readJson(path.join(home, 'security', 'cso', run.repoId, run.runId, 'snapshot.json'), 16 * MIB); - expect(manifest.changedPaths).toEqual(['node_modules/dep/index.js', 'src/core/users.ts']); - - fs.writeFileSync(path.join(repo, 'AGENTS.md'), '# agents, edited\n'); - fs.writeFileSync(path.join(repo, '.npmrc'), 'registry=https://registry.example.test/\n'); - expect(error(start()).message).toContain('--diff found 2 changed paths outside --paths (src/core): .npmrc, AGENTS.md.'); - git(repo, 'checkout', '--', 'AGENTS.md'); - fs.rmSync(path.join(repo, '.npmrc')); - - fs.writeFileSync(path.join(repo, 'src/other/a.ts'), 'export const a = 2\n'); - const modified = error(start()); - expect(modified.code).toBe('INVALID_ARGUMENT'); - expect(modified.message).toContain('--diff found 1 changed path outside --paths (src/core): src/other/a.ts.'); - git(repo, 'checkout', '--', 'src/other/a.ts'); - - fs.rmSync(path.join(repo, 'docs/b.md')); - fs.writeFileSync(path.join(repo, 'new.ts'), 'export const n = 1\n'); - const added = error(start()); - expect(added.message).toContain('--diff found 2 changed paths outside --paths (src/core): docs/b.md, new.ts.'); - fs.mkdirSync(path.join(repo, 'many')); - for (let i = 0; i < 21; i++) fs.writeFileSync(path.join(repo, 'many', `f${String(i).padStart(2, '0')}.ts`), `export const f = ${i}\n`); - expect(error(start()).message).toContain('--diff found 23 changed paths outside --paths (src/core): docs/b.md, many/f00.ts'); - expect(error(start()).message).toContain(', and 3 more. Add them to --paths or run without --diff'); - expect(runDirs(home)).toEqual([`${run.repoId}/${run.runId}`]); - }, 180_000); - - test('recheck rebuilds the original --paths scope', () => { - const repo = makeRepo('recheck-scope', { 'src/core/users.ts': USERS, 'tools/build.ts': 'export const build = 1\n' }), - started = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline', '--paths', 'src/core']); - expect(started.status).toBe(0); - const run = JSON.parse(started.stdout), - dir = runDir(run), - initial = readJson(path.join(dir, 'report.json')), - evidence = path.join(root, 'recheck-evidence.json'); - fs.writeFileSync(evidence, JSON.stringify({ application, findings: [finding], coverage: initial.coverage.filter((item: any) => !['snapshot-inputs', 'history-inputs'].includes(item.domain)).map((item: any) => ({ ...item, status: 'assessed', method: 'fresh caller and boundary trace', gaps: [], evidence: ['current captured source'] })), gaps: [] })); - const outside = path.join(root, 'outside-finding.json'); - fs.writeFileSync(outside, JSON.stringify({ findings: [{ ...finding, location: { ...finding.location, path: 'tools/build.ts' }, references: ['tools/build.ts:1'] }] })); - const refusedFinding = error(cso(repo, ['submit', run.runId, outside])); - expect(refusedFinding).toEqual({ code: 'INVALID_SCHEMA', message: 'Finding root cause is outside the --paths audit scope: tools/build.ts' }); - expect(cso(repo, ['submit', run.runId, evidence]).status).toBe(0); - expect(cso(repo, ['finish', run.runId]).status).toBe(0); - const final = readJson(path.join(dir, 'report.json')); - expect(final.findings).toHaveLength(1); - const rechecked = cso(repo, ['recheck', final.findings[0].id, '--repo', repo]); - expect(rechecked.stderr).toBe(''); - expect(rechecked.status).toBe(0); - const childRun = JSON.parse(rechecked.stdout), - child = readJson(path.join(runDir({ ...childRun, repoId: run.repoId }), 'report.json')); - expect(child.policy.paths).toEqual(['src/core']); - expect(child.coverage.find((item: any) => item.domain === 'snapshot-inputs').gaps).toEqual(['tools/build.ts: outside the --paths audit scope; payload was not captured or assessed']); - const claim = path.join(root, 'withheld-claim.json'); - fs.writeFileSync(claim, JSON.stringify({ recheck: { findingId: final.findings[0].id, outcome: 'resolved', rootCause: finding.rootCause, evidence: [{ kind: 'caller', path: 'tools/build.ts', line: 1, observation: 'A caller outside the audit scope' }, { kind: 'security_boundary', path: 'src/core/users.ts', line: 1, observation: 'Fresh boundary trace' }] } })); - expect(error(cso(repo, ['submit', childRun.runId, claim]))).toEqual({ code: 'INVALID_SCHEMA', message: 'Recheck evidence must reference freshly captured readable source' }); - const base = git(repo, 'rev-parse', 'HEAD').trim(); - fs.appendFileSync(path.join(repo, 'src/core/users.ts'), '// reviewed change\n'); - const diffStarted = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline', '--diff', '--base', base, '--paths', 'src/core']); - expect(diffStarted.stderr).toBe(''); - const diffRun = JSON.parse(diffStarted.stdout), - diffCoverage = readJson(path.join(runDir(diffRun), 'report.json')).coverage.filter((item: any) => !['snapshot-inputs', 'history-inputs'].includes(item.domain)); - fs.writeFileSync(evidence, JSON.stringify({ application, findings: [finding], coverage: diffCoverage.map((item: any) => ({ ...item, status: 'assessed', method: 'fresh caller and boundary trace', gaps: [], evidence: ['current captured source'] })), gaps: [] })); - expect(cso(repo, ['submit', diffRun.runId, evidence]).status).toBe(0); - expect(cso(repo, ['finish', diffRun.runId]).status).toBe(0); - fs.writeFileSync(path.join(repo, 'tools/build.ts'), 'export const build = 2\n'); - expect(error(cso(repo, ['recheck', final.findings[0].id, '--run', diffRun.runId, '--repo', repo])).message).toContain('--diff found 1 changed path outside --paths (src/core): tools/build.ts. A recheck keeps the original --diff and --paths policy, so start a new audit with them added to --paths or without --diff;'); - git(repo, 'checkout', '--', '.'); - git(repo, 'mv', 'src/core', 'src/kernel'); - git(repo, 'commit', '-qm', 'rename the audited directory'); - expect(error(cso(repo, ['recheck', final.findings[0].id, '--run', run.runId, '--repo', repo]))).toEqual({ code: 'INVALID_ARGUMENT', message: '--paths entry matches no source file: src/core' }); - }, 180_000); - - test.skipIf(process.platform === 'win32')('replay from supplied source recaptures with the original --paths scope', async () => { - const repo = makeRepo('replay-scope', { - 'package.json': JSON.stringify({ name: 'cso-paths-replay', version: '1.0.0', private: true, scripts: { start: 'node app.js', test: 'node --test' } }) + '\n', - 'package-lock.json': JSON.stringify({ name: 'cso-paths-replay', version: '1.0.0', lockfileVersion: 3, requires: true, packages: { '': { name: 'cso-paths-replay', version: '1.0.0' } } }) + '\n', - 'app.js': 'module.exports = "vulnerable"\n', - 'app.test.js': "const test=require('node:test');test('legitimate control remains available',()=>{});\n", - 'docs/notes.md': 'outside the audit\n', - }); - const started = cso(repo, ['start', '--repo', repo, '--comprehensive', '--offline', '--paths', 'app.js,app.test.js,package.json,package-lock.json']); - expect(started.stderr).toBe(''); - const run = JSON.parse(started.stdout), - dir = runDir(run), - snapshot = path.join(dir, 'snapshot'), - manifest = readJson(path.join(dir, 'snapshot.json'), 16 * MIB); - expect(manifest.entries.find((entry: any) => entry.path === 'docs/notes.md').transformation).toBe(OUTSIDE_AUDIT_PATHS); - const recordFinding = { ...finding, location: { path: 'app.js', line: 1, symbol: 'recordLookup' }, references: ['app.js:1', 'OWASP API1:2023'] }, - submission = path.join(root, 'replay-finding.json'); - fs.writeFileSync(submission, JSON.stringify({ findings: [recordFinding] })); - expect(cso(repo, ['submit', run.runId, submission]).status).toBe(0); - const report = readJson(path.join(dir, 'report.json')), - start = canonicalStartPlan(snapshot, 'node', 3456), - tests = canonicalTestPlan(snapshot, 'node'), - arch = process.arch === 'arm64' ? 'arm64' : 'amd64'; - const request: any = { findingId: report.findings[0].id, runtimeProfile: `node-24.4.0-${arch}`, port: 3456, start: start.command, legitimate: [{ name: 'legitimate control', path: '/control', method: 'GET', expected: { status: 200, includes: 'CONTROL_OK' } }], security: { name: 'unauthorized record is denied', path: '/records/other', method: 'GET', expected: { status: 403, includes: 'DENIED' }, vulnerable: { status: 200, includes: 'RECORD' } }, existingTests: tests.commands, fixtures: {}, boundaryFiles: ['app.js'], testFiles: tests.files, changes: [{ path: 'app.js', beforeSha256: sha256(fs.readFileSync(path.join(snapshot, 'app.js'))), after: 'module.exports = "fixed"\n', effect: 'source' }], review: { reviewer: 'independent-reviewer', independent: true, rootCauseRepaired: true, featurePreserved: true, boundaryMocks: false, rationale: 'The caller predicate is added while the legitimate control and existing test remain unchanged.', reviewedPatchHash: '' } }; - request.review.reviewedPatchHash = patchHash(request); - const tap = 'TAP version 13\n# Subtest: legitimate control remains available\nok 1 - legitimate control remains available\n ---\n duration_ms: 1\n ...\n1..1\n# tests 1\n# suites 0\n# pass 1\n# fail 0\n# cancelled 0\n# skipped 0\n# todo 0\n', - runtime: any = { id: request.runtimeProfile, stack: 'node', platform: `linux/${arch}`, image: `ghcr.io/garrytan/gstack/cso-staging/node-${arch}@sha256:${'b'.repeat(64)}` }, - executor = { - observe: async (_source: string, phase: 'before' | 'after', received: any, _runtime: any, _verifier: any, _work: string, _control: string, _execution: any, evidence: any, witness: any) => { - const observation: VerificationObservation = { booted: true, legitimate: true, security: phase === 'before' ? 'intended_failure' : 'pass', existingTests: false, output: `external ${phase} assertions passed`, inputHash: '' }, - receipt = await witness.attest(observation, [{ command: received.existingTests[0], code: 0, output: tap, minimumPassingTests: evidence.minimumPassingTests[0] }]); - return { observation: { ...observation, existingTests: receipt.diagnosticTestsPassed, inputHash: witness.binding.harnessHash }, witness: receipt }; - }, - }; - const verified = await verifyRepair({ runId: run.runId, runDir: dir, manifest, rawRequest: request, runtime, verifier: runtime, policyHash: ISOLATION_POLICY_HASH, auditPolicyHash: sha256(canonical(report.policy)), archives: [], executor } as any); - report.findings[0].reproduction = 'reproduced'; - report.findings[0].repair = 'runtime_tested'; - report.findings[0].verificationId = verified.bundle.id; - report.findings[0].verificationAssurance = { assertions: 'authenticated_out_of_process', testCompletion: 'self_reported', review: 'self_attested' }; - saveReport(dir, report); - fs.rmSync(snapshot, { recursive: true, force: true }); - fs.rmSync(path.join(dir, 'readable'), { recursive: true, force: true }); - const supplied = cso(repo, ['replay', verified.bundle.id, '--source', repo]); - expect(supplied.status).not.toBe(0); - expect(supplied.stderr).not.toContain('does not match the bundle input hashes'); - expect(supplied.stderr).toContain(replayRuntimeRejection(request.runtimeProfile, `linux/${arch}`).message); - }, 60_000); -}); diff --git a/test/cso-bounded-file.test.ts b/test/cso-bounded-file.test.ts deleted file mode 100644 index 76d27c685..000000000 --- a/test/cso-bounded-file.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { readBoundedStable } from '../lib/cso/bounded-file'; - -const roots:string[]=[];afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); - -describe('CSO caller control-file reader',()=>{ - test.skipIf(process.platform==='win32')('cannot block on a FIFO raced over a validated regular file',()=>{ - const root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-control-file-'));roots.push(root);const input=path.join(root,'request.json'),original=path.join(root,'request.original'),fifo=path.join(root,'request.fifo');fs.writeFileSync(input,'{}\n');expect(spawnSync('/usr/bin/mkfifo',[fifo],{timeout:5_000}).status).toBe(0);const open=fs.openSync;let checked=false; - const patched=spyOn(fs,'openSync').mockImplementation(((candidate:any,flags:any,mode?:any)=>{if(String(candidate)===input){checked=true;if((Number(flags)&(fs.constants.O_NONBLOCK??0))===0)throw new Error('reader would block on raced FIFO');fs.renameSync(input,original);fs.renameSync(fifo,input);}return mode===undefined?open(candidate,flags):open(candidate,flags,mode);}) as typeof fs.openSync); - try{expect(()=>readBoundedStable(input,1024,'Input file')).toThrow('changed before it could be read');}finally{patched.mockRestore();} - expect(checked).toBe(true); - }); -}); diff --git a/test/cso-cache.test.ts b/test/cso-cache.test.ts deleted file mode 100644 index b3449d606..000000000 --- a/test/cso-cache.test.ts +++ /dev/null @@ -1,280 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { createHash } from 'node:crypto'; -import { PublicArchiveCache } from '../lib/cso/cache'; -import { CsoError } from '../lib/cso/contracts'; - -const roots: string[] = []; -function fixture(maxBytes = 1024, now: () => number = Date.now) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-cache-')); - roots.push(root); - const staging = path.join(root, 'staging'), cacheRoot = path.join(root, 'cache'); - fs.mkdirSync(staging, { mode: 0o700 }); - return { root, staging, cacheRoot, cache: new PublicArchiveCache({ root: cacheRoot, stagingRoot: staging, maxBytes, now }) }; -} -function stage(staging: string, name: string, value: string | Buffer): { path: string; digest: string } { - const file = path.join(staging, name); - fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); - fs.writeFileSync(file, value, { mode: 0o600 }); - return { path: name, digest: createHash('sha256').update(value).digest('hex') }; -} -function code(fn: () => unknown): string | undefined { - try { fn(); return undefined; } - catch (error) { return error instanceof CsoError ? error.code : undefined; } -} -afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); - -describe('CSO immutable public archive cache', () => { - test('promotes only matching bytes and verifies the full hash on every hit', () => { - let tick = 100; - const { staging, cacheRoot, cache } = fixture(1024, () => tick++); - const archive = stage(staging, 'pkg.tgz', 'verified-public-archive'); - const entry = cache.promote(archive.path, archive.digest); - expect(fs.readFileSync(entry.path, 'utf8')).toBe('verified-public-archive'); - expect(fs.statSync(cacheRoot).mode & 0o777).toBe(0o700); - expect(fs.statSync(entry.path).mode & 0o777).toBe(0o400); - expect(fs.statSync(path.join(cacheRoot, 'metadata', `${archive.digest}.json`)).mode & 0o777).toBe(0o600); - expect(cache.get(archive.digest)?.lastAccessedAt).toBeGreaterThan(entry.lastAccessedAt); - - fs.chmodSync(entry.path, 0o600); - fs.writeFileSync(entry.path, 'poisoned-public-archive'); - fs.chmodSync(entry.path, 0o400); - expect(code(() => cache.get(archive.digest))).toBe('INCOMPATIBLE_INPUT'); - }); - - test('rejects traversal, symlinks, hard links, directories, oversized files, and hash mismatches', () => { - const { root, staging, cache } = fixture(16); - const good = stage(staging, 'good', 'good'); - expect(code(() => cache.promote('../good', good.digest))).toBe('UNSAFE_PATH'); - - fs.symlinkSync(path.join(staging, 'good'), path.join(staging, 'link')); - expect(code(() => cache.promote('link', good.digest))).toBe('UNSAFE_PATH'); - fs.linkSync(path.join(staging, 'good'), path.join(staging, 'hard')); - expect(code(() => cache.promote('hard', good.digest))).toBe('UNSAFE_PATH'); - fs.unlinkSync(path.join(staging, 'hard')); - fs.mkdirSync(path.join(staging, 'directory')); - expect(code(() => cache.promote('directory', good.digest))).toBe('UNSAFE_PATH'); - - const large = stage(staging, 'large', Buffer.alloc(17, 1)); - expect(code(() => cache.promote(large.path, large.digest))).toBe('INSUFFICIENT_CAPACITY'); - expect(code(() => cache.promote(good.path, '0'.repeat(64)))).toBe('INCOMPATIBLE_INPUT'); - expect(code(() => cache.promote('/absolute', good.digest))).toBe('UNSAFE_PATH'); - expect(code(() => cache.promote(good.path, 'SHA256:bad'))).toBe('INVALID_ARGUMENT'); - expect(fs.readdirSync(path.join(root, 'cache', 'entries'))).toEqual([]); - }); - - test('evicts least-recently-used entries within a configurable byte ceiling', () => { - let now = 0; - const { staging, cache } = fixture(8, () => ++now); - const first = stage(staging, 'first', '1111'); - const second = stage(staging, 'second', '2222'); - const third = stage(staging, 'third', '3333'); - cache.promote(first.path, first.digest); - cache.promote(second.path, second.digest); - cache.get(first.digest); - cache.promote(third.path, third.digest); - expect(cache.get(first.digest)).toBeDefined(); - expect(cache.get(second.digest)).toBeUndefined(); - expect(cache.get(third.digest)).toBeDefined(); - expect(cache.stats()).toEqual({ entries: 2, bytes: 8, maxBytes: 8 }); - }); - - test('a hash-mismatched staging object cannot evict verified LRU entries', () => { - const { staging, cache } = fixture(8); - const first = stage(staging, 'first-kept', '1111'); - const second = stage(staging, 'second-kept', '2222'); - cache.promote(first.path, first.digest); - cache.promote(second.path, second.digest); - const invalid = stage(staging, 'invalid', '3333'); - expect(code(() => cache.promote(invalid.path, '0'.repeat(64)))).toBe('INCOMPATIBLE_INPUT'); - expect(cache.get(first.digest)).toBeDefined(); - expect(cache.get(second.digest)).toBeDefined(); - expect(cache.stats()).toEqual({ entries: 2, bytes: 8, maxBytes: 8 }); - }); - - test('materializes one immutable run-owned set atomically before later eviction', () => { - const { root, staging, cache } = fixture(8); - const first = stage(staging, 'first-pin', '1111'), second = stage(staging, 'second-pin', '2222'); - cache.promote(first.path, first.digest); cache.promote(second.path, second.digest); - const destination = path.join(root, 'run-owned'); fs.mkdirSync(destination, { mode: 0o700 }); - const copies = cache.materialize([first.digest, second.digest], destination); - expect(copies.map(item => item.sha256)).toEqual([first.digest, second.digest].sort()); - const third = stage(staging, 'third-pin', '3333'); cache.promote(third.path, third.digest); - expect(copies.every(item => fs.existsSync(item.path) && (fs.statSync(item.path).mode & 0o777) === 0o400)).toBe(true); - expect(copies.map(item => createHash('sha256').update(fs.readFileSync(item.path)).digest('hex')).sort()).toEqual([first.digest, second.digest].sort()); - }); - - test('bounds every public operation by an optional absolute deadline', () => { - const { root, staging, cache } = fixture(1024); - const archive = stage(staging, 'deadline', 'bounded'); - const expired = Date.now() - 1; - expect(code(() => cache.promote(archive.path, archive.digest, expired))).toBe('DEADLINE'); - const entry = cache.promote(archive.path, archive.digest); - expect(code(() => cache.get(entry.sha256, { deadline: expired }))).toBe('DEADLINE'); - expect(code(() => cache.stats({ deadline: expired }))).toBe('DEADLINE'); - const destination = path.join(root, 'deadline-materialization'); fs.mkdirSync(destination, { mode: 0o700 }); - expect(code(() => cache.materialize([entry.sha256], destination, { deadline: expired }))).toBe('DEADLINE'); - expect(fs.readdirSync(destination)).toEqual([]); - }); - - test('cancels between archive-copy chunks and removes the partial incoming object', () => { - const { staging, cacheRoot, cache } = fixture(512 * 1024); - const archive = stage(staging, 'cancel-copy', Buffer.alloc(192 * 1024, 0x61)); - const controller = new AbortController(), original = fs.writeSync.bind(fs); let archiveWrites = 0; - const writer = spyOn(fs, 'writeSync').mockImplementation(((fd: number, buffer: string | NodeJS.ArrayBufferView, - offsetOrPosition?: number | null, lengthOrEncoding?: number | BufferEncoding, position?: number | null) => { - const written = (original as any)(fd, buffer, offsetOrPosition, lengthOrEncoding, position); - if (Buffer.isBuffer(buffer) && lengthOrEncoding === 64 * 1024 && written > 0) { archiveWrites++; controller.abort(); } - return written; - }) as typeof fs.writeSync); - try { - expect(code(() => cache.promote(archive.path, archive.digest, { deadline: Date.now() + 60_000, signal: controller.signal }))).toBe('CANCELLED'); - } finally { writer.mockRestore(); } - expect(archiveWrites).toBe(1); - expect(fs.readdirSync(path.join(cacheRoot, 'incoming'))).toEqual([]); - expect(fs.readdirSync(path.join(cacheRoot, 'entries'))).toEqual([]); - expect(fs.readdirSync(path.join(cacheRoot, 'metadata'))).toEqual([]); - }); - - test('cancels between cache-hit read chunks without damaging the immutable entry', () => { - const { staging, cacheRoot, cache } = fixture(512 * 1024); - const archive = stage(staging, 'cancel-read', Buffer.alloc(192 * 1024, 0x62)), entry = cache.promote(archive.path, archive.digest); - const controller = new AbortController(), original = fs.readSync.bind(fs); let archiveReads = 0; - const reader = spyOn(fs, 'readSync').mockImplementation(((fd: number, buffer: NodeJS.ArrayBufferView, - offset: number, length: number, position: number | null) => { - const read = original(fd, buffer, offset, length, position); - if (length === 64 * 1024 && read > 0) { archiveReads++; controller.abort(); } - return read; - }) as typeof fs.readSync); - try { - expect(code(() => cache.get(entry.sha256, { signal: controller.signal }))).toBe('CANCELLED'); - } finally { reader.mockRestore(); } - expect(archiveReads).toBe(1); - expect(fs.existsSync(entry.path)).toBe(true); - expect(fs.readdirSync(path.join(cacheRoot, 'metadata'))).toEqual([`${entry.sha256}.json`]); - }); - - test('never overwrites an immutable entry and recovers interrupted entry publication', () => { - const { staging, cacheRoot, cache } = fixture(); - const archive = stage(staging, 'one', 'same bytes'); - const first = cache.promote(archive.path, archive.digest); - const inode = fs.statSync(first.path).ino; - stage(staging, 'two', 'same bytes'); - const again = cache.promote('two', archive.digest); - expect(fs.statSync(again.path).ino).toBe(inode); - - fs.unlinkSync(path.join(cacheRoot, 'metadata', `${archive.digest}.json`)); - expect(cache.get(archive.digest)).toBeUndefined(); - expect(fs.existsSync(first.path)).toBe(false); - expect(cache.promote(archive.path, archive.digest).sha256).toBe(archive.digest); - }); - - test('recovers dead immutable leases, never expires a live owner by age, and fences legacy directories', () => { - const stale = fixture(); - stale.cache.stats();const staleLeases=path.join(stale.cacheRoot,'.mutation-lock-leases'),staleToken='a'.repeat(32),staleLease=path.join(staleLeases,`${staleToken}.json`); - fs.writeFileSync(staleLease,JSON.stringify({pid:2147483647,processIdentity:'linux:1',token:staleToken,createdAt:1})+'\n',{mode:0o600}); - expect(stale.cache.stats()).toEqual({ entries: 0, bytes: 0, maxBytes: 1024 }); - expect(fs.existsSync(staleLease)).toBe(false);expect(fs.lstatSync(path.join(stale.cacheRoot,'.lock')).isFile()).toBe(true); - - const ownerless = fixture(); - fs.mkdirSync(path.join(ownerless.cacheRoot, '.lock'), { mode: 0o700 }); - const old = new Date(Date.now() - 60_000); - fs.utimesSync(path.join(ownerless.cacheRoot, '.lock'), old, old); - expect(code(()=>ownerless.cache.stats())).toBe('INSUFFICIENT_CAPACITY');expect(fs.lstatSync(path.join(ownerless.cacheRoot,'.lock')).isDirectory()).toBe(true); - - const live = fixture(); - live.cache.stats();const liveLeases=path.join(live.cacheRoot,'.mutation-lock-leases'),liveToken='b'.repeat(32),liveLease=path.join(liveLeases,`${liveToken}.json`); - fs.writeFileSync(liveLease,JSON.stringify({pid:process.pid,token:liveToken,createdAt:1})+'\n',{mode:0o600});fs.utimesSync(liveLease,old,old); - expect(code(() => live.cache.stats())).toBe('INSUFFICIENT_CAPACITY'); - }); - - test('recovers an exact cache-protocol publication link and rejects an unrecognized one',()=>{ - const recovered=fixture(),lock=path.join(recovered.cacheRoot,'.lock'),temporary=`${lock}.tmp.2147483647.deadbeef`; - fs.writeFileSync(lock,JSON.stringify({protocol:'immutable-cache-lease-set-v3'})+'\n',{mode:0o600,flag:'wx'});fs.linkSync(lock,temporary); - expect(recovered.cache.stats()).toEqual({entries:0,bytes:0,maxBytes:1024});expect(fs.statSync(lock).nlink).toBe(1);expect(fs.existsSync(temporary)).toBe(false); - const poisoned=fixture(),poisonedLock=path.join(poisoned.cacheRoot,'.lock'),unrecognized=`${poisonedLock}.tmp.dead.bad`; - fs.writeFileSync(poisonedLock,JSON.stringify({protocol:'immutable-cache-lease-set-v3'})+'\n',{mode:0o600,flag:'wx'});fs.linkSync(poisonedLock,unrecognized); - expect(code(()=>poisoned.cache.stats())).toBe('UNSAFE_PATH');expect(fs.statSync(poisonedLock).nlink).toBe(2); - }); - - test('recovers orphan metadata and transaction tombs but refuses poisoned recovery objects', () => { - const { root, cacheRoot, cache } = fixture(); - const digest = 'c'.repeat(64); - fs.writeFileSync(path.join(cacheRoot, 'metadata', `${digest}.json`), JSON.stringify({ - version: 1, sha256: digest, bytes: 1, createdAt: 1, lastAccessedAt: 1, - }), { mode: 0o600 }); - const tomb = `.recovery-entry-${digest}-${process.pid}-${'d'.repeat(24)}`; - fs.writeFileSync(path.join(cacheRoot, 'recovery', tomb), 'interrupted', { mode: 0o400 }); - expect(cache.stats().entries).toBe(0); - expect(fs.readdirSync(path.join(cacheRoot, 'metadata'))).toEqual([]); - expect(fs.readdirSync(path.join(cacheRoot, 'recovery'))).toEqual([]); - - const outside = path.join(root, 'outside-recovery'); - fs.writeFileSync(outside, 'untouched'); - fs.symlinkSync(outside, path.join(cacheRoot, 'entries', digest)); - expect(code(() => cache.get(digest))).toBe('UNSAFE_PATH'); - expect(fs.readFileSync(outside, 'utf8')).toBe('untouched'); - }); - - test('recovers atomic-write and publication hard links left by process death', () => { - const { staging, cacheRoot, cache } = fixture(); - const archive = stage(staging, 'archive', 'crash-safe'); - const entry = cache.promote(archive.path, archive.digest); - const metadata = path.join(cacheRoot, 'metadata', `${archive.digest}.json`); - fs.linkSync(metadata, `${metadata}.tmp.999.${'e'.repeat(8)}`); - expect(fs.statSync(metadata).nlink).toBe(2); - expect(cache.get(archive.digest)?.sha256).toBe(archive.digest); - expect(fs.statSync(metadata).nlink).toBe(1); - - const incoming = path.join(cacheRoot, 'incoming', `.incoming-999-${'f'.repeat(24)}`); - fs.linkSync(entry.path, incoming); - fs.unlinkSync(metadata); - expect(fs.statSync(entry.path).nlink).toBe(2); - expect(cache.get(archive.digest)).toBeUndefined(); - expect(fs.existsSync(incoming)).toBe(false); - expect(fs.existsSync(entry.path)).toBe(false); - }); - - test('a paused immutable lease publisher cannot be age-reclaimed or overlap a contender', () => { - const { cacheRoot, cache } = fixture(),lock=path.join(cacheRoot,'.lock'),leases=path.join(cacheRoot,'.mutation-lock-leases'),originalMkdir=fs.mkdirSync,originalUnlink=fs.unlinkSync; - let paused=false,contenderResult:string|undefined; - const contend=(published:string)=>{paused=true;const old=new Date(Date.now()-60_000);fs.utimesSync(published,old,old);contenderResult=code(()=>cache.stats());}; - // The mkdir hook deterministically reproduces the former empty-directory - // publication. The unlink hook pauses the immutable replacement after its - // complete inode is visible and its temporary hard link is gone. - const mkdir=spyOn(fs,'mkdirSync').mockImplementation(((target:fs.PathLike,options?:fs.MakeDirectoryOptions & {recursive?:false})=>{const result=originalMkdir(target,options as any);if(!paused&&String(target)===lock)contend(lock);return result;}) as typeof fs.mkdirSync); - const unlink=spyOn(fs,'unlinkSync').mockImplementation(((target:fs.PathLike)=>{const value=String(target),result=originalUnlink(target);if(!paused&&value.startsWith(`${leases}${path.sep}`)&&/^[a-f0-9]{32}\.json\.tmp\.\d+\.[a-f0-9]{8}$/.test(path.basename(value)))contend(value.replace(/\.tmp\.\d+\.[a-f0-9]{8}$/,''));return result;}) as typeof fs.unlinkSync); - let result;try{result=cache.stats();}finally{unlink.mockRestore();mkdir.mockRestore();} - expect(paused).toBe(true);expect(contenderResult).toBe('INSUFFICIENT_CAPACITY');expect(result).toEqual({entries:0,bytes:0,maxBytes:1024});expect(fs.readdirSync(leases)).toEqual([]);expect(fs.lstatSync(lock).isFile()).toBe(true); - }); - - test('LRU eviction refuses poisoned links without following or deleting their targets', () => { - const { root, staging, cacheRoot, cache } = fixture(4); - const outside = path.join(root, 'outside'); - fs.writeFileSync(outside, 'do-not-touch', { mode: 0o600 }); - const digest = 'a'.repeat(64); - fs.symlinkSync(outside, path.join(cacheRoot, 'entries', digest)); - fs.writeFileSync(path.join(cacheRoot, 'metadata', `${digest}.json`), JSON.stringify({ version: 1, sha256: digest, bytes: 12, createdAt: 1, lastAccessedAt: 1 }), { mode: 0o600 }); - const fresh = stage(staging, 'fresh', '1234'); - expect(code(() => cache.promote(fresh.path, fresh.digest))).toBe('UNSAFE_PATH'); - expect(fs.readFileSync(outside, 'utf8')).toBe('do-not-touch'); - }); - - test('fails closed on cache locks and poisoned incoming paths', () => { - const { staging, cacheRoot, cache } = fixture(); - const archive = stage(staging, 'one', 'archive'); - const lockTarget = path.join(cacheRoot, 'outside-lock'); - fs.writeFileSync(lockTarget, 'lock-target'); - fs.symlinkSync(lockTarget, path.join(cacheRoot, '.lock')); - expect(code(() => cache.promote(archive.path, archive.digest))).toBe('UNSAFE_PATH'); - fs.unlinkSync(path.join(cacheRoot, '.lock')); - - const outside = path.join(cacheRoot, 'outside-incoming'); - fs.writeFileSync(outside, 'outside'); - fs.symlinkSync(outside, path.join(cacheRoot, 'incoming', `.incoming-${process.pid}-${'b'.repeat(24)}`)); - expect(code(() => cache.promote(archive.path, archive.digest))).toBe('UNSAFE_PATH'); - expect(fs.readFileSync(outside, 'utf8')).toBe('outside'); - }); -}); diff --git a/test/cso-cli-lifecycle.test.ts b/test/cso-cli-lifecycle.test.ts deleted file mode 100644 index 8b54b0d66..000000000 --- a/test/cso-cli-lifecycle.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { canonical, sha256, type VerificationObservation } from '../lib/cso/contracts'; -import { ISOLATION_POLICY_HASH } from '../lib/cso/docker'; -import { saveReport, withLock } from '../lib/cso/state'; -import { replayRuntimeRejection } from './helpers/cso-runtime-catalog'; -import { canonicalStartPlan, canonicalTestPlan, patchHash, verifyRepair } from '../lib/cso/verification'; - -const ROOT=path.resolve(import.meta.dir,'..'),launcher=path.join(ROOT,'bin',process.platform==='win32'?'gstack-cso-launcher.exe':'gstack-cso-launcher'); -const tap=`TAP version 13 -# Subtest: legitimate control remains available -ok 1 - legitimate control remains available - --- - duration_ms: 1 - ... -1..1 -# tests 1 -# suites 0 -# pass 1 -# fail 0 -# cancelled 0 -# skipped 0 -# todo 0 -`; -let root='',repo='',state=''; - -function command(args:string[]){return spawnSync(launcher,args,{cwd:repo,encoding:'utf8',env:{HOME:root,GSTACK_HOME:state,PATH:'/usr/bin:/bin'},timeout:30_000});} -function git(...args:string[]){const result=spawnSync('/usr/bin/git',['-C',repo,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr);return result.stdout;} -function runDir(run:any){return path.join(state,'security','cso',run.repoId,run.runId);} -function writeInput(name:string,value:unknown){const file=path.join(root,name);fs.writeFileSync(file,JSON.stringify(value));return file;} - -beforeEach(()=>{ - root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-cli-lifecycle-'));repo=path.join(root,'repo');state=path.join(root,'state');fs.mkdirSync(repo); - git('init','-q');git('config','user.email','fixture@example.test');git('config','user.name','Fixture'); - fs.writeFileSync(path.join(repo,'package.json'),JSON.stringify({name:'cso-cli-lifecycle',version:'1.0.0',private:true,scripts:{start:'node app.js',test:'node --test'}})+'\n'); - fs.writeFileSync(path.join(repo,'package-lock.json'),JSON.stringify({name:'cso-cli-lifecycle',version:'1.0.0',lockfileVersion:3,requires:true,packages:{'':{name:'cso-cli-lifecycle',version:'1.0.0'}}})+'\n'); - fs.writeFileSync(path.join(repo,'app.js'),'module.exports = "vulnerable"\n'); - fs.writeFileSync(path.join(repo,'app.test.js'),"const test=require('node:test');test('legitimate control remains available',()=>{});\n"); - git('add','.');git('commit','-qm','fixture'); -}); -afterEach(()=>fs.rmSync(root,{recursive:true,force:true})); - -describe('CSO interrupted-run and replay commands',()=>{ - test('resume reports watchdog recovery without replenishing the original policy or deadline',()=>{ - const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline','--budget','120']).stdout),dir=runDir(run),reportPath=path.join(dir,'report.json'),original=JSON.parse(fs.readFileSync(reportPath,'utf8')); - const recovery='supervisor-death execution-copy cleanup complete',dockerRecovery='deadline cleanup complete',control=path.join(dir,'supervision','repair-attempt'),preparationControl=path.join(dir,'preparation-execution','offline-attempt');fs.mkdirSync(control,{recursive:true});fs.mkdirSync(preparationControl,{recursive:true});fs.writeFileSync(path.join(control,'attempt.event'),`${recovery}\n`);fs.writeFileSync(path.join(preparationControl,'watchdog.event'),`${dockerRecovery}\n`);const staging=path.join(dir,'archive-staging','acquire-partial');fs.mkdirSync(staging,{recursive:true});fs.writeFileSync(path.join(staging,'partial.tgz'),'partial'); - original.status='interrupted';saveReport(dir,original); - - const resumed=command(['resume',run.runId]);expect(resumed.status).toBe(0);const result=JSON.parse(resumed.stdout),active=JSON.parse(fs.readFileSync(reportPath,'utf8')); - expect(result).toMatchObject({runId:run.runId,deadline:original.deadline,policy:original.policy,recovery:[recovery,dockerRecovery]});expect(active.status).toBe('running');expect(active.deadline).toBe(original.deadline);expect(active.policy).toEqual(original.policy); - expect(active.events.filter((item:any)=>item.kind==='watchdog-recovery'&&[recovery,dockerRecovery].includes(item.message))).toHaveLength(2);expect(active.events.at(-1)).toMatchObject({kind:'resume',message:'Continued retained snapshot under original policy'}); - for(const name of ['supervision','preparation-execution','archive-staging'])expect(fs.readdirSync(path.join(dir,name))).toEqual([]); - - active.status='interrupted';active.deadline=new Date(Date.now()-1_000).toISOString();const exhaustedDeadline=active.deadline;saveReport(dir,active); - const expired=command(['resume',run.runId]);expect(expired.status).not.toBe(0);expect(expired.stderr).toContain('DEADLINE');expect(expired.stderr).toContain('Original run budget is exhausted'); - const retained=JSON.parse(fs.readFileSync(reportPath,'utf8'));expect(retained.status).toBe('interrupted');expect(retained.deadline).toBe(exhaustedDeadline);expect(retained.policy).toEqual(original.policy);expect(retained.events.at(-1)).toMatchObject({kind:'deadline',message:'Original budget is exhausted; resume did not replenish it'}); - expect(retained.events.filter((item:any)=>item.kind==='watchdog-recovery'&&[recovery,dockerRecovery].includes(item.message))).toHaveLength(2); - }); - - test.skipIf(process.platform==='win32')('replay accepts retained or exactly matching supplied source and rejects expired or changed inputs before Docker admission',async()=>{ - const started=command(['start','--repo',repo,'--comprehensive','--offline']);expect(started.status).toBe(0);const run=JSON.parse(started.stdout),dir=runDir(run),snapshot=path.join(dir,'snapshot'),manifest=JSON.parse(fs.readFileSync(path.join(dir,'snapshot.json'),'utf8')); - const finding={title:'Unprotected record read',rootCause:'Record lookup omits the caller authorization predicate',location:{path:'app.js',line:1,symbol:'recordLookup'},advisoryIds:[],severity:'high',confidence:'high',confidenceRationale:'The caller-to-record trace directly establishes the missing authorization predicate',evidence:'supported',attackerControl:'Authenticated caller chooses the record identifier',impact:'Another tenant record is returned',scenario:'A tenant supplies another tenant record identifier and receives the record',trace:['GET /records/:id','recordLookup','record response'],references:['app.js:1','OWASP API1:2023'],recommendation:'Bind the lookup to the authenticated caller before returning the record',challenge:{reviewer:'independent-reviewer',independent:true,mode:'independent_agent',callers:'Authenticated route forwards the record identifier',controls:'Authentication exists without record authorization',counterevidence:'Opaque identifiers reduce guessing but do not authorize known identifiers',conclusion:'The record lookup lacks a caller authorization predicate'}}; - expect(command(['submit',run.runId,writeInput('replay-finding.json',{findings:[finding]})]).status).toBe(0);const reportPath=path.join(dir,'report.json'),report=JSON.parse(fs.readFileSync(reportPath,'utf8')),findingId=report.findings[0].id,start=canonicalStartPlan(snapshot,'node',3456),tests=canonicalTestPlan(snapshot,'node'); - const request:any={findingId,runtimeProfile:`node-24.4.0-${process.arch==='arm64'?'arm64':'amd64'}`,port:3456,start:start.command,legitimate:[{name:'legitimate control',path:'/control',method:'GET',expected:{status:200,includes:'CONTROL_OK'}}],security:{name:'unauthorized record is denied',path:'/records/other',method:'GET',expected:{status:403,includes:'DENIED'},vulnerable:{status:200,includes:'RECORD'}},existingTests:tests.commands,fixtures:{},boundaryFiles:['app.js'],testFiles:tests.files,changes:[{path:'app.js',beforeSha256:sha256(fs.readFileSync(path.join(snapshot,'app.js'))),after:'module.exports = "fixed"\n',effect:'source'}],review:{reviewer:'independent-reviewer',independent:true,rootCauseRepaired:true,featurePreserved:true,boundaryMocks:false,rationale:'The caller predicate is added while the legitimate control and existing test remain unchanged.',reviewedPatchHash:''}};request.review.reviewedPatchHash=patchHash(request); - const platform=process.arch==='arm64'?'linux/arm64':'linux/amd64',rejection=replayRuntimeRejection(request.runtimeProfile,platform),runtime:any={id:request.runtimeProfile,stack:'node',platform,image:`ghcr.io/garrytan/gstack/cso-staging/node-${process.arch==='arm64'?'arm64':'amd64'}@sha256:${'b'.repeat(64)}`},executor={observe:async(_source:string,phase:'before'|'after',received:any,_runtime:any,_verifier:any,_work:string,_control:string,_execution:any,evidence:any,witness:any)=>{const observation:VerificationObservation={booted:true,legitimate:true,security:phase==='before'?'intended_failure':'pass',existingTests:false,output:`external ${phase} assertions passed`,inputHash:''},receipt=await witness.attest(observation,[{command:received.existingTests[0],code:0,output:tap,minimumPassingTests:evidence.minimumPassingTests[0]}]);return{observation:{...observation,existingTests:receipt.diagnosticTestsPassed,inputHash:witness.binding.harnessHash},witness:receipt};}}; - const verified=await verifyRepair({runId:run.runId,runDir:dir,manifest,rawRequest:request,runtime,verifier:runtime,policyHash:ISOLATION_POLICY_HASH,auditPolicyHash:sha256(canonical(report.policy)),archives:[],executor}); - report.findings[0].reproduction='reproduced';report.findings[0].repair='runtime_tested';report.findings[0].verificationId=verified.bundle.id;report.findings[0].verificationAssurance={assertions:'authenticated_out_of_process',testCompletion:'self_reported',review:'self_attested'};saveReport(dir,report); - - const leased=withLock(dir,()=>command(['replay',verified.bundle.id])) as ReturnType;expect(leased.status).not.toBe(0);expect(leased.stderr).toContain('INSUFFICIENT_CAPACITY');expect(leased.stderr).toContain('Another helper is updating this run'); - const retained=command(['replay',verified.bundle.id]);expect(retained.status).not.toBe(0);expect(retained.stderr).toContain(rejection.code);expect(retained.stderr).toContain(rejection.message); - const manifestPath=path.join(dir,'snapshot.json'),expiredManifest={...manifest,expiresAt:new Date(Date.now()-1_000).toISOString()};fs.writeFileSync(manifestPath,`${JSON.stringify(expiredManifest,null,2)}\n`); - const expiredPresent=command(['replay',verified.bundle.id]);expect(expiredPresent.status).not.toBe(0);expect(expiredPresent.stderr).toContain('MISSING_INPUT');expect(expiredPresent.stderr).toContain('Retained source expired'); - const suppliedExpired=command(['replay',verified.bundle.id,'--source',repo]);expect(suppliedExpired.status).not.toBe(0);expect(suppliedExpired.stderr).toContain(rejection.code);expect(suppliedExpired.stderr).toContain(rejection.message);expect(suppliedExpired.stderr).not.toContain('Retained source expired'); - const noncanonicalExpiry=new Date(Date.now()+86400_000).toISOString().replace(/\.\d{3}Z$/,'Z');fs.writeFileSync(manifestPath,`${JSON.stringify({...manifest,expiresAt:noncanonicalExpiry},null,2)}\n`); - const invalidExpiry=command(['replay',verified.bundle.id,'--source',repo]);expect(invalidExpiry.status).not.toBe(0);expect(invalidExpiry.stderr).toContain('INCOMPATIBLE_INPUT');expect(invalidExpiry.stderr).toContain('Retained snapshot expiry is invalid');expect(invalidExpiry.stderr).not.toContain(rejection.message); - fs.writeFileSync(manifestPath,`${JSON.stringify({...manifest,expiresAt:new Date(Date.now()+86400_000).toISOString()},null,2)}\n`);fs.writeFileSync(path.join(snapshot,'app.js'),'module.exports = "tampered"\n'); - const corruptRetained=command(['replay',verified.bundle.id,'--source',repo]);expect(corruptRetained.status).not.toBe(0);expect(corruptRetained.stderr).toContain('INCOMPATIBLE_INPUT');expect(corruptRetained.stderr).toContain('Retained snapshot changed');expect(corruptRetained.stderr).not.toContain(rejection.message); - fs.rmSync(snapshot,{recursive:true,force:true});fs.rmSync(path.join(dir,'readable'),{recursive:true,force:true}); - const expired=command(['replay',verified.bundle.id]);expect(expired.status).not.toBe(0);expect(expired.stderr).toContain('MISSING_INPUT');expect(expired.stderr).toContain('Retained source expired'); - fs.writeFileSync(path.join(repo,'app.js'),'module.exports = "changed"\n');const changed=command(['replay',verified.bundle.id,'--source',repo]);expect(changed.status).not.toBe(0);expect(changed.stderr).toContain('INCOMPATIBLE_INPUT');expect(changed.stderr).toContain('does not match the bundle input hashes'); - fs.writeFileSync(path.join(repo,'app.js'),'module.exports = "vulnerable"\n');const supplied=command(['replay',verified.bundle.id,'--source',repo]);expect(supplied.status).not.toBe(0);expect(supplied.stderr).toContain(rejection.code);expect(supplied.stderr).toContain(rejection.message);expect(supplied.stderr).not.toContain('does not match the bundle input hashes'); - },30_000); -}); - -describe('bounded verification attempts', () => { - test('a Rails attempt can prepare both phases; other stacks keep the five-minute bound', async () => { - const { verificationAttemptMs } = await import('../lib/cso/cli'); - const { MAX_VERIFICATION_ATTEMPT_MS } = await import('../lib/cso/contracts'); - for (const stack of ['node', 'bun', 'python']) expect(verificationAttemptMs(stack)).toBe(300_000); - expect(verificationAttemptMs('rails')).toBe(MAX_VERIFICATION_ATTEMPT_MS); - expect(MAX_VERIFICATION_ATTEMPT_MS).toBe(1_800_000); - }); -}); diff --git a/test/cso-cli-recheck.test.ts b/test/cso-cli-recheck.test.ts deleted file mode 100644 index eba8e4c30..000000000 --- a/test/cso-cli-recheck.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawn, spawnSync } from 'node:child_process'; - -const ROOT=path.resolve(import.meta.dir,'..'),launcher=path.join(ROOT,'bin',process.platform==='win32'?'gstack-cso-launcher.exe':'gstack-cso-launcher'); -let root='',repo='',state=''; -const application={actors:['tenant user'],assets:['tenant records'],entrypoints:['GET /users/:id'],tenantBoundaries:['tenant id'],sensitiveOperations:['record read'],invariants:['tenant isolation']}; -const finding={title:'Cross-tenant user read',rootCause:'Tenant query omits caller tenant predicate',location:{path:'src/users.ts',line:1,symbol:'tenantQuery'},advisoryIds:[],severity:'high',confidence:'high',confidenceRationale:'The caller-to-query trace and missing tenant predicate directly support the finding',evidence:'supported',attackerControl:'Authenticated caller chooses the record ID',impact:'Another tenant record is returned',scenario:'A tenant supplies a known record ID owned by another tenant and receives that record',trace:['GET /users/:id','tenantQuery','findUnique by id'],references:['src/users.ts:1','OWASP API1:2023'],recommendation:'Bind the lookup predicate to the authenticated tenant identifier',challenge:{reviewer:'independent-2',independent:true,mode:'independent_agent',callers:'Authenticated route forwards the ID',controls:'Authentication does not bind tenant',counterevidence:'Opaque IDs reduce guessing but do not authorize',conclusion:'The authorization invariant is absent'}}; -function command(args:string[]){return spawnSync(launcher,args,{cwd:repo,encoding:'utf8',env:{HOME:root,GSTACK_HOME:state,PATH:'/usr/bin:/bin'},timeout:30_000});} -function git(...args:string[]){const result=spawnSync('/usr/bin/git',['-C',repo,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr);return result.stdout;} -function reportPath(run:any){return path.join(state,'security','cso',run.repoId,run.runId,'report.json');} -function completeEvidence(report:any,findings:any[]=[]){return{application,findings,coverage:report.coverage.filter((item:any)=>!['snapshot-inputs','history-inputs'].includes(item.domain)).map((item:any)=>({...item,status:'assessed',method:'fresh caller and boundary trace',gaps:[],evidence:['current captured source']})),gaps:[]};} -function writeInput(name:string,value:unknown){const file=path.join(root,name);fs.writeFileSync(file,JSON.stringify(value));return file;} -function recheckEvidence(source='src/users.ts'){return[ - {kind:'caller',path:source,line:1,observation:'Fresh caller trace reaches the authorization predicate'}, - {kind:'security_boundary',path:source,line:1,observation:'Fresh boundary trace confirms cross-tenant access is denied'}, -];} -function finishedOriginal(name:string,candidate:any){ - const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),initial=JSON.parse(fs.readFileSync(reportPath(run),'utf8')); - expect(command(['submit',run.runId,writeInput(`${name}.json`,completeEvidence(initial,[candidate]))]).status).toBe(0); - expect(command(['finish',run.runId]).status).toBe(0); - return{run,findingId:JSON.parse(fs.readFileSync(reportPath(run),'utf8')).findings[0].id}; -} -beforeAll(()=>{root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-cli-recheck-'));repo=path.join(root,'repo');state=path.join(root,'state');fs.mkdirSync(repo);git('init','-q');git('config','user.email','fixture@example.test');git('config','user.name','Fixture');fs.mkdirSync(path.join(repo,'src'));fs.writeFileSync(path.join(repo,'src','users.ts'),'export const tenantQuery = (id:string) => db.user.findUnique({where:{id}})\n');fs.writeFileSync(path.join(repo,'src','other.ts'),'export const unrelated = true\n');git('add','src/users.ts','src/other.ts');git('commit','-qm','fixture');}); -afterAll(()=>fs.rmSync(root,{recursive:true,force:true})); - -describe('CSO recheck persistence',()=>{ - test('resolves a unique finished original audit from the current repository',()=>{const candidate={...finding,rootCause:'Unique fixture query omits its tenant predicate',location:{...finding.location,symbol:'uniqueTenantQuery'}},original=finishedOriginal('unique-original',candidate),rechecked=command(['recheck',original.findingId,'--repo',repo]);expect(rechecked.status).toBe(0);expect(rechecked.stderr).toBe('');const child=JSON.parse(rechecked.stdout);expect(child.parent).toEqual({runId:original.run.runId,findingId:original.findingId,kind:'recheck'});},30_000); - test('reports a missing original finding without requiring an internal run ID',()=>{const missing=command(['recheck','0'.repeat(32),'--repo',repo]);expect(missing.status).not.toBe(0);expect(missing.stderr).toContain('MISSING_INPUT');expect(missing.stderr).toContain('No finished original audit contains this finding');},30_000); - test('rejects ambiguous originals and accepts --run as an explicit disambiguator',()=>{const candidate={...finding,rootCause:'Ambiguous fixture query omits its tenant predicate',location:{...finding.location,symbol:'ambiguousTenantQuery'}},first=finishedOriginal('ambiguous-original-first',candidate),second=finishedOriginal('ambiguous-original-second',candidate);expect(second.findingId).toBe(first.findingId);const ambiguous=command(['recheck',first.findingId,'--repo',repo]);expect(ambiguous.status).not.toBe(0);expect(ambiguous.stderr).toContain('INVALID_ARGUMENT');expect(ambiguous.stderr).toContain('--run RUN');const selected=command(['recheck',first.findingId,'--repo',repo,'--run',second.run.runId]);expect(selected.status).toBe(0);expect(JSON.parse(selected.stdout).parent.runId).toBe(second.run.runId);},30_000); - test('requires an immutable finished original audit',()=>{const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),report=JSON.parse(fs.readFileSync(reportPath(run),'utf8'));expect(command(['submit',run.runId,writeInput('unfinished.json',completeEvidence(report,[finding]))]).status).toBe(0);const id=JSON.parse(fs.readFileSync(reportPath(run),'utf8')).findings[0].id,recheck=command(['recheck',id,'--run',run.runId,'--repo',repo]);expect(recheck.status).not.toBe(0);expect(recheck.stderr).toContain('finished original audit');},30_000); - test('resolved closure rejects free-form or unrelated boundary evidence',()=>{const original=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),originalPath=reportPath(original),initial=JSON.parse(fs.readFileSync(originalPath,'utf8'));expect(command(['submit',original.runId,writeInput('bound-original.json',completeEvidence(initial,[finding]))]).status).toBe(0);expect(command(['finish',original.runId]).status).toBe(0);const findingId=JSON.parse(fs.readFileSync(originalPath,'utf8')).findings[0].id,started=JSON.parse(command(['recheck',findingId,'--run',original.runId,'--repo',repo]).stdout); - const freeForm=command(['submit',started.runId,writeInput('free-form-claim.json',{recheck:{findingId,outcome:'resolved',evidence:['caller words','boundary words'],rootCause:finding.rootCause}})]);expect(freeForm.status).not.toBe(0);expect(freeForm.stderr).toContain('recheck evidence[0]'); - const unrelated=command(['submit',started.runId,writeInput('unrelated-boundary-claim.json',{recheck:{findingId,outcome:'resolved',evidence:[{kind:'caller',path:'src/users.ts',line:1,observation:'Fresh caller trace reaches the predicate'},{kind:'security_boundary',path:'src/other.ts',line:1,observation:'Unrelated source says nothing about authorization'}],rootCause:finding.rootCause}})]);expect(unrelated.status).not.toBe(0);expect(unrelated.stderr).toContain('original finding location'); - const phantomLine=command(['submit',started.runId,writeInput('phantom-line-claim.json',{recheck:{findingId,outcome:'resolved',evidence:[{kind:'caller',path:'src/users.ts',line:2,observation:'A trailing newline must not create a source line'},{kind:'security_boundary',path:'src/users.ts',line:1,observation:'Fresh boundary trace checks authorization'}],rootCause:finding.rootCause}})]);expect(phantomLine.status).not.toBe(0);expect(phantomLine.stderr).toContain('line is outside the fresh source file'); - },30_000); - test('a failed report write cannot leave a closure claim behind',()=>{const original=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),originalPath=reportPath(original),initial=JSON.parse(fs.readFileSync(originalPath,'utf8'));expect(command(['submit',original.runId,writeInput('original.json',completeEvidence(initial,[finding]))]).status).toBe(0);expect(command(['finish',original.runId]).status).toBe(0);const originalReport=JSON.parse(fs.readFileSync(originalPath,'utf8')),findingId=originalReport.findings[0].id,started=command(['recheck',findingId,'--run',original.runId,'--repo',repo]);expect(started.status).toBe(0);const child=JSON.parse(started.stdout),childPath=reportPath({...child,repoId:original.repoId}),childDir=path.dirname(childPath),childInitial=JSON.parse(fs.readFileSync(childPath,'utf8'));expect(command(['submit',child.runId,writeInput('child-baseline.json',completeEvidence(childInitial))]).status).toBe(0);const complete=JSON.parse(fs.readFileSync(childPath,'utf8'));expect(complete.completeness).toBe('complete');complete.events.push({at:new Date().toISOString(),kind:'padding',message:''});const empty=Buffer.byteLength(JSON.stringify(complete,null,2)+'\n'),target=1024*1024-8;complete.events.at(-1).message='x'.repeat(target-empty);const encoded=JSON.stringify(complete,null,2)+'\n';expect(Buffer.byteLength(encoded)).toBe(target);fs.writeFileSync(childPath,encoded);const failed=command(['submit',child.runId,writeInput('failed-claim.json',{modelUsage:{source:'host',tokens:0},recheck:{findingId,outcome:'resolved',evidence:recheckEvidence(),rootCause:finding.rootCause}})]);expect(failed.status).not.toBe(0);expect(failed.stderr).toContain('PERSISTENCE_FAILED');expect(fs.existsSync(path.join(childDir,'recheck-claim.json'))).toBe(false);},30_000); - test.skipIf(process.platform==='win32')('retention and recheck share the lease that protects an expiring parent',async()=>{const original=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),currentDir=path.dirname(reportPath(original)),initial=JSON.parse(fs.readFileSync(reportPath(original),'utf8'));expect(command(['submit',original.runId,writeInput('leased-original.json',completeEvidence(initial,[finding]))]).status).toBe(0);expect(command(['finish',original.runId]).status).toBe(0);const finished=JSON.parse(fs.readFileSync(reportPath(original),'utf8')),findingId=finished.findings[0].id,created=Date.now()-30*86400_000+60_000,oldRun=`${created}-${'8'.repeat(16)}`,oldDir=path.join(path.dirname(currentDir),oldRun);finished.runId=oldRun;fs.writeFileSync(path.join(currentDir,'report.json'),JSON.stringify(finished,null,2)+'\n');fs.renameSync(currentDir,oldDir);original.runId=oldRun; - const leases=path.join(oldDir,'.mutation-lock-leases'),active=/^[a-f0-9]{32}\.active\.[a-f0-9]{16}$/,ready=path.join(root,'lease-ready'),release=path.join(root,'lease-release'),holderSource=`import * as fs from 'node:fs';import {withLock} from ${JSON.stringify(path.join(ROOT,'lib/cso/state.ts'))};await withLock(${JSON.stringify(oldDir)},async()=>{fs.writeFileSync(${JSON.stringify(ready)},'ready',{flag:'wx'});while(!fs.existsSync(${JSON.stringify(release)}))await Bun.sleep(5);});`; - let holderStderr='';const holder=spawn(process.execPath,['--eval',holderSource],{env:{HOME:root,GSTACK_HOME:state,PATH:process.env.PATH},stdio:['ignore','ignore','pipe']}),holderClosed=new Promise(resolve=>holder.on('close',resolve));holder.stderr!.setEncoding('utf8');holder.stderr!.on('data',chunk=>holderStderr+=chunk);let holderCode:number|null|'timeout'='timeout'; - try{const readyOutcome=await Promise.race([(async()=>{const deadline=Date.now()+10_000;while(Date.now()`closed:${code}` as const)]);expect(readyOutcome).toBe('ready');expect(fs.readdirSync(leases).some(name=>active.test(name))).toBe(true);const sweepNow=created+30*86400_000+1,sweep=spawnSync(process.execPath,['--eval',`import {retention} from ${JSON.stringify(path.join(ROOT,'lib/cso/state.ts'))};retention(${sweepNow});`],{encoding:'utf8',env:{HOME:root,GSTACK_HOME:state,PATH:process.env.PATH},timeout:30_000});expect(sweep.status).toBe(0);expect(fs.existsSync(path.join(oldDir,'report.json'))).toBe(true);const blocked=command(['recheck',findingId,'--run',oldRun,'--repo',repo]);expect(blocked.status).not.toBe(0);expect(blocked.stderr).toContain('INSUFFICIENT_CAPACITY');expect(blocked.stderr).toContain('Another helper is updating this run');}finally{fs.writeFileSync(release,'release');holderCode=await Promise.race([holderClosed,Bun.sleep(10_000).then(()=>'timeout' as const)]);if(holderCode==='timeout'){holder.kill('SIGKILL');holderCode=await holderClosed;}} - expect(holderCode).toBe(0);expect(holderStderr).toBe('');expect(fs.readdirSync(leases)).toEqual([]);const completed=command(['recheck',findingId,'--run',oldRun,'--repo',repo]);expect(completed.status).toBe(0);expect(completed.stderr).toBe('');const result=JSON.parse(completed.stdout);expect(fs.existsSync(path.join(oldDir,'report.json'))).toBe(true);expect(fs.existsSync(path.join(state,'security','cso',original.repoId,result.runId,'report.json'))).toBe(true); - },30_000); - test('closure cannot survive mutation of the fresh recheck snapshot',()=>{const original=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),originalPath=reportPath(original),initial=JSON.parse(fs.readFileSync(originalPath,'utf8'));expect(command(['submit',original.runId,writeInput('source-bound-original.json',completeEvidence(initial,[finding]))]).status).toBe(0);expect(command(['finish',original.runId]).status).toBe(0);const originalReport=JSON.parse(fs.readFileSync(originalPath,'utf8')),findingId=originalReport.findings[0].id,started=command(['recheck',findingId,'--run',original.runId,'--repo',repo]);expect(started.status).toBe(0);const child=JSON.parse(started.stdout),childPath=reportPath({...child,repoId:original.repoId}),childDir=path.dirname(childPath),childInitial=JSON.parse(fs.readFileSync(childPath,'utf8')),claim={findingId,outcome:'resolved',evidence:recheckEvidence(),rootCause:finding.rootCause};expect(command(['submit',child.runId,writeInput('source-bound-claim.json',{...completeEvidence(childInitial),recheck:claim})]).status).toBe(0);fs.writeFileSync(path.join(childDir,'snapshot','src','users.ts'),'mutated retained evidence\n');const finished=command(['finish',child.runId]);expect(finished.status).not.toBe(0);expect(finished.stderr).toContain('Retained snapshot changed');expect(JSON.parse(fs.readFileSync(originalPath,'utf8')).findings[0].closure).toBe('open');},30_000); - test('complete fresh-source evidence resolves only the targeted original finding',()=>{const second={...finding,title:'Unprotected audit export',rootCause:'Audit export omits the caller authorization predicate',location:{...finding.location,symbol:'auditExport'},trace:['GET /audit/export','auditExport','record response'],references:['src/users.ts:1'],scenario:'A tenant requests another tenant audit export and receives it'},original=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),originalPath=reportPath(original),initial=JSON.parse(fs.readFileSync(originalPath,'utf8'));expect(command(['submit',original.runId,writeInput('closure-original.json',completeEvidence(initial,[finding,second]))]).status).toBe(0);expect(command(['finish',original.runId]).status).toBe(0);const finishedOriginal=JSON.parse(fs.readFileSync(originalPath,'utf8')),findingId=finishedOriginal.findings.find((item:any)=>item.rootCause===finding.rootCause).id,otherId=finishedOriginal.findings.find((item:any)=>item.rootCause===second.rootCause).id,originalHash=finishedOriginal.source.originalHash,source=path.join(repo,'src','users.ts'),before=fs.readFileSync(source,'utf8'); - try{ - fs.writeFileSync(source,'export const tenantQuery = (tenantId:string,id:string) => db.user.findUnique({where:{id,tenantId}})\n');const started=command(['recheck',findingId,'--run',original.runId,'--repo',repo]);expect(started.status).toBe(0);const child=JSON.parse(started.stdout),childPath=reportPath({...child,repoId:original.repoId}),childInitial=JSON.parse(fs.readFileSync(childPath,'utf8')),claim={findingId,outcome:'resolved',evidence:recheckEvidence(),rootCause:finding.rootCause};expect(childInitial.source.originalHash).not.toBe(originalHash);expect(JSON.parse(fs.readFileSync(originalPath,'utf8')).findings.every((item:any)=>item.closure==='open')).toBe(true); - expect(command(['submit',child.runId,writeInput('closure-claim-first.json',{recheck:claim})]).status).toBe(0);expect(JSON.parse(fs.readFileSync(originalPath,'utf8')).findings.find((item:any)=>item.id===findingId).closure).toBe('open');const incomplete=command(['finish',child.runId]);expect(incomplete.status).not.toBe(0);expect(incomplete.stderr).toContain('Partial or incompatible rechecks cannot establish closure');expect(JSON.parse(fs.readFileSync(originalPath,'utf8')).findings.find((item:any)=>item.id===findingId).closure).toBe('open'); - expect(command(['submit',child.runId,writeInput('closure-fresh-evidence.json',completeEvidence(childInitial))]).status).toBe(0);const closed=command(['finish',child.runId]);expect(closed.status).toBe(0);expect(JSON.parse(closed.stdout)).toMatchObject({status:'finished',completeness:'complete'});const updated=JSON.parse(fs.readFileSync(originalPath,'utf8'));expect(updated.findings.find((item:any)=>item.id===findingId).closure).toBe('resolved');expect(updated.findings.find((item:any)=>item.id===otherId).closure).toBe('open');expect(updated.events.at(-1)).toMatchObject({kind:'closure'});expect(updated.events.at(-1).message).toContain(`resolved ${findingId}`); - }finally{fs.writeFileSync(source,before);} - },30_000); -}); diff --git a/test/cso-cli.test.ts b/test/cso-cli.test.ts deleted file mode 100644 index a283d9e48..000000000 --- a/test/cso-cli.test.ts +++ /dev/null @@ -1,216 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import { spawnSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { fingerprint, sha256 } from '../lib/cso/contracts'; -import { patchHash } from '../lib/cso/verification'; -import { redact } from '../lib/cso/process'; -const ROOT=path.resolve(import.meta.dir,'..'),launcher=path.join(ROOT,'bin',process.platform==='win32'?'gstack-cso-launcher.exe':'gstack-cso-launcher');let root='',repo='',state=''; -const CREDENTIAL_CANARY=['ghp_','abcdefghijklmnopqrstuvwxyz1234567890'].join(''); -function command(args:string[],extra:Record={},file=launcher){const r=spawnSync(file,args,{cwd:repo,encoding:'utf8',env:{HOME:root,GSTACK_HOME:state,PATH:`${repo}/hostile-bin:/usr/bin:/bin`,BUN_OPTIONS:`--preload=${repo}/preload.ts`,BUN_BE_BUN:'1',NODE_OPTIONS:`--require=${repo}/preload.cjs`,RUBYOPT:`-r${repo}/preload.rb`,PYTHONPATH:repo,LD_PRELOAD:path.join(repo,'missing.so'),BASH_ENV:path.join(repo,'bashenv'),...extra},timeout:30_000});return r;} -function git(...args:string[]){const r=spawnSync('/usr/bin/git',['-C',repo,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(r.status)throw new Error(r.stderr);return r.stdout;} -beforeAll(()=>{root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-cli-'));repo=path.join(root,'repo');state=path.join(root,'state');fs.mkdirSync(repo);git('init','-q');git('config','user.email','fixture@example.test');git('config','user.name','Fixture');fs.mkdirSync(path.join(repo,'src'));fs.writeFileSync(path.join(repo,'src','users.ts'),'export const tenantQuery = (id:string) => db.user.findUnique({where:{id}})\n');fs.writeFileSync(path.join(repo,'src','control.test.ts'),'export const control = true\n');fs.writeFileSync(path.join(repo,'.env'),`TOKEN=${CREDENTIAL_CANARY}\n`);git('add','src/users.ts','src/control.test.ts','.env');git('commit','-qm','fixture');fs.mkdirSync(path.join(repo,'hostile-bin'));for(const tool of ['git','dirname'])fs.writeFileSync(path.join(repo,'hostile-bin',tool),`#!/bin/sh\ntouch '${path.join(repo,'path-shim-ran')}'\nexit 99\n`,{mode:0o755});for(const f of ['preload.ts','preload.cjs','preload.rb','bashenv'])fs.writeFileSync(path.join(repo,f),`require('fs').writeFileSync('${path.join(repo,'autoload-ran')}','yes')\n`);}); -afterAll(()=>fs.rmSync(root,{recursive:true,force:true})); - -describe('compiled CSO command workflow',()=>{ - test('trusted launcher resists runtime autoload variables and repository PATH shims',()=>{const r=command(['--version']);expect(r.status).toBe(0);expect(JSON.parse(r.stdout)).toEqual({version:'3.0.0',abi:3});expect(fs.existsSync(path.join(repo,'autoload-ran'))).toBe(false);expect(fs.existsSync(path.join(repo,'path-shim-ran'))).toBe(false);}); - test('trusted launcher resolves relative caller paths without trusting an inherited cwd override',()=>{const hostile=path.join(root,'missing-caller-cwd'),diagnosed=command(['doctor','--repo','.'],{GSTACK_CSO_CALLER_CWD:hostile,DOCKER_HOST:'tcp://127.0.0.1:2375'});expect(diagnosed.status).toBe(0);expect(JSON.parse(diagnosed.stdout).checks.find((item:any)=>item.capability==='static-snapshot')).toMatchObject({status:'ready'});const started=command(['start','--repo','.','--scope','auth','--offline'],{GSTACK_CSO_CALLER_CWD:hostile});expect(started.status).toBe(0);const run=JSON.parse(started.stdout),input=path.join(repo,'relative-submission.json');try{fs.writeFileSync(input,'{}');expect(command(['submit',run.runId,'relative-submission.json'],{GSTACK_CSO_CALLER_CWD:hostile}).status).toBe(0);}finally{fs.rmSync(input,{force:true});}}); - test.skipIf(process.platform!=='linux')('static launcher prevents loader injection before environment scrubbing',()=>{const source=path.join(root,'preload.c'),library=path.join(root,'preload.so'),marker=path.join(root,'loader-ran');fs.writeFileSync(source,'#include \n#include \n#include \n__attribute__((constructor)) static void mark(void){const char*p=getenv("CSO_PRELOAD_MARKER");if(p){int f=open(p,O_WRONLY|O_CREAT,0600);if(f>=0)close(f);}}\n');const built=spawnSync('/usr/bin/cc',['-shared','-fPIC',source,'-o',library],{encoding:'utf8',timeout:30_000});expect(built.status).toBe(0);const r=command(['--version'],{LD_PRELOAD:library,CSO_PRELOAD_MARKER:marker});expect(r.status).toBe(0);expect(fs.existsSync(marker)).toBe(false);}); - test('package-manager launcher symlinks resolve the trusted sibling core',()=>{const npmBin=path.join(root,'npm-bin');fs.mkdirSync(npmBin,{recursive:true});const link=path.join(npmBin,'gstack-cso');fs.symlinkSync(launcher,link);const r=command(['--version'],{},link);expect(r.status).toBe(0);expect(JSON.parse(r.stdout)).toEqual({version:'3.0.0',abi:3});}); - test.skipIf(process.platform==='win32')('compiled core starts in the canonical trusted launcher directory',()=>{const install=path.join(root,'trusted launcher'),hostile=path.join(repo,'hostile cwd');fs.mkdirSync(install);fs.mkdirSync(hostile);const publicLauncher=path.join(install,'gstack-cso-launcher'),fixtureCore=path.join(install,'gstack-cso-core'),source=path.join(root,'cwd-fixture.c');fs.writeFileSync(source,'#include \n#include \n#include \nint main(void){char cwd[PATH_MAX];if(!getcwd(cwd,sizeof cwd))return 2;puts(cwd);return 0;}\n');const built=spawnSync('/usr/bin/cc',[source,'-o',fixtureCore],{encoding:'utf8',timeout:30_000});expect(built.status).toBe(0);const digest=createHash('sha256').update(fs.readFileSync(fixtureCore)).digest('hex'),launcherBuild=spawnSync('/usr/bin/cc',['-std=c11','-D_POSIX_C_SOURCE=200809L','-O2',`-DGSTACK_CSO_CORE_SHA256=\"${digest}\"`,path.join(ROOT,'lib/cso/launcher.c'),'-o',publicLauncher],{encoding:'utf8',timeout:30_000});expect(launcherBuild.status).toBe(0);fs.writeFileSync(path.join(install,'.gstack-cso-generation'),`${digest}\n`);const r=spawnSync(publicLauncher,[],{cwd:hostile,encoding:'utf8',env:{...process.env,HOME:root,GSTACK_HOME:state},timeout:30_000});expect(r.status).toBe(0);expect(r.stdout.trim()).toBe(fs.realpathSync(install));expect(r.stdout.trim()).not.toBe(fs.realpathSync(hostile));}); - test('schema advertises only caller-owned verification input',()=>{const r=command(['schema']);expect(r.status).toBe(0);const schema=JSON.parse(r.stdout);expect(schema.verification).not.toHaveProperty('result');expect(schema.helperOwned).toContain('repair result and label');}); - test('v2 imports remain readable and immutable without upgrading legacy proof',()=>{ - const source=path.join(root,'legacy-v2.json'),legacy={schemaVersion:2,findings:[{status:'VERIFIED',title:'Historical authorization finding',description:`Captured credential ${CREDENTIAL_CANARY}`,fingerprint:'legacy-fingerprint',location:{path:'src/legacy.ts',line:17,symbol:'legacyAuthorization'},impact:'Cross-tenant disclosure',recommendation:'Bind the lookup to the authenticated tenant',repair:'VERIFIED'}]}; - fs.writeFileSync(source,JSON.stringify(legacy)); - const imported=command(['import-v2',source]);expect(imported.status).toBe(0);expect(imported.stdout+imported.stderr).not.toContain(CREDENTIAL_CANARY);const result=JSON.parse(imported.stdout),finding=result.report.findings[0]; - expect(result.id).toMatch(/^[a-f0-9]{64}$/);expect(result.warning).toContain('does not establish reproduction, tested repair, or closure');expect(result.report).toMatchObject({schemaVersion:2,readOnly:true}); - expect(finding).toMatchObject({status:'VERIFIED',evidence:'legacy_review',reproduction:'not_attempted',repair:'not_attempted',closure:'unknown',legacy:{fingerprint:'legacy-fingerprint',location:{path:'src/legacy.ts',line:17,symbol:'legacyAuthorization'},impact:'Cross-tenant disclosure',recommendation:'Bind the lookup to the authenticated tenant',repair:'VERIFIED'}}); - fs.writeFileSync(source,JSON.stringify({schemaVersion:2,findings:[]})); - const inspected=command(['inspect-v2',result.id]);expect(inspected.status).toBe(0);expect(inspected.stdout+inspected.stderr).not.toContain(CREDENTIAL_CANARY);expect(JSON.parse(inspected.stdout)).toEqual({id:result.id,report:result.report}); - const stored=path.join(state,'security','cso','legacy-imports',`${result.id}.json`);expect(fs.existsSync(stored)).toBe(true);expect(fs.readFileSync(stored,'utf8')).not.toContain(CREDENTIAL_CANARY); - const invalid=command(['inspect-v2','../legacy-v2.json']);expect(invalid.status).not.toBe(0);expect(invalid.stderr).toContain('64-character import ID'); - const missing=command(['inspect-v2','0'.repeat(64)]);expect(missing.status).not.toBe(0);expect(missing.stderr).toContain('MISSING_INPUT'); - const beforeUnsafe=fs.readdirSync(path.dirname(stored)).length,unsafeKey=`severity\u202eHIGH`;fs.writeFileSync(source,JSON.stringify({schemaVersion:2,findings:[{status:'OPEN',title:'unsafe',nested:{[unsafeKey]:'forged'}}]}));const unsafe=command(['import-v2',source]);expect(unsafe.status).not.toBe(0);expect(unsafe.stderr).toContain('unsafe property');expect(unsafe.stdout+unsafe.stderr).not.toContain(unsafeKey);expect(fs.readdirSync(path.dirname(stored))).toHaveLength(beforeUnsafe); - const changed=JSON.parse(fs.readFileSync(stored,'utf8'));changed.findings[0].status='CHANGED';fs.writeFileSync(stored,JSON.stringify(changed,null,2)+'\n');const tampered=command(['inspect-v2',result.id]);expect(tampered.status).not.toBe(0);expect(tampered.stderr).toContain('identity is inconsistent'); - }); - test('wallet-shaped source paths remain addressable through stable opaque handles',()=>{ - const walletRepo=path.join(root,'wallet-path-repo'),wallet='0x1234567890abcdef1234567890abcdef12345678',sourcePath=`src/${wallet}.ts`; - fs.mkdirSync(path.join(walletRepo,'src'),{recursive:true}); - const runGit=(...args:string[])=>{const result=spawnSync('/usr/bin/git',['-C',walletRepo,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr);}; - runGit('init','-q');runGit('config','user.email','fixture@example.test');runGit('config','user.name','Fixture'); - fs.writeFileSync(path.join(walletRepo,sourcePath),`export const value = true\n// TOKEN=${CREDENTIAL_CANARY}\n`);fs.writeFileSync(path.join(walletRepo,'control.test.js'),'test(\"control\",()=>{})\n');runGit('add','.');runGit('commit','-qm','wallet-shaped path'); - const started=command(['start','--repo',walletRepo,'--comprehensive','--offline']);expect(started.status).toBe(0); - const run=JSON.parse(started.stdout),dir=path.join(state,'security','cso',run.repoId,run.runId),privateManifest=JSON.parse(fs.readFileSync(path.join(dir,'snapshot.json'),'utf8')); - const privateEntry=privateManifest.entries.find((item:any)=>item.path===sourcePath);expect(privateEntry.path).toBe(sourcePath);expect(privateEntry.pathId).toMatch(/^[a-f0-9]{32}$/); - const inspected=command(['inspect',run.runId]);expect(inspected.status).toBe(0);const view=JSON.parse(inspected.stdout),entry=view.manifest.entries.find((item:any)=>item.displayPath); - expect(JSON.stringify(view)).not.toContain(wallet);expect(JSON.stringify(view)).not.toContain('ghp_');expect(entry.path).toMatch(/^@cso-path\/\/[a-f0-9]{32}$/);expect(entry.displayPath).toContain('');expect(entry).not.toHaveProperty('pathId');expect(view.sensitiveEvidence.find((item:any)=>item.path===entry.path)).toBeDefined(); - const read=command(['read',run.runId,entry.path]);expect(read.status).toBe(0);expect(read.stdout).toContain('export const value = true'); - const history=command(['history',run.runId,entry.path]);expect(history.status).toBe(0);expect(history.stdout).toContain('');expect(history.stdout).toContain('export const value = true');expect(history.stdout).not.toContain('No retained patch hunks');expect(history.stdout).not.toContain(wallet); - const input=path.join(root,`wallet-path-${run.runId}.json`),finding={title:'Sensitive-shaped source path',rootCause:'Public route omits an authorization predicate',location:{path:entry.path,line:1,symbol:'value'},advisoryIds:[],severity:'high',confidence:'high',confidenceRationale:'A caller-to-sink trace establishes the missing predicate',evidence:'supported',attackerControl:'Caller chooses the identifier',impact:'Unauthorized record disclosure',scenario:'A caller requests another tenant record',trace:['route','value','response'],references:[`${entry.displayPath}:1`],recommendation:'Bind access to the authenticated tenant',challenge:{reviewer:'reviewer-session',independent:true,mode:'independent_agent',callers:'route caller checked',controls:'authorization is absent',counterevidence:'none found',conclusion:'the tenant predicate is absent'}}; - fs.writeFileSync(input,JSON.stringify({findings:[finding]}));const submitted=command(['submit',run.runId,input]);expect(submitted.status).toBe(0); - const report=JSON.parse(fs.readFileSync(path.join(dir,'report.json'),'utf8'));expect(report.findings).toHaveLength(1);expect(report.findings[0].location.path).toBe(entry.path);expect(report.findings[0].id).toBe(fingerprint(report.findings[0]));expect(JSON.stringify(report)).not.toContain(wallet); - const before=fs.readFileSync(path.join(dir,'snapshot',sourcePath),'utf8'),request:any={findingId:report.findings[0].id,runtimeProfile:'node-v1',port:3456,start:{executable:'/usr/local/bin/node',args:['app.js']},legitimate:[{name:'control',path:'/health',method:'GET',expected:{status:200}}],security:{name:'authorization',path:'/records/other',method:'GET',expected:{status:403},vulnerable:{status:200}},existingTests:[{executable:'/usr/local/bin/node',args:['--test']}],testFiles:['control.test.js'],fixtures:{},boundaryFiles:[entry.path],changes:[{path:entry.path,beforeSha256:sha256(before),after:'export const value = false\n',effect:'source'}],review:{reviewer:'reviewer-session',independent:true,rootCauseRepaired:true,featurePreserved:true,boundaryMocks:false,rationale:'The authorization decision replaces the vulnerable behavior while preserving the control',reviewedPatchHash:''}};request.review.reviewedPatchHash=patchHash(request);fs.writeFileSync(input,JSON.stringify(request));const reviewed=command(['record-review',run.runId,input,'--producer','producer-session']);expect(reviewed.status).toBe(0);request.review.artifactId=JSON.parse(reviewed.stdout).reviewArtifactId;fs.writeFileSync(input,JSON.stringify(request));const verified=command(['verify',run.runId,input]);expect(verified.status).not.toBe(0);expect(verified.stderr).toContain('PREREQUISITE');expect(verified.stderr).not.toContain('Boundary files');expect(verified.stderr).not.toContain('contained relative path'); - expect(report.coverage.find((item:any)=>item.domain==='snapshot-inputs')).toMatchObject({status:'assessed',gaps:[]}); - },15_000); - test('daily audits expose staged tracked deletions as replay-stable handles and material gaps',()=>{ - const deletedRepo=path.join(root,'deleted-path-repo'),wallet='0xabcdefabcdefabcdefabcdefabcdefabcdefabcd',sourcePath=`src/${wallet}.ts`; - fs.mkdirSync(path.join(deletedRepo,'src'),{recursive:true}); - const runGit=(...args:string[])=>{const result=spawnSync('/usr/bin/git',['-C',deletedRepo,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr);return result.stdout;}; - runGit('init','-q');runGit('config','user.email','fixture@example.test');runGit('config','user.name','Fixture');fs.writeFileSync(path.join(deletedRepo,sourcePath),'export const authorization = true\n');fs.writeFileSync(path.join(deletedRepo,'app.js'),'export const app = true\n');runGit('add','.');runGit('commit','-qm','tracked authorization source');runGit('rm','-q',sourcePath); - const started=command(['start','--repo',deletedRepo,'--scope','auth','--offline']);expect(started.status).toBe(0);const run=JSON.parse(started.stdout),dir=path.join(state,'security','cso',run.repoId,run.runId),privateManifest=JSON.parse(fs.readFileSync(path.join(dir,'snapshot.json'),'utf8')); - expect(privateManifest.entries.some((item:any)=>item.path===sourcePath)).toBe(false);expect(privateManifest.deletedPaths).toHaveLength(1);expect(privateManifest.deletedPaths[0]).toMatchObject({path:sourcePath});expect(privateManifest.deletedPaths[0].pathId).toMatch(/^[a-f0-9]{32}$/); - const inspected=command(['inspect',run.runId]);expect(inspected.status).toBe(0);const view=JSON.parse(inspected.stdout),deleted=view.manifest.deletedPaths[0],coverage=view.report.coverage.find((item:any)=>item.domain==='snapshot-inputs'); - expect(JSON.stringify(view)).not.toContain(wallet);expect(deleted.path).toMatch(/^@cso-path\/\/[a-f0-9]{32}$/);expect(deleted.displayPath).toContain('');expect(deleted).not.toHaveProperty('pathId');expect(coverage.status).toBe('partial');expect(coverage.gaps).toEqual([`${deleted.path}: tracked source is deleted from the worktree; only retained history is available for assessment`]);expect(view.report.source.transformations).toContainEqual({path:deleted.path,handling:'tracked source deleted; retained history only'}); - const history=command(['history',run.runId,deleted.path]);expect(history.status).toBe(0);expect(history.stdout).toContain('');expect(history.stdout).not.toContain(wallet);const read=command(['read',run.runId,deleted.path]);expect(read.status).not.toBe(0);expect(read.stderr).toContain('outside the retained inventory'); - const tampered=structuredClone(privateManifest);delete tampered.deletedPaths;fs.writeFileSync(path.join(dir,'snapshot.json'),JSON.stringify(tampered,null,2)+'\n');const rejected=command(['inspect',run.runId]);expect(rejected.status).not.toBe(0);expect(rejected.stderr).toContain('Snapshot original identity is inconsistent'); - }); - test('runtime plans encode sensitive canonical test argv with snapshot handles',()=>{ - const planRepo=path.join(root,'sensitive-plan-repo'),wallet='0x1111111111111111111111111111111111111112',testPath=`${wallet}.test.js`;fs.mkdirSync(planRepo); - const runGit=(...args:string[])=>{const result=spawnSync('/usr/bin/git',['-C',planRepo,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr);}; - runGit('init','-q');runGit('config','user.email','fixture@example.test');runGit('config','user.name','Fixture');fs.writeFileSync(path.join(planRepo,'package.json'),JSON.stringify({name:'sensitive-plan',version:'1.0.0',scripts:{start:'node app.js',test:'node --test'}}));fs.writeFileSync(path.join(planRepo,'package-lock.json'),JSON.stringify({name:'sensitive-plan',version:'1.0.0',lockfileVersion:3,packages:{'':{name:'sensitive-plan',version:'1.0.0'}}}));fs.writeFileSync(path.join(planRepo,'app.js'),'export const app = true\n');fs.writeFileSync(path.join(planRepo,testPath),'const test=require("node:test");test("control",()=>{})\n');runGit('add','.');runGit('commit','-qm','sensitive test path'); - const started=command(['start','--repo',planRepo,'--comprehensive','--offline']);expect(started.status).toBe(0);const run=JSON.parse(started.stdout),planned=command(['runtime-plan',run.runId,'node','--port','3456']);expect(planned.status).toBe(0);const plan=JSON.parse(planned.stdout),serialized=JSON.stringify(plan); - expect(serialized).not.toContain(wallet);const testHandle=plan.tests.files.find((value:string)=>value.startsWith('@cso-path//'));expect(testHandle).toMatch(/^@cso-path\/\/[a-f0-9]{32}$/);expect(plan.tests.commands[0].args).toContain(`./${testHandle}`);expect(plan.start.command).toEqual({executable:'/usr/local/bin/node',args:['app.js']}); - const budget=(Date.parse(run.deadline)-Date.parse(run.createdAt))/1000;for(const remaining of [run.remainingSeconds,plan.remainingSeconds]){expect(Number.isSafeInteger(remaining)).toBe(true);expect(remaining).toBeGreaterThan(budget-120);expect(remaining).toBeLessThanOrEqual(budget-60);}expect(plan.remainingSeconds).toBeLessThanOrEqual(run.remainingSeconds); - }); - test('run clock counts to the investigation deadline: zero in the reporting minute, which still accepts submit until the audit deadline',()=>{ - const started=command(['start','--repo',repo,'--scope','auth','--offline']);expect(started.status).toBe(0);const run=JSON.parse(started.stdout),reportPath=path.join(state,'security','cso',run.repoId,run.runId,'report.json'),input=path.join(root,`clock-${run.runId}.json`);fs.writeFileSync(input,'{}'); - const submitted=command(['submit',run.runId,input]);expect(submitted.status).toBe(0);const inspected=command(['inspect',run.runId]);expect(inspected.status).toBe(0); - for(const remaining of [JSON.parse(submitted.stdout).remainingSeconds,JSON.parse(inspected.stdout).remainingSeconds]){expect(Number.isSafeInteger(remaining)).toBe(true);expect(remaining).toBeGreaterThan(0);expect(remaining).toBeLessThanOrEqual(run.remainingSeconds);} - const report=JSON.parse(fs.readFileSync(reportPath,'utf8'));report.deadline=new Date(Date.now()+30_000).toISOString();fs.writeFileSync(reportPath,JSON.stringify(report,null,2)+'\n'); - const late=command(['inspect',run.runId]);expect(late.status).toBe(0);expect(JSON.parse(late.stdout).remainingSeconds).toBe(0); - const reporting=command(['submit',run.runId,input]);expect(reporting.status).toBe(0);expect(JSON.parse(reporting.stdout).remainingSeconds).toBe(0); - report.deadline=new Date(Date.now()-1_000).toISOString();fs.writeFileSync(reportPath,JSON.stringify({...JSON.parse(fs.readFileSync(reportPath,'utf8')),deadline:report.deadline},null,2)+'\n'); - const refused=command(['submit',run.runId,input]);expect(refused.status).not.toBe(0);expect(refused.stderr).toContain('DEADLINE');expect(refused.stdout).toBe(''); - }); - test('a refused submit keeps the audit open: finish refuses until a corrected submit lands, and closes over it only after the audit deadline',()=>{ - const reportOf=(run:any)=>path.join(state,'security','cso',run.repoId,run.runId,'report.json'),coverage={domain:'auth',scope:'src/users.ts',status:'not_assessed',method:'source review',gaps:['tenant checks not traced'],evidence:[]},bad=path.join(root,'refused-submit.json'),good=path.join(root,'corrected-submit.json'); - fs.writeFileSync(bad,JSON.stringify({coverage:[{...coverage,exclusions:'none'}]}));fs.writeFileSync(good,JSON.stringify({coverage:[{...coverage,exclusions:[]}]})); - const started=command(['start','--repo',repo,'--scope','auth','--offline','--budget','600']);expect(started.status).toBe(0);const run=JSON.parse(started.stdout); - const refused=command(['submit',run.runId,bad]);expect(refused.status).not.toBe(0);expect(refused.stderr).toContain('exclusions must be an array'); - const blocked=command(['finish',run.runId]);expect(blocked.status).not.toBe(0);expect(blocked.stderr).toContain('last submit was refused');expect(blocked.stderr).toContain('exclusions must be an array');expect(JSON.parse(fs.readFileSync(reportOf(run),'utf8')).status).toBe('running'); - const inspected=command(['inspect',run.runId]);expect(inspected.status).toBe(0);const remaining=JSON.parse(inspected.stdout).remainingSeconds;expect(Number.isSafeInteger(remaining)).toBe(true);expect(remaining).toBeGreaterThan(0);expect(remaining).toBeLessThanOrEqual(run.remainingSeconds); - const corrected=command(['submit',run.runId,good]);expect(corrected.status).toBe(0);const finished=command(['finish',run.runId]);expect(finished.status).toBe(0);expect(JSON.parse(finished.stdout).status).toBe('finished'); - const late=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline','--budget','600']).stdout);expect(command(['submit',late.runId,bad]).status).not.toBe(0); - fs.writeFileSync(reportOf(late),JSON.stringify({...JSON.parse(fs.readFileSync(reportOf(late),'utf8')),deadline:new Date(Date.now()-1_000).toISOString()},null,2)+'\n'); - const closed=command(['finish',late.runId]);expect(closed.status).toBe(0);expect(JSON.parse(closed.stdout).status).toBe('finished');expect(JSON.parse(fs.readFileSync(reportOf(late),'utf8')).gaps).toContain('A refused submission was never resubmitted: exclusions must be an array'); - }); - test('wallet-shaped helper finding IDs survive submit, review, and verification admission',()=>{const started=command(['start','--repo',repo,'--comprehensive','--offline']);expect(started.status).toBe(0);const run=JSON.parse(started.stdout),base:any={title:'Wallet-shaped helper ID',rootCause:'Tenant query omits caller tenant predicate 0',location:{path:'src/users.ts',line:1,symbol:'tenantQuery'},advisoryIds:[],severity:'high',confidence:'high',confidenceRationale:'Caller-to-sink trace directly establishes the missing predicate',evidence:'supported',attackerControl:'Tenant chooses the record ID',impact:'Cross-tenant record disclosure',scenario:'A tenant requests another tenant record by ID',trace:['route','tenantQuery','database'],references:['src/users.ts:1'],recommendation:'Bind the query to the authenticated tenant',challenge:{reviewer:'reviewer-session',independent:true,mode:'independent_agent',callers:'route caller checked',controls:'authentication lacks authorization',counterevidence:'none found',conclusion:'tenant predicate is absent'}};let helperId='';for(let i=0;i<10_000;i++){base.rootCause=`Tenant query omits caller tenant predicate ${i}`;helperId=fingerprint(base);if(redact(helperId)!==helperId)break;}expect(redact(helperId)).not.toBe(helperId);const input=path.join(root,`wallet-id-${run.runId}.json`);fs.writeFileSync(input,JSON.stringify({findings:[base]}));expect(command(['submit',run.runId,input]).status).toBe(0);const reportPath=path.join(state,'security','cso',run.repoId,run.runId,'report.json'),stored=JSON.parse(fs.readFileSync(reportPath,'utf8'));expect(stored.findings[0].id).toBe(helperId);const before=fs.readFileSync(path.join(repo,'src','users.ts'),'utf8'),request:any={findingId:helperId,runtimeProfile:'node-v1',port:3456,start:{executable:'/usr/local/bin/node',args:['src/users.ts']},legitimate:[{name:'control',path:'/health',method:'GET',expected:{status:200}}],security:{name:'tenant boundary',path:'/users/other',method:'GET',expected:{status:403},vulnerable:{status:200}},existingTests:[{executable:'/usr/local/bin/node',args:['--test']}],testFiles:['src/control.test.ts'],fixtures:{},boundaryFiles:['src/users.ts'],changes:[{path:'src/users.ts',beforeSha256:sha256(before),after:before+'// tenant predicate\n',effect:'source'}],review:{reviewer:'reviewer-session',independent:true,rootCauseRepaired:true,featurePreserved:true,boundaryMocks:false,rationale:'The tenant predicate is added while the control remains intact',reviewedPatchHash:''}};request.review.reviewedPatchHash=patchHash(request);fs.writeFileSync(input,JSON.stringify(request));const reviewed=command(['record-review',run.runId,input,'--producer','producer-session']);expect(reviewed.status).toBe(0);request.review.artifactId=JSON.parse(reviewed.stdout).reviewArtifactId;fs.writeFileSync(input,JSON.stringify(request));const verified=command(['verify',run.runId,input]);expect(verified.status).not.toBe(0);expect(verified.stderr).toContain('PREREQUISITE');expect(verified.stderr).not.toContain('REDACTION_FAILED');const review=JSON.parse(fs.readFileSync(path.join(path.dirname(reportPath),'reviews',`${request.review.artifactId}.json`),'utf8'));expect(review.findingId).toBe(helperId);}); - test('daily find, early submit, and finish persist a truthful report without changing source',()=>{const before=git('status','--porcelain=v1','-z'),started=command(['start','--repo',repo,'--scope','auth','--offline']);expect(started.status).toBe(0);const run=JSON.parse(started.stdout),runId=run.runId;expect(run.completeness).toBe('not assessed');const reportPath=path.join(state,'security','cso',run.repoId,runId,'report.json');expect(fs.existsSync(reportPath)).toBe(true);const current=JSON.parse(fs.readFileSync(reportPath,'utf8')); - const wallet='0x1234567890abcdef1234567890abcdef12345678',submission={application:{actors:['authenticated tenant user'],assets:['tenant records'],entrypoints:['GET /users/:id'],tenantBoundaries:['record.tenant_id equals session.tenant_id'],sensitiveOperations:['read tenant record'],invariants:['a tenant cannot read another tenant record']},findings:[{title:'Cross-tenant user read',rootCause:`Tenant query ${wallet} omits caller tenant predicate`,location:{path:'src/users.ts',line:1,symbol:'tenantQuery'},advisoryIds:[],severity:'high',confidence:'high',confidenceRationale:'The captured caller-to-sink trace and control review directly support the finding',evidence:'supported',attackerControl:'Authenticated caller chooses the record ID',impact:'Another tenant record is returned',scenario:'A tenant supplies a known record ID owned by another tenant and receives that record',trace:['GET /users/:id','tenantQuery','findUnique by id'],references:['src/users.ts:1','OWASP API1:2023'],recommendation:'Bind the lookup predicate to the authenticated tenant identifier before returning the record',challenge:{reviewer:'independent-2',independent:true,mode:'independent_agent',callers:'Authenticated route forwards path ID',controls:'Authentication exists; authorization predicate does not',counterevidence:'Opaque IDs reduce guessing but do not authorize',conclusion:'The caller can provide a known cross-tenant ID'}}],coverage:current.coverage.filter((c:any)=>!['snapshot-inputs','history-inputs'].includes(c.domain)).map((c:any)=>({...c,status:'assessed',method:'caller and middleware trace',gaps:[],evidence:[`${c.domain} inspected against captured source`]})),gaps:[]};const file=path.join(root,'submission.json');fs.writeFileSync(file,JSON.stringify(submission));const submitted=command(['submit',runId,file]);expect(submitted.status).toBe(0);expect(JSON.parse(fs.readFileSync(reportPath,'utf8')).findings).toHaveLength(1);const finished=command(['finish',runId]);expect(finished.status).toBe(0);const final=JSON.parse(fs.readFileSync(reportPath,'utf8'));expect(final.completeness).toBe('complete');expect(final.findings[0]).toMatchObject({reproduction:'not_attempted',repair:'not_attempted',closure:'open'});expect(final.findings[0].id).toBe(fingerprint(final.findings[0]));expect(JSON.stringify(final)).not.toContain(wallet);const markdown=fs.readFileSync(path.join(path.dirname(reportPath),'report.md'),'utf8');expect(markdown.startsWith('complete — domain:auth')).toBe(true);expect(markdown).toContain('.env: excluded: credential or execution configuration');expect(markdown).not.toContain('ghp_');expect(git('status','--porcelain=v1','-z')).toBe(before);}); - test('credential originals are withheld rather than printed',()=>{const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout);const result=command(['read',run.runId,'.env']);expect(result.status).toBe(0);expect(result.stdout.trim()).toBe('TOKEN=');expect(result.stderr).toBe('');expect(result.stdout+result.stderr).not.toContain('ghp_');expect(result.stdout+result.stderr).not.toContain(CREDENTIAL_CANARY);expect(fs.existsSync(path.join(state,'security','cso',run.repoId,run.runId,'snapshot','.env'))).toBe(false);}); - test('supplementary NFKC expansion cannot displace compiled reader redaction',()=>{ - const file=path.join(repo,'.env'); - expect(fs.realpathSync(file)).toBe(path.join(fs.realpathSync(repo),'.env')); - const original=fs.readFileSync(file),prefix='\uFA6C'.repeat(64)+'\n',suffix='\n'+'z'.repeat(256); - const value=['8Fk2pQ9vXz4wL7mN','3rT6yB1cD5eG0hJq'].join(''); - try{ - fs.writeFileSync(file,`${prefix}DB_PASSWORD=${value}${suffix}`); - const started=command(['start','--repo',repo,'--scope','auth','--offline']);expect(started.status).toBe(0); - const run=JSON.parse(started.stdout),result=command(['read',run.runId,'.env']); - expect(result.status).toBe(0);expect(result.stderr).toBe(''); - expect(result.stdout.trimEnd()).toBe(`${prefix}DB_PASSWORD=${suffix}`); - expect(result.stdout+result.stderr).not.toContain(value); - expect(fs.existsSync(path.join(state,'security','cso',run.repoId,run.runId,'snapshot','.env'))).toBe(false); - }finally{fs.writeFileSync(file,original);} - }); - test('marker-only credential payloads remain unavailable to the compiled reader',()=>{ - const file=path.join(repo,'.env'),original=fs.readFileSync(file),body=['-----BEGIN ','PRIVATE KEY-----\n','synthetic-key-body\n','-----END ','PRIVATE KEY-----\n'].join(''); - try{ - fs.writeFileSync(file,body); - const started=command(['start','--repo',repo,'--scope','auth','--offline']);expect(started.status).toBe(0); - const run=JSON.parse(started.stdout),result=command(['read',run.runId,'.env']); - expect(result.status).not.toBe(0);expect(result.stderr).toContain('MISSING_INPUT');expect(result.stdout+result.stderr).not.toContain('synthetic-key-body'); - const dir=path.join(state,'security','cso',run.repoId,run.runId); - expect(fs.existsSync(path.join(dir,'readable','.env'))).toBe(false);expect(fs.existsSync(path.join(dir,'snapshot','.env'))).toBe(false); - }finally{fs.writeFileSync(file,original);} - }); - test('bounded submission and snapshot readers reject multiply-linked pathnames',()=>{const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),dir=path.join(state,'security','cso',run.repoId,run.runId),inputSource=path.join(root,`linked-input-source-${run.runId}.json`),input=path.join(root,`linked-input-${run.runId}.json`);fs.writeFileSync(inputSource,'{}');fs.linkSync(inputSource,input);const submitted=command(['submit',run.runId,input]);expect(submitted.status).not.toBe(0);expect(submitted.stderr).toContain('one bounded regular file');const readable=path.join(dir,'readable','src','users.ts'),outside=path.join(root,`linked-readable-${run.runId}`);fs.linkSync(readable,outside);const read=command(['read',run.runId,'src/users.ts']);expect(read.status).not.toBe(0);expect(read.stderr).toContain('one bounded regular file');}); - test.skipIf(process.platform==='win32')('rejects a SARIF FIFO without blocking on open',()=>{const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),fifo=path.join(root,`sarif-${run.runId}.pipe`);expect(spawnSync('/usr/bin/mkfifo',[fifo],{encoding:'utf8',timeout:5_000}).status).toBe(0);const started=Date.now(),imported=command(['import-sarif',run.runId,fifo]);expect(Date.now()-started).toBeLessThan(2_000);expect(imported.status).not.toBe(0);expect(imported.stderr).toContain('bounded regular file');}); - test('model submissions cannot overwrite helper-owned readiness or scanner coverage',()=>{const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),file=path.join(root,'helper-coverage.json');fs.writeFileSync(file,JSON.stringify({coverage:[{domain:'runtime-readiness',scope:'node',status:'assessed',method:'claimed by model',gaps:[],exclusions:[],evidence:['untrusted claim']}]}));const result=command(['submit',run.runId,file]);expect(result.status).not.toBe(0);expect(result.stderr).toContain('helper-owned');const report=JSON.parse(fs.readFileSync(path.join(state,'security','cso',run.repoId,run.runId,'report.json'),'utf8'));expect(report.coverage.some((x:any)=>x.domain==='runtime-readiness')).toBe(false);}); - test('submission typos are rejected instead of silently weakening evidence',()=>{const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),file=path.join(root,'typo-submission.json');for(const value of [{finding:[]},{modelUsage:{source:'host',tokens:1,tokenz:1}},{application:{actors:['a'],assets:['b'],entrypoints:['c'],tenantBoundaries:['d'],sensitiveOperations:['e'],invariants:['f'],unknown:['g']}}]){fs.writeFileSync(file,JSON.stringify(value));const result=command(['submit',run.runId,file]);expect(result.status).not.toBe(0);expect(result.stderr).toContain('Unexpected');}}); - test('submission collections and numeric usage fail with precise schema errors',()=>{const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),file=path.join(root,'invalid-submission-shape.json');for(const [body,message] of [['{"findings":{}}','submission.findings must be an array'],['{"coverage":{}}','submission.coverage must be an array'],['{"modelUsage":{"source":"host","tokens":0,"cost":1e400}}','finite nonnegative']]){fs.writeFileSync(file,body);const result=command(['submit',run.runId,file]);expect(result.status).not.toBe(0);expect(result.stderr).toContain(message);}}); - test('the reserved reporting minute accepts evidence until the actual deadline',()=>{const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),reportPath=path.join(state,'security','cso',run.repoId,run.runId,'report.json'),report=JSON.parse(fs.readFileSync(reportPath,'utf8')),file=path.join(root,`reporting-reserve-${run.runId}.json`);fs.writeFileSync(file,'{}');report.deadline=new Date(Date.now()+30_000).toISOString();fs.writeFileSync(reportPath,JSON.stringify(report,null,2)+'\n');expect(command(['submit',run.runId,file]).status).toBe(0);report.deadline=new Date(Date.now()-1_000).toISOString();fs.writeFileSync(reportPath,JSON.stringify(report,null,2)+'\n');const expired=command(['submit',run.runId,file]);expect(expired.status).not.toBe(0);expect(expired.stderr).toContain('Audit deadline reached');}); - test('explicit base pins history even when finding scope is not diff-only',()=>{const head=git('rev-parse','HEAD').trim(),started=command(['start','--repo',repo,'--scope','auth','--offline','--base','HEAD']);expect(started.status).toBe(0);const run=JSON.parse(started.stdout),dir=path.join(state,'security','cso',run.repoId,run.runId),report=JSON.parse(fs.readFileSync(path.join(dir,'report.json'),'utf8')),history=JSON.parse(fs.readFileSync(path.join(dir,'history-status.json'),'utf8'));expect(report.policy.diff).toBe(false);expect(report.source.baseCommit).toBe(head);expect(history.range).toBe(`${head}..${head}`);const invalid=command(['start','--repo',repo,'--scope','auth','--offline','--base','missing-ref']);expect(invalid.status).not.toBe(0);expect(invalid.stderr).toContain('MISSING_INPUT');}); - test('an optional scanner prerequisite does not turn completed manual coverage partial',()=>{ - const run=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout); - // The scanner prerequisite must be absent here, so point Docker at a dead socket: a machine with Docker and a pulled image otherwise scans. - const scanned=command(['scan',run.runId,'gitleaks'],{DOCKER_HOST:`unix://${path.join(root,'no-docker.sock')}`});expect(scanned.status).toBe(0);expect(JSON.parse(scanned.stdout).status).toBe('not_assessed'); - const reportPath=path.join(state,'security','cso',run.repoId,run.runId,'report.json'),report=JSON.parse(fs.readFileSync(reportPath,'utf8')); - const input=path.join(root,`manual-${run.runId}.json`);fs.writeFileSync(input,JSON.stringify({application:{actors:['tenant user'],assets:['tenant records'],entrypoints:['GET /users/:id'],tenantBoundaries:['tenant id'],sensitiveOperations:['record read'],invariants:['tenant isolation']},coverage:report.coverage.filter((c:any)=>!c.domain.startsWith('scanner:')&&!['snapshot-inputs','history-inputs'].includes(c.domain)).map((c:any)=>({...c,status:'assessed',method:'manual source and caller review',gaps:[],evidence:['fresh captured-source trace']})),gaps:[]})); - expect(command(['submit',run.runId,input]).status).toBe(0);expect(command(['finish',run.runId]).status).toBe(0);const final=JSON.parse(fs.readFileSync(reportPath,'utf8'));expect(final.completeness).toBe('complete');expect(final.coverage.find((c:any)=>c.domain==='scanner:gitleaks').status).toBe('not_assessed'); - }); - test('unread tracked source is a disclosed helper-owned material gap',()=>{ - const binaryRepo=path.join(root,'binary-repo'),runGit=(...args:string[])=>{const result=spawnSync('/usr/bin/git',['-C',binaryRepo,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr);}; - fs.mkdirSync(binaryRepo);runGit('init','-q');runGit('config','user.email','fixture@example.test');runGit('config','user.name','Fixture'); - fs.writeFileSync(path.join(binaryRepo,'app.js'),'export const ready = true\n');fs.writeFileSync(path.join(binaryRepo,'auth.wasm'),Buffer.from([0,97,115,109,1,0,0,0])); - runGit('add','app.js','auth.wasm');runGit('commit','-qm','binary security boundary'); - const started=command(['start','--repo',binaryRepo,'--scope','auth','--offline']);expect(started.status).toBe(0); - const run=JSON.parse(started.stdout),reportPath=path.join(state,'security','cso',run.repoId,run.runId,'report.json'),initial=JSON.parse(fs.readFileSync(reportPath,'utf8')); - expect(initial.coverage.find((item:any)=>item.domain==='snapshot-inputs')).toMatchObject({status:'partial',gaps:['auth.wasm: in-scope source payload was unread and withheld from static and runtime assessment']}); - expect(initial.source.transformations).toContainEqual({path:'auth.wasm',handling:'withheld: binary or redaction failed'}); - const override=path.join(root,`snapshot-override-${run.runId}.json`);fs.writeFileSync(override,JSON.stringify({coverage:[{domain:'snapshot-inputs',scope:'domain:auth',status:'assessed',method:'model claim',gaps:[],exclusions:[],evidence:['claimed complete']}]})); - const rejected=command(['submit',run.runId,override]);expect(rejected.status).not.toBe(0);expect(rejected.stderr).toContain('helper-owned'); - const evidence=path.join(root,`binary-evidence-${run.runId}.json`);fs.writeFileSync(evidence,JSON.stringify({application:{actors:['authenticated user'],assets:['authorization policy'],entrypoints:['application request'],tenantBoundaries:['authorization boundary'],sensitiveOperations:['protected operation'],invariants:['authorization is enforced']},coverage:initial.coverage.filter((item:any)=>!['snapshot-inputs','history-inputs'].includes(item.domain)).map((item:any)=>({...item,status:'assessed',method:'captured source review',gaps:[],evidence:['reviewed readable captured source']})),gaps:[]})); - expect(command(['submit',run.runId,evidence]).status).toBe(0);expect(command(['finish',run.runId]).status).toBe(0); - const final=JSON.parse(fs.readFileSync(reportPath,'utf8')),markdown=fs.readFileSync(path.join(path.dirname(reportPath),'report.md'),'utf8'); - expect(final.completeness).toBe('partial');expect(final.coverage.find((item:any)=>item.domain==='snapshot-inputs').status).toBe('partial'); - expect(markdown.startsWith('partial — domain:auth')).toBe(true);expect(markdown).toContain('auth.wasm: in-scope source payload was unread');expect(markdown).toContain('auth.wasm: withheld: binary or redaction failed'); - }); - test('a surviving root-cause variant leaves the fresh recheck open for correction',()=>{const original=JSON.parse(command(['start','--repo',repo,'--scope','auth','--offline']).stdout),rootCause='Tenant query omits caller tenant predicate',finding={title:'Cross-tenant user read',rootCause,location:{path:'src/users.ts',line:1,symbol:'tenantQuery'},advisoryIds:[],severity:'high',confidence:'high',confidenceRationale:'The captured caller-to-sink trace and control review directly support the finding',evidence:'supported',attackerControl:'Authenticated caller chooses the record ID',impact:'Another tenant record is returned',scenario:'A tenant supplies a known record ID owned by another tenant and receives that record',trace:['GET /users/:id','tenantQuery','findUnique by id'],references:['src/users.ts:1','OWASP API1:2023'],recommendation:'Bind the lookup predicate to the authenticated tenant identifier before returning the record',challenge:{reviewer:'independent-2',independent:true,mode:'independent_agent',callers:'Authenticated route forwards path ID',controls:'Authentication exists; authorization predicate does not',counterevidence:'Opaque IDs reduce guessing but do not authorize',conclusion:'The caller can provide a known cross-tenant ID'}},application={actors:['tenant user'],assets:['records'],entrypoints:['GET /users/:id'],tenantBoundaries:['tenant id'],sensitiveOperations:['record read'],invariants:['tenant isolation']},reportPath=path.join(state,'security','cso',original.repoId,original.runId,'report.json'),report=JSON.parse(fs.readFileSync(reportPath,'utf8')),submission=path.join(root,'recheck-original.json');fs.writeFileSync(submission,JSON.stringify({application,findings:[finding],coverage:report.coverage.filter((c:any)=>!['snapshot-inputs','history-inputs'].includes(c.domain)).map((c:any)=>({...c,status:'assessed',gaps:[],method:'fresh trace',evidence:['captured source']})),gaps:[]}));expect(command(['submit',original.runId,submission]).status).toBe(0);expect(command(['finish',original.runId]).status).toBe(0);const findingId=JSON.parse(fs.readFileSync(reportPath,'utf8')).findings[0].id,rechecked=command(['recheck',findingId,'--run',original.runId,'--repo',repo]);expect(rechecked.status).toBe(0);const child=JSON.parse(rechecked.stdout),childPath=path.join(state,'security','cso',original.repoId,child.runId,'report.json'),childReport=JSON.parse(fs.readFileSync(childPath,'utf8')),claim=path.join(root,'recheck-claim.json'),variant={...finding,title:'Moved cross-tenant user read',location:{...finding.location,symbol:'movedTenantQuery'}};fs.writeFileSync(claim,JSON.stringify({application,findings:[variant],coverage:childReport.coverage.filter((c:any)=>!['snapshot-inputs','history-inputs'].includes(c.domain)).map((c:any)=>({...c,status:'assessed',gaps:[],method:'fresh current-source trace',evidence:['new snapshot']})),gaps:[],recheck:{findingId,outcome:'resolved',evidence:[{kind:'caller',path:'src/users.ts',line:1,observation:'Fresh caller trace reaches the tenant predicate'},{kind:'security_boundary',path:'src/users.ts',line:1,observation:'Fresh boundary trace checks cross-tenant denial'}],rootCause}}));expect(command(['submit',child.runId,claim]).status).toBe(0);const finished=command(['finish',child.runId]);expect(finished.status).not.toBe(0);expect(finished.stderr).toContain('surviving root-cause');expect(JSON.parse(fs.readFileSync(childPath,'utf8')).status).toBe('running');}); - test('doctor performs no downloads and rejects a remote Docker endpoint',()=>{const r=command(['doctor','--repo',repo],{DOCKER_HOST:'tcp://127.0.0.1:2375'});expect(r.status).toBe(0);const value=JSON.parse(r.stdout);expect(value.downloads).toBe(false);expect(value.checks.find((x:any)=>x.capability==='local-docker-isolation')).toMatchObject({status:'missing'});expect(JSON.stringify(value)).toContain('Remote TCP');}); - test('doctor returns exact missing capabilities for an unavailable repository',()=>{const r=command(['doctor','--repo',path.join(root,'missing-repository')],{DOCKER_HOST:'tcp://127.0.0.1:2375'});expect(r.status).toBe(0);const value=JSON.parse(r.stdout);expect(value.elapsedMs).toBeLessThan(30_000);expect(value.checks.find((x:any)=>x.capability==='static-snapshot')).toMatchObject({status:'missing'});expect(value.checks.find((x:any)=>x.capability==='application-preparation')).toMatchObject({status:'missing'});expect(value.checks.find((x:any)=>x.capability==='qualified-runtimes')).toMatchObject({status:'missing'});}); - test('audits nonignored source in a newly initialized repository before its first commit',()=>{ - const unborn=path.join(root,'unborn-repo');fs.mkdirSync(unborn);const runGit=(...args:string[])=>{const result=spawnSync('/usr/bin/git',['-C',unborn,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr);};runGit('init','-q');fs.writeFileSync(path.join(unborn,'app.js'),'export const newProject = true\n'); - const diagnosed=command(['doctor','--repo',unborn],{DOCKER_HOST:'tcp://127.0.0.1:2375'});expect(diagnosed.status).toBe(0);expect(JSON.parse(diagnosed.stdout).checks.find((item:any)=>item.capability==='static-snapshot')).toMatchObject({status:'ready'}); - const started=command(['start','--repo',unborn,'--scope','auth','--offline']);expect(started.status).toBe(0);const run=JSON.parse(started.stdout),dir=path.join(state,'security','cso',run.repoId,run.runId),manifest=JSON.parse(fs.readFileSync(path.join(dir,'snapshot.json'),'utf8')),history=JSON.parse(fs.readFileSync(path.join(dir,'history-status.json'),'utf8')); - expect(manifest).not.toHaveProperty('headCommit');expect(manifest.entries.find((item:any)=>item.path==='app.js')?.executionHash).toMatch(/^[a-f0-9]{64}$/);expect(history).toEqual({status:'captured',range:'unborn HEAD',commits:0,bytes:0}); - }); - test('state configured inside the audited repository is rejected before changing it',()=>{const before=git('status','--porcelain=v1','-z'),r=command(['start','--repo',repo],{GSTACK_HOME:path.join(repo,'.private-state')});expect(r.status).not.toBe(0);expect(r.stderr).toContain('UNSAFE_PATH');expect(fs.existsSync(path.join(repo,'.private-state'))).toBe(false);expect(git('status','--porcelain=v1','-z')).toBe(before);}); -}); - - -test('native public reports conceal the source root while private snapshots retain their identity', () => { - const canonicalRepo = fs.realpathSync(repo), statusBefore = git('status', '--porcelain=v1', '--untracked-files=all'); - const sourceFiles = git('ls-files', '-z').split('\0').filter(Boolean); - const sourceHashes = () => Object.fromEntries(sourceFiles.map(file => [file, sha256(fs.readFileSync(path.join(repo, file)))])); - const before = sourceHashes(), maskedRoot = ''; - const started = command(['start', '--repo', repo, '--scope', 'auth', '--offline', '--base', 'HEAD']); - expect(started.status).toBe(0); - expect(started.stdout).not.toContain(canonicalRepo); - expect(started.stdout).not.toContain(CREDENTIAL_CANARY); - const run = JSON.parse(started.stdout); - expect(run.source.root).toBe(maskedRoot); - const dir = path.join(state, 'security', 'cso', run.repoId, run.runId); - const manifestPath = path.join(dir, 'snapshot.json'), manifestBytes = fs.readFileSync(manifestPath, 'utf8'); - const manifest = JSON.parse(manifestBytes); - expect(manifest.root).toBe(canonicalRepo); - expect(manifest.executionHash).toBe(run.source.snapshotHash); - expect(manifest.originalHash).toBe(run.source.originalHash); - const reportPath = path.join(dir, 'report.json'); - const persisted = JSON.parse(fs.readFileSync(reportPath, 'utf8')); - expect(persisted.source.root).toBe(maskedRoot); - // An older retained report may still contain the root. Public inspection - // must mask it without rewriting the private snapshot or the old report. - const legacy = JSON.stringify({ ...persisted, source: { ...persisted.source, root: canonicalRepo } }, null, 2) + '\n'; - fs.writeFileSync(reportPath, legacy, { mode: 0o600 }); - const inspected = command(['inspect', run.runId]); - expect(inspected.status).toBe(0); - expect(inspected.stdout).not.toContain(canonicalRepo); - expect(inspected.stdout).not.toContain(CREDENTIAL_CANARY); - const view = JSON.parse(inspected.stdout); - expect(view.report.source.root).toBe(maskedRoot); - expect(view.manifest.root).toBe(maskedRoot); - expect(view.manifest.executionHash).toBe(manifest.executionHash); - expect(view.manifest.originalHash).toBe(manifest.originalHash); - expect(fs.readFileSync(reportPath, 'utf8')).toBe(legacy); - const finished = command(['finish', run.runId]); - expect(finished.status).toBe(0); - expect(JSON.parse(finished.stdout).status).toBe('finished'); - const raw = fs.readFileSync(reportPath, 'utf8'); - expect(raw).not.toContain(canonicalRepo); - expect(raw).not.toContain(CREDENTIAL_CANARY); - expect(JSON.parse(raw).source.root).toBe(maskedRoot); - expect(fs.readFileSync(path.join(dir, 'report.md'), 'utf8')).not.toContain(canonicalRepo); - expect(fs.readFileSync(manifestPath, 'utf8')).toBe(manifestBytes); - expect(sourceHashes()).toEqual(before); - expect(git('status', '--porcelain=v1', '--untracked-files=all')).toBe(statusBefore); -}); diff --git a/test/cso-contracts.test.ts b/test/cso-contracts.test.ts deleted file mode 100644 index 3f8f452be..000000000 --- a/test/cso-contracts.test.ts +++ /dev/null @@ -1,327 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import * as crypto from 'node:crypto'; -import { canonical, completeness, CsoError, fingerprint, importLegacy, renderReport, sha256, snapshotPathHandle, snapshotPathId, validateCoverage, validateFinding, validateVerificationObservation, validateVerificationRequest } from '../lib/cso/contracts'; -import { assertCanonicalStartPlan, canonicalStartPlan, canonicalTestPlan, certify, fileEffect, makeReviewArtifact, patchHash, preparePatchedSource, resolveVerificationRequestPaths, testExecutionPassed, treeHash, validateRepairBundle, validateReviewArtifact, verificationHarnessHash, verificationIdentity, verifyRepair } from '../lib/cso/verification'; -import { assertionWitnessPairHash, witnessObservationHash } from '../lib/cso/witness'; -import { admit, machinePoolRoot, markSupervised, release } from '../lib/cso/admission'; -import { sanitizeHelperForJson } from '../lib/cso/process'; -import { spawnSync } from 'node:child_process'; -import { dispatchCsoCommand } from '../lib/cso/cli'; -import { RUNTIME_CATALOG } from '../lib/cso/runtime-catalog'; - -const dirs:string[]=[];const tmp=()=>{const p=fs.mkdtempSync(path.join(os.tmpdir(),'cso-contract-'));dirs.push(p);return p;};afterEach(()=>{for(const p of dirs.splice(0))fs.rmSync(p,{recursive:true,force:true});}); -const CREDENTIAL_CANARY=['ghp_','abcdefghijklmnopqrstuvwxyz1234567890'].join(''); -const finding:any={title:'Cross-tenant read',rootCause:'Tenant query omits caller tenant predicate',location:{path:'src/users.ts',line:4,symbol:'getUser'},advisoryIds:[],severity:'high',confidence:'high',confidenceRationale:'The captured caller-to-sink trace and control review directly support the finding',evidence:'supported',attackerControl:'Authenticated user selects another object ID',impact:'Reads another tenant record',scenario:'A tenant supplies a known record ID owned by a second tenant and receives that record',trace:['GET /users/:id','getUser','db.user.findUnique'],references:['src/users.ts:4','OWASP API1:2023'],recommendation:'Bind every record lookup to the authenticated tenant identifier and reject a missing tenant context',challenge:{reviewer:'reviewer-2',independent:true,mode:'independent_agent',callers:'Route is public to authenticated tenants',controls:'Session middleware authenticates but does not bind tenant',counterevidence:'UUID is unguessable only by convention',conclusion:'Authorization invariant is absent'}}; -const request=(before:string,after:string)=>({findingId:'a'.repeat(32),runtimeProfile:'node',port:3456,start:{executable:'/usr/local/bin/node',args:['app.js']},legitimate:[{name:'health',path:'/health',method:'GET',expected:{status:200,includes:'ok'}}],security:{name:'tenant isolation',path:'/user?id=2',method:'GET',expected:{status:403},vulnerable:{status:200,includes:'tenant-b'}},existingTests:[{executable:'/usr/local/bin/node',args:['test.js']}],testFiles:['test.js'],fixtures:{'tenant.json':'{}'},boundaryFiles:['app.js'],changes:[{path:'app.js',beforeSha256:sha256(before),after,effect:'source'}],review:{reviewer:'independent-reviewer',independent:true,rootCauseRepaired:true,featurePreserved:true,boundaryMocks:false,rationale:'Predicate now binds the caller tenant and health behavior is preserved',reviewedPatchHash:''}}); -// Structural signed fixture for bundle-reader mutation tests. Production -// issuance uses AssertionWitnessSession in verifyRepair instead. -function authenticatedBundleFixture(certified:ReturnType,params:any,outcomes?:Record<'before'|'after',{executedTests:number;passingTests:number}>,externalAssertionsPassed:Record<'before'|'after',boolean>={before:true,after:true}):any{ - const verification=structuredClone(certified.manifest),identityRequest=params.identityRequest??params.request,pair=crypto.generateKeyPairSync('ed25519'),publicKey=pair.publicKey.export({format:'der',type:'spki'}).toString('hex'),keyId=sha256(Buffer.from(publicKey,'hex')),createdAt=verification.createdAt,runner={testToolchain:params.testToolchain,startPlanHash:verification.startPlanHash,testPlanHash:verification.testPlanHash,commandsHash:sha256(canonical(params.request.existingTests)),minimumPassingTestsHash:sha256(canonical(params.request.existingTests.map(()=>1)))},make=(phase:'before'|'after')=>{const observation=verification[phase],counts=outcomes?.[phase]??{executedTests:1,passingTests:1},binding:any={schemaVersion:1,protocol:'gstack-cso-assertion-witness-v1',nonce:sha256(`${phase}:${createdAt}`),phase,issuedAt:createdAt,expiresAt:new Date(Date.parse(createdAt)+300_000).toISOString(),runId:params.runId,findingId:identityRequest.findingId,policyHash:verification.policyHash,auditPolicyHash:verification.auditPolicyHash,runtime:{image:params.runtime.image,verifierImage:params.verifier.image,platform:params.runtime.platform,profile:params.runtime.id},runner,sourceHash:phase==='before'?verification.beforeSourceHash:verification.afterSourceHash,dependencyHash:phase==='before'?verification.beforeDependencies:verification.afterDependencies,configurationHash:phase==='before'?verification.beforeConfiguration:verification.afterConfiguration,requestHash:verification.requestHash,patchHash:verification.patchHash,harnessHash:verification.harnessHash,assertionHash:sha256(canonical({legitimate:identityRequest.legitimate,security:identityRequest.security})),fixturesHash:verification.fixturesHash},executions=params.request.existingTests.map((command:any)=>({commandHash:sha256(canonical(command)),exitCode:0,outputHash:sha256(`structural signed fixture ${phase}`),minimumPassingTests:1,...counts,reportedPassed:counts.passingTests>=1})),unsigned:any={schemaVersion:1,binding,keyId,publicKey,observationHash:witnessObservationHash(observation),externalAssertionsPassed:externalAssertionsPassed[phase],diagnosticTestsPassed:executions.every((execution:any)=>execution.reportedPassed),executions};return{...unsigned,signature:crypto.sign(null,Buffer.from(canonical(unsigned)),pair.privateKey).toString('hex')}};const witness={before:make('before'),after:make('after')};verification.assertionAssurance='authenticated_out_of_process';verification.testCompletionAssurance='self_reported';verification.witnessHash=assertionWitnessPairHash(witness);verification.result='runtime_tested';verification.id='';const id=verificationIdentity(verification);verification.id=id; - return{schemaVersion:3,runId:params.runId,id,createdAt,expiresAt:new Date(Date.parse(createdAt)+30*86400_000).toISOString(),requiredInputs:{sourceHash:params.manifest.executionHash,originalHash:params.manifest.originalHash,runtimeImage:params.runtime.image,platform:params.runtime.platform,archives:params.archives,...(params.dependencyClosures?{dependencyClosures:params.dependencyClosures}:{})},request:identityRequest,verification,transformations:params.manifest.entries.filter((entry:any)=>entry.transformation),...(params.preparation?{preparation:params.preparation}:{}),witness}; -} - -describe('CSO evidence contracts',()=>{ - test('stable fingerprints normalize root-cause whitespace and advisory identity while ignoring generated prose',()=>{const a=validateFinding({...finding,advisoryIds:['ghsa-abcd-1234-efgh','CVE-2026-12345']}),b=validateFinding({...finding,title:'Different words',severity:'medium',confidence:'medium',scenario:'Different scenario prose',recommendation:'Different repair prose',rootCause:' TENANT query\n omits caller tenant predicate ',advisoryIds:['cve-2026-12345','GHSA-ABCD-1234-EFGH','cve-2026-12345'],location:{...finding.location,line:99}});expect(a.fingerprint).toBe(b.fingerprint);expect(b.advisoryIds).toEqual(['CVE-2026-12345','GHSA-ABCD-1234-EFGH']);}); - test('model output cannot set proof or closure states',()=>{expect(()=>validateFinding({...finding,reproduction:'reproduced'})).toThrow('helper-owned');expect(()=>validateFinding({...finding,repair:'tested'})).toThrow('helper-owned');expect(()=>validateFinding({...finding,closure:'resolved'})).toThrow('helper-owned');expect(()=>validateFinding({...finding,verificationAssurance:{assertions:'authenticated_out_of_process',testCompletion:'authenticated_out_of_process',review:'self_attested'}})).toThrow('helper-owned');}); - test('opaque snapshot handles resolve to exact private verification paths and command arguments',()=>{const root='/private/repository',appId=snapshotPathId(root,'src/private.js'),testId=snapshotPathId(root,'test/control.js'),appHandle=snapshotPathHandle(appId),testHandle=snapshotPathHandle(testId),raw:any=request('vulnerable\n','fixed\n');raw.start.args=[appHandle];raw.existingTests[0].args=[`./${testHandle}`];raw.boundaryFiles=[appHandle];raw.testFiles=[testHandle];raw.changes[0].path=appHandle;raw.review.reviewedPatchHash=patchHash(raw);const publicRequest=validateVerificationRequest(raw),manifest:any={root,entries:[{path:'src/private.js',pathId:appId},{path:'test/control.js',pathId:testId}]},resolved=resolveVerificationRequestPaths(manifest,publicRequest);expect(publicRequest.start.args).toEqual([appHandle]);expect(publicRequest.existingTests[0].args).toEqual([`./${testHandle}`]);expect(publicRequest.boundaryFiles[0]).toBe(appHandle);expect(resolved.start.args).toEqual(['src/private.js']);expect(resolved.existingTests[0].args).toEqual(['./test/control.js']);expect(resolved.boundaryFiles).toEqual(['src/private.js']);expect(resolved.testFiles).toEqual(['test/control.js']);expect(resolved.changes[0].path).toBe('src/private.js');expect(resolved.review.reviewedPatchHash).toBe(patchHash(publicRequest));}); - test('supported evidence needs references, a repair, a challenge, a trace, and calibrated confidence',()=>{expect(()=>validateFinding({...finding,trace:[]})).toThrow();expect(()=>validateFinding({...finding,references:[]})).toThrow('supporting references');expect(()=>validateFinding({...finding,confidence:'low'})).toThrow();expect(()=>validateFinding({...finding,challenge:{...finding.challenge,independent:false}})).toThrow('fallback label');expect(()=>validateFinding({...finding,challenge:{...finding.challenge,reviewer:'sequential challenge; independent agent unavailable'}})).toThrow('fallback label');const fallback=validateFinding({...finding,challenge:{...finding.challenge,reviewer:'sequential challenge; independent agent unavailable',independent:false,mode:'sequential_fallback'}});expect(fallback.challenge).toMatchObject({independent:false,mode:'sequential_fallback'});const missing=structuredClone(finding);delete missing.challenge.independent;expect(()=>validateFinding(missing)).toThrow('must be a boolean');}); - test('every incomplete coverage state names its gap',()=>{expect(()=>validateCoverage({domain:'auth',scope:'all',status:'assessed',method:'trace',gaps:['admin not read'],exclusions:[],evidence:['route']})).toThrow();expect(()=>validateCoverage({domain:'auth',scope:'all',status:'partial',method:'trace',gaps:[],exclusions:[],evidence:['route']})).toThrow('concrete gap');expect(()=>validateCoverage({domain:'auth',scope:'all',status:'not_assessed',method:'trace',gaps:[],exclusions:[],evidence:[]})).toThrow('concrete gap');expect(()=>validateCoverage({domain:'payments',scope:'all',status:'not_applicable',method:'model',gaps:[],exclusions:[],evidence:[]})).toThrow();}); - test('completeness is independent of findings and renders the required empty phrase',()=>{const base:any={coverage:[{domain:'auth',scope:'all',status:'assessed',method:'trace',gaps:[],exclusions:[],evidence:['routes']}],gaps:[]};expect(completeness(base)).toBe('complete');const report:any={...base,schemaVersion:3,runId:'r',repoId:'x',createdAt:'2026-01-01',deadline:'2026-01-01',status:'finished',completeness:'complete',policy:{mode:'daily',scope:'all',diff:false,base:'main',offline:true,budgetSeconds:600,maxWorkers:3,maxRepairs:3},source:{root:'/x',snapshotHash:'s',originalHash:'o'},application:{actors:[],assets:[],entrypoints:[],tenantBoundaries:[],sensitiveOperations:[],invariants:[]},findings:[],events:[]};expect(renderReport(report)).toContain('No supported findings in the assessed scope.');base.gaps=['scanner failed'];expect(completeness(base)).toBe('partial');}); - test('readable reports show timing and supplied host model usage without inventing either',()=>{const base:any={schemaVersion:3,runId:'r',repoId:'x',createdAt:'2026-01-01T00:00:00.000Z',deadline:'2026-01-01T00:10:00.000Z',status:'finished',completeness:'complete',policy:{mode:'daily',scope:'all',diff:false,base:'main',offline:true,budgetSeconds:600,maxWorkers:3,maxRepairs:3},source:{root:'/x',snapshotHash:'s',originalHash:'o'},application:{actors:[],assets:[],entrypoints:[],tenantBoundaries:[],sensitiveOperations:[],invariants:[]},coverage:[{domain:'auth',scope:'all',status:'assessed',method:'trace',gaps:[],exclusions:[],evidence:['routes']}],findings:[],gaps:[],events:[{at:'2026-01-01T00:01:05.500Z',kind:'terminal',message:'finished'}]};const markdown=renderReport({...base,modelUsage:{source:'host api',tokens:1234,cost:0.25}});expect(markdown).toContain('Timing: started 2026-01-01T00:00:00.000Z; deadline 2026-01-01T00:10:00.000Z; terminal 2026-01-01T00:01:05.500Z; elapsed 65500 ms.');expect(markdown).toContain('Model usage: 1234 host-reported tokens from host api; host-reported cost 0.25.');expect(renderReport(base)).not.toContain('Model usage:');}); - test('readable reports include substantiating detail and explicit proof assurances',()=>{const supported=validateFinding({...finding,title:'Cross tenant\n# FORGED SECTION',scenario:'Caller sends `id`\n- forged bullet'});supported.repair='tested';supported.verificationId='a'.repeat(32);supported.verificationAssurance={assertions:'authenticated_out_of_process',testCompletion:'authenticated_out_of_process',review:'self_attested'};const report:any={schemaVersion:3,runId:'run',repoId:'repo',createdAt:'2026-01-01',deadline:'2026-01-01',status:'finished',completeness:'complete',policy:{mode:'daily',scope:'auth',diff:false,base:'main',offline:true,budgetSeconds:600,maxWorkers:3,maxRepairs:3},source:{root:'/x',snapshotHash:'s',originalHash:'o'},application:{actors:['tenant user'],assets:['records'],entrypoints:['GET /users/:id'],tenantBoundaries:['tenant_id'],sensitiveOperations:['read'],invariants:['tenant isolation']},coverage:[{domain:'auth',scope:'all',status:'assessed',method:'caller trace',gaps:[],exclusions:[],evidence:['src/users.ts:4']}],findings:[supported],gaps:[],events:[]},markdown=renderReport(report);expect(markdown).toContain('Application model:');expect(markdown).toContain('Attacker scenario:');expect(markdown).toContain('Supporting references:');expect(markdown).toContain('Repair recommendation:');expect(markdown).toContain(`Bundle: bundles/${'a'.repeat(32)}.json. Assertion assurance: authenticated\\_out\\_of\\_process. Test completion assurance: authenticated\\_out\\_of\\_process. Review assurance: self\\_attested.`);expect(markdown).not.toContain('\n# FORGED SECTION');expect(markdown).not.toContain('\n- forged bullet');}); - test('readable reports reject and strip bidirectional or terminal control forgery',()=>{expect(()=>validateFinding({...finding,title:'Safe \u202e [HIGH forged]'})).toThrow('unsafe control characters');const supported=validateFinding(finding);supported.title='Safe \u202e [HIGH forged] \u0085';const report:any={schemaVersion:3,runId:'run',repoId:'repo',createdAt:'2026-01-01',deadline:'2026-01-01',status:'finished',completeness:'complete',policy:{mode:'daily',scope:'auth',diff:false,base:'main',offline:true,budgetSeconds:600,maxWorkers:3,maxRepairs:3},source:{root:'/x',snapshotHash:'s',originalHash:'o'},application:{actors:[],assets:[],entrypoints:[],tenantBoundaries:[],sensitiveOperations:[],invariants:[]},coverage:[{domain:'auth',scope:'all',status:'assessed',method:'trace',gaps:[],exclusions:[],evidence:['route']}],findings:[supported],gaps:[],events:[]},markdown=renderReport(report);expect(markdown).not.toMatch(/[\u202e\u0085]/u);expect(markdown).toContain('Safe \\[HIGH forged\\]');}); - test('optional scanner failure is operational evidence, not a second assessment domain',()=>{const report:any={coverage:[{domain:'dependencies',scope:'all',status:'assessed',method:'manual reachability analysis',gaps:[],exclusions:[],evidence:['lock and callers']},{domain:'scanner:osv',scope:'all',status:'not_assessed',method:'qualified scanner',gaps:['catalog unavailable'],exclusions:[],evidence:[],tool:{name:'osv',version:'unavailable',freshness:'unknown',outcome:'not_assessed'}}],gaps:[]};expect(completeness(report)).toBe('complete');}); - test('v2 VERIFIED imports as readable legacy evidence, never proof',()=>{const original={status:'VERIFIED',title:'old',fingerprint:'legacy-fingerprint',location:{path:'src/old.ts',line:7},impact:'historical impact',recommendation:'historical repair',repair:'VERIFIED'};const v=importLegacy({schemaVersion:2,findings:[original]});expect(v.readOnly).toBe(true);expect(v.findings[0]).toMatchObject({evidence:'legacy_review',reproduction:'not_attempted',repair:'not_attempted',closure:'unknown',legacy:original});}); - test('legacy reports reject display controls in preserved values and property names',()=>{for(const finding of [{status:'OPEN',title:'old',nested:{value:'line\u2028forgery'}},{status:'OPEN',title:'old',nested:{['severity\u202eHIGH']:'forged'}}])expect(()=>importLegacy({schemaVersion:2,findings:[finding]})).toThrow(/unsafe (?:control characters|property)/);}); - test('Docker admission is machine-wide and supervised slots survive owner deadlines until cleanup',()=>{const endpoint=`unix:///tmp/cso-${process.pid}-${Date.now()}.sock`,old=process.env.GSTACK_HOME,a=admit(endpoint,'a',Date.now()-1);markSupervised(a);process.env.GSTACK_HOME=tmp();const b=admit(endpoint,'b',Date.now()+60_000);try{expect(()=>admit(endpoint,'c',Date.now()+60_000)).toThrow('Two reproduction groups');}finally{release(a);release(b);if(old===undefined)delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME=old;}}); - test('wallet-shaped random lease capabilities remain byte-identical protocol metadata',()=>{const endpoint=`unix:///tmp/cso-wallet-token-${process.pid}-${Date.now()}.sock`,token='1abcdefabcdefabcdefabcdefabcdefa',random=crypto.randomBytes,patched=spyOn(crypto,'randomBytes').mockImplementation(((size:number)=>size===16?Buffer.from(token,'hex'):random(size)) as typeof crypto.randomBytes);let lease:ReturnType|undefined;try{lease=admit(endpoint,'wallet-token',Date.now()+60_000);expect(lease.token).toBe(token);expect(JSON.parse(fs.readFileSync(path.join(lease.path,'lease.json'),'utf8')).token).toBe(token);expect(fs.readFileSync(path.join(lease.path,'lease.token'),'utf8').trim()).toBe(token);markSupervised(lease);expect(JSON.parse(fs.readFileSync(path.join(lease.path,'lease.json'),'utf8')).token).toBe(token);}finally{patched.mockRestore();if(lease)release(lease);}}); - test('a paused initializer cannot have its incomplete slot reclaimed or overwritten',()=>{ - const endpoint=`unix:///tmp/cso-initializer-${process.pid}-${Date.now()}.sock`,pool=path.join(machinePoolRoot(),sha256(endpoint).slice(0,24)),slot0=path.join(pool,'slot-0'),originalMkdir=fs.mkdirSync; - let paused=false,contender:ReturnType|undefined; - const mkdir=spyOn(fs,'mkdirSync').mockImplementation(((target:fs.PathLike,options?:fs.MakeDirectoryOptions & {recursive?:false})=>{ - const result=originalMkdir(target,options as any); - if(!paused&&String(target)===slot0){paused=true;const old=new Date(Date.now()-60_000);fs.utimesSync(slot0,old,old);contender=admit(endpoint,'contender',Date.now()+60_000);} - return result; - }) as typeof fs.mkdirSync); - let initializer:ReturnType|undefined;try{initializer=admit(endpoint,'initializer',Date.now()+60_000);}finally{mkdir.mockRestore();} - expect(paused).toBe(true);expect(initializer!.slot).toBe(0);expect(contender!.slot).toBe(1);expect(initializer!.token).not.toBe(contender!.token); - for(const lease of [initializer!,contender!]){expect(JSON.parse(fs.readFileSync(path.join(lease.path,'lease.json'),'utf8')).token).toBe(lease.token);expect(fs.readFileSync(path.join(lease.path,'lease.token'),'utf8').trim()).toBe(lease.token);expect(fs.readdirSync(path.join(pool,`.slot-${lease.slot}.control`))).toEqual([]);} - try{expect(()=>admit(endpoint,'third',Date.now()+60_000)).toThrow('Two reproduction groups');}finally{release(initializer!);release(contender!);} - }); - test('a fully published recovery claim remains owned while its initializer is paused',()=>{ - const endpoint=`unix:///tmp/cso-claim-publish-${process.pid}-${Date.now()}.sock`,pool=path.join(machinePoolRoot(),sha256(endpoint).slice(0,24)),claim=path.join(pool,'.slot-0.control','.recovery'),originalMkdir=fs.mkdirSync,originalUnlink=fs.unlinkSync; - let paused=false,contender:ReturnType|undefined; - const contend=()=>{paused=true;const old=new Date(Date.now()-60_000);fs.utimesSync(claim,old,old);contender=admit(endpoint,'claim-contender',Date.now()+60_000);}; - // The mkdir hook reproduces the former directory claim's empty publication - // window. The unlink hook pauses the replacement protocol immediately after - // its complete temp inode has been atomically published. - const mkdir=spyOn(fs,'mkdirSync').mockImplementation(((target:fs.PathLike,options?:fs.MakeDirectoryOptions & {recursive?:false})=>{const result=originalMkdir(target,options as any);if(!paused&&String(target)===claim)contend();return result;}) as typeof fs.mkdirSync); - const unlink=spyOn(fs,'unlinkSync').mockImplementation(((target:fs.PathLike)=>{const result=originalUnlink(target);if(!paused&&String(target).startsWith(`${claim}.tmp.`))contend();return result;}) as typeof fs.unlinkSync); - let initializer:ReturnType|undefined;try{initializer=admit(endpoint,'claim-initializer',Date.now()+60_000);}finally{unlink.mockRestore();mkdir.mockRestore();} - expect(paused).toBe(true);expect(initializer!.slot).toBe(0);expect(contender!.slot).toBe(1);try{release(initializer!);release(contender!);}catch(error){throw error;} - }); - test('a crashed initializer claim and partial slot are recovered exactly',()=>{ - const endpoint=`unix:///tmp/cso-initializer-crash-${process.pid}-${Date.now()}.sock`,pool=path.join(machinePoolRoot(),sha256(endpoint).slice(0,24)),control=path.join(pool,'.slot-0.control'),claim=path.join(control,'.recovery'),slot=path.join(pool,'slot-0'); - fs.mkdirSync(pool,{mode:0o700});fs.mkdirSync(control,{mode:0o700});fs.writeFileSync(claim,JSON.stringify({pid:2147483647,processIdentity:'linux:1',token:'7'.repeat(32),createdAt:1}),{mode:0o600});fs.mkdirSync(slot,{mode:0o700});const old=new Date(Date.now()-60_000);fs.utimesSync(slot,old,old); - const recovered=admit(endpoint,'recovered',Date.now()+60_000);try{expect(recovered.slot).toBe(0);expect(JSON.parse(fs.readFileSync(path.join(slot,'lease.json'),'utf8')).token).toBe(recovered.token);expect(fs.readdirSync(control)).toEqual([]);expect(fs.readdirSync(pool).some(name=>name.includes('.stale-'))).toBe(false);}finally{release(recovered);} - }); - test('admission recovers only the exact no-replace claim link of a dead publisher',()=>{ - const endpoint=`unix:///tmp/cso-claim-hardlink-${process.pid}-${Date.now()}.sock`,pool=path.join(machinePoolRoot(),sha256(endpoint).slice(0,24)),control=path.join(pool,'.slot-0.control'),claim=path.join(control,'.recovery'),temporary=`${claim}.tmp.2147483647.deadbeef`; - fs.mkdirSync(pool,{mode:0o700});fs.mkdirSync(control,{mode:0o700});fs.writeFileSync(claim,JSON.stringify({pid:2147483647,processIdentity:'linux:1',token:'6'.repeat(32),createdAt:1})+'\n',{mode:0o600});fs.linkSync(claim,temporary); - const recovered=admit(endpoint,'hardlink-recovered',Date.now()+60_000);try{expect(recovered.slot).toBe(0);expect(fs.readdirSync(control)).toEqual([]);}finally{release(recovered);fs.rmSync(pool,{recursive:true,force:true});} - }); - test('admission fails closed when a claim temp names a different publisher',()=>{ - const endpoint=`unix:///tmp/cso-claim-mismatch-${process.pid}-${Date.now()}.sock`,pool=path.join(machinePoolRoot(),sha256(endpoint).slice(0,24)),control=path.join(pool,'.slot-0.control'),claim=path.join(control,'.recovery'),temporary=`${claim}.tmp.2147483646.cafebabe`; - fs.mkdirSync(pool,{mode:0o700});fs.mkdirSync(control,{mode:0o700});fs.writeFileSync(claim,JSON.stringify({pid:2147483647,processIdentity:'linux:1',token:'5'.repeat(32),createdAt:1})+'\n',{mode:0o600});fs.linkSync(claim,temporary); - try{expect(()=>admit(endpoint,'must-not-admit',Date.now()+60_000)).toThrow('invalid');expect(fs.statSync(claim).nlink).toBe(2);}finally{fs.rmSync(pool,{recursive:true,force:true});} - }); - test('admission recovery never steals a replacement lease and exact release rejects changed ownership',()=>{ - const endpoint=`unix:///tmp/cso-recovery-${process.pid}-${Date.now()}.sock`,pool=path.join(machinePoolRoot(),sha256(endpoint).slice(0,24));fs.mkdirSync(pool,{mode:0o700}); - const lease=(slot:number,runId:string,token:string,ownerPid:number,supervised:boolean)=>({endpoint,slot,path:path.join(pool,`slot-${slot}`),runId,ownerPid,expiresAt:Date.now()+60_000,token,supervised}); - const publish=(value:ReturnType)=>{fs.mkdirSync(value.path,{mode:0o700});fs.writeFileSync(path.join(value.path,'lease.json'),JSON.stringify(value),{mode:0o600});fs.writeFileSync(path.join(value.path,'lease.token'),value.token+'\n',{mode:0o600});}; - const stale=lease(0,'stale','8'.repeat(32),2147483647,false),replacement=lease(0,'replacement','9'.repeat(32),process.pid,true),other=lease(1,'other','a'.repeat(32),process.pid,true);publish(stale);publish(other); - const originalLink=fs.linkSync,originalRename=fs.renameSync;let barrier=false,thirdCode='',canonicalMoves=0,displaced=''; - const rename=spyOn(fs,'renameSync').mockImplementation(((from:fs.PathLike,to:fs.PathLike)=>{if(String(from)===stale.path)canonicalMoves++;return originalRename(from,to);}) as typeof fs.renameSync); - const link=spyOn(fs,'linkSync').mockImplementation(((from:fs.PathLike,to:fs.PathLike)=>{const result=originalLink(from,to);if(!barrier&&String(to)===path.join(stale.path,'.recovery')){barrier=true;displaced=`${stale.path}.displaced`;originalRename(stale.path,displaced);publish(replacement);fs.writeFileSync(String(from),'publisher-temp-placeholder',{mode:0o600,flag:'wx'});try{admit(endpoint,'third',Date.now()+60_000);}catch(error:any){thirdCode=error?.code??'';}}return result;}) as typeof fs.linkSync); - try{expect(()=>admit(endpoint,'recoverer',Date.now()+60_000)).toThrow();}finally{link.mockRestore();rename.mockRestore();} - expect(barrier).toBe(true);expect(thirdCode).toBe('INSUFFICIENT_CAPACITY');expect(canonicalMoves).toBe(0);expect(JSON.parse(fs.readFileSync(path.join(replacement.path,'lease.json'),'utf8')).token).toBe(replacement.token);expect(fs.existsSync(path.join(replacement.path,'.recovery'))).toBe(false); - fs.writeFileSync(path.join(replacement.path,'lease.token'),'b'.repeat(32)+'\n',{mode:0o600});expect(()=>release(replacement)).toThrow('ownership changed');expect(fs.existsSync(replacement.path)).toBe(true);fs.writeFileSync(path.join(replacement.path,'lease.token'),replacement.token+'\n',{mode:0o600});release(replacement);release(other);if(displaced)fs.rmSync(displaced,{recursive:true,force:true}); - }); -}); - -describe('tested repair certificate gate',()=>{ - test('canonical plans bind test infrastructure and run every Rails suite',()=>{ - const root=tmp(); - fs.writeFileSync(path.join(root,'package.json'),JSON.stringify({scripts:{test:'jest'}})); - fs.mkdirSync(path.join(root,'tests','fixtures'),{recursive:true}); - fs.writeFileSync(path.join(root,'tests','app.test.js'),'test("ok",()=>{})'); - fs.writeFileSync(path.join(root,'tests','fixtures','account.json'),'{}'); - fs.writeFileSync(path.join(root,'jest.config.js'),'module.exports={}'); - fs.writeFileSync(path.join(root,'app.js'),'server.listen(process.env.PORT)'); - const node=canonicalTestPlan(root,'node'); - expect(node.files).toEqual(['jest.config.js','tests/app.test.js','tests/fixtures/account.json']); - expect(node.commands).toEqual([{executable:'/work/node_modules/.bin/jest',args:['--runTestsByPath','--passWithNoTests=false','--json','./tests/app.test.js']}]); - expect(canonicalStartPlan(root,'node',3456).command).toEqual({executable:'/usr/local/bin/node',args:['app.js']}); - expect(()=>assertCanonicalStartPlan({...request('vulnerable\n','fixed\n'),start:{executable:'/usr/local/bin/python',args:['-m','http.server']}} as any,root,'node')).toThrow('helper-derived'); - - const bunRoot=tmp(); - fs.writeFileSync(path.join(bunRoot,'package.json'),JSON.stringify({scripts:{start:'bun app.js',test:'bun test'}})); - fs.writeFileSync(path.join(bunRoot,'app.js'),'Bun.serve({fetch(){return new Response("ok")}})'); - fs.writeFileSync(path.join(bunRoot,'app.test.js'),'import {test} from "bun:test"; test("ok",()=>{});'); - const bunPolicy=['--no-install','--config=/opt/cso/no-auto-install.toml']; - expect(canonicalTestPlan(bunRoot,'bun').commands).toEqual([{executable:'/usr/local/bin/bun',args:[...bunPolicy,'test','./app.test.js']}]); - expect(canonicalStartPlan(bunRoot,'bun',3456).command).toEqual({executable:'/usr/local/bin/bun',args:[...bunPolicy,'app.js']}); - - const python=tmp();fs.mkdirSync(path.join(python,'tests')); - fs.writeFileSync(path.join(python,'conftest.py'),'import pytest\n'); - fs.writeFileSync(path.join(python,'tests','test_app.py'),'def test_ok():\n assert True\n'); - const pythonArgs=canonicalTestPlan(python,'python').commands[0].args; - expect(pythonArgs.slice(0,3)).toEqual(['-I','-S','-c']);expect(pythonArgs[3]).toContain('import pytest;sys.path.insert');expect(pythonArgs.slice(4)).toEqual(['-q','--color=no','--','./tests/test_app.py']); - - const rails=tmp();fs.mkdirSync(path.join(rails,'spec','support'),{recursive:true});fs.mkdirSync(path.join(rails,'test','fixtures'),{recursive:true}); - fs.writeFileSync(path.join(rails,'spec','app_spec.rb'),'RSpec.describe("app") {}'); - fs.writeFileSync(path.join(rails,'spec','support','auth.rb'),'module Auth; end'); - fs.writeFileSync(path.join(rails,'test','app_test.rb'),'class AppTest < ActiveSupport::TestCase; end'); - fs.writeFileSync(path.join(rails,'test','fixtures','users.yml'),'one: {}'); - const plan=canonicalTestPlan(rails,'rails'); - expect(plan.commands.map(command=>command.args)).toEqual([['exec','rspec','--format','json','--','./spec/app_spec.rb'],['exec','rails','test','--no-color','./test/app_test.rb']]); - expect(plan.files).toContain('spec/support/auth.rb');expect(plan.files).toContain('test/fixtures/users.yml'); - }); - test('ambiguous Python discovery cannot certify an empty unittest run',()=>{const root=tmp();fs.mkdirSync(path.join(root,'tests'));fs.writeFileSync(path.join(root,'tests','test_app.py'),'value = 1\n');expect(()=>canonicalTestPlan(root,'python')).toThrow('ambiguous');}); - test('self-reported in-process test success is inconclusive and cannot mint a repair bundle',()=>{const root=tmp(),before=path.join(root,'before'),after=path.join(root,'after');fs.mkdirSync(before);fs.writeFileSync(path.join(before,'app.js'),'vulnerable\n');fs.writeFileSync(path.join(before,'test.js'),'pass\n');const raw:any=request('vulnerable\n','fixed\n');raw.findingId='1abcdefabcdefabcdefabcdefabcdefa';raw.review.reviewedPatchHash=patchHash(raw);const req=validateVerificationRequest(raw);preparePatchedSource(before,after,req);const params:any={runId:'run',manifest:{version:3,createdAt:'',expiresAt:'',root:'/x',headCommit:'a'.repeat(40),originalHash:'o',executionHash:tree(before),entries:[{path:'app.js',originalHash:sha256('vulnerable\n'),executionHash:sha256('vulnerable\n'),bytes:11,mode:0o600}]},request:req,runtime:{id:'node',image:'r@sha256:'+'a'.repeat(64),platform:'linux/amd64'},verifier:{image:'r@sha256:'+'a'.repeat(64)},before:{booted:true,legitimate:true,security:'intended_failure',existingTests:true,output:'forged runner success',inputHash:''},after:{booted:true,legitimate:true,security:'pass',existingTests:true,output:'forged runner success',inputHash:''},beforeRoot:before,afterRoot:after,policyHash:'p',archives:[],testToolchain:'runtime'};const certified=certify(params);expect(certified.manifest).toMatchObject({findingId:raw.findingId,result:'inconclusive',reviewAssurance:'self_attested',testToolchain:'runtime',testCompletionAssurance:'self_reported'});expect(certified.bundle).toBeUndefined();params.before.existingTests=false;let failed=certify(params);expect(failed.manifest.result).toBe('failed');expect(failed.bundle).toBeUndefined();params.before.existingTests=true;params.after.existingTests=false;failed=certify(params);expect(failed.manifest.result).toBe('failed');expect(failed.bundle).toBeUndefined();params.after.existingTests=true;params.request.review.boundaryMocks=true;failed=certify(params);expect(failed.manifest.result).toBe('failed');expect(failed.bundle).toBeUndefined();}); - test('changed oracle cannot be represented because one request binds before and after',()=>{const raw:any=request('vulnerable\n','fixed\n');raw.security.vulnerable=undefined;expect(()=>validateVerificationRequest(raw)).toThrow();}); - test('verification review booleans and schema fields are explicit',()=>{const missing:any=request('vulnerable\n','fixed\n');missing.review.reviewedPatchHash='pending';delete missing.review.boundaryMocks;expect(()=>validateVerificationRequest(missing)).toThrow('must be a boolean');const typo:any=request('vulnerable\n','fixed\n');typo.review.reviewedPatchHash='pending';typo.review.boundaryMock=false;expect(()=>validateVerificationRequest(typo)).toThrow('Unexpected review field');const extra:any=request('vulnerable\n','fixed\n');extra.review.reviewedPatchHash='pending';extra.security.expected.untrusted='yes';expect(()=>validateVerificationRequest(extra)).toThrow('Unexpected security.expected field');}); - test('a generic successful command cannot impersonate relevant existing tests',()=>{const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash='pending';raw.existingTests=[{executable:'/bin/true',args:['README.md']}];raw.testFiles=['README.md'];expect(()=>validateVerificationRequest(raw)).toThrow('Generic success');}); - test('canonical package tests execute the exact direct runner and reject wrappers or lifecycle mutation',()=>{ - const node=tmp();fs.writeFileSync(path.join(node,'package.json'),JSON.stringify({scripts:{test:'node --test'}}));fs.writeFileSync(path.join(node,'app.test.js'),'test("ok",()=>{})');expect(canonicalTestPlan(node,'node').commands).toEqual([{executable:'/usr/local/bin/node',args:['--test','--test-reporter=tap','./app.test.js']}]); - const hooked=tmp();fs.writeFileSync(path.join(hooked,'package.json'),JSON.stringify({scripts:{pretest:'rm -rf tests',test:'node --test'}}));fs.writeFileSync(path.join(hooked,'app.test.js'),'test("must run",()=>{})');expect(()=>canonicalTestPlan(hooked,'node')).toThrow('lifecycle hooks'); - const bunJest=tmp();fs.writeFileSync(path.join(bunJest,'package.json'),JSON.stringify({scripts:{test:'jest'}}));fs.writeFileSync(path.join(bunJest,'app.test.js'),'test("must run",()=>{})');expect(canonicalTestPlan(bunJest,'bun').commands).toEqual([{executable:'/work/node_modules/.bin/jest',args:['--runTestsByPath','--passWithNoTests=false','--json','./app.test.js']}]); - const bunHooked=tmp();fs.writeFileSync(path.join(bunHooked,'package.json'),JSON.stringify({scripts:{test:'bun test',posttest:'rm -rf tests'}}));fs.writeFileSync(path.join(bunHooked,'app.test.js'),'import {test} from "bun:test"; test("must run",()=>{});');expect(()=>canonicalTestPlan(bunHooked,'bun')).toThrow('lifecycle hooks'); - const mismatched=tmp();fs.writeFileSync(path.join(mismatched,'package.json'),JSON.stringify({scripts:{test:'bun test'}}));fs.writeFileSync(path.join(mismatched,'app.test.js'),'test("must run",()=>{})');expect(()=>canonicalTestPlan(mismatched,'node')).toThrow('cannot depend on the Bun test runtime'); - for(const script of ['node tools/run-tests.js','node --test --test-name-pattern=NO_MATCH','tap']){const root=tmp();fs.writeFileSync(path.join(root,'package.json'),JSON.stringify({scripts:{test:script}}));fs.writeFileSync(path.join(root,'app.test.js'),'test("fails",()=>{throw Error("must run")})');expect(()=>canonicalTestPlan(root,'node')).toThrow('recognized direct standard runner');} - }); - test('canonical starts bypass package lifecycles',()=>{ - const root=tmp();fs.writeFileSync(path.join(root,'package.json'),JSON.stringify({scripts:{start:'node app.js',test:'node --test'}}));fs.writeFileSync(path.join(root,'app.js'),'server.listen(3456)');fs.writeFileSync(path.join(root,'app.test.js'),'test("ok",()=>{})');expect(canonicalStartPlan(root,'node',3456).command).toEqual({executable:'/usr/local/bin/node',args:['app.js']}); - fs.writeFileSync(path.join(root,'package.json'),JSON.stringify({scripts:{prestart:'node rewrite-app.js',start:'node app.js',test:'node --test'}}));expect(()=>canonicalStartPlan(root,'node',3456)).toThrow('lifecycle hooks'); - }); - test('every canonical runner requires unredacted positive passing-test count evidence',()=>{ - const pytestRoot=tmp();fs.mkdirSync(path.join(pytestRoot,'tests'));fs.writeFileSync(path.join(pytestRoot,'tests','test_app.py'),'def test_ok():\n assert True\n');const pytest=canonicalTestPlan(pytestRoot,'python').commands[0]; - const unittestRoot=tmp();fs.mkdirSync(path.join(unittestRoot,'tests'));fs.writeFileSync(path.join(unittestRoot,'tests','test_app.py'),'import unittest\nclass T(unittest.TestCase):\n def test_ok(self): pass\n');const unittest=canonicalTestPlan(unittestRoot,'python').commands[0]; - const cases:Array<{name:string;command:any;positive:string;multiple:string;zero:string}>=[ - {name:'node',command:{executable:'/usr/local/bin/node',args:['--test','--test-reporter=tap','./app.test.js']},positive:'TAP version 13\n# Subtest: named assertion\nok 1 - named assertion\n1..1\n# tests 1\n# pass 1\n# fail 0\n# cancelled 0\n',multiple:'TAP version 13\n# Subtest: first assertion\nok 1 - first assertion\n# Subtest: second assertion\nok 2 - second assertion\n1..2\n# tests 2\n# pass 2\n# fail 0\n# cancelled 0\n',zero:'TAP version 13\n# Subtest: /work/app.test.js\nok 1 - /work/app.test.js\n1..1\n# tests 1\n# pass 1\n# fail 0\n# cancelled 0\n'}, - {name:'bun',command:{executable:'/usr/local/bin/bun',args:['--no-install','test','./app.test.js']},positive:' 1 pass\n 0 fail\nRan 1 test across 1 file.\n',multiple:' 2 pass\n 0 fail\nRan 2 tests across 1 file.\n',zero:' 0 pass\n 0 fail\n 1 skip\nRan 1 test across 1 file.\n'}, - {name:'jest',command:{executable:'/work/node_modules/.bin/jest',args:['--runTestsByPath','--passWithNoTests=false','--json','./app.test.js']},positive:JSON.stringify({success:true,numPassedTests:1,numFailedTests:0,numRuntimeErrorTestSuites:0,numTotalTests:1}),multiple:JSON.stringify({success:true,numPassedTests:2,numFailedTests:0,numRuntimeErrorTestSuites:0,numTotalTests:2}),zero:JSON.stringify({success:true,numPassedTests:0,numFailedTests:0,numRuntimeErrorTestSuites:0,numTotalTests:1})}, - {name:'vitest',command:{executable:'/work/node_modules/.bin/vitest',args:['run','--passWithNoTests=false','--reporter=verbose','./app.test.js']},positive:' Tests 1 passed (1)\n',multiple:' Tests 2 passed (2)\n',zero:' Tests 1 skipped (1)\n'}, - {name:'mocha',command:{executable:'/work/node_modules/.bin/mocha',args:['--fail-zero','--no-dry-run','--forbid-only','--reporter','json','./test/app.test.js']},positive:JSON.stringify({stats:{tests:1,passes:1,pending:0,failures:0}}),multiple:JSON.stringify({stats:{tests:2,passes:2,pending:0,failures:0}}),zero:JSON.stringify({stats:{tests:1,passes:0,pending:1,failures:0}})}, - {name:'ava',command:{executable:'/work/node_modules/.bin/ava',args:['--tap','./test/app.test.js']},positive:'TAP version 13\n# tests 1\n# pass 1\n# fail 0\n',multiple:'TAP version 13\n# tests 2\n# pass 2\n# fail 0\n',zero:'TAP version 13\n# tests 1\n# pass 0\n# fail 0\n'}, - {name:'pytest',command:pytest,positive:'1 passed in 0.01s\n',multiple:'2 passed in 0.01s\n',zero:'1 skipped in 0.01s\n'}, - {name:'unittest',command:unittest,positive:'Ran 1 test in 0.001s\n\nOK\n',multiple:'Ran 2 tests in 0.001s\n\nOK\n',zero:'Ran 1 test in 0.001s\n\nOK (skipped=1)\n'}, - {name:'rspec',command:{executable:'/usr/local/bin/bundle',args:['exec','rspec','--format','json','--','./spec/app_spec.rb']},positive:JSON.stringify({summary:{example_count:1,pending_count:0,failure_count:0,errors_outside_of_examples_count:0}}),multiple:JSON.stringify({summary:{example_count:2,pending_count:0,failure_count:0,errors_outside_of_examples_count:0}}),zero:JSON.stringify({summary:{example_count:1,pending_count:1,failure_count:0,errors_outside_of_examples_count:0}})}, - {name:'rails',command:{executable:'/usr/local/bin/bundle',args:['exec','rails','test','--no-color','./test/app_test.rb']},positive:'1 runs, 0 assertions, 0 failures, 0 errors, 0 skips\n',multiple:'2 runs, 0 assertions, 0 failures, 0 errors, 0 skips\n',zero:'1 runs, 0 assertions, 0 failures, 0 errors, 1 skips\n'}, - ]; - for(const item of cases){expect(testExecutionPassed(item.command,0,item.positive),`${item.name} positive output`).toBe(true);expect(testExecutionPassed(item.command,0,item.positive,2),`${item.name} must reject a result below the helper-derived floor`).toBe(false);expect(testExecutionPassed(item.command,0,item.multiple,2),`${item.name} must accept a result meeting the helper-derived floor`).toBe(true);for(const output of [item.zero,'','custom reporter output','[sensitive process output redacted]'])expect(testExecutionPassed(item.command,0,output),`${item.name} must reject missing/zero/redacted counts`).toBe(false);expect(testExecutionPassed(item.command,1,item.positive),`${item.name} nonzero exit`).toBe(false);} - const node=cases[0];expect(testExecutionPassed(node.command,0,node.positive,2),'Node must meet the statically derived registration floor').toBe(false);expect(testExecutionPassed(node.command,0,`${node.positive}# Subtest: /work/app.test.js\nok 2 - /work/app.test.js\n`),'Node path-wrapper success remains evidence of an early exit even when another named test passed').toBe(false); - }); - test('a repair cannot turn existing tests into skips and retain a runtime-tested label',()=>{ - const root=tmp(),before=path.join(root,'before'),after=path.join(root,'after');fs.mkdirSync(before);fs.writeFileSync(path.join(before,'app.js'),'vulnerable\n');fs.writeFileSync(path.join(before,'test.js'),'two registered tests\n');const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash=patchHash(raw);const req=validateVerificationRequest(raw);preparePatchedSource(before,after,req); - const params:any={runId:'run',manifest:{originalHash:'d'.repeat(64),executionHash:treeHash(before),entries:[]},request:req,runtime:{id:'node',image:'runtime@sha256:'+'a'.repeat(64),platform:'linux/amd64'},verifier:{image:'runtime@sha256:'+'a'.repeat(64)},before:{booted:true,legitimate:true,security:'intended_failure',existingTests:true,output:'before',inputHash:''},after:{booted:true,legitimate:true,security:'pass',existingTests:true,output:'after',inputHash:''},beforeRoot:before,afterRoot:after,policyHash:'c'.repeat(64),auditPolicyHash:'e'.repeat(64),archives:[],testToolchain:'runtime'},unsigned=certify(params),witness=authenticatedBundleFixture(unsigned,params,{before:{executedTests:2,passingTests:2},after:{executedTests:2,passingTests:1}}).witness; - expect(()=>certify({...params,witness})).toThrow('existing-test execution count or outcome'); - }); - test('a witness whose external assertions failed is an assertion failure, and a mismatched observation stays incompatible input',()=>{ - const root=tmp(),before=path.join(root,'before'),after=path.join(root,'after');fs.mkdirSync(before);fs.writeFileSync(path.join(before,'app.js'),'vulnerable\n');fs.writeFileSync(path.join(before,'test.js'),'one registered test\n');const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash=patchHash(raw);const req=validateVerificationRequest(raw);preparePatchedSource(before,after,req); - const params:any={runId:'run',manifest:{originalHash:'d'.repeat(64),executionHash:treeHash(before),entries:[]},request:req,runtime:{id:'node',image:'runtime@sha256:'+'a'.repeat(64),platform:'linux/amd64'},verifier:{image:'runtime@sha256:'+'a'.repeat(64)},before:{booted:true,legitimate:true,security:'intended_failure',existingTests:true,output:'before',inputHash:''},after:{booted:true,legitimate:true,security:'inconclusive',existingTests:true,output:'after',inputHash:''},beforeRoot:before,afterRoot:after,policyHash:'c'.repeat(64),auditPolicyHash:'e'.repeat(64),archives:[],testToolchain:'runtime'},unsigned=certify(params); - const failed=authenticatedBundleFixture(unsigned,params,undefined,{before:true,after:false}).witness; - expect(()=>certify({...params,witness:failed})).toThrow(expect.objectContaining({code:'ASSERTION_FAILED',message:'External assertions failed in the after phase: booted true, legitimate true, security inconclusive'})); - const mismatched=authenticatedBundleFixture({...unsigned,manifest:{...unsigned.manifest,after:{...unsigned.manifest.after,output:'a different observation'}}},params,undefined,{before:true,after:false}).witness; - expect(()=>certify({...params,witness:mismatched})).toThrow(expect.objectContaining({code:'INCOMPATIBLE_INPUT'})); - }); - test('canonical Python starts use direct prepared launchers and reject root framework shadows',()=>{ - const pin=(name:string)=>`${name}==1.0.0 --hash=sha256:${'a'.repeat(64)}\n`; - const flask=tmp();fs.writeFileSync(path.join(flask,'requirements.txt'),pin('Flask'));fs.writeFileSync(path.join(flask,'app.py'),'from flask import Flask\napp = Flask(__name__)\n');const flaskCommand=canonicalStartPlan(flask,'python',3456).command;expect(flaskCommand.executable).toBe('/work/.venv/bin/python');expect(flaskCommand.args.slice(0,3)).toEqual(['-I','-S','-c']);expect(flaskCommand.args[3]).toContain('from flask.cli import main');expect(flaskCommand.args.slice(4)).toEqual(['--app','app:app','run','--host','127.0.0.1','--port','3456']);fs.writeFileSync(path.join(flask,'flask.py'),'raise RuntimeError("shadow")\n');expect(()=>canonicalStartPlan(flask,'python',3456)).toThrow('root import shadow'); - const fastapi=tmp();fs.writeFileSync(path.join(fastapi,'requirements.txt'),pin('fastapi')+pin('uvicorn'));fs.writeFileSync(path.join(fastapi,'main.py'),'from fastapi import FastAPI\napp = FastAPI()\n');const fastapiCommand=canonicalStartPlan(fastapi,'python',3456).command;expect(fastapiCommand.executable).toBe('/work/.venv/bin/python');expect(fastapiCommand.args.slice(0,3)).toEqual(['-I','-S','-c']);expect(fastapiCommand.args[3]).toContain('from uvicorn.main import main');expect(fastapiCommand.args.slice(4)).toEqual(['main:app','--app-dir','/work','--host','127.0.0.1','--port','3456']);fs.mkdirSync(path.join(fastapi,'uvicorn'));expect(()=>canonicalStartPlan(fastapi,'python',3456)).toThrow('root import shadow'); - const django=tmp();fs.writeFileSync(path.join(django,'requirements.txt'),pin('Django'));fs.writeFileSync(path.join(django,'manage.py'),'from django.core.management import execute_from_command_line\n');const djangoCommand=canonicalStartPlan(django,'python',3456).command;expect(djangoCommand.executable).toBe('/work/.venv/bin/python');expect(djangoCommand.args.slice(0,3)).toEqual(['-I','-S','-c']);expect(djangoCommand.args[3]).toContain("runpy.run_path('manage.py'");expect(djangoCommand.args.slice(4)).toEqual(['runserver','127.0.0.1:3456','--noreload']);fs.writeFileSync(path.join(django,'django.py'),'raise RuntimeError("shadow")\n');expect(()=>canonicalStartPlan(django,'python',3456)).toThrow('root import shadow'); - }); - test('empty-dependency Python applications use one isolated conventional entrypoint',()=>{const python=tmp();fs.writeFileSync(path.join(python,'requirements.txt'),'');fs.writeFileSync(path.join(python,'app.py'),"from http.server import HTTPServer,BaseHTTPRequestHandler\nHTTPServer(('127.0.0.1',3456),BaseHTTPRequestHandler).serve_forever()\n");fs.mkdirSync(path.join(python,'tests'));fs.writeFileSync(path.join(python,'tests','test_app.py'),'import unittest\nclass TestApp(unittest.TestCase):\n def test_control(self): self.assertTrue(True)\n');expect(canonicalTestPlan(python,'python').toolchain).toBe('runtime');expect(canonicalStartPlan(python,'python',3456)).toMatchObject({kind:'isolated standard-library Python application',command:{executable:'/usr/local/bin/python',args:['-I','app.py']},entrypointFiles:['app.py']});fs.writeFileSync(path.join(python,'server.py'),'print("ambiguous")\n');expect(()=>canonicalStartPlan(python,'python',3456)).toThrow('ambiguous');}); - test('official Python and RSpec configs are immutable and no-execution controls are rejected',()=>{ - const python=tmp();fs.mkdirSync(path.join(python,'tests'));fs.writeFileSync(path.join(python,'tests','test_app.py'),'def test_ok():\n assert True\n');fs.writeFileSync(path.join(python,'.pytest.ini'),'[pytest]\naddopts = --collect-only\n');expect(()=>canonicalTestPlan(python,'python')).toThrow('collect only'); - fs.writeFileSync(path.join(python,'.pytest.ini'),'[pytest]\n');expect(canonicalTestPlan(python,'python').files).toContain('.pytest.ini');fs.writeFileSync(path.join(python,'.pytest.toml'),'[pytest]\n');expect(canonicalTestPlan(python,'python').files).toContain('.pytest.toml'); - const rails=tmp();fs.mkdirSync(path.join(rails,'spec'));fs.writeFileSync(path.join(rails,'spec','app_spec.rb'),'RSpec.describe("app") { it("works") {} }');fs.writeFileSync(path.join(rails,'.rspec-local'),'--dry-run\n');expect(()=>canonicalTestPlan(rails,'rails')).toThrow('dry-run');fs.writeFileSync(path.join(rails,'.rspec-local'),'--format progress\n');expect(canonicalTestPlan(rails,'rails').files).toContain('.rspec-local'); - }); - test('dependency repairs cannot swap a project-installed test runner',async()=>{ - const runDir=tmp(),snapshot=path.join(runDir,'snapshot');fs.mkdirSync(snapshot);const files:Record={'package.json':JSON.stringify({scripts:{test:'jest'}}),'package-lock.json':'{}\n','app.js':'server.listen(3456)\n','app.test.js':'test("ok",()=>{})\n'};for(const [name,body] of Object.entries(files))fs.writeFileSync(path.join(snapshot,name),body);const plan=canonicalTestPlan(snapshot,'node'),raw:any=request(files['app.js'],'server.listen(3456)\n');raw.start={executable:'/usr/local/bin/node',args:['app.js']};raw.existingTests=plan.commands;raw.testFiles=plan.files;raw.changes=[{path:'package-lock.json',beforeSha256:sha256(files['package-lock.json']),after:'{"changed":true}\n',effect:'dependency'}];raw.review.reviewedPatchHash=patchHash(raw);const entries=Object.entries(files).map(([path,body])=>({path,originalHash:sha256(body),executionHash:sha256(body),bytes:Buffer.byteLength(body),mode:0o600})),manifest:any={version:3,createdAt:'2026-01-01T00:00:00Z',expiresAt:'2026-01-08T00:00:00Z',root:'/repo',headCommit:'a'.repeat(40),originalHash:'b'.repeat(64),executionHash:treeHash(snapshot),entries};let executed=false;await expect(verifyRepair({runId:'run',runDir,manifest,rawRequest:raw,runtime:{id:'node',stack:'node',image:'runtime@sha256:'+'a'.repeat(64),platform:'linux/amd64'} as any,verifier:{id:'node',stack:'node',image:'runtime@sha256:'+'a'.repeat(64),platform:'linux/amd64'} as any,policyHash:'c'.repeat(64),archives:[],executor:{observe:async()=>{executed=true;throw new Error('must not run');}},persist:false})).rejects.toMatchObject({code:'PREREQUISITE'});expect(executed).toBe(false); - }); - test('overlapping security oracles and no-op repairs cannot be certified',()=>{const overlapping:any=request('vulnerable\n','fixed\n');overlapping.review.reviewedPatchHash='pending';overlapping.security.vulnerable={...overlapping.security.expected};expect(()=>validateVerificationRequest(overlapping)).toThrow('mutually exclusive');const noop:any=request('vulnerable\n','vulnerable\n');noop.review.reviewedPatchHash='pending';expect(()=>validateVerificationRequest(noop)).toThrow('material patch');}); - test('a security expectation may list several safe statuses only while it excludes the vulnerable marker',()=>{ - const make=(edit:(raw:any)=>void)=>{const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash='pending';edit(raw);return raw;}; - expect(validateVerificationRequest(make(raw=>{raw.security.expected={status:[403,404],excludes:'tenant-b'};})).security).toMatchObject({expected:{status:[403,404],excludes:'tenant-b'}}); - expect(validateVerificationRequest(make(raw=>{raw.security.expected={status:[200,403],excludes:'tenant-b'};})).security).toMatchObject({expected:{status:[200,403]}}); - expect(()=>validateVerificationRequest(make(raw=>{raw.security.expected={status:[200,403],excludes:'unrelated'};}))).toThrow('mutually exclusive'); - expect(()=>validateVerificationRequest(make(raw=>{raw.security.expected={status:[403,404]};}))).toThrow('must exclude the vulnerable marker'); - for(const status of [[],[403,403],[99,403],[400,401,403,404,405,409,410,422,429]])expect(()=>validateVerificationRequest(make(raw=>{raw.security.expected={status,excludes:'tenant-b'};}))).toThrow('distinct HTTP statuses'); - expect(()=>validateVerificationRequest(make(raw=>{raw.security.vulnerable={status:[200,206],includes:'tenant-b'};}))).toThrow('security.vulnerable.status must be an HTTP status'); - expect(()=>validateVerificationRequest(make(raw=>{raw.legitimate[0].expected={status:[200,403],excludes:'denied'};}))).toThrow('legitimate[0].expected.status must be an HTTP status'); - expect(()=>validateVerificationRequest(make(raw=>{raw.security=[{...raw.security,expected:{status:[403,404],excludes:'tenant-b'}},{...raw.security,name:'second',expected:{status:[403,404]}}];}))).toThrow('security[1].expected with a set of safe statuses'); - }); - test('review is a separate content-bound but explicitly self-attested artifact',()=>{const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash=patchHash(raw);const req=validateVerificationRequest(raw),artifact=makeReviewArtifact('run',req,'producer-session');raw.review.artifactId=artifact.id;const bound=validateVerificationRequest(raw);expect(validateReviewArtifact(artifact,'run',bound)).toMatchObject({producer:'producer-session',assurance:'self_attested'});expect(()=>makeReviewArtifact('run',req,req.review.reviewer)).toThrow('distinct');expect(()=>validateReviewArtifact({...artifact,rationale:'changed'},'run',bound)).toThrow('does not bind');}); - test('executor observations have a strict helper-owned shape',()=>{expect(()=>validateVerificationObservation({booted:true,legitimate:true,security:'pass',existingTests:true,output:'ok',inputHash:'',tested:true})).toThrow('Unexpected');expect(()=>validateVerificationObservation({booted:'yes',legitimate:true,security:'pass',existingTests:true,output:'ok',inputHash:''})).toThrow('booleans');}); - test('secret-bearing fixtures cannot enter a replayable verification bundle',async()=>{const runDir=tmp(),snapshot=path.join(runDir,'snapshot');fs.mkdirSync(snapshot);fs.writeFileSync(path.join(snapshot,'app.js'),'vulnerable\n');const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash=patchHash(raw);raw.fixtures={'secret.txt':CREDENTIAL_CANARY};const manifest:any={entries:[{path:'app.js',transformation:undefined}]};const runtime:any={id:'node',image:'runtime@sha256:'+'a'.repeat(64),platform:'linux/amd64'};expect(verifyRepair({runId:'run',runDir,manifest,rawRequest:raw,runtime,verifier:runtime,policyHash:'c'.repeat(64),archives:[],executor:{observe:async()=>{throw new Error('must not execute');}},persist:false})).rejects.toMatchObject({code:'REDACTION_FAILED'});}); - test('a non-root producer patches a read-only snapshot file and keeps its mode',()=>{const root=tmp(),before=path.join(root,'before'),after=path.join(root,'after');fs.mkdirSync(before);fs.writeFileSync(path.join(before,'app.js'),'vulnerable\n');fs.chmodSync(path.join(before,'app.js'),0o444);const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash=patchHash(raw);preparePatchedSource(before,after,validateVerificationRequest(raw));expect(fs.readFileSync(path.join(after,'app.js'),'utf8')).toBe('fixed\n');expect(fs.statSync(path.join(after,'app.js')).mode&0o777).toBe(0o444);}); - test('declared patches require exact pristine preimages',()=>{const root=tmp(),before=path.join(root,'before'),after=path.join(root,'after');fs.mkdirSync(before);fs.writeFileSync(path.join(before,'app.js'),'changed\n');const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash=patchHash(raw);expect(()=>preparePatchedSource(before,after,validateVerificationRequest(raw))).toThrow('preimage');}); - test('helper derives dependency and configuration patch effects',()=>{expect(fileEffect('package.json')).toBe('dependency');expect(fileEffect('apps/x/pyproject.toml')).toBe('dependency');expect(fileEffect('config/environments/test.rb')).toBe('configuration');const root=tmp(),before=path.join(root,'before'),after=path.join(root,'after');fs.mkdirSync(before);fs.writeFileSync(path.join(before,'package.json'),'{}');const raw:any=request('vulnerable\n','fixed\n');raw.changes=[{path:'package.json',beforeSha256:sha256('{}'),after:'{"dependencies":{}}',effect:'configuration'}];raw.boundaryFiles=['package.json'];raw.review.reviewedPatchHash=patchHash(raw);expect(()=>preparePatchedSource(before,after,validateVerificationRequest(raw))).toThrow('must be declared as dependency');}); - test('verification evidence stays outside both source trees and temporary copies are deleted on errors',async()=>{const runDir=tmp(),snapshot=path.join(runDir,'snapshot');fs.mkdirSync(snapshot);fs.writeFileSync(path.join(snapshot,'app.js'),'vulnerable\n',{mode:0o755});const testBody='test("ok",()=>{})\n';fs.writeFileSync(path.join(snapshot,'app.test.js'),testBody);const packageJson='{"scripts":{"test":"node --test"}}';fs.writeFileSync(path.join(snapshot,'package.json'),packageJson);const raw:any=request('vulnerable\n','fixed\n');raw.findingId='1abcdefabcdefabcdefabcdefabcdefa';raw.existingTests=[{executable:'/usr/local/bin/node',args:['--test','--test-reporter=tap','./app.test.js']}];raw.testFiles=['app.test.js'];raw.changes.push({path:'security/policy.js',beforeSha256:null,after:'export const enforced = true\n',effect:'source'});raw.review.reviewedPatchHash=patchHash(raw);const manifest:any={version:3,createdAt:'2026-01-01T00:00:00Z',expiresAt:'2026-01-08T00:00:00Z',root:'/repo',headCommit:'a'.repeat(40),originalHash:'b'.repeat(64),executionHash:treeHash(snapshot),entries:[{path:'app.js',originalHash:sha256('vulnerable\n'),executionHash:sha256('vulnerable\n'),bytes:11,mode:0o755},{path:'app.test.js',originalHash:sha256(testBody),executionHash:sha256(testBody),bytes:Buffer.byteLength(testBody),mode:0o600},{path:'package.json',originalHash:sha256(packageJson),executionHash:sha256(packageJson),bytes:packageJson.length,mode:0o600}]};const runtime:any={id:'node',stack:'node',image:'runtime@sha256:'+'a'.repeat(64),platform:'linux/amd64'};const executor:any={observe:async(source:string,phase:string,_request:any,_runtime:any,_verifier:any,work:string)=>{expect(work.startsWith(source+path.sep)).toBe(false);fs.mkdirSync(path.join(work,phase),{recursive:true});fs.writeFileSync(path.join(work,phase,'policy.json'),'evidence');return{booted:true,legitimate:true,security:phase==='before'?'intended_failure':'pass',existingTests:true,output:'ok',inputHash:''};}};let unattested:any;try{await verifyRepair({runId:'run',runDir,manifest,rawRequest:raw,runtime,verifier:runtime,policyHash:'c'.repeat(64),archives:[],executor,persist:false});}catch(error){unattested=error;}expect(unattested).toMatchObject({code:'PREREQUISITE',attempt:{artifactKind:'repair_candidate',findingId:raw.findingId,reproduction:'reproduced',repair:'proposed',bundleIssued:false,testCompletionAssurance:'self_reported'}});expect(unattested.message).toContain('out-of-process external assertion witness');expect(fs.existsSync(path.join(runDir,'bundles'))).toBe(false);expect(fs.readdirSync(path.join(runDir,'verification'))).toEqual([]);expect(fs.statSync(path.join(snapshot,'app.js')).mode&0o777).toBe(0o755);const failing:any={observe:async()=>{throw new Error('stop');}};expect(verifyRepair({runId:'run',runDir,manifest,rawRequest:raw,runtime,verifier:runtime,policyHash:'c'.repeat(64),archives:[],executor:failing,persist:false})).rejects.toThrow('stop');expect(fs.readdirSync(path.join(runDir,'verification'))).toEqual([]);const afterFailure:any={observe:async(_source:string,phase:string)=>{if(phase==='after')throw new CsoError('TOOL_FAILED','after setup failed');return{booted:true,legitimate:true,security:'intended_failure',existingTests:true,output:'reproduced safely',inputHash:''};}};let failed:any;try{await verifyRepair({runId:'run',runDir,manifest,rawRequest:raw,runtime,verifier:runtime,policyHash:'c'.repeat(64),archives:[],executor:afterFailure});}catch(error){failed=error;}expect(failed).toMatchObject({code:'TOOL_FAILED',attempt:{findingId:raw.findingId,reproduction:'reproduced',repair:'failed',bundleIssued:false}});const attempt=failed.attempt,artifact=JSON.parse(fs.readFileSync(path.join(runDir,'verification-attempts',`${attempt.id}.json`),'utf8'));expect(artifact).toMatchObject({id:attempt.id,findingId:raw.findingId,reproduction:'reproduced',repair:'failed',bundleIssued:false});expect(fs.existsSync(path.join(runDir,'bundles'))).toBe(false);expect(fs.readdirSync(path.join(runDir,'verification'))).toEqual([]);const assertionFailure:any={observe:async(_source:string,phase:string)=>({booted:true,legitimate:true,security:'intended_failure',existingTests:true,output:phase==='before'?'reproduced safely':'repair remained vulnerable',inputHash:''})};let notRepaired:any;try{await verifyRepair({runId:'run',runDir,manifest,rawRequest:raw,runtime,verifier:runtime,policyHash:'c'.repeat(64),archives:[],executor:assertionFailure});}catch(error){notRepaired=error;}expect(notRepaired).toMatchObject({code:'ASSERTION_FAILED',attempt:{reproduction:'reproduced',repair:'failed',bundleIssued:false,after:{security:'intended_failure'}}});expect(fs.existsSync(path.join(runDir,'bundles'))).toBe(false);expect(fs.readdirSync(path.join(runDir,'verification-attempts'))).toHaveLength(2);const brokenStartup:any={observe:async()=>({booted:false,legitimate:false,security:'pass',existingTests:false,output:'application never started',inputHash:''})};let blocked:any;try{await verifyRepair({runId:'run',runDir,manifest,rawRequest:raw,runtime,verifier:runtime,policyHash:'c'.repeat(64),archives:[],executor:brokenStartup});}catch(error){blocked=error;}expect(blocked).toMatchObject({attempt:{reproduction:'blocked',repair:'failed',bundleIssued:false}});expect(fs.readdirSync(path.join(runDir,'verification-attempts'))).toHaveLength(3);fs.writeFileSync(path.join(snapshot,'unmanifested.txt'),'changed after snapshot identity\n');let executed=false;const mustNotExecute:any={observe:async()=>{executed=true;return{booted:true,legitimate:true,security:'pass',existingTests:true,output:'',inputHash:''};}};await expect(verifyRepair({runId:'run',runDir,manifest,rawRequest:raw,runtime,verifier:runtime,policyHash:'c'.repeat(64),archives:[],executor:mustNotExecute,persist:false})).rejects.toMatchObject({code:'INCOMPATIBLE_INPUT'});expect(executed).toBe(false);}); - test('handle-bearing bundles validate against matching source copied to a new root',()=>{ - const root=tmp(),before=path.join(root,'original'),matching=path.join(root,'matching'),after=path.join(root,'after');fs.mkdirSync(before); - fs.writeFileSync(path.join(before,'app.js'),'vulnerable\n');fs.writeFileSync(path.join(before,'test.js'),'test("ok",()=>{})\n'); - const appId=snapshotPathId(before,'app.js'),testId=snapshotPathId(before,'test.js'),appHandle=snapshotPathHandle(appId),testHandle=snapshotPathHandle(testId),raw:any=request('vulnerable\n','fixed\n'); - raw.start.args=[appHandle];raw.existingTests[0].args=[`./${testHandle}`];raw.boundaryFiles=[appHandle];raw.testFiles=[testHandle];raw.changes[0].path=appHandle;raw.review.reviewedPatchHash=patchHash(raw); - const identityRequest=validateVerificationRequest(raw),entries=[{path:'app.js',pathId:appId},{path:'test.js',pathId:testId}],manifest:any={root:before,originalHash:'d'.repeat(64),executionHash:treeHash(before),entries},executionRequest=resolveVerificationRequestPaths(manifest,identityRequest); - preparePatchedSource(before,after,executionRequest);const runtime:any={id:'node',image:'runtime@sha256:'+'a'.repeat(64),platform:'linux/amd64'},params:any={runId:'run',manifest,request:executionRequest,identityRequest,runtime,verifier:runtime,before:{booted:true,legitimate:true,security:'intended_failure',existingTests:true,output:'before',inputHash:''},after:{booted:true,legitimate:true,security:'pass',existingTests:true,output:'after',inputHash:''},beforeRoot:before,afterRoot:after,policyHash:'c'.repeat(64),auditPolicyHash:'e'.repeat(64),archives:[],testToolchain:'runtime'},bundle=authenticatedBundleFixture(certify(params),params); - fs.cpSync(before,matching,{recursive:true});const matchingManifest:any={...manifest,root:matching,entries:entries.map(entry=>({...entry,pathId:snapshotPathId(matching,entry.path)}))}; - expect(snapshotPathId(matching,'app.js')).toBe(appId);expect(treeHash(matching)).toBe(manifest.executionHash);expect(bundle.request.start.args).toEqual([appHandle]);expect(bundle.request.existingTests[0].args).toEqual([`./${testHandle}`]);expect(()=>validateRepairBundle(bundle,bundle.id,matching)).toThrow('matching snapshot manifest');expect(validateRepairBundle(bundle,bundle.id,matching,matchingManifest).id).toBe(bundle.id); - }); - test('reserved authenticated bundle reader detects changed observations, replay inputs, and retention timestamps',()=>{const root=tmp(),before=path.join(root,'before'),after=path.join(root,'after');fs.mkdirSync(before);fs.writeFileSync(path.join(before,'app.js'),'vulnerable\n');fs.writeFileSync(path.join(before,'test.js'),'pass\n');const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash=patchHash(raw);const req=validateVerificationRequest(raw);preparePatchedSource(before,after,req);const params:any={runId:'run',manifest:{originalHash:'d'.repeat(64),executionHash:treeHash(before),entries:[]},request:req,runtime:{id:'node',image:'runtime@sha256:'+'a'.repeat(64),platform:'linux/amd64'},verifier:{image:'runtime@sha256:'+'a'.repeat(64)},before:{booted:true,legitimate:true,security:'intended_failure',existingTests:true,output:'before',inputHash:''},after:{booted:true,legitimate:true,security:'pass',existingTests:true,output:'after',inputHash:''},beforeRoot:before,afterRoot:after,policyHash:'c'.repeat(64),auditPolicyHash:'e'.repeat(64),archives:[],testToolchain:'runtime'};const certified=certify(params),bundle=authenticatedBundleFixture(certified,params);expect(validateRepairBundle(bundle,bundle.id,before).id).toBe(bundle.id);expect(()=>validateRepairBundle({...bundle,verification:{...bundle.verification,after:{...bundle.verification.after,output:'tampered'}}},bundle.id,before)).toThrow('identity');const changed=structuredClone(bundle);changed.request.legitimate[0].path='/different';expect(()=>validateRepairBundle(changed,changed.id,before)).toThrow('harness');const expired=structuredClone(bundle);expired.expiresAt=new Date(Date.parse(expired.expiresAt)+1000).toISOString();expect(()=>validateRepairBundle(expired,expired.id,before)).toThrow('timestamps');const rebased=structuredClone(bundle);rebased.createdAt=new Date(Date.parse(rebased.createdAt)+1000).toISOString();rebased.expiresAt=new Date(Date.parse(rebased.createdAt)+30*86400_000).toISOString();expect(()=>validateRepairBundle(rebased,rebased.id,before)).toThrow('timestamps');}); - test('project test-toolchain provenance requires equal prepared bytes and survives bundle identity rebinding',()=>{ - const root=tmp(),before=path.join(root,'before'),after=path.join(root,'after');fs.mkdirSync(before);fs.writeFileSync(path.join(before,'app.js'),'vulnerable\n');fs.writeFileSync(path.join(before,'test.js'),'pass\n');const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash=patchHash(raw);const req=validateVerificationRequest(raw);preparePatchedSource(before,after,req);const h=(value:string)=>value.repeat(64),proof=(dependency:string)=>({schemaVersion:1 as const,dependencyClosureHash:h('1'),configurationHash:h('2'),sourceProjectionHash:h('3'),preparedManifestHash:h('4'),preparedDependencyHash:dependency,receiptHash:h('5'),executionEnvironmentHash:h('6'),databaseHash:h('7'),transformations:[]}); - const params:any={runId:'run',manifest:{originalHash:h('8'),executionHash:treeHash(before),entries:[]},request:req,runtime:{id:'node',image:`runtime@sha256:${h('a')}`,platform:'linux/amd64'},verifier:{image:`runtime@sha256:${h('a')}`},before:{booted:true,legitimate:true,security:'intended_failure',existingTests:true,output:'before',inputHash:''},after:{booted:true,legitimate:true,security:'pass',existingTests:true,output:'after',inputHash:''},beforeRoot:before,afterRoot:after,policyHash:h('c'),auditPolicyHash:h('e'),archives:[],testToolchain:'project',preparation:{before:proof(h('9')),after:proof(h('9'))}}; - const certified=certify(params),bundle=authenticatedBundleFixture(certified,params);expect(certified.manifest.testToolchain).toBe('project');expect(certified.bundle).toBeUndefined();expect(validateRepairBundle(bundle,bundle.id,before).id).toBe(bundle.id); - const missing=structuredClone(bundle);delete missing.preparation;expect(()=>validateRepairBundle(missing,missing.id,before)).toThrow('omitted project test-toolchain'); - const drift=structuredClone(bundle);drift.preparation!.after.preparedDependencyHash=h('b');drift.verification.preparationHash=sha256(canonical(drift.preparation));drift.verification.id='';const rebound=verificationIdentity(drift.verification);drift.verification.id=rebound;drift.id=rebound;expect(()=>validateRepairBundle(drift,rebound,before)).toThrow('test toolchain changed'); - expect(()=>certify({...params,preparation:undefined})).toThrow('require before/after prepared dependency proofs');expect(()=>certify({...params,preparation:{before:proof(h('9')),after:proof(h('b'))}})).toThrow('toolchain bytes changed'); - }); - const securityArray=()=>[ - {name:'tenant isolation',path:'/user?id=2',method:'GET',expected:{status:403},vulnerable:{status:200,includes:'tenant-b'}}, - {name:'tenant isolation by header',path:'/user',method:'GET',headers:{'x-tenant':'b'},expected:{status:403},vulnerable:{status:200,includes:'tenant-b'}}, - {name:'tenant isolation on write',path:'/user/2',method:'PUT',body:'{"name":"x"}',expected:{status:404},vulnerable:{status:204}}, - ]; - test('single-object security keeps its pre-array request, patch, assertion, and harness bytes',()=>{ - const root=tmp();fs.writeFileSync(path.join(root,'test.js'),'pass\n');fs.chmodSync(path.join(root,'test.js'),0o644); - const raw:any=request('vulnerable\n','fixed\n');raw.review.reviewedPatchHash=patchHash(raw);const req=validateVerificationRequest(raw); - expect(Array.isArray(req.security)).toBe(false);expect(canonical(req.security)).toBe(canonical(raw.security)); - expect({patch:patchHash(req),request:sha256(canonical(req)),assertion:sha256(canonical({legitimate:req.legitimate,security:req.security})),harness:verificationHarnessHash(req,root)}).toEqual({ - patch:'cc6ab00ee0160ce484a86130f94a5e6e5f588f3ec975c781c4d077647adff483', - request:'85175d755f1b297eb7d15dc1d9850e1ac453d1d129ceee58213d89cbab0ee59c', - assertion:'7e0f792881bc14137f2aa70b0662a013939749903e49eb507c1ecf48561b0771', - harness:'2a74b61982270fd10c071f0bdd32ae37f04de6e3eca1db6c9225132de29b4309', - }); - }); - test('security accepts a bounded array of distinct assertions that each carry an exclusive vulnerable oracle',()=>{ - const make=(security:unknown)=>{const raw:any=request('vulnerable\n','fixed\n');raw.security=security;raw.review.reviewedPatchHash=patchHash(raw);return raw;}; - const accepted=validateVerificationRequest(make(securityArray()));expect(accepted.security).toEqual(securityArray() as any); - expect(validateVerificationRequest(make(securityArray().slice(0,1))).security).toHaveLength(1); - const full=Array.from({length:8},(_,i)=>({...securityArray()[0],name:`payload ${i}`}));expect(validateVerificationRequest(make(full)).security).toHaveLength(8); - expect(()=>validateVerificationRequest(make([]))).toThrow('1..8 assertions'); - expect(()=>validateVerificationRequest(make([...full,{...full[0],name:'payload 8'}]))).toThrow('1..8 assertions'); - expect(()=>validateVerificationRequest(make([securityArray()[0],{...securityArray()[1],name:'tenant isolation'}]))).toThrow('names must be distinct'); - const missing=securityArray();delete (missing[2] as any).vulnerable;expect(()=>validateVerificationRequest(make(missing))).toThrow('distinct before/fixed security oracles'); - const overlapping=securityArray();overlapping[1].vulnerable={...overlapping[1].expected} as any;expect(()=>validateVerificationRequest(make(overlapping))).toThrow('mutually exclusive'); - const extra:any=securityArray();extra[0].expected.untrusted='yes';expect(()=>validateVerificationRequest(make(extra))).toThrow('Unexpected security[0].expected field'); - expect(()=>validateVerificationRequest(make([null]))).toThrow(); - }); - test('an array security request is observed in exactly one before/after pair and binds every member',async()=>{ - const runDir=tmp(),snapshot=path.join(runDir,'snapshot');fs.mkdirSync(snapshot);fs.writeFileSync(path.join(snapshot,'app.js'),'vulnerable\n');const testBody='test("ok",()=>{})\n';fs.writeFileSync(path.join(snapshot,'app.test.js'),testBody);const packageJson='{"scripts":{"test":"node --test"}}';fs.writeFileSync(path.join(snapshot,'package.json'),packageJson); - const raw:any=request('vulnerable\n','fixed\n');raw.findingId='1abcdefabcdefabcdefabcdefabcdefa';raw.security=securityArray();raw.existingTests=[{executable:'/usr/local/bin/node',args:['--test','--test-reporter=tap','./app.test.js']}];raw.testFiles=['app.test.js'];raw.review.reviewedPatchHash=patchHash(raw); - const manifest:any={version:3,createdAt:'2026-01-01T00:00:00Z',expiresAt:'2026-01-08T00:00:00Z',root:'/repo',headCommit:'a'.repeat(40),originalHash:'b'.repeat(64),executionHash:treeHash(snapshot),entries:[{path:'app.js',originalHash:sha256('vulnerable\n'),executionHash:sha256('vulnerable\n'),bytes:11,mode:0o600},{path:'app.test.js',originalHash:sha256(testBody),executionHash:sha256(testBody),bytes:Buffer.byteLength(testBody),mode:0o600},{path:'package.json',originalHash:sha256(packageJson),executionHash:sha256(packageJson),bytes:packageJson.length,mode:0o600}]}; - const runtime:any={id:'node',stack:'node',image:'runtime@sha256:'+'a'.repeat(64),platform:'linux/amd64'},phases:string[]=[]; - const executor:any={observe:async(_source:string,phase:string,observed:any)=>{phases.push(phase);expect(observed.security).toEqual(securityArray());return{booted:true,legitimate:true,security:phase==='before'?'intended_failure':'pass',existingTests:true,output:'ok',inputHash:''};}}; - let unattested:any;try{await verifyRepair({runId:'run',runDir,manifest,rawRequest:raw,runtime,verifier:runtime,policyHash:'c'.repeat(64),archives:[],executor,persist:false});}catch(error){unattested=error;} - expect(phases).toEqual(['before','after']);expect(unattested).toMatchObject({code:'PREREQUISITE',attempt:{reproduction:'reproduced',repair:'proposed',bundleIssued:false}}); - const root=tmp(),before=path.join(root,'before'),after=path.join(root,'after');fs.mkdirSync(before);fs.writeFileSync(path.join(before,'app.js'),'vulnerable\n');fs.writeFileSync(path.join(before,'test.js'),'pass\n'); - const plain:any=request('vulnerable\n','fixed\n');plain.security=securityArray();plain.review.reviewedPatchHash=patchHash(plain);const req=validateVerificationRequest(plain);preparePatchedSource(before,after,req); - const params:any={runId:'run',manifest:{originalHash:'d'.repeat(64),executionHash:treeHash(before),entries:[]},request:req,runtime:{id:'node',image:'runtime@sha256:'+'a'.repeat(64),platform:'linux/amd64'},verifier:{image:'runtime@sha256:'+'a'.repeat(64)},before:{booted:true,legitimate:true,security:'intended_failure',existingTests:true,output:'before',inputHash:''},after:{booted:true,legitimate:true,security:'pass',existingTests:true,output:'after',inputHash:''},beforeRoot:before,afterRoot:after,policyHash:'c'.repeat(64),auditPolicyHash:'e'.repeat(64),archives:[],testToolchain:'runtime'}; - const bundle=authenticatedBundleFixture(certify(params),params);expect(validateRepairBundle(bundle,bundle.id,before).id).toBe(bundle.id); - const dropped=structuredClone(bundle);(dropped.request.security as any[]).pop();expect(()=>validateRepairBundle(dropped,dropped.id,before)).toThrow('harness'); - expect(certify({...params,after:{...params.after,security:'inconclusive'}}).manifest.result).toBe('inconclusive'); - }); -}); -function tree(root:string){return sha256(JSON.stringify(fs.readdirSync(root).sort().map(p=>{const file=path.join(root,p),stat=fs.statSync(file);return[p,sha256(fs.readFileSync(file)),stat.mode&0o777];})));} - -describe('#2894 truthful completion in the report the user receives',()=>{ - const coverage=(domain:string,status:string,gaps:string[]=[],tool?:any)=>({domain,scope:'all',status,method:'trace',gaps,exclusions:[],evidence:[],...(tool?{tool}:{})}); - const report=(entries:any[],status='finished'):any=>{const base:any={coverage:entries,gaps:[]};return{...base,schemaVersion:3,runId:'1700000000000-0123456789abcdef',repoId:'x',createdAt:'2026-01-01',deadline:'2026-01-01',status,completeness:completeness(base),policy:{mode:'daily',scope:'all',diff:false,base:'main',offline:true,budgetSeconds:600,maxWorkers:3,maxRepairs:3},source:{root:'/x',snapshotHash:'s',originalHash:'o'},application:{actors:[],assets:[],entrypoints:[],tenantBoundaries:[],sensitiveOperations:[],invariants:[]},findings:[],events:[]};}; - test('not assessed names what ran, what is missing, why, and the next step, and never reads as clean',()=>{ - const markdown=renderReport(report([coverage('snapshot-inputs','assessed'),coverage('auth','not_assessed',['Investigation deadline reached']),coverage('secrets','not_assessed',['Assessment has not been submitted'])])); - const lines=markdown.split('\n'); - expect(lines[0]).toStartWith('not assessed — '); - expect(lines[1]).toBe('Status: not assessed. No security domain was assessed, so this report is not a clean result.'); - expect(lines[2]).toBe('Ran: snapshot-inputs (assessed). Missing: auth (not\\_assessed); secrets (not\\_assessed).'); - expect(lines[3]).toBe('Reason: Investigation deadline reached; Assessment has not been submitted.'); - expect(lines[4]).toStartWith('Next: start a new /cso audit'); - expect(markdown).not.toContain('No supported findings in the assessed scope.'); - expect(markdown).toContain('No findings: nothing was assessed.'); - const running=renderReport(report([coverage('auth','not_assessed')],'running')); - expect(running).toContain('Reason: no assessment evidence was recorded for the missing domains.'); - expect(running).toContain('Next: resume this run with `gstack-cso resume 1700000000000-0123456789abcdef`'); - }); - test('partial and complete keep the exact empty phrase; partial names missing coverage first and optional scanners without results',()=>{ - const partial=renderReport(report([coverage('auth','assessed'),coverage('secrets','partial',['Scanner timed out']),coverage('scanner:gitleaks','not_assessed',['Scanner catalog unavailable'],{name:'gitleaks',version:'unavailable',freshness:'not reported',outcome:'not_assessed'})])); - expect(partial).toStartWith('partial — all\nStatus: partial. Some required coverage is missing;'); - expect(partial).toContain('Ran: auth (assessed); secrets (partial). Missing: secrets (partial).'); - expect(partial).toContain('Optional scanners without results: gitleaks (not\\_assessed: Scanner catalog unavailable).'); - expect(partial).toContain('No supported findings in the assessed scope.'); - expect(partial.indexOf('Status: partial')).toBeLessThan(partial.indexOf('No supported findings')); - const complete=renderReport(report([coverage('auth','assessed')])); - expect(complete).toContain('No supported findings in the assessed scope.'); - expect(complete).not.toContain('Status:'); - }); - test('a finished run with no submitted evidence writes a not-assessed report.md',async()=>{ - const previous=process.env.GSTACK_HOME,base=tmp();process.env.GSTACK_HOME=path.join(base,'state'); - try{ - const repo=path.join(base,'repo');fs.mkdirSync(repo); - for(const args of [['init','-q'],['config','user.email','fixture@example.test'],['config','user.name','Fixture']])expect(spawnSync('git',args,{cwd:repo,timeout:10_000}).status).toBe(0); - fs.writeFileSync(path.join(repo,'app.js'),'console.log("fixture")\n'); - for(const args of [['add','app.js'],['commit','-qm','fixture']])expect(spawnSync('git',args,{cwd:repo,timeout:10_000}).status).toBe(0); - const dependencies={runtimeCatalog:RUNTIME_CATALOG,catalogImageSession:async()=>{throw new Error('unused');},watchdogPath:()=>'/unused'} as any; - const started=await dispatchCsoCommand('start',['--repo',repo,'--offline'],dependencies) as any; - await dispatchCsoCommand('finish',[started.runId],dependencies); - const markdown=fs.readFileSync(path.join(base,'state','security','cso',started.repoId,started.runId,'report.md'),'utf8'); - expect(markdown).toStartWith('not assessed — '); - expect(markdown).toContain('Status: not assessed. No security domain was assessed, so this report is not a clean result.'); - expect(markdown).toContain('Missing: application-model (not\\_assessed)'); - expect(markdown).toMatch(/\nReason: [^\n]*Assessment has not been submitted[^\n]*\nNext: start a new \/cso audit/); - expect(markdown).not.toContain('No supported findings in the assessed scope.'); - }finally{if(previous===undefined)delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME=previous;} - },30_000); -}); diff --git a/test/cso-distribution.test.ts b/test/cso-distribution.test.ts deleted file mode 100644 index 04f367121..000000000 --- a/test/cso-distribution.test.ts +++ /dev/null @@ -1,758 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { createHash } from 'node:crypto'; -import { tmpdir } from 'node:os'; -import { dirname, join, resolve } from 'node:path'; -import { spawnSync } from 'node:child_process'; -import committedCatalog from '../lib/cso/runtime-catalog.json'; -import buildInputs from '../lib/cso/images/build-inputs.json'; -import { committedImageBuildMatrix, imageBuildMatrix } from '../scripts/cso-image-matrix'; -import { catalogPromotionCandidate, requiredChecks } from '../scripts/cso-runtime-promotion'; -import { runBashScript } from './helpers/bash-script'; -import { requalificationTriggers } from '../scripts/cso-requalification'; - -const CURRENT_TRIGGERS = await requalificationTriggers(); - -const ROOT = resolve(import.meta.dir, '..'); -const temps: string[] = []; -afterEach(() => { for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true }); }); -const quote = (s: string) => "'" + s.replaceAll("'", "'\\''") + "'"; -const CREDENTIAL_IMAGE = ['https://user:', 'pass@example.test/node'].join(''); - -function buildFixture() { - const dir = mkdtempSync(join(tmpdir(), 'gstack-cso-build-')); temps.push(dir); - for (const sub of ['scripts', 'bin', 'lib/cso']) mkdirSync(join(dir, sub), { recursive: true }); - copyFileSync(join(ROOT, 'scripts/build-cso.sh'), join(dir, 'scripts/build-cso.sh')); - const publisher = [ - '#!/bin/sh', - 'set -eu', - 'directory=$1', - 'shift', - 'if [ "$(uname -s)" = Linux ]; then', - " exec /usr/bin/flock -n -E 73 \"$directory\" /bin/sh -c '", - ' if [ -n "${CSO_PUBLISH_BARRIER:-}" ]; then', - ' : > "${CSO_PUBLISH_BARRIER}.ready"', - ' while [ ! -f "${CSO_PUBLISH_BARRIER}.go" ]; do sleep .01; done', - ' fi', - ' export GSTACK_CSO_PUBLISH_LOCKED=1', - ' exec "$@"', - " ' cso-publish \"$@\"", - 'fi', - 'export GSTACK_CSO_PUBLISH_LOCKED=1', - 'exec "$@"', - '', - ].join('\n'); - writeFileSync(join(dir, 'publish lock wrapper'), publisher); chmodSync(join(dir, 'publish lock wrapper'), 0o755); - // The recorder substitutes compilation only. The build command itself is the - // real script, so quoting, flag propagation and failed-compiler behavior run. - const recorder = '#!/bin/sh\nset -eu\nprintf "%s\\n" "$@" >> "$CSO_BUILD_LOG"\ncount_file="$CSO_BUILD_LOG.count"\ncount=0\n[ ! -f "$count_file" ] || count=$(cat "$count_file")\ncount=$((count+1))\nprintf "%s\\n" "$count" > "$count_file"\nif [ -n "${CSO_BUILD_BARRIER:-}" ] && [ "$count" = 1 ]; then touch "$CSO_BUILD_BARRIER.ready"; while [ ! -f "$CSO_BUILD_BARRIER.go" ]; do sleep .01; done; fi\nif [ "${CSO_FAIL_COMPILER:-0}" = 1 ] || [ "${CSO_FAIL_COMPILER_N:-0}" = "$count" ]; then exit 42; fi\noutput=""\nwhile [ "$#" -gt 0 ]; do\n case "$1" in --outfile|-o) shift; output="$1" ;; esac\n shift\ndone\nif [ -n "$output" ]; then\n case "$output" in\n *gstack-cso-publish-lock*) cp "$CSO_FAKE_LOCKER_TEMPLATE" "$output" ;;\n *) generation="${CSO_BUILD_GENERATION:-NEW}"; cat > "$output" <readFileSync(join(dir,'bin',name),'utf8'));} -function expectPublishedBundle(dir:string,generation='NEW'){ - const contents=bundleContents(dir); - expect(contents.slice(0,3).every(content=>content.includes(generation))).toBe(true); - expect(contents[3]).toMatch(/^[a-f0-9]{64}\n$/); -} -function fakeBuildCommand(dir:string,extra=''){const log=join(dir,'compiler.log');return `${extra} BUN_CMD=${quote(join(dir,'compiler recorder'))} CSO_CC=${quote(join(dir,'compiler recorder'))} CSO_BUILD_LOG=${quote(log)} CSO_FAKE_LOCKER_TEMPLATE=${quote(join(dir,'publish lock wrapper'))} bash ${quote(join(dir,'scripts/build-cso.sh'))}`;} -function fakeBuild(dir:string,extra=''){return runBashScript(fakeBuildCommand(dir,extra),{timeout:10_000});} - -function reviewedInputs(): any { - const pinned = (repository: string, fill: string) => `${repository}@sha256:${fill.repeat(64)}`; - const family = (repository: string, tag: string, index: string, amd64: string, arm64: string) => ({ - source: `${repository}:${tag}`, - indexImage: pinned(repository, index), - images: { 'linux/amd64': pinned(repository, amd64), 'linux/arm64': pinned(repository, arm64) }, - }); - const sbom = family('docker.io/tool/sbom', '1.0.0', '1', '2', '3'); - const base = (repository: string, tag: string, index: string, amd64: string, arm64: string) => { - const value = family(repository, tag, index, amd64, arm64); - return { source: value.source, indexImage: value.indexImage, baseImages: value.images }; - }; - return { - schemaVersion: 1, helperAbi: 3, state: 'reviewed', revision: 'fixture-runtime-inputs', - reviewedAt: '2026-09-10T00:00:00.000Z', - reviewMethod: 'Fixture review metadata long enough to exercise the strict source-controlled build input contract.', - sbomGenerator: sbom, - profiles: [ - { id: 'node-24.4.0', stack: 'node', ...base('docker.io/library/node', '24.4.0', '4', '5', '6'), versions: { node: '24.4.0', npm: '11.4.2', 'cso-preparation': '1.0.0' } }, - { id: 'bun-1.3.10', stack: 'bun', ...base('docker.io/oven/bun', '1.3.10', '7', '8', '9'), versions: { bun: '1.3.10', 'cso-preparation': '1.0.0' } }, - { id: 'python-3.13.4-uv-0.8.0', stack: 'python', ...base('docker.io/library/python', '3.13.4', 'a', 'b', 'c'), - uvSource: 'ghcr.io/astral-sh/uv:0.8.0', uvIndexImage: pinned('ghcr.io/astral-sh/uv', 'd'), - uvImages: { 'linux/amd64': pinned('ghcr.io/astral-sh/uv', 'e'), 'linux/arm64': pinned('ghcr.io/astral-sh/uv', 'f') }, - versions: { python: '3.13.4', uv: '0.8.0', 'cso-preparation': '1.0.0' } }, - { id: 'rails-ruby-3.4.4', stack: 'rails', ...base('docker.io/library/ruby', '3.4.4', '0', 'a', 'b'), versions: { ruby: '3.4.4', bundler: '2.6.7', 'cso-preparation': '1.0.0' } }, - { id: 'postgresql-17.2', stack: 'postgresql', ...base('docker.io/library/postgres', '17.2', 'c', 'd', 'e'), versions: { postgresql: '17.2' } }, - ], - }; -} - -describe('CSO build and distribution wiring', () => { - test('POSIX helpers expose Darwin no-follow flags before system headers', () => { - for (const relative of ['lib/cso/launcher.c', 'lib/cso/watchdog.c', 'lib/cso/publish-lock.c']) { - const source = readFileSync(join(ROOT, relative), 'utf8'); - const darwinFeature = source.indexOf('#define _DARWIN_C_SOURCE 1'); - const fileFlags = source.indexOf('#include '); - expect(darwinFeature, relative).toBeGreaterThanOrEqual(0); - expect(fileFlags, relative).toBeGreaterThan(darwinFeature); - expect(source, relative).toContain('O_NOFOLLOW'); - } - }); - - test('the cached eval image proves the static C toolchain required by direct builds', () => { - const dockerfile = readFileSync(join(ROOT, '.github/docker/Dockerfile.ci'), 'utf8'); - expect(dockerfile).toMatch(/\bgcc libc6-dev\b/); - expect(dockerfile).toContain('cc -std=c11 -static /tmp/gstack-cso-cc-probe.c'); - expect(dockerfile).toContain('/tmp/gstack-cso-cc-probe'); - }); - - test.skipIf(process.platform === 'win32')('real build script supplies all startup-hardening flags and compiles its watchdog', () => { - const dir = buildFixture(), log = join(dir, 'compiler.log'); - const r = fakeBuild(dir); - expect(r.status).toBe(0); - const args = readFileSync(log, 'utf8').split('\n'); - for (const flag of ['--no-compile-autoload-dotenv', '--no-compile-autoload-bunfig', '--no-compile-autoload-tsconfig', '--no-compile-autoload-package-json']) expect(args.filter(a => a === flag)).toHaveLength(1); - expect(args).toContain('lib/cso/cli.ts'); - expect(args.some(arg=>/bin\/\.gstack-cso-stage\.[^/]+\/gstack-cso-core$/.test(arg))).toBe(true); - expect(args).toContain('lib/cso/launcher.c'); - expect(args.some(arg=>/bin\/\.gstack-cso-stage\.[^/]+\/gstack-cso-launcher$/.test(arg))).toBe(true); - expect(args).toContain('lib/cso/watchdog.c'); - expect(args.some(arg=>/bin\/\.gstack-cso-stage\.[^/]+\/gstack-cso-watchdog$/.test(arg))).toBe(true); - expect(args).toContain('lib/cso/publish-lock.c'); - expect(args.some(arg=>/bin\/\.gstack-cso-stage\.[^/]+\/gstack-cso-publish-lock$/.test(arg))).toBe(true); - expect(spawnSync(join(dir,'bin/gstack-cso-launcher'),['--version'],{encoding:'utf8',timeout:5000}).stdout.trim()).toBe('NEW'); - expectPublishedBundle(dir); - }); - - test.skipIf(process.platform === 'win32')('generation validation accepts BSD wc padding', () => { - const dir = buildFixture(), tools = join(dir, 'bsd-tools'), wc = join(tools, 'wc'); - mkdirSync(tools); - writeFileSync(wc, '#!/bin/sh\nset -eu\ncount=$(/usr/bin/wc -c "$@")\nprintf " %s\\n" "$count"\n'); - chmodSync(wc, 0o755); - const result = fakeBuild(dir, `PATH=${quote(`${tools}:/usr/bin:/bin`)}`); - expect(result.status).toBe(0); - expectPublishedBundle(dir); - }); - - test.skipIf(process.platform === 'win32').each([1,2,3,4])('compiler failure at stage %i preserves the exact runnable old bundle', failure => { - const dir=buildFixture();seedBundle(dir);const before=bundleContents(dir); - const r=fakeBuild(dir,`CSO_FAIL_COMPILER_N=${failure}`); - expect(r.status).toBe(42); - expect(bundleContents(dir)).toEqual(before); - expect(spawnSync(join(dir,'bin/gstack-cso-launcher'),{encoding:'utf8',timeout:5000}).stdout.trim()).toBe('OLD'); - }); - - test.skipIf(process.platform === 'win32').each(['withdraw-launcher','publish-core','publish-watchdog','before-publish-launcher','publish-launcher'])('publication failure after %s rolls back to the exact old bundle', checkpoint=>{ - const dir=buildFixture();seedBundle(dir);const before=bundleContents(dir); - const r=fakeBuild(dir,`GSTACK_CSO_BUILD_TESTING=1 GSTACK_CSO_BUILD_TEST_FAIL_AFTER=${checkpoint}`); - expect(r.status).toBe(86);expect(bundleContents(dir)).toEqual(before); - expect(spawnSync(join(dir,'bin/gstack-cso-launcher'),{encoding:'utf8',timeout:5000}).stdout.trim()).toBe('OLD'); - }); - - test.skipIf(process.platform === 'win32')('SIGKILL before launcher publication leaves no runnable mixed bundle',()=>{ - const dir=buildFixture();seedBundle(dir);const r=fakeBuild(dir,'GSTACK_CSO_BUILD_TESTING=1 GSTACK_CSO_BUILD_TEST_KILL_AFTER=publish-core'); - expect(r.status).not.toBe(0);expect(() => readFileSync(join(dir,'bin/gstack-cso-launcher'))).toThrow(); - expect(fakeBuild(dir).status).toBe(0); - expectPublishedBundle(dir); - }); - - test.skipIf(process.platform === 'win32')('SIGKILL after launcher-last publication leaves a complete new bundle',()=>{ - const dir=buildFixture();seedBundle(dir);const r=fakeBuild(dir,'GSTACK_CSO_BUILD_TESTING=1 GSTACK_CSO_BUILD_TEST_KILL_AFTER=publish-launcher'); - expect(r.status).not.toBe(0);expectPublishedBundle(dir); - expect(spawnSync(join(dir,'bin/gstack-cso-launcher'),{encoding:'utf8',timeout:5000}).stdout.trim()).toBe('NEW'); - }); - - test.skipIf(process.platform === 'win32')('a failed rollback withholds the launcher and retains recovery material',()=>{ - const dir=buildFixture();seedBundle(dir); - const r=fakeBuild(dir,'GSTACK_CSO_BUILD_TESTING=1 GSTACK_CSO_BUILD_TEST_FAIL_AFTER=publish-core GSTACK_CSO_BUILD_TEST_FAIL_RESTORE=core'); - expect(r.status).not.toBe(0);expect(() => readFileSync(join(dir,'bin/gstack-cso-launcher'))).toThrow(); - expect(r.stderr).toContain('recovery files remain'); - expect(readFileSync(join(dir,'bin/gstack-cso-watchdog'),'utf8')).toContain('OLD'); - }); - - test.skipIf(process.platform !== 'linux')('publisher lock rejects a competing OS lock without mutating the installed bundle',async()=>{ - const dir=buildFixture(),ready=join(dir,'lock.ready'),release=join(dir,'lock.release');seedBundle(dir);const before=bundleContents(dir); - const holder=Bun.spawn(['/usr/bin/flock','-n',join(dir,'bin'),'/bin/sh','-c',`: > ${quote(ready)}; while [ ! -f ${quote(release)} ]; do sleep .01; done`],{stdout:'pipe',stderr:'pipe'}); - const deadline=Date.now()+3000;while(!existsSync(ready)&&Date.now(){ - const dir=buildFixture();seedBundle(dir);mkdirSync(join(dir,'bin/.gstack-cso-build.lock')); - expect(fakeBuild(dir).status).toBe(0); - expectPublishedBundle(dir); - }); - - test.skipIf(process.platform !== 'linux')('concurrent publishers cannot interleave generations under the exclusive publication lock',async()=>{ - const dir=buildFixture(),barrier=join(dir,'barrier');seedBundle(dir); - const first=Bun.spawn(['/bin/bash','-c',fakeBuildCommand(dir,`CSO_PUBLISH_BARRIER=${quote(barrier)} CSO_BUILD_GENERATION=A`)],{stdout:'pipe',stderr:'pipe'}); - const deadline=Date.now()+3000;while(!existsSync(`${barrier}.ready`)&&Date.now(){ - const dir=buildFixture(),tools=join(dir,'tools'),marker=join(dir,'signal-after-mv');seedBundle(dir);mkdirSync(tools); - const realMv=Bun.which('mv');expect(realMv).toBeTruthy(); - writeFileSync(join(tools,'mv'),`#!/bin/sh\n${quote(realMv!)} "$@"\nstatus=$?\nif [ "$status" -eq 0 ] && [ ! -f "$CSO_SIGNAL_AFTER_MV_MARKER" ]; then\n : > "$CSO_SIGNAL_AFTER_MV_MARKER"\n kill -TERM "$PPID"\n sleep .05\nfi\nexit "$status"\n`); - chmodSync(join(tools,'mv'),0o755); - const r=fakeBuild(dir,`PATH=${quote(`${tools}:/usr/bin:/bin`)} CSO_SIGNAL_AFTER_MV_MARKER=${quote(marker)}`); - expect(r.status).toBe(0);expect(existsSync(marker)).toBe(true);expectPublishedBundle(dir); - }); - - test.skipIf(process.platform !== 'linux')('a macOS build fails closed when hardened-runtime signing is unavailable', () => { - const dir = buildFixture(), log = join(dir, 'compiler.log'), tools = join(dir, 'tools'); - seedBundle(dir);const before=bundleContents(dir); - mkdirSync(tools); - writeFileSync(join(tools, 'uname'), '#!/bin/sh\nprintf "Darwin\\n"\n'); - chmodSync(join(tools, 'uname'), 0o755); - const r = runBashScript(`PATH=${quote(`${tools}:/usr/bin:/bin`)} BUN_CMD=${quote(join(dir, 'compiler recorder'))} CSO_CC=${quote(join(dir, 'compiler recorder'))} CSO_BUILD_LOG=${quote(log)} bash ${quote(join(dir, 'scripts/build-cso.sh'))}`, { timeout: 10_000 }); - expect(r.status).toBe(1); - expect(r.stderr).toContain('requires macOS codesign'); - expect(bundleContents(dir)).toEqual(before); - }); - - test.skipIf(process.platform !== 'linux')('a macOS signing failure cannot mutate the installed generation',()=>{ - const dir=buildFixture(),log=join(dir,'compiler.log'),tools=join(dir,'tools');seedBundle(dir);const before=bundleContents(dir);mkdirSync(tools); - writeFileSync(join(tools,'uname'),'#!/bin/sh\nprintf "Darwin\\n"\n');writeFileSync(join(tools,'codesign'),'#!/bin/sh\nexit 1\n'); - chmodSync(join(tools,'uname'),0o755);chmodSync(join(tools,'codesign'),0o755); - const r=runBashScript(`PATH=${quote(`${tools}:/usr/bin:/bin`)} BUN_CMD=${quote(join(dir,'compiler recorder'))} CSO_CC=${quote(join(dir,'compiler recorder'))} CSO_BUILD_LOG=${quote(log)} bash ${quote(join(dir,'scripts/build-cso.sh'))}`,{timeout:10_000}); - expect(r.status).not.toBe(0);expect(bundleContents(dir)).toEqual(before); - }); - - test('setup distributes the helper pair without promising an incomplete npm bin', () => { - const pkg = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8')); - const build = readFileSync(join(ROOT, 'scripts/build.sh'), 'utf8'); - const setup = readFileSync(join(ROOT, 'setup'), 'utf8'); - const ignore = readFileSync(join(ROOT, '.gitignore'), 'utf8').split('\n'); - expect(pkg.bin).not.toHaveProperty('gstack-cso'); - expect(pkg.scripts['build:cso']).toBe('bash scripts/build-cso.sh'); - expect(pkg.scripts['test:cso:macos']).toBe('bun test test/cso-macos-launcher.test.ts test/cso-registry-socket.test.ts'); - expect(pkg.scripts['test:cso:docker']).toContain('test/cso-node-lifecycle-integration.test.ts'); - expect(pkg.scripts['test:cso:docker']).toContain('test/cso-stack-cold-integration.test.ts'); - expect(pkg.scripts['test:cso:docker']).toContain('--max-concurrency 1'); - expect(build).toContain('bash scripts/build-cso.sh'); - const signed = setup.match(/for _bin in ([^;]+);/)![1].split(/\s+/); - for (const name of ['bin/gstack-cso-launcher','bin/gstack-cso-core', 'bin/gstack-cso-watchdog']) { - expect(signed).not.toContain(name); expect(ignore).toContain(name); expect(ignore).toContain(`${name}.exe`); - } - expect(readFileSync(join(ROOT,'scripts/build-cso.sh'),'utf8')).toContain('cso_sign_macos_artifact "$CSO_STAGE_LAUNCHER" 1'); - for (const name of ['lib/cso/images/gstack-cso-verifier', 'lib/cso/images/gstack-cso-preparation']) expect(ignore).toContain(name); - expect(setup).toContain('gstack-cso-launcher$_EXE" provision-images --setup-summary'); - expect(setup).toContain('anonymous exact-digest pulls'); - expect(setup).toContain('static audits remain available'); - // Host skill installers already distribute bin and lib together. - expect(/for asset in bin lib browse review qa/.test(setup)).toBe(true); - }); -}); - -const EVALUATION_REF = `sha256:${'e'.repeat(64)}`; -const STAGING_RUN = '777'; -function dispatchedStatements(): any[] { - return committedImageBuildMatrix().include.map(row => ({ - schemaVersion: 1, helperAbi: 3, state: 'qualified', buildRevision: row.inputRevision, runtimeId: row.runtimeId, - stack: row.stack, platform: row.platform, versions: row.versions, sourceCommit: 'a'.repeat(40), - image: `ghcr.io/garrytan/gstack/cso-staging/${row.stack}-${row.arch}@sha256:${Bun.hash(row.runtimeId).toString(16).padStart(64, '0')}`, - checks: Object.fromEntries(requiredChecks(row.stack).map(key => [key, true])), - evaluationRef: EVALUATION_REF, - })); -} -function ingressStep(name: string): string { - const job = (Bun.YAML.parse(readFileSync(join(ROOT, '.github/workflows/cso-runtime-qualification.yml'), 'utf8')) as any).jobs.qualify; - return (job.steps.find((step: any) => step.name === name).run as string).replaceAll('bun run scripts/', `bun run ${quote(ROOT)}/scripts/`); -} -function ingressFixture() { - const dir = mkdtempSync(join(tmpdir(), 'cso-ingress-')); temps.push(dir); - const bin = join(dir, 'bin'), work = join(dir, 'work'), fake = join(dir, 'gh-fixtures'); - for (const path of [bin, work, fake]) mkdirSync(path); - writeFileSync(join(bin, 'gh'), [ - '#!/bin/sh', - 'set -eu', - 'case "$1 $2" in', - ' "attestation verify")', - ' case "$*" in', - ' *https://slsa.dev/provenance/v1*) jq --arg image "$3" \'.[0].verificationResult.statement.subject[0].name = $image\' "$FAKE_GH/provenance.json" ;;', - ' *) jq -n --arg image "$3" \'[{verificationResult:{statement:{predicateType:"https://spdx.dev/Document/v2.3",subject:[{name:$image}]}}}]\' ;;', - ' esac ;;', - ' "api --paginate") cat "$FAKE_GH/jobs.json" ;;', - ' "run download") while [ "$#" -gt 0 ]; do [ "$1" != --dir ] || dir=$2; shift; done; mkdir -p "$dir"; cp "$FAKE_GH/requalification.json" "$dir/" ;;', - ' "api repos/"*) cat "$FAKE_GH/run.json" ;;', - ' *) echo "unexpected gh $*" >&2; exit 2 ;;', - 'esac', - '', - ].join('\n')); - chmodSync(join(bin, 'gh'), 0o755); - const invocation = `https://github.com/garrytan/gstack/actions/runs/${STAGING_RUN}/attempts/1`; - writeFileSync(join(fake, 'provenance.json'), JSON.stringify([{ verificationResult: { - signature: { certificate: { runInvocationURI: invocation } }, - statement: { predicateType: 'https://slsa.dev/provenance/v1', subject: [{ name: '' }], predicate: { runDetails: { metadata: { invocationId: invocation } } } }, - } }])); - const run = (overrides: Record = {}) => writeFileSync(join(fake, 'run.json'), JSON.stringify({ - id: Number(STAGING_RUN), path: '.github/workflows/cso-runtime-images.yml', event: 'workflow_dispatch', head_branch: 'main', - head_sha: 'a'.repeat(40), status: 'completed', conclusion: 'success', - repository: { full_name: 'garrytan/gstack' }, head_repository: { full_name: 'garrytan/gstack' }, ...overrides, - })); - const jobs = (conclusion = 'success') => { - const list = committedImageBuildMatrix().include.map((row, index) => ({ - name: `qualify-native ${row.runtimeId}`, run_id: Number(STAGING_RUN), status: 'completed', conclusion: index === 0 ? conclusion : 'success', - })); - writeFileSync(join(fake, 'jobs.json'), JSON.stringify([{ total_count: list.length, jobs: list }])); - }; - run(); jobs(); - writeFileSync(join(fake, 'requalification.json'), JSON.stringify(CURRENT_TRIGGERS)); - const event = join(dir, 'event.json'); - writeFileSync(event, JSON.stringify({ action: 'cso-runtime-qualified', client_payload: { evaluationRef: EVALUATION_REF, statements: dispatchedStatements() } })); - const env = { ...process.env, PATH: `${bin}:${dirname(process.execPath)}:${process.env.PATH}`, FAKE_GH: fake, GITHUB_EVENT_PATH: event, - GITHUB_REPOSITORY: 'garrytan/gstack', GITHUB_RUN_ID: '555' }; - const step = (name: string) => runBashScript(ingressStep(name), { cwd: work, env, timeout: 60_000 }); - return { work, run, jobs, step }; -} - -describe('CSO runtime staging gates', () => { - test('runtime workflow shell blocks parse after GitHub expressions are substituted', () => { - for (const relative of [ - '.github/workflows/cso-runtime-images.yml', - '.github/workflows/cso-runtime-qualification.yml', - '.github/workflows/cso-runtime-promote.yml', - '.github/workflows/cso-scanner-images.yml', - ]) { - const raw = readFileSync(join(ROOT, relative), 'utf8'); - const workflow = Bun.YAML.parse(raw) as any; - expect(raw).not.toMatch(/\s\+\s+--(?:no-|name|arg|evidence|output|security)/); - for (const job of Object.values(workflow.jobs) as any[]) for (const step of job.steps ?? []) { - if (typeof step.run !== 'string') continue; - const script = step.run.replace(/\$\{\{[\s\S]*?\}\}/g, 'GH_EXPR'); - const parsed = spawnSync('/bin/bash', ['-n'], { input: script, encoding: 'utf8', timeout: 30_000 }); - expect(parsed.status, `${relative}: ${step.name ?? step.run}\n${parsed.stderr}`).toBe(0); - } - } - }); - - test('reviewed inputs produce every application and database stack on each native Linux architecture', () => { - const matrix = imageBuildMatrix(reviewedInputs()); - expect(matrix.include).toHaveLength(10); - for (const stack of ['node', 'bun', 'python', 'rails', 'postgresql']) { - const rows = matrix.include.filter(r => r.stack === stack); - expect(rows.map(r => r.platform)).toEqual(['linux/amd64', 'linux/arm64']); - expect(rows.map(r => r.runner)).toEqual(['ubuntu-24.04', 'ubuntu-24.04-arm']); - } - }); - - test('unreviewed or incomplete inputs cannot silently publish a partial matrix', () => { - const inputs = reviewedInputs(); inputs.state = 'pending'; - expect(() => imageBuildMatrix(inputs)).toThrow('MISSING_REVIEWED_BUILD_INPUTS'); - inputs.state = 'reviewed'; inputs.profiles.pop(); - expect(() => imageBuildMatrix(inputs)).toThrow('INCOMPLETE_STACK_MATRIX'); - }); - - test.each(['node:latest', 'docker.io/library/node:24', CREDENTIAL_IMAGE, 'docker.io/library/node@sha256:bad', 'docker.io/library/node@sha256:' + 'A'.repeat(64), 'docker.io/library/node@sha256:' + 'a'.repeat(64) + '\nBAD=value'])('untrusted base input %s cannot enter the workflow matrix', image => { - const inputs = reviewedInputs(); inputs.profiles[0].baseImages['linux/amd64'] = image; - expect(() => imageBuildMatrix(inputs)).toThrow('UNPINNED_BASE_IMAGE'); - }); - - test('SBOM generator and toolchain inputs must be pinned too', () => { - const inputs = reviewedInputs(); inputs.sbomGenerator.images['linux/amd64'] = 'docker.io/tool/sbom:latest'; - expect(() => imageBuildMatrix(inputs)).toThrow('UNPINNED_SBOM_GENERATOR'); - const versions = reviewedInputs(); versions.profiles[0].versions.node = '^24'; - expect(() => imageBuildMatrix(versions)).toThrow('UNPINNED_TOOL_VERSION'); - }); - - test.each(['docker.io/tool/sbom:1', 'docker.io/tool/sbom:1.24', 'docker.io/tool/sbom:1.24-slim', 'docker.io/tool/sbom:latest', 'docker.io/tool/sbom:stable'])('floating source tag %s cannot pin a reviewed family', source => { - const sbom = reviewedInputs(); sbom.sbomGenerator.source = source; - expect(() => imageBuildMatrix(sbom)).toThrow('FLOATING_SBOM_GENERATOR_SOURCE'); - const base = reviewedInputs(); base.profiles[0].source = source.replace('docker.io/tool/sbom', 'docker.io/library/node'); - expect(() => imageBuildMatrix(base)).toThrow('FLOATING_BASE_SOURCE'); - }); - - test('PostgreSQL alone may name a two-part release, which is exact for it', () => { - const postgres = reviewedInputs(); postgres.profiles[4].source = 'docker.io/library/postgres:17-bookworm'; - expect(() => imageBuildMatrix(postgres)).toThrow('FLOATING_BASE_SOURCE'); - const python = reviewedInputs(); python.profiles[2].source = 'docker.io/library/python:3.13-slim-bookworm'; - expect(() => imageBuildMatrix(python)).toThrow('FLOATING_BASE_SOURCE'); - expect(imageBuildMatrix(reviewedInputs()).include.find(row => row.stack === 'postgresql')?.baseSource).toBe('docker.io/library/postgres:17.2'); - }); - - test('the committed build inputs name release tags for every source', () => { - expect(buildInputs.sbomGenerator.source).toBe('docker.io/docker/scout-sbom-indexer:1.24.0'); - expect(committedImageBuildMatrix().include).toHaveLength(10); - }); - - test('duplicate stacks and missing Python uv images fail precisely', () => { - const duplicate = reviewedInputs(); duplicate.profiles[1].stack = 'node'; - expect(() => imageBuildMatrix(duplicate)).toThrow('INVALID_STACK'); - const python = reviewedInputs(); python.profiles[2].uvImages!['linux/arm64'] = ''; - expect(() => imageBuildMatrix(python)).toThrow('UNPINNED_UV_IMAGE'); - }); - - test('dedicated Docker CI is secretless and mandatory when its prerequisites are missing', () => { - const raw = readFileSync(join(ROOT, '.github/workflows/free-tests.yml'), 'utf8'); - const workflow = Bun.YAML.parse(raw) as any; - const job = workflow.jobs['cso-docker-integration']; - expect(job).toBeTruthy(); - const gate = job.steps.find((step: any) => step.run?.trim() === 'bun test --max-concurrency 1 test/cso-docker-integration.test.ts'); - expect(gate.env.GSTACK_CSO_DOCKER_TESTS).toBe('1'); - expect(JSON.stringify(job)).not.toContain('secrets.'); - expect(raw.match(/secrets\s*(?:\.|\[)\s*['"]?[A-Za-z0-9_-]*|toJSON\(\s*secrets\b/gi)).toEqual(['secrets.TRUNK_API_TOKEN']); - expect(job.steps.map((s: any) => s.run ?? '').join('\n')).toContain('docker --host unix:///var/run/docker.sock info'); - expect(job['continue-on-error']).not.toBe(true); - expect(gate['continue-on-error']).not.toBe(true); - const required = workflow.jobs['free-tests']; - expect(required.if).toBe('always()'); - expect(required.needs).toEqual(['reuse', 'docs-scope', 'docs-lane', 'free-suite', 'typecheck', 'quick-bun-default', 'cso-macos-launcher', 'macos-named-regressions', 'cso-windows-launcher', 'cso-docker-integration']); - expect(job.needs).toEqual(['reuse', 'docs-scope']); - expect(job.if).toBe("${{ !cancelled() && (needs.reuse.result != 'success' || needs.reuse.outputs.reused != 'true') && !(needs.docs-scope.result == 'success' && needs.docs-scope.outputs.docs_only == 'true') }}"); - const route = required.steps[0]; - expect(route.id).toBe('route'); - expect(route.env.REUSE_RESULT).toBe('${{ needs.reuse.result }}'); - expect(route.run).toContain('if [ "$REUSE_RESULT" != success ] || [ "$REUSED" != true ]; then'); - const strict = required.steps.find((step: any) => step.run?.includes('test "$CSO_DOCKER_RESULT" = success')); - expect(strict.env.CSO_DOCKER_RESULT).toBe('${{ needs.cso-docker-integration.result }}'); - expect(strict.if).toBe("steps.route.outputs.skip != 'true'"); - expect(required.steps.indexOf(strict)).toBe(1); - for (const current of Object.values(workflow.jobs) as any[]) for (const step of current.steps) { - if (step.uses?.startsWith('oven-sh/setup-bun')) expect(step.uses).toBe('oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6'); - } - }); - - test('macOS runs the actual signed launcher gate on a native hosted runner', () => { - const raw = readFileSync(join(ROOT, '.github/workflows/free-tests.yml'), 'utf8'); - const workflow = Bun.YAML.parse(raw) as any; - const job = workflow.jobs['cso-macos-launcher']; - expect(job['runs-on']).toBe('macos-latest'); - expect(job.steps.some((step: any) => step.run === 'bun run build:cso')).toBe(true); - const gate = job.steps.find((step: any) => step.run === 'bun run test:cso:macos'); - expect(gate.env.GSTACK_CSO_MACOS_TESTS).toBe('1'); - expect(gate['continue-on-error']).not.toBe(true); - }); - - test('native macOS ownership and settings regressions are required by the free gate', () => { - const workflow = Bun.YAML.parse(readFileSync(join(ROOT, '.github/workflows/free-tests.yml'), 'utf8')) as any; - const job = workflow.jobs['cso-macos-launcher']; - const gate = job.steps.find((step: any) => step.name === 'Exercise native agent ownership and linked settings'); - expect(job['runs-on']).toBe('macos-latest'); - expect(gate.env.TMPDIR).toBe('/tmp'); - expect(gate.run).toContain('test -f "$file"'); - expect(gate.run).toContain('bun test "${files[@]}"'); - for (const file of [ - 'browse/test/terminal-agent-lifecycle.test.ts', - 'browse/test/terminal-agent-native-observation.test.ts', - 'browse/test/terminal-agent-watchdog.test.ts', - 'browse/test/server-embedder-terminal-port.test.ts', - 'browse/test/server-factory.test.ts', - 'test/gstack-settings-hook-symlink.test.ts', - 'test/gstack-settings-hook-schema-aware.test.ts', - ]) expect(gate.run).toContain(file); - expect(gate['continue-on-error']).not.toBe(true); - expect(workflow.jobs['free-tests'].needs).toContain('cso-macos-launcher'); - }); - - test('publication requires manual protected-main review, signed evidence, and native containment checks', () => { - const raw = readFileSync(join(ROOT, '.github/workflows/cso-runtime-images.yml'), 'utf8'); - const workflow = Bun.YAML.parse(raw) as any; - expect(Object.keys(workflow.on)).toEqual(['pull_request', 'workflow_dispatch']); - expect(workflow.jobs['validate-native'].if).toContain("github.event_name == 'pull_request'"); - expect(workflow.jobs['validate-native'].permissions).toEqual({ contents: 'read' }); - expect(workflow.jobs['validate-native'].steps.some((s: any) => s.run?.includes('cso-verify-runtime-base.ts'))).toBe(true); - expect(workflow.jobs['validate-native'].steps.some((s: any) => s.with?.push === false && s.with?.load === true)).toBe(true); - expect(workflow.jobs.stage.if).toContain("github.ref == 'refs/heads/main'"); - expect(workflow.jobs.stage.environment).toBe('cso-runtime-release'); - const steps = workflow.jobs.stage.steps; - expect(steps.some((s: any) => s.with?.provenance === 'mode=max')).toBe(true); - expect(steps.some((s: any) => s.with?.attests?.includes('generator=${{ matrix.sbomGeneratorImage }}'))).toBe(true); - expect(steps.filter((s: any) => s.uses?.startsWith('actions/attest@'))).toHaveLength(2); - expect(raw).toContain('--source-digest "$GITHUB_SHA"'); - expect(raw).toContain('--cert-identity "$signer"'); - expect(raw).toContain('--predicate-type https://slsa.dev/provenance/v1'); - expect(raw).toContain('--predicate-type https://spdx.dev/Document/v2.3'); - expect(raw).toContain('scripts/cso-public-ghcr.ts verify'); - expect(raw).toContain('--repository "$GITHUB_REPOSITORY" --output public-image.json'); - expect(raw).toContain('sha256sum public-image.json'); - expect(raw).toContain('GSTACK_CSO_TEST_IMAGE:'); - expect(raw).toContain('GSTACK_CSO_TEST_STACK:'); - expect(raw).toContain('bun run test:cso:docker'); - expect(workflow.jobs['qualify-native'].needs).toEqual(['reviewed-inputs', 'stage']); - expect(raw).toContain('cso-staged-postgresql-${{ matrix.arch }}'); - expect(raw).toContain('GSTACK_CSO_TEST_POSTGRES_IMAGE'); - const qualify = workflow.jobs['qualify-native']; - expect(qualify.name).toBe('qualify-native ${{ matrix.runtimeId }}'); - expect(raw).not.toMatch(/Passed:\s*true/); - const tested = qualify.steps.findIndex((s: any) => s.run?.includes('bun run test:cso:docker --reporter=junit --reporter-outfile=native-tests.junit.xml')); - const derived = qualify.steps.findIndex((s: any) => s.run?.includes('scripts/cso-native-evidence.ts --stack "$CSO_STACK" --platform "$CSO_PLATFORM"')); - expect(tested).toBeGreaterThanOrEqual(0); - expect(derived).toBe(tested + 1); - expect(qualify.steps[derived].run).toContain('--junit native-tests.junit.xml --staged staged-application/staged-image.json'); - expect(qualify.steps[derived + 1].with.path.split('\n').filter(Boolean)).toEqual(['qualification-evidence.json', 'native-tests.junit.xml']); - expect(raw).not.toContain('setup-qemu'); - expect(raw).not.toContain('git push'); - expect(raw).not.toContain('gh pr create'); - expect(raw).not.toContain('contents: write'); - const bunDockerfile=readFileSync(join(ROOT,'lib/cso/images/bun.Dockerfile'),'utf8'); - const bunPolicy=readFileSync(join(ROOT,'lib/cso/images/bun-no-auto-install.toml'),'utf8'); - expect(bunDockerfile).toContain('bun-no-auto-install.toml /opt/cso/no-auto-install.toml'); - expect(bunPolicy).toBe('[install]\nauto = "disable"\n'); - for (const job of Object.values(workflow.jobs) as any[]) for (const step of job.steps) { - if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/); - if (step.uses?.startsWith('oven-sh/setup-bun')) expect(step.uses).toBe('oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6'); - } - }); - - test('catalog promotion authenticates one successful main run and opens an exact attested candidate PR', () => { - const raw = readFileSync(join(ROOT, '.github/workflows/cso-runtime-promote.yml'), 'utf8'); - const workflow = Bun.YAML.parse(raw) as any; - const job = workflow.jobs.propose; - expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch']); - expect(job.if).toContain("github.ref == 'refs/heads/main'"); - expect(job.environment).toBe('cso-runtime-release'); - expect(job.permissions).toMatchObject({ contents: 'write', 'pull-requests': 'write', actions: 'write', packages: 'read', 'id-token': 'write', attestations: 'write' }); - expect(raw).toContain('.head_branch == "main"'); - expect(raw).toContain('.path == ".github/workflows/cso-runtime-qualification.yml"'); - expect(raw).toContain('.event == "repository_dispatch"'); - expect(raw).toContain('--name cso-qualified-runtime-statements'); - expect(raw).toContain('scripts/cso-runtime-promotion.ts'); - expect(raw).toContain('runtime-catalog.candidate.json'); - expect(raw).toContain('subject-path: runtime-catalog.candidate.json'); - expect(raw).toContain('gh attestation verify runtime-catalog.candidate.json'); - expect(raw).toContain('--cert-identity "$signer"'); - expect(raw).toContain('--source-digest "$GITHUB_SHA"'); - expect(raw).toContain('cso-attestation-evidence.ts digest'); - expect(raw).toContain('candidate-attestation-evidence.json'); - expect(raw).toContain('scripts/cso-public-ghcr.ts verify'); - expect(raw).toContain('--remove-after'); - expect(raw).toContain('cso-runtime-promotion.ts validate-transition'); - expect(raw).toContain('cmp runtime-catalog.candidate.json committed-runtime-catalog.json'); - expect(raw).toContain('git push'); - expect(raw).toContain('gh pr create --base main'); - expect(raw).toContain('branch="cso-runtime-catalog-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"'); - expect(raw).not.toContain('branch="cso-runtime-catalog-$GITHUB_RUN_ID"'); - const attested = raw.indexOf('subject-path: runtime-catalog.candidate.json'); - const publicPull = raw.indexOf('scripts/cso-public-ghcr.ts verify'); - const verified = raw.indexOf('gh attestation verify runtime-catalog.candidate.json'); - const committed = raw.indexOf('git add lib/cso/runtime-catalog.json'); - expect(publicPull).toBeGreaterThanOrEqual(0); - expect(attested).toBeGreaterThan(publicPull); - expect(verified).toBeGreaterThan(attested); - expect(committed).toBeGreaterThan(verified); - for (const step of job.steps) if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/); - }); - - test('catalog promotion PRs dispatch the required free-tests check on the pushed branch', () => { - const freeTests = Bun.YAML.parse(readFileSync(join(ROOT, '.github/workflows/free-tests.yml'), 'utf8')) as any; - expect(Object.keys(freeTests.on)).toContain('workflow_dispatch'); - expect(freeTests.jobs['free-tests'].if).toBe('always()'); - expect(freeTests.jobs['free-tests'].name).toBeUndefined(); - for (const [relative, jobName] of [ - ['.github/workflows/cso-runtime-promote.yml', 'propose'], - ['.github/workflows/cso-scanner-images.yml', 'promote-catalog'], - ]) { - const job = (Bun.YAML.parse(readFileSync(join(ROOT, relative), 'utf8')) as any).jobs[jobName]; - expect(job.permissions.actions, relative).toBe('write'); - const script = job.steps.find((step: any) => step.run?.includes('gh pr create')).run as string; - const pushed = script.indexOf('git push --set-upstream origin "$branch"'); - const dispatched = script.indexOf('gh workflow run free-tests.yml --repo "$GITHUB_REPOSITORY" --ref "$branch"'); - expect(pushed, relative).toBeGreaterThan(0); - expect(dispatched, relative).toBeGreaterThan(pushed); - expect(script.indexOf('gh pr create'), relative).toBeGreaterThan(dispatched); - } - }); - - test('private qualification enters only through an actor-restricted protected environment and re-verifies staged attestations', () => { - const raw = readFileSync(join(ROOT, '.github/workflows/cso-runtime-qualification.yml'), 'utf8'); - const workflow = Bun.YAML.parse(raw) as any; - const job = workflow.jobs.qualify; - expect(Object.keys(workflow.on)).toEqual(['repository_dispatch']); - expect(job.environment).toBe('cso-runtime-release'); - expect(job.permissions).toEqual({ contents: 'read', packages: 'read', attestations: 'read', actions: 'read' }); - expect(job.needs).toBe('dispatch-summary'); - const summary = workflow.jobs['dispatch-summary']; - expect(summary.permissions).toEqual({}); - expect(summary.environment).toBeUndefined(); - expect(summary.steps.every((step: any) => !step.uses)).toBe(true); - expect(raw).toContain('test "$GITHUB_ACTOR" = "$CSO_QUALIFICATION_ACTOR"'); - expect(raw).toContain('.client_payload.statements | type == "array" and length == 10'); - expect(raw).not.toContain('^ghcr.io/'); - expect(raw).toContain('^ghcr\\\\.io/garrytan/gstack/cso-staging/'); - const names = job.steps.map((step: any) => step.name); - const attested = names.indexOf('Verify each staged image attestation and normalize qualification statements'); - const staging = names.indexOf('Require one successful protected-main staging run with every native gate passed'); - const contract = names.indexOf('Enforce the complete release contract before retaining evidence'); - expect(attested).toBeGreaterThan(0); - expect(staging).toBe(attested + 1); - expect(contract).toBe(staging + 1); - expect(job.steps[staging].run).toContain('gh api --paginate --slurp "repos/$GITHUB_REPOSITORY/actions/runs/$run_id/jobs?filter=latest&per_page=100"'); - expect(job.steps.at(-1).with.path).toContain('staging-run-evidence'); - expect(raw).toContain('--cert-identity "$signer"'); - expect(raw).toContain('--source-digest "$source_commit"'); - expect(raw).toContain('--deny-self-hosted-runners'); - expect(raw).toContain('Recheck public visibility and anonymous pulls for every qualified digest'); - expect(raw).toContain('scripts/cso-public-ghcr.ts verify'); - expect(raw).toContain('public-image-evidence'); - expect(raw).toContain('--remove-after'); - expect(raw).toContain('scripts/cso-runtime-promotion.ts'); - expect(raw).toContain('name: cso-qualified-runtime-statements'); - expect(raw).not.toContain('contents: write'); - for (const step of job.steps) if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/); - }); - - test('staged images enter the daemon only after signed evidence checks and before no-pull execution', () => { - const workflow = Bun.YAML.parse(readFileSync(join(ROOT, '.github/workflows/cso-runtime-images.yml'), 'utf8')) as any; - const steps = workflow.jobs.stage.steps; - const verified = steps.findIndex((s: any) => s.run?.includes('--predicate-type https://spdx.dev/Document/v2.3')); - const pulled = steps.findIndex((s: any) => s.run?.includes('scripts/cso-public-ghcr.ts verify')); - const executed = steps.findIndex((s: any) => s.run?.includes('test/cso-docker-integration.test.ts')); - expect(verified).toBeGreaterThanOrEqual(0); - expect(pulled).toBeGreaterThan(verified); - expect(executed).toBeGreaterThan(pulled); - expect(steps[pulled].env.CSO_IMAGE).toBe('${{ steps.image.outputs.name }}@${{ steps.build.outputs.digest }}'); - expect(steps[pulled].env.GH_TOKEN).toBe('${{ github.token }}'); - expect(steps[pulled].run).toContain('--image "$CSO_IMAGE" --platform "$CSO_PLATFORM"'); - expect(steps[pulled].run).toContain('--repository "$GITHUB_REPOSITORY" --output public-image.json'); - expect(steps[pulled]['continue-on-error']).not.toBe(true); - const qualify=workflow.jobs['qualify-native']; - const loaded=qualify.steps.findIndex((s:any)=>s.run?.includes('GSTACK_CSO_TEST_IMAGE')); - const cold=qualify.steps.findIndex((s:any)=>s.run?.includes('bun run test:cso:docker')); - expect(loaded).toBeGreaterThanOrEqual(0);expect(cold).toBeGreaterThan(loaded); - expect(qualify.needs).toEqual(['reviewed-inputs','stage']); - expect(qualify.steps.some((s:any)=>s.uses?.startsWith('docker/login-action@'))).toBe(false); - expect(qualify.steps[loaded].run).toContain('scripts/cso-public-ghcr.ts verify'); - expect(qualify.steps[loaded].env.GH_TOKEN).toBe('${{ github.token }}'); - }); - - test('the ingress payload gate accepts an optional evaluation reference and summarizes it before approval', () => { - const script = (Bun.YAML.parse(readFileSync(join(ROOT, '.github/workflows/cso-runtime-qualification.yml'), 'utf8')) as any).jobs['dispatch-summary'].steps[0].run; - const dir = mkdtempSync(join(tmpdir(), 'cso-dispatch-summary-')); temps.push(dir); - const event = join(dir, 'event.json'), summary = join(dir, 'summary.md'); - const dispatch = (payload: unknown) => { - writeFileSync(event, JSON.stringify({ action: 'cso-runtime-qualified', client_payload: payload })); - writeFileSync(summary, ''); - const result = runBashScript(script, { cwd: dir, env: { ...process.env, GITHUB_EVENT_PATH: event, GITHUB_STEP_SUMMARY: summary }, timeout: 30_000 }); - return { status: result.status, summary: readFileSync(summary, 'utf8') }; - }; - const statements = dispatchedStatements(); - expect(dispatch({ statements }).summary).toContain('- evaluationRef: `none`'); - const accepted = dispatch({ evaluationRef: EVALUATION_REF, statements }); - expect(accepted.status).toBe(0); - expect(accepted.summary).toContain(`- evaluationRef: \`${EVALUATION_REF}\``); - expect(accepted.summary).toContain(`- sourceCommit: \`${'a'.repeat(40)}\``); - for (const statement of statements) expect(accepted.summary).toContain(`| \`${statement.runtimeId}\` | \`${statement.image}\` |`); - const rejected = (payload: unknown) => expect(dispatch(payload).status).not.toBe(0); - rejected({ evaluationRef: 'sha256:abc', statements }); - rejected({ evaluationRef: EVALUATION_REF.toUpperCase(), statements }); - rejected({ evaluationRef: null, statements }); - rejected({ evaluationRef: EVALUATION_REF, statements, finding: 'held-out detail' }); - rejected({ statements: statements.slice(1) }); - rejected({ statements: statements.map((item, index) => index ? item : { ...item, sourceCommit: 'b'.repeat(40) }) }); - rejected({ statements: statements.map((item, index) => index ? item : { ...item, image: item.image.replace('ghcr.io', 'ghcrxio') }) }); - rejected({ statements: statements.map((item, index) => index ? item : { ...item, runtimeId: 'node`|injected' }) }); - }); - - test('the protected ingress binds verified statements to one successful staging run and never carries the evaluation reference', () => { - const fixture = ingressFixture(); - const normalized = fixture.step('Verify each staged image attestation and normalize qualification statements'); - expect(normalized.status, normalized.stderr).toBe(0); - const staging = fixture.step('Require one successful protected-main staging run with every native gate passed'); - expect(staging.status, staging.stderr).toBe(0); - expect(staging.stdout).toContain('STAGING RUN VERIFIED'); - const contract = fixture.step('Enforce the complete release contract before retaining evidence'); - expect(contract.status, contract.stderr).toBe(0); - - const statements = committedImageBuildMatrix().include.map(row => - JSON.parse(readFileSync(join(fixture.work, 'qualification-evidence', row.runtimeId, 'qualified-runtime.json'), 'utf8'))); - for (const statement of statements) { - expect(statement).not.toHaveProperty('evaluationRef'); - expect(statement.workflow).toBe('https://github.com/garrytan/gstack/actions/runs/555'); - } - expect(JSON.parse(readFileSync(join(fixture.work, 'qualification-evidence', 'requalification.json'), 'utf8'))).toEqual(CURRENT_TRIGGERS); - const candidate = JSON.stringify(catalogPromotionCandidate(committedCatalog, buildInputs, statements, CURRENT_TRIGGERS)); - expect(candidate).not.toContain('evaluationRef'); - expect(candidate).not.toContain('e'.repeat(64)); - - for (const [mutate, error] of [ - [() => fixture.run({ conclusion: 'failure' }), 'STAGING_RUN_NOT_SUCCESSFUL'], - [() => fixture.jobs('failure'), 'STAGING_NATIVE_GATE_NOT_PASSED'], - ] as const) { - fixture.run(); fixture.jobs(); mutate(); - rmSync(join(fixture.work, 'staging-run-evidence'), { recursive: true, force: true }); - const rejected = fixture.step('Require one successful protected-main staging run with every native gate passed'); - expect(rejected.status).not.toBe(0); - expect(rejected.stderr).toContain(error); - } - }); -}); - -describe('CSO evaluation-only candidate builds', () => { - const revision = `cso-eval-123456-${'a'.repeat(12)}`; - const sha = (path: string) => createHash('sha256').update(readFileSync(path)).digest('hex'); - function candidateFixture(catalogRevision = revision) { - const dir = buildFixture(), outside = mkdtempSync(join(tmpdir(), 'gstack-cso-eval-out-')); temps.push(outside); - mkdirSync(join(dir, 'test/helpers'), { recursive: true }); - const catalog = join(outside, 'candidate.json'); - writeFileSync(catalog, JSON.stringify({ schemaVersion: 1, revision: catalogRevision, runtimes: [] }, null, 2) + '\n'); - return { dir, outside, catalog, output: join(outside, 'unit') }; - } - const candidateBuild = (dir: string, catalog: string, output: string, extra = '') => - runBashScript(`${fakeBuildCommand(dir, extra)} --evaluation-candidate ${quote(catalog)} --output ${quote(output)}`, { timeout: 20_000 }); - - test.skipIf(process.platform === 'win32')('builds a marked five-artifact producer unit outside the checkout without touching bin/', () => { - const { dir, outside, catalog, output } = candidateFixture(); - const result = candidateBuild(dir, catalog, output); - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout.trim())).toEqual({ output, revision, evaluationOnly: true }); - expect(readdirSync(output).sort()).toEqual(['.gstack-cso-evaluation', '.gstack-cso-generation', 'cso-eval-producer', 'gstack-cso-core', 'gstack-cso-launcher', 'gstack-cso-watchdog']); - const marker = JSON.parse(readFileSync(join(output, '.gstack-cso-evaluation'), 'utf8')); - expect(marker).toEqual({ schemaVersion: 1, evaluationOnly: true, runtimeCatalogRevision: revision, runtimeCatalogSha256: sha(catalog), coreSha256: sha(join(output, 'gstack-cso-core')) }); - expect(readFileSync(join(output, '.gstack-cso-generation'), 'utf8')).toBe(`${marker.coreSha256}\n`); - expect(readdirSync(join(dir, 'bin'))).toEqual([]); - expect(readdirSync(outside).sort()).toEqual(['candidate.json', 'unit']); - const args = readFileSync(join(dir, 'compiler.log'), 'utf8').trim().split('\n'); - const check = args.indexOf('check-evaluation'); - expect(check).toBeGreaterThan(0); expect(args[check + 1]).toBe('lib/cso/runtime-catalog.json'); - expect(check).toBeLessThan(args.indexOf('lib/cso/cli.ts')); - expect(args).toContain('scripts/cso-eval-producer.ts'); - expect(args.filter(arg => arg === '--no-compile-autoload-package-json')).toHaveLength(2); - }); - - test.skipIf(process.platform === 'win32')('refuses unmarked catalogs, in-checkout or existing outputs, and leaves nothing on a failed check', () => { - const plain = candidateFixture('cso-v3-123456-aaaaaaaaaaaa'); - expect(candidateBuild(plain.dir, plain.catalog, plain.output).status).toBe(65); - const inside = candidateFixture(); - const insideResult = candidateBuild(inside.dir, inside.catalog, join(inside.dir, 'unit')); - expect(insideResult.status).toBe(73); expect(existsSync(join(inside.dir, 'unit'))).toBe(false); - const existing = candidateFixture(); mkdirSync(existing.output); - expect(candidateBuild(existing.dir, existing.catalog, existing.output).status).toBe(73); - const failed = candidateFixture(); - expect(candidateBuild(failed.dir, failed.catalog, failed.output, 'CSO_FAIL_COMPILER_N=1').status).toBe(42); - expect(readdirSync(failed.outside)).toEqual(['candidate.json']); - }); - - test.skipIf(process.platform === 'win32')('distribution builds refuse an evaluation catalog in the source tree', () => { - const dir = buildFixture(); - writeFileSync(join(dir, 'lib/cso/runtime-catalog.json'), JSON.stringify({ revision }, null, 2)); - const result = fakeBuild(dir); - expect(result.status).toBe(65); expect(result.stderr).toContain('evaluation-only catalog'); - expect(existsSync(join(dir, 'compiler.log'))).toBe(false); - }); - - test('the candidate gate rejects the committed release catalog', () => { - const result = spawnSync(process.execPath, ['scripts/cso-runtime-promotion.ts', 'check-evaluation', 'lib/cso/runtime-catalog.json'], { cwd: ROOT, encoding: 'utf8', timeout: 30_000 }); - expect(result.status).toBe(1); expect(result.stderr).toContain('NOT_AN_EVALUATION_CATALOG'); - expect(String((committedCatalog as { revision: string }).revision).startsWith('cso-eval-')).toBe(false); - }); - - test('setup refuses a marked or self-reporting evaluation helper', () => { - const setup = readFileSync(join(ROOT, 'setup'), 'utf8'); - expect(setup).toContain('[ -e "$SOURCE_GSTACK_DIR/bin/.gstack-cso-evaluation" ]'); - expect(setup).toContain(`--version 2>/dev/null | grep -q '"evaluationOnly": *true'`); - expect(setup.indexOf('bin/ holds an evaluation-only CSO helper')).toBeLessThan(setup.indexOf('provision-images --setup-summary')); - }); -}); diff --git a/test/cso-docker-argv0.test.ts b/test/cso-docker-argv0.test.ts deleted file mode 100644 index 3e66d7297..000000000 --- a/test/cso-docker-argv0.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import { spawn, spawnSync } from 'node:child_process'; -import * as fs from 'node:fs'; -import * as net from 'node:net'; -import * as os from 'node:os'; -import { join, resolve } from 'node:path'; -import { dockerExactImagePresent, runDocker } from '../lib/cso/docker'; -import { childEnvironment, runProcess } from '../lib/cso/process'; - -// OrbStack installs docker as a symlink to a multicall binary that dispatches -// on argv[0]; the CSO resolves the symlink, so it must still pass "docker" as -// argv[0]. A #! script never sees argv[0], so the fake is compiled C. -const FAKE_MULTICALL = String.raw` -#include -#include -int main(int argc, char **argv) { - const char *slash = strrchr(argv[0], '/'); - const char *name = slash ? slash + 1 : argv[0]; - if (strcmp(name, "docker") != 0) { - fprintf(stderr, "unsupported argv0 \"%s\"\n", name); - return 127; - } - FILE *log = fopen(LOG_PATH, "a"); - if (log) { - for (int i = 1; i < argc; i++) fprintf(log, "%s%s", i > 1 ? " " : "", argv[i]); - fputc('\n', log); - fclose(log); - } - if (argc >= 3 && strcmp(argv[1], "context") == 0 && strcmp(argv[2], "show") == 0) { - puts("orbstack"); - return 0; - } - if (argc >= 3 && strcmp(argv[1], "image") == 0 && strcmp(argv[2], "inspect") == 0) { - printf("{\"Os\":\"linux\",\"Architecture\":\"amd64\",\"Id\":\"sha256:%064d\",\"RepoDigests\":[\"%s\"],\"Config\":{\"Entrypoint\":[\"/opt/cso/entrypoint\"]}}\n", 0, argv[argc - 1]); - return 0; - } - for (int i = 1; i < argc; i++) - if (strcmp(argv[i], "ps") == 0 && strncmp(argv[argc - 1], "id=", 3) == 0) puts(argv[argc - 1] + 3); - return 0; -} -`; - -describe.skipIf(process.platform === 'win32')('CSO Docker invocation through a multicall binary', () => { - let root = ''; - let multicall = ''; - let log = ''; - beforeAll(() => { - root = fs.realpathSync(fs.mkdtempSync(join(os.tmpdir(), 'cso-argv0-'))); - log = join(root, 'docker.log'); - const source = join(root, 'docker-tools.c'); - fs.writeFileSync(source, FAKE_MULTICALL); - multicall = join(root, 'docker-tools'); - const built = spawnSync('/usr/bin/cc', ['-std=c11', `-DLOG_PATH="${log}"`, source, '-o', multicall], { - encoding: 'utf8', - timeout: 30_000, - }); - expect(built.status).toBe(0); - fs.symlinkSync('docker-tools', join(root, 'docker')); - }); - afterAll(() => { - fs.rmSync(root, { recursive: true, force: true }); - }); - - test('the fake refuses its canonical name, as OrbStack does', async () => { - const r = await runProcess(multicall, ['context', 'show'], { - cwd: root, - env: childEnvironment(root), - raw: true, - }); - expect(r.code).toBe(127); - expect(r.stderr).toContain('unsupported argv0 "docker-tools"'); - }); - - test('runDocker invokes the canonical path as docker', async () => { - const r = await runDocker(multicall, ['context', 'show'], { - cwd: root, - env: childEnvironment(root), - raw: true, - }); - expect(r.code).toBe(0); - expect(r.stdout.trim()).toBe('orbstack'); - }); - - test('a production image probe admits an image through the multicall binary', async () => { - const socket = join(root, 'probe.sock'); - const server = net.createServer().listen(socket); - await new Promise((done) => server.once('listening', done)); - try { - const stat = fs.statSync(socket); - const image = `registry.example/cso/semgrep@sha256:${'b'.repeat(64)}`; - const present = await dockerExactImagePresent( - { uri: `unix://${socket}`, socket, executable: multicall, device: stat.dev, inode: stat.ino }, - root, - image, - 'linux/amd64', - ); - expect(present).toBe(true); - expect(fs.readFileSync(log, 'utf8')).toContain(`image inspect --format {{json .}} ${image}`); - } finally { - server.close(); - } - }); - - test('runProcess refuses an argv0 that is not a bare command name', async () => { - await expect( - runProcess(multicall, ['context', 'show'], { cwd: root, env: childEnvironment(root), argv0: '../docker' }), - ).rejects.toThrow('Invalid child argv0'); - }); - - test('the watchdog cleans up through the canonical multicall path', async () => { - const watchdog = join(root, 'watchdog'); - const built = spawnSync( - '/usr/bin/cc', - [ - '-std=c11', - '-D_POSIX_C_SOURCE=200809L', - '-O2', - resolve(import.meta.dir, '../lib/cso/watchdog.c'), - '-o', - watchdog, - ], - { encoding: 'utf8', timeout: 30_000 }, - ); - expect(built.status).toBe(0); - const run = join(root, 'run'); - const lease = join(run, 'lease'); - fs.mkdirSync(lease, { recursive: true }); - const token = 'c'.repeat(32); - fs.writeFileSync(join(lease, 'lease.json'), '{}'); - fs.writeFileSync(join(lease, 'lease.token'), `${token}\n`); - const id = 'a'.repeat(64); - fs.writeFileSync(join(run, 'resources.journal'), `container:${id}\n`, { mode: 0o600 }); - const socket = join(run, 'daemon.sock'); - const made = spawnSync('/usr/bin/python3', [ - '-c', - 'import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1]); s.close()', - socket, - ], { timeout: 30_000 }); - expect(made.status).toBe(0); - const stat = fs.lstatSync(socket); - const owner = spawn('/bin/sleep', ['0.2'], { stdio: 'ignore' }); - const child = spawn( - watchdog, - [ - '--owner', - String(owner.pid), - '--deadline', - String(Math.ceil((Date.now() + 10_000) / 1000)), - '--run-dir', - run, - '--docker', - multicall, - '--endpoint', - `unix://${socket}`, - '--socket-device', - String(stat.dev), - '--socket-inode', - String(stat.ino), - '--run-label', - 'argv0-label', - '--lease-path', - lease, - '--lease-token', - token, - ], - { stdio: 'ignore' }, - ); - expect(await new Promise((done) => child.on('close', done))).toBe(0); - expect(fs.readFileSync(log, 'utf8')).toContain(`rm --force --volumes ${id}`); - expect(fs.readFileSync(join(run, 'watchdog.event'), 'utf8')).toContain('cleanup complete'); - expect(fs.existsSync(lease)).toBe(false); - }); -}); diff --git a/test/cso-docker-integration.test.ts b/test/cso-docker-integration.test.ts deleted file mode 100644 index dfa8a6591..000000000 --- a/test/cso-docker-integration.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import { spawn, spawnSync } from 'node:child_process'; -import { DockerGroup, dockerEndpoint, dockerProbe } from '../lib/cso/docker';import { admit, release } from '../lib/cso/admission'; -const enabled=process.env.GSTACK_CSO_DOCKER_TESTS==='1',suite=enabled?describe:describe.skip;let root='',state='',image='',volumeImage='',endpoint:any,watchdog=''; -function exec(file:string,args:string[],env:Record={}){const r=spawnSync(file,args,{encoding:'utf8',env:{PATH:'/usr/local/bin:/usr/bin:/bin',HOME:root,GSTACK_HOME:state,DOCKER_HOST:'unix:///var/run/docker.sock',...env},timeout:120_000});if(r.status!==0)throw new Error(`${file} failed: ${r.stderr}`);return r.stdout.trim();} -beforeAll(()=>{if(!enabled)return;root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-docker-'));state=path.join(root,'state');process.env.GSTACK_HOME=state;watchdog=path.resolve(import.meta.dir,'../bin/gstack-cso-watchdog');if(!fs.existsSync(watchdog))throw new Error('GSTACK_CSO_DOCKER_TESTS=1 requires the compiled watchdog'); - const source=`#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \nstatic int blocked4(const char *ip,int port){int s=socket(AF_INET,SOCK_STREAM,0);struct sockaddr_in a={.sin_family=AF_INET,.sin_port=htons(port)};inet_pton(AF_INET,ip,&a.sin_addr);int r=connect(s,(void*)&a,sizeof a);close(s);return r!=0;}\nstatic int blocked6(void){int s=socket(AF_INET6,SOCK_STREAM,0);struct sockaddr_in6 a={.sin6_family=AF_INET6,.sin6_port=htons(443)};inet_pton(AF_INET6,"2606:4700:4700::1111",&a.sin6_addr);int r=connect(s,(void*)&a,sizeof a);close(s);return r!=0;}\nint main(int argc,char**argv){if(strstr(argv[0],"entrypoint")){if(argc<2||argv[1][0]!='/')return 64;execv(argv[1],argv+1);return 69;}if(strstr(argv[0],"sleep")){for(;;)sleep(3600);}if(strstr(argv[0],"reader")){char a[16]={0},b[16]={0};FILE*x=fopen("/source/source.txt","r"),*y=fopen("/policy/verification.json","r");if(!x||!y||!fgets(a,sizeof a,x)||!fgets(b,sizeof b,y))return 12;fclose(x);fclose(y);if(strcmp(a,"source\\n")||strcmp(b,"policy\\n"))return 13;puts("INPUTS_OK");return 0;}if(strstr(argv[0],"server")){int s=socket(AF_INET,SOCK_STREAM,0),c;struct sockaddr_in a={.sin_family=AF_INET,.sin_port=htons(34567),.sin_addr.s_addr=htonl(INADDR_LOOPBACK)};int one=1;setsockopt(s,SOL_SOCKET,SO_REUSEADDR,&one,sizeof one);if(bind(s,(void*)&a,sizeof a)||listen(s,2))return 2;for(;;){c=accept(s,0,0);if(c>=0){write(c,"ok",2);close(c);}}}int fd=open("/should-not-write",O_WRONLY|O_CREAT,0600);if(fd>=0)return 10;FILE*f=fopen("/proc/self/status","r");char line[256];int caps=1,nnp=0;while(f&&fgets(line,sizeof line,f)){if(!strncmp(line,"CapEff:",7))caps=strtoull(line+7,0,16)!=0;if(!strncmp(line,"NoNewPrivs:",11))nnp=atoi(line+11);}if(f)fclose(f);int s=socket(AF_INET,SOCK_STREAM,0);struct sockaddr_in a={.sin_family=AF_INET,.sin_port=htons(34567),.sin_addr.s_addr=htonl(INADDR_LOOPBACK)};int loop=connect(s,(void*)&a,sizeof a)==0;close(s);struct addrinfo*h=0;int dns=getaddrinfo("example.com",0,0,&h);if(h)freeaddrinfo(h);if(getuid()==0||caps||!nnp||!loop||!blocked4("8.8.8.8",443)||!blocked4("169.254.169.254",80)||!blocked6()||dns==0)return 11;puts("CONTAINMENT_OK");return 0;}\n`; - fs.writeFileSync(path.join(root,'probe.c'),source);exec('/usr/bin/cc',['-static','-O2',path.join(root,'probe.c'),'-o',path.join(root,'probe')]);exec('/usr/bin/cc',['-static','-O2',path.join(import.meta.dir,'fixtures/cso-http-smoke.c'),'-o',path.join(root,'http-server')]);fs.writeFileSync(path.join(root,'Dockerfile'),'FROM scratch\nCOPY probe /opt/cso/entrypoint\nCOPY probe /bin/sleep\nCOPY probe /server\nCOPY probe /client\nCOPY probe /reader\nCOPY probe /policy/.keep\nCOPY probe /source/.keep\nCOPY http-server /http-server\nUSER 10001:10001\nENTRYPOINT ["/opt/cso/entrypoint"]\n');const tag=`gstack-cso-fixture:${process.pid}`;exec('/usr/bin/docker',['--host','unix:///var/run/docker.sock','build','--network=none','--tag',tag,root]);image=exec('/usr/bin/docker',['--host','unix:///var/run/docker.sock','image','inspect','--format','{{.Id}}',tag]);fs.writeFileSync(path.join(root,'VolumeDockerfile'),`FROM ${tag}\nVOLUME ["/unbounded"]\n`);const volumeTag=`gstack-cso-volume-fixture:${process.pid}`;exec('/usr/bin/docker',['--host','unix:///var/run/docker.sock','build','--network=none','--file',path.join(root,'VolumeDockerfile'),'--tag',volumeTag,root]);volumeImage=exec('/usr/bin/docker',['--host','unix:///var/run/docker.sock','image','inspect','--format','{{.Id}}',volumeTag]);},300_000); -afterAll(()=>{if(root){for(const candidate of [volumeImage,image])try{if(candidate)spawnSync('/usr/bin/docker',['--host','unix:///var/run/docker.sock','image','rm','--force',candidate],{stdio:'ignore',timeout:30_000});}catch{}fs.rmSync(root,{recursive:true,force:true});}delete process.env.GSTACK_HOME;},120_000); - -suite('CSO Docker containment integration',()=>{ - test('hard fails when local daemon enforcement prerequisites are absent',async()=>{endpoint=await dockerEndpoint(root,{HOME:root,DOCKER_HOST:'unix:///var/run/docker.sock'});const info=await dockerProbe(endpoint,root);expect(info.security.some((x:string)=>x.includes('seccomp'))).toBe(true);}); - test('rejects image-declared writable volumes before container creation',async()=>{const dir=path.join(root,'volume-rejection');fs.mkdirSync(dir);const group=await DockerGroup.create(endpoint,`volume-${Date.now()}`,dir,Date.now()+60_000,image,watchdog);try{const before=exec('/usr/bin/docker',['--host',endpoint.uri,'volume','ls','--quiet']);await expect(group.createContainer({role:'app',image:volumeImage,command:['/bin/sleep','1']})).rejects.toThrow('declares writable volumes');expect(exec('/usr/bin/docker',['--host',endpoint.uri,'volume','ls','--quiet'])).toBe(before);}finally{await group.cleanup();}},120_000); - test('shares only loopback while denying egress, privileges, and daemon logs, and reads private source/policy mounts',async()=>{ - const dir=path.join(root,'group');fs.mkdirSync(dir); - const group=await DockerGroup.create(endpoint,`integration-${Date.now()}`,dir,Date.now()+60_000,image,watchdog); - let server='',client=''; - try{ - server=await group.createContainer({role:'app',image,command:['/server']});await group.start(server); - client=await group.createContainer({role:'verifier',image,command:['/client']}); - const result=await group.startAttach(client);expect(result).toEqual({code:0,output:'CONTAINMENT_OK\n'}); - const sourceDir=path.join(dir,'private-source'),policy=path.join(dir,'verification.json'); - fs.mkdirSync(sourceDir,{mode:0o700});fs.writeFileSync(path.join(sourceDir,'source.txt'),'source\n',{mode:0o600});fs.writeFileSync(policy,'policy\n',{mode:0o600}); - const reader=await group.createContainer({role:'browser',image,source:sourceDir,command:['/reader'],readonlyFiles:[{host:policy,container:'/policy/verification.json'}]}); - expect(await group.startAttach(reader)).toEqual({code:0,output:'INPUTS_OK\n'}); - const readerInspect=JSON.parse(exec('/usr/bin/docker',['--host',endpoint.uri,'inspect',reader]))[0]; - expect(readerInspect.HostConfig.Mounts).toHaveLength(2); - for(const [Source,Target] of [[sourceDir,'/source'],[policy,'/policy/verification.json']]){ - expect(readerInspect.HostConfig.Mounts.find((mount:any)=>mount.Target===Target)).toMatchObject({Type:'bind',Source,Target,ReadOnly:true,BindOptions:{NonRecursive:true}}); - expect(readerInspect.Mounts.find((mount:any)=>mount.Destination===Target)).toMatchObject({Type:'bind',Source,Destination:Target,RW:false}); - } - const raw=exec('/usr/bin/docker',['--host',endpoint.uri,'inspect',client]),inspect=JSON.parse(raw)[0]; - expect(inspect.HostConfig).toMatchObject({ReadonlyRootfs:true,NetworkMode:`container:${group.anchor}`,PidsLimit:32,ShmSize:8*1024*1024,LogConfig:{Type:'none',Config:{}}}); - expect(inspect.Config.User).toBe(`${process.getuid?.()}:${process.getgid?.()}`); - expect(inspect.HostConfig.CapDrop).toEqual(['ALL']);expect(inspect.HostConfig.SecurityOpt).toContain('no-new-privileges:true'); - expect(inspect.HostConfig.PortBindings).toEqual({});expect(inspect.Mounts.every((m:any)=>m.Destination!=='/var/run/docker.sock')).toBe(true); - }finally{await group.cleanup();} - expect(spawnSync('/usr/bin/docker',['--host',endpoint.uri,'inspect',client],{timeout:30_000}).status).not.toBe(0); - }); - test('machine-wide admission allows only two groups per endpoint',()=>{const a=admit(endpoint.uri,'a',Date.now()+60_000),b=admit(endpoint.uri,'b',Date.now()+60_000);try{expect(()=>admit(endpoint.uri,'c',Date.now()+60_000)).toThrow('Two reproduction groups');}finally{release(a);release(b);}}); - test.skipIf(!process.env.GSTACK_CSO_TEST_IMAGE)('staged runtime executes its trusted verifier and checks every declared tool version', async () => { - const staged = process.env.GSTACK_CSO_TEST_IMAGE!; - expect(staged).toMatch(/@sha256:[a-f0-9]{64}$/); - expect(process.env.GSTACK_CSO_TEST_PLATFORM).toBe(process.arch === 'arm64' ? 'linux/arm64' : 'linux/amd64'); - const versions = JSON.parse(process.env.GSTACK_CSO_EXPECTED_VERSIONS || '{}'); - const commands: Record> = { - node: {node: ['/usr/local/bin/node', '--version'], npm: ['/usr/local/bin/npm', '--version'], 'cso-preparation': ['/opt/cso/preparation', '--version']}, - bun: {bun: ['/usr/local/bin/bun', '--version'], 'cso-preparation': ['/opt/cso/preparation', '--version']}, - python: {python: ['/usr/local/bin/python', '--version'], uv: ['/usr/local/bin/uv', '--version'], 'cso-preparation': ['/opt/cso/preparation', '--version']}, - rails: {ruby: ['/usr/local/bin/ruby', '--version'], bundler: ['/usr/local/bin/bundle', '--version'], 'cso-preparation': ['/opt/cso/preparation', '--version']}, - postgresql: {postgresql: ['/opt/cso/bin/postgres', '--version']}, - }; - const prefixes: Record = {node: 'v', npm: '', bun: '', python: 'Python ', uv: 'uv ', ruby: 'ruby ', bundler: 'Bundler version ', postgresql: 'postgres (PostgreSQL) ', 'cso-preparation': ''}; - const stack = commands[process.env.GSTACK_CSO_TEST_STACK || '']; - expect(stack).toBeDefined(); - expect(Object.keys(versions).sort()).toEqual(Object.keys(stack).sort()); - const dir = path.join(root, 'staged'); fs.mkdirSync(dir, {mode: 0o700}); - const policy = { - phase: 'after', port: 34568, - legitimate: [{name: 'available feature', path: '/control', method: 'GET', expected: {status: 200, includes: 'CONTROL_OK'}}], - security: {name: 'denied access', path: '/security', method: 'GET', expected: {status: 403, includes: 'DENIED'}, vulnerable: {status: 200, includes: 'SECRET'}}, - }; - const positivePath = path.join(dir, 'positive.json'), negativePath = path.join(dir, 'broken-control.json'); - fs.writeFileSync(positivePath, JSON.stringify(policy), {mode: 0o600}); - fs.writeFileSync(negativePath, JSON.stringify({...policy, legitimate: [{...policy.legitimate[0], expected: {status: 201, includes: 'CONTROL_OK'}}]}), {mode: 0o600}); - const group = await DockerGroup.create(endpoint, `staged-${Date.now()}`, dir, Date.now() + 90_000, staged, watchdog); - try { - const verifier = await group.createContainer({ - role: 'verifier', image: staged, command: ['/bin/sleep', '2147483647'], - readonlyFiles: [{host: positivePath, container: '/policy/positive.json'}, {host: negativePath, container: '/policy/broken-control.json'}], - }); - await group.start(verifier); - for (const [tool, version] of Object.entries(versions)) { - const result = await group.execAttach(verifier, stack[tool]); - expect(result.code).toBe(0); - const expected = `${prefixes[tool]}${version}`.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - expect(result.output.trim()).toMatch(new RegExp(`^${expected}(?:$|\\s)`)); - } - if(process.env.GSTACK_CSO_TEST_STACK==='postgresql'){ - const databases=path.join(dir,'postgresql.databases');fs.writeFileSync(databases,'cso_primary\ncso_queue\n',{mode:0o444}); - const postgres=await group.createContainer({role:'postgres',image:staged,command:['/opt/cso/run-postgresql','/policy/postgresql.databases'],postgresDatabasePolicy:databases});await group.start(postgres); - let ready=false;for(let attempt=0;attempt<100&&!ready;attempt++){const checked=await group.execAttach(postgres,['/opt/cso/postgresql-ready','/policy/postgresql.databases']);ready=checked.code===0;if(!ready)await Bun.sleep(50);}expect(ready).toBe(true); - const raw=exec('/usr/bin/docker',['--host',endpoint.uri,'inspect',postgres]),inspect=JSON.parse(raw)[0];expect(inspect.Config.User).toBe('10001:10001'); - await group.removeContainer(postgres); - } - const server = await group.createContainer({role: 'app', image, command: ['/http-server']}); - await group.start(server); - const positive = await group.execAttach(verifier, ['/opt/cso/verifier', '/policy/positive.json']); - expect(positive.code).toBe(0); - expect(JSON.parse(positive.output)).toMatchObject({booted: true, legitimate: true, security: 'pass'}); - const negative = await group.execAttach(verifier, ['/opt/cso/verifier', '/policy/broken-control.json']); - expect(negative.code).toBe(0); - expect(JSON.parse(negative.output)).toMatchObject({booted: true, legitimate: false, security: 'pass'}); - } finally { await group.cleanup(); } - }, 120_000); -}); diff --git a/test/cso-docker-mounts.test.ts b/test/cso-docker-mounts.test.ts deleted file mode 100644 index af60ab1b2..000000000 --- a/test/cso-docker-mounts.test.ts +++ /dev/null @@ -1,205 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { CONTAINER_SHM_BYTES, DockerGroup, preparedExportRejection, type ContainerSpec } from '../lib/cso/docker'; -import * as processModule from '../lib/cso/process'; -import { COMMAND_TIMEOUT_MS, PREPARATION_COMMAND_TIMEOUT_MS, commandTimeoutMs } from '../lib/cso/process'; - -const roots: string[] = []; -const restores: Array<() => void> = []; -afterEach(() => { - for (const restore of restores.splice(0).reverse()) restore(); - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); - -function fixture() { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-m-')); - roots.push(root); - const directory = path.join(root, 'input'), file = path.join(root, 'policy'), socket = path.join(root, 'r.sock'); - fs.mkdirSync(directory, { mode: 0o700 }); - fs.writeFileSync(file, 'cso_primary\n', { mode: 0o444 }); - fs.chmodSync(file, 0o444); - const listener = Bun.listen({ unix: socket, socket: { data() {} } }); - restores.push(() => listener.stop(true)); - const image = `sha256:${'a'.repeat(64)}`, id = 'b'.repeat(64), calls: string[][] = []; - let createArgs: string[] = []; - const inspectHooks: Array<(value: any) => void> = []; - const group = new (DockerGroup as any)({}, 'mount-regression', root, Date.now() + 60_000, {}) as DockerGroup; - if (process.getuid!() === 0) { - const uid = spyOn(process, 'getuid').mockReturnValue(1001); - const lstat = fs.lstatSync; - const owner = spyOn(fs, 'lstatSync').mockImplementation(((...args: Parameters) => { - const stat = lstat(...args); - if (stat) stat.uid = typeof stat.uid === 'bigint' ? 1001n : 1001; - return stat; - }) as typeof fs.lstatSync); - restores.push(() => uid.mockRestore(), () => owner.mockRestore()); - } - group.anchor = 'c'.repeat(64); - (group as any).docker = async (args: string[]) => { - calls.push(args); - if (args[0] === 'image') return JSON.stringify({ - Id: image, Os: 'linux', Architecture: process.arch === 'arm64' ? 'arm64' : 'amd64', - Config: { Entrypoint: ['/opt/cso/entrypoint'] }, - }); - if (args[0] === 'create') { createArgs = args; return id; } - if (args[0] === 'inspect') { - const tmpfs = createArgs.flatMap((arg, index) => arg === '--tmpfs' ? [createArgs[index + 1].split(':')[0]] : []); - const mounts = createArgs.flatMap((arg, index) => arg === '--mount' ? [createArgs[index + 1]] : []); - const binds = mounts.filter(mount => !mount.startsWith('type=volume,')); - const volumes = mounts.filter(mount => mount.startsWith('type=volume,')).map(mount => ({ - target: /dst=([^,]+)/.exec(mount)![1], o: /"volume-opt=o=([^"]+)"/.exec(mount)![1], - })); - const value = { - HostConfig: { ReadonlyRootfs: true, ShmSize: CONTAINER_SHM_BYTES, Tmpfs: Object.fromEntries(tmpfs.map(target => [target, 'rw'])), - Mounts: [...binds.map(() => ({ Type: 'bind' })), ...volumes.map(volume => ({ Type: 'volume', Target: volume.target, - VolumeOptions: { DriverConfig: { Name: 'local', Options: { device: 'tmpfs', o: volume.o, type: 'tmpfs' } } } }))] }, - Mounts: [...tmpfs.map(Destination => ({ Type: 'tmpfs', Destination })), ...binds.map(mount => ({ - Type: 'bind', Destination: mount.split(',').find(part => part.startsWith('dst='))!.slice(4), - })), ...volumes.map(volume => ({ Type: 'volume', Destination: volume.target, Driver: 'local' }))], - }; - for (const hook of inspectHooks) hook(value); - return JSON.stringify(value); - } - throw new Error(`Unexpected Docker call: ${args.join(' ')}`); - }; - return { root, directory, file, socket, group, image, id, calls, inspectHooks }; -} - -describe.skipIf(process.platform === 'win32')('CSO Docker nonrecursive bind mounts', () => { - const cases: Array<{ name: string; target: string; spec: (f: ReturnType) => Partial }> = [ - { name: 'source', target: '/source', spec: f => ({ source: f.directory }) }, - { name: 'policy file', target: '/policy/check.json', spec: f => ({ readonlyFiles: [{ host: f.file, container: '/policy/check.json' }] }) }, - { name: 'PostgreSQL policy', target: '/policy/postgresql.databases', spec: f => ({ role: 'postgres', postgresDatabasePolicy: f.file }) }, - { name: 'fixtures', target: '/fixtures', spec: f => ({ readonlyDirectories: [{ host: f.directory, container: '/fixtures' }] }) }, - { name: 'offline metadata', target: '/metadata', spec: f => ({ readonlyMetadata: f.directory }) }, - { name: 'acquisition input metadata', target: '/input-metadata', spec: f => ({ readonlyInputMetadata: f.directory, metadataTmpfsBytes: 1024 }) }, - { name: 'offline archives', target: '/archives', spec: f => ({ readonlyArchiveDirectory: f.directory }) }, - { name: 'registry socket', target: '/run/cso-registry.sock', spec: f => ({ registrySocket: f.socket }) }, - ]; - - for (const item of cases) test(`${item.name} uses the supported read-only nonrecursive option`, async () => { - const f = fixture(); - expect(await f.group.createContainer({ role: 'app', image: f.image, command: ['/bin/sleep', '1'], ...item.spec(f) })).toBe(f.id); - const args = f.calls.find(call => call[0] === 'create')!; - const mounts = args.flatMap((arg, index) => arg === '--mount' ? [args[index + 1].split(',')] : []); - expect(mounts).toHaveLength(1); - expect(mounts[0]).toContain(`dst=${item.target}`); - expect(mounts[0]).toContain('readonly'); - expect(mounts[0]).toContain('bind-recursive=disabled'); - expect(mounts[0].some(option => option.startsWith('bind-nonrecursive'))).toBe(false); - expect(args).toContain('--read-only'); - expect(args[args.indexOf('--cap-drop') + 1]).toBe('ALL'); - expect(args).toContain('no-new-privileges:true'); - expect(args).toContain('seccomp=builtin'); - expect(args[args.indexOf('--network') + 1]).toBe(`container:${f.group.anchor}`); - expect(fs.readFileSync(path.join(f.root, 'resources.journal'), 'utf8')).toBe(`container:${f.id}\n`); - }); - - test('unsafe bind paths and permissions fail before Docker create', async () => { - const f = fixture(), link = path.join(f.root, 'link'); - fs.symlinkSync(f.directory, link); - const invalid: Array> = [ - { source: link }, - { readonlyFiles: [{ host: link, container: '/policy/check.json' }] }, - { readonlyFiles: [{ host: f.file, container: '/outside-policy' }] }, - { role: 'postgres', postgresDatabasePolicy: f.directory }, - { readonlyDirectories: [{ host: link, container: '/fixtures' }] }, - { readonlyMetadata: link }, - { readonlyInputMetadata: link, metadataTmpfsBytes: 1024 }, - { readonlyArchiveDirectory: link }, - { registrySocket: f.file }, - ]; - for (const spec of invalid) await expect(f.group.createContainer({ role: 'app', image: f.image, command: ['/bin/sleep', '1'], ...spec })).rejects.toThrow(); - fs.chmodSync(f.directory, 0o777); - await expect(f.group.createContainer({ role: 'app', image: f.image, command: ['/bin/sleep', '1'], readonlyMetadata: f.directory })).rejects.toThrow('private owned directory'); - expect(f.calls.some(call => call[0] === 'create')).toBe(false); - expect(fs.existsSync(path.join(f.root, 'resources.journal'))).toBe(false); - }); - - // docker cp cannot read tmpfs mounts, so both export sources are tmpfs-backed local volumes. - test.each([ - ['acquisition archives', '/archives', { archiveTmpfsBytes: 4096 }, 'noexec,nosuid,nodev'], - ['prepared-tree work', '/work', { exportableWork: true as const }, 'nosuid,nodev'], - ])('%s export from a bounded in-memory volume docker cp can read', async (_name, target, spec, flags) => { - const f = fixture(); - expect(await f.group.createContainer({ role: 'app', image: f.image, command: ['/bin/sleep', '1'], ...(spec as Partial) })).toBe(f.id); - const args = f.calls.find(call => call[0] === 'create')!; - const volume = args.flatMap((arg, index) => arg === '--mount' && args[index + 1].startsWith('type=volume,') ? [args[index + 1]] : []); - expect(volume).toHaveLength(1); - expect(volume[0]).toStartWith(`type=volume,dst=${target},volume-driver=local,volume-opt=type=tmpfs,volume-opt=device=tmpfs,"volume-opt=o=size=`); - expect(volume[0]).toEndWith(`,mode=700,uid=${process.getuid!()},gid=${process.getgid!()},${flags}"`); - expect(args.flatMap((arg, index) => arg === '--tmpfs' ? [args[index + 1].split(':')[0]] : [])).not.toContain(target); - }); - - test.each([ - ['dropped tmpfs driver options', (value: any) => { value.HostConfig.Mounts.at(-1).VolumeOptions.DriverConfig.Options.type = 'none'; }], - ['a host-backed volume source', (value: any) => { value.HostConfig.Mounts.at(-1).Source = '/var/tmp/export'; }], - ['an extra daemon volume', (value: any) => { value.Mounts.push({ Type: 'volume', Destination: '/data', Driver: 'local' }); }], - ['a missing volume mount', (value: any) => { value.HostConfig.Mounts.pop(); }], - ])('export volumes fail closed on %s', async (_name, mutate) => { - const f = fixture(); f.inspectHooks.push(mutate); - await expect(f.group.createContainer({ role: 'app', image: f.image, command: ['/bin/sleep', '1'], archiveTmpfsBytes: 4096 })).rejects.toThrow('Docker did not preserve'); - expect(fs.existsSync(path.join(f.root, 'resources.journal'))).toBe(false); - }); -}); - -describe('CSO preparation command ceiling', () => { - test('only the preparation phase gets the longer ceiling, and neither outlives the deadline', () => { - const now = 1_000_000, later = now + 2 * 60 * 60_000; - expect(PREPARATION_COMMAND_TIMEOUT_MS).toBe(900_000); - expect(COMMAND_TIMEOUT_MS).toBe(300_000); - expect(commandTimeoutMs(later, 'command', now)).toBe(COMMAND_TIMEOUT_MS); - expect(commandTimeoutMs(later, 'preparation', now)).toBe(PREPARATION_COMMAND_TIMEOUT_MS); - expect(commandTimeoutMs(now + 60_000, 'preparation', now)).toBe(60_000); - expect(commandTimeoutMs(now + 60_000, 'command', now)).toBe(60_000); - expect(commandTimeoutMs(now - 1, 'preparation', now)).toBe(1); - }); - - test('execCapture passes the preparation ceiling to the child only when asked, bounded by the group deadline', async () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-t-')); - roots.push(root); - const seen: Array<{ timeoutMs?: number; preparationCommand?: true }> = []; - const run = spyOn(processModule, 'runProcess').mockImplementation(async (_file, _args, opts) => { - seen.push({ timeoutMs: opts.timeoutMs, preparationCommand: opts.preparationCommand }); - return { code: 0, stdout: '', stderr: '', timedOut: false, truncated: false, capturedBytes: 0 }; - }); - restores.push(() => run.mockRestore()); - const group = (deadline: number) => - new (DockerGroup as any)({ executable: '/usr/bin/docker' }, 'timeout-ceiling', root, deadline, {}) as DockerGroup; - const far = group(Date.now() + 2 * 60 * 60_000), near = group(Date.now() + 60_000); - await far.execCapture('x', ['/bin/true']); - await far.execCapture('x', ['/bin/true'], { preparationCommand: true }); - await near.execCapture('x', ['/bin/true'], { preparationCommand: true }); - expect(seen[0]).toEqual({ timeoutMs: COMMAND_TIMEOUT_MS, preparationCommand: undefined }); - expect(seen[1]).toEqual({ timeoutMs: PREPARATION_COMMAND_TIMEOUT_MS, preparationCommand: true }); - expect(seen[2].preparationCommand).toBe(true); - expect(seen[2].timeoutMs!).toBeLessThanOrEqual(60_000); - }); - - test('only the acquisition and offline dependency command loops request the preparation ceiling', () => { - const directory = path.join(import.meta.dir, '../lib/cso'); - const uses = fs.readdirSync(directory).filter(name => name.endsWith('.ts')).flatMap(name => { - const lines = fs.readFileSync(path.join(directory, name), 'utf8').split('\n'); - return lines.flatMap((line, index) => line.includes('preparationCommand: true') ? [{ name, context: lines.slice(Math.max(0, index - 4), index).join('\n') }] : []); - }); - expect(uses.map(use => use.name)).toEqual(['preparation-docker.ts', 'preparation-docker.ts']); - for (const use of uses) expect(use.context).toContain('[command.executable, ...command.args]'); - }); -}); - -describe('CSO prepared export rejection reason', () => { - test('names the helper reason or errno and never echoes paths', () => { - expect(preparedExportRejection('4 | throw new Error("prepared tree contains a hard-linked file");\n ^\nerror: prepared tree contains a hard-linked file\n at f (/$bunfs/root/preparation:4:9)\n')) - .toBe('prepared tree contains a hard-linked file'); - expect(preparedExportRejection("ENOENT: no such file or directory, lstat '/work/secret-name'\n path: \"/work/secret-name\",\n syscall: \"lstat\",\n errno: -2,\n code: \"ENOENT\"\n")) - .toBe('filesystem error ENOENT during lstat'); - expect(preparedExportRejection('prepared tree contains a publicly writable directory\n')).toBe('prepared tree contains a publicly writable directory'); - expect(preparedExportRejection("ENOENT: no such file or directory, lstat '/work/secret-name'\n")).toBe('filesystem error ENOENT during lstat'); - expect(preparedExportRejection('prepared /work/secret-name\n')).toBe('unrecognized helper failure'); - expect(preparedExportRejection('error: prepared /work/secret-name\n')).toBe('unrecognized helper failure'); - expect(preparedExportRejection('error: prepared tree contains a FIFO, socket, device, or other special object\n')).toBe('prepared tree contains a FIFO, socket, device, or other special object'); - expect(preparedExportRejection('')).toBe('unrecognized helper failure'); - }); -}); diff --git a/test/cso-docker-policy.test.ts b/test/cso-docker-policy.test.ts deleted file mode 100644 index c08b6e0ed..000000000 --- a/test/cso-docker-policy.test.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { GROUP_LIMITS, ROLE_LIMITS, type Role } from '../lib/cso/admission'; -import { CONTAINER_SHM_BYTES, writableAllocation } from '../lib/cso/docker'; - -describe('CSO Docker writable-storage policy',()=>{ - test('every default role includes the explicitly bounded shm allocation',()=>{ - for(const role of Object.keys(ROLE_LIMITS) as Role[]){ - const allocation=writableAllocation(role); - expect(allocation.shmBytes).toBe(CONTAINER_SHM_BYTES); - expect(allocation.totalBytes).toBe(ROLE_LIMITS[role].writableMiB*1024*1024); - expect(allocation.temporaryBytes).toBeGreaterThan(0); - expect(allocation.workBytes).toBeGreaterThan(0); - } - }); - - test('the Rails PostgreSQL group stays within two GiB including every shm mount',()=>{ - const roles:Role[]=['anchor','postgres','app','verifier']; - const bytes=roles.reduce((sum,role)=>sum+writableAllocation(role).totalBytes,0); - expect(bytes).toBe(GROUP_LIMITS.writableMiB*1024*1024); - }); - - test('dependency acquisition accounts for metadata, archives, and shm together',()=>{ - const mib=1024*1024,allocation=writableAllocation('app',{ - temporaryTmpfsBytes:64*mib,workTmpfsBytes:64*mib,metadataTmpfsBytes:1024*mib,archiveTmpfsBytes:384*mib, - }); - expect(allocation.totalBytes).toBe((64+64+1024+384)*mib+CONTAINER_SHM_BYTES); - expect(writableAllocation('anchor').totalBytes+allocation.totalBytes).toBeLessThan(GROUP_LIMITS.writableMiB*mib); - }); -}); diff --git a/test/cso-docker-socket-realpath.test.ts b/test/cso-docker-socket-realpath.test.ts deleted file mode 100644 index 315d1f3f4..000000000 --- a/test/cso-docker-socket-realpath.test.ts +++ /dev/null @@ -1,118 +0,0 @@ -import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as net from 'node:net'; -import * as os from 'node:os'; -import { join } from 'node:path'; -import { realpathSocket } from '../lib/cso/docker'; - -describe.skipIf(process.platform === 'win32')('CSO Docker socket path resolution', () => { - let root = ''; - let socketPath = ''; - let server: net.Server; - beforeAll(async () => { - root = fs.mkdtempSync(join(os.tmpdir(), 'cso-sock-')); - socketPath = join(root, 'docker.sock'); - server = net.createServer(); - await new Promise((resolve, reject) => { - server.once('error', reject); - server.listen(socketPath, () => resolve()); - }); - }); - afterAll(async () => { - await new Promise((resolve) => server.close(() => resolve())); - fs.rmSync(root, { recursive: true, force: true }); - }); - - test('resolves a Unix socket that realpath cannot open', () => { - const real = realpathSocket(socketPath); - expect(fs.statSync(real).isSocket()).toBe(true); - expect(real).toBe(join(fs.realpathSync(root), 'docker.sock')); - }); - - test('follows absolute and relative symbolic links down to the socket', () => { - const absoluteLink = join(root, 'absolute.sock'); - fs.symlinkSync(socketPath, absoluteLink); - const relativeLink = join(root, 'relative.sock'); - fs.symlinkSync('absolute.sock', relativeLink); - const expected = realpathSocket(socketPath); - expect(realpathSocket(absoluteLink)).toBe(expected); - expect(realpathSocket(relativeLink)).toBe(expected); - }); - - test('resolves a socket through a symlinked parent directory', () => { - const linkedDirectory = join(root, 'run'); - fs.symlinkSync(root, linkedDirectory); - expect(realpathSocket(join(linkedDirectory, 'docker.sock'))).toBe(realpathSocket(socketPath)); - }); - - test('still reports a missing socket as an error', () => { - expect(() => realpathSocket(join(root, 'missing.sock'))).toThrow(); - }); - - test('matches realpath for ordinary files', () => { - const file = join(root, 'plain'); - fs.writeFileSync(file, 'x'); - expect(realpathSocket(file)).toBe(fs.realpathSync(file)); - }); -}); - -// On macOS Bun's own realpath fails on a socket, so the suite above already -// exercises the fallback there. Linux resolves sockets natively, so this block -// forces the failure to keep the fallback covered on every CI platform. -describe.skipIf(process.platform === 'win32')( - 'CSO Docker socket path resolution when realpath refuses sockets', - () => { - let root = ''; - let socketPath = ''; - let server: net.Server; - const realpath = fs.realpathSync; - const refusing = (code: string) => - ((path: fs.PathLike, ...rest: any[]) => { - if (fs.statSync(path).isSocket()) { - const error = new Error(`${code}: operation not supported on socket`) as NodeJS.ErrnoException; - error.code = code; - throw error; - } - return realpath(path, ...rest); - }) as typeof fs.realpathSync; - beforeAll(async () => { - root = fs.mkdtempSync(join(os.tmpdir(), 'cso-sock-stub-')); - socketPath = join(root, 'docker.sock'); - server = net.createServer(); - await new Promise((resolve, reject) => { - server.once('error', reject); - server.listen(socketPath, () => resolve()); - }); - }); - afterAll(async () => { - await new Promise((resolve) => server.close(() => resolve())); - fs.rmSync(root, { recursive: true, force: true }); - }); - afterEach(() => { - (fs.realpathSync as any).mockRestore?.(); - }); - - test('falls back to resolving the leaf by hand on EOPNOTSUPP', () => { - const stub = spyOn(fs, 'realpathSync').mockImplementation(refusing('EOPNOTSUPP')); - expect(realpathSocket(socketPath)).toBe(join(realpath(root), 'docker.sock')); - expect(stub).toHaveBeenCalledWith(socketPath); - expect(stub.mock.calls.length).toBeGreaterThan(1); - }); - - test('still follows symbolic links to the socket on EOPNOTSUPP', () => { - spyOn(fs, 'realpathSync').mockImplementation(refusing('EOPNOTSUPP')); - const link = join(root, 'link.sock'); - fs.symlinkSync('docker.sock', link); - const directory = join(root, 'run'); - fs.symlinkSync(root, directory); - const expected = join(realpath(root), 'docker.sock'); - expect(realpathSocket(link)).toBe(expected); - expect(realpathSocket(join(directory, 'docker.sock'))).toBe(expected); - }); - - test('propagates any other realpath error unchanged', () => { - spyOn(fs, 'realpathSync').mockImplementation(refusing('EACCES')); - expect(() => realpathSocket(socketPath)).toThrow(/EACCES/); - }); - }, -); diff --git a/test/cso-e2e-report-contract.test.ts b/test/cso-e2e-report-contract.test.ts deleted file mode 100644 index b865b73b0..000000000 --- a/test/cso-e2e-report-contract.test.ts +++ /dev/null @@ -1,68 +0,0 @@ -// Release gate census 45216872389 (main @ c4cfe6d1) failed cso-diff-mode twice at the e2e report check's old -// rule that every daily finding is supported. #4739 made /cso keep an unconfirmed candidate as a -// low-confidence hypothesis instead of dropping it, and the captured run did exactly that. These are that -// run's two submissions (attempt 1, paid-slice-8-a1), replayed through the real helper on the case's fixture. -import { describe, expect, test } from 'bun:test'; -import { spawnSync } from 'node:child_process'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import type { RunReportV3 } from '../lib/cso/contracts'; -import { DIFF_MODE_BASE, DIFF_MODE_CHANGE, withFixture, requireReport, expectDailyFinding, expectDiffModeReport, isWebhookAuthFinding, type Fixture } from './helpers/cso-e2e-report'; - -const ROOT = path.resolve(import.meta.dir, '..'); -const launcher = path.join(ROOT, 'bin', process.platform === 'win32' ? 'gstack-cso-launcher.exe' : 'gstack-cso-launcher'); -const CAPTURED = ['diff-mode-45216872389-sub1.json', 'diff-mode-45216872389-sub2.json'] - .map(name => path.join(ROOT, 'test', 'fixtures', 'cso-e2e', name)); - -function replayCapturedRun(f: Fixture): void { - const home = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-e2e-replay-')); - try { - const cso = (...args: string[]) => { - const result = spawnSync(launcher, args, { cwd: f.repo, encoding: 'utf8', timeout: 120_000, - env: { HOME: home, GSTACK_HOME: f.state, PATH: process.env.PATH ?? '' } }); - if (result.status !== 0) throw new Error(`gstack-cso ${args[0]} exited ${result.status}: ${result.stderr}${result.stdout}`); - return JSON.parse(result.stdout.slice(result.stdout.indexOf('{'))); - }; - const run = cso('start', '--repo', f.repo, '--diff', '--base', 'main', '--offline').runId as string; - const control = path.join(home, 'control'); - fs.mkdirSync(control, { mode: 0o700 }); - for (const capture of CAPTURED) { - const file = path.join(control, path.basename(capture)); - fs.writeFileSync(file, fs.readFileSync(capture), { mode: 0o600 }); - cso('submit', run, file); - fs.rmSync(file); - } - cso('finish', run); - } finally { - fs.rmSync(home, { recursive: true, force: true }); - } -} - -describe('cso e2e report contract (release gate 45216872389)', () => { - test('the captured diff-mode run, with one low-confidence hypothesis, meets the daily and diff-mode contract', async () => { - await withFixture(DIFF_MODE_BASE, DIFF_MODE_CHANGE, async f => { - replayCapturedRun(f); - const report = requireReport(f); - expectDiffModeReport(report, f); - expect(report.findings.map(item => item.evidence).sort()).toEqual(['hypothesis', 'supported', 'supported', 'supported']); - }); - }, 60_000); - - test('the checks still reject a confident hypothesis, a downgraded target and a finding outside the diff', async () => { - await withFixture(DIFF_MODE_BASE, DIFF_MODE_CHANGE, async f => { - replayCapturedRun(f); - const report = requireReport(f); - const hypothesis = report.findings.find(item => item.evidence === 'hypothesis')!; - expect(() => expectDailyFinding({ ...hypothesis, confidence: 'medium' })).toThrow(); - const downgraded: RunReportV3 = structuredClone(report); - const targets = downgraded.findings.filter(isWebhookAuthFinding); - expect(targets).toHaveLength(1); - Object.assign(targets[0], { evidence: 'hypothesis', confidence: 'low' }); - expect(() => expectDiffModeReport(downgraded, f)).toThrow(); - const outside: RunReportV3 = structuredClone(report); - outside.findings[0].location.path = 'app.js'; - expect(() => expectDiffModeReport(outside, f)).toThrow(); - }); - }, 60_000); -}); diff --git a/test/cso-eval.test.ts b/test/cso-eval.test.ts deleted file mode 100644 index 9e01b2501..000000000 --- a/test/cso-eval.test.ts +++ /dev/null @@ -1,1371 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as childProcess from 'node:child_process'; -import { chmodSync, cpSync, existsSync, linkSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, symlinkSync, writeFileSync } from 'node:fs'; -import { createHash } from 'node:crypto'; -import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; -import { collectProducerReceipts, createEvalBaseline, createEvalMatrix, createPortableSkillPayload, loadPortableSkillPayload, prepareEvalJobs, REQUIRED_CONTAINMENT, scoreCollectedEval, scoreEval, validateMatrix, validatePortableSkillPayload, type EvalBaseline, type EvalCell, type EvalFinding, type EvalMatrix, type EvalResult, type PreparedEvalSchedule } from '../scripts/cso-eval'; -import { assertProducerArtifactPath, PRODUCER_PROVIDER_POLICY, producerFailureMessage, producerProviderTimeoutMs, producerInstallationIdentity, resolveProducerHelperBinding, runProducerCell, sanitizeProducerRun, validateProductionProducerInstallation } from '../scripts/cso-eval-producer'; -import { producerArtifactInventoryHash, producerHostPlatform, producerInstallationIdentityHash, producerProviderIdentityHash, producerReceiptHash, sha256, type ProducerArtifactInventory, type ProducerInstallationIdentity, type ProducerProviderIdentity, type ProducerReceipt } from '../scripts/cso-eval-protocol'; -import type { Family, ProviderAdapter, RunOpts, RunResult } from './helpers/providers/types'; -import { CORPUS_VERSION, FAMILIES, STACKS, defineEvalCorpus, loadCorpusManifest, materializeCase, sourceFiles, sourceHash, validateCorpusManifest, type CorpusManifest, type EvalVariant } from './fixtures/cso-eval/materialize'; -import { judgeRepair, oracleFor, type PrivateEvidence } from './helpers/cso-eval-oracles'; -import { inspectPreparation } from '../lib/cso/preparation'; -import { assertRuntimeCompatible, CSO_HELPER_ABI, RUNTIME_CATALOG, type RuntimeCatalog } from '../lib/cso/runtime-catalog'; -import { canonicalStartPlan, canonicalTestPlan } from '../lib/cso/verification'; -import { canonical, CsoError } from '../lib/cso/contracts'; -import committedRuntimeCatalog from '../lib/cso/runtime-catalog.json'; -import buildInputs from '../lib/cso/images/build-inputs.json'; -import { imageBuildMatrix } from '../scripts/cso-image-matrix'; -import { evaluationCandidateCatalog } from '../scripts/cso-runtime-promotion'; -import { scan } from '../lib/redact-engine'; -import { redactProducerText, sourceCredentialValues } from '../scripts/cso-eval-output-redaction'; -import { geminiProducerPaths, geminiProducerSystemSettings } from './helpers/providers/gemini'; - -const temporary: string[] = []; -const randomHex = (bytes: number) => createHash('sha256').update(`${Math.random()}:${process.hrtime.bigint()}`).digest('hex').slice(0, bytes * 2); -const root = () => { const path = mkdtempSync(join(tmpdir(), 'cso-eval-')); temporary.push(path); return path; }; -function unlockTemporary(path: string): void { - if (!existsSync(path)) return; - const stat = lstatSync(path); - if (stat.isSymbolicLink()) return; - if (!stat.isDirectory()) { try { chmodSync(path, 0o600); } catch {} return; } - try { chmodSync(path, 0o700); } catch {} - for (const entry of readdirSync(path)) unlockTemporary(join(path, entry)); -} -afterEach(() => { for (const path of temporary.splice(0)) { unlockTemporary(path); rmSync(path, { recursive: true, force: true }); } }); -const corpus = loadCorpusManifest(); -const matrix = createEvalMatrix({ model: 'matched-test-model', host: 'codex', skillHashes: { v2: 'a'.repeat(64), v3: 'b'.repeat(64) } }); -const qualification = { containment: Object.fromEntries(REQUIRED_CONTAINMENT.map(name => [name, 'passed' as const])) }; - -function portableSkill(version: 'v2' | 'v3', sectionMarker: string): string { - const manifest = JSON.stringify({ $schema: 'https://gstack.dev/schemas/section-manifest.json', skill: 'cso', version: 1, sections: [{ id: 'audit-phases', file: 'audit-phases.md', title: 'Audit phases', trigger: 'during audit phases' }] }, null, 2) + '\n'; - return createPortableSkillPayload(version, [ - { path: 'SKILL.md', contents: `---\nname: cso\nversion: ${version.slice(1)}.0.0\n---\n# CSO ${version}\nRead cso/sections/audit-phases.md before auditing.\n` }, - { path: 'sections/manifest.json', contents: manifest }, - { path: 'sections/audit-phases.md', contents: `# Complete ${version} phases\n${sectionMarker}\n` }, - ]); -} - -/** Synthetic accounting records exercise the scorer. These are not measured agent results. */ -const syntheticResult = (cell: EvalCell): EvalResult => syntheticResultFor(cell, corpus); -function syntheticResultFor(cell: EvalCell, manifest: CorpusManifest): EvalResult { - const runtime = cell.mode === 'comprehensive'; - const positive = cell.variant === 'vulnerable'; - const repairEvidenceHash = 'c'.repeat(64), recheckEvidenceHash = 'd'.repeat(64); - return { cellId: cell.id, sourceHash: cell.sourceHash, skillHash: cell.skillHash, model: cell.model, host: cell.host, budgetSeconds: cell.budgetSeconds, - reportPresent: true, reportFinished: true, reportComplete: true, - findings: positive ? [{ id: 'finding-1', evidence: cell.version === 'v2' ? 'legacy_review' : 'supported', claimedTested: runtime && cell.version === 'v3', judgment: 'correct', matchedCaseId: cell.caseId, - ...(runtime && cell.version === 'v3' ? { trustedVerification: { repair: 'passed' as const, repairEvidenceHash, recheck: 'passed' as const, recheckEvidenceHash } } : {}) }] : [], - setup: runtime ? 'passed' : 'not_attempted', reproduction: runtime && positive ? 'passed' : 'not_attempted', repair: runtime && positive ? 'passed' : 'not_attempted', recheck: runtime && positive ? 'passed' : 'not_attempted', - ...(runtime && positive ? { oracleEvidenceHash: repairEvidenceHash, oracleVersion: manifest.version, currentSourceHash: manifest.cases.find(fixture => fixture.id === cell.caseId)!.filesHash.fixed, recheckEvidenceHash } : {}), - heldOutAssertionsPassed: runtime && positive, freshRecheck: runtime && positive, latencyMs: 1500, firstUsefulResultMs: positive ? 500 : null, - }; -} -const group = (score: ReturnType, version: string, mode: string) => score.groups.find(item => item.version === version && item.mode === mode)!; -function syntheticInstallationIdentity(seed = '1', catalogSeed = seed): ProducerInstallationIdentity { - const artifact = (offset: number) => ({ sha256: sha256(`${seed}:artifact:${offset}`), bytes: 100 + offset }); - const core = artifact(3); - const withoutHash: Omit = { - schemaVersion: 1, - producer: artifact(1), launcher: artifact(2), core, watchdog: artifact(4), - generation: { coreSha256: core.sha256, manifest: { sha256: sha256(`${core.sha256}\n`), bytes: 65 } }, - embeddedCatalogs: { - runtimeRevision: 'runtime-test', runtimeBuildRevision: 'runtime-build-test', runtimeSha256: sha256(`${catalogSeed}:runtime`), - scannerRevision: 'scanner-test', scannerSha256: sha256(`${catalogSeed}:scanner`), - }, - }; - return { ...withoutHash, identityHash: producerInstallationIdentityHash(withoutHash) }; -} -function syntheticProviderIdentity(family: Family = 'gpt', seed = '1'): ProducerProviderIdentity { - const withoutHash: Omit = { - schemaVersion: 1, family, policyRevision: `${family}-test-policy`, - executable: { sha256: sha256(`${seed}:${family}:provider`), bytes: 200 }, argsPrefix: [], version: `${family}-test-version`, - }; - return { ...withoutHash, identityHash: producerProviderIdentityHash(withoutHash) }; -} -function syntheticArtifactInventory(): ProducerArtifactInventory { - const base = { schemaVersion: 1 as const, root: 'security/cso' as const, entries: [], totalBytes: 0 }; - return { ...base, identityHash: producerArtifactInventoryHash(base) }; -} -/** Platform-pinned cells get one native installation and provider binary per platform, sharing catalogs and provider policy. */ -function syntheticReceipt(cell: EvalCell): ProducerReceipt { - const seed = cell.platform ?? '1'; - const withoutHash: Omit = { schemaVersion: 2, cellRef: cell.id, inputHash: 'e'.repeat(64), installationIdentity: syntheticInstallationIdentity(seed, '1'), providerIdentity: syntheticProviderIdentity(cell.host === 'codex' ? 'gpt' : cell.host, seed), artifacts: syntheticArtifactInventory(), startedAt: '2026-01-01T00:00:00.000Z', finishedAt: '2026-01-01T00:00:01.000Z', status: 'succeeded', requestedModel: cell.model, modelUsed: `resolved-${cell.model}`, modelIdentitySource: 'provider_reported', durationMs: 1000, firstUsefulResultMs: null, toolCalls: 1, output: 'synthetic producer transcript', outputHash: sha256('synthetic producer transcript'), usage: { inputTokens: 10, outputTokens: 5, cachedTokens: 0, estimatedCostUSD: 0.001 } }; - return { ...withoutHash, receiptHash: producerReceiptHash(withoutHash) }; -} -function syntheticSchedule(target: EvalMatrix = matrix): PreparedEvalSchedule { - return { schemaVersion: 1, matrixHash: createHash('sha256').update(JSON.stringify(target)).digest('hex'), scheduledCells: target.cells.length, preparedCells: target.cells.length, jobs: target.cells.map(cell => ({ cellId: cell.id, relativePath: `jobs/${cell.id}`, inputHash: 'e'.repeat(64) })) }; -} -function rehashReceipt(receipt: ProducerReceipt): ProducerReceipt { - const { receiptHash: _receiptHash, ...withoutHash } = receipt; - return { ...withoutHash, receiptHash: producerReceiptHash(withoutHash) }; -} -function syntheticBatch() { - return collectProducerReceipts(matrix, syntheticSchedule(), matrix.cells.map(syntheticReceipt)); -} - -describe('CSO immutable evaluation corpus', () => { - test('contains forty distinct vulnerable/fixed pairs across ten families and four stacks', () => { - expect(corpus.cases).toHaveLength(40); - for (const stack of STACKS) expect(corpus.cases.filter(fixture => fixture.stack === stack).map(fixture => fixture.family)).toEqual([...FAMILIES]); - for (const fixture of corpus.cases) { - expect(fixture.filesHash.vulnerable).not.toBe(fixture.filesHash.fixed); - for (const variant of ['vulnerable', 'fixed'] as const) expect(sourceHash(sourceFiles(fixture.id, variant))).toBe(fixture.filesHash[variant]); - } - }); - test('producer snapshots contain app source but no private oracle, labels, or alternative fixed copy', () => { - const parent = root(); const result = materializeCase('node-sql-injection', 'vulnerable', join(parent, 'app')); - expect(result.sourceHash).toBe(corpus.cases[0].filesHash.vulnerable); - expect(readdirSync(result.path).sort()).toEqual(['README.md', 'app.mjs', 'package-lock.json', 'package.json', 'test']); - const combined = ['README.md', 'app.mjs', 'package-lock.json', 'package.json', 'test/control.test.mjs'] - .map(file => readFileSync(join(result.path, file), 'utf8')).join('\n'); - expect(combined).not.toContain('ORACLE_SQL_MARKER'); expect(combined).not.toContain('filesHash'); expect(combined).not.toContain('heldOut'); - expect(combined).toContain('the intended member workflow remains available'); - expect(() => materializeCase('node-sql-injection', 'fixed', result.path)).toThrow('CORPUS_DESTINATION_EXISTS'); - }); - test('rejects unknown cases and symlink destination ancestors', () => { - const parent = root(); symlinkSync(parent, join(parent, 'alias')); - expect(() => materializeCase('unknown', 'fixed', join(parent, 'no'))).toThrow('UNKNOWN_CORPUS_CASE'); - expect(() => materializeCase('node-sql-injection', 'fixed', join(parent, 'alias', 'no'))).toThrow('UNSAFE_CORPUS_DESTINATION'); - }); - test('all source fixtures have supported inert dependency metadata, including real Rails locks', () => { - const parent = root(); - for (const fixture of corpus.cases) { - const { path } = materializeCase(fixture.id, 'vulnerable', join(parent, fixture.id)); - const plan = inspectPreparation(path, fixture.stack); - expect({ id: fixture.id, status: plan.status, prerequisites: plan.prerequisites }).toEqual({ id: fixture.id, status: 'ready', prerequisites: [] }); - const reviewed = RUNTIME_CATALOG.profiles.find(profile => profile.stack === fixture.stack && profile.platform === 'linux/amd64'); - expect(reviewed).toBeDefined(); - expect(() => assertRuntimeCompatible(plan, reviewed as any)).not.toThrow(); - } - }); - test('every pair exposes a helper-derived startup and nonempty legitimate regression suite', () => { - const parent = root(); - for (const fixture of corpus.cases) for (const variant of ['vulnerable', 'fixed'] as const) { - const { path } = materializeCase(fixture.id, variant, join(parent, `${fixture.id}-${variant}`)); - const start = canonicalStartPlan(path, fixture.stack, 8000); - const tests = canonicalTestPlan(path, fixture.stack); - expect(start.command.executable.startsWith('/')).toBe(true); - expect(start.entrypointFiles.length).toBeGreaterThan(0); - expect(tests.commands.length).toBeGreaterThan(0); - expect(tests.minimumPassingTests.every(count => count >= 1)).toBe(true); - expect(tests.files.some(file => /(?:test|spec)/.test(file))).toBe(true); - } - }); - test('Rails lock provenance binds the native resolver inputs and exact public archive metadata', () => { - const source = sourceFiles('rails-sql-injection', 'vulnerable'); - const provenance = JSON.parse(readFileSync(new URL('./fixtures/cso-eval/rails-lock-provenance.json', import.meta.url), 'utf8')); - const hash = (value: string) => createHash('sha256').update(value).digest('hex'); - expect(hash(source.Gemfile)).toBe(provenance.gemfileSha256); expect(hash(source['Gemfile.lock'])).toBe(provenance.lockSha256); - const pins = [...source['Gemfile.lock'].matchAll(/^ ([A-Za-z0-9_.-]+) \(([^)]+)\)$/gm)]; - expect(provenance.archives).toHaveLength(pins.length); - for (const [, name, version] of pins) expect(provenance.archives.some((archive: any) => archive.name === name && archive.version === version && /^[a-f0-9]{64}$/.test(archive.sha256))).toBe(true); - expect(provenance.qualification).toContain('not-run'); - }); -}); - -describe('CSO private repair oracles', () => { - function validEvidence(): PrivateEvidence { - const oracle = oracleFor('object-authorization'); - const control = { request: oracle.controls[0].request, response: { status: 200, body: '{"owner":"member-1","total":12}' } }; - return { original: { booted: true, controls: [control], attack: { request: oracle.attack, response: { status: 200, body: '{"owner":"member-2","total":9800}' } } }, - patched: { booted: true, controls: [control], attack: { request: oracle.attack, response: { status: 403, body: '{"error":"forbidden"}' } }, heldOut: oracle.heldOut.map(assertion => ({ request: assertion.request, response: { status: 403, body: '{"error":"forbidden"}' } })), existingTestsPassed: true }, - immutableVerifier: true, independentRootCauseReview: true, featurePreserved: true, boundaryMocks: false }; - } - test('requires original exploit, unchanged verifier, legitimate behavior, and held-out assertions', () => { - const evidence = validEvidence(); expect(judgeRepair('object-authorization', evidence).correctRepair).toBe(true); - for (const mutation of [(item: PrivateEvidence) => { item.original.booted = false; }, (item: PrivateEvidence) => { item.patched.controls = []; }, (item: PrivateEvidence) => { item.patched.heldOut = []; }, (item: PrivateEvidence) => { item.immutableVerifier = false; }, (item: PrivateEvidence) => { item.featurePreserved = false; }, (item: PrivateEvidence) => { item.boundaryMocks = true; }]) { - const changed = structuredClone(evidence); mutation(changed); expect(judgeRepair('object-authorization', changed).correctRepair).toBe(false); - } - }); - test('a setup error cannot become an intended security assertion failure', () => { - const evidence = validEvidence(); evidence.original.attack.response = { status: 500, body: 'database unavailable' }; - expect(judgeRepair('object-authorization', evidence).reproduced).toBe(false); - }); - test('every family has a legitimate control and at least one withheld alternate assertion', () => { - for (const family of FAMILIES) { const oracle = oracleFor(family); expect(oracle.controls.length).toBeGreaterThan(0); expect(oracle.heldOut.length).toBeGreaterThan(0); } - }); -}); - -describe('CSO matched evaluation accounting', () => { - test('pins three repetitions and identical models, sources, budgets, and host for v2/v3', () => { - expect(matrix.cells).toHaveLength(960); expect(matrix.repetitions).toBe(3); expect(new Set(matrix.cells.map(cell => cell.id)).size).toBe(960); - validateMatrix(matrix); - const changed = structuredClone(matrix); changed.cells[1].budgetSeconds += 1; expect(() => validateMatrix(changed)).toThrow('UNMATCHED_OR_INCOMPLETE'); - expect(() => createEvalMatrix({ model: 'model', host: 'codex', skillHashes: { v2: 'a'.repeat(64), v3: 'a'.repeat(64) } })).toThrow('INVALID_MATCHED_EVAL_INPUT'); - }); - test('empty results are unmeasured, with honest denominators and unknown cost', () => { - const score = scoreEval(matrix, []); expect(score.status).toBe('unmeasured'); expect(Object.values(score.gates).every(value => value === 'unmeasured')).toBe(true); - const comprehensive = group(score, 'v3', 'comprehensive'); expect(comprehensive.reproduction).toEqual({ numerator: 0, denominator: 120, value: 0 }); expect(comprehensive.precision.value).toBeNull(); expect(comprehensive.cost.totalUSD).toBeNull(); - }); - test('fully adjudicated synthetic results exercise all release gates without missing denominators', () => { - const score = scoreEval(matrix, matrix.cells.map(syntheticResult), qualification); - expect(score.status).toBe('qualified'); expect(Object.values(score.gates).every(value => value === 'pass')).toBe(true); - expect(group(score, 'v3', 'daily').precision).toEqual({ numerator: 120, denominator: 120, value: 1 }); - expect(group(score, 'v3', 'comprehensive').highCriticalRecall).toEqual({ numerator: 96, denominator: 96, value: 1 }); - expect(score.perStack.rails).toEqual({ correctHeldOutRepairs: 10, denominator: 10 }); - }); - test('finished partial reports count their findings and outcomes and satisfy the report gates; completeness stays its own measured rate', () => { - const results = matrix.cells.map(syntheticResult); - for (const result of results) result.reportComplete = false; - const score = scoreEval(matrix, results, qualification), daily = group(score, 'v3', 'daily'), comprehensive = group(score, 'v3', 'comprehensive'); - expect(daily.reports).toEqual({ numerator: 0, denominator: 240, value: 0 }); - expect(daily.finishedReports).toEqual({ numerator: 240, denominator: 240, value: 1 }); - expect(daily.precision).toEqual({ numerator: 120, denominator: 120, value: 1 }); - expect(comprehensive.highCriticalRecall).toEqual({ numerator: 96, denominator: 96, value: 1 }); - expect(comprehensive.repair.numerator).toBe(comprehensive.repair.denominator); - expect(score.perStack.rails).toEqual({ correctHeldOutRepairs: 10, denominator: 10 }); - expect(score.gates).toMatchObject({ comprehensiveHighCriticalRecall80: 'pass', dailyPrecision95: 'pass', mandatoryReports: 'pass', matchedCompleteMatrix: 'pass' }); - expect(score.status).toBe('qualified'); - }); - test('one unfinished report fails both report gates even when every other report is finished', () => { - const results = matrix.cells.map(syntheticResult); - Object.assign(results[0], { reportComplete: false, reportFinished: false }); - const score = scoreEval(matrix, results, qualification); - expect(score.gates).toMatchObject({ mandatoryReports: 'fail', matchedCompleteMatrix: 'fail' }); - expect(score.status).toBe('partial'); - }); - test('running or missing reports contribute no security evidence and cannot qualify a complete matrix', () => { - const results = matrix.cells.map(syntheticResult); - results.forEach((result, index) => { - result.reportComplete = false; result.reportFinished = false; - if (index % 2) { result.reportPresent = false; result.findings = []; } - }); - expect(() => scoreEval(matrix, [{ ...syntheticResult(matrix.cells[0]), reportFinished: false }], qualification)).toThrow('MISSING_EVAL_REPORT'); - expect(() => scoreEval(matrix, [{ ...syntheticResult(matrix.cells[0]), reportPresent: false, reportComplete: false, findings: [] }], qualification)).toThrow('MISSING_EVAL_REPORT'); - const score = scoreEval(matrix, results, qualification), daily = group(score, 'v3', 'daily'), comprehensive = group(score, 'v3', 'comprehensive'); - expect(score.status).toBe('partial'); - expect(score.gates.matchedCompleteMatrix).toBe('fail'); - expect(score.gates.mandatoryReports).toBe('fail'); - expect(daily.reports).toEqual({ numerator: 0, denominator: 240, value: 0 }); - expect(daily.finishedReports).toEqual({ numerator: 0, denominator: 240, value: 0 }); - expect(daily.precision).toEqual({ numerator: 0, denominator: 0, value: null }); - expect(daily.recall.numerator).toBe(0); - expect(comprehensive.setup.numerator).toBe(0); - expect(comprehensive.reproduction.numerator).toBe(0); - expect(comprehensive.repair.numerator).toBe(0); - expect(comprehensive.recheck.numerator).toBe(0); - expect(score.perStack.rails.correctHeldOutRepairs).toBe(0); - }); - test('release scoring binds every trusted judgment to a complete matched producer batch', () => { - const batch = syntheticBatch(); - const results = matrix.cells.map(cell => ({ ...syntheticResult(cell), producerReceiptHash: batch.receipts.find(receipt => receipt.cell.id === cell.id)!.receiptHash })); - expect(scoreCollectedEval(matrix, batch, results, qualification)).toMatchObject({ status: 'qualified', producerBatchHash: batch.batchHash }); - delete results[0].producerReceiptHash; - expect(() => scoreCollectedEval(matrix, batch, results, qualification)).toThrow('UNBOUND_EVAL_RESULT'); - const incomplete = structuredClone(batch); incomplete.receipts.pop(); - expect(() => scoreCollectedEval(matrix, incomplete, matrix.cells.map(syntheticResult), qualification)).toThrow('INCOMPLETE_PRODUCER_BATCH'); - }); - test('rejects tampered and mixed producer installation/provider identities across incomplete batches', () => { - const cells = matrix.cells.filter(cell => cell.version === 'v2').slice(0, 2); - const first = syntheticReceipt(cells[0]); - const tampered = structuredClone(first); - tampered.installationIdentity.core.sha256 = 'f'.repeat(64); - expect(() => collectProducerReceipts(matrix, syntheticSchedule(), [rehashReceipt(tampered)])).toThrow('INVALID_PRODUCER_GENERATION_IDENTITY'); - - const artifactTamper = structuredClone(first); - artifactTamper.artifacts.totalBytes = 1; - expect(() => collectProducerReceipts(matrix, syntheticSchedule(), [rehashReceipt(artifactTamper)])).toThrow('INVALID_PRODUCER_RECEIPT'); - - const timed = rehashReceipt({ ...structuredClone(first), toolTimeline: [{ atMs: 5, endMs: 9, tool: 'Bash', agent: 'main' }, { atMs: 7, tool: 'Agent', agent: 'subagent' }] }); - expect(collectProducerReceipts(matrix, syntheticSchedule(), [timed]).receipts[0]).not.toHaveProperty('toolTimeline'); - for (const entry of [{ atMs: 9, endMs: 5, tool: 'Bash', agent: 'main' }, { atMs: 1, tool: 'cat /secret', agent: 'main' }, { atMs: 1, tool: 'Bash', agent: 'main', input: 'x' }]) - expect(() => collectProducerReceipts(matrix, syntheticSchedule(), [rehashReceipt({ ...structuredClone(first), toolTimeline: [entry] } as ProducerReceipt)])).toThrow('INVALID_PRODUCER_RECEIPT'); - - const mixedInstallation = syntheticReceipt(cells[1]); - mixedInstallation.installationIdentity = syntheticInstallationIdentity('different-installation'); - expect(() => collectProducerReceipts(matrix, syntheticSchedule(), [first, rehashReceipt(mixedInstallation)])).toThrow('UNMATCHED_PRODUCER_INSTALLATIONS'); - - const mixedProvider = syntheticReceipt(cells[1]); - mixedProvider.providerIdentity = syntheticProviderIdentity('gpt', 'different-provider'); - expect(() => collectProducerReceipts(matrix, syntheticSchedule(), [first, rehashReceipt(mixedProvider)])).toThrow('UNMATCHED_PRODUCER_PROVIDERS'); - }); - test('receipts name only an opaque cellRef that the trusted matrix resolves', () => { - const cell = matrix.cells.find(item => item.version === 'v3')!, receipt = syntheticReceipt(cell); - expect(Object.keys(receipt)).not.toContain('cell'); expect(JSON.stringify(receipt)).not.toMatch(/caseId|variant|vulnerable|"fixed"/); - expect(JSON.stringify(receipt)).not.toContain(cell.caseId); - const unknown = structuredClone(receipt); unknown.cellRef = 'f'.repeat(64); - expect(() => collectProducerReceipts(matrix, syntheticSchedule(), [rehashReceipt(unknown)])).toThrow('UNKNOWN_OR_DUPLICATE_PRODUCER_RECEIPT'); - const smuggled = rehashReceipt({ ...structuredClone(receipt), cell } as ProducerReceipt); - expect(() => collectProducerReceipts(matrix, syntheticSchedule(), [smuggled])).toThrow('INVALID_PRODUCER_RECEIPT'); - const batch = syntheticBatch(); - expect(batch.receipts.every(index => index.cellRef === index.cell.id && JSON.stringify(index.cell) === JSON.stringify(matrix.cells.find(item => item.id === index.cellRef)))).toBe(true); - const relabeled = structuredClone(batch); relabeled.receipts[0].cellRef = relabeled.receipts[1].cellRef; - const { batchHash: _hash, ...rest } = relabeled; relabeled.batchHash = createHash('sha256').update(JSON.stringify(rest)).digest('hex'); - expect(() => scoreCollectedEval(matrix, relabeled, [], qualification)).toThrow('INVALID_PRODUCER_BATCH'); - }); - test('high/critical recall includes critical cases and detects a v3 regression',()=>{ - const criticalCorpus=structuredClone(corpus);criticalCorpus.cases.find(item=>item.severity==='medium')!.severity='critical'; - const criticalMatrix=createEvalMatrix({model:'matched-test-model',host:'codex',skillHashes:{v2:'a'.repeat(64),v3:'b'.repeat(64)}},criticalCorpus),complete=criticalMatrix.cells.map(syntheticResult); - expect(group(scoreEval(criticalMatrix,complete,qualification,criticalCorpus),'v3','comprehensive').highCriticalRecall).toEqual({numerator:99,denominator:99,value:1}); - const criticalId=criticalCorpus.cases.find(item=>item.severity==='critical')!.id; - for(let index=0;index { - const cell = matrix.cells.find(item => item.version === 'v3' && item.mode === 'comprehensive' && item.variant === 'vulnerable')!; - const result = syntheticResult(cell); result.setup = 'blocked'; result.prerequisite = 'missing native library'; result.findings = []; result.reproduction = result.repair = result.recheck = 'blocked'; - const score = scoreEval(matrix, [result]); const comprehensive = group(score, 'v3', 'comprehensive'); - expect(comprehensive.setup).toEqual({ numerator: 0, denominator: 240, value: 0 }); expect(comprehensive.highCriticalRecall.denominator).toBe(96); expect(comprehensive.setupBlocked).toBe(1); - }); - test('duplicate findings do not inflate precision and fixed-source false positives count', () => { - const positive = matrix.cells.find(item => item.version === 'v3' && item.mode === 'daily' && item.variant === 'vulnerable')!; - const negative = matrix.cells.find(item => item.version === 'v3' && item.mode === 'daily' && item.variant === 'fixed')!; - const one = syntheticResult(positive); one.findings.push({ ...one.findings[0], id: 'duplicate' }); - const two = syntheticResult(negative); two.findings.push({ id: 'false-positive', evidence: 'supported', claimedTested: false, judgment: 'incorrect' }); - expect(group(scoreEval(matrix, [one, two]), 'v3', 'daily').precision).toEqual({ numerator: 1, denominator: 3, value: 1 / 3 }); - }); - test('confirmed incidental issues count once each for precision, declared instrumentation counts in neither term, and recall still needs the seeded issue', () => { - const positive = matrix.cells.find(item => item.version === 'v3' && item.mode === 'daily' && item.variant === 'vulnerable')!; - const negative = matrix.cells.find(item => item.version === 'v3' && item.mode === 'daily' && item.variant === 'fixed')!; - const key = (seed: string) => createHash('sha256').update(seed).digest('hex'); - const one = syntheticResult(positive); - one.findings.push({ id: 'jwt', evidence: 'supported', claimedTested: false, judgment: 'incidental', incidentalKey: key('jwt') }, { id: 'jwt-again', evidence: 'supported', claimedTested: false, judgment: 'incidental', incidentalKey: key('jwt') }); - one.findings.push({ id: 'canary', evidence: 'supported', claimedTested: false, judgment: 'instrumentation' }, { id: 'guess', evidence: 'hypothesis', claimedTested: false, judgment: 'incidental', incidentalKey: key('guess') }); - const two = syntheticResult(negative); - two.findings.push({ id: 'admin', evidence: 'supported', claimedTested: false, judgment: 'incidental', incidentalKey: key('admin') }, { id: 'probe', evidence: 'supported', claimedTested: false, judgment: 'instrumentation' }, { id: 'noise', evidence: 'supported', claimedTested: false, judgment: 'incorrect' }); - expect(() => scoreEval(matrix, [one])).toThrow('INVALID_FINDING_JUDGMENT'); - one.findings.pop(); - expect(group(scoreEval(matrix, [one, two]), 'v3', 'daily').precision).toEqual({ numerator: 3, denominator: 5, value: 3 / 5 }); - const missed = syntheticResult(positive); missed.findings = [{ id: 'only-incidental', evidence: 'supported', claimedTested: false, judgment: 'incidental', incidentalKey: key('x') }]; - expect(group(scoreEval(matrix, [missed]), 'v3', 'daily').recall.numerator).toBe(0); - for (const bad of [{ judgment: 'incidental' }, { judgment: 'incidental', incidentalKey: 'short' }, { judgment: 'incorrect', incidentalKey: key('y') }, { judgment: 'instrumentation', matchedCaseId: positive.caseId }, { judgment: 'incidental', incidentalKey: key('z'), matchedCaseId: positive.caseId }]) { - const result = syntheticResult(positive); result.findings.push({ id: 'bad', evidence: 'supported', claimedTested: false, ...bad } as EvalFinding); - expect(() => scoreEval(matrix, [result])).toThrow('INVALID_FINDING_JUDGMENT'); - } - }); - test('producer tested claims require independent successful held-out repair evidence', () => { - const cell = matrix.cells.find(item => item.version === 'v3' && item.mode === 'comprehensive' && item.variant === 'vulnerable')!; - const result = syntheticResult(cell); delete result.oracleEvidenceHash; - const score = scoreEval(matrix, [result]); expect(group(score, 'v3', 'comprehensive').falseTested).toBe(1); expect(group(score, 'v3', 'comprehensive').repair.numerator).toBe(0); - }); - test('one trusted cell repair cannot certify another claimed-tested finding', () => { - const results = matrix.cells.map(syntheticResult), cell = matrix.cells.find(item => item.version === 'v3' && item.mode === 'comprehensive' && item.variant === 'vulnerable')!, result = results.find(item => item.cellId === cell.id)!; - result.findings.push({ id: 'unbound-tested-claim', evidence: 'supported', claimedTested: true, judgment: 'correct', matchedCaseId: cell.caseId }); - const score = scoreEval(matrix, results, qualification); - expect(group(score, 'v3', 'comprehensive').falseTested).toBe(1); expect(score.gates.zeroFalselyTestedRepairs).toBe('fail'); expect(score.status).toBe('partial'); - result.findings[1].trustedVerification = structuredClone(result.findings[0].trustedVerification); - expect(() => scoreEval(matrix, results, qualification)).toThrow('DUPLICATE_TRUSTED_REPAIR_BINDING'); - }); - test('tested claims on declared instrumentation count in neither direction; an incidental claim needs a passing replay of its signed bundle', () => { - const key = (seed: string) => createHash('sha256').update(seed).digest('hex'); - const vulnerable = matrix.cells.find(item => item.version === 'v3' && item.mode === 'comprehensive' && item.variant === 'vulnerable')!; - const fixed = matrix.cells.find(item => item.version === 'v3' && item.mode === 'comprehensive' && item.variant === 'fixed')!; - const daily = matrix.cells.find(item => item.version === 'v3' && item.mode === 'daily' && item.variant === 'fixed')!; - const score = (edit: (byId: Map) => void) => { - const results = matrix.cells.map(syntheticResult), byId = new Map(results.map(result => [result.cellId, result])); - edit(byId); - return scoreEval(matrix, results, qualification); - }; - const clean = score(() => {}); - expect(clean.gates.zeroFalselyTestedRepairs).toBe('pass'); - const incidental = (id: string, replay?: EvalFinding['trustedReplay']): EvalFinding => ({ id, evidence: 'supported', claimedTested: true, judgment: 'incidental', incidentalKey: key(id), ...(replay ? { trustedReplay: replay } : {}) }); - - const instrumented = score(byId => { - byId.get(fixed.id)!.findings.push({ id: 'canary-claim', evidence: 'supported', claimedTested: true, judgment: 'instrumentation' }); - byId.get(daily.id)!.findings.push({ id: 'probe-claim', evidence: 'supported', claimedTested: true, judgment: 'instrumentation' }); - }); - expect(group(instrumented, 'v3', 'comprehensive').falseTested).toBe(0); expect(group(instrumented, 'v3', 'daily').falseTested).toBe(0); - expect(instrumented.gates.zeroFalselyTestedRepairs).toBe('pass'); - - const instrumentationOnly = score(byId => { - const result = byId.get(vulnerable.id)!, binding = result.findings[0].trustedVerification!; - result.findings = [{ id: 'canary-claim', evidence: 'supported', claimedTested: true, judgment: 'instrumentation', trustedVerification: structuredClone(binding) }]; - }); - const empty = score(byId => { byId.get(vulnerable.id)!.findings = []; }), baseline = group(clean, 'v3', 'comprehensive'); - const sameAsNoFinding = (scored: ReturnType) => { - const actual = group(scored, 'v3', 'comprehensive'), none = group(empty, 'v3', 'comprehensive'); - expect(actual.falseTested).toBe(0); - expect([actual.recall, actual.highCriticalRecall, actual.repair, actual.recheck]).toEqual([none.recall, none.highCriticalRecall, none.repair, none.recheck]); - expect(scored.perStack).toEqual(empty.perStack); - expect(actual.recall.numerator).toBe(baseline.recall.numerator - 1); - expect(actual.repair.numerator).toBe(baseline.repair.numerator - 1); - }; - sameAsNoFinding(instrumentationOnly); - - for (const [replay, expected] of [[undefined, 1], [{ result: 'missing' }, 1], [{ result: 'failed' }, 1], [{ result: 'passed', replayEvidenceHash: key('replay') }, 0]] as const) { - const scored = score(byId => byId.get(fixed.id)!.findings.push(incidental('jwt-claim', replay as EvalFinding['trustedReplay']))); - expect(group(scored, 'v3', 'comprehensive').falseTested).toBe(expected); - expect(scored.gates.zeroFalselyTestedRepairs).toBe(expected ? 'fail' : 'pass'); - } - const replayedOnly = score(byId => { byId.get(vulnerable.id)!.findings = [incidental('admin-claim', { result: 'passed', replayEvidenceHash: key('admin') })]; }); - sameAsNoFinding(replayedOnly); - - const passed = { result: 'passed', replayEvidenceHash: key('r') } as const; - for (const bad of [ - { id: 'on-correct', evidence: 'supported', claimedTested: true, judgment: 'correct', matchedCaseId: vulnerable.caseId, trustedReplay: passed }, - { id: 'on-instrumentation', evidence: 'supported', claimedTested: true, judgment: 'instrumentation', trustedReplay: passed }, - { id: 'on-incorrect', evidence: 'supported', claimedTested: true, judgment: 'incorrect', trustedReplay: { result: 'failed' } }, - { ...incidental('unclaimed', passed), claimedTested: false }, - incidental('no-hash', { result: 'passed' } as EvalFinding['trustedReplay']), - incidental('failed-hash', { result: 'failed', replayEvidenceHash: key('f') } as EvalFinding['trustedReplay']), - incidental('short-hash', { result: 'passed', replayEvidenceHash: 'abc' }), - incidental('extra-key', { ...passed, repair: 'passed' } as EvalFinding['trustedReplay']), - incidental('bad-result', { result: 'skipped' } as unknown as EvalFinding['trustedReplay']), - ] as EvalFinding[]) { - expect(() => score(byId => byId.get(vulnerable.id)!.findings.push(bad))).toThrow('INVALID_TRUSTED_REPLAY'); - } - expect(() => score(byId => byId.get(fixed.id)!.findings.push(incidental('one', passed), incidental('two', passed)))).toThrow('DUPLICATE_TRUSTED_REPLAY_BINDING'); - }); - test('per-stack held-out repair requires the matching supported discovery', () => { - const results = matrix.cells.map(syntheticResult); - for (let index = 0; index < matrix.cells.length; index++) { - const cell = matrix.cells[index]; - if (cell.version === 'v3' && cell.mode === 'comprehensive' && cell.variant === 'vulnerable' && cell.stack === 'rails') results[index].findings = []; - } - const score = scoreEval(matrix, results, qualification); - expect(score.perStack.rails).toEqual({ correctHeldOutRepairs: 0, denominator: 10 }); - expect(score.gates.heldOutRepairEachStack).toBe('fail'); - }); - test('legacy review evidence cannot raise v3 recall or earn tested repair', () => { - const cell = matrix.cells.find(item => item.version === 'v3' && item.mode === 'comprehensive' && item.variant === 'vulnerable')!; - const result = syntheticResult(cell); result.findings[0].evidence = 'legacy_review'; - const score = scoreEval(matrix, [result]); expect(group(score, 'v3', 'comprehensive').recall.numerator).toBe(0); expect(group(score, 'v3', 'comprehensive').falseTested).toBe(1); - }); - test('old-source recheck and missing held-out assertions cannot establish repair success', () => { - const cell = matrix.cells.find(item => item.version === 'v3' && item.mode === 'comprehensive' && item.variant === 'vulnerable')!; - const result = syntheticResult(cell); result.currentSourceHash = cell.sourceHash; - expect(group(scoreEval(matrix, [result]), 'v3', 'comprehensive').recheck.numerator).toBe(0); - result.heldOutAssertionsPassed = false; expect(group(scoreEval(matrix, [result]), 'v3', 'comprehensive').repair.numerator).toBe(0); - }); - test('accepts a correct alternative patch but rejects reused repair evidence for closure', () => { - const cell = matrix.cells.find(item => item.version === 'v3' && item.mode === 'comprehensive' && item.variant === 'vulnerable')!; - const result = syntheticResult(cell); result.currentSourceHash = 'e'.repeat(64); - expect(group(scoreEval(matrix, [result]), 'v3', 'comprehensive').recheck.numerator).toBe(1); - result.recheckEvidenceHash = result.oracleEvidenceHash; - expect(group(scoreEval(matrix, [result]), 'v3', 'comprehensive').recheck.numerator).toBe(0); - }); - test('rejects mismatched model budgets, duplicate results, and application execution in daily mode', () => { - const result = syntheticResult(matrix.cells[0]); - expect(() => scoreEval(matrix, [result, result])).toThrow('UNKNOWN_OR_DUPLICATE'); - expect(() => scoreEval(matrix, [{ ...result, model: 'other-model' }])).toThrow('UNMATCHED_EVAL_RESULT'); - expect(() => scoreEval(matrix, [{ ...result, setup: 'passed' }])).toThrow('DAILY_EVAL_EXECUTED'); - const comprehensive = syntheticResult(matrix.cells.find(cell => cell.version === 'v3' && cell.mode === 'comprehensive' && cell.variant === 'vulnerable')!); - comprehensive.findings[0].trustedVerification = { repair: 'failed', repairEvidenceHash: 'not-a-hash', recheck: 'not_attempted' }; - expect(() => scoreEval(matrix, [comprehensive])).toThrow('INVALID_TRUSTED_FINDING_VERIFICATION'); - }); - test('missing containment tests remain unmeasured and a failed canary fails qualification', () => { - const results = matrix.cells.map(syntheticResult); - expect(scoreEval(matrix, results).gates.containmentAndCanaries).toBe('unmeasured'); - expect(scoreEval(matrix, results, { containment: { 'split-output-secrets': 'failed' } }).gates.containmentAndCanaries).toBe('fail'); - }); - test('precision and high-impact recall thresholds fail independently on a complete matrix', () => { - const results = matrix.cells.map(syntheticResult); - let falsePositives = 0, misses = 0; - for (let index = 0; index < matrix.cells.length; index++) { - const cell = matrix.cells[index]; - if (cell.version === 'v3' && cell.mode === 'daily' && cell.variant === 'fixed' && falsePositives < 7) { - results[index].findings = [{ id: 'false-positive', evidence: 'supported', claimedTested: false, judgment: 'incorrect' }]; falsePositives++; - } - if (cell.version === 'v3' && cell.mode === 'comprehensive' && cell.variant === 'vulnerable' && corpus.cases.find(fixture => fixture.id === cell.caseId)!.severity === 'high' && misses < 20) { - results[index].findings = []; misses++; - } - } - const score = scoreEval(matrix, results, qualification); - expect(score.gates.dailyPrecision95).toBe('fail'); expect(score.gates.comprehensiveHighCriticalRecall80).toBe('fail'); expect(score.gates.noHighCriticalRecallRegression).toBe('fail'); - }); -}); - -/** Synthetic stand-in with the private corpus layout. It is not held-out content. */ -const privateFiles = (id: string, variant: EvalVariant): Record => ({ 'README.md': '# Synthetic service\n', 'src/app.txt': `synthetic ${id} ${variant}\n` }); -const privateManifest: CorpusManifest = { schemaVersion: 1, version: 'synthetic-private-1', cases: STACKS.flatMap(stack => ['alpha-family', 'beta-family'].map((family, index) => { - const id = `${stack}-${family}`; - return { id, stack, family, severity: index === 0 ? 'high' as const : 'medium' as const, rootCause: family, location: { path: 'src/app.txt', symbol: 'action' }, - coreColdStart: true as const, heldOut: true as const, filesHash: { vulnerable: sourceHash(privateFiles(id, 'vulnerable')), fixed: sourceHash(privateFiles(id, 'fixed')) } }; -})) }; -const privateCorpus = defineEvalCorpus(privateManifest, privateFiles); -const releasePlatforms = { daily: 'linux/amd64' as const, comprehensive: Object.fromEntries(privateManifest.cases.map((fixture, index) => [fixture.id, index % 2 ? 'linux/arm64' as const : 'linux/amd64' as const])) }; -const releaseOptions = { profile: 'release' as const, model: 'matched-test-model', host: 'codex' as const, skillHashes: { v3: 'b'.repeat(64) }, platforms: releasePlatforms }; -function privateBaseline(mutate: (results: EvalResult[], cells: EvalCell[]) => void = () => {}): EvalBaseline { - const baselineMatrix = createEvalMatrix({ profile: 'baseline', model: 'matched-test-model', host: 'codex', skillHashes: { v2: 'a'.repeat(64) }, platforms: { comprehensive: releasePlatforms.comprehensive } }, privateManifest); - const batch = collectProducerReceipts(baselineMatrix, syntheticSchedule(baselineMatrix), baselineMatrix.cells.map(syntheticReceipt), privateManifest); - const results = baselineMatrix.cells.map(cell => ({ ...syntheticResultFor(cell, privateManifest), producerReceiptHash: batch.receipts.find(receipt => receipt.cell.id === cell.id)!.receiptHash })); - mutate(results, baselineMatrix.cells); - return createEvalBaseline(baselineMatrix, batch, results, privateManifest); -} -function releaseRun(baseline: EvalBaseline | null = privateBaseline()) { - const release = createEvalMatrix({ ...releaseOptions, ...(baseline ? { baseline } : {}) }, privateManifest); - const batch = collectProducerReceipts(release, syntheticSchedule(release), release.cells.map(syntheticReceipt), privateManifest); - const results = release.cells.map(cell => ({ ...syntheticResultFor(cell, privateManifest), producerReceiptHash: batch.receipts.find(receipt => receipt.cell.id === cell.id)!.receiptHash })); - return { release, batch, results }; -} - -describe('CSO release profile on an injected corpus', () => { - test('the full profile matrix is byte-identical to its pre-release-profile form', () => { - expect(createHash('sha256').update(JSON.stringify(matrix)).digest('hex')).toBe('a0f20a127c8c92c73bb2a277f740295c153ccf95901e92cffab34a4553ef976b'); - expect('profile' in matrix).toBe(false); expect(matrix.cells.every(cell => !('platform' in cell))).toBe(true); - }); - test('an injected corpus shares the public layout and binds every generated source', () => { - expect(validateCorpusManifest(structuredClone(corpus))).toEqual(corpus); - const destination = join(root(), 'case'); - expect(materializeCase('rails-beta-family', 'fixed', destination, privateCorpus).sourceHash).toBe(privateManifest.cases.find(item => item.id === 'rails-beta-family')!.filesHash.fixed); - expect(readFileSync(join(destination, 'src/app.txt'), 'utf8')).toBe('synthetic rails-beta-family fixed\n'); - expect(() => defineEvalCorpus({ ...privateManifest, version: CORPUS_VERSION }, privateFiles)).toThrow('INJECTED_CORPUS_REUSES_PUBLIC_VERSION'); - expect(() => defineEvalCorpus(privateManifest, (id, variant) => ({ ...privateFiles(id, variant), extra: 'drift' }))).toThrow('CORPUS_INTEGRITY_MISMATCH'); - expect(() => defineEvalCorpus(privateManifest, () => ({ '../escape.txt': 'x' }))).toThrow('INVALID_CORPUS_SOURCE'); - const unknownStack = structuredClone(privateManifest); (unknownStack.cases[0] as any).stack = 'php'; - expect(() => validateCorpusManifest(unknownStack)).toThrow('INVALID_CORPUS_MANIFEST'); - const extraField = structuredClone(privateManifest); (extraField.cases[0] as any).answer = 'oracle'; - expect(() => validateCorpusManifest(extraField)).toThrow('INVALID_CORPUS_MANIFEST'); - }); - test('release pins v3, one repetition, and one native platform per cell', () => { - const release = createEvalMatrix(releaseOptions, privateManifest); - expect(release.cells).toHaveLength(privateManifest.cases.length * 4); expect(release.repetitions).toBe(1); expect(release.baselineHash).toBeNull(); - expect(release.cells.every(cell => cell.version === 'v3' && cell.repetition === 1)).toBe(true); - expect(release.cells.filter(cell => cell.mode === 'daily').every(cell => cell.platform === 'linux/amd64')).toBe(true); - for (const cell of release.cells.filter(item => item.mode === 'comprehensive')) expect(cell.platform).toBe(releasePlatforms.comprehensive[cell.caseId]); - expect(new Set(release.cells.filter(cell => cell.mode === 'comprehensive').map(cell => cell.platform))).toEqual(new Set(['linux/amd64', 'linux/arm64'])); - validateMatrix(release, privateManifest); - const moved = structuredClone(release); moved.platforms.comprehensive[privateManifest.cases[0].id] = 'linux/arm64'; - expect(() => validateMatrix(moved, privateManifest)).toThrow('UNMATCHED_OR_INCOMPLETE_EVAL_MATRIX'); - const { [privateManifest.cases[0].id]: _omitted, ...partial } = releasePlatforms.comprehensive; - expect(() => createEvalMatrix({ ...releaseOptions, platforms: { daily: 'linux/amd64', comprehensive: partial } }, privateManifest)).toThrow('INVALID_EVAL_PLATFORMS'); - expect(() => createEvalMatrix({ ...releaseOptions, platforms: { daily: 'linux/riscv64' as any, comprehensive: releasePlatforms.comprehensive } }, privateManifest)).toThrow('INVALID_EVAL_PLATFORMS'); - expect(() => createEvalMatrix({ ...releaseOptions, skillHashes: { v2: 'a'.repeat(64), v3: 'b'.repeat(64) } as any }, privateManifest)).toThrow('INVALID_MATCHED_EVAL_INPUT'); - }); - test('a two-platform batch collects and scores qualified against a hash-bound v2 baseline', () => { - const { release, batch, results } = releaseRun(); - expect(new Set(batch.receipts.map(receipt => receipt.installationIdentity.identityHash)).size).toBe(2); - expect(batch.summary.groups.map(group => `${group.version}:${group.mode}`)).toEqual(['v3:daily', 'v3:comprehensive']); - const baseline = privateBaseline(); - const score = scoreCollectedEval(release, batch, results, qualification, privateManifest, baseline); - expect(score.status).toBe('qualified'); expect(Object.values(score.gates).every(value => value === 'pass')).toBe(true); - expect(score.profile).toBe('release'); expect(score.baseline).toEqual({ baselineHash: baseline.baselineHash, highCriticalRecall: { numerator: 4, denominator: 4, value: 1 } }); - expect(score.groups.map(item => `${item.version}:${item.mode}`)).toEqual(['v3:daily', 'v3:comprehensive']); - }); - test('a mixed-corpus batch is rejected', () => { - const { release, batch, results } = releaseRun(); - expect(() => scoreCollectedEval(release, batch, results, qualification)).toThrow('UNMATCHED_OR_INCOMPLETE_EVAL_MATRIX'); - expect(() => collectProducerReceipts(release, syntheticSchedule(release), release.cells.map(syntheticReceipt))).toThrow('UNMATCHED_OR_INCOMPLETE_EVAL_MATRIX'); - const mixed = structuredClone(release); mixed.cells[0] = { ...matrix.cells.find(cell => cell.version === 'v3' && cell.repetition === 1)!, platform: 'linux/amd64' }; - expect(() => validateMatrix(mixed, privateManifest)).toThrow('UNMATCHED_OR_INCOMPLETE_EVAL_MATRIX'); - const publicCell = matrix.cells.find(cell => cell.version === 'v3')!; - expect(() => collectProducerReceipts(release, syntheticSchedule(release), [syntheticReceipt(publicCell)], privateManifest)).toThrow('UNKNOWN_OR_DUPLICATE_PRODUCER_RECEIPT'); - expect(() => scoreCollectedEval(release, syntheticBatch(), results, qualification, privateManifest)).toThrow('INVALID_PRODUCER_BATCH'); - expect(() => scoreEval(release, [syntheticResult(publicCell)], qualification, privateManifest)).toThrow('UNKNOWN_OR_DUPLICATE_EVAL_RESULT'); - }); - test('artifact inventories need unique paths in the order their identity hash binds, including 1.91.75 locale order', () => { - const release = createEvalMatrix(releaseOptions, privateManifest), schedule = syntheticSchedule(release), cell = release.cells[0]; - const withEntries = (paths: string[]) => { - const receipt = syntheticReceipt(cell), entries = paths.map(path => ({ path: `${'e'.repeat(24)}/1791702612575-${'a'.repeat(16)}/${path}`, sha256: sha256(path), bytes: 1 })); - const base = { schemaVersion: 1 as const, root: 'security/cso' as const, entries, totalBytes: entries.length }; - receipt.artifacts = { ...base, identityHash: producerArtifactInventoryHash(base) }; - return rehashReceipt(receipt); - }; - for (const order of [['README.md', 'package.json', 'snapshot.json', 'snapshot/x'], ['package.json', 'README.md', 'snapshot.json', 'snapshot/x']]) { - expect(collectProducerReceipts(release, schedule, [withEntries(order)], privateManifest).summary.submitted).toBe(1); - } - expect(() => collectProducerReceipts(release, schedule, [withEntries(['README.md', 'package.json', 'README.md'])], privateManifest)).toThrow('INVALID_PRODUCER_RECEIPT'); - }); - test('platforms whose evaluation catalogs differ only in qualification time match when the embedded bodies prove it', () => { - const staged = imageBuildMatrix(buildInputs).include.map(row => ({ - schemaVersion: 1, helperAbi: CSO_HELPER_ABI, state: 'staged', verifiedProvenance: true, buildRevision: row.inputRevision, runtimeId: row.runtimeId, stack: row.stack, platform: row.platform, - image: `ghcr.io/garrytan/gstack/cso-staging/${row.stack}-${row.arch}@sha256:${sha256(row.runtimeId)}`, versions: row.versions, sourceCommit: 'a'.repeat(40), - workflow: 'https://github.com/garrytan/gstack/actions/runs/123456', sbomDigest: `sha256:${sha256(`sbom:${row.runtimeId}`)}`, provenanceDigest: `sha256:${sha256(`provenance:${row.runtimeId}`)}`, - qualification: 'pending native and private release gates; no automatic promotion', - })); - const [amdCatalog, armCatalog] = ['2026-10-11T07:05:29.256Z', '2026-10-11T07:05:32.067Z'].map(at => evaluationCandidateCatalog(committedRuntimeCatalog, buildInputs, staged, at)); - const release = createEvalMatrix(releaseOptions, privateManifest), schedule = syntheticSchedule(release); - const amd = release.cells.find(cell => cell.platform === 'linux/amd64')!, arm = release.cells.find(cell => cell.platform === 'linux/arm64')!; - const embedding = (cell: EvalCell, catalog: RuntimeCatalog) => { - const receipt = syntheticReceipt(cell), { identityHash: _hash, ...identity } = receipt.installationIdentity; - identity.embeddedCatalogs = { ...identity.embeddedCatalogs, runtimeRevision: catalog.revision, runtimeSha256: sha256(JSON.stringify(catalog)) }; - receipt.installationIdentity = { ...identity, identityHash: producerInstallationIdentityHash(identity) }; - return rehashReceipt(receipt); - }; - const receipts = [embedding(amd, amdCatalog), embedding(arm, armCatalog)]; - expect(() => collectProducerReceipts(release, schedule, receipts, privateManifest)).toThrow('UNMATCHED_PRODUCER_INSTALLATIONS'); - const batch = collectProducerReceipts(release, schedule, receipts, privateManifest, [armCatalog, amdCatalog]); - expect(batch.embeddedCatalogs).toEqual([armCatalog, amdCatalog]); - expect(collectProducerReceipts(release, schedule, [embedding(amd, amdCatalog), embedding(arm, amdCatalog)], privateManifest).embeddedCatalogs).toBeUndefined(); - const complete = collectProducerReceipts(release, schedule, release.cells.map(cell => embedding(cell, cell.platform === 'linux/amd64' ? amdCatalog : armCatalog)), privateManifest, [amdCatalog, armCatalog]); - const results = release.cells.map(cell => ({ ...syntheticResultFor(cell, privateManifest), producerReceiptHash: complete.receipts.find(receipt => receipt.cell.id === cell.id)!.receiptHash })); - expect(scoreCollectedEval(release, complete, results, qualification, privateManifest).groups.every(item => item.submitted === item.cells)).toBe(true); - const { batchHash: _batchHash, embeddedCatalogs: _catalogs, ...stripped } = complete; - expect(() => scoreCollectedEval(release, { ...stripped, batchHash: sha256(JSON.stringify(stripped)) }, results, qualification, privateManifest)).toThrow('UNMATCHED_PRODUCER_INSTALLATIONS'); - const movedImage = structuredClone(armCatalog); movedImage.runtimes[0].image = movedImage.runtimes[0].image.replace(/@sha256:.{8}/, '@sha256:00000000'); - movedImage.evaluation!.evidenceDigest = `sha256:${sha256(canonical(movedImage.runtimes))}`; - for (const bodies of [[amdCatalog], [amdCatalog, amdCatalog], [amdCatalog, movedImage]]) { - const tampered = bodies.includes(movedImage) ? [embedding(amd, amdCatalog), embedding(arm, movedImage)] : receipts; - expect(() => collectProducerReceipts(release, schedule, tampered, privateManifest, bodies)).toThrow('UNMATCHED_PRODUCER_INSTALLATIONS'); - } - }); - test('identity checks hold per platform and require shared catalogs and provider policy across platforms', () => { - const release = createEvalMatrix(releaseOptions, privateManifest), schedule = syntheticSchedule(release); - const amd = release.cells.filter(cell => cell.platform === 'linux/amd64'), arm = release.cells.find(cell => cell.platform === 'linux/arm64')!; - const relabel = (cell: EvalCell, change: (receipt: ProducerReceipt) => void) => { const receipt = syntheticReceipt(cell); change(receipt); return rehashReceipt(receipt); }; - expect(() => collectProducerReceipts(release, schedule, [syntheticReceipt(amd[0]), relabel(amd[1], receipt => { receipt.installationIdentity = syntheticInstallationIdentity('second-amd64', '1'); })], privateManifest)).toThrow('UNMATCHED_PRODUCER_INSTALLATIONS'); - expect(() => collectProducerReceipts(release, schedule, [syntheticReceipt(amd[0]), relabel(amd[1], receipt => { receipt.providerIdentity = syntheticProviderIdentity('gpt', 'second-amd64'); })], privateManifest)).toThrow('UNMATCHED_PRODUCER_PROVIDERS'); - expect(() => collectProducerReceipts(release, schedule, [syntheticReceipt(amd[0]), relabel(arm, receipt => { receipt.installationIdentity = syntheticInstallationIdentity('linux/amd64', '1'); })], privateManifest)).toThrow('UNMATCHED_PRODUCER_PLATFORMS'); - expect(() => collectProducerReceipts(release, schedule, [syntheticReceipt(amd[0]), relabel(arm, receipt => { receipt.installationIdentity = syntheticInstallationIdentity('linux/arm64', 'other-catalog'); })], privateManifest)).toThrow('UNMATCHED_PRODUCER_INSTALLATIONS'); - const otherPolicy = (() => { const { identityHash: _hash, ...base } = syntheticProviderIdentity('gpt', 'linux/arm64'); const changed = { ...base, policyRevision: 'gpt-other-policy' }; return { ...changed, identityHash: producerProviderIdentityHash(changed) }; })(); - expect(() => collectProducerReceipts(release, schedule, [syntheticReceipt(amd[0]), relabel(arm, receipt => { receipt.providerIdentity = otherPolicy; })], privateManifest)).toThrow('UNMATCHED_PRODUCER_PROVIDERS'); - expect(() => collectProducerReceipts(release, schedule, [syntheticReceipt(amd[0]), relabel(amd[1], receipt => { receipt.modelUsed = 'resolved-other-model'; })], privateManifest)).toThrow('UNMATCHED_EFFECTIVE_MODELS'); - }); - test('the external v2 baseline is pre-registered, complete, and bound to the release inputs', () => { - const unpinned = releaseRun(null); - const unmeasured = scoreCollectedEval(unpinned.release, unpinned.batch, unpinned.results, qualification, privateManifest); - expect(unmeasured.gates.noHighCriticalRecallRegression).toBe('unmeasured'); expect(unmeasured.status).toBe('partial'); expect(unmeasured.baseline).toBeNull(); - const baseline = privateBaseline(); - expect(() => scoreCollectedEval(unpinned.release, unpinned.batch, unpinned.results, qualification, privateManifest, baseline)).toThrow('UNBOUND_EVAL_BASELINE'); - const { release, batch, results } = releaseRun(baseline); - const forged = structuredClone(baseline); forged.cases[0].found = false; - expect(() => scoreCollectedEval(release, batch, results, qualification, privateManifest, forged)).toThrow('UNBOUND_EVAL_BASELINE'); - const weaker = privateBaseline(found => { found.forEach(result => { result.findings = []; }); }); - expect(() => scoreCollectedEval(release, batch, results, qualification, privateManifest, weaker)).toThrow('UNBOUND_EVAL_BASELINE'); - expect(() => createEvalMatrix({ ...releaseOptions, model: 'other-model', baseline }, privateManifest)).toThrow('UNBOUND_EVAL_BASELINE'); - expect(() => createEvalMatrix({ ...releaseOptions, budgets: { daily: 600, comprehensive: 1200 }, baseline }, privateManifest)).toThrow('UNBOUND_EVAL_BASELINE'); - const otherProvider = structuredClone(baseline); otherProvider.provider.version = 'gpt-other-version'; - const { baselineHash: _hash, ...record } = otherProvider; otherProvider.baselineHash = createHash('sha256').update(JSON.stringify(record)).digest('hex'); - const rebound = releaseRun(otherProvider); - expect(() => scoreCollectedEval(rebound.release, rebound.batch, rebound.results, qualification, privateManifest, otherProvider)).toThrow('UNBOUND_EVAL_BASELINE'); - const highId = privateManifest.cases.find(item => item.severity === 'high')!.id; - for (let index = 0; index < release.cells.length; index++) { - const cell = release.cells[index]; - if (cell.mode === 'comprehensive' && cell.variant === 'vulnerable' && cell.caseId === highId) results[index].findings = []; - } - const regressed = scoreCollectedEval(release, batch, results, qualification, privateManifest, baseline); - expect(regressed.gates.noHighCriticalRecallRegression).toBe('fail'); expect(regressed.baseline!.highCriticalRecall.value).toBe(1); - }); - test('a baseline finds a seeded issue in a finished partial report, never in a running or missing one', () => { - const vulnerable: string[] = []; - const baseline = privateBaseline((results, cells) => { - const indexes = cells.flatMap((cell, index) => cell.variant === 'vulnerable' ? [index] : []).slice(0, 3); - vulnerable.push(...indexes.map(index => cells[index].caseId)); - results[indexes[0]].reportComplete = false; - Object.assign(results[indexes[1]], { reportComplete: false, reportFinished: false }); - Object.assign(results[indexes[2]], { reportComplete: false, reportFinished: false, reportPresent: false, findings: [] }); - }); - expect(vulnerable.map(caseId => baseline.cases.find(entry => entry.caseId === caseId)!.found)).toEqual([true, false, false]); - }); - test('baseline records refuse incomplete or unadjudicated runs and baseline matrices never qualify', () => { - expect(() => privateBaseline(results => { results.pop(); })).toThrow('INCOMPLETE_EVAL_BASELINE'); - expect(() => privateBaseline((results, cells) => { results[cells.findIndex(cell => cell.variant === 'vulnerable')].findings[0].judgment = 'unadjudicated'; })).toThrow('UNADJUDICATED_EVAL_BASELINE'); - const baselineMatrix = createEvalMatrix({ profile: 'baseline', model: 'matched-test-model', host: 'codex', skillHashes: { v2: 'a'.repeat(64) }, platforms: { comprehensive: releasePlatforms.comprehensive } }, privateManifest); - expect(baselineMatrix.cells.every(cell => cell.version === 'v2' && cell.mode === 'comprehensive')).toBe(true); - expect(() => scoreEval(baselineMatrix, [], qualification, privateManifest)).toThrow('BASELINE_PROFILE_NOT_QUALIFIABLE'); - expect(() => scoreEval(matrix, [], qualification, corpus, privateBaseline())).toThrow('UNBOUND_EVAL_BASELINE'); - }); -}); - -describe('CSO matched producer orchestration', () => { - const skills = { v2: portableSkill('v2', 'V2_SECTION_ONLY'), v3: portableSkill('v3', 'V3_SECTION_ONLY') }; - const producerMatrix = createEvalMatrix({ model: 'exact-eval-model', host: 'codex', skillHashes: { v2: sha256(skills.v2), v3: sha256(skills.v3) } }); - const selected = producerMatrix.cells.filter(cell => cell.caseId === 'node-sql-injection' && cell.variant === 'vulnerable' && cell.mode === 'daily' && cell.repetition === 1); - const isolate = (prepared: string, cell: EvalCell) => { - const producerRoot = join(root(), 'producer'); mkdirSync(producerRoot); - const job = join(producerRoot, 'job'); cpSync(join(prepared, 'jobs', cell.id), job, { recursive: true }); - return { job, input: join(job, 'producer-input.json'), source: join(job, 'source') }; - }; - const helperBundle = (directory = join(root(), 'helpers')) => { - mkdirSync(directory, { recursive: true }); - const suffix = process.platform === 'win32' ? '.exe' : ''; - for (const name of ['cso-eval-producer', 'gstack-cso-launcher', 'gstack-cso-core', 'gstack-cso-watchdog']) { - const path = join(directory, `${name}${suffix}`); - writeFileSync(path, process.platform === 'win32' ? 'test executable\n' : '#!/bin/sh\nexit 0\n', { mode: 0o755 }); - if (process.platform !== 'win32') chmodSync(path, 0o755); - } - const core = join(directory, `gstack-cso-core${suffix}`); - writeFileSync(join(directory, '.gstack-cso-generation'), `${sha256(readFileSync(core))}\n`, { mode: 0o644 }); - writeFileSync(join(directory, `provider-test${suffix}`), process.platform === 'win32' ? 'test provider\n' : '#!/bin/sh\nexit 0\n', { mode: 0o755 }); - return join(directory, `gstack-cso-launcher${suffix}`); - }; - const providerCommandFor = (launcher: string) => ({ executable: join(dirname(launcher), `provider-test${process.platform === 'win32' ? '.exe' : ''}`), argsPrefix: [] as string[] }); - const providerIdentityFor = (family: Family, launcher: string): ProducerProviderIdentity => { - const command = providerCommandFor(launcher), contents = readFileSync(command.executable); - const withoutHash: Omit = { - schemaVersion: 1, - family, - policyRevision: `${family}-test-policy`, - executable: { sha256: sha256(contents), bytes: contents.byteLength }, - argsPrefix: [], - version: `${family}-test-version`, - }; - return { ...withoutHash, identityHash: producerProviderIdentityHash(withoutHash) }; - }; - - test('documents the complete five-artifact production installation', () => { - const guide = readFileSync(new URL('./fixtures/cso-eval/README.md', import.meta.url), 'utf8'); - expect(guide).toContain('Trusted five-artifact producer unit'); - expect(guide).toContain('bin/.gstack-cso-generation "$stage/.gstack-cso-generation"'); - expect(guide).toContain('/opt/gstack-cso-producer/.gstack-cso-generation'); - expect(guide).toContain('CSO_EVAL_PAID=1 /opt/gstack-cso-producer/cso-eval-producer run'); - expect(guide).not.toMatch(/four-file|all four files|\/usr\/local\/bin\/cso-eval-producer/); - }); - const withHelper = (options: T, launcher = helperBundle()) => ({ - ...options, - testHelperLauncherPath: launcher, - testProviderIdentity: providerIdentityFor((options as T & { adapter?: ProviderAdapter }).adapter?.family ?? 'gpt', launcher), - testProviderCommand: providerCommandFor(launcher), - }); - - // The helper's real layout: `/-`; the secret redactor reads that epoch as a phone number. - const helperRun = `${'e'.repeat(24)}/${Date.now()}-${'0123456789abcdef'}`; - class FakeAdapter implements ProviderAdapter { - readonly name = 'fake'; - constructor( - private readonly inspect: (opts: RunOpts) => void, - private readonly actualModel = 'gpt-5.4', - readonly family: Family = 'gpt', - private readonly outcome: Partial = {}, - ) {} - async available() { return { ok: true }; } - async run(opts: RunOpts) { - this.inspect(opts); - return { output: 'complete — assessed source\nNo supported findings in the assessed scope', tokens: { input: 120, output: 30, cached: 10 }, durationMs: 1234, toolCalls: 4, modelUsed: this.actualModel, ...this.outcome }; - } - estimateCost() { return 0.0042; } - } - - test('pins reviewed provider CLI versions and policy identities', () => { - expect(PRODUCER_PROVIDER_POLICY).toEqual({ - claude: { family: 'claude', policyRevision: 'claude-2.1.263-cso-v2', version: '2.1.263 (Claude Code)' }, - codex: { family: 'gpt', policyRevision: 'codex-0.153.4-cso-v3-generation', version: 'codex-cli 0.153.4' }, - gemini: { family: 'gemini', policyRevision: 'gemini-0.59.0-cso-v1', version: '0.59.0' }, - }); - }); - - test('prepares independent one-cell producer jobs without private or sibling source inputs', () => { - const destination = join(root(), 'prepared'); - const schedule = prepareEvalJobs(producerMatrix, skills, destination, selected.map(cell => cell.id)); - expect(schedule).toMatchObject({ scheduledCells: 960, preparedCells: 2 }); - expect(readdirSync(join(destination, 'jobs')).sort()).toEqual(selected.map(cell => cell.id).sort()); - for (const cell of selected) { - const source = join(destination, 'jobs', cell.id, 'source'); - expect(existsSync(join(source, '.git'))).toBe(true); - const allSource = readdirSync(source).filter(name => name !== '.git').map(name => name).join('\n') + readFileSync(join(source, 'README.md'), 'utf8'); - expect(allSource).not.toContain('ORACLE_SQL_MARKER'); - expect(allSource).not.toContain('vulnerable'); - expect(existsSync(join(destination, 'jobs', cell.id, 'producer-input.json'))).toBe(true); - const input = JSON.parse(readFileSync(join(destination, 'jobs', cell.id, 'producer-input.json'), 'utf8')); - expect(input.skill).toBe(skills[cell.version]); - expect(input.execution.skillHash).toBe(sha256(input.skill)); - expect(input.cellRef).toBe(cell.id); - expect(input.skill).toContain(`${cell.version.toUpperCase()}_SECTION_ONLY`); - expect(input.skill).not.toContain(cell.version === 'v2' ? 'V3_SECTION_ONLY' : 'V2_SECTION_ONLY'); - expect(validatePortableSkillPayload(input.skill, cell.version).files.map(file => file.path)).toEqual(['SKILL.md', 'sections/manifest.json', 'sections/audit-phases.md']); - } - expect(() => prepareEvalJobs(producerMatrix, { ...skills, v3: portableSkill('v3', 'CHANGED_V3_SECTION') }, join(root(), 'bad'), selected.map(cell => cell.id))).toThrow('EVAL_SKILL_HASH_MISMATCH'); - }); - - test('prepared Git sources start no automatic maintenance before their immediate copy', () => { - const parent = root(), destination = join(parent, 'prepared'), trace = join(parent, 'git-trace.jsonl'); - const actualExec = childProcess.execFileSync; - // Observe the real production commands without inheriting a process-wide - // Git trace setting that the initializer correctly excludes from its env. - const traced = spyOn(childProcess, 'execFileSync').mockImplementation((command, args, options: any) => - actualExec(command, args as string[], { ...options, timeout: 5000, env: { ...options.env, GIT_TRACE2_EVENT: trace } })); - let git: string, env: NodeJS.ProcessEnv; - try { - prepareEvalJobs(producerMatrix, skills, destination, [selected[0].id]); - expect(traced).toHaveBeenCalledTimes(3); - git = traced.mock.calls[0]![0] as string; - env = (traced.mock.calls[0]![2] as childProcess.ExecFileSyncOptions).env!; - } finally { traced.mockRestore(); } - const events = readFileSync(trace, 'utf8').trim().split('\n').map(line => JSON.parse(line)); - const starts = events.filter(event => event.event === 'start'); - for (const command of ['init', 'add', 'commit']) expect(starts.some(event => event.argv.includes(command))).toBe(true); - const maintenance = events.filter(event => event.event === 'child_start' && - event.argv?.some((arg: string) => /^(?:maintenance|gc)$/.test(arg))); - expect(maintenance).toEqual([]); - const isolated = isolate(destination, selected[0]); - const options = { cwd: isolated.source, env, encoding: 'utf8' as const, timeout: 5000 }; - expect(actualExec(git, ['log', '-1', '--format=%s'], options).trim()).toBe('immutable evaluation fixture'); - expect(actualExec(git, ['status', '--porcelain'], options)).toBe(''); - expect(existsSync(join(isolated.source, '.git', 'objects', 'maintenance.lock'))).toBe(false); - }); - - test('binds every generated section byte and rejects incomplete or cross-version payloads', () => { - const changedSection = portableSkill('v3', 'V3_SECTION_CHANGED_BY_ONE_BYTE'); - expect(sha256(changedSection)).not.toBe(sha256(skills.v3)); - expect(validatePortableSkillPayload(skills.v2, 'v2').version).toBe('v2'); - expect(validatePortableSkillPayload(skills.v3, 'v3').version).toBe('v3'); - expect(() => validatePortableSkillPayload(skills.v2, 'v3')).toThrow('INVALID_CSO_EVAL_PAYLOAD'); - expect(() => prepareEvalJobs(producerMatrix, { v2: '# root-only v2', v3: skills.v3 }, join(root(), 'root-only'), selected.map(cell => cell.id))).toThrow('INVALID_CSO_EVAL_PAYLOAD'); - expect(() => createPortableSkillPayload('v3', [ - { path: 'SKILL.md', contents: '---\nname: cso\nversion: 3.0.0\n---\n' }, - { path: 'sections/manifest.json', contents: JSON.stringify({ skill: 'cso', version: 1, sections: [{ id: 'audit-phases', file: 'audit-phases.md', title: 'Audit phases', trigger: 'during audit phases' }] }) }, - ])).toThrow('INCOMPLETE_CSO_EVAL_PAYLOAD'); - - const directory = join(root(), 'skill'); mkdirSync(join(directory, 'sections'), { recursive: true }); - writeFileSync(join(directory, 'SKILL.md'), '---\nname: cso\nversion: 3.0.0\n---\nRead sections/audit-phases.md.\n'); - writeFileSync(join(directory, 'sections', 'manifest.json'), JSON.stringify({ skill: 'cso', version: 1, sections: [{ id: 'audit-phases', file: 'audit-phases.md', title: 'Audit phases', trigger: 'during audit phases' }] })); - writeFileSync(join(directory, 'sections', 'audit-phases.md'), 'COMPLETE_DIRECTORY_SECTION\n'); - const loaded = loadPortableSkillPayload('v3', directory); - expect(loaded).toContain('COMPLETE_DIRECTORY_SECTION'); - expect(() => loadPortableSkillPayload('v2', directory)).toThrow('CSO_EVAL_PAYLOAD_VERSION_MISMATCH'); - writeFileSync(join(directory, 'sections', 'unlisted.md'), 'must not be omitted\n'); - expect(() => loadPortableSkillPayload('v3', directory)).toThrow('UNLISTED_CSO_EVAL_SECTION'); - }); - - test('binds only a complete adjacent executable helper bundle outside source and state', () => { - const source = join(root(), 'source'); mkdirSync(source); - const state = join(root(), 'state'); - const launcher = helperBundle(); - const suffix = process.platform === 'win32' ? '.exe' : ''; - expect(resolveProducerHelperBinding(source, state, launcher)).toEqual({ - producer: join(dirname(launcher), `cso-eval-producer${suffix}`), - launcher, - core: join(dirname(launcher), `gstack-cso-core${suffix}`), - watchdog: join(dirname(launcher), `gstack-cso-watchdog${suffix}`), - generation: join(dirname(launcher), '.gstack-cso-generation'), - }); - - const missingGeneration = helperBundle(); - rmSync(join(dirname(missingGeneration), '.gstack-cso-generation')); - expect(() => resolveProducerHelperBinding(source, state, missingGeneration)).toThrow('INVALID_PRODUCER_HELPER'); - - const malformedGeneration = helperBundle(); - writeFileSync(join(dirname(malformedGeneration), '.gstack-cso-generation'), 'f'.repeat(64)); - expect(() => resolveProducerHelperBinding(source, state, malformedGeneration)).toThrow('INVALID_PRODUCER_HELPER'); - - const mismatchedGeneration = helperBundle(); - writeFileSync(join(dirname(mismatchedGeneration), '.gstack-cso-generation'), `${'f'.repeat(64)}\n`); - const mismatchedBinding = resolveProducerHelperBinding(source, state, mismatchedGeneration); - expect(() => producerInstallationIdentity(mismatchedBinding)).toThrow('PRODUCER_HELPER_GENERATION_MISMATCH'); - - const missingWatchdog = helperBundle(); - rmSync(join(dirname(missingWatchdog), `gstack-cso-watchdog${suffix}`)); - expect(() => resolveProducerHelperBinding(source, state, missingWatchdog)).toThrow('INVALID_PRODUCER_HELPER'); - - const nonExecutable = helperBundle(); - if (process.platform !== 'win32') { - chmodSync(join(dirname(nonExecutable), 'gstack-cso-core'), 0o600); - expect(() => resolveProducerHelperBinding(source, state, nonExecutable)).toThrow('INVALID_PRODUCER_HELPER'); - } - - const symlinked = helperBundle(); - if (process.platform !== 'win32') { - rmSync(symlinked); - symlinkSync(join(dirname(symlinked), 'gstack-cso-core'), symlinked); - expect(() => resolveProducerHelperBinding(source, state, symlinked)).toThrow('INVALID_PRODUCER_HELPER'); - } - - const containedDirectory = join(source, 'helpers'); mkdirSync(containedDirectory); - const containedLauncher = join(containedDirectory, `gstack-cso-launcher${suffix}`); - for (const name of ['cso-eval-producer', 'gstack-cso-launcher', 'gstack-cso-core', 'gstack-cso-watchdog']) { - const path = join(containedDirectory, `${name}${suffix}`); - writeFileSync(path, 'test executable\n', { mode: 0o755 }); - if (process.platform !== 'win32') chmodSync(path, 0o755); - } - expect(() => resolveProducerHelperBinding(source, state, containedLauncher)).toThrow('INVALID_PRODUCER_HELPER'); - - const stateContainedLauncher = helperBundle(join(state, 'helpers')); - expect(() => resolveProducerHelperBinding(source, state, stateContainedLauncher)).toThrow('INVALID_PRODUCER_HELPER'); - }); - - test('production binding rejects a privileged or producer-writable binary and directory chain', () => { - const source = join(root(), 'source'); mkdirSync(source); - const state = join(root(), 'state'); - const suffix = process.platform === 'win32' ? '.exe' : ''; - - const writableBinary = helperBundle(); - const binaryDirectory = dirname(writableBinary); - const producerBinary = join(binaryDirectory, `cso-eval-producer${suffix}`); - if (process.platform !== 'win32') { - chmodSync(binaryDirectory, 0o555); - chmodSync(producerBinary, 0o555); - chmodSync(join(binaryDirectory, `gstack-cso-core${suffix}`), 0o555); - chmodSync(join(binaryDirectory, `gstack-cso-watchdog${suffix}`), 0o555); - chmodSync(writableBinary, 0o755); - } - const writableBinaryBinding = resolveProducerHelperBinding(source, state, writableBinary); - const binaryError = () => validateProductionProducerInstallation(writableBinaryBinding, producerBinary); - if (typeof process.getuid === 'function' && process.getuid() === 0) expect(binaryError).toThrow('ROOT_PRODUCER_UNSUPPORTED'); - else expect(binaryError).toThrow('WRITABLE_PRODUCER_INSTALLATION'); - if (process.platform !== 'win32') chmodSync(binaryDirectory, 0o755); - - const writableDirectory = helperBundle(); - const directory = dirname(writableDirectory); - const adjacentProducer = join(directory, `cso-eval-producer${suffix}`); - if (process.platform !== 'win32') { - for (const path of [writableDirectory, join(directory, `gstack-cso-core${suffix}`), join(directory, `gstack-cso-watchdog${suffix}`), adjacentProducer]) chmodSync(path, 0o555); - chmodSync(directory, 0o755); - } - const writableDirectoryBinding = resolveProducerHelperBinding(source, state, writableDirectory); - const directoryError = () => validateProductionProducerInstallation(writableDirectoryBinding, adjacentProducer); - if (typeof process.getuid === 'function' && process.getuid() === 0) expect(directoryError).toThrow('ROOT_PRODUCER_UNSUPPORTED'); - else expect(directoryError).toThrow('WRITABLE_PRODUCER_INSTALLATION'); - }); - - test('requires explicit authorization, consumes labels before the model starts, and records measured receipts', async () => { - const destination = join(root(), 'prepared'); - const schedule = prepareEvalJobs(producerMatrix, skills, destination, selected.map(cell => cell.id)); - const cell = selected.find(item => item.version === 'v2')!; - const inPlace = join(destination, 'jobs', cell.id, 'producer-input.json'); - const receipts = join(root(), 'receipts'); mkdirSync(receipts); - const output = join(receipts, `${cell.id}.json`); - const invalidLauncher = join(root(), 'missing', `gstack-cso-launcher${process.platform === 'win32' ? '.exe' : ''}`); - await expect(runProducerCell(inPlace, output, { adapter: new FakeAdapter(() => {}), paidExecutionAuthorized: false, testHelperLauncherPath: invalidLauncher })).rejects.toThrow('PAID_EXECUTION_NOT_AUTHORIZED'); - await expect(runProducerCell(inPlace, output, { adapter: new FakeAdapter(() => {}), paidExecutionAuthorized: true, testHelperLauncherPath: invalidLauncher })).rejects.toThrow('NON_ISOLATED_PRODUCER_LAYOUT'); - const isolated = isolate(destination, cell), input = isolated.input; - const launcher = helperBundle(); - const adapter = new FakeAdapter(opts => { - expect(existsSync(input)).toBe(false); - expect(opts).toMatchObject({ - model: cell.model, - timeoutMs: (cell.budgetSeconds + 300) * 1000, - workdir: join(isolated.job, 'state'), - csoProducer: { - stateDirectory: join(isolated.job, 'state'), - sourceDirectory: isolated.source, - helperLauncher: launcher, - helperGeneration: join(dirname(launcher), '.gstack-cso-generation'), - providerCommand: providerCommandFor(launcher), - }, - }); - expect(opts.extraArgs).toBeUndefined(); - expect(readdirSync(isolated.job).sort()).toEqual(['source', 'state']); - expect(opts.prompt).toContain(skills.v2); - expect(opts.prompt).toContain('/cso --budget 600'); - expect(opts.prompt).toContain(`application repository at ${isolated.source}`); - expect(opts.prompt).toContain('permission profile grants read-only access to exactly that immutable snapshot'); - expect(opts.prompt).toContain('Use only the trusted helper to inspect or act on source'); - expect(opts.prompt).toContain(`absolute launcher path ${JSON.stringify(launcher)}`); - expect(opts.prompt).toContain('do not discover or invoke another helper through PATH'); - expect(opts.prompt).not.toContain(cell.caseId); - expect(opts.prompt).not.toContain(cell.variant); - expect(opts.prompt).not.toContain('ORACLE_SQL_MARKER'); - const artifactRoot = join(process.env.GSTACK_HOME!, 'security', 'cso', helperRun); - mkdirSync(artifactRoot, { recursive: true }); - writeFileSync(join(artifactRoot, 'report.json'), '{"status":"complete"}\n'); - writeFileSync(join(artifactRoot, 'repair.patch'), 'diff --git a/app.mjs b/app.mjs\n'); - if (process.platform !== 'win32') { - expect(statSync(isolated.source).mode & 0o777).toBe(0o555); - expect(statSync(join(isolated.source, 'app.mjs')).mode & 0o777).toBe(0o444); - } - expect(process.env.GSTACK_SESSION_KIND).toBe('spawned'); - expect(process.env.GSTACK_HEADLESS).toBe('1'); - }); - await expect(runProducerCell(input, output, { adapter, paidExecutionAuthorized: false, testHelperLauncherPath: invalidLauncher })).rejects.toThrow('PAID_EXECUTION_NOT_AUTHORIZED'); - expect(existsSync(input)).toBe(true); - const receipt = await runProducerCell(input, output, withHelper({ adapter, paidExecutionAuthorized: true }, launcher)); - expect(receipt).toMatchObject({ status: 'succeeded', requestedModel: 'exact-eval-model', modelUsed: 'gpt-5.4', modelIdentitySource: 'provider_reported', durationMs: 1234, firstUsefulResultMs: null, usage: { inputTokens: 120, outputTokens: 30, cachedTokens: 10, estimatedCostUSD: 0.0042 } }); - expect(receipt.installationIdentity.identityHash).toMatch(/^[a-f0-9]{64}$/); - expect(receipt.installationIdentity.schemaVersion).toBe(1); - expect(receipt.installationIdentity.generation.coreSha256).toBe(receipt.installationIdentity.core.sha256); - expect(receipt.installationIdentity.generation.manifest).toEqual({ - sha256: sha256(`${receipt.installationIdentity.core.sha256}\n`), - bytes: 65, - }); - for (const artifact of [receipt.installationIdentity.producer, receipt.installationIdentity.launcher, receipt.installationIdentity.core, receipt.installationIdentity.watchdog, receipt.installationIdentity.generation.manifest]) { - expect(artifact.bytes).toBeGreaterThan(0); - expect(artifact.sha256).toMatch(/^[a-f0-9]{64}$/); - } - expect(receipt.providerIdentity).toEqual(providerIdentityFor('gpt', launcher)); - expect(receipt.artifacts).toMatchObject({ schemaVersion: 1, root: 'security/cso' }); - expect(receipt.artifacts.totalBytes).toBe(receipt.artifacts.entries.reduce((sum, entry) => sum + entry.bytes, 0)); - expect(receipt.artifacts.entries.map(entry => entry.path)).toEqual([`${helperRun}/repair.patch`, `${helperRun}/report.json`]); - expect(receipt.artifacts.identityHash).toBe(producerArtifactInventoryHash({ schemaVersion: 1, root: 'security/cso', entries: receipt.artifacts.entries, totalBytes: receipt.artifacts.totalBytes })); - const retainedHome = join(isolated.job, 'state', 'cso-home'); - expect(readFileSync(join(retainedHome, 'security', 'cso', helperRun, 'report.json'), 'utf8')).toContain('complete'); - expect(receipt.artifacts.entries.every(entry => !/provider|credential|session/i.test(entry.path))).toBe(true); - expect(JSON.parse(readFileSync(output, 'utf8'))).toEqual(receipt); - const { receiptHash, ...receiptWithoutHash } = receipt; - expect(producerReceiptHash(receiptWithoutHash)).toBe(receiptHash); - const batch = collectProducerReceipts(producerMatrix, schedule, [receipt]); - expect(batch.summary).toMatchObject({ scheduled: 960, prepared: 2, submitted: 1, missing: 959, matchedPairsExpected: 480, matchedPairsSubmitted: 0, modelMismatches: [] }); - expect(batch.summary.groups.find(group => group.version === 'v2' && group.mode === 'daily')).toMatchObject({ scheduled: 240, submitted: 1, missing: 239, latency: { samples: 1, denominator: 240, p95Ms: 1234 }, firstUsefulResult: { samples: 0, denominator: 240, p95Ms: null }, modelTokens: { measured: 1, denominator: 240, total: 150 }, estimatedCost: { measured: 1, denominator: 240, totalUSD: 0.0042 } }); - }); - - test('passes the same producer policy to every host and removes Gemini CLI state', async () => { - for (const [host, family] of [['codex', 'gpt'], ['claude', 'claude'], ['gemini', 'gemini']] as const) { - const hostMatrix = createEvalMatrix({ model: 'exact-eval-model', host, skillHashes: { v2: sha256(skills.v2), v3: sha256(skills.v3) } }); - const cell = hostMatrix.cells.find(item => item.caseId === 'node-sql-injection' && item.variant === 'vulnerable' && item.version === 'v3' && item.mode === 'daily' && item.repetition === 1)!; - const destination = join(root(), `${host}-prepared`); - prepareEvalJobs(hostMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell), state = join(isolated.job, 'state'), launcher = helperBundle(); - const outputRoot = join(root(), `${host}-receipts`); mkdirSync(outputRoot); - const adapter = new FakeAdapter(opts => { - expect(opts.csoProducer).toEqual({ - stateDirectory: state, - sourceDirectory: isolated.source, - helperLauncher: launcher, - helperGeneration: join(dirname(launcher), '.gstack-cso-generation'), - providerCommand: providerCommandFor(launcher), - }); - expect(opts.extraArgs).toBeUndefined(); - if (host === 'gemini') { - const paths = geminiProducerPaths(state); - expect(JSON.parse(readFileSync(paths.systemDefaults, 'utf8'))).toEqual({}); - const settings = JSON.parse(readFileSync(paths.systemSettings, 'utf8')); - const contextFileName = settings.context.fileName[0]; - expect(contextFileName).toMatch(/^\.gstack-cso-context-[a-f0-9]{32}\.md$/); - expect(settings).toEqual(geminiProducerSystemSettings(contextFileName, launcher)); - expect(statSync(paths.root).mode & 0o777).toBe(0o700); - expect(statSync(paths.home).mode & 0o777).toBe(0o700); - expect(statSync(paths.workdir).mode & 0o777).toBe(0o700); - expect(statSync(paths.systemSettings).mode & 0o777).toBe(0o600); - expect(readdirSync(paths.workdir)).toEqual([]); - for (const directory of [paths.root, paths.home, paths.workdir]) { - expect(existsSync(join(directory, 'GEMINI.md'))).toBe(false); - expect(existsSync(join(directory, 'AGENTS.md'))).toBe(false); - expect(existsSync(join(directory, 'MEMORY.md'))).toBe(false); - } - expect(opts.prompt).toContain(`application repository at ${isolated.source}`); - expect(opts.prompt).toContain('neutral current working directory'); - if (process.platform !== 'win32') { - expect(statSync(isolated.source).mode & 0o777).toBe(0o555); - expect(statSync(join(isolated.source, 'app.mjs')).mode & 0o777).toBe(0o444); - } - } - }, cell.model, family); - const receipt = await runProducerCell(isolated.input, join(outputRoot, `${cell.id}.json`), withHelper({ adapter, paidExecutionAuthorized: true }, launcher)); - expect(receipt.status).toBe('succeeded'); - if (host === 'gemini') expect(existsSync(geminiProducerPaths(state).root)).toBe(false); - } - }); - - test('removes disposable Gemini CLI state when the provider throws', async () => { - const hostMatrix = createEvalMatrix({ model: 'exact-eval-model', host: 'gemini', skillHashes: { v2: sha256(skills.v2), v3: sha256(skills.v3) } }); - const cell = hostMatrix.cells.find(item => item.caseId === 'node-sql-injection' && item.variant === 'vulnerable' && item.version === 'v3' && item.mode === 'daily' && item.repetition === 1)!; - const destination = join(root(), 'gemini-throw-prepared'); - prepareEvalJobs(hostMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell), state = join(isolated.job, 'state'); - const outputRoot = join(root(), 'gemini-throw-receipts'); mkdirSync(outputRoot); - const adapter: ProviderAdapter = { - name: 'fake', family: 'gemini', - async available() { return { ok: true }; }, - async run() { expect(existsSync(geminiProducerPaths(state).root)).toBe(true); throw new Error('provider stopped'); }, - estimateCost() { return 0; }, - }; - await expect(runProducerCell(isolated.input, join(outputRoot, `${cell.id}.json`), withHelper({ adapter, paidExecutionAuthorized: true }))).rejects.toThrow('provider stopped'); - expect(existsSync(geminiProducerPaths(state).root)).toBe(false); - }); - - test('records an exit-zero blank provider result as a failed receipt',async()=>{ - const destination=join(root(),'blank-prepared'),cell=selected[0]; - prepareEvalJobs(producerMatrix,skills,destination,[cell.id]); - const isolated=isolate(destination,cell),output=join(root(),`${cell.id}.json`); - const receipt=await runProducerCell(isolated.input,output,withHelper({adapter:new FakeAdapter(()=>{},cell.model,'gpt',{output:' \n',tokens:{input:0,output:0}}),paidExecutionAuthorized:true})); - expect(receipt.status).toBe('failed'); - expect(receipt.error).toEqual({code:'unknown',reason:'empty output from provider CLI (exit 0)'}); - expect(receipt.outputHash).toBe(sha256(receipt.output)); - expect(JSON.parse(readFileSync(output,'utf8'))).toEqual(receipt); - }); - - test('preserves provider-declared exit-zero errors as failed receipts',async()=>{ - const destination=join(root(),'provider-error-prepared'),cell=selected[0];prepareEvalJobs(producerMatrix,skills,destination,[cell.id]); - const isolated=isolate(destination,cell),output=join(root(),`${cell.id}.json`),error={code:'unknown' as const,reason:'empty or invalid output from claude CLI (exit 0)'}; - const receipt=await runProducerCell(isolated.input,output,withHelper({adapter:new FakeAdapter(()=>{},cell.model,'gpt',{output:'',error}),paidExecutionAuthorized:true})); - expect(receipt.status).toBe('failed');expect(receipt.error).toEqual(error);expect(receipt.outputHash).toBe(sha256(receipt.output)); - }); - - test('redacts producer output and split error canaries into unsuccessful receipts', async () => { - for (const [suffix, outputText, error] of [ - ['output', `report contains sk-proj-${'a'.repeat(40)}`, undefined], - ['split', 'diagnostic ends with sk-proj-', { code: 'unknown' as const, reason: 'b'.repeat(40) }], - ] as const) { - const destination = join(root(), `${suffix}-prepared`); - const cell = selected[0]; - prepareEvalJobs(producerMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell); - const outputRoot = join(root(), `${suffix}-receipts`); mkdirSync(outputRoot); - const receiptPath = join(outputRoot, `${cell.id}.json`); - const adapter = new FakeAdapter(() => {}, cell.model, 'gpt', { output: outputText, ...(error ? { error } : {}) }); - const receipt = await runProducerCell(isolated.input, receiptPath, withHelper({ adapter, paidExecutionAuthorized: true })); - expect(receipt.status).toBe('failed'); - expect(receipt.output).toBe('[sensitive producer output redacted]'); - expect(receipt.outputHash).toBe(sha256(receipt.output)); - expect(receipt.error).toEqual({ code: 'unknown', reason: 'Sensitive producer output or error withheld: credential-class rule openai.key×1' }); - const stored = readFileSync(receiptPath, 'utf8'); - expect(stored).not.toContain('sk-proj-'); - expect(stored).not.toContain('b'.repeat(40)); - } - }); - - test('withholds a source canary quoted without its credential name, whole or split across output and error', () => { - const source = join(root(), 'canary-source'), canary = `cso_${randomHex(10)}_${randomHex(10)}`; - mkdirSync(join(source, 'test'), { recursive: true }); - writeFileSync(join(source, '.env'), `API_TOKEN=${canary}\nNODE_ENV=production\n`); - writeFileSync(join(source, 'test', 'canary.txt'), `${canary}\n`); - const credentials = sourceCredentialValues(source, ['.env', 'test/canary.txt']); - expect(credentials).toEqual([canary]); - const base = { output: '', modelUsed: 'm', durationMs: 1, toolCalls: 1, tokens: { input: 1, output: 1 } } as RunResult; - expect(sanitizeProducerRun({ ...base, output: `The token is ${canary}` }, [])).toMatchObject({ output: `The token is ${canary}` }); - for (const run of [{ ...base, output: `The token is ${canary}.` }, { ...base, output: canary.slice(0, 12), error: { code: 'unknown', reason: canary.slice(12) } }] as RunResult[]) { - const sanitized = sanitizeProducerRun(run, credentials); - expect(sanitized).toMatchObject({ output: '[sensitive producer output redacted]', error: { reason: 'Sensitive producer output or error withheld: credential-class rule source.env.kv×1' } }); - expect(JSON.stringify(sanitized)).not.toContain(canary); - } - }); - - test('keeps a succeeded run that quotes helper identifiers, span-redacts PII shapes, and fails credential-class output by rule', async () => { - const runId = `${Date.now()}-${randomHex(8)}`; - let walletShaped = ''; - while (!walletShaped) { const id = randomHex(16); if (redactProducerText(`review ${id}`).text === `review ${id}` && scan(id).findings.some(finding => finding.id === 'pii.wallet')) walletShaped = id; } - expect(scan(runId).findings.map(finding => finding.id)).toContain('pii.phone.e164'); - const report = [ - `complete — run ${runId}, catalog cso-eval-38078005392-${randomHex(6)}, scanner artifact gitleaks-${randomHex(8)}-${randomHex(8)}.`, - `Finding ${randomHex(16)} reviewed by ${walletShaped}; snapshot ${randomHex(32)}.`, - 'The /health-hooks route connects to 169.254.169.254:80.', - ].join('\n'); - const run = async (name: string, output: string) => { - const destination = join(root(), `${name}-prepared`), cell = selected[0]; - prepareEvalJobs(producerMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell), receiptPath = join(root(), `${cell.id}.json`); - return runProducerCell(isolated.input, receiptPath, withHelper({ adapter: new FakeAdapter(() => {}, 'gpt-5.4', 'gpt', { output }), paidExecutionAuthorized: true })); - }; - const kept = await run('helper-ids', report); - expect(kept.status).toBe('succeeded'); - expect(kept.error).toBeUndefined(); - expect(kept.output).toBe(report.replace('169.254.169.254', '')); - const envLine = `API_TOKEN=cso_${randomHex(12)}_${randomHex(12)}`; - const key = `sk-ant-api03-${randomHex(40)}`; - for (const [name, leak, rule] of [['env-line', envLine, 'env.kv×1'], ['credential', key, 'anthropic.key×1']] as const) { - const failed = await run(name, `${report}\n${leak}`); - expect(failed).toMatchObject({ status: 'failed', output: '[sensitive producer output redacted]', error: { code: 'unknown', reason: `Sensitive producer output or error withheld: credential-class rule ${rule}` }, usage: { inputTokens: 120 } }); - expect(JSON.stringify(failed)).not.toContain(leak); - } - }); - - test('collects and scores real receipts of every kind: succeeded, span-redacted, credential-withheld, timeout and post-run check failure', async () => { - const platform = producerHostPlatform(); - if (!platform) return; - const launcher = helperBundle(), runId = `${Date.now()}-${randomHex(8)}`, run = `${'e'.repeat(24)}/${runId}`; - const helperFiles = ['readable/.env', 'readable/README.md', 'report.json', 'report.md', `scanner-outcomes/gitleaks-${randomHex(8)}-${randomHex(8)}.json`, 'snapshot.json', 'snapshot/README.md', 'snapshot/package.json']; - const kinds: Array<[string, Partial, ((source: string) => void)?]> = [ - ['succeeded', {}], - ['span-redacted', { output: `complete — run ${runId}; /health-hooks reaches 169.254.169.254:80` }], - ['credential-withheld', { output: `complete — quoted sk-ant-api03-${randomHex(40)}` }], - ['timeout', { output: 'last assistant text before the kill', error: { code: 'timeout', reason: 'exceeded 2100000ms' } }], - ['post-run-check-failed', {}, source => { const file = join(source, 'src', 'app.txt'); chmodSync(file, 0o644); writeFileSync(file, 'changed by producer\n'); chmodSync(file, 0o444); }], - ]; - const produce = async (target: EvalMatrix, payloads: Partial>) => { - const prepared = join(root(), 'prepared'), schedule = prepareEvalJobs(target, payloads, prepared, undefined, privateCorpus); - const receipts: ProducerReceipt[] = []; - for (const [index, cell] of target.cells.entries()) { - const [, outcome, mutate] = kinds[index % kinds.length], isolated = isolate(prepared, cell); - const adapter = new FakeAdapter(opts => { - for (const file of helperFiles) { const path = join(process.env.GSTACK_HOME!, 'security', 'cso', run, file); mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, `${file}\n`); } - mutate?.(opts.csoProducer!.sourceDirectory); - }, 'gpt-5.4', 'gpt', outcome); - receipts.push(await runProducerCell(isolated.input, join(root(), `${cell.id}.json`), withHelper({ adapter, paidExecutionAuthorized: true }, launcher))); - } - return { schedule, receipts, results: target.cells.map(cell => ({ ...syntheticResultFor(cell, privateManifest), producerReceiptHash: receipts.find(receipt => receipt.cellRef === cell.id)!.receiptHash })) }; - }; - const platforms = Object.fromEntries(privateManifest.cases.map(fixture => [fixture.id, platform])); - const baselineMatrix = createEvalMatrix({ profile: 'baseline', model: 'exact-eval-model', host: 'codex', skillHashes: { v2: sha256(skills.v2) }, platforms: { comprehensive: platforms } }, privateManifest); - const baseline = await produce(baselineMatrix, { v2: skills.v2 }); - expect(baseline.receipts.slice(0, kinds.length).map(receipt => [receipt.status, receipt.error?.code ?? null, receipt.artifacts.entries.length])).toEqual([ - ['succeeded', null, 8], ['succeeded', null, 8], ['failed', 'unknown', 8], ['failed', 'timeout', 8], ['failed', 'INVALID_PRODUCER_SOURCE', 0], - ]); - expect(baseline.receipts[0].artifacts.entries.map(entry => entry.path)).toEqual(helperFiles.map(file => `${run}/${file}`)); - expect(baseline.receipts[1].output).toBe(`complete — run ${runId}; /health-hooks reaches :80`); - expect(baseline.receipts[2]).toMatchObject({ output: '[sensitive producer output redacted]', error: { reason: 'Sensitive producer output or error withheld: credential-class rule anthropic.key×1' } }); - const baselineBatch = collectProducerReceipts(baselineMatrix, baseline.schedule, baseline.receipts, privateManifest); - expect(baselineBatch.summary.groups).toMatchObject([{ version: 'v2', mode: 'comprehensive', scheduled: 16, submitted: 16, succeeded: 7, failed: 9 }]); - const recorded = createEvalBaseline(baselineMatrix, baselineBatch, baseline.results, privateManifest); - expect(recorded.baselineHash).toMatch(/^[a-f0-9]{64}$/); - const succeeded = new Set(baseline.receipts.filter(receipt => receipt.status === 'succeeded').map(receipt => receipt.cellRef)); - const vulnerableCell = (caseId: string) => baselineMatrix.cells.find(cell => cell.caseId === caseId && cell.variant === 'vulnerable')!.id; - expect(recorded.cases.map(item => item.found)).toEqual(recorded.cases.map(item => succeeded.has(vulnerableCell(item.caseId)))); - expect(recorded.cases.some(item => item.found) && recorded.cases.some(item => !item.found)).toBe(true); - const releaseMatrix = createEvalMatrix({ profile: 'release', model: 'exact-eval-model', host: 'codex', skillHashes: { v3: sha256(skills.v3) }, platforms: { daily: platform, comprehensive: platforms } }, privateManifest); - const release = await produce(releaseMatrix, { v3: skills.v3 }); - const scored = scoreCollectedEval(releaseMatrix, collectProducerReceipts(releaseMatrix, release.schedule, release.receipts, privateManifest), release.results, { containment: {} }, privateManifest); - expect(scored.groups.map(item => [item.version, item.mode, item.submitted])).toEqual([['v3', 'daily', 16], ['v3', 'comprehensive', 16]]); - }, 120_000); - - const expectIntegrityReceipt = (receipt: ProducerReceipt, receiptPath: string, error: { code: string; reason: string }) => { - expect(receipt).toMatchObject({ status: 'failed', error, output: '', outputHash: sha256(''), durationMs: 1234, toolCalls: 4, usage: { inputTokens: 120, outputTokens: 30, cachedTokens: 10, estimatedCostUSD: 0.0042 } }); - expect(receipt.artifacts.entries).toEqual([]); - expect(JSON.parse(readFileSync(receiptPath, 'utf8'))).toEqual(receipt); - }; - - test('records a failed receipt with usage when the bound provider executable changes during a cell', async () => { - const destination = join(root(), 'provider-race-prepared'), cell = selected[0]; - prepareEvalJobs(producerMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell), launcher = helperBundle(); - const outputRoot = join(root(), 'provider-race-receipts'); mkdirSync(outputRoot); - const receiptPath = join(outputRoot, `${cell.id}.json`); - const adapter = new FakeAdapter(opts => writeFileSync(opts.csoProducer!.providerCommand.executable, '#!/bin/sh\nexit 1\n')); - const receipt = await runProducerCell(isolated.input, receiptPath, withHelper({ adapter, paidExecutionAuthorized: true }, launcher)); - expectIntegrityReceipt(receipt, receiptPath, { code: 'PRODUCER_PROVIDER_INSTALLATION_RACE', reason: 'provider installation check: provider executable changed during the run' }); - }); - - test('records a failed receipt with usage when the helper generation changes during a cell', async () => { - const destination = join(root(), 'helper-generation-race-prepared'), cell = selected[0]; - prepareEvalJobs(producerMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell), launcher = helperBundle(); - const outputRoot = join(root(), 'helper-generation-race-receipts'); mkdirSync(outputRoot); - const receiptPath = join(outputRoot, `${cell.id}.json`); - const adapter = new FakeAdapter(opts => { - const core = join(dirname(opts.csoProducer!.helperLauncher), `gstack-cso-core${process.platform === 'win32' ? '.exe' : ''}`); - writeFileSync(core, process.platform === 'win32' ? 'new test executable\n' : '#!/bin/sh\nexit 1\n', { mode: 0o755 }); - writeFileSync(opts.csoProducer!.helperGeneration, `${sha256(readFileSync(core))}\n`); - }); - const receipt = await runProducerCell(isolated.input, receiptPath, withHelper({ adapter, paidExecutionAuthorized: true }, launcher)); - expectIntegrityReceipt(receipt, receiptPath, { code: 'PRODUCER_HELPER_GENERATION_CHANGED', reason: 'helper installation check: installed helper identity changed during the run' }); - }); - - test('records a failed receipt with usage when the provider output exceeds the limit', async () => { - const destination = join(root(), 'output-limit-prepared'), cell = selected[0]; - prepareEvalJobs(producerMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell), receiptPath = join(root(), `${cell.id}.json`); - const output = 'x'.repeat(32 * 1024 * 1024 + 1); - const receipt = await runProducerCell(isolated.input, receiptPath, withHelper({ adapter: new FakeAdapter(() => {}, 'gpt-5.4', 'gpt', { output }), paidExecutionAuthorized: true })); - expectIntegrityReceipt(receipt, receiptPath, { code: 'PRODUCER_OUTPUT_TOO_LARGE', reason: `output size check: output is ${output.length} bytes; the limit is ${32 * 1024 * 1024}` }); - }); - - test('accepts real helper artifact names the secret redactor misreads, and names the check that rejects the rest', async () => { - const { redact } = await import('../lib/cso/process'); - const runId = `${Date.now()}-${'0123456789abcdef'}`; - let walletShaped = ''; - while (!walletShaped) { const id = randomHex(16); if (redact(id) !== id) walletShaped = id; } - expect(redact(runId)).not.toBe(runId); - const repo = 'e'.repeat(24); - let closure = ''; - while (!closure) { const name = `${randomHex(32)}-before-${randomHex(8)}.json`; if (redact(name) !== name) closure = name; } - let helperFindingClosure = ''; - while (!helperFindingClosure) { const name = `${randomHex(16)}-after-${randomHex(8)}.json`; if (redact(name) !== name) helperFindingClosure = name; } - const accepted = [`${repo}/${runId}/report.json`, `${repo}/${runId}/reviews/${walletShaped}.json`, `${repo}/${runId}/scanner-outcomes/gitleaks-${randomHex(8)}-${randomHex(8)}.json`, - `${repo}/${runId}/dependency-closures/${closure}`, `${repo}/${runId}/dependency-closures/${closure.replace('-before-', '-after-')}`, - `${repo}/${runId}/dependency-closures/${helperFindingClosure}`, `${repo}/${runId}/dependency-closures/${helperFindingClosure.replace('-after-', '-before-')}`, - `${repo}/${runId}/snapshot/test/fixtures/cso-canary-token.txt`, 'public-cache/osv/index.json']; - for (const path of accepted) expect(() => assertProducerArtifactPath(path)).not.toThrow(); - for (const [path, message] of [ - [`run-1/report.json`, 'INVALID_PRODUCER_ARTIFACTS: an artifact lies outside'], - [`${repo}/report.json`, 'INVALID_PRODUCER_ARTIFACTS: an artifact lies outside'], - [`${repo}/${runId}/bad name.json`, 'INVALID_PRODUCER_ARTIFACTS: an artifact path has a component outside'], - ] as const) expect(() => assertProducerArtifactPath(path)).toThrow(message); - expect(() => assertProducerArtifactPath(`${repo}/${runId}/dependency-closures/${closure.replace('-before-', '-during-')}`)).toThrow('looks like a secret'); - expect(() => assertProducerArtifactPath(`${repo}/${runId}/dependency-closures/${helperFindingClosure.replace('-after-', '-during-')}`)).toThrow('looks like a secret'); - const planted = `sk-ant-api03-${randomHex(24)}`; - expect(redact(planted)).not.toBe(planted); - let failure: unknown; - try { assertProducerArtifactPath(`${repo}/${runId}/notes/${planted}.txt`); } catch (error) { failure = error; } - expect((failure as CsoError).code).toBe('REDACTION_FAILED'); - expect((failure as Error).message).toBe('artifact path component 4 under "ID/ID/notes" looks like a secret; the component is withheld'); - const destination = join(root(), 'planted-artifact-prepared'), cell = selected[0]; - prepareEvalJobs(producerMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell), receiptPath = join(root(), `${cell.id}.json`); - const adapter = new FakeAdapter(() => { - const directory = join(process.env.GSTACK_HOME!, 'security', 'cso', repo, runId, 'notes'); - mkdirSync(directory, { recursive: true }); writeFileSync(join(directory, `${planted}.txt`), 'x'); - }, 'gpt-5.4', 'gpt', { error: { code: 'timeout', reason: 'exceeded 1ms' } }); - const receipt = await runProducerCell(isolated.input, receiptPath, withHelper({ adapter, paidExecutionAuthorized: true })); - expectIntegrityReceipt(receipt, receiptPath, { code: 'REDACTION_FAILED', reason: 'artifact inventory check: artifact path component 4 under "ID/ID/notes" looks like a secret; the component is withheld; the provider run also failed (timeout)' }); - expect(readFileSync(receiptPath, 'utf8')).not.toContain(planted); - }); - - test('gives the provider the budget plus the reporting grace and keeps a timed-out run\'s usage and last result', async () => { - expect(producerProviderTimeoutMs(1800)).toBe(2100 * 1000); - const destination = join(root(), 'timeout-prepared'), cell = selected[0]; - prepareEvalJobs(producerMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell), receiptPath = join(root(), `${cell.id}.json`); - const adapter = new FakeAdapter(() => {}, 'gpt-5.4', 'gpt', { output: 'last assistant text before the kill', error: { code: 'timeout', reason: 'exceeded 2100000ms' } }); - const receipt = await runProducerCell(isolated.input, receiptPath, withHelper({ adapter, paidExecutionAuthorized: true })); - expect(receipt).toMatchObject({ status: 'failed', error: { code: 'timeout', reason: 'exceeded 2100000ms' }, output: 'last assistant text before the kill', toolCalls: 4, usage: { inputTokens: 120, outputTokens: 30, cachedTokens: 10, estimatedCostUSD: 0.0042 } }); - }); - - test('names the first offending source path and rule in a failed receipt that keeps usage', async () => { - if (process.platform === 'win32') return; - const writable = (directory: string, change: () => void) => { chmodSync(directory, 0o755); try { change(); } finally { chmodSync(directory, 0o555); } }; - const cases: Array<[string, (source: string, outside: string) => void, string]> = [ - ['mount-point', source => writable(source, () => writeFileSync(join(source, '.mcp.json'), '', { mode: 0o444 })), '".mcp.json" is not in the expected source listing'], - ['missing', source => writable(source, () => rmSync(join(source, 'app.mjs'))), '"app.mjs" is missing from the source'], - ['hard-link', (source, outside) => linkSync(join(source, 'app.mjs'), join(outside, 'app.mjs')), '"app.mjs" has 2 hard links; expected 1'], - ['content', source => { - const file = join(source, 'app.mjs'), size = statSync(file).size; - chmodSync(file, 0o644); writeFileSync(file, 'y'.repeat(size)); chmodSync(file, 0o444); - }, '"app.mjs" does not match its expected sha256'], - ]; - for (const [name, mutate, reason] of cases) { - const destination = join(root(), `${name}-prepared`), cell = selected[0], outside = root(); - const schedule = prepareEvalJobs(producerMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell), receiptPath = join(root(), `${cell.id}.json`); - const receipt = await runProducerCell(isolated.input, receiptPath, withHelper({ adapter: new FakeAdapter(opts => mutate(opts.csoProducer!.sourceDirectory, outside)), paidExecutionAuthorized: true })); - expectIntegrityReceipt(receipt, receiptPath, { code: 'INVALID_PRODUCER_SOURCE', reason: `source content check: ${reason}` }); - const group = collectProducerReceipts(producerMatrix, schedule, [receipt]).summary.groups.find(item => item.version === cell.version && item.mode === cell.mode); - expect(group).toMatchObject({ submitted: 1, succeeded: 0, failed: 1, estimatedCost: { measured: 1, totalUSD: 0.0042 } }); - } - }); - - test('fails closed without a receipt or raw console reason when redaction cannot inspect output', async () => { - const destination = join(root(), 'redaction-failure-prepared'), cell = selected[0]; - prepareEvalJobs(producerMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell); - const outputRoot = join(root(), 'redaction-failure-receipts'); mkdirSync(outputRoot); - const receiptPath = join(outputRoot, `${cell.id}.json`); - const canary = 'secret-canary-' + 'x'.repeat(1024 * 1024 + 1); - let failure: unknown; - try { - await runProducerCell(isolated.input, receiptPath, withHelper({ adapter: new FakeAdapter(() => {}, cell.model, 'gpt', { output: canary }), paidExecutionAuthorized: true })); - } catch (error) { failure = error; } - expect(failure).toBeInstanceOf(CsoError); - expect((failure as CsoError).code).toBe('REDACTION_FAILED'); - expect(existsSync(receiptPath)).toBe(false); - expect(producerFailureMessage(failure)).toBe('REDACTION_FAILED: producer payload withheld'); - expect(producerFailureMessage(failure)).not.toContain(canary.slice(0, 32)); - }); - - test('rejects effective-model mismatches between otherwise matched v2 and v3 cells', async () => { - const destination = join(root(), 'prepared'); - const schedule = prepareEvalJobs(producerMatrix, skills, destination, selected.map(cell => cell.id)); - const receiptsRoot = join(root(), 'receipts'); mkdirSync(receiptsRoot); - const receipts = []; - for (const cell of selected) { - const adapter = new FakeAdapter(() => {}, cell.version === 'v2' ? 'resolved-a' : 'resolved-b'); - const isolated = isolate(destination, cell); - receipts.push(await runProducerCell(isolated.input, join(receiptsRoot, `${cell.id}.json`), withHelper({ adapter, paidExecutionAuthorized: true }))); - } - expect(() => collectProducerReceipts(producerMatrix, schedule, receipts)).toThrow('UNMATCHED_EFFECTIVE_MODELS'); - const tampered = structuredClone(receipts[0]); tampered.output += 'changed'; - expect(() => collectProducerReceipts(producerMatrix, schedule, [tampered])).toThrow('INVALID_PRODUCER_RECEIPT'); - }); - - test('a platform-pinned release cell runs only on its native producer platform', async () => { - const release = createEvalMatrix({ ...releaseOptions, skillHashes: { v3: sha256(skills.v3) } }, privateManifest); - const host = producerHostPlatform(), foreign = host === 'linux/amd64' ? 'linux/arm64' : 'linux/amd64'; - const native = release.cells.find(cell => cell.mode === 'comprehensive' && cell.platform === host); - const other = release.cells.find(cell => cell.mode === 'comprehensive' && cell.platform === foreign)!; - const destination = join(root(), 'prepared'); - expect(() => prepareEvalJobs(release, skills, join(root(), 'both'), [other.id], privateCorpus)).toThrow('EVAL_SKILL_HASH_MISMATCH'); - prepareEvalJobs(release, { v3: skills.v3 }, destination, [other.id, ...(native ? [native.id] : [])], privateCorpus); - const receipts = join(root(), 'receipts'); mkdirSync(receipts); - const isolatedOther = isolate(destination, other); - const opaque = readFileSync(isolatedOther.input, 'utf8'), parsed = JSON.parse(opaque); - expect(Object.keys(parsed).sort()).toEqual(['cellRef', 'execution', 'schemaVersion', 'skill', 'source']); - expect(parsed).toMatchObject({ schemaVersion: 2, cellRef: other.id, execution: { mode: 'comprehensive', platform: other.platform, sourceHash: other.sourceHash } }); - expect(opaque).not.toMatch(/caseId|variant|vulnerable|"fixed"|"version"|repetition/); expect(opaque).not.toContain(other.caseId); - const smuggled = isolate(destination, other); - writeFileSync(smuggled.input, JSON.stringify({ ...parsed, caseId: other.caseId })); - await expect(runProducerCell(smuggled.input, join(receipts, `${other.id}.json`), withHelper({ adapter: new FakeAdapter(() => {}), paidExecutionAuthorized: true }))).rejects.toThrow('INVALID_PRODUCER_INPUT'); - expect(readFileSync(join(isolatedOther.source, 'src/app.txt'), 'utf8')).toBe(`synthetic ${other.caseId} ${other.variant}\n`); - await expect(runProducerCell(isolatedOther.input, join(receipts, `${other.id}.json`), withHelper({ adapter: new FakeAdapter(() => {}), paidExecutionAuthorized: true }))).rejects.toThrow('UNMATCHED_PRODUCER_PLATFORM'); - if (!native) return; - const isolatedNative = isolate(destination, native); - const receipt = await runProducerCell(isolatedNative.input, join(receipts, `${native.id}.json`), withHelper({ adapter: new FakeAdapter(() => {}), paidExecutionAuthorized: true })); - expect(receipt.cellRef).toBe(native.id); - const written = readFileSync(join(receipts, `${native.id}.json`), 'utf8'); - expect(JSON.parse(written)).not.toHaveProperty('cell'); - expect(written).not.toMatch(/caseId|variant|vulnerable|"fixed"/); expect(written).not.toContain(native.caseId); - }); - - test('seals source read-only and records a failed receipt after a mode/content mutation', async () => { - const destination = join(root(), 'prepared'); - const cell = selected[0]; - prepareEvalJobs(producerMatrix, skills, destination, [cell.id]); - const isolated = isolate(destination, cell); - const receipt = join(root(), `${cell.id}.json`); - const original = readFileSync(join(isolated.source, 'app.mjs'), 'utf8'); - const adapter = new FakeAdapter(opts => { - const source = opts.csoProducer!.sourceDirectory; - expect(source).toBe(isolated.source); - if (process.platform !== 'win32') { - expect(statSync(source).mode & 0o777).toBe(0o555); - expect(statSync(join(source, 'app.mjs')).mode & 0o777).toBe(0o444); - // Simulate a stronger same-UID compromise: postchecks must still detect it. - chmodSync(join(source, 'app.mjs'), 0o644); - } - writeFileSync(join(source, 'app.mjs'), 'changed by producer\n'); - }); - const written = await runProducerCell(isolated.input, receipt, withHelper({ adapter, paidExecutionAuthorized: true })); - expectIntegrityReceipt(written, receipt, process.platform === 'win32' - ? { code: 'INVALID_PRODUCER_SOURCE', reason: `source content check: "app.mjs" is ${'changed by producer\n'.length} bytes; expected ${Buffer.byteLength(original)}` } - : { code: 'PRODUCER_CHANGED_SOURCE_MODE', reason: 'source modes check: "app.mjs" has mode 644; expected 444' }); - expect(readFileSync(join(isolated.source, 'app.mjs'), 'utf8')).not.toBe(original); - }); -}); diff --git a/test/cso-file-ceiling.test.ts b/test/cso-file-ceiling.test.ts deleted file mode 100644 index 89dd6bc17..000000000 --- a/test/cso-file-ceiling.test.ts +++ /dev/null @@ -1,276 +0,0 @@ -// /cso file-count ceiling (#3068, manifest half of #2993): snapshot.json has its own -// 16 MiB cap and compact form, every per-entry list in a 1 MiB private artifact is -// bounded with an omitted count, and both capacity errors say what to do next. -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { MAX_OUTPUT } from '../lib/cso/contracts'; -import { - SNAPSHOT_MANIFEST_LIMIT, - capture, - readSnapshotManifest, - snapshotManifestCapMessage, - sourceCapMessage, -} from '../lib/cso/snapshot'; -import { boundedList, newRun, readJson } from '../lib/cso/state'; -import { runProcess } from '../lib/cso/process'; - -const ROOT = path.resolve(import.meta.dir, '..'); -const launcher = path.join(ROOT, 'bin', process.platform === 'win32' ? 'gstack-cso-launcher.exe' : 'gstack-cso-launcher'); -const MIB = 1024 * 1024; -const ISSUE = 'https://github.com/garrytan/gstack/issues/2993'; -const KEY = ['pass', 'word'].join(''); -let root = ''; -let state = ''; -const originalHome = process.env.GSTACK_HOME; - -function git(repo: string, ...args: string[]): string { - const result = spawnSync('/usr/bin/git', ['-C', repo, ...args], { encoding: 'utf8', env: { HOME: root, PATH: '/usr/bin:/bin' }, timeout: 60_000 }); - if (result.status) throw new Error(result.stderr); - return result.stdout; -} -function cso(repo: string, args: string[]) { - return spawnSync(launcher, args, { cwd: repo, encoding: 'utf8', env: { HOME: root, GSTACK_HOME: state, PATH: '/usr/bin:/bin' }, timeout: 120_000, maxBuffer: 64 * MIB }); -} -function makeRepo(name: string, files: Record): string { - const repo = path.join(root, name); - fs.mkdirSync(repo); - git(repo, 'init', '-q'); - git(repo, 'config', 'user.email', 'fixture@example.test'); - git(repo, 'config', 'user.name', 'Fixture'); - for (const [file, body] of Object.entries(files)) { - fs.mkdirSync(path.dirname(path.join(repo, file)), { recursive: true }); - fs.writeFileSync(path.join(repo, file), body); - } - git(repo, 'add', '-A'); - git(repo, 'commit', '-qm', 'fixture'); - return repo; -} -function runDir(run: { repoId: string; runId: string }): string { - return path.join(state, 'security', 'cso', run.repoId, run.runId); -} -function writeInput(name: string, value: unknown): string { - const file = path.join(root, name); - fs.writeFileSync(file, JSON.stringify(value)); - return file; -} -const application = { actors: ['tenant user'], assets: ['tenant records'], entrypoints: ['GET /users/:id'], tenantBoundaries: ['tenant id'], sensitiveOperations: ['record read'], invariants: ['tenant isolation'] }; -const finding = { title: 'Cross-tenant user read', rootCause: 'Tenant query omits caller tenant predicate', location: { path: 'src/users.ts', line: 1, symbol: 'tenantQuery' }, advisoryIds: [], severity: 'high', confidence: 'high', confidenceRationale: 'The caller-to-query trace and missing tenant predicate directly support the finding', evidence: 'supported', attackerControl: 'Authenticated caller chooses the record ID', impact: 'Another tenant record is returned', scenario: 'A tenant supplies a known record ID owned by another tenant and receives that record', trace: ['GET /users/:id', 'tenantQuery', 'findUnique by id'], references: ['src/users.ts:1', 'OWASP API1:2023'], recommendation: 'Bind the lookup predicate to the authenticated tenant identifier', challenge: { reviewer: 'independent-2', independent: true, mode: 'independent_agent', callers: 'Authenticated route forwards the ID', controls: 'Authentication does not bind tenant', counterevidence: 'Opaque IDs reduce guessing but do not authorize', conclusion: 'The authorization invariant is absent' } }; -function completeEvidence(report: any, findings: unknown[]) { - return { application, findings, coverage: report.coverage.filter((item: any) => !['snapshot-inputs', 'history-inputs'].includes(item.domain)).map((item: any) => ({ ...item, status: 'assessed', method: 'fresh caller and boundary trace', gaps: [], evidence: ['current captured source'] })), gaps: [] }; -} -const USERS = 'export const tenantQuery = (id:string) => db.user.findUnique({where:{id}})\n'; -// Long nested paths where most files are excluded or withheld and many carry -// scanner hits: the shape that overflowed report.json and sensitive-evidence.json. -function hostileFiles(count: number): Record { - const files: Record = { 'src/users.ts': USERS }; - for (let i = 1; i < count; i++) { - const dir = `packages/very-long-workspace-package-name-${i % 50}/src/components/deeply/nested/feature-area-${i % 17}`; - switch (i % 5) { - case 0: - files[`${dir}/module_file_number_${i}.ts`] = Array.from({ length: 12 }, (_, k) => `${KEY} = "Sup3rS3cretValue${i}x${k}"\n`).join(''); - break; - case 1: - files[`node_modules/${dir}/dependency_file_number_${i}.js`] = `module.exports=${i}\n`; - break; - case 2: - files[`.claude/${dir}/agent_config_file_number_${i}.md`] = `cfg ${i}\n`; - break; - case 3: - files[`${dir}/binary_asset_number_${i}.bin`] = Buffer.from(`a\0b${i}`); - break; - default: - files[`${dir}/certificate_number_${i}.pem`] = `not a key ${i}\n`; - } - } - return files; -} - -beforeAll(() => { - root = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-ceiling-')); - state = path.join(root, 'state'); - process.env.GSTACK_HOME = state; -}); -afterAll(() => { - if (originalHome === undefined) delete process.env.GSTACK_HOME; - else process.env.GSTACK_HOME = originalHome; - fs.rmSync(root, { recursive: true, force: true }); -}); - -describe('CSO snapshot manifest cap', () => { - test('the snapshot cap is local to snapshot.json; shared limits stay 1 MiB', () => { - expect(MAX_OUTPUT).toBe(MIB); - expect(SNAPSHOT_MANIFEST_LIMIT).toBe(16 * MIB); - const dir = fs.mkdtempSync(path.join(root, 'caps-')); - fs.chmodSync(dir, 0o700); - const big = JSON.stringify({ padding: 'x'.repeat(MIB + 16) }); - for (const name of ['report.json', 'snapshot.json']) fs.writeFileSync(path.join(dir, name), big, { mode: 0o600 }); - expect(() => readJson(path.join(dir, 'report.json'))).toThrow('Invalid private state file'); - expect(() => readJson(path.join(dir, 'snapshot.json'))).toThrow('Invalid private state file'); - expect(readSnapshotManifest(dir)).toEqual(JSON.parse(big)); - fs.writeFileSync(path.join(dir, 'snapshot.json'), JSON.stringify({ padding: 'x'.repeat(16 * MIB) }), { mode: 0o600 }); - expect(() => readSnapshotManifest(dir)).toThrow('Invalid private state file'); - }); - - test('every snapshot.json read in the helper goes through readSnapshotManifest', () => { - const files = fs.readdirSync(path.join(ROOT, 'lib', 'cso')).filter((file) => file.endsWith('.ts')); - for (const file of files) { - const source = fs.readFileSync(path.join(ROOT, 'lib', 'cso', file), 'utf8'); - expect(source).not.toMatch(/readJson\(\s*join\([^)]*'snapshot\.json'\)\s*\)/); - } - const cli = fs.readFileSync(path.join(ROOT, 'lib', 'cso', 'cli.ts'), 'utf8'); - expect(cli.match(/readSnapshotManifest\(/g)?.length).toBeGreaterThanOrEqual(13); - const snapshot = fs.readFileSync(path.join(ROOT, 'lib', 'cso', 'snapshot.ts'), 'utf8'); - expect(snapshot).toContain("readJson(join(runDir, 'snapshot.json'), SNAPSHOT_MANIFEST_LIMIT)"); - expect(snapshot).toContain('> SNAPSHOT_MANIFEST_LIMIT'); - expect(snapshot).not.toContain('JSON.stringify(manifest, null, 2)'); - }); - - test('both capacity errors name the bound cap, measured value, what counts, next step and #2993', () => { - const manifest = snapshotManifestCapMessage(61_234, 17_000_000); - expect(manifest).toStartWith('Snapshot manifest cap exceeded:'); - for (const part of ['61234 source entries', '17000000 byte', 'cap is 16.0 MiB', 'One entry is recorded for every tracked', 'Next step:', ISSUE, 'No supported workaround']) - expect(manifest).toContain(part); - const source = sourceCapMessage(346_199_207, 7_561); - expect(source).toStartWith('64 MiB source cap exceeded:'); - for (const part of ['7561 source files', '346199207 bytes', 'cap is 64.0 MiB', 'files over 1 MiB whose payloads are withheld', 'Next step:', ISSUE, 'No supported workaround']) - expect(source).toContain(part); - }); - - test('the 64 MiB source cap still fails closed, with the actionable message on stderr', () => { - const repo = makeRepo('over-source-cap', { 'src/users.ts': USERS, 'assets/a.bin': Buffer.alloc(40 * MIB, 1), 'assets/b.bin': Buffer.alloc(25 * MIB, 1) }); - const result = cso(repo, ['start', '--repo', repo, '--offline']); - expect(result.status).not.toBe(0); - expect(result.stdout).toBe(''); - const error = JSON.parse(result.stderr).error; - expect(error.code).toBe('MISSING_INPUT'); - expect(error.message).toStartWith('64 MiB source cap exceeded: 3 source files hold about 65.0 MiB'); - expect(error.message).toContain(ISSUE); - expect(error.message).toContain('No supported workaround'); - }, 120_000); -}); - -describe('CSO bounded per-entry lists', () => { - test('keeps leading items, appends one omitted-count summary, and leaves short lists untouched', () => { - const items = Array.from({ length: 1000 }, (_, i) => `entry-${i}`); - expect(boundedList(3, (i) => items[i], { bytes: 4096 }, 2, (n) => `${n} omitted`)).toEqual(items.slice(0, 3)); - const budget = { bytes: 2048 }, - kept = boundedList(items.length, (i) => items[i], budget, 2, (n) => `${n} omitted`); - expect(kept.length).toBeLessThan(items.length); - expect(kept.at(-1)).toBe(`${items.length - kept.length + 1} omitted`); - expect(kept.slice(0, -1)).toEqual(items.slice(0, kept.length - 1)); - expect(budget.bytes).toBeGreaterThanOrEqual(0); - }); -}); - -describe('CSO above the old file-count ceiling', () => { - test('a 2,500-file repository still captures and round-trips', async () => { - const files: Record = {}; - for (let i = 1; i <= 2500; i++) files[`src/pkg/sub/file_number_${i}.ts`] = `export const v${i} = ${i};\n`; - const repo = makeRepo('plain-2500', files), - run = newRun(repo), - manifest = await capture(repo, run.dir); - expect(manifest.entries).toHaveLength(2500); - expect(readSnapshotManifest(run.dir)).toEqual(manifest); - }, 120_000); - - test('Git path listings over 1 MiB are admitted, with and without a comparison base', async () => { - const files: Record = {}, - dir = Array.from({ length: 6 }, (_, i) => `workspace-segment-with-a-long-descriptive-name-${i}`).join('/'); - for (let i = 1; i <= 5000; i++) files[`${dir}/file_number_${i}.ts`] = `export const v${i} = ${i};\n`; - const repo = makeRepo('long-listing', files); - expect(Buffer.byteLength(git(repo, 'ls-files', '-z'))).toBeGreaterThan(MIB); - const plain = await capture(repo, newRun(repo).dir); - expect(plain.entries).toHaveLength(5000); - const based = await capture(repo, newRun(repo).dir, 'HEAD'); - expect(based.entries).toHaveLength(5000); - expect(based.changedPaths).toEqual([]); - }, 180_000); - - test('only raw callers can opt in to output above MAX_OUTPUT', async () => { - const cwd = fs.mkdtempSync(path.join(root, 'raw-')), - script = ['-c', 'head -c 1200000 /dev/zero | tr "\\0" a'], - env = { PATH: '/usr/bin:/bin' }; - expect((await runProcess('/bin/sh', script, { cwd, env, maxBytes: 2 * MIB })).truncated).toBe(true); - expect((await runProcess('/bin/sh', script, { cwd, env, raw: true })).truncated).toBe(true); - const raw = await runProcess('/bin/sh', script, { cwd, env, raw: true, maxBytes: 2 * MIB }); - expect(raw.truncated).toBe(false); - expect(raw.stdout).toHaveLength(1_200_000); - }); - - test('5,000 long nested paths, mostly excluded or withheld with many scanner hits, run start to final report and recheck', () => { - const repo = makeRepo('hostile-5000', hostileFiles(5000)), - started = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline']); - expect(started.stderr).toBe(''); - expect(started.status).toBe(0); - expect(Buffer.byteLength(started.stdout)).toBeLessThan(MIB); - const run = JSON.parse(started.stdout), - dir = runDir(run); - - const rawManifest = fs.readFileSync(path.join(dir, 'snapshot.json'), 'utf8'), - manifest = readSnapshotManifest(dir); - expect(Buffer.byteLength(rawManifest)).toBeGreaterThan(MIB); - expect(rawManifest).toBe(JSON.stringify(manifest) + '\n'); - expect(manifest.entries).toHaveLength(5000); - - const evidence = readJson(path.join(dir, 'sensitive-evidence.json')); - expect(fs.statSync(path.join(dir, 'sensitive-evidence.json')).size).toBeLessThan(MIB); - expect(evidence.at(-1).note).toContain(`${evidence.at(-1).omitted} more files with sensitive-pattern findings are not listed`); - expect(evidence.length - 1 + evidence.at(-1).omitted).toBe(999); - - const initial = readJson(path.join(dir, 'report.json')), - snapshot = initial.coverage.find((item: any) => item.domain === 'snapshot-inputs'), - transformations = initial.source.transformations; - expect(fs.statSync(path.join(dir, 'report.json')).size).toBeLessThan(400 * 1024); - expect(snapshot.evidence).toEqual(['1000 sanitized execution inputs captured; 3000 explicit non-executable exclusions; 1000 unread in-scope inputs; 0 tracked deletions']); - expect(snapshot.status).toBe('partial'); - const omittedCount = (line: string) => Number(line.match(/^(\d+) more/)?.[1]); - expect(snapshot.gaps.length - 1 + omittedCount(snapshot.gaps.at(-1))).toBe(1000); - expect(snapshot.gaps.at(-1)).toContain('more unread or deleted in-scope inputs are not listed to keep report.json within its 1 MiB bound'); - expect(snapshot.exclusions.length - 1 + omittedCount(snapshot.exclusions.at(-1))).toBe(3000); - expect(transformations.at(-1).path).toBe('[not listed]'); - expect(transformations.length - 1 + omittedCount(transformations.at(-1).handling)).toBe(4999); - expect(transformations.length).toBeGreaterThan(100); - expect(initial.events[0].message).toBe('Captured 5000 source entries; 4999 transformations disclosed'); - - const inspected = cso(repo, ['inspect', run.runId]); - expect(inspected.status).toBe(0); - expect(JSON.parse(inspected.stdout).manifest.entries).toHaveLength(5000); - - expect(cso(repo, ['submit', run.runId, writeInput('hostile-evidence.json', completeEvidence(initial, [finding]))]).status).toBe(0); - const finished = cso(repo, ['finish', run.runId]); - expect(finished.stderr).toBe(''); - expect(finished.status).toBe(0); - const final = readJson(path.join(dir, 'report.json')); - expect(final.status).toBe('finished'); - expect(final.findings).toHaveLength(1); - expect(fs.statSync(path.join(dir, 'report.json')).size).toBeLessThan(MIB); - - const rechecked = cso(repo, ['recheck', final.findings[0].id, '--repo', repo]); - expect(rechecked.stderr).toBe(''); - expect(rechecked.status).toBe(0); - const child = JSON.parse(rechecked.stdout); - expect(child.parent).toEqual({ runId: run.runId, findingId: final.findings[0].id, kind: 'recheck' }); - expect(readSnapshotManifest(runDir({ ...child, repoId: run.repoId })).entries).toHaveLength(5000); - }, 300_000); - - test('a retained pretty-printed snapshot.json from an older helper still loads in recheck', () => { - const repo = makeRepo('legacy-pretty', { 'src/users.ts': USERS, 'src/other.ts': 'export const unrelated = true\n' }), - run = JSON.parse(cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline']).stdout), - dir = runDir(run), - initial = readJson(path.join(dir, 'report.json')); - expect(cso(repo, ['submit', run.runId, writeInput('legacy-evidence.json', completeEvidence(initial, [finding]))]).status).toBe(0); - expect(cso(repo, ['finish', run.runId]).status).toBe(0); - const file = path.join(dir, 'snapshot.json'); - fs.writeFileSync(file, JSON.stringify(JSON.parse(fs.readFileSync(file, 'utf8')), null, 2) + '\n'); - expect(fs.readFileSync(file, 'utf8')).toContain('\n "entries": ['); - expect(cso(repo, ['inspect', run.runId]).status).toBe(0); - const findingId = readJson(path.join(dir, 'report.json')).findings[0].id, - rechecked = cso(repo, ['recheck', findingId, '--run', run.runId, '--repo', repo]); - expect(rechecked.stderr).toBe(''); - expect(rechecked.status).toBe(0); - expect(JSON.parse(rechecked.stdout).parent.runId).toBe(run.runId); - }, 120_000); -}); diff --git a/test/cso-git-global-config.test.ts b/test/cso-git-global-config.test.ts deleted file mode 100644 index d33eadf66..000000000 --- a/test/cso-git-global-config.test.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { afterAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { childEnvironment, EMPTY_GLOBAL_GIT_CONFIG, executable } from '../lib/cso/process'; - -const roots: string[] = []; -afterAll(() => { - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); - -function homeWithGlobalConfig(): string { - const home = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-git-global-')); - roots.push(home); - fs.writeFileSync(path.join(home, '.gitconfig'), '[user]\n\tname = leaked-global\n'); - fs.mkdirSync(path.join(home, '.config', 'git'), { recursive: true }); - fs.writeFileSync(path.join(home, '.config', 'git', 'config'), '[user]\n\temail = leaked@xdg.invalid\n'); - return home; -} - -function gitConfig(home: string, env: Record, args: string[]) { - return spawnSync(executable('git'), ['config', ...args], { cwd: home, env, encoding: 'utf8', timeout: 30_000 }); -} - -describe('CSO child Git reads no global or system config (#3082)', () => { - test('uses the /dev/null spelling on every platform and keeps NOSYSTEM', () => { - const env = childEnvironment(os.tmpdir()); - expect(EMPTY_GLOBAL_GIT_CONFIG).toBe('/dev/null'); - expect(env.GIT_CONFIG_GLOBAL).toBe('/dev/null'); - expect(env.GIT_CONFIG_NOSYSTEM).toBe('1'); - }); - - test('the fixture home is read when the override is absent', () => { - const home = homeWithGlobalConfig(); - const { GIT_CONFIG_GLOBAL: _ignored, ...env } = childEnvironment(home); - const result = gitConfig(home, env, ['--global', '--list']); - expect(result.status).toBe(0); - expect(result.stdout).toContain('user.name=leaked-global'); - }); - - test('git config --global --list is empty and exits 0 under the CSO environment', () => { - const home = homeWithGlobalConfig(); - const result = gitConfig(home, childEnvironment(home), ['--global', '--list']); - expect(result.stderr).toBe(''); - expect(result.status).toBe(0); - expect(result.stdout).toBe(''); - }); - - test('neither the home nor the XDG config reaches the merged view', () => { - const home = homeWithGlobalConfig(); - const result = gitConfig(home, childEnvironment(home), ['--list']); - expect(result.status).toBe(0); - expect(result.stdout).not.toContain('leaked'); - }); -}); diff --git a/test/cso-git-hardening.test.ts b/test/cso-git-hardening.test.ts deleted file mode 100644 index 99021e7d4..000000000 --- a/test/cso-git-hardening.test.ts +++ /dev/null @@ -1,169 +0,0 @@ -import { afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { capture } from '../lib/cso/snapshot'; -import { childEnvironment, executable, git as readGitMetadata, runProcess } from '../lib/cso/process'; - -const roots:string[]=[]; -afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); - -const fixtureGit=(repo:string,home:string)=>(...args:string[])=>{const result=spawnSync('/usr/bin/git',['-C',repo,...args],{encoding:'utf8',env:{HOME:home,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.error||result.status!==0)throw new Error(`fixture git ${args.join(' ')} failed (status ${result.status}, signal ${result.signal}): ${result.error?.message??result.stderr}`);return result.stdout;}; -// Each fixture builds its own repository from Git; nothing is copied from a shared -// template (Free Tests 40288142343 shard 17: fs.cpSync of the template threw inside -// its directory walk once and passed on the serial retry). Auto-maintenance is off -// because `git commit` otherwise starts a detached `git maintenance run --auto` that -// creates and deletes .git/objects/maintenance.lock after the commit returns, under -// the tests' own .git reads and the afterEach rmSync (docs/TESTING_INTERNALS.md, -// Free-suite flake rules); fixtureGit's replacement env never sees the shard backstop. -function seedRepo(repo:string,home:string){ - const git=fixtureGit(repo,home);fs.mkdirSync(repo); - git('init','-q');git('config','user.email','fixture@example.test');git('config','user.name','Fixture'); - git('config','maintenance.auto','false');git('config','gc.auto','0'); - fs.writeFileSync(path.join(repo,'tracked.ts'),'export const tracked = true\n');git('add','tracked.ts');git('commit','-qm','base'); - return git; -} -// The first /usr/bin/git spawns on a cold macOS runner can eat a test's whole 5 s budget before the code under test runs; pay them once here. -// Every test below skips on Windows, which has no /usr/bin/git, so the warm-up does too. -beforeAll(()=>{ - if(process.platform==='win32')return; - const warm=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cso-git-hardening-warm-'))); - try{seedRepo(path.join(warm,'repo'),warm);}finally{fs.rmSync(warm,{recursive:true,force:true});} -},{timeout:30_000}); - -function fixture(){ - const root=fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(),'cso-git-hardening-'))),repo=path.join(root,'repo'),runDir=path.join(root,'state','run'); - roots.push(root);const git=seedRepo(repo,root);fs.mkdirSync(runDir,{recursive:true,mode:0o700}); - return{root,repo,runDir,git}; -} - -function replaceWithSymlinkAfterLstat(target:string,replacement:string,occurrence=1){ - const original=fs.lstatSync;let hits=0,swapped=false; - const patched=spyOn(fs,'lstatSync').mockImplementation(((candidate:any,options?:any)=>{ - const result=options===undefined?original(candidate):original(candidate,options); - if(path.resolve(String(candidate))===target&&++hits===occurrence){ - fs.renameSync(target,`${target}.parked`);fs.symlinkSync(replacement,target);swapped=true; - } - return result; - }) as typeof fs.lstatSync); - return{patched,wasSwapped:()=>swapped}; -} - -describe('CSO Git metadata hardening',()=>{ - test.skipIf(process.platform==='win32')('reports a bounded operation and exit status without exposing Git argv or paths',async()=>{ - const {root,repo}=fixture();let failure:any; - try{await readGitMetadata(repo,['rev-parse','--verify','secret-ref-name'],root);}catch(error){failure=error;} - expect(failure).toMatchObject({code:'MISSING_INPUT'}); - expect(failure.message).toContain('rev-parse exited'); - expect(failure.message).toContain('(request rejected)'); - expect(failure.message).not.toContain(root); - expect(failure.message).not.toContain('secret-ref-name'); - }); - - test.skipIf(process.platform==='win32')('labels the fixed object-format phase without exposing repository data',async()=>{ - const {root,repo}=fixture();fs.appendFileSync(path.join(repo,'.git','config'),'\n[broken configuration\n');let failure:any; - try{await readGitMetadata(repo,['rev-parse','--show-object-format'],root);}catch(error){failure=error;} - expect(failure).toMatchObject({code:'MISSING_INPUT'}); - expect(failure.message).toContain('object-format exited'); - expect(failure.message).toContain('(configuration rejected)'); - expect(failure.message).not.toContain(root); - }); - - test.skipIf(process.platform==='win32')('refuses trusted Git calls that are not bound to one audited worktree',async()=>{ - const {root}=fixture(); - await expect(runProcess(executable('git'),['rev-parse','--is-inside-work-tree'],{cwd:root,env:childEnvironment(root),raw:true})).rejects.toMatchObject({code:'INVALID_ARGUMENT'}); - }); - - test.skipIf(process.platform==='win32')('pins every metadata read to the audited worktree and ignores configured global excludes',async()=>{ - const {root,repo,runDir,git}=fixture(),empty=path.join(root,'decoy-worktree'),excludes=path.join(root,'global-excludes'); - fs.mkdirSync(empty);fs.writeFileSync(excludes,'untracked-security.ts\n'); - fs.writeFileSync(path.join(repo,'untracked-security.ts'),'export const vulnerable = true\n'); - const caseSensitive=!fs.existsSync(path.join(repo,'TRACKED.ts')); - if(caseSensitive)fs.writeFileSync(path.join(repo,'TRACKED.ts'),'export const caseVariant = true\n'); - git('config','core.worktree',empty);git('config','core.excludesFile',excludes);git('config','core.ignoreCase','true');git('config','core.precomposeUnicode','true'); - - const manifest=await capture(repo,runDir,'HEAD'); - - expect(manifest.entries.map(entry=>entry.path)).toContain('untracked-security.ts'); - if(caseSensitive)expect(manifest.entries.map(entry=>entry.path)).toContain('TRACKED.ts'); - expect(fs.readFileSync(path.join(runDir,'snapshot','untracked-security.ts'),'utf8')).toContain('vulnerable'); - expect(manifest.changedPaths).toContain('untracked-security.ts'); - }); - - test.skipIf(process.platform==='win32')('ignores replacement refs when retaining tracked deletions and history',async()=>{ - const {repo,runDir,git}=fixture(),head=git('rev-parse','HEAD').trim(),emptyTree=git('mktree').trim(),replacement=git('commit-tree',emptyTree,'-m','replacement-history').trim(); - git('replace',head,replacement);git('rm','-q','-f','tracked.ts'); - - const manifest=await capture(repo,runDir); - const history=fs.readFileSync(path.join(runDir,'history.txt'),'utf8'); - - expect(manifest.headCommit).toBe(head); - expect(manifest.deletedPaths).toEqual([{path:'tracked.ts',pathId:expect.stringMatching(/^[a-f0-9]{32}$/)}]); - expect(history).toContain('Subject: base'); - expect(history).not.toContain('replacement-history'); - }); - - test.skipIf(process.platform==='win32')('retained history withholds diffs of credential files the snapshot excludes',async()=>{ - const {repo,runDir,git}=fixture(); - fs.writeFileSync(path.join(repo,'.env'),'UPSTREAM_TOKEN=planted-history-value\n');fs.writeFileSync(path.join(repo,'tracked.ts'),'export const tracked = false\n'); - git('add','.env','tracked.ts');git('commit','-qm','configure upstream'); - - await capture(repo,runDir); - const history=fs.readFileSync(path.join(runDir,'history.txt'),'utf8'); - - expect(history).not.toContain('planted-history-value'); - expect(history).toContain('diff withheld: .env (credential or execution configuration)'); - expect(history).toContain('+export const tracked = false'); - expect(history).toContain('Subject: configure upstream'); - }); - - test.skipIf(process.platform==='win32')('rejects repository config includes before Git can consume them',async()=>{ - const {root,repo,runDir}=fixture(),included=path.join(root,'included.conf'); - fs.writeFileSync(included,'[core]\n\tworktree = /tmp/cso-decoy\n'); - fs.appendFileSync(path.join(repo,'.git','config'),`\n[include]\n\tpath = ${included}\n`); - - await expect(capture(repo,runDir)).rejects.toMatchObject({code:'UNSAFE_PATH',message:'Repository Git config includes are not allowed during a security snapshot'}); - }); - - test.skipIf(process.platform==='win32')('binds an absent main-worktree config so it cannot appear after inspection',async()=>{ - const {root,repo,git}=fixture(),worktreeConfig=path.join(repo,'.git','config.worktree'),lstat=fs.lstatSync; - git('config','extensions.worktreeConfig','true');let injected=false; - const patched=spyOn(fs,'lstatSync').mockImplementation(((candidate:any,options?:any)=>{ - try{return options===undefined?lstat(candidate):lstat(candidate,options);}catch(error:any){ - if(!injected&&path.resolve(String(candidate))===worktreeConfig&&error?.code==='ENOENT'){ - fs.writeFileSync(worktreeConfig,'[cso]\n\tmarker = created-after-inspection\n');injected=true; - } - throw error; - } - }) as typeof fs.lstatSync); - try{await expect(runProcess(executable('git'),['--no-optional-locks','-C',repo,'rev-parse','--is-inside-work-tree'],{cwd:root,env:childEnvironment(root),raw:true})).rejects.toMatchObject({code:'SNAPSHOT_RACE'});}finally{patched.mockRestore();} - expect(injected).toBe(true); - }); - - test.skipIf(process.platform==='win32')('does not follow a repository config swapped after its bounded lstat',async()=>{ - const {root,repo,runDir}=fixture(),config=path.join(repo,'.git','config'),oversized=path.join(root,'oversized-config'); - fs.writeFileSync(oversized,'[core]\n'+'.'.repeat(1024*1024)); - const race=replaceWithSymlinkAfterLstat(config,oversized); - try{await expect(capture(repo,runDir)).rejects.toMatchObject({code:'SNAPSHOT_RACE'});}finally{race.patched.mockRestore();} - expect(race.wasSwapped()).toBe(true); - }); - - test.skipIf(process.platform==='win32')('does not follow a worktree .git pointer swapped between lstat and open',async()=>{ - const {root,repo,runDir}=fixture(),gitDir=path.join(root,'git-data'),marker=path.join(repo,'.git'),oversized=path.join(root,'oversized-git-pointer'); - fs.renameSync(marker,gitDir);fs.writeFileSync(marker,'gitdir: ../git-data\n');fs.writeFileSync(oversized,'gitdir: '+'.'.repeat(16*1024)); - const race=replaceWithSymlinkAfterLstat(marker,oversized); - try{await expect(capture(repo,runDir)).rejects.toMatchObject({code:'SNAPSHOT_RACE'});}finally{race.patched.mockRestore();} - expect(race.wasSwapped()).toBe(true); - }); - - test.skipIf(process.platform==='win32')('does not follow a linked-worktree commondir pointer swapped after lstat',async()=>{ - const {root,repo,git}=fixture(),linked=path.join(root,'linked'); - git('worktree','add','-q','-b','linked-security-test',linked); - const marker=fs.readFileSync(path.join(linked,'.git'),'utf8').trim().replace(/^gitdir:\s*/,''),gitDir=fs.realpathSync(path.resolve(linked,marker)),common=path.join(gitDir,'commondir'),oversized=path.join(root,'oversized-commondir'); - fs.writeFileSync(oversized,'.'.repeat(16*1024)); - const race=replaceWithSymlinkAfterLstat(common,oversized); - try{await expect(runProcess(executable('git'),['--no-optional-locks','-C',linked,'rev-parse','--is-inside-work-tree'],{cwd:root,env:childEnvironment(root),raw:true})).rejects.toMatchObject({code:'SNAPSHOT_RACE'});}finally{race.patched.mockRestore();} - expect(race.wasSwapped()).toBe(true); - }); -}); diff --git a/test/cso-history.test.ts b/test/cso-history.test.ts deleted file mode 100644 index 71cde803b..000000000 --- a/test/cso-history.test.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { describe,expect,test } from 'bun:test'; -import { gitDiffHeaderPaths,historyForPath,withholdHistory } from '../lib/cso/history'; - -describe('CSO retained Git history path filtering',()=>{ - test('matches exact paths without leaking a prefix sibling hunk',()=>{ - const raw=`commit ${'a'.repeat(40)} -Author: Fixture -diff --git a/foo b/foo ---- a/foo -+++ b/foo -+wanted -diff --git a/foo-extra b/foo-extra ---- a/foo-extra -+++ b/foo-extra -+must-not-leak -`; - const selected=historyForPath(raw,'foo')!; - expect(selected).toContain('+wanted'); - expect(selected).not.toContain('must-not-leak'); - }); - - test('decodes Git C-quoted UTF-8 and space-bearing header paths',()=>{ - expect(gitDiffHeaderPaths('diff --git "a/caf\\303\\251 file.ts" "b/caf\\303\\251 file.ts"')).toEqual(['a/café file.ts','b/café file.ts']); - const raw=`commit ${'b'.repeat(40)}\nSubject: Unicode\ndiff --git "a/caf\\303\\251 file.ts" "b/caf\\303\\251 file.ts"\n+unicode-only\n`; - expect(historyForPath(raw,'café file.ts')).toContain('+unicode-only'); - }); - - test('withholds every diff section touching an excluded path, keeping commit preambles and other files',()=>{ - const raw=`commit ${'c'.repeat(40)} -Subject: add config -diff --git a/.env b/.env ---- /dev/null -+++ b/.env -+PLANTED_VALUE=excluded-file-body -diff --git a/app.ts b/app.ts ---- a/app.ts -+++ b/app.ts -+kept-line -commit ${'d'.repeat(40)} -Subject: rename -diff --git a/config/old.txt b/config/master.key -rename from config/old.txt -rename to config/master.key -+renamed-into-excluded -diff --git "a/foo b/foo -+unparseable-body -`; - const kept=withholdHistory(raw,(path)=>/(^|\/)(\.env|master\.key)$/.test(path)?'credential or execution configuration':undefined); - expect(kept).not.toContain('excluded-file-body'); - expect(kept).not.toContain('renamed-into-excluded'); - expect(kept).not.toContain('unparseable-body'); - expect(kept).toContain('diff withheld: .env (credential or execution configuration)'); - expect(kept).toContain('diff withheld: config/master.key (credential or execution configuration)'); - expect(kept).toContain('diff withheld: unknown path (unparseable diff header)'); - expect(kept).toContain('+kept-line'); - expect(kept).toContain('Subject: add config'); - expect(kept).toContain('Subject: rename'); - }); - - test('rejects malformed quoted headers instead of broadening the match',()=>{ - expect(gitDiffHeaderPaths('diff --git "a/foo b/foo')).toBeUndefined(); - expect(historyForPath('diff --git "a/foo b/foo\n+secret\n','foo')).toBeUndefined(); - }); -}); diff --git a/test/cso-image-provisioning.test.ts b/test/cso-image-provisioning.test.ts deleted file mode 100644 index caf33ac00..000000000 --- a/test/cso-image-provisioning.test.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import { join } from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { dispatchCsoCommand, type CsoCliDependencies } from '../lib/cso/cli'; -import { canonical, CsoError, sha256 } from '../lib/cso/contracts'; -import { ISOLATION_POLICY_HASH } from '../lib/cso/docker'; -import { - catalogImageProvisioningPolicy, - inspectCatalogImages, - openLocalCatalogImageSession, - provisionCatalogImages, - qualifiedCatalogImages, - type CatalogImageSession, - type QualifiedCatalogImage, -} from '../lib/cso/image-provisioning'; -import { scannerVersionHash, type QualifiedScanner, type ScannerCatalog } from '../lib/cso/scanner-catalog'; -import { SCANNER_IDS, scannerPlans, type ScannerId } from '../lib/cso/scanners'; -import type { RuntimePlatform } from '../lib/cso/runtime-catalog'; -import { completeRuntimeCatalogFixture } from './helpers/cso-runtime-catalog'; - -const roots:string[]=[]; -afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); -const target:RuntimePlatform=process.arch==='arm64'?'linux/arm64':'linux/amd64'; -const hash='a'.repeat(64),digest=`sha256:${hash}`,sourceCommit='b'.repeat(40),workflow='https://github.com/garrytan/gstack/actions/runs/42'; -function scannerProfile(scanner:ScannerId,platform:RuntimePlatform):QualifiedScanner{ - const arch=platform.endsWith('arm64')?'arm64':'amd64',version=scanner==='osv'?'2.4.0':'4.0.0'; - return{id:`${scanner}-provision-${arch}`,scanner,state:'qualified',platform,image:`ghcr.io/garrytan/gstack/cso-scanners/${scanner}-${arch}@${digest}`, - entrypoint:'/opt/cso/entrypoint',executable:'/opt/cso/bin/scanner',version,versionOutputSha256:scannerVersionHash(`${scanner} version ${version}\n`),helperAbi:3,isolationPolicyHash:ISOLATION_POLICY_HASH, - capabilities:scannerPlans({snapshotRoot:'/source',offline:true,selected:[scanner]})[0].requiredFeatures, - ...(scanner==='semgrep'?{assets:{semgrepRules:{path:'/policy/catalog/semgrep.yml',sha256:hash}}}:{}), - ...(['osv','trivy'].includes(scanner)?{assets:{advisoryDatabase:{path:'/opt/cso/scanner-data/db',contentSha256:hash,updatedAt:'2026-09-09T00:00:00.000Z',ecosystems:['npm']}}}:{}), - qualifiedAt:'2026-09-09T00:00:00.000Z',qualification:{sourceCommit,workflow,sbomDigest:digest,provenanceDigest:digest,verifiedProvenance:true,containmentPassed:true,adapterContractPassed:true,offlineAssetsPassed:true}}; -} -function scannerCatalog():ScannerCatalog{ - const scanners=SCANNER_IDS.flatMap(scanner=>[scannerProfile(scanner,'linux/amd64'),scannerProfile(scanner,'linux/arm64')]); - return{schemaVersion:1,revision:'scanner-provisioning-fixture',helperAbi:3,promotion:{sourceCommit,workflow,evidenceDigest:`sha256:${sha256(canonical(scanners))}`},scanners}; -} -function session(options:{present?:(entry:QualifiedCatalogImage)=>boolean;pull?:(entry:QualifiedCatalogImage)=>void}={}):{value:CatalogImageSession;calls:{present:string[];pull:string[]};closed:()=>boolean}{ - const calls={present:[] as string[],pull:[] as string[]};let closed=false; - return{calls,closed:()=>closed,value:{docker:{endpoint:'unix:///trusted/docker.sock',version:'27.0.0',security:['seccomp']}, - present:async entry=>{calls.present.push(entry.image);return options.present?.(entry)??false;}, - pull:async entry=>{calls.pull.push(entry.image);options.pull?.(entry);},close:()=>{closed=true;}}}; -} -function nodeRepo():string{ - const root=fs.mkdtempSync(join(os.tmpdir(),'cso-image-doctor-'));roots.push(root); - fs.writeFileSync(join(root,'package.json'),JSON.stringify({name:'doctor-fixture',version:'1.0.0'})); - fs.writeFileSync(join(root,'package-lock.json'),JSON.stringify({name:'doctor-fixture',version:'1.0.0',lockfileVersion:3,packages:{'':{name:'doctor-fixture',version:'1.0.0'}}})); - fs.writeFileSync(join(root,'app.js'),'export const ready = true\n'); - for(const args of [['init','-q'],['config','user.email','fixture@example.test'],['config','user.name','Fixture'],['add','.'],['commit','-qm','fixture']]){ - const result=spawnSync('/usr/bin/git',['-C',root,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr); - } - return root; -} -function railsPostgresRepo():string{ - const root=fs.mkdtempSync(join(os.tmpdir(),'cso-image-doctor-rails-'));roots.push(root);fs.mkdirSync(join(root,'config')); - fs.writeFileSync(join(root,'Gemfile'),''); - fs.writeFileSync(join(root,'Gemfile.lock'),`GEM\n remote: https://rubygems.org/\n specs:\n pg (1.5.9)\n\nPLATFORMS\n ruby\n\nDEPENDENCIES\n pg\n\nRUBY VERSION\n ruby 3.3.6p108\n\nBUNDLED WITH\n 2.6.9\n`); - fs.writeFileSync(join(root,'config/database.yml'),'test:\n adapter: postgresql\n database: app_test\n'); - for(const args of [['init','-q'],['config','user.email','fixture@example.test'],['config','user.name','Fixture'],['add','.'],['commit','-qm','fixture']]){ - const result=spawnSync('/usr/bin/git',['-C',root,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr); - } - return root; -} - -describe('trusted CSO image provisioning',()=>{ - test('setup derives a bounded allowance per declared catalog image',()=>{ - expect(catalogImageProvisioningPolicy(11)).toEqual({perImageMs:30_000,aggregateMs:360_000}); - expect(catalogImageProvisioningPolicy(11,'300')).toEqual({perImageMs:300_000,aggregateMs:3_330_000}); - expect(()=>catalogImageProvisioningPolicy(11,'4')).toThrow('5..300'); - expect(()=>catalogImageProvisioningPolicy(11,'301')).toThrow('5..300'); - expect(()=>catalogImageProvisioningPolicy(12,'300')).toThrow('bounded setup preload capacity'); - }); - - test('plans only qualified exact-digest images for the native platform',()=>{ - const runtimes=completeRuntimeCatalogFixture('image-provisioning-fixture'),entries=qualifiedCatalogImages(runtimes,scannerCatalog(),target); - expect(entries).toHaveLength(11); - expect(entries.filter(entry=>entry.kind==='runtime')).toHaveLength(5);expect(entries.filter(entry=>entry.kind==='scanner')).toHaveLength(6); - expect(entries.every(entry=>entry.platform===target)).toBe(true); - expect(entries.every(entry=>/^ghcr\.io\/.+@sha256:[a-f0-9]{64}$/.test(entry.image))).toBe(true); - expect(entries.map(entry=>`${entry.kind}:${entry.id}`)).toEqual([...entries.map(entry=>`${entry.kind}:${entry.id}`)].sort()); - }); - - test('doctor inspection is read-only and marks exact absent digests unavailable',async()=>{ - const entries=qualifiedCatalogImages(completeRuntimeCatalogFixture('doctor-inspection-fixture'),scannerCatalog(),target),fake=session({present:()=>false}); - const result=await inspectCatalogImages(entries,async()=>fake.value); - expect(result.docker.status).toBe('ready'); - expect(result.images.every(item=>item.status==='unavailable'&&item.reason?.includes('not present'))).toBe(true); - expect(fake.calls.present).toEqual(entries.map(entry=>entry.image)); - expect(fake.calls.pull).toEqual([]); - expect(fake.closed()).toBe(true); - }); - - test('preload pulls only missing entries and reports failures without disabling static audits',async()=>{ - const entries=qualifiedCatalogImages(completeRuntimeCatalogFixture('setup-provisioning-fixture'),scannerCatalog(),target),present=entries[0],laterPresent=entries.at(-1)!,failed=entries[2],fake=session({ - present:entry=>entry.image===present.image||entry.image===laterPresent.image, - pull:entry=>{if(entry.image===failed.image)throw new CsoError('PREREQUISITE','Public registry is unavailable');}, - }); - const result=await provisionCatalogImages(entries,target,async()=>fake.value); - expect(result).toMatchObject({status:'partial',downloads:true,requested:11,inspected:11,alreadyPresent:2,downloaded:1,deadlineReached:false}); - expect(result.unavailable).toHaveLength(8);expect(result.unavailable[0]).toMatchObject({id:failed.id,status:'unavailable'}); - expect(result.unavailable.at(-1)?.reason).toContain('Network provisioning stopped'); - expect(fake.calls.present).toEqual(entries.map(entry=>entry.image));expect(fake.calls.pull).not.toContain(present.image);expect(fake.calls.pull).not.toContain(laterPresent.image);expect(fake.calls.pull).toHaveLength(2);expect(fake.closed()).toBe(true); - expect(result.summary).toContain('Rerun setup'); - }); - - test('the aggregate deadline still bounds the complete provisioning pass',async()=>{ - const entries=qualifiedCatalogImages(completeRuntimeCatalogFixture('setup-deadline-fixture'),scannerCatalog(),target).slice(0,4),started=Date.now(),deadline=started+100; - let receivedDeadline=0,presentCalls=0,pullCalls=0,closed=false; - const result=await provisionCatalogImages(entries,target,async value=>{receivedDeadline=value;return{docker:{endpoint:'unix:///trusted/docker.sock',version:'27.0.0',security:['seccomp']}, - present:async()=>{presentCalls++;return false;},pull:async()=>{pullCalls++;while(Date.now(){closed=true;}};},deadline); - expect(receivedDeadline).toBe(deadline);expect(Date.now()-started).toBeLessThan(1000); - expect(result).toMatchObject({status:'partial',requested:4,inspected:1,alreadyPresent:0,downloaded:0,deadlineReached:true}); - expect(result.unavailable).toHaveLength(4);expect(result.summary).toContain('bounded aggregate deadline'); - expect(presentCalls).toBe(1);expect(pullCalls).toBe(1);expect(closed).toBe(true); - }); - - test('one per-image timeout does not consume the remaining images allowance',async()=>{ - const entries=qualifiedCatalogImages(completeRuntimeCatalogFixture('setup-per-image-fixture'),scannerCatalog(),target).slice(0,2),pulls:string[]=[]; - const result=await provisionCatalogImages(entries,target,async deadline=>({docker:{endpoint:'unix:///trusted/docker.sock',version:'27.0.0',security:['seccomp']}, - present:async()=>false, - pull:async(entry,imageDeadline=deadline)=>{pulls.push(entry.id);if(entry===entries[0]){while(Date.now(){}, - }),Date.now()+1000,25); - expect(pulls).toEqual(entries.map(entry=>entry.id)); - expect(result).toMatchObject({status:'partial',requested:2,inspected:2,downloaded:1,deadlineReached:false}); - expect(result.unavailable).toEqual([expect.objectContaining({id:entries[0].id,reason:expect.stringContaining('per-image')})]); - expect(result.summary).toContain('GSTACK_CSO_IMAGE_PULL_TIMEOUT_SECONDS'); - }); - - test('a local image check completing after the aggregate deadline cannot be counted',async()=>{ - const entry=qualifiedCatalogImages(completeRuntimeCatalogFixture('setup-late-success-fixture'),scannerCatalog(),target)[0],deadline=Date.now()+25; - let pulls=0,closed=false; - const result=await provisionCatalogImages([entry],target,async()=>({docker:{endpoint:'unix:///trusted/docker.sock',version:'27.0.0',security:['seccomp']}, - present:async()=>{while(Date.now(){pulls++;},close:()=>{closed=true;}}),deadline); - expect(result).toMatchObject({status:'partial',requested:1,inspected:0,alreadyPresent:0,downloaded:0,deadlineReached:true}); - expect(result.unavailable).toEqual([expect.objectContaining({id:entry.id,status:'unavailable',reason:expect.stringContaining('deadline')})]); - expect(pulls).toBe(0);expect(closed).toBe(true); - }); - - test('the production session rejects remote Docker before inspecting or pulling images',async()=>{ - await expect(openLocalCatalogImageSession({HOME:os.tmpdir(),DOCKER_HOST:'tcp://127.0.0.1:2375'})).rejects.toThrow('Remote TCP'); - }); - - test.skipIf(process.platform==='win32')('doctor and setup command contracts share exact local availability without doctor downloads',async()=>{ - const repo=nodeRepo(),runtimeCatalog=completeRuntimeCatalogFixture('doctor-cli-fixture'),scanners=scannerCatalog(),fake=session({present:()=>false}),dependencies:CsoCliDependencies={ - runtimeCatalog,scannerCatalog:scanners,catalogImageSession:async()=>fake.value,watchdogPath:()=>'/trusted/watchdog', - }; - const doctor=await dispatchCsoCommand('doctor',['--repo',repo],dependencies) as any; - expect(doctor.downloads).toBe(false);expect(doctor.elapsedMs).toBeLessThan(30_000); - expect(doctor.checks.find((item:any)=>item.capability==='local-docker-isolation')).toMatchObject({status:'ready'}); - const runtime=doctor.checks.find((item:any)=>item.capability==='qualified-runtimes'); - expect(runtime).toMatchObject({status:'missing',detail:{availability:'unavailable'}});expect(runtime.detail.prerequisite).toContain('not present'); - for(const scanner of SCANNER_IDS)expect(doctor.checks.find((item:any)=>item.capability===`scanner:${scanner}`)).toMatchObject({status:'missing',detail:{availability:'unavailable'}}); - expect(fake.calls.pull).toEqual([]); - - const setupFake=session({present:()=>true}),summary=await dispatchCsoCommand('provision-images',['--setup-summary','--per-image-seconds','5'],{ - ...dependencies,catalogImageSession:async()=>setupFake.value, - }); - expect(summary).toBe('Qualified CSO images ready: 11 available (0 downloaded, 11 already local).'); - expect(setupFake.calls.pull).toEqual([]); - await expect(dispatchCsoCommand('provision-images',['--per-image-seconds','301'],dependencies)).rejects.toThrow('5..300'); - }); - - test.skipIf(process.platform==='win32')('doctor includes the required PostgreSQL sidecar in Rails readiness without pulling',async()=>{ - const repo=railsPostgresRepo(),runtimeCatalog=completeRuntimeCatalogFixture('doctor-rails-postgresql-fixture'),fake=session({present:entry=>!entry.id.includes('postgresql')}),dependencies:CsoCliDependencies={ - runtimeCatalog,scannerCatalog:scannerCatalog(),catalogImageSession:async()=>fake.value,watchdogPath:()=>'/trusted/watchdog', - }; - const doctor=await dispatchCsoCommand('doctor',['--repo',repo],dependencies) as any,runtime=doctor.checks.find((item:any)=>item.capability==='qualified-runtimes'); - expect(doctor.downloads).toBe(false);expect(doctor.checks.find((item:any)=>item.capability==='application-preparation')).toMatchObject({status:'ready'}); - expect(runtime).toMatchObject({status:'missing',detail:{availability:'unavailable',requiredSidecars:[{kind:'postgresql',availability:'unavailable'}]}}); - expect(runtime.detail.requiredSidecars[0].prerequisite).toContain('not present');expect(fake.calls.pull).toEqual([]);expect(fake.closed()).toBe(true); - }); -}); diff --git a/test/cso-json-redaction.test.ts b/test/cso-json-redaction.test.ts deleted file mode 100644 index 330a421cf..000000000 --- a/test/cso-json-redaction.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import { join } from 'node:path'; -import * as dockerModule from '../lib/cso/docker'; -import { DockerGroup } from '../lib/cso/docker'; -import { runProcess } from '../lib/cso/process'; -import { createDockerScannerRunner } from '../lib/cso/scanner-executor'; -import { parseScannerOutput, scannerPlans } from '../lib/cso/scanners'; -import { redactFindingSpans, redactJsonFindingSpans } from '../lib/redact-engine'; - -// #3185: a scanner's JSON report must stay parseable after redaction. A bare -// 10+ digit number (Semgrep's time.max_memory_bytes, an epoch) used to become an -// unquoted marker, JSON.parse failed and /cso reported INVALID_OUTPUT. - -const roots: string[] = []; -const restores: Array<() => void> = []; -afterEach(() => { - for (const restore of restores.splice(0).reverse()) restore(); - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); -const tmp = () => { - const dir = fs.realpathSync(fs.mkdtempSync(join(os.tmpdir(), 'cso-json-redaction-'))); - roots.push(dir); - return dir; -}; -const PHONE = ''; -const json = (input: string) => { - const result = redactJsonFindingSpans(input); - expect(result).not.toBeNull(); - // The released text is a fixpoint: a second scan finds nothing (the views check in lib/cso/process.ts). - expect(redactFindingSpans(result!.body)).toBe(result!.body); - return result!.body; -}; -const semgrepPlan = () => scannerPlans({ snapshotRoot: '/source', offline: true, selected: ['semgrep'], semgrepRules: '/policy/catalog/semgrep.yml' })[0]!; -const SEMGREP_REPORT = { - results: [{ check_id: 'test-rule', path: '/source/app.js', start: { line: 1, col: 1 }, extra: { message: 'Candidate code defect', severity: 'ERROR' } }], - errors: [], paths: { scanned: ['/source/app.js'] }, time: { max_memory_bytes: 1145427776 }, -}; - -describe('redactJsonFindingSpans', () => { - test('a bare number becomes a quoted marker and the document parses', () => { - expect(JSON.parse(json('{"a":4155551234}'))).toEqual({ a: PHONE }); - expect(JSON.parse(json('{"time":{"max_memory_bytes":1145427776}}'))).toEqual({ time: { max_memory_bytes: PHONE } }); - }); - - test('the whole number token is replaced: negative, exponent, every finding id', () => { - expect(JSON.parse(json('{"a":-4155551234}'))).toEqual({ a: PHONE }); - expect(JSON.parse(json('{"x":1e-4155551234}'))).toEqual({ x: PHONE }); - expect(JSON.parse(json('{"when": 1757012345678}'))).toEqual({ when: '' }); - }); - - test('arrays, whitespace, several top-level values and NDJSON', () => { - expect(JSON.parse(json('[4155551234,4155551235]'))).toEqual([PHONE, PHONE]); - expect(JSON.parse(json('{ "a" :\n 4155551234 }'))).toEqual({ a: PHONE }); - expect(json('{"k":1}\n{"k":4155551234}\n{"k":4155551235}\n').trim().split('\n').map(line => JSON.parse(line))) - .toEqual([{ k: 1 }, { k: PHONE }, { k: PHONE }]); - expect(json('{"k":4155551234}{"k":true}')).toBe(`{"k":"${PHONE}"}{"k":true}`); - }); - - test('spans inside strings keep the in-string marker, around punctuation and escaped quotes', () => { - expect(JSON.parse(json('{"t":"call 415-555-1234, ok"}'))).toEqual({ t: `call ${PHONE}, ok` }); - expect(JSON.parse(json('{"t":"x\\"4155551234\\"y"}'))).toEqual({ t: `x"${PHONE}"y` }); - expect(JSON.parse(json('{"t":"4155551234\\n"}'))).toEqual({ t: `${PHONE}\n` }); - }); - - test('a span across several tokens withholds; marker-only findings withhold', () => { - expect(redactFindingSpans('[4111 1111 1111 1111]')).toBe('[]'); - expect(redactJsonFindingSpans('[4111 1111 1111 1111]')).toBeNull(); - expect(redactJsonFindingSpans(['{"k":"-----BEGIN RSA ', 'PRIVATE KEY-----\\nMIIE"}'].join(''))).toBeNull(); - }); - - test('a stream that is not JSON keeps the plain splice', () => { - expect(json('plain 4155551234 text')).toBe(redactFindingSpans('plain 4155551234 text')!); - expect(redactFindingSpans('{"a":4155551234}')).toBe(`{"a":${PHONE}}`); - }); -}); - -describe.skipIf(process.platform === 'win32')('scan stdout through the process boundary', () => { - test('a JSON-declared stdout parses after redaction; stderr and undeclared streams stay plain', async () => { - const dir = tmp(); - const script = `printf '{"time":{"max_memory_bytes":11454'; sleep .05; printf 'peak 4155551234 bytes' >&2; sleep .05; printf '27776}}'`; - const declared = await runProcess('/bin/sh', ['-c', script], { cwd: dir, env: { PATH: '/usr/bin:/bin' }, redaction: 'splice', stdoutFormat: 'json' }); - expect(JSON.parse(declared.stdout)).toEqual({ time: { max_memory_bytes: PHONE } }); - expect(declared.stderr).toBe(`peak ${PHONE} bytes`); - const plain = await runProcess('/bin/sh', ['-c', `printf '{"a":4155551234}'`], { cwd: dir, env: { PATH: '/usr/bin:/bin' }, redaction: 'splice' }); - expect(plain.stdout).toBe(`{"a":${PHONE}}`); - }); - - test('a secret split across channels is still withheld with a JSON-declared stdout', async () => { - const dir = tmp(); - const r = await runProcess('/bin/sh', ['-c', "printf '{\"k\":\"ghp_abcdefghijklmnop'; printf 'qrstuvwxyz1234567890\"}' >&2"], - { cwd: dir, env: { PATH: '/usr/bin:/bin' }, redaction: 'splice', stdoutFormat: 'json' }); - expect(r.stdout + r.stderr).not.toContain('abcdefghijklmnop'); - expect(r.stdout).toBe('[sensitive process output redacted]'); - }); -}); - -describe.skipIf(process.platform === 'win32')('Semgrep through the real executor capture path', () => { - test('version then scan with stderr interleaved: the spliced report is complete', async () => { - const dir = tmp(); - const report = JSON.stringify(SEMGREP_REPORT), cut = report.indexOf('1145427776') + 4; - fs.writeFileSync(join(dir, 'part1'), report.slice(0, cut)); - fs.writeFileSync(join(dir, 'part2'), report.slice(cut)); - const docker = join(dir, 'docker'); - fs.writeFileSync(docker, [ - '#!/bin/sh', - 'for last; do :; done', - `if [ "$last" = --version ]; then printf 'semgrep 1.179.0 (max 4155551234)\\n'; exit 0; fi`, - `cat '${join(dir, 'part1')}'; sleep .05; printf 'Scanning 1 file with 4155551234 bytes\\n' >&2; sleep .05; cat '${join(dir, 'part2')}'`, - ].join('\n') + '\n', { mode: 0o755 }); - const endpoint = { uri: 'unix:///run/fake.sock', socket: '/run/fake.sock', executable: docker, device: 0, inode: 0 }; - const spies = [ - spyOn(dockerModule, 'dockerEndpoint').mockResolvedValue(endpoint), - spyOn(DockerGroup, 'create').mockImplementation(async (_e, runId, groupDir, deadline) => { - const group = new (DockerGroup as any)(endpoint, runId, groupDir, deadline, {}) as DockerGroup; - spyOn(group, 'createContainer').mockResolvedValue('c'.repeat(64)); - spyOn(group, 'start').mockResolvedValue(undefined); - spyOn(group, 'cleanup').mockResolvedValue(undefined); - return group; - }), - ]; - for (const spy of spies) restores.push(() => spy.mockRestore()); - const plan = semgrepPlan(); - const runner = await createDockerScannerRunner({ - input: { id: 'semgrep', runDir: dir, watchdogPath: '/trusted/test-watchdog' } as any, - plan, profile: { image: `ghcr.io/garrytan/gstack/cso-scanners/semgrep-amd64@sha256:${'a'.repeat(64)}`, executable: '/opt/cso/bin/scanner' } as any, - deadline: Date.now() + 60_000, - }); - const version = await runner.version(); - const scan = await runner.scan(); - await runner.cleanup(); - expect(version.stdout).toBe(`semgrep 1.179.0 (max ${PHONE})\n`); - expect(scan.stderr).toBe(`Scanning 1 file with ${PHONE} bytes\n`); - expect(JSON.parse(scan.stdout).time).toEqual({ max_memory_bytes: PHONE }); - const outcome = parseScannerOutput(plan, { ...scan, version: version.stdout }); - expect(outcome.gaps).toEqual([]); - expect(outcome.status).toBe('complete'); - expect(outcome.candidates).toHaveLength(1); - }); -}); diff --git a/test/cso-launcher-generation.test.ts b/test/cso-launcher-generation.test.ts deleted file mode 100644 index 1533d7f91..000000000 --- a/test/cso-launcher-generation.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { createHash } from 'node:crypto'; -import { chmodSync, existsSync, linkSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; -import { spawnSync } from 'node:child_process'; - -const ROOT=resolve(import.meta.dir,'..'),temps:string[]=[]; -afterEach(()=>{for(const dir of temps.splice(0))rmSync(dir,{recursive:true,force:true});}); -function temporary(){const dir=mkdtempSync(join(tmpdir(),'cso-generation-'));temps.push(dir);return dir;} -function digest(path:string){return createHash('sha256').update(readFileSync(path)).digest('hex');} -function compileC(source:string,output:string,args:string[]=[]){const result=spawnSync('/usr/bin/cc',['-std=c11','-D_POSIX_C_SOURCE=200809L','-O2',...args,source,'-o',output],{encoding:'utf8',timeout:30_000});expect(result.status,result.stderr).toBe(0);chmodSync(output,0o755);} -function compileLauncher(directory:string,coreDigest:string,testing=false){const output=join(directory,'gstack-cso-launcher'),args=[`-DGSTACK_CSO_CORE_SHA256=\"${coreDigest}\"`,...(testing?['-DGSTACK_CSO_TESTING']:[])];compileC(join(ROOT,'lib/cso/launcher.c'),output,args);return output;} -async function waitFor(path:string){const deadline=Date.now()+5000;while(!existsSync(path)&&Date.now(){ - test('the launcher rejects changed core bytes even when the generation manifest is unchanged',()=>{ - const directory=temporary(),core=join(directory,'gstack-cso-core'),source=join(directory,'core.c'); - writeFileSync(source,'#include \nint main(void){puts("OLD");return 0;}\n');compileC(source,core);const expected=digest(core),launcher=compileLauncher(directory,expected);writeFileSync(join(directory,'.gstack-cso-generation'),`${expected}\n`); - writeFileSync(source,'#include \nint main(void){puts("CHANGED");return 0;}\n');compileC(source,core); - const result=spawnSync(launcher,[],{cwd:directory,encoding:'utf8',timeout:5000});expect(result.status).toBe(69);expect(result.stdout).not.toContain('CHANGED');expect(result.stderr).toContain('digest does not match'); - }); - - test('the launcher rejects a multiply-linked core before execution',()=>{ - const directory=temporary(),core=join(directory,'gstack-cso-core'),source=join(directory,'core.c'); - writeFileSync(source,'#include \nint main(void){puts("UNSAFE");return 0;}\n');compileC(source,core);const expected=digest(core),launcher=compileLauncher(directory,expected);writeFileSync(join(directory,'.gstack-cso-generation'),`${expected}\n`);linkSync(core,join(directory,'core-alias')); - const result=spawnSync(launcher,[],{cwd:directory,encoding:'utf8',timeout:5000});expect(result.status).toBe(69);expect(result.stdout).not.toContain('UNSAFE');expect(result.stderr).toContain('trusted compiled helper is missing'); - }); - - test.skipIf(process.platform!=='linux')('the launcher executes the verified descriptor across a noncooperative pathname swap',async()=>{ - const directory=temporary(),core=join(directory,'gstack-cso-core'),source=join(directory,'core.c'),ready=join(directory,'ready'),release=join(directory,'release'); - writeFileSync(source,'#include \nint main(void){puts("VERIFIED");return 0;}\n');compileC(source,core);const expected=digest(core),launcher=compileLauncher(directory,expected,true);writeFileSync(join(directory,'.gstack-cso-generation'),`${expected}\n`); - const running=Bun.spawn([launcher,'__cso-test-pause-after-core-verification',ready,release],{cwd:directory,stdout:'pipe',stderr:'pipe'});await waitFor(ready); - const replacement=join(directory,'replacement-core');writeFileSync(source,'#include \nint main(void){puts("SWAPPED");return 0;}\n');compileC(source,replacement);renameSync(replacement,core);writeFileSync(release,'go'); - const stdout=await new Response(running.stdout).text(),stderr=await new Response(running.stderr).text();expect(await running.exited,stderr).toBe(0);expect(stdout.trim()).toBe('VERIFIED');expect(stdout).not.toContain('SWAPPED'); - }); - - test('an already-loaded old launcher rejects the publisher-winning core generation',async()=>{ - const directory=temporary(),core=join(directory,'gstack-cso-core'),source=join(directory,'core.c'),ready=join(directory,'ready'),release=join(directory,'release'); - writeFileSync(source,'#include \nint main(void){puts("OLD");return 0;}\n');compileC(source,core);const oldDigest=digest(core),launcher=compileLauncher(directory,oldDigest,true);writeFileSync(join(directory,'.gstack-cso-generation'),`${oldDigest}\n`); - const running=Bun.spawn([launcher,'__cso-test-pause-before-generation-lock',ready,release],{cwd:directory,stdout:'pipe',stderr:'pipe'});await waitFor(ready); - const next=join(directory,'next-core');writeFileSync(source,'#include \nint main(void){puts("NEW");return 0;}\n');compileC(source,next);const nextDigest=digest(next),manifest=join(directory,'next-generation');writeFileSync(manifest,`${nextDigest}\n`);renameSync(next,core);renameSync(manifest,join(directory,'.gstack-cso-generation'));writeFileSync(release,'go'); - const stdout=await new Response(running.stdout).text(),stderr=await new Response(running.stderr).text();expect(await running.exited).toBe(69);expect(stdout).not.toContain('NEW');expect(stderr).toContain('generations do not match'); - }); - - test('Bun retains the shared generation lock while the core runs and drops it before detached children',async()=>{ - const directory=temporary(),source=join(directory,'core.ts'),core=join(directory,'gstack-cso-core'),launcher=join(directory,'gstack-cso-launcher'),locker=join(directory,'gstack-cso-publish-lock'),ready=join(directory,'ready'),release=join(directory,'release'),childReady=join(directory,'child-ready'),childRelease=join(directory,'child-release'),published=join(directory,'published'); - writeFileSync(source,`import{fstatSync,writeFileSync,existsSync}from'node:fs';const fd=Number(process.env.GSTACK_CSO_GENERATION_LOCK_FD);if(!Number.isInteger(fd)||!fstatSync(fd).isDirectory())process.exit(71);writeFileSync(${JSON.stringify(ready)},'ready');while(!existsSync(${JSON.stringify(release)}))await Bun.sleep(5);const child=Bun.spawn(['/bin/sh','-c',${JSON.stringify(`touch '${childReady}'; while [ ! -f '${childRelease}' ]; do sleep .01; done`)}],{stdin:'ignore',stdout:'ignore',stderr:'ignore'});child.unref();`); - const built=spawnSync(process.execPath,['build','--compile','--no-compile-autoload-dotenv','--no-compile-autoload-bunfig','--no-compile-autoload-tsconfig','--no-compile-autoload-package-json',source,'--outfile',core],{encoding:'utf8',timeout:60_000});expect(built.status,built.stderr).toBe(0);const coreDigest=digest(core);compileLauncher(directory,coreDigest);writeFileSync(join(directory,'.gstack-cso-generation'),`${coreDigest}\n`);compileC(join(ROOT,'lib/cso/publish-lock.c'),locker); - const running=Bun.spawn([launcher],{cwd:directory,stdout:'pipe',stderr:'pipe'});await waitFor(ready);const blocked=spawnSync(locker,[directory,'/bin/sh','-c',`touch '${published}'`],{encoding:'utf8',timeout:5000});expect(blocked.status).toBe(73);expect(existsSync(published)).toBe(false); - writeFileSync(release,'go');expect(await running.exited).toBe(0);await waitFor(childReady);const admitted=spawnSync(locker,[directory,'/bin/sh','-c',`touch '${published}'`],{encoding:'utf8',timeout:5000});expect(admitted.status,admitted.stderr).toBe(0);expect(existsSync(published)).toBe(true);writeFileSync(childRelease,'go'); - },70_000); -}); diff --git a/test/cso-lease-identity.test.ts b/test/cso-lease-identity.test.ts deleted file mode 100644 index 094406401..000000000 --- a/test/cso-lease-identity.test.ts +++ /dev/null @@ -1,332 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { privateRoot, recoverAtomicNoReplaceJson, retention, withLock } from '../lib/cso/state'; -import { darwinIdentityFromBsdInfo, identityStartedAtMs, PROCESS_IDENTITY, processIdentitySource } from '../lib/cso/process-identity'; -import { dispatchCsoCommand } from '../lib/cso/cli'; -import { RUNTIME_CATALOG } from '../lib/cso/runtime-catalog'; - -const roots:string[]=[]; -const tmp=()=>{const root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-lease-identity-'));roots.push(root);return root;}; -afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); - -function syntheticIds(root:string,first:bigint,step=1n):()=>void{ - const lstat=fs.lstatSync.bind(fs),fstat=fs.fstatSync.bind(fs),ids=new Map(); - const map=(stat:fs.Stats|fs.BigIntStats,bigint:boolean)=>{ - const key=`${stat.dev}:${stat.ino}`; - if(!ids.has(key))return stat; - const ino=ids.get(key)!; - return Object.assign(Object.create(Object.getPrototypeOf(stat)),stat,{dev:bigint?first:Number(first),ino:bigint?ino:Number(ino)}); - }; - const pathSpy=spyOn(fs,'lstatSync').mockImplementation(((file:any,options?:any)=>{ - const stat=lstat(file,options); - if(String(file).startsWith(root+path.sep)){ - const key=`${stat.dev}:${stat.ino}`; - if(!ids.has(key))ids.set(key,first+step*BigInt(ids.size)); - } - return map(stat,options?.bigint===true); - }) as typeof fs.lstatSync); - const fdSpy=spyOn(fs,'fstatSync').mockImplementation(((fd:any,options?:any)=>map(fstat(fd,options),options?.bigint===true)) as typeof fs.fstatSync); - return()=>{fdSpy.mockRestore();pathSpy.mockRestore();}; -} - -function leaseFixture(dir:string,ownerPid:number,token:string){ - withLock(dir,()=>0); - const leases=path.join(dir,'.mutation-lock-leases'),candidate=path.join(leases,`${token}.json`),decision=path.join(leases,`${token}.decision`); - fs.writeFileSync(candidate,JSON.stringify({pid:ownerPid,token,createdAt:0})+'\n',{mode:0o600}); - const stat=fs.lstatSync(candidate,{bigint:true}); - fs.writeFileSync(decision,JSON.stringify({schemaVersion:1,token,kind:'ticket',ticket:'0000000000000001',candidateDev:String(stat.dev),candidateIno:String(stat.ino),ownerPid,ownerCreatedAt:0,publisherPid:ownerPid,createdAt:0})+'\n',{mode:0o600}); - return {leases,candidate,decision,stat}; -} - -describe('CSO exact filesystem lease identity',()=>{ - test('the last safe integer and its next inode remain distinct',()=>{ - const dir=tmp(),restore=syntheticIds(dir,9007199254740991n); - try{ - const first=path.join(dir,'first'),second=path.join(dir,'second'); - fs.writeFileSync(first,'a');fs.writeFileSync(second,'b'); - expect(fs.lstatSync(first,{bigint:true}).ino).toBe(9007199254740991n); - expect(fs.lstatSync(second,{bigint:true}).ino).toBe(9007199254740992n); - expect(withLock(dir,()=>1)).toBe(1); - }finally{restore();} - }); - - test.each([9007199254740991n,9007199254740992n,9007199254740993n])('serializes and releases identity starting at %s across consecutive mutations',(first)=>{ - const dir=tmp(),restore=syntheticIds(dir,first); - try{ - for(let i=0;i<4;i++)expect(withLock(dir,()=>{ - const leases=path.join(dir,'.mutation-lock-leases'),files=fs.readdirSync(leases); - const candidate=path.join(leases,files.find(name=>name.endsWith('.json'))!),decision=path.join(leases,files.find(name=>name.endsWith('.decision'))!),record=JSON.parse(fs.readFileSync(decision,'utf8')); - expect(record.candidateDev).toBe(String(fs.lstatSync(candidate,{bigint:true}).dev)); - expect(record.candidateIno).toBe(String(fs.lstatSync(candidate,{bigint:true}).ino)); - expect(BigInt(record.candidateIno)).toBeGreaterThanOrEqual(first); - return i; - })).toBe(i); - expect(fs.readdirSync(path.join(dir,'.mutation-lock-leases'))).toEqual([]); - }finally{restore();} - }); - - test('recovers a dead owner and its exact high-ID decision, then admits the next operation',()=>{ - const dir=tmp(),restore=syntheticIds(dir,9007199254740992n); - try{ - const {leases,candidate,decision}=leaseFixture(dir,2147483647,'a'.repeat(32)); - expect(withLock(dir,()=>1)).toBe(1); - expect(fs.existsSync(candidate)).toBe(false);expect(fs.existsSync(decision)).toBe(false); - expect(withLock(dir,()=>2)).toBe(2);expect(fs.readdirSync(leases)).toEqual([]); - }finally{restore();} - }); - - test('a decision left after exact candidate removal keeps its high ID until recovery',()=>{ - const dir=tmp(),restore=syntheticIds(dir,9007199254740992n); - try{ - const {leases,candidate,decision,stat}=leaseFixture(dir,2147483647,'e'.repeat(32)); - expect(JSON.parse(fs.readFileSync(decision,'utf8')).candidateIno).toBe(String(stat.ino)); - fs.unlinkSync(candidate); - expect(withLock(dir,()=>3)).toBe(3); - expect(fs.readdirSync(leases)).toEqual([]); - }finally{restore();} - }); - - test('a live foreign lease is not stolen, even when its timestamp is old',()=>{ - const dir=tmp(),restore=syntheticIds(dir,9007199254740992n); - try{ - const {candidate,decision}=leaseFixture(dir,process.pid,'b'.repeat(32)); - expect(()=>withLock(dir,()=>1)).toThrow('Another operation in this helper'); - expect(fs.existsSync(candidate)).toBe(true);expect(fs.existsSync(decision)).toBe(true); - }finally{restore();} - }); - - test('a legacy rounded high-ID decision is ambiguous and remains blocked',()=>{ - const dir=tmp(),restore=syntheticIds(dir,9007199254740993n,2n); - try{ - const token='c'.repeat(32),{candidate,decision,stat}=leaseFixture(dir,2147483647,token); - expect(stat.ino%2n).toBe(1n); - const record=JSON.parse(fs.readFileSync(decision,'utf8')); - record.candidateIno=String(Number(stat.ino)); - fs.writeFileSync(decision,JSON.stringify(record)+'\n',{mode:0o600}); - expect(record.candidateIno).not.toBe(String(stat.ino)); - let failure:unknown;try{withLock(dir,()=>1);}catch(error){failure=error;} - expect(failure).toMatchObject({code:'UNSAFE_PATH'}); - expect(fs.existsSync(candidate)).toBe(true);expect(fs.existsSync(decision)).toBe(true); - }finally{restore();} - }); - - test('a neighboring replacement inode is rejected during exact release',()=>{ - const dir=tmp(),restore=syntheticIds(dir,9007199254740992n); - try{ - let replaced=''; - let failure:unknown;try{withLock(dir,()=>{ - const leases=path.join(dir,'.mutation-lock-leases'),active=fs.readdirSync(leases).find(name=>name.includes('.active.'))!; - replaced=path.join(leases,active);const bytes=fs.readFileSync(replaced); - fs.renameSync(replaced,`${replaced}.original`);fs.writeFileSync(replaced,bytes,{mode:0o600}); - });}catch(error){failure=error;} - expect(failure).toMatchObject({code:'PERSISTENCE_FAILED'}); - expect(fs.existsSync(replaced)).toBe(true); - }finally{restore();} - }); - - test.skipIf(process.platform==='win32')('a symlink substituted for a dead owner is never reclaimed',()=>{ - const dir=tmp(),restore=syntheticIds(dir,9007199254740992n); - try{ - const {candidate,decision}=leaseFixture(dir,2147483647,'f'.repeat(32)),original=`${candidate}.original`; - fs.renameSync(candidate,original);fs.symlinkSync(original,candidate); - let failure:unknown;try{withLock(dir,()=>1);}catch(error){failure=error;} - expect(failure).toMatchObject({code:'UNSAFE_PATH'}); - expect(fs.lstatSync(candidate).isSymbolicLink()).toBe(true); - expect(fs.existsSync(decision)).toBe(true); - }finally{restore();} - }); - - test('atomic recovery matches only the exact high-ID hard-link publication',()=>{ - const dir=tmp(),restore=syntheticIds(dir,9007199254740992n); - try{ - const target=path.join(dir,'artifact.json'),temporary=`${target}.tmp.2147483647.deadbeef`; - fs.writeFileSync(temporary,'{"value":"retained"}\n',{mode:0o600});fs.linkSync(temporary,target); - recoverAtomicNoReplaceJson(target,{label:'Synthetic publication',maxBytes:4096}); - expect(fs.existsSync(temporary)).toBe(false);expect(JSON.parse(fs.readFileSync(target,'utf8'))).toEqual({value:'retained'}); - }finally{restore();} - }); - - test('adjacent IDs that round to the same Number cannot impersonate a publication',()=>{ - const dir=tmp(),restore=syntheticIds(dir,9007199254740992n); - try{ - const target=path.join(dir,'artifact.json'),temporary=`${target}.tmp.2147483647.deadbeef`,time=new Date(1_700_000_000_000); - fs.writeFileSync(target,'{"value":"retained"}\n',{mode:0o600}); - fs.writeFileSync(temporary,'{"value":"retained"}\n',{mode:0o600}); - fs.utimesSync(target,time,time);fs.utimesSync(temporary,time,time); - fs.linkSync(target,path.join(dir,'other'));fs.linkSync(temporary,path.join(dir,'another')); - const original=fs.lstatSync(target,{bigint:true}),foreign=fs.lstatSync(temporary,{bigint:true}); - expect(foreign.ino-original.ino).toBe(1n); - expect(Number(foreign.ino)).toBe(Number(original.ino)); - let failure:unknown;try{recoverAtomicNoReplaceJson(target,{label:'Synthetic publication',maxBytes:4096});}catch(error){failure=error;} - expect(failure).toMatchObject({code:'UNSAFE_PATH'}); - expect(fs.existsSync(temporary)).toBe(true); - expect(fs.readFileSync(target,'utf8')).toBe('{"value":"retained"}\n'); - }finally{restore();} - }); - - test('atomic recovery rejects a same-millisecond timestamp change while the file is opened',()=>{ - const dir=tmp(),target=path.join(dir,'artifact.json'),temporary=`${target}.tmp.2147483647.deadbeef`,fstat=fs.fstatSync; - fs.writeFileSync(temporary,'{"value":"retained"}\n',{mode:0o600});fs.linkSync(temporary,target); - fs.utimesSync(target,1_700_000_000.0001,1_700_000_000.0001); - let injected=false,failure:unknown; - const reader=spyOn(fs,'fstatSync').mockImplementation(((fd:any,options?:any)=>{ - const stat=fstat(fd,options); - if(injected||options?.bigint!==true)return stat; - injected=true; - return Object.assign(Object.create(Object.getPrototypeOf(stat)),stat,{mtimeNs:stat.mtimeMs*1_000_000n+600_000n}); - }) as typeof fs.fstatSync); - try{recoverAtomicNoReplaceJson(target,{label:'Synthetic publication',maxBytes:4096});}catch(error){failure=error;}finally{reader.mockRestore();} - expect(injected).toBe(true); - expect(failure).toMatchObject({code:'SNAPSHOT_RACE'}); - expect(fs.existsSync(temporary)).toBe(true); - }); -}); - -const FILETIME_UNIX_EPOCH=116444736000000000n; -const win32Identity=(ms:number)=>`win32:${BigInt(ms)*10000n+FILETIME_UNIX_EPOCH}`; -type OwnerRecord={pid:number;token:string;createdAt:number;processIdentity?:string}; -function ownedLease(dir:string,owner:OwnerRecord,active=false){ - withLock(dir,()=>0); - const leases=path.join(dir,'.mutation-lock-leases'),candidate=path.join(leases,`${owner.token}.json`),decision=path.join(leases,`${owner.token}.decision`),activePath=path.join(leases,`${owner.token}.active.0000000000000001`); - fs.writeFileSync(candidate,JSON.stringify(owner)+'\n',{mode:0o600}); - const stat=fs.lstatSync(candidate,{bigint:true}); - fs.writeFileSync(decision,JSON.stringify({schemaVersion:1,token:owner.token,kind:'ticket',ticket:'0000000000000001',candidateDev:String(stat.dev),candidateIno:String(stat.ino),ownerPid:owner.pid,...(owner.processIdentity?{ownerProcessIdentity:owner.processIdentity}:{}),ownerCreatedAt:owner.createdAt,publisherPid:owner.pid,...(owner.processIdentity?{publisherProcessIdentity:owner.processIdentity}:{}),createdAt:owner.createdAt})+'\n',{mode:0o600}); - if(active)fs.linkSync(candidate,activePath); - return {leases,records:[candidate,decision,...(active?[activePath]:[])]}; -} -function withHolder(fn:(pid:number)=>T):T{ - const holder=Bun.spawn([process.execPath,'-e','setTimeout(()=>{},60000)'],{stdio:['ignore','ignore','ignore']}); - try{return fn(holder.pid);}finally{holder.kill();} -} -function identityAs(pid:number,identity:string|undefined){ - const original=processIdentitySource.read.bind(processIdentitySource); - return spyOn(processIdentitySource,'read').mockImplementation((value:number)=>value===pid?identity:original(value)); -} -function failureOf(fn:()=>unknown):any{try{fn();}catch(error){return error;}return undefined;} - -describe('#2894 lease owner identity and stale-lease recovery',()=>{ - function unverifiableOtherRun(){ - const other=path.join(privateRoot(),'b'.repeat(24),`${Date.now()}-${'1'.repeat(16)}`);fs.mkdirSync(other,{recursive:true,mode:0o700}); - const {records}=ownedLease(other,{pid:2147483647,token:'c'.repeat(32),createdAt:1}); - const decision=JSON.parse(fs.readFileSync(records[1],'utf8'));decision.candidateIno=String(BigInt(decision.candidateIno)+1n); - fs.writeFileSync(records[1],JSON.stringify(decision)+'\n',{mode:0o600}); - return {other,records}; - } - function expectStillBlocked(other:string,records:string[]){ - const blocked=failureOf(()=>withLock(other,()=>1)); - expect(blocked).toMatchObject({code:'UNSAFE_PATH'}); - expect(blocked.message).toContain('does not match its candidate owner'); - expect(blocked.message).toContain('Next: start a new run'); - expect(blocked.message).not.toMatch(/delete|remove the lock/i); - for(const record of records)expect(fs.existsSync(record)).toBe(true); - } - function isolatedState(fn:(base:string)=>T):T{ - const previous=process.env.GSTACK_HOME,base=tmp();process.env.GSTACK_HOME=path.join(base,'state'); - const restore=()=>{if(previous===undefined)delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME=previous;}; - try{const value=fn(base);if(value instanceof Promise)return value.finally(restore) as T;restore();return value;}catch(error){restore();throw error;} - } - - test('maintenance skips another run whose lease decision cannot be verified and leaves it blocked',()=>isolatedState(()=>{ - const {other,records}=unverifiableOtherRun(); - expect(retention(Date.now()).complete).toBe(true); - expectStillBlocked(other,records); - })); - - test.skipIf(process.platform==='win32')('start is not blocked by another repository run whose lease decision cannot be verified',()=>isolatedState(async base=>{ - const repo=path.join(base,'repo');fs.mkdirSync(repo); - for(const args of [['init','-q'],['config','user.email','fixture@example.test'],['config','user.name','Fixture']])expect(spawnSync('git',args,{cwd:repo,timeout:10_000}).status).toBe(0); - fs.writeFileSync(path.join(repo,'app.js'),'console.log("fixture")\n'); - for(const args of [['add','app.js'],['commit','-qm','fixture']])expect(spawnSync('git',args,{cwd:repo,timeout:10_000}).status).toBe(0); - const {other,records}=unverifiableOtherRun(); - const started=await dispatchCsoCommand('start',['--repo',repo,'--offline'],{runtimeCatalog:RUNTIME_CATALOG,catalogImageSession:async()=>{throw new Error('unused');},watchdogPath:()=>'/unused'} as any) as any; - expect(started.status).toBe('running'); - expectStillBlocked(other,records); - }),30_000); - - test('identity decoding: Windows FILETIME and macOS proc_bsdinfo start times',()=>{ - expect(identityStartedAtMs(win32Identity(1_700_000_000_123))).toBe(1_700_000_000_123); - expect(identityStartedAtMs(`win32:${FILETIME_UNIX_EPOCH}`)).toBe(0); - expect(identityStartedAtMs('darwin:1700000000123456')).toBe(1_700_000_000_123); - expect(identityStartedAtMs('linux:123456')).toBeUndefined(); - const info=new Uint8Array(136),view=new DataView(info.buffer); - view.setUint32(12,4242,true);view.setBigUint64(120,1_700_000_000n,true);view.setBigUint64(128,123_456n,true); - expect(darwinIdentityFromBsdInfo(info,4242)).toBe('darwin:1700000000123456'); - expect(darwinIdentityFromBsdInfo(info,4243)).toBeUndefined(); - expect(darwinIdentityFromBsdInfo(info.subarray(0,135),4242)).toBeUndefined(); - for(const value of ['linux:1','win32:133000000000000000','darwin:1700000000123456'])expect(PROCESS_IDENTITY.test(value)).toBe(true); - for(const value of ['win32:','macos:1','win32:-1','linux:1 '])expect(PROCESS_IDENTITY.test(value)).toBe(false); - }); - - test.skipIf(!['linux','darwin','win32'].includes(process.platform))('the live identity source distinguishes this process from a child',()=>{ - const own=processIdentitySource.read(process.pid); - expect(own).toMatch(PROCESS_IDENTITY);expect(processIdentitySource.read(process.pid)).toBe(own!); - withHolder(pid=>{const child=processIdentitySource.read(pid);expect(child).toMatch(PROCESS_IDENTITY);expect(child).not.toBe(own!);}); - }); - - test('a recycled PID on Windows or macOS (holder started after the record) is reclaimed',()=>withHolder(pid=>{ - const dir=tmp(),createdAt=Date.now()-60_000,{leases,records}=ownedLease(dir,{pid,token:'a'.repeat(32),createdAt}); - for(const identity of [win32Identity(Date.now()-1_000),`darwin:${BigInt(Date.now()-1_000)*1000n}`]){ - const spy=identityAs(pid,identity); - try{expect(withLock(dir,()=>7)).toBe(7);}finally{spy.mockRestore();} - for(const record of records)expect(fs.existsSync(record)).toBe(false); - expect(fs.readdirSync(leases)).toEqual([]); - ownedLease(dir,{pid,token:'a'.repeat(32),createdAt}); - } - })); - - test('a holder that started before the record, or a record with no creation time, is never stolen',()=>withHolder(pid=>{ - for(const [createdAt,started] of [[Date.now()-1_000,Date.now()-60_000],[0,Date.now()-1_000]]){ - const dir=tmp(),{records}=ownedLease(dir,{pid,token:'b'.repeat(32),createdAt},true),spy=identityAs(pid,win32Identity(started)); - let failure:any;try{failure=failureOf(()=>withLock(dir,()=>1));}finally{spy.mockRestore();} - expect(failure).toMatchObject({code:'INSUFFICIENT_CAPACITY'}); - expect(failure.message).toContain(`process ${pid} is running and the lease record predates process identity`); - for(const record of records)expect(fs.existsSync(record)).toBe(true); - } - })); - - test('an unknown identity stays conservative and names the owner pid with a safe next step',()=>withHolder(pid=>{ - const dir=tmp(),{records}=ownedLease(dir,{pid,token:'d'.repeat(32),createdAt:Date.now(),processIdentity:win32Identity(Date.now()-5_000)},true),spy=identityAs(pid,undefined); - let failure:any;try{failure=failureOf(()=>withLock(dir,()=>1));}finally{spy.mockRestore();} - expect(failure).toMatchObject({code:'INSUFFICIENT_CAPACITY'}); - expect(failure.message).toContain('Another helper is updating this run'); - expect(failure.message).toContain(`process ${pid} is running; process identity unavailable`); - expect(failure.message).toContain('Status: blocked; this command changed nothing'); - expect(failure.message).toContain('wait for that session to finish or check the owning session'); - expect(failure.message).not.toMatch(/delete|remove the lock/i); - for(const record of records)expect(fs.existsSync(record)).toBe(true); - })); - - // A second helper process runs while this one is suspended at one point of its - // reclaim. Whatever the interleaving, exactly one helper acquires the lease and - // the recycled-PID records are consumed once. - const contender=(dir:string,script:string)=>{ - const result=spawnSync(process.execPath,[script,dir],{encoding:'utf8',timeout:30_000}); - expect(result.status).toBe(0);return JSON.parse(result.stdout.trim()); - }; - test.skipIf(process.platform!=='linux').each([ - ['while the first helper is reclaiming','unlinkSync','.json','second'], - ['after the first helper holds its ticket','linkSync','.active.','first'], - ] as const)('two helpers racing for a recycled-PID lease: %s',(_name,hook,marker,winner)=>withHolder(pid=>{ - const dir=tmp(),script=path.join(dir,'..',`${path.basename(dir)}-contender.ts`);roots.push(script); - fs.writeFileSync(script,`import {withLock} from ${JSON.stringify(path.resolve(import.meta.dir,'../lib/cso/state'))}; -try{withLock(process.argv[2],()=>0);console.log(JSON.stringify({won:true}));}catch(error:any){console.log(JSON.stringify({won:false,code:error?.code,message:error?.message}));}`); - const {leases,records}=ownedLease(dir,{pid,token:'e'.repeat(32),createdAt:Date.now(),processIdentity:'linux:1'}); - const original=(fs as any)[hook].bind(fs);let second:any; - const spy=spyOn(fs as any,hook).mockImplementation((...args:any[])=>{ - const target=String(args[hook==='linkSync'?1:0]); - if(!second&&target.includes(marker)&&(hook==='linkSync'||target===records[0]))second=contender(dir,script); - return original(...args); - }); - let first:any; - try{try{first={won:withLock(dir,()=>true)};}catch(error:any){first={won:false,code:error?.code,message:error?.message};}}finally{spy.mockRestore();} - expect(second).toBeDefined(); - expect([first.won,second.won].filter(Boolean)).toHaveLength(1); - expect(winner==='first'?first.won:second.won).toBe(true); - expect((winner==='first'?second:first).code).toBe('INSUFFICIENT_CAPACITY'); - for(const record of records)expect(fs.existsSync(record)).toBe(false); - expect(fs.readdirSync(leases)).toEqual([]); - })); -}); diff --git a/test/cso-macos-launcher.test.ts b/test/cso-macos-launcher.test.ts deleted file mode 100644 index 289a8eeae..000000000 --- a/test/cso-macos-launcher.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawn, spawnSync } from 'node:child_process'; -import { identityStartedAtMs, processIdentitySource } from '../lib/cso/process-identity'; - -const ROOT = path.resolve(import.meta.dir, '..'); -const macos = process.platform === 'darwin'; -const required = process.env.GSTACK_CSO_MACOS_TESTS === '1'; -if (required && !macos) throw new Error('GSTACK_CSO_MACOS_TESTS=1 requires native macOS; emulation does not qualify the launcher.'); -let temporary = '', marker = '', library = ''; - -beforeAll(() => { - if (!macos) return; - temporary = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'gstack-cso-macos-')); - marker = path.join(temporary, 'dyld-constructor-ran'); - library = path.join(temporary, 'hostile.dylib'); - const source = path.join(temporary, 'hostile.c'); - fs.writeFileSync(source, '#include \n#include \n#include \n__attribute__((constructor)) static void mark(void){const char*p=getenv("CSO_PRELOAD_MARKER");if(p){int f=open(p,O_WRONLY|O_CREAT,0600);if(f>=0)close(f);}}\n'); - const built = spawnSync('/usr/bin/clang', ['-dynamiclib', source, '-o', library], { encoding: 'utf8', timeout: 30_000 }); - expect(built.status).toBe(0); -}, 40_000); - -afterAll(() => { if (temporary) fs.rmSync(temporary, { recursive: true, force: true }); }); - -describe('CSO native macOS build contract', () => { - test('macOS CI runs native signature and injection checks', () => { - const workflow = Bun.YAML.parse(fs.readFileSync(path.join(ROOT, '.github/workflows/free-tests.yml'), 'utf8')) as any; - const build = fs.readFileSync(path.join(ROOT, 'scripts/build-cso.sh'), 'utf8'); - const job = workflow.jobs['cso-macos-launcher']; - expect(job['runs-on']).toBe('macos-latest'); - expect(job.steps.some((step: any) => step.run === 'bun run build:cso')).toBe(true); - const gate = job.steps.find((step: any) => step.run === 'bun run test:cso:macos'); - expect(gate.env.GSTACK_CSO_MACOS_TESTS).toBe('1'); - expect(gate['continue-on-error']).not.toBe(true); - expect(build).toContain('-Wl,-sectcreate,__RESTRICT,__restrict,/dev/null'); - }); -}); - -(macos ? describe : describe.skip)('CSO native macOS startup', () => { - test('#2894 the darwin process identity source reads real process start times', async () => { - const own = processIdentitySource.read(process.pid), started = identityStartedAtMs(own ?? ''); - expect(own).toMatch(/^darwin:\d+$/); - expect(processIdentitySource.read(process.pid)).toBe(own!); - expect(started!).toBeLessThanOrEqual(Date.now()); - expect(started!).toBeGreaterThan(Date.now() - 3_600_000); - await Bun.sleep(20); - const child = spawn(process.execPath, ['-e', 'setTimeout(()=>{},30000)'], { stdio: 'ignore' }); - try { - const identity = processIdentitySource.read(child.pid!); - expect(identity).toMatch(/^darwin:\d+$/); - expect(identity).not.toBe(own!); - expect(identityStartedAtMs(identity!)!).toBeGreaterThanOrEqual(started!); - } finally { child.kill(); } - expect(processIdentitySource.read(2147483647)).toBeUndefined(); - }); - - test('the public launcher has a valid hardened-runtime signature', () => { - const launcher = path.join(ROOT, 'bin', 'gstack-cso-launcher'); - const verified = spawnSync('/usr/bin/codesign', ['--verify', '--strict', launcher], { encoding: 'utf8', timeout: 30_000 }); - expect(verified.status).toBe(0); - const details = spawnSync('/usr/bin/codesign', ['-d', '--verbose=4', launcher], { encoding: 'utf8', timeout: 30_000 }); - expect(details.status).toBe(0); - expect(details.stderr).toMatch(/flags=.*runtime/); - const layout = spawnSync('/usr/bin/otool', ['-l', launcher], { encoding: 'utf8', timeout: 30_000 }); - expect(layout.status).toBe(0); - expect(layout.stdout).toMatch(/sectname __restrict\s+segname __RESTRICT/); - }); - - test('DYLD constructor injection cannot run before the launcher scrubs the environment', () => { - const launcher = path.join(ROOT, 'bin', 'gstack-cso-launcher'); - const result = spawnSync(launcher, ['--version'], { - cwd: temporary, - encoding: 'utf8', - timeout: 30_000, - env: { ...process.env, HOME: temporary, GSTACK_HOME: path.join(temporary, 'state'), DYLD_INSERT_LIBRARIES: library, CSO_PRELOAD_MARKER: marker }, - }); - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout)).toEqual({ version: '3.0.0', abi: 3 }); - expect(fs.existsSync(marker)).toBe(false); - }); -}); diff --git a/test/cso-native-evidence.test.ts b/test/cso-native-evidence.test.ts deleted file mode 100644 index 721e9db3b..000000000 --- a/test/cso-native-evidence.test.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { spawnSync } from 'node:child_process'; -import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; -import { deriveNativeChecks, nativeEvidence, nativeTestRequirements, parseJUnit, type JUnitCase } from '../scripts/cso-native-evidence'; -import { requiredChecks } from '../scripts/cso-runtime-promotion'; - -const ROOT = resolve(import.meta.dir, '..'); -const STACKS = ['node', 'bun', 'python', 'rails', 'postgresql'] as const; -const temps: string[] = []; -afterEach(() => { for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true }); }); - -const escape = (value: string) => value.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>').replaceAll('"', '"'); - -// Mirrors Bun 1.4.0 `bun test --reporter=junit` output: passing cases self-close, skips and failures carry a child element. -function report(cases: JUnitCase[]): string { - const body = cases.map(item => { - const open = ``; - const child = item.status === 'skipped' ? '' : 'AssertionError'; - return ` ${open}>\n ${child}\n `; - }).join('\n'); - const failures = cases.filter(item => item.status === 'failed').length; - return `\n\n \n${body}\n \n\n`; -} - -function passing(stack: typeof STACKS[number]): JUnitCase[] { - const seen = new Map(); - for (const refs of Object.values(nativeTestRequirements(stack))) for (const ref of refs) seen.set(`${ref.file}\0${ref.name}`, { ...ref, status: 'passed', assertions: 3 }); - return [...seen.values()]; -} - -function staged(stack: string, platform = 'linux/amd64') { - return { schemaVersion: 1, state: 'staged', stack, platform, image: `ghcr.io/garrytan/gstack/cso-staging/${stack}-amd64@sha256:${'a'.repeat(64)}` }; -} - -describe('CSO native gate evidence', () => { - test('native check keys are release gates of their stack, and private checks are exactly the remainder', () => { - for (const stack of STACKS) { - const native = Object.keys(nativeTestRequirements(stack)); - expect(native.every(key => requiredChecks(stack).includes(key))).toBe(true); - const evidence = nativeEvidence(staged(stack), stack, 'linux/amd64', report(passing(stack))) as any; - expect(Object.values(evidence.nativeChecks).every(value => value === true)).toBe(true); - expect(Object.keys(evidence.privateChecks).sort()).toEqual(requiredChecks(stack).filter(key => !native.includes(key))); - expect(Object.values(evidence.privateChecks).every(value => value === 'pending')).toBe(true); - expect(evidence).toMatchObject({ state: 'native-gates-passed', qualified: false, stack }); - expect(evidence.nativeTestReport).toMatch(/^sha256:[a-f0-9]{64}$/); - } - const postgres = nativeEvidence(staged('postgresql'), 'postgresql', 'linux/amd64', report(passing('postgresql'))) as any; - expect(Object.keys(postgres.privateChecks).sort()).toEqual(['secretCanaryPassed', 'watchdogCleanupPassed']); - const rails = nativeEvidence(staged('rails'), 'rails', 'linux/amd64', report(passing('rails'))) as any; - expect(Object.keys(rails.privateChecks).sort()).toEqual(['accuracyGatesPassed', 'heldOutRepairPassed', 'secretCanaryPassed', 'watchdogCleanupPassed']); - }); - - test('a skipped, missing, failed, duplicated, or assertion-free named test leaves its checks false', () => { - const named = nativeTestRequirements('node').positiveNegativeAssertionsPassed[0]; - const mutate = (change: (cases: JUnitCase[]) => JUnitCase[]) => deriveNativeChecks('node', parseJUnit(report(change(passing('node'))))); - const skipped = mutate(cases => cases.map(item => item.name === named.name ? { ...item, status: 'skipped' as const, assertions: 0 } : item)); - expect(skipped.positiveNegativeAssertionsPassed).toBe(false); - expect(skipped.containmentPassed).toBe(false); - expect(skipped.coldStartPassed).toBe(true); - expect(mutate(cases => cases.filter(item => item.name !== named.name)).positiveNegativeAssertionsPassed).toBe(false); - expect(mutate(cases => [...cases, cases.find(item => item.name === named.name)!]).positiveNegativeAssertionsPassed).toBe(false); - expect(mutate(cases => cases.map(item => item.name === named.name ? { ...item, assertions: 0 } : item)).positiveNegativeAssertionsPassed).toBe(false); - const unrelatedFailure = mutate(cases => [...cases, { file: 'test/other.test.ts', name: '(unnamed)', status: 'failed', assertions: 0 }]); - expect(Object.values(unrelatedFailure).every(value => value === false)).toBe(true); - expect(() => nativeEvidence(staged('node'), 'node', 'linux/amd64', report(passing('node').map(item => item.name === named.name ? { ...item, status: 'skipped', assertions: 0 } : item)))) - .toThrow('NATIVE_GATE_NOT_PASSED: containmentPassed, positiveNegativeAssertionsPassed'); - }); - - test('a different file with the same test name does not satisfy a gate', () => { - const cases = passing('bun').map(item => item.file === 'test/cso-stack-cold-integration.test.ts' ? { ...item, file: 'test/elsewhere.test.ts' } : item); - const checks = deriveNativeChecks('bun', cases); - expect(checks.coldStartPassed).toBe(false); - expect(checks.acquisitionPublicOnlyPassed).toBe(false); - expect(checks.positiveNegativeAssertionsPassed).toBe(true); - }); - - test('staged evidence must describe the same stack and platform', () => { - expect(() => nativeEvidence(staged('bun'), 'node', 'linux/amd64', report(passing('node')))).toThrow('STAGED_EVIDENCE_MISMATCH'); - expect(() => nativeEvidence(staged('node', 'linux/arm64'), 'node', 'linux/amd64', report(passing('node')))).toThrow('STAGED_EVIDENCE_MISMATCH'); - expect(() => nativeEvidence({ ...staged('node'), state: 'qualified' }, 'node', 'linux/amd64', report(passing('node')))).toThrow('STAGED_EVIDENCE_MISMATCH'); - expect(() => parseJUnit('')).toThrow('INVALID_JUNIT_REPORT'); - expect(() => parseJUnit('\n')).toThrow('EMPTY_JUNIT_REPORT'); - }); - - test.skipIf(process.platform==='win32')('the real Bun JUnit report of the Docker suites names every required test, and skipped suites prove nothing', () => { - const dir = mkdtempSync(join(tmpdir(), 'cso-native-junit-')); temps.push(dir); - const outfile = join(dir, 'native.xml'); - const env = { ...process.env }; - for (const key of ['GSTACK_CSO_DOCKER_TESTS', 'GSTACK_CSO_TEST_IMAGE', 'GSTACK_CSO_TEST_STACK']) delete env[key]; - const run = spawnSync(process.execPath, ['run', 'test:cso:docker', '--reporter=junit', `--reporter-outfile=${outfile}`], { cwd: ROOT, env, encoding: 'utf8', timeout: 120_000 }); - expect(run.status, run.stderr).toBe(0); - const cases = parseJUnit(readFileSync(outfile, 'utf8')); - for (const stack of STACKS) { - for (const refs of Object.values(nativeTestRequirements(stack))) for (const ref of refs) { - expect(cases.filter(item => item.file === ref.file && item.name === ref.name).map(item => item.status)).toEqual(['skipped']); - } - expect(Object.values(deriveNativeChecks(stack, cases)).every(value => value === false)).toBe(true); - } - }); -}); diff --git a/test/cso-node-lifecycle-integration.test.ts b/test/cso-node-lifecycle-integration.test.ts deleted file mode 100644 index 9f73c26fa..000000000 --- a/test/cso-node-lifecycle-integration.test.ts +++ /dev/null @@ -1,324 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { publicArchiveCacheRoot } from '../lib/cso/cache'; -import { sha256, type RunReportV3, type VerificationRequest } from '../lib/cso/contracts'; -import { dockerEndpoint, type DockerEndpoint } from '../lib/cso/docker'; -import { patchHash } from '../lib/cso/verification'; -import { qualifiedNodeCli, type QualifiedCsoCli } from './helpers/cso-qualified-cli'; - -const requested = process.env.GSTACK_CSO_DOCKER_TESTS === '1' && process.env.GSTACK_CSO_TEST_STACK === 'node'; -const enabled = requested && Boolean(process.env.GSTACK_CSO_TEST_IMAGE); -const suite = requested ? describe : describe.skip; - -let root = ''; -let repo = ''; -let state = ''; -let endpoint: DockerEndpoint; -let cli: QualifiedCsoCli; - -const application = { - actors: ['unauthenticated caller'], - assets: ['protected response body'], - entrypoints: ['GET /security'], - tenantBoundaries: ['authorization boundary'], - sensitiveOperations: ['protected response read'], - invariants: ['unauthenticated requests cannot read the protected response'], -}; -const finding = { - title: 'Unauthenticated security route discloses a secret', - rootCause: 'The security route returns protected data without an authorization decision', - location: { path: 'policy.js', line: 1, symbol: 'module.exports' }, - advisoryIds: [], - severity: 'high', - confidence: 'high', - confidenceRationale: 'The captured caller-to-sink trace and control review directly support the finding', - evidence: 'supported', - attackerControl: 'An unauthenticated caller can request /security', - impact: 'The response discloses protected data', - scenario: 'An unauthenticated caller requests /security and receives the protected response body', - trace: ['GET /security', 'app.js route', 'policy.js status and body'], - references: ['policy.js:1', 'app.js security route'], - recommendation: 'Require an authorization decision before returning the protected body while preserving the control route', - challenge: { - reviewer: 'lifecycle-fixture-challenger', - independent: true, - mode: 'independent_agent', - callers: 'The loopback verifier calls the route without credentials', - controls: 'No middleware or route authorization protects /security', - counterevidence: 'The legitimate /control route is separate and remains available', - conclusion: 'The captured route reaches the vulnerable policy without a protective control', - }, -}; - -function writeSource(target: string, fixed = false): void { - fs.mkdirSync(target, { recursive: true, mode: 0o700 }); - const files: Record = { - 'package.json': JSON.stringify({ - name: 'cso-node-lifecycle', version: '1.0.0', private: true, - scripts: { start: 'node app.js', test: 'node --test' }, - dependencies: { 'escape-html': '1.0.3' }, - }) + '\n', - 'package-lock.json': JSON.stringify({ - name: 'cso-node-lifecycle', version: '1.0.0', lockfileVersion: 3, requires: true, - packages: { - '': { name: 'cso-node-lifecycle', version: '1.0.0', dependencies: { 'escape-html': '1.0.3' } }, - 'node_modules/escape-html': { - version: '1.0.3', - resolved: 'https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz', - integrity: 'sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==', - }, - }, - }) + '\n', - 'app.js': "const http=require('node:http');const policy=require('./policy');const {control}=require('./control');const port=Number(process.env.PORT);http.createServer((req,res)=>{if(req.url==='/control'){res.writeHead(200);res.end(control());return}if(req.url==='/security'){res.writeHead(policy.status);res.end(policy.body);return}res.writeHead(404);res.end('missing')}).listen(port,'127.0.0.1');\n", - 'control.js': "const escape=require('escape-html');exports.control=()=>escape('CONTROL_OK');\n", - 'policy.js': fixed - ? "module.exports={status:403,body:'DENIED'};\n" - : "module.exports={status:200,body:'SECRET'};\n", - 'app.test.js': "const test=require('node:test');const assert=require('node:assert/strict');const {control}=require('./control');test('legitimate control remains available',()=>assert.equal(control(),'CONTROL_OK'));\n", - }; - for (const [name, body] of Object.entries(files)) fs.writeFileSync(path.join(target, name), body, { mode: 0o600 }); -} - -function git(...args: string[]): string { - const result = spawnSync('/usr/bin/git', ['-C', repo, ...args], { - encoding: 'utf8', env: { HOME: root, PATH: '/usr/bin:/bin' }, timeout: 30_000, - }); - if (result.status) throw new Error(result.stderr); - return result.stdout; -} - -function runDirectory(run: Pick): string { - return path.join(state, 'security', 'cso', run.repoId, run.runId); -} - -function report(run: Pick): RunReportV3 { - return JSON.parse(fs.readFileSync(path.join(runDirectory(run), 'report.json'), 'utf8')); -} - -function writeInput(name: string, value: unknown): string { - const file = path.join(root, name); - fs.writeFileSync(file, JSON.stringify(value), { mode: 0o600 }); - return file; -} - -function helperOwnedCoverage(domain: string): boolean { - return ['snapshot-inputs', 'history-inputs', 'runtime-readiness'].includes(domain) - || domain.startsWith('scanner:') || domain.startsWith('preparation:') || domain.startsWith('execution:'); -} - -function completeEvidence(current: RunReportV3, findings: unknown[] = []): Record { - return { - application, - findings, - coverage: current.coverage.filter(item => !helperOwnedCoverage(item.domain)).map(item => ({ - ...item, - status: 'assessed', - method: 'fresh caller and security-boundary trace', - gaps: [], - evidence: ['current captured source'], - })), - gaps: [], - }; -} - -function dockerContainers(): string[] { - const result = spawnSync(endpoint.executable, ['--host', endpoint.uri, 'ps', '--all', '--quiet', '--no-trunc'], { - encoding: 'utf8', timeout: 30_000, - }); - expect(result.status).toBe(0); - return result.stdout.trim().split('\n').filter(Boolean).sort(); -} - -function expectEmptyDirectory(directory: string): void { - expect(fs.existsSync(directory)).toBe(true); - expect(fs.readdirSync(directory).sort()).toEqual([]); -} - -beforeAll(async () => { - if (!requested) return; - if (!enabled) throw new Error('Node lifecycle qualification requires GSTACK_CSO_TEST_IMAGE; a requested cold gate cannot skip'); - const platform = process.arch === 'arm64' ? 'linux/arm64' : 'linux/amd64'; - if (process.env.GSTACK_CSO_TEST_PLATFORM !== platform) throw new Error(`Node lifecycle qualification requires native ${platform}`); - - root = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-node-lifecycle-')); - repo = path.join(root, 'repo'); - state = path.join(root, 'state'); - process.env.GSTACK_HOME = state; - writeSource(repo); - git('init', '-q'); - git('config', 'user.email', 'fixture@example.test'); - git('config', 'user.name', 'Fixture'); - git('add', '.'); - git('commit', '-qm', 'vulnerable fixture'); - - const watchdogPath = path.resolve(import.meta.dir, '../bin/gstack-cso-watchdog'); - const dockerHome = path.join(root, 'docker-home'); - fs.mkdirSync(dockerHome, { recursive: true, mode: 0o700 }); - endpoint = await dockerEndpoint(dockerHome, { - HOME: root, - DOCKER_HOST: process.env.DOCKER_HOST ?? 'unix:///var/run/docker.sock', - }); - cli = qualifiedNodeCli({ - image: process.env.GSTACK_CSO_TEST_IMAGE!, - versions: JSON.parse(process.env.GSTACK_CSO_EXPECTED_VERSIONS || '{}'), - watchdogPath, - platform, - }); -}); - -afterAll(() => { - if (root) { - fs.rmSync(root, { recursive: true, force: true }); - delete process.env.GSTACK_HOME; - } -}); - -suite('CSO Node producer-visible repair lifecycle fixture', () => { - test('finds, reproduces, bundles, replays, and closes against current source through the command dispatcher', async () => { - const beforeContainers = dockerContainers(); - let originalRunDirectory = ''; - let completed = false; - try { - const original = await cli.command(['start', '--repo', repo, '--comprehensive']); - originalRunDirectory = runDirectory(original); - expect(original.coverage.find(item => item.domain === 'runtime-readiness')).toMatchObject({ status: 'assessed' }); - expect(await cli.command(['submit', original.runId, writeInput('finding.json', completeEvidence(original, [finding]))])).toMatchObject({ findings: 1, completeness: 'complete' }); - - const submitted = report(original); - const submittedFinding = submitted.findings[0]; - expect(submittedFinding).toMatchObject({ reproduction: 'not_attempted', repair: 'not_attempted', closure: 'open' }); - const plan = await cli.command(['runtime-plan', original.runId, 'node', '--port', '34569']); - expect(plan.runtimeProfile).toBe(cli.runtime.id); - const vulnerable = fs.readFileSync(path.join(originalRunDirectory, 'snapshot', 'policy.js'), 'utf8'); - const repaired = "module.exports={status:403,body:'DENIED'};\n"; - const request: VerificationRequest = { - findingId: submittedFinding.id, - runtimeProfile: plan.runtimeProfile, - port: 34569, - start: plan.start.command, - legitimate: [{ name: 'legitimate control', path: '/control', method: 'GET', expected: { status: 200, includes: 'CONTROL_OK' } }], - security: { name: 'unauthorized secret is denied', path: '/security', method: 'GET', expected: { status: 403, includes: 'DENIED' }, vulnerable: { status: 200, includes: 'SECRET' } }, - existingTests: plan.tests.commands, - fixtures: {}, - boundaryFiles: ['app.js', 'policy.js'], - testFiles: plan.tests.files, - changes: [{ path: 'policy.js', beforeSha256: sha256(vulnerable), after: repaired, effect: 'source' }], - review: { - reviewer: 'independent-lifecycle-fixture-reviewer', - independent: true, - rootCauseRepaired: true, - featurePreserved: true, - boundaryMocks: false, - rationale: 'The access decision now denies the unauthorized path while the legitimate control and original test remain intact.', - reviewedPatchHash: '', - }, - }; - request.review.reviewedPatchHash = patchHash(request); - const requestPath = writeInput('verification.json', request); - const review = await cli.command(['record-review', original.runId, requestPath, '--producer', 'lifecycle-fixture-producer']); - request.review.artifactId = review.reviewArtifactId; - writeInput('verification.json', request); - - const verified = await cli.command(['verify', original.runId, requestPath]); - expect(verified).toMatchObject({ - result: 'runtime_tested', - verification: { - result: 'runtime_tested', - assertionAssurance: 'authenticated_out_of_process', - testCompletionAssurance: 'self_reported', - reviewAssurance: 'self_attested', - before: { booted: true, legitimate: true, security: 'intended_failure', existingTests: true }, - after: { booted: true, legitimate: true, security: 'pass', existingTests: true }, - }, - }); - const verifiedReport = report(original); - expect(verifiedReport.findings[0]).toMatchObject({ - reproduction: 'reproduced', - repair: 'runtime_tested', - verificationId: verified.verification.id, - verificationAssurance: { - assertions: 'authenticated_out_of_process', - testCompletion: 'self_reported', - review: 'self_attested', - }, - }); - const bundle = JSON.parse(fs.readFileSync(path.join(originalRunDirectory, verified.bundle), 'utf8')); - expect(bundle).toMatchObject({ id: verified.verification.id, requiredInputs: { runtimeImage: cli.runtime.image } }); - expect(bundle.requiredInputs.dependencyClosures.before.archives).toEqual([ - expect.objectContaining({ - name: 'escape-html', - version: '1.0.3', - requestedHost: 'registry.npmjs.org', - declaredIntegrity: 'sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==', - }), - ]); - - const replayed = await cli.command(['replay', verified.verification.id]); - expect(replayed).toMatchObject({ bundle: verified.verification.id, result: 'runtime_tested' }); - expect(JSON.parse(fs.readFileSync(path.join(originalRunDirectory, 'replays', `${replayed.replayId}.json`), 'utf8'))).toMatchObject({ - replayId: replayed.replayId, - bundleId: verified.verification.id, - verification: { result: 'runtime_tested' }, - }); - expect(await cli.command(['finish', original.runId])).toMatchObject({ status: 'finished', completeness: 'complete' }); - - fs.writeFileSync(path.join(repo, 'policy.js'), repaired, { mode: 0o600 }); - git('add', 'policy.js'); - git('commit', '-qm', 'repair authorization policy'); - const recheck = await cli.command(['recheck', submittedFinding.id, '--run', original.runId, '--repo', repo]); - const recheckRun = { repoId: original.repoId, runId: recheck.runId }; - const fresh = report(recheckRun); - expect(fresh.parent).toEqual({ runId: original.runId, findingId: submittedFinding.id, kind: 'recheck' }); - expect(fresh.source.originalHash).not.toBe(original.source.originalHash); - expect(report(original).findings[0]).toMatchObject({ closure: 'open', verificationId: verified.verification.id }); - const freshBoundary = fs.readFileSync(path.join(runDirectory(recheckRun), 'snapshot', 'policy.js'), 'utf8'); - expect(freshBoundary).toBe(repaired); - - const claim = { - findingId: submittedFinding.id, - outcome: 'resolved', - evidence: [ - { kind: 'caller', path: 'policy.js', line: 1, observation: 'Fresh route trace reaches the repaired authorization decision' }, - { kind: 'security_boundary', path: 'policy.js', line: 1, observation: 'Fresh boundary source returns the denial without the protected body' }, - ], - rootCause: finding.rootCause, - }; - expect(await cli.command(['submit', recheck.runId, writeInput('recheck.json', { ...completeEvidence(fresh), recheck: claim })])).toMatchObject({ findings: 0, completeness: 'complete' }); - const retainedClaim = JSON.parse(fs.readFileSync(path.join(runDirectory(recheckRun), 'recheck-claim.json'), 'utf8')); - expect(retainedClaim.evidence).toEqual([ - expect.objectContaining({ kind: 'caller', path: expect.stringMatching(/^@cso-path\/\//), sourceState: 'present', snapshotHash: fresh.source.originalHash, sourceHash: sha256(Buffer.from(repaired)), executionHash: sha256(Buffer.from(repaired)) }), - expect.objectContaining({ kind: 'security_boundary', path: expect.stringMatching(/^@cso-path\/\//), sourceState: 'present', snapshotHash: fresh.source.originalHash, sourceHash: sha256(Buffer.from(repaired)), executionHash: sha256(Buffer.from(repaired)) }), - ]); - expect(await cli.command(['finish', recheck.runId])).toMatchObject({ status: 'finished', completeness: 'complete' }); - expect(report(original).findings[0]).toMatchObject({ - closure: 'resolved', - reproduction: 'reproduced', - repair: 'runtime_tested', - verificationId: verified.verification.id, - }); - completed = true; - } finally { - expect(dockerContainers()).toEqual(beforeContainers); - if (originalRunDirectory) { - for (const directory of ['archive-staging', 'archive-materializations', 'preparation-execution', 'verification']) { - const full = path.join(originalRunDirectory, directory); - if (fs.existsSync(full)) expect(fs.readdirSync(full).sort()).toEqual([]); - } - } - } - - expect(completed).toBe(true); - for (const directory of ['archive-staging', 'archive-materializations', 'preparation-execution', 'verification']) { - expectEmptyDirectory(path.join(originalRunDirectory, directory)); - } - const cache = publicArchiveCacheRoot(); - expect(fs.lstatSync(path.join(cache, '.lock')).isFile()).toBe(true); - expect(fs.readdirSync(path.join(cache, 'entries'))).toHaveLength(1); - expect(fs.readdirSync(path.join(cache, 'metadata'))).toHaveLength(1); - expectEmptyDirectory(path.join(cache, '.mutation-lock-leases')); - for (const directory of ['incoming', 'recovery']) expectEmptyDirectory(path.join(cache, directory)); - }, 10 * 60_000); -}); diff --git a/test/cso-ntfs-fixture.test.ts b/test/cso-ntfs-fixture.test.ts deleted file mode 100644 index 19b2f6e54..000000000 --- a/test/cso-ntfs-fixture.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { afterEach, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { createPrecisionLossCandidate } from './helpers/cso-ntfs-fixture'; - -const roots: string[] = []; -afterEach(() => { - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); - -function fixture() { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ntfs-fixture-')); - roots.push(root); - return { root, target: path.join(root, 'candidate.json') }; -} - -test('the actual candidate builder reaches a precision-losing generation in a fresh allocator model', () => { - const { root, target } = fixture(); - const generations = new Map(); - let reads = 0; - let selectedIdentity: bigint | undefined; - const inode = createPrecisionLossCandidate(target, 'owned candidate', file => { - reads++; - const slot = Number(path.basename(file).split('-').at(-1)); - const generation = (generations.get(slot) ?? 0n) + 1n; - generations.set(slot, generation); - const result = (generation << 48n) + BigInt(101 + slot); - if (result > BigInt(Number.MAX_SAFE_INTEGER) && String(Number(result)) !== String(result)) { - selectedIdentity = fs.lstatSync(file, { bigint: true }).ino; - } - return result; - }); - expect(inode).toBeGreaterThan(BigInt(Number.MAX_SAFE_INTEGER)); - expect(String(Number(inode))).not.toBe(String(inode)); - expect(reads).toBeLessThanOrEqual(1024); - expect(fs.lstatSync(target, { bigint: true }).ino).toBe(selectedIdentity); - expect(fs.readFileSync(target, 'utf8')).toBe('owned candidate'); - expect(fs.readdirSync(root)).toEqual(['candidate.json']); -}); - -test('an unavailable precision-losing ID fails at the original creation bound and leaves no candidate', () => { - const { root, target } = fixture(); - for (const inode of [1n, 2n ** 54n]) { - let reads = 0; - expect(() => createPrecisionLossCandidate(target, 'owned candidate', () => { reads++; return inode; })) - .toThrow('within 1024 file creations'); - expect(reads).toBe(1024); - expect(fs.readdirSync(root)).toEqual([]); - } -}); - -test('existing targets and candidate-inspection failures never overwrite unrelated fixture state', () => { - const { root, target } = fixture(); - fs.writeFileSync(target, 'preserved'); - expect(() => createPrecisionLossCandidate(target, 'replacement')).toThrow('already exists'); - expect(fs.readFileSync(target, 'utf8')).toBe('preserved'); - const next = path.join(root, 'next.json'); - expect(() => createPrecisionLossCandidate(next, 'owned candidate', () => { throw new Error('inspection failed'); })) - .toThrow('inspection failed'); - expect(fs.readdirSync(root)).toEqual(['candidate.json']); -}); - -test('a concurrent target and a linked parent are preserved rather than written through', () => { - const { root, target } = fixture(); - expect(() => createPrecisionLossCandidate(target, 'replacement', () => { - fs.writeFileSync(target, 'concurrent fixture'); - return (1n << 54n) + 1n; - })).toThrow(); - expect(fs.readFileSync(target, 'utf8')).toBe('concurrent fixture'); - const owned = path.join(root, 'owned'); - const link = path.join(root, 'linked'); - fs.mkdirSync(owned); - fs.symlinkSync(owned, link, process.platform === 'win32' ? 'junction' : 'dir'); - expect(() => createPrecisionLossCandidate(path.join(link, 'candidate.json'), 'replacement')) - .toThrow('must not be linked'); - expect(fs.readdirSync(owned)).toEqual([]); -}); diff --git a/test/cso-ordinary-repos.test.ts b/test/cso-ordinary-repos.test.ts deleted file mode 100644 index b674dce3d..000000000 --- a/test/cso-ordinary-repos.test.ts +++ /dev/null @@ -1,520 +0,0 @@ -// Regressions for /cso on ordinary user repositories: an untracked nested Git -// repository (#3255 bug 1), a patch history over the 1 MiB bound (#3255 bug 2), -// a Docker socket that realpath refuses to open (#3248), and tracked symlinks, -// which are recorded by their target string and never followed (#4540). -import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as net from 'node:net'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { NESTED_REPOSITORY, OUTSIDE_AUDIT_PATHS, capture, historyMarker, symlinkTransformation } from '../lib/cso/snapshot'; -import { newRun, readJson } from '../lib/cso/state'; -import { MAX_OUTPUT } from '../lib/cso/contracts'; -import { dockerEndpoint } from '../lib/cso/docker'; -import { TRUSTED_DIRECTORIES } from '../lib/cso/process'; - -const ROOT = path.resolve(import.meta.dir, '..'); -const launcher = path.join(ROOT, 'bin', process.platform === 'win32' ? 'gstack-cso-launcher.exe' : 'gstack-cso-launcher'); -const MIB = 1024 * 1024; -const CREDENTIAL_CANARY = ['ghp_', 'abcdefghijklmnopqrstuvwxyz1234567890'].join(''); -const OLD_CANARY = ['ghp_', 'zyxwvutsrqponmlkjihgfedcba0987654321'].join(''); -const MARKER = '[gstack-cso history truncated:'; -const roots: string[] = []; -const originalHome = process.env.GSTACK_HOME; -let state = ''; -beforeAll(() => { - state = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cso-ordinary-state-'))); - process.env.GSTACK_HOME = state; -}); -afterEach(() => { - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); -afterAll(() => { - if (originalHome === undefined) delete process.env.GSTACK_HOME; - else process.env.GSTACK_HOME = originalHome; - fs.rmSync(state, { recursive: true, force: true }); -}); - -function tmp(): string { - const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cso-ordinary-'))); - roots.push(root); - return root; -} -function git(repo: string, ...args: string[]): string { - const result = spawnSync('/usr/bin/git', ['-C', repo, ...args], { encoding: 'utf8', env: { HOME: path.dirname(repo), PATH: '/usr/bin:/bin' }, timeout: 60_000 }); - if (result.status) throw new Error(result.stderr); - return result.stdout; -} -function init(repo: string): string { - fs.mkdirSync(repo, { recursive: true }); - git(repo, 'init', '-q'); - git(repo, 'config', 'user.email', 'fixture@example.test'); - git(repo, 'config', 'user.name', 'Fixture'); - return repo; -} -function commit(repo: string, files: Record, subject: string): void { - for (const [file, body] of Object.entries(files)) fs.writeFileSync(path.join(repo, file), body); - git(repo, 'add', '-A'); - git(repo, 'commit', '-qm', subject); -} -function filler(tag: string, bytes: number): string { - const lines: string[] = []; - for (let i = 0, size = 0; size < bytes; i++) { - const line = `export const ${tag}${i} = ${i};`; - lines.push(line); - size += line.length + 1; - } - return lines.join('\n') + '\n'; -} -function nestedRepository(outer: string, name: string, files: Record): string { - const inner = init(path.join(outer, name)); - commit(inner, files, 'inner'); - return inner; -} -function cso(repo: string, args: string[]) { - return spawnSync(launcher, args, { cwd: repo, encoding: 'utf8', env: { HOME: path.dirname(repo), GSTACK_HOME: state, PATH: '/usr/bin:/bin' }, timeout: 120_000, maxBuffer: 64 * MIB }); -} -function runFiles(dir: string): string[] { - return fs.readdirSync(dir, { recursive: true, withFileTypes: true }).filter((item) => item.isFile()).map((item) => path.join(item.parentPath, item.name)); -} - -describe('CSO start on a repository with an untracked nested repository (#3255 bug 1)', () => { - test('start succeeds, records the boundary as an explicit exclusion, and never reads the nested source', () => { - const repo = init(path.join(tmp(), 'repo')); - commit(repo, { 'README.md': 'outer\n' }, 'outer'); - nestedRepository(repo, 'inner', { 'secret.txt': `TOKEN=${CREDENTIAL_CANARY}\n` }); - const started = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline']); - expect(started.stderr).toBe(''); - expect(started.status).toBe(0); - const run = JSON.parse(started.stdout), - dir = path.join(state, 'security', 'cso', run.repoId, run.runId), - report = readJson(path.join(dir, 'report.json')), - snapshot = report.coverage.find((item: any) => item.domain === 'snapshot-inputs'); - expect(snapshot.exclusions).toEqual([`inner: ${NESTED_REPOSITORY}`]); - expect(snapshot.gaps).toEqual([]); - for (const file of runFiles(dir)) expect(fs.readFileSync(file, 'utf8')).not.toContain(CREDENTIAL_CANARY); - expect(fs.existsSync(path.join(dir, 'snapshot', 'inner'))).toBe(false); - expect(fs.existsSync(path.join(dir, 'readable', 'inner'))).toBe(false); - }); - - test.skipIf(process.platform === 'win32')('negative control: an untracked symlink to a directory is recorded as a link, never treated as a boundary or followed (#4540)', () => { - const root = tmp(), - repo = init(path.join(root, 'repo')), - outside = path.join(root, 'outside'); - commit(repo, { 'README.md': 'outer\n' }, 'outer'); - nestedRepository(repo, 'inner', { 'f.txt': 'x\n' }); - fs.mkdirSync(outside); - fs.writeFileSync(path.join(outside, 'host.txt'), `TOKEN=${CREDENTIAL_CANARY}\n`); - fs.symlinkSync(outside, path.join(repo, 'escape')); - const started = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline']); - expect(started.stderr).toBe(''); - expect(started.status).toBe(0); - const run = JSON.parse(started.stdout), - dir = path.join(state, 'security', 'cso', run.repoId, run.runId), - snapshot = readJson(path.join(dir, 'report.json')).coverage.find((item: any) => item.domain === 'snapshot-inputs'); - expect(snapshot.exclusions.sort()).toEqual([`escape: ${symlinkTransformation('escape', outside)}`, `inner: ${NESTED_REPOSITORY}`]); - expect(snapshot.gaps).toEqual([]); - for (const file of runFiles(dir)) expect(fs.readFileSync(file, 'utf8')).not.toContain(CREDENTIAL_CANARY); - expect(fs.existsSync(path.join(dir, 'snapshot', 'escape'))).toBe(false); - }); - - test('negative control: a nested repository swapped for another directory during capture fails as a snapshot race', async () => { - const root = tmp(), - repo = init(path.join(root, 'repo')), - target = path.join(repo, 'vendor', 'inner'), - replacement = path.join(root, 'replacement'); - commit(repo, { 'README.md': 'outer\n' }, 'outer'); - fs.mkdirSync(path.join(repo, 'vendor')); - nestedRepository(repo, 'vendor/inner', { 'f.txt': 'x\n' }); - nestedRepository(root, 'replacement', { 'f.txt': 'y\n' }); - const original = fs.lstatSync; - let hits = 0; - const counting = spyOn(fs, 'lstatSync').mockImplementation(((candidate: any, options?: any) => { - if (path.resolve(String(candidate)) === target) hits++; - return options === undefined ? original(candidate) : original(candidate, options); - }) as typeof fs.lstatSync); - try { - await capture(repo, newRun(repo).dir, 'HEAD'); - } finally { - counting.mockRestore(); - } - const last = hits; - expect(last).toBeGreaterThan(1); - hits = 0; - let swapped = false; - const swapping = spyOn(fs, 'lstatSync').mockImplementation(((candidate: any, options?: any) => { - if (path.resolve(String(candidate)) === target && ++hits === last) { - fs.renameSync(target, `${target}.parked`); - fs.renameSync(replacement, target); - swapped = true; - } - return options === undefined ? original(candidate) : original(candidate, options); - }) as typeof fs.lstatSync); - try { - await expect(capture(repo, newRun(repo).dir, 'HEAD')).rejects.toMatchObject({ code: 'SNAPSHOT_RACE', message: 'Source changed before snapshot persistence: vendor/inner' }); - } finally { - swapping.mockRestore(); - } - expect(swapped).toBe(true); - }); -}); - -describe.skipIf(process.platform === 'win32')('CSO on a repository that tracks symlinks (#4540)', () => { - const OUTSIDE_CANARY = ['outside', 'payload', 'never', 'read'].join('-'); - const LINKS: Record = { - 'CLAUDE.md': 'README.md', - handbook: 'docs', - 'web/guide.md': '../docs/guide.md', - 'host-users': '/etc/passwd', - 'null-device': '/dev/null', - escape: '../outside.txt', - 'docs/deep-escape': '../../outside.txt', - 'loop-a': 'loop-b', - 'loop-b': 'loop-a', - dangling: 'missing.txt', - }; - function linkedRepo(): { root: string; repo: string } { - const root = tmp(), - repo = init(path.join(root, 'repo')); - fs.writeFileSync(path.join(root, 'outside.txt'), `${OUTSIDE_CANARY}\n`); - fs.mkdirSync(path.join(repo, 'docs')); - fs.mkdirSync(path.join(repo, 'web')); - commit(repo, { 'README.md': 'readme\n', 'docs/guide.md': 'guide\n', 'web/app.ts': 'export {};\n' }, 'base'); - for (const [name, target] of Object.entries(LINKS)) fs.symlinkSync(target, path.join(repo, name)); - git(repo, 'add', '-A'); - git(repo, 'commit', '-qm', 'links'); - return { root, repo }; - } - - test('start audits the repository and reports every tracked link by its target string', () => { - const { repo } = linkedRepo(); - const started = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline']); - expect(started.stderr).toBe(''); - expect(started.status).toBe(0); - const run = JSON.parse(started.stdout), - dir = path.join(state, 'security', 'cso', run.repoId, run.runId), - report = readJson(path.join(dir, 'report.json')), - snapshot = report.coverage.find((item: any) => item.domain === 'snapshot-inputs'); - expect(snapshot.exclusions.sort()).toEqual( - Object.entries(LINKS) - .map(([name, target]) => `${name}: ${symlinkTransformation(name, target)}`) - .sort(), - ); - expect(snapshot.gaps).toEqual([]); - expect(symlinkTransformation('host-users', '/etc/passwd')).toContain('"/etc/passwd"'); - expect(symlinkTransformation('escape', '../outside.txt')).toContain('escapes the repository'); - expect(symlinkTransformation('handbook', 'docs')).toContain('"docs" inside the repository'); - const retained = runFiles(path.join(dir, 'snapshot')).map((file) => path.relative(path.join(dir, 'snapshot'), file)).sort(); - expect(retained).toEqual(['README.md', 'docs/guide.md', 'web/app.ts']); - for (const file of runFiles(dir)) { - const body = fs.readFileSync(file, 'utf8'); - expect(body).not.toContain(OUTSIDE_CANARY); - expect(body).not.toContain('root:x:0:0'); - } - }); - - test('capture never opens, stats or resolves a link: only lstat and readlink touch it', async () => { - const { repo } = linkedRepo(), - linkPaths = Object.keys(LINKS).map((name) => path.join(repo, name)), - touched: string[] = [], - spies = (['statSync', 'realpathSync', 'openSync', 'readFileSync', 'opendirSync', 'existsSync', 'accessSync', 'readdirSync'] as const).map((name) => { - const original = (fs as any)[name]; - return spyOn(fs, name as any).mockImplementation(((...args: any[]) => { - if (typeof args[0] === 'string' || args[0] instanceof URL || Buffer.isBuffer(args[0])) touched.push(path.resolve(String(args[0]))); - return original(...args); - }) as any); - }); - let manifest: Awaited>; - try { - manifest = await capture(repo, newRun(repo).dir); - } finally { - for (const spy of spies) spy.mockRestore(); - } - expect(touched).toContain(path.join(repo, 'README.md')); - expect(touched.filter((item) => linkPaths.some((link) => item === link || item.startsWith(`${link}${path.sep}`)))).toEqual([]); - for (const [name, target] of Object.entries(LINKS)) { - const entry = manifest.entries.find((item) => item.path === name); - expect(entry).toMatchObject({ - originalHash: createHash('sha256').update(target).digest('hex'), - bytes: Buffer.byteLength(target), - transformation: symlinkTransformation(name, target), - }); - expect(entry?.executionHash).toBeUndefined(); - } - }); - - test('a comparison base sees a retargeted link as changed and an unchanged link as unchanged', async () => { - const { repo } = linkedRepo(), - base = git(repo, 'rev-parse', 'HEAD').trim(); - fs.unlinkSync(path.join(repo, 'handbook')); - fs.symlinkSync('web', path.join(repo, 'handbook')); - commit(repo, { 'web/app.ts': 'export const changed = 1;\n' }, 'change'); - const manifest = await capture(repo, newRun(repo).dir, base); - expect(manifest.changedPaths).toEqual(['handbook', 'web/app.ts']); - }); - - test('negative controls: an untracked FIFO or socket is still refused', async () => { - const { repo } = linkedRepo(), - fifo = path.join(repo, 'request.pipe'); - expect(spawnSync('/usr/bin/mkfifo', [fifo], { timeout: 10_000 }).status).toBe(0); - await expect(capture(repo, newRun(repo).dir)).rejects.toMatchObject({ code: 'UNSAFE_PATH', message: 'Symlink or special source file: request.pipe' }); - fs.unlinkSync(fifo); - const server = net.createServer(), - socket = path.join(repo, 'web', 'app.sock'); - await new Promise((done) => server.listen(socket, done)); - try { - await expect(capture(repo, newRun(repo).dir)).rejects.toMatchObject({ code: 'UNSAFE_PATH', message: 'Symlink or special source file: web/app.sock' }); - } finally { - await new Promise((done) => server.close(() => done())); - } - }); - - test('--paths narrows the special-file walk: a FIFO outside the scope no longer blocks, one inside still does', async () => { - const { repo } = linkedRepo(); - expect(spawnSync('/usr/bin/mkfifo', [path.join(repo, 'request.pipe')], { timeout: 10_000 }).status).toBe(0); - const manifest = await capture(repo, newRun(repo).dir, undefined, undefined, {}, ['web']); - expect(manifest.entries.find((item) => item.path === 'web/guide.md')?.transformation).toBe(symlinkTransformation('web/guide.md', '../docs/guide.md')); - expect(manifest.entries.find((item) => item.path === 'host-users')?.transformation).toBe(OUTSIDE_AUDIT_PATHS); - expect(spawnSync('/usr/bin/mkfifo', [path.join(repo, 'web', 'request.pipe')], { timeout: 10_000 }).status).toBe(0); - await expect(capture(repo, newRun(repo).dir, undefined, undefined, {}, ['web'])).rejects.toMatchObject({ code: 'UNSAFE_PATH', message: 'Symlink or special source file: web/request.pipe' }); - }); - - test('negative control: a link retargeted during capture fails as a snapshot race', async () => { - const { repo } = linkedRepo(), - link = path.join(repo, 'handbook'), - original = fs.readlinkSync; - let hits = 0; - const counting = spyOn(fs, 'readlinkSync').mockImplementation(((candidate: any, options?: any) => { - if (path.resolve(String(candidate)) === link) hits++; - return original(candidate, options); - }) as typeof fs.readlinkSync); - try { - await capture(repo, newRun(repo).dir); - } finally { - counting.mockRestore(); - } - expect(hits).toBeGreaterThan(1); - const last = hits; - hits = 0; - let swapped = false; - const swapping = spyOn(fs, 'readlinkSync').mockImplementation(((candidate: any, options?: any) => { - if (path.resolve(String(candidate)) === link && ++hits === last) { - fs.unlinkSync(link); - fs.symlinkSync('/etc', link); - swapped = true; - } - return original(candidate, options); - }) as typeof fs.readlinkSync); - try { - await expect(capture(repo, newRun(repo).dir)).rejects.toMatchObject({ code: 'SNAPSHOT_RACE', message: expect.stringContaining('handbook') }); - } finally { - swapping.mockRestore(); - } - expect(swapped).toBe(true); - }); -}); - -describe('CSO history capture over the 1 MiB bound (#3255 bug 2)', () => { - test('keeps the newest whole commits that fit, marks the truncation, and still redacts', async () => { - const repo = init(path.join(tmp(), 'repo')); - commit(repo, { 'old.ts': filler('old', 450 * 1024) + `// ${OLD_CANARY}\n` }, 'oldest'); - commit(repo, { 'mid.ts': filler('mid', 450 * 1024) }, 'middle'); - commit(repo, { 'new.ts': filler('new', 300 * 1024) + `// ${CREDENTIAL_CANARY}\n` }, 'newest'); - const run = newRun(repo); - await capture(repo, run.dir); - const status = readJson(path.join(run.dir, 'history-status.json')), - history = fs.readFileSync(path.join(run.dir, 'history.txt'), 'utf8'); - expect(status).toMatchObject({ status: 'captured', commits: 2 }); - expect(status.truncated).toBe(`the newest 2 of 3 commits were retained with patches; 1 older commits were omitted to stay within the ${MAX_OUTPUT}-byte history limit`); - expect(history.startsWith(historyMarker(status.truncated))).toBe(true); - expect(Buffer.byteLength(history)).toBeLessThanOrEqual(MAX_OUTPUT); - expect(status.bytes).toBe(Buffer.byteLength(history)); - expect(history).toContain('Subject: newest'); - expect(history).toContain('Subject: middle'); - expect(history).not.toContain('Subject: oldest'); - expect(history).toContain('diff --git a/new.ts b/new.ts'); - expect(history).not.toContain(CREDENTIAL_CANARY); - expect(history).not.toContain(OLD_CANARY); - }); - - test('falls back to commit metadata when the newest patch alone exceeds the bound, and still redacts', async () => { - const repo = init(path.join(tmp(), 'repo')); - commit(repo, { 'a.ts': 'export const a = 1;\n' }, 'first'); - commit(repo, { 'big.ts': filler('big', 1.2 * MIB) }, `rotate ${CREDENTIAL_CANARY}`); - const run = newRun(repo); - await capture(repo, run.dir); - const status = readJson(path.join(run.dir, 'history-status.json')), - history = fs.readFileSync(path.join(run.dir, 'history.txt'), 'utf8'); - expect(status).toMatchObject({ status: 'captured', commits: 'metadata for at most 100' }); - expect(status.truncated).toMatch(/^patches were withheld because/); - expect(history.startsWith(historyMarker(status.truncated))).toBe(true); - expect(history).toContain('Subject: first'); - expect(history).toContain('Subject: rotate'); - expect(history).not.toContain('diff --git'); - expect(history).not.toContain(CREDENTIAL_CANARY); - }); - - test('a history within the bound is retained whole with no marker', async () => { - const repo = init(path.join(tmp(), 'repo')); - commit(repo, { 'a.ts': 'export const a = 1;\n' }, 'first'); - commit(repo, { 'b.ts': `// ${CREDENTIAL_CANARY}\n` }, 'second'); - const run = newRun(repo); - await capture(repo, run.dir); - const status = readJson(path.join(run.dir, 'history-status.json')), - history = fs.readFileSync(path.join(run.dir, 'history.txt'), 'utf8'); - expect(status).toEqual({ status: 'captured', range: status.range, commits: 'at most 100', bytes: Buffer.byteLength(history) }); - expect(history.startsWith('commit ')).toBe(true); - expect(history).toContain('Subject: first'); - expect(history).not.toContain(MARKER); - expect(history).not.toContain(CREDENTIAL_CANARY); - }); - - test('start reports the truncated history as partial coverage and history stays readable', () => { - const repo = init(path.join(tmp(), 'repo')); - commit(repo, { 'old.ts': filler('old', 700 * 1024) }, 'oldest'); - commit(repo, { 'new.ts': filler('new', 700 * 1024) }, 'newest'); - const started = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline']); - expect(started.stderr).toBe(''); - expect(started.status).toBe(0); - const run = JSON.parse(started.stdout), - report = readJson(path.join(state, 'security', 'cso', run.repoId, run.runId, 'report.json')), - coverage = report.coverage.find((item: any) => item.domain === 'history-inputs'); - expect(coverage.status).toBe('partial'); - expect(coverage.gaps).toEqual([`History truncated: the newest 1 of 2 commits were retained with patches; 1 older commits were omitted to stay within the ${MAX_OUTPUT}-byte history limit`]); - expect(coverage.evidence[0]).toStartWith('Captured 1 from '); - const whole = cso(repo, ['history', run.runId]); - expect(whole.status).toBe(0); - expect(whole.stdout.startsWith(MARKER)).toBe(true); - const scoped = cso(repo, ['history', run.runId, 'new.ts']); - expect(scoped.status).toBe(0); - expect(scoped.stdout.startsWith('commit ')).toBe(true); - expect(scoped.stdout).toContain('diff --git a/new.ts b/new.ts'); - }); -}); - -const dockerInstalled = TRUSTED_DIRECTORIES.some((directory) => fs.existsSync(path.join(directory, 'docker'))); -describe.skipIf(process.platform === 'win32' || !dockerInstalled)('CSO Docker endpoint admission when realpath refuses sockets (#3248)', () => { - let root = ''; - let socketPath = ''; - let server: net.Server; - const realpath = fs.realpathSync; - const refusing = ((candidate: fs.PathLike, ...rest: any[]) => { - let socket = false; - try { - socket = fs.statSync(candidate).isSocket(); - } catch {} - if (socket) { - const error = new Error('EOPNOTSUPP: operation not supported on socket') as NodeJS.ErrnoException; - error.code = 'EOPNOTSUPP'; - throw error; - } - return realpath(candidate, ...rest); - }) as typeof fs.realpathSync; - beforeAll(async () => { - root = realpath(fs.mkdtempSync(path.join(os.tmpdir(), 'cso-endpoint-'))); - socketPath = path.join(root, 'docker.sock'); - server = net.createServer(); - await new Promise((resolve, reject) => { - server.once('error', reject); - server.listen(socketPath, () => resolve()); - }); - }); - afterAll(async () => { - await new Promise((resolve) => server.close(() => resolve())); - fs.rmSync(root, { recursive: true, force: true }); - }); - afterEach(() => { - (fs.realpathSync as any).mockRestore?.(); - }); - const admit = (host: string) => dockerEndpoint(root, { HOME: root, DOCKER_HOST: host }); - - test('admits a socket reached through a symlinked directory and a symlinked leaf, pinned to its identity', async () => { - const linkedDirectory = path.join(root, 'run'), - leaf = path.join(root, 'colima.sock'); - fs.symlinkSync(root, linkedDirectory); - fs.symlinkSync('docker.sock', leaf); - const stub = spyOn(fs, 'realpathSync').mockImplementation(refusing); - const identity = fs.statSync(socketPath); - for (const host of [`unix://${socketPath}`, `unix://${path.join(linkedDirectory, 'colima.sock')}`]) { - const endpoint = await admit(host); - expect(endpoint).toMatchObject({ socket: socketPath, uri: `unix://${socketPath}`, device: identity.dev, inode: identity.ino }); - } - expect(stub.mock.calls.some(([candidate]) => String(candidate) === socketPath)).toBe(true); - }); - - test('negative controls: non-sockets, dangling or looping links, and non-local URIs are still refused', async () => { - spyOn(fs, 'realpathSync').mockImplementation(refusing); - const file = path.join(root, 'plain.sock'), - dangling = path.join(root, 'dangling.sock'), - loopA = path.join(root, 'loop-a.sock'), - loopB = path.join(root, 'loop-b.sock'); - fs.writeFileSync(file, ''); - fs.symlinkSync(path.join(root, 'missing.sock'), dangling); - fs.symlinkSync(loopB, loopA); - fs.symlinkSync(loopA, loopB); - await expect(admit(`unix://${file}`)).rejects.toMatchObject({ code: 'ISOLATION_FAILED', message: 'Docker endpoint is not a local Unix socket' }); - for (const candidate of [dangling, loopA]) - await expect(admit(`unix://${candidate}`)).rejects.toMatchObject({ code: 'ISOLATION_FAILED', message: 'Pinned local Docker socket is unavailable' }); - await expect(admit(`unix://${root}/../${path.basename(root)}/docker.sock`)).rejects.toMatchObject({ code: 'ISOLATION_FAILED' }); - await expect(admit('tcp://127.0.0.1:2375')).rejects.toMatchObject({ code: 'ISOLATION_FAILED' }); - }); -}); - -test('a symlink transformation never carries an unredacted secret or raw control text from its target (#4540)', () => { - const inside = symlinkTransformation('cfg/link', `keys/${CREDENTIAL_CANARY}`), - crafted = symlinkTransformation('cfg/link', 'a\nexcluded: fake sentence'); - expect(inside).not.toContain(CREDENTIAL_CANARY); - expect(inside).toContain('inside the repository'); - expect(crafted).not.toContain('\n'); - expect(crafted).toContain('"cfg/a\\nexcluded: fake sentence" inside the repository'); -}); - -test.skipIf(process.platform === 'win32')('negative controls: nested and deeply nested links carrying password, api_key and token values never leak them into the report or manifest (#4540)', () => { - const repo = init(path.join(tmp(), 'repo')), - keys = [['pass', 'word'].join(''), ['api', 'key'].join('_'), ['to', 'ken'].join('')], - values = keys.map((key) => `${key}=${['Xk9', 'qPz7Lm2Rt8Vw4Ny6', key.length].join('')}`), - secrets = values.map((value) => value.split('=')[1]), - links: [string, string][] = []; - fs.mkdirSync(path.join(repo, 'cfg', 'a', 'b', 'c', 'd'), { recursive: true }); - commit(repo, { 'README.md': 'readme\n' }, 'base'); - for (const dir of ['cfg', 'cfg/a/b/c/d']) - keys.forEach((key, index) => { - links.push([`${dir}/${key}-link`, values[index]], [`${dir}/${key}-up`, `../${values[index]}`]); - }); - for (const [name, target] of links) { - fs.symlinkSync(target, path.join(repo, name)); - const text = symlinkTransformation(name, target); - for (const secret of secrets) expect(text).not.toContain(secret); - } - git(repo, 'add', '-A'); - git(repo, 'commit', '-qm', 'links'); - const started = cso(repo, ['start', '--repo', repo, '--scope', 'auth', '--offline']); - expect(started.stderr).toBe(''); - expect(started.status).toBe(0); - const run = JSON.parse(started.stdout), - dir = path.join(state, 'security', 'cso', run.repoId, run.runId), - snapshot = readJson(path.join(dir, 'report.json')).coverage.find((item: any) => item.domain === 'snapshot-inputs'); - expect(snapshot.exclusions).toHaveLength(links.length); - for (const file of ['report.json', 'snapshot.json']) { - const body = fs.readFileSync(path.join(dir, file), 'utf8'); - for (const secret of secrets) expect(body).not.toContain(secret); - } -}); - -test('fail closed: a link target that matches a secret pattern, whole or per segment, is withheld with its resolved path (#4540)', () => { - const value = ['Xk9', 'qPz7Lm2Rt8Vw4Ny6'].join(''), - halves = [['c3Hd6Ty8Qp2Z', 'x7Lm4Nb9'].join(''), ['Vw1Rk5Js0Gh3', 'Fd8Ks2Pq'].join('')], - cases: [string, string, string[]][] = [ - ['cfg/db', ['postgres://alice:', value, '@localhost/db'].join(''), [value]], - ['cfg/aws', [['AWS', 'SECRET', 'ACCESS', 'KEY'].join('_'), '=', halves[0], '/', halves[1]].join(''), halves], - ['cfg/a/b/up', ['../', ['pass', 'word'].join(''), '=', value].join(''), [value]], - ]; - for (const [name, target, secrets] of cases) { - const text = symlinkTransformation(name, target); - for (const secret of secrets) expect(text).not.toContain(secret); - expect(text).toContain('a target withheld because it matches a secret pattern'); - expect(text).not.toContain('resolves lexically'); - } -}); diff --git a/test/cso-postgresql-policy.test.ts b/test/cso-postgresql-policy.test.ts deleted file mode 100644 index 6c3b548eb..000000000 --- a/test/cso-postgresql-policy.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { validatePostgresDatabasePolicy } from '../lib/cso/docker'; - -const roots:string[]=[]; -afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); -function policy(body:string,mode=0o444):string{const root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-pg-policy-'));roots.push(root);const file=path.join(root,'databases');fs.writeFileSync(file,body,{mode});return file;} - -describe('CSO PostgreSQL synthetic policy mount',()=>{ - test('requires fixed-user-readable immutable permissions without weakening private policies',()=>{ - expect(validatePostgresDatabasePolicy(policy('cso_primary\ncso_queue\n'))).toEqual(['cso_primary','cso_queue']); - expect(()=>validatePostgresDatabasePolicy(policy('cso_primary\n',0o600))).toThrow('public-readable'); - }); - test('rejects malformed, duplicate, and overlong database identities',()=>{ - for(const body of ['cso_primary\ncso_primary\n','cso_bad-name\n',`cso_${'a'.repeat(49)}\n`,'cso_primary']) - expect(()=>validatePostgresDatabasePolicy(policy(body))).toThrow(); - }); -}); diff --git a/test/cso-preparation-adversarial.test.ts b/test/cso-preparation-adversarial.test.ts deleted file mode 100644 index 10a442e0f..000000000 --- a/test/cso-preparation-adversarial.test.ts +++ /dev/null @@ -1,228 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { createHash } from 'node:crypto'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { PublicArchiveCache } from '../lib/cso/cache'; -import { canonical, CsoError, sha256 } from '../lib/cso/contracts'; -import { inspectPreparation, type CsoStack } from '../lib/cso/preparation'; -import { - admitPreparationRuntime, - PreparationExecutor, - type AcquisitionReceipt, - type OfflinePreparationReceipt, - type OfflinePreparationRequest, - type PreparationAcquireRequest, - type PreparationSandboxRunner, -} from '../lib/cso/preparation-executor'; -import { CSO_HELPER_ABI } from '../lib/cso/runtime-catalog'; -import { completeRuntimeCatalogFixture } from './helpers/cso-runtime-catalog'; - -const roots: string[] = []; -const archiveBytes = Buffer.from('adversarial-public-archive'); -const sha512 = (value: Buffer | string) => createHash('sha512').update(value).digest('base64'); - -function temporary(prefix: string): string { - const value = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); - roots.push(value); - return value; -} - -function writeTree(root: string, files: Record): void { - for (const [relative, value] of Object.entries(files)) { - const target = path.join(root, relative); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.writeFileSync(target, typeof value === 'string' ? value : JSON.stringify(value)); - } -} - -function catalog(_stack: 'node' | 'bun') { return completeRuntimeCatalogFixture('adversarial-test-v1'); } - -function cacheFixture(): PublicArchiveCache { - const root = temporary('cso-adversarial-cache-'); - const stagingRoot = path.join(root, 'staging'); - fs.mkdirSync(stagingRoot, { mode: 0o700 }); - return new PublicArchiveCache({ root: path.join(root, 'cache'), stagingRoot, maxBytes: 1024 * 1024 }); -} - -const qualification = { - schemaVersion: 1 as const, helperAbi: CSO_HELPER_ABI, runnerId: 'adversarial-qualified-runner', - policyVersion: 'cso-preparation-v1' as const, supportedStacks: ['node', 'bun', 'python', 'rails'] as CsoStack[], - registryRestrictionQualified: true as const, dnsRebindingTestsPassed: true as const, - acquisitionExcludesSource: true as const, offlineContainmentQualified: true as const, - immutableArchiveMounts: true as const, resourceLimitsEnforced: true as const, -}; - -function commandReceipts(commands: PreparationAcquireRequest['commands']) { - return commands.map((command, index) => ({ - index, commandHash: sha256(canonical(command)), exitCode: 0, timedOut: false, outputTruncated: false, - })); -} - -function offlineReceipt(request: OfflinePreparationRequest): OfflinePreparationReceipt { - return { - schemaVersion: 1, planHash: request.planHash, runtimeId: request.runtime.id, runtimeImage: request.runtime.image, - platform: request.runtime.platform, sourceHash: request.sourceHash, dependencyClosureHash: request.dependencyClosureHash, - configurationHash: request.configurationHash, databaseHash: request.databaseHash, deadlineEnforced: true, - network: { mode: 'none', namespaceAnchor: 'adversarial-anchor', externalEgress: false, dnsAvailable: false, - publishedPorts: false, services: ['application'] }, - commands: commandReceipts(request.commands), inputSourceReadOnly: true, preparedCopySeparate: true, - archivesReadOnly: true, applicationCodeExecutedOnlyOffline: true, - }; -} - -class PreparedSymlinkRunner implements PreparationSandboxRunner { - readonly qualification = qualification; - constructor(private readonly linkTarget: string) {} - async acquire(): Promise { throw new Error('fixture has no public dependencies'); } - async prepareOffline(request: OfflinePreparationRequest) { - const call = temporary('cso-adversarial-prepared-'); - const preparedRoot = path.join(call, 'prepared'); - fs.mkdirSync(preparedRoot, { mode: 0o700 }); - fs.cpSync(request.sourceRoot, preparedRoot, { recursive: true }); - fs.mkdirSync(path.join(preparedRoot, 'node_modules/.bin'), { recursive: true }); - fs.mkdirSync(path.join(preparedRoot, 'node_modules/.cache'), { recursive: true }); - fs.writeFileSync(path.join(preparedRoot, 'node_modules/.cache/tool.js'), 'export default 1;\n'); - fs.writeFileSync(path.join(call, 'outside.txt'), 'outside\n'); - fs.symlinkSync(this.linkTarget, path.join(preparedRoot, 'node_modules/.bin/tool')); - return { preparedRoot, receipt: offlineReceipt(request) }; - } - disposePrepared(preparedRoot: string): void { fs.rmSync(path.dirname(preparedRoot), { recursive: true, force: true }); } -} - -function dependencyFreeNode(): string { - const root = temporary('cso-adversarial-node-'); - writeTree(root, { - 'package.json': { name: 'app', version: '1.0.0' }, - 'package-lock.json': { name: 'app', version: '1.0.0', lockfileVersion: 3, - packages: { '': { name: 'app', version: '1.0.0' } } }, - }); - return root; -} - -async function prepareWithLink(linkTarget: string) { - const snapshot = dependencyFreeNode(), plan = inspectPreparation(snapshot, 'node'); - expect(plan.status).toBe('ready'); - const admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('node') }); - const executor = new PreparationExecutor({ cache: cacheFixture(), runner: new PreparedSymlinkRunner(linkTarget) }); - const deadline = Date.now() + 60_000; - const closure = await executor.acquire({ plan, admission, snapshot, deadline }); - return executor.prepareOffline({ plan, admission, snapshot, closure, deadline }); -} - -class ConcurrentAcquisitionRunner implements PreparationSandboxRunner { - readonly qualification = qualification; - readonly stagingRoots: string[] = []; - private arrivals = 0; - private release!: () => void; - private readonly barrier = new Promise(resolve => { this.release = resolve; }); - - async acquire(request: PreparationAcquireRequest): Promise { - this.stagingRoots.push(request.stagingRoot); - this.arrivals++; - if (this.arrivals === 2) this.release(); - await this.barrier; - const stagingPath = 'cso-public/same-plan-0.archive'; - const target = path.join(request.stagingRoot, stagingPath); - fs.mkdirSync(path.dirname(target), { recursive: true }); - fs.writeFileSync(target, archiveBytes, { flag: 'wx', mode: 0o600 }); - const input = request.inputs[0].input; - const hash = sha256(archiveBytes); - const requestedUrl = input.url!; - return { - schemaVersion: 1, planHash: request.planHash, runtimeId: request.runtime.id, runtimeImage: request.runtime.image, - platform: request.runtime.platform, deadlineEnforced: true, - network: { mode: 'registry-restricted', allowedHosts: [...request.network.allowedHosts], - contactedHosts: [new URL(requestedUrl).hostname], redirectVisibility: 'opaque-tls', - dnsRebindingBlocked: true, credentialsMounted: false, sourceMounted: false, dockerSocketMounted: false }, - lifecycleScriptsExecuted: false, targetCodeExecuted: false, commands: commandReceipts(request.commands), - artifacts: [{ inputIndex: request.inputs[0].index, stagingPath, installPath: 'node/0.tgz', sha256: hash, - bytes: archiveBytes.length, requestedHost: new URL(requestedUrl).hostname, requestedUrl, resolvedUrl: null, - registryResponseSha256: hash }], - }; - } - async prepareOffline(): Promise { throw new Error('not used'); } - disposePrepared():void{} -} - -function oneDependencyNode(): string { - const root = temporary('cso-adversarial-node-dependency-'); - writeTree(root, { - 'package.json': { name: 'app', version: '1.0.0', dependencies: { cookie: '1.0.0' } }, - 'package-lock.json': { name: 'app', version: '1.0.0', lockfileVersion: 3, packages: { - '': { name: 'app', version: '1.0.0', dependencies: { cookie: '1.0.0' } }, - 'node_modules/cookie': { name: 'cookie', version: '1.0.0', - resolved: 'https://registry.npmjs.org/cookie/-/cookie-1.0.0.tgz', - integrity: `sha512-${sha512(archiveBytes)}` }, - } }, - }); - return root; -} - -afterEach(() => { - for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); -}); - -describe('CSO preparation adversarial regressions', () => { - test('accepts a contained relative symlink in a prepared dependency tree', async () => { - const prepared = await prepareWithLink('../.cache/tool.js'); - expect(prepared.preparedManifestHash).toMatch(/^[a-f0-9]{64}$/); - }); - - for (const target of ['../../../outside.txt', '/etc/passwd']) { - test(`rejects a prepared dependency symlink escaping through ${target.startsWith('/') ? 'an absolute target' : 'a relative target'}`, async () => { - try { - await prepareWithLink(target); - throw new Error('expected escaping prepared-tree symlink to be rejected'); - } catch (error) { - expect(error).toBeInstanceOf(CsoError); - expect((error as CsoError).code).toBe('UNSAFE_PATH'); - } - }); - } - - test('rejects conflicting duplicate Node logical lock identities', () => { - const root = temporary('cso-adversarial-node-conflict-'); - writeTree(root, { - 'package.json': { name: 'app', version: '1.0.0', dependencies: { cookie: '1.0.0' } }, - 'package-lock.json': { name: 'app', version: '1.0.0', lockfileVersion: 3, packages: { - '': { name: 'app', version: '1.0.0', dependencies: { cookie: '1.0.0' } }, - 'node_modules/cookie': { name: 'cookie', version: '1.0.0', - resolved: 'https://registry.npmjs.org/cookie/-/cookie-1.0.0.tgz', integrity: `sha512-${sha512('first')}` }, - 'node_modules/nested/node_modules/cookie': { name: 'cookie', version: '1.0.0', - resolved: 'https://registry.npmjs.org/cookie/-/cookie-other-1.0.0.tgz', integrity: `sha512-${sha512('second')}` }, - } }, - }); - const plan = inspectPreparation(root, 'node'); - expect(plan.status).toBe('prerequisites'); - expect(plan.prerequisites[0]?.code).toBe('CONFLICTING_LOCK_IDENTITY'); - expect(plan.acquisition).toEqual([]); - }); - - test('rejects conflicting duplicate Bun logical lock identities', () => { - const root = temporary('cso-adversarial-bun-conflict-'); - writeTree(root, { - 'package.json': { name: 'app', version: '1.0.0', dependencies: { cookie: '1.0.0' } }, - 'bun.lock': { lockfileVersion: 1, workspaces: { '': { name: 'app', dependencies: { cookie: '1.0.0' } } }, packages: { - first: ['cookie@1.0.0', 'https://registry.npmjs.org/cookie/-/cookie-1.0.0.tgz', {}, `sha512-${sha512('first')}`], - second: ['cookie@1.0.0', 'https://registry.npmjs.org/cookie/-/cookie-other-1.0.0.tgz', {}, `sha512-${sha512('second')}`], - } }, - }); - const plan = inspectPreparation(root, 'bun'); - expect(plan.status).toBe('prerequisites'); - expect(plan.prerequisites[0]?.code).toBe('CONFLICTING_LOCK_IDENTITY'); - expect(plan.acquisition).toEqual([]); - }); - - test('gives concurrent acquisitions of the same plan non-colliding staging namespaces', async () => { - const snapshot = oneDependencyNode(), plan = inspectPreparation(snapshot, 'node'); - expect(plan.status).toBe('ready'); - const admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('node') }); - const runner = new ConcurrentAcquisitionRunner(); - const executor = new PreparationExecutor({ cache: cacheFixture(), runner }); - const requests = [1, 2].map(() => executor.acquire({ plan, admission, snapshot, deadline: Date.now() + 60_000 })); - const results = await Promise.allSettled(requests); - expect(results.map(result => result.status)).toEqual(['fulfilled', 'fulfilled']); - expect(new Set(runner.stagingRoots).size).toBe(2); - }); -}); diff --git a/test/cso-preparation-container.test.ts b/test/cso-preparation-container.test.ts deleted file mode 100644 index 6cde0dc9a..000000000 --- a/test/cso-preparation-container.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { createPreparedExport, recordNpmArchiveEntry } from '../lib/cso/preparation-container'; -import { materializePreparedExport, writeOfflineTransformations } from '../lib/cso/preparation-docker'; -import { heldApplicationReady, validateSingleContainerProcessOutput } from '../lib/cso/docker'; - -const roots: string[] = []; -function temporary(): string { const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-prepared-export-')); roots.push(root); return root; } -afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); - -describe('CSO preparation container archive limits', () => { - test('a zero-byte directory flood consumes the same bounded tar-entry budget as files', () => { - let entries = 0; - for (let index = 0; index < 200_000; index++) entries = recordNpmArchiveEntry(entries, '5'); - expect(entries).toBe(200_000); - expect(() => recordNpmArchiveEntry(entries, '5')).toThrow('npm archive exceeded extraction limits'); - expect(() => recordNpmArchiveEntry(entries, '0')).toThrow('npm archive exceeded extraction limits'); - }); - - test('exports only inert regular blobs and reconstructs contained dependency symlinks', () => { - const root = temporary(), work = path.join(root, 'work'), exported = path.join(work, `.gstack-cso-export-${'a'.repeat(24)}`), - inert = path.join(root, 'inert'), prepared = path.join(root, 'prepared'); - fs.mkdirSync(path.join(work, 'node_modules/lib'), { recursive: true, mode: 0o700 }); - fs.mkdirSync(path.join(work, 'node_modules/.bin'), { mode: 0o700 }); - fs.writeFileSync(path.join(work, 'package.json'), '{"name":"fixture"}\n', { mode: 0o600 }); - fs.writeFileSync(path.join(work, 'node_modules/lib/tool.js'), 'export default 1;\n', { mode: 0o500 }); - fs.symlinkSync('../lib/tool.js', path.join(work, 'node_modules/.bin/tool')); - fs.mkdirSync(prepared, { mode: 0o700 }); - - const manifest = createPreparedExport(work, exported, 1024 * 1024); - expect(fs.readdirSync(exported).sort()).toEqual(['blobs', 'manifest.json']); - for (const name of fs.readdirSync(path.join(exported, 'blobs'))) expect(fs.lstatSync(path.join(exported, 'blobs', name)).isFile()).toBe(true); - expect(manifest.entries.some(entry => entry.kind === 'symlink')).toBe(true); - fs.cpSync(exported, inert, { recursive: true }); - materializePreparedExport(inert, prepared, 1024 * 1024); - expect(fs.readFileSync(path.join(prepared, 'node_modules/.bin/tool'), 'utf8')).toBe('export default 1;\n'); - expect(fs.readlinkSync(path.join(prepared, 'node_modules/.bin/tool'))).toBe('../lib/tool.js'); - }); - - test('rejects escaping links and special lifecycle output before an export is created', () => { - for (const kind of ['symlink', 'fifo'] as const) { - if (kind === 'fifo' && process.platform === 'win32') continue; - const root = temporary(), work = path.join(root, 'work'), exported = path.join(work, `.gstack-cso-export-${(kind === 'symlink' ? 'b' : 'c').repeat(24)}`); - fs.mkdirSync(work, { mode: 0o700 }); - if (kind === 'symlink') fs.symlinkSync('../../outside', path.join(work, 'host-escape')); - else { - const result = spawnSync('mkfifo', [path.join(work, 'lifecycle.fifo')], { timeout: 30_000 }); - expect(result.status).toBe(0); - } - expect(() => createPreparedExport(work, exported, 1024 * 1024)).toThrow(kind === 'symlink' ? 'escaping symlink' : 'special object'); - expect(fs.existsSync(exported)).toBe(false); - } - }); - - test('refuses acquisition or preparation export while a manager-owned background process remains', () => { - expect(() => validateSingleContainerProcessOutput('PID\n123\n')).not.toThrow(); - expect(() => validateSingleContainerProcessOutput('PID\n123\n456\n')).toThrow('background process'); - expect(() => validateSingleContainerProcessOutput('PID COMMAND\n123 bun\n')).toThrow('background process'); - }); - - test('treats a held application as ready only after run-app has finished copying its source', () => { - expect(heldApplicationReady('PID COMMAND\n273296 sleep\n')).toBe(true); - expect(heldApplicationReady('PID COMMAND\n1 sh\n2 cp\n')).toBe(false); - expect(heldApplicationReady('PID COMMAND\n1 sh\n2 sleep\n')).toBe(false); - expect(heldApplicationReady('PID COMMAND\n1 sh\n')).toBe(false); - }); -}); - -describe('offline transformations in an execution copy', () => { - test.skipIf(process.platform === 'win32')('replace a read-only copied file under a read-only directory instead of writing through it', () => { - const source = temporary(), config = path.join(source, 'config'), database = path.join(config, 'database.yml'), outside = path.join(temporary(), 'outside.yml'); - fs.mkdirSync(config); - fs.writeFileSync(database, 'production: sealed\n'); - fs.chmodSync(database, 0o444); - fs.chmodSync(config, 0o555); - fs.writeFileSync(outside, 'untouched\n'); - const content = 'test:\n adapter: sqlite3\n', sha256 = createHash('sha256').update(content).digest('hex'); - writeOfflineTransformations(source, [ - { path: 'config/database.yml', content, sha256, reason: 'helper test configuration' }, - { path: 'config/initializers/zzzz_cso_test.rb', content, sha256, reason: 'helper test configuration' }, - ]); - expect(fs.readFileSync(database, 'utf8')).toBe(content); - expect(fs.statSync(database).mode & 0o777).toBe(0o600); - expect(fs.readFileSync(path.join(config, 'initializers', 'zzzz_cso_test.rb'), 'utf8')).toBe(content); - expect(() => writeOfflineTransformations(source, [{ path: 'config/database.yml', content, sha256: 'f'.repeat(64), reason: 'tampered' }])).toThrow('Offline transformation content hash changed'); - fs.rmSync(database); - fs.symlinkSync(outside, database); - writeOfflineTransformations(source, [{ path: 'config/database.yml', content, sha256, reason: 'helper test configuration' }]); - expect(fs.lstatSync(database).isSymbolicLink()).toBe(false); - expect(fs.readFileSync(outside, 'utf8')).toBe('untouched\n'); - }); -}); diff --git a/test/cso-preparation-executor.test.ts b/test/cso-preparation-executor.test.ts deleted file mode 100644 index b54dc7f17..000000000 --- a/test/cso-preparation-executor.test.ts +++ /dev/null @@ -1,551 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import * as net from 'node:net'; -import { createHash } from 'node:crypto'; -import { PublicArchiveCache } from '../lib/cso/cache'; -import { CsoError } from '../lib/cso/contracts'; -import { inspectPreparation, type CsoStack } from '../lib/cso/preparation'; -import { - admitPreparationRuntime, admitPreparationSidecar, PreparationExecutor, - type AcquisitionReceipt, type OfflinePreparationReceipt, type PreparationAcquireRequest, - type PreparationSandboxRunner, type OfflinePreparationRequest, preparedIdentityEntry, proveNpmLockIdentities } from '../lib/cso/preparation-executor'; -import { CSO_HELPER_ABI } from '../lib/cso/runtime-catalog'; -import { DockerPreparationSandboxRunner, isBlockedRegistryAddress, RegistryEgressBroker } from '../lib/cso/preparation-docker'; -import { completeRuntimeCatalogFixture, qualifiedRuntimeFixture, unqualifiedRuntimeCatalog } from './helpers/cso-runtime-catalog'; - -const roots: string[] = []; -const digest = 'a'.repeat(64); -const artifactBytes = (stack: CsoStack) => Buffer.from(`${stack}-verified-public-archive`); -const h256 = (value: Buffer | string) => createHash('sha256').update(value).digest('hex'); -const h512 = (value: Buffer | string) => createHash('sha512').update(value).digest('base64'); - -function root(prefix: string): string { const value = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); roots.push(value); return value; } -function writeTree(base: string, files: Record): void { - for (const [name, content] of Object.entries(files)) { - const target = path.join(base, name); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, content); - } -} -function snapshot(stack: CsoStack): string { - const base = root(`cso-executor-${stack}-`), bytes = artifactBytes(stack); - if (stack === 'node') writeTree(base, { - 'package.json': JSON.stringify({ name: 'app', version: '1.0.0', dependencies: { cookie: '1.0.0' }, scripts: { postinstall: 'touch /tmp/unsafe' } }), - 'package-lock.json': JSON.stringify({ name: 'app', lockfileVersion: 3, packages: { - '': { name: 'app', version: '1.0.0', dependencies: { cookie: '1.0.0' } }, - 'node_modules/cookie': { name: 'cookie', version: '1.0.0', resolved: 'https://registry.npmjs.org/cookie/-/cookie-1.0.0.tgz', integrity: `sha512-${h512(bytes)}` }, - } }), - }); - if (stack === 'bun') writeTree(base, { - 'package.json': JSON.stringify({ name: 'app', version: '1.0.0', dependencies: { cookie: '1.0.0' } }), - 'bun.lock': JSON.stringify({ lockfileVersion: 1, workspaces: { '': { name: 'app', dependencies: { cookie: '1.0.0' } } }, - packages: { cookie: ['cookie@1.0.0', 'https://registry.npmjs.org/cookie/-/cookie-1.0.0.tgz', {}, `sha512-${h512(bytes)}`] } }), - }); - if (stack === 'python') writeTree(base, { 'requirements.txt': `flask==3.1.0 --hash=sha256:${h256(bytes)}\n` }); - if (stack === 'rails') writeTree(base, { - 'Gemfile': 'source "https://rubygems.org"\ngem "rack"\ngem "sqlite3"\ngem "pg"\n', - 'Gemfile.lock': `GEM\n remote: https://rubygems.org/\n specs:\n pg (1.5.9)\n rack (3.1.8)\n sqlite3 (2.5.0-x86_64-linux-gnu)\n\nPLATFORMS\n ruby\n x86_64-linux-gnu\n\nDEPENDENCIES\n pg\n rack\n sqlite3\n\nRUBY VERSION\n ruby 3.3.6p108\n\nBUNDLED WITH\n 2.6.9\n`, - }); - return base; -} - -function runtime(stack: Parameters[0]) { return qualifiedRuntimeFixture(stack); } -function catalog(..._stacks: Array) { return completeRuntimeCatalogFixture('executor-test-v1'); } -function cacheFixture() { - const base = root('cso-executor-cache-'), staging = path.join(base, 'staging'); fs.mkdirSync(staging, { mode: 0o700 }); - return new PublicArchiveCache({ root: path.join(base, 'cache'), stagingRoot: staging, maxBytes: 1024 * 1024 }); -} -// Match the helper's stable-key canonicalization without importing an internal helper. -function canonical(value: any): string { - if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`; - if (value && typeof value === 'object') return `{${Object.keys(value).sort().map(key => `${JSON.stringify(key)}:${canonical(value[key])}`).join(',')}}`; - return JSON.stringify(value); -} -function receipts(commands: PreparationAcquireRequest['commands']) { - return commands.map((command, index) => ({ index, commandHash: h256(canonical(command)), exitCode: 0, timedOut: false, outputTruncated: false })); -} - -class FakeRunner implements PreparationSandboxRunner { - readonly qualification = { schemaVersion: 1 as const, helperAbi: CSO_HELPER_ABI, runnerId: 'fake-qualified-runner', - policyVersion: 'cso-preparation-v1' as const, supportedStacks: ['node', 'bun', 'python', 'rails'] as CsoStack[], - registryRestrictionQualified: true as const, dnsRebindingTestsPassed: true as const, acquisitionExcludesSource: true as const, - offlineContainmentQualified: true as const, immutableArchiveMounts: true as const, resourceLimitsEnforced: true as const }; - acquireCalls = 0; - prepareCalls = 0; - acquireRequests: PreparationAcquireRequest[] = []; - offlineRequests: OfflinePreparationRequest[] = []; - mutateAcquisition?: (receipt: AcquisitionReceipt) => void; - mutatePrepared?: (preparedRoot:string) => void; - disposed:string[]=[]; - beforePrepare?: (request: OfflinePreparationRequest) => void; - bytes?: Buffer; - - async acquire(request: PreparationAcquireRequest): Promise { - this.acquireCalls++; this.acquireRequests.push(request); - const artifacts = [] as AcquisitionReceipt['artifacts']; - const seen = new Set(); - for (const { index, input } of request.inputs) { - const key = `${input.name}\0${input.version}`; if (seen.has(key)) continue; seen.add(key); - const bytes = this.bytes ?? artifactBytes(request.stack), stagingPath = `${request.stack}-${index}.archive`; - fs.writeFileSync(path.join(request.stagingRoot, stagingPath), bytes, { mode: 0o600 }); - const requestedUrl = input.url ?? (request.stack === 'rails' - ? `https://rubygems.org/gems/${input.name}-${input.version}.gem` - : `https://${request.network.allowedHosts[0]}/packages/${input.name}-${input.version}.archive`); - const requestedHost = new URL(requestedUrl).hostname, hash = h256(bytes); - artifacts.push({ inputIndex: index, stagingPath, installPath: `${request.stack}/${input.name}-${input.version}.archive`, - sha256: hash, bytes: bytes.length, requestedHost, requestedUrl, resolvedUrl: null, registryResponseSha256: hash }); - } - const receipt: AcquisitionReceipt = { schemaVersion: 1, planHash: request.planHash, runtimeId: request.runtime.id, - runtimeImage: request.runtime.image, platform: request.runtime.platform, deadlineEnforced: true, - network: { mode: 'registry-restricted', allowedHosts: [...request.network.allowedHosts], - contactedHosts: [...new Set(artifacts.map(item => item.requestedHost))], redirectVisibility: 'opaque-tls', dnsRebindingBlocked: true, - credentialsMounted: false, sourceMounted: false, dockerSocketMounted: false }, - lifecycleScriptsExecuted: false, targetCodeExecuted: false, commands: receipts(request.commands), artifacts }; - this.mutateAcquisition?.(receipt); - return receipt; - } - - async prepareOffline(request: OfflinePreparationRequest) { - this.prepareCalls++; this.offlineRequests.push(request); - this.beforePrepare?.(request); - for (const archive of request.archives) { - expect(fs.existsSync(archive.hostPath)).toBe(true); - expect(h256(fs.readFileSync(archive.hostPath))).toBe(archive.sha256); - } - const preparedRoot = root(`cso-prepared-${request.stack}-`); - fs.cpSync(request.sourceRoot, preparedRoot, { recursive: true }); - for (const file of request.transformations) { - const target = path.join(preparedRoot, file.path); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, file.content); - } - const dependencyRoot = request.stack === 'python' ? '.venv' : request.stack === 'rails' ? 'vendor/bundle' : 'node_modules'; - fs.mkdirSync(path.join(preparedRoot, dependencyRoot), { recursive: true }); - fs.writeFileSync(path.join(preparedRoot, dependencyRoot, '.cso-dependencies'), request.dependencyClosureHash, { mode: 0o600 }); - this.mutatePrepared?.(preparedRoot); - const services: Array<'application' | 'postgresql'> = ['application']; - const receipt: OfflinePreparationReceipt = { schemaVersion: 1, planHash: request.planHash, runtimeId: request.runtime.id, - runtimeImage: request.runtime.image, platform: request.runtime.platform, sourceHash: request.sourceHash, - dependencyClosureHash: request.dependencyClosureHash, configurationHash: request.configurationHash, - databaseHash: request.databaseHash, deadlineEnforced: true, - network: { mode: 'none', namespaceAnchor: 'fake-network-anchor', externalEgress: false, dnsAvailable: false, - publishedPorts: false, services }, commands: receipts(request.commands), inputSourceReadOnly: true, - preparedCopySeparate: true, archivesReadOnly: true, applicationCodeExecutedOnlyOffline: true }; - return { preparedRoot, receipt }; - } - disposePrepared(preparedRoot:string):void{this.disposed.push(preparedRoot);fs.rmSync(preparedRoot,{recursive:true,force:true});} -} - -function errorCode(error: unknown): string | undefined { return error instanceof CsoError ? error.code : undefined; } -afterEach(() => { for (const value of roots.splice(0)) fs.rmSync(value, { recursive: true, force: true }); }); - -describe('CSO constrained dependency preparation executor', () => { - test('an unqualified catalog and forged admissions fail closed', async () => { - const source = snapshot('node'), plan = inspectPreparation(source, 'node'), runner = new FakeRunner(), cache = cacheFixture(); - expect(() => admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: unqualifiedRuntimeCatalog() })).toThrow('MISSING_QUALIFIED_RUNTIME'); - const executor = new PreparationExecutor({ cache, runner }); - try { - await executor.acquire({ plan, admission: { schemaVersion: 1, catalogRevision: 'forged', runtime: runtime('node') }, - snapshot: source, deadline: Date.now() + 60_000 }); - throw new Error('expected forged admission to fail'); - } catch (error) { expect(errorCode(error)).toBe('PREREQUISITE'); } - expect(runner.acquireCalls).toBe(0); - }); - - for (const stack of ['node', 'bun', 'python', 'rails'] as const) test(`${stack} acquisition is registry-restricted and target setup is offline`, async () => { - const source = snapshot(stack), plan = inspectPreparation(source, stack); expect(plan.status).toBe('ready'); - const admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog(stack) }); - const runner = new FakeRunner(), cache = cacheFixture(), executor = new PreparationExecutor({ cache, runner }); - const deadline = Date.now() + 60_000; - const closure = await executor.acquire({ plan, admission, snapshot: source, deadline }); - expect(closure.archives.length).toBeGreaterThan(0); - expect(cache.get(closure.archives[0].sha256)?.bytes).toBe(artifactBytes(stack).length); - expect(runner.acquireRequests[0].sourceMounted).toBe(false); - expect('sourceRoot' in runner.acquireRequests[0]).toBe(false); - expect(runner.acquireRequests[0].network.allowedHosts).toEqual(plan.registryHosts); - - const reused = await executor.acquire({ plan, admission, snapshot: source, deadline, offline: true, existingClosure: closure }); - expect(reused.closureHash).toBe(closure.closureHash); expect(runner.acquireCalls).toBe(1); - const prepared = await executor.prepareOffline({ plan, admission, snapshot: source, closure, deadline, - database: stack === 'rails' ? { adapter: 'sqlite' } : undefined }); - expect(prepared.preparedRoot).not.toBe(source); expect(prepared.preparedManifestHash).toMatch(/^[a-f0-9]{64}$/);expect(prepared.preparedDependencyHash).toMatch(/^[a-f0-9]{64}$/); - if (stack === 'rails') { - expect(prepared.executionEnvironment).toMatchObject({ PATH: '/usr/local/bin:/usr/bin:/bin', BUNDLE_PATH: '/work/vendor/bundle', BUNDLE_FROZEN: 'true' }); - expect(prepared.executionEnvironment).not.toHaveProperty('RAILS_ENV'); - expect(prepared.executionEnvironment).not.toHaveProperty('RACK_ENV'); - expect(prepared.executionEnvironment).not.toHaveProperty('SECRET_KEY_BASE'); - } - expect(prepared.receipt.network.mode).toBe('none'); expect(prepared.receipt.network.externalEgress).toBe(false); - expect(runner.offlineRequests[0].archives.every(item => item.containerPath.startsWith('/archives/'))).toBe(true); - }); - - test('offline mode names the missing closure before invoking acquisition', async () => { - const source = snapshot('python'), plan = inspectPreparation(source, 'python'), admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('python') }); - const runner = new FakeRunner(), executor = new PreparationExecutor({ cache: cacheFixture(), runner }); - try { await executor.acquire({ plan, admission, snapshot: source, deadline: Date.now() + 60_000, offline: true }); } - catch (error) { expect(errorCode(error)).toBe('MISSING_INPUT'); } - expect(runner.acquireCalls).toBe(0); - }); - - test('prepared dependency identity detects offline test-toolchain mutation',async()=>{ - const source=snapshot('node'),plan=inspectPreparation(source,'node'),admission=admitPreparationRuntime({plan,platform:'linux/amd64',catalog:catalog('node')}),runner=new FakeRunner(),executor=new PreparationExecutor({cache:cacheFixture(),runner}),deadline=Date.now()+60_000,closure=await executor.acquire({plan,admission,snapshot:source,deadline}); - const before=await executor.prepareOffline({plan,admission,snapshot:source,closure,deadline});runner.mutatePrepared=root=>fs.writeFileSync(path.join(root,'node_modules','.cso-dependencies'),'changed toolchain bytes');const after=await executor.prepareOffline({plan,admission,snapshot:source,closure,deadline});expect(after.preparedDependencyHash).not.toBe(before.preparedDependencyHash); - }); - - test('Rails build diagnostics with random build directories stay out of the prepared identity', () => { - for (const path of [ - 'vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/date-3.5.1/gem_make.out', - 'vendor/bundle/ruby/3.4.0/extensions/aarch64-linux/3.4.0/json-3.0.2/mkmf.log', - 'vendor/bundle/ruby/3.4.0/gems/sqlite3-2.9.0/ext/sqlite3/tmp/x86_64-linux-gnu/ports/sqlite3/3.51.1/sqlite-autoconf-3510100/config.log', - ]) expect(preparedIdentityEntry('rails', path)).toBe(false); - for (const path of [ - 'vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/date-3.5.1/date_core.so', - 'vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/date-3.5.1/gem.build_complete', - 'vendor/bundle/ruby/3.4.0/gems/sqlite3-2.9.0/lib/sqlite3/sqlite3_native.so', - 'vendor/bundle/ruby/3.4.0/gems/rails-8.1.2/lib/rails.rb', - 'log/gem_make.out', - ]) expect(preparedIdentityEntry('rails', path)).toBe(true); - expect(preparedIdentityEntry('node', 'vendor/bundle/ruby/3.4.0/extensions/x86_64-linux/3.4.0/date-3.5.1/gem_make.out')).toBe(true); - }); - - test('network-policy and exact-command receipt changes are rejected before promotion', async () => { - const source = snapshot('node'), plan = inspectPreparation(source, 'node'), admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('node') }); - const runner = new FakeRunner(), cache = cacheFixture(), executor = new PreparationExecutor({ cache, runner }); - runner.mutateAcquisition = receipt => { receipt.network.contactedHosts.push('evil.invalid'); receipt.commands[0].commandHash = digest; }; - try { await executor.acquire({ plan, admission, snapshot: source, deadline: Date.now() + 60_000 }); } - catch (error) { expect(errorCode(error)).toBe('ISOLATION_FAILED'); } - expect(cache.stats().entries).toBe(0); - }); - - test('lock integrity is independently checked over staged bytes', async () => { - const source = snapshot('bun'), plan = inspectPreparation(source, 'bun'), admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('bun') }); - const runner = new FakeRunner(); runner.bytes = Buffer.from('tampered-registry-response'); - try { await new PreparationExecutor({ cache: cacheFixture(), runner }).acquire({ plan, admission, snapshot: source, deadline: Date.now() + 60_000 }); } - catch (error) { expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); return; } - throw new Error('expected mismatched lock integrity to fail'); - }); - - test('every offline cache hit is rehashed and poison blocks reuse', async () => { - const source = snapshot('node'), plan = inspectPreparation(source, 'node'), admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('node') }); - const runner = new FakeRunner(), cache = cacheFixture(), executor = new PreparationExecutor({ cache, runner }), deadline = Date.now() + 60_000; - const closure = await executor.acquire({ plan, admission, snapshot: source, deadline }); - const hit = cache.get(closure.archives[0].sha256)!; fs.chmodSync(hit.path, 0o600); fs.writeFileSync(hit.path, 'poison'); fs.chmodSync(hit.path, 0o400); - try { await executor.acquire({ plan, admission, snapshot: source, deadline, offline: true, existingClosure: closure }); } - catch (error) { expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); return; } - throw new Error('expected poisoned cache reuse to fail'); - }); - - test('threads cancellation into retained-closure cache verification', async () => { - const source = snapshot('node'), plan = inspectPreparation(source, 'node'), admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('node') }); - const runner = new FakeRunner(), cache = cacheFixture(), executor = new PreparationExecutor({ cache, runner }), deadline = Date.now() + 60_000; - const closure = await executor.acquire({ plan, admission, snapshot: source, deadline }); - const controller = new AbortController(), original = fs.readSync.bind(fs); let cacheReads = 0; - const reader = spyOn(fs, 'readSync').mockImplementation(((fd: number, buffer: NodeJS.ArrayBufferView, - offset: number, length: number, position: number | null) => { - const read = original(fd, buffer, offset, length, position); - if (length === 64 * 1024 && read > 0) { cacheReads++; controller.abort(); } - return read; - }) as typeof fs.readSync); - try { - await executor.acquire({ plan, admission, snapshot: source, deadline, signal: controller.signal, offline: true, existingClosure: closure }); - throw new Error('expected retained closure verification to be cancelled'); - } catch (error) { expect(errorCode(error)).toBe('CANCELLED'); } - finally { reader.mockRestore(); } - expect(cacheReads).toBe(1); expect(runner.acquireCalls).toBe(1); - }); - - test('cancels acquisition while independently hashing staged archive bytes', async () => { - const source = snapshot('node'), plan = inspectPreparation(source, 'node'), admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('node') }); - const runner = new FakeRunner(), cache = cacheFixture(), executor = new PreparationExecutor({ cache, runner }); - const controller = new AbortController(), original = fs.readSync.bind(fs); let stagedReads = 0; - const reader = spyOn(fs, 'readSync').mockImplementation(((fd: number, buffer: NodeJS.ArrayBufferView, - offset: number, length: number, position: number | null) => { - const read = original(fd, buffer, offset, length, position); - if (length === 64 * 1024 && read > 0) { stagedReads++; controller.abort(); } - return read; - }) as typeof fs.readSync); - try { - await executor.acquire({ plan, admission, snapshot: source, deadline: Date.now() + 60_000, signal: controller.signal }); - throw new Error('expected staged archive verification to be cancelled'); - } catch (error) { expect(errorCode(error)).toBe('CANCELLED'); } - finally { reader.mockRestore(); } - expect(stagedReads).toBe(1); expect(runner.acquireCalls).toBe(1); expect(cache.stats().entries).toBe(0); - }); - - test('run-owned archive copies survive a cache eviction between validation and runner start', async () => { - const source = snapshot('node'), plan = inspectPreparation(source, 'node'), admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('node') }); - const runner = new FakeRunner(), base = root('cso-eviction-race-'), staging = path.join(base, 'staging'); fs.mkdirSync(staging, { mode: 0o700 }); - const bytes = artifactBytes('node'), cache = new PublicArchiveCache({ root: path.join(base, 'cache'), stagingRoot: staging, maxBytes: bytes.length }); - const executor = new PreparationExecutor({ cache, runner }), deadline = Date.now() + 60_000; - const closure = await executor.acquire({ plan, admission, snapshot: source, deadline }); - runner.beforePrepare = request => { - expect(request.archives[0].hostPath).not.toBe(cache.get(closure.archives[0].sha256)?.path); - const replacement = Buffer.alloc(bytes.length, 0x78), replacementPath = path.join(staging, 'replacement'); fs.writeFileSync(replacementPath, replacement, { mode: 0o600 }); - cache.promote('replacement', h256(replacement)); - expect(cache.get(closure.archives[0].sha256)).toBeUndefined(); - }; - const prepared = await executor.prepareOffline({ plan, admission, snapshot: source, closure, deadline }); - expect(prepared.dependencyClosureHash).toBe(closure.closureHash); - }); - - test('offline lifecycle source mutation fails closed and disposes the returned execution copy', async () => { - const source=snapshot('node'),plan=inspectPreparation(source,'node'),admission=admitPreparationRuntime({plan,platform:'linux/amd64',catalog:catalog('node')}),runner=new FakeRunner(),executor=new PreparationExecutor({cache:cacheFixture(),runner}),deadline=Date.now()+60_000; - const closure=await executor.acquire({plan,admission,snapshot:source,deadline});runner.mutatePrepared=prepared=>fs.writeFileSync(path.join(prepared,'package.json'),'{}'); - try{await executor.prepareOffline({plan,admission,snapshot:source,closure,deadline});throw new Error('expected lifecycle source mutation to fail');} - catch(error){expect(errorCode(error)).toBe('ISOLATION_FAILED');} - expect(runner.disposed).toHaveLength(1);expect(fs.existsSync(runner.disposed[0])).toBe(false); - }); - - const installManifest = (prepared: string, lockPath: string, manifest: object) => - writeTree(prepared, { [`${lockPath}/package.json`]: JSON.stringify(manifest) }); - async function prepareWith(source: string, install: (prepared: string) => void) { - const plan = inspectPreparation(source, 'node'), admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('node') }); - const runner = new FakeRunner(), executor = new PreparationExecutor({ cache: cacheFixture(), runner }), deadline = Date.now() + 60_000; - const closure = await executor.acquire({ plan, admission, snapshot: source, deadline }); - runner.mutatePrepared = install; - try { return { prepared: await executor.prepareOffline({ plan, admission, snapshot: source, closure, deadline }), runner }; } - catch (error) { return { error, runner }; } - } - function bundledSnapshot(): string { - const base = root('cso-executor-node-bundled-'); - writeTree(base, { - 'package.json': JSON.stringify({ name: 'app', version: '1.0.0', dependencies: { wrapper: '2.0.0' } }), - 'package-lock.json': JSON.stringify({ name: 'app', lockfileVersion: 3, packages: { - '': { name: 'app', version: '1.0.0', dependencies: { wrapper: '2.0.0' } }, - 'node_modules/wrapper': { version: '2.0.0', resolved: 'https://registry.npmjs.org/wrapper/-/wrapper-2.0.0.tgz', integrity: `sha512-${h512(artifactBytes('node'))}`, bundleDependencies: ['child'] }, - 'node_modules/wrapper/node_modules/child': { version: '1.1.0', inBundle: true }, - } }), - }); - return base; - } - test('npm preparation refuses an installed package whose version differs from the lock', async () => { - const { error, runner } = await prepareWith(snapshot('node'), prepared => installManifest(prepared, 'node_modules/cookie', { name: 'cookie', version: '0.9.0' })); - expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); - expect((error as Error).message).toContain('node_modules/cookie'); - expect(runner.disposed).toHaveLength(1); - }); - test('npm preparation refuses an installed package whose name differs from the lock', async () => { - const { error } = await prepareWith(snapshot('node'), prepared => installManifest(prepared, 'node_modules/cookie', { name: 'not-cookie', version: '1.0.0' })); - expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); - }); - test('npm preparation refuses a bundled package whose installed version differs from the lock', async () => { - const { error } = await prepareWith(bundledSnapshot(), prepared => { - installManifest(prepared, 'node_modules/wrapper', { name: 'wrapper', version: '2.0.0' }); - installManifest(prepared, 'node_modules/wrapper/node_modules/child', { name: 'child', version: '1.0.0' }); - }); - expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); - expect((error as Error).message).toContain('node_modules/wrapper/node_modules/child'); - }); - test('npm preparation refuses an installed package the lock does not list', async () => { - const { error } = await prepareWith(bundledSnapshot(), prepared => { - installManifest(prepared, 'node_modules/wrapper', { name: 'wrapper', version: '2.0.0' }); - installManifest(prepared, 'node_modules/wrapper/node_modules/child', { name: 'child', version: '1.1.0' }); - installManifest(prepared, 'node_modules/wrapper/node_modules/@hidden/extra', { name: '@hidden/extra', version: '1.0.0' }); - }); - expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); - expect((error as Error).message).toContain('node_modules/wrapper/node_modules/@hidden/extra is not listed'); - }); - for (const [label, install] of [ - ['invalid JSON', (prepared: string) => writeTree(prepared, { 'node_modules/cookie/package.json': '{not json' })], - ['a directory', (prepared: string) => fs.mkdirSync(path.join(prepared, 'node_modules/cookie/package.json'), { recursive: true })], - ] as const) test(`npm preparation refuses an installed package.json that is ${label}`, async () => { - const { error, runner } = await prepareWith(snapshot('node'), install); - expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); expect(runner.disposed).toHaveLength(1); - }); - for (const [label, install, message] of [ - ['a listed package directory with no package.json', (prepared: string) => writeTree(prepared, { 'node_modules/cookie/index.js': 'module.exports = 1;' }), 'node_modules/cookie has no readable package.json'], - ['an unlisted package directory with no package.json', (prepared: string) => writeTree(prepared, { 'node_modules/extra/index.js': 'module.exports = 1;' }), 'node_modules/extra is not listed'], - ['a loose module file in node_modules', (prepared: string) => writeTree(prepared, { 'node_modules/cookie.js': 'module.exports = 1;' }), 'node_modules/cookie.js is not listed'], - ['an unlisted symlink in node_modules', (prepared: string) => { installManifest(prepared, 'node_modules/cookie', { name: 'cookie', version: '1.0.0' }); fs.symlinkSync('cookie', path.join(prepared, 'node_modules/extra')); }, 'node_modules/extra is not listed'], - ] as const) test(`npm preparation refuses ${label}`, async () => { - const { error, runner } = await prepareWith(snapshot('node'), install); - expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); - expect((error as Error).message).toContain(message); - expect(runner.disposed).toHaveLength(1); - }); - test('npm preparation bounds installed manifest values it echoes in its refusal', async () => { - const { error } = await prepareWith(snapshot('node'), prepared => installManifest(prepared, 'node_modules/cookie', { name: 'x'.repeat(5000), version: 'y'.repeat(5000) })); - expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); - expect((error as Error).message.length).toBeLessThan(400); - expect((error as Error).message).toContain('the lock says cookie@1.0.0'); - }); - test('npm preparation compares versions the way npm normalizes them', async () => { - for (const version of ['v1.0.0', '=1.0.0', ' 1.0.0 ', '1.0.0+build.5', '01.0.0']) { - const { error } = await prepareWith(snapshot('node'), prepared => installManifest(prepared, 'node_modules/cookie', { name: ' cookie ', version })); - expect(error).toBeUndefined(); - } - for (const version of ['v2.0.0', '1.0.0-beta', '1.0', 'latest']) { - const { error } = await prepareWith(snapshot('node'), prepared => installManifest(prepared, 'node_modules/cookie', { name: 'cookie', version })); - expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); - } - }); - test('npm lock identity check honors cancellation and the deadline', () => { - const source = snapshot('node'), plan = inspectPreparation(source, 'node'), prepared = root('cso-executor-identity-'); - installManifest(prepared, 'node_modules/cookie', { name: 'cookie', version: '1.0.0' }); - expect(() => proveNpmLockIdentities(plan, prepared, Date.now() + 60_000)).not.toThrow(); - const controller = new AbortController(); controller.abort(); - for (const [deadline, signal, code] of [[Date.now() + 60_000, controller.signal, 'CANCELLED'], [Date.now() - 1, undefined, 'DEADLINE']] as const) { - let caught: unknown; - try { proveNpmLockIdentities(plan, prepared, deadline, signal); } catch (error) { caught = error; } - expect(errorCode(caught)).toBe(code); - } - }); - test('npm preparation accepts installed packages that match the lock', async () => { - for (const [source, install] of [ - [snapshot('node'), (prepared: string) => installManifest(prepared, 'node_modules/cookie', { name: 'cookie', version: '1.0.0' })], - [snapshot('node'), (prepared: string) => writeTree(prepared, { 'node_modules/.package-lock.json': '{}', 'node_modules/.bin/tool': '' })], - [bundledSnapshot(), (prepared: string) => { - installManifest(prepared, 'node_modules/wrapper', { name: 'wrapper', version: '2.0.0' }); - installManifest(prepared, 'node_modules/wrapper/node_modules/child', { name: 'child', version: '1.1.0' }); - }], - ] as const) { - const { prepared, error } = await prepareWith(source, install); - expect(error).toBeUndefined(); expect(prepared!.preparedManifestHash).toMatch(/^[a-f0-9]{64}$/); - } - }); - - test('Rails PostgreSQL requires and records a same-catalog qualified sidecar', async () => { - const source = snapshot('rails'), plan = inspectPreparation(source, 'rails'), runtimes = catalog('rails', 'postgresql'); - const admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: runtimes }); - const sidecar = admitPreparationSidecar({ platform: 'linux/amd64', catalog: runtimes }); - const runner = new FakeRunner(), executor = new PreparationExecutor({ cache: cacheFixture(), runner }), deadline = Date.now() + 60_000; - const closure = await executor.acquire({ plan, admission, snapshot: source, deadline }); - const prepared = await executor.prepareOffline({ plan, admission, snapshot: source, closure, deadline, database: { adapter: 'postgresql', sidecar } }); - expect(prepared.receipt.network.services).toEqual(['application']); - expect(prepared.database).toEqual({ adapter: 'postgresql', connections: ['primary'], - sidecar: { id: sidecar.runtime.id, image: sidecar.runtime.image } }); - expect(prepared.databaseHash).toBe(runner.offlineRequests[0].databaseHash); - expect(runner.offlineRequests[0].database?.sidecar?.image).toContain('@sha256:'); - }); - - test('the host registry broker rejects unallowlisted and private-address CONNECT requests', async () => { - for (const [allowed, requested] of [['registry.npmjs.org', 'evil.invalid'], ['localhost', 'localhost']] as const) { - let verified = false; - // Bun 1.3.10 can transiently report ENOENT on the first Unix-socket - // connect immediately after a verified listen when many shard processes - // are creating sockets. Retry only that runtime transient against a new - // private socket; every policy error and repeated ENOENT still fails. - for (let attempt = 0; attempt < 3 && !verified; attempt++) { - const base = root('cso-broker-'), socketPath = path.join(base, 'registry.sock'); - const broker = new RegistryEgressBroker(socketPath, [allowed], Date.now() + 30_000, 1024 * 1024); - await broker.start(); - try { - let reply: string; - try { - reply = await new Promise((resolveReply, reject) => { - const socket = net.createConnection({ path: socketPath }); let output = ''; - socket.setTimeout(5_000, () => socket.destroy(new Error('registry broker test connection timed out'))); - socket.once('connect', () => socket.write(`CONNECT ${requested}:443 HTTP/1.1\r\nHost: ${requested}:443\r\n\r\n`)); - socket.on('data', chunk => { output += chunk.toString(); }); socket.once('end', () => resolveReply(output)); socket.once('error', reject); - }); - } catch (error: any) { - if (error?.code === 'ENOENT' && attempt < 2) continue; - throw error; - } - expect(reply).toContain('403 Forbidden'); - expect(() => broker.assertClean()).toThrow(); - expect(broker.contactedHosts.size).toBe(0); - verified = true; - } finally { await broker.close(); } - } - expect(verified).toBe(true); - } - }); - - test('registry broker close cancels and joins a pending DNS task before removing its socket', async () => { - const base = root('cso-broker-close-'), socketPath = path.join(base, 'registry.sock'); - let completeLookup!: (addresses: Array<{ address: string; family: 4 | 6 }>) => void, markLookup!: () => void, cancellations = 0; - const lookupStarted = new Promise(resolve => { markLookup = resolve; }); - const lookup = new Promise>(resolve => { completeLookup = resolve; }); - const broker = new RegistryEgressBroker(socketPath, ['registry.npmjs.org'], Date.now() + 30_000, 1024 * 1024, () => { - markLookup(); return { promise: lookup, cancel: () => { cancellations++; } }; - }); - await broker.start(); - const socket = net.createConnection({ path: socketPath }); socket.on('error', () => {}); - const socketClosed = new Promise(resolve => socket.once('close', () => resolve())); - await new Promise((resolveConnect, reject) => { socket.once('connect', resolveConnect); socket.once('error', reject); }); - socket.write('CONNECT registry.npmjs.org:443 HTTP/1.1\r\nHost: registry.npmjs.org:443\r\n\r\n'); - await lookupStarted; - await Promise.race([broker.close(), Bun.sleep(1_000).then(() => { throw new Error('broker close did not join cancelled DNS work'); })]); - await Promise.race([socketClosed, Bun.sleep(1_000).then(() => { throw new Error('broker client socket remained open after close'); })]); - expect(cancellations).toBe(1); expect(socket.destroyed).toBe(true); expect(fs.existsSync(socketPath)).toBe(false); - completeLookup([{ address: '8.8.8.8', family: 4 }]); await Bun.sleep(10); - expect(broker.contactedHosts.size).toBe(0); - }); - - test('registry broker bounds DNS resolution by the connection deadline', async () => { - const base = root('cso-broker-deadline-'), socketPath = path.join(base, 'registry.sock'); let cancellations = 0, markCancelled!: () => void; - const cancelled = new Promise(resolve => { markCancelled = resolve; }); - const broker = new RegistryEgressBroker(socketPath, ['registry.npmjs.org'], Date.now() + 250, 1024 * 1024, - () => ({ promise: new Promise(() => {}), cancel: () => { cancellations++; markCancelled(); } })); - await broker.start(); - try { - const reply = await new Promise((resolveReply, reject) => { - const socket = net.createConnection({ path: socketPath }); let output = ''; - socket.once('connect', () => socket.write('CONNECT registry.npmjs.org:443 HTTP/1.1\r\nHost: registry.npmjs.org:443\r\n\r\n')); - socket.on('data', chunk => { output += chunk.toString(); }); socket.once('end', () => resolveReply(output)); socket.once('error', reject); - }); - expect(reply).toContain('403 Forbidden'); - await Promise.race([cancelled, Bun.sleep(500).then(() => { throw new Error('registry DNS cancellation did not settle after the deadline response'); })]); - expect(cancellations).toBe(1); expect(() => broker.assertClean()).toThrow(); - } finally { await broker.close(); } - }); - - // Rails acquires ~70 gems in sequence. Under Bun, stream.pipe left each finished - // tunnel's upstream open, so the broker hit its 64-connection limit mid-acquisition. - test('finished registry tunnels release both sockets across more tunnels than the connection limit', async () => { - const base = root('cso-broker-release-'), socketPath = path.join(base, 'registry.sock'); - const registry = net.createServer(upstream => { upstream.on('data', chunk => upstream.write(chunk)); upstream.on('end', () => upstream.end()); }); - await new Promise(resolve => registry.listen(0, '127.0.0.1', resolve)); - const registryPort = (registry.address() as net.AddressInfo).port, dial = net.connect; - const connect = spyOn(net, 'connect').mockImplementation(((options: any, ...rest: any[]) => - dial({ host: '127.0.0.1', port: options?.port === 443 ? registryPort : options?.port }, ...rest)) as typeof net.connect); - const broker = new RegistryEgressBroker(socketPath, ['rubygems.org'], Date.now() + 60_000, 64 * 1024 * 1024, - () => ({ promise: Promise.resolve([{ address: '151.101.1.227', family: 4 as const }]), cancel: () => {} })); - await broker.start(); - try { - for (let index = 0; index < 70; index++) { - const echoed = await new Promise((resolveEcho, reject) => { - const client = net.createConnection({ path: socketPath }); let output = ''; - client.setTimeout(5_000, () => client.destroy(new Error(`tunnel ${index} stalled`))); - client.once('connect', () => client.write('CONNECT rubygems.org:443 HTTP/1.1\r\nHost: rubygems.org:443\r\n\r\n')); - client.on('data', chunk => { - output += chunk.toString(); - if (output === 'HTTP/1.1 200 Connection Established\r\n\r\n') { client.write(`gem-${index}`); return; } - if (output.endsWith(`gem-${index}`)) client.end(); - }); - client.once('close', () => resolveEcho(output)); client.once('error', reject); - }); - expect(echoed).toEndWith(`gem-${index}`); - } - const deadline = Date.now() + 2_000; - while ((broker as any).sockets.size && Date.now() < deadline) await Bun.sleep(10); - expect((broker as any).sockets.size).toBe(0); - expect(() => broker.assertClean()).not.toThrow(); - expect([...broker.contactedHosts]).toEqual(['rubygems.org']); - } finally { - connect.mockRestore(); await broker.close(); await new Promise(resolve => registry.close(() => resolve())); - } - }); - - test('registry address classification rejects mapped, translated, private, and unspecified destinations', () => { - for (const address of ['127.0.0.1', '169.254.169.254', '10.2.3.4', '100.64.0.1']) - expect(isBlockedRegistryAddress(address, 4)).toBe(true); - for (const address of ['::', '::1', '::ffff:127.0.0.1', '::ffff:169.254.169.254', '::ffff:7f00:1', - '64:ff9b::7f00:1', '64:ff9b:1::a9fe:a9fe', '100::1', '2001:db8::1', '2002:7f00:1::', - '3fff::1', 'fc00::1', 'fe80::1', 'fec0::1', 'ff02::1']) - expect(isBlockedRegistryAddress(address, 6)).toBe(true); - expect(isBlockedRegistryAddress('8.8.8.8', 4)).toBe(false); - expect(isBlockedRegistryAddress('2606:4700:4700::1111', 6)).toBe(false); - expect(isBlockedRegistryAddress('not-an-address', 4)).toBe(true); - expect(isBlockedRegistryAddress('127.0.0.1', 6)).toBe(true); - }); - - test('the concrete Docker runner requires the catalog-qualified container helper contract', () => { - const source = snapshot('node'), plan = inspectPreparation(source, 'node'), withoutHelper = catalog('node'); - delete withoutHelper.runtimes[0].versions['cso-preparation']; - expect(() => admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: withoutHelper })).toThrow('MISSING_RUNTIME_TOOL_VERSION'); - const withHelper = catalog('node'); - const admitted = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: withHelper }); - const runner = new DockerPreparationSandboxRunner({ endpoint: {} as any, watchdogPath: '/missing', controlRoot: root('cso-docker-runner-'), admission: admitted }); - expect(runner.qualification).toMatchObject({ runnerId: 'docker-registry-broker-v1', registryRestrictionQualified: true, offlineContainmentQualified: true }); - }); -}); diff --git a/test/cso-preparation-java.test.ts b/test/cso-preparation-java.test.ts deleted file mode 100644 index cb8c32001..000000000 --- a/test/cso-preparation-java.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -/** - * A Java/Maven repository was reported as `stack: python` and asked for a - * requirements.txt, because no supported stack matched and preparation - * defaulted to Python. A root Maven or Gradle build now names the stack as - * Java (unsupported for runtime preparation, so static assessment only), and - * Python helper scripts or metadata beside it do not turn it into Python. - */ -import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { inspectPreparation } from '../lib/cso/preparation'; - -const roots: string[] = []; -afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); - -function fixture(files: Record): string { - const root = mkdtempSync(join(tmpdir(), 'cso-preparation-java-')); - roots.push(root); - for (const [path, contents] of Object.entries(files)) { - mkdirSync(join(root, path, '..'), { recursive: true }); - writeFileSync(join(root, path), contents); - } - return root; -} - -const maven = { - 'pom.xml': '4.0.0aapp1\n', - 'src/main/java/app/App.java': 'package app;\npublic class App { public static void main(String[] a) {} }\n', - 'scripts/release.py': 'print("helper")\n', - 'tools/lint_check.py': 'import sys\n', -}; - -describe('/cso preparation: a Maven repository with helper Python scripts is Java', () => { - test('helper .py scripts only', () => { - const plan = inspectPreparation(fixture(maven)); - expect(plan.stack).toBe('java'); - expect(plan.status).toBe('prerequisites'); - expect(plan.prerequisites).toEqual([{ - code: 'UNSUPPORTED_STACK', - message: 'Java (pom.xml) is not a supported runtime stack yet; supported runtime stacks are Node, Bun, Python, and Rails.', - path: 'pom.xml', - }]); - expect(JSON.stringify(plan)).not.toContain('requirements.txt'); - }); - - test('helper scripts with a root requirements.txt stay Java', () => { - const plan = inspectPreparation(fixture({ ...maven, 'requirements.txt': 'requests==2.32.3\n' })); - expect(plan.stack).toBe('java'); - expect(plan.prerequisites[0]?.code).toBe('UNSUPPORTED_STACK'); - }); - - test('Gradle builds are Java too', () => { - const plan = inspectPreparation(fixture({ 'build.gradle.kts': 'plugins { java }\n', 'scripts/x.py': '' })); - expect(plan.stack).toBe('java'); - expect(plan.prerequisites[0]?.message).toContain('Java (build.gradle.kts)'); - }); - - test('a Python project without a JVM build is still Python (control)', () => { - expect(inspectPreparation(fixture({ 'requirements.txt': 'requests==2.32.3\n', 'app.py': '' })).stack).toBe('python'); - }); -}); diff --git a/test/cso-preparation.test.ts b/test/cso-preparation.test.ts deleted file mode 100644 index 290591123..000000000 --- a/test/cso-preparation.test.ts +++ /dev/null @@ -1,357 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { tmpdir } from 'node:os'; -import { inspectPreparation, railsTestConfiguration } from '../lib/cso/preparation'; -import { assertRuntimeCompatible, RUNTIME_CATALOG, rollbackCatalog, selectRuntime, validateRuntimeCatalog } from '../lib/cso/runtime-catalog'; -import { completeRuntimeCatalogFixture, qualifiedRuntimeFixture, unqualifiedRuntimeCatalog } from './helpers/cso-runtime-catalog'; - -const roots: string[] = []; -const hash = 'a'.repeat(64); -const sri = `sha512-${Buffer.alloc(64, 1).toString('base64')}`; -const CREDENTIAL_ARCHIVE_URL = ['https://user:', 'secret@registry.npmjs.org/a.tgz'].join(''); -function fixture(files: Record): string { - const root = mkdtempSync(join(tmpdir(), 'cso-preparation-')); roots.push(root); - for (const [path, contents] of Object.entries(files)) { - const full = join(root, path); mkdirSync(join(full, '..'), { recursive: true }); - writeFileSync(full, typeof contents === 'string' ? contents : JSON.stringify(contents)); - } - return root; -} -afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); -const nodeFiles = (version = 3) => ({ - 'package.json': { name: 'app', version: '1.0.0', dependencies: { cookie: '1.0.0' }, scripts: { postinstall: 'touch /tmp/CSO_UNSAFE' } }, - 'package-lock.json': { name: 'app', lockfileVersion: version, packages: { '': { name: 'app', version: '1.0.0', dependencies: { cookie: '1.0.0' } }, 'node_modules/cookie': { version: '1.0.0', resolved: 'https://registry.npmjs.org/cookie/-/cookie-1.0.0.tgz', integrity: sri, hasInstallScript: true } } }, -}); -const gemLock = `GEM - remote: https://rubygems.org/ - specs: - rack (3.1.8) - sqlite3 (2.5.0-x86_64-linux-gnu) - -PLATFORMS - ruby - x86_64-linux-gnu - -DEPENDENCIES - rack - sqlite3 - -RUBY VERSION - ruby 3.3.6p108 - -BUNDLED WITH - 2.6.9 -`; - -describe('CSO inert Node preparation', () => { - for (const version of [2, 3]) test(`accepts npm lock v${version} and separates lifecycle execution`, () => { - const plan = inspectPreparation(fixture(nodeFiles(version))); - expect(plan.status).toBe('ready'); expect(plan.stack).toBe('node'); - expect(plan.inputs).toHaveLength(1); expect(plan.inputs[0].integrity).toBe(sri); - expect(plan.metadata.find(m => m.path === 'package.json')!.content).not.toContain('postinstall'); - expect(plan.acquisition[0].args).toContain('--ignore-scripts'); - expect(plan.acquisition[0].args).toContain('--no-audit'); - expect(plan.offline[0].args).toContain('--offline'); - expect(plan.offline[1].args[0]).toBe('rebuild'); - }); - test('rejects lock v1 without emitting executable fragments', () => { - const plan = inspectPreparation(fixture(nodeFiles(1))); - expect(plan.prerequisites[0].code).toBe('UNSUPPORTED_LOCK'); expect(plan.acquisition).toEqual([]); expect(plan.metadata).toEqual([]); - }); - // npm 11 refuses one file loaded as both user and global config ("double-loading config"). - test('every npm command loads distinct empty user and global configs', () => { - const plan = inspectPreparation(fixture(nodeFiles(3))); - const npm = [...plan.acquisition, ...plan.offline].filter(command => command.executable === '/usr/local/bin/npm'); - expect(npm.length).toBeGreaterThanOrEqual(3); - for (const command of npm) { - const value = (flag: string) => command.args[command.args.indexOf(flag) + 1]; - expect([value('--userconfig'), value('--globalconfig')]).toEqual(['/opt/cso/empty-config', '/opt/cso/empty-globalconfig']); - } - expect(readFileSync(join(import.meta.dir, '../lib/cso/images/node.Dockerfile'), 'utf8')).toContain('touch /opt/cso/empty-config /opt/cso/empty-globalconfig'); - }); - for (const url of [CREDENTIAL_ARCHIVE_URL, 'http://registry.npmjs.org/a.tgz', 'https://registry.npmjs.org.evil.invalid/a.tgz', 'https://127.0.0.1/a.tgz', 'git+ssh://github.com/a/b', 'https://registry.npmjs.org/a.tgz?token=secret']) test(`rejects non-public archive ${url.split('@').at(-1)}`, () => { - const files = nodeFiles(); files['package-lock.json'].packages['node_modules/cookie'].resolved = url; - const plan = inspectPreparation(fixture(files)); expect(plan.status).toBe('prerequisites'); expect(plan.acquisition).toEqual([]); - }); - const bundledFiles = () => { - const files: any = nodeFiles(); - const packages = files['package-lock.json'].packages; - packages['node_modules/@tailwindcss/oxide-wasm32-wasi'] = { version: '4.1.11', resolved: 'https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.1.11.tgz', integrity: sri, bundleDependencies: ['@emnapi/core', 'tslib'], optional: true }; - packages['node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core'] = { version: '1.4.3', inBundle: true, optional: true, dependencies: { '@emnapi/wasi-threads': '1.0.2' } }; - packages['node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/node_modules/@emnapi/wasi-threads'] = { version: '1.0.2', inBundle: true, optional: true }; - packages['node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib'] = { version: '2.8.0', inBundle: true, license: '0BSD', optional: true }; - return files; - }; - test('accepts bundled npm entries covered by their parent archive', () => { - const plan = inspectPreparation(fixture(bundledFiles())); - expect(plan.status).toBe('ready'); - expect(plan.inputs.map(i => i.name).sort()).toEqual(['@tailwindcss/oxide-wasm32-wasi', 'cookie']); - }); - for (const [label, edit] of [ - ['missing', ({ 'package-lock.json': { packages: p } }: any) => { delete p['node_modules/@tailwindcss/oxide-wasm32-wasi']; }], - ['unresolved', ({ 'package-lock.json': { packages: p } }: any) => { delete p['node_modules/@tailwindcss/oxide-wasm32-wasi'].resolved; }], - ['unhashed', ({ 'package-lock.json': { packages: p } }: any) => { p['node_modules/@tailwindcss/oxide-wasm32-wasi'].integrity = 'sha1-weak'; }], - ['off-registry', ({ 'package-lock.json': { packages: p } }: any) => { p['node_modules/@tailwindcss/oxide-wasm32-wasi'].resolved = 'https://evil.invalid/oxide.tgz'; }], - ['workspace link', (files: any) => { const p = files['package-lock.json'].packages; p['node_modules/@tailwindcss/oxide-wasm32-wasi'] = { resolved: 'packages/local', link: true }; p['packages/local'] = { name: 'local', version: '1.0.0' }; files['packages/local/package.json'] = { name: 'local', version: '1.0.0' }; }], - ['itself bundled without an archive', ({ 'package-lock.json': { packages: p } }: any) => { p['node_modules/@tailwindcss/oxide-wasm32-wasi'] = { version: '4.1.11', inBundle: true }; }], - ] as const) test(`rejects a bundled npm entry whose parent is ${label}`, () => { - const files = bundledFiles(); edit(files); - const plan = inspectPreparation(fixture(files)); - expect(plan.status).toBe('prerequisites'); expect(plan.acquisition).toEqual([]); - }); - test('rejects a bundled npm entry with no parent package', () => { - const files: any = nodeFiles(); - files['package-lock.json'].packages['node_modules/tslib'] = { version: '2.8.0', inBundle: true }; - const plan = inspectPreparation(fixture(files)); - expect(plan.prerequisites[0].code).toBe('UNPINNED_ARCHIVE'); expect(plan.acquisition).toEqual([]); - }); - test('keeps refusing a non-bundled npm entry without a resolved archive', () => { - const files: any = bundledFiles(); - delete files['package-lock.json'].packages['node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib'].inBundle; - const plan = inspectPreparation(fixture(files)); - expect(plan.prerequisites[0].code).toBe('UNPINNED_ARCHIVE'); expect(plan.acquisition).toEqual([]); - }); - test('still validates a bundled npm entry that names its own archive', () => { - const files: any = bundledFiles(); - files['package-lock.json'].packages['node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib'].resolved = 'https://evil.invalid/tslib.tgz'; - const plan = inspectPreparation(fixture(files)); - expect(plan.prerequisites[0].code).toBe('UNSUPPORTED_SOURCE'); expect(plan.acquisition).toEqual([]); - }); - test('rejects archive without cryptographic integrity', () => { - const files = nodeFiles(); files['package-lock.json'].packages['node_modules/cookie'].integrity = 'sha1-weak'; - expect(inspectPreparation(fixture(files)).prerequisites[0].code).toBe('UNPINNED_ARCHIVE'); - }); - test('rejects hostile workspace paths before package-manager invocation', () => { - const files: any = nodeFiles(); files['package.json'].workspaces = ['../../host/*']; - expect(inspectPreparation(fixture(files)).prerequisites[0].code).toBe('EXTERNAL_PATH'); - }); - test('contains and sanitizes declared workspaces', () => { - const files: any = nodeFiles(); - files['package.json'].workspaces = ['packages/*']; - files['package-lock.json'].packages['packages/local'] = { name: 'local', version: '1.0.0' }; - files['package-lock.json'].packages['node_modules/local'] = { resolved: 'packages/local', link: true }; - files['packages/local/package.json'] = { name: 'local', version: '1.0.0', scripts: { install: 'false' } }; - const plan = inspectPreparation(fixture(files)); expect(plan.status).toBe('ready'); - expect(plan.inputs.some(i => i.kind === 'local')).toBe(true); - expect(plan.metadata.find(m => m.path === 'packages/local/package.json')!.content).not.toContain('scripts'); - }); - test('never follows metadata symlinks', () => { - const root = fixture({ 'secret.json': nodeFiles()['package.json'] }); symlinkSync('secret.json', join(root, 'package.json')); - const plan = inspectPreparation(root); expect(plan.status).toBe('prerequisites'); expect(plan.prerequisites[0].code).toBe('UNSAFE_METADATA'); - }); -}); - -describe('CSO inert Bun preparation', () => { - test('accepts text locks with trailing commas and ignores scripts online', () => { - const plan = inspectPreparation(fixture({ - 'package.json': nodeFiles()['package.json'], - 'bun.lock': `{"lockfileVersion":1,"workspaces":{"":{"name":"app","dependencies":{"cookie":"1.0.0",},},},"packages":{"cookie":["cookie@1.0.0","",{},"${sri}"],},}`, - 'bunfig.toml': 'preload = ["./hostile.ts"]', - })); - expect(plan.status).toBe('ready'); expect(plan.stack).toBe('bun'); - expect(plan.acquisition[0].args).toContain('--frozen-lockfile'); expect(plan.acquisition[0].args).toContain('--ignore-scripts'); - expect(plan.acquisition[0].args).toContain('--config=/opt/cso/empty-config'); expect(plan.acquisition[0].args).toContain('--registry=https://registry.npmjs.org'); - expect(plan.offline[0].args).toContain('--backend=copyfile'); - expect(plan.metadata.some(m => m.path === 'bunfig.toml')).toBe(false); - }); - test('does not treat lock text as JavaScript', () => { - const plan = inspectPreparation(fixture({ 'bun.lock': '({workspaces: (()=>{throw Error("EXECUTED")})()})' })); - expect(plan.prerequisites[0].code).toBe('INVALID_METADATA'); - }); - test('reports binary lock prerequisite', () => { - expect(inspectPreparation(fixture({ 'bun.lockb': 'binary', 'package.json': {} })).prerequisites[0].code).toBe('UNSUPPORTED_LOCK'); - }); -}); - -describe('CSO inert Python preparation', () => { - test('requires exact hashed wheels and excludes target config', () => { - const plan = inspectPreparation(fixture({ 'requirements.txt': `# generated pins\nFlask==3.1.0 \\\n --hash=sha256:${hash}\n`, 'pip.conf': '[global]\nextra-index-url=https://evil.invalid' })); - expect(plan.status).toBe('ready'); expect(plan.inputs[0].name).toBe('Flask'); - expect(plan.acquisition[0].args).toContain('--only-binary=:all:'); expect(plan.acquisition[0].args).toContain('--require-hashes'); - expect(plan.metadata).toHaveLength(1); expect(plan.offline[1].args).toContain('--no-index'); - }); - test('offline Python preparation writes reproducible checked-hash bytecode', () => { - const plan = inspectPreparation(fixture({ 'requirements.txt': `Flask==3.1.0 --hash=sha256:${hash}\n` })); - expect(plan.status).toBe('ready'); - // venv/ensurepip and pip compile .pyc files; without a fixed epoch each preparation differs and replay cannot match. - for (const command of plan.offline) expect(command.env.SOURCE_DATE_EPOCH).toMatch(/^[0-9]+$/); - }); - for (const requirement of ['flask>=3', '-e .', 'flask @ https://evil.invalid/x.whl', '--index-url https://evil.invalid', '-r other.txt', 'flask==3.1.0']) test(`rejects unpinned or executable requirement ${requirement}`, () => { - expect(inspectPreparation(fixture({ 'requirements.txt': requirement })).prerequisites[0].code).toBe('UNPINNED_REQUIREMENTS'); - }); - const uvFixture = () => ({ - 'uv.lock': `version = 1\nrequires-python = ">=3.12"\n[[package]]\nname = "app"\nversion = "1.0.0"\nsource = { editable = "." }\n[[package]]\nname = "flask"\nversion = "3.1.0"\nsource = { registry = "https://pypi.org/simple" }\nwheels = [{url = "https://files.pythonhosted.org/packages/flask.whl", hash = "sha256:${hash}"}]\n`, - 'pyproject.toml': '[project]\nname="app"\nversion="1.0.0"\ndependencies=["flask==3.1.0"]\n[build-system]\nrequires=[]\nbuild-backend="evil_backend"\n', - }); - test('uv explicitly omits first-party packages during online export', () => { - const plan = inspectPreparation(fixture(uvFixture())); expect(plan.status).toBe('ready'); - expect(plan.acquisition[0].args).toContain('--no-emit-local'); expect(plan.acquisition[0].args).toContain('--frozen'); - expect(plan.metadata.find(m => m.path === 'pyproject.toml')!.content).not.toContain('evil_backend'); - expect(plan.offline[0].args).toContain('--offline'); - expect(plan.offline.some(command => command.args.includes('--require-hashes'))).toBe(true); - expect(plan.offline.find(c => c.args.includes('--no-build-isolation'))!.args).toContain('/work/.'); - expect(plan.inputs.some(i => i.kind === 'local' && i.path === '.')).toBe(true); - }); - test('uv rejects local packages outside the snapshot', () => { - const files = uvFixture(); files['uv.lock'] = files['uv.lock'].replace('editable = "."', 'editable = "../private"'); - expect(inspectPreparation(fixture(files)).prerequisites[0].code).toBe('EXTERNAL_PATH'); - }); - test('uv rejects public dependencies with only source distributions', () => { - const files = uvFixture(); files['uv.lock'] = files['uv.lock'].replace(/wheels = .*/, 'wheels = []'); - expect(inspectPreparation(fixture(files)).prerequisites[0].code).toBe('MISSING_PUBLIC_WHEEL'); - }); - test('uv reports cross-platform marker locks as a readiness prerequisite', () => { - const files = uvFixture(); - files['uv.lock'] = files['uv.lock'].replace('[[package]]\nname = "flask"', `[[package]]\nname = "colorama"\nversion = "0.4.6"\nsource = { registry = "https://pypi.org/simple" }\nwheels = [{url = "https://files.pythonhosted.org/packages/colorama.whl", hash = "sha256:${hash}"}]\ndependencies = [{ name = "win32", marker = "sys_platform == 'win32'" }]\n[[package]]\nname = "flask"`); - const plan = inspectPreparation(fixture(files)); - expect(plan.status).toBe('prerequisites'); - expect(plan.prerequisites.some(item => item.code === 'UNSUPPORTED_MARKER')).toBe(true); - }); - test('uv requires exact public wheels for every local build dependency', () => { - const files = uvFixture(); files['pyproject.toml'] = files['pyproject.toml'].replace('requires=[]', 'requires=["setuptools>=40.8.0"]'); - expect(inspectPreparation(fixture(files)).prerequisites[0].code).toBe('MISSING_BUILD_DEPENDENCY'); - }); -}); - -describe('CSO preparation names a Go module as Go (#3263)', () => { - const goFiles = { - 'go.mod': 'module example.com/app\n\ngo 1.23\n\nrequire github.com/google/uuid v1.6.0\n', - 'go.sum': 'github.com/google/uuid v1.6.0 h1:abc=\n', - 'main.go': 'package main\n\nfunc main() {}\n', - }; - const GO_UNSUPPORTED = { code: 'UNSUPPORTED_STACK', message: 'Go (go.mod) is not a supported runtime stack yet; supported runtime stacks are Node, Bun, Python, and Rails.', path: 'go.mod' }; - test('a go.mod repository is Go, unsupported, and never asks for requirements.txt', () => { - const plan = inspectPreparation(fixture(goFiles)); - expect([plan.stack, plan.runtimeProfile, plan.status]).toEqual(['go', 'go', 'prerequisites']); - expect(plan.prerequisites).toEqual([GO_UNSUPPORTED]); - expect(JSON.stringify(plan)).not.toContain('requirements.txt'); - }); - test('Python helper metadata beside go.mod stays Go', () => { - const plan = inspectPreparation(fixture({ ...goFiles, 'requirements.txt': `mkdocs==1.6.1 --hash=sha256:${hash}\n` })); - expect(plan.stack).toBe('go'); - expect(plan.prerequisites).toEqual([GO_UNSUPPORTED]); - }); - test('controls: go.mod beside a Node lockfile stays Node; Python without go.mod stays Python', () => { - const node = inspectPreparation(fixture({ ...goFiles, ...nodeFiles() })); - expect([node.stack, node.status]).toEqual(['node', 'ready']); - expect(inspectPreparation(fixture({ 'requirements.txt': `Flask==3.1.0 --hash=sha256:${hash}\n` })).stack).toBe('python'); - expect(inspectPreparation(fixture({ 'go.sum': '', 'main.go': '' })).stack).toBe('python'); - }); -}); - -describe('CSO inert Rails preparation', () => { - test('does not silently choose Node in a multi-stack repository',()=>{const plan=inspectPreparation(fixture({...nodeFiles(),'Gemfile.lock':gemLock,'Gemfile':''}));expect(plan.status).toBe('prerequisites');expect(plan.prerequisites[0].code).toBe('MULTIPLE_STACKS');expect(inspectPreparation(fixture({...nodeFiles(),'Gemfile.lock':gemLock,'Gemfile':''}),'rails').stack).toBe('rails');}); - test('fetches exact gems without evaluating Gemfiles or building native extensions', () => { - const plan = inspectPreparation(fixture({ 'Gemfile.lock': gemLock, 'Gemfile': 'system("touch /tmp/CSO_UNSAFE")\nsource "https://rubygems.org"' })); - expect(plan.status).toBe('ready'); expect(plan.stack).toBe('rails'); expect(plan.metadata.some(m => m.path === 'Gemfile')).toBe(false); - expect(plan.acquisition).toHaveLength(2); expect(plan.acquisition.every(c => c.args[0] === 'fetch')).toBe(true); - // One gem process per platform: each process loads the full RubyGems index once. - for (const command of plan.acquisition) { - const platform = command.args[command.args.indexOf('--platform') + 1]; - expect(command.args.slice(1, command.args.indexOf('--platform'))).toEqual(plan.inputs.filter(input => input.platform === platform).map(input => `${input.name}:${input.version}`)); - expect(command.args).not.toContain('--version'); - } - expect(plan.inputs[1].platform).toBe('x86_64-linux-gnu'); expect(plan.inputs[0].integritySource).toBe('registry-on-acquisition'); - expect(plan.runtimeRequirements).toEqual({ ruby: '3.3.6', bundler: '2.6.9' }); - expect(plan.offline[0].args).toContain('--local'); expect(plan.offline[0].env.BUNDLE_IGNORE_CONFIG).toBe('true'); - // Parallel Bundler threads race RubyGems' File.umask calls and leave 0777 directories. - expect(plan.offline[0].args.slice(plan.offline[0].args.indexOf('--jobs'), plan.offline[0].args.indexOf('--jobs') + 2)).toEqual(['--jobs', '1']); - expect(plan.offline[0].env.GEM_HOME).toBeUndefined(); expect(plan.offline[0].env.GEM_PATH).toBeUndefined(); - }); - test('records lock checksums separately from newly acquired archive hashes', () => { - const plan = inspectPreparation(fixture({ 'Gemfile.lock': gemLock + `\nCHECKSUMS\n rack (3.1.8) sha256=${hash}\n`, 'Gemfile': '' })); - expect(plan.status).toBe('ready'); expect(plan.inputs[0].integrity).toBe(`sha256:${hash}`); expect(plan.inputs[0].integritySource).toBe('lock'); - }); - for (const section of ['GIT', 'PATH', 'PLUGIN']) test(`rejects ${section} sources`, () => { - expect(inspectPreparation(fixture({ 'Gemfile.lock': gemLock + `\n${section}\n remote: https://evil.invalid\n`, 'Gemfile': '' })).prerequisites[0].code).toBe('UNSUPPORTED_SOURCE'); - }); - test('enumerates every static connection without evaluating ERB', () => { - const plan = inspectPreparation(fixture({ 'Gemfile.lock': gemLock, 'Gemfile': '', 'config/database.yml': `test:\n primary:\n adapter: sqlite3\n database: <%= ENV["DATABASE_URL"] %>\n queue:\n adapter: postgresql\nproduction:\n analytics:\n adapter: postgresql\n` })); - expect(plan.status).toBe('ready'); expect(plan.database?.connections).toEqual(['analytics', 'primary', 'queue']); - for (const adapter of ['sqlite', 'postgresql'] as const) { - const files = railsTestConfiguration(plan.database!.connections, adapter); - const database = JSON.parse(files[0].content); expect(Object.keys(database.test)).toHaveLength(3); expect(database.production).toBeUndefined(); - expect(files.map(f => f.content).join('')).not.toContain('ENV["DATABASE_URL"]'); - } - }); - test('accepts the stock Rails default anchor without expanding arbitrary YAML aliases',()=>{ - const database=`default: &default\n adapter: sqlite3\n pool: 5\ntest:\n <<: *default\n database: storage/test.sqlite3\nproduction:\n primary:\n <<: *default\n database: storage/primary.sqlite3\n queue:\n <<: *default\n database: storage/queue.sqlite3\n`; - const plan=inspectPreparation(fixture({'Gemfile.lock':gemLock,'Gemfile':'','config/database.yml':database}),'rails'); - expect(plan.status).toBe('ready');expect(plan.database).toMatchObject({supported:['sqlite'],selected:'sqlite',connections:['primary','queue']}); - const hostile=database.replace('primary:\n','primary: &primary\n').replace('queue:\n','queue:\n <<: *primary\n'); - expect(inspectPreparation(fixture({'Gemfile.lock':gemLock,'Gemfile':'','config/database.yml':hostile}),'rails').prerequisites[0].code).toBe('DYNAMIC_DATABASE_CONFIG'); - }); - test('advertises and selects only database adapters actually present in the lock',()=>{ - const pgLock=gemLock.replace('sqlite3 (2.5.0-x86_64-linux-gnu)','pg (1.5.9)').replace(/sqlite3/g,'pg'); - const pg=inspectPreparation(fixture({'Gemfile.lock':pgLock,'Gemfile':'','config/database.yml':'test:\n adapter: postgresql\n database: app_test\n'}),'rails'); - expect(pg.status).toBe('ready');expect(pg.database).toMatchObject({supported:['postgresql'],selected:'postgresql'}); - const noAdapter=gemLock.replace(' sqlite3 (2.5.0-x86_64-linux-gnu)\n','').replace(' sqlite3\n',''); - expect(inspectPreparation(fixture({'Gemfile.lock':noAdapter,'Gemfile':''}),'rails').prerequisites[0].code).toBe('MISSING_DATABASE_ADAPTER'); - }); - test('structural ERB requires explicit synthetic connection names', () => { - const plan = inspectPreparation(fixture({ 'Gemfile.lock': gemLock, 'Gemfile': '', 'config/database.yml': '<% dynamic_config %>\n' })); - expect(plan.prerequisites[0].code).toBe('DYNAMIC_DATABASE_CONFIG'); expect(plan.acquisition).toEqual([]); - }); - test('rejects prototype-mutating synthetic connection names', () => { - expect(() => railsTestConfiguration(['__proto__'], 'sqlite')).toThrow('Invalid Rails connection names'); - }); -}); - -describe('CSO runtime catalog admission', () => { - const runtime = () => qualifiedRuntimeFixture('node'); - const catalog = () => completeRuntimeCatalogFixture('test-1'); - test('default catalog admits only digest-pinned reviewed profiles and unqualified profiles cannot execute', () => { - expect(RUNTIME_CATALOG.profiles).toHaveLength(10); - for (const runtime of RUNTIME_CATALOG.runtimes) { - expect(RUNTIME_CATALOG.profiles.filter(profile => profile.id === runtime.id && profile.stack === runtime.stack && profile.platform === runtime.platform)).toHaveLength(1); - expect(runtime.image).toMatch(/@sha256:[a-f0-9]{64}$/); - } - expect(() => selectRuntime('node', 'linux/amd64', unqualifiedRuntimeCatalog())).toThrow('Reviewed build profile node-24.4.0-amd64 is awaiting a qualified image promotion'); - }); - test('selects exact qualified digest and platform', () => { - expect(selectRuntime('node', 'linux/amd64', catalog()).image).toContain('@sha256:'); - expect(selectRuntime('node', 'linux/arm64', catalog()).platform).toBe('linux/arm64'); - expect(() => selectRuntime('missing', 'linux/arm64', catalog())).toThrow('MISSING_QUALIFIED_RUNTIME'); - }); - test('runtime stack and declared tool versions must match preparation',()=>{const files:any=nodeFiles();files['package.json'].engines={node:'>=24 <25'};files['package.json'].packageManager='npm@^11.0.0';const plan=inspectPreparation(fixture(files),'node'),good=runtime();expect(()=>assertRuntimeCompatible(plan,good)).not.toThrow();good.versions.node='23.9.0';expect(()=>assertRuntimeCompatible(plan,good)).toThrow('does not satisfy');const wrong={...runtime(),stack:'python' as const,versions:{python:'3.12.1',uv:'0.8.0'}};expect(()=>assertRuntimeCompatible(plan,wrong)).toThrow('cannot run');}); - test('a Bun-backed node fallback cannot satisfy a declared Node engine', () => { - const plan = inspectPreparation(fixture({ - 'package.json': { name: 'app', version: '1.0.0', engines: { node: '>=24' } }, - 'bun.lock': `{"lockfileVersion":1,"workspaces":{"":{"name":"app"}},"packages":{}}`, - }), 'bun'); - expect(plan.status).toBe('ready'); - const bunRuntime = { - ...runtime(), id: 'bun-qualified-test', stack: 'bun' as const, - versions: { bun: '1.3.10', 'cso-preparation': '1.0.0' }, - }; - expect(() => assertRuntimeCompatible(plan, bunRuntime)).toThrow('does not declare a real node release'); - }); - test('rejects tags and missing qualification evidence', () => { - const c = catalog(); c.runtimes[0].image = 'node:latest'; expect(() => validateRuntimeCatalog(c)).toThrow('UNQUALIFIED_RUNTIME'); - c.runtimes[0] = runtime(); (c.runtimes[0].qualification as any).heldOutRepairPassed = false; expect(() => validateRuntimeCatalog(c)).toThrow('MISSING_APPLICATION_QUALIFICATION'); - }); - test('qualification evidence is exact and specific to application and PostgreSQL roles', () => { - const missingVerifierEvidence=catalog();delete (missingVerifierEvidence.runtimes[0].qualification as any).positiveNegativeAssertionsPassed; - expect(()=>validateRuntimeCatalog(missingVerifierEvidence)).toThrow('MISSING_APPLICATION_QUALIFICATION'); - const application=catalog();(application.runtimes[0].qualification as any).multiDatabasePassed=true; - expect(()=>validateRuntimeCatalog(application)).toThrow('MISSING_APPLICATION_QUALIFICATION'); - const valid=catalog();expect(()=>validateRuntimeCatalog(valid)).not.toThrow(); - const postgresql=valid.runtimes.find(item=>item.stack==='postgresql'&&item.platform==='linux/amd64')!; - (postgresql.qualification as any).heldOutRepairPassed=true; - expect(()=>validateRuntimeCatalog(valid)).toThrow('MISSING_POSTGRESQL_QUALIFICATION'); - const standaloneVerifier=catalog();Object.assign(standaloneVerifier.runtimes[0],{stack:'verifier',versions:{verifier:'1.0.0'}}); - expect(()=>validateRuntimeCatalog(standaloneVerifier)).toThrow('UNSUPPORTED_RUNTIME_PLATFORM'); - }); - test('rejects partial nonempty catalogs and images outside the promoted gstack namespace', () => { - const partial = catalog(); partial.runtimes = [partial.runtimes[0]]; - expect(() => validateRuntimeCatalog(partial)).toThrow('INCOMPLETE_QUALIFIED_RUNTIME_MATRIX'); - const arbitrary = catalog(); arbitrary.runtimes[0].image = `ghcr.io/attacker/forged@sha256:${hash}`; - expect(() => validateRuntimeCatalog(arbitrary)).toThrow('UNQUALIFIED_RUNTIME'); - }); - test('rollback requires the previous compatible helper/catalog pair', () => { - const previous = catalog(); const current = completeRuntimeCatalogFixture('test-2', 'test-1'); - expect(rollbackCatalog(current, previous)).toBe(previous); - expect(() => rollbackCatalog({ ...current, previousRevision: 'other' }, previous)).toThrow('INCOMPATIBLE_RUNTIME_ROLLBACK'); - }); -}); diff --git a/test/cso-preserved.test.ts b/test/cso-preserved.test.ts deleted file mode 100644 index 4d7e07355..000000000 --- a/test/cso-preserved.test.ts +++ /dev/null @@ -1,107 +0,0 @@ -/** Security-critical CSO routing/proof policy must remain in the always-loaded controller. */ -import { describe, test, expect } from 'bun:test'; -import * as fs from 'fs'; -import * as path from 'path'; -import { expectMentions, expectTokens } from './helpers/prompt-structure'; - -const ROOT = path.resolve(import.meta.dir, '..'); -const controller = () => fs.readFileSync(path.join(ROOT, 'cso/SKILL.md'), 'utf8'); -const template = () => fs.readFileSync(path.join(ROOT, 'cso/SKILL.md.tmpl'), 'utf8'); -const domain = () => fs.readFileSync(path.join(ROOT, 'cso/sections/audit-phases.md'), 'utf8'); - -describe('CSO v3 always-loaded policy', () => { - test('dispatch and execution boundaries are available before a host section read', () => { - const text = controller(); - const stop = text.indexOf('> **STOP.**'); - for (const directive of ['## Arguments', '## Mode Resolution', '**Private startup.**', 'untrusted evidence']) { - expect(text.indexOf(directive)).toBeGreaterThan(-1); - if (stop >= 0) expect(text.indexOf(directive)).toBeLessThan(stop); - } - for (const phase of [0, 1, 12, 13, 14]) expect(text).toContain(`### Phase ${phase}:`); - }); - - test('every scope and lifecycle entrypoint survives host generation', () => { - const text = controller(); - for (const flag of ['--infra', '--code', '--skills', '--supply-chain', '--owasp', '--scope', '--diff', '--base', '--budget', '--offline', '--comprehensive', '--doctor', '--resume', '--replay', '--recheck']) { - expect(text).toContain(flag); - } - expect(text).toContain('mutually exclusive'); - for (const command of ['start', 'doctor', 'resume', 'replay', 'recheck', 'inspect', 'read', 'history', 'scan', 'import-sarif', 'submit', 'verify', 'finish', 'import-v2', 'inspect-v2', 'schema']) { - expect(text).toContain(`gstack-cso ${command}`); - } - }); - - test('CSO cannot acquire shared preamble execution or content-export hooks', () => { - for (const forbidden of ['{{PREAMBLE}}', '{{GBRAIN_CONTEXT_LOAD}}', '{{GBRAIN_SAVE_RESULTS}}', '{{LEARNINGS_SEARCH}}', '{{LEARNINGS_LOG}}', '{{CONFIDENCE_CALIBRATION}}']) { - expect(template()).not.toContain(forbidden); - } - const text = controller(); - expect(text).not.toContain('gstack-skill-start'); - expect(text).not.toContain('gstack-telemetry-log'); - expect(text).not.toContain('gstack-review-log'); - expectMentions(text, [['do not', 'harnesses', 'findings']], 'text'); - expect(text).toContain('trusted installed gstack distribution'); - }); - - test('static review cannot acquire tested or current-source closure labels', () => { - const text = controller(); - for (const proof of ['CSO evidence rubric', 'identical security assertion', 'legitimate control passes', 'pristine second copy', 'before/after configuration and dependency closures', 'boundary-replacing mocks', 'legacy review evidence', 'new evidence covering the same root cause']) { - expect(text).toContain(proof); - } - expectMentions(text, [['cannot', 'application', 'establish']], 'text'); - }); - - test('runtime and scanner execution claims require qualified catalog profiles', () => { - const text = controller(); - expectMentions(text, [['without', 'assessment', 'available']], 'text'); - expect(text).toContain('matching qualified runtime catalog profile'); - expect(text).toContain('Project-test completion remains `self_reported`'); - expectTokens(text, ['`tested`'], 'text'); - expectMentions(text, [['until', 'target-independent', 'completion']], 'text'); - expect(domain()).toContain('matching qualified scanner catalog profile'); - }); - - test('sensitive helper control files stay out of the audited working tree', () => { - const text = controller(); - for (const proof of ['Private control files', 'umask 077', 'mode-`0700`', 'mode-`0600`', 'outside the audited repository', 'remove each control file immediately']) expect(text).toContain(proof); - for (const proof of ['Audited-source access invariant', "only with that run's `inspect`, `read`, `search`, and `history`", 'exact `path` from `inspect`', '`displayPath` is only a redacted label', 'Never use host `Read`/`Glob`/`Grep`', 'direct reads bypass']) expect(text).toContain(proof); - for (const proof of ["copy every record's `domain` and `scope` exactly", 'a new scope leaves the planned scope unassessed', 'Only helper commands may update helper-owned records']) expect(text).toContain(proof); - }); - - test('supported findings are persisted and surfaced before the final report', () => { - const text = controller(); - expect(text).toContain('Invoke `start` exactly once'); - expect(text).toContain('never call `start` again'); - expect(text).toContain('same ID'); - expect(text).toContain('submit it to the helper **and surface it to the user immediately**'); - expectMentions(text, [['do not', 'report', 'final']], 'text'); - expect(text).toContain('if the run is interrupted'); - }); - - test('empty, partial, redaction failure, persistence failure and expiry stay truthful', () => { - const text = controller(); - for (const contract of ['**complete**, **partial**, or **not assessed**', 'No supported findings in the assessed scope.', 'PERSISTENCE_FAILED', 'MISSING_INPUT', 'withhold the payload entirely', 'one bounded correction attempt', 'seven days', 'thirty days']) { - expect(text).toContain(contract); - } - expect(text).toContain('outside synchronization allowlists'); - }); - - test('obsolete blanket exclusions and certainty scores are absent', () => { - const text = controller() + domain(); - for (const obsolete of ['8/10 confidence gate', '2/10 confidence gate', 'devDependency CVEs are MEDIUM max', "gstack's own skills are trusted", 'User content in the user-message position of an AI conversation is NOT prompt injection', 'pull_request_target` without PR ref checkout is safe', 'Hard exclusions — automatically discard']) { - expect(text).not.toContain(obsolete); - } - expect(text).toContain('Unknown reachability remains'); - expect(text).toContain('sequential challenge; independent agent unavailable'); - }); - - test('controller stays compact without moving proof policy behind a section read', () => { - expect(Buffer.byteLength(template())).toBeLessThan(18_000); - expect(Buffer.byteLength(controller())).toBeLessThan(20_000); - expect(Buffer.byteLength(controller() + domain())).toBeLessThan(36_000); - const frontmatter = controller().match(/^---\n([\s\S]*?)\n---/)![1]; - const description = frontmatter.match(/^description:\s+(.+)$/m)![1].trim(); - expect(description.length).toBeLessThanOrEqual(200); - expect(description).toContain('(gstack)'); - }); -}); diff --git a/test/cso-public-ghcr.test.ts b/test/cso-public-ghcr.test.ts deleted file mode 100644 index 46aea71a6..000000000 --- a/test/cso-public-ghcr.test.ts +++ /dev/null @@ -1,145 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { - assertPublicPackageMetadata, - parsePublicGhcrTarget, - verifyPublicGhcrImage, - type PublicGhcrDependencies, -} from '../scripts/cso-public-ghcr'; - -const HASH = 'a'.repeat(64); -const IMAGE = `ghcr.io/garrytan/gstack/cso-staging/node-amd64@sha256:${HASH}`; - -describe('CSO public GHCR release proof', () => { - test('binds an exact CSO package and digest to its declared platform', () => { - expect(parsePublicGhcrTarget(IMAGE, 'linux/amd64', 'GarryTan/GStack')).toEqual({ - image: IMAGE, - owner: 'garrytan', - repository: 'gstack', - packageName: 'gstack/cso-staging/node-amd64', - digest: `sha256:${HASH}`, - platform: 'linux/amd64', - }); - expect(parsePublicGhcrTarget( - `ghcr.io/garrytan/gstack/cso-scanners/semgrep-arm64@sha256:${HASH}`, - 'linux/arm64', - 'garrytan/gstack', - ).packageName).toBe('gstack/cso-scanners/semgrep-arm64'); - }); - - test('rejects tags, foreign repositories, unknown packages, and platform substitution', () => { - for (const [image, platform, repository] of [ - ['ghcr.io/garrytan/gstack/cso-staging/node-amd64:latest', 'linux/amd64', 'garrytan/gstack'], - [IMAGE.replace('garrytan/gstack', 'attacker/gstack'), 'linux/amd64', 'garrytan/gstack'], - [IMAGE.replace('node-amd64', 'unknown-amd64'), 'linux/amd64', 'garrytan/gstack'], - [IMAGE, 'linux/arm64', 'garrytan/gstack'], - ]) expect(() => parsePublicGhcrTarget(image, platform, repository)).toThrow(); - }); - - test('accepts only exact public container metadata for the expected owner', () => { - const target = parsePublicGhcrTarget(IMAGE, 'linux/amd64', 'garrytan/gstack'); - const valid = { name: target.packageName, package_type: 'container', visibility: 'public', owner: { login: 'GarryTan' } }; - expect(() => assertPublicPackageMetadata(valid, target)).not.toThrow(); - for (const mutation of [ - { ...valid, visibility: 'private' }, - { ...valid, name: 'gstack/cso-staging/other-amd64' }, - { ...valid, package_type: 'npm' }, - { ...valid, owner: { login: 'attacker' } }, - ]) expect(() => assertPublicPackageMetadata(mutation, target)).toThrow('GHCR_PACKAGE_IS_NOT_PUBLIC'); - }); - - test('pulls through an isolated empty Docker config and strips ambient credentials', async () => { - const calls: Array<{ args: string[]; env: Record }> = []; - const fetch = (async (url: string | URL | Request, init?: RequestInit) => { - expect((init?.headers as Record).Authorization).toBe('Bearer metadata-token'); - const value = String(url).includes('/packages/container/') - ? { name: 'gstack/cso-staging/node-amd64', package_type: 'container', visibility: 'public', owner: { login: 'garrytan' } } - : { login: 'garrytan', type: 'User' }; - return new Response(JSON.stringify(value), { status: 200 }); - }) as typeof globalThis.fetch; - const runDocker: PublicGhcrDependencies['runDocker'] = async (args, env) => { - calls.push({ args, env }); - const configRoot = args[args.indexOf('--config') + 1]; - expect(fs.readFileSync(`${configRoot}/config.json`, 'utf8')).toBe('{"auths":{}}\n'); - expect(env).not.toHaveProperty('GH_TOKEN'); - expect(env).not.toHaveProperty('GITHUB_TOKEN'); - expect(env.HOME).toBe(configRoot); - expect(env.DOCKER_CONFIG).toBe(configRoot); - if (args.includes('inspect')) return { exitCode: 0, stdout: JSON.stringify([IMAGE]), stderr: '' }; - return { exitCode: 0, stdout: IMAGE, stderr: '' }; - }; - const proof = await verifyPublicGhcrImage( - { image: IMAGE, platform: 'linux/amd64', githubRepository: 'garrytan/gstack', removeAfter: true }, - { fetch, githubToken: 'metadata-token', dockerPath: '/usr/bin/docker', runDocker, now: () => '2026-09-11T00:00:00.000Z', sleep: async () => {} }, - ); - expect(proof).toMatchObject({ image: IMAGE, packageVisibility: 'public', anonymousPull: 'passed', dockerConfig: 'isolated-empty-auths' }); - expect(calls).toHaveLength(3); - expect(calls[0].args).toContain('pull'); - expect(calls[0].args).toContain('--quiet'); - expect(calls[2].args).toContain('rm'); - }); - - test('fails closed before pulling a non-public package or accepting another digest', async () => { - let dockerCalls = 0; - const privateFetch = (async (url: string | URL | Request) => new Response(JSON.stringify( - String(url).includes('/packages/container/') - ? { name: 'gstack/cso-staging/node-amd64', package_type: 'container', visibility: 'private', owner: { login: 'garrytan' } } - : { login: 'garrytan', type: 'User' }, - ), { status: 200 })) as typeof globalThis.fetch; - await expect(verifyPublicGhcrImage( - { image: IMAGE, platform: 'linux/amd64', githubRepository: 'garrytan/gstack' }, - { fetch: privateFetch, githubToken: 'metadata-token', dockerPath: '/usr/bin/docker', runDocker: async () => { dockerCalls++; return { exitCode: 0, stdout: '', stderr: '' }; }, sleep: async () => {} }, - )).rejects.toThrow('GHCR_PACKAGE_IS_NOT_PUBLIC'); - expect(dockerCalls).toBe(0); - - const publicFetch = (async (url: string | URL | Request) => new Response(JSON.stringify( - String(url).includes('/packages/container/') - ? { name: 'gstack/cso-staging/node-amd64', package_type: 'container', visibility: 'public', owner: { login: 'garrytan' } } - : { login: 'garrytan', type: 'User' }, - ), { status: 200 })) as typeof globalThis.fetch; - await expect(verifyPublicGhcrImage( - { image: IMAGE, platform: 'linux/amd64', githubRepository: 'garrytan/gstack' }, - { fetch: publicFetch, githubToken: 'metadata-token', dockerPath: '/usr/bin/docker', runDocker: async args => args.includes('inspect') - ? { exitCode: 0, stdout: JSON.stringify([IMAGE.replace(HASH, 'b'.repeat(64))]), stderr: '' } - : { exitCode: 0, stdout: '', stderr: '' }, sleep: async () => {} }, - )).rejects.toThrow('ANONYMOUS_IMAGE_DIGEST_MISMATCH'); - }); - - test('requires scoped GitHub authentication for visibility metadata without passing it to Docker', async () => { - let fetched = false, pulled = false; - await expect(verifyPublicGhcrImage( - { image: IMAGE, platform: 'linux/amd64', githubRepository: 'garrytan/gstack' }, - { - githubToken: '', - dockerPath: '/usr/bin/docker', - fetch: (async () => { fetched = true; return new Response('{}'); }) as typeof globalThis.fetch, - runDocker: async () => { pulled = true; return { exitCode: 0, stdout: '', stderr: '' }; }, - }, - )).rejects.toThrow('GITHUB_PACKAGE_METADATA_TOKEN_REQUIRED'); - expect(fetched).toBe(false); - expect(pulled).toBe(false); - }); - - // The public-image release verifier runs in Linux CI. This case exercises - // its process-kill path with a POSIX shebang fixture; Windows CreateProcess - // cannot execute that fixture, while the metadata contract above remains - // portable and continues to run in the curated Windows lane. - test.skipIf(process.platform === 'win32')('kills a Docker client as soon as bounded output exceeds the release limit', async () => { - const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-public-docker-test-')); - const docker = path.join(directory, 'docker'); - fs.writeFileSync(docker, '#!/bin/sh\npython3 -c "import sys; sys.stdout.write(chr(120) * 70000)"\n', { mode: 0o700 }); - const fetch = (async (url: string | URL | Request) => new Response(JSON.stringify( - String(url).includes('/packages/container/') - ? { name: 'gstack/cso-staging/node-amd64', package_type: 'container', visibility: 'public', owner: { login: 'garrytan' } } - : { login: 'garrytan', type: 'User' }, - ), { status: 200 })) as typeof globalThis.fetch; - try { - await expect(verifyPublicGhcrImage( - { image: IMAGE, platform: 'linux/amd64', githubRepository: 'garrytan/gstack' }, - { fetch, githubToken: 'metadata-token', dockerPath: docker, sleep: async () => {} }, - )).rejects.toThrow('ANONYMOUS_DOCKER_OUTPUT_LIMIT'); - } finally { fs.rmSync(directory, { recursive: true, force: true }); } - }); -}); diff --git a/test/cso-python-runner-shadow.test.ts b/test/cso-python-runner-shadow.test.ts deleted file mode 100644 index b9ffcb49e..000000000 --- a/test/cso-python-runner-shadow.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { expect, test } from 'bun:test'; -import { spawnSync } from 'node:child_process'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { canonicalStartPlan, canonicalTestPlan, testExecutionPassed } from '../lib/cso/verification'; - -const python = process.platform === 'win32' ? undefined : Bun.which('python3'); - -function write(root:string, relative:string, body:string):void { - const file=path.join(root,relative);fs.mkdirSync(path.dirname(file),{recursive:true});fs.writeFileSync(file,body); -} - -test.skipIf(!python)('Python test runners are imported before the application root without breaking app imports',()=>{ - const root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-python-shadow-')); - try{ - const venv=path.join(root,'venv'),created=spawnSync(python!,['-m','venv',venv],{encoding:'utf8',timeout:120_000}); - expect(created.status,created.stderr).toBe(0); - const venvPython=path.join(venv,'bin','python'),located=spawnSync(venvPython,['-c','import sysconfig;print(sysconfig.get_paths()["purelib"])'],{encoding:'utf8',timeout:30_000}); - expect(located.status,located.stderr).toBe(0); - const fakePytest=path.join(located.stdout.trim(),'pytest','__init__.py'); - fs.mkdirSync(path.dirname(fakePytest),{recursive:true}); - fs.writeFileSync(fakePytest,`def main(args): - import pathlib - from app import VALUE - config=pathlib.Path('.pytest.ini').read_text() - pathlib.Path('pytest-observation').write_text(repr([VALUE,args,config])) - return 0 -`); - fs.writeFileSync(path.join(located.stdout.trim(),'hostile-startup.pth'),"import pathlib;pathlib.Path('pth-startup-ran').write_text('unsafe')\n"); - - const pytestRoot=path.join(root,'pytest-project');fs.mkdirSync(pytestRoot); - write(pytestRoot,'app.py','VALUE = 42\n'); - write(pytestRoot,'.pytest.ini','[pytest]\naddopts = -q\n'); - write(pytestRoot,'tests/test_app.py','from app import VALUE\ndef test_value(): assert VALUE == 42\n'); - const pytestBefore=canonicalTestPlan(pytestRoot,'python'); - write(pytestRoot,'pytest.py','raise RuntimeError("application shadow replaced trusted pytest")\n'); - const pytestAfter=canonicalTestPlan(pytestRoot,'python'); - expect(pytestAfter).toEqual(pytestBefore); - const pytestCommand=pytestBefore.commands[0]; - expect(pytestCommand.executable).toBe('/work/.venv/bin/python'); - expect(pytestCommand.args.slice(0,3)).toEqual(['-I','-S','-c']); - expect(pytestCommand.args[3]).toContain('import pytest;sys.path.insert'); - expect(pytestCommand.args.slice(4)).toEqual(['-q','--color=no','--','./tests/test_app.py']); - const ranPytest=spawnSync(venvPython,pytestCommand.args,{cwd:pytestRoot,encoding:'utf8',timeout:30_000}); - expect(ranPytest.status,ranPytest.stderr).toBe(0); - expect(fs.readFileSync(path.join(pytestRoot,'pytest-observation'),'utf8')).toContain("[42, ['-q', '--color=no', '--', './tests/test_app.py'], '[pytest]\\naddopts = -q\\n']"); - expect(fs.existsSync(path.join(pytestRoot,'pth-startup-ran'))).toBe(false); - - const unittestRoot=path.join(root,'unittest-project');fs.mkdirSync(unittestRoot); - write(unittestRoot,'app.py','VALUE = 42\n'); - write(unittestRoot,'tests/test_app.py',`import unittest -from app import VALUE -class AppTest(unittest.TestCase): - def test_value(self): self.assertEqual(VALUE, 42) -`); - const unittestBefore=canonicalTestPlan(unittestRoot,'python'); - write(unittestRoot,'unittest.py','raise RuntimeError("application shadow replaced standard unittest")\n'); - const unittestAfter=canonicalTestPlan(unittestRoot,'python'); - expect(unittestAfter).toEqual(unittestBefore); - const unittestCommand=unittestBefore.commands[0]; - expect(unittestCommand.executable).toBe('/work/.venv/bin/python'); - expect(unittestCommand.args.slice(0,3)).toEqual(['-I','-S','-c']); - expect(unittestCommand.args[3]).toContain("import os,sys,unittest;sys.path.append"); - expect(unittestCommand.args.slice(4)).toEqual(['./tests/test_app.py']); - const ranUnittest=spawnSync(venvPython,unittestCommand.args,{cwd:unittestRoot,encoding:'utf8',timeout:30_000}),output=ranUnittest.stdout+ranUnittest.stderr; - expect(ranUnittest.status,output).toBe(0); - expect(output).toContain('Ran 1 test'); - expect(testExecutionPassed(unittestCommand,ranUnittest.status??-1,output)).toBe(true); - expect(fs.existsSync(path.join(unittestRoot,'pth-startup-ran'))).toBe(false); - - const fakeDjango=path.join(located.stdout.trim(),'django','__init__.py');fs.mkdirSync(path.dirname(fakeDjango),{recursive:true});fs.writeFileSync(fakeDjango,"ORIGIN = 'trusted-site-package'\n"); - const djangoRoot=path.join(root,'django-project');fs.mkdirSync(djangoRoot);write(djangoRoot,'requirements.txt',`Django==1.0.0 --hash=sha256:${'a'.repeat(64)}\n`);write(djangoRoot,'manage.py',"import pathlib,django\npathlib.Path('django-observation').write_text(django.ORIGIN)\n"); - const djangoCommand=canonicalStartPlan(djangoRoot,'python',3456).command;expect(djangoCommand.args.slice(0,3)).toEqual(['-I','-S','-c']);const ranDjango=spawnSync(venvPython,djangoCommand.args,{cwd:djangoRoot,encoding:'utf8',timeout:30_000});expect(ranDjango.status,ranDjango.stderr).toBe(0);expect(fs.readFileSync(path.join(djangoRoot,'django-observation'),'utf8')).toBe('trusted-site-package');expect(fs.existsSync(path.join(djangoRoot,'pth-startup-ran'))).toBe(false); - }finally{fs.rmSync(root,{recursive:true,force:true});} -}); diff --git a/test/cso-rails-verification.test.ts b/test/cso-rails-verification.test.ts deleted file mode 100644 index fba3d1769..000000000 --- a/test/cso-rails-verification.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { DockerGroup } from '../lib/cso/docker'; -import { DockerVerificationExecutor } from '../lib/cso/verification'; - -const roots:string[]=[]; -afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); - -describe('CSO Rails database verification lifecycle',()=>{ - test('creates fresh multi-database PostgreSQL per phase and prepares every private work tree',async()=>{ - const root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-rails-verification-'));roots.push(root); - const source=path.join(root,'source'),work=path.join(root,'work'),control=path.join(root,'control');for(const dir of [source,work,control])fs.mkdirSync(dir); - const events:string[]=[],policies:string[][]=[];let groupNumber=0; - const create=spyOn(DockerGroup,'create').mockImplementation(async()=>{ - const group=++groupNumber;let next=0; - return { - anchor:`anchor-${group}`, - createContainer:async(spec:any)=>{const id=`${group}-${spec.role}-${++next}`;events.push(`create:${id}:${spec.command.join(' ')}`);if(spec.postgresDatabasePolicy){policies.push(fs.readFileSync(spec.postgresDatabasePolicy,'utf8').trim().split('\n'));expect(fs.statSync(spec.postgresDatabasePolicy).mode&0o777).toBe(0o444);}return id;}, - start:async(id:string)=>{events.push(`start:${id}`);},startHeldApplication:async(id:string)=>{events.push(`held:${id}`);}, - execCapture:async(id:string,command:string[])=>{events.push(`exec:${id}:${command.join(' ')}`);return{code:0,stdout:'',stderr:''};}, - execDetached:async(id:string,command:string[])=>{events.push(`detach:${id}:${command.join(' ')}`);}, - startAttach:async(id:string)=>{events.push(`attach:${id}`);return{code:0,output:JSON.stringify({booted:true,legitimate:true,security:'pass',existingTests:false,output:'ok',inputHash:''})};}, - removeContainer:async(id:string)=>{events.push(`remove:${id}`);},cleanup:async()=>{events.push(`cleanup:${group}`);}, - } as any; - }); - try{ - const runtime:any={id:'rails',stack:'rails',image:`runtime@sha256:${'a'.repeat(64)}`,platform:'linux/amd64'}; - const request:any={findingId:'b'.repeat(32),port:3456,start:{executable:'/usr/local/bin/bundle',args:['exec','rails','server']}, - legitimate:[],security:{},fixtures:{},existingTests:[{executable:'/usr/local/bin/bundle',args:['exec','rspec']},{executable:'/usr/local/bin/bundle',args:['exec','rails','test']}]}; - const executor=new DockerVerificationExecutor({} as any,'/watchdog',Date.now()+60_000); - const execution:any={environment:{BUNDLE_PATH:'/work/vendor/bundle'},database:{adapter:'postgresql',connections:['primary','queue'],sidecar:{id:'postgresql-17',image:`postgres@sha256:${'c'.repeat(64)}`}}}; - await executor.observe(source,'before',request,runtime,runtime,work,control,execution); - await executor.observe(source,'after',request,runtime,runtime,work,control,execution); - }finally{create.mockRestore();} - expect(policies).toEqual([['cso_primary','cso_queue'],['cso_primary','cso_queue']]); - expect(events.filter(event=>event.includes('/opt/cso/postgresql-ready'))).toHaveLength(2); - expect(events.filter(event=>event.includes('/usr/local/bin/bundle exec rails db:prepare'))).toHaveLength(6); - for(const [index,event] of events.entries())if(event.includes('exec rails db:prepare'))expect(events.slice(0,index)).toContain(`held:${event.split(':')[1]}`); - expect(events.some(event=>/^start:\d-(app|tests)-/.test(event))).toBe(false); - for(const group of [1,2]){ - const removeApp=events.findIndex(event=>event===`remove:${group}-app-2`),createFirstTest=events.findIndex(event=>event.startsWith(`create:${group}-tests-4:`)); - expect(removeApp).toBeGreaterThan(-1);expect(createFirstTest).toBeGreaterThan(removeApp); - } - }); - - test('SQLite prepares the app and each test copy without a sidecar',async()=>{ - const root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-rails-sqlite-'));roots.push(root);for(const name of ['source','work','control'])fs.mkdirSync(path.join(root,name)); - const commands:string[]=[];let next=0; - const create=spyOn(DockerGroup,'create').mockResolvedValue({ - createContainer:async(spec:any)=>{commands.push(`create:${spec.role}`);return`${spec.role}-${++next}`;},start:async()=>{},startHeldApplication:async(id:string)=>{commands.push(`held:${id}`);}, - execCapture:async(_id:string,command:string[])=>{commands.push(command.join(' '));return{code:0,stdout:'',stderr:''};},execDetached:async()=>{}, - startAttach:async()=>({code:0,output:JSON.stringify({booted:true,legitimate:true,security:'pass',existingTests:false,output:'ok',inputHash:''})}),removeContainer:async()=>{},cleanup:async()=>{}, - } as any); - try{const runtime:any={stack:'rails',image:`runtime@sha256:${'a'.repeat(64)}`},request:any={findingId:'d'.repeat(32),port:3456,start:{executable:'/usr/local/bin/bundle',args:['exec','rails','server']},legitimate:[],security:{},fixtures:{},existingTests:[{executable:'/usr/local/bin/bundle',args:['exec','rails','test']}]};await new DockerVerificationExecutor({} as any,'/watchdog',Date.now()+60_000).observe(path.join(root,'source'),'before',request,runtime,runtime,path.join(root,'work'),path.join(root,'control'),{environment:{},database:{adapter:'sqlite',connections:['primary']}});}finally{create.mockRestore();} - expect(commands.some(command=>command==='create:postgres')).toBe(false);expect(commands.filter(command=>command.includes('exec rails db:prepare'))).toHaveLength(2);expect(commands.filter(command=>command.startsWith('held:'))).toHaveLength(2); - }); -}); diff --git a/test/cso-recall.test.ts b/test/cso-recall.test.ts deleted file mode 100644 index f8695e048..000000000 --- a/test/cso-recall.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -// Recall regressions for /cso, from the gstack-evals#443 real-advisory run (52 GitHub -// security advisories, Opus 5.5): with /cso the audit named 3 of 51 advisories against 12 -// for a plain audit, reported 0.75 findings per session against 14.8, and in 5 of 10 misses -// never opened a file the fix changed. Pinned here against the real helper: a refused start -// the skill told the model never to retry, a file list the model could not see past a cut-off -// shell result, and a report rule (enforced by the helper) that dropped every finding short of proof. -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; - -const ROOT = path.resolve(import.meta.dir, '..'); -const launcher = path.join(ROOT, 'bin', process.platform === 'win32' ? 'gstack-cso-launcher.exe' : 'gstack-cso-launcher'); -const MIB = 1024 * 1024; -const skill = () => fs.readFileSync(path.join(ROOT, 'cso/SKILL.md'), 'utf8'); -let root = ''; -let state = ''; -beforeAll(() => { - root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cso-recall-'))); - state = path.join(root, 'state'); - fs.mkdirSync(state); -}); -afterAll(() => fs.rmSync(root, { recursive: true, force: true })); - -function git(repo: string, ...args: string[]): void { - const result = spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8', env: { HOME: root, PATH: process.env.PATH ?? '' }, timeout: 60_000 }); - if (result.status) throw new Error(result.stderr); -} -function cso(repo: string, args: string[]) { - return spawnSync(launcher, args, { cwd: repo, encoding: 'utf8', env: { HOME: root, GSTACK_HOME: state, PATH: process.env.PATH ?? '' }, timeout: 120_000, maxBuffer: 64 * MIB }); -} -function findReport(dir: string, run: string, name: string): string { - for (const entry of fs.readdirSync(dir, { recursive: true }) as string[]) - if (entry.endsWith(path.join(run, name))) return path.join(dir, entry); - throw new Error('no ' + name + ' for ' + run); -} -function json(stdout: string): any { - return JSON.parse(stdout.slice(stdout.indexOf('{'))); -} -/** A library shaped like the eval's units: many ordinary modules, with the vulnerable parser late in the inventory. */ -function library(name: string): { repo: string; files: string[] } { - const repo = path.join(root, name); - const files: Record = { 'package.json': '{"name":"fixture-lib","version":"1.0.0","main":"src/index.js"}\n' }; - for (let i = 0; i < 320; i++) files[`src/modules/m${String(i).padStart(3, '0')}.js`] = `module.exports = (x) => x + ${i};\n`; - files['src/zz-format/parse.js'] = 'module.exports = (input) => { const o = {}; for (const [k, v] of input) o[k] = v; return o; };\n'; - files['src/index.js'] = "module.exports = { parse: require('./zz-format/parse') };\n"; - for (const [file, body] of Object.entries(files)) { - fs.mkdirSync(path.dirname(path.join(repo, file)), { recursive: true }); - fs.writeFileSync(path.join(repo, file), body); - } - git(repo, 'init', '-q'); - git(repo, 'add', '-A'); - git(repo, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.test', 'commit', '-qm', 'fixture'); - return { repo, files: Object.keys(files).sort() }; -} - -describe('/cso recall (gstack-evals#443)', () => { - test('a refused start is corrected and retried, and the source-cap correction is --paths', () => { - const text = skill(); - const invariant = text.slice(text.indexOf('**One-run invariant.**'), text.indexOf('**Audited-source access invariant.**')); - expect(invariant).toContain('A refused `start` (`"ok":false`) holds no run'); - expect(invariant).toContain('start again'); - expect(invariant).toContain('64 MiB'); - expect(invariant).toContain('--paths'); - expect(invariant).toMatch(/Once a `start` returns a run ID, never call `start` again/); - expect(invariant).not.toMatch(/On failure, make one correction, then finish partial/); - }); - - test('the skill names a command that lists the whole inventory from real inspect output', () => { - const { repo, files } = library('inventory'); - const start = cso(repo, ['start', '--repo', repo, '--offline']); - expect(start.status).toBe(0); - const run = json(start.stdout).runId as string; - const inspect = cso(repo, ['inspect', run]); - expect(inspect.status).toBe(0); - const filter = skill().match(/jq -r '([^']+)'/)?.[1]; - expect(filter).toBe('.manifest.entries[].path'); - const listed = (json(inspect.stdout).manifest.entries as Array<{ path: string }>).map((entry) => entry.path).sort(); - expect(listed).toEqual(files); - const read = cso(repo, ['read', run, 'src/zz-format/parse.js']); - expect(read.status).toBe(0); - expect(read.stdout).toContain('o[k] = v'); - expect(cso(repo, ['finish', run]).status).toBe(0); - }); - - test('search reads every file in one call, never runs a file name, and lists what it could not search', () => { - const repo = path.join(root, 'hostile'); - fs.mkdirSync(path.join(repo, 'src'), { recursive: true }); - const hostile = 'src/a$(touch PWNED).js'; - fs.writeFileSync(path.join(repo, hostile), 'eval(input)\n'); - fs.writeFileSync(path.join(repo, 'src/parse.js'), 'const x = 1;\neval(input)\n'); - fs.writeFileSync(path.join(repo, 'src/big.js'), 'eval(input)\n' + 'x'.repeat(MIB + 16)); - fs.writeFileSync(path.join(repo, 'src/min.js'), 'a(b,c);'.repeat(140_000) + 'eval(late)'); - fs.mkdirSync(path.join(repo, '.gstack')); - fs.writeFileSync(path.join(repo, '.gstack/state.js'), 'eval(input)\n'); - git(repo, 'init', '-q'); - git(repo, 'add', '-A'); - git(repo, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.test', 'commit', '-qm', 'fixture'); - const run = json(cso(repo, ['start', '--repo', repo, '--offline']).stdout).runId as string; - expect(skill()).toContain("gstack-cso search ''"); - const found = cso(repo, ['search', run, 'eval\\(']); - expect(found.status).toBe(0); - expect(found.stdout).toContain('src/parse.js:2:eval(input)'); - expect(found.stdout).toContain(hostile + ':1:eval(input)'); - expect(found.stdout).toMatch(/src\/min\.js:1:[a-c(),;]{100}eval\(late\)/); - expect(found.stdout).toMatch(/1 unsearched paths .*coverage gap: src\/big\.js\]/); - expect(found.stdout).not.toContain('.gstack/state.js'); - expect(found.stdout).toContain('1 paths the snapshot excluded or withheld have no readable copy'); - expect(found.stdout).toMatch(/1 paths have lines over 4096 characters.*: src\/min\.js\]/); - expect(fs.existsSync(path.join(root, 'PWNED'))).toBe(false); - expect(fs.existsSync(path.join(repo, 'PWNED'))).toBe(false); - const none = cso(repo, ['search', run, 'zzz-no-such-text']).stdout; - expect(none).toContain('[gstack-cso search: no matches]'); - expect(none).toMatch(/1 unsearched paths .*src\/big\.js/); - const bad = cso(repo, ['search', run, '(']); - expect(bad.status).not.toBe(0); - expect(bad.stderr).toContain('not a valid regular expression'); - expect(cso(repo, ['search', run, 'x', '--seconds', '61']).stderr).toContain('--seconds must be a whole number from 1 to 60'); - expect(cso(repo, ['finish', run]).status).toBe(0); - }); - - test('search stays fast on a one-line 1 MiB file and stops a runaway pattern at its time limit with the hits found so far', () => { - const repo = path.join(root, 'minified'); - fs.mkdirSync(path.join(repo, 'src'), { recursive: true }); - fs.writeFileSync(path.join(repo, 'src/a.js'), 'eval(first)\n'); - fs.writeFileSync(path.join(repo, 'src/b.min.js'), 'eval(second)\n' + 'x'.repeat(MIB - 64)); - git(repo, 'init', '-q'); - git(repo, 'add', '-A'); - git(repo, '-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.test', 'commit', '-qm', 'fixture'); - const run = json(cso(repo, ['start', '--repo', repo, '--offline']).stdout).runId as string; - let started = Date.now(); - const quadratic = cso(repo, ['search', run, '.*password']); - expect(quadratic.status).toBe(0); - expect(quadratic.stdout).toContain('[gstack-cso search: no matches]'); - expect(Date.now() - started).toBeLessThan(30_000); - started = Date.now(); - const runaway = cso(repo, ['search', run, '(x+x+)+y|eval\\((first|second)', '--seconds', '2']); - expect(runaway.status).toBe(0); - expect(runaway.stdout).toContain('src/a.js:1:eval(first)'); - expect(runaway.stdout).toContain('src/b.min.js:1:eval(second)'); - expect(runaway.stdout).toMatch(/stopped at the 2-second limit; 1 paths not searched, a coverage gap: src\/b\.min\.js/); - expect(Date.now() - started).toBeLessThan(20_000); - expect(cso(repo, ['finish', run]).status).toBe(0); - }, 90_000); - - test('the report rule keeps every supported finding and lists hypotheses instead of dropping them', () => { - const text = skill(); - for (const dropped of ['Daily reports hold only', 'Omit daily candidates', 'Prioritize unresolved high impact', 'demonstrated in-scope impact']) expect(text).not.toContain(dropped); - for (const kept of ['jq -r .runId', "sed -n '1,500p'", 'gstack-cso search', 'Report every finding the code supports', 'never omission', 'Hypotheses (unconfirmed)', 'even with callers outside the snapshot', 'Drop one only when code you read disproves it', 'Never narrow by file name']) expect(text).toContain(kept); - }); - - test('a daily run saves supported findings and low-confidence hypotheses, and report.md lists them in separate sections', () => { - const { repo } = library('report'); - const run = json(cso(repo, ['start', '--repo', repo, '--offline']).stdout).runId as string; - const finding = (evidence: string, confidence: string, title: string, rootCause: string) => ({ - title, rootCause, - location: { path: 'src/zz-format/parse.js', line: 1, symbol: 'parse' }, advisoryIds: [], severity: 'high', confidence, - confidenceRationale: 'the loop assigns every key without a guard', evidence, - attackerControl: 'entries passed to the public parse API', impact: 'a __proto__ entry sets the returned object\'s prototype, so properties the caller reads but never set come from the attacker', - scenario: 'a caller parses untrusted entries including __proto__', trace: ['index.js parse', 'parse.js loop'], - references: ['src/zz-format/parse.js:1'], recommendation: 'reject __proto__, constructor and prototype keys', - challenge: { reviewer: 'sequential challenge; independent agent unavailable', independent: false, mode: 'sequential_fallback', callers: 'public API', controls: 'none found', counterevidence: 'none', conclusion: 'holds' }, - }); - const submit = (evidence: string, confidence: string, title: string, rootCause: string) => { - const dir = fs.mkdtempSync(path.join(root, 'submission-')); - const file = path.join(dir, 'submission.json'); - fs.writeFileSync(file, JSON.stringify({ findings: [finding(evidence, confidence, title, rootCause)] })); - return cso(repo, ['submit', run, file]); - }; - const supported = submit('supported', 'medium', 'Prototype injection in parse', 'parse copies attacker keys onto a plain object'); - expect(supported.status).toBe(0); - expect(json(supported.stdout).findings).toBe(1); - const hypothesis = submit('hypothesis', 'low', "Prototype injection through caller-named keys $' and $&", 'parse copies keys named by the caller'); - expect(hypothesis.status).toBe(0); - expect(json(hypothesis.stdout).findings).toBe(2); - expect(cso(repo, ['finish', run]).status).toBe(0); - const saved = json(fs.readFileSync(findReport(state, run, 'report.json'), 'utf8')).findings as Array<{ title: string; evidence: string; confidence: string }>; - expect(saved.map((f) => [f.title, f.evidence, f.confidence]).sort()).toEqual([ - ['Prototype injection in parse', 'supported', 'medium'], - ["Prototype injection through caller-named keys $' and $&", 'hypothesis', 'low'], - ]); - const report = fs.readFileSync(findReport(state, run, 'report.md'), 'utf8'); - const supportedSection = report.slice(report.indexOf('Supported findings:'), report.indexOf('Hypotheses (unconfirmed):')); - const hypotheses = report.slice(report.indexOf('Hypotheses (unconfirmed):'), report.indexOf('Snapshot transformations:')); - expect(report.indexOf('Hypotheses (unconfirmed):')).toBeGreaterThan(report.indexOf('Supported findings:')); - expect(supportedSection).toContain('Prototype injection in parse'); - expect(supportedSection).not.toContain('caller-named keys'); - expect(hypotheses).toContain('Prototype injection through caller-named keys'); - expect(hypotheses).not.toContain('Prototype injection in parse'); - expect(hypotheses).toContain('$&'); - expect(report.split('Snapshot transformations:').length).toBe(2); - }); -}); diff --git a/test/cso-registry-socket.test.ts b/test/cso-registry-socket.test.ts deleted file mode 100644 index a311d6441..000000000 --- a/test/cso-registry-socket.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as net from 'node:net'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawn, spawnSync } from 'node:child_process'; -import { - REGISTRY_SOCKET_PATH_MAX_BYTES, - RegistryEgressBroker, - superviseRegistrySocket, - type SupervisedRegistrySocket, -} from '../lib/cso/preparation-docker'; - -const posixDescribe = process.platform === 'win32' ? describe.skip : describe; - -posixDescribe('short supervised CSO registry sockets', () => { - let fixtureRoot = ''; - let watchdogPath = ''; - - beforeAll(() => { - fixtureRoot = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'cso-registry-socket-'))); - watchdogPath = path.join(fixtureRoot, 'watchdog'); - const result = spawnSync('/usr/bin/cc', ['-std=c11', '-D_POSIX_C_SOURCE=200809L', '-O2', '-Wall', '-Wextra', - path.resolve(import.meta.dir, '../lib/cso/watchdog.c'), '-o', watchdogPath], { encoding: 'utf8', timeout: 30_000 }); - expect(result.status).toBe(0); expect(result.stderr).toBe(''); - }); - - afterAll(() => { if (fixtureRoot) fs.rmSync(fixtureRoot, { recursive: true, force: true }); }); - - async function close(handle: SupervisedRegistrySocket | undefined): Promise { - if (!handle) return; - await handle.dispose(); - } - - test('binds and connects through a private collision-resistant path below the Darwin limit', async () => { - const first = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 10_000 }); - const second = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 10_000 }); - const broker = new RegistryEgressBroker(first.socketPath, ['registry.npmjs.org'], Date.now() + 10_000, 1024 * 1024); - try { - expect(first.root).not.toBe(second.root); - expect(Buffer.byteLength(first.socketPath)).toBeLessThanOrEqual(REGISTRY_SOCKET_PATH_MAX_BYTES); - expect(Buffer.byteLength(second.socketPath)).toBeLessThanOrEqual(REGISTRY_SOCKET_PATH_MAX_BYTES); - for (const handle of [first, second]) { - expect(path.basename(handle.root)).toMatch(/^gscso-\d+-[a-f0-9]{32}$/); - const stat = fs.lstatSync(handle.root); - expect(stat.isDirectory()).toBe(true); expect(stat.isSymbolicLink()).toBe(false); - expect(stat.mode & 0o077).toBe(0); if (process.getuid) expect(stat.uid).toBe(process.getuid()); - expect(fs.realpathSync(handle.root)).toBe(handle.root); - } - await broker.start(); - const socketStat = fs.lstatSync(first.socketPath); - expect(socketStat.isSocket()).toBe(true); expect(socketStat.isSymbolicLink()).toBe(false); - expect(socketStat.mode & 0o077).toBe(0); if (process.getuid) expect(socketStat.uid).toBe(process.getuid()); - const reply = await new Promise((resolveReply, reject) => { - const socket = net.createConnection({ path: first.socketPath }); let output = ''; - socket.once('connect', () => socket.write('CONNECT denied.example:443 HTTP/1.1\r\nHost: denied.example:443\r\n\r\n')); - socket.on('data', chunk => { output += chunk.toString(); }); socket.once('end', () => resolveReply(output)); socket.once('error', reject); - }); - expect(reply).toContain('403 Forbidden'); - } finally { - await broker.close(); await close(first); await close(second); - } - expect(fs.existsSync(first.root)).toBe(false); expect(fs.existsSync(second.root)).toBe(false); - }); - - test('owner-death cleanup removes the exact socket root while preserving an unrelated concurrent root', async () => { - const owner = spawn('/bin/sleep', ['30'], { stdio: 'ignore' }); - const doomed = await superviseRegistrySocket({ watchdogPath, ownerPid: owner.pid!, deadline: Date.now() + 10_000 }); - const survivor = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 10_000 }); - const broker = new RegistryEgressBroker(doomed.socketPath, ['registry.npmjs.org'], Date.now() + 10_000, 1024 * 1024); - try { - await broker.start(); owner.kill('SIGKILL'); await new Promise(resolve => owner.once('close', resolve)); - for (let attempt = 0; attempt < 50 && fs.existsSync(doomed.root); attempt++) await Bun.sleep(100); - expect(fs.existsSync(doomed.root)).toBe(false); - expect(fs.existsSync(survivor.root)).toBe(true); - } finally { - try { owner.kill('SIGKILL'); } catch {} - await broker.close(); await close(doomed); await close(survivor); - } - }, 15_000); - - test('deadline cleanup removes the whole per-call socket root without a global temp sweep', async () => { - // The watchdog takes whole seconds and cleans as soon as the deadline passes, so a deadline inside the ~1 s startup - // handshake fails it on a slow start (Free Tests 42772387147): expire it after the handshake instead. - const doomed = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 2_000 }); - const survivor = await superviseRegistrySocket({ watchdogPath, ownerPid: process.pid, deadline: Date.now() + 10_000 }); - const broker = new RegistryEgressBroker(doomed.socketPath, ['registry.npmjs.org'], Date.now() + 10_000, 1024 * 1024); - try { - await broker.start(); fs.writeFileSync(path.join(doomed.root, 'owned-fixture'), 'bounded'); - for (let attempt = 0; attempt < 50 && fs.existsSync(doomed.root); attempt++) await Bun.sleep(100); - expect(fs.existsSync(doomed.root)).toBe(false); - expect(fs.existsSync(survivor.root)).toBe(true); - } finally { - await broker.close(); await close(doomed); await close(survivor); - } - }, 15_000); - - test('the detached cleaner refuses a same-path replacement instead of deleting it', async () => { - const base = fs.realpathSync('/tmp'), root = fs.mkdtempSync(path.join(base, 'gscso-identity-')), - control = path.join(root, 'control'), moved = `${root}.original`; - fs.chmodSync(root, 0o700); fs.mkdirSync(control, { mode: 0o700 }); - const owner = spawn('/bin/sleep', ['30'], { stdio: 'ignore' }); - const child = spawn(watchdogPath, ['--ephemeral-owner', String(owner.pid), '--deadline', String(Math.ceil((Date.now() + 10_000) / 1000)), - '--control-dir', control, '--work-root', root, '--run-root', base], { cwd: control, env: { PATH: '/usr/bin:/bin' }, stdio: 'ignore' }); - const ownerClosed = new Promise(resolve => owner.once('close', resolve)), childClosed = new Promise(resolve => child.once('close', resolve)); - try { - for (let attempt = 0; attempt < 100 && !fs.existsSync(path.join(control, 'attempt.ready')); attempt++) await Bun.sleep(10); - expect(fs.existsSync(path.join(control, 'attempt.ready'))).toBe(true); - fs.renameSync(root, moved); fs.mkdirSync(root, { mode: 0o700 }); fs.mkdirSync(control, { mode: 0o700 }); - owner.kill('SIGKILL'); await ownerClosed; - const event = path.join(control, 'attempt.event'); - for (let attempt = 0; attempt < 50 && !fs.existsSync(event); attempt++) await Bun.sleep(100); - expect(fs.readFileSync(event, 'utf8')).toContain('identity changed; refusing removal'); - expect(fs.existsSync(root)).toBe(true); expect(fs.existsSync(moved)).toBe(true); - } finally { - try { owner.kill('SIGKILL'); } catch {} child.kill('SIGKILL'); - await childClosed; - if (fs.existsSync(root)) fs.rmSync(root, { recursive: true, force: true }); - if (fs.existsSync(moved)) fs.rmSync(moved, { recursive: true, force: true }); - } - }, 15_000); -}); diff --git a/test/cso-runtime-promotion.test.ts b/test/cso-runtime-promotion.test.ts deleted file mode 100644 index 212e34a66..000000000 --- a/test/cso-runtime-promotion.test.ts +++ /dev/null @@ -1,297 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { spawnSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; -import committedCatalog from '../lib/cso/runtime-catalog.json'; -import buildInputs from '../lib/cso/images/build-inputs.json'; -import { isEvaluationRuntimeCatalog, validateRuntimeCatalog } from '../lib/cso/runtime-catalog'; -import { imageBuildMatrix, type ImageBuildRow } from '../scripts/cso-image-matrix'; -import { catalogPromotionCandidate, evaluationCandidateCatalog, releaseCandidate, validateEvaluationCandidate, validateRuntimeCatalogTransition, type RuntimeQualificationStatement } from '../scripts/cso-runtime-promotion'; -import { assertVersionOutput, probesForBuildRow } from '../scripts/cso-verify-runtime-base'; -import { committedPreparation, requalificationTriggers } from '../scripts/cso-requalification'; -import { gitArgvIn } from './helpers/scratch-repo'; - -const TRIGGERS = await requalificationTriggers(); -const digest = (value: string) => `sha256:${createHash('sha256').update(value).digest('hex')}`; - -function checks(row: ImageBuildRow): Record { - if (row.stack === 'postgresql') return { - containmentPassed: true, - coldStartPassed: true, - multiDatabasePassed: true, - readinessPassed: true, - secretCanaryPassed: true, - watchdogCleanupPassed: true, - }; - const value: Record = { - accuracyGatesPassed: true, - acquisitionPublicOnlyPassed: true, - coldStartPassed: true, - containmentPassed: true, - heldOutRepairPassed: true, - offlineLifecyclePassed: true, - positiveNegativeAssertionsPassed: true, - secretCanaryPassed: true, - watchdogCleanupPassed: true, - }; - if (row.stack === 'rails') { - value.nativeExtensionsPassed = true; - value.railsPostgresqlPassed = true; - value.railsSqlitePassed = true; - } - return value; -} - -function statements(): RuntimeQualificationStatement[] { - return imageBuildMatrix(buildInputs).include.map(row => ({ - schemaVersion: 1, - helperAbi: 3, - state: 'qualified', - buildRevision: row.inputRevision, - runtimeId: row.runtimeId, - stack: row.stack, - platform: row.platform, - image: `ghcr.io/garrytan/gstack/cso-staging/${row.stack}-${row.arch}@${digest(row.runtimeId)}`, - versions: row.versions, - sourceCommit: 'a'.repeat(40), - workflow: 'https://github.com/garrytan/gstack/actions/runs/123456', - qualifiedAt: '2026-09-10T12:00:00.000Z', - sbomDigest: digest(`sbom:${row.runtimeId}`), - provenanceDigest: digest(`provenance:${row.runtimeId}`), - checks: checks(row), - })); -} - -describe('CSO runtime catalog promotion', () => { - test('committed build review declares both native profiles without admitting unpublished images', () => { - const matrix = imageBuildMatrix(buildInputs); - expect(matrix.include).toHaveLength(10); - expect(committedCatalog.profiles).toHaveLength(10); - for (const runtime of committedCatalog.runtimes) { - expect(committedCatalog.profiles.filter(profile => profile.id === runtime.id && profile.stack === runtime.stack && profile.platform === runtime.platform)).toHaveLength(1); - expect(runtime.image).toMatch(/@sha256:[a-f0-9]{64}$/); - } - expect(committedCatalog.buildRevision).toBe(buildInputs.revision); - expect(matrix.include.find(row => row.stack === 'bun')!.versions).not.toHaveProperty('node'); - validateRuntimeCatalog(committedCatalog); - }); - - test('complete same-run evidence generates a validated review candidate bound to its evidence', () => { - const candidate = catalogPromotionCandidate(committedCatalog, buildInputs, statements(), TRIGGERS); - expect(candidate.previousRevision).toBe(committedCatalog.revision); - expect(candidate.runtimes).toHaveLength(10); - expect(candidate.promotion).toMatchObject({ - sourceCommit: 'a'.repeat(40), - workflow: 'https://github.com/garrytan/gstack/actions/runs/123456', - }); - expect(candidate.promotion!.evidenceDigest).toMatch(/^sha256:[a-f0-9]{64}$/); - expect(candidate.promotion!.qualificationEvidenceDigest).toMatch(/^sha256:[a-f0-9]{64}$/); - expect(candidate.runtimes.every(runtime => runtime.image.includes('@sha256:'))).toBe(true); - validateRuntimeCatalog(candidate); - }); - - test('missing release checks, mutable images, and split qualification runs cannot be promoted', () => { - const missing = statements(); - delete missing[0].checks.heldOutRepairPassed; - expect(() => catalogPromotionCandidate(committedCatalog, buildInputs, missing, TRIGGERS)).toThrow('MISSING_RELEASE_GATES'); - - const mutable = statements(); - mutable[0].image = 'ghcr.io/garrytan/gstack/cso-staging/node-amd64:latest'; - expect(() => catalogPromotionCandidate(committedCatalog, buildInputs, mutable, TRIGGERS)).toThrow('INVALID_QUALIFIED_IMAGE'); - - const split = statements(); - split[0].workflow = 'https://github.com/garrytan/gstack/actions/runs/999999'; - expect(() => catalogPromotionCandidate(committedCatalog, buildInputs, split, TRIGGERS)).toThrow('SPLIT_QUALIFICATION_RUN'); - - const extra = statements() as Array; - extra[0].finding = 'must not enter a public release artifact'; - expect(() => catalogPromotionCandidate(committedCatalog, buildInputs, extra, TRIGGERS)).toThrow('INVALID_QUALIFICATION_STATEMENT_FIELDS'); - }); - - test('qualification statements must match reviewed versions and every expected platform row', () => { - const drift = statements(); - drift[0].versions = { ...drift[0].versions, node: '24.5.0' }; - expect(() => catalogPromotionCandidate(committedCatalog, buildInputs, drift, TRIGGERS)).toThrow('QUALIFICATION_BUILD_MISMATCH'); - expect(() => catalogPromotionCandidate(committedCatalog, buildInputs, statements().slice(1), TRIGGERS)).toThrow('INCOMPLETE_QUALIFICATION_MATRIX'); - }); - - test('promotion is a compare-and-swap against the exact reviewed catalog revision', () => { - const candidate = catalogPromotionCandidate(committedCatalog, buildInputs, statements(), TRIGGERS); - expect(() => validateRuntimeCatalogTransition(committedCatalog, candidate)).not.toThrow(); - expect(() => validateRuntimeCatalogTransition( - { ...committedCatalog, revision: 'catalog-advanced-concurrently' }, - candidate, - )).toThrow('RUNTIME_CATALOG_BASE_REVISION_MISMATCH'); - expect(() => validateRuntimeCatalogTransition(committedCatalog, { - ...candidate, - profiles: candidate.profiles.map((profile, index) => index === 0 - ? { ...profile, reviewedAt: '2026-09-11T00:00:00.000Z' } - : profile), - })).toThrow('RUNTIME_CATALOG_PROFILE_TRANSITION_MISMATCH'); - }); - - test('retained promotion evidence rejects a post-generation runtime image substitution', () => { - const candidate = catalogPromotionCandidate(committedCatalog, buildInputs, statements(), TRIGGERS); - const altered = structuredClone(candidate); - altered.runtimes[0].image = altered.runtimes[0].image.replace(/[a-f0-9]{64}$/, 'e'.repeat(64)); - expect(altered.promotion!.evidenceDigest).toBe(candidate.promotion!.evidenceDigest); - expect(() => validateRuntimeCatalog(altered)).toThrow('RUNTIME_PROMOTION_EVIDENCE_MISMATCH'); - expect(() => validateRuntimeCatalogTransition(committedCatalog, altered)).toThrow('RUNTIME_PROMOTION_EVIDENCE_MISMATCH'); - }); -}); - -describe('CSO reviewed base version probes', () => { - test('uses only real executables declared by each base profile', () => { - const rows = imageBuildMatrix(buildInputs).include.filter(row => row.platform === 'linux/amd64'); - expect(probesForBuildRow(rows.find(row => row.stack === 'node')!).map(item => item.name)).toEqual(['node', 'npm']); - expect(probesForBuildRow(rows.find(row => row.stack === 'bun')!).map(item => item.name)).toEqual(['bun']); - expect(probesForBuildRow(rows.find(row => row.stack === 'python')!).map(item => item.name)).toEqual(['python', 'uv']); - expect(probesForBuildRow(rows.find(row => row.stack === 'rails')!).map(item => item.name)).toEqual(['ruby', 'bundler']); - expect(probesForBuildRow(rows.find(row => row.stack === 'postgresql')!).map(item => item.name)).toEqual(['postgresql']); - }); - - test('rejects a probe that reports any different release', () => { - expect(() => assertVersionOutput('node', '24.4.0', 'v24.4.0\n')).not.toThrow(); - expect(() => assertVersionOutput('node', '24.4.0', 'v24.5.0\n')).toThrow('RUNTIME_VERSION_MISMATCH'); - expect(() => assertVersionOutput('bundler', '2.6.7', 'Bundler version 2.6.7\n')).not.toThrow(); - }); -}); - -/** staged-image.json records exactly as the stage job writes them. */ -function stagedRecords(): Record[] { - return statements().map(({ checks: _checks, qualifiedAt: _qualifiedAt, state: _state, ...statement }) => ({ - ...statement, state: 'staged', verifiedProvenance: true, qualification: 'pending native and private release gates; no automatic promotion', - })); -} - -describe('CSO evaluation-only runtime catalogs', () => { - test('one staging run yields an evaluation catalog with no measured release gate', () => { - const candidate = evaluationCandidateCatalog(committedCatalog, buildInputs, stagedRecords(), '2026-10-05T00:00:00.000Z'); - expect(candidate.revision).toBe(`cso-eval-123456-${'a'.repeat(12)}`); - expect(isEvaluationRuntimeCatalog(candidate)).toBe(true); expect(isEvaluationRuntimeCatalog(committedCatalog as any)).toBe(false); - expect(candidate.promotion).toBeUndefined(); expect(candidate.evaluation?.workflow).toBe('https://github.com/garrytan/gstack/actions/runs/123456'); - expect(candidate.runtimes.every(runtime => runtime.state === 'evaluation_candidate' && runtime.qualification.kind === 'evaluation')).toBe(true); - expect(JSON.stringify(candidate)).not.toMatch(/Passed/); - expect(validateEvaluationCandidate(candidate, buildInputs)).toBe(candidate); - expect(() => validateEvaluationCandidate(committedCatalog, buildInputs)).toThrow('NOT_AN_EVALUATION_CATALOG'); - }); - test('evaluation-candidate --created-at writes identical catalog bytes on every platform build', () => { - const staged = mkdtempSync(join(tmpdir(), 'cso-staged-')); - try { - stagedRecords().forEach((record, index) => { mkdirSync(join(staged, `row-${index}`)); writeFileSync(join(staged, `row-${index}`, 'staged-image.json'), JSON.stringify(record)); }); - const build = (name: string, ...extra: string[]) => { - const output = join(staged, name); - const result = spawnSync('bun', ['scripts/cso-runtime-promotion.ts', 'evaluation-candidate', '--staged-root', staged, '--output', output, ...extra], { cwd: join(import.meta.dir, '..'), encoding: 'utf8', timeout: 30_000 }); - expect(result.status).toBe(0); - return readFileSync(output, 'utf8'); - }; - const [amd64, arm64] = ['amd64.json', 'arm64.json'].map(name => build(name, '--created-at', '2026-10-11T07:05:00.000Z')); - expect(arm64).toBe(amd64); - expect(JSON.parse(amd64).runtimes.every((runtime: { qualifiedAt: string }) => runtime.qualifiedAt === '2026-10-11T07:05:00.000Z')).toBe(true); - expect(JSON.parse(build('now.json')).runtimes[0].qualifiedAt).not.toBe('2026-10-11T07:05:00.000Z'); - } finally { rmSync(staged, { recursive: true, force: true }); } - }); - test('staging records must come from one run and match the reviewed build rows', () => { - const split = stagedRecords(); split[1].workflow = 'https://github.com/garrytan/gstack/actions/runs/999'; - expect(() => evaluationCandidateCatalog(committedCatalog, buildInputs, split, '2026-10-05T00:00:00.000Z')).toThrow('SPLIT_STAGING_RUN'); - const unstaged = stagedRecords(); unstaged[0].state = 'qualified'; - expect(() => evaluationCandidateCatalog(committedCatalog, buildInputs, unstaged, '2026-10-05T00:00:00.000Z')).toThrow('INVALID_STAGED_RUNTIME'); - const moved = stagedRecords(); moved[0].buildRevision = 'other-build-revision'; - expect(() => evaluationCandidateCatalog(committedCatalog, buildInputs, moved, '2026-10-05T00:00:00.000Z')).toThrow('QUALIFICATION_BUILD_MISMATCH'); - expect(() => evaluationCandidateCatalog(committedCatalog, buildInputs, stagedRecords().slice(1), '2026-10-05T00:00:00.000Z')).toThrow('INCOMPLETE_QUALIFICATION_MATRIX'); - }); - test('evaluation and release catalogs cannot borrow each other\'s shape', () => { - const candidate = evaluationCandidateCatalog(committedCatalog, buildInputs, stagedRecords(), '2026-10-05T00:00:00.000Z'); - const rebound = structuredClone(candidate); rebound.revision = `cso-eval-999-${'a'.repeat(12)}`; - expect(() => validateRuntimeCatalog(rebound)).toThrow('INVALID_EVALUATION_RUNTIME_CATALOG'); - const promoted = structuredClone(candidate) as any; promoted.promotion = { ...promoted.evaluation, qualificationEvidenceDigest: digest('x'), requalification: TRIGGERS }; delete promoted.evaluation; - expect(() => validateRuntimeCatalog(promoted)).toThrow('INVALID_EVALUATION_RUNTIME_CATALOG'); - const disguised = structuredClone(candidate) as any; disguised.revision = `cso-v3-123456-${'a'.repeat(12)}`; - expect(() => validateRuntimeCatalog(disguised)).toThrow('UNQUALIFIED_RUNTIME'); - const gated = structuredClone(candidate) as any; gated.runtimes[0].qualification.heldOutRepairPassed = true; - expect(() => validateRuntimeCatalog(gated)).toThrow('INVALID_EVALUATION_RUNTIME'); - const released = catalogPromotionCandidate(committedCatalog, buildInputs, statements(), TRIGGERS) as any; - released.revision = `cso-eval-123456-${'a'.repeat(12)}`; - expect(() => validateRuntimeCatalog(released)).toThrow('UNQUALIFIED_RUNTIME'); - }); - test('promotion and catalog transitions refuse evaluation catalogs', () => { - const candidate = evaluationCandidateCatalog(committedCatalog, buildInputs, stagedRecords(), '2026-10-05T00:00:00.000Z'); - expect(() => catalogPromotionCandidate(candidate, buildInputs, statements(), TRIGGERS)).toThrow('EVALUATION_CATALOG_NOT_PROMOTABLE'); - expect(() => validateRuntimeCatalogTransition(committedCatalog, candidate)).toThrow('EVALUATION_CATALOG_NOT_PROMOTABLE'); - expect(() => validateRuntimeCatalogTransition(candidate, catalogPromotionCandidate(committedCatalog, buildInputs, statements(), TRIGGERS))).toThrow('EVALUATION_CATALOG_NOT_PROMOTABLE'); - expect(isEvaluationRuntimeCatalog(committedCatalog as any)).toBe(false); - }); -}); - -/** preparationSha256 recorded by staging run 39325583697 at 133cb36 (cso-requalification-triggers), before S1. */ -const RUN5_RECORD = 'b069f7ef9b19dba9a770cac02a5b6b4b5d60fa68ac058321864b614de14d59f6'; -const HELPERS = ['lib/cso/verifier.ts', 'lib/cso/preparation-container.ts']; -const CHECKOUT = join(import.meta.dir, '..'); - -describe.skipIf(process.platform === 'win32')('CSO release contract preparation fingerprint', () => { - const temps: string[] = []; - afterEach(() => { for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true }); }); - const rewrite = (root: string, file: string, change: (lines: string[]) => void) => { - const lines = readFileSync(join(root, file), 'utf8').split('\n'); change(lines); writeFileSync(join(root, file), lines.join('\n')); - }; - /** A copy of the checkout's tracked lib/ tree, optionally edited. */ - const trackedLib = (edit?: (root: string) => void): string => { - const root = mkdtempSync(join(tmpdir(), 'cso-release-contract-')); temps.push(root); - const listed = spawnSync('git', ['ls-files', '-z', 'lib'], { cwd: CHECKOUT, encoding: 'utf8', timeout: 30_000, maxBuffer: 16 * 1024 * 1024 }); - expect(listed.status).toBe(0); - for (const file of listed.stdout.split('\0').filter(Boolean)) { - mkdirSync(dirname(join(root, file)), { recursive: true }); - copyFileSync(join(CHECKOUT, file), join(root, file)); - } - edit?.(root); - return root; - }; - const current = (edit?: (root: string) => void) => requalificationTriggers(trackedLib(edit)); - /** The staged commit, rebuilt in a scratch repository: this tree with both helpers' S1 shebang reverted. */ - const stagedCommit = () => { - const repo = trackedLib(root => { for (const helper of HELPERS) rewrite(root, helper, lines => { lines[0] = '#!/usr/bin/env bun'; }); }); - for (const args of [['init', '-q'], ['add', '-A'], ['commit', '-q', '-m', 'staged']]) expect(gitArgvIn(repo, args, 30_000).status).toBe(0); - const commit = gitArgvIn(repo, ['rev-parse', 'HEAD'], 30_000).stdout.toString().trim(); - return { repo, commit, evidence: statements().map(statement => ({ ...statement, sourceCommit: commit })) }; - }; - - test('the run-5 record is this tree with S1\'s shebangs reverted, and the release contract accepts it under the current rule', async () => { - const staged = stagedCommit(); - const measured = await committedPreparation(staged.commit, staged.repo); - const main = await current(); - const record = { ...main, preparationSha256: RUN5_RECORD }; - if (measured.legacy !== RUN5_RECORD) { - // An image source moved since run 5 beyond the shebangs, so its record can no longer be released. - await expect(releaseCandidate(staged.evidence, record, main, staged.repo)).rejects.toThrow(/STALE_RUNTIME_QUALIFICATION|REQUALIFICATION_TRIGGERS_MISMATCH/); - return; - } - // The same SHA-256 over every image source byte: the rebuilt commit is 133cb36's image source, byte for byte. - expect(main.preparationSha256).not.toBe(RUN5_RECORD); - expect(measured.current).toBe(main.preparationSha256); - const released = await releaseCandidate(staged.evidence, record, main, staged.repo); - expect(released.promotion!.requalification).toEqual(main); - }, 120_000); - - test('the release contract ignores only a compiled helper\'s leading #! line, on both sides', async () => { - const staged = stagedCommit(); - const legacy = (await committedPreparation(staged.commit, staged.repo)).legacy; - const recordFor = (triggers: Awaited>, preparationSha256 = legacy) => ({ ...triggers, preparationSha256 }); - const release = (triggers: Awaited>, preparationSha256?: string) => - releaseCandidate(staged.evidence, recordFor(triggers, preparationSha256), triggers, staged.repo); - - const main = await current(); - expect((await release(main)).promotion!.requalification.preparationSha256).toBe(main.preparationSha256); - for (const helper of HELPERS) { - expect((await current(root => rewrite(root, helper, lines => { lines[0] = '#!/usr/bin/env node'; }))).preparationSha256).toBe(main.preparationSha256); - const drifted = await current(root => rewrite(root, helper, lines => { lines.splice(1, 0, '// drift'); })); - await expect(release(drifted)).rejects.toThrow('STALE_RUNTIME_QUALIFICATION: preparationSha256'); - } - await expect(release(await current(root => writeFileSync(join(root, 'lib/cso/images/rails.Dockerfile'), '\n', { flag: 'a' })))).rejects.toThrow('STALE_RUNTIME_QUALIFICATION: preparationSha256'); - await expect(release(await current(root => rewrite(root, 'lib/cso/images/entrypoint', lines => { lines[0] = '#!/bin/bash'; })))).rejects.toThrow('STALE_RUNTIME_QUALIFICATION: preparationSha256'); - await expect(release(main, 'd'.repeat(64))).rejects.toThrow('REQUALIFICATION_TRIGGERS_MISMATCH'); - const recordedUnderCurrentRule = await releaseCandidate(staged.evidence, main, main, join(tmpdir(), 'no-such-checkout')); - expect(recordedUnderCurrentRule.promotion!.requalification).toEqual(main); - }, 180_000); -}); diff --git a/test/cso-scanner-cli.test.ts b/test/cso-scanner-cli.test.ts deleted file mode 100644 index 83a3d42eb..000000000 --- a/test/cso-scanner-cli.test.ts +++ /dev/null @@ -1,81 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import { join, resolve } from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { withLock } from '../lib/cso/state'; - -const launcher = resolve(import.meta.dir, '../bin/gstack-cso-launcher'); -let root = '', repo = '', state = '', sarif = ''; -const env = () => ({ HOME: root, GSTACK_HOME: state, PATH: '/usr/bin:/bin' }); -function command(args: string[], extra: Record = {}) { return spawnSync(launcher, args, { cwd: repo, env: { ...env(), ...extra }, encoding: 'utf8', timeout: 30000 }); } -function start() { - const r = command(['start', '--repo', repo, '--offline']); expect(r.status).toBe(0); - const report = JSON.parse(r.stdout), dir = join(state, 'security/cso', report.repoId, report.runId); - return { runId: report.runId as string, dir, report: () => JSON.parse(fs.readFileSync(join(dir, 'report.json'), 'utf8')), artifacts: () => fs.existsSync(join(dir, 'scanner-outcomes')) ? fs.readdirSync(join(dir, 'scanner-outcomes')) : [] }; -} -beforeAll(() => { - root = fs.mkdtempSync(join(fs.realpathSync(os.tmpdir()), 'cso-scanner-cli-')); repo = join(root, 'repo'); state = join(root, 'state'); fs.mkdirSync(repo); - for (const args of [['init', '-q'], ['config', 'user.email', 'test@example.test'], ['config', 'user.name', 'Test']]) { const r = spawnSync('/usr/bin/git', ['-C', repo, ...args], { env: env(), encoding: 'utf8', timeout: 30000 }); expect(r.status).toBe(0); } - fs.writeFileSync(join(repo, 'app.js'), 'export const example = true;\n'); - for (const args of [['add', 'app.js'], ['commit', '-qm', 'fixture']]) expect(spawnSync('/usr/bin/git', ['-C', repo, ...args], { env: env(), encoding: 'utf8', timeout: 30000 }).status).toBe(0); - sarif = join(root, 'results.sarif'); fs.writeFileSync(sarif, JSON.stringify({ version: '2.1.0', runs: [{ tool: { driver: { name: 'CodeQL', version: '2.22.0' } }, results: [{ ruleId: 'js/test', message: { text: 'Candidate defect' }, locations: [{ physicalLocation: { artifactLocation: { uri: 'app.js' }, region: { startLine: 1 } } }] }] }] })); -}); -afterAll(() => fs.rmSync(root, { recursive: true, force: true })); - -describe('compiled scanner evidence persistence', () => { - test('scan without a locally present qualified image records helper-owned coverage without host execution', () => { - // No usable Docker here (a dead socket): a machine with Docker and a pulled image would otherwise scan. - const run = start(), r = command(['scan', run.runId, 'gitleaks'], { DOCKER_HOST: `unix://${join(root, 'no-docker.sock')}` }); expect(r.status).toBe(0); - const out = JSON.parse(r.stdout); expect(out.status).toBe('not_assessed'); expect(out.gaps[0].message).toMatch(/^No qualified gitleaks|^Pinned runtime image is not already present locally: \S+@sha256:[a-f0-9]{64}$|^Pinned local Docker socket is unavailable$|^docker is not installed in a trusted system executable directory$/); - expect(out.artifactId).toMatch(/^gitleaks-[a-f0-9]{16}-[a-f0-9]{16}$/); - expect(run.artifacts()).toEqual([`${out.artifactId}.json`]); - const stored = JSON.parse(fs.readFileSync(join(run.dir,out.artifact), 'utf8')); const shipped = JSON.parse(fs.readFileSync(join(import.meta.dir, '../lib/cso/scanner-images/catalog.json'), 'utf8')).scanners.find((p: any) => p.scanner === 'gitleaks' && p.platform === (process.arch === 'arm64' ? 'linux/arm64' : 'linux/amd64')); expect(stored.provenance.image).toBe(shipped?.image ?? null); expect(stored.outcome).not.toHaveProperty('repair'); - expect(run.report().coverage.find((x: any) => x.domain === 'scanner:gitleaks')).toMatchObject({ status: 'not_assessed' }); - }); - test('trivy SARIF whose ROOTPATH is the started checkout imports its findings (#3011)', () => { - const run = start(), doc = JSON.parse(fs.readFileSync(resolve(import.meta.dir, 'fixtures/cso-sarif/trivy-0.75.0-fs.sarif'), 'utf8')); - doc.runs[0].originalUriBaseIds.ROOTPATH.uri = `file://${repo}/`; - const file = join(root, 'trivy.sarif'); fs.writeFileSync(file, JSON.stringify(doc)); - const r = command(['import-sarif', run.runId, file]); expect(r.status).toBe(0); - const out = JSON.parse(r.stdout); expect(out.gaps).toEqual([]); expect(out.candidates.map((c: any) => c.location.path)).toEqual(['Dockerfile', 'Dockerfile']); - }); - test('repeated same-content SARIF imports get distinct immutable artifacts and coverage records', () => { - const run = start(), first = command(['import-sarif', run.runId, sarif]); expect(first.status).toBe(0); - const firstOut = JSON.parse(first.stdout), before = fs.readFileSync(join(run.dir,firstOut.artifact), 'utf8'); - const second = command(['import-sarif', run.runId, sarif]); expect(second.status).toBe(0); const secondOut = JSON.parse(second.stdout); - expect(firstOut.artifactId).not.toBe(secondOut.artifactId); expect(run.artifacts()).toHaveLength(2); expect(fs.readFileSync(join(run.dir,firstOut.artifact), 'utf8')).toBe(before); - const coverage = run.report().coverage.filter((x: any) => x.domain === 'scanner:sarif'); expect(coverage).toHaveLength(2); - expect(coverage.every((x: any) => x.evidence.some((e: string) => e.startsWith('Immutable outcome:')))).toBe(true); - }); - test('model submissions cannot erase a scanner failure or replace imported scanner evidence', () => { - const run = start(); expect(command(['scan', run.runId, 'gitleaks']).status).toBe(0); - const reportBefore = fs.readFileSync(join(run.dir, 'report.json'), 'utf8'); - const file = join(root, 'scanner-coverage.json'); fs.writeFileSync(file, JSON.stringify({ coverage: [{ domain: 'scanner:gitleaks', scope: 'default', status: 'assessed', method: 'model says clean', gaps: [], exclusions: [], evidence: ['claim'] }] })); - const r = command(['submit', run.runId, file]); expect(r.status).not.toBe(0); expect(r.stderr).toContain('helper-owned'); expect(fs.readFileSync(join(run.dir, 'report.json'), 'utf8')).toBe(reportBefore); - }); - test('finished reports reject scanner execution and SARIF persistence without changing artifacts', () => { - const run = start(); expect(command(['finish', run.runId]).status).toBe(0); const before = fs.readFileSync(join(run.dir, 'report.json'), 'utf8'); - for (const args of [['scan', run.runId, 'gitleaks'], ['import-sarif', run.runId, sarif]]) { const r = command(args); expect(r.status).not.toBe(0); expect(r.stderr).toContain('running audit'); } - expect(run.artifacts()).toEqual([]); expect(fs.readFileSync(join(run.dir, 'report.json'), 'utf8')).toBe(before); - }); - test('a live mutation lock protects both scan and SARIF writes', () => { - const run = start(); - const before = fs.readFileSync(join(run.dir, 'report.json'), 'utf8'); - withLock(run.dir,()=>{for (const args of [['scan', run.runId, 'gitleaks'], ['import-sarif', run.runId, sarif]]) { const r = command(args); expect(r.status).not.toBe(0); expect(r.stderr).toContain('INSUFFICIENT_CAPACITY'); }}); - expect(run.artifacts()).toEqual([]); expect(fs.readFileSync(join(run.dir, 'report.json'), 'utf8')).toBe(before); - }); - test('concurrent imports preserve every successful artifact and never lose a coverage update', async () => { - const run = start(); - const attempt = async () => { const child = Bun.spawn([launcher, 'import-sarif', run.runId, sarif], { cwd: repo, env: env(), stdout: 'pipe', stderr: 'pipe' }); const [code, stdout, stderr] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]); return { code, stdout, stderr }; }; - const results = await Promise.all([attempt(), attempt()]), successes = results.filter(r => r.code === 0); - expect(successes.length).toBeGreaterThan(0); for (const failure of results.filter(r => r.code !== 0)) expect(failure.stderr).toContain('INSUFFICIENT_CAPACITY'); - expect(run.artifacts()).toHaveLength(successes.length); expect(run.report().coverage.filter((c: any) => c.domain === 'scanner:sarif')).toHaveLength(successes.length); - expect(new Set(successes.map(r => JSON.parse(r.stdout).artifactId)).size).toBe(successes.length); - }); - test('malformed SARIF remains a persisted coverage failure', () => { - const run = start(), malformed = join(root, 'broken.sarif'); fs.writeFileSync(malformed, '{'); - const r = command(['import-sarif', run.runId, malformed]); expect(r.status).toBe(0); expect(JSON.parse(r.stdout).status).toBe('not_assessed'); - expect(run.report().coverage.find((c: any) => c.domain === 'scanner:sarif')).toMatchObject({ status: 'not_assessed' }); - }); -}); diff --git a/test/cso-scanner-docker-integration.test.ts b/test/cso-scanner-docker-integration.test.ts deleted file mode 100644 index 94bedb69f..000000000 --- a/test/cso-scanner-docker-integration.test.ts +++ /dev/null @@ -1,122 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { canonical, sha256 } from '../lib/cso/contracts'; -import { dockerEndpoint, ISOLATION_POLICY_HASH } from '../lib/cso/docker'; -import { createDockerScannerRunner, ScannerRunInput } from '../lib/cso/scanner-executor'; -import { QualifiedRuntime } from '../lib/cso/runtime-catalog'; -import { assertScannerVersionOutput, QualifiedScanner, scannerVersionHash } from '../lib/cso/scanner-catalog'; -import { ScannerId, parseScannerOutput, scannerPlans } from '../lib/cso/scanners'; -import { secureDirectory } from '../lib/cso/state'; - -const requested = process.env.GSTACK_CSO_SCANNER_DOCKER_TESTS === '1'; -const suite = requested ? describe : describe.skip; -const HASH = 'a'.repeat(64), DIGEST = `sha256:${HASH}`; -let root = '', source = '', watchdog = '', staged: any; - -describe('scanner qualification version evidence',()=>{ - test.each([ - ['gitleaks','gitleaks version 8.30.1','8.30.1'], - ['osv','osv-scanner version: 2.4.0','2.4.0'], - ['semgrep','1.136.0','1.136.0'], - ['zizmor','zizmor 1.11.2','1.11.2'], - ['trivy','Version: 0.67.2','0.67.2'], - ['schemathesis','schemathesis, version 4.5.2','4.5.2'], - ] as const)('accepts a supported real version layout: %s %s',(scanner,output,version)=>{ - expect(()=>assertScannerVersionOutput(scanner,version,`${output}\n`)).not.toThrow(); - }); - test.each(['11.2.3','1.2.30','1.2.3-dev','prefix1.2.3','1.2.3suffix'])('rejects a substring version match: %s',output=>{ - expect(()=>assertScannerVersionOutput('gitleaks','1.2.3',output)).toThrow('exact catalog version'); - }); - test('rejects an expected version that appears only in secondary metadata',()=>{ - expect(()=>assertScannerVersionOutput('gitleaks','1.2.3','gitleaks version 9.9.9\nruntime 1.2.3\n')).toThrow('primary version'); - }); - test('uses the same 8192-byte output boundary as production execution',()=>{ - const prefix='gitleaks version 1.2.3\n',within=prefix+'x'.repeat(8192-Buffer.byteLength(prefix)); - expect(()=>assertScannerVersionOutput('gitleaks','1.2.3',within)).not.toThrow(); - expect(()=>assertScannerVersionOutput('gitleaks','1.2.3',within+'x')).toThrow('bounded output'); - }); -}); - -function write(name: string, body: string): void { - const target = path.join(source, name); fs.mkdirSync(path.dirname(target), { recursive: true }); fs.writeFileSync(target, body, { mode: 0o600 }); -} -function fixture(): void { - write('app.js', 'export const scannerQualification = true;\n'); - write('package.json', '{"name":"cso-scanner-qualification","version":"1.0.0","dependencies":{"lodash":"4.17.20"}}\n'); - write('package-lock.json', '{"name":"cso-scanner-qualification","version":"1.0.0","lockfileVersion":3,"packages":{"":{"name":"cso-scanner-qualification","version":"1.0.0","dependencies":{"lodash":"4.17.20"}},"node_modules/lodash":{"version":"4.17.20","resolved":"https://registry.npmjs.org/lodash/-/lodash-4.17.20.tgz","integrity":"sha512-PlhdFcillOINfeV7Ni6oF1TAEayyZBoZ8bcshTHqOYJYlrqzRK5hagpagky5o4HfCzzd1TRkXPMFq6cKk9rGmA=="}}}\n'); - write('.github/workflows/qualification.yml', 'name: qualification\non: [push]\npermissions: {}\njobs:\n test:\n runs-on: ubuntu-latest\n steps:\n - run: echo qualification\n'); - write('server.py', [ - 'from http.server import BaseHTTPRequestHandler, HTTPServer', - 'class H(BaseHTTPRequestHandler):', - ' def do_GET(self):', - " body = b'CONTROL_OK' if self.path == '/control' else b'[]'", - ' self.send_response(200)', - " self.send_header('Content-Type', 'application/json')", - " self.send_header('Content-Length', str(len(body)))", - ' self.end_headers(); self.wfile.write(body)', - ' def log_message(self, *args): pass', - "HTTPServer(('127.0.0.1', 34620), H).serve_forever()", - ].join('\n') + '\n'); -} -function request() { - return { api: { runtimeProfile: 'qualification-runtime', port: 34620, - start: { executable: staged.applicationExecutable, args: ['server.py'] }, - control: { name: 'qualification control', path: '/control', method: 'GET' as const, expected: { status: 200, includes: 'CONTROL_OK' } }, - boundaryFiles: ['server.py'], operationIds: ['listItems'], - schema: { openapi: '3.1.0', info: { title: 'CSO scanner qualification', version: '1.0.0' }, paths: { '/items': { get: { operationId: 'listItems', responses: { '200': { description: 'items' } } } } } } } }; -} - -beforeAll(async () => { - if (!requested) return; - const file = process.env.GSTACK_CSO_SCANNER_PROFILE; - if (!file) throw new Error('Scanner Docker qualification requires GSTACK_CSO_SCANNER_PROFILE'); - staged = JSON.parse(fs.readFileSync(file, 'utf8')); - if (!['gitleaks', 'osv', 'semgrep', 'zizmor', 'trivy', 'schemathesis'].includes(staged.scanner) || !/^.+@sha256:[a-f0-9]{64}$/.test(staged.image) || !/^[0-9][A-Za-z0-9.+_-]{0,100}$/.test(staged.version) || !Array.isArray(staged.capabilities)) throw new Error('Scanner Docker qualification profile is invalid'); - if (staged.isolationPolicyHash !== ISOLATION_POLICY_HASH) throw new Error('Scanner Docker qualification profile does not match the helper isolation policy'); - if (!process.env.GSTACK_CSO_SCANNER_VERSION_HASH) throw new Error('Scanner Docker qualification requires GSTACK_CSO_SCANNER_VERSION_HASH'); - const platform = process.arch === 'arm64' ? 'linux/arm64' : 'linux/amd64'; - if (staged.platform !== platform) throw new Error(`Scanner Docker qualification requires native ${platform}`); - if (staged.scanner === 'schemathesis' && (typeof staged.applicationExecutable !== 'string' || !staged.applicationExecutable.startsWith('/'))) throw new Error('Schemathesis qualification requires its reviewed fixture runtime executable'); - root = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'cso-scanner-docker-')); - source = secureDirectory(path.join(root, 'snapshot')); fixture(); - process.env.GSTACK_HOME = path.join(root, 'state'); - watchdog = path.resolve(import.meta.dir, '../bin/gstack-cso-watchdog'); - if (!fs.existsSync(watchdog)) throw new Error('Scanner Docker qualification requires the compiled watchdog'); - await dockerEndpoint(secureDirectory(path.join(root, 'docker-home')), { HOME: root, DOCKER_HOST: process.env.DOCKER_HOST ?? 'unix:///var/run/docker.sock' }); -}); -afterAll(() => { if (root) fs.rmSync(root, { recursive: true, force: true }); delete process.env.GSTACK_HOME; }); - -suite('qualified CSO scanner image', () => { - test('runs the exact adapter through DockerGroup with network-none inputs and bounded normalization', async () => { - const id = staged.scanner as ScannerId, api = id === 'schemathesis' ? request().api : undefined; - const plan = scannerPlans({ snapshotRoot: '/source', offline: true, selected: [id], deadlineSeconds: 120, - tools: { [id]: { available: true, version: staged.version, capabilities: staged.capabilities } }, - semgrepRules: staged.assets?.semgrepRules?.path, advisoryCache: staged.assets?.advisoryDatabase?.path, - ...(api ? { schemaPath: '/policy/openapi.json', baseUrl: `http://127.0.0.1:${api.port}/`, operationIds: api.operationIds, seed: 1, maxExamples: 3 } : {}) })[0]; - expect(plan.prerequisites).toEqual([]); - expect(plan.network).toBe(id === 'schemathesis' ? 'loopback' : 'none'); - const profile: QualifiedScanner = { id: `qualification-${id}`, scanner: id, state: 'qualified', platform: staged.platform, image: staged.image, - entrypoint: '/opt/cso/entrypoint', executable: '/opt/cso/bin/scanner', version: staged.version, versionOutputSha256: HASH, helperAbi: 3, - isolationPolicyHash: staged.isolationPolicyHash, capabilities: staged.capabilities, ...(staged.assets ? { assets: staged.assets } : {}), - qualifiedAt: '2026-01-01T00:00:00.000Z', qualification: { sourceCommit: 'a'.repeat(40), workflow: 'https://github.com/example/example/actions/runs/1', sbomDigest: DIGEST, provenanceDigest: DIGEST, verifiedProvenance: true, containmentPassed: true, adapterContractPassed: true, offlineAssetsPassed: true } }; - const manifest = { version: 3 as const, root: source, createdAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 60_000).toISOString(), entries: [], headCommit: 'a'.repeat(40), originalHash: sha256(canonical([])), executionHash: sha256(canonical([])) }; - const input: ScannerRunInput = { id, runId: `scanner-qualification-${Date.now()}`, runDir: root, manifest, policy: { mode: 'comprehensive', scope: 'qualification', diff: false, base: 'HEAD', offline: true, budgetSeconds: 600, maxWorkers: 3, maxRepairs: 3 }, executionDeadline: Date.now() + 120_000, platform: staged.platform, watchdogPath: watchdog, ...(api ? { request: { api } } : {}) }; - let runtime: QualifiedRuntime | undefined, application: any; - if (api) { - runtime = { id: 'qualification-runtime', stack: 'python', platform: staged.platform, state: 'qualified', image: staged.image, entrypoint: '/opt/cso/entrypoint', helperAbi: 3, versions: { python: '3.14.0', uv: '1.0.0', 'cso-preparation': '1.0.0' }, policyVersion: 'cso-isolation-v1', qualifiedAt: '2026-01-01T00:00:00.000Z', qualification: { kind: 'application', sourceCommit: 'a'.repeat(40), workflow: 'https://github.com/example/example/actions/runs/1', sbomDigest: DIGEST, provenanceDigest: DIGEST, verifiedProvenance: true, containmentPassed: true, coldStartPassed: true, positiveNegativeAssertionsPassed: true, heldOutRepairPassed: true } }; - application = { sourceRoot: source, environment: { PATH: '/usr/local/bin:/usr/bin:/bin', PYTHONUNBUFFERED: '1' }, proof: { dependencyClosureHash: HASH, preparedManifestHash: HASH, sourceProjectionHash: HASH, receiptHash: HASH, executionEnvironmentHash: HASH, databaseHash: HASH }, cleanup: async () => {} }; - } - const runner = await createDockerScannerRunner({ input, plan, profile, runtime, application, deadline: input.executionDeadline }); - try { - const version = await runner.version(); - expect(version.exitCode).toBe(0); expect(version.timedOut).not.toBe(true); expect(version.truncated).not.toBe(true); - assertScannerVersionOutput(id,staged.version,version.stdout,version.stderr); - profile.versionOutputSha256 = scannerVersionHash(version.stdout, version.stderr); - const execution = await runner.scan(), outcome = parseScannerOutput(plan, { ...execution, version: staged.version, databaseUpdatedAt: staged.assets?.advisoryDatabase?.updatedAt }); - expect(outcome.status).toBe('complete'); expect(outcome.gaps).toEqual([]); expect(outcome.version).toBe(staged.version); - fs.writeFileSync(path.resolve(process.env.GSTACK_CSO_SCANNER_VERSION_HASH!), `${profile.versionOutputSha256}\n`, { flag: 'wx', mode: 0o600 }); - } finally { await runner.cleanup(); } - }, 180_000); -}); diff --git a/test/cso-scanner-executor.test.ts b/test/cso-scanner-executor.test.ts deleted file mode 100644 index bae145946..000000000 --- a/test/cso-scanner-executor.test.ts +++ /dev/null @@ -1,227 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import { join } from 'node:path'; -import { CsoError, SnapshotManifest, canonical, sha256, snapshotPathHandle, snapshotPathId } from '../lib/cso/contracts'; -import { ISOLATION_POLICY_HASH } from '../lib/cso/docker'; -import { QualifiedScanner, SCANNER_CATALOG, ScannerCatalog, scannerVersionHash, selectScanner, validateScannerCatalog } from '../lib/cso/scanner-catalog'; -import { ScannerRequest, ScannerRunInput, ScannerRunnerContext, executeScanner, prepareDockerScannerApplication, schemathesisControlRole, validateScannerRequest } from '../lib/cso/scanner-executor'; -import { total } from '../lib/cso/admission'; -import { SCANNER_IDS, ScannerExecution, ScannerId, scannerPlans } from '../lib/cso/scanners'; -import { type PreparationSandboxRunner } from '../lib/cso/preparation-executor'; -import { canonicalStartPlan } from '../lib/cso/verification'; -import { completeRuntimeCatalogFixture, unqualifiedRuntimeCatalog } from './helpers/cso-runtime-catalog'; - -const roots: string[] = []; -afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); -const HASH = 'a'.repeat(64), DIGEST = `sha256:${HASH}`; -const version = (id: ScannerId) => `${id} version ${id === 'osv' ? '2.4.0' : '4.0.0'}\n`; -function profile(id: ScannerId, platform: 'linux/amd64' | 'linux/arm64' = 'linux/amd64'): QualifiedScanner { - const arch = platform.endsWith('arm64') ? 'arm64' : 'amd64'; - return { id: `${id}-test-${arch}`, scanner: id, state: 'qualified', platform, image: `ghcr.io/garrytan/gstack/cso-scanners/${id}-${arch}@${DIGEST}`, - entrypoint: '/opt/cso/entrypoint', executable: '/opt/cso/bin/scanner', version: id === 'osv' ? '2.4.0' : '4.0.0', versionOutputSha256: scannerVersionHash(version(id)), helperAbi: 3, isolationPolicyHash: ISOLATION_POLICY_HASH, - capabilities: scannerPlans({ snapshotRoot: '/source', offline: true, selected: [id] })[0].requiredFeatures, - ...(id === 'semgrep' ? { assets: { semgrepRules: { path: '/policy/catalog/semgrep.yml', sha256: HASH } } } : {}), - ...(['osv', 'trivy'].includes(id) ? { assets: { advisoryDatabase: { path: '/opt/cso/scanner-data/db', contentSha256: HASH, updatedAt: '2026-09-09T00:00:00.000Z', ecosystems: ['npm'] } } } : {}), - qualifiedAt: '2026-09-09T00:00:00.000Z', qualification: { sourceCommit: 'b'.repeat(40), workflow: 'https://github.com/garrytan/gstack/actions/runs/42', sbomDigest: DIGEST, provenanceDigest: DIGEST, verifiedProvenance: true, containmentPassed: true, adapterContractPassed: true, offlineAssetsPassed: true } }; -} -function catalog(..._ids: ScannerId[]): ScannerCatalog { - const scanners = SCANNER_IDS.flatMap(id => [profile(id), profile(id, 'linux/arm64')]); - return { schemaVersion: 1, helperAbi: 3, revision: 'unit-fixture-only', promotion: { sourceCommit: 'b'.repeat(40), workflow: 'https://github.com/garrytan/gstack/actions/runs/42', evidenceDigest: `sha256:${sha256(canonical(scanners))}` }, scanners }; -} -const EMPTY_CATALOG = { schemaVersion: 1, revision: 'cso-scanners-v3-unqualified', previousRevision: null, helperAbi: 3, scanners: [] } as unknown as ScannerCatalog; -const scannerProfile = (c: ScannerCatalog, id: ScannerId, platform: 'linux/amd64' | 'linux/arm64' = 'linux/amd64') => c.scanners.find(item => item.scanner === id && item.platform === platform)!; -const runtimes = completeRuntimeCatalogFixture('scanner-runtime-fixture'); -function request(): ScannerRequest { - return { api: { runtimeProfile: 'node', port: 3100, start: { executable: '/usr/local/bin/node', args: ['app.js'] }, control: { name: 'legitimate user', path: '/users', method: 'GET', expected: { status: 200, includes: 'users' } }, boundaryFiles: ['app.js'], operationIds: ['readUsers'], schema: { openapi: '3.1.0', info: { title: 'Unit fixture', version: '1.0.0' }, paths: { '/users': { get: { operationId: 'readUsers', responses: { '200': { description: 'Users' } } } } } } } }; -} -function input(id: ScannerId): ScannerRunInput { - const dir = fs.mkdtempSync(join(fs.realpathSync(os.tmpdir()), 'cso-scanner-executor-')); roots.push(dir); - const root = join(dir, 'snapshot'); fs.mkdirSync(root, { mode: 0o700 }); - const files = { 'app.js': 'export const app = true;\n', 'package.json': '{"name":"fixture","version":"1.0.0"}\n', 'package-lock.json': '{"name":"fixture","version":"1.0.0","lockfileVersion":3,"packages":{"":{"name":"fixture","version":"1.0.0"}}}\n' }; - const entries = Object.entries(files).map(([path, body]) => { fs.writeFileSync(join(root, path), body, { mode: 0o600 }); return { path, pathId: snapshotPathId(root,path), originalHash: sha256(body), executionHash: sha256(body), mode: 0o600, bytes: Buffer.byteLength(body) }; }).sort((a, b) => a.path.localeCompare(b.path)); - const manifest: SnapshotManifest = { version: 3, root, createdAt: new Date().toISOString(), expiresAt: new Date(Date.now() + 86400000).toISOString(), entries, headCommit: 'b'.repeat(40), originalHash: sha256(canonical(entries.map(e => [e.path, e.originalHash, e.mode]))), executionHash: sha256(canonical(entries.map(e => [e.path, e.executionHash, e.mode]))) }; - return { id, runId: 'unit-scanner-run', runDir: dir, manifest, policy: { mode: id === 'schemathesis' ? 'comprehensive' : 'daily', scope: 'default', diff: false, base: 'origin/main', offline: true, budgetSeconds: 600, maxWorkers: 3, maxRepairs: 3 }, executionDeadline: Date.now() + 300000, platform: 'linux/amd64', watchdogPath: '/trusted/test-watchdog', ...(id === 'schemathesis' ? { request: request() } : {}) }; -} -function preparedApplication(spec: ScannerRunInput, cleanup: () => void = () => {}) { - return { sourceRoot: join(spec.runDir, 'snapshot'), environment: { PATH: '/usr/local/bin:/usr/bin:/bin' }, - proof: { dependencyClosureHash: HASH, preparedManifestHash: HASH, sourceProjectionHash: HASH, receiptHash: HASH, executionEnvironmentHash: HASH, databaseHash: HASH }, - cleanup: async () => { cleanup(); } }; -} -function result(id: ScannerId): ScannerExecution { - const data: Record = { - gitleaks: [{ RuleID: 'test-rule', Description: 'Candidate secret', File: '/source/app.js', StartLine: 1 }], - osv: { results: [{ source: { path: '/source/package-lock.json' }, packages: [{ package: { name: 'fixture-package', version: '1.0.0', ecosystem: 'npm' }, vulnerabilities: [{ id: 'CVE-2026-12345', summary: 'Candidate dependency defect' }] }] }] }, - semgrep: { results: [{ check_id: 'test-rule', path: '/source/app.js', start: { line: 1, col: 1 }, extra: { message: 'Candidate code defect', severity: 'ERROR' } }], errors: [], paths: { scanned: ['/source/app.js'] } }, - zizmor: { version: '2.1.0', runs: [{ tool: { driver: { name: 'zizmor', version: '4.0.0' } }, results: [{ ruleId: 'test-rule', message: { text: 'Candidate workflow defect' }, locations: [{ physicalLocation: { artifactLocation: { uri: 'app.js' }, region: { startLine: 1 } } }] }] }] }, - trivy: { SchemaVersion: 2, Results: [{ Target: 'app.js', Secrets: [{ RuleID: 'test-rule', Title: 'Candidate secret', Severity: 'HIGH', StartLine: 1 }] }] }, - schemathesis: { schemathesis_version: '4.0.0', complete: true, stop_reason: 'completed', operations: { selected: 1, tested: 1, errored: 0, skipped: 0 }, errors: [], failures: [{ type: 'ServerError', title: 'Candidate API failure', severity: 'high', operations: ['GET /users'] }] }, - }; - return { stdout: JSON.stringify(data[id]), stderr: '', exitCode: id === 'gitleaks' ? 10 : ['osv', 'schemathesis'].includes(id) ? 1 : 0 }; -} - -describe('reviewed scanner catalog contract', () => { - test('the shipped catalog has no executable unqualified fallback', () => { - validateScannerCatalog(SCANNER_CATALOG); - for (const profile of SCANNER_CATALOG.scanners) expect([profile.state, profile.image]).toEqual(['qualified', expect.stringMatching(/@sha256:[a-f0-9]{64}$/)]); - for (const id of SCANNER_IDS) for (const platform of ['linux/amd64', 'linux/arm64'] as const) - if (!SCANNER_CATALOG.scanners.some(profile => profile.scanner === id && profile.platform === platform)) expect(() => selectScanner(id, platform)).toThrow('No qualified'); - expect(() => selectScanner('gitleaks', 'linux/amd64', undefined, EMPTY_CATALOG)).toThrow('No qualified'); - }); - test.each(SCANNER_IDS)('selects a qualified immutable %s profile', id => { const c = catalog(id); validateScannerCatalog(c); expect(selectScanner(id, 'linux/amd64', undefined, c)).toEqual(scannerProfile(c, id)); }); - test.each(['tag', 'entrypoint', 'policy', 'abi', 'qualification', 'executable', 'version', 'capabilities'])('rejects unreviewed %s', field => { - const c = catalog('gitleaks'), p = scannerProfile(c, 'gitleaks') as any; - if (field === 'tag') p.image = 'gitleaks:latest'; - if (field === 'entrypoint') p.entrypoint = '/bin/sh'; - if (field === 'policy') p.isolationPolicyHash = HASH; - if (field === 'abi') p.helperAbi = 2; - if (field === 'qualification') p.qualification.verifiedProvenance = false; - if (field === 'executable') p.executable = '/source/scanner'; - if (field === 'version') p.versionOutputSha256 = 'unknown'; - if (field === 'capabilities') p.capabilities = []; - expect(() => validateScannerCatalog(c)).toThrow(); - }); - test('missing IDs, duplicates, and platform substitution are rejected', () => { - const c = catalog('gitleaks'); delete (scannerProfile(c, 'gitleaks') as any).id; expect(() => validateScannerCatalog(c)).toThrow(); - const duplicate = catalog('gitleaks'); duplicate.scanners[1].id = duplicate.scanners[0].id; expect(() => validateScannerCatalog(duplicate)).toThrow(); - expect(() => selectScanner('gitleaks', 'linux/arm64', 'missing-profile', catalog('gitleaks'))).toThrow('No qualified'); - }); - test('rules and databases cannot point into repository source or mutable work space', () => { - const rules = catalog('semgrep'); scannerProfile(rules, 'semgrep').assets!.semgrepRules!.path = '/source/rules.yml'; expect(() => validateScannerCatalog(rules)).toThrow(); - const db = catalog('osv'); scannerProfile(db, 'osv').assets!.advisoryDatabase!.path = '/work/cache'; expect(() => validateScannerCatalog(db)).toThrow(); - }); - test('rejects a self-asserted partial catalog even when its one profile is otherwise plausible', () => { - const c = catalog('gitleaks'); c.scanners = [scannerProfile(c, 'gitleaks')]; expect(() => validateScannerCatalog(c)).toThrow('Incompatible scanner catalog'); - }); -}); - -describe('all six helper-owned scanner execution paths', () => { - test.each(SCANNER_IDS)('%s reaches version, scan, normalization, and cleanup through an injected runner', async id => { - const calls: string[] = []; let captured: ScannerRunnerContext | undefined; - const spec = input(id), record = await executeScanner(spec, { catalog: catalog(id), runtimes, - ...(id === 'schemathesis' ? { applicationPreparer: async () => preparedApplication(spec) } : {}), - runnerFactory: async context => { captured = context; return { version: async () => { calls.push('version'); return { stdout: version(id), exitCode: 0 }; }, scan: async () => { calls.push('scan'); return result(id); }, cleanup: async () => { calls.push('cleanup'); } }; } }); - expect(calls).toEqual(['version', 'scan', 'cleanup']); - expect(captured!.plan.execution).toBe('sandbox'); - expect(captured!.plan.network).toBe(id === 'schemathesis' ? 'loopback' : 'none'); - expect(captured!.plan.args.join(' ')).not.toMatch(/download|--network|docker.sock|--metrics=on/); - expect(captured!.deadline).toBeLessThanOrEqual(Date.now() + 300000); - expect(record.outcome.status).toBe('complete'); expect(record.outcome.candidates).toHaveLength(1); - expect(record.outcome.candidates[0]).toMatchObject({ evidence: 'scanner-candidate', trust: 'untrusted' }); - expect(record.outcome.candidates[0]).not.toHaveProperty('reproduced'); expect(record.outcome.candidates[0]).not.toHaveProperty('repair'); - expect(record.coverage).toMatchObject({ domain: `scanner:${id}`, status: 'assessed' }); - expect(record.provenance.versionOutputSha256).toBe(profile(id).versionOutputSha256); - expect(record.provenance.image).toBe(profile(id).image); - if (id === 'schemathesis') { expect(captured!.application?.sourceRoot).toBe(join(spec.runDir, 'snapshot')); expect(record.provenance.preparation?.dependencyClosureHash).toBe(HASH); } - else expect(record.provenance.preparation).toBeNull(); - if (id === 'osv' || id === 'trivy') expect(record.outcome.databaseUpdatedAt).toBe('2026-09-09T00:00:00.000Z'); - }); - test('missing catalog never creates a runner and records the exact prerequisite', async () => { - let calls = 0; const out = await executeScanner(input('gitleaks'), { catalog: EMPTY_CATALOG, runnerFactory: async () => { calls++; throw new Error('must not run'); } }); - expect(calls).toBe(0); expect(out.coverage.status).toBe('not_assessed'); expect(out.outcome.gaps[0].message).toContain('No qualified gitleaks'); - }); - test.each(['semgrep', 'osv', 'trivy'] as ScannerId[])('%s missing baked assets cannot launch a scanner or download replacements', async id => { - let calls = 0; const c = catalog(id); delete scannerProfile(c, id).assets; - const out = await executeScanner(input(id), { catalog: c, runnerFactory: async () => { calls++; throw new Error('must not run'); } }); - expect(calls).toBe(0); expect(out.outcome.status).toBe('not_assessed'); expect(out.outcome.gaps[0].code).toBe('PREREQUISITE'); - }); - test('version mismatch cleans up without scanning', async () => { - const calls: string[] = []; - const out = await executeScanner(input('gitleaks'), { catalog: catalog('gitleaks'), runnerFactory: async () => ({ version: async () => ({ stdout: 'different version', exitCode: 0 }), scan: async () => { calls.push('scan'); return result('gitleaks'); }, cleanup: async () => { calls.push('cleanup'); } }) }); - expect(calls).toEqual(['cleanup']); expect(out.outcome.status).toBe('not_assessed'); expect(out.outcome.version).toBeNull(); expect(out.outcome.gaps[0].message).toContain('version output'); - }); - test('an exact output hash cannot launder a substring version mismatch',async()=>{ - const c=catalog('gitleaks'),p=scannerProfile(c,'gitleaks'),reported='gitleaks version 14.0.0\n',calls:string[]=[]; - p.versionOutputSha256=scannerVersionHash(reported);c.promotion!.evidenceDigest=`sha256:${sha256(canonical(c.scanners))}`; - const out=await executeScanner(input('gitleaks'),{catalog:c,runnerFactory:async()=>({version:async()=>({stdout:reported,exitCode:0}),scan:async()=>{calls.push('scan');return result('gitleaks');},cleanup:async()=>{calls.push('cleanup');}})}); - expect(calls).toEqual(['cleanup']);expect(out.outcome.status).toBe('not_assessed');expect(out.outcome.gaps[0].message).toContain('exact catalog version'); - }); - test.each([['timeout', 'TIMEOUT'], ['redaction', 'REDACTION_FAILED'], ['invalid-output', 'INVALID_OUTPUT'], ['tool', 'TOOL_FAILED'], ['cleanup', 'ISOLATION_FAILED']] as const)('%s preserves truthful scanner coverage', async (failure, code) => { - let cleaned = false; - const out = await executeScanner(input('gitleaks'), { catalog: catalog('gitleaks'), runnerFactory: async () => ({ version: async () => ({ stdout: version('gitleaks'), exitCode: 0 }), scan: async () => { if (failure === 'timeout') throw new CsoError('DEADLINE', 'Scanner timed out'); if (failure === 'redaction') throw new CsoError('REDACTION_FAILED', 'Scanner output withheld'); if (failure === 'tool') throw new CsoError('TOOL_FAILED', 'Scanner process failed'); return failure === 'invalid-output' ? { stdout: '{', exitCode: 0 } : result('gitleaks'); }, cleanup: async () => { cleaned = true; if (failure === 'cleanup') throw new CsoError('ISOLATION_FAILED', 'Exact cleanup failed'); } }) }); - expect(cleaned).toBe(true); expect(out.outcome.status).toBe('not_assessed'); expect(out.outcome.candidates).toEqual([]); expect(out.outcome.gaps[0].code).toBe(code); - }); - test('online policy still supplies only offline scanner plans', async () => { - const spec = input('osv'); spec.policy.offline = false; - await executeScanner(spec, { catalog: catalog('osv'), runnerFactory: async c => { expect(c.plan.network).toBe('none'); expect(c.plan.args).toContain('--offline'); return { version: async () => ({ stdout: version('osv'), exitCode: 0 }), scan: async () => result('osv'), cleanup: async () => {} }; } }); - }); - test('expired or changed retained source cannot enter the runner', async () => { - for (const expired of [true, false]) { - const spec = input('gitleaks'); if (expired) spec.manifest.expiresAt = '2000-01-01T00:00:00.000Z'; else fs.writeFileSync(join(spec.runDir, 'snapshot/app.js'), 'changed'); - let calls = 0; const out = await executeScanner(spec, { catalog: catalog('gitleaks'), runnerFactory: async () => { calls++; throw new Error('must not run'); } }); - expect(calls).toBe(0); expect(out.outcome.status).toBe('not_assessed'); - } - }); - test('source changed during collection invalidates the candidate evidence', async () => { - const spec = input('gitleaks'); - const out = await executeScanner(spec, { catalog: catalog('gitleaks'), runnerFactory: async () => ({ version: async () => ({ stdout: version('gitleaks'), exitCode: 0 }), scan: async () => { fs.writeFileSync(join(spec.runDir, 'snapshot/app.js'), 'racing change'); return result('gitleaks'); }, cleanup: async () => {} }) }); - expect(out.outcome.candidates).toEqual([]); expect(out.outcome.gaps[0].message).toContain('snapshot changed'); - }); - test('deadline is subordinate to the reporting reserve', async () => { - const spec = input('gitleaks'); spec.executionDeadline = Date.now() - 1; let calls = 0; - const out = await executeScanner(spec, { catalog: catalog('gitleaks'), runnerFactory: async () => { calls++; throw new Error('must not run'); } }); - expect(calls).toBe(0); expect(out.outcome.gaps[0].code).toBe('TIMEOUT'); - }); -}); - -describe('Schemathesis application admission', () => { - test('opaque boundary and startup handles resolve only against the retained manifest',async()=>{ - const spec=input('schemathesis'),raw=request(),app=spec.manifest.entries.find(entry=>entry.path==='app.js')!,handle=snapshotPathHandle(app.pathId);raw.api!.boundaryFiles=[handle];raw.api!.start.args=[handle];spec.request=raw;let captured:ScannerRunnerContext|undefined; - const record=await executeScanner(spec,{catalog:catalog('schemathesis'),runtimes,applicationPreparer:async()=>preparedApplication(spec),runnerFactory:async context=>{captured=context;return{version:async()=>({stdout:version('schemathesis'),exitCode:0}),scan:async()=>result('schemathesis'),cleanup:async()=>{}};}}); - expect(record.outcome.status).toBe('complete');expect(captured!.input.request!.api).toMatchObject({boundaryFiles:['app.js'],start:{args:['app.js']}});expect(record.provenance.requestHash).toBe(sha256(canonical(validateScannerRequest(raw,'schemathesis')))); - }); - test('Rails with PostgreSQL and its control verifier fits the aggregate group admission', () => { - expect(schemathesisControlRole()).toBe('verifier'); - expect(total(['anchor', 'postgres', 'app', schemathesisControlRole()]).memoryMiB).toBe(3904); - expect(() => total(['anchor', 'postgres', 'app', 'tests'])).toThrow('aggregate reproduction-group limit'); - }); - test('daily mode blocks application execution before creating a runner', async () => { - const spec = input('schemathesis'); spec.policy.mode = 'daily'; let calls = 0; - const out = await executeScanner(spec, { catalog: catalog('schemathesis'), runtimes, runnerFactory: async () => { calls++; throw new Error('must not run'); } }); - expect(calls).toBe(0); expect(out.outcome.gaps[0].message).toContain('comprehensive mode'); - }); - test('transformed security boundaries block API execution', async () => { - const spec = input('schemathesis'); spec.manifest.entries.find(e => e.path === 'app.js')!.transformation = 'sanitized'; let calls = 0; - const out = await executeScanner(spec, { catalog: catalog('schemathesis'), runtimes, runnerFactory: async () => { calls++; throw new Error('must not run'); } }); - expect(calls).toBe(0); expect(out.outcome.gaps[0].message).toContain('boundary is missing or transformed'); - }); - test('no runtime profile means a prerequisite, not a scanner success', async () => { - const out = await executeScanner(input('schemathesis'), { catalog: catalog('schemathesis'), runtimes: unqualifiedRuntimeCatalog() }); - expect(out.outcome.status).toBe('not_assessed'); expect(out.outcome.gaps[0].message).toContain('runtime is unavailable'); - }); - test.each(['remote-ref', 'server', 'hook', 'callback', 'operation', 'unbounded', 'source-command'])('rejects hostile or ambiguous %s harness input', kind => { - const raw = request() as any; - if (kind === 'remote-ref') raw.api.schema.components = { schemas: { User: { $ref: 'https://example.test/user.json' } } }; - if (kind === 'server') raw.api.schema.servers = [{ url: 'https://example.test' }]; - if (kind === 'hook') raw.api.schema['x-hooks'] = 'module.py'; - if (kind === 'callback') raw.api.schema.callbacks = {}; - if (kind === 'operation') raw.api.operationIds = ['not-declared']; - if (kind === 'unbounded') raw.api.maxExamples = 100000; - if (kind === 'source-command') raw.api.start = { executable: 'node', args: [] }; - expect(() => validateScannerRequest(raw, 'schemathesis')).toThrow(); - }); - test('rejects an absolute synthetic server and startup boundaries that omit the canonical entrypoint', async () => { - for (const kind of ['synthetic', 'missing-entrypoint'] as const) { - const spec = input('schemathesis'), api = spec.request!.api!; let prepared = 0, runners = 0; - if (kind === 'synthetic') api.start = { executable: '/usr/local/bin/node', args: ['-e', "require('http').createServer((q,s)=>s.end('synthetic')).listen(3100)"] }; - else api.boundaryFiles = ['package.json']; - const out = await executeScanner(spec, { catalog: catalog('schemathesis'), runtimes, - applicationPreparer: async () => { prepared++; return preparedApplication(spec); }, - runnerFactory: async () => { runners++; throw new Error('must not run'); } }); - expect(prepared).toBe(0); expect(runners).toBe(0); expect(out.outcome.status).toBe('not_assessed'); - expect(out.outcome.gaps[0].message).toMatch(/helper-derived|canonical startup input/); - } - }); - test('materialized application cleanup failure withholds otherwise complete API coverage', async () => { - const spec = input('schemathesis'); - const out = await executeScanner(spec, { catalog: catalog('schemathesis'), runtimes, - applicationPreparer: async () => ({ ...preparedApplication(spec), cleanup: async () => { throw new CsoError('ISOLATION_FAILED', 'prepared source cleanup failed'); } }), - runnerFactory: async () => ({ version: async () => ({ stdout: version('schemathesis'), exitCode: 0 }), scan: async () => result('schemathesis'), cleanup: async () => {} }) }); - expect(out.outcome.status).toBe('not_assessed'); expect(out.outcome.candidates).toEqual([]); expect(out.outcome.gaps[0].message).toContain('cleanup failed'); - }); - test('scanner preparation construction failure preserves Docker watchdog journals for detached recovery',async()=>{const spec=input('schemathesis'),snapshot=join(spec.runDir,'snapshot'),integrity=Buffer.alloc(64,7).toString('base64');spec.policy.offline=false;fs.writeFileSync(join(snapshot,'package.json'),JSON.stringify({name:'fixture',version:'1.0.0',dependencies:{cookie:'1.0.0'}}));fs.writeFileSync(join(snapshot,'package-lock.json'),JSON.stringify({name:'fixture',lockfileVersion:3,packages:{'':{name:'fixture',version:'1.0.0',dependencies:{cookie:'1.0.0'}},'node_modules/cookie':{name:'cookie',version:'1.0.0',resolved:'https://registry.npmjs.org/cookie/-/cookie-1.0.0.tgz',integrity:`sha512-${integrity}`}}}));const runtime=runtimes.runtimes.find(item=>item.stack==='node'&&item.platform==='linux/amd64')!,qualification={schemaVersion:1 as const,helperAbi:3,runnerId:'scanner-construction-fault',policyVersion:'cso-preparation-v1' as const,supportedStacks:['node','bun','python','rails'] as any,registryRestrictionQualified:true as const,dnsRebindingTestsPassed:true as const,acquisitionExcludesSource:true as const,offlineContainmentQualified:true as const,immutableArchiveMounts:true as const,resourceLimitsEnforced:true as const};let control='';const runnerFactory=(options:any):PreparationSandboxRunner=>({qualification,acquire:async()=>{control=join(options.controlRoot,'acquisition-fault');fs.mkdirSync(control,{recursive:true});fs.writeFileSync(join(control,'watchdog.ready'),'ready\n',{mode:0o600});fs.writeFileSync(join(control,'watchdog.event'),'cleanup incomplete; retrying exact journaled resources\n',{mode:0o600});fs.writeFileSync(join(control,'resources.journal'),`container:${'a'.repeat(64)}\n`,{mode:0o600});throw new CsoError('ISOLATION_FAILED','Exact preparation cleanup failed; detached watchdog remains responsible');},prepareOffline:async()=>{throw new Error('must not prepare');},disposePrepared:()=>{}});await expect(prepareDockerScannerApplication({input:spec,runtime,stack:'node',startPlan:canonicalStartPlan(snapshot,'node',3100),deadline:Date.now()+30_000,catalog:runtimes},{endpoint:{} as any,runnerFactory,cacheRoot:join(spec.runDir,'cache')})).rejects.toThrow('detached watchdog remains responsible');expect(fs.existsSync(join(control,'resources.journal'))).toBe(true);expect(fs.existsSync(join(control,'watchdog.ready'))).toBe(true);expect(fs.existsSync(control)).toBe(true);}); - test('static scanners cannot accept application commands or arbitrary extra runner fields', () => { - expect(() => validateScannerRequest(request(), 'semgrep')).toThrow('Only Schemathesis'); - expect(() => validateScannerRequest({ image: 'evil:latest' }, 'gitleaks')).toThrow('Unexpected'); - }); -}); diff --git a/test/cso-scanner-release.test.ts b/test/cso-scanner-release.test.ts deleted file mode 100644 index fae0c7e7f..000000000 --- a/test/cso-scanner-release.test.ts +++ /dev/null @@ -1,177 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { spawnSync } from 'node:child_process'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { ISOLATION_POLICY_HASH } from '../lib/cso/docker'; -import { sha256 } from '../lib/cso/contracts'; -import { SCANNER_CATALOG, ScannerCatalog, scannerVersionHash } from '../lib/cso/scanner-catalog'; -import { SCANNER_IDS, ScannerId, scannerPlans } from '../lib/cso/scanners'; -import { scannerCatalogProposal, scannerAssetHash, validateScannerCatalogTransition } from '../scripts/cso-scanner-catalog'; -import { scannerBuildMatrix } from '../scripts/cso-scanner-matrix'; -import { verifiedStatementSetDigest } from '../scripts/cso-attestation-evidence'; - -const ROOT = path.resolve(import.meta.dir, '..'), HASH = 'a'.repeat(64), DIGEST = `sha256:${HASH}`; -const temps: string[] = []; -afterEach(() => { for (const dir of temps.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); }); -const image = (id: string) => `ghcr.io/garrytan/gstack/cso-scanners/${id}@sha256:${HASH}`; -const attested=(id:string,repository=`https://github.com/example/${id}`)=>({image:image(id),repository,sourceCommit:'b'.repeat(40),release:`v${id}-1.2.3`,signerWorkflow:`example/${id}/.github/workflows/release.yml`,signerDigest:'c'.repeat(40),provenanceStatementDigest:DIGEST,sbomStatementDigest:DIGEST}); -function reviewedInputs() { - return { schemaVersion: 1, helperAbi: 3, state: 'reviewed', sbomGenerator: attested('sbom'), profiles: SCANNER_IDS.map(scanner => ({ - scanner, version: scanner === 'gitleaks' ? '8.30.1' : '1.2.3', executable: `/usr/local/bin/${scanner === 'osv' ? 'osv-scanner' : scanner}`, - baseImages: { 'linux/amd64': attested(`${scanner}-base-amd64`, `https://github.com/example/${scanner}`), 'linux/arm64': attested(`${scanner}-base-arm64`, `https://github.com/example/${scanner}`) }, - ...(scanner === 'semgrep' ? { assets: { semgrepRules: { path: '/policy/catalog/semgrep.yml', sha256: HASH } } } - : ['osv', 'trivy'].includes(scanner) ? { assets: { advisoryDatabase: { path: `/opt/cso/scanner-data/${scanner}`, contentSha256: HASH, updatedAt: '2026-09-10T00:00:00.000Z', ecosystems: ['npm', 'PyPI'] } } } : {}), - ...(scanner === 'schemathesis' ? { applicationExecutable: '/usr/local/bin/python' } : {}), - })) }; -} -function qualified(scanner: ScannerId, platform: 'linux/amd64' | 'linux/arm64') { - const arch = platform.endsWith('arm64') ? 'arm64' : 'amd64', version = scanner === 'gitleaks' ? '8.30.1' : '1.2.3'; - return { id: `${scanner}-${version}-${arch}`, scanner, state: 'qualified' as const, platform, image: image(`${scanner}-${arch}`), entrypoint: '/opt/cso/entrypoint' as const, executable: '/opt/cso/bin/scanner', version, - versionOutputSha256: scannerVersionHash(`${scanner} ${version}\n`), helperAbi: 3 as const, isolationPolicyHash: ISOLATION_POLICY_HASH, - capabilities: scannerPlans({ snapshotRoot: '/source', offline: true, selected: [scanner] })[0].requiredFeatures, - ...(scanner === 'semgrep' ? { assets: { semgrepRules: { path: '/policy/catalog/semgrep.yml', sha256: HASH } } } - : ['osv', 'trivy'].includes(scanner) ? { assets: { advisoryDatabase: { path: `/opt/cso/scanner-data/${scanner}`, contentSha256: HASH, updatedAt: '2026-09-10T00:00:00.000Z', ecosystems: ['npm'] } } } : {}), - qualifiedAt: '2026-09-10T00:00:00.000Z', qualification: { sourceCommit: 'c'.repeat(40), workflow: 'https://github.com/garrytan/gstack/actions/runs/42', sbomDigest: DIGEST, provenanceDigest: DIGEST, verifiedProvenance: true as const, containmentPassed: true as const, adapterContractPassed: true as const, offlineAssetsPassed: true as const } }; -} - -describe('CSO scanner release inputs', () => { - test('requires all six scanners on both native architectures with derived adapter capabilities', () => { - const matrix = scannerBuildMatrix(reviewedInputs()); expect(matrix.include).toHaveLength(12); - for (const scanner of SCANNER_IDS) { - const rows = matrix.include.filter(row => row.scanner === scanner); - expect(rows.map(row => row.platform)).toEqual(['linux/amd64', 'linux/arm64']); - expect(rows.map(row => row.runner)).toEqual(['ubuntu-24.04', 'ubuntu-24.04-arm']); - expect(rows[0].capabilities).toEqual([...scannerPlans({ snapshotRoot: '/source', offline: true, selected: [scanner] })[0].requiredFeatures].sort()); - } - }); - test('pending, partial, mutable, assetless, or unverified input cannot publish', () => { - const pending = reviewedInputs() as any; pending.state = 'pending'; expect(() => scannerBuildMatrix(pending)).toThrow('MISSING_REVIEWED_SCANNER_INPUTS'); - const partial = reviewedInputs() as any; partial.profiles.pop(); expect(() => scannerBuildMatrix(partial)).toThrow('INCOMPLETE_SCANNER_MATRIX'); - const tagged = reviewedInputs() as any; tagged.profiles[0].baseImages['linux/amd64'].image = 'ghcr.io/example/gitleaks:latest'; expect(() => scannerBuildMatrix(tagged)).toThrow('INVALID_UPSTREAM_EVIDENCE'); - const assetless = reviewedInputs() as any; delete assetless.profiles.find((p: any) => p.scanner === 'osv').assets; expect(() => scannerBuildMatrix(assetless)).toThrow('MISSING_OFFLINE_ASSET'); - const unverified = reviewedInputs() as any; delete unverified.profiles[0].baseImages['linux/amd64'].signerDigest; expect(() => scannerBuildMatrix(unverified)).toThrow('INVALID_UPSTREAM_EVIDENCE'); - const generator = reviewedInputs() as any; generator.sbomGenerator.provenanceStatementDigest = 'unreviewed'; expect(() => scannerBuildMatrix(generator)).toThrow('UNVERIFIED_SBOM_GENERATOR'); - }); - test('binds verified attestation statements to the reviewed subject and predicate',()=>{ - const predicate='https://slsa.dev/provenance/v1',statement={_type:'https://in-toto.io/Statement/v1',subject:[{name:'image',digest:{sha256:HASH}}],predicateType:predicate,predicate:{buildType:'https://example.test/builder'}}; - const value=[{attestation:{},verificationResult:{statement}}],digest=verifiedStatementSetDigest(value,predicate,HASH); - expect(digest).toMatch(/^sha256:[a-f0-9]{64}$/);expect(verifiedStatementSetDigest(value,predicate,HASH)).toBe(digest); - expect(()=>verifiedStatementSetDigest(value,'https://spdx.dev/Document/v2.3',HASH)).toThrow('VERIFIED_ATTESTATION_IDENTITY_MISMATCH'); - expect(()=>verifiedStatementSetDigest(value,predicate,'d'.repeat(64))).toThrow('VERIFIED_ATTESTATION_IDENTITY_MISMATCH'); - }); - test('paths and matrix strings cannot inject build commands', () => { - for (const executable of ['/usr/bin/scanner;id', '../../scanner', '/usr/bin/scan ner', '/usr/bin/scanner\nBAD=1']) { - const input = reviewedInputs() as any; input.profiles[0].executable = executable; expect(() => scannerBuildMatrix(input)).toThrow('INVALID_SCANNER_EXECUTABLE'); - } - const extra = reviewedInputs() as any; extra.profiles[0].buildArgs = ['EVIL=1']; expect(() => scannerBuildMatrix(extra)).toThrow('INVALID_SCANNER_PROFILE'); - }); -}); - -describe('CSO scanner catalog promotion', () => { - const expected = { sourceCommit: 'c'.repeat(40), workflow: 'https://github.com/garrytan/gstack/actions/runs/42', imagePrefix: 'ghcr.io/garrytan/gstack/cso-scanners/' }; - const fragments = () => SCANNER_IDS.flatMap(scanner => ['linux/amd64', 'linux/arm64'].map(platform => qualified(scanner, platform as any))); - test('assembles only a complete qualified matrix and records rollback identity', () => { - const proposal = scannerCatalogProposal(SCANNER_CATALOG, fragments(), 'cso-scanners-qualified-42', expected); - expect(proposal.scanners).toHaveLength(12); expect(proposal.previousRevision).toBe(SCANNER_CATALOG.revision); - expect(proposal.promotion).toMatchObject({ sourceCommit: expected.sourceCommit, workflow: expected.workflow }); - expect(proposal.promotion!.evidenceDigest).toMatch(/^sha256:[a-f0-9]{64}$/); - expect(proposal.scanners.map(profile => `${profile.scanner}:${profile.platform}`)).toEqual([...proposal.scanners.map(profile => `${profile.scanner}:${profile.platform}`)].sort()); - }); - test('rejects missing platforms, claimed capabilities, provenance substitution, and foreign image repositories', () => { - const missing = fragments(); missing.pop(); expect(() => scannerCatalogProposal(SCANNER_CATALOG, missing, 'missing-profile', expected)).toThrow('INCOMPLETE_SCANNER_CATALOG_MATRIX'); - const capabilities = fragments() as any[]; capabilities[0].capabilities = ['invented']; expect(() => scannerCatalogProposal(SCANNER_CATALOG, capabilities, 'bad-capability', expected)).toThrow('capabilities do not match'); - const source = fragments() as any[]; source[0].qualification.sourceCommit = 'd'.repeat(40); expect(() => scannerCatalogProposal(SCANNER_CATALOG, source, 'wrong-source', expected)).toThrow('SOURCE_COMMIT_MISMATCH'); - const foreign = fragments() as any[]; foreign[0].image = image('foreign').replace('garrytan/gstack', 'other/repo'); expect(() => scannerCatalogProposal(SCANNER_CATALOG, foreign, 'foreign-image', expected)).toThrow('Scanner profile is not qualified'); - }); - test('promotion is a compare-and-swap against the currently reviewed revision', () => { - const proposal = scannerCatalogProposal(SCANNER_CATALOG, fragments(), 'cso-scanners-qualified-43', expected); - expect(() => validateScannerCatalogTransition(SCANNER_CATALOG, proposal)).not.toThrow(); - expect(() => validateScannerCatalogTransition({ ...SCANNER_CATALOG, revision: 'catalog-advanced-concurrently' }, proposal)).toThrow('SCANNER_CATALOG_BASE_REVISION_MISMATCH'); - }); - test('hashes files and trees deterministically and rejects linked asset payloads', () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-scanner-assets-')); temps.push(root); fs.mkdirSync(path.join(root, 'nested')); fs.writeFileSync(path.join(root, 'nested', 'b'), 'two'); fs.writeFileSync(path.join(root, 'a'), 'one'); - const first = scannerAssetHash(root); expect(first).toMatch(/^[a-f0-9]{64}$/); expect(scannerAssetHash(root)).toBe(first); expect(scannerAssetHash(path.join(root, 'a'))).toBe(sha256('one')); - fs.symlinkSync(path.join(root, 'a'), path.join(root, 'linked')); expect(() => scannerAssetHash(root)).toThrow('UNSAFE_SCANNER_ASSET'); - const top = path.join(path.dirname(root), `${path.basename(root)}-link`); temps.push(top); fs.symlinkSync(root, top); expect(() => scannerAssetHash(top)).toThrow('UNSAFE_SCANNER_ASSET'); - }); -}); - -describe('CSO scanner qualification workflow', () => { - test('keeps branch validation read-only while qualification and promotion are protected-main and review gated', () => { - const raw = fs.readFileSync(path.join(ROOT, '.github/workflows/cso-scanner-images.yml'), 'utf8'), workflow = Bun.YAML.parse(raw) as any; - expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch']); expect(workflow.permissions).toEqual({ contents: 'read' }); expect(workflow.jobs['reviewed-inputs'].if).toBeUndefined(); - const stage = workflow.jobs['stage-and-qualify']; - expect(stage.if).toContain("github.ref == 'refs/heads/main'"); expect(stage.if).toContain("github.event_name == 'workflow_dispatch'"); expect(stage.environment).toBe('cso-scanner-release'); - expect(stage.permissions).toMatchObject({ contents: 'read', packages: 'write', 'id-token': 'write', attestations: 'write', 'artifact-metadata': 'write' }); - const privileged = Object.entries(workflow.jobs).filter(([, job]: any) => ['packages', 'id-token', 'attestations', 'artifact-metadata'].some(permission => job.permissions?.[permission] === 'write')); - expect(privileged.map(([name]) => name)).toEqual(['stage-and-qualify']); - for (const permission of ['packages', 'id-token', 'attestations', 'artifact-metadata']) expect(workflow.jobs['reviewed-inputs'].permissions?.[permission]).toBeUndefined(); - expect(workflow.jobs['promote-catalog'].if).toContain("github.ref == 'refs/heads/main'"); expect(workflow.jobs['promote-catalog'].if).toContain('inputs.promote_catalog == true'); expect(workflow.jobs['promote-catalog'].environment).toBe('cso-scanner-release'); - expect(workflow.jobs['promote-catalog'].permissions.packages).toBe('read'); - expect(raw).toContain('test/cso-scanners.test.ts test/cso-scanner-executor.test.ts test/cso-scanner-release.test.ts'); - expect(raw).toContain('test/cso-scanner-docker-integration.test.ts'); expect(raw).toContain('GSTACK_CSO_SCANNER_VERSION_HASH'); expect(raw).toContain('hash-asset scanner-asset'); - expect(raw).toContain('Require a public package and anonymously load the verified immutable image'); - expect(raw).toContain('scripts/cso-public-ghcr.ts verify'); - expect(raw).toContain('--repository "$GITHUB_REPOSITORY" --output public-image.json'); - expect(raw).toContain('sha256sum "$output" staged-profile.json version.sha256 declared-assets.json public-image.json'); - const anonymousStage = workflow.jobs['stage-and-qualify'].steps.find((step: any) => step.run?.includes('scripts/cso-public-ghcr.ts verify')); - expect(anonymousStage.env.GH_TOKEN).toBe('${{ github.token }}'); - for(const value of ['--signer-workflow "$signer_workflow"','--signer-digest "$signer_digest"','--source-digest "$source_commit"','cso-attestation-evidence.ts digest','provenanceStatementDigest','sbomStatementDigest'])expect(raw).toContain(value); - expect(raw).not.toContain('cso-scanner-staging'); - const docker = fs.readFileSync(path.join(ROOT, 'lib/cso/docker.ts'), 'utf8').replace(/\s+/g, ''); - for (const flag of ["'--pull=never'", "'--read-only'", "'--cap-drop','ALL'", "'no-new-privileges:true'", "'seccomp=builtin'", "'--log-driver=none'", "'--network'"]) expect(docker).toContain(flag); - expect(docker).toContain("['rm','--force','--volumes',id]"); expect(docker).toContain('Pinnedruntimeimagedeclareswritablevolumes'); - expect(raw).toContain('cso-scanner-catalog.ts assemble'); expect(raw).toContain('cso-scanner-catalog.ts validate-transition lib/cso/scanner-images/catalog.json promotion/catalog-proposal.json'); expect(raw).toContain('gh pr create --base main'); - expect(raw).toContain('branch="cso-scanner-catalog-$GITHUB_RUN_ID-$GITHUB_RUN_ATTEMPT"'); expect(raw).not.toContain('branch="cso-scanner-catalog-$GITHUB_RUN_ID"'); - const publicPromotion = raw.indexOf('Recheck public visibility and anonymous pulls before promotion'); - const sourcePromotion = raw.indexOf('Revalidate and open the reviewable source catalog PR'); - expect(publicPromotion).toBeGreaterThanOrEqual(0); expect(sourcePromotion).toBeGreaterThan(publicPromotion); - expect(raw.slice(publicPromotion, sourcePromotion)).toContain('--remove-after'); - for (const job of Object.values(workflow.jobs) as any[]) for (const step of job.steps) if (step.uses) expect(step.uses).toMatch(/@[a-f0-9]{40}$/); - }); - test('commits either the empty placeholder or a complete reviewed matrix, and normalizes scanner images to the constrained helper contract', () => { - const inputs = JSON.parse(fs.readFileSync(path.join(ROOT, 'lib/cso/scanner-images/build-inputs.json'), 'utf8')); - if (inputs.state === 'pending') expect(inputs).toMatchObject({ profiles: [], sbomGenerator: null }); - else expect(scannerBuildMatrix(inputs).include).toHaveLength(12); - const dockerfile = fs.readFileSync(path.join(ROOT, 'lib/cso/scanner-images/scanner.Dockerfile'), 'utf8'); - for (const value of ['/opt/cso/entrypoint', '/opt/cso/bin/scanner', 'USER 10001:10001', 'test -x /bin/sleep', 'test -x /bin/cat']) expect(dockerfile).toContain(value); - expect(fs.readFileSync(path.join(ROOT, 'lib/cso/scanner-executor.ts'), 'utf8')).toContain("capture(['/bin/cat', plan.outputPath], plan.format)"); - const postgres = fs.readFileSync(path.join(ROOT, 'lib/cso/images/postgresql.Dockerfile'), 'utf8'); - for (const value of ['FROM ${BASE_IMAGE} AS upstream', 'FROM scratch', 'COPY --from=upstream / /']) expect(postgres).toContain(value); - }); -}); - -const SBOM_ROOT = path.resolve(import.meta.dir, '..'); -const jq = Bun.which('jq'); -const run = (filter: string, input: unknown, check = false) => spawnSync(jq!, [check ? '-e' : '-c', '-f', path.join(SBOM_ROOT, 'scripts', filter)], { input: JSON.stringify(input), encoding: 'utf8', timeout: 10_000 }); -const document = { - spdxVersion: 'SPDX-2.3', SPDXID: 'SPDXRef-DOCUMENT', name: 'image', - packages: [{ SPDXID: 'SPDXRef-Package-rails', name: 'rails', versionInfo: '8.0.2', hasFiles: ['SPDXRef-File-a'] }, { SPDXID: 'SPDXRef-Package-rack', name: 'rack', versionInfo: '3.1.0' }], - files: [{ SPDXID: 'SPDXRef-File-a', fileName: '/usr/local/bundle/gems/rails/a.rb' }, { SPDXID: 'SPDXRef-File-b', fileName: '/b' }], - relationships: [ - { spdxElementId: 'SPDXRef-DOCUMENT', relationshipType: 'DESCRIBES', relatedSpdxElement: 'SPDXRef-Package-rails' }, - { spdxElementId: 'SPDXRef-Package-rails', relationshipType: 'DEPENDS_ON', relatedSpdxElement: 'SPDXRef-Package-rack' }, - { spdxElementId: 'SPDXRef-Package-rails', relationshipType: 'CONTAINS', relatedSpdxElement: 'SPDXRef-File-a' }, - { spdxElementId: 'SPDXRef-File-b', relationshipType: 'OTHER', relatedSpdxElement: 'SPDXRef-Package-rack' }, - ], -}; - -describe.skipIf(!jq)('CSO signed SBOMs carry the package inventory only', () => { - test('file entries and every relationship that names a file are removed; packages and package edges stay', () => { - const result = run('cso-sbom-packages.jq', document); - expect(result.status, result.stderr).toBe(0); - const compact = JSON.parse(result.stdout); - expect(compact.files).toBeUndefined(); - expect(compact.packages.map((p: any) => [p.name, p.versionInfo, 'hasFiles' in p])).toEqual([['rails', '8.0.2', false], ['rack', '3.1.0', false]]); - expect(compact.relationships.map((r: any) => r.relationshipType)).toEqual(['DESCRIBES', 'DEPENDS_ON']); - expect(run('cso-sbom-packages-check.jq', compact, true).status).toBe(0); - }); - test('the check rejects file-bearing, empty, wrong-version, or dangling documents', () => { - expect(run('cso-sbom-packages-check.jq', document, true).status).not.toBe(0); - const compact = JSON.parse(run('cso-sbom-packages.jq', document).stdout); - expect(run('cso-sbom-packages-check.jq', { ...compact, packages: [] }, true).status).not.toBe(0); - expect(run('cso-sbom-packages-check.jq', { ...compact, spdxVersion: 'SPDX-2.2' }, true).status).not.toBe(0); - expect(run('cso-sbom-packages-check.jq', { ...compact, relationships: [...compact.relationships, { spdxElementId: 'SPDXRef-Package-rails', relationshipType: 'CONTAINS', relatedSpdxElement: 'SPDXRef-File-gone' }] }, true).status).not.toBe(0); - }); -}); diff --git a/test/cso-scanners.test.ts b/test/cso-scanners.test.ts deleted file mode 100644 index 5e352f570..000000000 --- a/test/cso-scanners.test.ts +++ /dev/null @@ -1,440 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import { - importSarif, MAX_SCANNER_OUTPUT_BYTES, parseScannerOutput, scannerLocation, - scannerPlans, validateScannerBaseUrl, type ScannerId, type ScannerPlan, -} from '../lib/cso/scanners'; - -function plan(id: ScannerId): ScannerPlan { - return scannerPlans({ - snapshotRoot: '/src', offline: true, selected: [id], semgrepRules: '/policy/rules.yml', advisoryCache: '/advisories', - schemaPath: '/policy/openapi.json', baseUrl: 'http://127.0.0.1:3000/', operationIds: ['readDocument'], - })[0]; -} - -function parse(id: ScannerId, data: unknown, exitCode = 0) { - return parseScannerOutput(plan(id), { stdout: JSON.stringify(data), exitCode, version: 'scanner 2.3.0', databaseUpdatedAt: '2026-09-09T00:00:00.000Z' }); -} - -function sarif(result?: Record) { - return { version: '2.1.0', runs: [{ tool: { driver: { name: 'CodeQL', version: '2.22.0', rules: [{ id: 'js/sql-injection', defaultConfiguration: { level: 'error' } }] } }, results: result ? [result] : [] }] }; -} -function sarifResult(uri = 'src/routes.ts') { - return { ruleIndex: 0, message: { text: 'Untrusted input reaches a query.' }, locations: [{ physicalLocation: { artifactLocation: { uri }, region: { startLine: 12, startColumn: 3 } } }] }; -} - -describe('CSO scanner execution plans', () => { - test('all six plans require containment and never acquire dependencies or inherit credentials', () => { - const plans = scannerPlans({ snapshotRoot: '/src', offline: false }); - expect(plans.map(p => p.id)).toEqual(['gitleaks', 'osv', 'semgrep', 'zizmor', 'trivy', 'schemathesis']); - for (const p of plans) { - expect(p.execution).toBe('sandbox'); - expect(p.network).toBe(p.id === 'schemathesis' ? 'loopback' : 'none'); - expect(p.timeoutSeconds).toBeLessThanOrEqual(300); - expect(p.maxOutputBytes).toBe(MAX_SCANNER_OUTPUT_BYTES); - expect(Object.keys(p.env)).not.toContain('GITHUB_TOKEN'); - expect(Object.keys(p.env)).not.toContain('PATH'); - expect(p.args.join(' ')).not.toMatch(/npx|uvx|--allow-local-builds|--call-analysis=|--autofix|download-offline/); - expect(p.provenanceSources.length).toBeGreaterThan(0); - } - }); - - test('OSV uses full offline v2 scanning with code analysis disabled', () => { - const p = plan('osv'); - expect(p.args).toContain('--offline'); - expect(p.args).not.toContain('--offline-vulnerabilities'); - expect(p.args).toContain('--no-call-analysis=all'); - expect(p.args.slice(0, 2)).toEqual(['scan', 'source']); - const old = scannerPlans({ snapshotRoot: '/src', offline: true, selected: ['osv'], advisoryCache: '/advisories', tools: { osv: { available: true, version: '1.9.0' } } })[0]; - expect(old.prerequisites.join(' ')).toContain('major version 2'); - }); - - test('Gitleaks scans current files and bypasses project suppressions with full redaction', () => { - const p = plan('gitleaks'); - expect(p.args[0]).toBe('dir'); - expect(p.args).toContain('--redact=100'); - expect(p.args).toContain('--report-path=-'); - expect(p.args).toContain('--ignore-gitleaks-allow'); - expect(p.trustedFiles.some(f => f.content.includes('useDefault = true'))).toBe(true); - const history = scannerPlans({ snapshotRoot: '/src', offline: true, selected: ['gitleaks'], gitHistory: '/history' })[0]; - expect(history.args[0]).toBe('git'); - expect(history.prerequisites.join(' ')).toContain('no hooks'); - }); - - test('Semgrep cannot select hosted rules, upload findings, or enable code builds', () => { - const p = plan('semgrep'); - expect(p.args[0]).toBe('scan'); - expect(p.args).toContain('--metrics=off'); - expect(p.args).toContain('--disable-version-check'); - expect(p.args).toContain('--oss-only'); - expect(() => scannerPlans({ snapshotRoot: '/src', offline: true, semgrepRules: 'p/security-audit' })).toThrow(); - expect(() => scannerPlans({ snapshotRoot: '/src', offline: true, semgrepRules: '/src/rules.yml' })).toThrow(); - }); - - test('zizmor ignores environment online defaults and repo config', () => { - const p = plan('zizmor'); - expect(p.args).toContain('--offline'); - expect(p.args).toContain('--no-config'); - expect(p.args).toContain('--no-ignores'); - expect(p.env.ZIZMOR_OFFLINE).toBe('1'); - }); - - test('Trivy suppresses telemetry, metadata calls, version checks, and every database update', () => { - const p = plan('trivy'); - for (const flag of ['--disable-telemetry', '--offline-scan', '--skip-db-update', '--skip-java-db-update', '--skip-check-update', '--skip-version-check', '--skip-vex-repo-update']) expect(p.args).toContain(flag); - expect(p.args).toContain('/policy/trivy.yaml'); - expect(p.args).toContain('/policy/trivyignore'); - }); - - test('Schemathesis restricts operation count, redirects, seed, time, and report location', () => { - const p = plan('schemathesis'); - expect(p.prerequisites).toEqual([]); - for (const arg of ['--workers=1', '--phases=fuzzing', '--max-redirects=0', '--seed', '--max-examples', '--max-time', '--report-json-path', '--include-operation-id']) expect(p.args).toContain(arg); - expect(p.outputPath).toBe('/work/schemathesis.json'); - expect(p.coverage.scope).toEqual(['operation:readDocument']); - expect(() => scannerPlans({ snapshotRoot: '/src', offline: true, schemaPath: 'https://example.test/api.json' })).toThrow(); - }); - - test.each(['http://example.com', 'http://localhost:3000', 'http://169.254.169.254/', 'http://127.1/', 'http://2130706433/', 'http://0x7f000001/', 'http://127.0.0.1.evil.test/', ['http://user:', 'pass@127.0.0.1/'].join(''), 'file:///tmp/app', 'http://[::ffff:127.0.0.1]/', 'http://127.0.0.1/?x=secret'])('rejects non-canonical or credential-bearing target %s', url => { - expect(() => validateScannerBaseUrl(url)).toThrow(); - }); - - test('numeric IPv4 and IPv6 loopback are accepted', () => { - expect(validateScannerBaseUrl('http://127.0.0.1:8080/api')).toBe('http://127.0.0.1:8080/api'); - expect(validateScannerBaseUrl('http://[::1]:8080/api')).toBe('http://[::1]:8080/api'); - }); - - test('invalid bounds and source-controlled policy are rejected before execution', () => { - expect(() => scannerPlans({ snapshotRoot: '/src', offline: true, deadlineSeconds: 301 })).toThrow(); - expect(() => scannerPlans({ snapshotRoot: '/src', offline: true, policyRoot: '/src/policy' })).toThrow(); - expect(() => scannerPlans({ snapshotRoot: '/src', offline: true, advisoryCache: '/src/cache' })).toThrow(); - expect(() => scannerPlans({ snapshotRoot: '/src/../etc', offline: true })).toThrow(); - expect(() => scannerPlans({ snapshotRoot: '/src', offline: true, selected: ['osv', 'osv'] })).toThrow(); - }); -}); - -describe('CSO scanner candidate normalization', () => { - test('Gitleaks retains location and rule while discarding secret-bearing fields', () => { - const secret = 'ghp_' + 'A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8'; - const result = parse('gitleaks', [{ RuleID: 'github-pat', Description: 'Possible token', File: '/src/config.ts', StartLine: 2, StartColumn: 5, Secret: secret, Match: secret, Line: secret, Author: 'person@example.test' }], 10); - expect(result.status).toBe('complete'); - expect(result.candidates[0].location?.path).toBe('config.ts'); - expect(result.candidates[0].evidence).toBe('scanner-candidate'); - expect(result.candidates[0].trust).toBe('untrusted'); - expect(JSON.stringify(result)).not.toContain(secret); - expect(JSON.stringify(result)).not.toContain('person@example.test'); - }); - - test('OSV aliases and affected version never imply reachability or production exposure', () => { - const result = parse('osv', { results: [{ source: { path: '/src/package-lock.json' }, packages: [{ package: { name: 'vulnerable-package', version: '1.0.0', ecosystem: 'npm' }, vulnerabilities: [{ id: 'GHSA-abcd-efgh-ijkl', aliases: ['CVE-2026-12345'], summary: 'Unsafe parsing' }] }] }] }, 1); - expect(result.status).toBe('complete'); - expect(result.candidates[0].dependency).toEqual({ name: 'vulnerable-package', version: '1.0.0', ecosystem: 'npm', reachability: 'unknown', exposure: 'unknown' }); - expect(result.candidates[0].advisoryIds).toContain('CVE-2026-12345'); - }); - - test('Semgrep keeps independent errors even with useful candidates', () => { - const result = parse('semgrep', { results: [{ check_id: 'sql-injection', path: 'api.ts', start: { line: 7, col: 3 }, extra: { message: 'Query input', severity: 'ERROR' } }], errors: [{ type: 'ParseError' }], paths: { scanned: ['api.ts'], skipped: ['legacy.rb'] } }); - expect(result.status).toBe('partial'); - expect(result.candidates).toHaveLength(1); - expect(result.gaps.map(g => g.code)).toEqual(['TOOL_FAILED', 'SKIPPED_INPUT']); - }); - - test('zizmor SARIF becomes candidate evidence and retains suppression', () => { - const data = sarif({ ...sarifResult('.github/workflows/deploy.yml'), ruleId: 'dangerous-triggers', suppressions: [{ kind: 'inSource' }] }); - const result = parse('zizmor', data); - expect(result.status).toBe('complete'); - expect(result.candidates[0].suppressed).toBe(true); - expect(result.candidates[0].tool).toBe('zizmor'); - }); - - test('Trivy normalizes dependency, secret, and infrastructure candidates separately', () => { - const result = parse('trivy', { SchemaVersion: 2, Results: [ - { Target: 'package-lock.json', Type: 'npm', Vulnerabilities: [{ VulnerabilityID: 'CVE-2026-12345', PkgName: 'lib', InstalledVersion: '2.0.0', Severity: 'HIGH' }] }, - { Target: 'Dockerfile', Misconfigurations: [{ ID: 'DS002', Title: 'Root user', Severity: 'MEDIUM', CauseMetadata: { StartLine: 2 } }] }, - { Target: 'config.rb', Secrets: [{ RuleID: 'generic-api-key', Title: 'Key', Severity: 'CRITICAL', StartLine: 1 }] }, - ] }); - expect(result.status).toBe('complete'); - expect(result.candidates).toHaveLength(3); - expect(result.candidates[0].dependency?.reachability).toBe('unknown'); - expect(result.candidates[1].location?.line).toBe(2); - }); - - test('Schemathesis assertion failures do not become reproduced vulnerabilities', () => { - const result = parse('schemathesis', { schemathesis_version: '4.0.0', complete: true, stop_reason: 'completed', operations: { selected: 1, tested: 1, errored: 0, skipped: 0 }, errors: [], failures: [{ type: 'ServerError', title: 'Server error', severity: 'critical', operations: ['GET /documents'] }] }, 1); - expect(result.status).toBe('complete'); - expect(result.candidates[0].operation).toBe('GET /documents'); - expect(result.candidates[0].evidence).toBe('scanner-candidate'); - expect(result.candidates[0]).not.toHaveProperty('reproduced'); - }); - - test('Schemathesis time-budget completion counts only when every selected operation ran', () => { - const complete = parse('schemathesis', { schemathesis_version: '4.29.1', complete: true, stop_reason: 'max_time', operations: { selected: 1, tested: 1, errored: 0, skipped: 0 }, errors: [], failures: [] }, 0); - expect(complete.status).toBe('complete'); - expect(complete.gaps).toEqual([]); - const untested = parse('schemathesis', { schemathesis_version: '4.29.1', complete: true, stop_reason: 'max_time', operations: { selected: 2, tested: 1, errored: 0, skipped: 0 }, errors: [], failures: [] }, 0); - expect(untested.status).toBe('partial'); - const interrupted = parse('schemathesis', { schemathesis_version: '4.29.1', complete: false, stop_reason: 'max_time', operations: { selected: 1, tested: 1, errored: 0, skipped: 0 }, errors: [], failures: [] }, 0); - expect(interrupted.status).toBe('partial'); - }); - - test('Schemathesis time budget leaves room inside the execution deadline', () => { - const plan = scannerPlans({ snapshotRoot: '/source', offline: true, selected: ['schemathesis'], deadlineSeconds: 120, schemaPath: '/policy/openapi.json', baseUrl: 'http://127.0.0.1:3000/', operationIds: ['listItems'] })[0]; - expect(plan.args[plan.args.indexOf('--max-time') + 1]).toBe('90'); - }); - - test('startup failure and zero exercised operations remain not covered', () => { - const result = parse('schemathesis', { schemathesis_version: '4.0.0', complete: false, stop_reason: 'interrupted', operations: null, errors: [{ title: 'Schema load failed' }], failures: [] }, 1); - expect(result.status).toBe('partial'); - expect(result.candidates).toHaveLength(0); - expect(result.gaps.some(g => g.message.includes('no operations'))).toBe(true); - }); - - test('fingerprints do not depend on generated descriptions', () => { - const row = { RuleID: 'hardcoded-token', Description: 'Original title', File: 'config.ts', StartLine: 4 }; - const a = parse('gitleaks', [row], 10), b = parse('gitleaks', [{ ...row, Description: 'New generated wording' }], 10); - expect(a.candidates[0].id).toBe(b.candidates[0].id); - expect(a.planSha256).toBe(b.planSha256); - }); -}); - -describe('CSO scanner failure and hostile-input handling', () => { - test('missing optional scanners do not return a clean assessment', () => { - const result = parseScannerOutput(plan('gitleaks'), { stdout: '', exitCode: null, unavailable: true }); - expect(result.status).toBe('not_assessed'); - expect(result.gaps[0].code).toBe('UNAVAILABLE'); - }); - - test('missing local rules/databases become precise prerequisites without downloads', () => { - const p = scannerPlans({ snapshotRoot: '/src', offline: true, selected: ['osv'] })[0]; - const result = parseScannerOutput(p, { stdout: '{"results":[]}', exitCode: 0 }); - expect(result.status).toBe('not_assessed'); - expect(result.gaps[0].code).toBe('PREREQUISITE'); - expect(result.gaps[0].message).toContain('offline OSV'); - }); - - test('an OSV extraction failure on stderr cannot produce empty-clean JSON coverage', () => { - const result = parseScannerOutput(plan('osv'), { stdout: '{"results":[]}', stderr: 'Error during extraction: no offline version of the OSV database is available', exitCode: 0, databaseUpdatedAt: '2026-09-09T00:00:00.000Z' }); - expect(result.status).toBe('partial'); - expect(result.gaps.some(g => g.code === 'TOOL_FAILED')).toBe(true); - }); - - test.each(['', '{', 'null', '[]', '{"results":[]}'])('malformed Semgrep output %s never passes', raw => { - const result = parseScannerOutput(plan('semgrep'), { stdout: raw, exitCode: 0 }); - expect(result.status).toBe('not_assessed'); - expect(result.gaps[0].code).toBe('INVALID_OUTPUT'); - }); - - test('unrecognized exit code and timeout remain gaps even with syntactically complete output', () => { - const result = parseScannerOutput(plan('gitleaks'), { stdout: '[]', exitCode: 2, timedOut: true }); - expect(result.status).toBe('partial'); - expect(result.gaps.map(g => g.code)).toEqual(['TIMEOUT', 'TOOL_FAILED']); - }); - - test('truncation withholds the entire payload including a secret split across capture chunks', () => { - const chunks = ['[{"RuleID":"x","Description":"gh', 'p_' + 'A'.repeat(36) + '","File":"x"}]']; - const result = parseScannerOutput(plan('gitleaks'), { stdout: chunks.join(''), exitCode: 10, truncated: true }); - expect(result.status).toBe('not_assessed'); - expect(result.gaps[0].code).toBe('OUTPUT_LIMIT'); - expect(result.candidates).toHaveLength(0); - }); - - test('capture budget applies to UTF-8 bytes and stderr together', () => { - const result = parseScannerOutput(plan('gitleaks'), { stdout: '[]', stderr: 'λ'.repeat(MAX_SCANNER_OUTPUT_BYTES / 2), exitCode: 0 }); - expect(result.gaps[0].code).toBe('OUTPUT_LIMIT'); - }); - - test('marker-only private keys withhold the entire decoded document', () => { - const data = [{ RuleID: 'key', Description: ['-----BEGIN ', 'PRIVATE KEY-----\nsecretbody\n-----END ', 'PRIVATE KEY-----'].join(''), File: 'config' }]; - const result = parse('gitleaks', data, 10); - expect(result.status).toBe('not_assessed'); - expect(result.gaps[0].code).toBe('REDACTION_FAILED'); - expect(JSON.stringify(result)).not.toContain('secretbody'); - }); - - test('JSON unicode escapes cannot bypass the decoded-string redactor', () => { - const secret = 'ghp_' + 'A1b2C3d4E5f6G7h8I9j0K1l2M3n4O5p6Q7r8'; - const raw = JSON.stringify([{ RuleID: 'key', Description: secret, File: 'config' }]).replace('ghp_', '\\u0067hp_'); - const result = parseScannerOutput(plan('gitleaks'), { stdout: raw, exitCode: 10 }); - expect(result.status).toBe('complete'); - expect(JSON.stringify(result)).not.toContain(secret); - expect(result.candidates[0].message).toContain('REDACTED'); - }); - - test('prototype keys and extreme nesting are rejected without leaking raw content', () => { - for (const raw of ['{"__proto__":{"polluted":true}}', '['.repeat(70) + '[]' + ']'.repeat(70)]) { - const result = parseScannerOutput(plan('gitleaks'), { stdout: raw, exitCode: 0 }); - expect(result.status).toBe('not_assessed'); - expect(result.gaps[0].code).toBe('INVALID_OUTPUT'); - } - expect(({} as Record).polluted).toBeUndefined(); - }); - - test('unknown database freshness is explicit even when there are no advisories', () => { - const result = parseScannerOutput(plan('osv'), { stdout: '{"results":[]}', exitCode: 0 }); - expect(result.status).toBe('partial'); - expect(result.databaseUpdatedAt).toBeNull(); - expect(result.gaps[0].code).toBe('UNKNOWN_FRESHNESS'); - }); - - test('finding exit codes cannot certify an empty-clean report', () => { - const result = parse('gitleaks', [], 10); - expect(result.status).toBe('partial'); - expect(result.gaps[0].code).toBe('INVALID_OUTPUT'); - }); - - test('a schema version alone is not evidence of a completed Trivy scan', () => { - const result = parse('trivy', { SchemaVersion: 2 }); - expect(result.status).toBe('not_assessed'); - expect(result.gaps[0].code).toBe('INVALID_OUTPUT'); - }); -}); - -describe('CSO SARIF import boundary', () => { - test('CodeQL SARIF imports read-only candidates with artifact-index locations', () => { - const data = sarif(sarifResult()); - const run = data.runs[0] as Record; - run.artifacts = [{ location: { uri: 'src/routes.ts' } }]; - run.results[0].locations[0].physicalLocation.artifactLocation = { index: 0 }; - const result = importSarif(JSON.stringify(data), { sourceRoot: '/src' }); - expect(result.status).toBe('complete'); - expect(result.tool).toBe('sarif'); - expect(result.candidates[0].tool).toBe('sarif'); - expect(result.candidates[0].ruleId).toBe('js/sql-injection'); - expect(result.candidates[0].location).toEqual({ path: 'src/routes.ts', line: 12, column: 3 }); - }); - - test.each(['../.ssh/id_rsa', '%2e%2e/.ssh/id_rsa', '%252e%252e/.ssh/id_rsa', 'file:///etc/passwd', 'file://remote/src/file.ts', 'https://evil.test/collect', 'javascript:alert(1)', '//evil.test/file', 'C:\\Users\\secret', 'src/../../secret', 'src/%00file'])('rejects unsafe artifact URI %s', uri => { - const result = importSarif(JSON.stringify(sarif(sarifResult(uri))), { sourceRoot: '/src' }); - expect(result.status).toBe('partial'); - expect(result.candidates).toHaveLength(0); - expect(result.gaps.length).toBeGreaterThan(0); - expect(() => scannerLocation(uri, '/src')).toThrow(); - }); - - test('failed invocation does not erase independently useful candidates or imply complete coverage', () => { - const data = sarif(sarifResult()); - (data.runs[0] as Record).invocations = [{ executionSuccessful: false }]; - const result = importSarif(JSON.stringify(data), { sourceRoot: '/src' }); - expect(result.status).toBe('partial'); - expect(result.candidates).toHaveLength(1); - expect(result.gaps[0].code).toBe('TOOL_FAILED'); - }); - - test('SARIF passing checks are not vulnerability candidates', () => { - const result = importSarif(JSON.stringify(sarif({ ...sarifResult(), kind: 'pass' })), { sourceRoot: '/src' }); - expect(result.status).toBe('complete'); - expect(result.candidates).toHaveLength(0); - }); - - test('an untrusted originalUriBaseIds map cannot change the assessment root', () => { - const data = sarif(sarifResult('secret.ts')); - const run = data.runs[0] as Record; - run.originalUriBaseIds = { ROOT: { uri: 'file:///etc/' } }; - run.results[0].locations[0].physicalLocation.artifactLocation.uriBaseId = 'ROOT'; - const result = importSarif(JSON.stringify(data), { sourceRoot: '/src' }); - expect(result.candidates).toHaveLength(0); - expect(result.status).toBe('partial'); - }); - - test('SARIF external properties are not fetched and missing runs are not a clean scan', () => { - const result = importSarif(JSON.stringify({ version: '2.1.0', runs: [], externalProperties: [{ uri: 'https://evil.test/' }] }), { sourceRoot: '/src' }); - expect(result.status).toBe('partial'); - expect(result.candidates).toHaveLength(0); - expect(result.gaps[0].code).toBe('SKIPPED_INPUT'); - }); - - test('external SARIF result references are an explicit coverage gap', () => { - const data = sarif(); - (data.runs[0] as Record).externalPropertyFileReferences = { results: [{ location: { uri: 'https://evil.test/results.json' } }] }; - const result = importSarif(JSON.stringify(data), { sourceRoot: '/src' }); - expect(result.status).toBe('partial'); - expect(result.gaps[0].message).toContain('External SARIF'); - }); -}); - -// #3011: real scanner SARIF carries `uriBaseId`. Fixtures were captured from -// semgrep 1.179.0 (`--sarif`, local rule) and trivy 0.75.0 (`fs` and `repo -// ` misconfig scans); the trivy fs ROOTPATH was the capture machine's -// checkout path, rewritten to /work/acme-app. -describe('CSO SARIF uriBaseId mappings from real scanner output (#3011)', () => { - const fixture = (name: string) => - JSON.parse(fs.readFileSync(path.join(import.meta.dir, 'fixtures', 'cso-sarif', name), 'utf8')); - const importDoc = (doc: unknown, checkoutRoot?: string) => - importSarif(JSON.stringify(doc), { sourceRoot: '/source', ...(checkoutRoot ? { checkoutRoot } : {}) }); - const withBase = (uri: string, baseId: string, bases?: Record, driver = 'CodeQL') => { - const data = sarif(sarifResult(uri)); - const run = data.runs[0] as Record; - run.tool.driver.name = driver; - if (bases) run.originalUriBaseIds = bases; - run.results[0].locations[0].physicalLocation.artifactLocation.uriBaseId = baseId; - return data; - }; - - test('semgrep %SRCROOT% (no originalUriBaseIds) resolves against the source root', () => { - const result = importDoc(fixture('semgrep-1.179.0.sarif')); - expect(result.gaps).toEqual([]); - expect(result.status).toBe('complete'); - expect(result.candidates.map((c) => c.location?.path).sort()).toEqual(['lib/run.py', 'src/dir with space/run.py']); - expect(result.candidates[0].ruleId).toBe('subprocess-shell-true'); - }); - - test('trivy fs ROOTPATH naming the checkout the run started on maps to the source root', () => { - const result = importDoc(fixture('trivy-0.75.0-fs.sarif'), '/work/acme-app'); - expect(result.gaps).toEqual([]); - expect(result.candidates.map((c) => [c.ruleId, c.location?.path])).toEqual([['DS-0002', 'Dockerfile'], ['DS-0026', 'Dockerfile']]); - }); - - test('trivy fs ROOTPATH for another directory is rejected with a counted, named gap', () => { - const result = importDoc(fixture('trivy-0.75.0-fs.sarif'), '/work/other-app'); - expect(result.status).toBe('partial'); - expect(result.candidates).toHaveLength(0); - expect(result.gaps).toHaveLength(1); - expect(result.gaps[0].code).toBe('UNSAFE_LOCATION'); - expect(result.gaps[0].message).toBe( - '2 SARIF result(s) could not be safely normalized and were not imported (first: rule DS-0002, base ROOTPATH=file:///work/acme-app/, path Dockerfile: URI base outside source root).', - ); - }); - - test('a home-directory checkout matches before redaction, and gaps never echo the raw path', () => { - const doc = fixture('trivy-0.75.0-fs.sarif'); - doc.runs[0].originalUriBaseIds.ROOTPATH.uri = 'file:///home/alice/code/acme-app/'; - expect(importDoc(doc, '/home/alice/code/acme-app').candidates).toHaveLength(2); - const other = importDoc(doc, '/home/bob/code/acme-app'); - expect(other.candidates).toHaveLength(0); - expect(other.gaps[0].message).not.toContain('/home/alice'); - }); - - test('trivy repo ROOTPATH (a URL folded into a path) is treated as undeclared', () => { - const doc = fixture('trivy-0.75.0-repo-url.sarif'); - expect(importDoc(doc).candidates.map((c) => c.location?.path)).toEqual(['Dockerfile.build', 'Dockerfile.build']); - // Same scan run from a working directory other than `/`. - doc.runs[0].originalUriBaseIds.ROOTPATH.uri = 'file:///home/dev/https:/github.com/docker-library/hello-world/'; - expect(importDoc(doc).gaps).toEqual([]); - }); - - test('declared bases inside the root, percent-encoded and Windows drive URIs resolve', () => { - const inside = importDoc(withBase('x.ts', 'SRC', { SRC: { uri: 'file:///source/pkg/' } })); - expect(inside.candidates[0].location?.path).toBe('pkg/x.ts'); - const encoded = importDoc(withBase('x.ts', 'SRC', { SRC: { uri: 'file:///work/acme%20app/lib/' } }), '/work/acme app'); - expect(encoded.candidates[0].location?.path).toBe('lib/x.ts'); - const win = importDoc(withBase('x.ts', 'SRC', { SRC: { uri: 'file:///c:/Users/Dev/Acme/' } }), 'C:\\Users\\dev\\acme'); - expect(win.candidates[0].location?.path).toBe('x.ts'); - }); - - test.each([ - ['an undeclared base from an unmapped scanner', withBase('x.ts', 'SRCROOT'), 'SRCROOT (undeclared)'], - ['semgrep %SRCROOT% declared outside the root', withBase('x.ts', '%SRCROOT%', { '%SRCROOT%': { uri: 'file:///etc/' } }, 'Semgrep OSS'), '%SRCROOT%=file:///etc/'], - ['a base that climbs out of the root', withBase('x.ts', 'SRC', { SRC: { uri: 'file:///source/../etc/' } }), 'SRC=file:///source/../etc/'], - ['a mapped base with an escaping uri', withBase('../secret', '%SRCROOT%', undefined, 'Semgrep OSS'), '%SRCROOT% (undeclared)'], - ['a nested base', withBase('x.ts', 'SRC', { SRC: { uri: 'pkg/', uriBaseId: 'ROOT' }, ROOT: { uri: 'file:///source/' } }), 'SRC=pkg/'], - ['a remote base', withBase('x.ts', 'SRC', { SRC: { uri: 'https://evil.test/' } }), 'SRC=https://evil.test/'], - ])('rejects %s and names it in the gap', (_label, doc, base) => { - const result = importDoc(doc, '/work/acme-app'); - expect(result.candidates).toHaveLength(0); - expect(result.status).toBe('partial'); - expect(result.gaps[0].message).toContain('1 SARIF result(s) could not be safely normalized and were not imported'); - expect(result.gaps[0].message).toContain(`base ${base}`); - expect(result.gaps[0].message).toContain('rule js/sql-injection'); - }); -}); diff --git a/test/cso-snapshot-disappearance-race.test.ts b/test/cso-snapshot-disappearance-race.test.ts deleted file mode 100644 index 8e2c4b0b3..000000000 --- a/test/cso-snapshot-disappearance-race.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { capture } from '../lib/cso/snapshot'; - -const roots:string[]=[]; -afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); - -function trustedGit():string{ - const executable=Bun.which('git'); - if(!executable)throw new Error('git is required for the snapshot disappearance fixture'); - return executable; -} -function gitEnvironment(home:string):NodeJS.ProcessEnv{ - return{...process.env,HOME:home,GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_TERMINAL_PROMPT:'0'}; -} -type FileIdentity={path:string;dev:bigint;ino:bigint}; -function canonicalFile(file:string):string{ - const resolved=fs.realpathSync.native(file); - return process.platform==='win32'?resolved.replace(/^\\\\\?\\UNC\\/i,'\\\\').replace(/^\\\\\?\\/,'').toLowerCase():resolved; -} -function fileIdentity(file:string):FileIdentity{const stat=fs.statSync(file,{bigint:true});return{path:canonicalFile(file),dev:stat.dev,ino:stat.ino};} -function isFileIdentity(candidate:unknown,expected:FileIdentity):boolean{ - if(path.basename(String(candidate)).toLowerCase()!=='tracked.txt')return false; - try{const file=String(candidate),current=fs.statSync(file,{bigint:true});return canonicalFile(file)===expected.path&¤t.dev===expected.dev&¤t.ino===expected.ino;}catch{return false;} -} - -function fixture(){ - const root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-snapshot-disappearance-'));roots.push(root); - const repo=path.join(root,'repo'),runDir=path.join(root,'run'); - fs.mkdirSync(repo);fs.mkdirSync(runDir,{mode:0o700}); - const git=(...args:string[])=>{const result=spawnSync(trustedGit(),['-C',repo,...args],{encoding:'utf8',env:gitEnvironment(root),timeout:30_000});if(result.status)throw new Error(result.stderr);return result.stdout.trim();}; - git('init','-q');git('config','user.email','fixture@example.test');git('config','user.name','Fixture'); - const tracked=path.join(repo,'tracked.txt');fs.writeFileSync(tracked,'security-relevant source\n');git('add','tracked.txt');git('commit','-qm','base'); - // Match the file itself instead of one pathname spelling. Windows may hand - // capture() an 8.3, long, or \\?\-namespaced spelling for this same inode. - return{repo,runDir,tracked,trackedIdentity:fileIdentity(tracked),parked:path.join(repo,'.tracked.txt.parked')}; -} - -describe('CSO snapshot source-disappearance races',()=>{ - // Bun on Windows does not patch the node:fs binding imported by snapshot.ts, - // so these syscall-choreography fixtures cannot activate there. The native - // Windows launcher suite instead mutates real source after capture history is - // recorded and requires start to fail closed without a snapshot or report. - test.skipIf(process.platform==='win32')('rejects a tracked path that disappears at its capture lstat and is restored before final membership validation',async()=>{ - const {repo,runDir,tracked,trackedIdentity,parked}=fixture(),lstat=fs.lstatSync; - let trackedLstats=0,injected=false,failure:unknown; - const patched=spyOn(fs,'lstatSync').mockImplementation(((candidate:any,options?:any)=>{ - if(isFileIdentity(candidate,trackedIdentity)&&++trackedLstats===2){ - // The first lstat is rejectSpecialFiles' directory walk. The second is - // capture's per-entry existence check. Move the tracked file for that - // exact syscall, then restore it before any final Git membership check. - injected=true;fs.renameSync(tracked,parked); - try{return options===undefined?lstat(candidate):lstat(candidate,options);} - finally{fs.renameSync(parked,tracked);} - } - return options===undefined?lstat(candidate):lstat(candidate,options); - }) as typeof fs.lstatSync); - try{await capture(repo,runDir);}catch(error){failure=error;}finally{patched.mockRestore();} - expect(injected).toBe(true); - expect(fs.readFileSync(tracked,'utf8')).toBe('security-relevant source\n'); - expect(failure).toMatchObject({code:'SNAPSHOT_RACE'}); - }); - test.skipIf(process.platform==='win32')('rejects a nonignored source file introduced during the final content validation',async()=>{ - const {repo,runDir,tracked,trackedIdentity}=fixture(),late=path.join(path.dirname(tracked),'late-vulnerable.js'),lstat=fs.lstatSync;let injected=false,failure:unknown; - const patched=spyOn(fs,'lstatSync').mockImplementation(((candidate:any,options?:any)=>{ - if(!injected&&isFileIdentity(candidate,trackedIdentity)&&fs.existsSync(path.join(runDir,'history-status.json'))){injected=true;fs.writeFileSync(late,'export const vulnerable = true\n');} - return options===undefined?lstat(candidate):lstat(candidate,options); - }) as typeof fs.lstatSync); - try{await capture(repo,runDir);}catch(error){failure=error;}finally{patched.mockRestore();} - expect(injected).toBe(true);expect(fs.readFileSync(late,'utf8')).toContain('vulnerable');expect(failure).toMatchObject({code:'SNAPSHOT_RACE'});expect(fs.existsSync(path.join(runDir,'snapshot.json'))).toBe(false); - }); - test.skipIf(process.platform==='win32')('binds the audited repository root while source is copied',async()=>{ - const root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-snapshot-root-swap-'));roots.push(root);const repo=path.join(root,'repo'),parked=path.join(root,'parked'),decoy=path.join(root,'decoy'),gitDir=path.join(root,'gitdir'),runDir=path.join(root,'run'),tracked=path.join(repo,'tracked.txt');fs.mkdirSync(repo);fs.mkdirSync(runDir,{mode:0o700}); - const run=(...args:string[])=>{const result=spawnSync(trustedGit(),args,{encoding:'utf8',env:gitEnvironment(root),timeout:30_000});if(result.status)throw new Error(result.stderr);}; - run('init','-q',`--separate-git-dir=${gitDir}`,repo);run('-C',repo,'config','user.email','fixture@example.test');run('-C',repo,'config','user.name','Fixture');fs.writeFileSync(tracked,'secure original source\n');run('-C',repo,'add','tracked.txt');run('-C',repo,'commit','-qm','base');fs.mkdirSync(decoy);fs.writeFileSync(path.join(decoy,'.git'),`gitdir: ${gitDir}\n`);fs.writeFileSync(path.join(decoy,'tracked.txt'),'vulnerable decoy source\n'); - const lstat=fs.lstatSync;let seen=0,injected=false,failure:unknown; - const patched=spyOn(fs,'lstatSync').mockImplementation(((candidate:any,options?:any)=>{if(path.resolve(String(candidate))===tracked&&++seen===2){injected=true;fs.renameSync(repo,parked);fs.renameSync(decoy,repo);}return options===undefined?lstat(candidate):lstat(candidate,options);}) as typeof fs.lstatSync); - try{await capture(repo,runDir);}catch(error){failure=error;}finally{patched.mockRestore();if(injected){fs.renameSync(repo,decoy);fs.renameSync(parked,repo);}} - expect(injected).toBe(true);expect(failure).toMatchObject({code:'SNAPSHOT_RACE'});expect(fs.readFileSync(path.join(repo,'tracked.txt'),'utf8')).toBe('secure original source\n');expect(fs.existsSync(path.join(runDir,'snapshot.json'))).toBe(false); - }); -}); diff --git a/test/cso-snapshot-identity.test.ts b/test/cso-snapshot-identity.test.ts deleted file mode 100644 index 685006aa6..000000000 --- a/test/cso-snapshot-identity.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { assertOpenedFileContained, assertSnapshot, capture } from '../lib/cso/snapshot'; -import { sha256 } from '../lib/cso/contracts'; - -const roots:string[]=[]; -afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); -function fixture(){ - const root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-snapshot-identity-'));roots.push(root); - const repo=path.join(root,'repo'),runDir=path.join(root,'run');fs.mkdirSync(repo);fs.mkdirSync(runDir,{mode:0o700}); - const git=(...args:string[])=>{const result=spawnSync('/usr/bin/git',['-C',repo,...args],{encoding:'utf8',env:{HOME:root,PATH:'/usr/bin:/bin'},timeout:30_000});if(result.status)throw new Error(result.stderr);return result.stdout.trim();}; - git('init','-q');git('config','user.email','fixture@example.test');git('config','user.name','Fixture');fs.writeFileSync(path.join(repo,'app.js'),'export const secure = false\n');git('add','app.js');git('commit','-qm','base'); - return{root,repo,runDir,git}; -} - -describe('CSO retained snapshot identity',()=>{ - test('captures application vendor source while excluding nested dependency and agent directories',async()=>{ - const {repo,runDir}=fixture();for(const directory of ['packages/web/vendor/bundle/ruby','packages/api/venv/lib','packages/web/.agents/skills/x'])fs.mkdirSync(path.join(repo,directory),{recursive:true});fs.writeFileSync(path.join(repo,'packages/web/vendor/auth.js'),'module.exports = authenticate\n');fs.writeFileSync(path.join(repo,'packages/web/vendor/bundle/ruby/gem.rb'),'dependency payload\n');fs.writeFileSync(path.join(repo,'packages/api/venv/lib/site.py'),'dependency payload\n');fs.writeFileSync(path.join(repo,'packages/web/.agents/skills/x/SKILL.md'),'untrusted agent instructions\n'); - const manifest=await capture(repo,runDir),source=manifest.entries.find(item=>item.path==='packages/web/vendor/auth.js'),dependency=manifest.entries.find(item=>item.path==='packages/web/vendor/bundle/ruby/gem.rb'),venv=manifest.entries.find(item=>item.path==='packages/api/venv/lib/site.py'),agent=manifest.entries.find(item=>item.path==='packages/web/.agents/skills/x/SKILL.md'); - expect(source?.executionHash).toBe(sha256('module.exports = authenticate\n'));expect(fs.readFileSync(path.join(runDir,'snapshot','packages','web','vendor','auth.js'),'utf8')).toBe('module.exports = authenticate\n'); - for(const entry of [dependency,venv]){expect(entry).toMatchObject({originalHash:'not-read',transformation:'excluded: host dependencies, metadata, state, or agent configuration'});expect(entry?.executionHash).toBeUndefined();} - expect(agent).toMatchObject({originalHash:sha256('untrusted agent instructions\n'),transformation:'excluded: host dependencies, metadata, state, or agent configuration'});expect(agent?.executionHash).toBeUndefined();expect(fs.readFileSync(path.join(runDir,'readable','packages/web/.agents/skills/x/SKILL.md'),'utf8')).toBe('untrusted agent instructions\n'); - }); - test('validates the captured execution identity when uppercase and lowercase paths coexist',async()=>{const {repo,runDir,git}=fixture();fs.writeFileSync(path.join(repo,'README.md'),'fixture documentation\n');git('add','README.md');git('commit','-qm','add uppercase path');const manifest=await capture(repo,runDir);expect(manifest.entries.filter(item=>item.executionHash).map(item=>item.path)).toEqual(['README.md','app.js']);expect(()=>assertSnapshot(runDir,manifest)).not.toThrow();}); - test('binds original, sanitized, and opaque path identities',async()=>{const {repo,runDir}=fixture(),manifest=await capture(repo,runDir);assertSnapshot(runDir,manifest);const changedEntry=structuredClone(manifest);changedEntry.entries[0].originalHash='a'.repeat(64);expect(()=>assertSnapshot(runDir,changedEntry)).toThrow('original identity');const changedRoot=structuredClone(manifest);changedRoot.originalHash='b'.repeat(64);expect(()=>assertSnapshot(runDir,changedRoot)).toThrow('original identity');const changedPathId=structuredClone(manifest);changedPathId.entries[0].pathId='c'.repeat(32);expect(()=>assertSnapshot(runDir,changedPathId)).toThrow('invalid source entry');}); - test.skipIf(process.platform==='win32')('preserves retained source modes under the required restrictive umask',async()=>{const {repo,runDir,git}=fixture(),script=path.join(repo,'tool.sh');fs.writeFileSync(script,'#!/bin/sh\nexit 0\n');fs.chmodSync(path.join(repo,'app.js'),0o644);fs.chmodSync(script,0o755);git('add','app.js','tool.sh');git('commit','-qm','add executable input');const previous=process.umask(0o077);let manifest;try{manifest=await capture(repo,runDir);}finally{process.umask(previous);}expect(manifest.entries.find(item=>item.path==='app.js')?.mode).toBe(0o644);expect(manifest.entries.find(item=>item.path==='tool.sh')?.mode).toBe(0o755);expect(fs.statSync(path.join(runDir,'snapshot','app.js')).mode&0o777).toBe(0o644);expect(fs.statSync(path.join(runDir,'snapshot','tool.sh')).mode&0o777).toBe(0o755);assertSnapshot(runDir,manifest);}); - test('rejects a replaced snapshot root before following it',async()=>{const {repo,runDir}=fixture(),manifest=await capture(repo,runDir),snapshot=path.join(runDir,'snapshot'),replacement=path.join(runDir,'snapshot-replacement');fs.renameSync(snapshot,replacement);fs.symlinkSync(replacement,snapshot);expect(()=>assertSnapshot(runDir,manifest)).toThrow('private owned directory');}); - test.skipIf(process.platform==='win32')('detects an ancestor symlink swap after a source file is opened',()=>{const {root,repo}=fixture(),outside=path.join(root,'outside'),alias=path.join(repo,'swapped'),secret=path.join(outside,'secret.txt');fs.mkdirSync(outside);fs.writeFileSync(secret,'outside source must not be captured\n');fs.symlinkSync(outside,alias);const full=path.join(alias,'secret.txt'),fd=fs.openSync(full,fs.constants.O_RDONLY);try{expect(()=>assertOpenedFileContained(repo,full,fd,fs.fstatSync(fd))).toThrow('escaped the audited root');}finally{fs.closeSync(fd);}}); - test.skipIf(process.platform==='win32')('rejects an untracked FIFO before opening it',async()=>{const {repo,runDir}=fixture(),fifo=path.join(repo,'request.pipe'),created=spawnSync('/usr/bin/mkfifo',[fifo],{encoding:'utf8',timeout:5_000});expect(created.status).toBe(0);const started=Date.now();await expect(capture(repo,runDir)).rejects.toThrow('Symlink or special source file');expect(Date.now()-started).toBeLessThan(2_000);}); - test('withholds a large regular source file without aborting the bounded snapshot',async()=>{const {repo,runDir}=fixture(),large=Buffer.alloc(1024*1024+1,0x61);fs.writeFileSync(path.join(repo,'large.txt'),large);const manifest=await capture(repo,runDir),entry=manifest.entries.find(item=>item.path==='large.txt');expect(entry).toMatchObject({bytes:large.length,originalHash:sha256(large),transformation:'withheld: exceeds the 1 MiB redacting-reader limit'});expect(entry?.executionHash).toBeUndefined();expect(fs.existsSync(path.join(runDir,'snapshot','large.txt'))).toBe(false);assertSnapshot(runDir,manifest);}); - test('binds a recheck snapshot to the exact captured descendant commit',async()=>{const {repo,runDir,git}=fixture(),ancestor=git('rev-parse','HEAD');git('checkout','--orphan','unrelated');fs.writeFileSync(path.join(repo,'app.js'),'export const unrelated = true\n');git('add','app.js');git('commit','-qm','unrelated root');await expect(capture(repo,runDir,undefined,ancestor)).rejects.toThrow('not a descendant');}); -}); diff --git a/test/cso-snapshot-state.test.ts b/test/cso-snapshot-state.test.ts deleted file mode 100644 index eb054c672..000000000 --- a/test/cso-snapshot-state.test.ts +++ /dev/null @@ -1,300 +0,0 @@ -import { afterAll, afterEach, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import { spawn, spawnSync } from 'node:child_process'; -import { assertSnapshot, capture, NESTED_REPOSITORY, symlinkTransformation } from '../lib/cso/snapshot';import { CsoError, snapshotPathHandle } from '../lib/cso/contracts';import { runProcess, sanitizeForJson, sanitizeHelperForJson } from '../lib/cso/process';import { discardAtomicNoReplaceTemp, finalizeReplayTemporary,reclaimDeadAttemptScratch, loadReport, newRun, privateRoot, readJson, recoverAtomicNoReplaceJson, retention, saveReport, secureDirectory, stateRoot, withLock, writeHelperJson, writeJson } from '../lib/cso/state'; -const roots:string[]=[];const tmp=()=>{const p=fs.mkdtempSync(path.join(os.tmpdir(),'cso-snapshot-'));roots.push(p);return p;};afterEach(()=>{for(const p of roots.splice(0))fs.rmSync(p,{recursive:true,force:true});}); -const originalState=process.env.GSTACK_HOME,state=fs.mkdtempSync(path.join(os.tmpdir(),'cso-state-'));process.env.GSTACK_HOME=state;afterAll(()=>{if(originalState===undefined)delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME=originalState;fs.rmSync(state,{recursive:true,force:true});}); -function git(repo:string,...args:string[]){const r=spawnSync('/usr/bin/git',['-C',repo,...args],{encoding:'utf8',env:{PATH:'/usr/bin:/bin',HOME:repo},timeout:30_000});if(r.status)throw new Error(r.stderr);return r.stdout;} -function repo(){const p=tmp();git(p,'init','-q');git(p,'config','user.email','fixture@example.test');git(p,'config','user.name','Fixture');fs.writeFileSync(path.join(p,'tracked.txt'),'base\n');git(p,'add','tracked.txt');git(p,'commit','-qm','base');return p;} -async function waitForPath(file:string,timeout=5000):Promise{const deadline=Date.now()+timeout;while(!fs.existsSync(file)){if(Date.now()>=deadline)throw new Error(`Timed out waiting for ${path.basename(file)}`);await Bun.sleep(5);}} -function childExit(child:ReturnType,timeout=5000):Promise{return new Promise((resolve,reject)=>{if(child.exitCode!==null){resolve(child.exitCode);return;}const timer=setTimeout(()=>reject(new Error(`Child ${child.pid} did not exit`)),timeout);child.once('error',error=>{clearTimeout(timer);reject(error);});child.once('close',code=>{clearTimeout(timer);resolve(code);});});} -function stopChildren(children:Array>):void{for(const child of children){if(!child.pid||child.exitCode!==null)continue;try{process.kill(child.pid,'SIGCONT');}catch{}try{process.kill(child.pid,'SIGKILL');}catch{}}} -async function resumeStopped(child:ReturnType,timeout=2000):Promise{const deadline=Date.now()+timeout;for(;;){if(child.exitCode!==null||child.signalCode!==null)throw new Error(`Child ${child.pid} exited (${child.exitCode??child.signalCode}) after marking its pause, before it stopped`);let state='';if(process.platform==='linux'){try{const stat=fs.readFileSync(`/proc/${child.pid}/stat`,'utf8');state=stat.slice(stat.lastIndexOf(')')+2);}catch(error){if((error as NodeJS.ErrnoException).code!=='ENOENT')throw new Error(`Child ${child.pid} stop check failed: ${(error as Error).message}`);}}else{const ps=spawnSync('ps',['-o','stat=','-p',String(child.pid)],{encoding:'utf8',timeout:2000});if(ps.error)throw new Error(`Child ${child.pid} stop check failed: ${ps.error.message}`);state=(ps.stdout??'').trim();}if(state[0]==='T')break;if(Date.now()>=deadline)throw new Error(`Child ${child.pid} marked its pause but never stopped`);await Bun.sleep(5);}process.kill(child.pid!,'SIGCONT');} -function leaseContenderSource():string{return `import fs from 'node:fs';import * as fsModule from 'node:fs';import * as cryptoModule from 'node:crypto';import path from 'node:path';import {spyOn} from 'bun:test'; -const dir=process.env.RACE_DIR!,barrier=process.env.BARRIER!,id=process.env.RACE_ID!,mode=process.env.RACE_MODE??'normal',token=process.env.RACE_TOKEN,leases=path.join(dir,'.mutation-lock-leases'),wait=new Int32Array(new SharedArrayBuffer(4));let triggered=false; -const write=fs.writeFileSync.bind(fs),mark=(name,value='ready')=>write(path.join(barrier,name),value,{flag:'wx'}),waitFor=(name)=>{const deadline=Date.now()+5000;while(!fs.existsSync(path.join(barrier,name))){if(Date.now()>=deadline)throw new Error('barrier timeout: '+name);Atomics.wait(wait,0,0,1);}}; -if(token){const random=cryptoModule.randomBytes.bind(cryptoModule);spyOn(cryptoModule,'randomBytes').mockImplementation(((size,...args)=>size===16?Buffer.from(token,'hex'):random(size,...args)) as typeof cryptoModule.randomBytes);} -const read=fs.readdirSync.bind(fs);spyOn(fsModule,'readdirSync').mockImplementation(((candidate,...args)=>{const result=read(candidate,...args),names=result as any[];if(mode==='pause-candidate'&&!triggered&&String(candidate)===leases&&names.some(name=>token?String(name)===token+'.json':/^[a-f0-9]{32}\.json$/.test(String(name)))){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}if(mode==='pause-later-scan'&&!triggered&&String(candidate)===leases&&names.filter(name=>String(name).endsWith('.decision')).length>=2&&!names.some(name=>String(name).includes('.active.'))){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}return result;}) as typeof fs.readdirSync); -spyOn(fsModule,'writeFileSync').mockImplementation(((target,data,...args)=>{const name=path.basename(String(target));if(name.includes('.decision.tmp.')){let decision;try{decision=JSON.parse(String(data));}catch{}if(decision?.kind==='ticket'&&decision.token===token){try{mark('choice-'+id,decision.ticket);}catch{}if(mode==='pause-before-decision'&&!triggered){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}}if(decision?.kind==='withdraw'&&mode==='pause-before-withdraw'&&!triggered){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}}return write(target,data,...args);}) as typeof fs.writeFileSync); -const link=fs.linkSync.bind(fs);spyOn(fsModule,'linkSync').mockImplementation(((source,target)=>{const name=path.basename(String(target));if(mode==='wait-active'&&!triggered&&name.includes('.active.')){triggered=true;mark('doorway-'+id);waitFor('paused-H');}return link(source,target);}) as typeof fs.linkSync); -const unlink=fs.unlinkSync.bind(fs);spyOn(fsModule,'unlinkSync').mockImplementation(((target)=>{const result=unlink(target),name=path.basename(String(target)),candidateToken=name.endsWith('.json')?name.slice(0,-5):'';if((mode==='pause-decision'||mode==='pause-ticket')&&!triggered&&name.includes('.decision.tmp.')&&(!token||name.startsWith(token+'.decision.tmp.'))){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}if((mode==='pause-after-candidate-cleanup'||mode==='pause-withdraw-cleanup')&&!triggered&&/^[a-f0-9]{32}$/.test(candidateToken)&&(!token||candidateToken===token)&&fs.existsSync(path.join(leases,candidateToken+'.decision'))){triggered=true;mark('paused-'+id);process.kill(process.pid,'SIGSTOP');}return result;}) as typeof fs.unlinkSync); -const {withLock}=await import(${JSON.stringify(path.resolve(import.meta.dir,'../lib/cso/state.ts'))});let outcome='success';try{withLock(dir,()=>{const active=path.join(barrier,'work-active');try{write(active,id,{flag:'wx'});}catch{fs.appendFileSync(path.join(barrier,'overlap'),'overlap\\n');}mark('entered-'+id);if(process.env.RACE_HOLD==='1')waitFor('release-'+id);try{if(fs.readFileSync(active,'utf8')===id)fs.unlinkSync(active);}catch{}});}catch(error){outcome=String(error?.code??error);}const result=path.join(barrier,'result-'+id);write(result+'.tmp',outcome);fs.renameSync(result+'.tmp',result);`;} -describe('CSO dirty snapshot boundary',()=>{ - test('captures tracked modifications and nonignored untracked source without changing Git state',async()=>{const p=repo();fs.writeFileSync(path.join(p,'tracked.txt'),'dirty\n');fs.writeFileSync(path.join(p,'new.txt'),'untracked\n');fs.writeFileSync(path.join(p,'.gitignore'),'ignored.txt\n');fs.writeFileSync(path.join(p,'ignored.txt'),'ignored\n');const before=git(p,'status','--porcelain=v1','-z'),run=newRun(p),m=await capture(p,run.dir,'HEAD');expect(fs.readFileSync(path.join(run.dir,'snapshot','tracked.txt'),'utf8')).toBe('dirty\n');expect(fs.readFileSync(path.join(run.dir,'snapshot','new.txt'),'utf8')).toBe('untracked\n');expect(fs.existsSync(path.join(run.dir,'snapshot','ignored.txt'))).toBe(false);expect(git(p,'status','--porcelain=v1','-z')).toBe(before);expect(m.changedPaths).toContain('new.txt');}); - test('records an untracked nested repository as one boundary entry instead of failing the run',async()=>{const p=repo(),inner=path.join(p,'inner');fs.mkdirSync(inner);git(inner,'init','-q');git(inner,'config','user.email','fixture@example.test');git(inner,'config','user.name','Fixture');fs.writeFileSync(path.join(inner,'f.txt'),'x\n');git(inner,'add','.');git(inner,'commit','-qm','inner');const run=newRun(p),manifest=await capture(p,run.dir,'HEAD');assertSnapshot(run.dir,manifest);const entry=manifest.entries.find(e=>e.path==='inner');expect(entry?.transformation).toBe(NESTED_REPOSITORY);expect(entry?.originalHash).toBe('not-read');expect(manifest.entries.map(e=>e.path).filter(p=>p==='tracked.txt'||p.startsWith('inner'))).toEqual(['inner','tracked.txt']);expect(manifest.changedPaths).toContain('inner');expect(fs.existsSync(path.join(run.dir,'snapshot','inner'))).toBe(false);expect(fs.existsSync(path.join(run.dir,'readable','inner'))).toBe(false);}); - test('records a registered submodule gitlink the same way as an untracked nested repository',async()=>{const p=repo(),src=tmp();git(src,'init','-q');git(src,'config','user.email','fixture@example.test');git(src,'config','user.name','Fixture');fs.writeFileSync(path.join(src,'g.txt'),'g\n');git(src,'add','.');git(src,'commit','-qm','sub');git(p,'-c','protocol.file.allow=always','submodule','add','-q',src,'sub');const run=newRun(p),manifest=await capture(p,run.dir,'HEAD');assertSnapshot(run.dir,manifest);expect(manifest.entries.find(e=>e.path==='sub')?.transformation).toBe(NESTED_REPOSITORY);expect(fs.existsSync(path.join(run.dir,'snapshot','sub','g.txt'))).toBe(false);}); - test('admits source membership and time before an unbounded startup walk',async()=>{const p=repo();fs.writeFileSync(path.join(p,'second.txt'),'second\n');const tooMany=newRun(p);await expect(capture(p,tooMany.dir,undefined,undefined,{maxEntries:1})).rejects.toMatchObject({code:'MISSING_INPUT'});expect(fs.existsSync(path.join(tooMany.dir,'snapshot'))).toBe(false);const expired=newRun(p);await expect(capture(p,expired.dir,undefined,undefined,{deadlineMs:Date.now()-1})).rejects.toMatchObject({code:'DEADLINE'});expect(fs.existsSync(path.join(expired.dir,'snapshot'))).toBe(false);}); - test('includes chmod-only changes in diff scope',async()=>{const p=repo();fs.chmodSync(path.join(p,'tracked.txt'),0o755);const manifest=await capture(p,newRun(p).dir,'HEAD');expect(manifest.changedPaths).toContain('tracked.txt');}); - test('does not invoke configured clean filters, hooks, fsmonitor, or PATH shims',async()=>{const p=repo(),marker=path.join(p,'marker');fs.writeFileSync(path.join(p,'.gitattributes'),'*.txt filter=hostile\n');git(p,'config','filter.hostile.clean',`/bin/sh -c 'touch ${marker}; cat'`);git(p,'config','core.fsmonitor',`/bin/sh -c 'touch ${marker}'`);const fake=path.join(p,'bin');fs.mkdirSync(fake);fs.writeFileSync(path.join(fake,'git'),`#!/bin/sh\ntouch '${marker}'\nexit 99\n`,{mode:0o755});const old=process.env.PATH;process.env.PATH=`${fake}:${old}`;try{await capture(p,newRun(p).dir,'HEAD');}finally{process.env.PATH=old;}expect(fs.existsSync(marker)).toBe(false);}); - test('never makes a symlink an execution input, and rejects hard links (#4540)',async()=>{const p=repo();fs.symlinkSync('/etc/passwd',path.join(p,'escape'));const run=newRun(p).dir,manifest=await capture(p,run),link=manifest.entries.find(e=>e.path==='escape');expect(link?.executionHash).toBeUndefined();expect(link?.transformation).toBe(symlinkTransformation('escape','/etc/passwd'));expect(fs.existsSync(path.join(run,'snapshot','escape'))).toBe(false);expect(fs.existsSync(path.join(run,'readable','escape'))).toBe(false);fs.unlinkSync(path.join(p,'escape'));fs.linkSync(path.join(p,'tracked.txt'),path.join(p,'hard'));await expect(capture(p,newRun(p).dir)).rejects.toThrow();}); - test.skipIf(process.platform==='win32')('checks source ancestors before any lstat, so a tracked path under a directory swapped for a symlink fails closed without stat-ing through it',async()=>{for(const target of ['dir','missing'] as const){const p=repo(),outside=tmp();fs.mkdirSync(path.join(p,'d'));fs.writeFileSync(path.join(p,'d','f'),'x\n');git(p,'add','d/f');git(p,'commit','-qm','d');if(target==='dir')fs.mkdirSync(path.join(outside,'f'));fs.rmSync(path.join(p,'d'),{recursive:true});fs.symlinkSync(outside,path.join(p,'d'));const through:string[]=[],lstat=fs.lstatSync,spy=spyOn(fs,'lstatSync').mockImplementation(((candidate:any,...rest:any[])=>{if(String(candidate).startsWith(path.join(p,'d')+path.sep))through.push(String(candidate));return (lstat as any)(candidate,...rest);}) as typeof fs.lstatSync);try{await expect(capture(p,newRun(p).dir)).rejects.toMatchObject({code:'UNSAFE_PATH',message:'Symlink or non-directory source ancestor: d/f'});}finally{spy.mockRestore();}expect(through).toEqual([]);}}); - test.skipIf(process.platform==='win32')('the source cap message measures no path through a symlinked ancestor',async()=>{const p=repo(),outside=tmp();fs.mkdirSync(path.join(p,'d'));fs.writeFileSync(path.join(p,'d','f'),'x\n');git(p,'add','d/f');git(p,'commit','-qm','d');fs.writeFileSync(path.join(outside,'f'),'outside\n');fs.rmSync(path.join(p,'d'),{recursive:true});fs.symlinkSync(outside,path.join(p,'d'));const big=path.join(p,'a.bin');fs.writeFileSync(big,'');fs.truncateSync(big,65*1024*1024);const through:string[]=[],lstat=fs.lstatSync,spy=spyOn(fs,'lstatSync').mockImplementation(((candidate:any,...rest:any[])=>{if(String(candidate).startsWith(path.join(p,'d')+path.sep))through.push(String(candidate));return (lstat as any)(candidate,...rest);}) as typeof fs.lstatSync);try{await expect(capture(p,newRun(p).dir)).rejects.toMatchObject({code:'MISSING_INPUT'});}finally{spy.mockRestore();}expect(through).toEqual([]);}); - test('records broken untracked symlinks instead of silently omitting them (#4540)',async()=>{const p=repo();fs.symlinkSync('missing-target',path.join(p,'broken'));const manifest=await capture(p,newRun(p).dir);expect(manifest.entries.find(e=>e.path==='broken')).toMatchObject({transformation:symlinkTransformation('broken','missing-target')});}); - for(const earlierSensitive of [false,true])test(earlierSensitive?'keeps credential evidence bound to .env when an earlier file is also sensitive':'redacts secrets and excludes credentials from execution while retaining safe evidence',async()=>{ - const p=repo(); - if(earlierSensitive)fs.writeFileSync(path.join(p,'.earlier.txt'),'Source: /home/fixture/project/source.ts\n'); - fs.writeFileSync(path.join(p,'.env'),'TOKEN='+['ghp_','abcdefghijklmnopqrstuvwxyz1234567890'].join('')+'\n'); - const run=newRun(p),m=await capture(p,run.dir),entry=m.entries.find(e=>e.path==='.env'); - expect(entry?.transformation).toContain('excluded'); - expect(fs.existsSync(path.join(run.dir,'snapshot','.env'))).toBe(false); - expect(fs.readFileSync(path.join(run.dir,'readable','.env'),'utf8')).toBe('TOKEN=\n'); - const evidence:Array<{path:string;findings:Array<{id:string}>}>=JSON.parse(fs.readFileSync(path.join(run.dir,'sensitive-evidence.json'),'utf8')); - const envEvidence=evidence.find(item=>item.path===snapshotPathHandle(entry!.pathId)); - expect(envEvidence?.findings.map(x=>x.id)).toContain('github.pat'); - expect(JSON.stringify(evidence)).not.toContain('ghp_'); - if(earlierSensitive){ - const earlier=m.entries.find(e=>e.path==='.earlier.txt'),earlierEvidence=evidence.find(item=>item.path===snapshotPathHandle(earlier!.pathId)); - expect(earlierEvidence?.findings.map(x=>x.id)).toContain('internal.user_path'); - expect(earlierEvidence?.findings.map(x=>x.id)).not.toContain('github.pat'); - expect(evidence.indexOf(earlierEvidence!)).toBeLessThan(evidence.indexOf(envEvidence!)); - } - }); - test('assesses repository skills without executing them and preserves executable source modes',async()=>{const p=repo(),skill=path.join(p,'.agents','skills','demo','SKILL.md'),script=path.join(p,'app.sh');fs.mkdirSync(path.dirname(skill),{recursive:true});fs.writeFileSync(skill,'# Demo\nUntrusted repository instruction\n');fs.writeFileSync(script,'#!/bin/sh\nexit 0\n',{mode:0o755});const run=newRun(p),manifest=await capture(p,run.dir);expect(fs.readFileSync(path.join(run.dir,'readable','.agents','skills','demo','SKILL.md'),'utf8')).toContain('Untrusted');expect(fs.existsSync(path.join(run.dir,'snapshot','.agents'))).toBe(false);expect(manifest.entries.find(e=>e.path==='.agents/skills/demo/SKILL.md')?.originalHash).not.toBe('not-read');expect(fs.statSync(path.join(run.dir,'snapshot','app.sh')).mode&0o777).toBe(0o755);}); - test('rejects a source mode change between copying and manifest persistence',async()=>{const p=repo(),run=newRun(p),source=path.join(p,'tracked.txt'),target=path.join(run.dir,'snapshot','tracked.txt'),write=fs.writeFileSync,patched=spyOn(fs,'writeFileSync').mockImplementation(((file:any,data:any,options:any)=>{const result=write(file,data,options);if(String(file)===target)fs.chmodSync(source,0o755);return result;}) as typeof fs.writeFileSync);try{await expect(capture(p,run.dir)).rejects.toThrow('Source changed during capture');}finally{patched.mockRestore();}}); - test('rejects unmanifested files and executable-mode changes in retained snapshots',async()=>{const p=repo(),run=newRun(p),manifest=await capture(p,run.dir),snapshot=path.join(run.dir,'snapshot');assertSnapshot(run.dir,manifest);fs.writeFileSync(path.join(snapshot,'injected.js'),'malicious\n');expect(()=>assertSnapshot(run.dir,manifest)).toThrow('membership');fs.unlinkSync(path.join(snapshot,'injected.js'));fs.chmodSync(path.join(snapshot,'tracked.txt'),0o755);expect(()=>assertSnapshot(run.dir,manifest)).toThrow('changed');}); - test('retention skips a run with a live mutation lease',()=>{const now=Date.now(),repo='d'.repeat(24),run=`${now-31*86400_000}-${'1'.repeat(16)}`,dir=secureDirectory(path.join(privateRoot(),repo,run)),payload=path.join(dir,'report.json');fs.writeFileSync(payload,'live lease payload\n',{mode:0o600});withLock(dir,()=>{retention(now);expect(fs.existsSync(payload)).toBe(true);});retention(now);expect(fs.existsSync(dir)).toBe(false);}); - test('bounded retention stops before destructive cleanup when its maintenance budget is exhausted',()=>{const now=Date.now(),repo='e'.repeat(24),run=`${now-31*86400_000}-${'8'.repeat(16)}`,dir=secureDirectory(path.join(privateRoot(),repo,run));fs.writeFileSync(path.join(dir,'report.json'),'expired private state\n',{mode:0o600});const result=retention(now,{deadlineMs:0,maxEntries:1});expect(result).toEqual({complete:false,visited:0});expect(fs.existsSync(dir)).toBe(true);retention(now);expect(fs.existsSync(dir)).toBe(false);}); - test('bounded retention completes discovery before deleting any run',()=>{const now=Date.now(),repo='f'.repeat(24),run=`${now-31*86400_000}-${'9'.repeat(16)}`,dir=secureDirectory(path.join(privateRoot(),repo,run));fs.writeFileSync(path.join(dir,'report.json'),'expired private state\n',{mode:0o600});const result=retention(now,{deadlineMs:now+60_000,maxEntries:6});expect(result).toEqual({complete:false,visited:6});expect(fs.existsSync(dir)).toBe(true);retention(now);expect(fs.existsSync(dir)).toBe(false);}); - test('bounded retention resumes an interrupted tree deletion without one recursive walk',()=>{const previous=process.env.GSTACK_HOME,isolate=tmp();process.env.GSTACK_HOME=isolate;try{const now=Date.now(),repo='1'.repeat(24),run=`${now-31*86400_000}-${'a'.repeat(16)}`,repoDir=path.join(privateRoot(),repo),dir=secureDirectory(path.join(repoDir,run)),snapshot=secureDirectory(path.join(dir,'snapshot'));for(let index=0;index<20;index++)fs.writeFileSync(path.join(snapshot,`${index}.txt`),'private state\n',{mode:0o600});const result=retention(now,{deadlineMs:now+60_000,maxEntries:30});expect(result).toEqual({complete:false,visited:30});expect(fs.existsSync(dir)).toBe(false);expect(fs.readdirSync(repoDir).some(name=>name.startsWith(`.retired-${run}-`))).toBe(true);retention(now);expect(fs.readdirSync(repoDir).some(name=>name.startsWith(`.retired-${run}-`))).toBe(false);}finally{if(previous===undefined)delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME=previous;}}); - test('repair bundles expire from their authenticated bundle time, independent of run age',()=>{const now=Date.now(),repo='c'.repeat(24),run=`${now-31*86400_000}-${'2'.repeat(16)}`,dir=secureDirectory(path.join(privateRoot(),repo,run)),bundles=secureDirectory(path.join(dir,'bundles')),expiredId='3'.repeat(32),retainedId='4'.repeat(32),record=(id:string,created:number)=>{const createdAt=new Date(created).toISOString();return{schemaVersion:3,id,runId:run,createdAt,expiresAt:new Date(created+30*86400_000).toISOString(),verification:{id,runId:run,createdAt}};};writeHelperJson(path.join(bundles,`${expiredId}.json`),record(expiredId,now-31*86400_000));writeHelperJson(path.join(bundles,`${retainedId}.json`),record(retainedId,now-86400_000));retention(now);expect(fs.existsSync(path.join(bundles,`${expiredId}.json`))).toBe(false);expect(fs.existsSync(path.join(bundles,`${retainedId}.json`))).toBe(true);expect(fs.existsSync(dir)).toBe(true);retention(now+30*86400_000);expect(fs.existsSync(dir)).toBe(false);}); - test('a killed attempt\'s scratch is reclaimed only after its detached watchdog records cleanup',()=>{const now=Date.now(),repo='c'.repeat(24),run=`${now}-${'6'.repeat(16)}`,dir=secureDirectory(path.join(privateRoot(),repo,run)),call=secureDirectory(path.join(dir,'preparation-execution','acquire-attempt')),staging=secureDirectory(path.join(dir,'archive-staging','acquire-partial')),kept=path.join(dir,'report.json');fs.writeFileSync(kept,'{}',{mode:0o600});fs.writeFileSync(path.join(staging,'partial.tgz'),'partial',{mode:0o600});fs.writeFileSync(path.join(call,'watchdog.ready'),'ready\n',{mode:0o600});fs.writeFileSync(path.join(call,'watchdog.event'),'cleanup incomplete; retrying exact journaled resources\n',{mode:0o600});expect(reclaimDeadAttemptScratch(dir)).toBe(false);expect(fs.existsSync(call)).toBe(true);expect(fs.existsSync(staging)).toBe(true);fs.writeFileSync(path.join(call,'watchdog.event'),'supervisor-death cleanup complete\n',{mode:0o600});expect(reclaimDeadAttemptScratch(dir)).toBe(true);for(const name of ['preparation-execution','archive-staging'])expect(fs.readdirSync(path.join(dir,name))).toEqual([]);expect(fs.existsSync(kept)).toBe(true);fs.rmSync(path.join(dir,'archive-staging'),{recursive:true});fs.symlinkSync(os.tmpdir(),path.join(dir,'archive-staging'));expect(()=>reclaimDeadAttemptScratch(dir)).toThrow('Attempt scratch is not a private directory');}); - test('replay temporary state survives cleanup failure until every detached watchdog acknowledges cleanup',()=>{const now=Date.now(),repo='b'.repeat(24),run=`${now}-${'5'.repeat(16)}`,dir=secureDirectory(path.join(privateRoot(),repo,run)),control=secureDirectory(path.join(dir,'supervision','repair-attempt')),docker=secureDirectory(path.join(dir,'preparation-execution','offline-attempt'));fs.writeFileSync(path.join(control,'attempt.ready'),'ready\n',{mode:0o600});fs.writeFileSync(path.join(control,'attempt.terminal'),'normal cleanup complete\n',{mode:0o600});fs.writeFileSync(path.join(docker,'watchdog.ready'),'ready\n',{mode:0o600});fs.writeFileSync(path.join(docker,'watchdog.event'),'cleanup incomplete; retrying exact journaled resources\n',{mode:0o600});finalizeReplayTemporary(dir);expect(fs.existsSync(path.join(dir,'.ephemeral-replay.json'))).toBe(true);retention(now);expect(fs.existsSync(control)).toBe(true);expect(fs.existsSync(docker)).toBe(true);fs.writeFileSync(path.join(control,'attempt.stopped'),'normal cleanup acknowledged\n',{mode:0o600});retention(now);expect(fs.existsSync(dir)).toBe(true);fs.writeFileSync(path.join(docker,'watchdog.stopped'),'normal cleanup acknowledged\n',{mode:0o600});retention(now);expect(fs.existsSync(dir)).toBe(false);}); - test('retention recovers a hidden run retirement left by a dead helper',()=>{const now=Date.now(),repo='a'.repeat(24),run=`${now-31*86400_000}-${'6'.repeat(16)}`,retired=secureDirectory(path.join(privateRoot(),repo,`.retired-${run}-${'7'.repeat(32)}`));fs.writeFileSync(path.join(retired,'payload'),'private state\n',{mode:0o600});retention(now);expect(fs.existsSync(retired)).toBe(false);}); -}); -describe('private state and process output',()=>{ - test('state root mirrors the plugin convention and private writes use restrictive modes',()=>{const base=tmp(),root=stateRoot({HOME:base,GSTACK_HOME:'',CLAUDE_PLUGIN_ROOT:'',CLAUDE_PLUGIN_DATA:''});expect(root).toBe(path.join(base,'.gstack'));const dir=secureDirectory(path.join(base,'state')),file=path.join(dir,'x.json');writeJson(file,{token:'safe'});expect(fs.statSync(dir).mode&0o777).toBe(0o700);expect(fs.statSync(file).mode&0o777).toBe(0o600);}); - test('private root preserves caller-owned container modes and secures only its own boundary',()=>{if(process.platform==='win32')return;const old=process.env.GSTACK_HOME,base=tmp(),selected=path.join(base,'selected'),security=path.join(selected,'security'),sentinel=path.join(selected,'keep');fs.mkdirSync(security,{recursive:true});fs.chmodSync(selected,0o755);fs.chmodSync(security,0o751);fs.writeFileSync(sentinel,'kept');const selectedInode=fs.statSync(selected).ino,securityInode=fs.statSync(security).ino;process.env.GSTACK_HOME=selected;try{expect(privateRoot()).toBe(path.join(security,'cso'));expect(privateRoot()).toBe(path.join(security,'cso'));expect(fs.statSync(selected).mode&0o777).toBe(0o755);expect(fs.statSync(security).mode&0o777).toBe(0o751);expect(fs.statSync(selected).ino).toBe(selectedInode);expect(fs.statSync(security).ino).toBe(securityInode);expect(fs.readFileSync(sentinel,'utf8')).toBe('kept');expect(fs.statSync(path.join(security,'cso')).mode&0o777).toBe(0o700);}finally{if(old===undefined)delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME=old;}}); - test('private root creates a missing selected container privately',()=>{const old=process.env.GSTACK_HOME,base=tmp(),selected=path.join(base,'missing');process.env.GSTACK_HOME=selected;try{expect(privateRoot()).toBe(path.join(selected,'security','cso'));for(const directory of [selected,path.join(selected,'security'),path.join(selected,'security','cso')])expect(fs.statSync(directory).mode&0o777).toBe(0o700);}finally{if(old===undefined)delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME=old;}}); - test('private root rejects unsafe or filesystem-root containers without repairing them',()=>{if(process.platform==='win32')return;const old=process.env.GSTACK_HOME,base=tmp(),selected=path.join(base,'unsafe');fs.mkdirSync(selected);fs.chmodSync(selected,0o770);const inode=fs.statSync(selected).ino;try{process.env.GSTACK_HOME=selected;expect(()=>privateRoot()).toThrow('group- or world-writable ancestor');expect(fs.statSync(selected).mode&0o777).toBe(0o770);expect(fs.statSync(selected).ino).toBe(inode);expect(fs.existsSync(path.join(selected,'security'))).toBe(false);process.env.GSTACK_HOME=path.parse(selected).root;const chmod=spyOn(fs,'chmodSync');try{expect(()=>privateRoot()).toThrow('filesystem root');expect(chmod.mock.calls.some(call=>path.resolve(String(call[0]))===path.parse(selected).root)).toBe(false);}finally{chmod.mockRestore();}}finally{if(old===undefined)delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME=old;}}); - test('concurrent first-run directory creation accepts only the expected EEXIST race',()=>{const base=tmp(),target=path.join(base,'first','second'),first=path.join(base,'first'),mkdir=fs.mkdirSync;let raced=false;const patched=spyOn(fs,'mkdirSync').mockImplementation(((candidate:any,options:any)=>{if(String(candidate)===first&&!raced){raced=true;mkdir(candidate,options);const error:any=new Error('created concurrently');error.code='EEXIST';throw error;}return mkdir(candidate,options);}) as typeof fs.mkdirSync);try{expect(secureDirectory(target)).toBe(target);expect(raced).toBe(true);expect(fs.statSync(target).mode&0o777).toBe(0o700);}finally{patched.mockRestore();}}); - test('private state rejects a non-sticky group-writable ancestor',()=>{if(process.platform==='win32')return;const base=tmp();fs.chmodSync(base,0o770);expect(()=>secureDirectory(path.join(base,'private'))).toThrow('group- or world-writable ancestor');}); - test('split process output is joined and redacted before return',async()=>{const dir=tmp(),r=await runProcess('/bin/sh',['-c',"printf 'ghp_abcdefghijklmnop'; printf 'qrstuvwxyz1234567890' >&2"],{cwd:dir,env:{PATH:'/usr/bin:/bin'}});expect(r.stdout+r.stderr).not.toContain('ghp_');expect(r.stdout.toLowerCase()).toContain('redacted');}); - test('alternating stdout and stderr chunks cannot split a secret marker',async()=>{const dir=tmp(),r=await runProcess('/bin/sh',['-c',"printf g; sleep .02; printf hp_abcdefghijklmnop >&2; sleep .02; printf qrstuvwxyz1234567890"],{cwd:dir,env:{PATH:'/usr/bin:/bin'}});expect(r.stdout+r.stderr).not.toContain('abcdefghijklmnop');expect(r.stdout.toLowerCase()).toContain('redacted');}); - test('qualified catalog workflow run URLs persist unchanged while the same digits elsewhere stay redacted',()=>{const url='https://github.com/garrytan/gstack/actions/runs/37249065172';expect(sanitizeHelperForJson({qualification:{workflow:url}})).toEqual({qualification:{workflow:url}});expect(JSON.stringify(sanitizeHelperForJson({note:url}))).not.toContain('37249065172');expect(JSON.stringify(sanitizeHelperForJson({workflow:`${url}?call=37249065172`}))).not.toContain('call=37249065172');for(const [key,revision] of [['scannerCatalog','cso-scanners-f97aefe654fb-37249065172'],['catalog','cso-v3-37249065172-f97aefe654fb'],['catalogRevision','cso-eval-37249065172-f97aefe654fb']])expect(sanitizeHelperForJson({[key]:revision})).toEqual({[key]:revision});expect(JSON.stringify(sanitizeHelperForJson({catalog:'call 37249065172'}))).not.toContain('37249065172');}); - test('splice redaction keeps structured scanner output and marks only located spans',async()=>{const dir=tmp(),r=await runProcess('/bin/sh',['-c',"printf '{\"url\":\"https://security.netapp.com/advisory/ntap-20210312-0006\",\"ok\":true}'; printf 'log line' >&2"],{cwd:dir,env:{PATH:'/usr/bin:/bin'},redaction:'splice'});expect(r.stdout).not.toContain('20210312-0006');expect(JSON.parse(r.stdout).ok).toBe(true);expect(r.stdout).toContain('{const dir=tmp();for(const script of ["printf 'ghp_abcdefghijklmnop'; printf 'qrstuvwxyz1234567890' >&2","printf g; sleep .02; printf hp_abcdefghijklmnop >&2; sleep .02; printf qrstuvwxyz1234567890"]){const r=await runProcess('/bin/sh',['-c',script],{cwd:dir,env:{PATH:'/usr/bin:/bin'},redaction:'splice'});expect(r.stdout+r.stderr).not.toContain('abcdefghijklmnop');expect(r.stdout).toBe('[sensitive process output redacted]');}}); - test('splice redaction replaces a whole-channel secret instead of leaking it',async()=>{const dir=tmp(),token=['ghp','abcdefghijklmnopqrstuvwxyz1234567890'].join('_'),r=await runProcess('/bin/sh',['-c',`printf 'token=${token} done'`],{cwd:dir,env:{PATH:'/usr/bin:/bin'},redaction:'splice'});expect(r.stdout).not.toContain('abcdefghijklmnop');expect(r.stdout).toContain('done');}); - test('marker-only private keys withhold the whole payload',async()=>{const dir=tmp();expect(runProcess('/bin/sh',['-c',"printf '%s' \"$1\"",'sh',['-----BEGIN ','PRIVATE KEY-----\nraw\n-----END ','PRIVATE KEY-----'].join('')],{cwd:dir,env:{PATH:'/usr/bin:/bin'}})).rejects.toMatchObject({code:'REDACTION_FAILED'});}); - test('untrusted hash-like keys do not bypass structured redaction',()=>{const dir=tmp(),file=path.join(dir,'value.json');writeJson(file,{payloadHash:['ghp_','abcdefghijklmnopqrstuvwxyz1234567890'].join('')});expect(fs.readFileSync(file,'utf8')).not.toContain('ghp_');}); - test('only schema-bound helper metadata bypasses content redaction',()=>{const token='1abcdefabcdefabcdefabcdefabcdefa',hash='a'.repeat(64),untrusted=sanitizeForJson({id:token,findingId:token,sourceHash:hash}) as any;expect(untrusted.id).not.toBe(token);expect(untrusted.findingId).not.toBe(token);const trusted=sanitizeHelperForJson({id:token,findingId:token,artifactId:token,reviewArtifactId:token,bundleId:token,sourceHash:hash,preparedManifestHash:hash}) as any;expect(trusted).toEqual({id:token,findingId:token,artifactId:token,reviewArtifactId:token,bundleId:token,sourceHash:hash,preparedManifestHash:hash});const dir=tmp(),file=path.join(dir,'claim.json');writeHelperJson(file,{findingId:token,outcome:'open'});expect(readJson(file)).toEqual({findingId:token,outcome:'open'});}); - test('oversized report growth is rejected before replacing the last readable report',()=>{const dir=tmp(),report:any={schemaVersion:3,runId:'1'.repeat(13)+'-'+'a'.repeat(16),repoId:'b'.repeat(24),createdAt:new Date().toISOString(),deadline:new Date(Date.now()+60_000).toISOString(),status:'running',completeness:'not assessed',policy:{mode:'daily',scope:'default',diff:false,base:'origin/main',offline:true,budgetSeconds:600,maxWorkers:3,maxRepairs:3},source:{root:'/source',snapshotHash:'c'.repeat(64),originalHash:'d'.repeat(64)},application:{actors:[],assets:[],entrypoints:[],tenantBoundaries:[],sensitiveOperations:[],invariants:[]},coverage:[],findings:[],gaps:[],events:[]};saveReport(dir,report);const original=fs.readFileSync(path.join(dir,'report.json'),'utf8');report.events=Array.from({length:4000},(_,i)=>({at:new Date().toISOString(),kind:'evidence',message:`${i}:`+'x'.repeat(300)}));expect(()=>saveReport(dir,report)).toThrow('previous artifact was preserved');expect(fs.readFileSync(path.join(dir,'report.json'),'utf8')).toBe(original);expect(loadReport(dir).status).toBe('running');}); - test('a fully published dead legacy owner migrates to the immutable lease protocol',()=>{const dir=tmp(),lock=path.join(dir,'.mutation-lock');fs.mkdirSync(lock);fs.writeFileSync(path.join(lock,'owner.json'),JSON.stringify({pid:2147483647,token:'old',createdAt:0,expiresAt:0}));expect(withLock(dir,()=>42)).toBe(42);expect(fs.lstatSync(lock).isFile()).toBe(true);expect(JSON.parse(fs.readFileSync(lock,'utf8')).protocol).toBe('immutable-lease-set-v3');expect(fs.readdirSync(path.join(dir,'.mutation-lock-leases'))).toEqual([]);}); - test('a dead legacy migration claim is recovered after an interrupted migration',()=>{const dir=tmp(),lock=path.join(dir,'.mutation-lock'),claim=path.join(lock,'.v3-migration'),token='b'.repeat(32);fs.mkdirSync(lock);fs.writeFileSync(path.join(lock,'owner.json'),JSON.stringify({pid:2147483647,token:'old',createdAt:0}));fs.writeFileSync(claim,JSON.stringify({pid:2147483647,token,createdAt:0})+'\n',{mode:0o600,flag:'wx'});expect(withLock(dir,()=>42)).toBe(42);expect(fs.lstatSync(lock).isFile()).toBe(true);expect(fs.readdirSync(path.join(dir,'.mutation-lock-leases'))).toEqual([]);expect(fs.readdirSync(dir).some(name=>name.includes('.legacy-'))).toBe(false);}); - test('an expired timestamp cannot steal a lock from a live owner',()=>{const dir=tmp(),lock=path.join(dir,'.mutation-lock');fs.mkdirSync(lock);fs.writeFileSync(path.join(lock,'owner.json'),JSON.stringify({pid:process.pid,token:'live',createdAt:0,expiresAt:0}));expect(()=>withLock(dir,()=>42)).toThrow('Another helper');}); - test('an incomplete legacy lock is never age-reclaimed from a paused initializer',()=>{const dir=tmp(),lock=path.join(dir,'.mutation-lock'),entered=path.join(dir,'entered');fs.mkdirSync(lock);const old=new Date(Date.now()-60_000);fs.utimesSync(lock,old,old);expect(()=>withLock(dir,()=>fs.writeFileSync(entered,'unsafe'))).toThrow('may still be initializing');expect(fs.existsSync(entered)).toBe(false);expect(fs.lstatSync(lock).isDirectory()).toBe(true);fs.writeFileSync(path.join(lock,'owner.json'),JSON.stringify({pid:process.pid,token:'paused',createdAt:0,expiresAt:0}));expect(()=>withLock(dir,()=>fs.writeFileSync(entered,'unsafe'))).toThrow('Another helper');expect(fs.existsSync(entered)).toBe(false);}); - test('a dead immutable lease is recovered without replacing its inode',()=>{const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token='a'.repeat(32),lease=path.join(leases,`${token}.json`);fs.writeFileSync(lease,JSON.stringify({pid:2147483647,token,createdAt:0})+'\n',{mode:0o600,flag:'wx'});expect(withLock(dir,()=>2)).toBe(2);expect(fs.existsSync(lease)).toBe(false);}); - test('an in-flight cooperating lease publication is contention rather than poisoned state',()=>{const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token='9'.repeat(32),lease=path.join(leases,`${token}.json`),temporary=`${lease}.tmp.${process.pid}.deadbeef`,write=fs.writeFileSync,lstat=fs.lstatSync;let injected=false,transitioned=false,entered=false,caught:unknown;const writer=spyOn(fs,'writeFileSync').mockImplementation(((file:any,data:any,options:any)=>{const result=write(file,data,options);const candidate=String(file);if(!injected&&path.dirname(candidate)===leases&&/^[a-f0-9]{32}\.json\.tmp\.\d+\.[a-f0-9]{8}$/.test(path.basename(candidate))){injected=true;write(temporary,JSON.stringify({pid:process.pid,token,createdAt:Date.now()})+'\n',{mode:0o600,flag:'wx'});}return result;}) as typeof fs.writeFileSync),reader=spyOn(fs,'lstatSync').mockImplementation(((file:any,options?:any)=>{if(!transitioned&&String(file)===temporary){transitioned=true;fs.linkSync(temporary,lease);fs.unlinkSync(temporary);}return options===undefined?lstat(file):lstat(file,options);}) as typeof fs.lstatSync);try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}finally{reader.mockRestore();writer.mockRestore();}expect(injected).toBe(true);expect(transitioned).toBe(true);expect(entered).toBe(false);expect(caught).toMatchObject({code:'INSUFFICIENT_CAPACITY'});expect(fs.readdirSync(leases)).toEqual([path.basename(lease)]);}); - test('a live publisher unlinking its temp after target observation remains ordinary contention',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1); - const leases=path.join(dir,'.mutation-lock-leases'),token='7'.repeat(32),lease=path.join(leases,`${token}.json`),temporary=`${lease}.tmp.${process.pid}.abcdef12`; - fs.writeFileSync(temporary,JSON.stringify({pid:process.pid,token,createdAt:Date.now()})+'\n',{mode:0o600,flag:'wx'});fs.linkSync(temporary,lease); - const lstat=fs.lstatSync;let targetReads=0,transitioned=false,entered=false,caught:unknown; - const reader=spyOn(fs,'lstatSync').mockImplementation(((file:any,options?:any)=>{ - if(String(file)===lease&&++targetReads===2){fs.unlinkSync(temporary);transitioned=true;} - return options===undefined?lstat(file):lstat(file,options); - }) as typeof fs.lstatSync); - try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}finally{reader.mockRestore();} - expect(transitioned).toBe(true);expect(entered).toBe(false);expect(caught).toMatchObject({code:'INSUFFICIENT_CAPACITY'});expect(fs.statSync(lease).nlink).toBe(1); - }); - test('a live publisher unlinking its temp after canonical validation is rescanned as contention',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1); - const leases=path.join(dir,'.mutation-lock-leases'),token='5'.repeat(32),lease=path.join(leases,`${token}.json`),temporary=`${lease}.tmp.${process.pid}.a1b2c3d4`; - fs.writeFileSync(temporary,JSON.stringify({pid:process.pid,token,createdAt:Date.now()})+'\n',{mode:0o600,flag:'wx'});fs.linkSync(temporary,lease); - const readdir=fs.readdirSync;let leaseReads=0,transitioned=false,entered=false,caught:unknown; - const reader=spyOn(fs,'readdirSync').mockImplementation(((directory:any,options?:any)=>{ - if(String(directory)===leases&&++leaseReads===2){fs.unlinkSync(temporary);transitioned=true;} - return options===undefined?readdir(directory):readdir(directory,options); - }) as typeof fs.readdirSync); - try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}finally{reader.mockRestore();} - expect(transitioned).toBe(true);expect(entered).toBe(false);expect(caught).toMatchObject({code:'INSUFFICIENT_CAPACITY'});expect(fs.statSync(lease).nlink).toBe(1); - }); - test('a live temp linked after the absent-target check remains ordinary contention',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1); - const leases=path.join(dir,'.mutation-lock-leases'),token='8'.repeat(32),lease=path.join(leases,`${token}.json`),temporary=`${lease}.tmp.${process.pid}.1234abcd`; - fs.writeFileSync(temporary,JSON.stringify({pid:process.pid,token,createdAt:Date.now()})+'\n',{mode:0o600,flag:'wx'}); - const exists=fs.existsSync;let transitioned=false,entered=false,caught:unknown; - const observer=spyOn(fs,'existsSync').mockImplementation(((file:any)=>{ - const result=exists(file);if(!transitioned&&String(file)===lease&&!result){fs.linkSync(temporary,lease);transitioned=true;}return result; - }) as typeof fs.existsSync); - try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}finally{observer.mockRestore();} - expect(transitioned).toBe(true);expect(entered).toBe(false);expect(caught).toMatchObject({code:'INSUFFICIENT_CAPACITY'});expect(fs.statSync(lease).nlink).toBe(2); - }); - test('an unrecognized multiply-linked lease temp remains poisoned state',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1); - const leases=path.join(dir,'.mutation-lock-leases'),token='6'.repeat(32),temporary=path.join(leases,`${token}.json.tmp.2147483647.1234abcd`),outside=path.join(dir,'outside-link'); - fs.writeFileSync(temporary,JSON.stringify({pid:2147483647,token,createdAt:0})+'\n',{mode:0o600,flag:'wx'});fs.linkSync(temporary,outside); - let entered=false,caught:unknown;try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;} - expect(entered).toBe(false);expect(caught).toMatchObject({code:'UNSAFE_PATH'});expect(fs.existsSync(temporary)).toBe(true);expect(fs.existsSync(outside)).toBe(true); - }); - test('a same-inode same-size content rewrite is not treated as publication progress',()=>{ - const dir=tmp(),token='0'.repeat(32),publisherPid=2147483647,target=path.join(dir,`${token}.json`),temporary=`${target}.tmp.${publisherPid}.abcdef12`,original=JSON.stringify({pid:publisherPid,token,createdAt:0})+'\n',replacement=JSON.stringify({pid:publisherPid,token,createdAt:1})+'\n';expect(replacement.length).toBe(original.length);fs.writeFileSync(temporary,original,{mode:0o600,flag:'wx'});fs.linkSync(temporary,target); - const fstat=fs.fstatSync;let reads=0,rewritten=false;const reader=spyOn(fs,'fstatSync').mockImplementation(((fd:any,options?:any)=>{if(++reads===2){fs.writeFileSync(target,replacement);rewritten=true;}return options===undefined?fstat(fd):fstat(fd,options);}) as typeof fs.fstatSync); - let caught:unknown;try{discardAtomicNoReplaceTemp(temporary,publisherPid,{label:'Test publication',maxBytes:4096});}catch(error){caught=error;}finally{reader.mockRestore();} - expect(rewritten).toBe(true);expect(caught).toMatchObject({code:'SNAPSHOT_RACE'});expect(fs.existsSync(target)).toBe(true);expect(fs.existsSync(temporary)).toBe(true); - }); - test('a live publisher identity cannot launder a stable same-size rewrite as contention',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token='f'.repeat(32),publisherPid=process.pid,target=path.join(leases,`${token}.json`),temporary=`${target}.tmp.${publisherPid}.abcdef12`,original=JSON.stringify({pid:publisherPid,token,createdAt:0})+'\n',replacement=JSON.stringify({pid:publisherPid,token,createdAt:1})+'\n';expect(replacement.length).toBe(original.length);fs.writeFileSync(temporary,original,{mode:0o600,flag:'wx'});fs.linkSync(temporary,target); - const fstat=fs.fstatSync;let reads=0,rewritten=false,entered=false,caught:unknown;const reader=spyOn(fs,'fstatSync').mockImplementation(((fd:any,options?:any)=>{if(++reads===2){fs.writeFileSync(target,replacement);rewritten=true;}return options===undefined?fstat(fd):fstat(fd,options);}) as typeof fs.fstatSync);try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}finally{reader.mockRestore();} - expect(rewritten).toBe(true);expect(entered).toBe(false);expect(caught).toMatchObject({code:'SNAPSHOT_RACE'});expect(fs.existsSync(target)).toBe(true);expect(fs.existsSync(temporary)).toBe(true); - }); - test('a stable malformed hard-link publication stays unsafe even when its named PID is live',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token='9'.repeat(32),target=path.join(leases,`${token}.json`),temporary=`${target}.tmp.${process.pid}.deadbeef`;fs.writeFileSync(temporary,'{"malformed":\n',{mode:0o600,flag:'wx'});fs.linkSync(temporary,target);let entered=false,caught:unknown;try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}expect(entered).toBe(false);expect(caught).toMatchObject({code:'UNSAFE_PATH'});expect(fs.existsSync(target)).toBe(true);expect(fs.existsSync(temporary)).toBe(true); - }); - test('a zero-byte hard-linked publication stays unsafe even when its named PID is live',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token='7'.repeat(32),target=path.join(leases,`${token}.json`),temporary=`${target}.tmp.${process.pid}.deadbeef`;fs.writeFileSync(temporary,'',{mode:0o600,flag:'wx'});fs.linkSync(temporary,target);let entered=false,caught:unknown;try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}expect(entered).toBe(false);expect(caught).toMatchObject({code:'UNSAFE_PATH'});expect(fs.statSync(target).nlink).toBe(2);expect(fs.statSync(temporary).nlink).toBe(2); - }); - test('settled publication contention cannot launder a stable incoherent lease phase',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),poisonToken='a'.repeat(32),liveToken='b'.repeat(32),poison=path.join(leases,`${poisonToken}.active.0000000000000001`),temporary=path.join(leases,`${liveToken}.json.tmp.${process.pid}.abcdef12`);fs.writeFileSync(poison,JSON.stringify({pid:process.pid,token:poisonToken,createdAt:0})+'\n',{mode:0o600,flag:'wx'}); - const write=fs.writeFileSync;let injected=false;const publisher=spyOn(fs,'writeFileSync').mockImplementation(((file:any,data:any,options:any)=>{const result=write(file,data,options),name=path.basename(String(file));if(!injected&&path.dirname(String(file))===leases&&/^[a-f0-9]{32}\.json\.tmp\.\d+\.[a-f0-9]{8}$/.test(name)&&!name.startsWith(liveToken)){injected=true;write(temporary,JSON.stringify({pid:process.pid,token:liveToken,createdAt:0})+'\n',{mode:0o600,flag:'wx'});}return result;}) as typeof fs.writeFileSync); - const wait=Atomics.wait.bind(Atomics);let settled=false,entered=false,caught:unknown;const sleeper=spyOn(Atomics,'wait').mockImplementation(((array:any,index:any,value:any,timeout?:any)=>{if(!settled&&fs.existsSync(temporary)){settled=true;fs.unlinkSync(temporary);}return wait(array,index,value,timeout);}) as typeof Atomics.wait);try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}finally{sleeper.mockRestore();publisher.mockRestore();} - expect(injected).toBe(true);expect(settled).toBe(true);expect(entered).toBe(false);expect(caught).toMatchObject({code:'UNSAFE_PATH'});expect(fs.existsSync(poison)).toBe(true); - }); - test('successful recovery on the final bounded rescan remains transient capacity',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),liveToken='c'.repeat(32),temporary=path.join(leases,`${liveToken}.json.tmp.${process.pid}.abcdef12`),write=fs.writeFileSync;let injected=false;const publisher=spyOn(fs,'writeFileSync').mockImplementation(((file:any,data:any,options:any)=>{const result=write(file,data,options),name=path.basename(String(file));if(!injected&&path.dirname(String(file))===leases&&/^[a-f0-9]{32}\.json\.tmp\.\d+\.[a-f0-9]{8}$/.test(name)&&!name.startsWith(liveToken)){injected=true;write(temporary,JSON.stringify({pid:process.pid,token:liveToken,createdAt:0})+'\n',{mode:0o600,flag:'wx'});}return result;}) as typeof fs.writeFileSync); - const now=spyOn(Date,'now').mockReturnValue(1000),kill=process.kill.bind(process);let probes=0,entered=false,caught:unknown;const liveness=spyOn(process,'kill').mockImplementation(((pid:any,signal?:any)=>{if(Number(pid)===process.pid&&signal===0&&++probes===532){const error:any=new Error('gone');error.code='ESRCH';throw error;}return Number(pid)===process.pid&&signal===0?true:(signal===undefined?kill(pid):kill(pid,signal));}) as typeof process.kill);try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}finally{liveness.mockRestore();now.mockRestore();publisher.mockRestore();} - expect(injected).toBe(true);expect(probes).toBe(532);expect(entered).toBe(false);expect(caught).toMatchObject({code:'INSUFFICIENT_CAPACITY'});expect(fs.existsSync(temporary)).toBe(false);expect(fs.readdirSync(leases)).toEqual([]); - }); - test('a settled publication remains bound to the originally observed inode',()=>{ - const dir=tmp(),token='4'.repeat(32),publisherPid=2147483647,target=path.join(dir,`${token}.json`),temporary=`${target}.tmp.${publisherPid}.abcdef12`,parked=`${target}.replaced`,owner=JSON.stringify({pid:publisherPid,token,createdAt:0})+'\n'; - fs.writeFileSync(temporary,owner,{mode:0o600,flag:'wx'});fs.linkSync(temporary,target);const original=fs.statSync(target).ino,lstat=fs.lstatSync;let targetReads=0,replaced=false,caught:unknown; - const reader=spyOn(fs,'lstatSync').mockImplementation(((file:any,options?:any)=>{ - if(String(file)===target&&++targetReads===2){fs.unlinkSync(target);fs.renameSync(temporary,parked);fs.writeFileSync(target,owner,{mode:0o600,flag:'wx'});replaced=true;} - return options===undefined?lstat(file):lstat(file,options); - }) as typeof fs.lstatSync); - try{discardAtomicNoReplaceTemp(temporary,publisherPid,{label:'Test publication',maxBytes:4096,validate:(value,pid)=>{expect((value as any).token).toBe(token);expect(pid).toBe(publisherPid);}});}catch(error){caught=error;}finally{reader.mockRestore();} - expect(replaced).toBe(true);expect(caught).toMatchObject({code:'UNSAFE_PATH'});expect(fs.statSync(parked).ino).toBe(original);expect(fs.statSync(target).ino).not.toBe(original); - }); - test('a link transition on an open inode cannot launder a replacement pathname',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1); - const leases=path.join(dir,'.mutation-lock-leases'),token='3'.repeat(32),publisherPid=2147483647,target=path.join(leases,`${token}.json`),temporary=`${target}.tmp.${publisherPid}.1234abcd`,owner=JSON.stringify({pid:publisherPid,token,createdAt:0})+'\n'; - fs.writeFileSync(temporary,owner,{mode:0o600,flag:'wx'});fs.linkSync(temporary,target);const original=fs.statSync(target).ino,fstat=fs.fstatSync;let reads=0,replaced=false,entered=false,caught:unknown; - const reader=spyOn(fs,'fstatSync').mockImplementation(((fd:any,options?:any)=>{ - if(++reads===2){fs.unlinkSync(target);fs.writeFileSync(target,owner,{mode:0o600,flag:'wx'});replaced=true;} - return options===undefined?fstat(fd):fstat(fd,options); - }) as typeof fs.fstatSync); - try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}finally{reader.mockRestore();} - expect(replaced).toBe(true);expect(entered).toBe(false);expect(caught).toMatchObject({name:'CsoError',code:'SNAPSHOT_RACE'});expect(fs.statSync(target).ino).not.toBe(original);expect(fs.existsSync(temporary)).toBe(true); - }); - test('a cooperating lease released between open and fstat is rescanned',()=>{ - const dir=tmp();expect(withLock(dir,()=>1)).toBe(1); - const leases=path.join(dir,'.mutation-lock-leases'),token='2'.repeat(32),lease=path.join(leases,`${token}.json`);fs.writeFileSync(lease,JSON.stringify({pid:process.pid,token,createdAt:Date.now()})+'\n',{mode:0o600,flag:'wx'}); - const fstat=fs.fstatSync;let released=false,entered=false;const reader=spyOn(fs,'fstatSync').mockImplementation(((fd:any,options?:any)=>{if(!released){fs.unlinkSync(lease);released=true;}return options===undefined?fstat(fd):fstat(fd,options);}) as typeof fs.fstatSync); - try{withLock(dir,()=>{entered=true;});}finally{reader.mockRestore();} - expect(released).toBe(true);expect(entered).toBe(true);expect(fs.existsSync(lease)).toBe(false); - }); - test('recovers the exact no-replace lease hard link left by a dead publisher',()=>{const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token='1'.repeat(32),lease=path.join(leases,`${token}.json`),temporary=`${lease}.tmp.2147483647.deadbeef`;fs.writeFileSync(lease,JSON.stringify({pid:2147483647,token,createdAt:0})+'\n',{mode:0o600,flag:'wx'});fs.linkSync(lease,temporary);expect(fs.statSync(lease).nlink).toBe(2);expect(withLock(dir,()=>2)).toBe(2);expect(fs.existsSync(lease)).toBe(false);expect(fs.existsSync(temporary)).toBe(false);}); - test('private immutable reads recover only a recognized same-inode no-replace temp',()=>{const dir=tmp(),artifact=path.join(dir,'artifact.json'),temporary=`${artifact}.tmp.2147483647.cafebabe`;fs.writeFileSync(artifact,JSON.stringify({value:'bound'})+'\n',{mode:0o600,flag:'wx'});fs.linkSync(artifact,temporary);expect(readJson(artifact)).toEqual({value:'bound'});expect(fs.statSync(artifact).nlink).toBe(1);expect(fs.existsSync(temporary)).toBe(false);const poisoned=path.join(dir,'poisoned.json'),unrecognized=`${poisoned}.tmp.dead.bad`;fs.writeFileSync(poisoned,'{}\n',{mode:0o600,flag:'wx'});fs.linkSync(poisoned,unrecognized);expect(()=>readJson(poisoned)).toThrow('hard link does not match');expect(fs.existsSync(unrecognized)).toBe(true);}); - test('private JSON reads reject rename and symlink substitutions between validation and open',()=>{for(const kind of ['rename','symlink'] as const){const dir=tmp(),artifact=path.join(dir,'artifact.json'),original=path.join(dir,'original.json'),poison=path.join(dir,'poison.json');fs.writeFileSync(artifact,JSON.stringify({value:'bound'})+'\n',{mode:0o600});fs.writeFileSync(poison,JSON.stringify({value:'poison'})+'\n',{mode:0o600});const open=fs.openSync,patched=spyOn(fs,'openSync').mockImplementation(((candidate:any,flags:any,mode?:any)=>{if(String(candidate)===artifact){fs.renameSync(artifact,original);if(kind==='rename')fs.renameSync(poison,artifact);else fs.symlinkSync(poison,artifact);}return mode===undefined?open(candidate,flags):open(candidate,flags,mode);}) as typeof fs.openSync);try{expect(()=>readJson(artifact)).toThrow(/changed while it was opened/);}finally{patched.mockRestore();}}}); - test('mismatched lease publisher identity fails closed',()=>{const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token='2'.repeat(32),lease=path.join(leases,`${token}.json`),temporary=`${lease}.tmp.2147483646.abcdef12`;fs.writeFileSync(lease,JSON.stringify({pid:2147483647,token,createdAt:0})+'\n',{mode:0o600,flag:'wx'});fs.linkSync(lease,temporary);expect(()=>withLock(dir,()=>2)).toThrow('does not match its publisher');expect(fs.statSync(lease).nlink).toBe(2);}); - test('malformed and multiply-linked immutable owners fail closed instead of being reclaimed',()=>{for(const kind of ['schema','hardlink'] as const){const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token=(kind==='schema'?'c':'d').repeat(32),lease=path.join(leases,`${token}.json`),value=JSON.stringify(kind==='schema'?{pid:'dead',token,createdAt:0}:{pid:2147483647,token,createdAt:0})+'\n';fs.writeFileSync(lease,value,{mode:0o600,flag:'wx'});if(kind==='hardlink')fs.linkSync(lease,path.join(dir,'outside-link'));let entered=false;expect(()=>withLock(dir,()=>{entered=true;})).toThrow('Run mutation lease');expect(entered).toBe(false);expect(fs.existsSync(lease)).toBe(true);}}); - test('PID reuse is distinguished by the Linux process-start identity',()=>{if(process.platform!=='linux')return;const raw=fs.readFileSync(`/proc/${process.pid}/stat`,'utf8'),tail=raw.slice(raw.lastIndexOf(')')+2).trim().split(/\s+/),identity=BigInt(tail[19]),dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token='e'.repeat(32),lease=path.join(leases,`${token}.json`);fs.writeFileSync(lease,JSON.stringify({pid:process.pid,processIdentity:`linux:${identity+1n}`,token,createdAt:0})+'\n',{mode:0o600,flag:'wx'});expect(withLock(dir,()=>2)).toBe(2);expect(fs.existsSync(lease)).toBe(false);}); - test('interrupted lease publications use process identity to distinguish PID reuse',()=>{if(process.platform!=='linux')return;const raw=fs.readFileSync(`/proc/${process.pid}/stat`,'utf8'),tail=raw.slice(raw.lastIndexOf(')')+2).trim().split(/\s+/),identity=BigInt(tail[19]);for(const linked of [false,true]){const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token=(linked?'b':'a').repeat(32),lease=path.join(leases,`${token}.json`),temporary=`${lease}.tmp.${process.pid}.abcdef12`,owner=JSON.stringify({pid:process.pid,processIdentity:`linux:${identity+1n}`,token,createdAt:0})+'\n';fs.writeFileSync(temporary,owner,{mode:0o600,flag:'wx'});if(linked)fs.linkSync(temporary,lease);expect(withLock(dir,()=>2)).toBe(2);expect(fs.existsSync(temporary)).toBe(false);expect(fs.existsSync(lease)).toBe(false);}}); - test('EPERM liveness keeps an active cross-process lease intact',()=>{const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),token='d'.repeat(32),pid=2147483647,createdAt=0,candidate=path.join(leases,`${token}.json`),decision=path.join(leases,`${token}.decision`),ticket='1'.padStart(16,'0'),active=path.join(leases,`${token}.active.${ticket}`);fs.writeFileSync(candidate,JSON.stringify({pid,token,createdAt})+'\n',{mode:0o600,flag:'wx'});const stat=fs.statSync(candidate);fs.writeFileSync(decision,JSON.stringify({schemaVersion:1,token,kind:'ticket',ticket,candidateDev:String(stat.dev),candidateIno:String(stat.ino),ownerPid:pid,ownerCreatedAt:createdAt,publisherPid:pid,createdAt})+'\n',{mode:0o600,flag:'wx'});fs.linkSync(candidate,active);const kill=process.kill.bind(process),probe=spyOn(process,'kill').mockImplementation(((target:any,signal?:any)=>{if(Number(target)===pid){const error:any=new Error('not permitted');error.code='EPERM';throw error;}return signal===undefined?kill(target):kill(target,signal);}) as typeof process.kill);let entered=false,caught:unknown;try{withLock(dir,()=>{entered=true;});}catch(error){caught=error;}finally{probe.mockRestore();}expect(entered).toBe(false);expect(caught).toMatchObject({code:'INSUFFICIENT_CAPACITY'});expect([candidate,decision,active].every(file=>fs.existsSync(file))).toBe(true);expect(fs.statSync(candidate).nlink).toBe(2);expect(fs.statSync(decision).nlink).toBe(1);}); - test('an active lease binds a separate decision to its candidate and active inode',()=>{const dir=tmp();withLock(dir,()=>{const leases=path.join(dir,'.mutation-lock-leases'),names=fs.readdirSync(leases);expect(names.length).toBe(3);const candidate=names.find(name=>name.endsWith('.json'))!,decision=names.find(name=>name.endsWith('.decision'))!,active=names.find(name=>name.includes('.active.'))!,candidateStat=fs.statSync(path.join(leases,candidate)),decisionStat=fs.statSync(path.join(leases,decision)),activeStat=fs.statSync(path.join(leases,active)),record=JSON.parse(fs.readFileSync(path.join(leases,decision),'utf8'));expect(`${candidateStat.dev}:${candidateStat.ino}`).toBe(`${activeStat.dev}:${activeStat.ino}`);expect(candidateStat.nlink).toBe(2);expect(activeStat.nlink).toBe(2);expect(`${decisionStat.dev}:${decisionStat.ino}`).not.toBe(`${candidateStat.dev}:${candidateStat.ino}`);expect(decisionStat.nlink).toBe(1);expect(record.kind).toBe('ticket');expect(record.candidateDev).toBe(String(candidateStat.dev));expect(record.candidateIno).toBe(String(candidateStat.ino));});expect(fs.readdirSync(path.join(dir,'.mutation-lock-leases'))).toEqual([]);}); - test('post-link verification failure cleans every recorded lease phase',()=>{const dir=tmp();expect(withLock(dir,()=>1)).toBe(1);const leases=path.join(dir,'.mutation-lock-leases'),fakeToken='f'.repeat(32),fakeTemp=path.join(leases,`${fakeToken}.json.tmp.${process.pid}.deadbeef`),link=fs.linkSync,injectedOwner=JSON.stringify({pid:process.pid,token:fakeToken,createdAt:Date.now()})+'\n';let injected=false,caught:unknown;const publisher=spyOn(fs,'linkSync').mockImplementation(((source:any,target:any)=>{const result=link(source,target);if(!injected&&String(target).includes('.active.')){injected=true;fs.writeFileSync(fakeTemp,injectedOwner,{mode:0o600,flag:'wx'});}return result;}) as typeof fs.linkSync);try{withLock(dir,()=>1);}catch(error){caught=error;}finally{publisher.mockRestore();}expect(injected).toBe(true);expect(caught).toMatchObject({code:'INSUFFICIENT_CAPACITY'});expect(fs.readdirSync(leases)).toEqual([path.basename(fakeTemp)]);fs.unlinkSync(fakeTemp);expect(withLock(dir,()=>2)).toBe(2);expect(fs.readdirSync(leases)).toEqual([]);}); - test('an async callback retains its lease until settlement without blocking its own event loop',async()=>{const dir=tmp();let release!:()=>void;const pending=new Promise(resolve=>{release=resolve;}),outer=withLock(dir,async()=>{await pending;return 7;}),started=Date.now();expect(()=>withLock(dir,()=>99)).toThrow('Another operation in this helper');expect(Date.now()-started).toBeLessThan(200);release();expect(await outer).toBe(7);expect(withLock(dir,()=>9)).toBe(9);}); - test('a synchronous exact-release failure is attempted only once',()=>{const dir=tmp(),lstat=fs.lstatSync;let observed=0,reader:any;try{expect(()=>withLock(dir,()=>{const leases=path.join(dir,'.mutation-lock-leases'),names=fs.readdirSync(leases),candidate=path.join(leases,names.find(name=>name.endsWith('.json'))!),active=path.join(leases,names.find(name=>name.includes('.active.'))!),value=fs.readFileSync(active);fs.unlinkSync(active);fs.writeFileSync(active,value,{mode:0o600,flag:'wx'});reader=spyOn(fs,'lstatSync').mockImplementation(((file:any,options?:any)=>{if(String(file)===candidate)observed++;return options===undefined?lstat(file):lstat(file,options);}) as typeof fs.lstatSync);})).toThrow('active phase changed before cleanup');expect(observed).toBe(1);}finally{reader?.mockRestore();}}); - test('exact release rejects active or decision inode substitution and overrides callback success or failure',()=>{for(const phase of ['active','decision'] as const){const dir=tmp();let replacement='',parked='';expect(()=>withLock(dir,()=>{const leases=path.join(dir,'.mutation-lock-leases'),name=fs.readdirSync(leases).find(value=>phase==='active'?value.includes('.active.'):value.endsWith('.decision'))!,lease=path.join(leases,name),value=fs.readFileSync(lease);parked=`${lease}.replaced`;fs.renameSync(lease,parked);fs.writeFileSync(lease,value,{mode:0o600,flag:'wx'});replacement=lease;if(phase==='active')throw new Error('callback failed');return 1;})).toThrow(/changed before (cleanup|exact release)/);expect(fs.existsSync(replacement)).toBe(true);expect(fs.existsSync(parked)).toBe(true);expect(fs.statSync(replacement).ino).not.toBe(fs.statSync(parked).ino);fs.rmSync(dir,{recursive:true,force:true});}}); - test('concurrent stale-lock recovery never admits overlapping report writers',async()=>{const dir=tmp(),lock=path.join(dir,'.mutation-lock'),script=path.join(dir,'racer.ts');fs.mkdirSync(lock);fs.writeFileSync(path.join(lock,'owner.json'),JSON.stringify({pid:2147483647,token:'stale',createdAt:0,expiresAt:0}));fs.writeFileSync(script,`import fs from 'node:fs';import path from 'node:path';import {withLock} from ${JSON.stringify(path.resolve(import.meta.dir,'../lib/cso/state.ts'))};const dir=process.env.RACE_DIR!;try{await withLock(dir,async()=>{const active=path.join(dir,'active');try{fs.writeFileSync(active,String(process.pid),{flag:'wx'});}catch{fs.appendFileSync(path.join(dir,'overlap'),'yes\\n');}await Bun.sleep(50);try{if(fs.readFileSync(active,'utf8')===String(process.pid))fs.unlinkSync(active);}catch{}});}catch{}`);const children=Array.from({length:8},()=>spawn(process.execPath,[script],{env:{...process.env,RACE_DIR:dir},stdio:'ignore'}));await Promise.all(children.map(child=>new Promise(resolve=>child.on('close',()=>resolve()))));expect(fs.existsSync(path.join(dir,'overlap'))).toBe(false);}); - test.each(['removed','replaced'] as const)('publication %s during candidate enumeration stays fail-closed',(change)=>{ - const dir=tmp(),target=path.join(dir,'artifact.json'),temporary=`${target}.tmp.2147483647.cafebabe`,replacement=path.join(dir,'replacement.json'); - fs.writeFileSync(target,'{"value":"original"}\n',{mode:0o600});fs.linkSync(target,temporary); - fs.writeFileSync(replacement,'{"value":"replacement"}\n',{mode:0o600}); - const readdir=fs.readdirSync;let changed=false; - const reader=spyOn(fs,'readdirSync').mockImplementation(((directory:any,options?:any)=>{ - const entries=options===undefined?readdir(directory):readdir(directory,options); - if(String(directory)===dir&&!changed){changed=true;fs.unlinkSync(temporary);if(change==='removed')fs.unlinkSync(target);else fs.renameSync(replacement,target);} - return entries; - }) as typeof fs.readdirSync); - try{ - let caught:unknown;try{recoverAtomicNoReplaceJson(target,{label:'Test publication',maxBytes:4096});}catch(error){caught=error;} - expect(changed).toBe(true); - expect(caught).toMatchObject(change==='removed'?{name:'AtomicPublicationTransition',code:'SNAPSHOT_RACE'}:{code:'UNSAFE_PATH'}); - if(change==='removed')expect(fs.existsSync(target)).toBe(false);else expect(fs.readFileSync(target,'utf8')).toBe('{"value":"replacement"}\n'); - }finally{reader.mockRestore();} - }); - test('concurrent recovery of one dead hard-link publication has a winner and no raw race errors',async()=>{ - const dir=tmp(),barrier=path.join(dir,'barrier'),script=path.join(dir,'recovery-racer.ts');fs.mkdirSync(barrier);expect(withLock(dir,()=>1)).toBe(1); - const leases=path.join(dir,'.mutation-lock-leases'),token='c'.repeat(32),lease=path.join(leases,`${token}.json`),temporary=`${lease}.tmp.2147483647.deadbeef`; - fs.writeFileSync(temporary,JSON.stringify({pid:2147483647,token,createdAt:0})+'\n',{mode:0o600,flag:'wx'});fs.linkSync(temporary,lease); - fs.writeFileSync(script,`import fs from 'node:fs';import path from 'node:path';import {withLock} from ${JSON.stringify(path.resolve(import.meta.dir,'../lib/cso/state.ts'))};const dir=process.env.RACE_DIR!,barrier=process.env.BARRIER!,id=process.env.RACE_ID!,wait=new Int32Array(new SharedArrayBuffer(4));fs.writeFileSync(path.join(barrier,'ready-'+id),'ready',{flag:'wx'});while(!fs.existsSync(path.join(barrier,'go')))Atomics.wait(wait,0,0,1);let outcome='success';try{withLock(dir,()=>{const active=path.join(barrier,'work-active');try{fs.writeFileSync(active,id,{flag:'wx'});}catch{fs.appendFileSync(path.join(barrier,'overlap'),'yes\\n');}Atomics.wait(wait,0,0,20);try{if(fs.readFileSync(active,'utf8')===id)fs.unlinkSync(active);}catch{}});}catch(error){outcome=String(error?.code??error)+':'+String(error?.message??'');}fs.writeFileSync(path.join(barrier,'result-'+id),outcome);`); - const children=Array.from({length:8},(_,index)=>spawn(process.execPath,[script],{env:{...process.env,RACE_DIR:dir,BARRIER:barrier,RACE_ID:String(index)},stdio:'ignore'})),done=children.map(child=>childExit(child)); - try{ - for(let index=0;indexfs.readFileSync(path.join(barrier,`result-${index}`),'utf8')); - expect(outcomes).toContain('success');expect(outcomes.filter(value=>value!=='success'&&!value.startsWith('INSUFFICIENT_CAPACITY:'))).toEqual([]); - expect(fs.existsSync(path.join(barrier,'overlap'))).toBe(false);expect(fs.readdirSync(leases)).toEqual([]); - }finally{stopChildren(children);} - }); - test('two synchronized cooperating publishers admit work without overlap or an all-loser outcome',async()=>{ - const dir=tmp(),barrier=path.join(dir,'barrier'),script=path.join(dir,'contender.ts');fs.mkdirSync(barrier);expect(withLock(dir,()=>1)).toBe(1); - fs.writeFileSync(script,`import fs from 'node:fs';import path from 'node:path';import {withLock} from ${JSON.stringify(path.resolve(import.meta.dir,'../lib/cso/state.ts'))}; -const dir=process.env.RACE_DIR!,barrier=process.env.BARRIER!,id=process.env.RACE_ID!,leases=path.join(dir,'.mutation-lock-leases'),read=fs.readdirSync;let reads=0; -fs.readdirSync=((candidate,...args)=>{if(String(candidate)===leases&&++reads===2){fs.writeFileSync(path.join(barrier,'ready-'+id),'ready',{flag:'wx'});const deadline=Date.now()+5000;while(fs.readdirSync(barrier).filter(name=>name.startsWith('ready-')).length<2){if(Date.now()>deadline)throw new Error('barrier timeout');Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,1);}}return read.call(fs,candidate,...args);}); -let outcome='success';try{withLock(dir,()=>{const active=path.join(barrier,'active');try{fs.writeFileSync(active,id,{flag:'wx'});}catch{fs.writeFileSync(path.join(barrier,'overlap'),'overlap');}Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,25);try{if(fs.readFileSync(active,'utf8')===id)fs.unlinkSync(active);}catch{}});}catch(error){outcome=String(error?.code??error);}fs.writeFileSync(path.join(barrier,'result-'+id),outcome);`); - const children=['a','b'].map(id=>spawn(process.execPath,[script],{env:{...process.env,RACE_DIR:dir,BARRIER:barrier,RACE_ID:id},stdio:'ignore'})); - await Promise.all(children.map(child=>new Promise((resolve,reject)=>child.on('error',reject).on('close',code=>code===0?resolve():reject(new Error(`contender exited ${code}`)))))); - const outcomes=['a','b'].map(id=>fs.readFileSync(path.join(barrier,`result-${id}`),'utf8')); - expect(outcomes.filter(value=>value==='success').length).toBeGreaterThan(0);expect(outcomes.every(value=>value==='success'||value==='INSUFFICIENT_CAPACITY')).toBe(true);expect(fs.existsSync(path.join(barrier,'overlap'))).toBe(false); - }); - test('equal ticket decisions use token order and a late withdrawal cannot revoke the active winner',async()=>{ - if(process.platform==='win32')return; - const dir=tmp(),barrier=path.join(dir,'barrier'),script=path.join(dir,'contender.ts'),lowToken='1'.repeat(32),highToken='e'.repeat(32);fs.mkdirSync(barrier);expect(withLock(dir,()=>1)).toBe(1);fs.writeFileSync(script,leaseContenderSource()); - const env={...process.env,RACE_DIR:dir,BARRIER:barrier},children:Array>=[]; - try{ - const low=spawn(process.execPath,[script],{env:{...env,RACE_ID:'L',RACE_MODE:'pause-before-decision',RACE_TOKEN:lowToken,RACE_HOLD:'1'},stdio:'ignore'});children.push(low);const lowDone=childExit(low);await waitForPath(path.join(barrier,'paused-L'));expect(fs.readFileSync(path.join(barrier,'choice-L'),'utf8')).toBe('0000000000000001'); - const high=spawn(process.execPath,[script],{env:{...env,RACE_ID:'H',RACE_MODE:'pause-before-withdraw',RACE_TOKEN:highToken},stdio:'ignore'});children.push(high);const highDone=childExit(high);await waitForPath(path.join(barrier,'paused-H'),2500);expect(fs.readFileSync(path.join(barrier,'choice-H'),'utf8')).toBe('0000000000000001'); - await resumeStopped(low);await waitForPath(path.join(barrier,'entered-L'));const decision=JSON.parse(fs.readFileSync(path.join(dir,'.mutation-lock-leases',lowToken+'.decision'),'utf8'));expect(decision.kind).toBe('ticket');expect(decision.ticket).toBe('0000000000000001'); - await resumeStopped(high);await waitForPath(path.join(barrier,'result-H'));expect(fs.readFileSync(path.join(barrier,'result-H'),'utf8')).toBe('INSUFFICIENT_CAPACITY');expect(await highDone).toBe(0); - fs.writeFileSync(path.join(barrier,'release-L'),'release');await waitForPath(path.join(barrier,'result-L'));expect(fs.readFileSync(path.join(barrier,'result-L'),'utf8')).toBe('success');expect(await lowDone).toBe(0);expect(fs.existsSync(path.join(barrier,'overlap'))).toBe(false);expect(fs.readdirSync(path.join(dir,'.mutation-lock-leases'))).toEqual([]); - }finally{stopChildren(children);} - }); - test('a paused candidate is fenced so a progressing ticket wins within the bound',async()=>{if(process.platform==='win32')return;const dir=tmp(),barrier=path.join(dir,'barrier'),script=path.join(dir,'contender.ts');fs.mkdirSync(barrier);expect(withLock(dir,()=>1)).toBe(1);fs.writeFileSync(script,leaseContenderSource());const env={...process.env,RACE_DIR:dir,BARRIER:barrier},children:Array>=[];try{const earlier=spawn(process.execPath,[script],{env:{...env,RACE_ID:'L',RACE_MODE:'pause-candidate'},stdio:'ignore'});children.push(earlier);const earlierDone=childExit(earlier);await waitForPath(path.join(barrier,'paused-L'));const started=Date.now(),later=spawn(process.execPath,[script],{env:{...env,RACE_ID:'H',RACE_MODE:'normal'},stdio:'ignore'});children.push(later);const laterDone=childExit(later);await waitForPath(path.join(barrier,'result-H'),2500);expect(Date.now()-started).toBeLessThan(2000);expect(fs.readFileSync(path.join(barrier,'result-H'),'utf8')).toBe('success');expect(await laterDone).toBe(0);await resumeStopped(earlier);await waitForPath(path.join(barrier,'result-L'));expect(fs.readFileSync(path.join(barrier,'result-L'),'utf8')).toBe('INSUFFICIENT_CAPACITY');expect(await earlierDone).toBe(0);expect(fs.existsSync(path.join(barrier,'overlap'))).toBe(false);expect(fs.readdirSync(path.join(dir,'.mutation-lock-leases'))).toEqual([]);}finally{stopChildren(children);}}); - test('a paused earlier ticket bounds later contenders without withdrawing the winner',async()=>{if(process.platform==='win32')return;const dir=tmp(),barrier=path.join(dir,'barrier'),script=path.join(dir,'contender.ts');fs.mkdirSync(barrier);expect(withLock(dir,()=>1)).toBe(1);fs.writeFileSync(script,leaseContenderSource());const env={...process.env,RACE_DIR:dir,BARRIER:barrier},children:Array>=[];try{const earlier=spawn(process.execPath,[script],{env:{...env,RACE_ID:'L',RACE_MODE:'pause-ticket'},stdio:'ignore'});children.push(earlier);const earlierDone=childExit(earlier);await waitForPath(path.join(barrier,'paused-L'));const started=Date.now(),later=spawn(process.execPath,[script],{env:{...env,RACE_ID:'H',RACE_MODE:'normal'},stdio:'ignore'});children.push(later);const laterDone=childExit(later);await waitForPath(path.join(barrier,'result-H'),2500);expect(Date.now()-started).toBeLessThan(2000);expect(fs.readFileSync(path.join(barrier,'result-H'),'utf8')).toBe('INSUFFICIENT_CAPACITY');expect(await laterDone).toBe(0);await resumeStopped(earlier);await waitForPath(path.join(barrier,'result-L'));expect(fs.readFileSync(path.join(barrier,'result-L'),'utf8')).toBe('success');expect(await earlierDone).toBe(0);expect(fs.existsSync(path.join(barrier,'overlap'))).toBe(false);expect(fs.readdirSync(path.join(dir,'.mutation-lock-leases'))).toEqual([]);}finally{stopChildren(children);}}); - test('a paused loser cleanup leaves only an ineligible decision and cannot block the winner',async()=>{if(process.platform==='win32')return;const dir=tmp(),barrier=path.join(dir,'barrier'),script=path.join(dir,'contender.ts');fs.mkdirSync(barrier);expect(withLock(dir,()=>1)).toBe(1);fs.writeFileSync(script,leaseContenderSource());const env={...process.env,RACE_DIR:dir,BARRIER:barrier},children:Array>=[];try{const winner=spawn(process.execPath,[script],{env:{...env,RACE_ID:'L',RACE_MODE:'pause-ticket'},stdio:'ignore'});children.push(winner);const winnerDone=childExit(winner);await waitForPath(path.join(barrier,'paused-L'));const loser=spawn(process.execPath,[script],{env:{...env,RACE_ID:'H',RACE_MODE:'pause-withdraw-cleanup'},stdio:'ignore'});children.push(loser);const loserDone=childExit(loser);await waitForPath(path.join(barrier,'paused-H'));const phases=fs.readdirSync(path.join(dir,'.mutation-lock-leases'));expect(phases.filter(name=>name.endsWith('.decision')).length).toBe(2);expect(phases.filter(name=>name.endsWith('.json')).length).toBe(1);await resumeStopped(winner);await waitForPath(path.join(barrier,'result-L'));expect(fs.readFileSync(path.join(barrier,'result-L'),'utf8')).toBe('success');expect(await winnerDone).toBe(0);await resumeStopped(loser);await waitForPath(path.join(barrier,'result-H'));expect(fs.readFileSync(path.join(barrier,'result-H'),'utf8')).toBe('INSUFFICIENT_CAPACITY');expect(await loserDone).toBe(0);expect(fs.existsSync(path.join(barrier,'overlap'))).toBe(false);expect(fs.readdirSync(path.join(dir,'.mutation-lock-leases'))).toEqual([]);}finally{stopChildren(children);}}); - test('a paused later contender cannot turn a cached lower ticket into an all-loser outcome',async()=>{if(process.platform==='win32')return;const dir=tmp(),barrier=path.join(dir,'barrier'),script=path.join(dir,'contender.ts');fs.mkdirSync(barrier);expect(withLock(dir,()=>1)).toBe(1);fs.writeFileSync(script,leaseContenderSource());const env={...process.env,RACE_DIR:dir,BARRIER:barrier},children:Array>=[];try{const earlier=spawn(process.execPath,[script],{env:{...env,RACE_ID:'L',RACE_MODE:'wait-active',RACE_HOLD:'1'},stdio:'ignore'});children.push(earlier);const earlierDone=childExit(earlier);await waitForPath(path.join(barrier,'doorway-L'));const later=spawn(process.execPath,[script],{env:{...env,RACE_ID:'H',RACE_MODE:'pause-later-scan'},stdio:'ignore'});children.push(later);const laterDone=childExit(later);await waitForPath(path.join(barrier,'paused-H'));await waitForPath(path.join(barrier,'entered-L'));await resumeStopped(later);await waitForPath(path.join(barrier,'result-H'),2500);expect(fs.readFileSync(path.join(barrier,'result-H'),'utf8')).toBe('INSUFFICIENT_CAPACITY');expect(await laterDone).toBe(0);fs.writeFileSync(path.join(barrier,'release-L'),'release');await waitForPath(path.join(barrier,'result-L'));expect(fs.readFileSync(path.join(barrier,'result-L'),'utf8')).toBe('success');expect(await earlierDone).toBe(0);expect(fs.existsSync(path.join(barrier,'overlap'))).toBe(false);expect(fs.readdirSync(path.join(dir,'.mutation-lock-leases'))).toEqual([]);}finally{stopChildren(children);}}); - test('legacy report imports expire after thirty days without following links',()=>{const old=process.env.GSTACK_HOME,base=tmp();process.env.GSTACK_HOME=base;try{const archive=secureDirectory(path.join(base,'security','cso','legacy-imports')),expired=path.join(archive,'a'.repeat(64)+'.json'),retained=path.join(archive,'b'.repeat(64)+'.json');fs.writeFileSync(expired,'{}');fs.writeFileSync(retained,'{}');const now=Date.now();fs.utimesSync(expired,new Date(now-31*86400_000),new Date(now-31*86400_000));retention(now);expect(fs.existsSync(expired)).toBe(false);expect(fs.existsSync(retained)).toBe(true);const unsafe=path.join(archive,'c'.repeat(64)+'.json');fs.symlinkSync(retained,unsafe);expect(()=>retention(now)).toThrow('unsafe artifact');expect(fs.readFileSync(retained,'utf8')).toBe('{}');}finally{if(old===undefined)delete process.env.GSTACK_HOME;else process.env.GSTACK_HOME=old;}}); - test('an active recheck pins only its expired parent report, never expired repair material',()=>{const now=Date.now(),repo='f'.repeat(24),oldRun=`${now-31*86400_000}-${'a'.repeat(16)}`,childRun=`${now}-${'b'.repeat(16)}`,findingId='c'.repeat(32),repoDir=secureDirectory(path.join(privateRoot(),repo)),parent=secureDirectory(path.join(repoDir,oldRun)),child=secureDirectory(path.join(repoDir,childRun)),bundles=secureDirectory(path.join(parent,'bundles')),reviews=secureDirectory(path.join(parent,'reviews')),attempts=secureDirectory(path.join(parent,'verification-attempts'));writeHelperJson(path.join(parent,'report.json'),{schemaVersion:3,runId:oldRun,repoId:repo,status:'finished',coverage:[],findings:[{id:findingId}]});writeJson(path.join(bundles,'bundle.json'),{schemaVersion:3});writeJson(path.join(reviews,'review.json'),{schemaVersion:3});writeJson(path.join(attempts,'attempt.json'),{schemaVersion:3});writeHelperJson(path.join(child,'report.json'),{schemaVersion:3,runId:childRun,repoId:repo,status:'running',deadline:new Date(now+60_000).toISOString(),coverage:[],findings:[],parent:{runId:oldRun,findingId,kind:'recheck'}});retention(now);expect(fs.existsSync(path.join(parent,'report.json'))).toBe(true);expect(fs.existsSync(bundles)).toBe(false);expect(fs.existsSync(reviews)).toBe(false);expect(fs.existsSync(attempts)).toBe(false);fs.rmSync(child,{recursive:true});retention(now);expect(fs.existsSync(parent)).toBe(false);}); - test('finished, expired, and malformed child reports cannot extend parent retention',()=>{const now=Date.now(),repo='e'.repeat(24),repoDir=secureDirectory(path.join(privateRoot(),repo)),findingId='d'.repeat(32);for(const [index,childValue] of [[0,{status:'finished',repoId:repo,deadline:new Date(now+60_000).toISOString()}],[1,{status:'running',repoId:repo,deadline:new Date(now-1).toISOString()}],[2,{status:'running',repoId:'0'.repeat(24),deadline:new Date(now+60_000).toISOString()}]] as const){const parentRun=`${now-(31+index)*86400_000}-${String(index+1).repeat(16)}`,childRun=`${now-index}-${String(index+4).repeat(16)}`,parent=secureDirectory(path.join(repoDir,parentRun)),child=secureDirectory(path.join(repoDir,childRun));writeHelperJson(path.join(parent,'report.json'),{schemaVersion:3,runId:parentRun,repoId:repo,status:'finished',coverage:[],findings:[{id:findingId}]});writeHelperJson(path.join(child,'report.json'),{schemaVersion:3,runId:childRun,repoId:childValue.repoId,status:childValue.status,deadline:childValue.deadline,coverage:[],findings:[],parent:{runId:parentRun,findingId,kind:'recheck'}});}retention(now);for(const name of fs.readdirSync(repoDir).filter(name=>Number(name.split('-')[0]) { - const maskedRoot = ''; - const reportFor = (sourceRoot: string): any => ({ - schemaVersion: 3, runId: '1789450000000-aaaaaaaaaaaaaaaa', repoId: 'b'.repeat(24), - createdAt: '2026-09-15T06:00:00.000Z', deadline: '2026-09-15T06:10:00.000Z', - status: 'finished', completeness: 'partial', - policy: { mode: 'daily', scope: 'default', diff: true, base: 'main', offline: true, budgetSeconds: 600, maxWorkers: 3, maxRepairs: 3 }, - source: { root: sourceRoot, snapshotHash: 'c'.repeat(64), originalHash: 'd'.repeat(64), baseCommit: 'e'.repeat(40), transformations: [{ path: 'src/root.ts', handling: 'public source' }] }, - application: { actors: ['root administrator'], assets: ['/source/project'], entrypoints: ['read'], tenantBoundaries: ['tenant'], sensitiveOperations: ['read'], invariants: ['Root access remains restricted.'] }, - coverage: [{ domain: 'authorization', scope: 'default', status: 'partial', method: 'manual static review', gaps: ['Remaining source review'], exclusions: [], evidence: ['Source read'] }], - findings: [], gaps: [], events: [], - }); - - test.each([ - ['POSIX temporary', '/tmp/cso-private-project/repo'], - ['POSIX custom', '/srv/company-project/repo'], - ['Linux home', '/home/alice/company-project'], - ['macOS home', '/Users/alice/company-project'], - ['Windows custom', String.raw`D:\teams\company-project`], - ['Windows home', String.raw`C:\Users\Alice\company-project`], - ])('masks %s source roots without changing private identity', (_label, sourceRoot) => { - const dir = tmp(), report = reportFor(sourceRoot), original = structuredClone(report); - saveReport(dir, report); - const file = path.join(dir, 'report.json'), raw = fs.readFileSync(file, 'utf8'); - expect(raw).not.toContain(sourceRoot); - const saved = JSON.parse(raw); - expect(saved.source.root).toBe(maskedRoot); - expect(saved).toEqual({ ...original, source: { ...original.source, root: maskedRoot } }); - expect(report).toEqual(original); - expect(fs.readFileSync(path.join(dir, 'report.md'), 'utf8')).not.toContain(sourceRoot); - // Retained reports from before this fix are projected on read, without - // mutating their private file or any identity hashes. - const legacy = JSON.stringify(original, null, 2) + '\n'; - fs.writeFileSync(file, legacy, { mode: 0o600 }); - expect(loadReport(dir)).toEqual(saved); - expect(fs.readFileSync(file, 'utf8')).toBe(legacy); - expect(sanitizeHelperForJson({ root: 'administrator', label: 'root access', path: '/source/project' })) - .toEqual({ root: 'administrator', label: 'root access', path: '/source/project' }); - }); -}); diff --git a/test/cso-spec-taxonomy-alignment.test.ts b/test/cso-spec-taxonomy-alignment.test.ts deleted file mode 100644 index b3da8b70e..000000000 --- a/test/cso-spec-taxonomy-alignment.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -/** CSO uses versioned domain mappings and the shared fail-closed secret taxonomy. */ -import { describe, test, expect } from 'bun:test'; -import * as fs from 'fs'; -import * as path from 'path'; - -const ROOT = path.resolve(import.meta.dir, '..'); -const CSO = fs.readFileSync(path.join(ROOT, 'cso/SKILL.md'), 'utf8') + '\n' - + fs.readFileSync(path.join(ROOT, 'cso/sections/audit-phases.md'), 'utf8'); - -describe('CSO domain source and redaction contracts', () => { - test('credential recognition uses the shared taxonomy without raw history commands', () => { - for (const prefix of ['AKIA', 'ghp_', 'sk-ant-', 'BEGIN']) expect(CSO).toContain(prefix); - expect(CSO).toContain('lib/redact-patterns.ts'); - expect(CSO).toContain('Secrets Archaeology'); - expect(CSO).toContain('Never print raw `git log -p --all`'); - expect(CSO).toContain('Do not call live provider APIs'); - }); - - test('OWASP 2025 mapping does not retain obsolete 2021 category numbers', () => { - const rows = CSO.split('\n').filter(line => /^\| A\d\d \|/.test(line)); - expect(rows).toHaveLength(10); - const categories = new Map(rows.map(line => { - const [, id, name] = line.split('|').map(part => part.trim()); - return [id, name]; - })); - expect(categories.get('A02')).toBe('Security Misconfiguration'); - expect(categories.get('A03')).toBe('Software Supply Chain Failures'); - expect(categories.get('A10')).toBe('Mishandling of Exceptional Conditions'); - expect(rows.find(line => line.startsWith('| A01 |'))).toContain('SSRF'); - }); - - test('domain standards carry inspected versions and no inferred compliance', () => { - for (const version of ['OWASP Top 10:2025', 'OWASP API Security Top 10:2023', 'ASVS version: 5.0.0', 'v5.0.0-1.2.5', 'LLM Top 10 2026', 'Agentic Applications Top 10 2026', 'MCP security guidance version: 2026-07-28']) expect(CSO).toContain(version); - expect(CSO).toContain('artifact 56857'); - expect(CSO).toContain('unset publication-date field'); - expect(CSO).toContain('artifact 52117'); - expect(CSO).toContain('Do not invent IDs'); - }); - - test('all declared scanners retain execution and evidence boundaries', () => { - for (const scanner of ['Gitleaks', 'OSV-Scanner', 'Semgrep', 'zizmor', 'Trivy', 'Schemathesis']) expect(CSO).toContain(scanner); - expect(CSO).toContain('Import existing SARIF'); - expect(CSO).toContain('public wheels'); - expect(CSO).toContain('Gemfile.lock` parsed as inert data'); - expect(CSO).toContain('Python `--no-build` alone'); - expect(CSO).toContain('every database connection'); - }); -}); diff --git a/test/cso-stack-cold-integration.test.ts b/test/cso-stack-cold-integration.test.ts deleted file mode 100644 index 89db2822d..000000000 --- a/test/cso-stack-cold-integration.test.ts +++ /dev/null @@ -1,202 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { PublicArchiveCache } from '../lib/cso/cache'; -import type { VerificationRequest } from '../lib/cso/contracts'; -import { dockerEndpoint, type DockerEndpoint } from '../lib/cso/docker'; -import { DockerPreparationSandboxRunner } from '../lib/cso/preparation-docker'; -import { - admitPreparationRuntime, admitPreparationSidecar, PreparationExecutor, - type PreparedApplication, type PreparationRuntimeAdmission, type RailsDatabaseSelection, -} from '../lib/cso/preparation-executor'; -import { inspectPreparation, type CsoStack, type PreparationPlan } from '../lib/cso/preparation'; -import { CSO_HELPER_ABI, validateRuntimeCatalog, type QualifiedRuntime, type RuntimeCatalog } from '../lib/cso/runtime-catalog'; -import { completeRuntimeCatalogFixture, installStagedRuntime } from './helpers/cso-runtime-catalog'; -import { secureDirectory } from '../lib/cso/state'; -import { canonicalStartPlan, canonicalTestPlan, DockerVerificationExecutor } from '../lib/cso/verification'; - -const requestedStack = process.env.GSTACK_CSO_TEST_STACK; -const requested = process.env.GSTACK_CSO_DOCKER_TESTS === '1' && ['bun', 'python', 'rails'].includes(requestedStack ?? ''); -const suite = requested ? describe : describe.skip; -const platform = process.arch === 'arm64' ? 'linux/arm64' : 'linux/amd64'; -let root = '', watchdog = '', endpoint: DockerEndpoint, runtime: QualifiedRuntime, catalog: RuntimeCatalog; - -function qualification(kind: 'application' | 'postgresql') { - const common = { sourceCommit: 'b'.repeat(40), workflow: 'https://github.com/garrytan/gstack/actions/runs/1', - sbomDigest: `sha256:${'b'.repeat(64)}`, provenanceDigest: `sha256:${'c'.repeat(64)}`, verifiedProvenance: true as const }; - return kind === 'application' - ? { ...common, kind, containmentPassed: true as const, coldStartPassed: true as const, positiveNegativeAssertionsPassed: true as const, heldOutRepairPassed: true as const } - : { ...common, kind, containmentPassed: true as const, coldStartPassed: true as const, multiDatabasePassed: true as const, readinessPassed: true as const }; -} -function qualified(stack: CsoStack | 'postgresql', image: string, versions: Record): QualifiedRuntime { - return { id: `${stack}-staged-cold-${process.arch}`, stack, platform, state: 'qualified', image, - entrypoint: '/opt/cso/entrypoint', helperAbi: CSO_HELPER_ABI, versions, policyVersion: 'cso-isolation-v1', - qualifiedAt: '2026-09-09T00:00:00.000Z', qualification: qualification(stack === 'postgresql' ? 'postgresql' : 'application') }; -} -function writeFiles(directory: string, files: Record): void { - for (const [relative, body] of Object.entries(files)) { - const file = path.join(directory, relative); fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); - fs.writeFileSync(file, body, { mode: 0o600 }); - } -} -function bunSource(directory: string): void { - writeFiles(directory, { - 'package.json': JSON.stringify({ name: 'cso-bun-cold', version: '1.0.0', private: true, - scripts: { start: 'bun app.js', test: 'bun test' }, dependencies: { 'escape-html': '1.0.3' } }) + '\n', - 'bun.lock': `{ - "lockfileVersion": 1, - "configVersion": 1, - "workspaces": { "": { "name": "cso-bun-cold", "dependencies": { "escape-html": "1.0.3" } } }, - "packages": { "escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="] } -}\n`, - 'app.js': `import escape from "escape-html"; -const port=Number(process.env.PORT);Bun.serve({hostname:"127.0.0.1",port,fetch(request){const route=new URL(request.url).pathname;if(route==="/control")return new Response("CONTROL_OK:"+escape(""));if(route==="/security")return new Response("DENIED",{status:403});return new Response("missing",{status:404})}}); -`, - 'app.test.js': `import {expect,test} from "bun:test";import escape from "escape-html";test("cold dependency is executable",()=>expect(escape("")).toBe("<dependency>"));\n`, - }); -} -function pythonSource(directory: string): void { - writeFiles(directory, { - 'requirements.txt': `Django==4.2.30 --hash=sha256:4d07aaf1c62f9984842b67c2874ebbf7056a17be253860299b93ae1881faad65 -asgiref==3.11.1 --hash=sha256:e8667a091e69529631969fd45dc268fa79b99c92c5fcdda727757e52146ec133 -sqlparse==0.5.5 --hash=sha256:12a08b3bf3eec877c519589833aed092e2444e68240a3577e8e26148acc7b1ba -typing_extensions==4.16.0 --hash=sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8 -`, - 'manage.py': `#!/usr/bin/env python3 -import os,sys -os.environ.setdefault("DJANGO_SETTINGS_MODULE","settings") -from django.core.management import execute_from_command_line -execute_from_command_line(sys.argv) -`, - 'settings.py': `SECRET_KEY="cso-cold-fixture"\nDEBUG=False\nALLOWED_HOSTS=["127.0.0.1"]\nROOT_URLCONF="urls"\nINSTALLED_APPS=[]\nMIDDLEWARE=[]\n`, - 'urls.py': `from django.http import HttpResponse -from django.urls import path -def control(_request): return HttpResponse("CONTROL_OK:Django") -def security(_request): return HttpResponse("DENIED",status=403) -urlpatterns=[path("control",control),path("security",security)] -`, - 'test_app.py': `import os,unittest -os.environ.setdefault("DJANGO_SETTINGS_MODULE","settings") -import django -django.setup() -from django.test import Client -class ColdStartTest(unittest.TestCase): - def test_dependency_and_control(self): - response = Client().get("/control") - self.assertEqual(response.status_code, 200) - self.assertIn(b"CONTROL_OK", response.content) -`, - }); -} -function railsSource(directory: string, bundlerVersion: string): void { - let lock = fs.readFileSync(path.join(import.meta.dir, 'fixtures/cso-eval/rails.Gemfile.lock'), 'utf8'); - lock = lock.replace(' pp (0.6.4)\n', ' pg (1.6.2)\n pp (0.6.4)\n') - .replace(' puma (= 7.2.0)\n', ' pg (= 1.6.2)\n puma (= 7.2.0)\n') - .replace(/(BUNDLED WITH\n)\s+[^\n]+/, `$1 ${bundlerVersion}`); - writeFiles(directory, { - 'Gemfile': `source "https://rubygems.org"\ngem "rails", "= 8.1.2"\ngem "puma", "= 7.2.0"\ngem "sqlite3", "= 2.9.0"\ngem "pg", "= 1.6.2"\n`, - 'Gemfile.lock': lock, - 'config/boot.rb': `ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)\nrequire "bundler/setup"\n`, - 'config/application.rb': `require_relative "boot"\nrequire "rails"\nrequire "active_record/railtie"\nrequire "action_controller/railtie"\nmodule CsoCold;class Application < Rails::Application;config.load_defaults 8.1;config.eager_load=false;config.hosts.clear;end;end\n`, - 'config/environment.rb': `require_relative "application"\nRails.application.initialize!\n`, - 'config/routes.rb': `Rails.application.routes.draw do\n get "/control",to:"probe#control"\n get "/security",to:"probe#security"\nend\n`, - 'config/environments/test.rb': `Rails.application.configure do\n config.eager_load=false\n config.consider_all_requests_local=true\nend\n`, - 'config/database.yml': `default: &default\n pool: 3\ntest:\n primary:\n <<: *default\n adapter: sqlite3\n database: storage/test.sqlite3\n queue:\n <<: *default\n adapter: postgresql\n database: cso_queue\n`, - 'app/controllers/application_controller.rb': `class ApplicationController < ActionController::Base;end\n`, - 'app/controllers/probe_controller.rb': `class ProbeController < ApplicationController\n def control;render plain:"CONTROL_OK:Rails";end\n def security;render plain:"DENIED",status: :forbidden;end\nend\n`, - 'bin/rails': `#!/usr/bin/env ruby\nAPP_PATH = File.expand_path("../config/application", __dir__)\nrequire_relative "../config/boot"\nrequire "rails/commands"\n`, - 'Rakefile': `require_relative "config/application"\nRails.application.load_tasks\n`, - 'config.ru': `require_relative "config/environment"\nrun Rails.application\n`, - 'db/schema.rb': `ActiveRecord::Schema[8.1].define(version: 1) do\n create_table :cold_records, force: true do |t|\n t.string :name\n end\nend\n`, - 'test/test_helper.rb': `ENV["RAILS_ENV"] ||= "test"\nrequire_relative "../config/environment"\nrequire "rails/test_help"\n`, - 'test/cold_start_test.rb': `require "test_helper"\nclass ColdStartTest < ActionDispatch::IntegrationTest\n test "control boots" do\n get "/control"\n assert_response :success\n assert_includes response.body,"CONTROL_OK"\n end\nend\n`, - }); -} -function readyPlan(source: string, stack: CsoStack): PreparationPlan { - const plan = inspectPreparation(source, stack); - if (plan.status !== 'ready') throw new Error(`${stack} cold fixture is not ready: ${plan.prerequisites.map(item => `${item.code}: ${item.message}`).join('; ')}`); - return plan; -} -function preparation(runDir: string, admission: PreparationRuntimeAdmission): PreparationExecutor { - const staging = secureDirectory(path.join(runDir, 'archive-staging')); - const cache = new PublicArchiveCache({ root: path.join(runDir, 'public-cache'), stagingRoot: staging, maxBytes: 512 * 1024 * 1024 }); - const runner = new DockerPreparationSandboxRunner({ endpoint, watchdogPath: watchdog, runRoot: runDir, - controlRoot: secureDirectory(path.join(runDir, 'preparation-execution')), admission }); - return new PreparationExecutor({ cache, runner, materializationRoot: secureDirectory(path.join(runDir, 'archive-materializations')) }); -} -function requestFor(source: string, stack: CsoStack, port: number): VerificationRequest { - const start = canonicalStartPlan(source, stack, port), tests = canonicalTestPlan(source, stack); - return { findingId: 'd'.repeat(32), runtimeProfile: runtime.id, port, start: start.command, - legitimate: [{ name: 'cold-start control', path: '/control', method: 'GET', expected: { status: 200, includes: 'CONTROL_OK' } }], - security: { name: 'fixture denial', path: '/security', method: 'GET', expected: { status: 403, includes: 'DENIED' }, vulnerable: { status: 200, includes: 'SECRET' } }, - existingTests: tests.commands, fixtures: {}, boundaryFiles: start.entrypointFiles, testFiles: tests.files, changes: [], - review: { reviewer: 'cold-start-gate', independent: true, rootCauseRepaired: true, featurePreserved: true, - boundaryMocks: false, rationale: 'Cold-start execution only.', reviewedPatchHash: 'e'.repeat(64) } }; -} -async function executeCold(stack: CsoStack, source: string, runDir: string, port: number, database?: RailsDatabaseSelection): Promise { - const plan = readyPlan(source, stack), admission = admitPreparationRuntime({ plan, platform, profile: runtime.id, catalog }); - const prep = preparation(runDir, admission), deadline = Date.now() + 15 * 60_000; - const closure = await prep.acquire({ plan, admission, snapshot: source, deadline }); - expect(closure.archives.length).toBeGreaterThan(0); - expect(closure.archives.every(item => item.requestedUrl.startsWith('https://'))).toBe(true); - if (stack === 'bun') expect(closure.archives.every(item => item.resolvedUrl?.startsWith('https://'))).toBe(true); - else expect(closure.archives.every(item => item.resolvedUrl === null)).toBe(true); - const prepared = await prep.prepareOffline({ plan, admission, snapshot: source, closure, deadline, database }); - try { - const observation = await new DockerVerificationExecutor(endpoint, watchdog, deadline).observe( - prepared.preparedRoot, 'after', requestFor(prepared.preparedRoot, stack, port), runtime, runtime, - secureDirectory(path.join(runDir, 'observations')), secureDirectory(path.join(runDir, 'verification-controls')), - { environment: prepared.executionEnvironment, database: prepared.database }, - ); - expect(observation).toMatchObject({ booted: true, legitimate: true, security: 'pass', existingTests: true }); - return prepared; - } finally { await prep.dispose(prepared); } -} - -beforeAll(async () => { - if (!requested) return; - const image = process.env.GSTACK_CSO_TEST_IMAGE; - if (!image) throw new Error(`${requestedStack} cold-start qualification requires GSTACK_CSO_TEST_IMAGE; a requested gate cannot skip`); - if (process.env.GSTACK_CSO_TEST_PLATFORM !== platform) throw new Error(`${requestedStack} cold-start qualification requires native ${platform}`); - const versions = JSON.parse(process.env.GSTACK_CSO_EXPECTED_VERSIONS || '{}') as Record; - for (const key of ({ bun: ['bun','cso-preparation'], python: ['python','uv','cso-preparation'], rails: ['ruby','bundler','cso-preparation'] } as const)[requestedStack as 'bun'|'python'|'rails']) - if (!/^\d+\.\d+\.\d+$/.test(versions[key] ?? '')) throw new Error(`${requestedStack} cold-start qualification requires exact ${key} metadata`); - root = fs.mkdtempSync(path.join(os.tmpdir(), `cso-${requestedStack}-cold-`)); process.env.GSTACK_HOME = path.join(root, 'state'); - watchdog = path.resolve(import.meta.dir, '../bin/gstack-cso-watchdog'); - if (!fs.existsSync(watchdog)) throw new Error(`${requestedStack} cold-start qualification requires the compiled CSO watchdog`); - endpoint = await dockerEndpoint(secureDirectory(path.join(root, 'docker-home')), { HOME: root, DOCKER_HOST: process.env.DOCKER_HOST ?? 'unix:///var/run/docker.sock' }); - catalog = completeRuntimeCatalogFixture(`${requestedStack}-staged-cold`); - runtime = installStagedRuntime(catalog, qualified(requestedStack as CsoStack, image, versions)); - if (requestedStack === 'rails') { - const postgresImage = process.env.GSTACK_CSO_TEST_POSTGRES_IMAGE; - const postgresVersion = process.env.GSTACK_CSO_TEST_POSTGRES_VERSION; - if (!postgresImage || !/^\d+\.\d+(?:\.\d+)?$/.test(postgresVersion ?? '')) throw new Error('Rails cold-start qualification requires a staged PostgreSQL digest and exact version'); - installStagedRuntime(catalog, qualified('postgresql', postgresImage, { postgresql: postgresVersion! })); - } - validateRuntimeCatalog(catalog); -}); -afterAll(() => { if (root) fs.rmSync(root, { recursive: true, force: true }); delete process.env.GSTACK_HOME; }); - -suite('CSO staged Bun, Python, and Rails cold-start journeys', () => { - test('acquires, prepares, boots, controls, and tests the requested staged stack with no target egress', async () => { - const source = secureDirectory(path.join(root, 'source')); - if (requestedStack === 'bun') bunSource(source); - else if (requestedStack === 'python') pythonSource(source); - else railsSource(source, runtime.versions.bundler); - if (requestedStack !== 'rails') { - const prepared = await executeCold(requestedStack as CsoStack, source, secureDirectory(path.join(root, 'run')), requestedStack === 'bun' ? 34610 : 34611); - expect(prepared.database).toBeUndefined(); - return; - } - const plan = readyPlan(source, 'rails'); - expect(plan.database).toMatchObject({ supported: ['sqlite', 'postgresql'], connections: ['primary', 'queue'] }); - const appAdmission = admitPreparationRuntime({ plan, platform, profile: runtime.id, catalog }); - const sidecar = admitPreparationSidecar({ platform, catalog }); - const sqlite = await executeCold('rails', source, secureDirectory(path.join(root, 'run-sqlite')), 34612, { adapter: 'sqlite' }); - expect(sqlite.database).toEqual({ adapter: 'sqlite', connections: ['primary', 'queue'] }); - const postgres = await executeCold('rails', source, secureDirectory(path.join(root, 'run-postgresql')), 34613, { adapter: 'postgresql', sidecar }); - expect(postgres.database).toMatchObject({ adapter: 'postgresql', connections: ['primary', 'queue'], sidecar: { id: sidecar.runtime.id } }); - expect(appAdmission.catalogRevision).toBe(sidecar.catalogRevision); - }, 25 * 60_000); -}); diff --git a/test/cso-staging-run.test.ts b/test/cso-staging-run.test.ts deleted file mode 100644 index ce09cf8a6..000000000 --- a/test/cso-staging-run.test.ts +++ /dev/null @@ -1,164 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { spawnSync } from 'node:child_process'; -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join, resolve } from 'node:path'; -import { committedImageBuildMatrix } from '../scripts/cso-image-matrix'; -import { dispatchSourceCommit, stagingRunId, verifyStagingRun, type StagingRunEvidence } from '../scripts/cso-staging-run'; - -const ROOT = resolve(import.meta.dir, '..'); -const REPOSITORY = 'garrytan/gstack'; -const RUN_ID = '34980146643'; -const COMMIT = 'a'.repeat(40); -const RUNTIME_IDS = committedImageBuildMatrix().include.map(row => row.runtimeId); -const temps: string[] = []; -afterEach(() => { for (const dir of temps.splice(0)) rmSync(dir, { recursive: true, force: true }); }); - -function invocation(runId = RUN_ID, attempt = 1, repository = REPOSITORY): string { - return `https://github.com/${repository}/actions/runs/${runId}/attempts/${attempt}`; -} - -// Shape of one `gh attestation verify --format json` entry for an actions/attest provenance statement. -function verified(predicateInvocation = invocation(), certificateInvocation = predicateInvocation): unknown[] { - return [{ - attestation: { bundle: {} }, - verificationResult: { - mediaType: 'application/vnd.dev.sigstore.verificationresult+json;version=0.1', - signature: { certificate: { - subjectAlternativeName: `https://github.com/${REPOSITORY}/.github/workflows/cso-runtime-images.yml@refs/heads/main`, - githubWorkflowTrigger: 'workflow_dispatch', - sourceRepositoryDigest: COMMIT, - runInvocationURI: certificateInvocation, - } }, - statement: { - _type: 'https://in-toto.io/Statement/v1', - predicateType: 'https://slsa.dev/provenance/v1', - subject: [{ name: 'ghcr.io/garrytan/gstack/cso-staging/node-amd64', digest: { sha256: 'b'.repeat(64) } }], - predicate: { - buildDefinition: { externalParameters: { workflow: { path: '.github/workflows/cso-runtime-images.yml', ref: 'refs/heads/main' } } }, - runDetails: { builder: { id: 'builder' }, metadata: { invocationId: predicateInvocation } }, - }, - }, - }, - }]; -} - -function run(overrides: Record = {}): Record { - return { - id: Number(RUN_ID), path: '.github/workflows/cso-runtime-images.yml', event: 'workflow_dispatch', - head_branch: 'main', head_sha: COMMIT, status: 'completed', conclusion: 'success', run_attempt: 2, - repository: { full_name: REPOSITORY }, head_repository: { full_name: REPOSITORY }, ...overrides, - }; -} - -function jobs(): Array> { - const job = (name: string) => ({ name, run_id: Number(RUN_ID), status: 'completed', conclusion: 'success' }); - return [ - job('reviewed-inputs'), - { ...job('validate-native'), conclusion: 'skipped' }, - ...RUNTIME_IDS.map(id => job(`stage (${id})`)), - ...RUNTIME_IDS.map(id => job(`qualify-native ${id}`)), - ]; -} - -function pages(list = jobs(), size = 100): unknown[] { - const result: unknown[] = []; - for (let start = 0; start < list.length; start += size) result.push({ total_count: list.length, jobs: list.slice(start, start + size) }); - return result; -} - -function evidence(overrides: Partial = {}): StagingRunEvidence { - return { repository: REPOSITORY, runId: RUN_ID, sourceCommit: COMMIT, runtimeIds: RUNTIME_IDS, run: run(), jobPages: pages(), ...overrides }; -} - -describe('CSO staging run binding', () => { - test('the committed matrix has the ten native rows the ingress requires', () => { - expect(RUNTIME_IDS).toHaveLength(10); - }); - - test('resolves one staging run from every image provenance, across rerun attempts', () => { - const all = RUNTIME_IDS.map((_, index) => verified(invocation(RUN_ID, index === 0 ? 2 : 1))); - expect(stagingRunId(REPOSITORY, all)).toBe(RUN_ID); - }); - - test('rejects statements that resolve to different runs, foreign repositories, or forged invocations', () => { - const split = RUNTIME_IDS.map((_, index) => verified(invocation(index === 3 ? '999' : RUN_ID))); - expect(() => stagingRunId(REPOSITORY, split)).toThrow('STAGING_RUN_NOT_UNIQUE'); - const twoInOne = [[...verified(), ...verified(invocation('999'))]]; - expect(() => stagingRunId(REPOSITORY, twoInOne)).toThrow('STAGING_RUN_NOT_UNIQUE'); - expect(() => stagingRunId(REPOSITORY, [verified(invocation(RUN_ID, 1, 'someone/fork'))])).toThrow('STAGING_INVOCATION_MISMATCH'); - expect(() => stagingRunId(REPOSITORY, [verified(invocation(), invocation('999'))])).toThrow('STAGING_INVOCATION_MISMATCH'); - expect(() => stagingRunId(REPOSITORY, [verified(`${invocation()}/extra`)])).toThrow('STAGING_INVOCATION_MISMATCH'); - const sbom = verified() as any[]; - sbom[0].verificationResult.statement.predicateType = 'https://spdx.dev/Document/v2.3'; - expect(() => stagingRunId(REPOSITORY, [sbom])).toThrow('INVALID_STAGING_PROVENANCE'); - expect(() => stagingRunId(REPOSITORY, [[]])).toThrow('INVALID_STAGING_PROVENANCE'); - expect(() => stagingRunId(REPOSITORY, [])).toThrow('INVALID_STAGING_PROVENANCE'); - }); - - test('accepts the successful protected-main staging dispatch with every native gate passed, across job pages', () => { - expect(() => verifyStagingRun(evidence())).not.toThrow(); - expect(() => verifyStagingRun(evidence({ jobPages: pages(jobs(), 7) }))).not.toThrow(); - }); - - test('rejects a run that is not the successful protected-main staging dispatch at the statements commit', () => { - expect(() => verifyStagingRun(evidence({ run: run({ path: '.github/workflows/cso-runtime-qualification.yml' }) }))).toThrow('STAGING_WORKFLOW_MISMATCH'); - expect(() => verifyStagingRun(evidence({ run: run({ head_branch: 'feature' }) }))).toThrow('STAGING_RUN_NOT_PROTECTED_MAIN_DISPATCH'); - expect(() => verifyStagingRun(evidence({ run: run({ event: 'pull_request' }) }))).toThrow('STAGING_RUN_NOT_PROTECTED_MAIN_DISPATCH'); - expect(() => verifyStagingRun(evidence({ run: run({ conclusion: 'failure' }) }))).toThrow('STAGING_RUN_NOT_SUCCESSFUL'); - expect(() => verifyStagingRun(evidence({ run: run({ status: 'in_progress', conclusion: null }) }))).toThrow('STAGING_RUN_NOT_SUCCESSFUL'); - expect(() => verifyStagingRun(evidence({ run: run({ head_sha: 'c'.repeat(40) }) }))).toThrow('STAGING_SOURCE_COMMIT_MISMATCH'); - expect(() => verifyStagingRun(evidence({ run: run({ id: 1 }) }))).toThrow('STAGING_RUN_ID_MISMATCH'); - expect(() => verifyStagingRun(evidence({ run: run({ head_repository: { full_name: 'someone/fork' } }) }))).toThrow('STAGING_REPOSITORY_MISMATCH'); - }); - - test('rejects a failed, missing, extra, or truncated native gate job', () => { - const failed = jobs(); - failed[failed.length - 1].conclusion = 'failure'; - expect(() => verifyStagingRun(evidence({ jobPages: pages(failed) }))).toThrow('STAGING_NATIVE_GATE_NOT_PASSED'); - const skipped = jobs(); - skipped[skipped.length - 1].conclusion = 'skipped'; - expect(() => verifyStagingRun(evidence({ jobPages: pages(skipped) }))).toThrow('STAGING_NATIVE_GATE_NOT_PASSED'); - const missing = jobs().slice(0, -1); - expect(() => verifyStagingRun(evidence({ jobPages: pages(missing) }))).toThrow('STAGING_NATIVE_JOBS_MISMATCH'); - const extra = [...jobs(), { name: 'qualify-native unexpected', run_id: Number(RUN_ID), status: 'completed', conclusion: 'success' }]; - expect(() => verifyStagingRun(evidence({ jobPages: pages(extra) }))).toThrow('STAGING_NATIVE_JOBS_MISMATCH'); - const truncated = pages(jobs(), 7).slice(0, -1); - expect(() => verifyStagingRun(evidence({ jobPages: truncated }))).toThrow('INCOMPLETE_STAGING_JOBS'); - const otherRun = jobs(); - otherRun[otherRun.length - 1].run_id = 1; - expect(() => verifyStagingRun(evidence({ jobPages: pages(otherRun) }))).toThrow('STAGING_NATIVE_GATE_NOT_PASSED'); - expect(() => verifyStagingRun(evidence({ jobPages: [] }))).toThrow('INVALID_STAGING_JOBS'); - }); - - test('a dispatch must name one exact source commit', () => { - const statements = RUNTIME_IDS.map(runtimeId => ({ runtimeId, sourceCommit: COMMIT })); - expect(dispatchSourceCommit({ client_payload: { statements } })).toBe(COMMIT); - statements[4].sourceCommit = 'c'.repeat(40); - expect(() => dispatchSourceCommit({ client_payload: { statements } })).toThrow('STAGING_SOURCE_COMMIT_MISMATCH'); - expect(() => dispatchSourceCommit({ client_payload: { statements: [{ sourceCommit: 'main' }] } })).toThrow('STAGING_SOURCE_COMMIT_MISMATCH'); - }); - - test('the workflow command line resolves and verifies the run from retained files', () => { - const dir = mkdtempSync(join(tmpdir(), 'cso-staging-run-')); temps.push(dir); - const files = RUNTIME_IDS.map(id => { - const file = join(dir, `${id}.json`); - writeFileSync(file, JSON.stringify(verified())); - return file; - }); - const script = join(ROOT, 'scripts/cso-staging-run.ts'); - const resolved = spawnSync(process.execPath, ['run', script, 'run-id', '--repository', REPOSITORY, ...files], { encoding: 'utf8', timeout: 30_000 }); - expect(resolved.status, resolved.stderr).toBe(0); - expect(resolved.stdout).toBe(`${RUN_ID}\n`); - writeFileSync(join(dir, 'event.json'), JSON.stringify({ client_payload: { statements: RUNTIME_IDS.map(runtimeId => ({ runtimeId, sourceCommit: COMMIT })) } })); - writeFileSync(join(dir, 'run.json'), JSON.stringify(run())); - writeFileSync(join(dir, 'jobs.json'), JSON.stringify(pages())); - const args = ['run', script, 'verify', '--repository', REPOSITORY, '--run-id', RUN_ID, '--event', join(dir, 'event.json'), '--run', join(dir, 'run.json'), '--jobs', join(dir, 'jobs.json')]; - const accepted = spawnSync(process.execPath, args, { encoding: 'utf8', timeout: 30_000 }); - expect(accepted.status, accepted.stderr).toBe(0); - writeFileSync(join(dir, 'run.json'), JSON.stringify(run({ conclusion: 'failure' }))); - const rejected = spawnSync(process.execPath, args, { encoding: 'utf8', timeout: 30_000 }); - expect(rejected.status).toBe(1); - expect(rejected.stderr).toContain('STAGING_RUN_NOT_SUCCESSFUL'); - }); -}); diff --git a/test/cso-unreadable-secret-file.test.ts b/test/cso-unreadable-secret-file.test.ts deleted file mode 100644 index b774b730b..000000000 --- a/test/cso-unreadable-secret-file.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { spawnSync } from 'node:child_process'; -import { capture } from '../lib/cso/snapshot'; -import { CsoError } from '../lib/cso/contracts'; -import { newRun } from '../lib/cso/state'; - -// An unreadable secret-like file (a Claude Code sandbox deny rule such as Read(**/.env*), or a chmod 000 file) is -// already kept out of snapshot/, so start reports it as an unread input instead of aborting the whole audit (#4395). -const roots: string[] = []; -const tmp = () => { const p = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-unreadable-')); roots.push(p); return p; }; -afterEach(() => { for (const p of roots.splice(0)) { try { fs.chmodSync(path.join(p, '.env.example'), 0o600); } catch {} try { fs.chmodSync(path.join(p, 'app.ts'), 0o600); } catch {} fs.rmSync(p, { recursive: true, force: true }); } }); -let originalState: string | undefined, state = ''; -beforeAll(() => { originalState = process.env.GSTACK_HOME; state = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-unreadable-state-')); process.env.GSTACK_HOME = state; }); -afterAll(() => { if (originalState === undefined) delete process.env.GSTACK_HOME; else process.env.GSTACK_HOME = originalState; fs.rmSync(state, { recursive: true, force: true }); }); -function git(repo: string, ...args: string[]) { - const r = spawnSync('git', ['-C', repo, ...args], { encoding: 'utf8', env: { ...process.env, HOME: repo, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' }, timeout: 30_000 }); - if (r.status) throw new Error(r.stderr); -} -function repo() { - const p = tmp(); - git(p, 'init', '-q'); - git(p, 'config', 'user.email', 'fixture@example.test'); - git(p, 'config', 'user.name', 'Fixture'); - fs.writeFileSync(path.join(p, '.env.example'), 'FOO=bar\n'); - fs.writeFileSync(path.join(p, 'app.ts'), 'export const x = 1;\n'); - git(p, 'add', '.'); - git(p, 'commit', '-qm', 'base'); - return p; -} -const permissionsBind = process.platform !== 'win32' && process.getuid?.() !== 0; - -describe('cso snapshot with an unreadable secret-like file (#4395)', () => { - // Value: protects=a tracked .env.example that cannot be opened becomes an unread, withheld input and the capture - // continues; fails_when=open's EACCES aborts start with UNSAFE_PATH; why_new=no capture case had an unreadable - // file; seam=none - test.skipIf(!permissionsBind)('a file that cannot be opened is withheld as unread and the capture continues', async () => { - const p = repo(); - fs.chmodSync(path.join(p, '.env.example'), 0o000); - const run = newRun(p), m = await capture(p, run.dir); - const entry = m.entries.find(e => e.path === '.env.example')!; - expect(entry.originalHash).toBe('not-read'); - expect(entry.executionHash).toBeUndefined(); - expect(entry.transformation).toMatch(/^withheld: .*unreadable \(EACCES\)/); - expect(fs.existsSync(path.join(run.dir, 'readable', '.env.example'))).toBe(false); - expect(m.entries.find(e => e.path === 'app.ts')?.executionHash).toBeDefined(); - }); - - // Value: protects=the sandbox case, where even lstat is denied (EPERM), is withheld the same way; fails_when=the raw - // EPERM escapes and start reports a generic INVALID_SCHEMA; why_new=the case above denies only open; - // seam=fs.lstatSync on that one path - test('a file whose lstat is denied is withheld as unread and the capture continues', async () => { - const p = repo(), denied = path.join(p, '.env.example'), real = fs.lstatSync; - const spy = spyOn(fs, 'lstatSync').mockImplementation(((file: any, ...args: any[]) => { - if (String(file) === denied) throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' }); - return (real as any)(file, ...args); - }) as any); - try { - const m = await capture(p, newRun(p).dir); - const entry = m.entries.find(e => e.path === '.env.example')!; - expect([entry.originalHash, entry.bytes]).toEqual(['not-read', 0]); - expect(entry.transformation).toMatch(/^withheld: .*unreadable \(EPERM\)/); - } finally { spy.mockRestore(); } - }); - - // Value: protects=an unreadable ordinary source file still stops the capture, so the exemption covers only paths - // already excluded as secrets; fails_when=any unreadable file is silently withheld; why_new=the exemption is new; seam=none - test.skipIf(!permissionsBind)('an unreadable ordinary source file still refuses', async () => { - const p = repo(); - fs.chmodSync(path.join(p, 'app.ts'), 0o000); - const error = await capture(p, newRun(p).dir).then(() => null, e => e); - expect(error).toBeInstanceOf(CsoError); - expect((error as CsoError).code).toBe('UNSAFE_PATH'); - }); - - // Value: protects=an ordinary source file whose lstat is denied still stops the capture; fails_when=the lstat catch - // drops its exclusion check and silently withholds app.ts; why_new=the lstat exemption is new; seam=fs.lstatSync on that one path - test('an ordinary source file whose lstat is denied still refuses', async () => { - const p = repo(), denied = path.join(p, 'app.ts'), real = fs.lstatSync; - const spy = spyOn(fs, 'lstatSync').mockImplementation(((file: any, ...args: any[]) => { - if (String(file) === denied) throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' }); - return (real as any)(file, ...args); - }) as any); - try { - const error = await capture(p, newRun(p).dir).then(() => null, e => e); - expect((error as NodeJS.ErrnoException | null)?.code).toBe('EPERM'); - } finally { spy.mockRestore(); } - }); - - // Value: protects=a withheld lstat-denied path that becomes readable before the end of capture is a race, not a pass; - // fails_when=the end-of-capture re-check accepts a path it can now stat; why_new=the re-check is new; - // seam=fs.lstatSync on that one path, denied on every call but the last (counted from a fully denied capture) - test('an lstat-denied secret that becomes readable before the end of capture is a SNAPSHOT_RACE', async () => { - const p = repo(), denied = path.join(p, '.env.example'), real = fs.lstatSync; - let calls = 0, allow = Infinity; - const spy = spyOn(fs, 'lstatSync').mockImplementation(((file: any, ...args: any[]) => { - if (String(file) === denied && ++calls < allow) throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' }); - return (real as any)(file, ...args); - }) as any); - try { - await capture(p, newRun(p).dir); - allow = calls; - calls = 0; - const error = await capture(p, newRun(p).dir).then(() => null, e => e); - expect(error).toBeInstanceOf(CsoError); - expect((error as CsoError).code).toBe('SNAPSHOT_RACE'); - } finally { spy.mockRestore(); } - }); -}); diff --git a/test/cso-verification-cleanup.test.ts b/test/cso-verification-cleanup.test.ts deleted file mode 100644 index 62b09aa5a..000000000 --- a/test/cso-verification-cleanup.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { sha256 } from '../lib/cso/contracts'; -import { patchHash, treeHash, verifyRepair } from '../lib/cso/verification'; - -const roots:string[]=[]; -afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); - -describe('CSO verification persistence ordering',()=>{ - test('cleanup acknowledgement failure leaves no certified bundle on disk',async()=>{ - const runDir=fs.mkdtempSync(path.join(os.tmpdir(),'cso-cleanup-order-'));roots.push(runDir); - const snapshot=path.join(runDir,'snapshot');fs.mkdirSync(snapshot); - const files:Record={ - 'package.json':JSON.stringify({scripts:{test:'node --test'}}), - 'app.js':'vulnerable\n', - 'app.test.js':'test("ok",()=>{})\n', - }; - for(const [name,body] of Object.entries(files))fs.writeFileSync(path.join(snapshot,name),body); - const request:any={findingId:'a'.repeat(32),runtimeProfile:'node',port:3456,start:{executable:'/usr/local/bin/node',args:['app.js']}, - legitimate:[{name:'health',path:'/health',method:'GET',expected:{status:200,includes:'ok'}}], - security:{name:'tenant isolation',path:'/user?id=2',method:'GET',expected:{status:403},vulnerable:{status:200,includes:'tenant-b'}}, - existingTests:[{executable:'/usr/local/bin/node',args:['--test','--test-reporter=tap','./app.test.js']}],testFiles:['app.test.js'],fixtures:{},boundaryFiles:['app.js'], - changes:[{path:'app.js',beforeSha256:sha256(files['app.js']),after:'fixed\n',effect:'source'}], - review:{reviewer:'independent-reviewer',independent:true,rootCauseRepaired:true,featurePreserved:true,boundaryMocks:false, - rationale:'The tenant predicate is restored without changing the feature',reviewedPatchHash:''}}; - request.review.reviewedPatchHash=patchHash(request); - const entries=Object.entries(files).map(([name,body])=>({path:name,originalHash:sha256(body),executionHash:sha256(body),bytes:Buffer.byteLength(body),mode:0o600})); - const manifest:any={version:3,createdAt:'2026-01-01T00:00:00Z',expiresAt:'2026-01-08T00:00:00Z',root:'/repo',headCommit:'b'.repeat(40), - originalHash:'c'.repeat(64),executionHash:treeHash(snapshot),entries}; - const watchdog=path.join(runDir,'no-ack-watchdog'); - fs.writeFileSync(watchdog,'#!/bin/sh\nset -eu\ntouch "$6/attempt.ready"\nwhile test ! -f "$6/attempt.terminal"; do sleep 0.01; done\nexit 0\n',{mode:0o755}); - const runtime:any={id:'node',stack:'node',image:`runtime@sha256:${'d'.repeat(64)}`,platform:'linux/amd64'}; - const executor:any={observe:async(_source:string,phase:'before'|'after')=>({booted:true,legitimate:true, - security:phase==='before'?'intended_failure':'pass',existingTests:true,output:'ok',inputHash:''})}; - await expect(verifyRepair({runId:'run',runDir,manifest,rawRequest:request,runtime,verifier:runtime,policyHash:'e'.repeat(64),archives:[],executor, - watchdogPath:watchdog,attemptDeadline:Date.now()+10_000})).rejects.toThrow('did not acknowledge'); - const bundles=path.join(runDir,'bundles');expect(fs.existsSync(bundles)?fs.readdirSync(bundles):[]).toEqual([]); - }); -}); diff --git a/test/cso-verifier.test.ts b/test/cso-verifier.test.ts deleted file mode 100644 index 95cd725c0..000000000 --- a/test/cso-verifier.test.ts +++ /dev/null @@ -1,89 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import type { HttpAssertion } from '../lib/cso/contracts'; -import { boundedResponseBody, judgeSecurity } from '../lib/cso/verifier'; - -describe('CSO bounded loopback verifier response reader',()=>{ - test('accepts a response exactly at the configured byte limit',async()=>{ - const body='x'.repeat(65_536); - expect(await boundedResponseBody(new Response(body))).toBe(body); - }); - - test('cancels an endless chunked response immediately after the byte limit',async()=>{ - let pulls=0,cancelled=false; - const stream=new ReadableStream({ - pull(controller){pulls++;controller.enqueue(new Uint8Array(8192));}, - cancel(){cancelled=true;}, - }); - await expect(boundedResponseBody(new Response(stream))).rejects.toThrow('response too large'); - expect(cancelled).toBe(true); - expect(pulls).toBeLessThanOrEqual(10); - }); - - test('rejects an oversized declared body before consuming it',async()=>{ - let cancelled=false; - const stream=new ReadableStream({pull(controller){controller.enqueue(new Uint8Array(1));},cancel(){cancelled=true;}}); - const response=new Response(stream,{headers:{'content-length':'65537'}}); - await expect(boundedResponseBody(response)).rejects.toThrow('response too large'); - expect(cancelled).toBe(true); - }); -}); - -describe('CSO verifier security judgement',()=>{ - const payloads:HttpAssertion[]=[ - {name:'id parameter',path:'/user?id=2',method:'GET',expected:{status:403},vulnerable:{status:200,includes:'tenant-b'}}, - {name:'tenant header',path:'/user',method:'GET',headers:{'x-tenant':'b'},expected:{status:403},vulnerable:{status:200,includes:'tenant-b'}}, - {name:'write path',path:'/user/2',method:'PUT',body:'{}',expected:{status:404},vulnerable:{status:204}}, - ]; - const serve=(fixed:Set)=>{ - const seen:string[]=[]; - const server=Bun.serve({port:0,hostname:'127.0.0.1',fetch(req){ - const url=new URL(req.url),key=`${req.method} ${url.pathname}${url.search}`;seen.push(key); - if(req.method==='PUT')return new Response(null,{status:fixed.has(key)?404:204}); - return fixed.has(key)?new Response('denied',{status:403}):new Response('tenant-b secret',{status:200}); - }}); - return {server,seen,port:Number(server.port)}; - }; - const ALL=new Set(['GET /user?id=2','GET /user','PUT /user/2']); - - test('one booted server answers every array member and the before phase needs every vulnerable expectation',async()=>{ - const {server,seen,port}=serve(new Set()); - try{ - expect(await judgeSecurity('before',payloads,port)).toEqual({security:'intended_failure',members:['intended_failure','intended_failure','intended_failure']}); - expect(seen).toEqual(['GET /user?id=2','GET /user','PUT /user/2']); - }finally{server.stop(true);} - }); - - test('the after phase passes only when every array member passes its fixed expectation',async()=>{ - const fixed=serve(ALL); - try{expect(await judgeSecurity('after',payloads,fixed.port)).toEqual({security:'pass',members:['pass','pass','pass']});}finally{fixed.server.stop(true);} - const partial=serve(new Set(['GET /user?id=2','PUT /user/2'])); - try{ - expect(await judgeSecurity('after',payloads,partial.port)).toEqual({security:'inconclusive',members:['pass','inconclusive','pass']}); - expect(await judgeSecurity('before',payloads,partial.port)).toEqual({security:'inconclusive',members:['pass','intended_failure','pass']}); - }finally{partial.server.stop(true);} - const disproved=serve(ALL); - try{expect((await judgeSecurity('before',payloads,disproved.port)).security).toBe('pass');}finally{disproved.server.stop(true);} - }); - - test('a set of safe statuses passes any listed rejection that withholds the marker and nothing else',async()=>{ - const dotfile:HttpAssertion={name:'dotfile',path:'/.env',method:'GET',expected:{status:[403,404],excludes:'DOTFILE'},vulnerable:{status:200,includes:'DOTFILE'}}; - const answer=async(status:number,body:string)=>{ - const server=Bun.serve({port:0,hostname:'127.0.0.1',fetch:()=>new Response(body,{status})}); - try{return [(await judgeSecurity('before',dotfile,Number(server.port))).security,(await judgeSecurity('after',dotfile,Number(server.port))).security];}finally{server.stop(true);} - }; - expect(await answer(404,'not found')).toEqual(['pass','pass']); - expect(await answer(403,'denied')).toEqual(['pass','pass']); - expect(await answer(200,'DOTFILE=1')).toEqual(['intended_failure','inconclusive']); - expect(await answer(403,'denied DOTFILE=1')).toEqual(['inconclusive','inconclusive']); - expect(await answer(400,'bad request')).toEqual(['inconclusive','inconclusive']); - }); - - test('a single assertion keeps its original before and after outcomes',async()=>{ - const vulnerable=serve(new Set()),fixed=serve(ALL); - try{ - expect(await judgeSecurity('before',payloads[0],vulnerable.port)).toEqual({security:'intended_failure',members:['intended_failure']}); - expect(await judgeSecurity('after',payloads[0],vulnerable.port)).toEqual({security:'inconclusive',members:['inconclusive']}); - expect(await judgeSecurity('after',payloads[0],fixed.port)).toEqual({security:'pass',members:['pass']}); - }finally{vulnerable.server.stop(true);fixed.server.stop(true);} - }); -}); diff --git a/test/cso-watchdog.test.ts b/test/cso-watchdog.test.ts deleted file mode 100644 index c78073577..000000000 --- a/test/cso-watchdog.test.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { afterAll, afterEach, beforeAll, describe, expect, test } from 'bun:test';import * as fs from 'node:fs';import * as os from 'node:os';import * as path from 'node:path';import { spawn, spawnSync } from 'node:child_process'; -import { supervisePreparedCall } from '../lib/cso/preparation-docker'; -const dirs:string[]=[];const tmp=()=>{const p=fs.mkdtempSync(path.join(os.tmpdir(),'csowatchdog-'));dirs.push(p);return p;};afterEach(()=>{for(const p of dirs.splice(0))fs.rmSync(p,{recursive:true,force:true});}); -function compile(dir:string){const out=path.join(dir,'watchdog'),r=spawnSync('/usr/bin/cc',['-std=c11','-D_POSIX_C_SOURCE=200809L','-O2','-Wall','-Wextra',path.resolve(import.meta.dir,'../lib/cso/watchdog.c'),'-o',out],{encoding:'utf8',timeout:30_000});expect(r.status).toBe(0);expect(r.stderr).toBe('');return out;} -function pinnedEndpoint(dir:string){const socket=path.join(dir,'daemon.sock'),made=spawnSync('/usr/bin/python3',['-c','import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1]); s.close()',socket],{encoding:'utf8'});expect(made.status).toBe(0);const stat=fs.lstatSync(socket);expect(stat.isSocket()).toBe(true);return{uri:`unix://${socket}`,device:stat.dev,inode:stat.ino};} -describe('detached CSO watchdog',()=>{ - let seedDir:string; - beforeAll(()=>{seedDir=fs.mkdtempSync(path.join(os.tmpdir(),'csowatchdog-seed-'));compile(seedDir);}); - afterAll(()=>{if(seedDir)fs.rmSync(seedDir,{recursive:true,force:true});}); - function copyWatchdog(dir:string){const out=path.join(dir,'watchdog');fs.copyFileSync(path.join(seedDir,'watchdog'),out);return out;} - test('prepared-call guard acknowledges normal exact cleanup',async()=>{const run=tmp(),watchdog=copyWatchdog(run),call=path.join(run,'preparation-execution','offline-call'),control=path.join(run,'supervision','prepared-call');fs.mkdirSync(call,{recursive:true});fs.mkdirSync(control,{recursive:true});fs.writeFileSync(path.join(call,'prepared-source'),'copy');const guard=await supervisePreparedCall({watchdogPath:watchdog,ownerPid:process.pid,deadline:Date.now()+10_000,runRoot:run,callRoot:call,controlRoot:control});await guard.dispose();expect(fs.existsSync(call)).toBe(false);expect(fs.existsSync(control)).toBe(false);}); - test('prepared-call guard removes retained output after owner death and deadline',async()=>{for(const mode of ['owner','deadline'] as const){const run=tmp(),watchdog=copyWatchdog(run),call=path.join(run,'preparation-execution',mode),control=path.join(run,'supervision',mode),event=path.join(control,'attempt.event');fs.mkdirSync(call,{recursive:true});fs.mkdirSync(control,{recursive:true});fs.writeFileSync(path.join(call,'prepared-source'),'copy');const owner=mode==='owner'?spawn('/bin/sleep',['30'],{stdio:'ignore'}):undefined,guard=await supervisePreparedCall({watchdogPath:watchdog,ownerPid:owner?.pid??process.pid,deadline:Date.now()+(mode==='owner'?10_000:50),runRoot:run,callRoot:call,controlRoot:control});if(owner)owner.kill('SIGKILL');for(let attempt=0;attempt<40&&(!fs.existsSync(event)||fs.existsSync(call));attempt++)await Bun.sleep(100);expect(fs.existsSync(call)).toBe(false);expect(fs.readFileSync(event,'utf8')).toContain(`${mode==='owner'?'supervisor-death':'deadline'} execution-copy cleanup complete`);await guard.dispose();expect(fs.existsSync(control)).toBe(false);}}); - test('survives supervisor death and cleans journaled plus label-race resources',async()=>{const dir=tmp(),watchdog=copyWatchdog(dir),endpoint=pinnedEndpoint(dir),log=path.join(dir,'docker.log'),docker=path.join(dir,'docker'),id='a'.repeat(64),race='e'.repeat(64),lease=path.join(dir,'lease'),token='c'.repeat(32);fs.mkdirSync(lease);fs.writeFileSync(path.join(lease,'lease.json'),'{}');fs.writeFileSync(path.join(lease,'lease.token'),token+'\n');fs.writeFileSync(docker,`#!/bin/sh\nif [ "$3" = ps ]; then if [ "$8" = "id=${id}" ]; then printf '%s\\n' '${id}'; else printf '%s\\n' '${race}'; fi; exit 0; fi\nprintf '%s\\n' "$*" >> '${log}'\n`,{mode:0o755});fs.writeFileSync(path.join(dir,'resources.journal'),`container:${id}\n`,{mode:0o600});const owner=spawn('/bin/sleep',['1'],{stdio:'ignore'}),child=spawn(watchdog,['--owner',String(owner.pid),'--deadline',String(Math.ceil((Date.now()+10_000)/1000)),'--run-dir',dir,'--docker',docker,'--endpoint',endpoint.uri,'--socket-device',String(endpoint.device),'--socket-inode',String(endpoint.inode),'--run-label','test-label','--lease-path',lease,'--lease-token',token],{stdio:'ignore'}),closed=new Promise(resolve=>child.on('close',resolve));expect(await closed).toBe(0);const calls=fs.readFileSync(log,'utf8');expect(calls).toContain(`rm --force --volumes ${id}`);expect(calls).toContain(`rm --force --volumes ${race}`);expect(fs.readFileSync(path.join(dir,'watchdog.event'),'utf8')).toContain('supervisor-death cleanup complete');expect(fs.existsSync(lease)).toBe(false);}); - test('quarantines an authenticated lease before a concurrent TS recovery claim can strand release',async()=>{const dir=tmp(),watchdog=copyWatchdog(dir),endpoint=pinnedEndpoint(dir),docker=path.join(dir,'docker'),lease=path.join(dir,'lease'),token='1'.repeat(32),claim='2'.repeat(32);fs.mkdirSync(lease,{mode:0o700});fs.writeFileSync(path.join(lease,'lease.json'),JSON.stringify({token}),{mode:0o600});fs.writeFileSync(path.join(lease,'lease.token'),token+'\n',{mode:0o600});fs.writeFileSync(path.join(lease,'.recovery'),JSON.stringify({pid:process.pid,processIdentity:null,token:claim,createdAt:Date.now()})+'\n',{mode:0o600});fs.writeFileSync(docker,'#!/bin/sh\nif [ "$3" = ps ]; then exit 0; fi\nexit 0\n',{mode:0o755});const owner=spawn('/bin/sleep',['0.05'],{stdio:'ignore'}),child=spawn(watchdog,['--owner',String(owner.pid),'--deadline',String(Math.ceil((Date.now()+10_000)/1000)),'--run-dir',dir,'--docker',docker,'--endpoint',endpoint.uri,'--socket-device',String(endpoint.device),'--socket-inode',String(endpoint.inode),'--run-label','release-race','--lease-path',lease,'--lease-token',token],{stdio:'ignore'}),closed=new Promise(resolve=>child.on('close',resolve));const outcome=await Promise.race([closed,Bun.sleep(5000).then(()=>-999)]);if(outcome===-999)child.kill('SIGKILL');expect(outcome).toBe(0);expect(fs.existsSync(lease)).toBe(false);expect(fs.readdirSync(dir).some(name=>name.includes('.watchdog-release-'))).toBe(false);expect(fs.readFileSync(path.join(dir,'watchdog.event'),'utf8')).toContain('cleanup complete');}); - test('attempt mode removes a patched execution copy after supervisor death',async()=>{const run=tmp(),watchdog=copyWatchdog(run),control=path.join(run,'supervision','attempt'),work=path.join(run,'verification','attempt');fs.mkdirSync(control,{recursive:true});fs.mkdirSync(work,{recursive:true});fs.writeFileSync(path.join(work,'patched-source'),'sensitive execution copy');const owner=spawn('/bin/sleep',['1'],{stdio:'ignore'}),child=spawn(watchdog,['--attempt-owner',String(owner.pid),'--deadline',String(Math.ceil((Date.now()+10_000)/1000)),'--control-dir',control,'--work-root',work,'--run-root',run],{stdio:'ignore'}),closed=new Promise(resolve=>child.on('close',resolve));expect(await closed).toBe(0);expect(fs.existsSync(work)).toBe(false);expect(fs.readFileSync(path.join(control,'attempt.event'),'utf8')).toContain('execution-copy cleanup complete');}); - test('attempt cleanup cannot remove the concurrent Docker watchdog journal',async()=>{const run=tmp(),watchdog=copyWatchdog(run),endpoint=pinnedEndpoint(run),attemptControl=path.join(run,'supervision','attempt'),dockerControl=path.join(attemptControl,'docker-groups','before'),work=path.join(run,'verification','attempt'),lease=path.join(run,'lease'),log=path.join(dockerControl,'docker.log'),docker=path.join(dockerControl,'docker'),id='a'.repeat(64),race='e'.repeat(64),token='c'.repeat(32);for(const dir of [attemptControl,dockerControl,work,lease])fs.mkdirSync(dir,{recursive:true});fs.writeFileSync(path.join(work,'patched-source'),'sensitive execution copy');fs.writeFileSync(path.join(lease,'lease.json'),'{}');fs.writeFileSync(path.join(lease,'lease.token'),token+'\n');fs.writeFileSync(path.join(dockerControl,'resources.journal'),`container:${id}\n`,{mode:0o600});fs.writeFileSync(docker,`#!/bin/sh\nif [ "$3" = ps ]; then if [ "$8" = "id=${id}" ]; then printf '%s\\n' '${id}'; else printf '%s\\n' '${race}'; fi; exit 0; fi\nprintf '%s\\n' "$*" >> '${log}'\n`,{mode:0o755});const owner=spawn('/bin/sleep',['1'],{stdio:'ignore'}),attempt=spawn(watchdog,['--attempt-owner',String(owner.pid),'--deadline',String(Math.ceil((Date.now()+10_000)/1000)),'--control-dir',attemptControl,'--work-root',work,'--run-root',run],{stdio:'ignore'}),containers=spawn(watchdog,['--owner',String(owner.pid),'--deadline',String(Math.ceil((Date.now()+10_000)/1000)),'--run-dir',dockerControl,'--docker',docker,'--endpoint',endpoint.uri,'--socket-device',String(endpoint.device),'--socket-inode',String(endpoint.inode),'--run-label','test-label','--lease-path',lease,'--lease-token',token],{stdio:'ignore'});const closed=(child:any)=>new Promise(resolve=>child.on('close',resolve));expect(await Promise.all([closed(attempt),closed(containers)])).toEqual([0,0]);expect(fs.existsSync(work)).toBe(false);expect(fs.readFileSync(log,'utf8')).toContain(`rm --force --volumes ${id}`);expect(fs.existsSync(lease)).toBe(false);expect(fs.readFileSync(path.join(dockerControl,'watchdog.event'),'utf8')).toContain('cleanup complete');}); - test('a terminal marker prevents any cleanup call',async()=>{const dir=tmp(),watchdog=copyWatchdog(dir),endpoint=pinnedEndpoint(dir),log=path.join(dir,'docker.log'),docker=path.join(dir,'docker'),lease=path.join(dir,'lease'),token='d'.repeat(32);fs.mkdirSync(lease);fs.writeFileSync(path.join(lease,'lease.json'),'{}');fs.writeFileSync(path.join(lease,'lease.token'),token+'\n');fs.writeFileSync(docker,`#!/bin/sh\ntouch '${log}'\n`,{mode:0o755});fs.writeFileSync(path.join(dir,'resources.journal'),`container:${'b'.repeat(64)}\n`);fs.writeFileSync(path.join(dir,'watchdog.terminal'),'done\n');const r=spawnSync(watchdog,['--owner',String(process.pid),'--deadline',String(Math.ceil((Date.now()+10_000)/1000)),'--run-dir',dir,'--docker',docker,'--endpoint',endpoint.uri,'--socket-device',String(endpoint.device),'--socket-inode',String(endpoint.inode),'--run-label','test-label','--lease-path',lease,'--lease-token',token],{timeout:30_000});expect(r.status).toBe(0);expect(fs.existsSync(log)).toBe(false);}); - test('acknowledges terminal cleanup well inside the caller deadline',async()=>{const dir=tmp(),watchdog=copyWatchdog(dir),endpoint=pinnedEndpoint(dir),docker=path.join(dir,'docker'),lease=path.join(dir,'lease'),token='9'.repeat(32),ready=path.join(dir,'watchdog.ready'),stopped=path.join(dir,'watchdog.stopped');fs.mkdirSync(lease);fs.writeFileSync(path.join(lease,'lease.json'),'{}');fs.writeFileSync(path.join(lease,'lease.token'),token+'\n');fs.writeFileSync(docker,'#!/bin/sh\nexit 0\n',{mode:0o755});const child=spawn(watchdog,['--owner',String(process.pid),'--deadline',String(Math.ceil((Date.now()+10_000)/1000)),'--run-dir',dir,'--docker',docker,'--endpoint',endpoint.uri,'--socket-device',String(endpoint.device),'--socket-inode',String(endpoint.inode),'--run-label','ack-latency','--lease-path',lease,'--lease-token',token],{stdio:'ignore'}),closed=new Promise(resolve=>child.once('close',resolve));for(let i=0;i<100&&!fs.existsSync(ready);i++)await Bun.sleep(10);expect(fs.existsSync(ready)).toBe(true);await Bun.sleep(50);const started=Date.now();fs.writeFileSync(path.join(dir,'watchdog.terminal'),'done\n');for(let i=0;i<100&&!fs.existsSync(stopped);i++)await Bun.sleep(10);expect(fs.existsSync(stopped)).toBe(true);expect(Date.now()-started).toBeLessThan(500);expect(await closed).toBe(0);}); - test('a torn final journal row cannot retain the machine lease after exact label sweeps',async()=>{const dir=tmp(),watchdog=copyWatchdog(dir),endpoint=pinnedEndpoint(dir),docker=path.join(dir,'docker'),lease=path.join(dir,'lease'),token='e'.repeat(32),id='a'.repeat(64);fs.mkdirSync(lease);fs.writeFileSync(path.join(lease,'lease.json'),'{}');fs.writeFileSync(path.join(lease,'lease.token'),token+'\n');fs.writeFileSync(docker,'#!/bin/sh\nif [ "$3" = ps ]; then exit 0; fi\nexit 0\n',{mode:0o755});fs.writeFileSync(path.join(dir,'resources.journal'),`container:${id}\ncontainer:abcd`,{mode:0o600});const owner=spawn('/bin/sleep',['1'],{stdio:'ignore'}),child=spawn(watchdog,['--owner',String(owner.pid),'--deadline',String(Math.ceil((Date.now()+10_000)/1000)),'--run-dir',dir,'--docker',docker,'--endpoint',endpoint.uri,'--socket-device',String(endpoint.device),'--socket-inode',String(endpoint.inode),'--run-label','test-label','--lease-path',lease,'--lease-token',token],{stdio:'ignore'});expect(await new Promise(resolve=>child.on('close',resolve))).toBe(0);expect(fs.existsSync(lease)).toBe(false);expect(fs.readFileSync(path.join(dir,'watchdog.event'),'utf8')).toContain('malformed journal ignored after two exact label sweeps');}); - test('a replaced Docker socket blocks cleanup and lease release',async()=>{const dir=tmp(),watchdog=copyWatchdog(dir),endpoint=pinnedEndpoint(dir),docker=path.join(dir,'docker'),lease=path.join(dir,'lease'),token='f'.repeat(32),log=path.join(dir,'docker.log');fs.mkdirSync(lease);fs.writeFileSync(path.join(lease,'lease.json'),'{}');fs.writeFileSync(path.join(lease,'lease.token'),token+'\n');fs.writeFileSync(docker,`#!/bin/sh\ntouch '${log}'\nexit 0\n`,{mode:0o755});const owner=spawn('/bin/sleep',['30'],{stdio:'ignore'}),child=spawn(watchdog,['--owner',String(owner.pid),'--deadline',String(Math.ceil((Date.now()+30_000)/1000)),'--run-dir',dir,'--docker',docker,'--endpoint',endpoint.uri,'--socket-device',String(endpoint.device),'--socket-inode',String(endpoint.inode),'--run-label','test-label','--lease-path',lease,'--lease-token',token],{stdio:'ignore'});for(let i=0;i<100&&!fs.existsSync(path.join(dir,'watchdog.ready'));i++)await Bun.sleep(10);expect(fs.existsSync(path.join(dir,'watchdog.ready'))).toBe(true);const socketPath=endpoint.uri.slice('unix://'.length);fs.renameSync(socketPath,`${socketPath}.old`);const replacement=pinnedEndpoint(dir);expect(replacement.inode).not.toBe(endpoint.inode);owner.kill('SIGKILL');for(let i=0;i<50&&!fs.existsSync(path.join(dir,'watchdog.event'));i++)await Bun.sleep(100);expect(fs.readFileSync(path.join(dir,'watchdog.event'),'utf8')).toContain('socket identity changed');expect(fs.existsSync(lease)).toBe(true);expect(fs.existsSync(log)).toBe(false);child.kill('SIGKILL');await new Promise(resolve=>child.once('close',resolve));}); -}); diff --git a/test/cso-windows-build-contract.test.ts b/test/cso-windows-build-contract.test.ts deleted file mode 100644 index ff0aa66f8..000000000 --- a/test/cso-windows-build-contract.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; - -const source = fs.readFileSync(path.join(import.meta.dir, 'cso-windows-launcher.test.ts'), 'utf8'); -const contract = source.slice(source.indexOf("describe('CSO native Windows build contract'"), source.indexOf("(windows ? describe : describe.skip)")); -const rejection = { status: 1, signal: null, stdout: '', stderr: 'direct, non-reparse staging directory' }; - -function registeredCases(result = rejection) { - const root = fs.mkdtempSync(path.join(os.tmpdir(), 'cso-build-contract-')); - fs.mkdirSync(path.join(root, 'bin')); - const cases: { name: string; run: () => void; timeout: number }[] = []; - const children: { args: string[]; options: { timeout: number } }[] = []; - const register = (name: string, run: () => void, timeout: number) => { - if (name.startsWith('Windows build ')) cases.push({ name, run, timeout }); - }; - const testAdapter = Object.assign(register, { - skipIf: () => testAdapter, - each: (rows: readonly unknown[][]) => (name: string, run: (...args: unknown[]) => void, timeout: number) => { - for (const row of rows) register(name.replace('%s', String(row[0])), () => run(...row), timeout); - }, - }); - const executable = new Bun.Transpiler({ loader: 'ts', target: 'bun' }).transformSync(contract); - new Function('describe', 'test', 'expect', 'fs', 'os', 'path', 'ROOT', 'windows', 'spawnSync', executable)( - (_name: string, run: () => void) => run(), testAdapter, expect, fs, os, path, root, true, - (command: string, args: string[], options: { timeout: number }) => { - expect(command).toBe('powershell.exe'); - children.push({ args, options }); - return result; - }, - ); - return { root, cases, children, cleanup: () => fs.rmSync(root, { recursive: true, force: true }) }; -} - -test('every native path probe has its own child deadline and bounded cleanup allowance', () => { - const fixture = registeredCases(); - try { - expect(fixture.cases).toHaveLength(5); - expect(new Set(fixture.cases.map(entry => entry.name)).size).toBe(5); - for (const entry of fixture.cases) { - const before = fixture.children.length; - entry.run(); - expect(fixture.children).toHaveLength(before + 1); - expect(fixture.children.at(-1)!.options.timeout).toBe(30_000); - expect(entry.timeout).toBe(35_000); - const args = fixture.children.at(-1)!.args; - const output = args[args.indexOf('-OutputPath') + 1]; - const lock = args[args.indexOf('-LockOutputPath') + 1]; - expect(output).toBeDefined(); - expect(lock).toBeDefined(); - expect(fs.readdirSync(path.join(fixture.root, 'bin'))).toEqual([]); - } - } finally { fixture.cleanup(); } -}); - -test.each([ - ['accepted output', { ...rejection, status: 0 }], - ['timeout after diagnostic', { ...rejection, status: null, signal: 'SIGTERM', error: new Error('ETIMEDOUT') }], - ['unrelated failure', { ...rejection, stderr: 'MSVC is unavailable' }], -] as const)('native path assertions reject %s and still clean their fixtures', (_name, result) => { - const fixture = registeredCases(result as typeof rejection); - try { - expect(fixture.cases).toHaveLength(5); - for (const entry of fixture.cases) { - expect(entry.run).toThrow(); - expect(fs.readdirSync(path.join(fixture.root, 'bin'))).toEqual([]); - } - } finally { fixture.cleanup(); } -}); diff --git a/test/cso-windows-docker.test.ts b/test/cso-windows-docker.test.ts deleted file mode 100644 index f5b3ae858..000000000 --- a/test/cso-windows-docker.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -/** - * /cso on Windows: docker.exe is discovered only under the known-folder - * install roots (resolved through [Environment]::GetFolderPath, not the - * process environment), by real path, with no symlink or junction on the way. - * lib/cso/docker.ts admits only unix:/// endpoints, so a trusted docker.exe - * yields the "native Windows Docker transport is not supported yet; static - * assessment only" outcome, never a run; anything else is refused. - */ -import { describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import { CsoError } from '../lib/cso/contracts'; -import { WINDOWS_DOCKER_ANCHOR, windowsDockerUnavailable, type WindowsDockerProbe } from '../lib/cso/windows-docker'; - -const ROOTS = ['C:\\Program Files', 'C:\\Program Files (x86)', 'C:\\Windows']; -const DESKTOP = 'C:\\Program Files\\Docker\\Docker\\resources\\bin\\docker.exe'; - -function probe(files: Record, opts: { reparse?: string[]; roots?: string[]; onPath?: string } = {}): WindowsDockerProbe { - const real = new Map(Object.entries(files).map(([k, v]) => [k.toLowerCase(), v])); - return { - knownFolders: () => opts.roots ?? ROOTS, - candidates: (roots) => [...(opts.onPath ? [opts.onPath] : []), ...roots.map((r) => `${r}\\Docker\\Docker\\resources\\bin\\docker.exe`)], - realpath: (p) => { - const hit = real.get(p.toLowerCase()); - if (!hit) throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); - return hit; - }, - isReparsePoint: (p) => (opts.reparse ?? []).some((r) => r.toLowerCase() === p.toLowerCase()), - }; -} - -function outcome(p: WindowsDockerProbe): string { - try { - windowsDockerUnavailable(p); - } catch (err) { - expect(err).toBeInstanceOf(CsoError); - return (err as Error).message; - } - throw new Error('windowsDockerUnavailable returned'); -} - -describe('/cso Windows Docker discovery', () => { - test('Docker Desktop under Program Files: not supported yet, static assessment only, with the anchor', () => { - const msg = outcome(probe({ [DESKTOP]: DESKTOP })); - expect(msg).toBe(`Docker found at ${DESKTOP}, but native Windows Docker transport is not supported yet; static assessment only. ${WINDOWS_DOCKER_ANCHOR}`); - expect(WINDOWS_DOCKER_ANCHOR).toBe('https://github.com/garrytan/gstack/blob/main/docs/troubleshooting.md#cso-windows-docker'); - }); - - test('a docker.exe on PATH in a user-writable directory is refused as outside the trusted install locations', () => { - const user = 'C:\\Users\\dev\\AppData\\Local\\bin\\docker.exe'; - const msg = outcome(probe({ [user]: user }, { onPath: user })); - expect(msg).toContain(`docker.exe at ${user} is outside the trusted install locations (${ROOTS.join(', ')})`); - expect(msg).toContain('A user-writable directory is untrusted for a child that carries registry credentials'); - expect(msg).toContain('Fix: install Docker Desktop under Program Files, or run /cso static-only'); - expect(msg).toContain('This is not overridable'); - expect(msg).toContain(WINDOWS_DOCKER_ANCHOR); - }); - - test('a sibling directory that only shares the prefix is not under Program Files', () => { - const evil = 'C:\\Program Files Evil\\docker.exe'; - expect(outcome(probe({ [evil]: evil }, { onPath: evil }))).toContain('is outside the trusted install locations'); - }); - - test('the real path decides: a Program Files path that resolves into a user directory is refused', () => { - const escaped = 'C:\\Users\\dev\\docker.exe'; - expect(outcome(probe({ [DESKTOP]: escaped }))).toContain(`docker.exe at ${DESKTOP} is outside the trusted install locations`); - }); - - test('a junction anywhere on the path is refused even when it resolves in place', () => { - const msg = outcome(probe({ [DESKTOP]: DESKTOP }, { reparse: ['C:\\Program Files\\Docker'] })); - expect(msg).toContain('reaches them through a symlink or junction'); - }); - - test('roots come from the known-folder probe: an unresolved probe trusts nothing', () => { - expect(outcome(probe({ [DESKTOP]: DESKTOP }, { roots: [], onPath: DESKTOP }))).toContain('outside the trusted install locations (none resolved)'); - }); - - test('no docker.exe anywhere keeps the not-installed error', () => { - expect(outcome(probe({}))).toBe('docker is not installed in a trusted system executable directory'); - }); - - test('the system probe asks PowerShell for the known folders, never the environment', () => { - const src = fs.readFileSync(path.join(import.meta.dir, '..', 'lib', 'cso', 'windows-docker.ts'), 'utf8'); - expect(src).toContain('[Environment]::GetFolderPath($_)'); - expect(src).toContain("'ProgramFiles','ProgramFilesX86','Windows'"); - expect(src).not.toMatch(/process\.env\.(ProgramFiles|ProgramW6432|"ProgramFiles)/); - expect(src).toContain('realpathSync.native'); - }); - - test('executable("docker") routes Windows through the discovery', () => { - const src = fs.readFileSync(path.join(import.meta.dir, '..', 'lib', 'cso', 'process.ts'), 'utf8'); - expect(src).toContain("if (process.platform === 'win32' && name.toLowerCase() === 'docker') windowsDockerUnavailable();"); - }); -}); diff --git a/test/cso-windows-launcher.test.ts b/test/cso-windows-launcher.test.ts deleted file mode 100644 index c32324cbd..000000000 --- a/test/cso-windows-launcher.test.ts +++ /dev/null @@ -1,504 +0,0 @@ -import { afterAll, beforeAll, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { createHash } from 'node:crypto'; -import { spawn, spawnSync } from 'node:child_process'; -import { identityStartedAtMs, processIdentitySource } from '../lib/cso/process-identity'; -import { createPrecisionLossCandidate } from './helpers/cso-ntfs-fixture'; - -const ROOT = path.resolve(import.meta.dir, '..'); -const windows = process.platform === 'win32'; -const required = process.env.GSTACK_CSO_WINDOWS_TESTS === '1'; -if (required && !windows) throw new Error('GSTACK_CSO_WINDOWS_TESTS=1 requires native Windows; emulation does not qualify the launcher.'); -let temporary = '', invocationCwd = '', launcher = '', core = '', marker = '', preload = '', publisher = '', buildStage = ''; -beforeAll(() => { - if (!windows) return; - const installed = path.join(ROOT, 'bin', 'gstack-cso-launcher.exe'); - if (!fs.existsSync(installed)) throw new Error('Native CSO launcher is missing; run bun run build:cso with MSVC first.'); - temporary = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'CSO launcher 空間 ')); - launcher = path.join(temporary, 'gstack-cso-launcher.exe'); - core = path.join(temporary, 'gstack-cso-core.exe'); - invocationCwd = path.join(temporary, 'audited cwd'); - fs.mkdirSync(invocationCwd); - marker = path.join(temporary, 'preload-ran'); - preload = path.join(temporary, 'preload.ts'); - fs.writeFileSync(preload, `import {writeFileSync} from 'node:fs'; writeFileSync(${JSON.stringify(marker)}, 'startup injection');`); - const source = path.join(temporary, 'core-fixture.ts'); - fs.writeFileSync(source, `import {existsSync,writeFileSync} from 'node:fs'; -const hold=process.argv.indexOf('--hold-until'); -if(hold>=0){writeFileSync(process.argv[hold+1],String(process.pid));while(!existsSync(process.argv[hold+2]))await Bun.sleep(10);writeFileSync(process.argv[hold+3],'exited');} -process.stdout.write(JSON.stringify({argv:process.argv.slice(2),env:process.env,cwd:process.cwd()})); -if(process.argv.includes('--exit-23'))process.exit(23);`); - const compiled = spawnSync(process.execPath, ['build', '--compile', '--no-compile-autoload-dotenv', '--no-compile-autoload-bunfig', '--no-compile-autoload-tsconfig', '--no-compile-autoload-package-json', source, '--outfile', core], { encoding: 'utf8', timeout: 60_000 }); - expect(compiled.status).toBe(0); - const digest = createHash('sha256').update(fs.readFileSync(core)).digest('hex'); - buildStage = fs.mkdtempSync(path.join(ROOT, 'bin', '.gstack-cso-stage.windows-launcher-test.')); - const stagedLauncher = path.join(buildStage, 'gstack-cso-launcher.exe'); - const stagedPublisher = path.join(buildStage, 'gstack-cso-publish-lock.exe'); - const native = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', - '-File', path.join(ROOT, 'scripts', 'build-cso-windows.ps1'), '-RepoRoot', ROOT, - '-OutputPath', stagedLauncher, '-LockOutputPath', stagedPublisher, '-CoreSha256', digest, '-GitExePath', Bun.which('git')!], - { encoding: 'utf8', timeout: 60_000 }); - if (native.status !== 0) throw new Error(`Fixture launcher compilation failed: ${native.stdout}${native.stderr}`); - fs.copyFileSync(stagedLauncher, launcher); - publisher = path.join(temporary, 'gstack-cso-publish-lock.exe'); - fs.copyFileSync(stagedPublisher, publisher); - fs.writeFileSync(path.join(temporary, '.gstack-cso-generation.lock'), ''); - fs.writeFileSync(path.join(temporary, '.gstack-cso-generation'), `${digest}\n`); - fs.rmSync(buildStage, { recursive: true, force: true }); buildStage = ''; -}, 140_000); -afterAll(() => { - if (buildStage) fs.rmSync(buildStage, { recursive: true, force: true }); - if (temporary) fs.rmSync(temporary, { recursive: true, force: true }); -}); - -function launchEnvironment(extra: Record = {}) { - return { ...process.env, HOME: temporary, GSTACK_HOME: path.join(temporary, 'state'), PATH: temporary, - NODE_OPTIONS: '--require=hostile', RUBYOPT: '-rhostile', PYTHONPATH: temporary, - GSTACK_CSO_SECRET_CANARY: 'must-not-cross-startup', ...extra }; -} - -function launch(args: string[], extra: Record = {}, file = launcher) { - return spawnSync(file, args, { - cwd: invocationCwd, encoding: 'utf8', timeout: 30_000, - env: launchEnvironment(extra), - }); -} - -async function waitForFile(file: string, timeout = 10_000) { - const deadline = Date.now() + timeout; - while (!fs.existsSync(file) && Date.now() < deadline) await Bun.sleep(10); - expect(fs.existsSync(file)).toBe(true); -} - -function publishProbe() { - return spawnSync(publisher, [temporary, process.execPath, '--version'], { encoding: 'utf8', timeout: 10_000 }); -} - -function pathIdentity(value: string) { - const stat = fs.statSync(value, { bigint: true }); - return { device: stat.dev, file: stat.ino }; -} - -function expectSuccessfulProcess(result: ReturnType, label: string) { - if (result.status === 0) return; - const bounded = (value: unknown) => String(value ?? '').slice(0, 8192); - throw new Error(`${label} failed: ${JSON.stringify({ - status: result.status, - signal: result.signal, - error: result.error?.message, - stdout: bounded(result.stdout), - stderr: bounded(result.stderr), - })}`); -} - -// Diagnostic snapshot of every lease artifact under a CSO state root. A failed -// native lease command embeds it in the assertion and keeps a copy outside the -// fixture so the exact owner/decision records survive cleanup. -function leaseRecords(root: string): string { - const records: unknown[] = []; - for (const leases of filesNamed(root, '.mutation-lock').map(lock => path.join(path.dirname(lock), '.mutation-lock-leases'))) { - let names: string[] = []; - try { names = fs.readdirSync(leases).sort(); } catch { continue; } - for (const name of names) { - const file = path.join(leases, name); - try { - const stat = fs.lstatSync(file, { bigint: true }), text = stat.size <= 4096n ? fs.readFileSync(file, 'utf8') : ''; - let pidAlive: boolean | undefined; - try { const value = JSON.parse(text), pid = value.ownerPid ?? value.pid; if (Number.isInteger(pid)) { try { process.kill(pid, 0); pidAlive = true; } catch (error: any) { pidAlive = error?.code === 'EPERM'; } } } catch {} - records.push({ file: path.relative(root, file), dev: String(stat.dev), ino: String(stat.ino), nlink: String(stat.nlink), size: String(stat.size), text, pidAlive }); - } catch (error: any) { records.push({ file: path.relative(root, file), error: error?.code ?? String(error) }); } - } - } - const serialized = JSON.stringify(records), keep = path.join(process.env.RUNNER_TEMP ?? os.tmpdir(), 'cso-lease-diagnostics'); - try { fs.mkdirSync(keep, { recursive: true }); fs.writeFileSync(path.join(keep, `${Date.now()}-${process.pid}.json`), serialized); } catch {} - return serialized.slice(0, 16_384); -} - -function expectLeaseCommand(result: ReturnType, label: string, root: string) { - try { expectSuccessfulProcess(result, label); } - catch (error: any) { throw new Error(`${error.message}\nlease records: ${leaseRecords(root)}`); } -} - -function filesNamed(root: string, name: string): string[] { - const found: string[] = []; - const walk = (directory: string) => { - let entries: fs.Dirent[]; - try { entries = fs.readdirSync(directory, { withFileTypes: true }); } catch { return; } - for (const entry of entries) { - const candidate = path.join(directory, entry.name); - if (entry.isSymbolicLink()) continue; - if (entry.isDirectory()) walk(candidate); - else if (entry.isFile() && entry.name === name) found.push(candidate); - } - }; - walk(root); - return found; -} - -describe('CSO native Windows build contract', () => { - test('Windows builds use MSVC with a static CRT and no Bun-hosted public launcher', () => { - const build = fs.readFileSync(path.join(ROOT, 'scripts/build-cso.sh'), 'utf8'); - const msvc = fs.readFileSync(path.join(ROOT, 'scripts/build-cso-windows.ps1'), 'utf8'); - expect(build).toContain('"$CSO_POWERSHELL" -NoProfile -NonInteractive'); - expect(build).toContain('build-cso-windows.ps1'); - expect(build).toContain('-OutputPath "$(cygpath -w "$CSO_STAGE_LAUNCHER")"'); - expect(build).toContain('-LockOutputPath "$(cygpath -w "$CSO_STAGE_LOCKER")"'); - expect(build).toContain('-CoreSha256 "$CSO_CORE_SHA256"'); - expect(build).toContain('-GitExePath "$(cygpath -aw "$CSO_WINDOWS_GIT")"'); - expect(build).toContain('CSO_PUBLISH_SHELL="$(cygpath -aw /usr/bin/bash.exe)"'); - expect(build).not.toContain('launcher-windows.ts'); - expect(fs.existsSync(path.join(ROOT, 'lib/cso/launcher-windows.ts'))).toBe(false); - expect(msvc).toContain('Launch-VsDevShell.ps1'); - expect(msvc).toContain('[switch]$CheckOnly'); - expect(msvc).toContain('Normal CSO Windows builds require staged outputs and a lowercase SHA-256 core binding.'); - expect(msvc).toContain("[System.IO.FileAttributes]::ReparsePoint"); - expect(msvc).not.toContain("Join-Path $RepoRoot 'bin\\gstack-cso-launcher.exe'"); - expect(msvc).toContain("Set-Content -LiteralPath $source"); - expect(msvc).toContain('-Arch amd64 -HostArch amd64 -SkipAutomaticLocation'); - expect(msvc).toContain('StartsWith($installationPrefix'); - expect(msvc).toContain('/MT'); - expect(msvc).toContain('/W4 /WX'); - expect(msvc).toContain('GSTACK_CSO_CORE_SHA256'); - expect(msvc).toContain('GSTACK_CSO_GIT_PATH'); - expect(msvc).toContain('/FI$binding'); - expect(msvc).toContain('if ($LASTEXITCODE -ne 0)'); - const processSource=fs.readFileSync(path.join(ROOT,'lib','cso','process.ts'),'utf8').replace(/\s+/g,''); - expect(processSource).toContain("includeNullPath=process.platform==='win32'?'/dev/null':nullPath"); - const launcherSource = fs.readFileSync(path.join(ROOT, 'lib/cso/launcher-windows.c'), 'utf8'); - expect(launcherSource).toContain('.gstack-cso-generation.lock'); - expect(launcherSource).toContain('.gstack-cso-generation'); - expect(launcherSource).toContain('GSTACK_CSO_CORE_SHA256'); - expect(launcherSource).toContain('BCryptOpenAlgorithmProvider'); - expect(launcherSource).toContain('MS_PRIMITIVE_PROVIDER'); - expect(launcherSource).toContain('sha256_handle(pinned_core'); - expect(launcherSource).toContain('#pragma comment(lib, "bcrypt.lib")'); - expect(launcherSource).toContain('PROC_THREAD_ATTRIBUTE_HANDLE_LIST'); - expect(launcherSource).toContain('joined_path'); - const childWait = launcherSource.indexOf('WaitForSingleObject(child.hProcess, INFINITE)'); - expect(childWait).toBeGreaterThan(0); - expect(launcherSource.lastIndexOf('CloseHandle(pinned_core)')).toBeGreaterThan(childWait); - expect(launcherSource.lastIndexOf('CloseHandle(generation_gate)')).toBeGreaterThan(childWait); - const publisherSource = fs.readFileSync(path.join(ROOT, 'lib/cso/publish-lock.c'), 'utf8'); - expect(publisherSource).toContain('joined_path'); - expect(publisherSource).toContain('GENERIC_READ | GENERIC_WRITE, 0'); - }); - - test('Windows CI runs the actual launcher tests rather than marking the platform supported from a source check', () => { - const workflow = Bun.YAML.parse(fs.readFileSync(path.join(ROOT, '.github/workflows/free-tests.yml'), 'utf8')) as any; - const job = workflow.jobs['cso-windows-launcher']; - expect(job['runs-on']).toBe('windows-latest'); - expect(job.steps.some((s: any) => s.run === 'bun run build:cso' && s.shell === 'bash')).toBe(true); - const smoke = job.steps.find((s: any) => s.run === 'bun run test:cso:windows'); - expect(smoke.env.GSTACK_CSO_WINDOWS_TESTS).toBe('1'); - expect(smoke['continue-on-error']).not.toBe(true); - }); - - // Each PowerShell invocation has its own deadline. A serial loop placed all - // five cold starts under Bun's default five-second timeout. - const pathEscapeCases = [ - ['launcher outside stage', (stage: string, outside: string) => [path.join(outside, 'gstack-cso-launcher.exe'), path.join(stage, 'gstack-cso-publish-lock.exe')]], - ['launcher in stage parent', (stage: string) => [path.join(stage, '..', 'gstack-cso-launcher.exe'), path.join(stage, 'gstack-cso-publish-lock.exe')]], - ['wrong launcher name', (stage: string) => [path.join(stage, 'wrong.exe'), path.join(stage, 'gstack-cso-publish-lock.exe')]], - ['lock outside stage', (stage: string, outside: string) => [path.join(stage, 'gstack-cso-launcher.exe'), path.join(outside, 'gstack-cso-publish-lock.exe')]], - ['wrong lock name', (stage: string) => [path.join(stage, 'gstack-cso-launcher.exe'), path.join(stage, 'wrong-lock.exe')]], - ] as const; - test.skipIf(!windows).each(pathEscapeCases)('Windows build rejects %s before invoking MSVC',(_name, outputs)=>{ - const script=path.join(ROOT,'scripts/build-cso-windows.ps1'),outside=fs.mkdtempSync(path.join(os.tmpdir(),'cso-bin-evil-')); - const stage=fs.mkdtempSync(path.join(ROOT,'bin','.gstack-cso-stage.path-test.')); - const [output,lock]=outputs(stage,outside),digest='a'.repeat(64); - try{ - const result=spawnSync('powershell.exe',['-NoProfile','-NonInteractive','-ExecutionPolicy','Bypass','-File',script,'-RepoRoot',ROOT,'-OutputPath',output,'-LockOutputPath',lock,'-CoreSha256',digest,'-GitExePath',Bun.which('git')!],{encoding:'utf8',timeout:30_000}); - expect(result.error).toBeUndefined();expect(result.signal).toBeNull();expect(result.status).not.toBeNull(); - expect(result.status).not.toBe(0);expect(`${result.stdout}${result.stderr}`).toContain('direct, non-reparse staging directory'); - }finally{fs.rmSync(stage,{recursive:true,force:true});fs.rmSync(outside,{recursive:true,force:true});} - },35_000); -}); - -(windows ? describe : describe.skip)('CSO native Windows startup', () => { - test('BUN_OPTIONS cannot execute a preload before the environment is scrubbed', () => { - const result = launch(['--version'], { BUN_OPTIONS: `--preload=${preload}` }); - expect(result.status).toBe(0); - expect(fs.existsSync(marker)).toBe(false); - const value = JSON.parse(result.stdout); - expect(value.argv).toEqual(['--version']); - expect(value.env.BUN_OPTIONS).toBeUndefined(); - expect(value.env.GSTACK_CSO_SECRET_CANARY).toBeUndefined(); - expect(value.env.NODE_OPTIONS).toBeUndefined(); - expect(value.env.GSTACK_HOME).toBe(path.join(temporary, 'state')); - expect(value.env.PATH).not.toBe(temporary); - expect(value.env.SystemRoot.toLowerCase()).toBe(process.env.SystemRoot!.toLowerCase()); - expect(pathIdentity(value.cwd)).toEqual(pathIdentity(temporary)); - expect(pathIdentity(value.cwd)).not.toEqual(pathIdentity(invocationCwd)); - }); - - test('BUN_BE_BUN cannot turn the public command into the Bun runtime', () => { - const result = launch(['--version'], { BUN_BE_BUN: '1' }); - expect(result.status).toBe(0); - const value = JSON.parse(result.stdout); - expect(value.argv).toEqual(['--version']); - expect(value.env.BUN_BE_BUN).toBeUndefined(); - }); - - test('preserves Unicode, empty, quoted, trailing-backslash and shell-looking arguments', () => { - const args = ['', '空間', 'with spaces', 'a"b', 'C:\\directory with spaces\\', '\\"', '& whoami', '%PATH%', 'line\nbreak']; - const result = launch(args); - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout).argv).toEqual(args); - }); - - test('forwards child exit status and fails closed on oversized inherited input', () => { - expect(launch(['--exit-23']).status).toBe(23); - const result = launch([], { GSTACK_HOME: 'x'.repeat(8193) }); - expect(result.status).toBe(69); - expect(result.stdout).toBe(''); - expect(result.stderr).toContain('environment input is too large'); - }); - - test('resolves launcher installation aliases before locating its sibling core', () => { - const alias = path.join(temporary, 'alias'); - fs.symlinkSync(temporary, alias, 'junction'); - const result = launch(['--version'], {}, path.join(alias, 'gstack-cso-launcher.exe')); - expect(result.status).toBe(0); - expect(JSON.parse(result.stdout).argv).toEqual(['--version']); - fs.unlinkSync(alias); - }); - - test('rejects a launcher/manifest generation mismatch before executing the core', () => { - const mismatched = path.join(temporary, 'mismatched generation'); - fs.mkdirSync(mismatched); - fs.copyFileSync(launcher, path.join(mismatched, 'gstack-cso-launcher.exe')); - fs.copyFileSync(core, path.join(mismatched, 'gstack-cso-core.exe')); - fs.writeFileSync(path.join(mismatched, '.gstack-cso-generation.lock'), ''); - fs.writeFileSync(path.join(mismatched, '.gstack-cso-generation'), `${'0'.repeat(64)}\n`); - const result = launch(['--version'], {}, path.join(mismatched, 'gstack-cso-launcher.exe')); - expect(result.status).toBe(69); - expect(result.stdout).toBe(''); - expect(result.stderr).toContain('generations do not match'); - }); - - test('rejects changed core bytes even when the generation manifest is unchanged', () => { - const tampered = path.join(temporary, 'tampered core'); - fs.mkdirSync(tampered); - const tamperedLauncher = path.join(tampered, 'gstack-cso-launcher.exe'); - const tamperedCore = path.join(tampered, 'gstack-cso-core.exe'); - fs.copyFileSync(launcher, tamperedLauncher); - fs.copyFileSync(core, tamperedCore); - fs.appendFileSync(tamperedCore, Buffer.from([0])); - fs.writeFileSync(path.join(tampered, '.gstack-cso-generation.lock'), ''); - fs.copyFileSync(path.join(temporary, '.gstack-cso-generation'), path.join(tampered, '.gstack-cso-generation')); - const result = launch(['--version'], {}, tamperedLauncher); - expect(result.status).toBe(69); - expect(result.stdout).toBe(''); - expect(result.stderr).toContain('digest does not match'); - }); - - test('the inherited generation gate survives launcher termination until the core exits', async () => { - const ready = path.join(temporary, 'held-core.ready'), release = path.join(temporary, 'held-core.release'), exited = path.join(temporary, 'held-core.exited'); - const running = spawn(launcher, ['--hold-until', ready, release, exited], { cwd: invocationCwd, env: launchEnvironment(), stdio: 'ignore' }); - try { - await waitForFile(ready); - const launcherExited = new Promise(resolveExit => running.once('exit', () => resolveExit())); - running.kill('SIGKILL'); - await launcherExited; - expect(publishProbe().status).toBe(73); - fs.writeFileSync(release, 'release'); - const deadline = Date.now() + 10_000; let result = publishProbe(); - while (result.status === 73 && Date.now() < deadline) { await Bun.sleep(20); result = publishProbe(); } - expect(result.status).toBe(0); - } finally { - fs.writeFileSync(release, 'release'); - if (!running.killed) running.kill('SIGKILL'); - const deadline = Date.now() + 5_000; - while (!fs.existsSync(exited) && Date.now() < deadline) await Bun.sleep(10); - } - }, 30_000); - - test('a missing core never falls back to a PATH executable or Bun', () => { - const missing = path.join(temporary, 'missing core'); - fs.mkdirSync(missing); - const copy = path.join(missing, 'gstack-cso-launcher.exe'); - fs.copyFileSync(launcher, copy); - fs.writeFileSync(path.join(missing, '.gstack-cso-generation.lock'), ''); - fs.copyFileSync(path.join(temporary, '.gstack-cso-generation'), path.join(missing, '.gstack-cso-generation')); - const result = launch(['--version'], {}, copy); - expect(result.status).toBe(69); - expect(result.stdout).toBe(''); - expect(result.stderr).toContain('trusted compiled helper is missing'); - }); - - test('the actual helper finds trusted Git and stores state under USERPROFILE without HOME', () => { - const repository=path.join(temporary,'actual repository'),profile=path.join(temporary,'profile'); - fs.mkdirSync(repository);fs.mkdirSync(profile); - const git='C:\\Program Files\\Git\\cmd\\git.exe',gitEnv={...process.env,HOME:profile}; - for(const args of [['init','-q'],['config','user.email','fixture@example.test'],['config','user.name','Fixture']] as string[][]){const result=spawnSync(git,args,{cwd:repository,encoding:'utf8',env:gitEnv,timeout:10_000});expect(result.status).toBe(0);} - fs.writeFileSync(path.join(repository,'app.js'),'console.log("safe")\n'); - for(const args of [['add','app.js'],['commit','-qm','fixture']] as string[][]){const result=spawnSync(git,args,{cwd:repository,encoding:'utf8',env:gitEnv,timeout:10_000});expect(result.status).toBe(0);} - const actual=path.join(ROOT,'bin','gstack-cso-launcher.exe'),env={...process.env,HOME:'',GSTACK_HOME:'',CLAUDE_PLUGIN_ROOT:'',CLAUDE_PLUGIN_DATA:'',USERPROFILE:profile,PATH:temporary,NODE_OPTIONS:'--require=hostile'}; - const doctor=spawnSync(actual,['doctor','--repo',repository],{cwd:repository,encoding:'utf8',env,timeout:30_000});expect(doctor.status).toBe(0);expect(JSON.parse(doctor.stdout).downloads).toBe(false); - const started=spawnSync(actual,['start','--repo',repository,'--offline'],{cwd:repository,encoding:'utf8',env,timeout:30_000});expectSuccessfulProcess(started,'gstack-cso start');expect(JSON.parse(started.stdout).schemaVersion).toBe(3);expect(fs.existsSync(path.join(profile,'.gstack','security','cso'))).toBe(true); - }, 120_000); - - test('NTFS high file IDs survive repeated native commands and ambiguous old decisions remain blocked', () => { - const repository=path.join(temporary,'lease lifecycle repository'),profile=path.join(temporary,'lease lifecycle profile'); - fs.mkdirSync(repository);fs.mkdirSync(profile); - const git='C:\\Program Files\\Git\\cmd\\git.exe',gitEnv={...process.env,HOME:profile}; - for(const args of [['init','-q'],['config','user.email','fixture@example.test'],['config','user.name','Fixture']] as string[][]){const result=spawnSync(git,args,{cwd:repository,encoding:'utf8',env:gitEnv,timeout:10_000});expect(result.status).toBe(0);} - fs.writeFileSync(path.join(repository,'app.js'),'console.log("fixture")\n'); - for(const args of [['add','app.js'],['commit','-qm','fixture']] as string[][]){const result=spawnSync(git,args,{cwd:repository,encoding:'utf8',env:gitEnv,timeout:10_000});expect(result.status).toBe(0);} - const actual=path.join(ROOT,'bin','gstack-cso-launcher.exe'),env={...process.env,HOME:'',GSTACK_HOME:'',CLAUDE_PLUGIN_ROOT:'',CLAUDE_PLUGIN_DATA:'',USERPROFILE:profile,PATH:temporary}; - const command=(args:string[])=>spawnSync(actual,args,{cwd:repository,encoding:'utf8',env,timeout:30_000}),submission=path.join(profile,'submission.json'); - fs.writeFileSync(submission,'{}\n'); - for(let i=0;i<3;i++){ - const started=command(['start','--repo',repository,'--offline']);expectSuccessfulProcess(started,'gstack-cso start'); - const run=JSON.parse(started.stdout),dir=path.join(profile,'.gstack','security','cso',run.repoId,run.runId),leases=path.join(dir,'.mutation-lock-leases'); - const initialized=command(['resume',run.runId]);expectSuccessfulProcess(initialized,'gstack-cso initialize mutation lease'); - expect(fs.realpathSync(leases).startsWith(fs.realpathSync(profile)+path.sep)).toBe(true); - if(i===0){ - const churn=path.join(leases,'churn');let inode=0n; - for(let attempt=0;attempt<1024;attempt++){ - fs.writeFileSync(churn,'x');inode=fs.lstatSync(churn,{bigint:true}).ino;fs.unlinkSync(churn); - if(inode>BigInt(Number.MAX_SAFE_INTEGER))break; - } - expect(inode).toBeGreaterThan(BigInt(Number.MAX_SAFE_INTEGER)); - } - const inspected=command(['inspect',run.runId]);expectSuccessfulProcess(inspected,'gstack-cso inspect'); - expect(JSON.parse(inspected.stdout).report.status).toBe('running'); - const read=command(['read',run.runId,'app.js']);expectSuccessfulProcess(read,'gstack-cso read');expect(read.stdout).toContain('fixture'); - const history=command(['history',run.runId]);expectSuccessfulProcess(history,'gstack-cso history'); - const submitted=command(['submit',run.runId,submission]);expectSuccessfulProcess(submitted,'gstack-cso submit'); - const resumed=command(['resume',run.runId]);expectSuccessfulProcess(resumed,'gstack-cso resume'); - const finished=command(['finish',run.runId]);expectSuccessfulProcess(finished,'gstack-cso finish'); - expect(JSON.parse(finished.stdout).completeness).not.toBe('complete'); - const report=JSON.parse(fs.readFileSync(path.join(dir,'report.json'),'utf8')); - expect(report.coverage.some((entry:any)=>entry.status==='not_assessed')).toBe(true); - expect(fs.readdirSync(leases)).toEqual([]); - if(i!==2)continue; - const token='d'.repeat(32),candidate=path.join(leases,`${token}.json`),decision=path.join(leases,`${token}.decision`); - for(const rounded of [false,true]){ - const selected=createPrecisionLossCandidate(candidate,JSON.stringify({pid:2147483647,token,createdAt:0})+'\n'); - const stat=fs.lstatSync(candidate,{bigint:true}),record={schemaVersion:1,token,kind:'ticket',ticket:'0000000000000001',candidateDev:String(stat.dev),candidateIno:rounded?String(Number(stat.ino)):String(stat.ino),ownerPid:2147483647,ownerCreatedAt:0,publisherPid:2147483647,createdAt:0}; - expect(stat.ino).toBe(selected); - expect(stat.ino).toBeGreaterThan(BigInt(Number.MAX_SAFE_INTEGER)); - expect(String(Number(stat.ino))).not.toBe(String(stat.ino)); - fs.writeFileSync(decision,JSON.stringify(record)+'\n'); - const result=command(['resume',run.runId]);expect(result.status).not.toBe(0); - if(rounded){ - expect(record.candidateIno).not.toBe(String(stat.ino));expect(result.stderr).toContain('UNSAFE_PATH'); - expect(fs.existsSync(candidate)).toBe(true);expect(fs.existsSync(decision)).toBe(true); - fs.unlinkSync(decision);fs.unlinkSync(candidate); - }else{ - expect(result.stderr).toContain('INVALID_SCHEMA'); - expect(fs.existsSync(candidate)).toBe(false);expect(fs.existsSync(decision)).toBe(false); - } - } - const next=command(['start','--repo',repository,'--offline']);expectSuccessfulProcess(next,'gstack-cso start after legacy state'); - expect(JSON.parse(next.stdout).runId).not.toBe(run.runId); - } - }, 180_000); - - test('#2894 the win32 process identity source reads real process start times', async () => { - const own = processIdentitySource.read(process.pid), started = identityStartedAtMs(own ?? ''); - expect(own).toMatch(/^win32:\d+$/); - expect(processIdentitySource.read(process.pid)).toBe(own!); - expect(started!).toBeLessThanOrEqual(Date.now()); - expect(started!).toBeGreaterThan(Date.now() - 3_600_000); - await Bun.sleep(20); - const child = spawn(process.execPath, ['-e', 'setTimeout(()=>{},30000)'], { stdio: 'ignore' }); - try { - const identity = processIdentitySource.read(child.pid!); - expect(identity).toMatch(/^win32:\d+$/); - expect(identity).not.toBe(own!); - expect(identityStartedAtMs(identity!)!).toBeGreaterThanOrEqual(started!); - } finally { child.kill(); } - expect(processIdentitySource.read(2147483647)).toBeUndefined(); - }); - - test('#2894 lease sequence: repeated commands, a legacy record elsewhere, and recycled or dead owners never brick start', async () => { - const repository=path.join(temporary,'issue 2894 repository'),other=path.join(temporary,'issue 2894 other repository'),profile=path.join(temporary,'issue 2894 profile'); - for(const directory of [repository,other,profile])fs.mkdirSync(directory); - const git='C:\\Program Files\\Git\\cmd\\git.exe',gitEnv={...process.env,HOME:profile}; - for(const repo of [repository,other]){ - for(const args of [['init','-q'],['config','user.email','fixture@example.test'],['config','user.name','Fixture']] as string[][]){const result=spawnSync(git,args,{cwd:repo,encoding:'utf8',env:gitEnv,timeout:10_000});expect(result.status).toBe(0);} - fs.writeFileSync(path.join(repo,'app.js'),'console.log("fixture")\n');fs.writeFileSync(path.join(repo,'other.js'),'console.log("other")\n'); - for(const args of [['add','app.js','other.js'],['commit','-qm','fixture']] as string[][]){const result=spawnSync(git,args,{cwd:repo,encoding:'utf8',env:gitEnv,timeout:10_000});expect(result.status).toBe(0);} - } - const actual=path.join(ROOT,'bin','gstack-cso-launcher.exe'),env={...process.env,HOME:'',GSTACK_HOME:'',CLAUDE_PLUGIN_ROOT:'',CLAUDE_PLUGIN_DATA:'',USERPROFILE:profile,PATH:temporary},state=path.join(profile,'.gstack','security','cso'); - const command=(args:string[],cwd=repository)=>spawnSync(actual,args,{cwd,encoding:'utf8',env,timeout:30_000}); - const step=(args:string[],label:string,cwd=repository)=>{const result=command(args,cwd);expectLeaseCommand(result,label,state);return result;}; - const started=JSON.parse(step(['start','--repo',repository,'--offline'],'start').stdout),dir=path.join(state,started.repoId,started.runId),leases=path.join(dir,'.mutation-lock-leases'); - for(const [args,label] of [[['resume',started.runId],'resume'],[['inspect',started.runId],'inspect'],[['read',started.runId,'app.js'],'read app.js'],[['read',started.runId,'other.js'],'read other.js'],[['history',started.runId],'history'],[['inspect',started.runId],'inspect again']] as [string[],string][])step(args,label); - expect(fs.readdirSync(leases)).toEqual([]); - // A record left by gstack <= 1.88.0 in another repository's run (lossy NTFS file ID) stays - // blocked for that run, but start for any repository still succeeds. - const otherRun=JSON.parse(step(['start','--repo',other,'--offline'],'start other',other).stdout),otherLeases=path.join(state,otherRun.repoId,otherRun.runId,'.mutation-lock-leases'); - step(['resume',otherRun.runId],'resume other',other); - const legacy='d'.repeat(32),legacyCandidate=path.join(otherLeases,`${legacy}.json`),legacyDecision=path.join(otherLeases,`${legacy}.decision`); - createPrecisionLossCandidate(legacyCandidate,JSON.stringify({pid:2147483647,token:legacy,createdAt:1})+'\n'); - const legacyStat=fs.lstatSync(legacyCandidate,{bigint:true}); - fs.writeFileSync(legacyDecision,JSON.stringify({schemaVersion:1,token:legacy,kind:'ticket',ticket:'0000000000000001',candidateDev:String(legacyStat.dev),candidateIno:String(Number(legacyStat.ino)),ownerPid:2147483647,ownerCreatedAt:1,publisherPid:2147483647,createdAt:1})+'\n'); - const next=JSON.parse(step(['start','--repo',repository,'--offline'],'start with a legacy record in another repository').stdout); - expect(next.runId).not.toBe(started.runId); - const blocked=command(['resume',otherRun.runId],other);expect(blocked.status).not.toBe(0);expect(blocked.stderr).toContain('UNSAFE_PATH'); - expect(fs.existsSync(legacyCandidate)).toBe(true);expect(fs.existsSync(legacyDecision)).toBe(true); - // A recycled PID: the recorded owner is gone and an unrelated process that started after the - // lease was written now holds that PID. A plain dead PID is reclaimed the same way. - const nextLeases=path.join(state,next.repoId,next.runId,'.mutation-lock-leases'); - step(['resume',next.runId],'resume next'); - const createdAt=Date.now();await Bun.sleep(2_500); - const holder=spawn(process.execPath,['-e','setTimeout(()=>{},60000)'],{stdio:'ignore'}); - try{ - for(const [token,pid] of [['e'.repeat(32),holder.pid!],['f'.repeat(32),2147483647]] as [string,number][]){ - const candidate=path.join(nextLeases,`${token}.json`),decision=path.join(nextLeases,`${token}.decision`); - fs.writeFileSync(candidate,JSON.stringify({pid,token,createdAt})+'\n'); - const stat=fs.lstatSync(candidate,{bigint:true}); - fs.writeFileSync(decision,JSON.stringify({schemaVersion:1,token,kind:'ticket',ticket:'0000000000000001',candidateDev:String(stat.dev),candidateIno:String(stat.ino),ownerPid:pid,ownerCreatedAt:createdAt,publisherPid:pid,createdAt})+'\n'); - step(['inspect',next.runId],`inspect after ${pid===2147483647?'dead':'recycled'} owner`); - expect(fs.existsSync(candidate)).toBe(false);expect(fs.existsSync(decision)).toBe(false); - } - expect(fs.readdirSync(nextLeases)).toEqual([]); - }finally{holder.kill();} - }, 180_000); - - test('the actual helper rejects source mutation during snapshot capture without certifying a report', async () => { - const repository=path.join(temporary,'racing repository'),profile=path.join(temporary,'race profile'),padding=path.join(repository,'padding'),target=path.join(repository,'zzzz-race-target.js'); - fs.mkdirSync(repository);fs.mkdirSync(profile);fs.mkdirSync(padding); - const git='C:\\Program Files\\Git\\cmd\\git.exe',gitEnv={...process.env,HOME:profile}; - for(const args of [['init','-q'],['config','user.email','fixture@example.test'],['config','user.name','Fixture']] as string[][]){const result=spawnSync(git,args,{cwd:repository,encoding:'utf8',env:gitEnv,timeout:10_000});expect(result.status).toBe(0);} - const sourceBytes=128*1024,stable=Buffer.alloc(sourceBytes,0x61),changed=Buffer.alloc(sourceBytes,0x62); - fs.writeFileSync(target,stable); - for(let index=0;index<192;index++)fs.writeFileSync(path.join(padding,`${String(index).padStart(4,'0')}.js`),stable); - for(const args of [['add',path.basename(target)],['commit','-qm','fixture']] as string[][]){const result=spawnSync(git,args,{cwd:repository,encoding:'utf8',env:gitEnv,timeout:30_000});expect(result.status).toBe(0);} - - const actual=path.join(ROOT,'bin','gstack-cso-launcher.exe'),env={...process.env,HOME:'',GSTACK_HOME:'',CLAUDE_PLUGIN_ROOT:'',CLAUDE_PLUGIN_DATA:'',USERPROFILE:profile,PATH:temporary},state=path.join(profile,'.gstack','security','cso'); - const child=spawn(actual,['start','--repo',repository,'--offline'],{cwd:repository,env,stdio:['ignore','pipe','pipe']}); - let stdout='',stderr='',closed=false; - child.stdout.on('data',chunk=>{stdout=(stdout+String(chunk)).slice(-8192);}); - child.stderr.on('data',chunk=>{stderr=(stderr+String(chunk)).slice(-8192);}); - const terminal=new Promise<{code:number|null;error?:string}>(resolve=>{ - child.once('error',error=>{closed=true;resolve({code:null,error:error.message});}); - child.once('close',code=>{closed=true;resolve({code});}); - }); - const markerDeadline=Date.now()+30_000;let mutations=0,outcome:{code:number|null;error?:string}|undefined; - try{ - while(!closed&&!filesNamed(state,'history-status.json').length&&Date.now(){const root=fs.mkdtempSync(path.join(os.tmpdir(),'cso-witness-'));roots.push(root);return root;}; -const H=(value:string)=>sha256(value); -const tap=`TAP version 13 -# Subtest: legitimate control remains available -ok 1 - legitimate control remains available - --- - duration_ms: 1 - ... -1..1 -# tests 1 -# suites 0 -# pass 1 -# fail 0 -# cancelled 0 -# skipped 0 -# todo 0 -`; -afterEach(()=>{for(const root of roots.splice(0))fs.rmSync(root,{recursive:true,force:true});}); - -function stable(phase:'before'|'after'):Omit{ - return{phase,runId:'witness-run',findingId:'a'.repeat(32),policyHash:H('policy'),auditPolicyHash:H('audit-policy'),runtime:{image:`runtime@sha256:${'b'.repeat(64)}`,verifierImage:`runtime@sha256:${'b'.repeat(64)}`,platform:'linux/amd64',profile:'node'},runner:{testToolchain:'runtime',startPlanHash:H('start'),testPlanHash:H('tests'),commandsHash:H(canonical([{executable:'/usr/local/bin/node',args:['--test','--test-reporter=tap','./app.test.js']}])),minimumPassingTestsHash:H(canonical([1]))},sourceHash:H(`source-${phase}`),dependencyHash:H(`dependency-${phase}`),configurationHash:H(`configuration-${phase}`),requestHash:H('request'),patchHash:H('patch'),harnessHash:H('harness'),assertionHash:H('assertions'),fixturesHash:H('fixtures')}; -} - -describe('CSO authenticated external assertion witness',()=>{ - test('a challenge lives as long as its attempt, never past the longest attempt bound',()=>{ - const now=Date.now(),lifetime=(deadline:number)=>{const binding=new AssertionWitnessSession(temporary(),deadline).handle(stable('before')).binding;return Date.parse(binding.expiresAt)-Date.parse(binding.issuedAt);}; - expect(lifetime(now+300_000)).toBeLessThanOrEqual(300_000); - expect(lifetime(now+MAX_VERIFICATION_ATTEMPT_MS)).toBeGreaterThan(300_000); - expect(lifetime(now+2*MAX_VERIFICATION_ATTEMPT_MS)).toBeLessThanOrEqual(MAX_VERIFICATION_ATTEMPT_MS); - const binding=new AssertionWitnessSession(temporary(),now+60_000).handle(stable('before')).binding; - expect(()=>validateAssertionWitnessBinding({...binding,expiresAt:new Date(Date.parse(binding.issuedAt)+MAX_VERIFICATION_ATTEMPT_MS+1).toISOString()})).toThrow('lifetime exceeds'); - }); - test('rejects forged, stale, and mismatched receipts after a valid out-of-process attestation',async()=>{ - const work=temporary(),session=new AssertionWitnessSession(work,Date.now()+60_000),handle=session.handle(stable('before')),observation:VerificationObservation={booted:true,legitimate:true,security:'intended_failure',existingTests:false,output:'external verifier passed',inputHash:''},command={executable:'/usr/local/bin/node',args:['--test','--test-reporter=tap','./app.test.js']}; - const receipt=await handle.attest(observation,[{command,code:0,output:tap,minimumPassingTests:1}]); - expect(receipt).toMatchObject({externalAssertionsPassed:true,diagnosticTestsPassed:true,binding:{phase:'before',policyHash:H('policy'),runner:{testToolchain:'runtime'}}});expect(validateStoredAssertionWitnessReceipt(receipt).keyId).toBe(session.keyId); - expect(()=>handle.validate({...receipt,signature:`${receipt.signature.slice(0,-1)}${receipt.signature.endsWith('0')?'1':'0'}`},observation)).toThrow('signature'); - const other=session.handle(stable('after'));expect(()=>other.validate(receipt,observation)).toThrow('does not bind'); - expect(()=>handle.validate(receipt,observation,Date.parse(receipt.binding.expiresAt)+1)).toThrow('stale'); - expect(()=>handle.validate(receipt,{...observation,legitimate:false})).toThrow('observation'); - }); - - test('the native launcher routes the private compiled witness child protocol',()=>{ - const root=temporary(),launcher=path.resolve(import.meta.dir,'../bin',process.platform==='win32'?'gstack-cso-launcher.exe':'gstack-cso-launcher'),core=path.resolve(import.meta.dir,'../bin',process.platform==='win32'?'gstack-cso-core.exe':'gstack-cso-core'); - const direct=spawnSync(core,['--version'],{cwd:root,encoding:'utf8',env:{...process.env,GSTACK_CSO_GENERATION_LOCK_FD:''},timeout:30_000});expect(direct.status).not.toBe(0);expect(direct.stderr).toContain('Direct use of the internal CSO payload is unsupported'); - const pair=generateKeyPairSync('ed25519'),privateKey=pair.privateKey.export({format:'pem',type:'pkcs8'}).toString(),publicKey=pair.publicKey.export({format:'der',type:'spki'}).toString('hex'),now=Date.now(),command={executable:'/usr/local/bin/node',args:['--test','--test-reporter=tap','./app.test.js']},binding={schemaVersion:1,protocol:'gstack-cso-assertion-witness-v1',nonce:H('compiled nonce'),issuedAt:new Date(now).toISOString(),expiresAt:new Date(now+60_000).toISOString(),...stable('before')},observation:VerificationObservation={booted:true,legitimate:true,security:'intended_failure',existingTests:false,output:'compiled external verifier passed',inputHash:''},child=spawnSync(launcher,['__cso-assertion-witness'],{cwd:root,encoding:'utf8',env:{HOME:root,GSTACK_HOME:path.join(root,'state'),PATH:'/usr/bin:/bin'},input:JSON.stringify({privateKey,publicKey,binding,observation,executions:[{command,code:0,output:tap,minimumPassingTests:1}]}),timeout:30_000});expect(child.status).toBe(0);const receipt=validateStoredAssertionWitnessReceipt(JSON.parse(child.stdout));expect(receipt).toMatchObject({publicKey,externalAssertionsPassed:true,diagnosticTestsPassed:true,binding:{nonce:H('compiled nonce'),phase:'before'}}); - }); - - test('a test file that prints a forged TAP summary is rejected as a path wrapper',()=>{ - const root=temporary(),file=path.join(root,'forged.test.js'),node=Bun.which('node');if(!node)throw new Error('Node is required for the CSO Node witness fixture'); - fs.writeFileSync(file,"console.log('# Subtest: forged pass')\nconsole.log('ok 1 - forged pass')\nconsole.log('1..1')\nconsole.log('# tests 1')\nconsole.log('# pass 1')\nconsole.log('# fail 0')\nconsole.log('# cancelled 0')\n"); - const command={executable:node,args:['--test','--test-reporter=tap','./forged.test.js']},result=spawnSync(node,command.args,{cwd:root,encoding:'utf8',timeout:30_000});expect(result.status).toBe(0);expect(result.stdout).toContain('# \\# Subtest: forged pass');expect(testExecutionPassed(command,result.status??-1,result.stdout+result.stderr,1)).toBe(false); - }); - - test('valid external assertions issue a runtime-tested bundle with replay-stable witness evidence',async()=>{ - const runDir=temporary(),snapshot=path.join(runDir,'snapshot');fs.mkdirSync(snapshot);const files:Record={'package.json':JSON.stringify({private:true,scripts:{start:'node app.js',test:'node --test'}})+'\n','app.js':'module.exports = "vulnerable"\n','app.test.js':"const test=require('node:test');test('legitimate control remains available',()=>{});\n"};for(const [name,body] of Object.entries(files))fs.writeFileSync(path.join(snapshot,name),body); - const start=canonicalStartPlan(snapshot,'node',3456),tests=canonicalTestPlan(snapshot,'node'),request:any={findingId:'a'.repeat(32),runtimeProfile:'node',port:3456,start:start.command,legitimate:[{name:'legitimate control',path:'/control',method:'GET',expected:{status:200,includes:'CONTROL_OK'}}],security:{name:'unauthorized secret is denied',path:'/security',method:'GET',expected:{status:403,includes:'DENIED'},vulnerable:{status:200,includes:'SECRET'}},existingTests:tests.commands,fixtures:{},boundaryFiles:['app.js'],testFiles:tests.files,changes:[{path:'app.js',beforeSha256:sha256(files['app.js']),after:'module.exports = "fixed"\n',effect:'source'}],review:{reviewer:'independent-reviewer',independent:true,rootCauseRepaired:true,featurePreserved:true,boundaryMocks:false,rationale:'The policy is repaired while the external control remains available.',reviewedPatchHash:''}};request.review.reviewedPatchHash=patchHash(request); - const entries=Object.entries(files).map(([name,body])=>({path:name,originalHash:sha256(body),executionHash:sha256(body),bytes:Buffer.byteLength(body),mode:0o600})),manifest:any={version:3,root:snapshot,createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+86_400_000).toISOString(),headCommit:'c'.repeat(40),originalHash:H('original'),executionHash:treeHash(snapshot),entries},runtime:any={id:'node',stack:'node',image:`runtime@sha256:${'b'.repeat(64)}`,platform:'linux/amd64'}; - let executionCount=0;const executor={observe:async(_source:string,phase:'before'|'after',received:any,_runtime:any,_verifier:any,_work:string,_control:string,_execution:any,evidence:any,witness:any)=>{const observation:VerificationObservation={booted:true,legitimate:true,security:phase==='before'?'intended_failure':'pass',existingTests:false,output:`external ${phase} assertions passed`,inputHash:''},output=tap.replace('duration_ms: 1',`duration_ms: ${++executionCount}`),receipt=await witness.attest(observation,[{command:received.existingTests[0],code:0,output,minimumPassingTests:evidence.minimumPassingTests[0]}]);return{observation:{...observation,existingTests:receipt.diagnosticTestsPassed,inputHash:witness.binding.harnessHash},witness:receipt};}}; - const first=await verifyRepair({runId:'witness-run',runDir,manifest,rawRequest:request,runtime,verifier:runtime,policyHash:H('policy'),auditPolicyHash:H('audit-policy'),archives:[],executor});expect(first.manifest).toMatchObject({result:'runtime_tested',assertionAssurance:'authenticated_out_of_process',testCompletionAssurance:'self_reported',reviewAssurance:'self_attested'});expect(first.bundle.witness?.before.publicKey).toBe(first.bundle.witness?.after.publicKey);expect(validateRepairBundle(first.bundle,first.bundle.id,snapshot,manifest).id).toBe(first.bundle.id);expect(fs.existsSync(path.join(runDir,'bundles',`${first.bundle.id}.json`))).toBe(true);const forged=structuredClone(first.bundle),signature=forged.witness!.before.signature;forged.witness!.before.signature=`${signature.slice(0,-1)}${signature.endsWith('0')?'1':'0'}`;expect(()=>validateRepairBundle(forged,forged.id,snapshot,manifest)).toThrow('signature');const reused=structuredClone(first.bundle);reused.witness!.after=reused.witness!.before;expect(()=>validateRepairBundle(reused,reused.id,snapshot,manifest)).toThrow('identity'); - const replay=await verifyRepair({runId:'witness-run',runDir,manifest,rawRequest:request,runtime,verifier:runtime,policyHash:H('policy'),auditPolicyHash:H('audit-policy'),archives:[],executor,persist:false});expect(replay.manifest.witnessHash).not.toBe(first.manifest.witnessHash);expect(assertionWitnessReplayHash(replay.bundle.witness!)).toBe(assertionWitnessReplayHash(first.bundle.witness!));expect(replay.bundle.witness?.before.binding.nonce).not.toBe(first.bundle.witness?.before.binding.nonce);const immutable=(value:any)=>{const {id:_,createdAt:__,before:___,after:____,witnessHash:______,...rest}=value;return rest;};expect(canonical(immutable(replay.manifest))).toBe(canonical(immutable(first.manifest))); - }); - - test('a signed forged reporter diagnostic cannot mint a runtime-tested bundle',async()=>{ - const root=temporary(),session=new AssertionWitnessSession(root,Date.now()+60_000),handle=session.handle(stable('before')),observation:VerificationObservation={booted:true,legitimate:true,security:'intended_failure',existingTests:false,output:'external verifier passed',inputHash:''},command={executable:'/usr/local/bin/node',args:['--test','--test-reporter=tap','./app.test.js']},forged="# Subtest: app.test.js\nok 1 - app.test.js\n1..1\n# tests 1\n# pass 1\n# fail 0\n# cancelled 0\n"; - const receipt=await handle.attest(observation,[{command,code:0,output:forged,minimumPassingTests:1}]);expect(receipt.externalAssertionsPassed).toBe(true);expect(receipt.diagnosticTestsPassed).toBe(false);expect(receipt.executions[0].reportedPassed).toBe(false); - }); -}); - -describe('CSO assertion witness child command selection',()=>{ - test('a Bun host runs the witness module directly with the scrubbed POSIX environment',()=>{ - expect(assertionWitnessChildCommand({execPath:'/usr/local/bin/bun',platform:'linux',modulePath:'/repo/lib/cso/witness.ts'})).toEqual({ - file:'/usr/local/bin/bun',args:['/repo/lib/cso/witness.ts','--child'],env:{PATH:'/usr/bin:/bin',LANG:'C.UTF-8',LC_ALL:'C.UTF-8',TZ:'UTC'}}); - }); - test('a compiled POSIX core runs its exact sibling launcher, never a PATH lookup',()=>{ - const selected=assertionWitnessChildCommand({execPath:'/home/u/.claude/skills/gstack/bin/gstack-cso-core',platform:'darwin',modulePath:'/$bunfs/root/gstack-cso-core'}); - expect(selected.file).toBe('/home/u/.claude/skills/gstack/bin/gstack-cso-launcher'); - expect(selected.args).toEqual(['__cso-assertion-witness']); - expect(selected.env.PATH).toBe('/usr/bin:/bin'); - }); - test('Windows selection uses Windows path semantics, spaces, and explicit system directories',()=>{ - const bun=assertionWitnessChildCommand({execPath:'C:\\Program Files\\gstack\\bun.exe',platform:'win32',modulePath:'C:\\gstack\\lib\\cso\\witness.ts'}); - expect(bun).toEqual({file:'C:\\Program Files\\gstack\\bun.exe',args:['C:\\gstack\\lib\\cso\\witness.ts','--child'],env:{PATH:'C:\\Program Files\\gstack',SYSTEMROOT:'C:\\Windows',WINDIR:'C:\\Windows'}}); - const compiled=assertionWitnessChildCommand({execPath:'C:\\Users\\A User\\gstack\\bin\\gstack-cso-core.exe',platform:'win32',modulePath:'B:\\~BUN\\root\\gstack-cso-core.exe',systemRoot:'D:\\Win',windir:'D:\\Win'}); - expect(compiled).toEqual({file:'C:\\Users\\A User\\gstack\\bin\\gstack-cso-launcher.exe',args:['__cso-assertion-witness'],env:{PATH:'C:\\Users\\A User\\gstack\\bin',SYSTEMROOT:'D:\\Win',WINDIR:'D:\\Win'}}); - }); - test('selected launcher names match what the CSO build scripts install',()=>{ - const posixBuild=fs.readFileSync(path.resolve(import.meta.dir,'../scripts/build-cso.sh'),'utf8'),windowsBuild=fs.readFileSync(path.resolve(import.meta.dir,'../scripts/build-cso-windows.ps1'),'utf8'); - expect(posixBuild).toContain('bin/gstack-cso-core$CSO_EXE');expect(posixBuild).toContain('bin/gstack-cso-launcher$CSO_EXE');expect(windowsBuild).toContain("'gstack-cso-launcher.exe'"); - expect(path.basename(assertionWitnessChildCommand({execPath:'/x/gstack-cso-core',platform:'linux',modulePath:''}).file)).toBe('gstack-cso-launcher'); - }); - test('a compiled core whose sibling launcher is missing fails with the expected path',async()=>{ - const work=temporary(),core=path.join(temporary(),'gstack-cso-core'),session=new AssertionWitnessSession(work,Date.now()+60_000,core),handle=session.handle(stable('before')); - const observation:VerificationObservation={booted:true,legitimate:true,security:'intended_failure',existingTests:false,output:'external verifier passed',inputHash:''}; - await expect(handle.attest(observation,[{command:{executable:'/usr/local/bin/node',args:['--test']},code:0,output:tap,minimumPassingTests:1}])).rejects.toThrow(`Assertion witness launcher is missing: ${path.join(path.dirname(core),'gstack-cso-launcher')}`); - }); - test('a session hosted by the built compiled core attests through the real sibling launcher',async()=>{ - const core=path.resolve(import.meta.dir,'../bin',process.platform==='win32'?'gstack-cso-core.exe':'gstack-cso-core'); - if(!fs.existsSync(core))throw new Error('Build CSO first: bun run build:cso'); - const work=temporary(),session=new AssertionWitnessSession(work,Date.now()+60_000,core),handle=session.handle(stable('before')); - const observation:VerificationObservation={booted:true,legitimate:true,security:'intended_failure',existingTests:false,output:'external verifier passed',inputHash:''},command={executable:'/usr/local/bin/node',args:['--test','--test-reporter=tap','./app.test.js']}; - const receipt=await handle.attest(observation,[{command,code:0,output:tap,minimumPassingTests:1}]); - expect(receipt).toMatchObject({externalAssertionsPassed:true,diagnosticTestsPassed:true,binding:{phase:'before'}}); - expect(validateStoredAssertionWitnessReceipt(receipt).keyId).toBe(session.keyId); - }); -}); diff --git a/test/docs-only-workflow.test.ts b/test/docs-only-workflow.test.ts index f1f20e0de..cef4a9b16 100644 --- a/test/docs-only-workflow.test.ts +++ b/test/docs-only-workflow.test.ts @@ -35,7 +35,7 @@ describe('docs-scope', () => { }); describe('free-tests', () => { - const suites = ['free-suite', 'typecheck', 'quick-bun-default', 'cso-macos-launcher', 'macos-named-regressions', 'cso-windows-launcher', 'cso-docker-integration']; + const suites = ['free-suite', 'typecheck', 'quick-bun-default', 'macos-named-regressions']; test('every suite job skips only when docs-scope succeeded and said docs-only', () => { for (const name of suites) { expect([name, needs(free[name])]).toEqual([name, expect.arrayContaining(['reuse', 'docs-scope'])]); diff --git a/test/fixtures/cso-e2e/diff-mode-45216872389-sub1.json b/test/fixtures/cso-e2e/diff-mode-45216872389-sub1.json deleted file mode 100644 index f3b44cf93..000000000 --- a/test/fixtures/cso-e2e/diff-mode-45216872389-sub1.json +++ /dev/null @@ -1,183 +0,0 @@ -{ - "application": { - "actors": [ - "unauthenticated network client", - "authenticated user holding a bearer session token (alice, bob)", - "payment provider sending webhook events (intended)" - ], - "assets": [ - "paid-plan entitlement state (payments Map)", - "premium revenue report", - "bearer session tokens", - "service availability" - ], - "entrypoints": [ - "POST /webhook/payment (webhook.js:11-17, unauthenticated)", - "GET /reports/premium (webhook.js:5-10, bearer auth + paid-plan check)" - ], - "tenantBoundaries": [ - "per-account entitlement keyed by accountId; account identity from sessions Map" - ], - "sensitiveOperations": [ - "granting paid plan via payments.set on webhook event", - "serving premium revenue report" - ], - "invariants": [ - "Only authenticated, provider-signed payment events may change an account's plan", - "Premium report is served only to accounts that actually paid", - "Malformed requests must not terminate the server process" - ] - }, - "findings": [ - { - "title": "Unauthenticated payment webhook lets anyone grant any account a paid plan", - "rootCause": "POST /webhook/payment applies payment events with no provider signature/secret verification, no replay protection, and no amount/account validation", - "location": { - "path": "webhook.js", - "line": 15, - "symbol": "payments.set (webhook handler)" - }, - "advisoryIds": [], - "severity": "high", - "confidence": "high", - "confidenceRationale": "Entire request chain is in one file read in full: no middleware, no framework, package.json has no dependencies; the handler reads the raw body, parses it and writes plan:'paid' for the attacker-chosen accountId without any check.", - "evidence": "supported", - "attackerControl": "JSON body fields accountId and amount on an unauthenticated POST to /webhook/payment", - "impact": "Payment bypass / broken function-level authorization: attacker unlocks paid entitlement (premium revenue report) for their own or any account without paying; can also set arbitrary amount values.", - "scenario": "Bob (valid session 'bob-token', unpaid) sends POST /webhook/payment with body {\"accountId\":\"bob\",\"amount\":0}. Server responds 'payment applied'. Bob then sends GET /reports/premium with Authorization: Bearer bob-token and receives the premium revenue report instead of 402.", - "trace": [ - "http.createServer request handler (webhook.js:4)", - "route check POST /webhook/payment (webhook.js:11)", - "body accumulation + JSON.parse (webhook.js:12-14)", - "payments.set(event.accountId, {plan:'paid'}) (webhook.js:15)", - "entitlement consumed by GET /reports/premium plan check (webhook.js:8)" - ], - "references": [ - "webhook.js:11-17", - "webhook.js:8", - "OWASP Top 10:2025 A01 Broken Access Control / A07 Authentication Failures", - "OWASP API Security Top 10:2023 API5 Broken Function Level Authorization, API6 Unrestricted Access to Sensitive Business Flows", - "ASVS v5.0.0-8.2.2" - ], - "recommendation": "Verify the provider signature over the raw request body with a shared secret (HMAC, constant-time compare) before parsing; reject events with stale timestamps and dedupe by event ID; derive account and amount from the verified provider event (or fetch it from the provider API) and confirm amount/plan match an expected price before granting entitlement; reject unsigned requests with 401.", - "challenge": { - "reviewer": "sequential challenge; independent agent unavailable", - "independent": false, - "mode": "sequential_fallback", - "callers": "Only caller is the single http.createServer handler in webhook.js; app.js is a console.log baseline and package.json declares no dependencies or scripts, so no middleware or wrapper exists in the snapshot.", - "controls": "Checked for signature headers (none read), shared secret/env var (none), IP allowlist (none), auth on webhook route (none; sessions lookup only on GET /reports/premium), amount/accountId validation (none).", - "counterevidence": "A deployed reverse proxy/gateway could enforce webhook auth, but no infrastructure or deployment config exists in the repo and the server listens on port 3000 on all interfaces; such a control is unverified, not evidence of safety.", - "conclusion": "Finding survives: attacker-controlled body reaches the entitlement write with no inspected control blocking it." - } - }, - { - "title": "Malformed webhook body crashes the server process (unhandled JSON.parse exception)", - "rootCause": "JSON.parse on attacker-supplied body inside the request 'end' event listener has no try/catch; the thrown SyntaxError is an uncaught exception that terminates the Node process", - "location": { - "path": "webhook.js", - "line": 14, - "symbol": "JSON.parse(body)" - }, - "advisoryIds": [], - "severity": "medium", - "confidence": "high", - "confidenceRationale": "Exception is thrown in an EventEmitter listener outside the createServer callback's synchronous frame; no process 'uncaughtException' handler or try/catch exists in the snapshot, so Node's default behavior is process exit.", - "evidence": "supported", - "attackerControl": "Raw body of an unauthenticated POST /webhook/payment (e.g. the bytes 'x')", - "impact": "Single unauthenticated request causes denial of service and, because entitlement state is held only in memory, wipes all recorded payments (paying users lose access until events are replayed).", - "scenario": "Attacker sends POST /webhook/payment with body 'not-json'; JSON.parse throws in the 'end' listener; Node prints the uncaught SyntaxError and exits; all clients lose service and the payments Map is lost.", - "trace": [ - "POST /webhook/payment (webhook.js:11)", - "req.on('end') listener (webhook.js:13)", - "JSON.parse(body) throws (webhook.js:14)" - ], - "references": [ - "webhook.js:12-17", - "OWASP Top 10:2025 A10 Mishandling of Exceptional Conditions", - "ASVS v5.0.0-16.5.3" - ], - "recommendation": "Wrap parsing in try/catch and respond 400 on invalid JSON; validate the parsed object's shape; verify the signature before parsing; run under a supervisor and persist entitlement state durably.", - "challenge": { - "reviewer": "sequential challenge; independent agent unavailable", - "independent": false, - "mode": "sequential_fallback", - "callers": "Same single handler; no wrapping error domain or framework error middleware.", - "controls": "No try/catch, no process.on('uncaughtException'), no body parser with error handling, no process supervisor config in repo.", - "counterevidence": "An external supervisor may restart the process (unverified, not in repo); restart would still lose in-memory payment state and allows repeated crashing.", - "conclusion": "Finding survives; severity medium (availability plus loss of entitlement state, unauthenticated, trivially repeatable)." - } - }, - { - "title": "Unbounded webhook request body accumulation enables memory exhaustion", - "rootCause": "Request body chunks are concatenated into a string with no size limit before parsing", - "location": { - "path": "webhook.js", - "line": 12, - "symbol": "req.on('data') body += chunk" - }, - "advisoryIds": [], - "severity": "low", - "confidence": "medium", - "confidenceRationale": "No length check in code; Node http imposes no default body-size limit. Practical impact depends on runtime memory limits and Node's requestTimeout, which were not observed at runtime.", - "evidence": "supported", - "attackerControl": "Size and streaming rate of an unauthenticated POST body", - "impact": "Memory exhaustion / degraded service; superseded in practice by the trivial crash in the JSON.parse finding.", - "scenario": "Attacker opens several concurrent POST /webhook/payment requests each streaming hundreds of MB; the process accumulates them in memory until OOM.", - "trace": [ - "POST /webhook/payment (webhook.js:11)", - "req.on('data') concatenation (webhook.js:12)" - ], - "references": [ - "webhook.js:12", - "OWASP API Security Top 10:2023 API4 Unrestricted Resource Consumption", - "ASVS v5.0.0-2.4.1" - ], - "recommendation": "Enforce a maximum body size (check Content-Length and running byte count; destroy the request with 413 when exceeded) and authenticate before buffering.", - "challenge": { - "reviewer": "sequential challenge; independent agent unavailable", - "independent": false, - "mode": "sequential_fallback", - "callers": "Same single handler.", - "controls": "No Content-Length check, no byte counter, no server.maxRequestsPerSocket or body limit configured.", - "counterevidence": "Node 18+ default requestTimeout (300s) bounds slow requests in time but not size; a reverse proxy body limit may exist but is not in the repo.", - "conclusion": "Survives as low severity." - } - }, - { - "title": "Static bearer session tokens hardcoded in source", - "rootCause": "Session tokens for named users are literal constants in webhook.js rather than issued secrets", - "location": { - "path": "webhook.js", - "line": 2, - "symbol": "sessions" - }, - "advisoryIds": [], - "severity": "low", - "confidence": "low", - "confidenceRationale": "Tokens appear to be synthetic placeholders; open question is whether this sessions map is used outside a fixture/demo. If deployed as-is, anyone with source access can authenticate as alice or bob.", - "evidence": "hypothesis", - "attackerControl": "Authorization header value copied from the repository", - "impact": "Account impersonation for alice/bob on GET /reports/premium (still gated by paid plan, which the webhook finding bypasses).", - "scenario": "Reader of the repository sends Authorization: Bearer alice-token and is treated as alice.", - "trace": [ - "GET /reports/premium (webhook.js:5)", - "sessions.get(token) (webhook.js:6)" - ], - "references": [ - "webhook.js:2", - "webhook.js:6", - "OWASP Top 10:2025 A07 Authentication Failures" - ], - "recommendation": "Issue random, expiring session tokens at login and store them server-side (hashed); never commit token values. Confirm whether these tokens are used in any deployed environment.", - "challenge": { - "reviewer": "sequential challenge; independent agent unavailable", - "independent": false, - "mode": "sequential_fallback", - "callers": "sessions is read only at webhook.js:6.", - "controls": "No login/issuance flow, expiry, or env-based override exists.", - "counterevidence": "Token strings look like test placeholders; no deployment evidence. Kept as hypothesis rather than dropped because no code disproves deployed use.", - "conclusion": "Hypothesis: confirm whether this file is deployed with these tokens." - } - } - ] -} diff --git a/test/fixtures/cso-e2e/diff-mode-45216872389-sub2.json b/test/fixtures/cso-e2e/diff-mode-45216872389-sub2.json deleted file mode 100644 index d9d45c690..000000000 --- a/test/fixtures/cso-e2e/diff-mode-45216872389-sub2.json +++ /dev/null @@ -1,136 +0,0 @@ -{ - "coverage": [ - { - "domain": "application-model", - "scope": "default", - "status": "assessed", - "method": "static read of all 3 snapshot files via helper", - "gaps": [], - "exclusions": [], - "evidence": [ - "Actors, assets, entrypoints, invariants derived from webhook.js (changed), app.js, package.json; submitted application model" - ] - }, - { - "domain": "attack-surface", - "scope": "default", - "status": "assessed", - "method": "static census of HTTP routes in diff and affected paths", - "gaps": [], - "exclusions": [], - "evidence": [ - "Two routes: POST /webhook/payment (unauthenticated), GET /reports/premium (bearer + plan); 404 fallthrough; server listens on port 3000 all interfaces" - ] - }, - { - "domain": "secrets", - "scope": "default", - "status": "assessed", - "method": "manual review of redacted current source and helper-retained history for base..HEAD (1 commit)", - "gaps": [], - "exclusions": [], - "evidence": [ - "No provider credential prefixes found; hardcoded synthetic session tokens recorded as hypothesis finding; Gitleaks not run (offline static run, no qualified scanner profile requested)" - ] - }, - { - "domain": "dependencies", - "scope": "default", - "status": "assessed", - "method": "manifest review", - "gaps": [], - "exclusions": [], - "evidence": [ - "package.json declares no dependencies, scripts or lockfile; only node:http builtin used; OSV not run (offline)" - ] - }, - { - "domain": "ci-cd", - "scope": "default", - "status": "not_applicable", - "method": "snapshot inventory review", - "gaps": [], - "exclusions": [], - "evidence": [ - "No CI/CD workflow files in snapshot inventory (3 files: app.js, package.json, webhook.js)" - ] - }, - { - "domain": "infrastructure", - "scope": "default", - "status": "not_applicable", - "method": "snapshot inventory review", - "gaps": [], - "exclusions": [], - "evidence": [ - "No Dockerfile, IaC, or deployment configuration in snapshot; deployed gateway controls unknown and noted in finding challenges" - ] - }, - { - "domain": "integrations", - "scope": "default", - "status": "assessed", - "method": "full trace of payment webhook handler", - "gaps": [], - "exclusions": [], - "evidence": [ - "Webhook lacks signature, timestamp/replay, idempotency, amount validation; recorded as high finding; OWASP API 2023 API4/API5/API6 checked" - ] - }, - { - "domain": "llm-agentic-mcp", - "scope": "default", - "status": "not_applicable", - "method": "snapshot inventory review", - "gaps": [], - "exclusions": [], - "evidence": [ - "No LLM, agent, or MCP code in snapshot" - ] - }, - { - "domain": "skill-supply-chain", - "scope": "default", - "status": "not_applicable", - "method": "snapshot inventory review", - "gaps": [], - "exclusions": [], - "evidence": [ - "No skill definitions, hooks, plugins, or agent configuration in snapshot" - ] - }, - { - "domain": "owasp-2025", - "scope": "default", - "status": "assessed", - "method": "OWASP Top 10:2025 mapping against diff and affected paths; ASVS 5.0.0 selected requirements", - "gaps": [], - "exclusions": [], - "evidence": [ - "A01/A07 webhook authorization (finding), A10 unhandled JSON.parse (finding), A06 business flow (amount unvalidated), A05 no injection sinks, A02 no debug surface; ASVS 8.2.2, 16.5.3, 2.4.1 failed; 1.2.4/1.2.5/1.3.6/5.3.2 not applicable" - ] - }, - { - "domain": "stride", - "scope": "default", - "status": "assessed", - "method": "STRIDE over webhook and premium report trust transitions", - "gaps": [], - "exclusions": [], - "evidence": [ - "Spoofing: forged payment provider (finding); Tampering: arbitrary amount/account; DoS: crash and unbounded body (findings); Elevation: unpaid to paid entitlement; Info disclosure: premium report via forged entitlement; Repudiation: no event logging" - ] - }, - { - "domain": "data-classification", - "scope": "default", - "status": "assessed", - "method": "static data flow review", - "gaps": [], - "exclusions": [], - "evidence": [ - "Restricted: bearer session tokens (hardcoded); Confidential: premium revenue report, payment amounts held in memory only; no PII persistence or logging observed" - ] - } - ] -} diff --git a/test/fixtures/cso-eval/README.md b/test/fixtures/cso-eval/README.md deleted file mode 100644 index 22a9b90e4..000000000 --- a/test/fixtures/cso-eval/README.md +++ /dev/null @@ -1,301 +0,0 @@ -# CSO vulnerable/fixed evaluation corpus - -This corpus contains **40 immutable source pairs**: ten each for Node, Bun, -Python, and Rails. `manifest.json` pins both source hashes, expected root cause, -location, severity, and evaluation eligibility. `materialize.ts` deterministically -creates either member of each pair. Changing source requires an explicit corpus -manifest update; the loader rejects silent drift. - -The ten families are SQL injection, command injection, path traversal, SSRF, -object authorization, tenant isolation, HTML injection, open redirects, mass -assignment, and resource exhaustion. Every app exposes `/action` and `/health` on -loopback port 8000. The SSRF fixtures additionally create a disposable loopback -status service on port 8001. Exhaustion assertions request 250 small records to -prove missing admission; they do not attempt to exhaust the evaluator. - -Node uses standard modules, including `node:sqlite`; Bun uses `bun:sqlite`; Python -uses its standard library. Rails fixtures contain an actual Rails application -and controller, with native SQLite and Puma dependencies. Their common lock was -generated by Ruby 3.2.8 / Bundler 2.6.7 from public registry metadata only. The -exact command, lock hash, and 68 public archive hashes are recorded in -`rails-lock-provenance.json`. No fixture application was run to generate this -lock. The recorded archive hashes must be checked by runtime qualification; a -successful resolver run does not establish cold-start support. - -Authentication is an explicit fixture precondition: the test adapter establishes -member-1 in tenant-a. The assessment scope is the selected endpoint's behavior. -This prevents an intentionally constant test identity from being mistaken for a -production authentication design. Application README files state legitimate -behavior; they never include attack payloads or expected finding labels. - -## Preparing matched evaluations - -From the repository root, export the v2 generated skill tree and build a -canonical portable payload for each version before pinning an exact model ID: - -```sh -mkdir -p .context/cso-v2-source -git archive origin/main cso/SKILL.md cso/sections | \ - tar -x -C .context/cso-v2-source --strip-components=1 -bun scripts/cso-eval.ts payload --version v2 \ - --skill-dir .context/cso-v2-source --output .context/cso-v2.payload.md -bun scripts/cso-eval.ts payload --version v3 \ - --skill-dir cso --output .context/cso-v3.payload.md -bun scripts/cso-eval.ts matrix \ - --model EXACT_MODEL_ID --host codex \ - --v2-payload .context/cso-v2.payload.md \ - --v3-payload .context/cso-v3.payload.md \ - --output .context/cso-eval-matrix.json -bun scripts/cso-eval.ts materialize node-sql-injection vulnerable .context/cso-eval-app -``` - -The full matrix contains 960 cells: 40 pairs × two source variants × two modes × -two skill versions × three repetitions. Each matched pair uses identical source, -model, host, and per-mode wall-clock budget. Daily runs have 600 seconds; -comprehensive runs have 1800 seconds. Each portable payload embeds the exact -generated `SKILL.md`, `sections/manifest.json`, and every generated section -listed by that manifest. The payload builder rejects missing or unlisted -generated sections and a mismatched major version. The matrix hashes the whole -payload, so a change to any section byte changes the pinned skill identity. The -commands above make no model calls and execute no fixture application. - -Prepare consumable one-cell jobs and compile the generic producer runner: - -```sh -bun build --compile \ - --no-compile-autoload-dotenv \ - --no-compile-autoload-bunfig \ - --no-compile-autoload-tsconfig \ - --no-compile-autoload-package-json \ - scripts/cso-eval-producer.ts --outfile .context/cso-eval-producer -bun scripts/cso-eval.ts prepare .context/cso-eval-matrix.json \ - --v2-payload .context/cso-v2.payload.md \ - --v3-payload .context/cso-v3.payload.md \ - --output .context/cso-eval-jobs -``` - -### Trusted five-artifact producer unit - -The `.context/cso-eval-producer` command above creates a preparation artifact; -ordinary `bun run build` does not distribute the private producer. For a paid -run, start from one clean checkout and build a five-artifact staging unit in one -session: - -```sh -stage="$(mktemp -d)" -bun run build:cso -bun build --compile \ - --no-compile-autoload-dotenv \ - --no-compile-autoload-bunfig \ - --no-compile-autoload-tsconfig \ - --no-compile-autoload-package-json \ - scripts/cso-eval-producer.ts --outfile "$stage/cso-eval-producer" -install -m 0555 bin/gstack-cso-launcher bin/gstack-cso-core \ - bin/gstack-cso-watchdog "$stage/" -install -m 0444 bin/.gstack-cso-generation "$stage/.gstack-cso-generation" -(cd "$stage" && (sha256sum cso-eval-producer gstack-cso-launcher \ - gstack-cso-core gstack-cso-watchdog .gstack-cso-generation 2>/dev/null || \ - shasum -a 256 cso-eval-producer gstack-cso-launcher gstack-cso-core \ - gstack-cso-watchdog .gstack-cso-generation)) -sudo install -d -o root -g root -m 0755 /opt/gstack-cso-producer -sudo install -o root -g root -m 0555 "$stage/cso-eval-producer" \ - "$stage/gstack-cso-launcher" "$stage/gstack-cso-core" \ - "$stage/gstack-cso-watchdog" /opt/gstack-cso-producer/ -sudo install -o root -g root -m 0444 "$stage/.gstack-cso-generation" \ - /opt/gstack-cso-producer/.gstack-cso-generation -``` - -Run `/opt/gstack-cso-producer/cso-eval-producer` as an unprivileged account. -Its startup check rejects missing, linked, writable, or non-root-owned members -and a writable or linked ancestor directory. Every receipt records the SHA-256 -and byte length of all five artifacts in one installation identity; collection -rejects a batch if those identities differ. Preserve the printed hashes with -the release evidence and move or replace the complete unit together. - -`prepare` creates a trusted `schedule.json` and 960 independent directories. -It initializes each generated application as a one-commit Git repository. Each -job has exactly one source variant and one versioned, complete instruction -payload. Root-skill pointers resolve only to sections embedded in that payload; -the producer must never load CSO instructions from `~/.claude`, another host -install, this source checkout, or the other version's payload. The generic runner -is compiled separately and contains no corpus generator, fixed alternative, -case oracle, or schedule. These preparation commands still make zero model calls. - -Run each job on a fresh producer filesystem that contains only that job, the -compiled runner, the authenticated provider CLI, and the reviewed executable -gstack helper/runtime files. Do not install or copy any CSO `SKILL.md`, carved -section, generated skill tree, schedule, this repository checkout, -sibling jobs, fixed alternatives, or evaluator code to that filesystem. The -producer runner reads its opaque control file into memory and deletes it before -the agent process starts. That file never names the case, variant, version, or -repetition: it is `{schemaVersion: 2, cellRef, skill, source, execution}`, where -`cellRef` is the matrix cell id and `execution` holds only the mode, model, host, -budget, source and skill hashes, and platform. The receipt binds `cellRef` and -`inputHash`, and `collect` rebuilds each cell from the matrix, so neither file -tells an agent with root on its cell VM which answer it is graded against. Copy the selected hash-named directory as the literal path -`/producer/job`; `/producer` must contain only `job`. Put the runner in a system -tool directory and use a separate receipt mount. The runner rejects the full -prepared batch layout, extra files beside `job`, a reused job with prior state, -and receipt paths under `/producer`. The dedicated VM/container must ensure -other host paths do not contain evaluator inputs; a local directory layout does -not constrain a tool-using agent's absolute filesystem access. - -The receipt must be written outside the isolated producer root: - -```sh -mkdir -m 700 /receipts -CSO_EVAL_PAID=1 /opt/gstack-cso-producer/cso-eval-producer run \ - /producer/job/producer-input.json /receipts/CELL_ID.json --execute-paid -``` - -Both the environment variable and flag are required because this is the only -command in the workflow that makes a paid model call. It reuses the repository's -Claude, Codex, and Gemini provider adapters and starts a fresh CLI process for -each cell. The requested model, normalized effective model, identity source, -timeout, output, token counts, pricing-table cost estimate, tool-call count, and -latency are bound into a hashed receipt. `provider_reported` means the CLI -resolved a different concrete ID; `requested_pin` means the adapter returned -the exact requested ID or had to fall back to that exact CLI pin. Use a concrete -model ID rather than an alias. The current adapters return only completed runs, -so first-useful-result latency is explicitly unmeasured rather than copied from -total latency. If a job is interrupted after its input is consumed, restore it -from the trusted prepared copy; never synthesize a receipt. - -After returning receipts to the trusted evaluator, collect them against the -matrix and schedule: - -```sh -bun scripts/cso-eval.ts collect .context/cso-eval-matrix.json \ - .context/cso-eval-jobs/schedule.json .context/cso-eval-receipts \ - .context/cso-eval-producer-batch.json -``` - -Collection makes no model calls. It rejects unknown, duplicate, changed, or -wrong-input receipts and reports scheduled/submitted/missing denominators for -every v2/v3 and daily/comprehensive group. It rejects an effective-model mismatch -between matched v2/v3 cells, leaving the source receipts available for diagnosis -and a clean rerun. The collected batch stores a compact receipt index and hashes; -raw transcripts remain in the private receipt directory for adjudication. Cost -in this batch is clearly labeled a -pricing-table estimate; only a host-billed amount may populate `EvalResult`'s -host-cost field. - -The producer host needs Git, the chosen authenticated CLI, and reviewed gstack -executables and catalogs without their skill source tree. Its CSO instruction -bytes come only from the cell payload, never the installed skill or installed -carved sections. Comprehensive cells additionally need a local Docker daemon, -the exact qualified helper/runtime catalog pair, public dependency inputs or -verified cache hits, and the authenticated out-of-process assertion witness. The runtime -image workflow currently emits native staging evidence with private accuracy, -held-out repair, canary, and watchdog gates still pending. Such evidence can -measure setup failures, but it cannot support a release-qualifying tested repair -until those gates and catalog promotion are complete. - -## Private oracle boundary - -`test/helpers/cso-eval-oracles.ts` belongs to the **trusted evaluator**. It contains -the legitimate controls, initial security assertions, alternate held-out -assertions, and non-vacuous repair judge. It is never copied into materialized -source. The fixed alternative, expected manifest, and this evaluator module must -remain unavailable to producing agents throughout their sessions. - -A separate directory alone does not restrict a host agent's file access. The -evaluation host must enforce this boundary with scoped tools or an isolated -producer filesystem and test it with the `held-out-oracle-visibility` gate. If it -cannot do that, report the gate as `not_run` and do not claim held-out -qualification. Product execution containment does not automatically isolate the -hosted producing agent. - -Only trusted runtime observations enter `judgeRepair`. Boot and legitimate -controls must pass on the original; the exact security assertion must fail for -the intended reason. The patched app must pass that assertion, all held-out -assertions, controls, and existing tests with unchanged verification inputs. -Independent root-cause/feature review is mandatory; boundary-replacing mocks or -disabled functionality fail certification. A producer's `tested` or -`runtime_tested` label is never an oracle result. - -`collect` preserves producer claims and performance receipts; it does not turn -them into `EvalResult`. The independent evaluator must inspect the retained CSO -report/bundle, execute the private assertions, and write finding judgments and -workflow outcomes. This separation is deliberate: automatically copying agent -claims into the trusted result contract would fabricate verification. - -## Scoring and release gates - -```sh -bun scripts/cso-eval.ts score .context/cso-eval-matrix.json \ - .context/cso-eval-producer-batch.json .context/trusted-cso-results.json \ - .context/cso-qualification.json -``` - -The result contract is `EvalResult` in `scripts/cso-eval.ts`. The independent -evaluator supplies finding judgments, the matching `producerReceiptHash`, and -hashes of private evidence. The release scoring command requires a complete -producer batch, checks its integrity and effective-model parity, and rejects any -trusted result that is not bound to that cell's receipt. Recheck -success additionally requires a distinct current-source observation and its -source hash. Correct alternative patches need not match the reference fix's -text. Keep actual transcripts and reports in private evaluation state; do not -commit them beside the fixtures. - -Each metric includes its numerator and denominator. Duplicate findings cannot -inflate true positives. Fixed variants contribute false positives. Missing and -setup-blocked supported scenarios remain misses in recall and workflow rates. -Hypotheses do not become supported discoveries; v2 legacy review evidence cannot -become v3 reproduced, runtime-tested, or tested evidence. Unknown usage remains -unknown, and wall-clock budgets are not represented as model-spend caps. - -The scorer checks 95% daily precision, 80% comprehensive high/critical recall, -no aggregate high/critical recall regression against v2, all core cold starts, -zero falsely certified runtime-tested repairs (claims on declared instrumentation -count in neither direction; an incidental claim needs a passing replay of its -signed bundle), and a correct held-out repair in -every application stack. It also requires complete matched results, mandatory -reports, containment/canary receipts, and enforced oracle separation. Missing -evaluations return -`unmeasured` or `partial`, never passing release gates. - -## Release profile, private corpora, and two architectures - -The matrix above is the `full` profile: matched v2/v3 cells, three repetitions, -and one producer installation. This public corpus is a development set, because -its oracles are public. A private evaluator scores a held-out corpus with the -same layout through the same code: - -- **Injected corpus.** `defineEvalCorpus(manifest, sourceFiles)` accepts a - manifest with this `manifest.json` layout and a deterministic source generator, - checks every variant's source hash, and refuses the public corpus version. - `prepareEvalJobs(..., corpus)` and `materializeCase(..., corpus)` materialize - from it; `createEvalMatrix`, `validateMatrix`, `collectProducerReceipts`, - `scoreCollectedEval`, and `createEvalBaseline` take its manifest. Its oracles - use the `PrivateOracle` shape from `test/helpers/cso-eval-oracles.ts` and stay - in the private evaluator. -- **`release` profile.** `createEvalMatrix({ profile: 'release', skillHashes: { v3 }, - platforms: { daily, comprehensive } })` builds v3-only cells with one repetition. - Daily cells run on one platform; each comprehensive case is fixed to - `linux/amd64` or `linux/arm64`. Every cell carries its `platform`, and the - producer refuses a cell whose platform differs from its host. -- **Per-platform identities.** One batch may hold both architectures. Each - platform must have exactly one producer installation and one provider binary; - platforms must use different installations with identical embedded catalogs - and identical provider family, policy revision, version, and arguments. All - cells must report one effective model. -- **External v2 baseline.** A `baseline` profile matrix holds v2 comprehensive - cells with the release platform assignment. `createEvalBaseline` turns its - complete, fully adjudicated, receipt-bound results into an `EvalBaseline` - record whose `baselineHash` covers the corpus hash, model, host, budget, - platform assignment, v2 payload hash, producer batch, effective model, provider - policy and version, and each case's outcome. A release matrix pins that hash - when it is created; scoring then requires the exact record and the same - effective model and provider policy. Without a pinned baseline the - regression gate stays `unmeasured`. - -A matrix, batch, or result from one corpus never validates against another: -the matrix binds the corpus hash, so a mixed-corpus batch is rejected. The -`collect`, `score`, and `baseline` commands accept `--corpus-manifest `, -and `score` accepts `--baseline `. The `full` profile's matrix bytes and -gates are unchanged. - -The free accounting tests use clearly labeled synthetic observations to test the -scorer. They are **not measured agent performance**. No paid comparison, fixture -cold-start qualification, or containment qualification is claimed by this corpus. diff --git a/test/fixtures/cso-eval/manifest.json b/test/fixtures/cso-eval/manifest.json deleted file mode 100644 index 96435c4ac..000000000 --- a/test/fixtures/cso-eval/manifest.json +++ /dev/null @@ -1,686 +0,0 @@ -{ - "schemaVersion": 1, - "version": "cso-v3-pairs-3", - "cases": [ - { - "id": "node-sql-injection", - "stack": "node", - "family": "sql-injection", - "severity": "high", - "rootCause": "sql-injection", - "location": { - "path": "app.mjs", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "87267be77a89123b31f36c86c9a52e6eafbd266a313f3aca788a16fc47be7c65", - "fixed": "069fb74d1b471879b4151ee60de6dcae5abe6b86935a811b3160afc888091ee5" - } - }, - { - "id": "node-command-injection", - "stack": "node", - "family": "command-injection", - "severity": "high", - "rootCause": "command-injection", - "location": { - "path": "app.mjs", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "4336fcd76b10ee6c36455288e14411c0ac2c62407e7ef22ae83cf957f77d17ed", - "fixed": "bcf6a044ca201dba861c4764696e800230d9b215644465cd7ed31479d218c12d" - } - }, - { - "id": "node-path-traversal", - "stack": "node", - "family": "path-traversal", - "severity": "high", - "rootCause": "path-traversal", - "location": { - "path": "app.mjs", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "d69e959678cc3076202dbe9963ecde251cfece5744ee6718f4e82387efd5c994", - "fixed": "48ba7360137d0732b139dc6061640768cbfa1e31f896d5feb93258bb341a4e34" - } - }, - { - "id": "node-ssrf", - "stack": "node", - "family": "ssrf", - "severity": "high", - "rootCause": "ssrf", - "location": { - "path": "app.mjs", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "dddf678fa3c900b2dd75953df953308c8e649eba1b061018075338163dba9d41", - "fixed": "c6b0a7d485fb0becae52f41e072d51096610d9c31c0cf790225350f40acb01b1" - } - }, - { - "id": "node-object-authorization", - "stack": "node", - "family": "object-authorization", - "severity": "high", - "rootCause": "object-authorization", - "location": { - "path": "app.mjs", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "de4a888619db2d1992b2d46671f0b5fcde48903d6909cb23321a4019a574674a", - "fixed": "32c3ddaa88abe9286e1905f68ee3261aaf9a4a209964d7e014f622d25f05dc2c" - } - }, - { - "id": "node-tenant-isolation", - "stack": "node", - "family": "tenant-isolation", - "severity": "high", - "rootCause": "tenant-isolation", - "location": { - "path": "app.mjs", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "fe9a035c0362f3513c7fb54d48acb5a835c84c424a9148be8a453f67dd1823fb", - "fixed": "6df2ee7243dcb8e624c988320d8df23814912ce0d3c2fb9282c50070f3f5b159" - } - }, - { - "id": "node-html-injection", - "stack": "node", - "family": "html-injection", - "severity": "medium", - "rootCause": "html-injection", - "location": { - "path": "app.mjs", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "a373a32baef89b2d6ae97aac6c0a8aa56aa2d43c2f4f1d034e24249b272cf1da", - "fixed": "c3c114c86bd25b1c1f1b2766ad39cbe100f1c42edaa961314a20a7c64d5cf8a3" - } - }, - { - "id": "node-open-redirect", - "stack": "node", - "family": "open-redirect", - "severity": "medium", - "rootCause": "open-redirect", - "location": { - "path": "app.mjs", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "12f0a273a9dc9960b7be8345794482274f7207f98b416c5211c0eb2e73633ba9", - "fixed": "1547a8c5cce7a47b054e8b0d9ce5a065703d0a686c2fea8be3d70016290cbe4d" - } - }, - { - "id": "node-mass-assignment", - "stack": "node", - "family": "mass-assignment", - "severity": "high", - "rootCause": "mass-assignment", - "location": { - "path": "app.mjs", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "f0c6f6e3465069d9eba208a6ca899b1a6438d679937b89ebcd56c768d9cbd85b", - "fixed": "cb08b01645e2186adfae2bdb17bd3d41240cb389f9ddd65223e286d91ac72d05" - } - }, - { - "id": "node-resource-exhaustion", - "stack": "node", - "family": "resource-exhaustion", - "severity": "high", - "rootCause": "resource-exhaustion", - "location": { - "path": "app.mjs", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "1671cb1dd6639c19aa687ec02f70190c39bbc1b7ccf436783560a173f9bb8d57", - "fixed": "a78998de27bd98b4a90600352f2e431f34c0cc7a8a4c9f5de4fc8ec1877bb9ba" - } - }, - { - "id": "bun-sql-injection", - "stack": "bun", - "family": "sql-injection", - "severity": "high", - "rootCause": "sql-injection", - "location": { - "path": "app.ts", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "6e55eb6286eb0cd7a550bc0e2057b2344af21d34e0e73ff950e12446a5e306bc", - "fixed": "b7e9df66ff955ebf4ed538798fbd8187e5929c1e4d3bd82c655e7513cb024269" - } - }, - { - "id": "bun-command-injection", - "stack": "bun", - "family": "command-injection", - "severity": "high", - "rootCause": "command-injection", - "location": { - "path": "app.ts", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "d4b222144463b15d360de50c675bbd4e01cd91b6fe97c090124e11406970bb0e", - "fixed": "0522b906f1460ebb514ec45c7d4261575bf8bccb67c3add14ec83bc5afce4e3c" - } - }, - { - "id": "bun-path-traversal", - "stack": "bun", - "family": "path-traversal", - "severity": "high", - "rootCause": "path-traversal", - "location": { - "path": "app.ts", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "8d9225578ad93d0bf243d23e23db719ddf77f486b25065ff8797c093e4d8529b", - "fixed": "380d546d31f4563edcecd8eeaed7c02aadb169a662776a9a4b026f7ea514468f" - } - }, - { - "id": "bun-ssrf", - "stack": "bun", - "family": "ssrf", - "severity": "high", - "rootCause": "ssrf", - "location": { - "path": "app.ts", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "80728866a613c4a3c1c5ffe468a098152f6e3632afa049905feb0ed286664f99", - "fixed": "05992952d8922605ac472d1a39e1aed9b058453eb95296b469d022c62b6d1114" - } - }, - { - "id": "bun-object-authorization", - "stack": "bun", - "family": "object-authorization", - "severity": "high", - "rootCause": "object-authorization", - "location": { - "path": "app.ts", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "2d72c60a1aa2b560f00d3f066bdc0947bc52978755de7323402ee2f75498f9a6", - "fixed": "b839b3f4f8354407eb6577f423d1651b40f7c3a68b079b04624b0b0d6de0294b" - } - }, - { - "id": "bun-tenant-isolation", - "stack": "bun", - "family": "tenant-isolation", - "severity": "high", - "rootCause": "tenant-isolation", - "location": { - "path": "app.ts", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "9d880c06e01294c8e785471165642a899a555c15e9409346946802f0189db53a", - "fixed": "dd1b4c7fb3cce974bfe998a5df337f6270f7675a97ce91ca9647067d29bd4368" - } - }, - { - "id": "bun-html-injection", - "stack": "bun", - "family": "html-injection", - "severity": "medium", - "rootCause": "html-injection", - "location": { - "path": "app.ts", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "280970e0c738f3f98f72388b2094b30a81ae8de24631aab9759c5c467eb04dce", - "fixed": "01d9ca12aeac526627c851609d034a35e57326b9f27e798853ad4338c8d6f0fe" - } - }, - { - "id": "bun-open-redirect", - "stack": "bun", - "family": "open-redirect", - "severity": "medium", - "rootCause": "open-redirect", - "location": { - "path": "app.ts", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "92e0f59a1a5cc9346dee8941ef218a82f739b5fb1ca06595a38ae4e3be3e5e50", - "fixed": "93da544141e869c13e5136b834f4ae59f0469d17b55bc5455e69c9b2efe0e144" - } - }, - { - "id": "bun-mass-assignment", - "stack": "bun", - "family": "mass-assignment", - "severity": "high", - "rootCause": "mass-assignment", - "location": { - "path": "app.ts", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "046ae2d46f8bc9a185a7384a1dac8902cd0d4b8f23447564b77a27354e2587eb", - "fixed": "79bb3ced148331d009b3e680c6c2040f6885e62873daedad0667fd2fd6173e1b" - } - }, - { - "id": "bun-resource-exhaustion", - "stack": "bun", - "family": "resource-exhaustion", - "severity": "high", - "rootCause": "resource-exhaustion", - "location": { - "path": "app.ts", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "785c96f9a0ee7b2e8a07135dd46c43fdf28d06caa2e5380d8c6d2a469397cc2c", - "fixed": "d8ed22d72e5eb14c5e745b5d702377147b53a071de634597e4239435fd3a1c42" - } - }, - { - "id": "python-sql-injection", - "stack": "python", - "family": "sql-injection", - "severity": "high", - "rootCause": "sql-injection", - "location": { - "path": "app.py", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "fc2cb6a773be0e191372c33014deed8837738fa48843fa99eb8ff63367f5675d", - "fixed": "07518c636f923497ed4d474b68e471216af0efb77bbd0751a3fdbc222055c71e" - } - }, - { - "id": "python-command-injection", - "stack": "python", - "family": "command-injection", - "severity": "high", - "rootCause": "command-injection", - "location": { - "path": "app.py", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "4137304be1b38300a68202f943e41680a0897a75c89a8fc222781e39c22f22a6", - "fixed": "99bf0f2010d595321018e25428e76d408cf5efc6c96284dd7144c5802c259091" - } - }, - { - "id": "python-path-traversal", - "stack": "python", - "family": "path-traversal", - "severity": "high", - "rootCause": "path-traversal", - "location": { - "path": "app.py", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "c261d74c7a569025259984448056928741ccb07383684f9fda5e51b9280a4d5c", - "fixed": "0fa6edad6b84f90efda50d1e49c584c8ca51ddb8ef9998034ad86b2bb7d81b76" - } - }, - { - "id": "python-ssrf", - "stack": "python", - "family": "ssrf", - "severity": "high", - "rootCause": "ssrf", - "location": { - "path": "app.py", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "5b06615f38d6d43ea4900551155eabd5b8ba9f856d15f78e79fde70856177792", - "fixed": "814315a11b6b600c5e338822fc42fc9c4d6f66b88fa86de664ab0ccdeb91166e" - } - }, - { - "id": "python-object-authorization", - "stack": "python", - "family": "object-authorization", - "severity": "high", - "rootCause": "object-authorization", - "location": { - "path": "app.py", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "a151cda5d96ba2e7e9b940ceb936e28070b680d572079ba5364ab56a993599da", - "fixed": "a8083c530ddb9fa4d0c0b0f6de4487ce0df7b811d2fb79c8cdbcdae0d8e3e2b4" - } - }, - { - "id": "python-tenant-isolation", - "stack": "python", - "family": "tenant-isolation", - "severity": "high", - "rootCause": "tenant-isolation", - "location": { - "path": "app.py", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "d8cad33e13f914d34c97eb365f5d7fed4f63c0cb64546abf182f28b8050c03e0", - "fixed": "7ac649e25edcf30030f0ed3c22aa3bfacb38516ab435db4dee240c5d8e8c45a4" - } - }, - { - "id": "python-html-injection", - "stack": "python", - "family": "html-injection", - "severity": "medium", - "rootCause": "html-injection", - "location": { - "path": "app.py", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "aa9ca878ed3c100845728ee70fb1e4254d1ee5ef76d655b3c17d1269c17b190b", - "fixed": "5a6cd758d4e007291eb01d922ef7994cc2f36371a7e96c99fcb4fabe643e3ce8" - } - }, - { - "id": "python-open-redirect", - "stack": "python", - "family": "open-redirect", - "severity": "medium", - "rootCause": "open-redirect", - "location": { - "path": "app.py", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "0c052ebc5fba7f165ba4e173ca477911f741ed512bd152e2b43a1b526f815267", - "fixed": "2a3e70475e00d98fe6e2d6505d0ff71b9a9985f701e6a9fd081801d0162dbbd1" - } - }, - { - "id": "python-mass-assignment", - "stack": "python", - "family": "mass-assignment", - "severity": "high", - "rootCause": "mass-assignment", - "location": { - "path": "app.py", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "74ffa12e965869af108f8cfbde9903a66d3a96fc76478ece6739a36712f97f69", - "fixed": "f4311765ac908b668ecfa3665d8023cf910e6afb1aff799802036a9f212c75ff" - } - }, - { - "id": "python-resource-exhaustion", - "stack": "python", - "family": "resource-exhaustion", - "severity": "high", - "rootCause": "resource-exhaustion", - "location": { - "path": "app.py", - "symbol": "action" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "50f4a5c5ad4ac5fd9fc0a935a37a0ede2d6735dbf31f7ed9fae9f63029d98181", - "fixed": "a25653768c0d551373d594a1505510325a01e06536fd1158c7b8617084fdb2dc" - } - }, - { - "id": "rails-sql-injection", - "stack": "rails", - "family": "sql-injection", - "severity": "high", - "rootCause": "sql-injection", - "location": { - "path": "app/controllers/cases_controller.rb", - "symbol": "CasesController#show" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "ebcfded5f3a00b76f803986cf1e82ca725df8ecd5268758ffe5c7b1ffed602e6", - "fixed": "3905e9acf8f564fb3ead4e53c823fca10a2bc6e28212b90cad95bf4cff515c7d" - } - }, - { - "id": "rails-command-injection", - "stack": "rails", - "family": "command-injection", - "severity": "high", - "rootCause": "command-injection", - "location": { - "path": "app/controllers/cases_controller.rb", - "symbol": "CasesController#show" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "7938f3f18bbd5effddbd28029476f305a443148351707142267411d56d5fb0b8", - "fixed": "a88dcb4e5d0bc19d79577791bbe4eccc946f22f7ad66a0471af005d83106bd5d" - } - }, - { - "id": "rails-path-traversal", - "stack": "rails", - "family": "path-traversal", - "severity": "high", - "rootCause": "path-traversal", - "location": { - "path": "app/controllers/cases_controller.rb", - "symbol": "CasesController#show" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "b49d633543845557b4dea97674b04542df2309d53c46c61dad6532b561b4179e", - "fixed": "a77ce178798cb01abaa55a815da3f8f16ab95add4103d540b27775735d857d9e" - } - }, - { - "id": "rails-ssrf", - "stack": "rails", - "family": "ssrf", - "severity": "high", - "rootCause": "ssrf", - "location": { - "path": "app/controllers/cases_controller.rb", - "symbol": "CasesController#show" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "e8fbb44ae9e01e44615dc991920c655ab97ad16c3ef8d425f9d94a3d215beedd", - "fixed": "0c2d952137fa644f4eba215b43988ad0092a4ce902863196309e65b30438661d" - } - }, - { - "id": "rails-object-authorization", - "stack": "rails", - "family": "object-authorization", - "severity": "high", - "rootCause": "object-authorization", - "location": { - "path": "app/controllers/cases_controller.rb", - "symbol": "CasesController#show" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "5378c421c287d6a79f1d7c4836e472fe0851a7436aaee431e23b317a7fc259ca", - "fixed": "976c0a27c7c647ddbd5e31d5a36668deb6e1ca5851702bbb280a2d1f81a3d84e" - } - }, - { - "id": "rails-tenant-isolation", - "stack": "rails", - "family": "tenant-isolation", - "severity": "high", - "rootCause": "tenant-isolation", - "location": { - "path": "app/controllers/cases_controller.rb", - "symbol": "CasesController#show" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "0a082cf0146c15cb4ca585b50a024e4596642dbb6462c3370b5452a8c25eb550", - "fixed": "5814fae616945cb1ead1d7046c89281c0f7215ccf4cb298a4cc517297adc0ba8" - } - }, - { - "id": "rails-html-injection", - "stack": "rails", - "family": "html-injection", - "severity": "medium", - "rootCause": "html-injection", - "location": { - "path": "app/controllers/cases_controller.rb", - "symbol": "CasesController#show" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "118599300873d0a10f3e920157707f71703cd58cae9d597e5c98cf046b410507", - "fixed": "12a2d8d6db8c6ed60faa1658aa63df414d60c6b85dcd7e417d229e7017a05949" - } - }, - { - "id": "rails-open-redirect", - "stack": "rails", - "family": "open-redirect", - "severity": "medium", - "rootCause": "open-redirect", - "location": { - "path": "app/controllers/cases_controller.rb", - "symbol": "CasesController#show" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "77cce00579bc9b10bfc0be2755b5b6446034585456799e4e3771740a0d7f59ab", - "fixed": "113b5e5c346fd4aebab9b4e3242d14784ee70e71c6e938c289e46dfcb968c4a8" - } - }, - { - "id": "rails-mass-assignment", - "stack": "rails", - "family": "mass-assignment", - "severity": "high", - "rootCause": "mass-assignment", - "location": { - "path": "app/controllers/cases_controller.rb", - "symbol": "CasesController#show" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "17fce4f956eaa654b1b90f6fe78ccc604accc820f9496517296800ca541bc436", - "fixed": "58b5132f336f6e115ff38b3c7b28bc0a00fca2444669008e3b30c3f6037a915e" - } - }, - { - "id": "rails-resource-exhaustion", - "stack": "rails", - "family": "resource-exhaustion", - "severity": "high", - "rootCause": "resource-exhaustion", - "location": { - "path": "app/controllers/cases_controller.rb", - "symbol": "CasesController#show" - }, - "coreColdStart": true, - "heldOut": true, - "filesHash": { - "vulnerable": "08e656bee75b724ba5b958c1887589df9931babec2c742e3b644236a677e007c", - "fixed": "fb7f5a5011d05e1f9d27d19c70aca5f64c11bd2cbc68d3396053e7169d8e94ec" - } - } - ] -} diff --git a/test/fixtures/cso-eval/materialize.ts b/test/fixtures/cso-eval/materialize.ts deleted file mode 100644 index d9c96b994..000000000 --- a/test/fixtures/cso-eval/materialize.ts +++ /dev/null @@ -1,383 +0,0 @@ -/** Immutable benchmark source generator. Expected outcomes live outside producer inputs. */ -import { createHash } from 'node:crypto'; -import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'; -import { dirname, join, resolve } from 'node:path'; - -export const CORPUS_VERSION = 'cso-v3-pairs-3'; -export const STACKS = ['node', 'bun', 'python', 'rails'] as const; -export const FAMILIES = ['sql-injection', 'command-injection', 'path-traversal', 'ssrf', 'object-authorization', 'tenant-isolation', 'html-injection', 'open-redirect', 'mass-assignment', 'resource-exhaustion'] as const; -export type EvalStack = typeof STACKS[number]; -export type EvalFamily = typeof FAMILIES[number]; -export type EvalVariant = 'vulnerable' | 'fixed'; -export interface CorpusCase { - id: string; stack: EvalStack; family: Family; severity: 'critical' | 'high' | 'medium'; - rootCause: string; location: { path: string; symbol: string }; - coreColdStart: true; heldOut: true; - filesHash: { vulnerable: string; fixed: string }; -} -export interface CorpusManifest { schemaVersion: 1; version: string; cases: CorpusCase[] } -/** - * A corpus with the public layout: a manifest plus a deterministic source - * generator for each case variant. Private evaluators inject their own; the - * default is this public development corpus. - */ -export interface EvalCorpus { - manifest: CorpusManifest; - sourceFiles(id: string, variant: EvalVariant): Record; -} -const hash = (input: string) => createHash('sha256').update(input).digest('hex'); -export function sourceHash(files: Record): string { - return hash(JSON.stringify(Object.keys(files).sort().map(path => [path, hash(files[path])]))); -} -function stackCase(id: string): { stack: EvalStack; family: EvalFamily } { - for (const stack of STACKS) for (const family of FAMILIES) if (id === `${stack}-${family}`) return { stack, family }; - throw new Error('UNKNOWN_CORPUS_CASE'); -} -const description: Record = { - 'sql-injection': 'Look up the note belonging to an exact customer name.', - 'command-injection': 'Format a display name using the system formatting utility. Display names contain letters, digits, underscores, and hyphens.', - 'path-traversal': 'Read a file from the public documents directory.', - ssrf: 'Load the public status document from the internal status service.', - 'object-authorization': 'Read an invoice belonging to the authenticated member.', - 'tenant-isolation': 'List documents in the authenticated member\'s tenant.', - 'html-injection': 'Render a welcome page containing a visitor-supplied display name as text.', - 'open-redirect': 'Redirect a signed-in member to an application-relative path.', - 'mass-assignment': 'Update the authenticated member\'s display name. Their role is managed by an administrator.', - 'resource-exhaustion': 'Generate up to 100 preview records per request.', -}; - -interface PublicControl { - method: 'GET' | 'POST'; - path: string; - body?: Record; - status: number; - bodyIncludes: string; - location?: string; -} - -/** - * Producer-visible regression controls exercise the feature's intended use. - * Attack payloads and alternate assertions stay in cso-eval-oracles.ts. - */ -function publicControl(family: EvalFamily): PublicControl { - const controls: Record = { - 'sql-injection': { method: 'GET', path: '/action?name=alice', status: 200, bodyIncludes: 'HELLO_ALICE' }, - 'command-injection': { method: 'GET', path: '/action?name=Ada', status: 200, bodyIncludes: 'Ada' }, - 'path-traversal': { method: 'GET', path: '/action?file=hello.txt', status: 200, bodyIncludes: 'PUBLIC_HELLO' }, - ssrf: { method: 'GET', path: '/action?url=http%3A%2F%2F127.0.0.1%3A8001%2Fpublic', status: 200, bodyIncludes: 'PUBLIC_STATUS' }, - 'object-authorization': { method: 'GET', path: '/action?id=invoice-1', status: 200, bodyIncludes: 'member-1' }, - 'tenant-isolation': { method: 'GET', path: '/action?tenant=tenant-a', status: 200, bodyIncludes: 'OWN_TENANT_DOCUMENT' }, - 'html-injection': { method: 'GET', path: '/action?name=Alice', status: 200, bodyIncludes: '
Welcome Alice
' }, - 'open-redirect': { method: 'GET', path: '/action?next=%2Faccount', status: 302, bodyIncludes: '/account', location: '/account' }, - 'mass-assignment': { method: 'POST', path: '/action', body: { display_name: 'Ada' }, status: 200, bodyIncludes: 'Ada' }, - 'resource-exhaustion': { method: 'GET', path: '/action?count=5', status: 200, bodyIncludes: 'count' }, - }; - return controls[family]; -} - -function javascriptControlTest(stack: 'node' | 'bun', family: EvalFamily): string { - const control = publicControl(family); - const imports = stack === 'node' - ? 'import test from "node:test";\nimport assert from "node:assert/strict";\nimport { spawn } from "node:child_process";' - : 'import { test, expect } from "bun:test";'; - const start = stack === 'node' - ? 'const child = spawn(process.execPath, ["app.mjs"], {stdio: "ignore"});' - : 'const child = Bun.spawn({cmd: [process.execPath, "--no-install", "app.ts"], stdout: "ignore", stderr: "ignore"});'; - const stop = stack === 'node' - ? 'child.kill("SIGTERM");\n if (child.exitCode === null) await new Promise(resolve => child.once("exit", resolve));' - : 'child.kill();\n await child.exited;'; - const equal = stack === 'node' - ? `assert.equal(response.status, ${control.status});\n assert.ok(body.includes(${JSON.stringify(control.bodyIncludes)}));${control.location ? `\n assert.equal(response.headers.get("location"), ${JSON.stringify(control.location)});` : ''}` - : `expect(response.status).toBe(${control.status});\n expect(body).toContain(${JSON.stringify(control.bodyIncludes)});${control.location ? `\n expect(response.headers.get("location")).toBe(${JSON.stringify(control.location)});` : ''}`; - const options = control.body - ? `{method: "POST", redirect: "manual", headers: {"content-type": "application/json"}, body: ${JSON.stringify(JSON.stringify(control.body))}}` - : '{redirect: "manual"}'; - return `${imports} - -async function waitUntilReady() { - for (let attempt = 0; attempt < 100; attempt++) { - try { if ((await fetch("http://127.0.0.1:8000/health")).status === 200) return; } catch {} - await new Promise(resolve => setTimeout(resolve, 20)); - } - throw new Error("application did not become ready"); -} - -test("the intended member workflow remains available", async () => { - ${start} - try { - await waitUntilReady(); - const response = await fetch(${JSON.stringify(`http://127.0.0.1:8000${control.path}`)}, ${options}); - const body = await response.text(); - ${equal} - } finally { ${stop} } -}); -`; -} - -function pythonControlTest(family: EvalFamily): string { - const control = publicControl(family); - const body = control.body ? JSON.stringify(control.body) : ''; - return `import http.client -import json -import subprocess -import sys -import time -import unittest - -class IntendedWorkflowTest(unittest.TestCase): - def test_intended_member_workflow_remains_available(self): - child = subprocess.Popen([sys.executable, "-I", "app.py"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - try: - for _ in range(100): - try: - connection = http.client.HTTPConnection("127.0.0.1", 8000, timeout=1) - connection.request("GET", "/health") - if connection.getresponse().status == 200: - break - except OSError: - time.sleep(0.02) - else: - self.fail("application did not become ready") - connection = http.client.HTTPConnection("127.0.0.1", 8000, timeout=2) - payload = ${JSON.stringify(body)} - headers = {"content-type": "application/json"} if payload else {} - connection.request(${JSON.stringify(control.method)}, ${JSON.stringify(control.path)}, body=payload or None, headers=headers) - response = connection.getresponse() - response_body = response.read().decode() - self.assertEqual(response.status, ${control.status}) - self.assertIn(${JSON.stringify(control.bodyIncludes)}, response_body) -${control.location ? ` self.assertEqual(response.getheader("location"), ${JSON.stringify(control.location)})\n` : ''} finally: - child.terminate() - try: - child.wait(timeout=2) - except subprocess.TimeoutExpired: - child.kill() - -if __name__ == "__main__": - unittest.main() -`; -} - -function railsControlTest(family: EvalFamily): string { - const control = publicControl(family); - const verb = control.method.toLowerCase(); - const request = control.body - ? `${verb} ${JSON.stringify(control.path)}, params: ${JSON.stringify(control.body)}` - : `${verb} ${JSON.stringify(control.path)}`; - return `require "test_helper" - -class IntendedWorkflowTest < ActionDispatch::IntegrationTest - test "the intended member workflow remains available" do - ${request} - assert_response ${control.status} - assert_includes response.body, ${JSON.stringify(control.bodyIncludes)} -${control.location ? ` assert_equal ${JSON.stringify(control.location)}, response.headers["Location"]\n` : ''} end -end -`; -} - -function jsSource(stack: 'node' | 'bun', family: EvalFamily, fixed: boolean): string { - const imports = ['import { createServer } from "node:http";']; - let setup = ''; - if (family === 'sql-injection') { - imports.push(stack === 'node' ? 'import { DatabaseSync } from "node:sqlite";' : 'import { Database } from "bun:sqlite";'); - setup += `const db = new ${stack === 'node' ? 'DatabaseSync' : 'Database'}(":memory:");\ndb.exec("CREATE TABLE notes (name TEXT, note TEXT); INSERT INTO notes VALUES ('alice', 'HELLO_ALICE'), ('admin', 'SECRET_ADMIN_NOTE')");\nconst query = (sql, ...args) => db.${stack === 'node' ? 'prepare' : 'query'}(sql).all(...args);\n`; - } - if (family === 'command-injection') imports.push('import { execSync, execFileSync } from "node:child_process";'); - if (family === 'path-traversal') imports.push('import { readFileSync } from "node:fs";', 'import { resolve, sep } from "node:path";'); - if (family === 'ssrf') setup += `createServer((request, response) => { response.end(request.url === "/public" ? "PUBLIC_STATUS" : "INTERNAL_SERVICE_SECRET"); }).listen(8001, "127.0.0.1");\n`; - if (family === 'object-authorization') setup += 'const invoices = {"invoice-1": {owner: "member-1", total: 12}, "invoice-2": {owner: "member-2", total: 9800}};\n'; - if (family === 'tenant-isolation') setup += 'const documents = [{tenant: "tenant-a", body: "OWN_TENANT_DOCUMENT"}, {tenant: "tenant-b", body: "OTHER_TENANT_SECRET"}];\n'; - if (family === 'mass-assignment') setup += 'const account = {id: "member-1", display_name: "Alice", role: "member"};\n'; - const actions: Record = { - 'sql-injection': fixed - ? 'return send(200, query("SELECT note FROM notes WHERE name = ?", params.get("name") ?? ""));' - : 'return send(200, query("SELECT note FROM notes WHERE name = \'" + (params.get("name") ?? "") + "\'"));', - 'command-injection': fixed - ? 'const name = params.get("name") ?? "";\n if (!/^[A-Za-z0-9_-]{1,60}$/.test(name)) return send(400, {error: "invalid display name"});\n return send(200, {output: execFileSync("/usr/bin/printf", ["%s", name], {encoding: "utf8"})});' - : 'const name = params.get("name") ?? "";\n return send(200, {output: execSync(\'printf "%s" "\' + name + \'"\', {encoding: "utf8"})});', - 'path-traversal': fixed - ? 'const base = resolve("public");\n const file = resolve(base, params.get("file") ?? "hello.txt");\n if (!file.startsWith(base + sep)) return send(403, {error: "outside public documents"});\n return send(200, {document: readFileSync(file, "utf8")});' - : 'const file = resolve("public", params.get("file") ?? "hello.txt");\n return send(200, {document: readFileSync(file, "utf8")});', - ssrf: `${fixed ? 'const target = new URL(params.get("url") ?? "http://127.0.0.1:8001/public");\n if (target.origin !== "http://127.0.0.1:8001" || target.pathname !== "/public" || target.username || target.password || target.search || target.hash) return send(403, {error: "unsupported status source"});\n const result = await fetch(target, {redirect: "error"});' : 'const result = await fetch(params.get("url") ?? "http://127.0.0.1:8001/public");'}\n return send(200, {status: await result.text()});`, - 'object-authorization': `const invoice = invoices[params.get("id") ?? "invoice-1"];\n if (!invoice) return send(404, {error: "not found"});\n ${fixed ? 'if (invoice.owner !== actor.id) return send(403, {error: "forbidden"});\n ' : ''}return send(200, invoice);`, - 'tenant-isolation': `return send(200, documents.filter(document => document.tenant === ${fixed ? 'actor.tenant' : '(params.get("tenant") ?? actor.tenant)'}));`, - 'html-injection': `const name = params.get("name") ?? "Alice";\n ${fixed ? 'const safe = name.replace(/[&<>"\']/g, char => ({"&": "&", "<": "<", ">": ">", \'"\': """, "\'": "'"}[char]));' : 'const safe = name;'}\n return send(200, "
Welcome " + safe + "
", "text/html");`, - 'open-redirect': `const target = params.get("next") ?? "/account";\n ${fixed ? 'if (!/^\\/(?!\\/)/.test(target) || /[\\\\\\r\\n]/.test(target)) return send(400, {error: "invalid redirect"});\n ' : ''}response.setHeader("Location", target);\n return send(302, {next: target});`, - 'mass-assignment': `${fixed ? 'if (typeof body.display_name === "string") account.display_name = body.display_name;' : 'Object.assign(account, body);'}\n return send(200, account);`, - 'resource-exhaustion': `const count = Number(params.get("count") ?? "5");\n ${fixed ? 'if (!Number.isInteger(count) || count < 1 || count > 100) return send(400, {error: "preview count must be 1-100"});\n ' : ''}const previews = Array.from({length: count}, (_, index) => "preview-" + index);\n return send(200, {count: previews.length});`, - }; - return `${imports.join('\n')}\n${setup}// Authentication middleware has established this member before the endpoint.\nconst actor = Object.freeze({id: "member-1", tenant: "tenant-a", role: "member"});\nasync function action(params, body, response, send) {\n ${actions[family]}\n}\ncreateServer(async (request, response) => {\n const send = (status, value, type = "application/json") => {response.writeHead(status, {"content-type": type}); response.end(type === "application/json" ? JSON.stringify(value) : value);};\n const url = new URL(request.url, "http://127.0.0.1:8000");\n if (url.pathname === "/health") return send(200, {ready: true});\n if (url.pathname !== "/action") return send(404, {error: "not found"});\n try {\n let raw = "";\n for await (const part of request) {raw += part; if (raw.length > 16384) return send(413, {error: "body too large"});}\n await action(url.searchParams, raw ? JSON.parse(raw) : {}, response, send);\n } catch {send(400, {error: "invalid request"});}\n}).listen(8000, "127.0.0.1");\n`; -} - -function pythonSource(family: EvalFamily, fixed: boolean): string { - const setup: Partial> = { - 'sql-injection': `db = sqlite3.connect(":memory:", check_same_thread=False)\ndb.executescript("CREATE TABLE notes (name TEXT, note TEXT); INSERT INTO notes VALUES ('alice', 'HELLO_ALICE'), ('admin', 'SECRET_ADMIN_NOTE')")`, - 'object-authorization': 'invoices = {"invoice-1": {"owner": "member-1", "total": 12}, "invoice-2": {"owner": "member-2", "total": 9800}}', - 'tenant-isolation': 'documents = [{"tenant": "tenant-a", "body": "OWN_TENANT_DOCUMENT"}, {"tenant": "tenant-b", "body": "OTHER_TENANT_SECRET"}]', - 'mass-assignment': 'account = {"id": "member-1", "display_name": "Alice", "role": "member"}', - ssrf: `class StatusService(BaseHTTPRequestHandler):\n def do_GET(self):\n self.send_response(200)\n self.end_headers()\n self.wfile.write(b"PUBLIC_STATUS" if self.path == "/public" else b"INTERNAL_SERVICE_SECRET")\n def log_message(self, *args):\n pass\nthreading.Thread(target=ThreadingHTTPServer(("127.0.0.1", 8001), StatusService).serve_forever, daemon=True).start()`, - }; - const actions: Record = { - 'sql-injection': `rows = db.execute(${fixed ? '"SELECT note FROM notes WHERE name = ?", (params.get("name", ""),)' : '"SELECT note FROM notes WHERE name = \'" + params.get("name", "") + "\'"'}).fetchall()\n return 200, [{"note": row[0]} for row in rows]`, - 'command-injection': `name = params.get("name", "")\n ${fixed ? 'if not re.fullmatch(r"[A-Za-z0-9_-]{1,60}", name):\n return 400, {"error": "invalid display name"}\n output = subprocess.check_output(["/usr/bin/printf", "%s", name], text=True)' : 'output = subprocess.check_output(\'printf "%s" "\' + name + \'"\', shell=True, text=True)'}\n return 200, {"output": output}`, - 'path-traversal': `base = pathlib.Path("public").resolve()\n path = (base / params.get("file", "hello.txt")).resolve()\n ${fixed ? 'if base not in path.parents:\n return 403, {"error": "outside public documents"}\n ' : ''}return 200, {"document": path.read_text()}`, - ssrf: `target = params.get("url", "http://127.0.0.1:8001/public")\n ${fixed ? 'parsed = urllib.parse.urlsplit(target)\n if parsed.scheme != "http" or parsed.netloc != "127.0.0.1:8001" or parsed.path != "/public" or parsed.query or parsed.fragment:\n return 403, {"error": "unsupported status source"}\n ' : ''}with urllib.request.urlopen(target, timeout=2) as result:\n return 200, {"status": result.read(16384).decode()}`, - 'object-authorization': `invoice = invoices.get(params.get("id", "invoice-1"))\n if invoice is None:\n return 404, {"error": "not found"}\n ${fixed ? 'if invoice["owner"] != actor["id"]:\n return 403, {"error": "forbidden"}\n ' : ''}return 200, invoice`, - 'tenant-isolation': `return 200, [document for document in documents if document["tenant"] == ${fixed ? 'actor["tenant"]' : 'params.get("tenant", actor["tenant"])'}]`, - 'html-injection': `name = params.get("name", "Alice")\n return 200, "
Welcome " + ${fixed ? 'html.escape(name, quote=True)' : 'name'} + "
"`, - 'open-redirect': `target = params.get("next", "/account")\n ${fixed ? 'if not target.startswith("/") or target.startswith("//") or any(char in target for char in "\\\\\\r\\n"):\n return 400, {"error": "invalid redirect"}\n ' : ''}return 302, {"next": target}`, - 'mass-assignment': `${fixed ? 'if isinstance(body.get("display_name"), str):\n account["display_name"] = body["display_name"]' : 'account.update(body)'}\n return 200, account`, - 'resource-exhaustion': `count = int(params.get("count", "5"))\n ${fixed ? 'if count < 1 or count > 100:\n return 400, {"error": "preview count must be 1-100"}\n ' : ''}previews = ["preview-" + str(index) for index in range(count)]\n return 200, {"count": len(previews)}`, - }; - return `import html\nimport json\nimport pathlib\nimport re\nimport sqlite3\nimport subprocess\nimport threading\nimport urllib.parse\nimport urllib.request\nfrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServer\n\n${setup[family] ?? ''}\n# Authentication middleware has established this member before the endpoint.\nactor = {"id": "member-1", "tenant": "tenant-a", "role": "member"}\n\ndef action(params, body):\n ${actions[family]}\n\nclass Application(BaseHTTPRequestHandler):\n def do_GET(self):\n self.dispatch()\n def do_POST(self):\n self.dispatch()\n def dispatch(self):\n url = urllib.parse.urlsplit(self.path)\n params = dict(urllib.parse.parse_qsl(url.query))\n try:\n size = int(self.headers.get("Content-Length", "0"))\n if size < 0 or size > 16384:\n status, value = 413, {"error": "body too large"}\n elif url.path == "/health":\n status, value = 200, {"ready": True}\n elif url.path != "/action":\n status, value = 404, {"error": "not found"}\n else:\n body = json.loads(self.rfile.read(size)) if size else {}\n status, value = action(params, body)\n except Exception:\n status, value = 400, {"error": "invalid request"}\n self.send_response(status)\n if status == 302:\n self.send_header("Location", value["next"])\n self.send_header("Content-Type", "text/html" if isinstance(value, str) else "application/json")\n self.end_headers()\n self.wfile.write((value if isinstance(value, str) else json.dumps(value)).encode())\n def log_message(self, *args):\n pass\n\nThreadingHTTPServer(("127.0.0.1", 8000), Application).serve_forever()\n`; -} - -function railsSources(family: EvalFamily, fixed: boolean): Record { - const setup: Partial> = { - 'sql-injection': '$database = SQLite3::Database.new(":memory:")\n$database.results_as_hash = true\n$database.execute_batch("CREATE TABLE notes (name TEXT, note TEXT); INSERT INTO notes VALUES (\'alice\', \'HELLO_ALICE\'), (\'admin\', \'SECRET_ADMIN_NOTE\')")', - 'object-authorization': '$invoices = {"invoice-1" => {owner: "member-1", total: 12}, "invoice-2" => {owner: "member-2", total: 9800}}', - 'tenant-isolation': '$documents = [{tenant: "tenant-a", body: "OWN_TENANT_DOCUMENT"}, {tenant: "tenant-b", body: "OTHER_TENANT_SECRET"}]', - 'mass-assignment': '$account = {"id" => "member-1", "display_name" => "Alice", "role" => "member"}', - ssrf: `Thread.new do\n server = TCPServer.new("127.0.0.1", 8001)\n loop do\n client = server.accept\n request = client.gets.to_s\n while (line = client.gets) && line != "\\r\\n"; end\n body = request.start_with?("GET /public ") ? "PUBLIC_STATUS" : "INTERNAL_SERVICE_SECRET"\n client.write("HTTP/1.1 200 OK\\r\\nContent-Length: #{body.bytesize}\\r\\nConnection: close\\r\\n\\r\\n#{body}")\n client.close\n end\nend`, - }; - const actions: Record = { - 'sql-injection': `rows = $database.execute(${fixed ? '"SELECT note FROM notes WHERE name = ?", [params[:name].to_s]' : '"SELECT note FROM notes WHERE name = \'#{params[:name]}\'"'})\n render json: rows`, - 'command-injection': `name = params[:name].to_s\n ${fixed ? 'return render(json: {error: "invalid display name"}, status: 400) unless /\\A[A-Za-z0-9_-]{1,60}\\z/.match?(name)\n output, = Open3.capture2("/usr/bin/printf", "%s", name)' : 'output, = Open3.capture2("sh", "-c", \'printf "%s" "\' + name + \'"\')'}\n render json: {output: output}`, - 'path-traversal': `base = Rails.root.join("public").to_s\n path = File.expand_path(params[:file] || "hello.txt", base)\n ${fixed ? 'return render(json: {error: "outside public documents"}, status: 403) unless path.start_with?(base + File::SEPARATOR)\n ' : ''}render json: {document: File.read(path)}`, - ssrf: `target = URI.parse(params[:url] || "http://127.0.0.1:8001/public")\n ${fixed ? 'return render(json: {error: "unsupported status source"}, status: 403) unless target.scheme == "http" && target.host == "127.0.0.1" && target.port == 8001 && target.path == "/public" && !target.userinfo && !target.query && !target.fragment\n ' : ''}render json: {status: Net::HTTP.get(target)}`, - 'object-authorization': `invoice = $invoices[params[:id] || "invoice-1"]\n return render(json: {error: "not found"}, status: 404) unless invoice\n ${fixed ? 'return render(json: {error: "forbidden"}, status: 403) unless invoice[:owner] == actor[:id]\n ' : ''}render json: invoice`, - 'tenant-isolation': `render json: $documents.select { |document| document[:tenant] == ${fixed ? 'actor[:tenant]' : '(params[:tenant] || actor[:tenant])'} }`, - 'html-injection': `name = params[:name] || "Alice"\n render html: ("
Welcome " + ${fixed ? 'ERB::Util.html_escape(name)' : 'name'} + "
").html_safe`, - 'open-redirect': `target = params[:next] || "/account"\n ${fixed ? 'return render(json: {error: "invalid redirect"}, status: 400) unless target.start_with?("/") && !target.start_with?("//") && !/[\\\\\\r\\n]/.match?(target)\n ' : ''}response.set_header("Location", target)\n render json: {next: target}, status: 302`, - 'mass-assignment': `$account.merge!(${fixed ? 'params.permit(:display_name).to_h' : 'params.permit!.to_h.except("controller", "action")'})\n render json: $account`, - 'resource-exhaustion': `count = Integer(params[:count] || "5")\n ${fixed ? 'return render(json: {error: "preview count must be 1-100"}, status: 400) unless (1..100).cover?(count)\n ' : ''}previews = Array.new(count) { |index| "preview-#{index}" }\n render json: {count: previews.length}`, - }; - return { - 'Gemfile': 'source "https://rubygems.org"\ngem "rails", "= 8.1.2"\ngem "puma", "= 7.2.0"\ngem "sqlite3", "= 2.9.0"\n', - 'Gemfile.lock': readFileSync(new URL('./rails.Gemfile.lock', import.meta.url), 'utf8'), - 'config.ru': 'require_relative "config/environment"\nrun Rails.application\n', - 'config/boot.rb': 'ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../Gemfile", __dir__)\nrequire "bundler/setup"\n', - 'config/application.rb': `require_relative "boot"\nrequire "rails"\nrequire "action_controller/railtie"\nrequire "sqlite3"\nrequire "open3"\nrequire "net/http"\nrequire "socket"\nrequire "erb"\nmodule MemberPortal\n class Application < Rails::Application\n config.load_defaults 8.1\n config.eager_load = false\n config.secret_key_base = "cso-synthetic-test-key-not-a-production-credential"\n config.hosts = ["127.0.0.1", "localhost"]\n config.action_controller.allow_forgery_protection = false if Rails.env.test?\n end\nend\n${setup[family] ?? ''}\n`, - 'config/environment.rb': 'require_relative "application"\nRails.application.initialize!\n', - 'config/routes.rb': 'Rails.application.routes.draw do\n match "/action", to: "cases#show", via: [:get, :post]\n get "/health", to: proc { [200, {"content-type" => "application/json"}, [\'{"ready":true}\']] }\nend\n', - 'app/controllers/cases_controller.rb': `class CasesController < ActionController::Base\n def show\n # Authentication middleware has established this member before the endpoint.\n actor = {id: "member-1", tenant: "tenant-a", role: "member"}\n ${actions[family]}\n end\nend\n`, - 'bin/rails': '#!/usr/bin/env ruby\nAPP_PATH = File.expand_path("../config/application", __dir__)\nrequire_relative "../config/boot"\nrequire "rails/commands"\n', - }; -} - -/** Only application files are returned. Neither oracle inputs nor expected labels are included. */ -export function sourceFiles(id: string, variant: EvalVariant): Record { - const { stack, family } = stackCase(id); - if (variant !== 'vulnerable' && variant !== 'fixed') throw new Error('INVALID_CORPUS_VARIANT'); - const fixed = variant === 'fixed'; - let files: Record; - if (stack === 'node' || stack === 'bun') { - const node = stack === 'node'; - files = { - [node ? 'app.mjs' : 'app.ts']: jsSource(stack, family, fixed), - [node ? 'test/control.test.mjs' : 'test/control.test.ts']: javascriptControlTest(stack, family), - 'package.json': JSON.stringify({ - name: 'member-portal', version: '1.0.0', private: true, type: 'module', - scripts: { start: node ? 'node app.mjs' : 'bun app.ts', test: node ? 'node --test' : 'bun test' }, - }, null, 2) + '\n', - }; - files[stack === 'node' ? 'package-lock.json' : 'bun.lock'] = JSON.stringify(stack === 'node' - ? { name: 'member-portal', version: '1.0.0', lockfileVersion: 3, packages: { '': { name: 'member-portal', version: '1.0.0' } } } - : { lockfileVersion: 1, configVersion: 1, workspaces: { '': { name: 'member-portal' } }, packages: {} }, null, 2) + '\n'; - } else if (stack === 'python') files = { - 'app.py': pythonSource(family, fixed), - 'test_control.py': pythonControlTest(family), - 'requirements.txt': '# Uses only the pinned Python runtime standard library.\n', - }; - else files = { - ...railsSources(family, fixed), - 'test/test_helper.rb': 'ENV["RAILS_ENV"] ||= "test"\nrequire_relative "../config/environment"\nrequire "rails/test_help"\n', - 'test/integration/intended_workflow_test.rb': railsControlTest(family), - }; - files['README.md'] = `# Member portal\n\n${description[family]}\n\nThe endpoint is /action. A test authentication adapter establishes member-1 in\ntenant-a with the member role before application logic. Authentication itself\nis outside this fixture's assessment scope. /health is a readiness endpoint.\n\nRun only through the CSO execution helper. This application is a security\nbenchmark and must not be exposed to a host network or deployed.\n`; - if (family === 'path-traversal') { files['public/hello.txt'] = 'PUBLIC_HELLO'; files['private.txt'] = 'PRIVATE_DOCUMENT_SECRET'; } - return files; -} - -export function createManifest(): CorpusManifest { - return { schemaVersion: 1, version: CORPUS_VERSION, cases: STACKS.flatMap(stack => FAMILIES.map(family => { - const id = `${stack}-${family}`; - return { id, stack, family, severity: ['html-injection', 'open-redirect'].includes(family) ? 'medium' as const : 'high' as const, - rootCause: family, location: { path: stack === 'rails' ? 'app/controllers/cases_controller.rb' : stack === 'node' ? 'app.mjs' : stack === 'bun' ? 'app.ts' : 'app.py', symbol: stack === 'rails' ? 'CasesController#show' : 'action' }, - coreColdStart: true as const, heldOut: true as const, filesHash: { vulnerable: sourceHash(sourceFiles(id, 'vulnerable')), fixed: sourceHash(sourceFiles(id, 'fixed')) } }; - })) }; -} -export function loadCorpusManifest(): CorpusManifest { - const manifest = JSON.parse(readFileSync(new URL('./manifest.json', import.meta.url), 'utf8')) as CorpusManifest; - if (JSON.stringify(manifest) !== JSON.stringify(createManifest())) throw new Error('CORPUS_INTEGRITY_MISMATCH'); - return manifest; -} -const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/; -const HEX = /^[a-f0-9]{64}$/; -const SOURCE_PATH = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/; -const safeSourcePath = (path: string) => SOURCE_PATH.test(path) && path.length <= 256 && path.split('/').every(part => part !== '.' && part !== '..'); - -/** Validate the manifest layout of a public or injected corpus without reading its sources. */ -export function validateCorpusManifest(value: unknown): CorpusManifest { - const manifest = value as CorpusManifest; - if (!manifest || typeof manifest !== 'object' || manifest.schemaVersion !== 1 || typeof manifest.version !== 'string' || !/^[a-z0-9][a-z0-9.-]{0,63}$/.test(manifest.version) || - !Array.isArray(manifest.cases) || manifest.cases.length === 0 || canonicalKeys(manifest) !== 'cases,schemaVersion,version') throw new Error('INVALID_CORPUS_MANIFEST'); - const ids = new Set(); - for (const item of manifest.cases) { - if (!item || canonicalKeys(item) !== 'coreColdStart,family,filesHash,heldOut,id,location,rootCause,severity,stack' || - typeof item.id !== 'string' || !SLUG.test(item.id) || ids.has(item.id) || !STACKS.includes(item.stack) || - typeof item.family !== 'string' || !SLUG.test(item.family) || !['critical', 'high', 'medium'].includes(item.severity) || - typeof item.rootCause !== 'string' || !item.rootCause.trim() || !item.location || typeof item.location.path !== 'string' || !safeSourcePath(item.location.path) || - typeof item.location.symbol !== 'string' || !item.location.symbol.trim() || item.coreColdStart !== true || item.heldOut !== true || - !item.filesHash || !HEX.test(item.filesHash.vulnerable) || !HEX.test(item.filesHash.fixed) || item.filesHash.vulnerable === item.filesHash.fixed) throw new Error('INVALID_CORPUS_MANIFEST'); - ids.add(item.id); - } - return manifest; -} -function canonicalKeys(value: object): string { return Object.keys(value).sort().join(','); } - -/** The public development corpus. Its oracles are public, so it is never held out. */ -export function publicCorpus(): EvalCorpus { - return { manifest: loadCorpusManifest(), sourceFiles }; -} - -/** - * Bind an injected corpus to its manifest: every variant's generated sources - * must hash to the pinned value. An injected corpus cannot reuse the public - * corpus version, so its matrices and results never alias public ones. - */ -export function defineEvalCorpus(manifestValue: unknown, generate: EvalCorpus['sourceFiles']): EvalCorpus { - const manifest = validateCorpusManifest(manifestValue); - if (manifest.version === CORPUS_VERSION) throw new Error('INJECTED_CORPUS_REUSES_PUBLIC_VERSION'); - const read = (id: string, variant: EvalVariant) => { - const files = generate(id, variant); - if (!files || typeof files !== 'object' || !Object.keys(files).length || Object.entries(files).some(([path, contents]) => !safeSourcePath(path) || typeof contents !== 'string')) throw new Error('INVALID_CORPUS_SOURCE'); - return files; - }; - for (const item of manifest.cases) for (const variant of ['vulnerable', 'fixed'] as const) { - if (sourceHash(read(item.id, variant)) !== item.filesHash[variant]) throw new Error('CORPUS_INTEGRITY_MISMATCH'); - } - return { manifest, sourceFiles: (id, variant) => { - if (!manifest.cases.some(item => item.id === id)) throw new Error('UNKNOWN_CORPUS_CASE'); - if (variant !== 'vulnerable' && variant !== 'fixed') throw new Error('INVALID_CORPUS_VARIANT'); - return read(id, variant); - } }; -} - -export function materializeCase(id: string, variant: EvalVariant, destination: string, corpus: EvalCorpus = publicCorpus()): { path: string; sourceHash: string } { - const spec = corpus.manifest.cases.find(item => item.id === id); - if (!spec) throw new Error('UNKNOWN_CORPUS_CASE'); - const path = resolve(destination); - if (existsSync(path)) throw new Error('CORPUS_DESTINATION_EXISTS'); - const parent = dirname(path); - if (realpathSync(parent) !== parent || !lstatSync(parent).isDirectory()) throw new Error('UNSAFE_CORPUS_DESTINATION'); - const files = corpus.sourceFiles(id, variant); - if (sourceHash(files) !== spec.filesHash[variant] || Object.keys(files).some(file => !safeSourcePath(file))) throw new Error('CORPUS_INTEGRITY_MISMATCH'); - mkdirSync(path, { mode: 0o700 }); - for (const [file, contents] of Object.entries(files)) { - const output = join(path, file); mkdirSync(dirname(output), { recursive: true, mode: 0o700 }); - writeFileSync(output, contents, { flag: 'wx', mode: 0o600 }); - } - return { path, sourceHash: spec.filesHash[variant] }; -} diff --git a/test/fixtures/cso-eval/rails-lock-provenance.json b/test/fixtures/cso-eval/rails-lock-provenance.json deleted file mode 100644 index 3a32c5aed..000000000 --- a/test/fixtures/cso-eval/rails-lock-provenance.json +++ /dev/null @@ -1,488 +0,0 @@ -{ - "schemaVersion": 1, - "generatedAt": "2026-09-11", - "ruby": "3.2.8", - "bundler": "2.6.7", - "command": "BUNDLE_FORCE_RUBY_PLATFORM=true BUNDLE_IGNORE_CONFIG=true bundle _2.6.7_ update --bundler=2.6.7", - "gemfileSha256": "f09fb9778d39ae776be3c559f7c49402cfa82b06853939e558bda81dde0dfc6c", - "lockSha256": "ab7c4cbb2f6f81a04cd400467bfd78cf7e7aa75fc600530d2646986f7ffaf139", - "archives": [ - { - "name": "action_text-trix", - "version": "2.1.19", - "sha256": "7012f59421009cf284aa651294896414d653a61a2417c9b8714c8476d2f74009", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "actioncable", - "version": "8.1.2", - "sha256": "dc31efc34cca9cdefc5c691ddb8b4b214c0ea5cd1372108cbc1377767fb91969", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "actionmailbox", - "version": "8.1.2", - "sha256": "058b2fb1980e5d5a894f675475fcfa45c62631103d5a2596d9610ec81581889b", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "actionmailer", - "version": "8.1.2", - "sha256": "f4c1d2060f653bfe908aa7fdc5a61c0e5279670de992146582f2e36f8b9175e9", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "actionpack", - "version": "8.1.2", - "sha256": "ced74147a1f0daafaa4bab7f677513fd4d3add574c7839958f7b4f1de44f8423", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "actiontext", - "version": "8.1.2", - "sha256": "0bf57da22a9c19d970779c3ce24a56be31b51c7640f2763ec64aa72e358d2d2d", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "actionview", - "version": "8.1.2", - "sha256": "80455b2588911c9b72cec22d240edacb7c150e800ef2234821269b2b2c3e2e5b", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "activejob", - "version": "8.1.2", - "sha256": "908dab3713b101859536375819f4156b07bdf4c232cc645e7538adb9e302f825", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "activemodel", - "version": "8.1.2", - "sha256": "e21358c11ce68aed3f9838b7e464977bc007b4446c6e4059781e1d5c03bcf33e", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "activerecord", - "version": "8.1.2", - "sha256": "acfbe0cadfcc50fa208011fe6f4eb01cae682ebae0ef57145ba45380c74bcc44", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "activestorage", - "version": "8.1.2", - "sha256": "8a63a48c3999caeee26a59441f813f94681fc35cc41aba7ce1f836add04fba76", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "activesupport", - "version": "8.1.2", - "sha256": "88842578ccd0d40f658289b0e8c842acfe9af751afee2e0744a7873f50b6fdae", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "base64", - "version": "0.3.0", - "sha256": "27337aeabad6ffae05c265c450490628ef3ebd4b67be58257393227588f5a97b", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "bigdecimal", - "version": "4.1.2", - "sha256": "ccc836eab720a525529f70ed0de26a206fdbc9a9e8ac67b3b4ac7318b03e114d", - "source": "RubyGems version API", - "platform": "java" - }, - { - "name": "builder", - "version": "3.3.0", - "sha256": "497918d2f9dca528fdca4b88d84e4ef4387256d984b8154e9d5d3fe5a9c8835f", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "concurrent-ruby", - "version": "1.3.8", - "sha256": "b2f1be836e968ccc78ccfce277ea79c72a88633f22306782c16ff23fb415d1e1", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "connection_pool", - "version": "3.0.2", - "sha256": "33fff5ba71a12d2aa26cb72b1db8bba2a1a01823559fb01d29eb74c286e62e0a", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "crass", - "version": "1.0.7", - "sha256": "94868719948664c89ddcaf0a37c65048413dfcb1c869470a5f7a7ceb5390b295", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "date", - "version": "3.5.1", - "sha256": "12e09477dc932afe45bf768cd362bf73026804e0db1e6c314186d6cd0bee3344", - "source": "RubyGems version API", - "platform": "java" - }, - { - "name": "drb", - "version": "2.2.3", - "sha256": "0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "erb", - "version": "6.0.7", - "sha256": "ef8339f928aa33be9205534be19e9c0daf310c4cc4eb85fd409141c094c57d61", - "source": "RubyGems version API", - "platform": "java" - }, - { - "name": "erubi", - "version": "1.13.1", - "sha256": "a082103b0885dbc5ecf1172fede897f9ebdb745a4b97a5e8dc63953db1ee4ad9", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "globalid", - "version": "1.4.0", - "sha256": "037f12fbf1d9d7a014d501c2d5c77356fd4ddd96d7a7991d6700bba96706f427", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "i18n", - "version": "1.15.2", - "sha256": "00f9eb62412fe593b2a65a97daa75300d37abb8f7202ec748e94b6d46a9dd1b5", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "io-console", - "version": "0.9.2", - "sha256": "efa74f891dd03c0939a931dfc6e74c2813d904763d456ea9762b0525e748db08", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "irb", - "version": "1.18.0", - "sha256": "de9454a0703a54704b9811a5ef31a60c86949fbf4013fcf244fabc7c775248e3", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "json", - "version": "3.0.2", - "sha256": "2afafb9c82faabfb60ed2f37707973fdcb766dba2c99f0b9ed85f073d1d4c3d0", - "source": "RubyGems version API", - "platform": "java" - }, - { - "name": "logger", - "version": "1.7.0", - "sha256": "196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "loofah", - "version": "2.25.2", - "sha256": "2007f746959ac65552456e04b433e83deb22759ab38c838b4445c70e43425918", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "mail", - "version": "2.9.1", - "sha256": "06574eca475253d6c18145dd70af80d0eb970182d55053497c5f4d797ea160e8", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "marcel", - "version": "1.2.1", - "sha256": "1678e9360e32f9eafa917c80029e2f6d10b2715c66a4b87b6d0da9b9cd1f859f", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "mini_mime", - "version": "1.1.5", - "sha256": "8681b7e2e4215f2a159f9400b5816d85e9d8c6c6b491e96a12797e798f8bccef", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "mini_portile2", - "version": "2.8.9", - "sha256": "0cd7c7f824e010c072e33f68bc02d85a00aeb6fce05bb4819c03dfd3c140c289", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "minitest", - "version": "6.0.6", - "sha256": "153ea36d1d987a62942382b61075745042a2b3123b1cd48f4c3675af9cc7d6f1", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "net-imap", - "version": "0.6.6", - "sha256": "96aa4ee50df3060203e649efc341f53480b791d49e150f2fdebf68beb141a8df", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "net-pop", - "version": "0.1.2", - "sha256": "848b4e982013c15b2f0382792268763b748cce91c9e91e36b0f27ed26420dff3", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "net-protocol", - "version": "0.3.0", - "sha256": "ba310c3d4f1cad46bb1ab20336b06669b1ff8f7c568d9cb9342b32a718547472", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "net-smtp", - "version": "0.5.1", - "sha256": "ed96a0af63c524fceb4b29b0d352195c30d82dd916a42f03c62a3a70e5b70736", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "nio4r", - "version": "2.7.5", - "sha256": "d14779d2a9b012ec0148a53344fbb2ed2a3c4d90c5dd923bf281135ab983b2c9", - "source": "RubyGems version API", - "platform": "java" - }, - { - "name": "nokogiri", - "version": "1.19.4", - "sha256": "50c951611c92bca05c51411aef45f1cbc50f2821c4802758c5c6d34696533ab5", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "pp", - "version": "0.6.4", - "sha256": "dfcb0fce700c41456265922884f9fe195d7fbb0674a3578e6c0f69588e82b570", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "prettyprint", - "version": "0.2.0", - "sha256": "2bc9e15581a94742064a3cc8b0fb9d45aae3d03a1baa6ef80922627a0766f193", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "prism", - "version": "1.9.0", - "sha256": "7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "puma", - "version": "7.2.0", - "sha256": "5ef97cc64c0579e6a507cded86286869b6387d58d28abe347c1dd1d7decdf6d0", - "source": "RubyGems version API", - "platform": "java" - }, - { - "name": "racc", - "version": "1.8.1", - "sha256": "54f2e6d1e1b91c154013277d986f52a90e5ececbe91465d29172e49342732b98", - "source": "RubyGems version API", - "platform": "java" - }, - { - "name": "rack", - "version": "3.2.7", - "sha256": "93e13e1c24f93556671d85d2d79fa228c3485815c50d7e2f265b5330c6528fb7", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "rack-session", - "version": "2.1.2", - "sha256": "595434f8c0c3473ae7d7ac56ecda6cc6dfd9d37c0b2b5255330aa1576967ffe8", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "rack-test", - "version": "2.2.0", - "sha256": "005a36692c306ac0b4a9350355ee080fd09ddef1148a5f8b2ac636c720f5c463", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "rackup", - "version": "2.3.1", - "sha256": "6c79c26753778e90983761d677a48937ee3192b3ffef6bc963c0950f94688868", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "rails", - "version": "8.1.2", - "sha256": "5069061b23dfa8706b9f0159ae8b9d35727359103178a26962b868a680ba7d95", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "rails-dom-testing", - "version": "2.3.0", - "sha256": "8acc7953a7b911ca44588bf08737bc16719f431a1cc3091a292bca7317925c1d", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "rails-html-sanitizer", - "version": "1.7.1", - "sha256": "e797a7c9b01e567307e317c576b49ab4168017e63eea4dba9ce3cb587e2f22c2", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "railties", - "version": "8.1.2", - "sha256": "1289ece76b4f7668fc46d07e55cc992b5b8751f2ad85548b7da351b8c59f8055", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "rake", - "version": "13.4.2", - "sha256": "cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "rbs", - "version": "4.1.3", - "sha256": "193582897752597ee7cd2b9d6bf0a7014acd05490d86eb47769cdfd9f2d00ff5", - "source": "RubyGems version API", - "platform": "java" - }, - { - "name": "rdoc", - "version": "8.0.0", - "sha256": "03bf8c08a9639658855a0cfd77c0abca8325c227693f7f33f82957811348c469", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "reline", - "version": "0.7.0", - "sha256": "5b012d8e55dbf9d450f12bde2cf7d15ff546ae80b3f8f3b30e570d431815583d", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "securerandom", - "version": "0.4.1", - "sha256": "cc5193d414a4341b6e225f0cb4446aceca8e50d5e1888743fac16987638ea0b1", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "sqlite3", - "version": "2.9.0", - "sha256": "ece9c00b32ec5f550d3a4a35c41ea8d738563589f090b9dfd0d510b7ae5f296c", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "thor", - "version": "1.5.0", - "sha256": "e3a9e55fe857e44859ce104a84675ab6e8cd59c650a49106a05f55f136425e73", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "timeout", - "version": "0.6.1", - "sha256": "78f57368a7e7bbadec56971f78a3f5ecbcfb59b7fcbb0a3ed6ddc08a5094accb", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "tsort", - "version": "0.2.0", - "sha256": "9650a793f6859a43b6641671278f79cfead60ac714148aabe4e3f0060480089f", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "tzinfo", - "version": "2.0.6", - "sha256": "8daf828cc77bcf7d63b0e3bdb6caa47e2272dcfaf4fbfe46f8c3a9df087a829b", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "uri", - "version": "1.1.1", - "sha256": "379fa58d27ffb1387eaada68c749d1426738bd0f654d812fcc07e7568f5c57c6", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "useragent", - "version": "0.16.11", - "sha256": "700e6413ad4bb954bb63547fa098dddf7b0ebe75b40cc6f93b8d54255b173844", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "websocket-driver", - "version": "0.8.2", - "sha256": "f60120d1377cccf24100bcd1ebc25ceea6f3d5a013fc8e9d16b721016200946e", - "source": "RubyGems version API", - "platform": "java" - }, - { - "name": "websocket-extensions", - "version": "0.1.5", - "sha256": "1c6ba63092cda343eb53fc657110c71c754c56484aad42578495227d717a8241", - "source": "RubyGems version API", - "platform": "ruby" - }, - { - "name": "zeitwerk", - "version": "2.8.3", - "sha256": "2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5", - "source": "RubyGems version API", - "platform": "ruby" - } - ], - "qualification": "not-run; metadata resolution only, no fixture application executed" -} diff --git a/test/fixtures/cso-eval/rails.Gemfile.lock b/test/fixtures/cso-eval/rails.Gemfile.lock deleted file mode 100644 index 03ed8afe5..000000000 --- a/test/fixtures/cso-eval/rails.Gemfile.lock +++ /dev/null @@ -1,210 +0,0 @@ -GEM - remote: https://rubygems.org/ - specs: - action_text-trix (2.1.19) - railties - actioncable (8.1.2) - actionpack (= 8.1.2) - activesupport (= 8.1.2) - nio4r (~> 2.0) - websocket-driver (>= 0.6.1) - zeitwerk (~> 2.6) - actionmailbox (8.1.2) - actionpack (= 8.1.2) - activejob (= 8.1.2) - activerecord (= 8.1.2) - activestorage (= 8.1.2) - activesupport (= 8.1.2) - mail (>= 2.8.0) - actionmailer (8.1.2) - actionpack (= 8.1.2) - actionview (= 8.1.2) - activejob (= 8.1.2) - activesupport (= 8.1.2) - mail (>= 2.8.0) - rails-dom-testing (~> 2.2) - actionpack (8.1.2) - actionview (= 8.1.2) - activesupport (= 8.1.2) - nokogiri (>= 1.8.5) - rack (>= 2.2.4) - rack-session (>= 1.0.1) - rack-test (>= 0.6.3) - rails-dom-testing (~> 2.2) - rails-html-sanitizer (~> 1.6) - useragent (~> 0.16) - actiontext (8.1.2) - action_text-trix (~> 2.1.15) - actionpack (= 8.1.2) - activerecord (= 8.1.2) - activestorage (= 8.1.2) - activesupport (= 8.1.2) - globalid (>= 0.6.0) - nokogiri (>= 1.8.5) - actionview (8.1.2) - activesupport (= 8.1.2) - builder (~> 3.1) - erubi (~> 1.11) - rails-dom-testing (~> 2.2) - rails-html-sanitizer (~> 1.6) - activejob (8.1.2) - activesupport (= 8.1.2) - globalid (>= 0.3.6) - activemodel (8.1.2) - activesupport (= 8.1.2) - activerecord (8.1.2) - activemodel (= 8.1.2) - activesupport (= 8.1.2) - timeout (>= 0.4.0) - activestorage (8.1.2) - actionpack (= 8.1.2) - activejob (= 8.1.2) - activerecord (= 8.1.2) - activesupport (= 8.1.2) - marcel (~> 1.0) - activesupport (8.1.2) - base64 - bigdecimal - concurrent-ruby (~> 1.0, >= 1.3.1) - connection_pool (>= 2.2.5) - drb - i18n (>= 1.6, < 2) - json - logger (>= 1.4.2) - minitest (>= 5.1) - securerandom (>= 0.3) - tzinfo (~> 2.0, >= 2.0.5) - uri (>= 0.13.1) - base64 (0.3.0) - bigdecimal (4.1.2) - builder (3.3.0) - concurrent-ruby (1.3.8) - connection_pool (3.0.2) - crass (1.0.7) - date (3.5.1) - drb (2.2.3) - erb (6.0.7) - erubi (1.13.1) - globalid (1.4.0) - activesupport (>= 6.1) - i18n (1.15.2) - concurrent-ruby (~> 1.0) - io-console (0.9.2) - irb (1.18.0) - pp (>= 0.6.0) - prism (>= 1.3.0) - rdoc (>= 4.0.0) - reline (>= 0.4.2) - json (3.0.2) - logger (1.7.0) - loofah (2.25.2) - crass (~> 1.0.2) - nokogiri (>= 1.12.0) - mail (2.9.1) - logger - mini_mime (>= 0.1.1) - net-imap - net-pop - net-smtp - marcel (1.2.1) - mini_mime (1.1.5) - mini_portile2 (2.8.9) - minitest (6.0.6) - drb (~> 2.0) - prism (~> 1.5) - net-imap (0.6.6) - date - net-protocol - net-pop (0.1.2) - net-protocol - net-protocol (0.3.0) - timeout - net-smtp (0.5.1) - net-protocol - nio4r (2.7.5) - nokogiri (1.19.4) - mini_portile2 (~> 2.8.2) - racc (~> 1.4) - pp (0.6.4) - prettyprint - prettyprint (0.2.0) - prism (1.9.0) - puma (7.2.0) - nio4r (~> 2.0) - racc (1.8.1) - rack (3.2.7) - rack-session (2.1.2) - base64 (>= 0.1.0) - rack (>= 3.0.0) - rack-test (2.2.0) - rack (>= 1.3) - rackup (2.3.1) - rack (>= 3) - rails (8.1.2) - actioncable (= 8.1.2) - actionmailbox (= 8.1.2) - actionmailer (= 8.1.2) - actionpack (= 8.1.2) - actiontext (= 8.1.2) - actionview (= 8.1.2) - activejob (= 8.1.2) - activemodel (= 8.1.2) - activerecord (= 8.1.2) - activestorage (= 8.1.2) - activesupport (= 8.1.2) - bundler (>= 1.15.0) - railties (= 8.1.2) - rails-dom-testing (2.3.0) - activesupport (>= 5.0.0) - minitest - nokogiri (>= 1.6) - rails-html-sanitizer (1.7.1) - loofah (~> 2.25, >= 2.25.2) - nokogiri (>= 1.15.7, != 1.16.7, != 1.16.6, != 1.16.5, != 1.16.4, != 1.16.3, != 1.16.2, != 1.16.1, != 1.16.0.rc1, != 1.16.0) - railties (8.1.2) - actionpack (= 8.1.2) - activesupport (= 8.1.2) - irb (~> 1.13) - rackup (>= 1.0.0) - rake (>= 12.2) - thor (~> 1.0, >= 1.2.2) - tsort (>= 0.2) - zeitwerk (~> 2.6) - rake (13.4.2) - rbs (4.1.3) - logger - prism (>= 1.6.0) - tsort - rdoc (8.0.0) - erb - prism (>= 1.6.0) - rbs (>= 4.0.0) - tsort - reline (0.7.0) - io-console (~> 0.5) - securerandom (0.4.1) - sqlite3 (2.9.0) - mini_portile2 (~> 2.8.0) - thor (1.5.0) - timeout (0.6.1) - tsort (0.2.0) - tzinfo (2.0.6) - concurrent-ruby (~> 1.0) - uri (1.1.1) - useragent (0.16.11) - websocket-driver (0.8.2) - base64 - websocket-extensions (>= 0.1.0) - websocket-extensions (0.1.5) - zeitwerk (2.8.3) - -PLATFORMS - ruby - -DEPENDENCIES - puma (= 7.2.0) - rails (= 8.1.2) - sqlite3 (= 2.9.0) - -BUNDLED WITH - 2.6.7 diff --git a/test/fixtures/cso-http-smoke.c b/test/fixtures/cso-http-smoke.c deleted file mode 100644 index 9c7360c73..000000000 --- a/test/fixtures/cso-http-smoke.c +++ /dev/null @@ -1,41 +0,0 @@ -/* Trusted, dependency-free loopback service for runtime/verifier smoke tests. - * This is infrastructure evidence, not a vulnerable/fixed evaluation pair. */ -#include -#include -#include -#include -#include -#include - -int main(void) { - signal(SIGPIPE, SIG_IGN); - int server = socket(AF_INET, SOCK_STREAM, 0), reuse = 1; - struct sockaddr_in address = {.sin_family = AF_INET, .sin_port = htons(34568), - .sin_addr.s_addr = htonl(INADDR_LOOPBACK)}; - if (server < 0 || setsockopt(server, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) || - bind(server, (void *)&address, sizeof(address)) || listen(server, 8)) return 2; - for (;;) { - int client = accept(server, NULL, NULL); - if (client < 0) continue; - char request[2048] = {0}, response[256]; - ssize_t received = read(client, request, sizeof(request) - 1); - const char *status = "404 Not Found", *body = "MISSING"; - if (received > 0 && strncmp(request, "GET /control ", 13) == 0) { - status = "200 OK"; body = "CONTROL_OK"; - } else if (received > 0 && strncmp(request, "GET /security ", 14) == 0) { - status = "403 Forbidden"; body = "DENIED"; - } - int length = snprintf(response, sizeof(response), - "HTTP/1.1 %s\r\nContent-Length: %zu\r\nConnection: close\r\n\r\n%s", - status, strlen(body), body); - if (length > 0 && (size_t)length < sizeof(response)) { - size_t sent = 0; - while (sent < (size_t)length) { - ssize_t count = write(client, response + sent, (size_t)length - sent); - if (count <= 0) break; - sent += (size_t)count; - } - } - close(client); - } -} diff --git a/test/fixtures/cso-sarif/semgrep-1.179.0.sarif b/test/fixtures/cso-sarif/semgrep-1.179.0.sarif deleted file mode 100644 index ebe8f7616..000000000 --- a/test/fixtures/cso-sarif/semgrep-1.179.0.sarif +++ /dev/null @@ -1,103 +0,0 @@ -{ - "version": "2.1.0", - "runs": [ - { - "invocations": [ - { - "executionSuccessful": true, - "toolExecutionNotifications": [] - } - ], - "results": [ - { - "fingerprints": { - "matchBasedId/v1": "requires login" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "lib/run.py", - "uriBaseId": "%SRCROOT%" - }, - "region": { - "endColumn": 44, - "endLine": 4, - "snippet": { - "text": " return subprocess.call(cmd, shell=True)" - }, - "startColumn": 12, - "startLine": 4 - } - } - } - ], - "message": { - "text": "subprocess call with shell=True" - }, - "properties": {}, - "ruleId": "subprocess-shell-true" - }, - { - "fingerprints": { - "matchBasedId/v1": "requires login" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "src/dir with space/run.py", - "uriBaseId": "%SRCROOT%" - }, - "region": { - "endColumn": 44, - "endLine": 4, - "snippet": { - "text": " return subprocess.call(cmd, shell=True)" - }, - "startColumn": 12, - "startLine": 4 - } - } - } - ], - "message": { - "text": "subprocess call with shell=True" - }, - "properties": {}, - "ruleId": "subprocess-shell-true" - } - ], - "tool": { - "driver": { - "name": "Semgrep OSS", - "rules": [ - { - "defaultConfiguration": { - "level": "error" - }, - "fullDescription": { - "text": "subprocess call with shell=True" - }, - "help": { - "markdown": "subprocess call with shell=True", - "text": "subprocess call with shell=True" - }, - "id": "subprocess-shell-true", - "name": "subprocess-shell-true", - "properties": { - "precision": "very-high", - "tags": [] - }, - "shortDescription": { - "text": "Semgrep Finding: subprocess-shell-true" - } - } - ], - "semanticVersion": "1.179.0" - } - } - } - ], - "$schema": "https://docs.oasis-open.org/sarif/sarif/v2.1.0/os/schemas/sarif-schema-2.1.0.json" -} diff --git a/test/fixtures/cso-sarif/trivy-0.75.0-fs.sarif b/test/fixtures/cso-sarif/trivy-0.75.0-fs.sarif deleted file mode 100644 index 222ca2830..000000000 --- a/test/fixtures/cso-sarif/trivy-0.75.0-fs.sarif +++ /dev/null @@ -1,134 +0,0 @@ -{ - "version": "2.1.0", - "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json", - "runs": [ - { - "tool": { - "driver": { - "fullName": "Trivy Vulnerability Scanner", - "informationUri": "https://github.com/aquasecurity/trivy", - "name": "Trivy", - "rules": [ - { - "id": "DS-0002", - "name": "Misconfiguration", - "shortDescription": { - "text": "Image user should not be 'root'" - }, - "fullDescription": { - "text": "Running containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile." - }, - "defaultConfiguration": { - "level": "error" - }, - "helpUri": "https://avd.aquasec.com/misconfig/ds-0002", - "help": { - "text": "Misconfiguration DS-0002\nType: Dockerfile Security Check\nSeverity: HIGH\nCheck: Image user should not be 'root'\nMessage: Specify at least 1 USER command in Dockerfile with non-root user as argument\nLink: [DS-0002](https://avd.aquasec.com/misconfig/ds-0002)\nRunning containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile.", - "markdown": "**Misconfiguration DS-0002**\n| Type | Severity | Check | Message | Link |\n| --- | --- | --- | --- | --- |\n|Dockerfile Security Check|HIGH|Image user should not be 'root'|Specify at least 1 USER command in Dockerfile with non-root user as argument|[DS-0002](https://avd.aquasec.com/misconfig/ds-0002)|\n\nRunning containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile." - }, - "properties": { - "precision": "very-high", - "security-severity": "8.0", - "tags": [ - "misconfiguration", - "security", - "HIGH" - ] - } - }, - { - "id": "DS-0026", - "name": "Misconfiguration", - "shortDescription": { - "text": "No HEALTHCHECK defined" - }, - "fullDescription": { - "text": "You should add HEALTHCHECK instruction in your docker container images to perform the health check on running containers." - }, - "defaultConfiguration": { - "level": "note" - }, - "helpUri": "https://avd.aquasec.com/misconfig/ds-0026", - "help": { - "text": "Misconfiguration DS-0026\nType: Dockerfile Security Check\nSeverity: LOW\nCheck: No HEALTHCHECK defined\nMessage: Add HEALTHCHECK instruction in your Dockerfile\nLink: [DS-0026](https://avd.aquasec.com/misconfig/ds-0026)\nYou should add HEALTHCHECK instruction in your docker container images to perform the health check on running containers.", - "markdown": "**Misconfiguration DS-0026**\n| Type | Severity | Check | Message | Link |\n| --- | --- | --- | --- | --- |\n|Dockerfile Security Check|LOW|No HEALTHCHECK defined|Add HEALTHCHECK instruction in your Dockerfile|[DS-0026](https://avd.aquasec.com/misconfig/ds-0026)|\n\nYou should add HEALTHCHECK instruction in your docker container images to perform the health check on running containers." - }, - "properties": { - "precision": "very-high", - "security-severity": "2.0", - "tags": [ - "misconfiguration", - "security", - "LOW" - ] - } - } - ], - "version": "0.75.0" - } - }, - "results": [ - { - "ruleId": "DS-0002", - "ruleIndex": 0, - "level": "error", - "message": { - "text": "Artifact: Dockerfile\nType: dockerfile\nVulnerability DS-0002\nSeverity: HIGH\nMessage: Specify at least 1 USER command in Dockerfile with non-root user as argument\nLink: [DS-0002](https://avd.aquasec.com/misconfig/ds-0002)" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "Dockerfile", - "uriBaseId": "ROOTPATH" - }, - "region": { - "startLine": 1, - "startColumn": 1, - "endLine": 1, - "endColumn": 1 - } - }, - "message": { - "text": "Dockerfile" - } - } - ] - }, - { - "ruleId": "DS-0026", - "ruleIndex": 1, - "level": "note", - "message": { - "text": "Artifact: Dockerfile\nType: dockerfile\nVulnerability DS-0026\nSeverity: LOW\nMessage: Add HEALTHCHECK instruction in your Dockerfile\nLink: [DS-0026](https://avd.aquasec.com/misconfig/ds-0026)" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "Dockerfile", - "uriBaseId": "ROOTPATH" - }, - "region": { - "startLine": 1, - "startColumn": 1, - "endLine": 1, - "endColumn": 1 - } - }, - "message": { - "text": "Dockerfile" - } - } - ] - } - ], - "columnKind": "utf16CodeUnits", - "originalUriBaseIds": { - "ROOTPATH": { - "uri": "file:///work/acme-app/" - } - } - } - ] -} diff --git a/test/fixtures/cso-sarif/trivy-0.75.0-repo-url.sarif b/test/fixtures/cso-sarif/trivy-0.75.0-repo-url.sarif deleted file mode 100644 index ed7a80f03..000000000 --- a/test/fixtures/cso-sarif/trivy-0.75.0-repo-url.sarif +++ /dev/null @@ -1,134 +0,0 @@ -{ - "version": "2.1.0", - "$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/main/sarif-2.1/schema/sarif-schema-2.1.0.json", - "runs": [ - { - "tool": { - "driver": { - "fullName": "Trivy Vulnerability Scanner", - "informationUri": "https://github.com/aquasecurity/trivy", - "name": "Trivy", - "rules": [ - { - "id": "DS-0002", - "name": "Misconfiguration", - "shortDescription": { - "text": "Image user should not be 'root'" - }, - "fullDescription": { - "text": "Running containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile." - }, - "defaultConfiguration": { - "level": "error" - }, - "helpUri": "https://avd.aquasec.com/misconfig/ds-0002", - "help": { - "text": "Misconfiguration DS-0002\nType: Dockerfile Security Check\nSeverity: HIGH\nCheck: Image user should not be 'root'\nMessage: Specify at least 1 USER command in Dockerfile with non-root user as argument\nLink: [DS-0002](https://avd.aquasec.com/misconfig/ds-0002)\nRunning containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile.", - "markdown": "**Misconfiguration DS-0002**\n| Type | Severity | Check | Message | Link |\n| --- | --- | --- | --- | --- |\n|Dockerfile Security Check|HIGH|Image user should not be 'root'|Specify at least 1 USER command in Dockerfile with non-root user as argument|[DS-0002](https://avd.aquasec.com/misconfig/ds-0002)|\n\nRunning containers with 'root' user can lead to a container escape situation. It is a best practice to run containers as non-root users, which can be done by adding a 'USER' statement to the Dockerfile." - }, - "properties": { - "precision": "very-high", - "security-severity": "8.0", - "tags": [ - "misconfiguration", - "security", - "HIGH" - ] - } - }, - { - "id": "DS-0026", - "name": "Misconfiguration", - "shortDescription": { - "text": "No HEALTHCHECK defined" - }, - "fullDescription": { - "text": "You should add HEALTHCHECK instruction in your docker container images to perform the health check on running containers." - }, - "defaultConfiguration": { - "level": "note" - }, - "helpUri": "https://avd.aquasec.com/misconfig/ds-0026", - "help": { - "text": "Misconfiguration DS-0026\nType: Dockerfile Security Check\nSeverity: LOW\nCheck: No HEALTHCHECK defined\nMessage: Add HEALTHCHECK instruction in your Dockerfile\nLink: [DS-0026](https://avd.aquasec.com/misconfig/ds-0026)\nYou should add HEALTHCHECK instruction in your docker container images to perform the health check on running containers.", - "markdown": "**Misconfiguration DS-0026**\n| Type | Severity | Check | Message | Link |\n| --- | --- | --- | --- | --- |\n|Dockerfile Security Check|LOW|No HEALTHCHECK defined|Add HEALTHCHECK instruction in your Dockerfile|[DS-0026](https://avd.aquasec.com/misconfig/ds-0026)|\n\nYou should add HEALTHCHECK instruction in your docker container images to perform the health check on running containers." - }, - "properties": { - "precision": "very-high", - "security-severity": "2.0", - "tags": [ - "misconfiguration", - "security", - "LOW" - ] - } - } - ], - "version": "0.75.0" - } - }, - "results": [ - { - "ruleId": "DS-0002", - "ruleIndex": 0, - "level": "error", - "message": { - "text": "Artifact: Dockerfile.build\nType: dockerfile\nVulnerability DS-0002\nSeverity: HIGH\nMessage: Specify at least 1 USER command in Dockerfile with non-root user as argument\nLink: [DS-0002](https://avd.aquasec.com/misconfig/ds-0002)" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "Dockerfile.build", - "uriBaseId": "ROOTPATH" - }, - "region": { - "startLine": 1, - "startColumn": 1, - "endLine": 1, - "endColumn": 1 - } - }, - "message": { - "text": "Dockerfile.build" - } - } - ] - }, - { - "ruleId": "DS-0026", - "ruleIndex": 1, - "level": "note", - "message": { - "text": "Artifact: Dockerfile.build\nType: dockerfile\nVulnerability DS-0026\nSeverity: LOW\nMessage: Add HEALTHCHECK instruction in your Dockerfile\nLink: [DS-0026](https://avd.aquasec.com/misconfig/ds-0026)" - }, - "locations": [ - { - "physicalLocation": { - "artifactLocation": { - "uri": "Dockerfile.build", - "uriBaseId": "ROOTPATH" - }, - "region": { - "startLine": 1, - "startColumn": 1, - "endLine": 1, - "endColumn": 1 - } - }, - "message": { - "text": "Dockerfile.build" - } - } - ] - } - ], - "columnKind": "utf16CodeUnits", - "originalUriBaseIds": { - "ROOTPATH": { - "uri": "file:///https:/github.com/docker-library/hello-world/" - } - } - } - ] -} diff --git a/test/helpers/cso-eval-oracles.ts b/test/helpers/cso-eval-oracles.ts deleted file mode 100644 index 553e15fe9..000000000 --- a/test/helpers/cso-eval-oracles.ts +++ /dev/null @@ -1,102 +0,0 @@ -/** Private evaluator inputs. Never copy this module or its JSON output into producer snapshots. */ -import { createHash } from 'node:crypto'; -import { CORPUS_VERSION, type EvalFamily } from '../fixtures/cso-eval/materialize'; - -export interface OracleRequest { method: 'GET' | 'POST'; path: string; body?: string; headers?: Record } -export interface OracleResponse { status: number; body: string; headers?: Record } -export interface PrivateOracle { - version: string; - controls: Array<{ request: OracleRequest; response: (value: OracleResponse) => boolean }>; - attack: OracleRequest; - vulnerable: (value: OracleResponse) => boolean; - fixed: (value: OracleResponse) => boolean; - /** More than the exposed training assertion: alternative attack payloads. */ - heldOut: Array<{ request: OracleRequest; fixed: (value: OracleResponse) => boolean }>; -} -const get = (params: Record): OracleRequest => ({ method: 'GET', path: `/action?${new URLSearchParams(params)}` }); -const post = (value: object): OracleRequest => ({ method: 'POST', path: '/action', body: JSON.stringify(value), headers: { 'content-type': 'application/json' } }); -const contains = (status: number, expected: string) => (response: OracleResponse) => response.status === status && response.body.includes(expected); -const rejects = (status: number) => (response: OracleResponse) => response.status === status; -const jsonValue = (value: OracleResponse): any => { try { return JSON.parse(value.body); } catch { return null; } }; - -export function oracleFor(family: EvalFamily): PrivateOracle { - const input: Record> = { - 'sql-injection': { - controls: [{ request: get({ name: 'alice' }), response: contains(200, 'HELLO_ALICE') }], - attack: get({ name: "nobody' OR 1=1 --" }), vulnerable: contains(200, 'SECRET_ADMIN_NOTE'), - fixed: value => value.status === 200 && Array.isArray(jsonValue(value)) && jsonValue(value).length === 0, - heldOut: [{ request: get({ name: "' UNION SELECT 'ORACLE_SQL_MARKER' --" }), fixed: value => value.status === 200 && !value.body.includes('ORACLE_SQL_MARKER') }], - }, - 'command-injection': { - controls: [{ request: get({ name: 'Ada' }), response: value => value.status === 200 && jsonValue(value)?.output === 'Ada' }], - attack: get({ name: '"; printf CSO_COMMAND_EXECUTED; #' }), vulnerable: value => value.status === 200 && jsonValue(value)?.output === 'CSO_COMMAND_EXECUTED', fixed: rejects(400), - heldOut: [{ request: get({ name: '$(printf ORACLE_COMMAND_MARKER)' }), fixed: rejects(400) }], - }, - 'path-traversal': { - controls: [{ request: get({ file: 'hello.txt' }), response: contains(200, 'PUBLIC_HELLO') }], - attack: get({ file: '../private.txt' }), vulnerable: contains(200, 'PRIVATE_DOCUMENT_SECRET'), fixed: rejects(403), - heldOut: [{ request: get({ file: 'subdir/../../private.txt' }), fixed: rejects(403) }], - }, - ssrf: { - controls: [{ request: get({ url: 'http://127.0.0.1:8001/public' }), response: contains(200, 'PUBLIC_STATUS') }], - attack: get({ url: 'http://127.0.0.1:8001/private' }), vulnerable: contains(200, 'INTERNAL_SERVICE_SECRET'), fixed: rejects(403), - heldOut: [{ request: get({ url: 'http://localhost:8001/private' }), fixed: rejects(403) }], - }, - 'object-authorization': { - controls: [{ request: get({ id: 'invoice-1' }), response: value => value.status === 200 && jsonValue(value)?.total === 12 }], - attack: get({ id: 'invoice-2' }), vulnerable: value => value.status === 200 && jsonValue(value)?.total === 9800, fixed: rejects(403), - heldOut: [{ request: get({ id: 'invoice-2', owner: 'member-1' }), fixed: rejects(403) }], - }, - 'tenant-isolation': { - controls: [{ request: get({ tenant: 'tenant-a' }), response: contains(200, 'OWN_TENANT_DOCUMENT') }], - attack: get({ tenant: 'tenant-b' }), vulnerable: contains(200, 'OTHER_TENANT_SECRET'), - fixed: value => value.status === 200 && value.body.includes('OWN_TENANT_DOCUMENT') && !value.body.includes('OTHER_TENANT_SECRET'), - heldOut: [{ request: get({ tenant: 'tenant-b', actor_tenant: 'tenant-b' }), fixed: value => value.status === 200 && !value.body.includes('OTHER_TENANT_SECRET') }], - }, - 'html-injection': { - controls: [{ request: get({ name: 'Alice' }), response: contains(200, '
Welcome Alice
') }], - attack: get({ name: '' }), vulnerable: contains(200, '' }), fixed: value => value.status === 200 && !value.body.includes(' value.status === 302 && jsonValue(value)?.next === '/account' && value.headers?.location === '/account' }], - attack: get({ next: 'https://attacker.invalid/collect' }), vulnerable: value => value.status === 302 && value.headers?.location === 'https://attacker.invalid/collect', fixed: rejects(400), - heldOut: [{ request: get({ next: '//attacker.invalid/collect' }), fixed: rejects(400) }, { request: get({ next: '/\\attacker.invalid/collect' }), fixed: rejects(400) }], - }, - 'mass-assignment': { - controls: [{ request: post({ display_name: 'Ada' }), response: value => value.status === 200 && jsonValue(value)?.display_name === 'Ada' }], - attack: post({ role: 'admin' }), vulnerable: value => value.status === 200 && jsonValue(value)?.role === 'admin', fixed: value => value.status === 200 && jsonValue(value)?.role === 'member', - heldOut: [{ request: post({ id: 'member-2', role: 'owner', display_name: 'Grace' }), fixed: value => value.status === 200 && jsonValue(value)?.id === 'member-1' && jsonValue(value)?.role === 'member' && jsonValue(value)?.display_name === 'Grace' }], - }, - 'resource-exhaustion': { - controls: [{ request: get({ count: '5' }), response: value => value.status === 200 && jsonValue(value)?.count === 5 }], - // Bounded proof of missing admission, not an attempt to exhaust the runner. - attack: get({ count: '250' }), vulnerable: value => value.status === 200 && jsonValue(value)?.count === 250, fixed: rejects(400), - heldOut: [{ request: get({ count: '101' }), fixed: rejects(400) }, { request: get({ count: '0' }), fixed: rejects(400) }], - }, - }; - return { version: CORPUS_VERSION, ...input[family] }; -} - -export interface Observation { request: OracleRequest; response: OracleResponse } -export interface PrivateEvidence { - original: { booted: boolean; controls: Observation[]; attack: Observation }; - patched: { booted: boolean; controls: Observation[]; attack: Observation; heldOut: Observation[]; existingTestsPassed: boolean }; - immutableVerifier: boolean; - independentRootCauseReview: boolean; - featurePreserved: boolean; - boundaryMocks: boolean; -} -const sameRequest = (left: OracleRequest, right: OracleRequest) => JSON.stringify(left) === JSON.stringify(right); -/** Only trusted runner observations may enter this function; producer claims are not observations. */ -export function judgeRepair(family: EvalFamily, evidence: PrivateEvidence): { reproduced: boolean; correctRepair: boolean; evidenceHash: string } { - const oracle = oracleFor(family); - const controls = (observations: Observation[]) => oracle.controls.every(control => observations.some(observation => sameRequest(control.request, observation.request) && control.response(observation.response))); - const original = evidence.original, patched = evidence.patched; - const reproduced = original.booted && controls(original.controls) && sameRequest(original.attack.request, oracle.attack) && oracle.vulnerable(original.attack.response); - const correctRepair = reproduced && patched.booted && controls(patched.controls) && sameRequest(patched.attack.request, oracle.attack) && oracle.fixed(patched.attack.response) - && oracle.heldOut.every(assertion => patched.heldOut.some(observation => sameRequest(assertion.request, observation.request) && assertion.fixed(observation.response))) - && patched.existingTestsPassed && evidence.immutableVerifier && evidence.independentRootCauseReview && evidence.featurePreserved && !evidence.boundaryMocks; - return { reproduced, correctRepair, evidenceHash: createHash('sha256').update(JSON.stringify({ version: oracle.version, family, evidence })).digest('hex') }; -} diff --git a/test/helpers/cso-ntfs-fixture.ts b/test/helpers/cso-ntfs-fixture.ts deleted file mode 100644 index dc7633d2e..000000000 --- a/test/helpers/cso-ntfs-fixture.ts +++ /dev/null @@ -1,34 +0,0 @@ -import * as fs from 'node:fs'; -import * as path from 'node:path'; - -export function createPrecisionLossCandidate( - target: string, - contents: string, - readFileId: (file: string) => bigint = file => fs.lstatSync(file, { bigint: true }).ino, -): bigint { - if (fs.existsSync(target)) throw new Error('Precision fixture target already exists'); - const directory = path.dirname(target); - if (fs.lstatSync(directory).isSymbolicLink()) throw new Error('Precision fixture directory must not be linked'); - const pool = fs.mkdtempSync(path.join(directory, 'ntfs-id-')); - let aboveSafe = 0; - try { - for (let batch = 0; batch < 512; batch++) { - const files: string[] = []; - for (let slot = 0; slot < 2; slot++) { - const file = path.join(pool, `candidate-${slot}`); - fs.writeFileSync(file, contents, { flag: 'wx' }); - files.push(file); - const inode = readFileId(file); - if (inode > BigInt(Number.MAX_SAFE_INTEGER)) aboveSafe++; - if (inode > BigInt(Number.MAX_SAFE_INTEGER) && String(Number(inode)) !== String(inode)) { - fs.linkSync(file, target); - return inode; - } - } - for (const file of files) fs.unlinkSync(file); - } - throw new Error(`No precision-losing NTFS file ID within 1024 file creations (${aboveSafe} above-safe observations)`); - } finally { - fs.rmSync(pool, { recursive: true, force: true }); - } -} diff --git a/test/helpers/cso-qualified-cli.ts b/test/helpers/cso-qualified-cli.ts deleted file mode 100644 index 543c8c7be..000000000 --- a/test/helpers/cso-qualified-cli.ts +++ /dev/null @@ -1,51 +0,0 @@ -import * as fs from 'node:fs'; -import * as path from 'node:path'; -import { dispatchCsoCommand, type CsoCliDependencies } from '../../lib/cso/cli'; -import { validateRuntimeCatalog, type QualifiedRuntime, type RuntimeCatalog, type RuntimePlatform } from '../../lib/cso/runtime-catalog'; -import { completeRuntimeCatalogFixture, installStagedRuntime } from './cso-runtime-catalog'; - -export interface QualifiedCsoCli { - readonly catalog: RuntimeCatalog; - readonly runtime: QualifiedRuntime; - command(args: string[]): Promise; -} - -/** Bind a staged Node image to the real command dispatcher without adding a production override. */ -export function qualifiedNodeCli(options: { - image: string; - versions: Record; - watchdogPath: string; - platform: RuntimePlatform; -}): QualifiedCsoCli { - if (!path.isAbsolute(options.watchdogPath) || !fs.statSync(options.watchdogPath).isFile()) { - throw new Error('Node lifecycle qualification requires an absolute compiled watchdog path'); - } - for (const key of ['node', 'npm', 'cso-preparation']) { - if (!/^\d+\.\d+\.\d+$/.test(options.versions[key] ?? '')) { - throw new Error(`Node lifecycle qualification requires exact ${key} version metadata`); - } - } - if (options.versions['cso-preparation'] !== '1.0.0') { - throw new Error('Node lifecycle qualification requires cso-preparation 1.0.0'); - } - - const catalog = completeRuntimeCatalogFixture('node-lifecycle-fixture'); - const fixture = catalog.runtimes.find(item => item.stack === 'node' && item.platform === options.platform); - if (!fixture) throw new Error('Node lifecycle catalog fixture is incomplete'); - const runtime = installStagedRuntime(catalog, { ...fixture, image: options.image, versions: options.versions }); - validateRuntimeCatalog(catalog); - - const dependencies: CsoCliDependencies = Object.freeze({ - runtimeCatalog: catalog, - watchdogPath: () => options.watchdogPath, - }); - return Object.freeze({ - catalog, - runtime, - async command(args: string[]): Promise { - const [command, ...commandArgs] = args; - if (!command) throw new Error('CSO qualification command is required'); - return await dispatchCsoCommand(command, commandArgs, dependencies) as T; - }, - }); -} diff --git a/test/helpers/free-fixtures-data.ts b/test/helpers/free-fixtures-data.ts index 1ad7e8676..0656e0ff1 100644 --- a/test/helpers/free-fixtures-data.ts +++ b/test/helpers/free-fixtures-data.ts @@ -75,10 +75,6 @@ export const FREE_FIXTURES: Readonly> = { 'test/fixtures/coverage-audit-two-file-grep.json': ['test/coverage-audit-evidence.test.ts'], 'test/fixtures/coverage-audit-wc-anchor.json': ['test/coverage-audit-evidence.test.ts'], 'test/fixtures/credential-rejection-39696775546.json': ['test/credential-rejection.test.ts'], - 'test/fixtures/cso-e2e/**': ['test/cso-e2e-report-contract.test.ts'], - 'test/fixtures/cso-eval/**': ['scripts/cso-eval.ts', 'test/cso-eval.test.ts', 'test/cso-stack-cold-integration.test.ts', 'test/helpers/cso-eval-oracles.ts'], - 'test/fixtures/cso-http-smoke.c': ['test/cso-docker-integration.test.ts'], - 'test/fixtures/cso-sarif/**': ['test/cso-scanner-cli.test.ts', 'test/cso-scanners.test.ts'], 'test/fixtures/design-completion-envelope-90f.json': ['test/plan-count-completion.test.ts'], 'test/fixtures/design-consultation-section-design-md.md': ['test/carve-section-sharding.test.ts'], 'test/fixtures/design-count-native-8525.json': ['test/plan-count-completion.test.ts'], diff --git a/test/retired-skills.test.ts b/test/retired-skills.test.ts index dd5d8de8d..e13cdd96a 100644 --- a/test/retired-skills.test.ts +++ b/test/retired-skills.test.ts @@ -426,3 +426,28 @@ describe('gstack-relink after /verify became /build-check (#4593)', () => { expect(fs.readdirSync(path.join(skills, 'verify'))).toEqual(['runbook.md']); }); }); + +describe('/cso stays removed (GST-3920)', () => { + const REMOVED_SCRIPTS = [ + 'scripts/cso-attestation-evidence.ts', + 'scripts/cso-eval.ts', + 'scripts/cso-native-evidence.ts', + 'scripts/cso-public-ghcr.ts', + 'scripts/cso-sbom-packages-check.jq', + 'scripts/cso-sbom-packages.jq', + 'scripts/cso-scanner-catalog.ts', + 'scripts/cso-scanner-matrix.ts', + 'scripts/cso-staging-run.ts', + 'scripts/cso-verify-runtime-base.ts', + ]; + const RUNNERS = ['package.json', 'setup', 'scripts/build.sh', ...fs.readdirSync(path.join(ROOT, '.github', 'workflows')).map(f => path.join('.github', 'workflows', f))]; + + test('its evaluation, image and scanner scripts are gone, and no package script, setup step or workflow still runs one', () => { + expect(REMOVED_SCRIPTS.filter(f => fs.existsSync(path.join(ROOT, f)))).toEqual([]); + const stillRun = RUNNERS.flatMap(runner => { + const text = fs.readFileSync(path.join(ROOT, runner), 'utf8'); + return REMOVED_SCRIPTS.filter(f => text.includes(path.basename(f))).map(f => `${runner}: ${f}`); + }); + expect(stillRun).toEqual([]); + }); +}); diff --git a/test/setup-cso-degrade.test.ts b/test/setup-cso-degrade.test.ts deleted file mode 100644 index 6d0430b2b..000000000 --- a/test/setup-cso-degrade.test.ts +++ /dev/null @@ -1,147 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { runBashScript } from './helpers/bash-script'; - -// #3071: an optional CSO failure no longer aborts setup. The prerequisite -// probe prefers PowerShell 7 and keeps an unknown failure's own output; the -// summary reads bin/.gstack-cso-build-result and names the failed stage, the -// diagnostic and the retry; only GSTACK_STRICT_BUILD=1 makes an incomplete CSO -// set fatal. Runs setup's real blocks with tools stubbed. -const ROOT = path.resolve(import.meta.dir, '..'); -const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf8'); -const fn = (name: string) => { - const start = setup.indexOf(`\n${name}() {`); - const end = setup.indexOf('\n}\n', start); - if (start < 0 || end < 0) throw new Error(`missing setup function ${name}`); - return setup.slice(start + 1, end + 3); -}; -const between = (from: string, to: string) => { - const start = setup.indexOf(from); - const end = setup.indexOf(to, start); - if (start < 0 || end < 0) throw new Error(`missing setup block ${from}`); - return setup.slice(start, end); -}; -const SUMMARY_END = '#cso-build-or-publish-failed"\nfi\n'; -const SUMMARY = between('# ─── CSO native-helper summary', SUMMARY_END) + SUMMARY_END; -const GATE = between('_CSO_READY=0\n', 'if [ "$_CSO_READY" -eq 1 ]; then'); -const tmps: string[] = []; -afterEach(() => { for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true, force: true }); }); -const temp = (prefix: string) => { const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); tmps.push(d); return d; }; -const stub = (dir: string, name: string, body: string) => fs.writeFileSync(path.join(dir, name), `#!/bin/sh\n${body}\n`, { mode: 0o755 }); - -function probe(tools: Record) { - const dir = temp('gstack-cso-probe-'); - for (const [name, body] of Object.entries(tools)) stub(dir, name, body); - stub(dir, 'cygpath', 'shift; echo "$1"'); - return runBashScript([ - 'IS_WINDOWS=1', `SOURCE_GSTACK_DIR="${ROOT}"`, - 'bun_cmd() { echo "--no-compile-autoload-dotenv --no-compile-autoload-bunfig --no-compile-autoload-tsconfig --no-compile-autoload-package-json"; }', - fn('_cso_unavailable'), fn('probe_cso_build_prerequisites'), - 'probe_cso_build_prerequisites', - 'printf "available=%s\\nreason=%s\\ndetail=%s\\n" "$CSO_BUILD_AVAILABLE" "$CSO_FAIL_REASON" "$CSO_PROBE_DETAIL"', - ].join('\n'), { env: { ...process.env, PATH: `${dir}:${process.env.PATH}` }, timeout: 30_000 }); -} - -function summary(record: string | null, opts: { launcher?: boolean; probe?: [reason: string, detail: string] } = {}) { - const dir = temp('gstack-cso-summary-'); - fs.mkdirSync(path.join(dir, 'bin')); - if (record !== null) fs.writeFileSync(path.join(dir, 'bin/.gstack-cso-build-result'), record); - if (opts.launcher) for (const name of ['gstack-cso-launcher', 'gstack-cso-core']) stub(path.join(dir, 'bin'), name, 'echo OLD'); - const probe = opts.probe ? `CSO_BUILD_AVAILABLE=0\nCSO_FAIL_REASON='${opts.probe[0]}'\nCSO_PROBE_DETAIL='${opts.probe[1]}'` : 'CSO_BUILD_AVAILABLE=1'; - const r = runBashScript(['QUIET=0', '_EXE=""', `SOURCE_GSTACK_DIR="${dir}"`, probe, 'log() { echo "$@"; }', SUMMARY].join('\n'), { timeout: 15_000 }); - expect(r.status).toBe(0); - return { out: r.stdout, dir }; -} - -describe.skipIf(process.platform === 'win32')('setup: Windows CSO probe uses PowerShell 7 and keeps unknown failures (#3071)', () => { - test('pwsh is preferred over Windows PowerShell 5.1', () => { - const r = probe({ pwsh: 'exit 0', 'powershell.exe': 'echo "5.1 must not run" >&2; exit 1' }); - expect(r.stdout).toContain('available=1\n'); - }); - - test('a crashed probe keeps its exit status and output instead of blaming the MSVC toolchain', () => { - const r = probe({ pwsh: 'echo "Fatal error. 0xC0000005"; exit 139' }); - expect(r.stdout).toContain('reason=windows-toolchain-probe\n'); - expect(r.stdout).toContain('detail=pwsh exited 139: Fatal error. 0xC0000005\n'); - }); - - test('the missing Visual Studio message still maps to the install instruction', () => { - const r = probe({ pwsh: "echo 'CSO Windows build requires Visual Studio 2022 Build Tools with the Desktop development with C++ workload.' >&2; exit 1" }); - expect(r.stdout).toContain('reason=windows-msvc-toolchain\n'); - }); - - test.skipIf(Bun.which('pwsh') !== null)('without pwsh the probe falls back to powershell.exe', () => { - const r = probe({ 'powershell.exe': 'echo "Native CSO Windows compiler probe failed (2)." >&2; exit 1' }); - expect(r.stdout).toContain('reason=windows-msvc-compile\n'); - }); -}); - -describe.skipIf(process.platform === 'win32')('setup: CSO summary reads the build-result record per stage (#3071)', () => { - const failed = (stage: string, reason: string, installed = '') => - `result=failed\nstage=${stage}\nreason=${reason}\nrevision=1.91.99.0 (abcdef123456)\ninstalled=${installed}\nlauncher=${installed ? 'yes' : 'no'}\ndiagnostic=/src/bin/.gstack-cso-build.log\n`; - - test('a probe failure keeps the prerequisite instruction and names the probe stage', () => { - const { out } = summary(null, { probe: ['windows-toolchain-probe', 'pwsh exited 139: Fatal error'] }); - expect(out).toContain('CSO unavailable: its native helper was not built (windows-toolchain-probe).'); - expect(out).toContain('Failed stage: probe.'); - expect(out).toContain('fix the PowerShell toolchain probe failure (pwsh exited 139: Fatal error)'); - }); - - test('a fresh build failure names the stage, the log and the retry, never a prerequisite install', () => { - const { out, dir } = summary(failed('build', 'exit 42')); - expect(out).toContain("CSO unavailable: the native helper's build step failed (exit 42), so /cso will report not assessed."); - expect(out).toContain('Diagnostic: /src/bin/.gstack-cso-build.log'); - expect(out).toContain('Everything else is installed and works.'); - expect(out).toContain(`Retry: cd ${dir} && bun run build:cso && ./setup`); - expect(out).toContain('troubleshooting.md#cso-build-or-publish-failed'); - expect(out).not.toContain('To enable /cso'); - expect(out).not.toMatch(/prerequisite|\binstall (?:a|the|Visual|Git|Bun)\b/i); - }); - - test('a failed publish that kept the earlier helper says previous CSO kept', () => { - const { out } = summary(failed('publish', 'exit 1', '1.91.34.0 (f67c478f05d8)'), { launcher: true }); - expect(out).toContain('CSO publish step failed (exit 1) for 1.91.99.0 (abcdef123456); previous CSO kept: 1.91.34.0 (f67c478f05d8).'); - expect(out).not.toContain('CSO unavailable'); - }); - - test('a recorded old helper whose files are gone is reported unavailable', () => { - expect(summary(failed('publish', 'exit 1', '1.91.34.0'), { launcher: false }).out).toContain("CSO unavailable: the native helper's publish step failed (exit 1)"); - }); - - test('an interrupted publish says so', () => { - expect(summary(failed('publish', 'interrupted')).out).toContain("publish step was interrupted"); - }); - - test('a successful build or a legacy install without a record prints nothing', () => { - expect(summary('result=ok\nstage=publish\nreason=committed\nrevision=1\ninstalled=1\nlauncher=yes\ndiagnostic=x\n').out).toBe(''); - expect(summary(null).out).toBe(''); - }); -}); - -test('a probe failure removes a stale build record and writes nothing into the source checkout', () => { - const block = between('if [ "$CSO_BUILD_AVAILABLE" -eq 0 ]; then\n rm -f', '\nfi\n'); - expect(block).toContain('rm -f "$SOURCE_GSTACK_DIR/bin/.gstack-cso-build-result"'); - expect(block).not.toContain('>'); -}); - -describe.skipIf(process.platform === 'win32')('setup: an incomplete CSO set is fatal only under GSTACK_STRICT_BUILD=1 (#3071)', () => { - function gate(strict?: string) { - const dir = temp('gstack-cso-gate-'); - fs.mkdirSync(path.join(dir, 'bin')); - const env: Record = { PATH: process.env.PATH ?? '' }; - if (strict !== undefined) env.GSTACK_STRICT_BUILD = strict; - return runBashScript(['set -e', 'CSO_BUILD_AVAILABLE=1', 'IS_WINDOWS=0', '_EXE=""', `SOURCE_GSTACK_DIR="${dir}"`, GATE, 'echo "ready=$_CSO_READY"'].join('\n'), { env, timeout: 15_000 }); - } - test('by default setup continues without CSO', () => { - const r = gate(); - expect(r.status).toBe(0); - expect(r.stdout).toContain('ready=0'); - }); - test('GSTACK_STRICT_BUILD=1 stops setup', () => { - const r = gate('1'); - expect(r.status).toBe(1); - expect(r.stderr).toContain('CSO build completed without its required native artifact set (GSTACK_STRICT_BUILD=1)'); - }); -}); diff --git a/test/setup-cso-windows-probe.test.ts b/test/setup-cso-windows-probe.test.ts deleted file mode 100644 index 554887706..000000000 --- a/test/setup-cso-windows-probe.test.ts +++ /dev/null @@ -1,73 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import * as fs from 'node:fs'; -import * as os from 'node:os'; -import * as path from 'node:path'; -import { runBashScript } from './helpers/bash-script'; - -// E2 (#3015): the Windows /cso build compiles with /W4 /WX, and the Windows -// SDK's winbase.h raises C5105, so every MSVC build failed; and setup reported -// every probe failure as a missing Visual Studio toolchain. The probe and the -// helper builds disable only C5105, and a probe that found MSVC but could not -// compile gets its own reason with the compiler's first diagnostic. Runs the -// real setup function on any OS with powershell.exe/cygpath stubbed. -const ROOT = path.resolve(import.meta.dir, '..'); -const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf8'); -const ps1 = fs.readFileSync(path.join(ROOT, 'scripts/build-cso-windows.ps1'), 'utf8'); -const fn = (name: string) => { - const start = setup.indexOf(`\n${name}() {`); - const end = setup.indexOf('\n}\n', start); - if (start < 0 || end < 0) throw new Error(`missing setup function ${name}`); - return setup.slice(start + 1, end + 3); -}; -const summaryStart = setup.indexOf(' case "$CSO_FAIL_REASON" in'); -const summaryCase = setup.slice(summaryStart, setup.indexOf('\n esac\n', summaryStart) + 8); - -const tmps: string[] = []; -afterEach(() => { for (const t of tmps.splice(0)) fs.rmSync(t, { recursive: true, force: true }); }); - -function probe(powershellOutput: string) { - const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-cso-win-')); - tmps.push(tmp); - // setup resolves pwsh before powershell.exe (#3071); stub both so a runner's - // real PowerShell 7 never answers the probe. - for (const name of ['pwsh', 'powershell.exe']) { - fs.writeFileSync(path.join(tmp, name), `#!/bin/sh\ncat <<'OUT' >&2\n${powershellOutput}\nOUT\nexit 1\n`, { mode: 0o755 }); - } - fs.writeFileSync(path.join(tmp, 'cygpath'), '#!/bin/sh\nshift; echo "$1"\n', { mode: 0o755 }); - return runBashScript([ - 'IS_WINDOWS=1', `SOURCE_GSTACK_DIR="${ROOT}"`, - 'bun_cmd() { echo "--no-compile-autoload-dotenv --no-compile-autoload-bunfig --no-compile-autoload-tsconfig --no-compile-autoload-package-json"; }', - fn('_cso_unavailable'), fn('probe_cso_build_prerequisites'), - 'probe_cso_build_prerequisites', summaryCase, - 'printf "reason=%s\\nprereq=%s\\n" "$CSO_FAIL_REASON" "$_CSO_PREREQ"', - ].join('\n'), { env: { ...process.env, PATH: `${tmp}:${process.env.PATH}` }, timeout: 30_000 }); -} - -describe('setup: Windows /cso build probe (E2)', () => { - test('both MSVC compile lines disable only C5105 and keep /W4 /WX', () => { - const lines = ps1.split('\n').filter(l => l.includes('& $compiler')); - expect(lines).toHaveLength(2); - for (const line of lines) expect(line).toContain('/W4 /WX /wd5105 '); - }); -}); - -// The stubs are POSIX shell scripts named powershell.exe and cygpath, so the -// reason mapping runs off Windows; the real probe needs MSVC (not verified here). -describe.skipIf(process.platform === 'win32')('setup: Windows /cso probe failure mapping (E2)', () => { - test('a compile failure with MSVC present names the compiler error, not a missing toolchain', () => { - const r = probe([ - "C:\\Program Files (x86)\\Windows Kits\\10\\include\\10.0.19041.0\\um\\winbase.h(9531): error C2220: the following warning is treated as an error", - 'Native CSO Windows compiler probe failed (2).', - ].join('\n')); - expect(r.stdout).toContain('reason=windows-msvc-compile\n'); - expect(r.stdout).toContain('prereq=fix the MSVC compile error its toolchain probe reported ('); - expect(r.stdout).toContain('error C2220: the following warning is treated as an error'); - expect(r.stdout).toContain('Visual Studio is already installed'); - }); - - test('a missing Visual Studio toolchain keeps the install instruction', () => { - const r = probe('CSO Windows build requires Visual Studio 2022 Build Tools with the Desktop development with C++ workload.'); - expect(r.stdout).toContain('reason=windows-msvc-toolchain\n'); - expect(r.stdout).toContain('prereq=install Visual Studio 2022 Build Tools with Desktop development with C++\n'); - }); -}); diff --git a/test/test-free-shards.test.ts b/test/test-free-shards.test.ts index 4acd4970a..a658c17ca 100644 --- a/test/test-free-shards.test.ts +++ b/test/test-free-shards.test.ts @@ -391,7 +391,6 @@ describe('test-free-shards: Windows curation', () => { // These replay real callbacks with injected subprocess/SDK boundaries. // Fixture-only bin paths must not hide the native PATH/supervision checks. expect(result.safe).toContain('test/setup-gbrain-remote-caller.test.ts'); - expect(result.safe).toContain('test/cso-windows-build-contract.test.ts'); // Sanity: at least one excluded entry, since we know test/ship-version-sync.test.ts uses /bin/bash expect(result.excluded.length).toBeGreaterThan(0); // Every excluded entry has a non-empty reason @@ -421,21 +420,6 @@ describe('test-free-shards: Windows curation', () => { for (const { reason } of result.excluded) expect(reason).toMatch(/Linux inotify|POSIX signal/); }); - test('excludes POSIX CSO helper suites while retaining portable image metadata coverage', () => { - const posixOnly = [ - 'test/cso-preparation-adversarial.test.ts', - 'test/cso-preparation-container.test.ts', - 'test/cso-preparation-executor.test.ts', - 'test/cso-scanner-cli.test.ts', - 'test/cso-verification-cleanup.test.ts', - 'test/cso-witness.test.ts', - ]; - const portable = ['test/cso-image-provisioning.test.ts', 'test/cso-public-ghcr.test.ts']; - const result = curateWindowsSafe([...posixOnly, ...portable], ROOT); - expect(result.safe).toEqual(portable); - expect(result.excluded.map(({ file }) => file).sort()).toEqual(posixOnly.sort()); - for (const { reason } of result.excluded) expect(reason).toMatch(/Linux|POSIX|Windows/); - }); }); describe('test-free-shards: sharding', () => { diff --git a/test/test-of-test-ratchet.test.ts b/test/test-of-test-ratchet.test.ts index 86ca6a706..ee324b2d8 100644 --- a/test/test-of-test-ratchet.test.ts +++ b/test/test-of-test-ratchet.test.ts @@ -62,8 +62,6 @@ const BASELINE = [ 'test/codex-eval-recording.test.ts', 'test/codex-resume-flag-semantics.test.ts', 'test/context-restore-fragment-verdict.test.ts', // GSTA-91: replays three captured false reds (0/3 on main cb99df4) through the paid context-restore-fragment-match case's fragmentRestoreVerdict - 'test/cso-ntfs-fixture.test.ts', - 'test/cso-windows-build-contract.test.ts', 'test/dependency-security.test.ts', 'test/deps-smoke.test.ts', 'test/design-completion-handoff-scored.test.ts', diff --git a/test/workflow-gh-token.test.ts b/test/workflow-gh-token.test.ts index 08b768291..4754244b9 100644 --- a/test/workflow-gh-token.test.ts +++ b/test/workflow-gh-token.test.ts @@ -34,14 +34,14 @@ export function tokenlessGhSteps(file: string, document: any): string[] { describe('workflow gh token', () => { test('no workflow step runs gh without GH_TOKEN or GITHUB_TOKEN in scope', () => { const files = fs.readdirSync(WORKFLOWS).filter(name => /\.ya?ml$/.test(name)); - expect(files).toContain('cso-runtime-promote.yml'); + expect(files).toContain('weekly-release.yml'); const missing = files.flatMap(file => tokenlessGhSteps(file, Bun.YAML.parse(fs.readFileSync(path.join(WORKFLOWS, file), 'utf8')))); expect(missing).toEqual([]); }); test('the scanner flags the promote run 39691485727 shape and accepts every scope that supplies a token', () => { const step = (env?: Record) => ({ name: 'candidate', env, run: 'set -e\nx="$(jq -r .a f)"\ngh api "repos/$R/compare/$a...$b" > out.json' }); - expect(tokenlessGhSteps('w.yml', { jobs: { propose: { steps: [step({ CSO_QUALIFICATION_RUN: '1' })] } } })).toEqual(['w.yml:propose:candidate']); + expect(tokenlessGhSteps('w.yml', { jobs: { propose: { steps: [step({ QUALIFICATION_RUN: '1' })] } } })).toEqual(['w.yml:propose:candidate']); expect(tokenlessGhSteps('w.yml', { jobs: { propose: { steps: [step({ GH_TOKEN: '${{ github.token }}' })] } } })).toEqual([]); expect(tokenlessGhSteps('w.yml', { jobs: { propose: { env: { GITHUB_TOKEN: 't' }, steps: [step()] } } })).toEqual([]); expect(tokenlessGhSteps('w.yml', { env: { GH_TOKEN: 't' }, jobs: { propose: { steps: [step()] } } })).toEqual([]);