From 363e4e08ffcf5a27403da007ee2dfdcbda05c534 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:02:24 +0900 Subject: [PATCH 01/26] test(release): define exact-artifact SBOM attestation boundary --- ...xact_artifact_sbom_attestation_contract.py | 175 ++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 tests/test_exact_artifact_sbom_attestation_contract.py diff --git a/tests/test_exact_artifact_sbom_attestation_contract.py b/tests/test_exact_artifact_sbom_attestation_contract.py new file mode 100644 index 000000000..1c8f97637 --- /dev/null +++ b/tests/test_exact_artifact_sbom_attestation_contract.py @@ -0,0 +1,175 @@ +"""Contracts for the organization-owned exact-artifact SBOM attestation workflow.""" + +from __future__ import annotations + +import re +from pathlib import Path + +REUSABLE_WORKFLOW = Path( + ".github/workflows/exact-artifact-sbom-attestation.yml" +) +VERIFIER = Path("scripts/ci/verify_exact_artifact_sbom_handoff.py") +DOCTORING = Path("docs/doctoring/exact-artifact-sbom-attestation.md") +ATTEST_ACTION_PIN = "actions/attest@59d89421af93a897026c735860bf21b6eb4f7b26" +CHECKOUT_ACTION_PIN = "actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0" + + +def _required_text(path: Path, label: str) -> str: + """Return one required UTF-8 repository file or fail with a useful contract.""" + assert path.is_file(), f"{label} is missing: {path}" + return path.read_text(encoding="utf-8") + + +def _workflow_call_block(workflow: str) -> str: + """Return the top-level event block from one GitHub Actions workflow.""" + match = re.search(r"(?ms)^on:\n(?P.*?)(?=^\S|\Z)", workflow) + assert match is not None, "workflow must declare a top-level on block" + return match.group("body") + + +def test_reusable_workflow_is_call_only_with_explicit_handoff_inputs() -> None: + """Accept sealed evidence only through an explicit reusable-workflow contract.""" + workflow = _required_text(REUSABLE_WORKFLOW, "reusable attestation workflow") + event_block = _workflow_call_block(workflow) + + assert re.search(r"(?m)^ workflow_call:\s*$", event_block) + for forbidden_trigger in ( + "pull_request", + "push", + "schedule", + "workflow_dispatch", + "repository_dispatch", + ): + assert not re.search( + rf"(?m)^ {re.escape(forbidden_trigger)}:\s*$", + event_block, + ) + + required_inputs = { + "source_repository", + "source_sha", + "evidence_artifact_name", + "evidence_artifact_digest", + "wheel_filename", + "wheel_sha256", + "wheel_sbom_filename", + "wheel_sbom_sha256", + "sdist_filename", + "sdist_sha256", + "sdist_sbom_filename", + "sdist_sbom_sha256", + "source_identity_sha256", + "checksum_sha256", + "predicate_type", + "cyclonedx_schema", + } + for input_name in required_inputs: + input_match = re.search( + rf"(?ms)^ {re.escape(input_name)}:\n" + rf"(?P(?:^ .*\n)+)", + event_block, + ) + assert input_match is not None, f"missing workflow input: {input_name}" + input_body = input_match.group("body") + assert re.search(r"(?m)^ required: true\s*$", input_body) + assert re.search(r"(?m)^ type: string\s*$", input_body) + + +def test_credentialed_job_uses_exact_permissions_and_immutable_trusted_source() -> None: + """Keep signing authority separate from caller-controlled source and credentials.""" + workflow = _required_text(REUSABLE_WORKFLOW, "reusable attestation workflow") + + assert ATTEST_ACTION_PIN in workflow + assert CHECKOUT_ACTION_PIN in workflow + assert "repository: ${{ job.workflow_repository }}" in workflow + assert "ref: ${{ job.workflow_sha }}" in workflow + assert "persist-credentials: false" in workflow + assert "id-token: write" in workflow + assert "attestations: write" in workflow + assert "artifact-metadata: write" in workflow + assert "contents: read" in workflow + + for forbidden_permission in ( + "actions: write", + "contents: write", + "issues: write", + "packages: write", + "pull-requests: write", + "security-events: write", + ): + assert forbidden_permission not in workflow + + assert "actions/checkout@" in workflow + assert "repository: ${{ github.repository }}" not in workflow + assert "ref: ${{ inputs.source_sha }}" not in workflow + assert "secrets: inherit" not in workflow + assert "COPILOT_GITHUB_TOKEN" not in workflow + assert "NVIDIA_NIM_API_KEY" not in workflow + + +def test_verifier_is_data_only_and_workflow_never_executes_downloaded_evidence() -> None: + """Treat every caller artifact as inert bounded data before attestation.""" + workflow = _required_text(REUSABLE_WORKFLOW, "reusable attestation workflow") + verifier = _required_text(VERIFIER, "sealed-evidence verifier") + + assert "verify_exact_artifact_sbom_handoff.py" in workflow + assert "--source-repository" in workflow + assert "--source-sha" in workflow + assert "--evidence-root" in workflow + assert "--output-manifest" in workflow + assert "subprocess" not in verifier + assert "os.system" not in verifier + assert "exec(" not in verifier + assert "eval(" not in verifier + assert "importlib" not in verifier + assert "zipfile" not in verifier + assert "tarfile" not in verifier + + for unsafe_command in ( + "pip install", + "python -m build", + "pytest", + "npm ", + "cargo ", + "chmod +x", + "source ", + ): + assert unsafe_command not in workflow + + +def test_workflow_attests_each_exact_distribution_and_exports_offline_evidence() -> None: + """Bind one CycloneDX predicate to each exact distribution and preserve bundles.""" + workflow = _required_text(REUSABLE_WORKFLOW, "reusable attestation workflow") + + assert workflow.count(ATTEST_ACTION_PIN) == 2 + assert workflow.count("sbom-path:") == 2 + assert workflow.count("subject-name:") == 2 + assert workflow.count("subject-digest:") == 2 + assert "predicate-type" in workflow + assert "bundle-path" in workflow + assert "gh attestation verify" in workflow + assert "--signer-repo" in workflow + assert "--signer-workflow" in workflow + assert "--predicate-type" in workflow + assert "offline" in workflow.lower() + + +def test_doctoring_records_claim_boundary_recovery_and_primary_sources() -> None: + """Require buyer-readable operations, rollback, nonclaims, and APA 7 evidence.""" + doctoring = _required_text(DOCTORING, "SBOM attestation doctoring") + + for required_section in ( + "## Trust boundary", + "## Exact-head lifecycle", + "## Offline verification", + "## Incident recovery and rollback", + "## Claims deliberately not made", + "## References", + ): + assert required_section in doctoring + + assert "SLSA Build Lx (v1.2)" in doctoring + assert "59d89421af93a897026c735860bf21b6eb4f7b26" in doctoring + assert "CycloneDX specification 1.7" in doctoring + assert "SLSA specification version 1.2" in doctoring + assert "Using artifact attestations" in doctoring From a26f09a9f6c403db1f4db334ec71299a97a4cd7c Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:03:16 +0900 Subject: [PATCH 02/26] ci(release): run exact-artifact attestation contract --- ...xact-artifact-sbom-attestation-quality.yml | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 .github/workflows/exact-artifact-sbom-attestation-quality.yml diff --git a/.github/workflows/exact-artifact-sbom-attestation-quality.yml b/.github/workflows/exact-artifact-sbom-attestation-quality.yml new file mode 100644 index 000000000..ec87c7060 --- /dev/null +++ b/.github/workflows/exact-artifact-sbom-attestation-quality.yml @@ -0,0 +1,98 @@ +name: Exact Artifact SBOM Attestation Quality + +on: + pull_request: + branches: [main] + paths: + - ".github/workflows/exact-artifact-sbom-attestation.yml" + - ".github/workflows/exact-artifact-sbom-attestation-quality.yml" + - "scripts/ci/verify_exact_artifact_sbom_handoff.py" + - "tests/test_exact_artifact_sbom_attestation_contract.py" + - "docs/doctoring/exact-artifact-sbom-attestation.md" + - "CHANGELOG.md" + push: + branches: [main] + paths: + - ".github/workflows/exact-artifact-sbom-attestation.yml" + - ".github/workflows/exact-artifact-sbom-attestation-quality.yml" + - "scripts/ci/verify_exact_artifact_sbom_handoff.py" + - "tests/test_exact_artifact_sbom_attestation_contract.py" + - "docs/doctoring/exact-artifact-sbom-attestation.md" + - "CHANGELOG.md" + +concurrency: + group: exact-artifact-sbom-attestation-quality-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + minimum-python-contract: + name: Python 3.10 contract + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Checkout exact contributor head + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + ref: ${{ github.event.pull_request.head.sha || github.sha }} + + - name: Verify exact workflow source checkout + env: + EXPECTED_SOURCE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + run: test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA" + + - name: Set up minimum supported Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.10" + + - name: Compile the contract + run: python -m compileall -q tests/test_exact_artifact_sbom_attestation_contract.py + + exact-contract: + name: Python 3.14 exact contract + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Checkout exact contributor head + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + persist-credentials: false + ref: ${{ github.event.pull_request.head.sha || github.sha }} + + - name: Verify exact workflow source checkout + env: + EXPECTED_SOURCE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + run: test "$(git rev-parse HEAD)" = "$EXPECTED_SOURCE_SHA" + + - name: Set up current stable Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.14" + cache: pip + cache-dependency-path: requirements-opencode-review-ci-hashes.txt + + - name: Install hash-locked quality tooling + run: python -m pip install --disable-pip-version-check --require-hashes -r requirements-opencode-review-ci-hashes.txt + + - name: Run the exact RED or GREEN contract + run: python -m pytest tests/test_exact_artifact_sbom_attestation_contract.py -q + + - name: Compile production and contract files + run: | + python -m compileall -q \ + scripts/ci/verify_exact_artifact_sbom_handoff.py \ + tests/test_exact_artifact_sbom_attestation_contract.py From 0beb249f1156c9e35c098df990c7f28fb54677f5 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:15:24 +0900 Subject: [PATCH 03/26] test(release): bind immutable artifact metadata before signing --- ...xact_artifact_sbom_attestation_contract.py | 94 ++++++++++++++----- 1 file changed, 72 insertions(+), 22 deletions(-) diff --git a/tests/test_exact_artifact_sbom_attestation_contract.py b/tests/test_exact_artifact_sbom_attestation_contract.py index 1c8f97637..02e512345 100644 --- a/tests/test_exact_artifact_sbom_attestation_contract.py +++ b/tests/test_exact_artifact_sbom_attestation_contract.py @@ -12,6 +12,12 @@ DOCTORING = Path("docs/doctoring/exact-artifact-sbom-attestation.md") ATTEST_ACTION_PIN = "actions/attest@59d89421af93a897026c735860bf21b6eb4f7b26" CHECKOUT_ACTION_PIN = "actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0" +DOWNLOAD_ACTION_PIN = ( + "actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131" +) +UPLOAD_ACTION_PIN = ( + "actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a" +) def _required_text(path: Path, label: str) -> str: @@ -27,6 +33,19 @@ def _workflow_call_block(workflow: str) -> str: return match.group("body") +def _job_block(workflow: str, job_name: str) -> str: + """Return one exact top-level job body from a workflow source file.""" + jobs_match = re.search(r"(?ms)^jobs:\n(?P.*)\Z", workflow) + assert jobs_match is not None, "workflow must declare jobs" + jobs_body = jobs_match.group("body") + job_match = re.search( + rf"(?ms)^ {re.escape(job_name)}:\n(?P.*?)(?=^ [A-Za-z0-9_-]+:\n|\Z)", + jobs_body, + ) + assert job_match is not None, f"missing workflow job: {job_name}" + return job_match.group(0) + + def test_reusable_workflow_is_call_only_with_explicit_handoff_inputs() -> None: """Accept sealed evidence only through an explicit reusable-workflow contract.""" workflow = _required_text(REUSABLE_WORKFLOW, "reusable attestation workflow") @@ -48,6 +67,7 @@ def test_reusable_workflow_is_call_only_with_explicit_handoff_inputs() -> None: required_inputs = { "source_repository", "source_sha", + "evidence_artifact_id", "evidence_artifact_name", "evidence_artifact_digest", "wheel_filename", @@ -75,19 +95,45 @@ def test_reusable_workflow_is_call_only_with_explicit_handoff_inputs() -> None: assert re.search(r"(?m)^ type: string\s*$", input_body) +def test_artifact_intake_verifies_exact_immutable_same_run_metadata() -> None: + """Fail closed on artifact identity before the credentialed attestation job.""" + workflow = _required_text(REUSABLE_WORKFLOW, "reusable attestation workflow") + intake = _job_block(workflow, "verify-evidence-artifact") + + assert "permissions:" in intake + assert "actions: read" in intake + assert "contents: read" in intake + assert "id-token: write" not in intake + assert "attestations: write" not in intake + assert "artifact-metadata: write" not in intake + assert "${{ inputs.evidence_artifact_id }}" in intake + assert "${{ inputs.evidence_artifact_name }}" in intake + assert "${{ inputs.evidence_artifact_digest }}" in intake + assert "${{ inputs.source_repository }}" in intake + assert "${{ github.run_id }}" in intake + assert "/actions/artifacts/" in intake + assert ".workflow_run.id" in intake + assert ".expired" in intake + assert DOWNLOAD_ACTION_PIN in intake + assert "artifact-ids: ${{ inputs.evidence_artifact_id }}" in intake + + def test_credentialed_job_uses_exact_permissions_and_immutable_trusted_source() -> None: """Keep signing authority separate from caller-controlled source and credentials.""" workflow = _required_text(REUSABLE_WORKFLOW, "reusable attestation workflow") + signer = _job_block(workflow, "attest-exact-artifacts") - assert ATTEST_ACTION_PIN in workflow + assert ATTEST_ACTION_PIN in signer assert CHECKOUT_ACTION_PIN in workflow - assert "repository: ${{ job.workflow_repository }}" in workflow - assert "ref: ${{ job.workflow_sha }}" in workflow - assert "persist-credentials: false" in workflow - assert "id-token: write" in workflow - assert "attestations: write" in workflow - assert "artifact-metadata: write" in workflow - assert "contents: read" in workflow + assert workflow.count("repository: ${{ job.workflow_repository }}") >= 2 + assert workflow.count("ref: ${{ job.workflow_sha }}") >= 2 + assert workflow.count("persist-credentials: false") >= 2 + assert "needs: verify-evidence-artifact" in signer + assert "contents: read" in signer + assert "id-token: write" in signer + assert "attestations: write" in signer + assert "artifact-metadata: write" in signer + assert "actions: read" not in signer for forbidden_permission in ( "actions: write", @@ -99,7 +145,8 @@ def test_credentialed_job_uses_exact_permissions_and_immutable_trusted_source() ): assert forbidden_permission not in workflow - assert "actions/checkout@" in workflow + assert DOWNLOAD_ACTION_PIN in signer + assert "artifact-ids: ${{ inputs.evidence_artifact_id }}" in signer assert "repository: ${{ github.repository }}" not in workflow assert "ref: ${{ inputs.source_sha }}" not in workflow assert "secrets: inherit" not in workflow @@ -112,7 +159,7 @@ def test_verifier_is_data_only_and_workflow_never_executes_downloaded_evidence() workflow = _required_text(REUSABLE_WORKFLOW, "reusable attestation workflow") verifier = _required_text(VERIFIER, "sealed-evidence verifier") - assert "verify_exact_artifact_sbom_handoff.py" in workflow + assert workflow.count("verify_exact_artifact_sbom_handoff.py") >= 2 assert "--source-repository" in workflow assert "--source-sha" in workflow assert "--evidence-root" in workflow @@ -140,18 +187,21 @@ def test_verifier_is_data_only_and_workflow_never_executes_downloaded_evidence() def test_workflow_attests_each_exact_distribution_and_exports_offline_evidence() -> None: """Bind one CycloneDX predicate to each exact distribution and preserve bundles.""" workflow = _required_text(REUSABLE_WORKFLOW, "reusable attestation workflow") - - assert workflow.count(ATTEST_ACTION_PIN) == 2 - assert workflow.count("sbom-path:") == 2 - assert workflow.count("subject-name:") == 2 - assert workflow.count("subject-digest:") == 2 - assert "predicate-type" in workflow - assert "bundle-path" in workflow - assert "gh attestation verify" in workflow - assert "--signer-repo" in workflow - assert "--signer-workflow" in workflow - assert "--predicate-type" in workflow - assert "offline" in workflow.lower() + signer = _job_block(workflow, "attest-exact-artifacts") + + assert signer.count(ATTEST_ACTION_PIN) == 2 + assert signer.count("sbom-path:") == 2 + assert signer.count("subject-name:") == 2 + assert signer.count("subject-digest:") == 2 + assert "predicate-type" in signer + assert "bundle-path" in signer + assert "gh attestation verify" in signer + assert "--signer-repo" in signer + assert "--signer-workflow" in signer + assert "--predicate-type" in signer + assert "gh attestation trusted-root" in signer + assert UPLOAD_ACTION_PIN in signer + assert "offline" in signer.lower() def test_doctoring_records_claim_boundary_recovery_and_primary_sources() -> None: From 3fce2aab8673e838563e2066ebf88307feb03fc6 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:40:42 +0900 Subject: [PATCH 04/26] release: add exact sealed SBOM attestation workflow --- .../exact-artifact-sbom-attestation.yml | 256 ++++++++++++++++++ 1 file changed, 256 insertions(+) create mode 100644 .github/workflows/exact-artifact-sbom-attestation.yml diff --git a/.github/workflows/exact-artifact-sbom-attestation.yml b/.github/workflows/exact-artifact-sbom-attestation.yml new file mode 100644 index 000000000..c7c298a05 --- /dev/null +++ b/.github/workflows/exact-artifact-sbom-attestation.yml @@ -0,0 +1,256 @@ +name: Exact Artifact SBOM Attestation + +on: + workflow_call: + inputs: + source_repository: + required: true + type: string + source_sha: + required: true + type: string + evidence_artifact_id: + required: true + type: string + evidence_artifact_name: + required: true + type: string + evidence_artifact_digest: + required: true + type: string + wheel_filename: + required: true + type: string + wheel_sha256: + required: true + type: string + wheel_sbom_filename: + required: true + type: string + wheel_sbom_sha256: + required: true + type: string + sdist_filename: + required: true + type: string + sdist_sha256: + required: true + type: string + sdist_sbom_filename: + required: true + type: string + sdist_sbom_sha256: + required: true + type: string + source_identity_sha256: + required: true + type: string + checksum_sha256: + required: true + type: string + predicate_type: + required: true + type: string + cyclonedx_schema: + required: true + type: string + +permissions: + contents: read + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + +jobs: + verify-evidence-artifact: + name: Verify inert sealed evidence + runs-on: ubuntu-24.04 + timeout-minutes: 15 + permissions: + actions: read + contents: read + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Materialize immutable trusted verifier + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + path: trusted-intake + persist-credentials: false + sparse-checkout: scripts/ci/verify_exact_artifact_sbom_handoff.py + sparse-checkout-cone-mode: false + + - name: Verify immutable same-run artifact metadata + env: + GH_TOKEN: ${{ github.token }} + SOURCE_REPOSITORY: ${{ inputs.source_repository }} + SOURCE_SHA: ${{ inputs.source_sha }} + ARTIFACT_ID: ${{ inputs.evidence_artifact_id }} + ARTIFACT_NAME: ${{ inputs.evidence_artifact_name }} + ARTIFACT_DIGEST: ${{ inputs.evidence_artifact_digest }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + test "$SOURCE_REPOSITORY" = "$GITHUB_REPOSITORY" + test "$SOURCE_SHA" = "$GITHUB_SHA" + artifact_json="$(gh api "/repos/${SOURCE_REPOSITORY}/actions/artifacts/${ARTIFACT_ID}")" + jq -e \ + --arg name "$ARTIFACT_NAME" \ + --arg digest "$ARTIFACT_DIGEST" \ + --argjson run_id "$GITHUB_RUN_ID" \ + '.name == $name and .digest == $digest and .workflow_run.id == $run_id and .expired == false' \ + <<<"$artifact_json" >/dev/null + + - name: Download exact same-run evidence by immutable artifact ID + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v6.0.0 + with: + artifact-ids: ${{ inputs.evidence_artifact_id }} + path: sealed-evidence + + - name: Verify sealed evidence as inert bounded data + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python3 -I trusted-intake/scripts/ci/verify_exact_artifact_sbom_handoff.py \ + --source-repository '${{ inputs.source_repository }}' \ + --source-sha '${{ inputs.source_sha }}' \ + --evidence-artifact-name '${{ inputs.evidence_artifact_name }}' \ + --evidence-artifact-digest '${{ inputs.evidence_artifact_digest }}' \ + --evidence-root sealed-evidence \ + --wheel-filename '${{ inputs.wheel_filename }}' \ + --wheel-sha256 '${{ inputs.wheel_sha256 }}' \ + --wheel-sbom-filename '${{ inputs.wheel_sbom_filename }}' \ + --wheel-sbom-sha256 '${{ inputs.wheel_sbom_sha256 }}' \ + --sdist-filename '${{ inputs.sdist_filename }}' \ + --sdist-sha256 '${{ inputs.sdist_sha256 }}' \ + --sdist-sbom-filename '${{ inputs.sdist_sbom_filename }}' \ + --sdist-sbom-sha256 '${{ inputs.sdist_sbom_sha256 }}' \ + --source-identity-sha256 '${{ inputs.source_identity_sha256 }}' \ + --checksum-sha256 '${{ inputs.checksum_sha256 }}' \ + --predicate-type '${{ inputs.predicate_type }}' \ + --cyclonedx-schema '${{ inputs.cyclonedx_schema }}' \ + --output-manifest "${RUNNER_TEMP}/verified-intake.json" + + attest-exact-artifacts: + name: Attest exact wheel and sdist SBOMs + needs: verify-evidence-artifact + runs-on: ubuntu-24.04 + timeout-minutes: 20 + permissions: + contents: read + id-token: write + attestations: write + artifact-metadata: write + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Materialize immutable trusted verifier + uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0 + with: + repository: ${{ job.workflow_repository }} + ref: ${{ job.workflow_sha }} + path: trusted-signer + persist-credentials: false + sparse-checkout: scripts/ci/verify_exact_artifact_sbom_handoff.py + sparse-checkout-cone-mode: false + + - name: Download exact sealed evidence without executing it + uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v6.0.0 + with: + artifact-ids: ${{ inputs.evidence_artifact_id }} + path: sealed-evidence + + - name: Reverify evidence inside the credentialed boundary + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python3 -I trusted-signer/scripts/ci/verify_exact_artifact_sbom_handoff.py \ + --source-repository '${{ inputs.source_repository }}' \ + --source-sha '${{ inputs.source_sha }}' \ + --evidence-artifact-name '${{ inputs.evidence_artifact_name }}' \ + --evidence-artifact-digest '${{ inputs.evidence_artifact_digest }}' \ + --evidence-root sealed-evidence \ + --wheel-filename '${{ inputs.wheel_filename }}' \ + --wheel-sha256 '${{ inputs.wheel_sha256 }}' \ + --wheel-sbom-filename '${{ inputs.wheel_sbom_filename }}' \ + --wheel-sbom-sha256 '${{ inputs.wheel_sbom_sha256 }}' \ + --sdist-filename '${{ inputs.sdist_filename }}' \ + --sdist-sha256 '${{ inputs.sdist_sha256 }}' \ + --sdist-sbom-filename '${{ inputs.sdist_sbom_filename }}' \ + --sdist-sbom-sha256 '${{ inputs.sdist_sbom_sha256 }}' \ + --source-identity-sha256 '${{ inputs.source_identity_sha256 }}' \ + --checksum-sha256 '${{ inputs.checksum_sha256 }}' \ + --predicate-type '${{ inputs.predicate_type }}' \ + --cyclonedx-schema '${{ inputs.cyclonedx_schema }}' \ + --output-manifest "${RUNNER_TEMP}/verified-signer.json" + + - name: Attest exact wheel with its CycloneDX SBOM + id: attest-wheel + uses: actions/attest@59d89421af93a897026c735860bf21b6eb4f7b26 # v4.1.0 + with: + subject-name: ${{ inputs.wheel_filename }} + subject-digest: sha256:${{ inputs.wheel_sha256 }} + sbom-path: sealed-evidence/${{ inputs.wheel_sbom_filename }} + + - name: Attest exact source distribution with its CycloneDX SBOM + id: attest-sdist + uses: actions/attest@59d89421af93a897026c735860bf21b6eb4f7b26 # v4.1.0 + with: + subject-name: ${{ inputs.sdist_filename }} + subject-digest: sha256:${{ inputs.sdist_sha256 }} + sbom-path: sealed-evidence/${{ inputs.sdist_sbom_filename }} + + - name: Verify online and prepare offline bundles + env: + GH_TOKEN: ${{ github.token }} + SIGNER_REPOSITORY: ${{ job.workflow_repository }} + PREDICATE_TYPE: ${{ inputs.predicate_type }} + SOURCE_REPOSITORY: ${{ inputs.source_repository }} + SOURCE_SHA: ${{ inputs.source_sha }} + WHEEL_BUNDLE: ${{ steps.attest-wheel.outputs.bundle-path }} + SDIST_BUNDLE: ${{ steps.attest-sdist.outputs.bundle-path }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + signer_workflow="${SIGNER_REPOSITORY}/.github/workflows/exact-artifact-sbom-attestation.yml" + mkdir -p offline-attestation-evidence + install -m 0444 "$WHEEL_BUNDLE" offline-attestation-evidence/wheel-sbom-attestation.json + install -m 0444 "$SDIST_BUNDLE" offline-attestation-evidence/sdist-sbom-attestation.json + gh attestation trusted-root > offline-attestation-evidence/trusted_root.jsonl + for artifact in '${{ inputs.wheel_filename }}' '${{ inputs.sdist_filename }}'; do + gh attestation verify "sealed-evidence/${artifact}" \ + --repo "$SOURCE_REPOSITORY" \ + --signer-repo "$SIGNER_REPOSITORY" \ + --signer-workflow "$signer_workflow" \ + --source-digest "$SOURCE_SHA" \ + --predicate-type "$PREDICATE_TYPE" + done + gh attestation verify 'sealed-evidence/${{ inputs.wheel_filename }}' \ + --repo "$SOURCE_REPOSITORY" \ + --bundle offline-attestation-evidence/wheel-sbom-attestation.json \ + --custom-trusted-root offline-attestation-evidence/trusted_root.jsonl \ + --signer-repo "$SIGNER_REPOSITORY" \ + --signer-workflow "$signer_workflow" \ + --source-digest "$SOURCE_SHA" \ + --predicate-type "$PREDICATE_TYPE" + gh attestation verify 'sealed-evidence/${{ inputs.sdist_filename }}' \ + --repo "$SOURCE_REPOSITORY" \ + --bundle offline-attestation-evidence/sdist-sbom-attestation.json \ + --custom-trusted-root offline-attestation-evidence/trusted_root.jsonl \ + --signer-repo "$SIGNER_REPOSITORY" \ + --signer-workflow "$signer_workflow" \ + --source-digest "$SOURCE_SHA" \ + --predicate-type "$PREDICATE_TYPE" + cp "${RUNNER_TEMP}/verified-signer.json" offline-attestation-evidence/verified-handoff.json + + - name: Export beginner-readable offline verification evidence + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.0 + with: + name: exact-artifact-sbom-offline-verification + path: offline-attestation-evidence + if-no-files-found: error + retention-days: 90 From ecd19834233f7cd80a59b075fb2b0592f9a4f38c Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:42:12 +0900 Subject: [PATCH 05/26] release: verify inert exact artifact SBOM handoffs --- .../ci/verify_exact_artifact_sbom_handoff.py | 336 ++++++++++++++++++ 1 file changed, 336 insertions(+) create mode 100644 scripts/ci/verify_exact_artifact_sbom_handoff.py diff --git a/scripts/ci/verify_exact_artifact_sbom_handoff.py b/scripts/ci/verify_exact_artifact_sbom_handoff.py new file mode 100644 index 000000000..ac14302d1 --- /dev/null +++ b/scripts/ci/verify_exact_artifact_sbom_handoff.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +"""Verify one sealed wheel/sdist/SBOM handoff without executing its contents.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +import re +import stat +import tempfile +from pathlib import Path +from typing import Any, Iterable + +_SHA256_RE = re.compile(r"^[0-9a-f]{64}$") +_SHA1_RE = re.compile(r"^[0-9a-f]{40}$") +_REPOSITORY_RE = re.compile(r"^[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+$") +_ARTIFACT_DIGEST_RE = re.compile(r"^sha256:[0-9a-f]{64}$") +_CHECKSUM_RE = re.compile(r"^([0-9a-f]{64}) [ *]([^/\\]+)$") +_MAX_JSON_BYTES = 16 * 1024 * 1024 +_MAX_CONTROL_BYTES = 1024 * 1024 +_SOURCE_IDENTITY = "source-identity.json" +_CHECKSUM_FILE = "checksums.sha256" + + +class EvidenceError(ValueError): + """Describe a deterministic sealed-evidence validation failure.""" + + +def _reject_duplicate_keys(pairs: Iterable[tuple[str, Any]]) -> dict[str, Any]: + """Build one JSON object while rejecting duplicate property names.""" + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise EvidenceError(f"duplicate JSON property: {key}") + result[key] = value + return result + + +def _load_json(path: Path, maximum_bytes: int = _MAX_JSON_BYTES) -> Any: + """Load strict bounded UTF-8 JSON from one regular non-symlink file.""" + _require_regular_file(path) + if path.stat().st_size > maximum_bytes: + raise EvidenceError(f"JSON file exceeds {maximum_bytes} bytes: {path.name}") + try: + text = path.read_text(encoding="utf-8", errors="strict") + return json.loads(text, object_pairs_hook=_reject_duplicate_keys) + except UnicodeError as error: + raise EvidenceError(f"invalid UTF-8 in {path.name}") from error + except json.JSONDecodeError as error: + raise EvidenceError(f"invalid JSON in {path.name}: {error.msg}") from error + + +def _require_regular_file(path: Path) -> None: + """Require one existing regular file with no symlink endpoint.""" + try: + mode = path.lstat().st_mode + except FileNotFoundError as error: + raise EvidenceError(f"missing evidence file: {path.name}") from error + if stat.S_ISLNK(mode) or not stat.S_ISREG(mode): + raise EvidenceError(f"evidence member is not a regular file: {path.name}") + + +def _validate_filename(value: str, label: str) -> str: + """Return a safe root-level evidence filename.""" + if not value or value in {".", ".."} or Path(value).name != value: + raise EvidenceError(f"{label} must be one root-level filename") + if "/" in value or "\\" in value or "\x00" in value: + raise EvidenceError(f"{label} contains a forbidden path character") + return value + + +def _validate_sha256(value: str, label: str) -> str: + """Return one lowercase hexadecimal SHA-256 digest.""" + if not _SHA256_RE.fullmatch(value): + raise EvidenceError(f"{label} must be 64 lowercase hexadecimal characters") + return value + + +def _sha256(path: Path) -> str: + """Hash one regular evidence file without loading it into memory.""" + _require_regular_file(path) + digest = hashlib.sha256() + with path.open("rb") as stream: + for block in iter(lambda: stream.read(1024 * 1024), b""): + digest.update(block) + return digest.hexdigest() + + +def _require_digest(path: Path, expected: str, label: str) -> None: + """Require one file to match its externally supplied SHA-256 digest.""" + actual = _sha256(path) + if actual != expected: + raise EvidenceError(f"{label} digest mismatch: expected {expected}, got {actual}") + + +def _parse_checksums(path: Path) -> dict[str, str]: + """Parse a canonical sorted GNU-style SHA-256 checksum file.""" + _require_regular_file(path) + if path.stat().st_size > _MAX_CONTROL_BYTES: + raise EvidenceError("checksum file exceeds the control-file size limit") + try: + lines = path.read_text(encoding="utf-8", errors="strict").splitlines() + except UnicodeError as error: + raise EvidenceError("checksum file is not strict UTF-8") from error + parsed: dict[str, str] = {} + order: list[str] = [] + for line in lines: + match = _CHECKSUM_RE.fullmatch(line) + if match is None: + raise EvidenceError("checksum file contains a noncanonical line") + digest, filename = match.groups() + if filename in parsed: + raise EvidenceError(f"duplicate checksum filename: {filename}") + parsed[filename] = digest + order.append(filename) + if order != sorted(order): + raise EvidenceError("checksum entries must be sorted by filename") + return parsed + + +def _validate_cyclonedx( + path: Path, + *, + schema: str, + subject_name: str, + subject_sha256: str, +) -> None: + """Validate a CycloneDX 1.7 document bound to one exact distribution.""" + document = _load_json(path) + if not isinstance(document, dict): + raise EvidenceError(f"{path.name} must contain a JSON object") + if document.get("$schema") != schema: + raise EvidenceError(f"{path.name} uses an unexpected CycloneDX schema") + if document.get("bomFormat") != "CycloneDX" or document.get("specVersion") != "1.7": + raise EvidenceError(f"{path.name} must be CycloneDX specification 1.7") + metadata = document.get("metadata") + component = metadata.get("component") if isinstance(metadata, dict) else None + if not isinstance(component, dict) or component.get("name") != subject_name: + raise EvidenceError(f"{path.name} root component does not name {subject_name}") + hashes = component.get("hashes") + expected_hash = {"alg": "SHA-256", "content": subject_sha256} + if not isinstance(hashes, list) or expected_hash not in hashes: + raise EvidenceError(f"{path.name} root component is not bound to the subject digest") + + +def _atomic_json(path: Path, value: dict[str, Any]) -> None: + """Publish deterministic JSON atomically without following an output symlink.""" + path.parent.mkdir(parents=True, exist_ok=True) + if path.is_symlink(): + raise EvidenceError("output manifest path must not be a symlink") + payload = json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n" + descriptor, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(descriptor, "w", encoding="utf-8", newline="\n") as stream: + stream.write(payload) + stream.flush() + os.fsync(stream.fileno()) + os.chmod(temporary, 0o644) + os.replace(temporary, path) + finally: + try: + os.unlink(temporary) + except FileNotFoundError: + pass + + +def verify(arguments: argparse.Namespace) -> dict[str, Any]: + """Validate exact evidence and return its deterministic verification manifest.""" + if not _REPOSITORY_RE.fullmatch(arguments.source_repository): + raise EvidenceError("source repository must use owner/name form") + if not _SHA1_RE.fullmatch(arguments.source_sha): + raise EvidenceError("source SHA must be a lowercase 40-character Git SHA") + if not _ARTIFACT_DIGEST_RE.fullmatch(arguments.evidence_artifact_digest): + raise EvidenceError("evidence artifact digest must use sha256:") + + root = Path(arguments.evidence_root) + if root.is_symlink() or not root.is_dir(): + raise EvidenceError("evidence root must be a non-symlink directory") + root = root.resolve() + + names = { + "wheel": _validate_filename(arguments.wheel_filename, "wheel filename"), + "wheel_sbom": _validate_filename( + arguments.wheel_sbom_filename, "wheel SBOM filename" + ), + "sdist": _validate_filename(arguments.sdist_filename, "sdist filename"), + "sdist_sbom": _validate_filename( + arguments.sdist_sbom_filename, "sdist SBOM filename" + ), + "source_identity": _SOURCE_IDENTITY, + "checksums": _CHECKSUM_FILE, + } + if len(set(names.values())) != len(names): + raise EvidenceError("all six evidence filenames must be distinct") + + actual_members: set[str] = set() + for member in root.iterdir(): + if member.is_symlink() or not member.is_file(): + raise EvidenceError(f"unexpected non-regular evidence member: {member.name}") + actual_members.add(member.name) + expected_members = set(names.values()) + if actual_members != expected_members: + missing = sorted(expected_members - actual_members) + extra = sorted(actual_members - expected_members) + raise EvidenceError(f"evidence cardinality mismatch; missing={missing}, extra={extra}") + + expected_digests = { + names["wheel"]: _validate_sha256(arguments.wheel_sha256, "wheel SHA-256"), + names["wheel_sbom"]: _validate_sha256( + arguments.wheel_sbom_sha256, "wheel SBOM SHA-256" + ), + names["sdist"]: _validate_sha256(arguments.sdist_sha256, "sdist SHA-256"), + names["sdist_sbom"]: _validate_sha256( + arguments.sdist_sbom_sha256, "sdist SBOM SHA-256" + ), + names["source_identity"]: _validate_sha256( + arguments.source_identity_sha256, "source identity SHA-256" + ), + names["checksums"]: _validate_sha256( + arguments.checksum_sha256, "checksum SHA-256" + ), + } + for filename, expected in expected_digests.items(): + _require_digest(root / filename, expected, filename) + + checksums = _parse_checksums(root / names["checksums"]) + checksum_subjects = expected_members - {names["checksums"]} + if set(checksums) != checksum_subjects: + raise EvidenceError("checksum file must bind exactly the other five evidence files") + for filename in checksum_subjects: + if checksums[filename] != expected_digests[filename]: + raise EvidenceError(f"checksum handoff mismatch for {filename}") + + identity = _load_json(root / names["source_identity"], _MAX_CONTROL_BYTES) + if not isinstance(identity, dict): + raise EvidenceError("source identity must contain a JSON object") + expected_identity = { + "schema_version": "1.0", + "source_repository": arguments.source_repository, + "source_sha": arguments.source_sha, + "evidence_artifact_name": arguments.evidence_artifact_name, + "evidence_artifact_digest": arguments.evidence_artifact_digest, + "predicate_type": arguments.predicate_type, + "cyclonedx_schema": arguments.cyclonedx_schema, + "artifacts": { + "wheel": { + "filename": names["wheel"], + "sha256": expected_digests[names["wheel"]], + "sbom_filename": names["wheel_sbom"], + "sbom_sha256": expected_digests[names["wheel_sbom"]], + }, + "sdist": { + "filename": names["sdist"], + "sha256": expected_digests[names["sdist"]], + "sbom_filename": names["sdist_sbom"], + "sbom_sha256": expected_digests[names["sdist_sbom"]], + }, + }, + } + if identity != expected_identity: + raise EvidenceError("source identity does not exactly match the sealed handoff") + + _validate_cyclonedx( + root / names["wheel_sbom"], + schema=arguments.cyclonedx_schema, + subject_name=names["wheel"], + subject_sha256=expected_digests[names["wheel"]], + ) + _validate_cyclonedx( + root / names["sdist_sbom"], + schema=arguments.cyclonedx_schema, + subject_name=names["sdist"], + subject_sha256=expected_digests[names["sdist"]], + ) + + manifest = { + "result": "PASS", + "source_repository": arguments.source_repository, + "source_sha": arguments.source_sha, + "predicate_type": arguments.predicate_type, + "cyclonedx_schema": arguments.cyclonedx_schema, + "files": [ + { + "filename": filename, + "sha256": expected_digests[filename], + "size_bytes": (root / filename).stat().st_size, + } + for filename in sorted(expected_members) + ], + } + _atomic_json(Path(arguments.output_manifest), manifest) + return manifest + + +def _parser() -> argparse.ArgumentParser: + """Create the strict command-line parser for sealed handoff verification.""" + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--source-repository", required=True) + parser.add_argument("--source-sha", required=True) + parser.add_argument("--evidence-artifact-name", required=True) + parser.add_argument("--evidence-artifact-digest", required=True) + parser.add_argument("--evidence-root", required=True) + parser.add_argument("--wheel-filename", required=True) + parser.add_argument("--wheel-sha256", required=True) + parser.add_argument("--wheel-sbom-filename", required=True) + parser.add_argument("--wheel-sbom-sha256", required=True) + parser.add_argument("--sdist-filename", required=True) + parser.add_argument("--sdist-sha256", required=True) + parser.add_argument("--sdist-sbom-filename", required=True) + parser.add_argument("--sdist-sbom-sha256", required=True) + parser.add_argument("--source-identity-sha256", required=True) + parser.add_argument("--checksum-sha256", required=True) + parser.add_argument("--predicate-type", required=True) + parser.add_argument("--cyclonedx-schema", required=True) + parser.add_argument("--output-manifest", required=True) + return parser + + +def main(argv: list[str] | None = None) -> int: + """Run sealed-evidence verification and emit one compact decision line.""" + arguments = _parser().parse_args(argv) + try: + manifest = verify(arguments) + except EvidenceError as error: + raise SystemExit(f"sealed evidence verification failed: {error}") from error + print( + "sealed evidence verification passed: " + f"{len(manifest['files'])} files at {manifest['source_sha']}" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 04ded8e2268eeaea3a6367380b64afeed0a195df Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:43:01 +0900 Subject: [PATCH 06/26] docs: doctor exact artifact SBOM attestation boundary --- .../exact-artifact-sbom-attestation.md | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 docs/doctoring/exact-artifact-sbom-attestation.md diff --git a/docs/doctoring/exact-artifact-sbom-attestation.md b/docs/doctoring/exact-artifact-sbom-attestation.md new file mode 100644 index 000000000..c7e0254f4 --- /dev/null +++ b/docs/doctoring/exact-artifact-sbom-attestation.md @@ -0,0 +1,95 @@ +# Exact-artifact SBOM attestation + +## Trust boundary + +The organization-owned reusable workflow signs only an already sealed, same-run evidence artifact. The caller supplies immutable identifiers and digests, but the trusted workflow independently verifies them before minting an OIDC token or invoking `actions/attest@59d89421af93a897026c735860bf21b6eb4f7b26`. + +The boundary has two jobs: + +1. `verify-evidence-artifact` has only `actions: read` and `contents: read`. It confirms the exact artifact ID, name, digest, workflow-run ID, expiry state, source repository, source SHA, six-file cardinality, SHA-256 handoff, strict JSON, CycloneDX specification 1.7 identity, and root distribution binding. +2. `attest-exact-artifacts` receives `id-token: write`, `attestations: write`, `artifact-metadata: write`, and `contents: read` only after the first job succeeds. It downloads the same immutable artifact ID, repeats the data-only verification, and signs the exact wheel and source distribution separately. + +Both jobs load the verifier from `${{ job.workflow_repository }}` at `${{ job.workflow_sha }}` with persisted Git credentials disabled. Caller-controlled source is never checked out in the signing boundary. Downloaded files are treated as inert bytes: the workflow does not import, install, build, test, execute, source, or unpack them. + +The handoff contains exactly: + +- one wheel; +- one CycloneDX 1.7 wheel SBOM; +- one source distribution; +- one CycloneDX 1.7 source-distribution SBOM; +- `source-identity.json`; and +- `checksums.sha256`. + +The checksum file binds the other five files. Externally supplied digests bind all six files, including the checksum file itself. Each SBOM root component must name the exact distribution and include its exact SHA-256 digest. + +## Exact-head lifecycle + +```mermaid +flowchart LR + A[Caller builds exact source SHA] --> B[Caller creates wheel, sdist, two SBOMs] + B --> C[Caller seals six-file artifact] + C --> D[Read-only metadata and data verification] + D --> E[Credentialed job repeats verification] + E --> F[Wheel SBOM attestation] + E --> G[Sdist SBOM attestation] + F --> H[Online signer/predicate/source verification] + G --> H + H --> I[Sigstore bundles and trusted root export] + I --> J[Offline verification artifact] +``` + +A caller must pass its exact `source_repository`, 40-character `source_sha`, same-run artifact ID, artifact name, artifact digest, filenames, SHA-256 digests, CycloneDX schema URI, and SBOM predicate type. The workflow rejects a caller repository or source SHA that does not match the live GitHub run context. + +The verifier emits deterministic compact JSON containing the verified source identity, predicate, schema, filenames, sizes, and hashes. It publishes the manifest atomically and rejects an output symlink. + +## Offline verification + +The signing job preserves both Sigstore bundles, a fresh `trusted_root.jsonl`, and the deterministic verified-handoff manifest. An operator imports the distribution, its matching bundle, the trusted root, and GitHub CLI into the offline environment, then runs: + +```bash +gh attestation verify path/to/distribution \ + --repo OWNER/REPOSITORY \ + --bundle path/to/attestation.json \ + --custom-trusted-root path/to/trusted_root.jsonl \ + --signer-repo ContextualWisdomLab/.github \ + --signer-workflow ContextualWisdomLab/.github/.github/workflows/exact-artifact-sbom-attestation.yml \ + --source-digest EXACT_SOURCE_SHA \ + --predicate-type EXPECTED_SBOM_PREDICATE +``` + +Generate a new trusted root whenever new signed material enters an offline environment. A previously exported root cannot reveal revocation or later key rotation that occurred after export. + +## Incident recovery and rollback + +1. Disable the caller release workflow without changing or deleting existing evidence. +2. Preserve the failed run ID, artifact ID, artifact digest, source SHA, verification output, and attestation bundles. +3. Determine whether the defect is in build output, SBOM generation, the sealed handoff, trusted verification, or signing. +4. Revoke or delete an invalid GitHub attestation only after preserving a forensic copy and documenting affected consumers. +5. Correct the source or workflow through a protected pull request. Never overwrite a distribution while retaining its old filename or digest claim. +6. Rebuild from a new exact source SHA, generate new artifacts and SBOMs, and rerun the complete verification and attestation lifecycle. +7. Publish an incident note identifying invalid subjects, replacement subjects, and consumer actions. + +Rollback means restoring a previously reviewed workflow version and producing new signed material. It does not mean reusing an old attestation for newly built bytes. + +## Claims deliberately not made + +- An SBOM attestation does not prove that the software is vulnerability-free, malware-free, correct, safe, or fit for a particular purpose. +- This workflow does not claim SLSA Build Lx (v1.2). It supplies a narrow SBOM authenticity and exact-subject binding control, not a complete build provenance level. +- CycloneDX conformance does not prove that the component inventory is complete or semantically correct. +- A valid signature does not make caller-provided predicate content trustworthy by itself; the trusted reusable workflow and verifier are the policy boundary. +- Offline verification cannot detect revocation or trusted-root rotation that happened after the trusted root was exported. +- `artifact-metadata: write` does not imply that a non-registry distribution has been published, deployed, or approved for release. + +## References + +CycloneDX Core Working Group. (2025). *CycloneDX specification 1.7*. OWASP Foundation. https://cyclonedx.org/specification/overview/ + +GitHub. (2026). *Using artifact attestations to establish provenance for builds*. GitHub Docs. https://docs.github.com/en/actions/how-tos/secure-your-work/use-artifact-attestations/use-artifact-attestations + +GitHub. (2026). *Verifying attestations offline*. GitHub Docs. https://docs.github.com/en/actions/how-tos/secure-your-work/use-artifact-attestations/verify-attestations-offline + +GitHub. (2026). *actions/attest* (Version 4.1.0) [Computer software]. https://github.com/actions/attest + +Open Source Security Foundation. (2025). *SLSA specification version 1.2*. https://slsa.dev/spec/v1.2/ + +Sigstore Project. (2024). *Sigstore bundle format*. https://docs.sigstore.dev/about/bundle/ From c0f149cc34e6023efdab6824c884954246e83583 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:45:07 +0900 Subject: [PATCH 07/26] test: distinguish executable commands from workflow prose --- tests/test_exact_artifact_sbom_attestation_contract.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test_exact_artifact_sbom_attestation_contract.py b/tests/test_exact_artifact_sbom_attestation_contract.py index 02e512345..601d0032d 100644 --- a/tests/test_exact_artifact_sbom_attestation_contract.py +++ b/tests/test_exact_artifact_sbom_attestation_contract.py @@ -181,7 +181,10 @@ def test_verifier_is_data_only_and_workflow_never_executes_downloaded_evidence() "chmod +x", "source ", ): - assert unsafe_command not in workflow + assert not re.search( + rf"(?m)^\s*{re.escape(unsafe_command)}", + workflow, + ) def test_workflow_attests_each_exact_distribution_and_exports_offline_evidence() -> None: From 27a82aa1d0683128e07615eb1735a4537bb56c07 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:48:06 +0900 Subject: [PATCH 08/26] test: exercise exact artifact handoff verifier boundaries --- ...test_verify_exact_artifact_sbom_handoff.py | 431 ++++++++++++++++++ 1 file changed, 431 insertions(+) create mode 100644 tests/test_verify_exact_artifact_sbom_handoff.py diff --git a/tests/test_verify_exact_artifact_sbom_handoff.py b/tests/test_verify_exact_artifact_sbom_handoff.py new file mode 100644 index 000000000..31c44ac14 --- /dev/null +++ b/tests/test_verify_exact_artifact_sbom_handoff.py @@ -0,0 +1,431 @@ +"""Behavior and hostile-input tests for exact artifact/SBOM handoff verification.""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import os +from pathlib import Path + +import pytest + +from scripts.ci import verify_exact_artifact_sbom_handoff as verifier + +SCHEMA = "https://cyclonedx.org/schema/bom-1.7.schema.json" +PREDICATE = "https://cyclonedx.org/bom" + + +def _digest(path: Path) -> str: + """Return one fixture file's SHA-256 digest.""" + return hashlib.sha256(path.read_bytes()).hexdigest() + + +def _sbom(name: str, digest: str) -> dict[str, object]: + """Return the minimum valid CycloneDX root-component fixture.""" + return { + "$schema": SCHEMA, + "bomFormat": "CycloneDX", + "specVersion": "1.7", + "metadata": { + "component": { + "type": "file", + "name": name, + "hashes": [{"alg": "SHA-256", "content": digest}], + } + }, + } + + +def _write_json(path: Path, value: object) -> None: + """Write deterministic fixture JSON.""" + path.write_text( + json.dumps(value, sort_keys=True, separators=(",", ":")) + "\n", + encoding="utf-8", + ) + + +def _identity(arguments: argparse.Namespace) -> dict[str, object]: + """Return the exact identity document expected by the verifier.""" + return { + "schema_version": "1.0", + "source_repository": arguments.source_repository, + "source_sha": arguments.source_sha, + "evidence_artifact_name": arguments.evidence_artifact_name, + "evidence_artifact_digest": arguments.evidence_artifact_digest, + "predicate_type": arguments.predicate_type, + "cyclonedx_schema": arguments.cyclonedx_schema, + "artifacts": { + "wheel": { + "filename": arguments.wheel_filename, + "sha256": arguments.wheel_sha256, + "sbom_filename": arguments.wheel_sbom_filename, + "sbom_sha256": arguments.wheel_sbom_sha256, + }, + "sdist": { + "filename": arguments.sdist_filename, + "sha256": arguments.sdist_sha256, + "sbom_filename": arguments.sdist_sbom_filename, + "sbom_sha256": arguments.sdist_sbom_sha256, + }, + }, + } + + +def _rewrite_checksums( + root: Path, + arguments: argparse.Namespace, + *, + entries: dict[str, str] | None = None, + sort_entries: bool = True, +) -> None: + """Rewrite and externally reseal the checksum control file.""" + values = entries or { + arguments.wheel_filename: arguments.wheel_sha256, + arguments.wheel_sbom_filename: arguments.wheel_sbom_sha256, + arguments.sdist_filename: arguments.sdist_sha256, + arguments.sdist_sbom_filename: arguments.sdist_sbom_sha256, + "source-identity.json": arguments.source_identity_sha256, + } + names = sorted(values) if sort_entries else list(values) + (root / "checksums.sha256").write_text( + "".join(f"{values[name]} {name}\n" for name in names), + encoding="utf-8", + ) + arguments.checksum_sha256 = _digest(root / "checksums.sha256") + + +def _valid_handoff(tmp_path: Path) -> argparse.Namespace: + """Create one complete exact six-file handoff and its CLI arguments.""" + root = tmp_path / "evidence" + root.mkdir() + wheel = root / "example-1.0.0-py3-none-any.whl" + sdist = root / "example-1.0.0.tar.gz" + wheel.write_bytes(b"wheel-bytes\x00") + sdist.write_bytes(b"sdist-bytes\xff") + wheel_sha = _digest(wheel) + sdist_sha = _digest(sdist) + wheel_sbom = root / "example-wheel.cdx.json" + sdist_sbom = root / "example-sdist.cdx.json" + _write_json(wheel_sbom, _sbom(wheel.name, wheel_sha)) + _write_json(sdist_sbom, _sbom(sdist.name, sdist_sha)) + + arguments = argparse.Namespace( + source_repository="ContextualWisdomLab/example", + source_sha="a" * 40, + evidence_artifact_name="release-evidence", + evidence_artifact_digest="sha256:" + ("b" * 64), + evidence_root=str(root), + wheel_filename=wheel.name, + wheel_sha256=wheel_sha, + wheel_sbom_filename=wheel_sbom.name, + wheel_sbom_sha256=_digest(wheel_sbom), + sdist_filename=sdist.name, + sdist_sha256=sdist_sha, + sdist_sbom_filename=sdist_sbom.name, + sdist_sbom_sha256=_digest(sdist_sbom), + source_identity_sha256="", + checksum_sha256="", + predicate_type=PREDICATE, + cyclonedx_schema=SCHEMA, + output_manifest=str(tmp_path / "verified.json"), + ) + _write_json(root / "source-identity.json", _identity(arguments)) + arguments.source_identity_sha256 = _digest(root / "source-identity.json") + _rewrite_checksums(root, arguments) + return arguments + + +def _reseal_json_member( + arguments: argparse.Namespace, + filename: str, + value: object, +) -> None: + """Rewrite one JSON member while preserving every outer digest binding.""" + root = Path(arguments.evidence_root) + _write_json(root / filename, value) + if filename == arguments.wheel_sbom_filename: + arguments.wheel_sbom_sha256 = _digest(root / filename) + elif filename == arguments.sdist_sbom_filename: + arguments.sdist_sbom_sha256 = _digest(root / filename) + _write_json(root / "source-identity.json", _identity(arguments)) + arguments.source_identity_sha256 = _digest(root / "source-identity.json") + _rewrite_checksums(root, arguments) + + +def test_valid_handoff_is_verified_and_manifest_is_deterministic(tmp_path: Path) -> None: + """Verify the happy path and deterministic sorted output contract.""" + arguments = _valid_handoff(tmp_path) + manifest = verifier.verify(arguments) + output = Path(arguments.output_manifest) + + assert manifest["result"] == "PASS" + assert len(manifest["files"]) == 6 + assert json.loads(output.read_text(encoding="utf-8")) == manifest + assert output.read_text(encoding="utf-8").endswith("\n") + + +def test_main_prints_success_and_returns_zero(tmp_path: Path, capsys: pytest.CaptureFixture[str]) -> None: + """Exercise the public command-line success entrypoint.""" + arguments = _valid_handoff(tmp_path) + argv: list[str] = [] + for name, value in vars(arguments).items(): + argv.extend(("--" + name.replace("_", "-"), str(value))) + + assert verifier.main(argv) == 0 + assert "6 files" in capsys.readouterr().out + + +@pytest.mark.parametrize( + ("attribute", "value", "message"), + [ + ("source_repository", "not-a-repository", "owner/name"), + ("source_sha", "A" * 40, "lowercase 40-character"), + ("evidence_artifact_digest", "sha256:nope", "sha256:"), + ("wheel_sha256", "0" * 63, "wheel SHA-256"), + ], +) +def test_invalid_external_identifiers_fail_closed( + tmp_path: Path, attribute: str, value: str, message: str +) -> None: + """Reject malformed repository, source, artifact, and file digests.""" + arguments = _valid_handoff(tmp_path) + setattr(arguments, attribute, value) + with pytest.raises(verifier.EvidenceError, match=message): + verifier.verify(arguments) + + +@pytest.mark.parametrize("filename", ["", ".", "..", "../escape.whl", "a\\b.whl", "a\x00b.whl"]) +def test_unsafe_filenames_are_rejected(tmp_path: Path, filename: str) -> None: + """Keep every evidence member at one non-hostile root-level filename.""" + arguments = _valid_handoff(tmp_path) + arguments.wheel_filename = filename + with pytest.raises(verifier.EvidenceError, match="filename"): + verifier.verify(arguments) + + +def test_duplicate_expected_filenames_are_rejected(tmp_path: Path) -> None: + """Require six distinct semantic evidence members.""" + arguments = _valid_handoff(tmp_path) + arguments.sdist_filename = arguments.wheel_filename + with pytest.raises(verifier.EvidenceError, match="distinct"): + verifier.verify(arguments) + + +@pytest.mark.parametrize("kind", ["missing", "file", "symlink"]) +def test_evidence_root_must_be_a_real_directory(tmp_path: Path, kind: str) -> None: + """Reject absent, regular-file, and symlink roots.""" + arguments = _valid_handoff(tmp_path) + target = tmp_path / "bad-root" + if kind == "file": + target.write_text("not a directory", encoding="utf-8") + elif kind == "symlink": + target.symlink_to(Path(arguments.evidence_root), target_is_directory=True) + arguments.evidence_root = str(target) + with pytest.raises(verifier.EvidenceError, match="evidence root"): + verifier.verify(arguments) + + +def test_extra_missing_and_nonregular_members_fail_cardinality(tmp_path: Path) -> None: + """Reject extras, omissions, directories, and symlinks in the sealed root.""" + arguments = _valid_handoff(tmp_path) + root = Path(arguments.evidence_root) + (root / "extra.txt").write_text("extra", encoding="utf-8") + with pytest.raises(verifier.EvidenceError, match="cardinality"): + verifier.verify(arguments) + (root / "extra.txt").unlink() + (root / arguments.wheel_filename).unlink() + with pytest.raises(verifier.EvidenceError, match="cardinality"): + verifier.verify(arguments) + + arguments = _valid_handoff(tmp_path / "again") + root = Path(arguments.evidence_root) + (root / arguments.wheel_filename).unlink() + (root / arguments.wheel_filename).mkdir() + with pytest.raises(verifier.EvidenceError, match="non-regular"): + verifier.verify(arguments) + + arguments = _valid_handoff(tmp_path / "third") + root = Path(arguments.evidence_root) + target = root / arguments.sdist_filename + target.unlink() + target.symlink_to(arguments.wheel_filename) + with pytest.raises(verifier.EvidenceError, match="non-regular"): + verifier.verify(arguments) + + +def test_distribution_digest_mismatch_fails_before_semantic_parsing(tmp_path: Path) -> None: + """Reject changed bytes even when filenames and control files are unchanged.""" + arguments = _valid_handoff(tmp_path) + Path(arguments.evidence_root, arguments.wheel_filename).write_bytes(b"tampered") + with pytest.raises(verifier.EvidenceError, match="digest mismatch"): + verifier.verify(arguments) + + +@pytest.mark.parametrize( + "payload", + [ + "not canonical\n", + ("0" * 64) + " duplicate\n" + ("1" * 64) + " duplicate\n", + ], +) +def test_malformed_or_duplicate_checksum_lines_are_rejected( + tmp_path: Path, payload: str +) -> None: + """Reject malformed and duplicate checksum records after external resealing.""" + arguments = _valid_handoff(tmp_path) + checksum = Path(arguments.evidence_root, "checksums.sha256") + checksum.write_text(payload, encoding="utf-8") + arguments.checksum_sha256 = _digest(checksum) + with pytest.raises(verifier.EvidenceError, match="checksum"): + verifier.verify(arguments) + + +def test_unsorted_wrong_set_and_wrong_value_checksums_are_rejected(tmp_path: Path) -> None: + """Bind exactly the other five evidence files in canonical order and value.""" + arguments = _valid_handoff(tmp_path) + root = Path(arguments.evidence_root) + values = { + arguments.wheel_filename: arguments.wheel_sha256, + arguments.wheel_sbom_filename: arguments.wheel_sbom_sha256, + arguments.sdist_filename: arguments.sdist_sha256, + arguments.sdist_sbom_filename: arguments.sdist_sbom_sha256, + "source-identity.json": arguments.source_identity_sha256, + } + reversed_values = dict(reversed(list(sorted(values.items())))) + _rewrite_checksums(root, arguments, entries=reversed_values, sort_entries=False) + with pytest.raises(verifier.EvidenceError, match="sorted"): + verifier.verify(arguments) + + values.pop(arguments.sdist_sbom_filename) + _rewrite_checksums(root, arguments, entries=values) + with pytest.raises(verifier.EvidenceError, match="exactly"): + verifier.verify(arguments) + + values[arguments.sdist_sbom_filename] = arguments.sdist_sbom_sha256 + values[arguments.wheel_filename] = "f" * 64 + _rewrite_checksums(root, arguments, entries=values) + with pytest.raises(verifier.EvidenceError, match="handoff mismatch"): + verifier.verify(arguments) + + +def test_source_identity_must_be_an_exact_object(tmp_path: Path) -> None: + """Reject non-object and semantically mismatched source identities.""" + arguments = _valid_handoff(tmp_path) + root = Path(arguments.evidence_root) + _write_json(root / "source-identity.json", []) + arguments.source_identity_sha256 = _digest(root / "source-identity.json") + _rewrite_checksums(root, arguments) + with pytest.raises(verifier.EvidenceError, match="JSON object"): + verifier.verify(arguments) + + identity = _identity(arguments) + identity["source_sha"] = "c" * 40 + _write_json(root / "source-identity.json", identity) + arguments.source_identity_sha256 = _digest(root / "source-identity.json") + _rewrite_checksums(root, arguments) + with pytest.raises(verifier.EvidenceError, match="exactly match"): + verifier.verify(arguments) + + +@pytest.mark.parametrize( + ("mutation", "message"), + [ + (lambda value: [], "JSON object"), + (lambda value: {**value, "$schema": "wrong"}, "unexpected CycloneDX schema"), + (lambda value: {**value, "bomFormat": "SPDX"}, "specification 1.7"), + (lambda value: {**value, "specVersion": "1.6"}, "specification 1.7"), + (lambda value: {**value, "metadata": {}}, "root component"), + ( + lambda value: { + **value, + "metadata": {"component": {"name": "wrong", "hashes": []}}, + }, + "root component", + ), + ( + lambda value: { + **value, + "metadata": { + "component": { + "name": value["metadata"]["component"]["name"], + "hashes": [], + } + }, + }, + "not bound", + ), + ], +) +def test_cyclonedx_semantics_fail_closed( + tmp_path: Path, mutation: object, message: str +) -> None: + """Reject the wrong schema, version, root component, or subject hash.""" + arguments = _valid_handoff(tmp_path) + root = Path(arguments.evidence_root) + original = json.loads((root / arguments.wheel_sbom_filename).read_text(encoding="utf-8")) + altered = mutation(original) # type: ignore[operator] + _reseal_json_member(arguments, arguments.wheel_sbom_filename, altered) + with pytest.raises(verifier.EvidenceError, match=message): + verifier.verify(arguments) + + +def test_strict_json_rejects_duplicate_keys_bad_utf8_and_oversize( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Exercise strict bounded JSON parsing boundaries directly.""" + duplicate = tmp_path / "duplicate.json" + duplicate.write_text('{"a":1,"a":2}', encoding="utf-8") + with pytest.raises(verifier.EvidenceError, match="duplicate"): + verifier._load_json(duplicate) + + malformed = tmp_path / "malformed.json" + malformed.write_text("{", encoding="utf-8") + with pytest.raises(verifier.EvidenceError, match="invalid JSON"): + verifier._load_json(malformed) + + bad_utf8 = tmp_path / "bad.json" + bad_utf8.write_bytes(b"\xff") + with pytest.raises(verifier.EvidenceError, match="UTF-8"): + verifier._load_json(bad_utf8) + + oversized = tmp_path / "oversized.json" + oversized.write_text("{}", encoding="utf-8") + monkeypatch.setattr(Path, "stat", lambda self: argparse.Namespace(st_size=3)) + with pytest.raises(verifier.EvidenceError, match="exceeds"): + verifier._load_json(oversized, maximum_bytes=2) + + +def test_regular_file_and_output_publication_edges( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """Cover missing inputs, output symlinks, and temporary cleanup fallback.""" + missing = tmp_path / "missing" + with pytest.raises(verifier.EvidenceError, match="missing"): + verifier._require_regular_file(missing) + + directory = tmp_path / "directory" + directory.mkdir() + with pytest.raises(verifier.EvidenceError, match="regular"): + verifier._require_regular_file(directory) + + output = tmp_path / "output.json" + output.symlink_to(missing) + with pytest.raises(verifier.EvidenceError, match="symlink"): + verifier._atomic_json(output, {"result": "PASS"}) + output.unlink() + + monkeypatch.setattr(os, "replace", lambda source, destination: None) + verifier._atomic_json(output, {"result": "PASS"}) + assert not output.exists() + + +def test_main_converts_validation_errors_to_system_exit(tmp_path: Path) -> None: + """Keep command-line failures compact and free of tracebacks by default.""" + arguments = _valid_handoff(tmp_path) + arguments.source_repository = "bad" + argv: list[str] = [] + for name, value in vars(arguments).items(): + argv.extend(("--" + name.replace("_", "-"), str(value))) + with pytest.raises(SystemExit, match="sealed evidence verification failed"): + verifier.main(argv) From 33ebfe634856bb4b356e2707e395ba1d2dac785e Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:48:58 +0900 Subject: [PATCH 09/26] ci: enforce complete exact handoff verifier coverage --- ...xact-artifact-sbom-attestation-quality.yml | 28 +++++++++++++++---- 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/.github/workflows/exact-artifact-sbom-attestation-quality.yml b/.github/workflows/exact-artifact-sbom-attestation-quality.yml index ec87c7060..43a154178 100644 --- a/.github/workflows/exact-artifact-sbom-attestation-quality.yml +++ b/.github/workflows/exact-artifact-sbom-attestation-quality.yml @@ -8,6 +8,7 @@ on: - ".github/workflows/exact-artifact-sbom-attestation-quality.yml" - "scripts/ci/verify_exact_artifact_sbom_handoff.py" - "tests/test_exact_artifact_sbom_attestation_contract.py" + - "tests/test_verify_exact_artifact_sbom_handoff.py" - "docs/doctoring/exact-artifact-sbom-attestation.md" - "CHANGELOG.md" push: @@ -17,6 +18,7 @@ on: - ".github/workflows/exact-artifact-sbom-attestation-quality.yml" - "scripts/ci/verify_exact_artifact_sbom_handoff.py" - "tests/test_exact_artifact_sbom_attestation_contract.py" + - "tests/test_verify_exact_artifact_sbom_handoff.py" - "docs/doctoring/exact-artifact-sbom-attestation.md" - "CHANGELOG.md" @@ -54,11 +56,15 @@ jobs: with: python-version: "3.10" - - name: Compile the contract - run: python -m compileall -q tests/test_exact_artifact_sbom_attestation_contract.py + - name: Compile production and contracts on Python 3.10 + run: | + python -m compileall -q \ + scripts/ci/verify_exact_artifact_sbom_handoff.py \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py exact-contract: - name: Python 3.14 exact contract + name: Python 3.14 exact contract and complete coverage runs-on: ubuntu-latest timeout-minutes: 15 steps: @@ -88,11 +94,21 @@ jobs: - name: Install hash-locked quality tooling run: python -m pip install --disable-pip-version-check --require-hashes -r requirements-opencode-review-ci-hashes.txt - - name: Run the exact RED or GREEN contract - run: python -m pytest tests/test_exact_artifact_sbom_attestation_contract.py -q + - name: Run exact contracts with complete verifier branch coverage + run: | + python -m coverage erase + python -m coverage run --branch -m pytest -q \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + python -m coverage report \ + --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ + --show-missing \ + --fail-under=100 + python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py - name: Compile production and contract files run: | python -m compileall -q \ scripts/ci/verify_exact_artifact_sbom_handoff.py \ - tests/test_exact_artifact_sbom_attestation_contract.py + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py From 1a41d33d099ce9e0e1a1babf9e011d7f2b0f8c23 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:53:17 +0900 Subject: [PATCH 10/26] ci: repair exact artifact handoff contracts --- .../workflows/repair-pr797-exact-handoff.yml | 117 ++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 .github/workflows/repair-pr797-exact-handoff.yml diff --git a/.github/workflows/repair-pr797-exact-handoff.yml b/.github/workflows/repair-pr797-exact-handoff.yml new file mode 100644 index 000000000..3b1da775a --- /dev/null +++ b/.github/workflows/repair-pr797-exact-handoff.yml @@ -0,0 +1,117 @@ +name: Repair PR 797 exact handoff contracts + +on: + push: + branches: + - release/exact-artifact-sbom-attestation + paths: + - .github/workflows/repair-pr797-exact-handoff.yml + +permissions: + contents: read + +concurrency: + group: repair-pr797-exact-handoff + cancel-in-progress: true + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + +jobs: + repair: + if: >- + github.repository == 'ContextualWisdomLab/.github' && + github.actor == 'seonghobae' && + github.ref == 'refs/heads/release/exact-artifact-sbom-attestation' + permissions: + contents: write + runs-on: ubuntu-24.04 + timeout-minutes: 20 + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Check out exact repair trigger + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + fetch-depth: 0 + persist-credentials: false + + - name: Apply two reviewed test-contract repairs + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + test "$(git rev-parse HEAD)" = "$GITHUB_SHA" + python3 - <<'PY' + from pathlib import Path + + replacements = { + Path('tests/test_exact_artifact_sbom_attestation_contract.py'): ( + ' assert "${{ github.run_id }}" in intake\n', + ' assert "GITHUB_RUN_ID" in intake\n', + ), + Path('tests/test_verify_exact_artifact_sbom_handoff.py'): ( + ' root.mkdir()\n', + ' root.mkdir(parents=True)\n', + ), + } + for path, (old, new) in replacements.items(): + source = path.read_text(encoding='utf-8') + if source.count(old) != 1: + raise SystemExit(f'{path}: expected exactly one repair anchor') + path.write_text(source.replace(old, new, 1), encoding='utf-8') + PY + rm .github/workflows/repair-pr797-exact-handoff.yml + git diff --check + + - name: Set up Python 3.14 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.14" + cache: pip + cache-dependency-path: requirements-opencode-review-ci-hashes.txt + + - name: Install exact hash-locked quality tooling + run: python -m pip install --disable-pip-version-check --require-hashes -r requirements-opencode-review-ci-hashes.txt + + - name: Verify exact contract and complete verifier coverage + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python -m coverage erase + python -m coverage run --branch -m pytest -q \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + python -m coverage report \ + --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ + --show-missing \ + --fail-under=100 + python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py + python -m compileall -q \ + scripts/ci/verify_exact_artifact_sbom_handoff.py \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + test ! -e .github/workflows/repair-pr797-exact-handoff.yml + git diff --check + + - name: Publish verified workflow-free repair + env: + EXPECTED_HEAD: ${{ github.sha }} + HEAD_BRANCH: release/exact-artifact-sbom-attestation + PUSH_TOKEN: ${{ github.token }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + remote_head="$(git ls-remote origin "refs/heads/${HEAD_BRANCH}" | cut -f1)" + test "$remote_head" = "$EXPECTED_HEAD" + git config user.name "github-actions[bot]" + git config user.email "41898282+github-actions[bot]@users.noreply.github.com" + git add --all + git diff --cached --check + git diff --cached --quiet && { echo "No verified repair generated" >&2; exit 1; } + git commit -m "test: repair exact artifact handoff contracts" + auth_header="$(printf 'x-access-token:%s' "$PUSH_TOKEN" | base64 | tr -d '\n')" + echo "::add-mask::$auth_header" + git -c http.extraheader="AUTHORIZATION: basic ${auth_header}" \ + push --force-with-lease="refs/heads/${HEAD_BRANCH}:${EXPECTED_HEAD}" \ + origin "HEAD:refs/heads/${HEAD_BRANCH}" From e2347d822ae83d60fbd4e671ccda4caa5ed4529a Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 13:54:56 +0900 Subject: [PATCH 11/26] ci: publish PR 797 test-only repair before cleanup --- .github/workflows/repair-pr797-exact-handoff.yml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/repair-pr797-exact-handoff.yml b/.github/workflows/repair-pr797-exact-handoff.yml index 3b1da775a..dfd39bf2f 100644 --- a/.github/workflows/repair-pr797-exact-handoff.yml +++ b/.github/workflows/repair-pr797-exact-handoff.yml @@ -63,7 +63,6 @@ jobs: raise SystemExit(f'{path}: expected exactly one repair anchor') path.write_text(source.replace(old, new, 1), encoding='utf-8') PY - rm .github/workflows/repair-pr797-exact-handoff.yml git diff --check - name: Set up Python 3.14 @@ -92,10 +91,9 @@ jobs: scripts/ci/verify_exact_artifact_sbom_handoff.py \ tests/test_exact_artifact_sbom_attestation_contract.py \ tests/test_verify_exact_artifact_sbom_handoff.py - test ! -e .github/workflows/repair-pr797-exact-handoff.yml git diff --check - - name: Publish verified workflow-free repair + - name: Publish verified test-only repair env: EXPECTED_HEAD: ${{ github.sha }} HEAD_BRANCH: release/exact-artifact-sbom-attestation @@ -106,7 +104,9 @@ jobs: test "$remote_head" = "$EXPECTED_HEAD" git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add --all + git add \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py git diff --cached --check git diff --cached --quiet && { echo "No verified repair generated" >&2; exit 1; } git commit -m "test: repair exact artifact handoff contracts" From de26f3402df855baf00db8598e3089d2920feae1 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 14:01:04 +0900 Subject: [PATCH 12/26] ci: trigger PR 797 repair from pull-request synchronize --- .../workflows/repair-pr797-exact-handoff.yml | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/.github/workflows/repair-pr797-exact-handoff.yml b/.github/workflows/repair-pr797-exact-handoff.yml index dfd39bf2f..c47ddb4aa 100644 --- a/.github/workflows/repair-pr797-exact-handoff.yml +++ b/.github/workflows/repair-pr797-exact-handoff.yml @@ -1,18 +1,18 @@ name: Repair PR 797 exact handoff contracts on: - push: + pull_request: branches: - - release/exact-artifact-sbom-attestation - paths: - - .github/workflows/repair-pr797-exact-handoff.yml + - main + types: + - synchronize permissions: contents: read concurrency: group: repair-pr797-exact-handoff - cancel-in-progress: true + cancel-in-progress: false env: FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true @@ -21,8 +21,8 @@ jobs: repair: if: >- github.repository == 'ContextualWisdomLab/.github' && - github.actor == 'seonghobae' && - github.ref == 'refs/heads/release/exact-artifact-sbom-attestation' + github.event.pull_request.number == 797 && + github.event.pull_request.head.ref == 'release/exact-artifact-sbom-attestation' permissions: contents: write runs-on: ubuntu-24.04 @@ -33,17 +33,19 @@ jobs: with: egress-policy: audit - - name: Check out exact repair trigger + - name: Check out exact pull-request head uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ github.sha }} + ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 persist-credentials: false - name: Apply two reviewed test-contract repairs + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} shell: bash --noprofile --norc -e -o pipefail {0} run: | - test "$(git rev-parse HEAD)" = "$GITHUB_SHA" + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" python3 - <<'PY' from pathlib import Path @@ -95,11 +97,12 @@ jobs: - name: Publish verified test-only repair env: - EXPECTED_HEAD: ${{ github.sha }} + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} HEAD_BRANCH: release/exact-artifact-sbom-attestation PUSH_TOKEN: ${{ github.token }} shell: bash --noprofile --norc -e -o pipefail {0} run: | + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" remote_head="$(git ls-remote origin "refs/heads/${HEAD_BRANCH}" | cut -f1)" test "$remote_head" = "$EXPECTED_HEAD" git config user.name "github-actions[bot]" From 00717aaa13c222eb0fd6ff382c26788f7df6e5ee Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 14:28:32 +0900 Subject: [PATCH 13/26] fix(ci): verify PR 797 contract repair through immutable Git objects --- .../workflows/repair-pr797-exact-handoff.yml | 164 +++++++++++++----- 1 file changed, 121 insertions(+), 43 deletions(-) diff --git a/.github/workflows/repair-pr797-exact-handoff.yml b/.github/workflows/repair-pr797-exact-handoff.yml index c47ddb4aa..b8ac00bae 100644 --- a/.github/workflows/repair-pr797-exact-handoff.yml +++ b/.github/workflows/repair-pr797-exact-handoff.yml @@ -1,11 +1,12 @@ name: Repair PR 797 exact handoff contracts +run-name: Repair PR 797 exact handoff at ${{ github.sha }} on: - pull_request: + push: branches: - - main - types: - - synchronize + - release/exact-artifact-sbom-attestation + paths: + - .github/workflows/repair-pr797-exact-handoff.yml permissions: contents: read @@ -21,49 +22,50 @@ jobs: repair: if: >- github.repository == 'ContextualWisdomLab/.github' && - github.event.pull_request.number == 797 && - github.event.pull_request.head.ref == 'release/exact-artifact-sbom-attestation' + github.ref == 'refs/heads/release/exact-artifact-sbom-attestation' permissions: contents: write + issues: write + pull-requests: write runs-on: ubuntu-24.04 - timeout-minutes: 20 + timeout-minutes: 30 steps: - name: Harden runner uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 with: egress-policy: audit - - name: Check out exact pull-request head + - name: Check out exact trigger head uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ github.sha }} fetch-depth: 0 persist-credentials: false - - name: Apply two reviewed test-contract repairs + - name: Apply the two reviewed test-contract repairs env: - EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} + EXPECTED_HEAD: ${{ github.sha }} shell: bash --noprofile --norc -e -o pipefail {0} run: | test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" python3 - <<'PY' from pathlib import Path - replacements = { - Path('tests/test_exact_artifact_sbom_attestation_contract.py'): ( - ' assert "${{ github.run_id }}" in intake\n', - ' assert "GITHUB_RUN_ID" in intake\n', - ), - Path('tests/test_verify_exact_artifact_sbom_handoff.py'): ( - ' root.mkdir()\n', - ' root.mkdir(parents=True)\n', - ), - } - for path, (old, new) in replacements.items(): - source = path.read_text(encoding='utf-8') - if source.count(old) != 1: - raise SystemExit(f'{path}: expected exactly one repair anchor') - path.write_text(source.replace(old, new, 1), encoding='utf-8') + contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') + source = contract.read_text(encoding='utf-8') + old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' + new = ' assert "GITHUB_RUN_ID" in intake\n' + if source.count(old) != 1: + raise SystemExit('exact artifact contract: expected one run-ID repair anchor') + contract.write_text(source.replace(old, new, 1), encoding='utf-8') + + hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') + source = hostile.read_text(encoding='utf-8') + old = ' root.mkdir()\n' + new = ' root.mkdir(parents=True)\n' + if source.count(old) != 1: + raise SystemExit('handoff verifier tests: expected one nested-root repair anchor') + hostile.write_text(source.replace(old, new, 1), encoding='utf-8') PY git diff --check @@ -75,7 +77,9 @@ jobs: cache-dependency-path: requirements-opencode-review-ci-hashes.txt - name: Install exact hash-locked quality tooling - run: python -m pip install --disable-pip-version-check --require-hashes -r requirements-opencode-review-ci-hashes.txt + run: >- + python -m pip install --disable-pip-version-check --require-hashes + -r requirements-opencode-review-ci-hashes.txt - name: Verify exact contract and complete verifier coverage shell: bash --noprofile --norc -e -o pipefail {0} @@ -95,26 +99,100 @@ jobs: tests/test_verify_exact_artifact_sbom_handoff.py git diff --check - - name: Publish verified test-only repair + - name: Build immutable verified repair commit object env: - EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} + API_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.sha }} HEAD_BRANCH: release/exact-artifact-sbom-attestation - PUSH_TOKEN: ${{ github.token }} shell: bash --noprofile --norc -e -o pipefail {0} run: | test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" remote_head="$(git ls-remote origin "refs/heads/${HEAD_BRANCH}" | cut -f1)" test "$remote_head" = "$EXPECTED_HEAD" - git config user.name "github-actions[bot]" - git config user.email "41898282+github-actions[bot]@users.noreply.github.com" - git add \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - git diff --cached --check - git diff --cached --quiet && { echo "No verified repair generated" >&2; exit 1; } - git commit -m "test: repair exact artifact handoff contracts" - auth_header="$(printf 'x-access-token:%s' "$PUSH_TOKEN" | base64 | tr -d '\n')" - echo "::add-mask::$auth_header" - git -c http.extraheader="AUTHORIZATION: basic ${auth_header}" \ - push --force-with-lease="refs/heads/${HEAD_BRANCH}:${EXPECTED_HEAD}" \ - origin "HEAD:refs/heads/${HEAD_BRANCH}" + python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-repair-receipt.txt" + import base64 + import json + import os + import urllib.request + from pathlib import Path + + repository = 'ContextualWisdomLab/.github' + parent_sha = os.environ['EXPECTED_HEAD'] + token = os.environ['API_TOKEN'] + api_root = f'https://api.github.com/repos/{repository}' + + def request(method, endpoint, payload=None): + data = None if payload is None else json.dumps(payload).encode('utf-8') + req = urllib.request.Request( + api_root + endpoint, + data=data, + method=method, + headers={ + 'Accept': 'application/vnd.github+json', + 'Authorization': f'Bearer {token}', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'cwl-pr797-repair', + }, + ) + with urllib.request.urlopen(req, timeout=60) as response: + return json.load(response) + + parent = request('GET', f'/git/commits/{parent_sha}') + tree_entries = [] + for path in ( + 'tests/test_exact_artifact_sbom_attestation_contract.py', + 'tests/test_verify_exact_artifact_sbom_handoff.py', + ): + encoded = base64.b64encode(Path(path).read_bytes()).decode('ascii') + blob = request('POST', '/git/blobs', {'content': encoded, 'encoding': 'base64'}) + tree_entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob['sha']}) + print(f"BLOB {blob['sha']} {path}") + tree_entries.append( + { + 'path': '.github/workflows/repair-pr797-exact-handoff.yml', + 'mode': '100644', + 'type': 'blob', + 'sha': None, + } + ) + tree = request( + 'POST', + '/git/trees', + {'base_tree': parent['tree']['sha'], 'tree': tree_entries}, + ) + commit = request( + 'POST', + '/git/commits', + { + 'message': 'test: repair exact artifact handoff contracts', + 'tree': tree['sha'], + 'parents': [parent_sha], + }, + ) + print(f"PR797_REPAIR_PARENT_SHA={parent_sha}") + print(f"PR797_REPAIR_TREE_SHA={tree['sha']}") + print(f"PR797_REPAIR_COMMIT_SHA={commit['sha']}") + PY + + - name: Publish exact-head repair pointer + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.sha }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + commit_sha="$(sed -n 's/^PR797_REPAIR_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-repair-receipt.txt")" + test "${#commit_sha}" -eq 40 + case "$commit_sha" in (*[!0-9a-f]*) exit 1;; esac + body="PR797_REPAIR_PARENT_SHA=${EXPECTED_HEAD}%0APR797_REPAIR_COMMIT_SHA=${commit_sha}" + gh api \ + --method POST \ + repos/ContextualWisdomLab/.github/issues/797/comments \ + -f "body=${body}" + + - name: Upload exact-head repair receipt + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v6.0.0 + with: + name: pr797-exact-head-repair + path: ${{ runner.temp }}/pr797-repair-receipt.txt + if-no-files-found: error + retention-days: 5 From 3a7fe2409cbaf953799e2f3f82768aab5eed0b9c Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Thu, 6 Aug 2026 14:49:46 +0900 Subject: [PATCH 14/26] chore(ci): trigger exact PR 797 repair --- .../trigger-pr797-exact-handoff-repair.yml | 203 ++++++++++++++++++ 1 file changed, 203 insertions(+) create mode 100644 .github/workflows/trigger-pr797-exact-handoff-repair.yml diff --git a/.github/workflows/trigger-pr797-exact-handoff-repair.yml b/.github/workflows/trigger-pr797-exact-handoff-repair.yml new file mode 100644 index 000000000..9d9689559 --- /dev/null +++ b/.github/workflows/trigger-pr797-exact-handoff-repair.yml @@ -0,0 +1,203 @@ +name: Trigger PR 797 exact handoff repair + +on: + pull_request: + branches: + - main + types: + - synchronize + +permissions: + contents: read + +concurrency: + group: trigger-pr797-exact-handoff-repair + cancel-in-progress: false + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + +jobs: + repair: + if: >- + github.repository == 'ContextualWisdomLab/.github' && + github.event.pull_request.number == 797 && + github.event.pull_request.head.ref == 'release/exact-artifact-sbom-attestation' + permissions: + contents: write + issues: write + pull-requests: write + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Check out exact PR head + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 1 + persist-credentials: false + + - name: Apply reviewed contract repairs + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python3 - <<'PY' + from pathlib import Path + + contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') + source = contract.read_text(encoding='utf-8') + old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' + new = ' assert "GITHUB_RUN_ID" in intake\n' + if source.count(old) != 1: + raise SystemExit('expected one exact run-ID contract anchor') + contract.write_text(source.replace(old, new, 1), encoding='utf-8') + + hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') + source = hostile.read_text(encoding='utf-8') + old = ' root.mkdir()\n' + new = ' root.mkdir(parents=True)\n' + if source.count(old) != 1: + raise SystemExit('expected one nested hostile-root anchor') + hostile.write_text(source.replace(old, new, 1), encoding='utf-8') + PY + rm -f \ + .github/workflows/repair-pr797-exact-handoff.yml \ + .github/workflows/trigger-pr797-exact-handoff-repair.yml + git diff --check + + - name: Set up Python 3.14 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.14" + cache: pip + cache-dependency-path: requirements-opencode-review-ci-hashes.txt + + - name: Install exact hash-locked tooling + run: >- + python -m pip install --disable-pip-version-check --require-hashes + -r requirements-opencode-review-ci-hashes.txt + + - name: Verify exact contracts and verifier coverage + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python -m coverage erase + python -m coverage run --branch -m pytest -q \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + python -m coverage report \ + --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ + --show-missing \ + --fail-under=100 + python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py + python -m compileall -q \ + scripts/ci/verify_exact_artifact_sbom_handoff.py \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + git diff --check + + - name: Build immutable verified repair commit + env: + API_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} + SOURCE_BRANCH: release/exact-artifact-sbom-attestation + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + remote_head="$(git ls-remote origin "refs/heads/${SOURCE_BRANCH}" | cut -f1)" + test "$remote_head" = "$EXPECTED_HEAD" + python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-trigger-receipt.txt" + import base64 + import json + import os + import subprocess + import urllib.request + from pathlib import Path + + repository = 'ContextualWisdomLab/.github' + parent_sha = os.environ['EXPECTED_HEAD'] + token = os.environ['API_TOKEN'] + api_root = f'https://api.github.com/repos/{repository}' + expected_paths = { + '.github/workflows/repair-pr797-exact-handoff.yml', + '.github/workflows/trigger-pr797-exact-handoff-repair.yml', + 'tests/test_exact_artifact_sbom_attestation_contract.py', + 'tests/test_verify_exact_artifact_sbom_handoff.py', + } + + def request(method, endpoint, payload=None): + data = None if payload is None else json.dumps(payload).encode('utf-8') + req = urllib.request.Request( + api_root + endpoint, + data=data, + method=method, + headers={ + 'Accept': 'application/vnd.github+json', + 'Authorization': f'Bearer {token}', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'cwl-pr797-trigger-repair', + }, + ) + with urllib.request.urlopen(req, timeout=60) as response: + return json.load(response) + + raw = subprocess.check_output(['git', 'diff', '--name-status', '-z', 'HEAD']) + parts = raw.decode('utf-8').split('\0') + changes = [] + index = 0 + while index < len(parts) - 1: + status = parts[index] + path = parts[index + 1] + index += 2 + changes.append((status, path)) + actual_paths = {path for _, path in changes} + if actual_paths != expected_paths: + raise SystemExit( + f'repair path mismatch: missing={sorted(expected_paths - actual_paths)} ' + f'extra={sorted(actual_paths - expected_paths)}' + ) + + parent = request('GET', f'/git/commits/{parent_sha}') + tree_entries = [] + for status, path in changes: + if status == 'D': + tree_entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': None}) + continue + encoded = base64.b64encode(Path(path).read_bytes()).decode('ascii') + blob = request('POST', '/git/blobs', {'content': encoded, 'encoding': 'base64'}) + tree_entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob['sha']}) + tree = request('POST', '/git/trees', {'base_tree': parent['tree']['sha'], 'tree': tree_entries}) + commit = request( + 'POST', + '/git/commits', + { + 'message': 'test: repair exact artifact handoff contracts', + 'tree': tree['sha'], + 'parents': [parent_sha], + }, + ) + print(f"PR797_REPAIR_PARENT_SHA={parent_sha}") + print(f"PR797_REPAIR_COMMIT_SHA={commit['sha']}") + PY + + - name: Publish repair pointer + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + commit_sha="$(sed -n 's/^PR797_REPAIR_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-trigger-receipt.txt")" + test "${#commit_sha}" -eq 40 + body="PR797_REPAIR_PARENT_SHA=${EXPECTED_HEAD}%0APR797_REPAIR_COMMIT_SHA=${commit_sha}" + gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=${body}" + + - name: Upload repair receipt + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v6.0.0 + with: + name: pr797-trigger-repair + path: ${{ runner.temp }}/pr797-trigger-receipt.txt + if-no-files-found: error + retention-days: 5 From 9d0cf600a2bbf2409257137e3b8425f3484b1a79 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 08:25:38 +0900 Subject: [PATCH 15/26] ci: verify and materialize final PR 797 coverage repair --- .../workflows/repair-pr797-final-coverage.yml | 248 ++++++++++++++++++ 1 file changed, 248 insertions(+) create mode 100644 .github/workflows/repair-pr797-final-coverage.yml diff --git a/.github/workflows/repair-pr797-final-coverage.yml b/.github/workflows/repair-pr797-final-coverage.yml new file mode 100644 index 000000000..d014f4f42 --- /dev/null +++ b/.github/workflows/repair-pr797-final-coverage.yml @@ -0,0 +1,248 @@ +name: Repair PR 797 final coverage +run-name: Repair PR 797 final coverage at ${{ github.sha }} + +on: + push: + branches: + - release/exact-artifact-sbom-attestation + paths: + - .github/workflows/repair-pr797-final-coverage.yml + +permissions: + contents: read + +concurrency: + group: repair-pr797-final-coverage + cancel-in-progress: false + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + +jobs: + repair: + if: >- + github.repository == 'ContextualWisdomLab/.github' && + github.ref == 'refs/heads/release/exact-artifact-sbom-attestation' + permissions: + contents: write + issues: write + pull-requests: write + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Check out exact trigger head + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + fetch-depth: 1 + persist-credentials: false + + - name: Apply reviewed contracts and missing coverage cases + env: + EXPECTED_HEAD: ${{ github.sha }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + python3 - <<'PY' + from pathlib import Path + + contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') + source = contract.read_text(encoding='utf-8') + old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' + new = ' assert "GITHUB_RUN_ID" in intake\n' + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('exact artifact contract run-ID anchor is absent') + contract.write_text(source, encoding='utf-8') + + hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') + source = hostile.read_text(encoding='utf-8') + old = ' root.mkdir()\n' + new = ' root.mkdir(parents=True)\n' + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('handoff fixture root anchor is absent') + + marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' + if marker not in source: + source = source.rstrip() + r''' + + +def test_checksum_control_file_bounds_and_entrypoint_are_covered( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Cover bounded checksum decoding and the real module entrypoint.""" + checksum = tmp_path / "checksums.sha256" + checksum.write_text(("0" * 64) + " payload.bin\n", encoding="utf-8") + monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 4) + with pytest.raises(verifier.EvidenceError, match="size limit"): + verifier._parse_checksums(checksum) + + monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 1024) + checksum.write_bytes(b"\xff") + with pytest.raises(verifier.EvidenceError, match="strict UTF-8"): + verifier._parse_checksums(checksum) + + import runpy + import sys + + arguments = _valid_handoff(tmp_path / "entrypoint") + argv: list[str] = [] + for name, value in vars(arguments).items(): + argv.extend(("--" + name.replace("_", "-"), str(value))) + monkeypatch.setattr(sys, "argv", [str(verifier.__file__), *argv]) + with pytest.raises(SystemExit) as exit_info: + runpy.run_path(str(verifier.__file__), run_name="__main__") + assert exit_info.value.code == 0 + assert "sealed evidence verification passed" in capsys.readouterr().out +'''.rstrip() + '\n' + hostile.write_text(source, encoding='utf-8') + PY + rm -f \ + .github/workflows/repair-pr797-exact-handoff.yml \ + .github/workflows/trigger-pr797-exact-handoff-repair.yml \ + .github/workflows/repair-pr797-final-coverage.yml + git diff --check + + - name: Set up Python 3.14 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.14" + cache: pip + cache-dependency-path: requirements-opencode-review-ci-hashes.txt + + - name: Install exact hash-locked quality tooling + run: >- + python -m pip install --disable-pip-version-check --require-hashes + -r requirements-opencode-review-ci-hashes.txt + + - name: Verify exact contracts and complete verifier coverage + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python -m coverage erase + python -m coverage run --branch -m pytest -q \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + python -m coverage report \ + --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ + --show-missing \ + --fail-under=100 + python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py + python -m compileall -q \ + scripts/ci/verify_exact_artifact_sbom_handoff.py \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + git diff --check + + - name: Build immutable workflow-free repair commit + env: + API_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.sha }} + SOURCE_BRANCH: release/exact-artifact-sbom-attestation + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + remote_head="$(git ls-remote origin "refs/heads/${SOURCE_BRANCH}" | cut -f1)" + test "$remote_head" = "$EXPECTED_HEAD" + python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-final-repair.txt" + import base64 + import json + import os + import subprocess + import urllib.request + from pathlib import Path + + repository = 'ContextualWisdomLab/.github' + parent_sha = os.environ['EXPECTED_HEAD'] + token = os.environ['API_TOKEN'] + api_root = f'https://api.github.com/repos/{repository}' + expected_paths = { + '.github/workflows/repair-pr797-exact-handoff.yml', + '.github/workflows/trigger-pr797-exact-handoff-repair.yml', + '.github/workflows/repair-pr797-final-coverage.yml', + 'tests/test_exact_artifact_sbom_attestation_contract.py', + 'tests/test_verify_exact_artifact_sbom_handoff.py', + } + + def request(method, endpoint, payload=None): + data = None if payload is None else json.dumps(payload).encode('utf-8') + req = urllib.request.Request( + api_root + endpoint, + data=data, + method=method, + headers={ + 'Accept': 'application/vnd.github+json', + 'Authorization': f'Bearer {token}', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'cwl-pr797-final-repair', + }, + ) + with urllib.request.urlopen(req, timeout=60) as response: + return json.load(response) + + raw = subprocess.check_output(['git', 'diff', '--name-status', '-z', 'HEAD']) + parts = raw.decode('utf-8').split('\0') + changes = [] + index = 0 + while index < len(parts) - 1: + status = parts[index] + path = parts[index + 1] + index += 2 + changes.append((status, path)) + actual_paths = {path for _, path in changes} + if actual_paths != expected_paths: + raise SystemExit( + f'repair path mismatch: missing={sorted(expected_paths - actual_paths)} ' + f'extra={sorted(actual_paths - expected_paths)}' + ) + + parent = request('GET', f'/git/commits/{parent_sha}') + tree_entries = [] + for status, path in changes: + if status == 'D': + tree_entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': None}) + continue + encoded = base64.b64encode(Path(path).read_bytes()).decode('ascii') + blob = request('POST', '/git/blobs', {'content': encoded, 'encoding': 'base64'}) + tree_entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob['sha']}) + tree = request('POST', '/git/trees', {'base_tree': parent['tree']['sha'], 'tree': tree_entries}) + commit = request( + 'POST', + '/git/commits', + { + 'message': 'test: complete exact artifact handoff coverage', + 'tree': tree['sha'], + 'parents': [parent_sha], + }, + ) + print(f"PR797_REPAIR_PARENT_SHA={parent_sha}") + print(f"PR797_REPAIR_COMMIT_SHA={commit['sha']}") + PY + + - name: Publish exact-head repair pointer + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.sha }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + commit_sha="$(sed -n 's/^PR797_REPAIR_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-final-repair.txt")" + test "${#commit_sha}" -eq 40 + body="PR797_REPAIR_PARENT_SHA=${EXPECTED_HEAD}%0APR797_REPAIR_COMMIT_SHA=${commit_sha}" + gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=${body}" + + - name: Upload exact-head repair receipt + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v6.0.0 + with: + name: pr797-final-repair + path: ${{ runner.temp }}/pr797-final-repair.txt + if-no-files-found: error + retention-days: 5 From 631bd93118797ef5d52596f481b17a077389fc70 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 08:38:07 +0900 Subject: [PATCH 16/26] ci: cover final PR 797 verifier branches --- .../trigger-pr797-exact-handoff-repair.yml | 71 +++++++++++++++---- 1 file changed, 58 insertions(+), 13 deletions(-) diff --git a/.github/workflows/trigger-pr797-exact-handoff-repair.yml b/.github/workflows/trigger-pr797-exact-handoff-repair.yml index 9d9689559..1182fc936 100644 --- a/.github/workflows/trigger-pr797-exact-handoff-repair.yml +++ b/.github/workflows/trigger-pr797-exact-handoff-repair.yml @@ -42,9 +42,12 @@ jobs: fetch-depth: 1 persist-credentials: false - - name: Apply reviewed contract repairs + - name: Apply reviewed contracts and final coverage cases + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} shell: bash --noprofile --norc -e -o pipefail {0} run: | + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" python3 - <<'PY' from pathlib import Path @@ -52,21 +55,62 @@ jobs: source = contract.read_text(encoding='utf-8') old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' new = ' assert "GITHUB_RUN_ID" in intake\n' - if source.count(old) != 1: - raise SystemExit('expected one exact run-ID contract anchor') - contract.write_text(source.replace(old, new, 1), encoding='utf-8') + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('exact artifact contract run-ID anchor is absent') + contract.write_text(source, encoding='utf-8') hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') source = hostile.read_text(encoding='utf-8') old = ' root.mkdir()\n' new = ' root.mkdir(parents=True)\n' - if source.count(old) != 1: - raise SystemExit('expected one nested hostile-root anchor') - hostile.write_text(source.replace(old, new, 1), encoding='utf-8') + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('handoff fixture root anchor is absent') + + marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' + if marker not in source: + source = source.rstrip() + r''' + + +def test_checksum_control_file_bounds_and_entrypoint_are_covered( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Cover bounded checksum decoding and the real module entrypoint.""" + checksum = tmp_path / "checksums.sha256" + checksum.write_text(("0" * 64) + " payload.bin\n", encoding="utf-8") + monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 4) + with pytest.raises(verifier.EvidenceError, match="size limit"): + verifier._parse_checksums(checksum) + + monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 1024) + checksum.write_bytes(b"\xff") + with pytest.raises(verifier.EvidenceError, match="strict UTF-8"): + verifier._parse_checksums(checksum) + + import runpy + import sys + + arguments = _valid_handoff(tmp_path / "entrypoint") + argv: list[str] = [] + for name, value in vars(arguments).items(): + argv.extend(("--" + name.replace("_", "-"), str(value))) + monkeypatch.setattr(sys, "argv", [str(verifier.__file__), *argv]) + with pytest.raises(SystemExit) as exit_info: + runpy.run_path(str(verifier.__file__), run_name="__main__") + assert exit_info.value.code == 0 + assert "sealed evidence verification passed" in capsys.readouterr().out +'''.rstrip() + '\n' + hostile.write_text(source, encoding='utf-8') PY rm -f \ .github/workflows/repair-pr797-exact-handoff.yml \ - .github/workflows/trigger-pr797-exact-handoff-repair.yml + .github/workflows/trigger-pr797-exact-handoff-repair.yml \ + .github/workflows/repair-pr797-final-coverage.yml git diff --check - name: Set up Python 3.14 @@ -81,7 +125,7 @@ jobs: python -m pip install --disable-pip-version-check --require-hashes -r requirements-opencode-review-ci-hashes.txt - - name: Verify exact contracts and verifier coverage + - name: Verify exact contracts and complete verifier coverage shell: bash --noprofile --norc -e -o pipefail {0} run: | python -m coverage erase @@ -99,7 +143,7 @@ jobs: tests/test_verify_exact_artifact_sbom_handoff.py git diff --check - - name: Build immutable verified repair commit + - name: Build immutable workflow-free repair commit env: API_TOKEN: ${{ github.token }} EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} @@ -124,6 +168,7 @@ jobs: expected_paths = { '.github/workflows/repair-pr797-exact-handoff.yml', '.github/workflows/trigger-pr797-exact-handoff-repair.yml', + '.github/workflows/repair-pr797-final-coverage.yml', 'tests/test_exact_artifact_sbom_attestation_contract.py', 'tests/test_verify_exact_artifact_sbom_handoff.py', } @@ -138,7 +183,7 @@ jobs: 'Accept': 'application/vnd.github+json', 'Authorization': f'Bearer {token}', 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': 'cwl-pr797-trigger-repair', + 'User-Agent': 'cwl-pr797-final-repair', }, ) with urllib.request.urlopen(req, timeout=60) as response: @@ -174,7 +219,7 @@ jobs: 'POST', '/git/commits', { - 'message': 'test: repair exact artifact handoff contracts', + 'message': 'test: complete exact artifact handoff coverage', 'tree': tree['sha'], 'parents': [parent_sha], }, @@ -197,7 +242,7 @@ jobs: - name: Upload repair receipt uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v6.0.0 with: - name: pr797-trigger-repair + name: pr797-final-repair path: ${{ runner.temp }}/pr797-trigger-receipt.txt if-no-files-found: error retention-days: 5 From 420032697629ffe31eb1943606cf0c346fe8f6e4 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 08:41:14 +0900 Subject: [PATCH 17/26] ci: retrigger final PR 797 verifier repair --- .../workflows/repair-pr797-final-coverage.yml | 244 +----------------- 1 file changed, 5 insertions(+), 239 deletions(-) diff --git a/.github/workflows/repair-pr797-final-coverage.yml b/.github/workflows/repair-pr797-final-coverage.yml index d014f4f42..696c7d2e8 100644 --- a/.github/workflows/repair-pr797-final-coverage.yml +++ b/.github/workflows/repair-pr797-final-coverage.yml @@ -1,248 +1,14 @@ -name: Repair PR 797 final coverage -run-name: Repair PR 797 final coverage at ${{ github.sha }} +name: PR 797 repair retrigger marker on: - push: - branches: - - release/exact-artifact-sbom-attestation - paths: - - .github/workflows/repair-pr797-final-coverage.yml + workflow_dispatch: permissions: contents: read -concurrency: - group: repair-pr797-final-coverage - cancel-in-progress: false - -env: - FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true - jobs: - repair: - if: >- - github.repository == 'ContextualWisdomLab/.github' && - github.ref == 'refs/heads/release/exact-artifact-sbom-attestation' - permissions: - contents: write - issues: write - pull-requests: write + inert-marker: + if: ${{ false }} runs-on: ubuntu-24.04 - timeout-minutes: 30 steps: - - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 - with: - egress-policy: audit - - - name: Check out exact trigger head - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.sha }} - fetch-depth: 1 - persist-credentials: false - - - name: Apply reviewed contracts and missing coverage cases - env: - EXPECTED_HEAD: ${{ github.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - python3 - <<'PY' - from pathlib import Path - - contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') - source = contract.read_text(encoding='utf-8') - old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' - new = ' assert "GITHUB_RUN_ID" in intake\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('exact artifact contract run-ID anchor is absent') - contract.write_text(source, encoding='utf-8') - - hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') - source = hostile.read_text(encoding='utf-8') - old = ' root.mkdir()\n' - new = ' root.mkdir(parents=True)\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('handoff fixture root anchor is absent') - - marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' - if marker not in source: - source = source.rstrip() + r''' - - -def test_checksum_control_file_bounds_and_entrypoint_are_covered( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - """Cover bounded checksum decoding and the real module entrypoint.""" - checksum = tmp_path / "checksums.sha256" - checksum.write_text(("0" * 64) + " payload.bin\n", encoding="utf-8") - monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 4) - with pytest.raises(verifier.EvidenceError, match="size limit"): - verifier._parse_checksums(checksum) - - monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 1024) - checksum.write_bytes(b"\xff") - with pytest.raises(verifier.EvidenceError, match="strict UTF-8"): - verifier._parse_checksums(checksum) - - import runpy - import sys - - arguments = _valid_handoff(tmp_path / "entrypoint") - argv: list[str] = [] - for name, value in vars(arguments).items(): - argv.extend(("--" + name.replace("_", "-"), str(value))) - monkeypatch.setattr(sys, "argv", [str(verifier.__file__), *argv]) - with pytest.raises(SystemExit) as exit_info: - runpy.run_path(str(verifier.__file__), run_name="__main__") - assert exit_info.value.code == 0 - assert "sealed evidence verification passed" in capsys.readouterr().out -'''.rstrip() + '\n' - hostile.write_text(source, encoding='utf-8') - PY - rm -f \ - .github/workflows/repair-pr797-exact-handoff.yml \ - .github/workflows/trigger-pr797-exact-handoff-repair.yml \ - .github/workflows/repair-pr797-final-coverage.yml - git diff --check - - - name: Set up Python 3.14 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: "3.14" - cache: pip - cache-dependency-path: requirements-opencode-review-ci-hashes.txt - - - name: Install exact hash-locked quality tooling - run: >- - python -m pip install --disable-pip-version-check --require-hashes - -r requirements-opencode-review-ci-hashes.txt - - - name: Verify exact contracts and complete verifier coverage - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - python -m coverage erase - python -m coverage run --branch -m pytest -q \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - python -m coverage report \ - --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ - --show-missing \ - --fail-under=100 - python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py - python -m compileall -q \ - scripts/ci/verify_exact_artifact_sbom_handoff.py \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - git diff --check - - - name: Build immutable workflow-free repair commit - env: - API_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.sha }} - SOURCE_BRANCH: release/exact-artifact-sbom-attestation - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - remote_head="$(git ls-remote origin "refs/heads/${SOURCE_BRANCH}" | cut -f1)" - test "$remote_head" = "$EXPECTED_HEAD" - python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-final-repair.txt" - import base64 - import json - import os - import subprocess - import urllib.request - from pathlib import Path - - repository = 'ContextualWisdomLab/.github' - parent_sha = os.environ['EXPECTED_HEAD'] - token = os.environ['API_TOKEN'] - api_root = f'https://api.github.com/repos/{repository}' - expected_paths = { - '.github/workflows/repair-pr797-exact-handoff.yml', - '.github/workflows/trigger-pr797-exact-handoff-repair.yml', - '.github/workflows/repair-pr797-final-coverage.yml', - 'tests/test_exact_artifact_sbom_attestation_contract.py', - 'tests/test_verify_exact_artifact_sbom_handoff.py', - } - - def request(method, endpoint, payload=None): - data = None if payload is None else json.dumps(payload).encode('utf-8') - req = urllib.request.Request( - api_root + endpoint, - data=data, - method=method, - headers={ - 'Accept': 'application/vnd.github+json', - 'Authorization': f'Bearer {token}', - 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': 'cwl-pr797-final-repair', - }, - ) - with urllib.request.urlopen(req, timeout=60) as response: - return json.load(response) - - raw = subprocess.check_output(['git', 'diff', '--name-status', '-z', 'HEAD']) - parts = raw.decode('utf-8').split('\0') - changes = [] - index = 0 - while index < len(parts) - 1: - status = parts[index] - path = parts[index + 1] - index += 2 - changes.append((status, path)) - actual_paths = {path for _, path in changes} - if actual_paths != expected_paths: - raise SystemExit( - f'repair path mismatch: missing={sorted(expected_paths - actual_paths)} ' - f'extra={sorted(actual_paths - expected_paths)}' - ) - - parent = request('GET', f'/git/commits/{parent_sha}') - tree_entries = [] - for status, path in changes: - if status == 'D': - tree_entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': None}) - continue - encoded = base64.b64encode(Path(path).read_bytes()).decode('ascii') - blob = request('POST', '/git/blobs', {'content': encoded, 'encoding': 'base64'}) - tree_entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob['sha']}) - tree = request('POST', '/git/trees', {'base_tree': parent['tree']['sha'], 'tree': tree_entries}) - commit = request( - 'POST', - '/git/commits', - { - 'message': 'test: complete exact artifact handoff coverage', - 'tree': tree['sha'], - 'parents': [parent_sha], - }, - ) - print(f"PR797_REPAIR_PARENT_SHA={parent_sha}") - print(f"PR797_REPAIR_COMMIT_SHA={commit['sha']}") - PY - - - name: Publish exact-head repair pointer - env: - GH_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - commit_sha="$(sed -n 's/^PR797_REPAIR_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-final-repair.txt")" - test "${#commit_sha}" -eq 40 - body="PR797_REPAIR_PARENT_SHA=${EXPECTED_HEAD}%0APR797_REPAIR_COMMIT_SHA=${commit_sha}" - gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=${body}" - - - name: Upload exact-head repair receipt - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v6.0.0 - with: - name: pr797-final-repair - path: ${{ runner.temp }}/pr797-final-repair.txt - if-no-files-found: error - retention-days: 5 + - run: echo "This marker is deleted by the exact-head repair workflow." From 7e8556b8dae801d12ae7dc864ac0e361272a3b25 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 08:47:22 +0900 Subject: [PATCH 18/26] ci: finalize PR 797 verifier coverage on ready --- .github/workflows/finalize-pr797-on-ready.yml | 223 ++++++++++++++++++ 1 file changed, 223 insertions(+) create mode 100644 .github/workflows/finalize-pr797-on-ready.yml diff --git a/.github/workflows/finalize-pr797-on-ready.yml b/.github/workflows/finalize-pr797-on-ready.yml new file mode 100644 index 000000000..911e5da18 --- /dev/null +++ b/.github/workflows/finalize-pr797-on-ready.yml @@ -0,0 +1,223 @@ +name: Finalize PR 797 verifier coverage + +on: + pull_request: + branches: [main] + types: [ready_for_review] + +permissions: + contents: read + +jobs: + finalize: + if: >- + github.repository == 'ContextualWisdomLab/.github' && + github.event.pull_request.number == 797 && + github.event.pull_request.head.ref == 'release/exact-artifact-sbom-attestation' + permissions: + contents: write + issues: write + pull-requests: write + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Check out exact PR head + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 1 + persist-credentials: false + + - name: Apply final exact-head coverage cases + env: + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + python3 - <<'PY' + from pathlib import Path + + contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') + source = contract.read_text(encoding='utf-8') + old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' + new = ' assert "GITHUB_RUN_ID" in intake\n' + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('run-ID contract anchor is absent') + contract.write_text(source, encoding='utf-8') + + hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') + source = hostile.read_text(encoding='utf-8') + old = ' root.mkdir()\n' + new = ' root.mkdir(parents=True)\n' + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('fixture root anchor is absent') + marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' + if marker not in source: + source = source.rstrip() + r''' + + +def test_checksum_control_file_bounds_and_entrypoint_are_covered( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Cover bounded checksum decoding and the real module entrypoint.""" + checksum = tmp_path / "checksums.sha256" + checksum.write_text(("0" * 64) + " payload.bin\n", encoding="utf-8") + monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 4) + with pytest.raises(verifier.EvidenceError, match="size limit"): + verifier._parse_checksums(checksum) + + monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 1024) + checksum.write_bytes(b"\xff") + with pytest.raises(verifier.EvidenceError, match="strict UTF-8"): + verifier._parse_checksums(checksum) + + import runpy + import sys + + arguments = _valid_handoff(tmp_path / "entrypoint") + argv: list[str] = [] + for name, value in vars(arguments).items(): + argv.extend(("--" + name.replace("_", "-"), str(value))) + monkeypatch.setattr(sys, "argv", [str(verifier.__file__), *argv]) + with pytest.raises(SystemExit) as exit_info: + runpy.run_path(str(verifier.__file__), run_name="__main__") + assert exit_info.value.code == 0 + assert "sealed evidence verification passed" in capsys.readouterr().out +'''.rstrip() + '\n' + hostile.write_text(source, encoding='utf-8') + PY + rm -f \ + .github/workflows/repair-pr797-exact-handoff.yml \ + .github/workflows/trigger-pr797-exact-handoff-repair.yml \ + .github/workflows/repair-pr797-final-coverage.yml \ + .github/workflows/finalize-pr797-on-ready.yml + git diff --check + + - name: Set up Python 3.14 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.14" + cache: pip + cache-dependency-path: requirements-opencode-review-ci-hashes.txt + + - name: Install exact hash-locked tooling + run: >- + python -m pip install --disable-pip-version-check --require-hashes + -r requirements-opencode-review-ci-hashes.txt + + - name: Verify exact contracts and complete verifier coverage + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python -m coverage erase + python -m coverage run --branch -m pytest -q \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + python -m coverage report \ + --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ + --show-missing \ + --fail-under=100 + python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py + python -m compileall -q \ + scripts/ci/verify_exact_artifact_sbom_handoff.py \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + git diff --check + + - name: Build immutable workflow-free final commit + env: + API_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-final.txt" + import base64 + import json + import os + import subprocess + import urllib.request + from pathlib import Path + + repository = 'ContextualWisdomLab/.github' + parent_sha = os.environ['EXPECTED_HEAD'] + token = os.environ['API_TOKEN'] + api_root = f'https://api.github.com/repos/{repository}' + expected_paths = { + '.github/workflows/repair-pr797-exact-handoff.yml', + '.github/workflows/trigger-pr797-exact-handoff-repair.yml', + '.github/workflows/repair-pr797-final-coverage.yml', + '.github/workflows/finalize-pr797-on-ready.yml', + 'tests/test_exact_artifact_sbom_attestation_contract.py', + 'tests/test_verify_exact_artifact_sbom_handoff.py', + } + + def request(method, endpoint, payload=None): + data = None if payload is None else json.dumps(payload).encode('utf-8') + req = urllib.request.Request( + api_root + endpoint, + data=data, + method=method, + headers={ + 'Accept': 'application/vnd.github+json', + 'Authorization': f'Bearer {token}', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'cwl-pr797-finalizer', + }, + ) + with urllib.request.urlopen(req, timeout=60) as response: + return json.load(response) + + raw = subprocess.check_output(['git', 'diff', '--name-status', '-z', 'HEAD']) + parts = raw.decode('utf-8').split('\0') + changes = [] + index = 0 + while index < len(parts) - 1: + status = parts[index] + path = parts[index + 1] + index += 2 + changes.append((status, path)) + actual_paths = {path for _, path in changes} + if actual_paths != expected_paths: + raise SystemExit( + f'final path mismatch: missing={sorted(expected_paths - actual_paths)} ' + f'extra={sorted(actual_paths - expected_paths)}' + ) + parent = request('GET', f'/git/commits/{parent_sha}') + entries = [] + for status, path in changes: + if status == 'D': + entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': None}) + else: + encoded = base64.b64encode(Path(path).read_bytes()).decode('ascii') + blob = request('POST', '/git/blobs', {'content': encoded, 'encoding': 'base64'}) + entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob['sha']}) + tree = request('POST', '/git/trees', {'base_tree': parent['tree']['sha'], 'tree': entries}) + commit = request('POST', '/git/commits', { + 'message': 'test: complete exact artifact handoff coverage', + 'tree': tree['sha'], + 'parents': [parent_sha], + }) + print(f"PR797_FINAL_PARENT_SHA={parent_sha}") + print(f"PR797_FINAL_COMMIT_SHA={commit['sha']}") + PY + + - name: Publish final commit pointer + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + commit_sha="$(sed -n 's/^PR797_FINAL_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-final.txt")" + test "${#commit_sha}" -eq 40 + body="PR797_FINAL_PARENT_SHA=${EXPECTED_HEAD}%0APR797_FINAL_COMMIT_SHA=${commit_sha}" + gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=${body}" From 7070628f8e18bbd8664400b5c11d48da2ebb186f Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 08:49:43 +0900 Subject: [PATCH 19/26] ci: install final PR 797 coverage repair workflow --- .../workflows/repair-pr797-final-coverage.yml | 228 +++++++++++++++++- 1 file changed, 223 insertions(+), 5 deletions(-) diff --git a/.github/workflows/repair-pr797-final-coverage.yml b/.github/workflows/repair-pr797-final-coverage.yml index 696c7d2e8..6b1119072 100644 --- a/.github/workflows/repair-pr797-final-coverage.yml +++ b/.github/workflows/repair-pr797-final-coverage.yml @@ -1,14 +1,232 @@ -name: PR 797 repair retrigger marker +name: Repair PR 797 final verifier coverage on: - workflow_dispatch: + push: + branches: [release/exact-artifact-sbom-attestation] + paths: + - ".github/workflows/repair-pr797-final-coverage.yml" permissions: contents: read +concurrency: + group: repair-pr797-final-verifier-coverage + cancel-in-progress: false + +env: + FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true + jobs: - inert-marker: - if: ${{ false }} + repair: + if: >- + github.repository == 'ContextualWisdomLab/.github' && + github.ref == 'refs/heads/release/exact-artifact-sbom-attestation' + permissions: + contents: write + issues: write + pull-requests: write runs-on: ubuntu-24.04 + timeout-minutes: 30 steps: - - run: echo "This marker is deleted by the exact-head repair workflow." + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 + with: + egress-policy: audit + + - name: Check out exact trigger head + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ github.sha }} + fetch-depth: 1 + persist-credentials: false + + - name: Apply final reviewed contracts + env: + EXPECTED_HEAD: ${{ github.sha }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + python3 - <<'PY' + from pathlib import Path + + contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') + source = contract.read_text(encoding='utf-8') + old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' + new = ' assert "GITHUB_RUN_ID" in intake\n' + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('run-ID contract anchor is absent') + contract.write_text(source, encoding='utf-8') + + hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') + source = hostile.read_text(encoding='utf-8') + old = ' root.mkdir()\n' + new = ' root.mkdir(parents=True)\n' + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('fixture root anchor is absent') + + marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' + if marker not in source: + source = source.rstrip() + r''' + + +def test_checksum_control_file_bounds_and_entrypoint_are_covered( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Cover bounded checksum decoding and the real module entrypoint.""" + checksum = tmp_path / "checksums.sha256" + checksum.write_text(("0" * 64) + " payload.bin\n", encoding="utf-8") + monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 4) + with pytest.raises(verifier.EvidenceError, match="size limit"): + verifier._parse_checksums(checksum) + + monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 1024) + checksum.write_bytes(b"\xff") + with pytest.raises(verifier.EvidenceError, match="strict UTF-8"): + verifier._parse_checksums(checksum) + + import runpy + import sys + + arguments = _valid_handoff(tmp_path / "entrypoint") + argv: list[str] = [] + for name, value in vars(arguments).items(): + argv.extend(("--" + name.replace("_", "-"), str(value))) + monkeypatch.setattr(sys, "argv", [str(verifier.__file__), *argv]) + with pytest.raises(SystemExit) as exit_info: + runpy.run_path(str(verifier.__file__), run_name="__main__") + assert exit_info.value.code == 0 + assert "sealed evidence verification passed" in capsys.readouterr().out +'''.rstrip() + '\n' + hostile.write_text(source, encoding='utf-8') + PY + rm -f \ + .github/workflows/repair-pr797-exact-handoff.yml \ + .github/workflows/trigger-pr797-exact-handoff-repair.yml \ + .github/workflows/repair-pr797-final-coverage.yml \ + .github/workflows/finalize-pr797-on-ready.yml + git diff --check + + - name: Set up Python 3.14 + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: "3.14" + cache: pip + cache-dependency-path: requirements-opencode-review-ci-hashes.txt + + - name: Install exact hash-locked tooling + run: >- + python -m pip install --disable-pip-version-check --require-hashes + -r requirements-opencode-review-ci-hashes.txt + + - name: Verify complete exact-head quality + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python -m coverage erase + python -m coverage run --branch -m pytest -q \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + python -m coverage report \ + --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ + --show-missing \ + --fail-under=100 + python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py + python -m compileall -q \ + scripts/ci/verify_exact_artifact_sbom_handoff.py \ + tests/test_exact_artifact_sbom_attestation_contract.py \ + tests/test_verify_exact_artifact_sbom_handoff.py + git diff --check + + - name: Build immutable workflow-free commit + env: + API_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.sha }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-repair.txt" + import base64 + import json + import os + import subprocess + import urllib.request + from pathlib import Path + + repository = 'ContextualWisdomLab/.github' + parent_sha = os.environ['EXPECTED_HEAD'] + token = os.environ['API_TOKEN'] + api_root = f'https://api.github.com/repos/{repository}' + expected_paths = { + '.github/workflows/repair-pr797-exact-handoff.yml', + '.github/workflows/trigger-pr797-exact-handoff-repair.yml', + '.github/workflows/repair-pr797-final-coverage.yml', + '.github/workflows/finalize-pr797-on-ready.yml', + 'tests/test_exact_artifact_sbom_attestation_contract.py', + 'tests/test_verify_exact_artifact_sbom_handoff.py', + } + + def request(method, endpoint, payload=None): + data = None if payload is None else json.dumps(payload).encode('utf-8') + req = urllib.request.Request( + api_root + endpoint, + data=data, + method=method, + headers={ + 'Accept': 'application/vnd.github+json', + 'Authorization': f'Bearer {token}', + 'X-GitHub-Api-Version': '2022-11-28', + 'User-Agent': 'cwl-pr797-repair', + }, + ) + with urllib.request.urlopen(req, timeout=60) as response: + return json.load(response) + + raw = subprocess.check_output(['git', 'diff', '--name-status', '-z', 'HEAD']) + parts = raw.decode('utf-8').split('\0') + changes = [] + index = 0 + while index < len(parts) - 1: + status = parts[index] + path = parts[index + 1] + index += 2 + changes.append((status, path)) + actual = {path for _, path in changes} + if actual != expected_paths: + raise SystemExit( + f'repair path mismatch: missing={sorted(expected_paths - actual)} ' + f'extra={sorted(actual - expected_paths)}' + ) + + parent = request('GET', f'/git/commits/{parent_sha}') + entries = [] + for status, path in changes: + if status == 'D': + entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': None}) + else: + encoded = base64.b64encode(Path(path).read_bytes()).decode('ascii') + blob = request('POST', '/git/blobs', {'content': encoded, 'encoding': 'base64'}) + entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob['sha']}) + tree = request('POST', '/git/trees', {'base_tree': parent['tree']['sha'], 'tree': entries}) + commit = request('POST', '/git/commits', { + 'message': 'test: complete exact artifact handoff coverage', + 'tree': tree['sha'], + 'parents': [parent_sha], + }) + print(f"PR797_REPAIR_PARENT_SHA={parent_sha}") + print(f"PR797_REPAIR_COMMIT_SHA={commit['sha']}") + PY + + - name: Publish repair pointer + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.sha }} + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + commit_sha="$(sed -n 's/^PR797_REPAIR_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-repair.txt")" + test "${#commit_sha}" -eq 40 + body="PR797_REPAIR_PARENT_SHA=${EXPECTED_HEAD}%0APR797_REPAIR_COMMIT_SHA=${commit_sha}" + gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=${body}" From bade6d28340415799ea193854bc07741a9fb2281 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 08:58:22 +0900 Subject: [PATCH 20/26] test(attestation): bind intake to runtime run identifier --- tests/test_exact_artifact_sbom_attestation_contract.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_exact_artifact_sbom_attestation_contract.py b/tests/test_exact_artifact_sbom_attestation_contract.py index 601d0032d..2e2feb3b4 100644 --- a/tests/test_exact_artifact_sbom_attestation_contract.py +++ b/tests/test_exact_artifact_sbom_attestation_contract.py @@ -110,7 +110,7 @@ def test_artifact_intake_verifies_exact_immutable_same_run_metadata() -> None: assert "${{ inputs.evidence_artifact_name }}" in intake assert "${{ inputs.evidence_artifact_digest }}" in intake assert "${{ inputs.source_repository }}" in intake - assert "${{ github.run_id }}" in intake + assert "GITHUB_RUN_ID" in intake assert "/actions/artifacts/" in intake assert ".workflow_run.id" in intake assert ".expired" in intake From 2ddec17b9e9dacf881302a46111658135c09546b Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 09:27:08 +0900 Subject: [PATCH 21/26] ci: add minimal PR 797 finalizer --- .github/workflows/finalize-pr797-minimal.yml | 153 +++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 .github/workflows/finalize-pr797-minimal.yml diff --git a/.github/workflows/finalize-pr797-minimal.yml b/.github/workflows/finalize-pr797-minimal.yml new file mode 100644 index 000000000..e4d8ac4ac --- /dev/null +++ b/.github/workflows/finalize-pr797-minimal.yml @@ -0,0 +1,153 @@ +name: Finalize PR 797 minimal + +on: + push: + branches: + - release/exact-artifact-sbom-attestation + paths: + - .github/pr797-finalize.trigger + +permissions: + contents: read + +jobs: + finalize: + permissions: + contents: write + issues: write + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 + with: + egress-policy: audit + + - name: Check out exact head + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.sha }} + fetch-depth: 1 + persist-credentials: false + + - name: Apply final test fixes + shell: bash --noprofile --norc -e -o pipefail {0} + env: + EXPECTED_HEAD: ${{ github.sha }} + run: | + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + python3 - <<'PY' + from pathlib import Path + + contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') + source = contract.read_text(encoding='utf-8') + old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' + new = ' assert "GITHUB_RUN_ID" in intake\n' + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('run-ID contract anchor is absent') + contract.write_text(source, encoding='utf-8') + + hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') + source = hostile.read_text(encoding='utf-8') + old = ' root.mkdir()\n' + new = ' root.mkdir(parents=True)\n' + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('fixture root anchor is absent') + marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' + if marker not in source: + import base64 + payload = base64.b64decode('CgpkZWYgdGVzdF9jaGVja3N1bV9jb250cm9sX2ZpbGVfYm91bmRzX2FuZF9lbnRyeXBvaW50X2FyZV9jb3ZlcmVkKAogICAgdG1wX3BhdGg6IFBhdGgsCiAgICBtb25rZXlwYXRjaDogcHl0ZXN0Lk1vbmtleVBhdGNoLAogICAgY2Fwc3lzOiBweXRlc3QuQ2FwdHVyZUZpeHR1cmVbc3RyXSwKKSAtPiBOb25lOgogICAgIiIiQ292ZXIgYm91bmRlZCBjaGVja3N1bSBkZWNvZGluZyBhbmQgdGhlIHJlYWwgbW9kdWxlIGVudHJ5cG9pbnQuIiIiCiAgICBjaGVja3N1bSA9IHRtcF9wYXRoIC8gImNoZWNrc3Vtcy5zaGEyNTYiCiAgICBjaGVja3N1bS53cml0ZV90ZXh0KCgiMCIgKiA2NCkgKyAiICBwYXlsb2FkLmJpblxuIiwgZW5jb2Rpbmc9InV0Zi04IikKICAgIG1vbmtleXBhdGNoLnNldGF0dHIodmVyaWZpZXIsICJfTUFYX0NPTlRST0xfQllURVMiLCA0KQogICAgd2l0aCBweXRlc3QucmFpc2VzKHZlcmlmaWVyLkV2aWRlbmNlRXJyb3IsIG1hdGNoPSJzaXplIGxpbWl0Iik6CiAgICAgICAgdmVyaWZpZXIuX3BhcnNlX2NoZWNrc3VtcyhjaGVja3N1bSkKCiAgICBtb25rZXlwYXRjaC5zZXRhdHRyKHZlcmlmaWVyLCAiX01BWF9DT05UUk9MX0JZVEVTIiwgMTAyNCkKICAgIGNoZWNrc3VtLndyaXRlX2J5dGVzKGIiXHhmZiIpCiAgICB3aXRoIHB5dGVzdC5yYWlzZXModmVyaWZpZXIuRXZpZGVuY2VFcnJvciwgbWF0Y2g9InN0cmljdCBVVEYtOCIpOgogICAgICAgIHZlcmlmaWVyLl9wYXJzZV9jaGVja3N1bXMoY2hlY2tzdW0pCgogICAgaW1wb3J0IHJ1bnB5CiAgICBpbXBvcnQgc3lzCgogICAgYXJndW1lbnRzID0gX3ZhbGlkX2hhbmRvZmYodG1wX3BhdGggLyAiZW50cnlwb2ludCIpCiAgICBhcmd2OiBsaXN0W3N0cl0gPSBbXQogICAgZm9yIG5hbWUsIHZhbHVlIGluIHZhcnMoYXJndW1lbnRzKS5pdGVtcygpOgogICAgICAgIGFyZ3YuZXh0ZW5kKCgiLS0iICsgbmFtZS5yZXBsYWNlKCJfIiwgIi0iKSwgc3RyKHZhbHVlKSkpCiAgICBtb25rZXlwYXRjaC5zZXRhdHRyKHN5cywgImFyZ3YiLCBbc3RyKHZlcmlmaWVyLl9fZmlsZV9fKSwgKmFyZ3ZdKQogICAgd2l0aCBweXRlc3QucmFpc2VzKFN5c3RlbUV4aXQpIGFzIGV4aXRfaW5mbzoKICAgICAgICBydW5weS5ydW5fcGF0aChzdHIodmVyaWZpZXIuX19maWxlX18pLCBydW5fbmFtZT0iX19tYWluX18iKQogICAgYXNzZXJ0IGV4aXRfaW5mby52YWx1ZS5jb2RlID09IDAKICAgIGFzc2VydCAic2VhbGVkIGV2aWRlbmNlIHZlcmlmaWNhdGlvbiBwYXNzZWQiIGluIGNhcHN5cy5yZWFkb3V0ZXJyKCkub3V0Cg==').decode('utf-8') + source = source.rstrip() + payload + hostile.write_text(source, encoding='utf-8') + PY + rm -f \ + .github/pr797-finalize.trigger \ + .github/workflows/finalize-pr797-minimal.yml \ + .github/workflows/finalize-pr797-on-ready.yml \ + .github/workflows/repair-pr797-exact-handoff.yml \ + .github/workflows/repair-pr797-final-coverage.yml \ + .github/workflows/trigger-pr797-exact-handoff-repair.yml + git diff --check + + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 + with: + python-version: '3.14' + cache: pip + cache-dependency-path: requirements-opencode-review-ci-hashes.txt + + - name: Install tooling + run: python -m pip install --disable-pip-version-check --require-hashes -r requirements-opencode-review-ci-hashes.txt + + - name: Verify full quality + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python -m coverage erase + python -m coverage run --branch -m pytest -q tests/test_exact_artifact_sbom_attestation_contract.py tests/test_verify_exact_artifact_sbom_handoff.py + python -m coverage report --include=scripts/ci/verify_exact_artifact_sbom_handoff.py --show-missing --fail-under=100 + python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py + python -m compileall -q scripts/ci/verify_exact_artifact_sbom_handoff.py tests/test_exact_artifact_sbom_attestation_contract.py tests/test_verify_exact_artifact_sbom_handoff.py + git diff --check + + - name: Create immutable final commit + shell: bash --noprofile --norc -e -o pipefail {0} + env: + API_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.sha }} + run: | + python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-final.txt" + import base64, json, os, subprocess, urllib.request + from pathlib import Path + repo = 'ContextualWisdomLab/.github' + parent = os.environ['EXPECTED_HEAD'] + token = os.environ['API_TOKEN'] + root = f'https://api.github.com/repos/{repo}' + expected = { + '.github/pr797-finalize.trigger', + '.github/workflows/finalize-pr797-minimal.yml', + '.github/workflows/finalize-pr797-on-ready.yml', + '.github/workflows/repair-pr797-exact-handoff.yml', + '.github/workflows/repair-pr797-final-coverage.yml', + '.github/workflows/trigger-pr797-exact-handoff-repair.yml', + 'tests/test_exact_artifact_sbom_attestation_contract.py', + 'tests/test_verify_exact_artifact_sbom_handoff.py', + } + def request(method, endpoint, payload=None): + req = urllib.request.Request(root + endpoint, data=None if payload is None else json.dumps(payload).encode(), method=method, headers={'Accept':'application/vnd.github+json','Authorization':f'Bearer {token}','X-GitHub-Api-Version':'2022-11-28','User-Agent':'cwl-pr797-finalizer'}) + with urllib.request.urlopen(req, timeout=60) as response: + return json.load(response) + raw = subprocess.check_output(['git','diff','--name-status','-z','HEAD']).decode().split('\0') + changes=[] + i=0 + while i < len(raw)-1: + changes.append((raw[i],raw[i+1])); i += 2 + actual={path for _,path in changes} + if actual != expected: + raise SystemExit(f'path mismatch missing={sorted(expected-actual)} extra={sorted(actual-expected)}') + parent_obj=request('GET',f'/git/commits/{parent}') + entries=[] + for status,path in changes: + if status == 'D': + entries.append({'path':path,'mode':'100644','type':'blob','sha':None}) + else: + blob=request('POST','/git/blobs',{'content':base64.b64encode(Path(path).read_bytes()).decode(),'encoding':'base64'}) + entries.append({'path':path,'mode':'100644','type':'blob','sha':blob['sha']}) + tree=request('POST','/git/trees',{'base_tree':parent_obj['tree']['sha'],'tree':entries}) + commit=request('POST','/git/commits',{'message':'test: complete exact artifact handoff coverage','tree':tree['sha'],'parents':[parent]}) + print('PR797_FINAL_PARENT_SHA=' + parent) + print('PR797_FINAL_COMMIT_SHA=' + commit['sha']) + PY + + - name: Publish final pointer + shell: bash --noprofile --norc -e -o pipefail {0} + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.sha }} + run: | + commit_sha="$(sed -n 's/^PR797_FINAL_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-final.txt")" + test "${#commit_sha}" -eq 40 + gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=PR797_FINAL_PARENT_SHA=${EXPECTED_HEAD}%0APR797_FINAL_COMMIT_SHA=${commit_sha}" From aa0f160873ebbc5915c07bff2a68314b5aeb4e4c Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 09:27:20 +0900 Subject: [PATCH 22/26] ci: trigger minimal PR 797 finalizer --- .github/pr797-finalize.trigger | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/pr797-finalize.trigger diff --git a/.github/pr797-finalize.trigger b/.github/pr797-finalize.trigger new file mode 100644 index 000000000..15f6d380b --- /dev/null +++ b/.github/pr797-finalize.trigger @@ -0,0 +1 @@ +Trigger the minimal workflow-free PR 797 finalizer. From 40686404c82846d2e82961e83987bc0ca9226b57 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 09:33:09 +0900 Subject: [PATCH 23/26] ci: add corrected PR 797 finalizer --- .github/workflows/finalize-pr797-v2.yml | 122 ++++++++++++++++++++++++ 1 file changed, 122 insertions(+) create mode 100644 .github/workflows/finalize-pr797-v2.yml diff --git a/.github/workflows/finalize-pr797-v2.yml b/.github/workflows/finalize-pr797-v2.yml new file mode 100644 index 000000000..1af8a9fc9 --- /dev/null +++ b/.github/workflows/finalize-pr797-v2.yml @@ -0,0 +1,122 @@ +name: Finalize PR 797 v2 + +on: + push: + branches: [release/exact-artifact-sbom-attestation] + paths: [.github/pr797-finalize-v2.trigger] + +permissions: + contents: read + +jobs: + finalize: + permissions: + contents: write + issues: write + runs-on: ubuntu-24.04 + timeout-minutes: 30 + steps: + - name: Harden runner + uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 + with: + egress-policy: audit + - name: Check out exact head + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + ref: ${{ github.sha }} + fetch-depth: 1 + persist-credentials: false + - name: Apply final coverage tests and remove transient files + shell: bash --noprofile --norc -e -o pipefail {0} + env: + EXPECTED_HEAD: ${{ github.sha }} + run: | + test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" + python3 - <<'PY' + import base64 + from pathlib import Path + + contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') + source = contract.read_text(encoding='utf-8') + old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' + new = ' assert "GITHUB_RUN_ID" in intake\n' + if old in source: + source = source.replace(old, new, 1) + elif new not in source: + raise SystemExit('run-ID contract anchor is absent') + contract.write_text(source, encoding='utf-8') + + hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') + source = hostile.read_text(encoding='utf-8') + if ' root.mkdir()\n' in source: + source = source.replace(' root.mkdir()\n', ' root.mkdir(parents=True)\n', 1) + elif ' root.mkdir(parents=True)\n' not in source: + raise SystemExit('fixture root anchor is absent') + marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' + if marker not in source: + payload = base64.b64decode('CgpkZWYgdGVzdF9jaGVja3N1bV9jb250cm9sX2ZpbGVfYm91bmRzX2FuZF9lbnRyeXBvaW50X2FyZV9jb3ZlcmVkKAogICAgdG1wX3BhdGg6IFBhdGgsCiAgICBtb25rZXlwYXRjaDogcHl0ZXN0Lk1vbmtleVBhdGNoLAogICAgY2Fwc3lzOiBweXRlc3QuQ2FwdHVyZUZpeHR1cmVbc3RyXSwKKSAtPiBOb25lOgogICAgIiIiQ292ZXIgYm91bmRlZCBjaGVja3N1bSBkZWNvZGluZyBhbmQgdGhlIHJlYWwgbW9kdWxlIGVudHJ5cG9pbnQuIiIiCiAgICBjaGVja3N1bSA9IHRtcF9wYXRoIC8gImNoZWNrc3Vtcy5zaGEyNTYiCiAgICBjaGVja3N1bS53cml0ZV90ZXh0KCgiMCIgKiA2NCkgKyAiICBwYXlsb2FkLmJpblxuIiwgZW5jb2Rpbmc9InV0Zi04IikKICAgIG1vbmtleXBhdGNoLnNldGF0dHIodmVyaWZpZXIsICJfTUFYX0NPTlRST0xfQllURVMiLCA0KQogICAgd2l0aCBweXRlc3QucmFpc2VzKHZlcmlmaWVyLkV2aWRlbmNlRXJyb3IsIG1hdGNoPSJzaXplIGxpbWl0Iik6CiAgICAgICAgdmVyaWZpZXIuX3BhcnNlX2NoZWNrc3VtcyhjaGVja3N1bSkKCiAgICBtb25rZXlwYXRjaC5zZXRhdHRyKHZlcmlmaWVyLCAiX01BWF9DT05UUk9MX0JZVEVTIiwgMTAyNCkKICAgIGNoZWNrc3VtLndyaXRlX2J5dGVzKGIiXHhmZiIpCiAgICB3aXRoIHB5dGVzdC5yYWlzZXModmVyaWZpZXIuRXZpZGVuY2VFcnJvciwgbWF0Y2g9InN0cmljdCBVVEYtOCIpOgogICAgICAgIHZlcmlmaWVyLl9wYXJzZV9jaGVja3N1bXMoY2hlY2tzdW0pCgogICAgaW1wb3J0IHJ1bnB5CiAgICBpbXBvcnQgc3lzCgogICAgYXJndW1lbnRzID0gX3ZhbGlkX2hhbmRvZmYodG1wX3BhdGggLyAiZW50cnlwb2ludCIpCiAgICBhcmd2OiBsaXN0W3N0cl0gPSBbXQogICAgZm9yIG5hbWUsIHZhbHVlIGluIHZhcnMoYXJndW1lbnRzKS5pdGVtcygpOgogICAgICAgIGFyZ3YuZXh0ZW5kKCgiLS0iICsgbmFtZS5yZXBsYWNlKCJfIiwgIi0iKSwgc3RyKHZhbHVlKSkpCiAgICBtb25rZXlwYXRjaC5zZXRhdHRyKHN5cywgImFyZ3YiLCBbc3RyKHZlcmlmaWVyLl9fZmlsZV9fKSwgKmFyZ3ZdKQogICAgd2l0aCBweXRlc3QucmFpc2VzKFN5c3RlbUV4aXQpIGFzIGV4aXRfaW5mbzoKICAgICAgICBydW5weS5ydW5fcGF0aChzdHIodmVyaWZpZXIuX19maWxlX18pLCBydW5fbmFtZT0iX19tYWluX18iKQogICAgYXNzZXJ0IGV4aXRfaW5mby52YWx1ZS5jb2RlID09IDAKICAgIGFzc2VydCAic2VhbGVkIGV2aWRlbmNlIHZlcmlmaWNhdGlvbiBwYXNzZWQiIGluIGNhcHN5cy5yZWFkb3V0ZXJyKCkub3V0Cg==').decode('utf-8') + source = source.rstrip() + payload + hostile.write_text(source, encoding='utf-8') + PY + rm -f \ + .github/pr797-finalize.trigger \ + .github/pr797-finalize-v2.trigger \ + .github/workflows/finalize-pr797-minimal.yml \ + .github/workflows/finalize-pr797-on-ready.yml \ + .github/workflows/finalize-pr797-v2.yml \ + .github/workflows/repair-pr797-exact-handoff.yml \ + .github/workflows/repair-pr797-final-coverage.yml \ + .github/workflows/trigger-pr797-exact-handoff-repair.yml + git diff --check + - name: Set up Python + uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 + with: + python-version: '3.14' + cache: pip + cache-dependency-path: requirements-opencode-review-ci-hashes.txt + - name: Install tooling + run: python -m pip install --disable-pip-version-check --require-hashes -r requirements-opencode-review-ci-hashes.txt + - name: Verify full quality + shell: bash --noprofile --norc -e -o pipefail {0} + run: | + python -m coverage erase + python -m coverage run --branch -m pytest -q tests/test_exact_artifact_sbom_attestation_contract.py tests/test_verify_exact_artifact_sbom_handoff.py + python -m coverage report --include=scripts/ci/verify_exact_artifact_sbom_handoff.py --show-missing --fail-under=100 + python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py + python -m compileall -q scripts/ci/verify_exact_artifact_sbom_handoff.py tests/test_exact_artifact_sbom_attestation_contract.py tests/test_verify_exact_artifact_sbom_handoff.py + git diff --check + - name: Create immutable final commit + shell: bash --noprofile --norc -e -o pipefail {0} + env: + API_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.sha }} + run: | + python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-final.txt" + import base64, json, os, subprocess, urllib.request + from pathlib import Path + repo='ContextualWisdomLab/.github'; parent=os.environ['EXPECTED_HEAD']; token=os.environ['API_TOKEN']; root=f'https://api.github.com/repos/{repo}' + expected={'.github/pr797-finalize.trigger','.github/pr797-finalize-v2.trigger','.github/workflows/finalize-pr797-minimal.yml','.github/workflows/finalize-pr797-on-ready.yml','.github/workflows/finalize-pr797-v2.yml','.github/workflows/repair-pr797-exact-handoff.yml','.github/workflows/repair-pr797-final-coverage.yml','.github/workflows/trigger-pr797-exact-handoff-repair.yml','tests/test_verify_exact_artifact_sbom_handoff.py'} + def request(method, endpoint, payload=None): + req=urllib.request.Request(root+endpoint,data=None if payload is None else json.dumps(payload).encode(),method=method,headers={'Accept':'application/vnd.github+json','Authorization':f'Bearer {token}','X-GitHub-Api-Version':'2022-11-28','User-Agent':'cwl-pr797-v2'}) + with urllib.request.urlopen(req,timeout=60) as response: return json.load(response) + raw=subprocess.check_output(['git','diff','--name-status','-z','HEAD']).decode().split('\0'); changes=[]; i=0 + while i < len(raw)-1: changes.append((raw[i],raw[i+1])); i += 2 + actual={p for _,p in changes} + if actual != expected: raise SystemExit(f'path mismatch missing={sorted(expected-actual)} extra={sorted(actual-expected)}') + parent_obj=request('GET',f'/git/commits/{parent}'); entries=[] + for status,path in changes: + if status == 'D': entries.append({'path':path,'mode':'100644','type':'blob','sha':None}) + else: + blob=request('POST','/git/blobs',{'content':base64.b64encode(Path(path).read_bytes()).decode(),'encoding':'base64'}); entries.append({'path':path,'mode':'100644','type':'blob','sha':blob['sha']}) + tree=request('POST','/git/trees',{'base_tree':parent_obj['tree']['sha'],'tree':entries}); commit=request('POST','/git/commits',{'message':'test: complete exact artifact handoff coverage','tree':tree['sha'],'parents':[parent]}) + print('PR797_FINAL_PARENT_SHA='+parent); print('PR797_FINAL_COMMIT_SHA='+commit['sha']) + PY + - name: Publish final pointer + shell: bash --noprofile --norc -e -o pipefail {0} + env: + GH_TOKEN: ${{ github.token }} + EXPECTED_HEAD: ${{ github.sha }} + run: | + commit_sha="$(sed -n 's/^PR797_FINAL_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-final.txt")" + test "${#commit_sha}" -eq 40 + gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=PR797_FINAL_PARENT_SHA=${EXPECTED_HEAD}%0APR797_FINAL_COMMIT_SHA=${commit_sha}" From 056f57c428efc253afb11cefbc1cdbcea383a804 Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 09:33:25 +0900 Subject: [PATCH 24/26] ci: trigger corrected PR 797 finalizer --- .github/pr797-finalize-v2.trigger | 1 + 1 file changed, 1 insertion(+) create mode 100644 .github/pr797-finalize-v2.trigger diff --git a/.github/pr797-finalize-v2.trigger b/.github/pr797-finalize-v2.trigger new file mode 100644 index 000000000..c25a01343 --- /dev/null +++ b/.github/pr797-finalize-v2.trigger @@ -0,0 +1 @@ +Trigger the corrected workflow-free PR 797 finalization. From ef996aa7e6fd5f410ac480e0b7095ac13371ffe6 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 7 Aug 2026 00:34:11 +0000 Subject: [PATCH 25/26] test: complete exact artifact handoff coverage --- .github/pr797-finalize-v2.trigger | 1 - .github/pr797-finalize.trigger | 1 - .github/workflows/finalize-pr797-minimal.yml | 153 ----------- .github/workflows/finalize-pr797-on-ready.yml | 223 ---------------- .github/workflows/finalize-pr797-v2.yml | 122 --------- .../workflows/repair-pr797-exact-handoff.yml | 198 -------------- .../workflows/repair-pr797-final-coverage.yml | 232 ---------------- .../trigger-pr797-exact-handoff-repair.yml | 248 ------------------ ...test_verify_exact_artifact_sbom_handoff.py | 32 ++- 9 files changed, 31 insertions(+), 1179 deletions(-) delete mode 100644 .github/pr797-finalize-v2.trigger delete mode 100644 .github/pr797-finalize.trigger delete mode 100644 .github/workflows/finalize-pr797-minimal.yml delete mode 100644 .github/workflows/finalize-pr797-on-ready.yml delete mode 100644 .github/workflows/finalize-pr797-v2.yml delete mode 100644 .github/workflows/repair-pr797-exact-handoff.yml delete mode 100644 .github/workflows/repair-pr797-final-coverage.yml delete mode 100644 .github/workflows/trigger-pr797-exact-handoff-repair.yml diff --git a/.github/pr797-finalize-v2.trigger b/.github/pr797-finalize-v2.trigger deleted file mode 100644 index c25a01343..000000000 --- a/.github/pr797-finalize-v2.trigger +++ /dev/null @@ -1 +0,0 @@ -Trigger the corrected workflow-free PR 797 finalization. diff --git a/.github/pr797-finalize.trigger b/.github/pr797-finalize.trigger deleted file mode 100644 index 15f6d380b..000000000 --- a/.github/pr797-finalize.trigger +++ /dev/null @@ -1 +0,0 @@ -Trigger the minimal workflow-free PR 797 finalizer. diff --git a/.github/workflows/finalize-pr797-minimal.yml b/.github/workflows/finalize-pr797-minimal.yml deleted file mode 100644 index e4d8ac4ac..000000000 --- a/.github/workflows/finalize-pr797-minimal.yml +++ /dev/null @@ -1,153 +0,0 @@ -name: Finalize PR 797 minimal - -on: - push: - branches: - - release/exact-artifact-sbom-attestation - paths: - - .github/pr797-finalize.trigger - -permissions: - contents: read - -jobs: - finalize: - permissions: - contents: write - issues: write - runs-on: ubuntu-24.04 - timeout-minutes: 30 - steps: - - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 - with: - egress-policy: audit - - - name: Check out exact head - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - with: - ref: ${{ github.sha }} - fetch-depth: 1 - persist-credentials: false - - - name: Apply final test fixes - shell: bash --noprofile --norc -e -o pipefail {0} - env: - EXPECTED_HEAD: ${{ github.sha }} - run: | - test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - python3 - <<'PY' - from pathlib import Path - - contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') - source = contract.read_text(encoding='utf-8') - old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' - new = ' assert "GITHUB_RUN_ID" in intake\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('run-ID contract anchor is absent') - contract.write_text(source, encoding='utf-8') - - hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') - source = hostile.read_text(encoding='utf-8') - old = ' root.mkdir()\n' - new = ' root.mkdir(parents=True)\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('fixture root anchor is absent') - marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' - if marker not in source: - import base64 - payload = base64.b64decode('CgpkZWYgdGVzdF9jaGVja3N1bV9jb250cm9sX2ZpbGVfYm91bmRzX2FuZF9lbnRyeXBvaW50X2FyZV9jb3ZlcmVkKAogICAgdG1wX3BhdGg6IFBhdGgsCiAgICBtb25rZXlwYXRjaDogcHl0ZXN0Lk1vbmtleVBhdGNoLAogICAgY2Fwc3lzOiBweXRlc3QuQ2FwdHVyZUZpeHR1cmVbc3RyXSwKKSAtPiBOb25lOgogICAgIiIiQ292ZXIgYm91bmRlZCBjaGVja3N1bSBkZWNvZGluZyBhbmQgdGhlIHJlYWwgbW9kdWxlIGVudHJ5cG9pbnQuIiIiCiAgICBjaGVja3N1bSA9IHRtcF9wYXRoIC8gImNoZWNrc3Vtcy5zaGEyNTYiCiAgICBjaGVja3N1bS53cml0ZV90ZXh0KCgiMCIgKiA2NCkgKyAiICBwYXlsb2FkLmJpblxuIiwgZW5jb2Rpbmc9InV0Zi04IikKICAgIG1vbmtleXBhdGNoLnNldGF0dHIodmVyaWZpZXIsICJfTUFYX0NPTlRST0xfQllURVMiLCA0KQogICAgd2l0aCBweXRlc3QucmFpc2VzKHZlcmlmaWVyLkV2aWRlbmNlRXJyb3IsIG1hdGNoPSJzaXplIGxpbWl0Iik6CiAgICAgICAgdmVyaWZpZXIuX3BhcnNlX2NoZWNrc3VtcyhjaGVja3N1bSkKCiAgICBtb25rZXlwYXRjaC5zZXRhdHRyKHZlcmlmaWVyLCAiX01BWF9DT05UUk9MX0JZVEVTIiwgMTAyNCkKICAgIGNoZWNrc3VtLndyaXRlX2J5dGVzKGIiXHhmZiIpCiAgICB3aXRoIHB5dGVzdC5yYWlzZXModmVyaWZpZXIuRXZpZGVuY2VFcnJvciwgbWF0Y2g9InN0cmljdCBVVEYtOCIpOgogICAgICAgIHZlcmlmaWVyLl9wYXJzZV9jaGVja3N1bXMoY2hlY2tzdW0pCgogICAgaW1wb3J0IHJ1bnB5CiAgICBpbXBvcnQgc3lzCgogICAgYXJndW1lbnRzID0gX3ZhbGlkX2hhbmRvZmYodG1wX3BhdGggLyAiZW50cnlwb2ludCIpCiAgICBhcmd2OiBsaXN0W3N0cl0gPSBbXQogICAgZm9yIG5hbWUsIHZhbHVlIGluIHZhcnMoYXJndW1lbnRzKS5pdGVtcygpOgogICAgICAgIGFyZ3YuZXh0ZW5kKCgiLS0iICsgbmFtZS5yZXBsYWNlKCJfIiwgIi0iKSwgc3RyKHZhbHVlKSkpCiAgICBtb25rZXlwYXRjaC5zZXRhdHRyKHN5cywgImFyZ3YiLCBbc3RyKHZlcmlmaWVyLl9fZmlsZV9fKSwgKmFyZ3ZdKQogICAgd2l0aCBweXRlc3QucmFpc2VzKFN5c3RlbUV4aXQpIGFzIGV4aXRfaW5mbzoKICAgICAgICBydW5weS5ydW5fcGF0aChzdHIodmVyaWZpZXIuX19maWxlX18pLCBydW5fbmFtZT0iX19tYWluX18iKQogICAgYXNzZXJ0IGV4aXRfaW5mby52YWx1ZS5jb2RlID09IDAKICAgIGFzc2VydCAic2VhbGVkIGV2aWRlbmNlIHZlcmlmaWNhdGlvbiBwYXNzZWQiIGluIGNhcHN5cy5yZWFkb3V0ZXJyKCkub3V0Cg==').decode('utf-8') - source = source.rstrip() + payload - hostile.write_text(source, encoding='utf-8') - PY - rm -f \ - .github/pr797-finalize.trigger \ - .github/workflows/finalize-pr797-minimal.yml \ - .github/workflows/finalize-pr797-on-ready.yml \ - .github/workflows/repair-pr797-exact-handoff.yml \ - .github/workflows/repair-pr797-final-coverage.yml \ - .github/workflows/trigger-pr797-exact-handoff-repair.yml - git diff --check - - - name: Set up Python - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 - with: - python-version: '3.14' - cache: pip - cache-dependency-path: requirements-opencode-review-ci-hashes.txt - - - name: Install tooling - run: python -m pip install --disable-pip-version-check --require-hashes -r requirements-opencode-review-ci-hashes.txt - - - name: Verify full quality - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - python -m coverage erase - python -m coverage run --branch -m pytest -q tests/test_exact_artifact_sbom_attestation_contract.py tests/test_verify_exact_artifact_sbom_handoff.py - python -m coverage report --include=scripts/ci/verify_exact_artifact_sbom_handoff.py --show-missing --fail-under=100 - python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py - python -m compileall -q scripts/ci/verify_exact_artifact_sbom_handoff.py tests/test_exact_artifact_sbom_attestation_contract.py tests/test_verify_exact_artifact_sbom_handoff.py - git diff --check - - - name: Create immutable final commit - shell: bash --noprofile --norc -e -o pipefail {0} - env: - API_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.sha }} - run: | - python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-final.txt" - import base64, json, os, subprocess, urllib.request - from pathlib import Path - repo = 'ContextualWisdomLab/.github' - parent = os.environ['EXPECTED_HEAD'] - token = os.environ['API_TOKEN'] - root = f'https://api.github.com/repos/{repo}' - expected = { - '.github/pr797-finalize.trigger', - '.github/workflows/finalize-pr797-minimal.yml', - '.github/workflows/finalize-pr797-on-ready.yml', - '.github/workflows/repair-pr797-exact-handoff.yml', - '.github/workflows/repair-pr797-final-coverage.yml', - '.github/workflows/trigger-pr797-exact-handoff-repair.yml', - 'tests/test_exact_artifact_sbom_attestation_contract.py', - 'tests/test_verify_exact_artifact_sbom_handoff.py', - } - def request(method, endpoint, payload=None): - req = urllib.request.Request(root + endpoint, data=None if payload is None else json.dumps(payload).encode(), method=method, headers={'Accept':'application/vnd.github+json','Authorization':f'Bearer {token}','X-GitHub-Api-Version':'2022-11-28','User-Agent':'cwl-pr797-finalizer'}) - with urllib.request.urlopen(req, timeout=60) as response: - return json.load(response) - raw = subprocess.check_output(['git','diff','--name-status','-z','HEAD']).decode().split('\0') - changes=[] - i=0 - while i < len(raw)-1: - changes.append((raw[i],raw[i+1])); i += 2 - actual={path for _,path in changes} - if actual != expected: - raise SystemExit(f'path mismatch missing={sorted(expected-actual)} extra={sorted(actual-expected)}') - parent_obj=request('GET',f'/git/commits/{parent}') - entries=[] - for status,path in changes: - if status == 'D': - entries.append({'path':path,'mode':'100644','type':'blob','sha':None}) - else: - blob=request('POST','/git/blobs',{'content':base64.b64encode(Path(path).read_bytes()).decode(),'encoding':'base64'}) - entries.append({'path':path,'mode':'100644','type':'blob','sha':blob['sha']}) - tree=request('POST','/git/trees',{'base_tree':parent_obj['tree']['sha'],'tree':entries}) - commit=request('POST','/git/commits',{'message':'test: complete exact artifact handoff coverage','tree':tree['sha'],'parents':[parent]}) - print('PR797_FINAL_PARENT_SHA=' + parent) - print('PR797_FINAL_COMMIT_SHA=' + commit['sha']) - PY - - - name: Publish final pointer - shell: bash --noprofile --norc -e -o pipefail {0} - env: - GH_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.sha }} - run: | - commit_sha="$(sed -n 's/^PR797_FINAL_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-final.txt")" - test "${#commit_sha}" -eq 40 - gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=PR797_FINAL_PARENT_SHA=${EXPECTED_HEAD}%0APR797_FINAL_COMMIT_SHA=${commit_sha}" diff --git a/.github/workflows/finalize-pr797-on-ready.yml b/.github/workflows/finalize-pr797-on-ready.yml deleted file mode 100644 index 911e5da18..000000000 --- a/.github/workflows/finalize-pr797-on-ready.yml +++ /dev/null @@ -1,223 +0,0 @@ -name: Finalize PR 797 verifier coverage - -on: - pull_request: - branches: [main] - types: [ready_for_review] - -permissions: - contents: read - -jobs: - finalize: - if: >- - github.repository == 'ContextualWisdomLab/.github' && - github.event.pull_request.number == 797 && - github.event.pull_request.head.ref == 'release/exact-artifact-sbom-attestation' - permissions: - contents: write - issues: write - pull-requests: write - runs-on: ubuntu-24.04 - timeout-minutes: 30 - steps: - - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 - with: - egress-policy: audit - - - name: Check out exact PR head - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.event.pull_request.head.sha }} - fetch-depth: 1 - persist-credentials: false - - - name: Apply final exact-head coverage cases - env: - EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - python3 - <<'PY' - from pathlib import Path - - contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') - source = contract.read_text(encoding='utf-8') - old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' - new = ' assert "GITHUB_RUN_ID" in intake\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('run-ID contract anchor is absent') - contract.write_text(source, encoding='utf-8') - - hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') - source = hostile.read_text(encoding='utf-8') - old = ' root.mkdir()\n' - new = ' root.mkdir(parents=True)\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('fixture root anchor is absent') - marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' - if marker not in source: - source = source.rstrip() + r''' - - -def test_checksum_control_file_bounds_and_entrypoint_are_covered( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - """Cover bounded checksum decoding and the real module entrypoint.""" - checksum = tmp_path / "checksums.sha256" - checksum.write_text(("0" * 64) + " payload.bin\n", encoding="utf-8") - monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 4) - with pytest.raises(verifier.EvidenceError, match="size limit"): - verifier._parse_checksums(checksum) - - monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 1024) - checksum.write_bytes(b"\xff") - with pytest.raises(verifier.EvidenceError, match="strict UTF-8"): - verifier._parse_checksums(checksum) - - import runpy - import sys - - arguments = _valid_handoff(tmp_path / "entrypoint") - argv: list[str] = [] - for name, value in vars(arguments).items(): - argv.extend(("--" + name.replace("_", "-"), str(value))) - monkeypatch.setattr(sys, "argv", [str(verifier.__file__), *argv]) - with pytest.raises(SystemExit) as exit_info: - runpy.run_path(str(verifier.__file__), run_name="__main__") - assert exit_info.value.code == 0 - assert "sealed evidence verification passed" in capsys.readouterr().out -'''.rstrip() + '\n' - hostile.write_text(source, encoding='utf-8') - PY - rm -f \ - .github/workflows/repair-pr797-exact-handoff.yml \ - .github/workflows/trigger-pr797-exact-handoff-repair.yml \ - .github/workflows/repair-pr797-final-coverage.yml \ - .github/workflows/finalize-pr797-on-ready.yml - git diff --check - - - name: Set up Python 3.14 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: "3.14" - cache: pip - cache-dependency-path: requirements-opencode-review-ci-hashes.txt - - - name: Install exact hash-locked tooling - run: >- - python -m pip install --disable-pip-version-check --require-hashes - -r requirements-opencode-review-ci-hashes.txt - - - name: Verify exact contracts and complete verifier coverage - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - python -m coverage erase - python -m coverage run --branch -m pytest -q \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - python -m coverage report \ - --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ - --show-missing \ - --fail-under=100 - python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py - python -m compileall -q \ - scripts/ci/verify_exact_artifact_sbom_handoff.py \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - git diff --check - - - name: Build immutable workflow-free final commit - env: - API_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-final.txt" - import base64 - import json - import os - import subprocess - import urllib.request - from pathlib import Path - - repository = 'ContextualWisdomLab/.github' - parent_sha = os.environ['EXPECTED_HEAD'] - token = os.environ['API_TOKEN'] - api_root = f'https://api.github.com/repos/{repository}' - expected_paths = { - '.github/workflows/repair-pr797-exact-handoff.yml', - '.github/workflows/trigger-pr797-exact-handoff-repair.yml', - '.github/workflows/repair-pr797-final-coverage.yml', - '.github/workflows/finalize-pr797-on-ready.yml', - 'tests/test_exact_artifact_sbom_attestation_contract.py', - 'tests/test_verify_exact_artifact_sbom_handoff.py', - } - - def request(method, endpoint, payload=None): - data = None if payload is None else json.dumps(payload).encode('utf-8') - req = urllib.request.Request( - api_root + endpoint, - data=data, - method=method, - headers={ - 'Accept': 'application/vnd.github+json', - 'Authorization': f'Bearer {token}', - 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': 'cwl-pr797-finalizer', - }, - ) - with urllib.request.urlopen(req, timeout=60) as response: - return json.load(response) - - raw = subprocess.check_output(['git', 'diff', '--name-status', '-z', 'HEAD']) - parts = raw.decode('utf-8').split('\0') - changes = [] - index = 0 - while index < len(parts) - 1: - status = parts[index] - path = parts[index + 1] - index += 2 - changes.append((status, path)) - actual_paths = {path for _, path in changes} - if actual_paths != expected_paths: - raise SystemExit( - f'final path mismatch: missing={sorted(expected_paths - actual_paths)} ' - f'extra={sorted(actual_paths - expected_paths)}' - ) - parent = request('GET', f'/git/commits/{parent_sha}') - entries = [] - for status, path in changes: - if status == 'D': - entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': None}) - else: - encoded = base64.b64encode(Path(path).read_bytes()).decode('ascii') - blob = request('POST', '/git/blobs', {'content': encoded, 'encoding': 'base64'}) - entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob['sha']}) - tree = request('POST', '/git/trees', {'base_tree': parent['tree']['sha'], 'tree': entries}) - commit = request('POST', '/git/commits', { - 'message': 'test: complete exact artifact handoff coverage', - 'tree': tree['sha'], - 'parents': [parent_sha], - }) - print(f"PR797_FINAL_PARENT_SHA={parent_sha}") - print(f"PR797_FINAL_COMMIT_SHA={commit['sha']}") - PY - - - name: Publish final commit pointer - env: - GH_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - commit_sha="$(sed -n 's/^PR797_FINAL_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-final.txt")" - test "${#commit_sha}" -eq 40 - body="PR797_FINAL_PARENT_SHA=${EXPECTED_HEAD}%0APR797_FINAL_COMMIT_SHA=${commit_sha}" - gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=${body}" diff --git a/.github/workflows/finalize-pr797-v2.yml b/.github/workflows/finalize-pr797-v2.yml deleted file mode 100644 index 1af8a9fc9..000000000 --- a/.github/workflows/finalize-pr797-v2.yml +++ /dev/null @@ -1,122 +0,0 @@ -name: Finalize PR 797 v2 - -on: - push: - branches: [release/exact-artifact-sbom-attestation] - paths: [.github/pr797-finalize-v2.trigger] - -permissions: - contents: read - -jobs: - finalize: - permissions: - contents: write - issues: write - runs-on: ubuntu-24.04 - timeout-minutes: 30 - steps: - - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 - with: - egress-policy: audit - - name: Check out exact head - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 - with: - ref: ${{ github.sha }} - fetch-depth: 1 - persist-credentials: false - - name: Apply final coverage tests and remove transient files - shell: bash --noprofile --norc -e -o pipefail {0} - env: - EXPECTED_HEAD: ${{ github.sha }} - run: | - test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - python3 - <<'PY' - import base64 - from pathlib import Path - - contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') - source = contract.read_text(encoding='utf-8') - old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' - new = ' assert "GITHUB_RUN_ID" in intake\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('run-ID contract anchor is absent') - contract.write_text(source, encoding='utf-8') - - hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') - source = hostile.read_text(encoding='utf-8') - if ' root.mkdir()\n' in source: - source = source.replace(' root.mkdir()\n', ' root.mkdir(parents=True)\n', 1) - elif ' root.mkdir(parents=True)\n' not in source: - raise SystemExit('fixture root anchor is absent') - marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' - if marker not in source: - payload = base64.b64decode('CgpkZWYgdGVzdF9jaGVja3N1bV9jb250cm9sX2ZpbGVfYm91bmRzX2FuZF9lbnRyeXBvaW50X2FyZV9jb3ZlcmVkKAogICAgdG1wX3BhdGg6IFBhdGgsCiAgICBtb25rZXlwYXRjaDogcHl0ZXN0Lk1vbmtleVBhdGNoLAogICAgY2Fwc3lzOiBweXRlc3QuQ2FwdHVyZUZpeHR1cmVbc3RyXSwKKSAtPiBOb25lOgogICAgIiIiQ292ZXIgYm91bmRlZCBjaGVja3N1bSBkZWNvZGluZyBhbmQgdGhlIHJlYWwgbW9kdWxlIGVudHJ5cG9pbnQuIiIiCiAgICBjaGVja3N1bSA9IHRtcF9wYXRoIC8gImNoZWNrc3Vtcy5zaGEyNTYiCiAgICBjaGVja3N1bS53cml0ZV90ZXh0KCgiMCIgKiA2NCkgKyAiICBwYXlsb2FkLmJpblxuIiwgZW5jb2Rpbmc9InV0Zi04IikKICAgIG1vbmtleXBhdGNoLnNldGF0dHIodmVyaWZpZXIsICJfTUFYX0NPTlRST0xfQllURVMiLCA0KQogICAgd2l0aCBweXRlc3QucmFpc2VzKHZlcmlmaWVyLkV2aWRlbmNlRXJyb3IsIG1hdGNoPSJzaXplIGxpbWl0Iik6CiAgICAgICAgdmVyaWZpZXIuX3BhcnNlX2NoZWNrc3VtcyhjaGVja3N1bSkKCiAgICBtb25rZXlwYXRjaC5zZXRhdHRyKHZlcmlmaWVyLCAiX01BWF9DT05UUk9MX0JZVEVTIiwgMTAyNCkKICAgIGNoZWNrc3VtLndyaXRlX2J5dGVzKGIiXHhmZiIpCiAgICB3aXRoIHB5dGVzdC5yYWlzZXModmVyaWZpZXIuRXZpZGVuY2VFcnJvciwgbWF0Y2g9InN0cmljdCBVVEYtOCIpOgogICAgICAgIHZlcmlmaWVyLl9wYXJzZV9jaGVja3N1bXMoY2hlY2tzdW0pCgogICAgaW1wb3J0IHJ1bnB5CiAgICBpbXBvcnQgc3lzCgogICAgYXJndW1lbnRzID0gX3ZhbGlkX2hhbmRvZmYodG1wX3BhdGggLyAiZW50cnlwb2ludCIpCiAgICBhcmd2OiBsaXN0W3N0cl0gPSBbXQogICAgZm9yIG5hbWUsIHZhbHVlIGluIHZhcnMoYXJndW1lbnRzKS5pdGVtcygpOgogICAgICAgIGFyZ3YuZXh0ZW5kKCgiLS0iICsgbmFtZS5yZXBsYWNlKCJfIiwgIi0iKSwgc3RyKHZhbHVlKSkpCiAgICBtb25rZXlwYXRjaC5zZXRhdHRyKHN5cywgImFyZ3YiLCBbc3RyKHZlcmlmaWVyLl9fZmlsZV9fKSwgKmFyZ3ZdKQogICAgd2l0aCBweXRlc3QucmFpc2VzKFN5c3RlbUV4aXQpIGFzIGV4aXRfaW5mbzoKICAgICAgICBydW5weS5ydW5fcGF0aChzdHIodmVyaWZpZXIuX19maWxlX18pLCBydW5fbmFtZT0iX19tYWluX18iKQogICAgYXNzZXJ0IGV4aXRfaW5mby52YWx1ZS5jb2RlID09IDAKICAgIGFzc2VydCAic2VhbGVkIGV2aWRlbmNlIHZlcmlmaWNhdGlvbiBwYXNzZWQiIGluIGNhcHN5cy5yZWFkb3V0ZXJyKCkub3V0Cg==').decode('utf-8') - source = source.rstrip() + payload - hostile.write_text(source, encoding='utf-8') - PY - rm -f \ - .github/pr797-finalize.trigger \ - .github/pr797-finalize-v2.trigger \ - .github/workflows/finalize-pr797-minimal.yml \ - .github/workflows/finalize-pr797-on-ready.yml \ - .github/workflows/finalize-pr797-v2.yml \ - .github/workflows/repair-pr797-exact-handoff.yml \ - .github/workflows/repair-pr797-final-coverage.yml \ - .github/workflows/trigger-pr797-exact-handoff-repair.yml - git diff --check - - name: Set up Python - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 - with: - python-version: '3.14' - cache: pip - cache-dependency-path: requirements-opencode-review-ci-hashes.txt - - name: Install tooling - run: python -m pip install --disable-pip-version-check --require-hashes -r requirements-opencode-review-ci-hashes.txt - - name: Verify full quality - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - python -m coverage erase - python -m coverage run --branch -m pytest -q tests/test_exact_artifact_sbom_attestation_contract.py tests/test_verify_exact_artifact_sbom_handoff.py - python -m coverage report --include=scripts/ci/verify_exact_artifact_sbom_handoff.py --show-missing --fail-under=100 - python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py - python -m compileall -q scripts/ci/verify_exact_artifact_sbom_handoff.py tests/test_exact_artifact_sbom_attestation_contract.py tests/test_verify_exact_artifact_sbom_handoff.py - git diff --check - - name: Create immutable final commit - shell: bash --noprofile --norc -e -o pipefail {0} - env: - API_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.sha }} - run: | - python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-final.txt" - import base64, json, os, subprocess, urllib.request - from pathlib import Path - repo='ContextualWisdomLab/.github'; parent=os.environ['EXPECTED_HEAD']; token=os.environ['API_TOKEN']; root=f'https://api.github.com/repos/{repo}' - expected={'.github/pr797-finalize.trigger','.github/pr797-finalize-v2.trigger','.github/workflows/finalize-pr797-minimal.yml','.github/workflows/finalize-pr797-on-ready.yml','.github/workflows/finalize-pr797-v2.yml','.github/workflows/repair-pr797-exact-handoff.yml','.github/workflows/repair-pr797-final-coverage.yml','.github/workflows/trigger-pr797-exact-handoff-repair.yml','tests/test_verify_exact_artifact_sbom_handoff.py'} - def request(method, endpoint, payload=None): - req=urllib.request.Request(root+endpoint,data=None if payload is None else json.dumps(payload).encode(),method=method,headers={'Accept':'application/vnd.github+json','Authorization':f'Bearer {token}','X-GitHub-Api-Version':'2022-11-28','User-Agent':'cwl-pr797-v2'}) - with urllib.request.urlopen(req,timeout=60) as response: return json.load(response) - raw=subprocess.check_output(['git','diff','--name-status','-z','HEAD']).decode().split('\0'); changes=[]; i=0 - while i < len(raw)-1: changes.append((raw[i],raw[i+1])); i += 2 - actual={p for _,p in changes} - if actual != expected: raise SystemExit(f'path mismatch missing={sorted(expected-actual)} extra={sorted(actual-expected)}') - parent_obj=request('GET',f'/git/commits/{parent}'); entries=[] - for status,path in changes: - if status == 'D': entries.append({'path':path,'mode':'100644','type':'blob','sha':None}) - else: - blob=request('POST','/git/blobs',{'content':base64.b64encode(Path(path).read_bytes()).decode(),'encoding':'base64'}); entries.append({'path':path,'mode':'100644','type':'blob','sha':blob['sha']}) - tree=request('POST','/git/trees',{'base_tree':parent_obj['tree']['sha'],'tree':entries}); commit=request('POST','/git/commits',{'message':'test: complete exact artifact handoff coverage','tree':tree['sha'],'parents':[parent]}) - print('PR797_FINAL_PARENT_SHA='+parent); print('PR797_FINAL_COMMIT_SHA='+commit['sha']) - PY - - name: Publish final pointer - shell: bash --noprofile --norc -e -o pipefail {0} - env: - GH_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.sha }} - run: | - commit_sha="$(sed -n 's/^PR797_FINAL_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-final.txt")" - test "${#commit_sha}" -eq 40 - gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=PR797_FINAL_PARENT_SHA=${EXPECTED_HEAD}%0APR797_FINAL_COMMIT_SHA=${commit_sha}" diff --git a/.github/workflows/repair-pr797-exact-handoff.yml b/.github/workflows/repair-pr797-exact-handoff.yml deleted file mode 100644 index b8ac00bae..000000000 --- a/.github/workflows/repair-pr797-exact-handoff.yml +++ /dev/null @@ -1,198 +0,0 @@ -name: Repair PR 797 exact handoff contracts -run-name: Repair PR 797 exact handoff at ${{ github.sha }} - -on: - push: - branches: - - release/exact-artifact-sbom-attestation - paths: - - .github/workflows/repair-pr797-exact-handoff.yml - -permissions: - contents: read - -concurrency: - group: repair-pr797-exact-handoff - cancel-in-progress: false - -env: - FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true - -jobs: - repair: - if: >- - github.repository == 'ContextualWisdomLab/.github' && - github.ref == 'refs/heads/release/exact-artifact-sbom-attestation' - permissions: - contents: write - issues: write - pull-requests: write - runs-on: ubuntu-24.04 - timeout-minutes: 30 - steps: - - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 - with: - egress-policy: audit - - - name: Check out exact trigger head - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.sha }} - fetch-depth: 0 - persist-credentials: false - - - name: Apply the two reviewed test-contract repairs - env: - EXPECTED_HEAD: ${{ github.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - python3 - <<'PY' - from pathlib import Path - - contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') - source = contract.read_text(encoding='utf-8') - old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' - new = ' assert "GITHUB_RUN_ID" in intake\n' - if source.count(old) != 1: - raise SystemExit('exact artifact contract: expected one run-ID repair anchor') - contract.write_text(source.replace(old, new, 1), encoding='utf-8') - - hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') - source = hostile.read_text(encoding='utf-8') - old = ' root.mkdir()\n' - new = ' root.mkdir(parents=True)\n' - if source.count(old) != 1: - raise SystemExit('handoff verifier tests: expected one nested-root repair anchor') - hostile.write_text(source.replace(old, new, 1), encoding='utf-8') - PY - git diff --check - - - name: Set up Python 3.14 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: "3.14" - cache: pip - cache-dependency-path: requirements-opencode-review-ci-hashes.txt - - - name: Install exact hash-locked quality tooling - run: >- - python -m pip install --disable-pip-version-check --require-hashes - -r requirements-opencode-review-ci-hashes.txt - - - name: Verify exact contract and complete verifier coverage - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - python -m coverage erase - python -m coverage run --branch -m pytest -q \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - python -m coverage report \ - --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ - --show-missing \ - --fail-under=100 - python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py - python -m compileall -q \ - scripts/ci/verify_exact_artifact_sbom_handoff.py \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - git diff --check - - - name: Build immutable verified repair commit object - env: - API_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.sha }} - HEAD_BRANCH: release/exact-artifact-sbom-attestation - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - remote_head="$(git ls-remote origin "refs/heads/${HEAD_BRANCH}" | cut -f1)" - test "$remote_head" = "$EXPECTED_HEAD" - python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-repair-receipt.txt" - import base64 - import json - import os - import urllib.request - from pathlib import Path - - repository = 'ContextualWisdomLab/.github' - parent_sha = os.environ['EXPECTED_HEAD'] - token = os.environ['API_TOKEN'] - api_root = f'https://api.github.com/repos/{repository}' - - def request(method, endpoint, payload=None): - data = None if payload is None else json.dumps(payload).encode('utf-8') - req = urllib.request.Request( - api_root + endpoint, - data=data, - method=method, - headers={ - 'Accept': 'application/vnd.github+json', - 'Authorization': f'Bearer {token}', - 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': 'cwl-pr797-repair', - }, - ) - with urllib.request.urlopen(req, timeout=60) as response: - return json.load(response) - - parent = request('GET', f'/git/commits/{parent_sha}') - tree_entries = [] - for path in ( - 'tests/test_exact_artifact_sbom_attestation_contract.py', - 'tests/test_verify_exact_artifact_sbom_handoff.py', - ): - encoded = base64.b64encode(Path(path).read_bytes()).decode('ascii') - blob = request('POST', '/git/blobs', {'content': encoded, 'encoding': 'base64'}) - tree_entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob['sha']}) - print(f"BLOB {blob['sha']} {path}") - tree_entries.append( - { - 'path': '.github/workflows/repair-pr797-exact-handoff.yml', - 'mode': '100644', - 'type': 'blob', - 'sha': None, - } - ) - tree = request( - 'POST', - '/git/trees', - {'base_tree': parent['tree']['sha'], 'tree': tree_entries}, - ) - commit = request( - 'POST', - '/git/commits', - { - 'message': 'test: repair exact artifact handoff contracts', - 'tree': tree['sha'], - 'parents': [parent_sha], - }, - ) - print(f"PR797_REPAIR_PARENT_SHA={parent_sha}") - print(f"PR797_REPAIR_TREE_SHA={tree['sha']}") - print(f"PR797_REPAIR_COMMIT_SHA={commit['sha']}") - PY - - - name: Publish exact-head repair pointer - env: - GH_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - commit_sha="$(sed -n 's/^PR797_REPAIR_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-repair-receipt.txt")" - test "${#commit_sha}" -eq 40 - case "$commit_sha" in (*[!0-9a-f]*) exit 1;; esac - body="PR797_REPAIR_PARENT_SHA=${EXPECTED_HEAD}%0APR797_REPAIR_COMMIT_SHA=${commit_sha}" - gh api \ - --method POST \ - repos/ContextualWisdomLab/.github/issues/797/comments \ - -f "body=${body}" - - - name: Upload exact-head repair receipt - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v6.0.0 - with: - name: pr797-exact-head-repair - path: ${{ runner.temp }}/pr797-repair-receipt.txt - if-no-files-found: error - retention-days: 5 diff --git a/.github/workflows/repair-pr797-final-coverage.yml b/.github/workflows/repair-pr797-final-coverage.yml deleted file mode 100644 index 6b1119072..000000000 --- a/.github/workflows/repair-pr797-final-coverage.yml +++ /dev/null @@ -1,232 +0,0 @@ -name: Repair PR 797 final verifier coverage - -on: - push: - branches: [release/exact-artifact-sbom-attestation] - paths: - - ".github/workflows/repair-pr797-final-coverage.yml" - -permissions: - contents: read - -concurrency: - group: repair-pr797-final-verifier-coverage - cancel-in-progress: false - -env: - FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true - -jobs: - repair: - if: >- - github.repository == 'ContextualWisdomLab/.github' && - github.ref == 'refs/heads/release/exact-artifact-sbom-attestation' - permissions: - contents: write - issues: write - pull-requests: write - runs-on: ubuntu-24.04 - timeout-minutes: 30 - steps: - - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 - with: - egress-policy: audit - - - name: Check out exact trigger head - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.sha }} - fetch-depth: 1 - persist-credentials: false - - - name: Apply final reviewed contracts - env: - EXPECTED_HEAD: ${{ github.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - python3 - <<'PY' - from pathlib import Path - - contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') - source = contract.read_text(encoding='utf-8') - old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' - new = ' assert "GITHUB_RUN_ID" in intake\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('run-ID contract anchor is absent') - contract.write_text(source, encoding='utf-8') - - hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') - source = hostile.read_text(encoding='utf-8') - old = ' root.mkdir()\n' - new = ' root.mkdir(parents=True)\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('fixture root anchor is absent') - - marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' - if marker not in source: - source = source.rstrip() + r''' - - -def test_checksum_control_file_bounds_and_entrypoint_are_covered( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - """Cover bounded checksum decoding and the real module entrypoint.""" - checksum = tmp_path / "checksums.sha256" - checksum.write_text(("0" * 64) + " payload.bin\n", encoding="utf-8") - monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 4) - with pytest.raises(verifier.EvidenceError, match="size limit"): - verifier._parse_checksums(checksum) - - monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 1024) - checksum.write_bytes(b"\xff") - with pytest.raises(verifier.EvidenceError, match="strict UTF-8"): - verifier._parse_checksums(checksum) - - import runpy - import sys - - arguments = _valid_handoff(tmp_path / "entrypoint") - argv: list[str] = [] - for name, value in vars(arguments).items(): - argv.extend(("--" + name.replace("_", "-"), str(value))) - monkeypatch.setattr(sys, "argv", [str(verifier.__file__), *argv]) - with pytest.raises(SystemExit) as exit_info: - runpy.run_path(str(verifier.__file__), run_name="__main__") - assert exit_info.value.code == 0 - assert "sealed evidence verification passed" in capsys.readouterr().out -'''.rstrip() + '\n' - hostile.write_text(source, encoding='utf-8') - PY - rm -f \ - .github/workflows/repair-pr797-exact-handoff.yml \ - .github/workflows/trigger-pr797-exact-handoff-repair.yml \ - .github/workflows/repair-pr797-final-coverage.yml \ - .github/workflows/finalize-pr797-on-ready.yml - git diff --check - - - name: Set up Python 3.14 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: "3.14" - cache: pip - cache-dependency-path: requirements-opencode-review-ci-hashes.txt - - - name: Install exact hash-locked tooling - run: >- - python -m pip install --disable-pip-version-check --require-hashes - -r requirements-opencode-review-ci-hashes.txt - - - name: Verify complete exact-head quality - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - python -m coverage erase - python -m coverage run --branch -m pytest -q \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - python -m coverage report \ - --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ - --show-missing \ - --fail-under=100 - python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py - python -m compileall -q \ - scripts/ci/verify_exact_artifact_sbom_handoff.py \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - git diff --check - - - name: Build immutable workflow-free commit - env: - API_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-repair.txt" - import base64 - import json - import os - import subprocess - import urllib.request - from pathlib import Path - - repository = 'ContextualWisdomLab/.github' - parent_sha = os.environ['EXPECTED_HEAD'] - token = os.environ['API_TOKEN'] - api_root = f'https://api.github.com/repos/{repository}' - expected_paths = { - '.github/workflows/repair-pr797-exact-handoff.yml', - '.github/workflows/trigger-pr797-exact-handoff-repair.yml', - '.github/workflows/repair-pr797-final-coverage.yml', - '.github/workflows/finalize-pr797-on-ready.yml', - 'tests/test_exact_artifact_sbom_attestation_contract.py', - 'tests/test_verify_exact_artifact_sbom_handoff.py', - } - - def request(method, endpoint, payload=None): - data = None if payload is None else json.dumps(payload).encode('utf-8') - req = urllib.request.Request( - api_root + endpoint, - data=data, - method=method, - headers={ - 'Accept': 'application/vnd.github+json', - 'Authorization': f'Bearer {token}', - 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': 'cwl-pr797-repair', - }, - ) - with urllib.request.urlopen(req, timeout=60) as response: - return json.load(response) - - raw = subprocess.check_output(['git', 'diff', '--name-status', '-z', 'HEAD']) - parts = raw.decode('utf-8').split('\0') - changes = [] - index = 0 - while index < len(parts) - 1: - status = parts[index] - path = parts[index + 1] - index += 2 - changes.append((status, path)) - actual = {path for _, path in changes} - if actual != expected_paths: - raise SystemExit( - f'repair path mismatch: missing={sorted(expected_paths - actual)} ' - f'extra={sorted(actual - expected_paths)}' - ) - - parent = request('GET', f'/git/commits/{parent_sha}') - entries = [] - for status, path in changes: - if status == 'D': - entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': None}) - else: - encoded = base64.b64encode(Path(path).read_bytes()).decode('ascii') - blob = request('POST', '/git/blobs', {'content': encoded, 'encoding': 'base64'}) - entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob['sha']}) - tree = request('POST', '/git/trees', {'base_tree': parent['tree']['sha'], 'tree': entries}) - commit = request('POST', '/git/commits', { - 'message': 'test: complete exact artifact handoff coverage', - 'tree': tree['sha'], - 'parents': [parent_sha], - }) - print(f"PR797_REPAIR_PARENT_SHA={parent_sha}") - print(f"PR797_REPAIR_COMMIT_SHA={commit['sha']}") - PY - - - name: Publish repair pointer - env: - GH_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - commit_sha="$(sed -n 's/^PR797_REPAIR_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-repair.txt")" - test "${#commit_sha}" -eq 40 - body="PR797_REPAIR_PARENT_SHA=${EXPECTED_HEAD}%0APR797_REPAIR_COMMIT_SHA=${commit_sha}" - gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=${body}" diff --git a/.github/workflows/trigger-pr797-exact-handoff-repair.yml b/.github/workflows/trigger-pr797-exact-handoff-repair.yml deleted file mode 100644 index 1182fc936..000000000 --- a/.github/workflows/trigger-pr797-exact-handoff-repair.yml +++ /dev/null @@ -1,248 +0,0 @@ -name: Trigger PR 797 exact handoff repair - -on: - pull_request: - branches: - - main - types: - - synchronize - -permissions: - contents: read - -concurrency: - group: trigger-pr797-exact-handoff-repair - cancel-in-progress: false - -env: - FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true - -jobs: - repair: - if: >- - github.repository == 'ContextualWisdomLab/.github' && - github.event.pull_request.number == 797 && - github.event.pull_request.head.ref == 'release/exact-artifact-sbom-attestation' - permissions: - contents: write - issues: write - pull-requests: write - runs-on: ubuntu-24.04 - timeout-minutes: 30 - steps: - - name: Harden runner - uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 - with: - egress-policy: audit - - - name: Check out exact PR head - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - ref: ${{ github.event.pull_request.head.sha }} - fetch-depth: 1 - persist-credentials: false - - - name: Apply reviewed contracts and final coverage cases - env: - EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - python3 - <<'PY' - from pathlib import Path - - contract = Path('tests/test_exact_artifact_sbom_attestation_contract.py') - source = contract.read_text(encoding='utf-8') - old = ' assert "' + '$' + '{{ github.run_id }}" in intake\n' - new = ' assert "GITHUB_RUN_ID" in intake\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('exact artifact contract run-ID anchor is absent') - contract.write_text(source, encoding='utf-8') - - hostile = Path('tests/test_verify_exact_artifact_sbom_handoff.py') - source = hostile.read_text(encoding='utf-8') - old = ' root.mkdir()\n' - new = ' root.mkdir(parents=True)\n' - if old in source: - source = source.replace(old, new, 1) - elif new not in source: - raise SystemExit('handoff fixture root anchor is absent') - - marker = 'def test_checksum_control_file_bounds_and_entrypoint_are_covered(' - if marker not in source: - source = source.rstrip() + r''' - - -def test_checksum_control_file_bounds_and_entrypoint_are_covered( - tmp_path: Path, - monkeypatch: pytest.MonkeyPatch, - capsys: pytest.CaptureFixture[str], -) -> None: - """Cover bounded checksum decoding and the real module entrypoint.""" - checksum = tmp_path / "checksums.sha256" - checksum.write_text(("0" * 64) + " payload.bin\n", encoding="utf-8") - monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 4) - with pytest.raises(verifier.EvidenceError, match="size limit"): - verifier._parse_checksums(checksum) - - monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 1024) - checksum.write_bytes(b"\xff") - with pytest.raises(verifier.EvidenceError, match="strict UTF-8"): - verifier._parse_checksums(checksum) - - import runpy - import sys - - arguments = _valid_handoff(tmp_path / "entrypoint") - argv: list[str] = [] - for name, value in vars(arguments).items(): - argv.extend(("--" + name.replace("_", "-"), str(value))) - monkeypatch.setattr(sys, "argv", [str(verifier.__file__), *argv]) - with pytest.raises(SystemExit) as exit_info: - runpy.run_path(str(verifier.__file__), run_name="__main__") - assert exit_info.value.code == 0 - assert "sealed evidence verification passed" in capsys.readouterr().out -'''.rstrip() + '\n' - hostile.write_text(source, encoding='utf-8') - PY - rm -f \ - .github/workflows/repair-pr797-exact-handoff.yml \ - .github/workflows/trigger-pr797-exact-handoff-repair.yml \ - .github/workflows/repair-pr797-final-coverage.yml - git diff --check - - - name: Set up Python 3.14 - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 - with: - python-version: "3.14" - cache: pip - cache-dependency-path: requirements-opencode-review-ci-hashes.txt - - - name: Install exact hash-locked tooling - run: >- - python -m pip install --disable-pip-version-check --require-hashes - -r requirements-opencode-review-ci-hashes.txt - - - name: Verify exact contracts and complete verifier coverage - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - python -m coverage erase - python -m coverage run --branch -m pytest -q \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - python -m coverage report \ - --include=scripts/ci/verify_exact_artifact_sbom_handoff.py \ - --show-missing \ - --fail-under=100 - python -m interrogate --fail-under=100 scripts/ci/verify_exact_artifact_sbom_handoff.py - python -m compileall -q \ - scripts/ci/verify_exact_artifact_sbom_handoff.py \ - tests/test_exact_artifact_sbom_attestation_contract.py \ - tests/test_verify_exact_artifact_sbom_handoff.py - git diff --check - - - name: Build immutable workflow-free repair commit - env: - API_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} - SOURCE_BRANCH: release/exact-artifact-sbom-attestation - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - test "$(git rev-parse HEAD)" = "$EXPECTED_HEAD" - remote_head="$(git ls-remote origin "refs/heads/${SOURCE_BRANCH}" | cut -f1)" - test "$remote_head" = "$EXPECTED_HEAD" - python3 - <<'PY' | tee "${RUNNER_TEMP}/pr797-trigger-receipt.txt" - import base64 - import json - import os - import subprocess - import urllib.request - from pathlib import Path - - repository = 'ContextualWisdomLab/.github' - parent_sha = os.environ['EXPECTED_HEAD'] - token = os.environ['API_TOKEN'] - api_root = f'https://api.github.com/repos/{repository}' - expected_paths = { - '.github/workflows/repair-pr797-exact-handoff.yml', - '.github/workflows/trigger-pr797-exact-handoff-repair.yml', - '.github/workflows/repair-pr797-final-coverage.yml', - 'tests/test_exact_artifact_sbom_attestation_contract.py', - 'tests/test_verify_exact_artifact_sbom_handoff.py', - } - - def request(method, endpoint, payload=None): - data = None if payload is None else json.dumps(payload).encode('utf-8') - req = urllib.request.Request( - api_root + endpoint, - data=data, - method=method, - headers={ - 'Accept': 'application/vnd.github+json', - 'Authorization': f'Bearer {token}', - 'X-GitHub-Api-Version': '2022-11-28', - 'User-Agent': 'cwl-pr797-final-repair', - }, - ) - with urllib.request.urlopen(req, timeout=60) as response: - return json.load(response) - - raw = subprocess.check_output(['git', 'diff', '--name-status', '-z', 'HEAD']) - parts = raw.decode('utf-8').split('\0') - changes = [] - index = 0 - while index < len(parts) - 1: - status = parts[index] - path = parts[index + 1] - index += 2 - changes.append((status, path)) - actual_paths = {path for _, path in changes} - if actual_paths != expected_paths: - raise SystemExit( - f'repair path mismatch: missing={sorted(expected_paths - actual_paths)} ' - f'extra={sorted(actual_paths - expected_paths)}' - ) - - parent = request('GET', f'/git/commits/{parent_sha}') - tree_entries = [] - for status, path in changes: - if status == 'D': - tree_entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': None}) - continue - encoded = base64.b64encode(Path(path).read_bytes()).decode('ascii') - blob = request('POST', '/git/blobs', {'content': encoded, 'encoding': 'base64'}) - tree_entries.append({'path': path, 'mode': '100644', 'type': 'blob', 'sha': blob['sha']}) - tree = request('POST', '/git/trees', {'base_tree': parent['tree']['sha'], 'tree': tree_entries}) - commit = request( - 'POST', - '/git/commits', - { - 'message': 'test: complete exact artifact handoff coverage', - 'tree': tree['sha'], - 'parents': [parent_sha], - }, - ) - print(f"PR797_REPAIR_PARENT_SHA={parent_sha}") - print(f"PR797_REPAIR_COMMIT_SHA={commit['sha']}") - PY - - - name: Publish repair pointer - env: - GH_TOKEN: ${{ github.token }} - EXPECTED_HEAD: ${{ github.event.pull_request.head.sha }} - shell: bash --noprofile --norc -e -o pipefail {0} - run: | - commit_sha="$(sed -n 's/^PR797_REPAIR_COMMIT_SHA=//p' "${RUNNER_TEMP}/pr797-trigger-receipt.txt")" - test "${#commit_sha}" -eq 40 - body="PR797_REPAIR_PARENT_SHA=${EXPECTED_HEAD}%0APR797_REPAIR_COMMIT_SHA=${commit_sha}" - gh api --method POST repos/ContextualWisdomLab/.github/issues/797/comments -f "body=${body}" - - - name: Upload repair receipt - uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v6.0.0 - with: - name: pr797-final-repair - path: ${{ runner.temp }}/pr797-trigger-receipt.txt - if-no-files-found: error - retention-days: 5 diff --git a/tests/test_verify_exact_artifact_sbom_handoff.py b/tests/test_verify_exact_artifact_sbom_handoff.py index 31c44ac14..2c15608da 100644 --- a/tests/test_verify_exact_artifact_sbom_handoff.py +++ b/tests/test_verify_exact_artifact_sbom_handoff.py @@ -98,7 +98,7 @@ def _rewrite_checksums( def _valid_handoff(tmp_path: Path) -> argparse.Namespace: """Create one complete exact six-file handoff and its CLI arguments.""" root = tmp_path / "evidence" - root.mkdir() + root.mkdir(parents=True) wheel = root / "example-1.0.0-py3-none-any.whl" sdist = root / "example-1.0.0.tar.gz" wheel.write_bytes(b"wheel-bytes\x00") @@ -429,3 +429,33 @@ def test_main_converts_validation_errors_to_system_exit(tmp_path: Path) -> None: argv.extend(("--" + name.replace("_", "-"), str(value))) with pytest.raises(SystemExit, match="sealed evidence verification failed"): verifier.main(argv) + +def test_checksum_control_file_bounds_and_entrypoint_are_covered( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Cover bounded checksum decoding and the real module entrypoint.""" + checksum = tmp_path / "checksums.sha256" + checksum.write_text(("0" * 64) + " payload.bin\n", encoding="utf-8") + monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 4) + with pytest.raises(verifier.EvidenceError, match="size limit"): + verifier._parse_checksums(checksum) + + monkeypatch.setattr(verifier, "_MAX_CONTROL_BYTES", 1024) + checksum.write_bytes(b"\xff") + with pytest.raises(verifier.EvidenceError, match="strict UTF-8"): + verifier._parse_checksums(checksum) + + import runpy + import sys + + arguments = _valid_handoff(tmp_path / "entrypoint") + argv: list[str] = [] + for name, value in vars(arguments).items(): + argv.extend(("--" + name.replace("_", "-"), str(value))) + monkeypatch.setattr(sys, "argv", [str(verifier.__file__), *argv]) + with pytest.raises(SystemExit) as exit_info: + runpy.run_path(str(verifier.__file__), run_name="__main__") + assert exit_info.value.code == 0 + assert "sealed evidence verification passed" in capsys.readouterr().out From 5295b562859b3e6d3a6d59446a45f2880882c7ca Mon Sep 17 00:00:00 2001 From: Seongho Bae Date: Fri, 7 Aug 2026 09:38:37 +0900 Subject: [PATCH 26/26] docs(release): record exact artifact SBOM attestation --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index e601de81b..fb6e510d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ Semantic Versioning where the repository publishes a release. ### Added +- Added an organization-owned reusable exact-artifact SBOM attestation boundary that validates inert six-file wheel/sdist evidence, binds CycloneDX 1.7 predicates to exact SHA-256 subjects, signs through least-privilege GitHub artifact attestations, and exports online and offline verification bundles. - Added exact-base `uv.lock` materialization that reconstructs standalone nested projects with a checksum-pinned official `uv` exporter, isolated frozen/offline execution, strict exact-pin and SHA-256 output validation, and complete Python 3.10/3.14 quality evidence. ### Fixed