From 0df7dfb42ab58c03ed79fb3df2d4bffd2c586c51 Mon Sep 17 00:00:00 2001 From: Chris Green Date: Mon, 16 Nov 2026 17:28:49 -0600 Subject: [PATCH 1/3] ci(codeql): preserve event-specific cache audit rationale --- .github/workflows/clang-tidy-check.yaml | 4 ++++ .github/workflows/cmake-build.yaml | 5 +++++ 2 files changed, 9 insertions(+) diff --git a/.github/workflows/clang-tidy-check.yaml b/.github/workflows/clang-tidy-check.yaml index 29bfe2d2c..2c47e1737 100644 --- a/.github/workflows/clang-tidy-check.yaml +++ b/.github/workflows/clang-tidy-check.yaml @@ -68,6 +68,10 @@ jobs: steps: - name: Checkout code + # CodeQL actions/cache-poisoning/poisonable-step: false positive for the + # reported workflow_dispatch origin. The pinned organization setup action + # resolves manual refs within this repository; pull-request runs do not + # share that cache-write scope. This is not a CodeQL suppression. uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: ref: diff --git a/.github/workflows/cmake-build.yaml b/.github/workflows/cmake-build.yaml index badfcda9e..2da0da3c9 100644 --- a/.github/workflows/cmake-build.yaml +++ b/.github/workflows/cmake-build.yaml @@ -182,6 +182,11 @@ jobs: steps: - name: Check out code + # CodeQL actions/cache-poisoning/poisonable-step: false positive for the + # reported schedule/workflow_dispatch origins. The pinned organization + # setup action resolves schedules to GITHUB_SHA and manual refs within + # this repository; pull-request runs do not share that cache-write scope. + # This records the audit rationale, not an inline CodeQL suppression. uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ needs.setup.outputs.checkout_path }} From 6100a03a6c8f77a4e1a8598e3e1e37ece2183224 Mon Sep 17 00:00:00 2001 From: Chris Green Date: Wed, 18 Nov 2026 09:43:36 -0600 Subject: [PATCH 2/3] ci: pin workflow execution to immutable sources --- .github/actions/report-fix-patch/action.yaml | 78 +++ .../actions/resolve-fix-snapshot/action.yaml | 109 ++++ .../resolve-source-snapshot/action.yaml | 162 ++++++ .github/codecov/requirements.txt | 2 + .github/dependabot.yml | 4 +- .github/workflows/clang-format-fix.yaml | 115 ++++- .github/workflows/clang-tidy-check.yaml | 182 ++++++- .github/workflows/clang-tidy-fix.yaml | 297 ++++++++--- .github/workflows/clang-tidy-report.yaml | 153 ++++-- .github/workflows/cmake-build.yaml | 140 ++++- .github/workflows/cmake-format-fix.yaml | 121 ++++- .github/workflows/codeql-analysis.yaml | 488 +++++++++++++++--- .github/workflows/codeql-comment.yaml | 156 +++--- .github/workflows/coverage.yaml | 367 +++++++++++-- .github/workflows/format-all.yaml | 111 +++- .github/workflows/header-guards-fix.yaml | 133 ++++- .github/workflows/jsonnet-format-fix.yaml | 123 ++++- .github/workflows/markdown-fix.yaml | 130 +++-- .github/workflows/python-check.yaml | 422 +++++++++++++-- .github/workflows/python-fix.yaml | 111 +++- .github/workflows/yaml-fix.yaml | 122 ++++- AGENTS.md | 30 +- docs/dev/WORKFLOW_CALLS.md | 85 ++- pyproject.toml | 7 +- scripts/check_codeql_alerts.py | 41 +- scripts/create_fix_patch.py | 145 ++++++ scripts/fix_header_guards.py | 23 +- scripts/run_markdownlint_sandbox.py | 148 ++++++ scripts/test/test_check_codeql_alerts.py | 34 +- scripts/test/test_create_fix_patch.py | 149 ++++++ scripts/test/test_fix_header_guards.py | 23 + scripts/test/test_run_markdownlint_sandbox.py | 103 ++++ .../test/test_validate_clang_tidy_fixes.py | 147 ++++++ scripts/test/test_workflow_cleanup.py | 15 +- scripts/test/test_workflow_tooling.py | 7 +- scripts/validate_clang_tidy_fixes.py | 172 ++++++ 36 files changed, 4029 insertions(+), 626 deletions(-) create mode 100644 .github/actions/report-fix-patch/action.yaml create mode 100644 .github/actions/resolve-fix-snapshot/action.yaml create mode 100644 .github/actions/resolve-source-snapshot/action.yaml create mode 100644 .github/codecov/requirements.txt create mode 100644 scripts/create_fix_patch.py create mode 100644 scripts/run_markdownlint_sandbox.py create mode 100644 scripts/test/test_create_fix_patch.py create mode 100644 scripts/test/test_run_markdownlint_sandbox.py create mode 100644 scripts/test/test_validate_clang_tidy_fixes.py create mode 100644 scripts/validate_clang_tidy_fixes.py diff --git a/.github/actions/report-fix-patch/action.yaml b/.github/actions/report-fix-patch/action.yaml new file mode 100644 index 000000000..45e9e8b1e --- /dev/null +++ b/.github/actions/report-fix-patch/action.yaml @@ -0,0 +1,78 @@ +name: Report formatter patch artifact +description: Report the immutable formatter snapshot and patch-only result. + +inputs: + tool: + description: Fixed formatter identifier. + required: true + source-sha: + description: Authorized source commit SHA. + required: true + changes: + description: Whether a patch artifact was created. + required: true + patch-name: + description: Expected fixed patch file name. + required: true + run-id: + description: Workflow run containing the artifact. + required: true + +runs: + using: composite + steps: + - name: Post patch-only result + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + TOOL: ${{ inputs.tool }} + SOURCE_SHA: ${{ inputs.source-sha }} + CHANGES: ${{ inputs.changes }} + PATCH_NAME: ${{ inputs.patch-name }} + RUN_ID: ${{ inputs.run-id }} + with: + script: | + const { owner, repo } = context.repo; + const pullNumber = context.payload.issue?.number; + if (!context.payload.issue?.pull_request || !Number.isSafeInteger(pullNumber)) { + throw new Error('Patch reports are only valid for pull requests.'); + } + if (!/^[0-9a-f]{40}$/i.test(process.env.SOURCE_SHA || '') || + !/^[a-z0-9-]{1,40}$/.test(process.env.TOOL || '') || + !/^[0-9]+$/.test(process.env.RUN_ID || '') || + !['true', 'false'].includes(process.env.CHANGES)) { + throw new Error('Invalid patch report metadata.'); + } + if (process.env.CHANGES === 'true' && + process.env.PATCH_NAME !== `${process.env.TOOL}.patch`) { + throw new Error('Patch report file name does not match the formatter.'); + } + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: pullNumber + }); + const isCurrent = pull.state === 'open' && pull.head.sha === process.env.SOURCE_SHA; + const artifactUrl = `${context.serverUrl}/${owner}/${repo}/actions/runs/${process.env.RUN_ID}#artifacts`; + const result = process.env.CHANGES === 'true' + ? `A patch-only artifact was created: \`${process.env.PATCH_NAME}\`.` + : 'No formatting changes were produced.'; + const freshness = isCurrent + ? 'The PR still points to the approved snapshot.' + : 'The PR head moved after approval; do not apply this patch. Rerun against the current full SHA.'; + const artifact = process.env.CHANGES === 'true' + ? `Download it from [this run's artifacts](${artifactUrl}).` + : ''; + await github.rest.issues.createComment({ + owner, + repo, + issue_number: pullNumber, + body: [ + `**${process.env.TOOL} formatter result**`, + '', + 'No repository branch was modified.', + `Approved source snapshot: \`${process.env.SOURCE_SHA}\`.`, + result, + freshness, + artifact + ].filter(Boolean).join('\n\n') + }); diff --git a/.github/actions/resolve-fix-snapshot/action.yaml b/.github/actions/resolve-fix-snapshot/action.yaml new file mode 100644 index 000000000..ff6f239e8 --- /dev/null +++ b/.github/actions/resolve-fix-snapshot/action.yaml @@ -0,0 +1,109 @@ +name: Resolve authorized formatter snapshot +description: Resolve and pin the PR source SHA before a patch-only formatter run. + +inputs: + command: + description: Bot command required for direct issue-comment requests. + required: true + ref: + description: Target branch resolved by the workflow setup action. + required: true + repo: + description: Target repository resolved by the workflow setup action. + required: true + source-sha: + description: Optional exact source SHA from a reusable workflow or manual run. + required: false + +outputs: + source_sha: + description: Authorized immutable source SHA. + value: ${{ steps.authorize.outputs.source_sha }} + source_repo: + description: Repository containing the authorized source SHA. + value: ${{ steps.authorize.outputs.source_repo }} + +runs: + using: composite + steps: + - name: Validate source authorization + id: authorize + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + COMMAND: ${{ inputs.command }} + TARGET_REF: ${{ inputs.ref }} + TARGET_REPO: ${{ inputs.repo }} + REQUESTED_SHA: ${{ inputs.source-sha }} + COMMENT_BODY: ${{ github.event.comment.body }} + WORKFLOW_REF: ${{ github.workflow_ref }} + with: + script: | + const { owner, repo } = context.repo; + const currentRepo = `${owner}/${repo}`; + const shaPattern = /^[0-9a-f]{40}$/i; + const requestedRepo = process.env.TARGET_REPO; + const requestedRef = process.env.TARGET_REF; + const command = process.env.COMMAND; + let sourceSha = process.env.REQUESTED_SHA; + let sourceRepo = requestedRepo; + if (!requestedRef || requestedRef.startsWith('refs/') || requestedRef.startsWith('-') || + !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(requestedRepo)) { + throw new Error('The formatter target repository or branch is invalid.'); + } + + if (context.eventName === 'issue_comment') { + if (!context.payload.issue?.pull_request) { + throw new Error('Formatter commands are available only on pull requests.'); + } + if (!sourceSha) { + const expected = new RegExp(`^@${repo}bot ${command}(?: --sha=([0-9a-f]{40}))?$`); + const match = process.env.COMMENT_BODY.match(expected); + if (!match) { + throw new Error(`Use @${repo}bot ${command} with no arguments, or append an optional full SHA.`); + } + sourceSha = match[1]; + } + if (sourceSha && !shaPattern.test(sourceSha)) { + throw new Error('Optional formatter SHA must contain exactly 40 hexadecimal characters.'); + } + } + + if (context.payload.pull_request || context.payload.issue?.pull_request) { + const pullNumber = context.payload.pull_request?.number || context.payload.issue.number; + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: pullNumber + }); + if (pull.state !== 'open' || pull.head.ref !== requestedRef || + pull.head.repo?.full_name !== requestedRepo || + (sourceSha && pull.head.sha.toLowerCase() !== sourceSha.toLowerCase())) { + throw new Error('The PR head moved or does not match the formatter target.'); + } + sourceSha = pull.head.sha; + sourceRepo = pull.head.repo.full_name; + } else { + if (requestedRepo !== currentRepo) { + throw new Error('Non-PR formatter runs must target this repository.'); + } + if (context.eventName === 'workflow_dispatch') { + const { data: repository } = await github.rest.repos.get({ owner, repo }); + if (!process.env.WORKFLOW_REF.endsWith(`@refs/heads/${repository.default_branch}`)) { + throw new Error('Manual formatter runs must use the default-branch workflow.'); + } + } + const { data: branch } = await github.rest.repos.getBranch({ + owner, + repo, + branch: requestedRef + }); + if (sourceSha && !shaPattern.test(sourceSha)) { + throw new Error('Optional formatter SHA must contain exactly 40 hexadecimal characters.'); + } + if (sourceSha && branch.commit.sha.toLowerCase() !== sourceSha.toLowerCase()) { + throw new Error('The target branch head does not match the approved source SHA.'); + } + sourceSha = branch.commit.sha; + } + core.setOutput('source_sha', sourceSha); + core.setOutput('source_repo', sourceRepo); diff --git a/.github/actions/resolve-source-snapshot/action.yaml b/.github/actions/resolve-source-snapshot/action.yaml new file mode 100644 index 000000000..5cf69f5e0 --- /dev/null +++ b/.github/actions/resolve-source-snapshot/action.yaml @@ -0,0 +1,162 @@ +name: Resolve immutable source snapshot +description: Bind workflow execution to the approved repository commit. + +inputs: + command: + description: Bot command for issue-comment requests; leave empty otherwise. + required: false + ref: + description: Target ref from workflow setup. + required: true + repo: + description: Target repository from workflow setup. + required: true + source-sha: + description: Explicit source SHA for manual or reusable workflow requests. + required: false + allow-arguments: + description: Allow a constrained argument list and optional SHA in issue comments. + required: false + default: "false" + +outputs: + source_sha: + description: Validated immutable source SHA. + value: ${{ steps.resolve.outputs.source_sha }} + source_repo: + description: Repository containing the validated source SHA. + value: ${{ steps.resolve.outputs.source_repo }} + source_ref: + description: Source branch or event ref associated with the snapshot. + value: ${{ steps.resolve.outputs.source_ref }} + command_args: + description: Constrained arguments preceding an optional SHA in a bot command. + value: ${{ steps.resolve.outputs.command_args }} + +runs: + using: composite + steps: + - name: Authorize the immutable source + id: resolve + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + COMMAND: ${{ inputs.command }} + TARGET_REF: ${{ inputs.ref }} + TARGET_REPO: ${{ inputs.repo }} + REQUESTED_SHA: ${{ inputs.source-sha }} + ALLOW_ARGUMENTS: ${{ inputs.allow-arguments }} + COMMENT_BODY: ${{ github.event.comment.body }} + WORKFLOW_REF: ${{ github.workflow_ref }} + with: + script: | + const { owner, repo } = context.repo; + const currentRepo = `${owner}/${repo}`; + const shaPattern = /^[0-9a-f]{40}$/i; + const targetRepo = process.env.TARGET_REPO; + const targetRef = process.env.TARGET_REF; + let sourceSha = process.env.REQUESTED_SHA; + let sourceRepo = targetRepo; + let sourceRef = targetRef; + if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(targetRepo || '') || + !targetRef || targetRef.startsWith('-')) { + throw new Error('Workflow setup returned an invalid target repository or ref.'); + } + + if (context.eventName === 'pull_request' || + (context.eventName === 'workflow_call' && context.payload.pull_request)) { + const pull = context.payload.pull_request; + if (!pull.head.repo) throw new Error('The PR source repository is unavailable.'); + if (sourceSha && sourceSha.toLowerCase() !== pull.head.sha.toLowerCase()) { + throw new Error('The requested SHA does not match the PR head.'); + } + const { data: currentPull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: pull.number + }); + if (currentPull.state !== 'open' || currentPull.head.sha !== pull.head.sha || + currentPull.head.repo?.full_name !== pull.head.repo.full_name || + currentPull.head.ref !== pull.head.ref) { + throw new Error('The PR head moved while resolving the source snapshot.'); + } + sourceSha = currentPull.head.sha; + sourceRepo = currentPull.head.repo.full_name; + sourceRef = currentPull.head.ref; + } else if (context.eventName === 'issue_comment') { + if (!context.payload.issue?.pull_request) { + throw new Error('This workflow command is supported only on pull requests.'); + } + const command = process.env.COMMAND; + const prefix = `^@${repo}bot ${command}`; + const expected = process.env.ALLOW_ARGUMENTS === 'true' + ? new RegExp(`${prefix}(?:[ \\t]+([A-Za-z0-9+/, -]*?))?(?:[ \\t]+--sha=([0-9a-f]{40}))?$`) + : new RegExp(`${prefix}(?:[ \\t]+--sha=([0-9a-f]{40}))?$`); + const match = process.env.COMMENT_BODY.match(expected); + if (!match) throw new Error(`Invalid @${repo}bot ${command} command.`); + const approvedSha = process.env.ALLOW_ARGUMENTS === 'true' ? match[2] : match[1]; + if (approvedSha && sourceSha && sourceSha.toLowerCase() !== approvedSha.toLowerCase()) { + throw new Error('The requested SHA does not match the optional command SHA.'); + } + if (process.env.ALLOW_ARGUMENTS === 'true') { + core.setOutput('command_args', (match[1] || '').trim()); + } + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: context.payload.issue.number + }); + if (pull.state !== 'open' || (approvedSha && pull.head.sha.toLowerCase() !== approvedSha.toLowerCase()) || + pull.head.repo?.full_name !== targetRepo || + pull.head.ref !== targetRef.replace(/^refs\/heads\//, '')) { + throw new Error('The PR head does not match the command target or optional SHA.'); + } + sourceSha = pull.head.sha; + sourceRepo = pull.head.repo.full_name; + sourceRef = pull.head.ref; + } else if (context.eventName === 'workflow_dispatch') { + const { data: repository } = await github.rest.repos.get({ owner, repo }); + const branchName = context.ref.replace(/^refs\/heads\//, ''); + const targetBranch = targetRef.replace(/^refs\/heads\//, ''); + if (!context.ref.startsWith('refs/heads/') || targetRepo !== currentRepo || + targetBranch !== branchName || process.env.WORKFLOW_REF.split('@').pop() !== context.ref || + !shaPattern.test(sourceSha || '') || sourceSha.toLowerCase() !== context.sha.toLowerCase()) { + throw new Error('Manual runs require an exact SHA for the selected workflow branch.'); + } + const { data: branch } = await github.rest.repos.getBranch({ owner, repo, branch: branchName }); + if (branch.commit.sha.toLowerCase() !== sourceSha.toLowerCase()) { + throw new Error('The selected branch head does not match the supplied source SHA.'); + } + if (branchName === repository.default_branch && branch.commit.sha !== context.sha) { + throw new Error('The default branch moved after this workflow was selected.'); + } + sourceSha = branch.commit.sha; + sourceRepo = currentRepo; + sourceRef = context.ref; + } else if (context.eventName === 'push' || context.eventName === 'schedule') { + if (targetRepo !== currentRepo || (sourceSha && sourceSha !== context.sha)) { + throw new Error('Push and schedule runs must use this repository event SHA.'); + } + sourceSha = context.sha; + sourceRepo = currentRepo; + sourceRef = context.ref; + } else if (context.eventName === 'workflow_call') { + if (targetRepo !== currentRepo || !shaPattern.test(sourceSha || '')) { + throw new Error('Reusable non-PR runs require this repository and a full source SHA.'); + } + const branchName = targetRef.replace(/^refs\/heads\//, ''); + const { data: branch } = await github.rest.repos.getBranch({ owner, repo, branch: branchName }); + if (branch.commit.sha.toLowerCase() !== sourceSha.toLowerCase()) { + throw new Error('Reusable workflow target branch does not match its source SHA.'); + } + sourceSha = branch.commit.sha; + sourceRepo = currentRepo; + sourceRef = branchName; + } else { + throw new Error(`Unsupported source event: ${context.eventName}`); + } + + if (!shaPattern.test(sourceSha || '')) throw new Error('Resolved source SHA is invalid.'); + core.setOutput('source_sha', sourceSha); + core.setOutput('source_repo', sourceRepo); + core.setOutput('source_ref', sourceRef); + if (process.env.ALLOW_ARGUMENTS !== 'true') core.setOutput('command_args', ''); diff --git a/.github/codecov/requirements.txt b/.github/codecov/requirements.txt new file mode 100644 index 000000000..14a08c151 --- /dev/null +++ b/.github/codecov/requirements.txt @@ -0,0 +1,2 @@ +# Dependabot updates this pin; workflows pass its version to codecov-action. +codecov-cli==11.3.2 diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 628906d6d..e7df5b842 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -24,6 +24,8 @@ updates: schedule: interval: "weekly" - package-ecosystem: "pip" - directory: "/ci" + directories: + - "/ci" + - "/.github/codecov" schedule: interval: "weekly" diff --git a/.github/workflows/clang-format-fix.yaml b/.github/workflows/clang-format-fix.yaml index 7cd320c42..9ccbbfd0d 100644 --- a/.github/workflows/clang-format-fix.yaml +++ b/.github/workflows/clang-format-fix.yaml @@ -13,6 +13,10 @@ run-name: "${{ github.actor }} fixing C++ code format" repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character source SHA to format" + required: true + type: string workflow_call: inputs: checkout-path: @@ -32,6 +36,10 @@ run-name: "${{ github.actor }} fixing C++ code format" required: false type: boolean default: false + source-sha: + description: "Exact 40-character source SHA to format" + required: false + type: string outputs: changes: description: "Whether any fixes were applied" @@ -50,9 +58,8 @@ run-name: "${{ github.actor }} fixing C++ code format" value: ${{ jobs.apply_formatting.outputs.patch_name }} permissions: - pull-requests: write - contents: write - issues: write + pull-requests: read + contents: read jobs: setup: @@ -69,6 +76,8 @@ jobs: ref: ${{ steps.setup.outputs.ref }} repo: ${{ steps.setup.outputs.repo }} checkout_path: ${{ steps.setup.outputs.checkout_path }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup @@ -79,24 +88,44 @@ jobs: repo: ${{ inputs.repo }} checkout-path: ${{ inputs.checkout-path }} + - name: Check out trusted workflow tooling + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: | + .github/actions/resolve-fix-snapshot + scripts/create_fix_patch.py + persist-credentials: false + + - name: Resolve approved source snapshot + id: source_snapshot + uses: ./workflow-tools/.github/actions/resolve-fix-snapshot + with: + command: clang-fix + ref: ${{ steps.setup.outputs.ref }} + repo: ${{ steps.setup.outputs.repo }} + source-sha: ${{ inputs.source-sha }} + apply_formatting: runs-on: ubuntu-latest name: Apply formatting needs: setup if: ${{ needs.setup.result == 'success' }} outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} + changes: ${{ steps.prepare_patch.outputs.changes }} + pushed: ${{ steps.prepare_patch.outputs.pushed }} + commit_sha: ${{ steps.prepare_patch.outputs.commit_sha }} + commit_sha_short: ${{ steps.prepare_patch.outputs.commit_sha_short }} + patch_name: ${{ steps.prepare_patch.outputs.patch_name }} steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - name: Check out immutable source + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} + ref: ${{ needs.setup.outputs.source_sha }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false - uses: DoozyX/clang-format-lint-action@bcb4eb2cb0d707ee4f3e5cc3b456eb075f12cf73 # v0.20 @@ -106,19 +135,55 @@ jobs: inplace: "True" extensions: cpp,hpp,cpp.in,hpp.in - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 + - name: Prepare patch artifact + id: prepare_patch + env: + SOURCE_PATH: ${{ needs.setup.outputs.checkout_path }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + TARGET_REPO: ${{ needs.setup.outputs.source_repo }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + TOOL: clang-format + run: python3 "$GITHUB_WORKSPACE/workflow-tools/scripts/create_fix_patch.py" + + - name: Upload patch artifact + if: steps.prepare_patch.outputs.changes == 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - tool: clang-format - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} + name: ${{ steps.prepare_patch.outputs.artifact_name }} + path: ${{ steps.prepare_patch.outputs.artifact_path }} + retention-days: 7 + if-no-files-found: error + + report: + name: Report patch artifact + needs: [setup, apply_formatting] + if: >- + github.event_name == 'issue_comment' && !inputs.skip-comment && needs.setup.result == 'success' && + needs.apply_formatting.result == 'success' + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + issues: write + pull-requests: read + steps: + - name: Check out trusted report action + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/report-fix-patch + persist-credentials: false - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 + - name: Report immutable patch result + uses: ./workflow-tools/.github/actions/report-fix-patch with: - status: ${{ job.status }} + tool: clang-format + source-sha: ${{ needs.setup.outputs.source_sha }} + changes: ${{ needs.apply_formatting.outputs.changes }} + patch-name: ${{ needs.apply_formatting.outputs.patch_name }} + run-id: ${{ github.run_id }} diff --git a/.github/workflows/clang-tidy-check.yaml b/.github/workflows/clang-tidy-check.yaml index 2c47e1737..a9ae74310 100644 --- a/.github/workflows/clang-tidy-check.yaml +++ b/.github/workflows/clang-tidy-check.yaml @@ -20,9 +20,13 @@ permissions: workflow_dispatch: inputs: ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." + description: "Branch matching this workflow run; source-sha must equal its current head." required: false type: string + source-sha: + description: "Exact 40-character SHA at the selected branch head" + required: true + type: string jobs: setup: @@ -43,15 +47,101 @@ jobs: pr_number: ${{ steps.setup.outputs.pr_number }} checkout_path: ${{ steps.setup.outputs.checkout_path }} build_path: ${{ steps.setup.outputs.build_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} + has_changes: ${{ steps.source_relevance.outputs.has_changes }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 + + - name: Check out trusted source resolver + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/resolve-source-snapshot + persist-credentials: false + + - name: Resolve immutable source snapshot + id: source_snapshot + uses: ./workflow-tools/.github/actions/resolve-source-snapshot + with: + command: tidy-check + ref: ${{ steps.setup.outputs.ref }} + repo: ${{ steps.setup.outputs.repo }} + source-sha: ${{ inputs.source-sha }} + + - name: Detect relevant changes in the immutable snapshot + id: source_relevance + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + SOURCE_SHA: ${{ steps.source_snapshot.outputs.source_sha }} + SOURCE_REPO: ${{ steps.source_snapshot.outputs.source_repo }} + PR_NUMBER: ${{ steps.setup.outputs.pr_number }} with: - file-type: | - cpp - cmake + script: | + const matches = filename => { + if (filename.startsWith('scripts/')) return false; + const basename = filename.split('/').pop(); + return /\.(cpp|hpp)(\.in)?$/.test(basename) || + /^(CMakeLists\.txt|.*\.cmake)(\.in)?$/.test(basename); + }; + let relevant = true; + if (context.eventName === 'pull_request' || context.eventName === 'issue_comment') { + try { + const pullNumber = Number(process.env.PR_NUMBER || context.payload.pull_request?.number || + context.payload.issue?.number); + const { data: before } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber + }); + if (before.head.sha === process.env.SOURCE_SHA && + before.head.repo?.full_name === process.env.SOURCE_REPO) { + const changedPaths = []; + for (let page = 1; ; page++) { + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber, + per_page: 100, + page + }); + changedPaths.push(...files.map(file => file.filename)); + if (files.length < 100 || page === 30) break; + } + const { data: after } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber + }); + relevant = after.head.sha !== process.env.SOURCE_SHA || + after.head.repo?.full_name !== process.env.SOURCE_REPO || + changedPaths.length >= 3000 || changedPaths.some(matches); + } + } catch (error) { + core.warning(`Could not verify PR relevance; running clang-tidy conservatively: ${error.message}`); + relevant = true; + } + } else if (context.eventName === 'push' && context.payload.before && + !/^0+$/.test(context.payload.before)) { + try { + const { data: comparison } = await github.rest.repos.compareCommits({ + owner: context.repo.owner, + repo: context.repo.repo, + base: context.payload.before, + head: process.env.SOURCE_SHA + }); + relevant = comparison.files?.length >= 300 || + (comparison.files || []).some(file => matches(file.filename)); + } catch (error) { + core.warning(`Could not verify push relevance; running clang-tidy conservatively: ${error.message}`); + relevant = true; + } + } + core.setOutput('has_changes', String(relevant)); clang-tidy-check: needs: setup @@ -64,22 +154,18 @@ jobs: needs.setup.outputs.has_changes == 'true') runs-on: ubuntu-24.04 container: - image: ghcr.io/framework-r-d/phlex-ci:latest + image: >- + ghcr.io/framework-r-d/phlex-ci:latest@sha256:d62317baa9f8b886da6db6250bdcc1d97d15bf85fb18b13d9842abafbfd82ce0 steps: - name: Checkout code - # CodeQL actions/cache-poisoning/poisonable-step: false positive for the - # reported workflow_dispatch origin. The pinned organization setup action - # resolves manual refs within this repository; pull-request runs do not - # share that cache-write scope. This is not a CodeQL suppression. + # The source resolver validates event SHAs, selected manual branch heads, + # and explicit issue-comment approvals before this immutable checkout. uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} + ref: ${{ needs.setup.outputs.source_sha }} path: ${{ needs.setup.outputs.checkout_path }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false # The diff must start at the actual merge base, which may predate the # current base SHA for an unrebased pull request. @@ -198,7 +284,9 @@ jobs: DIFF_EXIT=$? set -e - if [ "$TIDY_EXIT" -ne 0 ] || grep -q "No checks enabled\.\|Traceback\|RuntimeError\|ModuleNotFoundError\|ImportError" "$BUILD_DIR/clang-tidy.log"; then + if [ "$TIDY_EXIT" -ne 0 ] || grep -q \ + "No checks enabled\.\|Traceback\|RuntimeError\|ModuleNotFoundError\|ImportError" \ + "$BUILD_DIR/clang-tidy.log"; then echo "::error::run-clang-tidy failed (see log below)" echo "::group::clang-tidy.log (error)" cat "$BUILD_DIR/clang-tidy.log" @@ -231,19 +319,65 @@ jobs: mkdir -p "$BUILD_DIR" printf '%s\n' "$PR_NUMBER" > "$BUILD_DIR/pr_number.txt" + - name: Prepare clang-tidy report artifact + id: report_artifact + if: always() && github.event_name == 'pull_request' + env: + BUILD_PATH: ${{ needs.setup.outputs.build_path }} + SOURCE_SHA: ${{ github.event.pull_request.head.sha }} + SOURCE_REPO: ${{ github.event.pull_request.head.repo.full_name }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + PR_NUMBER: ${{ github.event.pull_request.number }} + run: | + python3 - <<'PY' >> "$GITHUB_OUTPUT" + import json + import os + import shutil + import tempfile + from pathlib import Path + + source = Path(os.environ["GITHUB_WORKSPACE"]) / os.environ["BUILD_PATH"] + if source.is_symlink() or not source.is_dir(): + raise SystemExit("The clang-tidy build directory is invalid") + artifact = Path(tempfile.mkdtemp(prefix="clang-tidy-report.", dir=os.environ["RUNNER_TEMP"])) + limits = { + "clang-tidy-analysis-complete.txt": 1024, + "clang-tidy-new-issues.txt": 65536, + "clang-tidy.log": 16777216, + } + for name, max_size in limits.items(): + candidate = source / name + if candidate.is_symlink(): + raise SystemExit(f"Refusing symlink report data: {name}") + if candidate.exists(): + if not candidate.is_file() or candidate.stat().st_size > max_size: + raise SystemExit(f"Invalid or oversized report data: {name}") + shutil.copyfile(candidate, artifact / name) + (artifact / "pr_number.txt").write_text(os.environ["PR_NUMBER"] + "\n", encoding="utf-8") + metadata = { + "source_sha": os.environ["SOURCE_SHA"], + "source_repo": os.environ["SOURCE_REPO"], + "workflow_ref": os.environ["WORKFLOW_REF"], + "run_id": os.environ["RUN_ID"], + "run_attempt": os.environ["RUN_ATTEMPT"], + } + (artifact / "provenance.json").write_text( + json.dumps(metadata, sort_keys=True) + "\n", encoding="utf-8" + ) + print(f"path={artifact}") + PY + - name: Upload artifacts - if: always() + if: always() && steps.report_artifact.outcome == 'success' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: clang-tidy-check + name: clang-tidy-check-${{ github.run_attempt }} path: | - ${{ needs.setup.outputs.build_path }}/clang-tidy-fixes.yaml - ${{ needs.setup.outputs.build_path }}/clang-tidy.log - ${{ needs.setup.outputs.build_path }}/clang-tidy-new-issues.txt - ${{ needs.setup.outputs.build_path }}/clang-tidy-analysis-complete.txt - ${{ needs.setup.outputs.build_path }}/pr_number.txt + ${{ steps.report_artifact.outputs.path }} retention-days: 7 - if-no-files-found: ignore + if-no-files-found: error report: needs: [setup, clang-tidy-check] diff --git a/.github/workflows/clang-tidy-fix.yaml b/.github/workflows/clang-tidy-fix.yaml index 73ef57b02..736fa60af 100644 --- a/.github/workflows/clang-tidy-fix.yaml +++ b/.github/workflows/clang-tidy-fix.yaml @@ -13,20 +13,28 @@ name: Clang-Tidy Fix repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character commit SHA to analyze and fix. Must still be the selected branch head." + required: true + type: string tidy-checks: description: "A comma-separated list of clang-tidy checks to apply." required: false type: string permissions: - pull-requests: write - contents: write - issues: write + actions: read + contents: read + issues: read + pull-requests: read jobs: setup: runs-on: ubuntu-latest name: Parse command + permissions: + contents: read + pull-requests: read if: > github.event_name == 'workflow_dispatch' || ( github.event_name == 'issue_comment' && @@ -41,6 +49,7 @@ jobs: repo: ${{ steps.setup.outputs.repo }} checkout_path: ${{ steps.setup.outputs.checkout_path }} build_path: ${{ steps.setup.outputs.build_path }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} pr_number: ${{ steps.setup.outputs.pr_number }} tidy_checks: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tidy-checks || @@ -54,8 +63,10 @@ jobs: run: | REPO_NAME="${GITHUB_REPOSITORY##*/}" bot_name="${REPO_NAME}bot" - checks_line=$(echo "$COMMENT_BODY" | + checks_line=$(printf '%s\n' "$COMMENT_BODY" | sed -nE "s/^@${bot_name}[[:space:]]+tidy-fix[[:space:]]+(.*)/\1/p" | tr -d '\r') + checks_line=$(printf '%s\n' "$checks_line" | + sed -E 's/[[:space:]]+--sha=[[:xdigit:]]{40}$//') if [ -n "$checks_line" ]; then tidy_checks="$(echo "$checks_line" | tr ',' ' ' | xargs -n1 | paste -sd, -)" echo "tidy_checks=$tidy_checks" >> "$GITHUB_OUTPUT" @@ -65,78 +76,100 @@ jobs: uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 with: mode: fix + ref: ${{ inputs.ref }} + - name: Validate immutable source snapshot + id: source_snapshot + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + REQUESTED_SHA: ${{ inputs.source-sha }} + TARGET_REF: ${{ steps.setup.outputs.ref }} + TARGET_REPO: ${{ steps.setup.outputs.repo }} + WORKFLOW_REF: ${{ github.workflow_ref }} + COMMENT_BODY: ${{ github.event.comment.body }} + with: + script: | + const { owner, repo } = context.repo; + const targetRef = process.env.TARGET_REF; + const targetRepo = process.env.TARGET_REPO; + const shaPattern = /^[0-9a-f]{40}$/i; + const { data: repository } = await github.rest.repos.get({ owner, repo }); + const trustedWorkflowRef = `@refs/heads/${repository.default_branch}`; + if (!process.env.WORKFLOW_REF.endsWith(trustedWorkflowRef)) { + throw new Error('Run this workflow from the repository default branch.'); + } - apply_tidy_fixes: + if (context.eventName === 'issue_comment') { + const prefix = `^@${repo}bot tidy-fix`; + const match = process.env.COMMENT_BODY.trim().match( + new RegExp(`${prefix}(?:[ \\t]+([A-Za-z0-9_.*+/, -]*?))?(?:[ \\t]+--sha=([0-9a-f]{40}))?$`) + ); + if (!match) throw new Error('Invalid tidy-fix command or check list.'); + const requestedChecks = (match[1] || '').trim(); + if (requestedChecks && !/^[A-Za-z0-9_.*+/, -]+$/.test(requestedChecks)) { + throw new Error('The tidy-fix check list contains unsupported characters.'); + } + const approvedSha = match[2]; + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: context.payload.issue.number + }); + if (pull.state !== 'open' || + (approvedSha && pull.head.sha.toLowerCase() !== approvedSha.toLowerCase())) { + throw new Error('The PR is closed or its head does not match the optional SHA.'); + } + if (pull.head.ref !== targetRef || pull.head.repo?.full_name !== targetRepo) { + throw new Error('The resolved target differs from the current PR head.'); + } + core.setOutput('source_sha', pull.head.sha); + return; + } + + const requestedSha = process.env.REQUESTED_SHA; + if (!shaPattern.test(requestedSha)) { + throw new Error('workflow_dispatch requires a full source-sha input.'); + } + if (targetRepo !== `${owner}/${repo}`) { + throw new Error('Manual runs may target only this repository.'); + } + const branch = targetRef.replace(/^refs\/heads\//, ''); + if (!branch || branch.startsWith('refs/')) { + throw new Error('Manual runs require a branch target.'); + } + const { data: branchData } = await github.rest.repos.getBranch({ owner, repo, branch }); + if (branchData.commit.sha.toLowerCase() !== requestedSha.toLowerCase()) { + throw new Error('The selected branch head does not match source-sha.'); + } + core.setOutput('source_sha', branchData.commit.sha); + + generate_tidy_fixes: runs-on: ubuntu-24.04 - name: Apply clang-tidy fixes + name: Generate clang-tidy fixes needs: setup if: ${{ needs.setup.result == 'success' }} + permissions: + contents: read container: - image: ghcr.io/framework-r-d/phlex-ci:latest + image: >- + ghcr.io/framework-r-d/phlex-ci:latest@sha256:d62317baa9f8b886da6db6250bdcc1d97d15bf85fb18b13d9842abafbfd82ce0 steps: - name: Checkout code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} + ref: ${{ needs.setup.outputs.source_sha }} repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} + token: ${{ github.token }} persist-credentials: false - - name: Try to download existing fixes from check workflow - id: download_fixes_check - if: needs.setup.outputs.tidy_checks == '' - uses: dawidd6/action-download-artifact@a92c7ae74cf1df8810783758581e485ac3aaa309 # v28 - with: - workflow: clang-tidy-check.yaml - name: clang-tidy-check - path: fixes - branch: ${{ needs.setup.outputs.ref }} - continue-on-error: true - - - name: Try to download existing fixes from previous fix workflow - id: download_fixes_fix - if: steps.download_fixes_check.outcome != 'success' && needs.setup.outputs.tidy_checks == '' - uses: dawidd6/action-download-artifact@a92c7ae74cf1df8810783758581e485ac3aaa309 # v28 - with: - workflow: clang-tidy-fix.yaml - name: clang-tidy-fix - path: fixes - branch: ${{ needs.setup.outputs.ref }} - continue-on-error: true - - - name: Apply fixes from artifact if available - id: apply_from_artifact - if: - needs.setup.outputs.tidy_checks == '' && (steps.download_fixes_check.outcome == 'success' || - steps.download_fixes_fix.outcome == 'success') - working-directory: ${{ needs.setup.outputs.checkout_path }} - run: | - # The artifact preserves the build directory prefix in its path structure. - FIXES_FILE="" - if [ -d "$GITHUB_WORKSPACE/fixes" ]; then - FIXES_FILE=$(find "$GITHUB_WORKSPACE/fixes" -name "clang-tidy-fixes.yaml" | head -1) - fi - if [ -n "$FIXES_FILE" ]; then - echo "Applying fixes from existing artifact..." - . /entrypoint.sh - FIXES_DIR="$(realpath "${FIXES_FILE%/*}")" - clang-apply-replacements "${FIXES_DIR}" || true - echo "applied=true" >> "$GITHUB_OUTPUT" - else - echo "applied=false" >> "$GITHUB_OUTPUT" - fi - - name: Setup build environment - if: steps.apply_from_artifact.outputs.applied != 'true' uses: Framework-R-D/action-setup-build-env@780fd75b00a291df6a42d9d2337651330ebdb907 # v1 with: build-path: ${{ needs.setup.outputs.build_path }} - name: Prepare clang-tidy options - if: steps.apply_from_artifact.outputs.applied != 'true' id: prep_tidy_opts env: TIDY_CHECKS: ${{ needs.setup.outputs.tidy_checks }} @@ -148,7 +181,6 @@ jobs: fi - name: Configure CMake - if: steps.apply_from_artifact.outputs.applied != 'true' uses: Framework-R-D/action-configure-cmake@caba9b42770d8f3ad2d8f294ef82dd88fc2c10c6 # v2 with: preset: clang-tidy @@ -156,7 +188,6 @@ jobs: build-path: ${{ needs.setup.outputs.build_path }} - name: Generate clang-tidy fixes - if: steps.apply_from_artifact.outputs.applied != 'true' working-directory: ${{ needs.setup.outputs.build_path }} env: TIDY_CHECKS: ${{ steps.prep_tidy_opts.outputs.clang_tidy_checks }} @@ -199,49 +230,167 @@ jobs: "$SOURCE_DIR/test" \ || true - - name: Apply clang-tidy fixes - if: steps.apply_from_artifact.outputs.applied != 'true' - working-directory: ${{ needs.setup.outputs.build_path }} + - name: Upload untrusted fixes for isolated validation + if: success() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: fix-input-${{ github.run_attempt }} + path: | + ${{ needs.setup.outputs.build_path }}/clang-tidy-fixes.yaml + retention-days: 1 + if-no-files-found: ignore + + apply_tidy_fixes: + runs-on: ubuntu-24.04 + name: Validate and prepare fixes + needs: [setup, generate_tidy_fixes] + if: ${{ needs.setup.result == 'success' && needs.generate_tidy_fixes.result == 'success' }} + outputs: + fix_artifact_url: ${{ steps.upload_fixes.outputs.artifact-url }} + has_changes: ${{ steps.apply_replacements.outputs.has_changes }} + permissions: + actions: read + contents: read + + container: + image: >- + ghcr.io/framework-r-d/phlex-ci:latest@sha256:d62317baa9f8b886da6db6250bdcc1d97d15bf85fb18b13d9842abafbfd82ce0 + + steps: + - name: Checkout reviewed source snapshot + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: ${{ needs.setup.outputs.checkout_path }} + ref: ${{ needs.setup.outputs.source_sha }} + repository: ${{ needs.setup.outputs.repo }} + persist-credentials: false + + - name: Checkout trusted workflow tools + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + path: workflow-tools + ref: ${{ github.workflow_sha }} + repository: ${{ github.repository }} + persist-credentials: false + + - name: Download current-run fixes + id: download_fixes + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: fix-input-${{ github.run_attempt }} + path: fixes + continue-on-error: true + + - name: Validate and apply replacements + id: apply_replacements + if: steps.download_fixes.outcome == 'success' + env: + SOURCE_PATH: ${{ needs.setup.outputs.checkout_path }} + BUILD_PATH: ${{ needs.setup.outputs.build_path }} run: | + FIXES_FILE="$GITHUB_WORKSPACE/fixes/clang-tidy-fixes.yaml" + SOURCE_DIR="$GITHUB_WORKSPACE/$SOURCE_PATH" + BUILD_DIR="$GITHUB_WORKSPACE/$BUILD_PATH" + if [ ! -f "$FIXES_FILE" ]; then + echo "::error::The current run's fixes artifact is missing its YAML file." + exit 1 + fi + + VALIDATED_DIR=$(mktemp -d "$RUNNER_TEMP/validated-clang-tidy-fixes.XXXXXXXX") + python3 -I "$GITHUB_WORKSPACE/workflow-tools/scripts/validate_clang_tidy_fixes.py" \ + "$FIXES_FILE" --source-root "$SOURCE_DIR" --output-dir "$VALIDATED_DIR" . /entrypoint.sh - if [ -f clang-tidy-fixes.yaml ]; then - clang-apply-replacements . || true + clang-apply-replacements "$VALIDATED_DIR" + + mkdir -p "$BUILD_DIR" + cp "$VALIDATED_DIR/clang-tidy-fixes.yaml" "$BUILD_DIR/clang-tidy-fixes.yaml" + if git -C "$SOURCE_DIR" diff --quiet; then + echo "has_changes=false" >> "$GITHUB_OUTPUT" + else + git -C "$SOURCE_DIR" diff --binary -- > "$GITHUB_WORKSPACE/clang-tidy-fix.patch" + echo "has_changes=true" >> "$GITHUB_OUTPUT" fi - - name: Upload artifacts - if: always() + - name: Upload validated fixes and patch + id: upload_fixes + if: success() && steps.download_fixes.outcome == 'success' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: clang-tidy-fix + name: clang-tidy-fix-${{ github.run_attempt }} path: | ${{ needs.setup.outputs.build_path }}/clang-tidy-fixes.yaml + clang-tidy-fix.patch retention-days: 7 if-no-files-found: ignore - - name: Handle fix commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 - with: - tool: clang-tidy - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - report: needs: [setup, apply_tidy_fixes] if: always() && needs.setup.result == 'success' && needs.setup.outputs.pr_number != '' runs-on: ubuntu-latest permissions: + actions: read pull-requests: write issues: write steps: + - name: Verify the PR still matches the approved snapshot + id: current_head + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + PR_NUMBER: ${{ needs.setup.outputs.pr_number }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + TARGET_REPO: ${{ needs.setup.outputs.repo }} + with: + script: | + const { owner, repo } = context.repo; + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: Number(process.env.PR_NUMBER) + }); + const isCurrent = pull.head.sha === process.env.SOURCE_SHA && + pull.head.ref === process.env.TARGET_REF && + pull.head.repo?.full_name === process.env.TARGET_REPO; + core.setOutput('is_current', String(isCurrent)); + if (!isCurrent) console.log('Skipping a report for a changed PR head.'); + - name: Post Clang-Tidy results + if: needs.apply_tidy_fixes.result == 'success' && steps.current_head.outputs.is_current == 'true' uses: Framework-R-D/action-post-clang-tidy-results@81c1a8f0b9125c701c8535fb63a05b8fdb6d968e # v2 with: build-path: ${{ needs.setup.outputs.build_path }} pr-number: ${{ needs.setup.outputs.pr_number }} + - name: Report patch-only fix + if: >- + needs.apply_tidy_fixes.result == 'success' && needs.apply_tidy_fixes.outputs.has_changes == 'true' && + steps.current_head.outputs.is_current == 'true' + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + ARTIFACT_URL: ${{ needs.apply_tidy_fixes.outputs.fix_artifact_url }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + PR_NUMBER: ${{ needs.setup.outputs.pr_number }} + with: + script: | + const body = [ + 'Clang-tidy fixes were prepared for reviewed source snapshot `' + process.env.SOURCE_SHA + '`.', + '', + 'Automatic pushing is disabled until the fix-commit action supports an exact source-SHA lease.', + 'Download the [fix patch artifact](' + process.env.ARTIFACT_URL + '), then apply', + '`clang-tidy-fix.patch` only if the branch is still at that snapshot.', + '', + 'To regenerate fixes after reviewing the current head, comment', + '`@' + context.repo.repo + 'bot tidy-fix`.' + ].join('\n'); + await github.rest.issues.createComment({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: Number(process.env.PR_NUMBER), + body + }); + - name: Update PR comment reactions + if: steps.current_head.outputs.is_current == 'true' && github.event_name == 'issue_comment' uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 with: status: ${{ needs.apply_tidy_fixes.result }} diff --git a/.github/workflows/clang-tidy-report.yaml b/.github/workflows/clang-tidy-report.yaml index f6b0d8aeb..ef57a3111 100644 --- a/.github/workflows/clang-tidy-report.yaml +++ b/.github/workflows/clang-tidy-report.yaml @@ -32,52 +32,130 @@ jobs: id: download uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - pattern: clang-tidy-* - merge-multiple: true + name: clang-tidy-check-${{ github.event.workflow_run.run_attempt }} run-id: ${{ github.event.workflow_run.id }} github-token: ${{ github.token }} path: artifacts continue-on-error: true - - name: Locate artifacts and PR number - id: locate - shell: bash + - name: Validate artifact provenance and source snapshot + id: provenance + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: DOWNLOAD_OUTCOME: ${{ steps.download.outcome }} - run: | - if [ "$DOWNLOAD_OUTCOME" = "failure" ]; then - echo "::error::Artifact download failed — check token permissions or artifact expiry" - exit 1 - fi - - pr_number_file=$(find artifacts -name "pr_number.txt" 2>/dev/null | head -1) - if [ -n "$pr_number_file" ]; then - pr_number=$(cat "$pr_number_file") - echo "pr_number=$pr_number" >> "$GITHUB_OUTPUT" - else - echo "::warning::pr_number.txt not found in downloaded artifacts; skipping PR comment" - fi - - issues_file=$(find artifacts -name "clang-tidy-new-issues.txt" 2>/dev/null | head -1) - if [ -n "$issues_file" ]; then - echo "issues_file=$issues_file" >> "$GITHUB_OUTPUT" - fi + with: + script: | + const fs = require('fs'); + const path = require('path'); + const run = context.payload.workflow_run; + const setOutputs = (values) => { + for (const [name, value] of Object.entries(values)) core.setOutput(name, value); + }; + if (process.env.DOWNLOAD_OUTCOME !== 'success') { + core.warning('The clang-tidy artifact is unavailable; skipping the PR comment.'); + setOutputs({ ready: 'false' }); + return; + } + if (run.name !== 'Clang-Tidy Check' || + run.repository?.full_name !== `${context.repo.owner}/${context.repo.repo}`) { + throw new Error('The artifact producer is not the expected repository workflow.'); + } + if (run.path !== '.github/workflows/clang-tidy-check.yaml' || + !Number.isSafeInteger(run.run_attempt) || run.run_attempt < 1) { + throw new Error('The artifact producer workflow path or attempt is invalid.'); + } + if (!/^[0-9a-f]{40}$/i.test(run.head_sha || '') || !run.head_repository?.full_name) { + throw new Error('The workflow run has no verifiable source repository and SHA.'); + } - completion_file=$(find artifacts -name "clang-tidy-analysis-complete.txt" 2>/dev/null | head -1) - if [ -n "$completion_file" ]; then - echo "analysis_complete=true" >> "$GITHUB_OUTPUT" - else - echo "::warning::clang-tidy analysis did not complete; retaining any prior PR comment" - fi + const file = name => path.join(process.env.GITHUB_WORKSPACE, 'artifacts', name); + const requireRegularFile = (name, maxBytes) => { + const target = file(name); + let stats; + try { + stats = fs.lstatSync(target); + } catch { + return null; + } + if (!stats.isFile() || stats.isSymbolicLink() || stats.size > maxBytes) { + throw new Error(`Invalid artifact file: ${name}`); + } + return target; + }; + const numberFile = requireRegularFile('pr_number.txt', 32); + const completionFile = requireRegularFile('clang-tidy-analysis-complete.txt', 1024); + const issuesFile = requireRegularFile('clang-tidy-new-issues.txt', 65536); + const manifestFile = requireRegularFile('provenance.json', 4096); + if (!numberFile || !completionFile || !issuesFile || !manifestFile) { + core.warning('The artifact is missing required PR, completion, findings, or provenance data.'); + setOutputs({ ready: 'false' }); + return; + } + const metadata = JSON.parse(fs.readFileSync(manifestFile, 'utf8')); + const expectedMetadata = { + source_sha: run.head_sha, + source_repo: run.head_repository.full_name, + run_id: String(run.id), + run_attempt: String(run.run_attempt) + }; + if (Object.keys(metadata).some(key => !Object.hasOwn(expectedMetadata, key)) || + Object.keys(expectedMetadata).some(key => metadata[key] !== expectedMetadata[key]) || + typeof metadata.workflow_ref !== 'string' || + !metadata.workflow_ref.includes('/.github/workflows/clang-tidy-check.yaml@')) { + throw new Error('The clang-tidy artifact provenance does not match its workflow run.'); + } + const allowedFiles = new Set([ + 'clang-tidy-analysis-complete.txt', 'clang-tidy-new-issues.txt', + 'clang-tidy.log', 'pr_number.txt', 'provenance.json' + ]); + for (const entry of fs.readdirSync(path.join(process.env.GITHUB_WORKSPACE, 'artifacts'), { + withFileTypes: true + })) { + if (!allowedFiles.has(entry.name) || !entry.isFile()) { + throw new Error(`Unexpected file in clang-tidy artifact: ${entry.name}`); + } + } + const numberText = fs.readFileSync(numberFile, 'utf8').trim(); + if (!/^[1-9][0-9]*$/.test(numberText)) { + throw new Error('The artifact contains an invalid PR number.'); + } + const prNumber = Number(numberText); + const linkedPull = (run.pull_requests || []).find(pull => pull.number === prNumber); + if (!linkedPull) { + throw new Error('The artifact PR number is not linked to its producing workflow run.'); + } + const { data: pull } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: prNumber + }); + const current = pull.head.sha === run.head_sha && + pull.head.ref === run.head_branch && + pull.head.repo?.full_name === run.head_repository.full_name && + (!linkedPull.head?.sha || linkedPull.head.sha === run.head_sha) && + (!linkedPull.head?.ref || linkedPull.head.ref === run.head_branch) && + (!linkedPull.head?.repo?.full_name || + linkedPull.head.repo.full_name === run.head_repository.full_name); + if (!current) { + console.log('Skipping stale clang-tidy artifacts for a moved PR head.'); + setOutputs({ ready: 'false' }); + return; + } + setOutputs({ + ready: 'true', + pr_number: String(prNumber), + issues_file: issuesFile || '' + }); - name: Update clang-tidy PR comment - if: steps.locate.outputs.pr_number != '' && steps.locate.outputs.analysis_complete == 'true' + if: steps.provenance.outputs.ready == 'true' uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 env: ARTIFACT_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.event.workflow_run.id }}#artifacts - ISSUES_FILE: ${{ steps.locate.outputs.issues_file }} - PR_NUMBER: ${{ steps.locate.outputs.pr_number }} + ISSUES_FILE: ${{ steps.provenance.outputs.issues_file }} + PR_NUMBER: ${{ steps.provenance.outputs.pr_number }} with: script: | const marker = ''; @@ -94,9 +172,12 @@ jobs: } const fs = require('fs'); const issuesFile = process.env.ISSUES_FILE; - const issues = issuesFile && fs.existsSync(issuesFile) + let issues = issuesFile && fs.existsSync(issuesFile) ? fs.readFileSync(issuesFile, 'utf8').trim() : ''; + if (Buffer.byteLength(issues, 'utf8') > 48000) { + issues = Buffer.from(issues, 'utf8').subarray(0, 48000).toString('utf8') + '\n[truncated]'; + } const comments = await github.paginate(github.rest.issues.listComments, { owner: context.repo.owner, repo: context.repo.repo, @@ -121,15 +202,17 @@ jobs: return; } + const backtickRuns = issues.match(/`+/g) || []; + const fence = '`'.repeat(Math.max(3, ...backtickRuns.map(run => run.length + 1))); const body = [ marker, '## Clang-Tidy Check Results', '', 'Clang-tidy found the following issue(s) on lines changed by this pull request:', '', - '```text', + `${fence}text`, issues, - '```', + fence, '', `[Download clang-tidy artifacts](${process.env.ARTIFACT_URL})` ].join('\n'); diff --git a/.github/workflows/cmake-build.yaml b/.github/workflows/cmake-build.yaml index 2da0da3c9..3e67726df 100644 --- a/.github/workflows/cmake-build.yaml +++ b/.github/workflows/cmake-build.yaml @@ -15,6 +15,10 @@ run-name: "${{ github.actor }} building and testing ${{ github.repository }}" description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character SHA at the selected branch head" + required: true + type: string build-combinations: description: | A space- or comma-separated list of build combinations to run. @@ -71,6 +75,10 @@ run-name: "${{ github.actor }} building and testing ${{ github.repository }}" description: "Head SHA of the PR for relevance check" required: false type: string + source-sha: + description: "Exact source SHA for manual or reusable runs" + required: false + type: string permissions: contents: read @@ -103,7 +111,10 @@ jobs: pr_number: ${{ steps.setup.outputs.pr_number }} checkout_path: ${{ steps.setup.outputs.checkout_path }} build_path: ${{ steps.setup.outputs.build_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} + has_changes: ${{ steps.source_relevance.outputs.has_changes }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} + build_combinations: ${{ steps.source_snapshot.outputs.command_args }} steps: - name: Workflow setup id: setup @@ -114,10 +125,100 @@ jobs: pr-base-sha: ${{ inputs.pr-base-sha }} checkout-path: ${{ inputs.checkout-path }} build-path: ${{ inputs.build-path }} - head-ref: ${{ inputs.pr-head-sha }} - file-type: | - cpp - cmake + + - name: Check out trusted source resolver + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/resolve-source-snapshot + persist-credentials: false + + - name: Resolve immutable source snapshot + id: source_snapshot + uses: ./workflow-tools/.github/actions/resolve-source-snapshot + with: + command: build + ref: ${{ steps.setup.outputs.ref }} + repo: ${{ steps.setup.outputs.repo }} + source-sha: ${{ inputs.source-sha }} + allow-arguments: true + + - name: Detect relevant changes in the immutable snapshot + id: source_relevance + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + SOURCE_SHA: ${{ steps.source_snapshot.outputs.source_sha }} + SOURCE_REPO: ${{ steps.source_snapshot.outputs.source_repo }} + PR_NUMBER: ${{ steps.setup.outputs.pr_number }} + SKIP_RELEVANCE: ${{ inputs.skip-relevance-check }} + with: + script: | + const matches = filename => { + if (filename.startsWith('scripts/')) return false; + const basename = filename.split('/').pop(); + return /\.(cpp|hpp)(\.in)?$/.test(basename) || + /^(CMakeLists\.txt|.*\.cmake)(\.in)?$/.test(basename); + }; + let relevant = process.env.SKIP_RELEVANCE === 'true'; + if (!relevant && (context.eventName === 'pull_request' || context.eventName === 'issue_comment')) { + try { + const pullNumber = Number(process.env.PR_NUMBER || context.payload.pull_request?.number || + context.payload.issue?.number); + const { data: before } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber + }); + if (before.head.sha !== process.env.SOURCE_SHA || + before.head.repo?.full_name !== process.env.SOURCE_REPO) { + relevant = true; + } else { + const changedPaths = []; + for (let page = 1; ; page++) { + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber, + per_page: 100, + page + }); + changedPaths.push(...files.map(file => file.filename)); + if (files.length < 100 || page === 30) break; + } + const { data: after } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber + }); + relevant = after.head.sha !== process.env.SOURCE_SHA || + after.head.repo?.full_name !== process.env.SOURCE_REPO || + changedPaths.length >= 3000 || changedPaths.some(matches); + } + } catch (error) { + core.warning(`Could not verify PR relevance; running the build conservatively: ${error.message}`); + relevant = true; + } + } else if (!relevant && context.eventName === 'push' && context.payload.before && + !/^0+$/.test(context.payload.before)) { + try { + const { data: comparison } = await github.rest.repos.compareCommits({ + owner: context.repo.owner, + repo: context.repo.repo, + base: context.payload.before, + head: process.env.SOURCE_SHA + }); + relevant = comparison.files?.length >= 300 || + (comparison.files || []).some(file => matches(file.filename)); + } catch (error) { + core.warning(`Could not verify push relevance; running the build conservatively: ${error.message}`); + relevant = true; + } + } else if (!relevant) { + relevant = true; + } + core.setOutput('has_changes', String(relevant)); generate-matrix: needs: setup @@ -134,8 +235,10 @@ jobs: - id: generate uses: Framework-R-D/action-generate-build-matrix@a867325d7153f7fcc7d64fc69eafcb2b97edae39 # v1 with: - user-input: ${{ inputs.build-combinations || github.event.inputs.build-combinations }} - comment-body: ${{ github.event.comment.body }} + user-input: >- + ${{ inputs.build-combinations || github.event.inputs.build-combinations || + needs.setup.outputs.build_combinations }} + comment-body: "" - name: Expand architecture matrix # Cross each compiler/sanitizer combo with the supported architectures and @@ -177,24 +280,19 @@ jobs: matrix: ${{ fromJSON(needs.generate-matrix.outputs.matrix) }} container: - image: ghcr.io/framework-r-d/phlex-ci:latest + image: >- + ghcr.io/framework-r-d/phlex-ci:latest@sha256:d62317baa9f8b886da6db6250bdcc1d97d15bf85fb18b13d9842abafbfd82ce0 options: --cap-add=SYS_PTRACE steps: - name: Check out code - # CodeQL actions/cache-poisoning/poisonable-step: false positive for the - # reported schedule/workflow_dispatch origins. The pinned organization - # setup action resolves schedules to GITHUB_SHA and manual refs within - # this repository; pull-request runs do not share that cache-write scope. - # This records the audit rationale, not an inline CodeQL suppression. + # The source resolver validates event SHAs, selected manual branch heads, + # and explicit issue-comment approvals before this immutable checkout. uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ needs.setup.outputs.checkout_path }} - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} + ref: ${{ needs.setup.outputs.source_sha }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false - name: Setup build environment @@ -271,7 +369,8 @@ jobs: # Set perf_event_paranoid for CPU profiling if [ "$PERFETTO_CPU_PROFILE" = "true" ]; then echo "Configuring perf_event_paranoid for CPU profiling" - echo -1 | tee /proc/sys/kernel/perf_event_paranoid 2>/dev/null || echo "Warning: Could not set perf_event_paranoid" + echo -1 | tee /proc/sys/kernel/perf_event_paranoid 2>/dev/null || \ + echo "Warning: Could not set perf_event_paranoid" fi # Configure profiling based on environment @@ -289,7 +388,8 @@ jobs: TEST_RESULT=0 if [ "${#TRACEBOX_ARGS[@]}" -gt 0 ]; then echo "::group::Running ctest with tracebox" - tracebox "${TRACEBOX_ARGS[@]}" -o "perfetto-trace.pftrace" -- ctest --progress --output-on-failure -j "$(nproc)" || TEST_RESULT=$? + tracebox "${TRACEBOX_ARGS[@]}" -o "perfetto-trace.pftrace" -- \ + ctest --progress --output-on-failure -j "$(nproc)" || TEST_RESULT=$? else echo "::group::Running ctest with Perfetto SDK tracing" ctest --progress --output-on-failure -j "$(nproc)" || TEST_RESULT=$? diff --git a/.github/workflows/cmake-format-fix.yaml b/.github/workflows/cmake-format-fix.yaml index c1f3a2edc..4f257c774 100644 --- a/.github/workflows/cmake-format-fix.yaml +++ b/.github/workflows/cmake-format-fix.yaml @@ -13,6 +13,10 @@ run-name: "${{ github.actor }} fixing CMake format" repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character source SHA to format" + required: true + type: string workflow_call: inputs: checkout-path: @@ -32,6 +36,10 @@ run-name: "${{ github.actor }} fixing CMake format" required: false type: boolean default: false + source-sha: + description: "Exact 40-character source SHA to format" + required: false + type: string outputs: changes: description: "Whether any fixes were applied" @@ -50,9 +58,8 @@ run-name: "${{ github.actor }} fixing CMake format" value: ${{ jobs.apply_cmake_formatting.outputs.patch_name }} permissions: - pull-requests: write - contents: write - issues: write + pull-requests: read + contents: read jobs: setup: @@ -69,6 +76,8 @@ jobs: ref: ${{ steps.setup.outputs.ref }} repo: ${{ steps.setup.outputs.repo }} checkout_path: ${{ steps.setup.outputs.checkout_path }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup @@ -79,17 +88,37 @@ jobs: repo: ${{ inputs.repo }} checkout-path: ${{ inputs.checkout-path }} + - name: Check out trusted snapshot action and patch tool + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: | + .github/actions/resolve-fix-snapshot + scripts/create_fix_patch.py + persist-credentials: false + + - name: Resolve approved source snapshot + id: source_snapshot + uses: ./workflow-tools/.github/actions/resolve-fix-snapshot + with: + command: cmake-fix + ref: ${{ steps.setup.outputs.ref }} + repo: ${{ steps.setup.outputs.repo }} + source-sha: ${{ inputs.source-sha }} + apply_cmake_formatting: runs-on: ubuntu-latest name: Apply CMake formatting needs: setup if: needs.setup.result == 'success' outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} + changes: ${{ steps.prepare_patch.outputs.changes }} + pushed: ${{ steps.prepare_patch.outputs.pushed }} + commit_sha: ${{ steps.prepare_patch.outputs.commit_sha }} + commit_sha_short: ${{ steps.prepare_patch.outputs.commit_sha_short }} + patch_name: ${{ steps.prepare_patch.outputs.patch_name }} steps: # Resolve tool dependencies from the workflow commit, never the PR branch. - name: Check out formatter dependencies @@ -98,16 +127,18 @@ jobs: repository: ${{ github.repository }} ref: ${{ github.workflow_sha }} path: workflow-tools - sparse-checkout: .github/format-tools + sparse-checkout: | + .github/format-tools + .gersemirc + scripts/create_fix_patch.py persist-credentials: false - - name: Checkout code + - name: Check out immutable source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} + ref: ${{ needs.setup.outputs.source_sha }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false - name: Install uv @@ -125,21 +156,57 @@ jobs: working-directory: ${{ needs.setup.outputs.checkout_path }} run: | echo "Applying CMake formatting..." - gersemi -i . + gersemi --config "$GITHUB_WORKSPACE/workflow-tools/.gersemirc" -i . - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 + - name: Prepare patch artifact + id: prepare_patch + env: + SOURCE_PATH: ${{ needs.setup.outputs.checkout_path }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + TARGET_REPO: ${{ needs.setup.outputs.source_repo }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + TOOL: cmake-format + run: python3 "$GITHUB_WORKSPACE/workflow-tools/scripts/create_fix_patch.py" + + - name: Upload patch artifact + if: steps.prepare_patch.outputs.changes == 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - tool: cmake-format - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} + name: ${{ steps.prepare_patch.outputs.artifact_name }} + path: ${{ steps.prepare_patch.outputs.artifact_path }} + retention-days: 7 + if-no-files-found: error + + report: + name: Report patch artifact + needs: [setup, apply_cmake_formatting] + if: >- + github.event_name == 'issue_comment' && !inputs.skip-comment && needs.setup.result == 'success' && + needs.apply_cmake_formatting.result == 'success' + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + issues: write + pull-requests: read + steps: + - name: Check out trusted report action + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/report-fix-patch + persist-credentials: false - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 + - name: Report immutable patch result + uses: ./workflow-tools/.github/actions/report-fix-patch with: - status: ${{ job.status }} + tool: cmake-format + source-sha: ${{ needs.setup.outputs.source_sha }} + changes: ${{ needs.apply_cmake_formatting.outputs.changes }} + patch-name: ${{ needs.apply_cmake_formatting.outputs.patch_name }} + run-id: ${{ github.run_id }} diff --git a/.github/workflows/codeql-analysis.yaml b/.github/workflows/codeql-analysis.yaml index 1e117525e..847f75834 100644 --- a/.github/workflows/codeql-analysis.yaml +++ b/.github/workflows/codeql-analysis.yaml @@ -10,9 +10,13 @@ name: "CodeQL Analysis" workflow_dispatch: inputs: ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." + description: "Branch whose current head must match source-sha. Defaults to the repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character commit SHA to analyze; required for workflow_dispatch." + required: true + type: string workflow_call: inputs: checkout-path: @@ -55,11 +59,14 @@ name: "CodeQL Analysis" description: "The repository to checkout from" required: false type: string + source-sha: + description: "Immutable source commit SHA for the workflow run" + required: false + type: string permissions: actions: read contents: read - security-events: write env: BUILD_TYPE: RelWithDebInfo @@ -77,9 +84,11 @@ jobs: checkout_path: ${{ steps.setup.outputs.checkout_path }} build_path: ${{ steps.setup.outputs.build_path }} skip_detection: ${{ steps.should_skip.outputs.skip }} - has_changes_cpp: ${{ steps.detect_cpp.outputs.has_changes }} - has_changes_python: ${{ steps.detect_python.outputs.has_changes }} - has_changes_actions: ${{ steps.detect_actions.outputs.has_changes }} + has_changes_cpp: ${{ steps.source_changes.outputs.cpp }} + has_changes_python: ${{ steps.source_changes.outputs.python }} + has_changes_actions: ${{ steps.source_changes.outputs.actions }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup @@ -91,6 +100,77 @@ jobs: checkout-path: ${{ inputs.checkout-path }} build-path: ${{ inputs.build-path }} + - name: Resolve immutable analysis source + id: source_snapshot + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + REQUESTED_SHA: ${{ inputs.source-sha }} + CALL_SOURCE_SHA: ${{ inputs.pr-head-sha }} + TARGET_REF: ${{ steps.setup.outputs.ref }} + TARGET_REPO: ${{ steps.setup.outputs.repo }} + WORKFLOW_REF: ${{ github.workflow_ref }} + with: + script: | + const { owner, repo } = context.repo; + const shaPattern = /^[0-9a-f]{40}$/i; + let sourceSha; + let sourceRepo; + if (context.eventName === 'pull_request') { + const head = context.payload.pull_request.head; + if (!head.repo) throw new Error('The PR source repository is unavailable.'); + sourceSha = head.sha; + sourceRepo = head.repo.full_name; + } else if (context.eventName === 'push' || context.eventName === 'schedule') { + sourceSha = context.sha; + sourceRepo = `${owner}/${repo}`; + } else if (context.eventName === 'workflow_dispatch') { + const targetRef = process.env.TARGET_REF.replace(/^refs\/heads\//, ''); + const selectedRef = context.ref.replace(/^refs\/heads\//, ''); + const requestedSha = process.env.REQUESTED_SHA; + if (!context.ref.startsWith('refs/heads/') || targetRef !== selectedRef || + process.env.WORKFLOW_REF.split('@').pop() !== context.ref || + !shaPattern.test(requestedSha) || process.env.TARGET_REPO !== `${owner}/${repo}` || + requestedSha.toLowerCase() !== context.sha.toLowerCase()) { + throw new Error('Manual runs require this branch, repository, workflow ref, and full source SHA.'); + } + const { data: branch } = await github.rest.repos.getBranch({ owner, repo, branch: targetRef }); + if (branch.commit.sha.toLowerCase() !== requestedSha.toLowerCase()) { + throw new Error('The selected branch head does not match source-sha.'); + } + sourceSha = branch.commit.sha; + sourceRepo = `${owner}/${repo}`; + } else if (context.eventName === 'workflow_call') { + sourceRepo = process.env.TARGET_REPO || `${owner}/${repo}`; + const requestedSha = process.env.CALL_SOURCE_SHA || process.env.REQUESTED_SHA; + if (context.payload.pull_request) { + const head = context.payload.pull_request.head; + if (!head.repo) throw new Error('The PR source repository is unavailable.'); + sourceSha = head.sha; + sourceRepo = head.repo.full_name; + if (requestedSha && requestedSha.toLowerCase() !== sourceSha.toLowerCase()) { + throw new Error('Reusable workflow source SHA does not match the PR head.'); + } + } else if (requestedSha) { + if (sourceRepo !== `${owner}/${repo}`) { + throw new Error('Reusable non-PR analysis must target the caller repository.'); + } + if (!shaPattern.test(requestedSha)) throw new Error('The reusable workflow source SHA is invalid.'); + sourceSha = requestedSha; + } else { + const [targetOwner, targetRepo] = sourceRepo.split('/'); + const { data: branch } = await github.rest.repos.getBranch({ + owner: targetOwner, + repo: targetRepo, + branch: process.env.TARGET_REF + }); + sourceSha = branch.commit.sha; + } + } else { + throw new Error(`Unsupported CodeQL source event: ${context.eventName}`); + } + core.setOutput('source_sha', sourceSha); + core.setOutput('source_repo', sourceRepo); + - name: Determine if detection should be skipped id: should_skip env: @@ -107,45 +187,96 @@ jobs: echo "skip=false" >> "$GITHUB_OUTPUT" fi - - name: Detect C++ changes - id: detect_cpp - if: steps.should_skip.outputs.skip != 'true' - uses: Framework-R-D/action-run-change-detection@047250bcbe1be9fb479c8f3ceeb85ac1084ede2e # v2 - with: - checkout-path: ${{ steps.setup.outputs.checkout_path }} - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - base-ref: ${{ steps.setup.outputs.base_sha }} - head-ref: ${{ inputs.pr-head-sha || steps.setup.outputs.ref }} - file-type: | - cpp - cmake - - - name: Detect Python changes - id: detect_python - if: steps.should_skip.outputs.skip != 'true' - uses: Framework-R-D/action-run-change-detection@047250bcbe1be9fb479c8f3ceeb85ac1084ede2e # v2 - with: - checkout-path: ${{ steps.setup.outputs.checkout_path }} - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - base-ref: ${{ steps.setup.outputs.base_sha }} - head-ref: ${{ inputs.pr-head-sha || steps.setup.outputs.ref }} - file-type: python - - - name: Detect Actions changes - id: detect_actions - if: steps.should_skip.outputs.skip != 'true' - uses: Framework-R-D/action-run-change-detection@047250bcbe1be9fb479c8f3ceeb85ac1084ede2e # v2 + - name: Detect language changes in the immutable snapshot + id: source_changes + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + SOURCE_SHA: ${{ steps.source_snapshot.outputs.source_sha }} + SOURCE_REPO: ${{ steps.source_snapshot.outputs.source_repo }} + BASE_SHA: ${{ steps.setup.outputs.base_sha }} + PR_NUMBER: ${{ steps.setup.outputs.pr_number }} + SKIP_DETECTION: ${{ steps.should_skip.outputs.skip }} with: - checkout-path: ${{ steps.setup.outputs.checkout_path }} - ref: ${{ steps.setup.outputs.ref }} - repo: ${{ steps.setup.outputs.repo }} - base-ref: ${{ steps.setup.outputs.base_sha }} - head-ref: ${{ inputs.pr-head-sha || steps.setup.outputs.ref }} - include-globs: | - .github/workflows/*.yaml - .github/workflows/*.yml + script: | + const changes = { cpp: false, python: false, actions: false }; + const classify = filename => { + const basename = filename.split('/').pop(); + if (/\.(cpp|hpp)(\.in)?$/.test(basename) || + /^(CMakeLists\.txt|.*\.cmake)(\.in)?$/.test(basename)) changes.cpp = true; + if (/\.py$/.test(basename)) changes.python = true; + if (/^\.github\/workflows\/[^/]+\.ya?ml$/.test(filename) || + /^\.github\/actions\/.*\.(ya?ml|[cm]?js|ts)$/.test(filename)) changes.actions = true; + }; + const allLanguages = () => { + changes.cpp = true; + changes.python = true; + changes.actions = true; + }; + if (process.env.SKIP_DETECTION !== 'true') { + if (context.eventName === 'pull_request' || context.eventName === 'issue_comment') { + try { + const pullNumber = Number(process.env.PR_NUMBER || context.payload.pull_request?.number || + context.payload.issue?.number); + const { data: before } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber + }); + if (before.head.sha !== process.env.SOURCE_SHA || + before.head.repo?.full_name !== process.env.SOURCE_REPO) { + allLanguages(); + } else { + const paths = []; + for (let page = 1; ; page++) { + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber, + per_page: 100, + page + }); + paths.push(...files.map(file => file.filename)); + if (files.length < 100 || page === 30) break; + } + const { data: after } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber + }); + if (after.head.sha !== process.env.SOURCE_SHA || + after.head.repo?.full_name !== process.env.SOURCE_REPO || paths.length >= 3000) { + allLanguages(); + } else { + paths.forEach(classify); + } + } + } catch (error) { + core.warning(`Could not verify PR relevance; analyzing all languages: ${error.message}`); + allLanguages(); + } + } else if ((context.eventName === 'push' && context.payload.before && + !/^0+$/.test(context.payload.before)) || + (context.eventName === 'workflow_call' && process.env.BASE_SHA)) { + try { + const { data: comparison } = await github.rest.repos.compareCommits({ + owner: context.repo.owner, + repo: context.repo.repo, + base: context.eventName === 'push' ? context.payload.before : process.env.BASE_SHA, + head: process.env.SOURCE_SHA + }); + if (comparison.files?.length >= 300) allLanguages(); + else (comparison.files || []).forEach(file => classify(file.filename)); + } catch (error) { + core.warning(`Could not verify source relevance; analyzing all languages: ${error.message}`); + allLanguages(); + } + } else { + allLanguages(); + } + } + for (const [language, changed] of Object.entries(changes)) { + core.setOutput(language, String(changed)); + } determine-languages: needs: setup @@ -166,12 +297,16 @@ jobs: # If detection was skipped, use all languages or the provided language-matrix if [ "${SKIP_DETECTION}" = "true" ]; then if [ "${GITHUB_EVENT_NAME}" = "workflow_call" ] && [ -n "${LANGUAGE_MATRIX}" ]; then - # Validate that language-matrix is valid JSON - if ! echo "${LANGUAGE_MATRIX}" | python3 -c "import sys, json; json.load(sys.stdin)" 2>/dev/null; then - echo "::error::Invalid language-matrix input: must be valid JSON array" + if ! LANGUAGES=$(jq -ce ' + if type == "array" and + all(.[]; . == "cpp" or . == "python" or . == "actions") and + length == (unique | length) + then . else error("invalid language-matrix") end + ' <<< "$LANGUAGE_MATRIX"); then + echo "::error::Invalid language-matrix input; allowed values are cpp, python, and actions." exit 1 fi - echo "languages=${LANGUAGE_MATRIX}" >> "$GITHUB_OUTPUT" + echo "languages=${LANGUAGES}" >> "$GITHUB_OUTPUT" else echo 'languages=["cpp", "python", "actions"]' >> "$GITHUB_OUTPUT" fi @@ -211,8 +346,13 @@ jobs: needs.determine-languages.result == 'success' && needs.determine-languages.outputs.languages != '[]' name: Analyze ${{ matrix.language }} with CodeQL runs-on: ubuntu-24.04 + permissions: + actions: read + contents: read + packages: read container: - image: ghcr.io/framework-r-d/phlex-ci:latest + image: >- + ghcr.io/framework-r-d/phlex-ci:latest@sha256:d62317baa9f8b886da6db6250bdcc1d97d15bf85fb18b13d9842abafbfd82ce0 env: local_checkout_path: . local_build_path: ${{ needs.setup.outputs.build_path }} @@ -232,11 +372,8 @@ jobs: - name: Checkout repository uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} + ref: ${{ needs.setup.outputs.source_sha }} + repository: ${{ needs.setup.outputs.source_repo }} path: ${{ env.local_checkout_path }} fetch-depth: 0 persist-credentials: false @@ -271,27 +408,236 @@ jobs: exit 1 fi - # Run CodeQL analysis (uploads results to code scanning) + # Save SARIF results for a separate uploader job. - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 with: checkout_path: ${{ env.local_checkout_path }} output: results category: ${{ matrix.language }} + upload: never + upload-database: false + + - name: Write CodeQL SARIF provenance manifest + env: + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + SOURCE_REPO: ${{ needs.setup.outputs.source_repo }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + LANGUAGE: ${{ matrix.language }} + run: | + python3 - <<'PY' + import json + import os + from pathlib import Path + + root = Path("results") + sarif = root / f"{os.environ['LANGUAGE']}.sarif" + if root.is_symlink() or sarif.is_symlink() or not sarif.is_file(): + raise SystemExit("Expected one regular CodeQL SARIF file") + metadata = { + "source_sha": os.environ["SOURCE_SHA"], + "source_repo": os.environ["SOURCE_REPO"], + "workflow_ref": os.environ["WORKFLOW_REF"], + "run_id": os.environ["RUN_ID"], + "run_attempt": os.environ["RUN_ATTEMPT"], + "language": os.environ["LANGUAGE"], + } + (root / f"provenance-{os.environ['LANGUAGE']}.json").write_text( + json.dumps(metadata, sort_keys=True) + "\n", encoding="utf-8" + ) + PY - name: Upload SARIF results uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: codeql-sarif-${{ matrix.language }} + name: codeql-sarif-${{ matrix.language }}-${{ github.run_attempt }} path: results retention-days: 7 + codeql-upload: + name: Upload validated CodeQL SARIF + needs: [setup, determine-languages, codeql] + if: needs.codeql.result == 'success' && needs.determine-languages.outputs.languages != '[]' + runs-on: ubuntu-24.04 + permissions: + actions: read + contents: read + pull-requests: read + security-events: write + outputs: + source_current: ${{ steps.current_source.outputs.is_current }} + steps: + - name: Check out exact source for SARIF mapping + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ needs.setup.outputs.source_repo }} + ref: ${{ needs.setup.outputs.source_sha }} + persist-credentials: false + + - name: Verify the source snapshot is still current + id: current_source + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + SOURCE_REPO: ${{ needs.setup.outputs.source_repo }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + PR_NUMBER: ${{ needs.setup.outputs.pr_number }} + with: + script: | + const { owner, repo } = context.repo; + let isCurrent = true; + if (context.eventName === 'pull_request') { + const pull = context.payload.pull_request; + const { data } = await github.rest.pulls.get({ owner, repo, pull_number: pull.number }); + isCurrent = data.head.sha === process.env.SOURCE_SHA && + data.head.ref === pull.head.ref && + data.head.repo?.full_name === process.env.SOURCE_REPO; + } else if (context.eventName === 'workflow_dispatch' || context.eventName === 'push' || + context.eventName === 'schedule') { + const branchName = context.ref.replace(/^refs\/heads\//, ''); + const { data: branch } = await github.rest.repos.getBranch({ owner, repo, branch: branchName }); + isCurrent = process.env.SOURCE_REPO === `${owner}/${repo}` && + context.ref.startsWith('refs/heads/') && context.sha === process.env.SOURCE_SHA && + branch.commit.sha === process.env.SOURCE_SHA; + } else if (context.eventName === 'workflow_call' && process.env.PR_NUMBER) { + const { data } = await github.rest.pulls.get({ + owner, + repo, + pull_number: Number(process.env.PR_NUMBER) + }); + isCurrent = data.head.sha === process.env.SOURCE_SHA && + data.head.ref === process.env.TARGET_REF && + data.head.repo?.full_name === process.env.SOURCE_REPO; + } else if (context.eventName === 'workflow_call') { + const branchName = process.env.TARGET_REF.replace(/^refs\/heads\//, ''); + const { data: branch } = await github.rest.repos.getBranch({ owner, repo, branch: branchName }); + isCurrent = process.env.SOURCE_REPO === `${owner}/${repo}` && + branchName === context.ref.replace(/^refs\/heads\//, '') && + branch.commit.sha === process.env.SOURCE_SHA; + } + core.setOutput('is_current', String(isCurrent)); + if (!isCurrent) console.log('Skipping stale CodeQL SARIF for a moved source branch.'); + + - name: Download C++ SARIF artifact + if: always() && contains(needs.determine-languages.outputs.languages, '"cpp"') + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: codeql-sarif-cpp-${{ github.run_attempt }} + path: sarif-input/cpp + + - name: Download Python SARIF artifact + if: always() && contains(needs.determine-languages.outputs.languages, '"python"') + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: codeql-sarif-python-${{ github.run_attempt }} + path: sarif-input/python + + - name: Download Actions SARIF artifact + if: always() && contains(needs.determine-languages.outputs.languages, '"actions"') + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: codeql-sarif-actions-${{ github.run_attempt }} + path: sarif-input/actions + + - name: Validate SARIF provenance and contents + id: validate_sarif + env: + LANGUAGES: ${{ needs.determine-languages.outputs.languages }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + SOURCE_REPO: ${{ needs.setup.outputs.source_repo }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + run: | + python3 - <<'PY' + import json + import os + from pathlib import Path + + languages = json.loads(os.environ["LANGUAGES"]) + if not isinstance(languages, list) or any( + language not in {"cpp", "python", "actions"} for language in languages + ): + raise SystemExit("Unexpected CodeQL language list") + root = Path("sarif-input") + if root.is_symlink(): + raise SystemExit("SARIF artifact root must not be a symlink") + expected_base = { + "source_sha": os.environ["SOURCE_SHA"], + "source_repo": os.environ["SOURCE_REPO"], + "workflow_ref": os.environ["WORKFLOW_REF"], + "run_id": os.environ["RUN_ID"], + "run_attempt": os.environ["RUN_ATTEMPT"], + } + outputs = [] + for language in ("cpp", "python", "actions"): + directory = root / language + if language not in languages: + if directory.exists() or directory.is_symlink(): + raise SystemExit(f"Unexpected SARIF artifact for {language}") + continue + if directory.is_symlink() or not directory.is_dir(): + raise SystemExit(f"Missing or invalid SARIF artifact directory: {language}") + report = directory / f"{language}.sarif" + manifest = directory / f"provenance-{language}.json" + if report.is_symlink() or manifest.is_symlink() or not report.is_file() or not manifest.is_file(): + raise SystemExit(f"Missing regular SARIF report or provenance for {language}") + if report.stat().st_size > 104857600: + raise SystemExit(f"SARIF report exceeds the size limit for {language}") + expected_files = {f"{language}.sarif", f"provenance-{language}.json"} + if {entry.name for entry in directory.iterdir()} != expected_files: + raise SystemExit(f"Unexpected files in SARIF artifact for {language}") + metadata = json.loads(manifest.read_text(encoding="utf-8")) + if metadata != {**expected_base, "language": language}: + raise SystemExit(f"SARIF provenance mismatch for {language}") + document = json.loads(report.read_text(encoding="utf-8")) + if document.get("version") != "2.1.0" or not isinstance(document.get("runs"), list): + raise SystemExit(f"Invalid SARIF document for {language}") + outputs.append(f"{language}_file={report}") + with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as output: + output.write("\n".join(outputs) + "\n") + PY + + - name: Upload C++ CodeQL SARIF + if: >- + steps.current_source.outputs.is_current == 'true' && steps.validate_sarif.outputs.cpp_file != '' + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + sarif_file: ${{ steps.validate_sarif.outputs.cpp_file }} + category: cpp + + - name: Upload Python CodeQL SARIF + if: >- + steps.current_source.outputs.is_current == 'true' && steps.validate_sarif.outputs.python_file != '' + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + sarif_file: ${{ steps.validate_sarif.outputs.python_file }} + category: python + + - name: Upload Actions CodeQL SARIF + if: >- + steps.current_source.outputs.is_current == 'true' && steps.validate_sarif.outputs.actions_file != '' + uses: github/codeql-action/upload-sarif@33d7b85da1a04171e211befe2c739303b9a4c066 # v4.39.3 + with: + sarif_file: ${{ steps.validate_sarif.outputs.actions_file }} + category: actions + codeql-report: name: Aggregate CodeQL alerts - needs: codeql + needs: [setup, determine-languages, codeql, codeql-upload] runs-on: ubuntu-24.04 - if: needs.codeql.result == 'success' + if: >- + needs.codeql.result == 'success' && needs.codeql-upload.result == 'success' && + needs.codeql-upload.outputs.source_current == 'true' && github.repository == 'Framework-R-D/phlex' && + (github.event_name != 'workflow_dispatch' || github.ref == format('refs/heads/{0}', + github.event.repository.default_branch)) permissions: + actions: read contents: read issues: write pull-requests: write @@ -360,10 +706,36 @@ jobs: steps.check_codeql.outputs.fixed_vs_base == 'true') && steps.check_codeql.outputs.comment_path != '' env: COMMENT_PATH: ${{ steps.check_codeql.outputs.comment_path }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + SOURCE_REPO: ${{ needs.setup.outputs.source_repo }} + SOURCE_REF: ${{ github.event.pull_request.head.ref }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} run: | + set -euo pipefail mkdir -p pr_comment_data jq -r '.pull_request.number // empty' "${GITHUB_EVENT_PATH}" > pr_comment_data/pr_number.txt cp "${COMMENT_PATH}" pr_comment_data/comment_body.md + python3 - <<'PY' + import json + import os + from pathlib import Path + + metadata = { + "source_sha": os.environ["SOURCE_SHA"], + "source_repo": os.environ["SOURCE_REPO"], + "source_ref": os.environ["SOURCE_REF"], + "workflow_ref": os.environ["WORKFLOW_REF"], + "run_id": os.environ["RUN_ID"], + "run_attempt": os.environ["RUN_ATTEMPT"], + } + if len(metadata["source_sha"]) != 40 or not metadata["source_repo"] or not metadata["source_ref"]: + raise SystemExit("Invalid PR CodeQL provenance") + Path("pr_comment_data/provenance.json").write_text( + json.dumps(metadata, sort_keys=True) + "\n", encoding="utf-8" + ) + PY - name: Upload PR comment data if: >- @@ -371,7 +743,7 @@ jobs: steps.check_codeql.outputs.fixed_vs_base == 'true') && steps.check_codeql.outputs.comment_path != '' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: codeql-pr-data + name: codeql-pr-data-${{ github.run_attempt }} path: pr_comment_data/ retention-days: 1 diff --git a/.github/workflows/codeql-comment.yaml b/.github/workflows/codeql-comment.yaml index 2a7779a31..c21481246 100644 --- a/.github/workflows/codeql-comment.yaml +++ b/.github/workflows/codeql-comment.yaml @@ -7,7 +7,9 @@ name: "CodeQL - Post Comment" - completed permissions: - pull-requests: write + actions: read + contents: read + pull-requests: read issues: write jobs: @@ -24,102 +26,128 @@ jobs: github.event.workflow_run.conclusion == 'failure') steps: - name: Download PR comment data + id: download uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - name: codeql-pr-data + name: codeql-pr-data-${{ github.event.workflow_run.run_attempt }} run-id: ${{ github.event.workflow_run.id }} - github-token: ${{ secrets.WORKFLOW_PAT }} # Needed to download artifacts from other runs if private/internal + repository: ${{ github.repository }} + github-token: ${{ github.token }} path: pr_comment_data continue-on-error: true - - name: Post Comment - # Only run if the artifact was found (meaning alerts exist) - if: success() && hashFiles('pr_comment_data/pr_number.txt') != '' + - name: Validate provenance and post CodeQL comment + if: steps.download.outcome == 'success' id: post_comment uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + RUN_ID: ${{ github.event.workflow_run.id }} + RUN_ATTEMPT: ${{ github.event.workflow_run.run_attempt }} with: - github-token: ${{ github.token }} script: | - const core = require('@actions/core'); const fs = require('fs'); const path = require('path'); - - const prNumberPath = path.join('pr_comment_data', 'pr_number.txt'); - const commentBodyPath = path.join('pr_comment_data', 'comment_body.md'); - - if (!fs.existsSync(prNumberPath) || !fs.existsSync(commentBodyPath)) { - console.log('Artifact data missing, skipping comment.'); + const run = context.payload.workflow_run; + const { owner, repo } = context.repo; + if (run.name !== 'CodeQL Analysis' || + run.path !== '.github/workflows/codeql-analysis.yaml' || + run.repository?.full_name !== `${owner}/${repo}` || run.event !== 'pull_request' || + !Number.isSafeInteger(run.run_attempt) || run.run_attempt < 1) { + throw new Error('The artifact producer is not the expected CodeQL PR workflow.'); + } + const artifactRoot = path.join(process.env.GITHUB_WORKSPACE, 'pr_comment_data'); + const rootStats = fs.lstatSync(artifactRoot); + if (!rootStats.isDirectory() || rootStats.isSymbolicLink()) { + throw new Error('The downloaded comment artifact directory is invalid.'); + } + const readRegularFile = (name, maxBytes) => { + const target = path.join(artifactRoot, name); + const stats = fs.lstatSync(target); + if (!stats.isFile() || stats.isSymbolicLink() || stats.size > maxBytes) { + throw new Error(`Invalid CodeQL comment artifact file: ${name}`); + } + return fs.readFileSync(target, 'utf8'); + }; + const expectedFiles = new Set(['comment_body.md', 'pr_number.txt', 'provenance.json']); + for (const entry of fs.readdirSync(artifactRoot, { withFileTypes: true })) { + if (!entry.isFile() || !expectedFiles.has(entry.name)) { + throw new Error(`Unexpected file in CodeQL comment artifact: ${entry.name}`); + } + } + const metadata = JSON.parse(readRegularFile('provenance.json', 4096)); + const metadataKeys = [ + 'run_attempt', 'run_id', 'source_ref', 'source_repo', 'source_sha', 'workflow_ref' + ]; + if (Object.keys(metadata).sort().join(',') !== metadataKeys.join(',') || + !/^[0-9a-f]{40}$/i.test(metadata.source_sha || '') || + !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(metadata.source_repo || '') || + typeof metadata.source_ref !== 'string' || !metadata.source_ref || + typeof metadata.workflow_ref !== 'string' || + !metadata.workflow_ref.includes('/.github/workflows/codeql-analysis.yaml@') || + metadata.run_id !== String(run.id) || metadata.run_id !== process.env.RUN_ID || + metadata.run_attempt !== String(run.run_attempt) || + metadata.run_attempt !== process.env.RUN_ATTEMPT) { + throw new Error('CodeQL comment provenance does not match its workflow run.'); + } + const numberText = readRegularFile('pr_number.txt', 32).trim(); + if (!/^[1-9][0-9]*$/.test(numberText)) { + throw new Error('The artifact contains an invalid pull request number.'); + } + const prNumber = Number(numberText); + const linkedPull = (run.pull_requests || []).find(pull => pull.number === prNumber); + if (!linkedPull) { + console.log('The producing workflow run is not linked to the artifact PR; skipping comment.'); return; } - - const prNumber = Number(fs.readFileSync(prNumberPath, 'utf8').trim()); - const body = fs.readFileSync(commentBodyPath, 'utf8'); + if ((linkedPull.head?.sha && linkedPull.head.sha !== metadata.source_sha) || + (linkedPull.head?.ref && linkedPull.head.ref !== metadata.source_ref) || + (linkedPull.head?.repo?.full_name && + linkedPull.head.repo.full_name !== metadata.source_repo)) { + throw new Error('Artifact source snapshot differs from the PR linked to the workflow run.'); + } + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: prNumber + }); + const isCurrent = pull.state === 'open' && pull.head.sha === metadata.source_sha && + pull.head.ref === metadata.source_ref && + pull.head.repo?.full_name === metadata.source_repo; + if (!isCurrent) { + console.log('Skipping stale CodeQL comment data for a moved PR head.'); + return; + } + const body = readRegularFile('comment_body.md', 65536); const marker = ''; const legacyMarker = ''; - - // Append marker if missing const finalBody = body.includes(marker) ? body : `${body}\n${marker}`; - - console.log(`Processing PR #${prNumber}`); - const { data: comments } = await github.rest.issues.listComments({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: prNumber, + owner, + repo, + issue_number: prNumber }); - const existing = comments.find(c => c.body.includes(marker) || c.body.includes(legacyMarker)); - let commentId; if (existing) { - console.log(`Updating existing comment ${existing.id}`); await github.rest.issues.updateComment({ - owner: context.repo.owner, - repo: context.repo.repo, + owner, + repo, comment_id: existing.id, body: finalBody }); commentId = existing.id; } else { - console.log(`Creating new comment`); const { data: created } = await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, + owner, + repo, issue_number: prNumber, body: finalBody }); commentId = created.id; } - core.setOutput('comment_id', commentId); - - - name: Cleanup old CodeQL comments - if: success() && hashFiles('pr_comment_data/pr_number.txt') != '' - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - env: - MARKER: "" - with: - script: | - const fs = require('fs'); - const marker = process.env.MARKER; - const prNumberPath = 'pr_comment_data/pr_number.txt'; - if (!fs.existsSync(prNumberPath)) { - console.log('pr_number.txt artifact not found, skipping cleanup'); - process.exit(0); - } - const pr = parseInt(fs.readFileSync(prNumberPath, 'utf8').trim(), 10); - if (isNaN(pr)) { console.log('No PR number, skipping cleanup'); process.exit(0); } - const { data: comments } = await github.rest.issues.listComments({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: pr - }); - for (const c of comments) { - if (c.body && c.body.includes(marker)) { - await github.rest.issues.deleteComment({ - owner: context.repo.owner, - repo: context.repo.repo, - comment_id: c.id - }); - console.log(`Deleted old comment ${c.id}`); + for (const comment of comments) { + if (comment.id !== commentId && comment.body && + (comment.body.includes(marker) || comment.body.includes(legacyMarker))) { + await github.rest.issues.deleteComment({ owner, repo, comment_id: comment.id }); } } diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 6ab09f3bd..48aa07749 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -11,11 +11,15 @@ run-name: "${{ github.actor }} running code coverage" workflow_dispatch: inputs: ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." + description: "The branch to checkout. Defaults to the repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character commit SHA to analyze; required for workflow_dispatch." + required: true + type: string repo: - description: "The repository to checkout. Defaults to the current repository." + description: "Repository to checkout; manual runs must target this repository." required: false type: string pr-base-sha: @@ -54,7 +58,8 @@ jobs: pr_number: ${{ steps.setup.outputs.pr_number }} checkout_path: ${{ steps.setup.outputs.checkout_path }} build_path: ${{ steps.setup.outputs.build_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} + has_changes: ${{ steps.source_relevance.outputs.has_changes }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} steps: - name: Workflow setup id: setup @@ -63,16 +68,137 @@ jobs: ref: ${{ inputs.ref }} repo: ${{ inputs.repo }} pr-base-sha: ${{ inputs.pr-base-sha }} - file-type: | - cpp - cmake - python - exclude-globs: scripts/** + - name: Validate immutable source snapshot + id: source_snapshot + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + REQUESTED_SHA: ${{ inputs.source-sha }} + TARGET_REF: ${{ steps.setup.outputs.ref }} + TARGET_REPO: ${{ steps.setup.outputs.repo }} + WORKFLOW_REF: ${{ github.workflow_ref }} + COMMENT_BODY: ${{ github.event.comment.body }} + with: + script: | + const { owner, repo } = context.repo; + const shaPattern = /^[0-9a-f]{40}$/i; + let sourceSha; + + if (context.eventName === 'workflow_dispatch') { + const requestedSha = process.env.REQUESTED_SHA; + const targetRef = process.env.TARGET_REF.replace(/^refs\/heads\//, ''); + const selectedRef = context.ref.replace(/^refs\/heads\//, ''); + if (!shaPattern.test(requestedSha) || process.env.TARGET_REPO !== `${owner}/${repo}` || + !context.ref.startsWith('refs/heads/') || targetRef !== selectedRef || + process.env.WORKFLOW_REF.split('@').pop() !== context.ref || + requestedSha.toLowerCase() !== context.sha.toLowerCase()) { + throw new Error('Manual runs require this branch, repository, workflow ref, and full source SHA.'); + } + const { data: branch } = await github.rest.repos.getBranch({ owner, repo, branch: targetRef }); + if (branch.commit.sha.toLowerCase() !== requestedSha.toLowerCase()) { + throw new Error('The selected branch head does not match source-sha.'); + } + sourceSha = branch.commit.sha; + } else if (context.eventName === 'issue_comment') { + const prefix = `@${repo}bot coverage`; + const body = process.env.COMMENT_BODY.trim(); + const match = body.match(new RegExp(`^${prefix}(?: --sha=([0-9a-f]{40}))?$`)); + if (!match) throw new Error('Use the coverage command without arguments.'); + const approvedSha = match[1]; + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: context.payload.issue.number + }); + if (pull.state !== 'open' || + (approvedSha && pull.head.sha.toLowerCase() !== approvedSha.toLowerCase()) || + pull.head.ref !== process.env.TARGET_REF || + pull.head.repo?.full_name !== process.env.TARGET_REPO) { + throw new Error('The PR head differs from the coverage target or optional SHA.'); + } + sourceSha = pull.head.sha; + } else if (context.eventName === 'pull_request') { + sourceSha = context.payload.pull_request.head.sha; + } else if (context.eventName === 'push') { + sourceSha = context.sha; + } else { + throw new Error(`Unsupported coverage event: ${context.eventName}`); + } + + core.setOutput('source_sha', sourceSha); + - name: Detect relevant changes in immutable source snapshot + id: source_relevance + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + SOURCE_SHA: ${{ steps.source_snapshot.outputs.source_sha }} + PR_NUMBER: >- + ${{ steps.setup.outputs.pr_number || github.event.pull_request.number || github.event.issue.number }} + with: + script: | + const matches = filename => { + if (filename.startsWith('scripts/')) return false; + const basename = filename.split('/').pop(); + return /\.(cpp|hpp)(\.in)?$/.test(basename) || + /^(CMakeLists\.txt|.*\.cmake)(\.in)?$/.test(basename) || + /\.py(\.in)?$/.test(basename); + }; + let relevant = true; + if (context.eventName === 'pull_request' || context.eventName === 'issue_comment') { + try { + const pullNumber = Number(process.env.PR_NUMBER); + const expectedSha = process.env.SOURCE_SHA; + const { data: before } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber + }); + const sourceSha = expectedSha || before.head.sha; + if (before.head.sha === sourceSha) { + const changedPaths = []; + for (let page = 1; ; page++) { + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber, + per_page: 100, + page + }); + changedPaths.push(...files.map(file => file.filename)); + if (files.length < 100 || page === 30) break; + } + const { data: after } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber + }); + relevant = after.head.sha !== sourceSha || changedPaths.length >= 3000 || + changedPaths.some(matches); + } + } catch (error) { + core.warning(`Could not verify PR relevance; running coverage conservatively: ${error.message}`); + relevant = true; + } + } else if (context.eventName === 'push' && context.payload.before && + !/^0+$/.test(context.payload.before)) { + try { + const { data: comparison } = await github.rest.repos.compareCommits({ + owner: context.repo.owner, + repo: context.repo.repo, + base: context.payload.before, + head: context.sha + }); + relevant = comparison.files?.length >= 300 || + (comparison.files || []).some(file => matches(file.filename)); + } catch (error) { + core.warning(`Could not verify push relevance; running coverage conservatively: ${error.message}`); + relevant = true; + } + } + core.setOutput('has_changes', String(relevant)); coverage: needs: setup if: > - always() && (github.event_name == 'workflow_dispatch' || needs.setup.outputs.has_changes == 'true') + always() && needs.setup.result == 'success' && needs.setup.outputs.has_changes == 'true' runs-on: ${{ matrix.runner }} strategy: fail-fast: false @@ -86,10 +212,8 @@ jobs: - arch: arm64 runner: ubuntu-24.04-arm container: - image: ghcr.io/framework-r-d/phlex-ci:latest - - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} + image: >- + ghcr.io/framework-r-d/phlex-ci:latest@sha256:d62317baa9f8b886da6db6250bdcc1d97d15bf85fb18b13d9842abafbfd82ce0 steps: - name: Determine coverage options @@ -112,8 +236,7 @@ jobs: - name: Check out source code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} + ref: ${{ needs.setup.outputs.source_sha }} path: ${{ needs.setup.outputs.checkout_path }} repository: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || @@ -291,6 +414,15 @@ jobs: - name: Prepare coverage artifact bundle if: ${{ steps.report_gcc.outcome != 'skipped' || steps.report_clang.outcome != 'skipped' }} shell: bash + env: + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + SOURCE_REPO: + ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || + needs.setup.outputs.repo }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + ARCH: ${{ matrix.arch }} working-directory: ${{ needs.setup.outputs.build_path }} run: | set -euo pipefail @@ -311,6 +443,25 @@ jobs: done if [ -d coverage-html ]; then cp -R coverage-html "$ARTIFACT_DIR/"; fi if [ -d coverage-python-html ]; then cp -R coverage-python-html "$ARTIFACT_DIR/"; fi + python3 - "$ARTIFACT_DIR/provenance.json" <<'PY' + import json + import sys + from pathlib import Path + + import os + + metadata = { + "source_sha": os.environ["SOURCE_SHA"], + "source_repo": os.environ["SOURCE_REPO"], + "workflow_ref": os.environ["WORKFLOW_REF"], + "run_id": os.environ["RUN_ID"], + "run_attempt": os.environ["RUN_ATTEMPT"], + "arch": os.environ["ARCH"], + } + if not metadata["source_repo"]: + raise SystemExit("The source repository could not be resolved") + Path(sys.argv[1]).write_text(json.dumps(metadata, sort_keys=True) + "\n", encoding="utf-8") + PY - name: Detect artifact upload availability id: artifact_runtime @@ -344,7 +495,7 @@ jobs: steps.artifact_runtime.outputs.available == 'true' && github.actor != 'nektos/act' }} uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: coverage-generated-${{ matrix.arch }} + name: coverage-generated-${{ matrix.arch }}-${{ github.run_attempt }} path: coverage-artifacts/ retention-days: 30 @@ -356,27 +507,57 @@ jobs: always() && needs.setup.result == 'success' && needs.coverage.result != 'skipped' && needs.coverage.result != 'cancelled' && github.actor != 'nektos/act' runs-on: ubuntu-latest - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - + permissions: + actions: read + contents: read + pull-requests: read + outputs: + source_current: ${{ steps.current_source.outputs.is_current }} steps: - name: Check out source code for Codecov mapping uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} + ref: ${{ needs.setup.outputs.source_sha }} repository: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || needs.setup.outputs.repo }} fetch-depth: 0 persist-credentials: false + - name: Check out trusted Codecov CLI version + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.event.pull_request.base.sha || github.workflow_sha }} + path: codecov-tools + sparse-checkout: .github/codecov/requirements.txt + persist-credentials: false + + - name: Resolve pinned Codecov CLI version + id: codecov_cli + run: | + python3 - <<'PY' >> "$GITHUB_OUTPUT" + import re + from pathlib import Path + + requirements = Path("codecov-tools/.github/codecov/requirements.txt").read_text(encoding="utf-8") + pins = [line.strip() for line in requirements.splitlines() + if line.strip() and not line.lstrip().startswith("#")] + match = re.fullmatch(r"codecov-cli==([0-9]+\.[0-9]+\.[0-9]+)", pins[0]) if len(pins) == 1 else None + if match is None: + raise SystemExit("Expected one exact codecov-cli version pin") + print(f"version=v{match.group(1)}") + PY + + - name: Create trusted empty Codecov configuration + run: printf '{}\n' > "$RUNNER_TEMP/codecov-upload.yml" + - name: Download amd64 coverage bundle if: always() continue-on-error: true uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - name: coverage-generated-amd64 + name: coverage-generated-amd64-${{ github.run_attempt }} path: coverage-artifacts/coverage-generated-amd64 - name: Download arm64 coverage bundle @@ -384,9 +565,63 @@ jobs: continue-on-error: true uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 with: - name: coverage-generated-arm64 + name: coverage-generated-arm64-${{ github.run_attempt }} path: coverage-artifacts/coverage-generated-arm64 + - name: Validate coverage artifact provenance and paths + env: + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + SOURCE_REPO: + ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || + needs.setup.outputs.repo }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + run: | + python3 - <<'PY' + import json + import os + import re + from pathlib import Path + + root = Path("coverage-artifacts") + if root.is_symlink(): + raise SystemExit("Coverage artifact root must not be a symlink") + expected_base = { + "source_sha": os.environ["SOURCE_SHA"], + "source_repo": os.environ["SOURCE_REPO"], + "workflow_ref": os.environ["WORKFLOW_REF"], + "run_id": os.environ["RUN_ID"], + "run_attempt": os.environ["RUN_ATTEMPT"], + } + if re.fullmatch(r"[0-9a-f]{40}", expected_base["source_sha"]) is None: + raise SystemExit("Expected a full source SHA for the coverage artifact") + + for arch in ("amd64", "arm64"): + report_dir = root / f"coverage-generated-{arch}" + if not report_dir.exists() and not report_dir.is_symlink(): + continue + if report_dir.is_symlink() or not report_dir.is_dir(): + raise SystemExit(f"Invalid coverage artifact directory: {report_dir}") + manifest = report_dir / "provenance.json" + if manifest.is_symlink() or not manifest.is_file(): + raise SystemExit(f"Missing regular provenance manifest: {manifest}") + metadata = json.loads(manifest.read_text(encoding="utf-8")) + expected = {**expected_base, "arch": arch} + if metadata != expected: + raise SystemExit(f"Coverage artifact provenance mismatch for {arch}") + for name in ("coverage.xml", "coverage-llvm.info", "coverage-python.xml"): + report = report_dir / name + if report.is_symlink(): + raise SystemExit(f"Coverage report must not be a symlink: {report}") + if report.exists() and (not report.is_file() or report.stat().st_size > 536870912): + raise SystemExit(f"Invalid or oversized coverage report: {report}") + for name in ("coverage-html", "coverage-python-html"): + html = report_dir / name + if html.is_symlink(): + raise SystemExit(f"Coverage HTML path must not be a symlink: {html}") + PY + - name: Determine coverage files for each architecture id: codecov_targets env: @@ -444,42 +679,107 @@ jobs: exit 1 fi + - name: Verify the source branch still matches this run + id: current_source + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + TARGET_REPO: ${{ needs.setup.outputs.repo }} + PR_NUMBER: >- + ${{ github.event_name == 'pull_request' && github.event.pull_request.number || needs.setup.outputs.pr_number + }} + with: + script: | + const { owner, repo } = context.repo; + let isCurrent = true; + if (context.eventName === 'pull_request' || context.eventName === 'issue_comment') { + const pullNumber = context.eventName === 'pull_request' + ? context.payload.pull_request.number + : Number(process.env.PR_NUMBER); + const { data: pull } = await github.rest.pulls.get({ + owner, + repo, + pull_number: pullNumber + }); + const expectedRepo = context.eventName === 'pull_request' + ? context.payload.pull_request.head.repo?.full_name + : process.env.TARGET_REPO; + const expectedRef = context.eventName === 'pull_request' + ? context.payload.pull_request.head.ref + : process.env.TARGET_REF; + isCurrent = pull.head.sha === process.env.SOURCE_SHA && + pull.head.ref === expectedRef && + pull.head.repo?.full_name === expectedRepo; + } else if (context.eventName === 'workflow_dispatch') { + const branchName = process.env.TARGET_REF.replace(/^refs\/heads\//, ''); + const { data: branch } = await github.rest.repos.getBranch({ owner, repo, branch: branchName }); + isCurrent = process.env.TARGET_REPO === `${owner}/${repo}` && + context.ref === `refs/heads/${branchName}` && + context.sha === process.env.SOURCE_SHA && branch.commit.sha === process.env.SOURCE_SHA; + } else if (context.eventName === 'push' && context.ref.startsWith('refs/heads/')) { + const branchName = context.ref.replace(/^refs\/heads\//, ''); + const { data: branch } = await github.rest.repos.getBranch({ owner, repo, branch: branchName }); + isCurrent = branch.commit.sha === process.env.SOURCE_SHA; + } + core.setOutput('is_current', String(isCurrent)); + if (!isCurrent) console.log('Skipping coverage upload for a moved source branch.'); + - name: Upload amd64 coverage to Codecov - if: ${{ always() && steps.codecov_targets.outputs.amd64_found == 'true' }} + if: >- + always() && steps.codecov_cli.outcome == 'success' && steps.codecov_targets.outputs.amd64_found == 'true' && + steps.current_source.outputs.is_current == 'true' uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: + version: ${{ steps.codecov_cli.outputs.version }} files: ${{ steps.codecov_targets.outputs.amd64_files }} flags: amd64 name: phlex-framework-coverage-amd64 fail_ci_if_error: true verbose: true root_dir: . - token: ${{ env.CODECOV_TOKEN }} + cleanup: true + disable_search: true + plugins: noop + codecov_yml_path: ${{ runner.temp }}/codecov-upload.yml + token: ${{ secrets.CODECOV_TOKEN }} - name: Upload arm64 coverage to Codecov - if: ${{ always() && steps.codecov_targets.outputs.arm64_found == 'true' }} + if: >- + always() && steps.codecov_cli.outcome == 'success' && steps.codecov_targets.outputs.arm64_found == 'true' && + steps.current_source.outputs.is_current == 'true' uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: + version: ${{ steps.codecov_cli.outputs.version }} files: ${{ steps.codecov_targets.outputs.arm64_files }} flags: arm64 name: phlex-framework-coverage-arm64 fail_ci_if_error: true verbose: true root_dir: . - token: ${{ env.CODECOV_TOKEN }} + cleanup: true + disable_search: true + plugins: noop + codecov_yml_path: ${{ runner.temp }}/codecov-upload.yml + token: ${{ secrets.CODECOV_TOKEN }} - name: Publish HTML coverage report - if: ${{ always() && steps.codecov_targets.outputs.has_html == 'true' }} + if: >- + always() && steps.codecov_targets.outputs.has_html == 'true' && steps.current_source.outputs.is_current == + 'true' uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - name: coverage-html-report + name: coverage-html-report-${{ github.run_attempt }} path: ${{ steps.codecov_targets.outputs.html_path }}/ if-no-files-found: warn retention-days: 30 coverage-complete: needs: [setup, coverage, coverage-upload] - if: always() && github.event_name == 'issue_comment' && needs.setup.result == 'success' + if: >- + always() && github.event_name == 'issue_comment' && needs.setup.result == 'success' && + needs.coverage-upload.outputs.source_current == 'true' runs-on: ubuntu-latest permissions: pull-requests: write @@ -519,6 +819,10 @@ jobs: message: | Coverage workflow completed. + Source snapshot: `${{ needs.setup.outputs.source_sha }}`. + To rerun against the current PR head, comment + `@${{ github.event.repository.name }}bot coverage`. + **Result:** ${{ (needs.coverage.result == 'failure' || needs.coverage-upload.result == 'failure') && '❌ Coverage analysis failed.' || (needs.coverage.result == 'cancelled' || needs.coverage-upload.result == 'cancelled') @@ -527,7 +831,8 @@ jobs: || needs.coverage.result == 'skipped' && 'ℹ️ No relevant changes detected; coverage skipped.' || format('ℹ️ Coverage completed with status: {0}.', needs.coverage.result) }} - See the [workflow run](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}) for detailed results. + See the workflow run for detailed results: + [${{ github.run_id }}](${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}). diff --git a/.github/workflows/format-all.yaml b/.github/workflows/format-all.yaml index eb924c761..06b412cbb 100644 --- a/.github/workflows/format-all.yaml +++ b/.github/workflows/format-all.yaml @@ -1,15 +1,14 @@ name: Format All run-name: "${{ github.actor }} fixing all format issues" -on: +"on": issue_comment: types: - created permissions: - pull-requests: write - contents: write - issues: write + pull-requests: read + contents: read jobs: setup: @@ -21,6 +20,8 @@ jobs: outputs: ref: ${{ steps.setup.outputs.ref }} repo: ${{ steps.setup.outputs.repo }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup @@ -28,14 +29,31 @@ jobs: with: mode: fix + - name: Check out trusted source authorization action + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/resolve-fix-snapshot + persist-credentials: false + + - name: Resolve approved source snapshot + id: source_snapshot + uses: ./workflow-tools/.github/actions/resolve-fix-snapshot + with: + command: format + ref: ${{ steps.setup.outputs.ref }} + repo: ${{ steps.setup.outputs.repo }} + clang-format: needs: setup uses: ./.github/workflows/clang-format-fix.yaml with: ref: ${{ needs.setup.outputs.ref }} repo: ${{ needs.setup.outputs.repo }} + source-sha: ${{ needs.setup.outputs.source_sha }} skip-comment: true - secrets: inherit cmake-format: needs: setup @@ -43,8 +61,8 @@ jobs: with: ref: ${{ needs.setup.outputs.ref }} repo: ${{ needs.setup.outputs.repo }} + source-sha: ${{ needs.setup.outputs.source_sha }} skip-comment: true - secrets: inherit header-guards: needs: setup @@ -52,8 +70,8 @@ jobs: with: ref: ${{ needs.setup.outputs.ref }} repo: ${{ needs.setup.outputs.repo }} + source-sha: ${{ needs.setup.outputs.source_sha }} skip-comment: true - secrets: inherit jsonnet-format: needs: setup @@ -61,8 +79,8 @@ jobs: with: ref: ${{ needs.setup.outputs.ref }} repo: ${{ needs.setup.outputs.repo }} + source-sha: ${{ needs.setup.outputs.source_sha }} skip-comment: true - secrets: inherit markdown: needs: setup @@ -70,8 +88,8 @@ jobs: with: ref: ${{ needs.setup.outputs.ref }} repo: ${{ needs.setup.outputs.repo }} + source-sha: ${{ needs.setup.outputs.source_sha }} skip-comment: true - secrets: inherit python: needs: setup @@ -79,8 +97,8 @@ jobs: with: ref: ${{ needs.setup.outputs.ref }} repo: ${{ needs.setup.outputs.repo }} + source-sha: ${{ needs.setup.outputs.source_sha }} skip-comment: true - secrets: inherit yaml: needs: setup @@ -88,13 +106,18 @@ jobs: with: ref: ${{ needs.setup.outputs.ref }} repo: ${{ needs.setup.outputs.repo }} + source-sha: ${{ needs.setup.outputs.source_sha }} skip-comment: true - secrets: inherit combine-results: needs: [setup, clang-format, cmake-format, header-guards, jsonnet-format, markdown, python, yaml] if: always() && needs.setup.result == 'success' runs-on: ubuntu-latest + permissions: + actions: read + contents: read + issues: write + pull-requests: write steps: - name: Collect results id: collect @@ -102,19 +125,69 @@ jobs: with: results-json: | { - "clang-format": { "result": "${{ needs.clang-format.result }}", "changes": "${{ needs.clang-format.outputs.changes }}", "pushed": "${{ needs.clang-format.outputs.pushed }}", "sha": "${{ needs.clang-format.outputs.commit_sha_short }}", "patch_name": "${{ needs.clang-format.outputs.patch_name }}" }, - "cmake-format": { "result": "${{ needs.cmake-format.result }}", "changes": "${{ needs.cmake-format.outputs.changes }}", "pushed": "${{ needs.cmake-format.outputs.pushed }}", "sha": "${{ needs.cmake-format.outputs.commit_sha_short }}", "patch_name": "${{ needs.cmake-format.outputs.patch_name }}" }, - "header-guards": { "result": "${{ needs.header-guards.result }}", "changes": "${{ needs.header-guards.outputs.changes }}", "pushed": "${{ needs.header-guards.outputs.pushed }}", "sha": "${{ needs.header-guards.outputs.commit_sha_short }}", "patch_name": "${{ needs.header-guards.outputs.patch_name }}" }, - "jsonnetfmt": { "result": "${{ needs.jsonnet-format.result }}", "changes": "${{ needs.jsonnet-format.outputs.changes }}", "pushed": "${{ needs.jsonnet-format.outputs.pushed }}", "sha": "${{ needs.jsonnet-format.outputs.commit_sha_short }}", "patch_name": "${{ needs.jsonnet-format.outputs.patch_name }}" }, - "markdownlint": { "result": "${{ needs.markdown.result }}", "changes": "${{ needs.markdown.outputs.changes }}", "pushed": "${{ needs.markdown.outputs.pushed }}", "sha": "${{ needs.markdown.outputs.commit_sha_short }}", "patch_name": "${{ needs.markdown.outputs.patch_name }}" }, - "ruff": { "result": "${{ needs.python.result }}", "changes": "${{ needs.python.outputs.changes }}", "pushed": "${{ needs.python.outputs.pushed }}", "sha": "${{ needs.python.outputs.commit_sha_short }}", "patch_name": "${{ needs.python.outputs.patch_name }}" }, - "YAML formatter": { "result": "${{ needs.yaml.result }}", "changes": "${{ needs.yaml.outputs.changes }}", "pushed": "${{ needs.yaml.outputs.pushed }}", "sha": "${{ needs.yaml.outputs.commit_sha_short }}", "patch_name": "${{ needs.yaml.outputs.patch_name }}" } + "clang-format": { + "result": "${{ needs.clang-format.result }}", + "changes": "${{ needs.clang-format.outputs.changes }}", + "pushed": "${{ needs.clang-format.outputs.pushed }}", + "sha": "${{ needs.clang-format.outputs.commit_sha_short }}", + "patch_name": "${{ needs.clang-format.outputs.patch_name }}" + }, + "cmake-format": { + "result": "${{ needs.cmake-format.result }}", + "changes": "${{ needs.cmake-format.outputs.changes }}", + "pushed": "${{ needs.cmake-format.outputs.pushed }}", + "sha": "${{ needs.cmake-format.outputs.commit_sha_short }}", + "patch_name": "${{ needs.cmake-format.outputs.patch_name }}" + }, + "header-guards": { + "result": "${{ needs.header-guards.result }}", + "changes": "${{ needs.header-guards.outputs.changes }}", + "pushed": "${{ needs.header-guards.outputs.pushed }}", + "sha": "${{ needs.header-guards.outputs.commit_sha_short }}", + "patch_name": "${{ needs.header-guards.outputs.patch_name }}" + }, + "jsonnetfmt": { + "result": "${{ needs.jsonnet-format.result }}", + "changes": "${{ needs.jsonnet-format.outputs.changes }}", + "pushed": "${{ needs.jsonnet-format.outputs.pushed }}", + "sha": "${{ needs.jsonnet-format.outputs.commit_sha_short }}", + "patch_name": "${{ needs.jsonnet-format.outputs.patch_name }}" + }, + "markdownlint": { + "result": "${{ needs.markdown.result }}", + "changes": "${{ needs.markdown.outputs.changes }}", + "pushed": "${{ needs.markdown.outputs.pushed }}", + "sha": "${{ needs.markdown.outputs.commit_sha_short }}", + "patch_name": "${{ needs.markdown.outputs.patch_name }}" + }, + "ruff": { + "result": "${{ needs.python.result }}", + "changes": "${{ needs.python.outputs.changes }}", + "pushed": "${{ needs.python.outputs.pushed }}", + "sha": "${{ needs.python.outputs.commit_sha_short }}", + "patch_name": "${{ needs.python.outputs.patch_name }}" + }, + "YAML formatter": { + "result": "${{ needs.yaml.result }}", + "changes": "${{ needs.yaml.outputs.changes }}", + "pushed": "${{ needs.yaml.outputs.pushed }}", + "sha": "${{ needs.yaml.outputs.commit_sha_short }}", + "patch_name": "${{ needs.yaml.outputs.patch_name }}" + } } - name: Post combined comment uses: thollander/actions-comment-pull-request@24bffb9b452ba05a4f3f77933840a6a841d1b32b # v3.0.1 with: - message: ${{ steps.collect.outputs.message }} + message: | + ${{ steps.collect.outputs.message }} + + All formatters used approved source snapshot + `${{ needs.setup.outputs.source_sha }}` and did not push changes. + Download [patch artifacts][artifacts] from this workflow run. + Review and apply each patch only to that exact source snapshot. + + [artifacts]: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}#artifacts - name: Update PR comment reactions uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 diff --git a/.github/workflows/header-guards-fix.yaml b/.github/workflows/header-guards-fix.yaml index d3df10864..51dd13211 100644 --- a/.github/workflows/header-guards-fix.yaml +++ b/.github/workflows/header-guards-fix.yaml @@ -24,6 +24,10 @@ run-name: "${{ github.actor }} fixing header guards" required: false type: boolean default: false + source-sha: + description: "Exact 40-character source SHA to format" + required: false + type: string outputs: changes: description: "Whether any fixes were applied" @@ -48,11 +52,14 @@ run-name: "${{ github.actor }} fixing header guards" repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character source SHA to format" + required: true + type: string permissions: - pull-requests: write - contents: write - issues: write + pull-requests: read + contents: read jobs: setup: @@ -69,6 +76,8 @@ jobs: ref: ${{ steps.setup.outputs.ref }} repo: ${{ steps.setup.outputs.repo }} checkout_path: ${{ steps.setup.outputs.checkout_path }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup @@ -79,25 +88,55 @@ jobs: repo: ${{ inputs.repo }} checkout-path: ${{ inputs.checkout-path }} + - name: Check out trusted snapshot action and patch tool + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: | + .github/actions/resolve-fix-snapshot + scripts/create_fix_patch.py + persist-credentials: false + + - name: Resolve approved source snapshot + id: source_snapshot + uses: ./workflow-tools/.github/actions/resolve-fix-snapshot + with: + command: header-guards-fix + ref: ${{ steps.setup.outputs.ref }} + repo: ${{ steps.setup.outputs.repo }} + source-sha: ${{ inputs.source-sha }} + apply_fixes: runs-on: ubuntu-latest name: Apply fixes needs: setup if: needs.setup.result == 'success' outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} + changes: ${{ steps.prepare_patch.outputs.changes }} + pushed: ${{ steps.prepare_patch.outputs.pushed }} + commit_sha: ${{ steps.prepare_patch.outputs.commit_sha }} + commit_sha_short: ${{ steps.prepare_patch.outputs.commit_sha_short }} + patch_name: ${{ steps.prepare_patch.outputs.patch_name }} steps: - - name: Checkout code + - name: Check out trusted patch tools + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: | + scripts/create_fix_patch.py + scripts/fix_header_guards.py + persist-credentials: false + + - name: Check out immutable source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} + ref: ${{ needs.setup.outputs.source_sha }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false - name: Set up Python @@ -107,23 +146,65 @@ jobs: - name: Fix header guards working-directory: ${{ needs.setup.outputs.checkout_path }} + env: + CHECKOUT_PATH: ${{ needs.setup.outputs.checkout_path }} run: | echo "Fixing header guards..." - python3 scripts/fix_header_guards.py --root . phlex plugins form || true + python3 "$GITHUB_WORKSPACE/workflow-tools/scripts/fix_header_guards.py" \ + --root "$GITHUB_WORKSPACE/$CHECKOUT_PATH" \ + "$GITHUB_WORKSPACE/$CHECKOUT_PATH/phlex" \ + "$GITHUB_WORKSPACE/$CHECKOUT_PATH/plugins" \ + "$GITHUB_WORKSPACE/$CHECKOUT_PATH/form" + + - name: Prepare patch artifact + id: prepare_patch + env: + SOURCE_PATH: ${{ needs.setup.outputs.checkout_path }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + TARGET_REPO: ${{ needs.setup.outputs.source_repo }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + TOOL: header-guards + run: python3 "$GITHUB_WORKSPACE/workflow-tools/scripts/create_fix_patch.py" - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 + - name: Upload patch artifact + if: steps.prepare_patch.outputs.changes == 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - tool: header-guards - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} + name: ${{ steps.prepare_patch.outputs.artifact_name }} + path: ${{ steps.prepare_patch.outputs.artifact_path }} + retention-days: 7 + if-no-files-found: error - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 + report: + name: Report patch artifact + needs: [setup, apply_fixes] + if: >- + github.event_name == 'issue_comment' && !inputs.skip-comment && needs.setup.result == 'success' && + needs.apply_fixes.result == 'success' + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + issues: write + pull-requests: read + steps: + - name: Check out trusted report action + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - status: ${{ job.status }} + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/report-fix-patch + persist-credentials: false + + - name: Report immutable patch result + uses: ./workflow-tools/.github/actions/report-fix-patch + with: + tool: header-guards + source-sha: ${{ needs.setup.outputs.source_sha }} + changes: ${{ needs.apply_fixes.outputs.changes }} + patch-name: ${{ needs.apply_fixes.outputs.patch_name }} + run-id: ${{ github.run_id }} diff --git a/.github/workflows/jsonnet-format-fix.yaml b/.github/workflows/jsonnet-format-fix.yaml index 82504b308..6113ce4dc 100644 --- a/.github/workflows/jsonnet-format-fix.yaml +++ b/.github/workflows/jsonnet-format-fix.yaml @@ -13,6 +13,10 @@ run-name: "${{ github.actor }} fixing Jsonnet format" repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character source SHA to format" + required: true + type: string workflow_call: inputs: checkout-path: @@ -32,6 +36,10 @@ run-name: "${{ github.actor }} fixing Jsonnet format" required: false type: boolean default: false + source-sha: + description: "Exact 40-character source SHA to format" + required: false + type: string outputs: changes: description: "Whether any fixes were applied" @@ -50,9 +58,8 @@ run-name: "${{ github.actor }} fixing Jsonnet format" value: ${{ jobs.apply_jsonnet_formatting.outputs.patch_name }} permissions: - pull-requests: write - contents: write - issues: write + pull-requests: read + contents: read jobs: setup: @@ -69,6 +76,8 @@ jobs: ref: ${{ steps.setup.outputs.ref }} repo: ${{ steps.setup.outputs.repo }} checkout_path: ${{ steps.setup.outputs.checkout_path }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup @@ -79,26 +88,54 @@ jobs: repo: ${{ inputs.repo }} checkout-path: ${{ inputs.checkout-path }} + - name: Check out trusted snapshot action and patch tool + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: | + .github/actions/resolve-fix-snapshot + scripts/create_fix_patch.py + persist-credentials: false + + - name: Resolve approved source snapshot + id: source_snapshot + uses: ./workflow-tools/.github/actions/resolve-fix-snapshot + with: + command: jsonnet-fix + ref: ${{ steps.setup.outputs.ref }} + repo: ${{ steps.setup.outputs.repo }} + source-sha: ${{ inputs.source-sha }} + apply_jsonnet_formatting: runs-on: ubuntu-latest name: Apply Jsonnet formatting needs: setup if: needs.setup.result == 'success' outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} + changes: ${{ steps.prepare_patch.outputs.changes }} + pushed: ${{ steps.prepare_patch.outputs.pushed }} + commit_sha: ${{ steps.prepare_patch.outputs.commit_sha }} + commit_sha_short: ${{ steps.prepare_patch.outputs.commit_sha_short }} + patch_name: ${{ steps.prepare_patch.outputs.patch_name }} steps: - - name: Checkout code + - name: Check out trusted patch tool + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: scripts/create_fix_patch.py + persist-credentials: false + + - name: Check out immutable source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} + ref: ${{ needs.setup.outputs.source_sha }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false - name: Setup jsonnet @@ -116,19 +153,55 @@ jobs: find "$CHECKOUT_PATH" \( -name '*.jsonnet' -o -name '*.libsonnet' \) -print0 | xargs -0 -r jsonnetfmt -i continue-on-error: true - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 + - name: Prepare patch artifact + id: prepare_patch + env: + SOURCE_PATH: ${{ needs.setup.outputs.checkout_path }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + TARGET_REPO: ${{ needs.setup.outputs.source_repo }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + TOOL: jsonnetfmt + run: python3 "$GITHUB_WORKSPACE/workflow-tools/scripts/create_fix_patch.py" + + - name: Upload patch artifact + if: steps.prepare_patch.outputs.changes == 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - tool: jsonnetfmt - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} + name: ${{ steps.prepare_patch.outputs.artifact_name }} + path: ${{ steps.prepare_patch.outputs.artifact_path }} + retention-days: 7 + if-no-files-found: error + + report: + name: Report patch artifact + needs: [setup, apply_jsonnet_formatting] + if: >- + github.event_name == 'issue_comment' && !inputs.skip-comment && needs.setup.result == 'success' && + needs.apply_jsonnet_formatting.result == 'success' + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + issues: write + pull-requests: read + steps: + - name: Check out trusted report action + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/report-fix-patch + persist-credentials: false - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 + - name: Report immutable patch result + uses: ./workflow-tools/.github/actions/report-fix-patch with: - status: ${{ job.status }} + tool: jsonnetfmt + source-sha: ${{ needs.setup.outputs.source_sha }} + changes: ${{ needs.apply_jsonnet_formatting.outputs.changes }} + patch-name: ${{ needs.apply_jsonnet_formatting.outputs.patch_name }} + run-id: ${{ github.run_id }} diff --git a/.github/workflows/markdown-fix.yaml b/.github/workflows/markdown-fix.yaml index b6a0ac939..ae0498737 100644 --- a/.github/workflows/markdown-fix.yaml +++ b/.github/workflows/markdown-fix.yaml @@ -24,6 +24,10 @@ run-name: "${{ github.actor }} fixing Markdown format" required: false type: boolean default: false + source-sha: + description: "Exact 40-character source SHA to format" + required: false + type: string outputs: changes: description: "Whether any fixes were applied" @@ -48,11 +52,14 @@ run-name: "${{ github.actor }} fixing Markdown format" repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character source SHA to format" + required: true + type: string permissions: - pull-requests: write - contents: write - issues: write + pull-requests: read + contents: read jobs: setup: @@ -69,6 +76,8 @@ jobs: ref: ${{ steps.setup.outputs.ref }} repo: ${{ steps.setup.outputs.repo }} checkout_path: ${{ steps.setup.outputs.checkout_path }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup @@ -79,17 +88,38 @@ jobs: repo: ${{ inputs.repo }} checkout-path: ${{ inputs.checkout-path }} + - name: Check out trusted snapshot action and patch tool + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: | + .github/actions/resolve-fix-snapshot + scripts/create_fix_patch.py + scripts/run_markdownlint_sandbox.py + persist-credentials: false + + - name: Resolve approved source snapshot + id: source_snapshot + uses: ./workflow-tools/.github/actions/resolve-fix-snapshot + with: + command: markdown-fix + ref: ${{ steps.setup.outputs.ref }} + repo: ${{ steps.setup.outputs.repo }} + source-sha: ${{ inputs.source-sha }} + apply_fixes: runs-on: ubuntu-latest name: Apply fixes needs: setup if: needs.setup.result == 'success' outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} + changes: ${{ steps.prepare_patch.outputs.changes }} + pushed: ${{ steps.prepare_patch.outputs.pushed }} + commit_sha: ${{ steps.prepare_patch.outputs.commit_sha }} + commit_sha_short: ${{ steps.prepare_patch.outputs.commit_sha_short }} + patch_name: ${{ steps.prepare_patch.outputs.patch_name }} steps: # Resolve tool dependencies from the workflow commit, never the PR branch. - name: Check out formatter dependencies @@ -98,16 +128,19 @@ jobs: repository: ${{ github.repository }} ref: ${{ github.workflow_sha }} path: workflow-tools - sparse-checkout: .github/format-tools + sparse-checkout: | + .github/format-tools + .markdownlint-cli2.yaml + scripts/create_fix_patch.py + scripts/run_markdownlint_sandbox.py persist-credentials: false - - name: Checkout code + - name: Check out immutable source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} + ref: ${{ needs.setup.outputs.source_sha }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false - name: Set up Node.js @@ -123,24 +156,63 @@ jobs: echo "$PWD/node_modules/.bin" >> "$GITHUB_PATH" - name: Run markdownlint-cli2 fix - working-directory: ${{ needs.setup.outputs.checkout_path }} + env: + SOURCE_PATH: ${{ needs.setup.outputs.checkout_path }} + TRUSTED_CONFIG: ${{ github.workspace }}/workflow-tools/.markdownlint-cli2.yaml + MARKDOWNLINT_EXECUTABLE: >- + ${{ github.workspace }}/workflow-tools/.github/format-tools/node_modules/.bin/markdownlint-cli2 run: | - echo "Fixing Markdown format with markdownlint-cli2..." - markdownlint-cli2 --fix "**/*.md" "!**/CHANGELOG.md" || true + python3 "$GITHUB_WORKSPACE/workflow-tools/scripts/run_markdownlint_sandbox.py" - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 + - name: Prepare patch artifact + id: prepare_patch + env: + SOURCE_PATH: ${{ needs.setup.outputs.checkout_path }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + TARGET_REPO: ${{ needs.setup.outputs.source_repo }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + TOOL: markdownlint + run: python3 "$GITHUB_WORKSPACE/workflow-tools/scripts/create_fix_patch.py" + + - name: Upload patch artifact + if: steps.prepare_patch.outputs.changes == 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - tool: markdownlint - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} + name: ${{ steps.prepare_patch.outputs.artifact_name }} + path: ${{ steps.prepare_patch.outputs.artifact_path }} + retention-days: 7 + if-no-files-found: error + + report: + name: Report patch artifact + needs: [setup, apply_fixes] + if: >- + github.event_name == 'issue_comment' && !inputs.skip-comment && needs.setup.result == 'success' && + needs.apply_fixes.result == 'success' + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + issues: write + pull-requests: read + steps: + - name: Check out trusted report action + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/report-fix-patch + persist-credentials: false - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 + - name: Report immutable patch result + uses: ./workflow-tools/.github/actions/report-fix-patch with: - status: ${{ job.status }} + tool: markdownlint + source-sha: ${{ needs.setup.outputs.source_sha }} + changes: ${{ needs.apply_fixes.outputs.changes }} + patch-name: ${{ needs.apply_fixes.outputs.patch_name }} + run-id: ${{ github.run_id }} diff --git a/.github/workflows/python-check.yaml b/.github/workflows/python-check.yaml index ff8d38f77..89bc24ceb 100644 --- a/.github/workflows/python-check.yaml +++ b/.github/workflows/python-check.yaml @@ -12,9 +12,13 @@ permissions: workflow_dispatch: inputs: ref: - description: "The branch, ref, or SHA to checkout. Defaults to the repository's default branch." + description: "Branch whose current head must match source-sha. Defaults to the repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character commit SHA to analyze; required for workflow_dispatch." + required: true + type: string workflow_call: inputs: checkout-path: @@ -42,6 +46,10 @@ permissions: description: "The repository to checkout from" required: false type: string + source-sha: + description: "Immutable source commit SHA for the workflow run" + required: false + type: string jobs: setup: @@ -53,28 +61,149 @@ jobs: base_sha: ${{ steps.setup.outputs.base_sha }} pr_number: ${{ steps.setup.outputs.pr_number }} checkout_path: ${{ steps.setup.outputs.checkout_path }} - has_changes: ${{ steps.setup.outputs.has_changes }} + has_changes: ${{ steps.source_relevance.outputs.has_changes }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup uses: Framework-R-D/action-workflow-setup@f73307dd8c13cb66c2565c9ace32571517b1cea8 # v1 with: - include-globs: | - scripts/** - ci/** - .devcontainer/** - .github/format-tools/** - pyproject.toml head-ref: ${{ inputs.pr-head-sha }} ref: ${{ inputs.ref }} repo: ${{ inputs.repo }} pr-base-sha: ${{ inputs.pr-base-sha }} checkout-path: ${{ inputs.checkout-path }} + - name: Resolve immutable source snapshot + id: source_snapshot + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + REQUESTED_SHA: ${{ inputs.source-sha }} + CALL_SOURCE_SHA: ${{ inputs.pr-head-sha }} + TARGET_REF: ${{ steps.setup.outputs.ref }} + TARGET_REPO: ${{ steps.setup.outputs.repo }} + WORKFLOW_REF: ${{ github.workflow_ref }} + with: + script: | + const { owner, repo } = context.repo; + const shaPattern = /^[0-9a-f]{40}$/i; + let sourceSha; + let sourceRepo; + + if (context.eventName === 'pull_request') { + const head = context.payload.pull_request.head; + if (!head.repo) throw new Error('The PR source repository is unavailable.'); + sourceSha = head.sha; + sourceRepo = head.repo.full_name; + } else if (context.eventName === 'push') { + sourceSha = context.sha; + sourceRepo = `${owner}/${repo}`; + } else if (context.eventName === 'workflow_dispatch') { + const targetRef = process.env.TARGET_REF.replace(/^refs\/heads\//, ''); + const selectedRef = context.ref.replace(/^refs\/heads\//, ''); + if (!shaPattern.test(process.env.REQUESTED_SHA) || + process.env.TARGET_REPO !== `${owner}/${repo}` || + !context.ref.startsWith('refs/heads/') || targetRef !== selectedRef || + process.env.WORKFLOW_REF.split('@').pop() !== context.ref || + process.env.REQUESTED_SHA.toLowerCase() !== context.sha.toLowerCase()) { + throw new Error('Manual runs require this branch, repository, workflow ref, and full source SHA.'); + } + const { data: branch } = await github.rest.repos.getBranch({ owner, repo, branch: targetRef }); + if (branch.commit.sha.toLowerCase() !== process.env.REQUESTED_SHA.toLowerCase()) { + throw new Error('The selected branch head does not match source-sha.'); + } + sourceSha = branch.commit.sha; + sourceRepo = `${owner}/${repo}`; + } else { + sourceRepo = process.env.TARGET_REPO || `${owner}/${repo}`; + const requestedSha = process.env.CALL_SOURCE_SHA || process.env.REQUESTED_SHA; + if (requestedSha) { + if (!shaPattern.test(requestedSha)) throw new Error('The reusable workflow source SHA is invalid.'); + sourceSha = requestedSha; + } else { + const [targetOwner, targetRepo] = sourceRepo.split('/'); + const { data: branch } = await github.rest.repos.getBranch({ + owner: targetOwner, + repo: targetRepo, + branch: process.env.TARGET_REF + }); + sourceSha = branch.commit.sha; + } + } + + core.setOutput('source_sha', sourceSha); + core.setOutput('source_repo', sourceRepo); + - name: Detect relevant changes in immutable source snapshot + id: source_relevance + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + SOURCE_SHA: ${{ steps.source_snapshot.outputs.source_sha }} + SOURCE_REPO: ${{ steps.source_snapshot.outputs.source_repo }} + PR_NUMBER: >- + ${{ steps.setup.outputs.pr_number || github.event.pull_request.number || github.event.issue.number }} + with: + script: | + const includesPath = path => [ + 'scripts/', 'ci/', '.devcontainer/', '.github/format-tools/' + ].some(prefix => path.startsWith(prefix)) || path === 'pyproject.toml'; + let relevant = true; + const changedPaths = []; + if (context.eventName === 'pull_request' || context.eventName === 'issue_comment') { + try { + const pullNumber = Number(process.env.PR_NUMBER); + const { data: before } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber + }); + if (before.head.sha === process.env.SOURCE_SHA && + before.head.repo?.full_name === process.env.SOURCE_REPO) { + for (let page = 1; ; page++) { + const { data: files } = await github.rest.pulls.listFiles({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber, + per_page: 100, + page + }); + changedPaths.push(...files.map(file => file.filename)); + if (files.length < 100 || page === 30) break; + } + const { data: after } = await github.rest.pulls.get({ + owner: context.repo.owner, + repo: context.repo.repo, + pull_number: pullNumber + }); + relevant = after.head.sha !== process.env.SOURCE_SHA || + after.head.repo?.full_name !== process.env.SOURCE_REPO || + changedPaths.length >= 3000 || changedPaths.some(includesPath); + } + } catch (error) { + core.warning(`Could not verify PR relevance; running checks conservatively: ${error.message}`); + relevant = true; + } + } else if (context.eventName === 'push' && context.payload.before && + !/^0+$/.test(context.payload.before)) { + try { + const { data: comparison } = await github.rest.repos.compareCommits({ + owner: context.repo.owner, + repo: context.repo.repo, + base: context.payload.before, + head: process.env.SOURCE_SHA + }); + relevant = comparison.files?.length >= 300 || + (comparison.files || []).some(file => includesPath(file.filename)); + } catch (error) { + core.warning(`Could not verify push relevance; running checks conservatively: ${error.message}`); + relevant = true; + } + } + core.setOutput('has_changes', String(relevant)); python-check: needs: setup if: > - always() && ( + always() && needs.setup.result == 'success' && ( github.event_name == 'workflow_dispatch' || inputs.skip-relevance-check || needs.setup.outputs.has_changes == 'true' @@ -87,19 +216,16 @@ jobs: - name: Checkout code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} + ref: ${{ needs.setup.outputs.source_sha }} path: ${{ needs.setup.outputs.checkout_path }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false - name: Check out trusted Python tooling uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: ${{ github.repository }} - ref: ${{ github.workflow_sha }} + ref: ${{ github.event.pull_request.base.sha || github.workflow_sha }} path: workflow-tools sparse-checkout: | .github/format-tools @@ -145,7 +271,7 @@ jobs: if [ "${{ steps.ruff.outcome }}" = 'success' ] && [ "${{ steps.mypy.outcome }}" = 'success' ]; then echo "✅ Python checks passed." else - echo "::error::Python checks failed. Comment '@${REPO_NAME}bot python-fix' on the PR to attempt auto-fix." + echo "::error::Python checks failed. Comment '@${REPO_NAME}bot python-fix' on the PR to request a fix." exit 1 fi # yamllint enable @@ -153,7 +279,7 @@ jobs: scripts-test: needs: setup if: > - always() && ( + always() && needs.setup.result == 'success' && ( github.event_name == 'workflow_dispatch' || inputs.skip-relevance-check || needs.setup.outputs.has_changes == 'true' @@ -172,26 +298,20 @@ jobs: runs-on: ${{ matrix.runner }} permissions: contents: read - env: - CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} - steps: - name: Checkout code uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - ref: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || needs.setup.outputs.ref }} + ref: ${{ needs.setup.outputs.source_sha }} path: ${{ needs.setup.outputs.checkout_path }} - repository: - ${{ github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name || - needs.setup.outputs.repo }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false - name: Check out trusted Python tooling uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: repository: ${{ github.repository }} - ref: ${{ github.workflow_sha }} + ref: ${{ github.event.pull_request.base.sha || github.workflow_sha }} path: workflow-tools sparse-checkout: .github/format-tools persist-credentials: false @@ -215,14 +335,252 @@ jobs: --cov-report="xml:${GITHUB_WORKSPACE}/coverage-scripts.xml" \ --cov-report=term-missing - - name: Upload scripts coverage to Codecov + - name: Prepare scripts coverage artifact + id: prepare_coverage if: ${{ hashFiles('coverage-scripts.xml') != '' }} + env: + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + SOURCE_REPO: ${{ needs.setup.outputs.source_repo }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + ARCH: ${{ matrix.arch }} + run: | + set -euo pipefail + if [ -L coverage-scripts.xml ] || [ ! -f coverage-scripts.xml ]; then + echo "::error::Scripts coverage output must be a regular file." + exit 1 + fi + ARTIFACT_DIR=$(mktemp -d "$RUNNER_TEMP/coverage-scripts.XXXXXXXX") + cp -- coverage-scripts.xml "$ARTIFACT_DIR/" + python3 - "$ARTIFACT_DIR/provenance.json" <<'PY' + import json + import os + import sys + from pathlib import Path + + metadata = { + "source_sha": os.environ["SOURCE_SHA"], + "source_repo": os.environ["SOURCE_REPO"], + "workflow_ref": os.environ["WORKFLOW_REF"], + "run_id": os.environ["RUN_ID"], + "run_attempt": os.environ["RUN_ATTEMPT"], + "arch": os.environ["ARCH"], + } + Path(sys.argv[1]).write_text(json.dumps(metadata, sort_keys=True) + "\n", encoding="utf-8") + PY + echo "artifact_dir=$ARTIFACT_DIR" >> "$GITHUB_OUTPUT" + + - name: Upload scripts coverage artifact + if: steps.prepare_coverage.outcome == 'success' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: coverage-scripts-${{ matrix.arch }}-${{ github.run_attempt }} + path: ${{ steps.prepare_coverage.outputs.artifact_dir }} + retention-days: 7 + if-no-files-found: error + + scripts-coverage-upload: + needs: [setup, scripts-test] + if: >- + always() && needs.setup.result == 'success' && needs.scripts-test.result != 'skipped' && needs.scripts-test.result + != 'cancelled' + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + pull-requests: read + steps: + - name: Check out exact source snapshot + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ needs.setup.outputs.source_repo }} + ref: ${{ needs.setup.outputs.source_sha }} + path: ${{ needs.setup.outputs.checkout_path }} + persist-credentials: false + + - name: Check out trusted Codecov CLI version + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.event.pull_request.base.sha || github.workflow_sha }} + path: codecov-tools + sparse-checkout: .github/codecov/requirements.txt + persist-credentials: false + + - name: Resolve pinned Codecov CLI version + id: codecov_cli + run: | + python3 - <<'PY' >> "$GITHUB_OUTPUT" + import re + from pathlib import Path + + requirements = Path("codecov-tools/.github/codecov/requirements.txt").read_text(encoding="utf-8") + pins = [line.strip() for line in requirements.splitlines() + if line.strip() and not line.lstrip().startswith("#")] + match = re.fullmatch(r"codecov-cli==([0-9]+\.[0-9]+\.[0-9]+)", pins[0]) if len(pins) == 1 else None + if match is None: + raise SystemExit("Expected one exact codecov-cli version pin") + print(f"version=v{match.group(1)}") + PY + + - name: Create trusted empty Codecov configuration + run: printf '{}\n' > "$RUNNER_TEMP/codecov-upload.yml" + + - name: Download amd64 scripts coverage + if: always() + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: coverage-scripts-amd64-${{ github.run_attempt }} + path: coverage-scripts/amd64 + + - name: Download arm64 scripts coverage + if: always() + continue-on-error: true + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: coverage-scripts-arm64-${{ github.run_attempt }} + path: coverage-scripts/arm64 + + - name: Validate scripts coverage artifacts + id: coverage_artifacts + if: always() + env: + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + SOURCE_REPO: ${{ needs.setup.outputs.source_repo }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + TEST_RESULT: ${{ needs.scripts-test.result }} + run: | + python3 - <<'PY' + import json + import os + from pathlib import Path + + expected_base = { + "source_sha": os.environ["SOURCE_SHA"], + "source_repo": os.environ["SOURCE_REPO"], + "workflow_ref": os.environ["WORKFLOW_REF"], + "run_id": os.environ["RUN_ID"], + "run_attempt": os.environ["RUN_ATTEMPT"], + } + outputs = [] + for arch in ("amd64", "arm64"): + report_dir = Path("coverage-scripts") / arch + manifest = report_dir / "provenance.json" + report = report_dir / "coverage-scripts.xml" + exists = report_dir.exists() or report_dir.is_symlink() + if not exists: + outputs.append(f"{arch}_found=false") + if os.environ["TEST_RESULT"] == "success": + raise SystemExit(f"Successful scripts test job has no {arch} coverage artifact") + continue + if report_dir.is_symlink() or manifest.is_symlink() or report.is_symlink(): + raise SystemExit(f"Scripts coverage artifact contains a symlink: {arch}") + if not manifest.is_file() or not report.is_file() or report.stat().st_size > 536870912: + raise SystemExit(f"Invalid scripts coverage files for {arch}") + if {entry.name for entry in report_dir.iterdir()} != {"provenance.json", "coverage-scripts.xml"}: + raise SystemExit(f"Unexpected files in scripts coverage artifact for {arch}") + metadata = json.loads(manifest.read_text(encoding="utf-8")) + if metadata != {**expected_base, "arch": arch}: + raise SystemExit(f"Scripts coverage provenance mismatch for {arch}") + outputs.extend((f"{arch}_found=true", f"{arch}_file={report}")) + with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as output: + output.write("\n".join(outputs) + "\n") + PY + + - name: Verify the source branch is still current + id: current_source + if: always() + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + env: + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + SOURCE_REPO: ${{ needs.setup.outputs.source_repo }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + PR_NUMBER: ${{ needs.setup.outputs.pr_number }} + with: + script: | + const { owner, repo } = context.repo; + let isCurrent = true; + if (context.eventName === 'pull_request') { + const pull = context.payload.pull_request; + const { data } = await github.rest.pulls.get({ owner, repo, pull_number: pull.number }); + isCurrent = data.head.sha === process.env.SOURCE_SHA && + data.head.ref === pull.head.ref && + data.head.repo?.full_name === process.env.SOURCE_REPO; + } else if (context.eventName === 'workflow_dispatch') { + const branchName = process.env.TARGET_REF.replace(/^refs\/heads\//, ''); + const { data: branch } = await github.rest.repos.getBranch({ + owner, + repo, + branch: branchName + }); + isCurrent = process.env.SOURCE_REPO === `${owner}/${repo}` && + context.ref === `refs/heads/${branchName}` && + context.sha === process.env.SOURCE_SHA && branch.commit.sha === process.env.SOURCE_SHA; + } else if ((context.eventName === 'issue_comment' || context.eventName === 'workflow_call') && + process.env.PR_NUMBER) { + const { data } = await github.rest.pulls.get({ + owner, + repo, + pull_number: Number(process.env.PR_NUMBER) + }); + isCurrent = data.head.sha === process.env.SOURCE_SHA && + data.head.ref === process.env.TARGET_REF && + data.head.repo?.full_name === process.env.SOURCE_REPO; + } else if (context.eventName === 'push' && context.ref.startsWith('refs/heads/')) { + const branchName = context.ref.replace(/^refs\/heads\//, ''); + const { data: branch } = await github.rest.repos.getBranch({ owner, repo, branch: branchName }); + isCurrent = branch.commit.sha === process.env.SOURCE_SHA && context.sha === process.env.SOURCE_SHA; + } else if (context.eventName === 'workflow_call') { + const [sourceOwner, sourceRepo] = process.env.SOURCE_REPO.split('/'); + const branchName = process.env.TARGET_REF.replace(/^refs\/heads\//, ''); + const { data: branch } = await github.rest.repos.getBranch({ + owner: sourceOwner, + repo: sourceRepo, + branch: branchName + }); + isCurrent = branch.commit.sha === process.env.SOURCE_SHA; + } + core.setOutput('is_current', String(isCurrent)); + if (!isCurrent) console.log('Skipping coverage upload for a moved source branch.'); + + - name: Upload amd64 scripts coverage to Codecov + if: >- + always() && steps.codecov_cli.outcome == 'success' && steps.coverage_artifacts.outputs.amd64_found == 'true' + && steps.current_source.outputs.is_current == 'true' + uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 + with: + version: ${{ steps.codecov_cli.outputs.version }} + files: ${{ steps.coverage_artifacts.outputs.amd64_file }} + flags: amd64 + name: phlex-scripts-coverage-amd64 + fail_ci_if_error: false + verbose: true + root_dir: ${{ needs.setup.outputs.checkout_path }} + cleanup: true + disable_search: true + plugins: noop + codecov_yml_path: ${{ runner.temp }}/codecov-upload.yml + token: ${{ secrets.CODECOV_TOKEN }} + + - name: Upload arm64 scripts coverage to Codecov + if: >- + always() && steps.codecov_cli.outcome == 'success' && steps.coverage_artifacts.outputs.arm64_found == 'true' + && steps.current_source.outputs.is_current == 'true' uses: codecov/codecov-action@303a32d7a59b442fa8d48b6a1cc6825c09c847a5 # v7.1.1 with: - files: coverage-scripts.xml - flags: ${{ matrix.arch }} - name: phlex-scripts-coverage-${{ matrix.arch }} + version: ${{ steps.codecov_cli.outputs.version }} + files: ${{ steps.coverage_artifacts.outputs.arm64_file }} + flags: arm64 + name: phlex-scripts-coverage-arm64 fail_ci_if_error: false verbose: true - root_dir: ${{ needs.setup.outputs.checkout_path || '.' }} - token: ${{ env.CODECOV_TOKEN }} + root_dir: ${{ needs.setup.outputs.checkout_path }} + cleanup: true + disable_search: true + plugins: noop + codecov_yml_path: ${{ runner.temp }}/codecov-upload.yml + token: ${{ secrets.CODECOV_TOKEN }} diff --git a/.github/workflows/python-fix.yaml b/.github/workflows/python-fix.yaml index 5ad3b9552..0bafa8572 100644 --- a/.github/workflows/python-fix.yaml +++ b/.github/workflows/python-fix.yaml @@ -13,6 +13,10 @@ run-name: "${{ github.actor }} fixing Python code" repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character source SHA to format" + required: true + type: string workflow_call: inputs: checkout-path: @@ -32,6 +36,10 @@ run-name: "${{ github.actor }} fixing Python code" required: false type: boolean default: false + source-sha: + description: "Exact 40-character source SHA to format" + required: false + type: string outputs: changes: description: "Whether any fixes were applied" @@ -50,9 +58,8 @@ run-name: "${{ github.actor }} fixing Python code" value: ${{ jobs.apply_fixes.outputs.patch_name }} permissions: - pull-requests: write - contents: write - issues: write + pull-requests: read + contents: read jobs: setup: @@ -69,6 +76,8 @@ jobs: ref: ${{ steps.setup.outputs.ref }} repo: ${{ steps.setup.outputs.repo }} checkout_path: ${{ steps.setup.outputs.checkout_path }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup @@ -79,24 +88,41 @@ jobs: repo: ${{ inputs.repo }} checkout-path: ${{ inputs.checkout-path }} + - name: Check out trusted snapshot action + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/resolve-fix-snapshot + persist-credentials: false + + - name: Resolve approved source snapshot + id: source_snapshot + uses: ./workflow-tools/.github/actions/resolve-fix-snapshot + with: + command: python-fix + ref: ${{ steps.setup.outputs.ref }} + repo: ${{ steps.setup.outputs.repo }} + source-sha: ${{ inputs.source-sha }} + apply_fixes: runs-on: ubuntu-latest name: Apply fixes needs: setup if: needs.setup.result == 'success' outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} + changes: ${{ steps.prepare_patch.outputs.changes }} + pushed: ${{ steps.prepare_patch.outputs.pushed }} + commit_sha: ${{ steps.prepare_patch.outputs.commit_sha }} + commit_sha_short: ${{ steps.prepare_patch.outputs.commit_sha_short }} + patch_name: ${{ steps.prepare_patch.outputs.patch_name }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} + ref: ${{ needs.setup.outputs.source_sha }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false - name: Check out trusted Python tooling @@ -108,6 +134,7 @@ jobs: sparse-checkout: | .github/format-tools pyproject.toml + scripts/create_fix_patch.py persist-credentials: false - name: Install uv @@ -131,19 +158,55 @@ jobs: echo "Fixing Python linter issues with ruff" ruff check --config "$GITHUB_WORKSPACE/workflow-tools/pyproject.toml" --fix . || true - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 + - name: Prepare patch artifact + id: prepare_patch + env: + SOURCE_PATH: ${{ needs.setup.outputs.checkout_path }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + TARGET_REPO: ${{ needs.setup.outputs.source_repo }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + TOOL: ruff + run: python3 "$GITHUB_WORKSPACE/workflow-tools/scripts/create_fix_patch.py" + + - name: Upload patch artifact + if: steps.prepare_patch.outputs.changes == 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - tool: ruff - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} + name: ${{ steps.prepare_patch.outputs.artifact_name }} + path: ${{ steps.prepare_patch.outputs.artifact_path }} + retention-days: 7 + if-no-files-found: error - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 + report: + name: Report patch artifact + needs: [setup, apply_fixes] + if: >- + github.event_name == 'issue_comment' && !inputs.skip-comment && needs.setup.result == 'success' && + needs.apply_fixes.result == 'success' + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + issues: write + pull-requests: read + steps: + - name: Check out trusted report action + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - status: ${{ job.status }} + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/report-fix-patch + persist-credentials: false + + - name: Report immutable patch result + uses: ./workflow-tools/.github/actions/report-fix-patch + with: + tool: ruff + source-sha: ${{ needs.setup.outputs.source_sha }} + changes: ${{ needs.apply_fixes.outputs.changes }} + patch-name: ${{ needs.apply_fixes.outputs.patch_name }} + run-id: ${{ github.run_id }} diff --git a/.github/workflows/yaml-fix.yaml b/.github/workflows/yaml-fix.yaml index ab9623210..8495fd950 100644 --- a/.github/workflows/yaml-fix.yaml +++ b/.github/workflows/yaml-fix.yaml @@ -13,6 +13,10 @@ name: YAML Fix repository's default branch." required: false type: string + source-sha: + description: "Exact 40-character source SHA to format" + required: true + type: string workflow_call: inputs: checkout-path: @@ -32,6 +36,10 @@ name: YAML Fix required: false type: boolean default: false + source-sha: + description: "Exact 40-character source SHA to format" + required: false + type: string outputs: changes: description: "Whether any fixes were applied" @@ -50,9 +58,8 @@ name: YAML Fix value: ${{ jobs.apply_yaml_fixes.outputs.patch_name }} permissions: - pull-requests: write - contents: write - issues: write + pull-requests: read + contents: read jobs: setup: @@ -69,6 +76,8 @@ jobs: ref: ${{ steps.setup.outputs.ref }} repo: ${{ steps.setup.outputs.repo }} checkout_path: ${{ steps.setup.outputs.checkout_path }} + source_sha: ${{ steps.source_snapshot.outputs.source_sha }} + source_repo: ${{ steps.source_snapshot.outputs.source_repo }} steps: - name: Workflow setup id: setup @@ -79,17 +88,37 @@ jobs: repo: ${{ inputs.repo }} checkout-path: ${{ inputs.checkout-path }} + - name: Check out trusted snapshot action and patch tool + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: | + .github/actions/resolve-fix-snapshot + scripts/create_fix_patch.py + persist-credentials: false + + - name: Resolve approved source snapshot + id: source_snapshot + uses: ./workflow-tools/.github/actions/resolve-fix-snapshot + with: + command: yaml-fix + ref: ${{ steps.setup.outputs.ref }} + repo: ${{ steps.setup.outputs.repo }} + source-sha: ${{ inputs.source-sha }} + apply_yaml_fixes: runs-on: ubuntu-latest name: Apply YAML fixes needs: setup if: ${{ needs.setup.result == 'success' }} outputs: - changes: ${{ steps.handle_commit.outputs.changes }} - pushed: ${{ steps.handle_commit.outputs.pushed }} - commit_sha: ${{ steps.handle_commit.outputs.commit_sha }} - commit_sha_short: ${{ steps.handle_commit.outputs.commit_sha_short }} - patch_name: ${{ steps.handle_commit.outputs.patch_name }} + changes: ${{ steps.prepare_patch.outputs.changes }} + pushed: ${{ steps.prepare_patch.outputs.pushed }} + commit_sha: ${{ steps.prepare_patch.outputs.commit_sha }} + commit_sha_short: ${{ steps.prepare_patch.outputs.commit_sha_short }} + patch_name: ${{ steps.prepare_patch.outputs.patch_name }} steps: # Resolve tool dependencies from the workflow commit, never the PR branch. @@ -99,16 +128,18 @@ jobs: repository: ${{ github.repository }} ref: ${{ github.workflow_sha }} path: workflow-tools - sparse-checkout: .github/format-tools + sparse-checkout: | + .github/format-tools + .prettierrc.yaml + scripts/create_fix_patch.py persist-credentials: false - - name: Checkout code + - name: Check out immutable source uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: path: ${{ needs.setup.outputs.checkout_path }} - ref: ${{ needs.setup.outputs.ref }} - repository: ${{ needs.setup.outputs.repo }} - token: ${{ secrets.WORKFLOW_PAT }} + ref: ${{ needs.setup.outputs.source_sha }} + repository: ${{ needs.setup.outputs.source_repo }} persist-credentials: false - name: Setup Node.js @@ -126,21 +157,58 @@ jobs: - name: Apply YAML formatting working-directory: ${{ needs.setup.outputs.checkout_path }} run: | - prettier --write '**/*.{yaml,yml}' + prettier --config "$GITHUB_WORKSPACE/workflow-tools/.prettierrc.yaml" \ + --write '**/*.{yaml,yml}' + + - name: Prepare patch artifact + id: prepare_patch + env: + SOURCE_PATH: ${{ needs.setup.outputs.checkout_path }} + SOURCE_SHA: ${{ needs.setup.outputs.source_sha }} + TARGET_REPO: ${{ needs.setup.outputs.source_repo }} + TARGET_REF: ${{ needs.setup.outputs.ref }} + WORKFLOW_REF: ${{ github.workflow_ref }} + RUN_ID: ${{ github.run_id }} + RUN_ATTEMPT: ${{ github.run_attempt }} + TOOL: yaml-format + run: python3 "$GITHUB_WORKSPACE/workflow-tools/scripts/create_fix_patch.py" - - name: Handle fix commit - id: handle_commit - uses: Framework-R-D/action-handle-fix-commit@c01368081dd06cbe5ef47b4a085dc6359a657a7f # v2 + - name: Upload patch artifact + if: steps.prepare_patch.outputs.changes == 'true' + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: - tool: YAML formatter - working-directory: ${{ needs.setup.outputs.checkout_path }} - token: ${{ secrets.WORKFLOW_PAT }} - pr-info-ref: ${{ needs.setup.outputs.ref }} - pr-info-repo: ${{ needs.setup.outputs.repo }} - skip-comment: ${{ inputs.skip-comment }} + name: ${{ steps.prepare_patch.outputs.artifact_name }} + path: ${{ steps.prepare_patch.outputs.artifact_path }} + retention-days: 7 + if-no-files-found: error + + report: + name: Report patch artifact + needs: [setup, apply_yaml_fixes] + if: >- + github.event_name == 'issue_comment' && !inputs.skip-comment && needs.setup.result == 'success' && + needs.apply_yaml_fixes.result == 'success' + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + issues: write + pull-requests: read + steps: + - name: Check out trusted report action + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: ${{ github.repository }} + ref: ${{ github.workflow_sha }} + path: workflow-tools + sparse-checkout: .github/actions/report-fix-patch + persist-credentials: false - - name: Update PR comment reactions - if: always() && github.event_name == 'issue_comment' && !inputs.skip-comment - uses: Framework-R-D/action-complete-pr-comment@5d16749c32fbb7b15503f264dde6e3c98b90b4fb # v2 + - name: Report immutable patch result + uses: ./workflow-tools/.github/actions/report-fix-patch with: - status: ${{ job.status }} + tool: yaml-format + source-sha: ${{ needs.setup.outputs.source_sha }} + changes: ${{ needs.apply_yaml_fixes.outputs.changes }} + patch-name: ${{ needs.apply_yaml_fixes.outputs.patch_name }} + run-id: ${{ github.run_id }} diff --git a/AGENTS.md b/AGENTS.md index 43bd3cb76..ae43282b0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -302,22 +302,20 @@ association). The bot name is `phlexbot` (derived from the repo name). | Comment | Effect | | ------- | ------ | -| `@phlexbot format` | Run **all** format fixers in parallel and push a single combined commit | -| `@phlexbot clang-fix` | clang-format only | -| `@phlexbot cmake-fix` | gersemi (CMake) only | -| `@phlexbot python-fix` | ruff (Python) only | -| `@phlexbot markdown-fix` | markdownlint only | -| `@phlexbot jsonnet-fix` | jsonnetfmt only | -| `@phlexbot yaml-fix` | prettier (YAML) only | -| `@phlexbot header-guards-fix` | Header guard fixer only | -| `@phlexbot tidy-fix [check1,check2,...]` | Apply clang-tidy fixes (optionally scoped to named checks) | -| `@phlexbot tidy-check` | Run clang-tidy check (read-only, posts results) | -| `@phlexbot build` | Trigger cmake-build workflow | -| `@phlexbot coverage` | Trigger coverage workflow | - -Fix workflows push commits directly to the PR branch and require -`WORKFLOW_PAT` to be set as a repository secret on the fork. Check workflows -are read-only and post results as PR comments. +| `@phlexbot format` | Run all formatters in parallel and publish patch artifacts | +| `@phlexbot clang-fix` | clang-format patch only | +| `@phlexbot cmake-fix` | gersemi (CMake) patch only | +| `@phlexbot python-fix` | ruff (Python) patch only | +| `@phlexbot markdown-fix` | markdownlint patch only | +| `@phlexbot jsonnet-fix` | jsonnetfmt patch only | +| `@phlexbot yaml-fix` | prettier (YAML) patch only | +| `@phlexbot header-guards-fix` | Header guard patch only | +| `@phlexbot tidy-fix [check1,check2,...]` | Generate clang-tidy fixes (optionally scoped to named checks) | +| `@phlexbot tidy-check` | Run clang-tidy check against the PR head snapshot | +| `@phlexbot build [combinations]` | Trigger CMake build for the PR head snapshot | +| `@phlexbot coverage` | Trigger coverage for the PR head snapshot | + +Authorized PR-comment commands resolve the current PR head once at workflow start, then check out and record that immutable SHA. Formatter workflows publish patch artifacts only and never push; review and apply each patch only if the PR still points to its recorded SHA. Build, coverage, and clang-tidy commands that execute untrusted project code also use the pinned snapshot and skip or reject stale results. Manual dispatches continue to require an explicit full SHA. ## Local GitHub Actions Testing diff --git a/docs/dev/WORKFLOW_CALLS.md b/docs/dev/WORKFLOW_CALLS.md index 77570c242..1eba63893 100644 --- a/docs/dev/WORKFLOW_CALLS.md +++ b/docs/dev/WORKFLOW_CALLS.md @@ -4,7 +4,7 @@ This document consolidates all information about reusable GitHub Actions workflo * `workflow_call` from another workflow (the primary reuse model) * `workflow_dispatch` for manual runs via the **Actions** tab -* Bot commands in PR comments (e.g. `@phlexbot clang-fix`) +* Patch-only formatter bot commands in PR comments (e.g. `@phlexbot clang-fix`) The same workflows are also automatically triggered by CI events such as `pull_request` and `push` where appropriate. @@ -36,18 +36,16 @@ jobs: uses: Framework-R-D/phlex/.github/workflows/.yaml@ with: # workflow-specific inputs - secrets: - WORKFLOW_PAT: ${{ secrets.WORKFLOW_PAT }} ``` *Prefer pinning to a specific commit SHA* rather than `@main` to avoid unintentionally pulling breaking changes. 1. **Trigger types** * **Check workflows** – `pull_request`, `push`, `workflow_dispatch`, `workflow_call`. They only analyze code. - * **Fix workflows** – `issue_comment` (gated to OWNER/COLLABORATOR/MEMBER), `workflow_dispatch`, `workflow_call`. They modify code and push commits. + * **Fix workflows** – `issue_comment` (gated to OWNER/COLLABORATOR/MEMBER), `workflow_dispatch`, `workflow_call`. They format an immutable source snapshot and publish patch-only artifacts; they never push. -2. **Why `WORKFLOW_PAT` is required** - Commits pushed using the default `GITHUB_TOKEN` do not trigger further workflows (GitHub suppresses them to prevent recursion). A personal access token with write permissions (`WORKFLOW_PAT`) is required for fix workflows to push changes and re-trigger CI. +2. **Source approval** + Authorized PR-comment commands resolve the current PR head once at workflow start, then pin and record that immutable SHA. Formatter commands publish artifacts only and never push; review and apply them only if the PR still points to the recorded SHA. Build, coverage, and clang-tidy commands execute the pinned snapshot and skip or reject stale results. Manual dispatches continue to require an explicit full SHA. --- @@ -57,8 +55,8 @@ Most workflows expose a `workflow_dispatch` trigger. To run one manually: 1. Open the **Actions** tab of the repository (or your fork). 2. Select the desired workflow on the left. -3. Click **Run workflow** and choose a branch/tag/commit. -4. Fill any additional inputs (e.g. `build-combinations` for `cmake-build`). +3. Choose the workflow branch to execute. +4. Fill any workflow-specific inputs (e.g. `build-combinations` for `cmake-build`) and provide `source-sha` where required. 5. Click **Run workflow**. ### Example (cmake-build) @@ -67,7 +65,8 @@ Most workflows expose a `workflow_dispatch` trigger. To run one manually: uses: ./.github/workflows/cmake-build.yaml with: build-combinations: "gcc/asan clang/tsan" - ref: refs/heads/main + ref: main + source-sha: ``` --- @@ -77,18 +76,12 @@ with: If you develop on a fork of `Framework-R-D/phlex`: * **Enable Actions** on the fork (click the *I understand my workflows…* button on the **Actions** tab). -* **Create a Personal Access Token** with `repo` scope (both `Contents` and `Pull requests` write permissions) and add it as a secret named `WORKFLOW_PAT` in the fork’s repository settings. -* Bot commands use the fork-derived bot name (e.g. `@my-phlexbot clang-fix`). - -### Creating a PAT - -1. Follow GitHub’s guide to create a fine-grained PAT. -2. Grant **Contents: Read & write** and **Pull requests: Read & write**. -3. Add the token as a repository secret `WORKFLOW_PAT` (`Settings → Secrets and variables → Actions`). +* Bot commands in the base repository use the base-repository bot name (e.g. `@phlexbot clang-fix`). +* Fix workflows need no write token: they resolve the PR head once and return a patch artifact, which must be reviewed and applied manually to that exact SHA. ### Authorization Model -Comment-triggered workflows (e.g. `@phlexbot clang-fix`) perform an explicit authorization check. Only comment authors with one of the following association types are allowed to trigger the workflow: +Comment-triggered workflows perform an explicit authorization check, resolve the current PR head once at workflow start, and record that immutable snapshot. Only comment authors with one of the following association types are allowed to trigger them: * `OWNER` * `COLLABORATOR` @@ -121,12 +114,13 @@ All check and fix workflows share these common inputs, provided by the `Framewor | `repo` | string | No | Repository to check out from | | `pr-base-sha` | string | No | Base SHA of the PR for relevance check | | `pr-head-sha` | string | No | Head SHA of the PR for relevance check | +| `source-sha` | string | Workflow-specific | Optional immutable source commit; otherwise resolve the event snapshot | --- ## Common Invocation Template -Below is a minimal reusable-workflow job snippet that can be copied into any consumer workflow. It supplies the shared inputs and the required `WORKFLOW_PAT` secret for fix workflows. Adjust the `uses:` line and any workflow-specific inputs as needed. +Below is a minimal reusable-workflow job snippet. Fix workflows derive the PR head from the caller event if `source-sha` is omitted. Adjust the `uses:` line and workflow-specific inputs as needed. ```yaml jobs: @@ -136,9 +130,8 @@ jobs: checkout-path: . # Optional: set skip-relevance-check to true for unconditional runs # skip-relevance-check: true + # Optional source-sha can pin a previously resolved snapshot. # Add workflow-specific inputs here (e.g. build-combinations, language-matrix) - secrets: - WORKFLOW_PAT: ${{ secrets.WORKFLOW_PAT }} ``` *Replace ``, ``, and `` with the appropriate values for the workflow you are invoking.* @@ -153,6 +146,7 @@ All check and fix workflows share these common inputs, provided by the `Framewor | `repo` | string | No | Repository to check out from | | `pr-base-sha` | string | No | Base SHA of the PR for relevance check | | `pr-head-sha` | string | No | Head SHA of the PR for relevance check | +| `source-sha` | string | Workflow-specific | Optional immutable source commit; otherwise resolve the event snapshot | --- @@ -227,10 +221,11 @@ Check workflows analyze code without making changes. They are triggered by `pull | `build-path` | string | No | N/A | Path for build artifacts | | `skip-relevance-check` | boolean | No | `false` | Bypass relevance detection | | `build-combinations` | string | No | N/A | Space- or comma-separated list of `/` combos (e.g. `gcc/asan clang/tsan`). `all` runs every matrix entry; `+` adds extra combos. | -| `ref` | string | No | N/A | Branch, ref, or SHA to checkout | +| `ref` | string | No | N/A | Target branch; the workflow checks out an immutable SHA | | `repo` | string | No | N/A | Repository to checkout from | | `pr-base-sha` | string | No | N/A | Base SHA for relevance check | | `pr-head-sha` | string | No | N/A | Head SHA for relevance check | +| `source-sha` | string | Manual: Yes | N/A | Full SHA that must match the selected workflow branch head | ### Example Invocation (cmake-build) @@ -240,56 +235,57 @@ jobs: uses: Framework-R-D/phlex/.github/workflows/cmake-build.yaml@ with: build-combinations: "gcc/asan clang/tsan" - ref: ${{ github.sha }} + ref: ${{ github.ref_name }} + source-sha: ${{ github.sha }} ``` --- ## Fix Workflows -Fix workflows modify code and push commits. They require `WORKFLOW_PAT`. +Fix workflows resolve the PR head once, format that immutable SHA, publish patch artifacts, and never push changes. ### Clang-Format Fix *File:* `.github/workflows/clang-format-fix.yaml` -*Required inputs:* `ref`, `repo` -*Optional:* `checkout-path`, `skip-comment` +*Required reusable-workflow inputs:* `ref`, `repo` +*Optional:* `checkout-path`, `skip-comment`, `source-sha` (required for non-PR callers) ### CMake Format Fix *File:* `.github/workflows/cmake-format-fix.yaml` -*Required inputs:* `ref`, `repo` -*Optional:* `checkout-path`, `skip-comment` +*Required reusable-workflow inputs:* `ref`, `repo` +*Optional:* `checkout-path`, `skip-comment`, `source-sha` (required for non-PR callers) ### Header-Guards Fix *File:* `.github/workflows/header-guards-fix.yaml` -*Required inputs:* `ref`, `repo` -*Optional:* `checkout-path`, `skip-comment` +*Required reusable-workflow inputs:* `ref`, `repo` +*Optional:* `checkout-path`, `skip-comment`, `source-sha` (required for non-PR callers) ### Jsonnet Format Fix *File:* `.github/workflows/jsonnet-format-fix.yaml` -*Required inputs:* `ref`, `repo` -*Optional:* `checkout-path`, `skip-comment` +*Required reusable-workflow inputs:* `ref`, `repo` +*Optional:* `checkout-path`, `skip-comment`, `source-sha` (required for non-PR callers) ### Markdown Fix *File:* `.github/workflows/markdown-fix.yaml` -*Required inputs:* `ref`, `repo` -*Optional:* `checkout-path`, `skip-comment` +*Required reusable-workflow inputs:* `ref`, `repo` +*Optional:* `checkout-path`, `skip-comment`, `source-sha` (required for non-PR callers) ### Python Fix *File:* `.github/workflows/python-fix.yaml` -*Required inputs:* `ref`, `repo` -*Optional:* `checkout-path`, `skip-comment` +*Required reusable-workflow inputs:* `ref`, `repo` +*Optional:* `checkout-path`, `skip-comment`, `source-sha` (required for non-PR callers) ### YAML Fix *File:* `.github/workflows/yaml-fix.yaml` -*Required inputs:* `ref`, `repo` -*Optional:* `checkout-path`, `skip-comment` +*Required reusable-workflow inputs:* `ref`, `repo` +*Optional:* `checkout-path`, `skip-comment`, `source-sha` (required for non-PR callers) ### Clang-Tidy Fix @@ -305,10 +301,10 @@ All `*-fix` workflows emit a standard set of outputs that can be used by downstr | Output | Description | | -------- | ------------- | | `changes` | `true` if any files were modified by the formatter/fixer, otherwise `false` | -| `pushed` | `true` if the changes were successfully pushed back to the repository, otherwise `false` | -| `commit_sha` | Full SHA of the commit created (if any) | -| `commit_sha_short` | Short (7-char) SHA of the commit | -| `patch_name` | Filename of an attached patch when the workflow could not push automatically | +| `pushed` | Always `false`; formatter workflows never push | +| `commit_sha` | Always empty; no commit is created | +| `commit_sha_short` | Always empty | +| `patch_name` | Filename of the patch artifact when formatting changed files | These outputs are available via `${{ steps..outputs. }}` in a consuming workflow. @@ -319,7 +315,7 @@ These outputs are available via `${{ steps..outputs. }}` in a c ### Format-All *File:* `.github/workflows/format-all.yaml` -Calls all individual formatter fix workflows in parallel and posts a single combined PR comment. Triggered only by `issue_comment` (`@phlexbot format`). +Calls all individual formatter fix workflows in parallel against one automatically resolved PR-head SHA and posts a combined patch-artifact comment. Triggered by `@phlexbot format`. --- @@ -351,7 +347,7 @@ The repository also contains several workflows that are **not** intended for `wo | Command | Description | | --------- | ------------- | | `@phlexbot clang-fix` | Run the Clang-Format fix workflow on the PR head branch. | -| `@phlexbot clang-tidy-fix` | Run the Clang-Tidy fix workflow. | +| `@phlexbot tidy-fix [checks]` | Generate Clang-Tidy fixes, optionally scoped to checks. | | `@phlexbot cmake-fix` | Run the CMake-Format fix workflow. | | `@phlexbot header-guards-fix` | Run the Header-Guards fix workflow. | | `@phlexbot jsonnet-fix` | Run the Jsonnet-Format fix workflow. | @@ -360,6 +356,7 @@ The repository also contains several workflows that are **not** intended for `wo | `@phlexbot yaml-fix` | Run the YAML-Fix workflow. | | `@phlexbot format` | Run **all** formatter fix workflows (calls `format-all.yaml`). | | `@phlexbot tidy-check` | Run the Clang-Tidy **check** workflow. | +| `@phlexbot build [combinations]` | Run CMake build and tests for the current PR head. | | `@phlexbot codeql-check` | Run the CodeQL analysis workflow. | | `@phlexbot coverage` | Generate coverage reports. | diff --git a/pyproject.toml b/pyproject.toml index d860642a3..875dca1b1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -61,8 +61,8 @@ extend-ignore = [ ] [tool.ruff.lint.isort] -# Scripts are treated as first-party so that `import clang_tidy_check_summary` -# and similar local imports are grouped correctly relative to third-party ones +# Scripts are treated as first-party so local imports are grouped correctly +# relative to third-party ones # (e.g. pytest), avoiding false I001 violations in scripts/test/. known-first-party = [ "check_codeql_alerts", @@ -71,11 +71,14 @@ known-first-party = [ "clang_tidy_fixes_to_problems", "codeql_reset_dismissed_alerts", "create_coverage_symlinks", + "create_fix_patch", + "run_markdownlint_sandbox", "export_llvm_lcov", "fix_header_guards", "normalize_coverage_lcov", "normalize_coverage_xml", "sarif_alerts", + "validate_clang_tidy_fixes", ] [tool.ruff.lint.pydocstyle] diff --git a/scripts/check_codeql_alerts.py b/scripts/check_codeql_alerts.py index c51b9c58c..6fd14af7d 100644 --- a/scripts/check_codeql_alerts.py +++ b/scripts/check_codeql_alerts.py @@ -7,6 +7,7 @@ import collections.abc import json import os +import re import sys import urllib.error import urllib.parse @@ -80,6 +81,15 @@ def _api_request( } +def _escape_markdown_text(value: str) -> str: + """Escape SARIF-controlled text before including it in a PR comment.""" + single_line = " ".join(value.splitlines()) + single_line = single_line.replace("&", "&").replace("<", "<").replace(">", ">") + single_line = single_line.replace("@", "@\u200b") + markdown_chars = "\\`*_{}[]()#+!|~" + return single_line.translate({ord(char): f"\\{char}" for char in markdown_chars}) + + @dataclass class Alert: """Represents a CodeQL alert extracted from SARIF.""" @@ -102,18 +112,23 @@ def icon(self) -> str: def level_title(self) -> str: """Returns a title-cased version of the alert's level.""" - return self.level.capitalize() + return _escape_markdown_text(self.level.capitalize()) def rule_display(self) -> str: """Returns a formatted string for the rule ID, including a link if available.""" - if self.help_uri: - return f"[{self.rule_id}]({self.help_uri})" - return f"`{self.rule_id}`" + safe_help_uri = re.fullmatch( + r"https://codeql\.github\.com/codeql-query-help/[A-Za-z0-9._/-]+/?", + self.help_uri or "", + ) + rule_id = _escape_markdown_text(self.rule_id) + if safe_help_uri: + return f"[{rule_id}]({self.help_uri})" + return rule_id def severity_suffix(self) -> str: """Returns a string indicating the security severity, if available.""" if self.security_severity: - return f" ({self.security_severity})" + return f" ({_escape_markdown_text(self.security_severity)})" return "" @@ -688,19 +703,29 @@ def _format_section( for alert in display: severity_note = alert.severity_suffix() # Prefer to show an alert number link when available - if alert.number and alert.html_url: + if ( + alert.number + and alert.html_url + and alert.html_url.startswith( + "https://github.com/Framework-R-D/phlex/security/code-scanning/" + ) + ): prefix = f"[# {alert.number}]({alert.html_url}) " elif alert.number: prefix = f"# {alert.number} " else: prefix = "" dismissed_note = ( - f" (dismissed: {alert.dismissed_reason})" if alert.dismissed_reason else "" + f" (dismissed: {_escape_markdown_text(alert.dismissed_reason)})" + if alert.dismissed_reason + else "" ) lines.append( f"- {bullet_prefix} **{alert.level_title()}**{severity_note} {prefix}" - f"{alert.rule_display()}{dismissed_note} at `{alert.location}` — {alert.message}" + f"{alert.rule_display()}{dismissed_note} at " + f"{_escape_markdown_text(alert.location)} — " + f"{_escape_markdown_text(alert.message)}" ) if remaining: lines.append( diff --git a/scripts/create_fix_patch.py b/scripts/create_fix_patch.py new file mode 100644 index 000000000..ae95847f8 --- /dev/null +++ b/scripts/create_fix_patch.py @@ -0,0 +1,145 @@ +"""Create a provenance-bound patch artifact without changing the source branch.""" + +from __future__ import annotations + +import json +import os +import re +import subprocess +import tempfile +from pathlib import Path +from typing import Mapping + +MAX_PATCH_SIZE = 16 * 1024 * 1024 +SHA_PATTERN = re.compile(r"[0-9a-f]{40}\Z") +REPOSITORY_PATTERN = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]*/[A-Za-z0-9_.-]+\Z") +TOOL_PATTERN = re.compile(r"[a-z0-9-]{1,40}\Z") + + +def _run_git(repository: Path, args: list[str], env: Mapping[str, str]) -> bytes: + result = subprocess.run( + ["git", "-c", "core.fsmonitor=false", *args], + cwd=repository, + env=dict(env), + capture_output=True, + check=False, + ) + if result.returncode: + raise ValueError("Could not inspect the formatter checkout") + return result.stdout + + +def create_fix_patch(repository: Path, settings: Mapping[str, str]) -> dict[str, str]: + """Write only a bounded binary diff and provenance to a unique temp directory.""" + source_sha = settings.get("SOURCE_SHA", "") + target_repo = settings.get("TARGET_REPO", "") + target_ref = settings.get("TARGET_REF", "") + tool = settings.get("TOOL", "") + if SHA_PATTERN.fullmatch(source_sha) is None: + raise ValueError("Expected a full approved source SHA") + if REPOSITORY_PATTERN.fullmatch(target_repo) is None or target_repo.split("/")[1] in { + ".", + "..", + }: + raise ValueError("Invalid patch target repository") + if ( + not target_ref + or target_ref.startswith(("-", "refs/")) + or any(ord(char) < 32 for char in target_ref) + ): + raise ValueError("Invalid patch target branch") + if TOOL_PATTERN.fullmatch(tool) is None: + raise ValueError("Invalid formatter label") + + if repository.is_symlink(): + raise ValueError("Formatter checkout must not be a symlink") + repository = repository.resolve(strict=True) + if not repository.is_dir(): + raise ValueError("Formatter checkout must be a directory") + + with tempfile.TemporaryDirectory(prefix="phlex-fix-patch-") as temporary_home: + env = { + "PATH": os.environ["PATH"], + "HOME": temporary_home, + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_TERMINAL_PROMPT": "0", + "GIT_OPTIONAL_LOCKS": "0", + "LC_ALL": "C", + } + head = ( + _run_git(repository, ["rev-parse", "--verify", "HEAD^{commit}"], env).decode().strip() + ) + if head != source_sha: + raise ValueError("Formatter checkout does not match the approved source SHA") + _run_git(repository, ["check-ref-format", f"refs/heads/{target_ref}"], env) + patch = _run_git( + repository, + [ + "--no-pager", + "diff", + "--binary", + "--no-ext-diff", + "--no-textconv", + source_sha, + "--", + ".", + ], + env, + ) + + if len(patch) > MAX_PATCH_SIZE: + raise ValueError("Formatter patch exceeds the artifact size limit") + if not patch: + return { + "changes": "false", + "pushed": "false", + "commit_sha": "", + "commit_sha_short": "", + "patch_name": "", + } + + artifact_root = Path(os.environ["RUNNER_TEMP"]) + if artifact_root.is_symlink() or not artifact_root.is_dir(): + raise ValueError("Runner temporary directory is invalid") + artifact = Path(tempfile.mkdtemp(prefix=f"{tool}-patch.", dir=artifact_root)) + patch_name = f"{tool}.patch" + (artifact / patch_name).write_bytes(patch) + metadata = { + "source_sha": source_sha, + "target_repo": target_repo, + "target_ref": target_ref, + "workflow_ref": settings.get("WORKFLOW_REF", ""), + "run_id": settings.get("RUN_ID", ""), + "run_attempt": settings.get("RUN_ATTEMPT", ""), + "tool": tool, + } + (artifact / "provenance.json").write_text( + json.dumps(metadata, sort_keys=True) + "\n", encoding="utf-8" + ) + return { + "changes": "true", + "pushed": "false", + "commit_sha": "", + "commit_sha_short": "", + "patch_name": patch_name, + "artifact_name": f"{tool}-patch-{metadata['run_attempt']}", + "artifact_path": str(artifact), + } + + +def main() -> None: + """Publish only fixed-name outputs for the workflow artifact step.""" + outputs = create_fix_patch(Path(os.environ["SOURCE_PATH"]), os.environ) + with Path(os.environ["GITHUB_OUTPUT"]).open("a", encoding="utf-8") as output: + for name, value in outputs.items(): + output.write(f"{name}={value}\n") + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, subprocess.SubprocessError): + raise SystemExit( + "Patch preparation failed closed; verify the source snapshot and artifact paths" + ) from None diff --git a/scripts/fix_header_guards.py b/scripts/fix_header_guards.py index 7ce4530a8..3db1f08e6 100755 --- a/scripts/fix_header_guards.py +++ b/scripts/fix_header_guards.py @@ -132,6 +132,20 @@ def fix_header_guard(file_path: Path, root: Path) -> bool: return modified +def _is_safe_header_path(file_path: Path, root: Path) -> bool: + """Require every path component to remain a regular path under the source root.""" + try: + relative_path = file_path.relative_to(root) + except ValueError: + return False + current = root + for part in relative_path.parts: + current /= part + if current.is_symlink(): + return False + return current.is_file() + + def main() -> None: """Check or fix header guards in C++ header files.""" parser = argparse.ArgumentParser(description="Check/fix header guards") @@ -144,10 +158,15 @@ def main() -> None: bad_files = [] for arg in args.paths: - path = Path(arg).resolve() + path = Path(arg) + if path.is_symlink(): + continue + path = path.resolve() + if not path.is_relative_to(root): + continue files = [path] if path.is_file() else [*path.rglob("*.hpp"), *path.rglob("*.h")] for f in files: - if f.suffix not in {".hpp", ".h"}: + if f.suffix not in {".hpp", ".h"} or not _is_safe_header_path(f, root): continue if args.check: valid, expected = check_header_guard(f, root) diff --git a/scripts/run_markdownlint_sandbox.py b/scripts/run_markdownlint_sandbox.py new file mode 100644 index 000000000..2bc7f9cdd --- /dev/null +++ b/scripts/run_markdownlint_sandbox.py @@ -0,0 +1,148 @@ +"""Run markdownlint on tracked files without loading repository plugins.""" + +from __future__ import annotations + +import os +import shutil +import subprocess +import tempfile +from pathlib import Path, PurePosixPath +from typing import Mapping + + +def _git_tracked_markdown(repository: Path, env: Mapping[str, str]) -> list[Path]: + result = subprocess.run( + ["git", "-c", "core.fsmonitor=false", "ls-files", "-z", "--", ":(glob)**/*.md"], + cwd=repository, + env=dict(env), + capture_output=True, + check=False, + ) + if result.returncode: + raise ValueError("Could not enumerate tracked Markdown files") + paths = [] + for raw_path in result.stdout.split(b"\0"): + if not raw_path: + continue + path = PurePosixPath(os.fsdecode(raw_path)) + if path.is_absolute() or ".." in path.parts or ".git" in path.parts: + raise ValueError("Git returned an unsafe Markdown path") + if path.name != "CHANGELOG.md": + paths.append(Path(*path.parts)) + return paths + + +def _contains_symlink(repository: Path, relative_path: Path) -> bool: + current = repository + for part in relative_path.parts: + current /= part + if current.is_symlink(): + return True + return False + + +def run_markdownlint_sandbox( + repository: Path, + trusted_config: Path, + executable: Path, + *, + temporary_root: Path, + inherited_path: str, +) -> list[str]: + """Format tracked Markdown in isolation and copy only edited files back.""" + if repository.is_symlink() or trusted_config.is_symlink() or temporary_root.is_symlink(): + raise ValueError( + "Repository, trusted configuration, and staging root must not be symlinks" + ) + executable_is_symlink = executable.is_symlink() + repository = repository.resolve(strict=True) + trusted_config = trusted_config.resolve(strict=True) + executable_parent = executable.parent.parent.resolve(strict=True) + executable = executable.resolve(strict=True) + temporary_root = temporary_root.resolve(strict=True) + if ( + not repository.is_dir() + or not trusted_config.is_file() + or not executable.is_file() + or not temporary_root.is_dir() + ): + raise ValueError("Invalid Markdown formatter paths") + if executable_is_symlink and not executable.is_relative_to(executable_parent): + raise ValueError("Markdown formatter symlinks must resolve inside trusted node_modules") + + with tempfile.TemporaryDirectory( + prefix="phlex-markdownlint-home.", dir=temporary_root + ) as temporary_home: + env = { + "PATH": inherited_path, + "HOME": temporary_home, + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_TERMINAL_PROMPT": "0", + "GIT_OPTIONAL_LOCKS": "0", + "LC_ALL": "C", + } + markdown_files = _git_tracked_markdown(repository, env) + stage = Path(tempfile.mkdtemp(prefix="phlex-markdownlint-stage.", dir=temporary_root)) + shutil.copyfile(trusted_config, stage / ".markdownlint-cli2.yaml") + staged_files: dict[Path, Path] = {} + for relative_path in markdown_files: + source = repository / relative_path + if _contains_symlink(repository, relative_path) or not source.is_file(): + raise ValueError(f"Tracked Markdown path is not a regular file: {relative_path}") + destination = stage / relative_path + destination.parent.mkdir(parents=True, exist_ok=True) + shutil.copyfile(source, destination) + shutil.copymode(source, destination) + staged_files[relative_path] = destination + + result = subprocess.run( + [ + str(executable), + "--config", + str(stage / ".markdownlint-cli2.yaml"), + "--fix", + "**/*.md", + "!**/CHANGELOG.md", + ], + cwd=stage, + env=env, + capture_output=True, + check=False, + ) + if result.returncode not in {0, 1}: + raise ValueError("Isolated Markdown formatter failed") + + changed = [] + for relative_path, staged_path in staged_files.items(): + if staged_path.is_symlink() or not staged_path.is_file(): + raise ValueError(f"Markdown formatter replaced a regular file: {relative_path}") + content = staged_path.read_bytes() + original = repository / relative_path + if _contains_symlink(repository, relative_path) or not original.is_file(): + raise ValueError( + f"Tracked Markdown path changed during formatting: {relative_path}" + ) + if content != original.read_bytes(): + original.write_bytes(content) + changed.append(relative_path.as_posix()) + return changed + + +def main() -> None: + """Run the isolated formatter using workflow-provided trusted paths.""" + changed = run_markdownlint_sandbox( + Path(os.environ["SOURCE_PATH"]), + Path(os.environ["TRUSTED_CONFIG"]), + Path(os.environ["MARKDOWNLINT_EXECUTABLE"]), + temporary_root=Path(os.environ["RUNNER_TEMP"]), + inherited_path=os.environ["PATH"], + ) + print(f"Formatted {len(changed)} tracked Markdown files in isolated staging.") + + +if __name__ == "__main__": + try: + main() + except (OSError, ValueError, subprocess.SubprocessError): + raise SystemExit("Isolated Markdown formatting failed closed") from None diff --git a/scripts/test/test_check_codeql_alerts.py b/scripts/test/test_check_codeql_alerts.py index 6f1d36ae6..582136b93 100644 --- a/scripts/test/test_check_codeql_alerts.py +++ b/scripts/test/test_check_codeql_alerts.py @@ -463,14 +463,24 @@ def test_level_title(self) -> None: assert self._alert(level="error").level_title() == "Error" def test_rule_display_with_uri(self) -> None: - """Rule display with uri.""" + """External SARIF help URIs are not emitted as clickable links.""" display = self._alert().rule_display() - assert display == "[py/sql-injection](https://example.com)" + assert display == "py/sql-injection" + + def test_rule_display_with_codeql_help_uri(self) -> None: + """Links only to the trusted CodeQL help host.""" + display = self._alert( + help_uri="https://codeql.github.com/codeql-query-help/python/py/sql-injection/" + ).rule_display() + assert ( + display + == "[py/sql-injection](https://codeql.github.com/codeql-query-help/python/py/sql-injection/)" + ) def test_rule_display_without_uri(self) -> None: """Rule display without uri.""" display = self._alert(help_uri=None).rule_display() - assert display == "`py/sql-injection`" + assert display == "py/sql-injection" def test_severity_suffix_present(self) -> None: """Severity suffix present.""" @@ -492,7 +502,7 @@ class TestFormatSection: def _alert(self, n: int, level: str = "error") -> M.Alert: return M.Alert( number=n, - html_url=f"https://example.com/{n}", + html_url=f"https://github.com/Framework-R-D/phlex/security/code-scanning/{n}", rule_id="py/r", level=level, message="msg", @@ -516,7 +526,7 @@ def test_alert_with_number_link(self) -> None: """Alert with number link.""" lines = M._format_section([self._alert(7)], max_results=10, bullet_prefix=":x:") assert "[# 7]" in lines[0] - assert "https://example.com/7" in lines[0] + assert "https://github.com/Framework-R-D/phlex/security/code-scanning/7" in lines[0] def test_dismissed_note_included(self) -> None: """Dismissed note included.""" @@ -526,6 +536,20 @@ def test_dismissed_note_included(self) -> None: assert "dismissed" in lines[0] assert "false positive" in lines[0] + def test_sarif_text_cannot_inject_markdown_or_mentions(self) -> None: + """Escapes untrusted SARIF strings before they reach a PR comment.""" + alert = self._alert(1) + alert.rule_id = "bad`rule" + alert.help_uri = "https://attacker.invalid/" + alert.location = "src/a.cpp`\n" + alert.message = "@everyone [click](https://attacker.invalid)" + line = M._format_section([alert], max_results=10, bullet_prefix=":x:")[0] + + assert "@everyone" not in line + assert "