From 567b9836891b237cc0f0404f91d663ee6e384206 Mon Sep 17 00:00:00 2001 From: Nathan Rover Date: Fri, 6 Nov 2026 13:29:43 -0500 Subject: [PATCH] Support trusted pull_request_target and repository_dispatch review callers The reusable review workflow now admits two default-branch caller events alongside pull_request and workflow_dispatch, which keep their current job selection, permissions, and behavior. - pull_request_target (opened, reopened, ready_for_review, synchronize) keeps the first-pass / follow-up split and runs only for PRs that target the default branch. - repository_dispatch from the default branch is a first pass. Callers map client_payload into pr_number, review_level, and the new optional expected_head_sha input, which fails the review and gate closed when the live PR head moved. - A new review-config step resolves the PR number, pass, and event head, base, and before SHAs explicitly, and rejects mismatched PR numbers. - The gate exposes the evaluated head and conclusion as gate_* workflow outputs. The new openrouter-review-gate-check.yml entry point publishes that result as a GitHub Actions check run on the exact evaluated head for default-branch dispatch runs. It is the only job that requests checks: write, so existing callers keep working without new scopes. - Reviewed checkouts stay inert data: submodules and LFS are explicitly off, and a commit containing the reserved trusted checkout paths is refused. - Bot-sent repository_dispatch reviews wake profile completion like bot-sent workflow_dispatch reviews. Profile provenance (Python and the Node consumer) admits the new events. repository_dispatch runs must be on the default branch with a matching caller blob. pull_request_target runs report the PR head, so their caller is proven through the head branch: every same-repository PR from it must target the default branch with no recorded base change. They also need the exact reusable pin, a run head equal to the receipt head, and a matching PR head branch. The Node consumer now also requires pull-request review runs to match the receipt head. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/openrouter-code-review.yml | 204 +++++++- .../openrouter-review-gate-check.yml | 124 +++++ README.md | 104 +++- scripts/gate_check.mjs | 137 ++++++ scripts/profile_completion.py | 28 +- scripts/profile_consumer.mjs | 74 ++- scripts/profile_gate.py | 61 ++- scripts/profile_github.py | 103 +++- scripts/profile_requests.py | 4 +- scripts/workflow_wakeup.mjs | 4 +- tests/gate-check.test.mjs | 173 +++++++ tests/profile-consumer.test.mjs | 142 +++++- tests/test_profile_completion.py | 99 +++- tests/test_profile_gate.py | 171 +++++++ tests/test_profile_github.py | 147 ++++++ tests/test_profile_requests.py | 46 ++ tests/test_profile_workflow.py | 462 ++++++++++++++++++ tests/workflow-wakeup.test.mjs | 13 + 18 files changed, 2063 insertions(+), 33 deletions(-) create mode 100644 .github/workflows/openrouter-review-gate-check.yml create mode 100644 scripts/gate_check.mjs create mode 100644 tests/gate-check.test.mjs diff --git a/.github/workflows/openrouter-code-review.yml b/.github/workflows/openrouter-code-review.yml index edf0e0b..bb1becb 100644 --- a/.github/workflows/openrouter-code-review.yml +++ b/.github/workflows/openrouter-code-review.yml @@ -81,6 +81,20 @@ # comment a dead run would otherwise leave saying "Reviewing…" # forever. # +# Trusted default-branch callers (optional): +# pull_request_target (opened / reopened / ready_for_review / +# synchronize) keeps the pull_request first-pass vs follow-up split. It +# runs only when the PR targets the default branch, so the caller comes +# from that branch. GitHub attaches these runs (and their native job +# checks) to the PR head commit. The reviewed checkout is inert data: +# no step runs its code, hooks, package scripts, or configuration. +# repository_dispatch from the default branch is a first-pass like +# workflow_dispatch. Callers map client_payload into with: (pr_number, +# review_level, expected_head_sha); github.event.inputs is empty here. +# Default-branch dispatch runs attach native checks to the default-branch +# tip, so pair them with openrouter-review-gate-check.yml, which repeats +# the gate result on the reviewed head from the gate_* outputs below. +# # Drafts never run on pull_request. The review-job if still refuses # NO SCAN repos even if a caller or ruleset would otherwise fire. # This repo (RetireGolden/.github) is NO SCAN — do not add a caller @@ -150,6 +164,11 @@ on: description: PR number to review when the caller is not a pull_request event required: false type: string + expected_head_sha: + description: Optional PR head a dispatcher observed; the review and gate fail closed if the live head differs + required: false + type: string + default: '' max_diff_kb: description: >- Embedded-diff cap in KB for openrouter-pr-review-action. Org @@ -165,6 +184,19 @@ on: OPENROUTER_API_KEY: description: "Org OpenRouter API key. Callers must pass this secret explicitly. Do not use secrets: inherit (product repos hold deploy/CLA/GPG secrets)." required: true + outputs: + gate_pr_number: + description: Pull request the first-pass gate evaluated + value: ${{ jobs.openrouter-first-pass-gate.outputs.pr_number }} + gate_head_sha: + description: Exact PR head the first-pass gate evaluated (empty when no head was evaluated) + value: ${{ jobs.openrouter-first-pass-gate.outputs.head_sha }} + gate_conclusion: + description: success or failure for gate_head_sha + value: ${{ jobs.openrouter-first-pass-gate.outputs.conclusion }} + gate_review_url: + description: Review the gate accepted, when it passed + value: ${{ jobs.openrouter-first-pass-gate.outputs.review_url }} permissions: actions: read @@ -180,13 +212,21 @@ jobs: github.repository != 'RetireGolden/cla-signatures' && github.repository != 'RetireGolden/RetireBench-private' && (github.event_name == 'workflow_dispatch' || - (github.event_name == 'pull_request' && !github.event.pull_request.draft)) + (github.event_name == 'pull_request' && !github.event.pull_request.draft) || + (github.event_name == 'repository_dispatch' && + github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) || + (github.event_name == 'pull_request_target' && + !github.event.pull_request.draft && + github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && + contains(fromJSON('["opened","reopened","ready_for_review","synchronize"]'), github.event.action))) runs-on: ubuntu-latest timeout-minutes: 3 permissions: actions: read contents: read outputs: + pr_number: ${{ steps.pr.outputs.pr_number }} + review_pass: ${{ steps.pr.outputs.pass }} org_sha: ${{ steps.source.outputs.sha }} review_profiles: ${{ steps.config.outputs.review_profiles }} models: ${{ steps.config.outputs.models }} @@ -194,6 +234,73 @@ jobs: effort: ${{ steps.config.outputs.effort }} custom_instructions: ${{ steps.config.outputs.custom_instructions }} steps: + # The caller's event names the PR for pull-request events; dispatches + # name it through inputs. github.sha is never treated as the PR head. + - name: Resolve pull request context + id: pr + env: + EVENT_NAME: ${{ github.event_name }} + EVENT_ACTION: ${{ github.event.action }} + EVENT_PR_NUMBER: ${{ github.event.pull_request.number }} + EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + EVENT_BASE_SHA: ${{ github.event.pull_request.base.sha }} + EVENT_BEFORE_SHA: ${{ github.event.before }} + INPUT_PR_NUMBER: ${{ inputs.pr_number }} + DISPATCH_PR_NUMBER: ${{ github.event.inputs.pr_number }} + EXPECTED_HEAD_SHA: ${{ inputs.expected_head_sha }} + shell: bash + run: | + set -euo pipefail + case "$EVENT_NAME" in + pull_request|pull_request_target) + number="$EVENT_PR_NUMBER" + if [ -n "${INPUT_PR_NUMBER:-}" ] && [ "$INPUT_PR_NUMBER" != "$number" ]; then + echo "::error::pr_number ${INPUT_PR_NUMBER} does not match the triggering PR ${number}." + exit 1 + fi + if [ "$EVENT_ACTION" = "synchronize" ]; then pass=follow-up; else pass=first-pass; fi + ;; + workflow_dispatch) + # Same precedence as the review jobs' PR_NUMBER expression. + number="${INPUT_PR_NUMBER:-${DISPATCH_PR_NUMBER:-}}" + pass=first-pass + ;; + repository_dispatch) + # client_payload is never read here; the caller maps it into with:. + number="${INPUT_PR_NUMBER:-}" + pass=first-pass + ;; + *) + echo "::error::Unsupported review event ${EVENT_NAME}." + exit 1 + ;; + esac + if ! [[ "$number" =~ ^[1-9][0-9]{0,9}$ ]]; then + echo "::error::A positive PR number is required for ${EVENT_NAME}." + exit 1 + fi + if [ -n "${EXPECTED_HEAD_SHA:-}" ] && ! [[ "$EXPECTED_HEAD_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::expected_head_sha must be a lowercase full commit SHA." + exit 1 + fi + { + echo "pr_number=$number" + echo "pass=$pass" + echo "event_head_sha=${EVENT_HEAD_SHA:-}" + } >> "$GITHUB_OUTPUT" + { + echo "### OpenRouter pull request context" + echo "" + echo "| Field | Value |" + echo "| --- | --- |" + echo "| Event | \`${EVENT_NAME}\` \`${EVENT_ACTION:-}\` |" + echo "| PR | \`#${number}\` |" + echo "| Pass | \`${pass}\` |" + echo "| Event head | \`${EVENT_HEAD_SHA:-resolved live}\` |" + echo "| Event base | \`${EVENT_BASE_SHA:-resolved live}\` |" + echo "| Before (synchronize) | \`${EVENT_BEFORE_SHA:-none}\` |" + echo "| Workflow commit | \`${GITHUB_SHA}\` (not the PR head) |" + } >> "$GITHUB_STEP_SUMMARY" - name: Resolve this reusable workflow's immutable source id: source if: inputs.review_profiles_enabled @@ -217,7 +324,7 @@ jobs: - name: Select standing roster and shared guidance id: config env: - FOLLOW_UP: ${{ github.event.action == 'synchronize' && 'true' || 'false' }} + FOLLOW_UP: ${{ steps.pr.outputs.pass == 'follow-up' && 'true' || 'false' }} RESET_REVIEW: ${{ inputs.reset_review && 'true' || 'false' }} REVIEW_POLICY: ${{ inputs.review_policy || 'off' }} PROFILES_ENABLED: ${{ inputs.review_profiles_enabled && 'true' || 'false' }} @@ -324,7 +431,11 @@ jobs: github.repository != 'RetireGolden/cla-signatures' && github.repository != 'RetireGolden/RetireBench-private' && (github.event_name == 'workflow_dispatch' || - (github.event_name == 'pull_request' && + (github.event_name == 'repository_dispatch' && + github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) || + ((github.event_name == 'pull_request' || + (github.event_name == 'pull_request_target' && + github.ref == format('refs/heads/{0}', github.event.repository.default_branch))) && !github.event.pull_request.draft && (github.event.action == 'opened' || github.event.action == 'reopened' || @@ -345,6 +456,7 @@ jobs: id: head env: EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + EXPECTED_HEAD_SHA: ${{ inputs.expected_head_sha }} GH_TOKEN: ${{ github.token }} run: | set -euo pipefail @@ -360,14 +472,38 @@ jobs: echo "::error::Could not resolve PR head SHA for PR ${PR_NUMBER}." exit 1 fi + if [ -n "${EXPECTED_HEAD_SHA:-}" ] && [ "$HEAD_SHA" != "$EXPECTED_HEAD_SHA" ]; then + echo "::error::PR ${PR_NUMBER} head is ${HEAD_SHA}, not the dispatched ${EXPECTED_HEAD_SHA}; dispatch again for the current head." + exit 1 + fi echo "sha=$HEAD_SHA" >> "$GITHUB_OUTPUT" + # Inert data checkout of the exact reviewed head. Under pull_request_target + # and repository_dispatch this job holds secrets, so nothing below executes + # checkout content: no local actions, hooks (none are fetched), submodules, + # LFS filters, package scripts, or repository configuration. Python runs + # with -P and a trusted PYTHONPATH; git only reads objects. - name: Checkout PR head uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 with: persist-credentials: false fetch-depth: 0 + submodules: false + lfs: false ref: ${{ steps.head.outputs.sha }} + - name: Refuse reserved trusted paths in the reviewed checkout + shell: bash + run: | + set -euo pipefail + # Trusted coordinator and contract checkouts land at these paths. A + # reviewed commit must not pre-seed or redirect them (for example + # with a symlink). + for reserved in .trusted-review-org .trusted-review-action; do + if [ -e "$reserved" ] || [ -L "$reserved" ]; then + echo "::error::The reviewed commit contains reserved path ${reserved}; remove it to run a review." + exit 1 + fi + done # checkout's full-history refspec includes all refs/heads, so live main # history is present even when it is not an ancestor of this PR head. @@ -411,6 +547,7 @@ jobs: role: setup github_token: ${{ github.token }} pr_number: ${{ env.PR_NUMBER }} + head_sha: ${{ github.event_name == 'repository_dispatch' && steps.head.outputs.sha || '' }} review_policy: base review_profiles: ${{ needs.review-config.outputs.review_profiles }} model_routes: ${{ needs.review-config.outputs.model_routes }} @@ -460,6 +597,8 @@ jobs: with: github_token: ${{ github.token }} pr_number: ${{ github.event.pull_request.number || inputs.pr_number || github.event.inputs.pr_number }} + # repository_dispatch has no event head; review exactly the checked-out commit. + head_sha: ${{ github.event_name == 'repository_dispatch' && steps.head.outputs.sha || '' }} models: ${{ needs.review-config.outputs.models }} model_routes: ${{ needs.review-config.outputs.model_routes }} effort: ${{ needs.review-config.outputs.effort }} @@ -559,16 +698,29 @@ jobs: !cancelled() && inputs.review_level != 'cancel' && (github.event_name == 'pull_request' || - github.event_name == 'workflow_dispatch') + github.event_name == 'workflow_dispatch' || + (github.event_name == 'repository_dispatch' && + github.ref == format('refs/heads/{0}', github.event.repository.default_branch)) || + (github.event_name == 'pull_request_target' && + github.ref == format('refs/heads/{0}', github.event.repository.default_branch) && + contains(fromJSON('["opened","reopened","ready_for_review","synchronize"]'), github.event.action))) # Deliberately no concurrency group. GitHub keeps only one pending run per # group even when cancel-in-progress is false, so grouping could replace a # pending gate for a different head before it emits a terminal check. runs-on: ubuntu-latest timeout-minutes: 35 + # Exposed as gate_* workflow outputs for openrouter-review-gate-check.yml. + outputs: + pr_number: ${{ steps.gate.outputs.pr_number }} + head_sha: ${{ steps.gate.outputs.head_sha }} + conclusion: ${{ steps.gate.outputs.conclusion }} + review_url: ${{ steps.gate.outputs.review_url }} env: PR_NUMBER: ${{ github.event.pull_request.number || inputs.pr_number || github.event.inputs.pr_number }} - EVENT_ACTION: ${{ github.event.action }} + # A repository_dispatch action is its free-form event type, never a PR action. + EVENT_ACTION: ${{ (github.event_name == 'pull_request' || github.event_name == 'pull_request_target') && github.event.action || '' }} EVENT_HEAD_SHA: ${{ github.event.pull_request.head.sha }} + EXPECTED_HEAD_SHA: ${{ inputs.expected_head_sha }} IS_DRAFT: ${{ github.event.pull_request.draft || false }} FIRST_PASS_RESULT: ${{ needs.openrouter-first-pass.result }} ACTION_OUTCOME: ${{ needs.openrouter-first-pass.outputs.action_outcome }} @@ -578,8 +730,11 @@ jobs: RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} steps: - name: Evaluate OpenRouter first-pass gate + id: gate run: | set -euo pipefail + # Record the terminal result for the head-bound check publisher. + trap 'if [ "$?" -eq 0 ]; then echo "conclusion=success"; else echo "conclusion=failure"; fi >> "$GITHUB_OUTPUT"' EXIT case "$GITHUB_REPOSITORY" in RetireGolden/.github|RetireGolden/cla-signatures|RetireGolden/RetireBench-private) @@ -592,6 +747,11 @@ jobs: echo "::error::openrouter-first-pass-gate: missing PR number." exit 1 fi + if ! [[ "$PR_NUMBER" =~ ^[1-9][0-9]{0,9}$ ]]; then + echo "::error::openrouter-first-pass-gate: PR number must be a positive integer." + exit 1 + fi + echo "pr_number=$PR_NUMBER" >> "$GITHUB_OUTPUT" if [ "$IS_DRAFT" = "true" ]; then echo "::error::Draft PR: OpenRouter first-pass has not run. Mark it ready for review to start the gate." exit 1 @@ -608,6 +768,16 @@ jobs: echo "::error::Could not resolve the current PR head SHA." exit 1 fi + if ! [[ "$HEAD_SHA" =~ ^[0-9a-f]{40}$ ]]; then + echo "::error::The current PR head is not a full commit SHA." + exit 1 + fi + # Every later decision (and any published check) binds to this head. + echo "head_sha=$HEAD_SHA" >> "$GITHUB_OUTPUT" + if [ -n "${EXPECTED_HEAD_SHA:-}" ] && [ "$HEAD_SHA" != "$EXPECTED_HEAD_SHA" ]; then + echo "::error::PR head is ${HEAD_SHA}, not the dispatched ${EXPECTED_HEAD_SHA}; dispatch again for the current head." + exit 1 + fi # A carry candidate must be a real bot-authored initial, full-PR verify, or rebase # review. Verification requires a ledger. Initial partials @@ -678,6 +848,7 @@ jobs: local review_url="$1" local message="$2" carry_status "$review_url" + echo "review_url=$review_url" >> "$GITHUB_OUTPUT" echo "$message" exit 0 } @@ -737,7 +908,9 @@ jobs: github.repository != 'RetireGolden/.github' && github.repository != 'RetireGolden/cla-signatures' && github.repository != 'RetireGolden/RetireBench-private' && - github.event_name == 'pull_request' && + (github.event_name == 'pull_request' || + (github.event_name == 'pull_request_target' && + github.ref == format('refs/heads/{0}', github.event.repository.default_branch))) && !github.event.pull_request.draft && github.event.action == 'synchronize' runs-on: ubuntu-latest @@ -813,7 +986,23 @@ jobs: with: persist-credentials: false fetch-depth: 0 + submodules: false + lfs: false ref: ${{ steps.head.outputs.sha }} + - name: Refuse reserved trusted paths in the reviewed checkout + if: steps.seeded.outputs.ready == 'true' + shell: bash + run: | + set -euo pipefail + # Trusted coordinator and contract checkouts land at these paths. A + # reviewed commit must not pre-seed or redirect them (for example + # with a symlink). + for reserved in .trusted-review-org .trusted-review-action; do + if [ -e "$reserved" ] || [ -L "$reserved" ]; then + echo "::error::The reviewed commit contains reserved path ${reserved}; remove it to run a review." + exit 1 + fi + done # Full history fetches all branch refs, including the trusted main tip. @@ -988,7 +1177,8 @@ jobs: if: >- always() && inputs.review_profiles_enabled && needs.review-config.result == 'success' && - github.event_name == 'workflow_dispatch' && github.actor == 'github-actions[bot]' + (github.event_name == 'workflow_dispatch' || github.event_name == 'repository_dispatch') && + github.actor == 'github-actions[bot]' runs-on: ubuntu-latest timeout-minutes: 3 permissions: diff --git a/.github/workflows/openrouter-review-gate-check.yml b/.github/workflows/openrouter-review-gate-check.yml new file mode 100644 index 0000000..d186a2c --- /dev/null +++ b/.github/workflows/openrouter-review-gate-check.yml @@ -0,0 +1,124 @@ +# Head-bound gate check for trusted default-branch review callers. +# +# Default-branch runs (workflow_dispatch, repository_dispatch) attach their +# native job checks to the default-branch tip, not to the reviewed PR head. +# This workflow repeats openrouter-code-review.yml's first-pass gate result as a +# check run (GitHub Actions app) on the exact head that gate evaluated, so a +# required `review / openrouter-first-pass-gate` check is satisfied, or fails, +# on that commit. Pull-request runs, including pull_request_target, already +# report on the PR head, so `auto` mode leaves them to the native job check. +# +# It is a separate entry point because only this job needs `checks: write`. +# GitHub validates every reusable-job permission against the caller before +# runtime conditions, so adding the permission to the review workflow would +# reject existing callers that do not grant it. +# +# jobs: +# review: +# uses: RetireGolden/.github/.github/workflows/openrouter-code-review.yml@ +# ... +# gate-check: +# needs: review +# if: always() && needs.review.outputs.gate_head_sha != '' +# uses: RetireGolden/.github/.github/workflows/openrouter-review-gate-check.yml@ +# permissions: +# actions: read +# checks: write +# contents: read +# pull-requests: read +# with: +# pr_number: ${{ needs.review.outputs.gate_pr_number }} +# head_sha: ${{ needs.review.outputs.gate_head_sha }} +# conclusion: ${{ needs.review.outputs.gate_conclusion }} +# review_url: ${{ needs.review.outputs.gate_review_url }} +# +# It never checks out or executes pull-request content. +name: OpenRouter review gate check + +on: + workflow_call: + inputs: + pr_number: + description: Pull request the first-pass gate evaluated + required: true + type: string + head_sha: + description: Exact PR head commit the first-pass gate evaluated + required: true + type: string + conclusion: + description: First-pass gate result; anything except success publishes failure + required: false + type: string + default: '' + review_url: + description: Optional review the gate accepted, linked from the check summary + required: false + type: string + default: '' + gate_check_name: + description: Check run name; match the required check on the target branch + required: false + type: string + default: 'review / openrouter-first-pass-gate' + publish_mode: + description: auto publishes only for default-branch runs; always also repeats pull-request results + required: false + type: string + default: 'auto' + +permissions: + actions: read + checks: write + contents: read + pull-requests: read + +jobs: + publish: + name: Publish head-bound gate check + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + actions: read + checks: write + contents: read + pull-requests: read + steps: + - name: Resolve this reusable workflow's immutable source + id: source + env: + GH_TOKEN: ${{ github.token }} + shell: bash + run: | + set -euo pipefail + source_sha="$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}" \ + --jq '[.referenced_workflows[] | select(.path | startswith("RetireGolden/.github/.github/workflows/openrouter-review-gate-check.yml@")) | .sha] | unique | if length == 1 then .[0] else error("ambiguous reusable workflow source") end')" + [[ "$source_sha" =~ ^[0-9a-f]{40}$ ]] || exit 1 + echo "sha=$source_sha" >> "$GITHUB_OUTPUT" + - name: Checkout the trusted gate check helper + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + repository: RetireGolden/.github + ref: ${{ steps.source.outputs.sha }} + path: .trusted-review-org + persist-credentials: false + - name: Publish the gate result on the reviewed head + uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + env: + GATE_PR_NUMBER: ${{ inputs.pr_number }} + GATE_HEAD_SHA: ${{ inputs.head_sha }} + GATE_CONCLUSION: ${{ inputs.conclusion }} + GATE_REVIEW_URL: ${{ inputs.review_url }} + GATE_CHECK_NAME: ${{ inputs.gate_check_name }} + GATE_PUBLISH_MODE: ${{ inputs.publish_mode }} + with: + script: | + const { publishGateCheck } = await import(`${process.env.GITHUB_WORKSPACE}/.trusted-review-org/scripts/gate_check.mjs`) + await publishGateCheck(github, core, context, { + prNumber: process.env.GATE_PR_NUMBER, + headSha: process.env.GATE_HEAD_SHA, + conclusion: process.env.GATE_CONCLUSION, + reviewUrl: process.env.GATE_REVIEW_URL, + name: process.env.GATE_CHECK_NAME, + mode: process.env.GATE_PUBLISH_MODE, + }) diff --git a/README.md b/README.md index a884a6c..c216f74 100644 --- a/README.md +++ b/README.md @@ -158,6 +158,108 @@ Minimum secret: `OPENROUTER_API_KEY` passed explicitly (never `secrets: inherit` Branch protection should require `review / openrouter-first-pass-gate`. +### Trusted default-branch review callers (optional) + +The same review workflow also accepts two default-branch caller events. Existing +`pull_request` and `workflow_dispatch` callers need no change. + +- `pull_request_target` (`opened`, `reopened`, `ready_for_review`, + `synchronize`) keeps the `pull_request` split: `synchronize` is a follow-up, + the others are first passes. It runs only when the PR targets the default + branch, so the caller file comes from that branch. GitHub records these runs, + and their native job checks, on the PR head commit. +- `repository_dispatch` from the default branch is a first pass, like + `workflow_dispatch`. A called workflow sees no `github.event.inputs`, and this + workflow never reads `client_payload`; map payload fields into `with:`. + `expected_head_sha` makes the review and gate fail closed when the live PR + head differs from the head the dispatcher saw. Explicit `deep` and `cancel` + levels still require a maintainer and the default branch. + +Under both events the reviewed head is checked out as inert data in jobs that +hold the OpenRouter key. No step runs its code, hooks, submodules, LFS +filters, package scripts or configuration, and a commit that contains the +reserved `.trusted-review-org` or `.trusted-review-action` paths is refused. + +Default-branch dispatch runs attach native job checks to the default-branch +tip, so the required `review / openrouter-first-pass-gate` never reaches the PR +head on its own. `openrouter-review-gate-check.yml` repeats the gate result +(success or failure) as a GitHub Actions check run on the exact head the gate +evaluated. It reads the `gate_*` outputs of the review workflow, publishes only +from default-branch runs, skips heads that moved, and in `auto` mode leaves +pull-request runs to their native check. It is a separate entry point because +it is the only job that needs `checks: write`: GitHub checks reusable-job +permissions against the caller before runtime conditions, and current callers +do not grant that scope. + +```yaml +name: OpenRouter code review +run-name: "${{ format('OpenRouter PR #{0}: {1}', github.event.pull_request.number || github.event.client_payload.pr_number || inputs.pr_number, github.event.client_payload.review_level || inputs.review_level || 'auto') }}" + +on: + pull_request_target: + types: [opened, synchronize, reopened, ready_for_review] + repository_dispatch: + types: [openrouter-review] + workflow_dispatch: + inputs: + pr_number: { required: true, type: string } + review_level: { default: auto, type: choice, options: [auto, deep, cancel] } + +permissions: + actions: write + checks: write + contents: read + pull-requests: write + statuses: write + +jobs: + review: + if: github.event_name != 'pull_request_target' || !github.event.pull_request.draft + uses: RetireGolden/.github/.github/workflows/openrouter-code-review.yml@ + secrets: + OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }} + permissions: + actions: write + contents: read + pull-requests: write + statuses: write + with: + pr_number: ${{ github.event.pull_request.number || github.event.client_payload.pr_number || inputs.pr_number }} + review_level: ${{ github.event.client_payload.review_level || inputs.review_level || 'auto' }} + expected_head_sha: ${{ github.event.client_payload.head_sha || '' }} + review_profiles_enabled: false + review_policy: off + gate-check: + needs: review + if: always() && needs.review.outputs.gate_head_sha != '' + uses: RetireGolden/.github/.github/workflows/openrouter-review-gate-check.yml@ + permissions: + actions: read + checks: write + contents: read + pull-requests: read + with: + pr_number: ${{ needs.review.outputs.gate_pr_number }} + head_sha: ${{ needs.review.outputs.gate_head_sha }} + conclusion: ${{ needs.review.outputs.gate_conclusion }} + review_url: ${{ needs.review.outputs.gate_review_url }} +``` + +Keep the review job id `review`; profile evidence names its jobs +`review / ...`. `gate_check_name` defaults to +`review / openrouter-first-pass-gate`. Bot-sent `repository_dispatch` reviews +wake profile completion the same way bot-sent `workflow_dispatch` reviews do. + +Profile evidence admits these events with the same bounds as before. +`repository_dispatch` runs must be on the default branch, and their caller +blob at the run's default-branch commit must match the trusted caller. A +`pull_request_target` run reports the PR head rather than the commit whose +caller ran. Evidence from it therefore requires every same-repository PR from +that head branch to target the default branch with no recorded base change, +the exact trusted reusable pin, a run head equal to the receipt head, and a PR +whose head branch matches the run. A receipt for an older head never satisfies +a newer one. If a PR was retargeted, push the change on a fresh branch. + ### Thin completion caller (example) Runs only on the default branch. Never executes PR code. @@ -242,7 +344,7 @@ git clone --no-checkout https://github.com/FlyOverCoderKY/openrouter-pr-review-a git -C .trusted-review-action checkout 212775ffea22e806cddcb706c73a3df26fbcb6d0 export PYTHONPATH="$PWD/.trusted-review-action/src" uv run --with jq --with pyyaml python -m unittest discover -s tests -node --test tests/profile-consumer.test.mjs tests/workflow-wakeup.test.mjs +node --test tests/profile-consumer.test.mjs tests/workflow-wakeup.test.mjs tests/gate-check.test.mjs ``` `scripts/profile_consumer.mjs` is the shared Node validator used by existing diff --git a/scripts/gate_check.mjs b/scripts/gate_check.mjs new file mode 100644 index 0000000..40be099 --- /dev/null +++ b/scripts/gate_check.mjs @@ -0,0 +1,137 @@ +// Publishes the first-pass gate result as a check run on the reviewed PR head. +// +// Default-branch dispatch runs (workflow_dispatch, repository_dispatch) attach +// their native job checks to the default-branch tip, so a required +// `review / openrouter-first-pass-gate` check never reaches the PR head. This +// helper repeats the gate's own conclusion on the exact head the gate evaluated. +// Pull-request runs (including pull_request_target) already attach their native +// job checks to the PR head; in `auto` mode they are left alone to avoid +// duplicate check runs with the same name. + +export const DEFAULT_GATE_CHECK_NAME = 'review / openrouter-first-pass-gate'; +export const GITHUB_ACTIONS_APP_ID = 15368; +const SHA_RE = /^[0-9a-f]{40}$/; +const PR_RE = /^[1-9][0-9]{0,9}$/; +const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9 ._/#:()-]{0,99}$/; +const MODES = new Set(['auto', 'always']); +const PULL_REQUEST_EVENTS = new Set(['pull_request', 'pull_request_target']); + +function fail(message) { + throw new Error(message); +} + +export function normalizeGateInputs({ prNumber, headSha, conclusion, reviewUrl, name, mode }, repository) { + const number = String(prNumber ?? ''); + if (!PR_RE.test(number) || !Number.isSafeInteger(Number(number))) fail('pr_number must be a positive integer'); + const sha = String(headSha ?? ''); + if (!SHA_RE.test(sha)) fail('head_sha must be a lowercase full commit SHA'); + const checkName = name === undefined || name === '' ? DEFAULT_GATE_CHECK_NAME : String(name); + if (!NAME_RE.test(checkName)) fail('gate_check_name is invalid'); + const publishMode = mode === undefined || mode === '' ? 'auto' : String(mode); + if (!MODES.has(publishMode)) fail('publish_mode must be auto or always'); + // Anything other than an explicit success is a failed gate (fail closed). + const result = conclusion === 'success' ? 'success' : 'failure'; + const reviewPattern = new RegExp( + `^https://github\\.com/${repository.replace(/[.]/g, '\\.')}/pull/${number}#pullrequestreview-[1-9][0-9]*$`, + ); + const review = typeof reviewUrl === 'string' && reviewPattern.test(reviewUrl) ? reviewUrl : ''; + return { prNumber: Number(number), headSha: sha, conclusion: result, reviewUrl: review, name: checkName, mode: publishMode }; +} + +async function existingCheckRun(github, { owner, repo, headSha, name, externalId }) { + for (let page = 1; page <= 10; page += 1) { + const { data } = await github.request('GET /repos/{owner}/{repo}/commits/{ref}/check-runs', { + owner, repo, ref: headSha, check_name: name, filter: 'all', per_page: 100, page, + }); + const runs = Array.isArray(data?.check_runs) ? data.check_runs : fail('check-run listing is invalid'); + const match = runs.find((run) => run?.external_id === externalId && run?.app?.id === GITHUB_ACTIONS_APP_ID); + if (match) return match; + if (runs.length < 100) return null; + } + fail('check-run listing exceeds its bound'); +} + +/** + * Returns { published, reason, checkRunId? }. Never publishes for a PR head + * other than the one the gate evaluated, and only from default-branch runs. + */ +export async function publishGateCheck(github, core, context, inputs) { + const { owner, repo } = context.repo; + const repository = `${owner}/${repo}`; + const gate = normalizeGateInputs(inputs, repository); + const { data: repoData } = await github.request('GET /repos/{owner}/{repo}', { owner, repo }); + const defaultBranch = repoData?.default_branch; + if (repoData?.full_name !== repository || typeof defaultBranch !== 'string' || !defaultBranch) { + fail('repository identity is invalid'); + } + // A PR-branch caller (pull_request) cannot borrow this publisher: only + // workflows that GitHub ran from the default branch may publish. + if (context.ref !== `refs/heads/${defaultBranch}`) { + return skip(core, 'only default-branch callers publish head-bound gate checks'); + } + if (!Number.isSafeInteger(context.runId) || context.runId <= 0) fail('invalid workflow run id'); + const { data: run } = await github.request('GET /repos/{owner}/{repo}/actions/runs/{run_id}', { + owner, repo, run_id: context.runId, + }); + if (run?.id !== context.runId || run?.repository?.full_name !== repository) fail('workflow run identity is invalid'); + // Native job checks attach to the run's head. For PR events that is already + // the PR head; for default-branch dispatches it is the default-branch tip. + const nativeCoversHead = PULL_REQUEST_EVENTS.has(run.event) || run.head_sha === gate.headSha; + if (gate.mode === 'auto' && nativeCoversHead) { + return skip(core, 'the native gate job check already reports on the pull request head'); + } + const { data: pr } = await github.request('GET /repos/{owner}/{repo}/pulls/{pull_number}', { + owner, repo, pull_number: gate.prNumber, + }); + if (pr?.number !== gate.prNumber || pr?.base?.repo?.full_name !== repository) { + fail('pull request does not belong to this repository'); + } + if (pr.head?.sha !== gate.headSha) { + // The newer head is evaluated by its own run; never move this result onto it. + return skip(core, `pull request head moved from ${gate.headSha}; leaving the newer head to its own run`); + } + const runUrl = `${context.serverUrl}/${repository}/actions/runs/${context.runId}`; + const externalId = `openrouter-first-pass-gate:${context.runId}`; + const passed = gate.conclusion === 'success'; + const lines = [ + passed + ? `The OpenRouter first-pass gate passed for \`${gate.headSha}\`.` + : `The OpenRouter first-pass gate did not pass for \`${gate.headSha}\`.`, + '', + `Evaluated by [workflow run ${context.runId}](${runUrl}) (${run.event}).`, + ]; + if (gate.reviewUrl) lines.push(`Review: ${gate.reviewUrl}`); + const summary = lines.join('\n'); + const payload = { + owner, + repo, + name: gate.name, + head_sha: gate.headSha, + status: 'completed', + conclusion: gate.conclusion, + completed_at: new Date().toISOString(), + details_url: runUrl, + external_id: externalId, + output: { + title: passed ? 'OpenRouter first-pass gate passed' : 'OpenRouter first-pass gate failed', + summary, + }, + }; + const existing = await existingCheckRun(github, { owner, repo, headSha: gate.headSha, name: gate.name, externalId }); + let data; + if (existing) { + ({ data } = await github.request('PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}', { + ...payload, check_run_id: existing.id, + })); + } else { + ({ data } = await github.request('POST /repos/{owner}/{repo}/check-runs', payload)); + } + if (data?.head_sha !== gate.headSha || data?.name !== gate.name) fail('check run response does not match the request'); + core.info(`Published ${gate.name}=${gate.conclusion} on ${gate.headSha} (check run ${data.id}).`); + return { published: true, reason: 'published', checkRunId: data.id }; +} + +function skip(core, reason) { + core.info(`Gate check not published: ${reason}.`); + return { published: false, reason }; +} diff --git a/scripts/profile_completion.py b/scripts/profile_completion.py index 74eb7b5..4726c8f 100644 --- a/scripts/profile_completion.py +++ b/scripts/profile_completion.py @@ -31,6 +31,8 @@ from or_pr_review.review_policy import resolve_policy from scripts.profile_github import ( + DEFAULT_BRANCH_EVENTS, + PULL_REQUEST_EVENTS, ProfileGitHub, ProfileGitHubError, VerifiedRun, @@ -410,7 +412,9 @@ def _prove_review( verified = self._verify_source(run) self._require_successful_run(verified) self._reviewing_job(verified) - self._bind_source_heads(verified, marker_receipt.head_sha) + self._bind_source_heads( + verified, marker_receipt.head_sha, marker_receipt.pr_number + ) receipt_bytes = self._client.artifact( verified, receipt_artifact_name(run_id, attempt), @@ -546,13 +550,29 @@ def _reviewing_job(self, verified: VerifiedRun) -> str: ) return matches[0] - def _bind_source_heads(self, verified: VerifiedRun, receipt_head_sha: str) -> None: - if verified.event == "pull_request": + def _bind_source_heads( + self, verified: VerifiedRun, receipt_head_sha: str, pr_number: int + ) -> None: + if verified.event in PULL_REQUEST_EVENTS: if verified.head_sha != receipt_head_sha: raise ProfileCompletionError( "receipt head SHA does not match the verified pull request run" ) - elif verified.event == "workflow_dispatch": + if verified.event == "pull_request_target": + # The run names its triggering PR only by head branch and SHA. + pr = self._client.get_pr(pr_number) + head = pr.get("head") + head_repo = head.get("repo") if isinstance(head, Mapping) else None + if ( + not isinstance(head, Mapping) + or head.get("ref") != verified.head_branch + or not isinstance(head_repo, Mapping) + or head_repo.get("full_name") != self.repository + ): + raise ProfileCompletionError( + "receipt pull request is not the verified run's head branch" + ) + elif verified.event in DEFAULT_BRANCH_EVENTS: if verified.head_branch != self._client.config.default_branch: raise ProfileCompletionError( "dispatch run is not on the default branch" diff --git a/scripts/profile_consumer.mjs b/scripts/profile_consumer.mjs index 07910e1..c5f2068 100644 --- a/scripts/profile_consumer.mjs +++ b/scripts/profile_consumer.mjs @@ -59,7 +59,18 @@ const REVIEW_PIN_RE = const DISPATCH_TITLE_RE = /^OpenRouter PR #([1-9][0-9]*): (auto|deep|cancel)$/; const PROOF_JOB_RE = /^complete \/ profile #([1-9][0-9]*) ([0-9a-f]{64})$/; const COMPLETION_EVENTS = new Set(['workflow_run', 'push', 'workflow_dispatch']); -const REVIEW_EVENTS = new Set(['pull_request', 'workflow_dispatch']); +const PULL_REQUEST_EVENTS = new Set(['pull_request', 'pull_request_target']); +const DEFAULT_BRANCH_EVENTS = new Set(['workflow_dispatch', 'repository_dispatch']); +const REVIEW_EVENTS = new Set([...PULL_REQUEST_EVENTS, ...DEFAULT_BRANCH_EVENTS]); +export const MAX_HEAD_PULL_REQUESTS = 100; +// Keep in step with scripts/profile_github.py. +const HEAD_PULLS_QUERY = + 'query($owner: String!, $name: String!, $head: String!) {' + + ' repository(owner: $owner, name: $name) {' + + ` pullRequests(headRefName: $head, first: ${MAX_HEAD_PULL_REQUESTS}, states: [OPEN, CLOSED, MERGED]) {` + + ' totalCount nodes { number baseRefName headRepository { nameWithOwner }' + + ' timelineItems(itemTypes: [BASE_REF_CHANGED_EVENT, AUTOMATIC_BASE_CHANGE_SUCCEEDED_EVENT], first: 1) { totalCount } } } } }'; +const BRANCH_RE = /^[^\x00-\x1f\x7f ~^:?*\[\\]{1,255}$/; function unauthorized(reason) { return { authorized: false, reason }; @@ -197,6 +208,50 @@ async function activeWorkflow(github, owner, repo, path) { return data.id; } +// pull_request_target runs report the PR head, but GitHub executes the caller +// from the PR's base branch at event time. Require every same-repository PR from +// that head branch to target the default branch with no recorded base change. +export async function verifyTargetBase(github, { owner, repo, repository, defaultBranch }, headBranch) { + if (typeof headBranch !== 'string' || !BRANCH_RE.test(headBranch)) { + throw new Error('pull_request_target run has an invalid head branch'); + } + if (typeof github?.graphql !== 'function') { + throw new Error('GraphQL client is unavailable for pull_request_target provenance'); + } + const data = await github.graphql(HEAD_PULLS_QUERY, { owner, name: repo, head: headBranch }); + const pulls = data?.repository?.pullRequests; + const nodes = pulls?.nodes; + if ( + !Array.isArray(nodes) || + !Number.isInteger(pulls?.totalCount) || + pulls.totalCount !== nodes.length || + pulls.totalCount > MAX_HEAD_PULL_REQUESTS + ) { + throw new Error('head branch pull requests are unavailable or unbounded'); + } + const numbers = []; + for (const node of nodes) { + if (!node || typeof node !== 'object') { + throw new Error('head branch pull request entry is invalid'); + } + if (node.headRepository?.nameWithOwner !== repository.full_name) { + continue; + } + const changed = node.timelineItems?.totalCount; + if (!Number.isInteger(node.number) || node.number <= 0 || !Number.isInteger(changed)) { + throw new Error('head branch pull request entry is invalid'); + } + if (node.baseRefName !== defaultBranch || changed !== 0) { + throw new Error('pull_request_target head branch has a non-default or changed base'); + } + numbers.push(node.number); + } + if (numbers.length === 0) { + throw new Error('pull_request_target run has no default-branch pull request'); + } + return numbers.sort((left, right) => left - right); +} + async function verifyReviewRunProvenance( github, { owner, repo, repository, defaultBranch, reviewPin, trustedCallerSha }, @@ -211,7 +266,7 @@ async function verifyReviewRunProvenance( if (!REVIEW_EVENTS.has(run.event)) { throw new Error('review run event is not trusted'); } - if (run.event === 'workflow_dispatch' && run.head_branch !== defaultBranch) { + if (DEFAULT_BRANCH_EVENTS.has(run.event) && run.head_branch !== defaultBranch) { throw new Error('dispatch review run is not on the default branch'); } const workflowId = await activeWorkflow(github, owner, repo, REVIEW_CALLER_PATH); @@ -222,6 +277,10 @@ async function verifyReviewRunProvenance( if (!reusablePinned(run, expectedReusable, reviewPin)) { throw new Error('review run lacks the exact trusted reusable workflow pin'); } + if (run.event === 'pull_request_target') { + await verifyTargetBase(github, { owner, repo, repository, defaultBranch }, run.head_branch); + return; + } const headBlob = await readCallerBlob(github, owner, repo, run.head_sha); if (headBlob.sha !== trustedCallerSha) { throw new Error('review run caller blob differs from trusted default caller'); @@ -546,7 +605,7 @@ function proofJobFor(jobs, pullNumber, receiptDigest) { } function runMatchesPull(run, pullNumber, headSha) { - if (run.event === 'workflow_dispatch') { + if (DEFAULT_BRANCH_EVENTS.has(run.event)) { const titleMatch = typeof run.display_title === 'string' ? DISPATCH_TITLE_RE.exec(run.display_title) : null; return Boolean(titleMatch && Number(titleMatch[1]) === pullNumber); @@ -688,6 +747,15 @@ export async function authorizeProfileReceipt( if (reviewRun.status !== 'completed' || reviewRun.conclusion !== 'success') { return unauthorized('review run is not successful'); } + if (PULL_REQUEST_EVENTS.has(reviewRun.event)) { + // A pull-request run reviews its own head; an older head never satisfies a newer one. + if (reviewRun.head_sha !== expectedHead) { + return unauthorized('review run head SHA does not match the receipt head'); + } + if (reviewRun.event === 'pull_request_target' && livePr.pr.head?.ref !== reviewRun.head_branch) { + return unauthorized('review run head branch does not match the pull request'); + } + } if (receipt.run_url !== reviewRunUrl || receipt.run_attempt !== reviewRunAttempt) { return unauthorized('receipt does not bind to the supplied review run'); } diff --git a/scripts/profile_gate.py b/scripts/profile_gate.py index a278339..7810a44 100644 --- a/scripts/profile_gate.py +++ b/scripts/profile_gate.py @@ -35,6 +35,8 @@ VerifiedReview, ) from scripts.profile_github import ( + DEFAULT_BRANCH_EVENTS, + PULL_REQUEST_EVENTS, ProfileGitHub, ProfileGitHubError, TrustedWorkflow, @@ -189,6 +191,22 @@ def _file_at(source: Path, commit: str, path: str = CALLER_PATH) -> tuple[str, b return blob, content +def _referenced_pin(run: Mapping[str, Any]) -> str: + """Return the run's single org review workflow pin as GitHub attested it.""" + references = run.get("referenced_workflows") if isinstance(run, Mapping) else None + pins = { + match.group(1) + for item in (references if isinstance(references, list) else ()) + if isinstance(item, Mapping) + and isinstance(item.get("path"), str) + and (match := PIN.fullmatch(item["path"])) is not None + and item.get("sha") == match.group(1) + } + if len(pins) != 1: + raise ProfileGitHubError("run lacks exactly one org review workflow pin") + return pins.pop() + + def _caller_pin(content: bytes) -> str: try: text = content.decode("utf-8", "strict") @@ -202,6 +220,13 @@ def _caller_pin(content: bytes) -> str: return pins[0] +def _caller_pin_or_none(content: bytes) -> Optional[str]: + try: + return _caller_pin(content) + except GateError: + return None + + def _repository_parts() -> tuple[str, str]: value = _env("GITHUB_REPOSITORY") parts = value.split("/") @@ -292,6 +317,17 @@ def verify(run: Mapping[str, Any]) -> VerifiedRun: head = run.get("head_sha") if isinstance(run, Mapping) else None if not isinstance(head, str) or not SHA.fullmatch(head): raise ProfileGitHubError("workflow run lacks a full commit SHA") + if run.get("event") == "pull_request_target": + # Its caller came from the default branch (verify_run proves the base), + # so the reusable pin must be one that trusted default history used. + pin = _referenced_pin(run) + for blob, content in candidates.items(): + if _caller_pin_or_none(content) == pin: + historical = _configured_client(client, default_branch, pin) + return historical.verify_run(run, blob, require_success=False) + raise ProfileGitHubError( + "run reusable pin is not reachable from trusted default history" + ) actual_blob = client._content_blob(head) content = candidates.get(actual_blob) if content is None: @@ -691,13 +727,13 @@ def begin() -> None: bare, current_blob, pin_matches_main=pin_matches_main ) event = _env("GITHUB_EVENT_NAME") + default_ref = f"refs/heads/{bare.config.default_branch}" + if event == "pull_request_target" and _env("GITHUB_REF") != default_ref: + raise GateError("pull_request_target reviews require a default-branch base") if level in {"deep", "cancel"}: - if ( - event != "workflow_dispatch" - or _env("GITHUB_REF") != f"refs/heads/{bare.config.default_branch}" - ): + if event not in DEFAULT_BRANCH_EVENTS or _env("GITHUB_REF") != default_ref: raise GateError( - "explicit deep and cancel require default-branch workflow_dispatch" + "explicit deep and cancel require a default-branch dispatch" ) actor = os.environ.get("GITHUB_TRIGGERING_ACTOR", "") or _env("GITHUB_ACTOR") if not bare.maintainer(actor): @@ -962,7 +998,7 @@ def _active_matching_run( if not isinstance(run, Mapping) or run.get("status") == "completed": continue if not _run_plausible_pr(run, number) and not ( - run.get("event") == "pull_request" and run.get("head_sha") == head + run.get("event") in PULL_REQUEST_EVENTS and run.get("head_sha") == head ): continue try: @@ -972,7 +1008,7 @@ def _active_matching_run( # work for the PR. Defer additional paid work until it finishes. return True if _run_plausible_pr(verified.run, number) or ( - verified.event == "pull_request" and verified.head_sha == head + verified.event in PULL_REQUEST_EVENTS and verified.head_sha == head ): return True return False @@ -1038,7 +1074,13 @@ def _is_current_receipt_source( client: ProfileGitHub, review: VerifiedReview, current_blob: str ) -> bool: """Keep historical proof separate from the stronger current-producer proof.""" - if client._content_blob(review.source.head_sha) != current_blob: + if review.source.event == "pull_request_target": + # The executed caller is the default branch's; re-prove that base below. + try: + client.verify_target_base(review.source.head_branch) + except ProfileGitHubError: + return False + elif client._content_blob(review.source.head_sha) != current_blob: return False expected = f"{client.config.reusable_path}@{client.config.reusable_sha}" references = review.source.run.get("referenced_workflows") @@ -1180,6 +1222,9 @@ def _source_pr( match = TITLE.fullmatch(title) if isinstance(title, str) else None if match: return int(match.group(1)) + if verified.event == "repository_dispatch": + # Default-branch runs list PRs that merely share the default-branch head. + raise GateError("source dispatch run title does not identify a pull request") pulls = verified.run.get("pull_requests") if ( not isinstance(pulls, list) diff --git a/scripts/profile_github.py b/scripts/profile_github.py index 4dce05b..adfdbc9 100644 --- a/scripts/profile_github.py +++ b/scripts/profile_github.py @@ -26,6 +26,23 @@ _SHA = re.compile(r"^[0-9a-f]{40}$") _LOGIN = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$") _REPOSITORY = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]*$") +_BRANCH = re.compile(r"^[^\x00-\x1f\x7f ~^:?*\[\\]{1,255}$") + +# Review caller events. Pull-request events run for the PR head; dispatches run +# from the default branch and name the PR through workflow inputs. +PULL_REQUEST_EVENTS = frozenset({"pull_request", "pull_request_target"}) +DEFAULT_BRANCH_EVENTS = frozenset({"workflow_dispatch", "repository_dispatch"}) +REVIEW_EVENTS = PULL_REQUEST_EVENTS | DEFAULT_BRANCH_EVENTS +MAX_HEAD_PULL_REQUESTS = 100 +# A base change means earlier pull_request_target runs used another branch's caller. +_BASE_CHANGE_ITEMS = "BASE_REF_CHANGED_EVENT, AUTOMATIC_BASE_CHANGE_SUCCEEDED_EVENT" +_HEAD_PULLS_QUERY = ( + "query($owner: String!, $name: String!, $head: String!) {" + " repository(owner: $owner, name: $name) {" + " pullRequests(headRefName: $head, first: %d, states: [OPEN, CLOSED, MERGED]) {" + " totalCount nodes { number baseRefName headRepository { nameWithOwner }" + " timelineItems(itemTypes: [%s], first: 1) { totalCount } } } } }" +) % (MAX_HEAD_PULL_REQUESTS, _BASE_CHANGE_ITEMS) class ProfileGitHubError(RuntimeError): @@ -417,18 +434,18 @@ def verify_run( event = run.get("event") if not isinstance(path, str) or path != self.config.caller_path: raise ProfileGitHubError("workflow run has an untrusted caller or event") - if not isinstance(event, str) or event not in { - "pull_request", - "workflow_dispatch", - }: + if not isinstance(event, str) or event not in REVIEW_EVENTS: raise ProfileGitHubError("workflow run has an untrusted caller or event") head_branch = run.get("head_branch") - if event == "workflow_dispatch": + if event in DEFAULT_BRANCH_EVENTS: if ( not isinstance(head_branch, str) or head_branch != self.config.default_branch ): raise ProfileGitHubError("dispatch run is not on the default branch") + elif event == "pull_request_target": + if not isinstance(head_branch, str) or not _BRANCH.fullmatch(head_branch): + raise ProfileGitHubError("workflow run has an invalid head branch") elif head_branch is not None and not isinstance(head_branch, str): raise ProfileGitHubError("workflow run has an invalid head branch") status = run.get("status") @@ -472,7 +489,12 @@ def verify_run( raise ProfileGitHubError( "run lacks the exact trusted reusable workflow pin" ) - if self._content_blob(head_sha) != trusted_blob: + if event == "pull_request_target": + # GitHub reports the PR head for these runs, but executes the caller + # from the PR's base branch. Prove that base was always the default + # branch; the exact reusable pin was checked above. + self.verify_target_base(head_branch) + elif self._content_blob(head_sha) != trusted_blob: raise ProfileGitHubError( "exact-head caller blob differs from trusted default caller" ) @@ -495,6 +517,75 @@ def verify_run( tuple(jobs), ) + def _graphql(self, query: str, variables: Mapping[str, str]) -> Mapping[str, Any]: + value = self._api( + "/graphql", + method="POST", + payload={"query": query, "variables": dict(variables)}, + ) + if ( + not isinstance(value, Mapping) + or value.get("errors") + or not isinstance(value.get("data"), Mapping) + ): + raise ProfileGitHubError("GitHub GraphQL response is invalid") + return value["data"] + + def verify_target_base(self, head_branch: str) -> tuple[int, ...]: + """Prove pull_request_target runs from ``head_branch`` used the default caller. + + GitHub runs pull_request_target with the workflow file from the PR's base + branch at event time. The run API exposes only the PR head, so require + every same-repository PR from this head branch to target the default branch + without any recorded base change. A PR that was ever retargeted (or one + from the same branch into another base) fails closed; open a fresh branch. + """ + if not isinstance(head_branch, str) or not _BRANCH.fullmatch(head_branch): + raise ProfileGitHubError("pull_request_target run has an invalid head branch") + data = self._graphql( + _HEAD_PULLS_QUERY, + {"owner": self.config.owner, "name": self.config.name, "head": head_branch}, + ) + repository = data.get("repository") + pulls = repository.get("pullRequests") if isinstance(repository, Mapping) else None + nodes = pulls.get("nodes") if isinstance(pulls, Mapping) else None + total = pulls.get("totalCount") if isinstance(pulls, Mapping) else None + if ( + not isinstance(nodes, list) + or not isinstance(total, int) + or isinstance(total, bool) + or total != len(nodes) + or total > MAX_HEAD_PULL_REQUESTS + ): + raise ProfileGitHubError("head branch pull requests are unavailable or unbounded") + numbers: list[int] = [] + for node in nodes: + if not isinstance(node, Mapping): + raise ProfileGitHubError("head branch pull request entry is invalid") + head_repo = node.get("headRepository") + owner = head_repo.get("nameWithOwner") if isinstance(head_repo, Mapping) else None + if owner != self.config.full_name: + continue # Fork runs are rejected by head_repository; forks cannot retarget ours. + number = node.get("number") + changes = node.get("timelineItems") + changed = changes.get("totalCount") if isinstance(changes, Mapping) else None + if ( + not isinstance(number, int) + or isinstance(number, bool) + or number <= 0 + or not isinstance(changed, int) + or isinstance(changed, bool) + ): + raise ProfileGitHubError("head branch pull request entry is invalid") + if node.get("baseRefName") != self.config.default_branch or changed != 0: + raise ProfileGitHubError( + "pull_request_target head branch has a non-default or changed base" + ) + numbers.append(number) + if not numbers: + raise ProfileGitHubError("pull_request_target run has no default-branch pull request") + return tuple(sorted(numbers)) + @staticmethod def _safe_artifact_url(location: str) -> str: parsed = urllib.parse.urlsplit(location) diff --git a/scripts/profile_requests.py b/scripts/profile_requests.py index f2404e7..032af8a 100644 --- a/scripts/profile_requests.py +++ b/scripts/profile_requests.py @@ -22,6 +22,7 @@ from or_pr_review.review_context import restore_context from scripts.profile_github import ( + PULL_REQUEST_EVENTS, ProfileGitHub, ProfileGitHubError, VerifiedRun, @@ -713,7 +714,8 @@ def _prove_record( raise ProfileRequestError( "accepted request does not match the verified workflow run" ) - if verified.event == "pull_request" and record.head_sha != verified.head_sha: + # Pull-request events run for the PR head; dispatches bind it via the live PR. + if verified.event in PULL_REQUEST_EVENTS and record.head_sha != verified.head_sha: raise ProfileRequestError( "accepted request head SHA does not match the verified run" ) diff --git a/scripts/workflow_wakeup.mjs b/scripts/workflow_wakeup.mjs index 88f590f..bc45c7f 100644 --- a/scripts/workflow_wakeup.mjs +++ b/scripts/workflow_wakeup.mjs @@ -4,7 +4,9 @@ export async function dispatchWorkflowWake(github, core, context, target, optional = false) { const allowed = new Set(['openrouter-profile-completion.yml', 'openrouter-ci-broker.yml']); if (!allowed.has(target)) throw new Error('unsupported completion wake target'); - if (context.eventName !== 'workflow_dispatch' || context.actor !== 'github-actions[bot]') { + // Bot-sent workflow_dispatch and repository_dispatch runs suppress workflow_run. + const dispatched = context.eventName === 'workflow_dispatch' || context.eventName === 'repository_dispatch'; + if (!dispatched || context.actor !== 'github-actions[bot]') { return core.info('Native completion events cover this run'); } if (!Number.isSafeInteger(context.runId) || context.runId <= 0) { diff --git a/tests/gate-check.test.mjs b/tests/gate-check.test.mjs new file mode 100644 index 0000000..ef72b5e --- /dev/null +++ b/tests/gate-check.test.mjs @@ -0,0 +1,173 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + DEFAULT_GATE_CHECK_NAME, + GITHUB_ACTIONS_APP_ID, + normalizeGateInputs, + publishGateCheck, +} from '../scripts/gate_check.mjs'; + +const HEAD = 'a'.repeat(40); +const MAIN = 'b'.repeat(40); +const REPOSITORY = 'RetireGolden/example'; +const REVIEW_URL = `https://github.com/${REPOSITORY}/pull/7#pullrequestreview-99`; + +function fixture({ run = {}, pr = {}, context = {}, existing = [] } = {}) { + const calls = []; + const state = { + repo: { full_name: REPOSITORY, default_branch: 'main' }, + run: { id: 42, event: 'repository_dispatch', head_sha: MAIN, head_branch: 'main', repository: { full_name: REPOSITORY }, ...run }, + pr: { number: 7, head: { sha: HEAD }, base: { repo: { full_name: REPOSITORY } }, ...pr }, + }; + const github = { + request: async (route, params = {}) => { + calls.push([route, params]); + switch (route) { + case 'GET /repos/{owner}/{repo}': + return { data: state.repo }; + case 'GET /repos/{owner}/{repo}/actions/runs/{run_id}': + return { data: state.run }; + case 'GET /repos/{owner}/{repo}/pulls/{pull_number}': + return { data: state.pr }; + case 'GET /repos/{owner}/{repo}/commits/{ref}/check-runs': + return { data: { check_runs: existing } }; + case 'POST /repos/{owner}/{repo}/check-runs': + return { data: { id: 501, head_sha: params.head_sha, name: params.name } }; + case 'PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}': + return { data: { id: params.check_run_id, head_sha: params.head_sha, name: params.name } }; + default: + throw new Error(`unexpected route ${route}`); + } + }, + }; + const ctx = { + repo: { owner: 'RetireGolden', repo: 'example' }, + ref: 'refs/heads/main', + runId: 42, + serverUrl: 'https://github.com', + ...context, + }; + const core = { info() {} }; + return { github, core, ctx, calls }; +} + +const inputs = (overrides = {}) => ({ + prNumber: '7', headSha: HEAD, conclusion: 'success', reviewUrl: REVIEW_URL, name: '', mode: '', ...overrides, +}); + +const writes = (calls) => calls.filter(([route]) => !route.startsWith('GET ')); + +test('default-branch dispatch publishes the gate result on the evaluated PR head', async () => { + for (const event of ['repository_dispatch', 'workflow_dispatch']) { + const f = fixture({ run: { event } }); + const result = await publishGateCheck(f.github, f.core, f.ctx, inputs()); + assert.deepEqual(result, { published: true, reason: 'published', checkRunId: 501 }); + const [[route, payload]] = writes(f.calls); + assert.equal(route, 'POST /repos/{owner}/{repo}/check-runs'); + assert.equal(payload.name, DEFAULT_GATE_CHECK_NAME); + assert.equal(payload.head_sha, HEAD); + assert.notEqual(payload.head_sha, MAIN); + assert.equal(payload.status, 'completed'); + assert.equal(payload.conclusion, 'success'); + assert.equal(payload.details_url, 'https://github.com/RetireGolden/example/actions/runs/42'); + assert.equal(payload.external_id, 'openrouter-first-pass-gate:42'); + assert.match(payload.output.summary, /pullrequestreview-99/); + assert.match(payload.output.summary, new RegExp(event)); + } +}); + +test('a failed or missing gate conclusion publishes failure', async () => { + for (const conclusion of ['failure', '', undefined, 'cancelled', 'SUCCESS']) { + const f = fixture(); + await publishGateCheck(f.github, f.core, f.ctx, inputs({ conclusion })); + const [[, payload]] = writes(f.calls); + assert.equal(payload.conclusion, 'failure'); + assert.equal(payload.output.title, 'OpenRouter first-pass gate failed'); + } +}); + +test('an existing check from the same run is updated instead of duplicated', async () => { + const f = fixture({ + existing: [ + { id: 7, external_id: 'openrouter-first-pass-gate:41', app: { id: GITHUB_ACTIONS_APP_ID } }, + { id: 8, external_id: 'openrouter-first-pass-gate:42', app: { id: 999 } }, + { id: 9, external_id: 'openrouter-first-pass-gate:42', app: { id: GITHUB_ACTIONS_APP_ID } }, + ], + }); + const result = await publishGateCheck(f.github, f.core, f.ctx, inputs({ conclusion: 'failure' })); + assert.equal(result.checkRunId, 9); + const [[route, payload]] = writes(f.calls); + assert.equal(route, 'PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}'); + assert.equal(payload.check_run_id, 9); + assert.equal(payload.conclusion, 'failure'); +}); + +test('a configurable name keeps the required check contract', async () => { + const f = fixture(); + await publishGateCheck(f.github, f.core, f.ctx, inputs({ name: 'openrouter / openrouter-first-pass-gate' })); + assert.equal(writes(f.calls)[0][1].name, 'openrouter / openrouter-first-pass-gate'); +}); + +test('pull-request runs leave the head to their native job check in auto mode', async () => { + for (const run of [ + { event: 'pull_request_target', head_sha: HEAD, head_branch: 'topic' }, + { event: 'pull_request_target', head_sha: MAIN, head_branch: 'topic' }, + { event: 'pull_request', head_sha: HEAD, head_branch: 'topic' }, + // A dispatch whose default-branch tip equals the PR head is already covered. + { event: 'repository_dispatch', head_sha: HEAD, head_branch: 'main' }, + ]) { + const f = fixture({ run }); + const result = await publishGateCheck(f.github, f.core, f.ctx, inputs()); + assert.equal(result.published, false); + assert.deepEqual(writes(f.calls), []); + } + const f = fixture({ run: { event: 'pull_request_target', head_sha: HEAD, head_branch: 'topic' } }); + const result = await publishGateCheck(f.github, f.core, f.ctx, inputs({ mode: 'always' })); + assert.equal(result.published, true); +}); + +test('non-default refs never publish, so branch callers cannot borrow it', async () => { + for (const ref of ['refs/pull/7/merge', 'refs/heads/topic', '']) { + const f = fixture({ context: { ref } }); + const result = await publishGateCheck(f.github, f.core, f.ctx, inputs({ mode: 'always' })); + assert.equal(result.published, false); + assert.deepEqual(f.calls.map(([route]) => route), ['GET /repos/{owner}/{repo}']); + } +}); + +test('a moved PR head is left to its own run', async () => { + const f = fixture({ pr: { head: { sha: 'c'.repeat(40) } } }); + const result = await publishGateCheck(f.github, f.core, f.ctx, inputs()); + assert.equal(result.published, false); + assert.match(result.reason, /head moved/); + assert.deepEqual(writes(f.calls), []); +}); + +test('forged numbers, heads, names, modes and foreign PRs fail closed', async () => { + for (const overrides of [ + { prNumber: '0' }, { prNumber: '7/../8' }, { prNumber: '' }, { headSha: HEAD.toUpperCase() }, + { headSha: 'main' }, { name: 'x'.repeat(101) }, { name: 'bad\nname' }, { mode: 'force' }, + ]) { + const f = fixture(); + await assert.rejects(publishGateCheck(f.github, f.core, f.ctx, inputs(overrides))); + assert.deepEqual(writes(f.calls), []); + } + for (const pr of [{ number: 8 }, { base: { repo: { full_name: 'fork/example' } } }]) { + const f = fixture({ pr }); + await assert.rejects(publishGateCheck(f.github, f.core, f.ctx, inputs())); + assert.deepEqual(writes(f.calls), []); + } + const f = fixture({ run: { id: 43 } }); + await assert.rejects(publishGateCheck(f.github, f.core, f.ctx, inputs())); +}); + +test('review links outside this PR are dropped from the summary', () => { + for (const reviewUrl of [ + 'https://github.com/RetireGolden/example/pull/8#pullrequestreview-1', + 'https://evil.example/RetireGolden/example/pull/7#pullrequestreview-1', + 'javascript:alert(1)', + ]) { + assert.equal(normalizeGateInputs(inputs({ reviewUrl }), REPOSITORY).reviewUrl, ''); + } + assert.equal(normalizeGateInputs(inputs(), REPOSITORY).reviewUrl, REVIEW_URL); +}); diff --git a/tests/profile-consumer.test.mjs b/tests/profile-consumer.test.mjs index f09d169..52e135f 100644 --- a/tests/profile-consumer.test.mjs +++ b/tests/profile-consumer.test.mjs @@ -226,6 +226,18 @@ function buildStore(options = {}) { }; const github = { + graphql: async (query, variables) => { + store.graphqlCalls = [...(store.graphqlCalls ?? []), { query, variables }]; + const nodes = options.targetPulls ?? [ + { + number: PULL_NUMBER, + baseRefName: DEFAULT_BRANCH, + headRepository: { nameWithOwner: REPOSITORY.full_name }, + timelineItems: { totalCount: 0 }, + }, + ]; + return { repository: { pullRequests: { totalCount: options.targetTotal ?? nodes.length, nodes } } }; + }, request: async (route, params = {}) => { if (route === 'GET /repos/{owner}/{repo}') { return { data: { default_branch: DEFAULT_BRANCH } }; @@ -254,7 +266,7 @@ function buildStore(options = {}) { state: 'open', draft: false, created_at: options.createdAt ?? PR_CREATED_AT, - head: { sha: store.headSha, repo: REPOSITORY }, + head: { sha: store.headSha, ref: options.headRef ?? 'topic', repo: REPOSITORY }, base: { sha: resolvedBaseSha, ref: DEFAULT_BRANCH, repo: REPOSITORY }, }, }; @@ -660,6 +672,134 @@ describe('authorizeProfileReceipt', () => { }); }); +describe('authorizeProfileReceipt trusted caller events', () => { + const target = { event: 'pull_request_target', head_branch: 'topic' }; + const targetPull = (overrides = {}) => ({ + number: PULL_NUMBER, + baseRefName: DEFAULT_BRANCH, + headRepository: { nameWithOwner: REPOSITORY.full_name }, + timelineItems: { totalCount: 0 }, + ...overrides, + }); + + it('authorizes a pull_request_target review from a default-base head branch', async () => { + // The PR head's own caller file never ran, so its blob is irrelevant. + const { github, store } = buildStore({ + reviewRunOverrides: target, + reviewRuns: [reviewRun(target)], + headCallerSha: '5'.repeat(40), + }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, true, result.reason); + assert.equal(store.graphqlCalls.length, 1); + assert.deepEqual(store.graphqlCalls[0].variables, { owner: OWNER, name: REPO, head: 'topic' }); + assert.match(store.graphqlCalls[0].query, /BASE_REF_CHANGED_EVENT/); + assert.match(store.graphqlCalls[0].query, /AUTOMATIC_BASE_CHANGE_SUCCEEDED_EVENT/); + }); + + it('ignores fork PRs that share the head branch name', async () => { + const { github, store } = buildStore({ + reviewRunOverrides: target, + reviewRuns: [reviewRun(target)], + targetPulls: [ + targetPull(), + targetPull({ number: 8, baseRefName: 'release', headRepository: { nameWithOwner: 'fork/example' } }), + targetPull({ number: 9, headRepository: null }), + ], + }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, true, result.reason); + }); + + it('rejects retargeted, non-default, unbounded or missing head-branch PRs', async () => { + for (const options of [ + { targetPulls: [targetPull({ timelineItems: { totalCount: 1 } })] }, + { targetPulls: [targetPull({ baseRefName: 'release' })] }, + { targetPulls: [targetPull(), targetPull({ number: 8, baseRefName: 'release' })] }, + { targetPulls: [] }, + { targetPulls: [targetPull()], targetTotal: 2 }, + { targetPulls: [targetPull({ timelineItems: null })] }, + ]) { + const { github, store } = buildStore({ reviewRunOverrides: target, reviewRuns: [reviewRun(target)], ...options }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, false); + assert.match(result.reason, /head branch|default-branch pull request/i); + } + }); + + it('rejects stale pull-request heads and a mismatched head branch', async () => { + for (const event of ['pull_request', 'pull_request_target']) { + const overrides = { event, head_branch: 'topic', head_sha: 'e'.repeat(40) }; + const { github, store } = buildStore({ reviewRunOverrides: overrides, reviewRuns: [reviewRun(overrides)] }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, false); + assert.match(result.reason, /head SHA does not match the receipt head/); + } + const { github, store } = buildStore({ reviewRunOverrides: target, reviewRuns: [reviewRun(target)], headRef: 'other' }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, false); + assert.match(result.reason, /head branch does not match/); + }); + + it('rejects pull_request_target runs from fork heads or without the trusted pin', async () => { + for (const overrides of [ + { ...target, head_repository: { full_name: 'fork/example' } }, + { ...target, referenced_workflows: [] }, + { ...target, head_branch: 'bad branch' }, + ]) { + const { github, store } = buildStore({ reviewRunOverrides: overrides, reviewRuns: [reviewRun(overrides)] }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, false); + } + }); + + it('authorizes repository_dispatch only from the default branch caller', async () => { + const dispatch = { event: 'repository_dispatch', head_branch: DEFAULT_BRANCH, head_sha: MAIN_SHA, display_title: `OpenRouter PR #${PULL_NUMBER}: deep` }; + let built = buildStore({ reviewRunOverrides: dispatch, reviewRuns: [reviewRun(dispatch)] }); + let result = await authorizeProfileReceipt(built.github, authorizeContext(built.store)); + assert.equal(result.authorized, true, result.reason); + assert.equal(built.store.graphqlCalls, undefined); + built = buildStore({ reviewRunOverrides: { ...dispatch, head_branch: 'topic' } }); + result = await authorizeProfileReceipt(built.github, authorizeContext(built.store)); + assert.equal(result.authorized, false); + assert.match(result.reason, /default branch/); + built = buildStore({ reviewRunOverrides: { ...dispatch, head_sha: '6'.repeat(40) }, headCallerSha: '5'.repeat(40) }); + result = await authorizeProfileReceipt(built.github, authorizeContext(built.store)); + assert.equal(result.authorized, false); + assert.match(result.reason, /caller blob/); + }); + + it('blocks on an active repository_dispatch review titled for this PR', async () => { + const dispatch = { event: 'repository_dispatch', head_branch: DEFAULT_BRANCH, head_sha: MAIN_SHA }; + const { github, store } = buildStore({ + reviewRuns: [ + reviewRun(), + reviewRun({ ...dispatch, id: 101, status: 'in_progress', conclusion: null, display_title: `OpenRouter PR #${PULL_NUMBER}: auto` }), + ], + }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, false); + assert.match(result.reason, /still active/); + // Default-branch runs list PRs that merely share the default head; titles decide. + const other = buildStore({ + reviewRuns: [ + reviewRun(), + reviewRun({ ...dispatch, id: 102, status: 'in_progress', conclusion: null, display_title: 'OpenRouter PR #99: auto', pull_requests: [{ number: PULL_NUMBER }] }), + ], + }); + assert.equal((await authorizeProfileReceipt(other.github, authorizeContext(other.store))).authorized, true); + }); + + it('keeps rejecting untrusted review events', async () => { + for (const event of ['push', 'workflow_run', 'pull_request_review']) { + const { github, store } = buildStore({ reviewRunOverrides: { event } }); + const result = await authorizeProfileReceipt(github, authorizeContext(store)); + assert.equal(result.authorized, false); + assert.match(result.reason, /event is not trusted/); + } + }); +}); + describe('completionPullRequests', () => { it('returns only PR numbers from successful completed proof jobs', async () => { const { github, store } = buildStore(); diff --git a/tests/test_profile_completion.py b/tests/test_profile_completion.py index b9d744a..e503371 100644 --- a/tests/test_profile_completion.py +++ b/tests/test_profile_completion.py @@ -29,7 +29,7 @@ context_artifact_name, receipt_artifact_name, ) -from scripts.profile_github import HTTPResponse, ProfileGitHub, TrustedWorkflow +from scripts.profile_github import HTTPResponse, ProfileGitHub, TrustedWorkflow, VerifiedRun SHA = "a" * 40 MAIN_SHA = "b" * 40 @@ -541,6 +541,103 @@ def test_collect_dispatch_accepts_equal_source_and_pr_head(self): self.assertEqual(items[0].source.head_sha, SHA) self.assertEqual(items[0].receipt.head_sha, SHA) + def trusted_target_reader(self, store, *, head_ref="topic", base="main", changes=0): + """Reader whose GitHub fake also answers the pull_request_target proofs.""" + inner = self.store_handler(store) + store["pr_reads"] = 0 + + def handler(method, url, headers, cap, data): + if url == "https://api.github.com/graphql": + return response( + { + "data": { + "repository": { + "pullRequests": { + "totalCount": 1, + "nodes": [ + { + "number": PR, + "baseRefName": base, + "headRepository": {"nameWithOwner": REPO}, + "timelineItems": {"totalCount": changes}, + } + ], + } + } + } + } + ) + if url.endswith(f"/repos/{REPO}/pulls/{PR}"): + store["pr_reads"] += 1 + return response( + {"number": PR, "head": {"ref": head_ref, "sha": SHA, "repo": {"full_name": REPO}}} + ) + return inner(method, url, headers, cap, data) + + client = self.client(handler) + return ReceiptEvidence( + client, + lambda run: client.verify_run(run, SHA, require_success=True), + (JOB_INITIAL, JOB_VERIFY), + [REVIEW_STEP], + ) + + def test_collect_pull_request_target_binds_receipt_head_and_head_branch(self): + store = self.make_store() + bundle = bundle_for(head_sha=SHA) + self.install_bundle(store, bundle, event="pull_request_target", head_branch="topic") + items = self.trusted_target_reader(store).collect(PR, [self.review_record(bundle)]) + self.assertEqual(len(items), 1) + self.assertEqual(items[0].source.event, "pull_request_target") + self.assertEqual(items[0].receipt.head_sha, SHA) + self.assertEqual(store["pr_reads"], 1) + + def test_collect_pull_request_target_rejects_stale_head_branch_and_base_changes(self): + cases = ( + # The run reviewed an older head: an older receipt never satisfies a newer head. + ({"head_sha": MAIN_SHA}, {}), + # Receipt claims a PR that the run's head branch did not trigger. + ({}, {"head_ref": "other"}), + # The PR was ever retargeted, or targets a non-default branch. + ({}, {"changes": 1}), + ({}, {"base": "release"}), + ) + for install, reader in cases: + with self.subTest(install=install, reader=reader): + store = self.make_store() + bundle = bundle_for(head_sha=SHA) + self.install_bundle( + store, bundle, event="pull_request_target", head_branch="topic", **install + ) + with self.assertRaises(ProfileCompletionError): + self.trusted_target_reader(store, **reader).collect( + PR, [self.review_record(bundle)] + ) + + def test_collect_repository_dispatch_requires_default_branch_source(self): + store = self.make_store() + bundle = bundle_for(head_sha=SHA) + self.install_bundle( + store, bundle, head_sha=MAIN_SHA, event="repository_dispatch", head_branch="main" + ) + items = self.reader(store).collect(PR, [self.review_record(bundle)]) + self.assertEqual((items[0].source.event, items[0].source.head_sha), ("repository_dispatch", MAIN_SHA)) + self.assertEqual(items[0].receipt.head_sha, SHA) + store = self.make_store() + self.install_bundle( + store, bundle, head_sha=MAIN_SHA, event="repository_dispatch", head_branch="topic" + ) + with self.assertRaises(ProfileCompletionError): + self.reader(store).collect(PR, [self.review_record(bundle)]) + + def test_bind_source_heads_rejects_unknown_events_even_from_a_verifier(self): + reader = self.reader(self.make_store()) + for event in ("push", "workflow_run"): + verified = VerifiedRun("RetireGolden", "example", RUN_ID, ATTEMPT, SHA, event, "main", 9, {}, ()) + with self.subTest(event=event): + with self.assertRaises(ProfileCompletionError): + reader._bind_source_heads(verified, SHA, PR) + def test_collect_ignores_legacy_review_without_marker(self): store = self.make_store() bundle = bundle_for() diff --git a/tests/test_profile_gate.py b/tests/test_profile_gate.py index 973fc80..33b7023 100644 --- a/tests/test_profile_gate.py +++ b/tests/test_profile_gate.py @@ -1269,6 +1269,177 @@ def test_publish_attempts_all_matrix_items_before_aggregate_failure(self) -> Non self.assertEqual(bare.create_status.call_args_list[1].args[1], "success") +class TrustedCallerEventGateTests(unittest.TestCase): + """pull_request_target and repository_dispatch in gate orchestration.""" + + CALLER = ( + b"uses: RetireGolden/.github/.github/workflows/openrouter-code-review.yml@" + + PIN.encode() + ) + + def config(self): + return TrustedWorkflow("RetireGolden", "example", "main", reusable_sha=PIN) + + def target_run(self, pin=PIN, **overrides): + run = { + "id": 5, + "run_attempt": 1, + "head_sha": SHA_A, + "head_branch": "topic", + "event": "pull_request_target", + "referenced_workflows": [ + { + "path": f"RetireGolden/.github/.github/workflows/openrouter-code-review.yml@{pin}", + "sha": pin, + } + ], + } + run.update(overrides) + return run + + def historical(self, client): + return ( + patch.object(gate, "_source_workspace", return_value=gate.Path("fixture")), + patch.object(gate, "_git", side_effect=[(SHA_B + "\n").encode()]), + patch.object(gate, "_file_at", return_value=(SHA_B, self.CALLER)), + ) + + def test_historical_target_run_uses_its_attested_pin_not_the_pr_head_blob(self): + client = SimpleNamespace(config=self.config(), _content_blob=Mock(side_effect=AssertionError)) + configured = Mock() + configured.verify_run.return_value = "verified" + source, git, file_at = self.historical(client) + with source, git, file_at, patch.object(gate, "_configured_client", return_value=configured) as made: + verify = gate._historical_verifier(client, "main", SHA_B) # type: ignore[arg-type] + self.assertEqual(verify(self.target_run()), "verified") + made.assert_called_once_with(client, "main", PIN) + configured.verify_run.assert_called_once_with(self.target_run(), SHA_B, require_success=False) + client._content_blob.assert_not_called() + + def test_historical_target_run_rejects_pins_outside_default_history(self): + client = SimpleNamespace(config=self.config(), _content_blob=Mock(side_effect=AssertionError)) + for run in ( + self.target_run(pin="9" * 40), + self.target_run(referenced_workflows=[]), + self.target_run( + referenced_workflows=[ + {"path": f"RetireGolden/.github/.github/workflows/openrouter-code-review.yml@{PIN}", "sha": "9" * 40} + ] + ), + ): + source, git, file_at = self.historical(client) + with self.subTest(run=run), source, git, file_at: + verify = gate._historical_verifier(client, "main", SHA_B) # type: ignore[arg-type] + with self.assertRaises(ProfileGitHubError): + verify(run) + + def target_review(self, pin=PIN, event="pull_request_target"): + run = self.target_run(pin=pin, event=event) + source = VerifiedRun("RetireGolden", "example", 5, 1, SHA_A, event, "topic", 9, run, ()) + return SimpleNamespace(source=source) + + def test_current_target_receipt_requires_default_base_and_current_pin(self): + ok = Mock(return_value=(7,)) + client = SimpleNamespace(config=self.config(), verify_target_base=ok, _content_blob=Mock(side_effect=AssertionError)) + self.assertTrue(gate._is_current_receipt_source(client, self.target_review(), SHA_B)) + ok.assert_called_once_with("topic") + self.assertFalse(gate._is_current_receipt_source(client, self.target_review(pin="9" * 40), SHA_B)) + client.verify_target_base = Mock(side_effect=ProfileGitHubError("retargeted")) + self.assertFalse(gate._is_current_receipt_source(client, self.target_review(), SHA_B)) + client._content_blob.assert_not_called() + + def test_current_pull_request_receipt_still_requires_exact_caller_blob(self): + client = SimpleNamespace(config=self.config(), verify_target_base=Mock(side_effect=AssertionError), + _content_blob=Mock(return_value="9" * 40)) + self.assertFalse(gate._is_current_receipt_source(client, self.target_review(event="pull_request"), SHA_B)) + client._content_blob.return_value = SHA_B + self.assertTrue(gate._is_current_receipt_source(client, self.target_review(event="pull_request"), SHA_B)) + + def begin_env(self, temporary, **overrides): + env = { + "REVIEW_LEVEL": "auto", + "GITHUB_EVENT_NAME": "pull_request_target", + "GITHUB_REF": "refs/heads/main", + "GITHUB_ACTOR": "maintainer", + "PR_NUMBER": "7", + "HEAD_SHA": SHA_A, + "GITHUB_RUN_ID": "101", + "GITHUB_RUN_ATTEMPT": "1", + "ORG_WORKFLOW_SHA": PIN, + "REQUEST_STATE_FILE": str(Path(temporary) / "state.json"), + "GITHUB_REPOSITORY": REPO, + } + env.update(overrides) + return env + + def run_begin(self, env, title="OpenRouter PR #7: auto", pr=None): + history = Mock() + history.load.return_value = () + history.fold_history.return_value = None + bare = SimpleNamespace(config=self.config(), maintainer=lambda login: login == "maintainer") + captured = {} + with ( + patch.dict(os.environ, env, clear=True), + patch.object(gate, "_client", return_value=Mock()), + patch.object(gate, "_current_trust", return_value=(bare, SHA_B, SHA_A, b"")), + patch.object(gate, "_verify_begin_run", return_value=False), + patch.object(gate, "_current_run", return_value={"display_title": title}), + patch.object(gate, "_live_pr", return_value=pr or live_pr()), + patch.object(gate, "_history_and_evidence", return_value=(history, Mock(collect=Mock(return_value=())), Mock())), + patch.object(gate, "_output", side_effect=captured.update), + ): + gate.begin() + return captured + + def test_begin_admits_default_base_pull_request_target_and_binds_live_head(self): + with tempfile.TemporaryDirectory() as temporary: + captured = self.run_begin(self.begin_env(temporary)) + self.assertEqual((captured["request_kind"], captured["head_sha"]), ("none", SHA_A)) + for overrides, message in ( + ({"GITHUB_REF": "refs/heads/release"}, "default-branch base"), + ({"HEAD_SHA": "9" * 40}, "does not match the live pull request"), + ({"PR_NUMBER": "8"}, "title does not match"), + ({"REVIEW_LEVEL": "deep"}, "default-branch dispatch"), + ): + with self.subTest(overrides=overrides), tempfile.TemporaryDirectory() as temporary: + with self.assertRaisesRegex(gate.GateError, message): + self.run_begin(self.begin_env(temporary, **overrides), title="OpenRouter PR #7: " + overrides.get("REVIEW_LEVEL", "auto")) + + def test_begin_allows_maintainer_deep_only_from_default_branch_repository_dispatch(self): + with tempfile.TemporaryDirectory() as temporary: + env = self.begin_env(temporary, GITHUB_EVENT_NAME="repository_dispatch", REVIEW_LEVEL="deep") + captured = self.run_begin(env, title="OpenRouter PR #7: deep") + self.assertEqual(captured["request_kind"], "deep") + for overrides, message in ( + ({"GITHUB_REF": "refs/heads/topic"}, "default-branch dispatch"), + ({"GITHUB_ACTOR": "contributor"}, "require a maintainer"), + ): + with self.subTest(overrides=overrides), tempfile.TemporaryDirectory() as temporary: + env = self.begin_env(temporary, GITHUB_EVENT_NAME="repository_dispatch", REVIEW_LEVEL="deep", **overrides) + with self.assertRaisesRegex(gate.GateError, message): + self.run_begin(env, title="OpenRouter PR #7: deep") + + def test_source_pr_for_repository_dispatch_requires_its_title(self): + def verified(title, pulls): + return VerifiedRun("RetireGolden", "example", 99, 1, SHA_B, "repository_dispatch", "main", 9, + {"display_title": title, "pull_requests": pulls}, ()) + + client = SimpleNamespace(config=self.config(), _api=Mock(return_value={"id": 99})) + with patch.dict(os.environ, {"SOURCE_RUN_ID": "99"}, clear=True): + self.assertEqual(gate._source_pr(client, lambda run: verified("OpenRouter PR #7: auto", [])), 7) + # PRs whose head happens to equal the default branch are not the dispatched PR. + with self.assertRaisesRegex(gate.GateError, "title"): + gate._source_pr(client, lambda run: verified("recover", [{"number": 3}])) + + def test_active_target_run_for_the_head_defers_additional_spend(self): + run = {"id": 5, "run_attempt": 1, "status": "in_progress", "event": "pull_request_target", + "head_sha": SHA_A, "display_title": "unrelated", "pull_requests": []} + verified = VerifiedRun("RetireGolden", "example", 5, 1, SHA_A, "pull_request_target", "topic", 9, run, ()) + client = SimpleNamespace(config=self.config(), paginated=_active_run_pages({"in_progress": [run]})) + self.assertTrue(gate._active_matching_run(client, lambda value: verified, 7, SHA_A)) + self.assertFalse(gate._active_matching_run(client, lambda value: verified, 7, SHA_B)) + + def verified_run(): return VerifiedRun( "RetireGolden", "example", 1, 1, SHA_A, "workflow_dispatch", "main", 9, {}, () diff --git a/tests/test_profile_github.py b/tests/test_profile_github.py index 2933584..761d593 100644 --- a/tests/test_profile_github.py +++ b/tests/test_profile_github.py @@ -444,5 +444,152 @@ def test_permissions_and_unsafe_artifact_redirect(self): ProfileGitHub._safe_artifact_url("https://user@127.0.0.1/zip") +def head_pulls(*nodes, total=None): + """GraphQL payload for PRs that share one head branch.""" + return { + "data": { + "repository": { + "pullRequests": { + "totalCount": len(nodes) if total is None else total, + "nodes": list(nodes), + } + } + } + } + + +def head_pull(number=7, base="main", owner="RetireGolden/example", changes=0): + return { + "number": number, + "baseRefName": base, + "headRepository": None if owner is None else {"nameWithOwner": owner}, + "timelineItems": {"totalCount": changes}, + } + + +class TrustedCallerEventTests(unittest.TestCase): + """pull_request_target and repository_dispatch admission in verify_run.""" + + def setUp(self): + self.config = TrustedWorkflow( + "RetireGolden", "example", "main", reusable_sha=PIN + ) + + def run_for(self, **overrides): + run = { + "id": RUN_ID, + "run_attempt": 1, + "workflow_id": 9, + "head_sha": SHA, + "head_branch": "topic", + "event": "pull_request_target", + "path": self.config.caller_path, + "repository": {"full_name": self.config.full_name}, + "head_repository": {"full_name": self.config.full_name}, + "referenced_workflows": [ + {"path": f"{self.config.reusable_path}@{PIN}", "sha": PIN} + ], + "status": "completed", + "conclusion": "success", + } + run.update(overrides) + return run + + def client(self, graphql=None, blob_sha=SHA): + self.calls = [] + + def handler(method, url, headers, cap, data): + self.calls.append((method, url, data)) + if url == "https://api.github.com/graphql": + self.assertEqual(method, "POST") + payload = json.loads(data.decode()) + self.assertIn("headRefName: $head", payload["query"]) + self.assertIn("BASE_REF_CHANGED_EVENT", payload["query"]) + self.assertIn("AUTOMATIC_BASE_CHANGE_SUCCEEDED_EVENT", payload["query"]) + self.assertEqual( + payload["variables"], + {"owner": "RetireGolden", "name": "example", "head": "topic"}, + ) + return response(graphql if graphql is not None else head_pulls(head_pull())) + if "/actions/workflows/" in url: + return response( + {"id": 9, "path": self.config.caller_path, "state": "active"} + ) + if "/contents/" in url: + return response({"type": "file", "sha": blob_sha}) + if url.endswith("/jobs?per_page=100&page=1"): + return response({"jobs": []}) + raise AssertionError(url) + + return ProfileGitHub(self.config, "secret", FakeTransport(handler)) + + def test_pull_request_target_uses_default_base_proof_not_pr_head_caller_blob(self): + # The PR head may even carry a different caller file: it never ran. + client = self.client(blob_sha="d" * 40) + verified = client.verify_run(self.run_for(), SHA, require_success=True) + self.assertEqual((verified.event, verified.head_sha), ("pull_request_target", SHA)) + self.assertEqual(verified.head_branch, "topic") + self.assertFalse(any("/contents/" in url for _, url, _ in self.calls)) + self.assertTrue(any(url.endswith("/graphql") for _, url, _ in self.calls)) + + def test_pull_request_target_ignores_fork_prs_sharing_the_branch_name(self): + client = self.client( + head_pulls(head_pull(), head_pull(8, base="release", owner="fork/example"), + head_pull(9, owner=None)) + ) + self.assertEqual(client.verify_target_base("topic"), (7,)) + + def test_pull_request_target_rejects_retargeted_or_non_default_bases(self): + for graphql in ( + head_pulls(head_pull(base="release")), + head_pulls(head_pull(changes=1)), + head_pulls(head_pull(), head_pull(8, base="release")), + head_pulls(head_pull(owner="fork/example")), + head_pulls(), + head_pulls(head_pull(), total=2), + head_pulls(*[head_pull(n) for n in range(1, 102)]), + {"errors": [{"message": "denied"}], "data": None}, + {"data": {"repository": None}}, + head_pulls({"number": True, "baseRefName": "main", + "headRepository": {"nameWithOwner": "RetireGolden/example"}, + "timelineItems": {"totalCount": 0}}), + head_pulls({**head_pull(), "timelineItems": None}), + ): + with self.subTest(graphql=graphql): + with self.assertRaises(ProfileGitHubError): + self.client(graphql).verify_run(self.run_for(), SHA) + + def test_pull_request_target_rejects_fork_heads_pin_and_invalid_branches(self): + for changed in ( + {"head_repository": {"full_name": "fork/example"}}, + {"referenced_workflows": []}, + {"head_branch": None}, + {"head_branch": ""}, + {"head_branch": "bad branch"}, + {"head_branch": "line\nbreak"}, + ): + with self.subTest(changed=changed): + with self.assertRaises(ProfileGitHubError): + self.client().verify_run(self.run_for(**changed), SHA) + + def test_repository_dispatch_requires_default_branch_and_exact_caller_blob(self): + dispatch = self.run_for(event="repository_dispatch", head_branch="main", head_sha="c" * 40) + verified = self.client().verify_run(dispatch, SHA) + self.assertEqual(verified.event, "repository_dispatch") + self.assertFalse(any(url.endswith("/graphql") for _, url, _ in self.calls)) + for changed in ({"head_branch": "topic"}, {"head_branch": None}): + with self.subTest(changed=changed): + with self.assertRaises(ProfileGitHubError): + self.client().verify_run({**dispatch, **changed}, SHA) + with self.assertRaises(ProfileGitHubError): + self.client(blob_sha="d" * 40).verify_run(dispatch, SHA) + + def test_untrusted_events_remain_rejected(self): + for event in ("push", "workflow_run", "pull_request_review", "issue_comment", None): + with self.subTest(event=event): + with self.assertRaises(ProfileGitHubError): + self.client().verify_run(self.run_for(event=event), SHA) + + if __name__ == "__main__": # pragma: no cover unittest.main() diff --git a/tests/test_profile_requests.py b/tests/test_profile_requests.py index 8fcd1f0..e93942f 100644 --- a/tests/test_profile_requests.py +++ b/tests/test_profile_requests.py @@ -370,6 +370,52 @@ def test_dispatch_request_binds_pr_head_independently_of_source_main(self): store["runs"][(100, 1)].update(event="workflow_dispatch", head_branch="main") self.assertEqual(self.reader(self.store_handler(store)).load(PR), (record,)) + def with_target_base(self, handler, base="main"): + def wrapped(method, url, headers, cap, data): + if url == "https://api.github.com/graphql": + node = { + "number": PR, + "baseRefName": base, + "headRepository": {"nameWithOwner": REPO}, + "timelineItems": {"totalCount": 0}, + } + return response( + {"data": {"repository": {"pullRequests": {"totalCount": 1, "nodes": [node]}}}} + ) + return handler(method, url, headers, cap, data) + + return wrapped + + def test_pull_request_target_request_binds_the_run_head(self): + store = self.make_store() + record = record_payload() + self.install_run(store, 100, 1, record, artifact_name=primary_artifact_name(PR)) + store["runs"][(100, 1)].update(event="pull_request_target", head_branch="topic") + handler = self.with_target_base(self.store_handler(store)) + self.assertEqual(self.reader(handler).load(PR), (record,)) + # A request accepted for another head than the run's PR head is rejected. + store = self.make_store() + self.install_run(store, 100, 1, record, head_sha=BASE, artifact_name=primary_artifact_name(PR)) + store["runs"][(100, 1)].update(event="pull_request_target", head_branch="topic") + with self.assertRaises(ProfileRequestError): + self.reader(self.with_target_base(self.store_handler(store))).load(PR) + # A head branch that ever targeted another base cannot supply requests. + store = self.make_store() + self.install_run(store, 100, 1, record, artifact_name=primary_artifact_name(PR)) + store["runs"][(100, 1)].update(event="pull_request_target", head_branch="topic") + with self.assertRaises(ProfileRequestError): + self.reader(self.with_target_base(self.store_handler(store), base="release")).load(PR) + + def test_repository_dispatch_request_requires_default_branch(self): + store = self.make_store() + record = record_payload() + self.install_run(store, 100, 1, record, head_sha=BASE, artifact_name=primary_artifact_name(PR)) + store["runs"][(100, 1)].update(event="repository_dispatch", head_branch="main") + self.assertEqual(self.reader(self.store_handler(store)).load(PR), (record,)) + store["runs"][(100, 1)].update(head_branch="topic") + with self.assertRaises(ProfileRequestError): + self.reader(self.store_handler(store)).load(PR) + def test_load_first_acceptance_and_carry(self): store = self.make_store() deep = record_payload(run_id=100, accepted_at_ms=ACCEPT_MS) diff --git a/tests/test_profile_workflow.py b/tests/test_profile_workflow.py index fdb2677..197e067 100644 --- a/tests/test_profile_workflow.py +++ b/tests/test_profile_workflow.py @@ -1,11 +1,29 @@ """Contract checks against the pinned reusable workflow YAML blocks.""" +import os +import shutil +import subprocess +import tempfile +import textwrap import unittest from pathlib import Path import yaml ROOT = Path(__file__).parents[1] +GATE_CHECK = yaml.load( + (ROOT / '.github/workflows/openrouter-review-gate-check.yml').read_text(encoding='utf-8'), + Loader=yaml.BaseLoader, +) +GIT_BASH = Path('C:/Program Files/Git/bin/bash.exe') +BASH = str(GIT_BASH) if GIT_BASH.exists() else shutil.which('bash') +DEFAULT_REF = "github.ref == format('refs/heads/{0}', github.event.repository.default_branch)" +PR_ACTIONS = """contains(fromJSON('["opened","reopened","ready_for_review","synchronize"]'), github.event.action)""" +# Permissions every RetireGolden review caller grants today (top level, no job override). +LEGACY_CALLER_PERMISSIONS = { + 'actions': 'write', 'contents': 'read', 'pull-requests': 'write', 'statuses': 'write', +} +LEVEL = {'none': 0, 'read': 1, 'write': 2} REVIEW = yaml.load( (ROOT / '.github/workflows/openrouter-code-review.yml').read_text(encoding='utf-8'), Loader=yaml.BaseLoader, @@ -137,5 +155,449 @@ def test_profile_gate_runs_only_through_trusted_pythonpath_and_private_modules(s self.assertTrue(step['run'].startswith('python3 -P -m scripts.profile_gate')) +class Expression: + """Tiny evaluator for the GitHub expression subset used in job conditions.""" + + import re as _re + TOKEN = _re.compile(r"\s*(\|\||&&|==|!=|!|\(|\)|,|'(?:[^']|'')*'|[A-Za-z_][A-Za-z0-9_.-]*)") + + def __init__(self, text, context): + text = text.strip() + if text.startswith('${{') and text.endswith('}}'): + text = text[3:-2] + self.tokens, position = [], 0 + while position < len(text.rstrip()): + match = self.TOKEN.match(text, position) + if not match: + raise ValueError(f'cannot parse {text[position:]!r}') + self.tokens.append(match.group(1)) + position = match.end() + self.index, self.context = 0, context + + def evaluate(self): + value = self.or_() + if self.index != len(self.tokens): + raise ValueError(f'trailing tokens {self.tokens[self.index:]}') + return value + + def peek(self): + return self.tokens[self.index] if self.index < len(self.tokens) else None + + def take(self, expected=None): + token = self.peek() + if expected is not None and token != expected: + raise ValueError(f'expected {expected}, found {token}') + self.index += 1 + return token + + @staticmethod + def truthy(value): + return value not in (None, '', 0, False) + + def or_(self): + value = self.and_() + while self.peek() == '||': + self.take() + right = self.and_() + value = value if self.truthy(value) else right + return value + + def and_(self): + value = self.compare() + while self.peek() == '&&': + self.take() + right = self.compare() + value = right if self.truthy(value) else value + return value + + def compare(self): + value = self.unary() + while self.peek() in ('==', '!='): + operator = self.take() + right = self.unary() + left_cmp = value.lower() if isinstance(value, str) else value + right_cmp = right.lower() if isinstance(right, str) else right + value = (left_cmp == right_cmp) == (operator == '==') + return value + + def unary(self): + if self.peek() == '!': + self.take() + return not self.truthy(self.unary()) + return self.primary() + + def primary(self): + token = self.take() + if token == '(': + value = self.or_() + self.take(')') + return value + if token.startswith("'"): + return token[1:-1].replace("''", "'") + if token in ('true', 'false'): + return token == 'true' + if self.peek() == '(': + self.take('(') + args = [] + while self.peek() != ')': + args.append(self.or_()) + if self.peek() == ',': + self.take() + self.take(')') + return self.call(token, args) + value = self.context + for part in token.split('.'): + value = value.get(part) if isinstance(value, dict) else None + return value + + def call(self, name, args): + if name in ('always', 'success'): + return True + if name == 'cancelled': + return False + if name == 'format': + return args[0].replace('{0}', str(args[1])) + if name == 'fromJSON': + import json + return json.loads(args[0]) + if name == 'contains': + return args[1] in args[0] + raise ValueError(name) + + +def caller_context(event_name, action=None, *, ref='refs/heads/main', draft=False, number=7, **inputs): + pull_request = None if event_name.endswith('dispatch') else {'draft': draft, 'number': number} + return { + 'github': { + 'event_name': event_name, + 'ref': ref, + 'repository': 'RetireGolden/example', + 'actor': inputs.pop('actor', 'maintainer'), + 'event': { + 'action': action, + 'pull_request': pull_request, + 'repository': {'default_branch': 'main'}, + }, + }, + 'inputs': {'review_level': 'auto', 'review_profiles_enabled': True, **inputs}, + 'needs': {'review-config': {'result': 'success'}}, + } + + +def runs(job_id, context, workflow=None): + return bool(Expression((workflow or REVIEW)['jobs'][job_id]['if'], context).evaluate()) + + +class TrustedCallerEventContractTests(unittest.TestCase): + JOBS = ('review-config', 'openrouter-first-pass', 'openrouter-follow-up', 'openrouter-first-pass-gate') + + def selected(self, context): + return {job for job in self.JOBS if runs(job, context)} + + def test_legacy_pull_request_and_dispatch_selection_is_unchanged(self): + for action in ('opened', 'reopened', 'ready_for_review'): + self.assertEqual( + self.selected(caller_context('pull_request', action, ref='refs/pull/7/merge')), + {'review-config', 'openrouter-first-pass', 'openrouter-first-pass-gate'}, + ) + self.assertEqual( + self.selected(caller_context('pull_request', 'synchronize', ref='refs/pull/7/merge')), + {'review-config', 'openrouter-follow-up', 'openrouter-first-pass-gate'}, + ) + # A pull_request draft still reaches only the gate, which reports the draft. + self.assertEqual( + self.selected(caller_context('pull_request', 'opened', ref='refs/pull/7/merge', draft=True)), + {'openrouter-first-pass-gate'}, + ) + # workflow_dispatch from any ref keeps its former job selection. + for ref in ('refs/heads/main', 'refs/heads/topic'): + self.assertEqual( + self.selected(caller_context('workflow_dispatch', ref=ref)), + {'review-config', 'openrouter-first-pass', 'openrouter-first-pass-gate'}, + ) + self.assertEqual(self.selected(caller_context('workflow_dispatch', review_level='cancel')), + {'review-config', 'openrouter-first-pass'}) + + def test_pull_request_target_keeps_first_pass_and_follow_up_split(self): + for action in ('opened', 'reopened', 'ready_for_review'): + self.assertEqual( + self.selected(caller_context('pull_request_target', action)), + {'review-config', 'openrouter-first-pass', 'openrouter-first-pass-gate'}, + ) + self.assertEqual( + self.selected(caller_context('pull_request_target', 'synchronize')), + {'review-config', 'openrouter-follow-up', 'openrouter-first-pass-gate'}, + ) + + def test_pull_request_target_requires_default_base_and_review_actions(self): + # A PR into another branch would run that branch's caller. + self.assertEqual(self.selected(caller_context('pull_request_target', 'opened', ref='refs/heads/release')), set()) + self.assertEqual(self.selected(caller_context('pull_request_target', 'synchronize', ref='refs/heads/release')), set()) + # Other PR actions never publish a failing gate on the head. + for action in ('labeled', 'edited', 'closed', None): + self.assertEqual(self.selected(caller_context('pull_request_target', action)), set()) + self.assertEqual( + self.selected(caller_context('pull_request_target', 'opened', draft=True)), + {'openrouter-first-pass-gate'}, + ) + + def test_repository_dispatch_is_a_default_branch_first_pass(self): + # The dispatch event type is free-form; even "synchronize" stays a first pass. + for event_type in ('openrouter-review', 'synchronize'): + self.assertEqual( + self.selected(caller_context('repository_dispatch', event_type)), + {'review-config', 'openrouter-first-pass', 'openrouter-first-pass-gate'}, + ) + self.assertEqual(self.selected(caller_context('repository_dispatch', 'x', ref='refs/heads/topic')), set()) + self.assertEqual( + self.selected(caller_context('repository_dispatch', 'x', review_level='cancel')), + {'review-config', 'openrouter-first-pass'}, + ) + + def test_untrusted_events_select_no_job(self): + for event in ('push', 'workflow_run', 'issue_comment', 'pull_request_review'): + self.assertEqual(self.selected(caller_context(event, 'opened')), set()) + + def test_no_scan_repositories_still_skip_review_jobs(self): + for repo in ('RetireGolden/.github', 'RetireGolden/cla-signatures', 'RetireGolden/RetireBench-private'): + for event in ('pull_request_target', 'repository_dispatch'): + context = caller_context(event, 'opened') + context['github']['repository'] = repo + self.assertFalse(runs('review-config', context)) + self.assertFalse(runs('openrouter-first-pass', context)) + + def test_bot_dispatches_wake_profile_completion(self): + for event, actor, expected in ( + ('workflow_dispatch', 'github-actions[bot]', True), + ('repository_dispatch', 'github-actions[bot]', True), + ('repository_dispatch', 'maintainer', False), + ('pull_request_target', 'github-actions[bot]', False), + ): + with self.subTest(event=event, actor=actor): + self.assertEqual(runs('notify-profile-completion', caller_context(event, 'opened', actor=actor)), expected) + + def test_review_workflow_requests_no_permission_beyond_current_callers(self): + def within(permissions): + for scope, level in permissions.items(): + self.assertLessEqual(LEVEL[level], LEVEL[LEGACY_CALLER_PERMISSIONS.get(scope, 'none')], scope) + + within(REVIEW['permissions']) + for job_id, job in REVIEW['jobs'].items(): + with self.subTest(job=job_id): + within(job.get('permissions', REVIEW['permissions'])) + self.assertNotIn('checks', str(REVIEW['permissions'])) + self.assertFalse(any('checks' in job.get('permissions', {}) for job in REVIEW['jobs'].values())) + + def test_gate_check_entrypoint_holds_the_only_checks_permission(self): + self.assertEqual( + GATE_CHECK['permissions'], + {'actions': 'read', 'checks': 'write', 'contents': 'read', 'pull-requests': 'read'}, + ) + self.assertEqual(list(GATE_CHECK['jobs']), ['publish']) + job = GATE_CHECK['jobs']['publish'] + self.assertEqual(job['permissions'], GATE_CHECK['permissions']) + inputs = GATE_CHECK['on']['workflow_call']['inputs'] + self.assertEqual(inputs['gate_check_name']['default'], 'review / openrouter-first-pass-gate') + self.assertEqual(inputs['publish_mode']['default'], 'auto') + self.assertEqual(inputs['head_sha']['required'], 'true') + self.assertEqual(inputs['pr_number']['required'], 'true') + source, checkout, publish = job['steps'] + self.assertIn('openrouter-review-gate-check.yml@', source['run']) + self.assertIn('referenced_workflows', source['run']) + self.assertEqual(checkout['with'], { + 'repository': 'RetireGolden/.github', + 'ref': '${{ steps.source.outputs.sha }}', + 'path': '.trusted-review-org', + 'persist-credentials': 'false', + }) + self.assertIn('.trusted-review-org/scripts/gate_check.mjs', publish['with']['script']) + self.assertNotEqual(job['name'], 'openrouter-first-pass-gate') + + def test_gate_outputs_flow_to_the_gate_check_entrypoint(self): + outputs = REVIEW['on']['workflow_call']['outputs'] + for name in ('pr_number', 'head_sha', 'conclusion', 'review_url'): + self.assertEqual(outputs['gate_' + name]['value'], + '${{ jobs.openrouter-first-pass-gate.outputs.' + name + ' }}') + self.assertEqual(REVIEW['jobs']['openrouter-first-pass-gate']['outputs'][name], + '${{ steps.gate.outputs.' + name + ' }}') + gate = step_named(job_steps(REVIEW, 'openrouter-first-pass-gate'), 'Evaluate OpenRouter first-pass gate') + self.assertEqual(gate['id'], 'gate') + self.assertIn("trap '", gate['run']) + self.assertIn('echo "head_sha=$HEAD_SHA" >> "$GITHUB_OUTPUT"', gate['run']) + + def test_dispatch_event_type_is_not_a_pull_request_action(self): + env = REVIEW['jobs']['openrouter-first-pass-gate']['env'] + self.assertEqual( + env['EVENT_ACTION'], + "${{ (github.event_name == 'pull_request' || github.event_name == 'pull_request_target') && github.event.action || '' }}", + ) + for event, action, expected in ( + ('pull_request', 'synchronize', 'synchronize'), + ('pull_request_target', 'synchronize', 'synchronize'), + ('repository_dispatch', 'synchronize', ''), + ('workflow_dispatch', None, ''), + ): + self.assertEqual(Expression(env['EVENT_ACTION'], caller_context(event, action)).evaluate(), expected) + self.assertEqual(env['EXPECTED_HEAD_SHA'], '${{ inputs.expected_head_sha }}') + + def test_repository_dispatch_reviews_the_exact_checked_out_head(self): + steps = job_steps(REVIEW, 'openrouter-first-pass') + expression = "${{ github.event_name == 'repository_dispatch' && steps.head.outputs.sha || '' }}" + for name in ('Prepare shared review snapshot', 'Run OpenRouter first-pass review'): + self.assertEqual(step_named(steps, name)['with']['head_sha'], expression) + resolve = step_named(steps, 'Resolve PR head SHA') + self.assertEqual(resolve['env']['EXPECTED_HEAD_SHA'], '${{ inputs.expected_head_sha }}') + self.assertIn('[ "$HEAD_SHA" != "$EXPECTED_HEAD_SHA" ]', resolve['run']) + context = caller_context('repository_dispatch', 'x') + context['steps'] = {'head': {'outputs': {'sha': 'a' * 40}}} + self.assertEqual(Expression(expression, context).evaluate(), 'a' * 40) + context['github']['event_name'] = 'pull_request' + self.assertEqual(Expression(expression, context).evaluate(), '') + + def test_secret_holding_review_jobs_never_execute_checkout_content(self): + for job_id in ('openrouter-first-pass', 'openrouter-follow-up'): + steps = job_steps(REVIEW, job_id) + names = [step.get('name') for step in steps] + checkout = step_named(steps, 'Checkout PR head') + self.assertEqual(checkout['with']['persist-credentials'], 'false') + self.assertEqual(checkout['with']['submodules'], 'false') + self.assertEqual(checkout['with']['lfs'], 'false') + self.assertEqual(checkout['with']['ref'], '${{ steps.head.outputs.sha }}') + guard = names.index('Refuse reserved trusted paths in the reviewed checkout') + self.assertEqual(guard, names.index('Checkout PR head') + 1) + self.assertLess(guard, names.index('Checkout trusted profile coordinator')) + for step in steps: + uses = step.get('uses', '') + self.assertFalse(uses.startswith('./'), step.get('name')) + if uses: + self.assertRegex(uses, r'@[0-9a-f]{40}$') + run = step.get('run', '') + for forbidden in ('npm ', 'npx ', 'pnpm ', 'yarn ', 'pip install', 'make ', 'bash ./', 'sh ./', 'source ', '. ./'): + self.assertNotIn(forbidden, run, step.get('name')) + for line in run.splitlines(): + if 'python' in line and 'python3 -P' not in line and 'shell: python' not in line: + self.fail(f'{step.get("name")}: {line}') + for step in steps: + if step.get('uses', '').startswith('actions/checkout@') and step.get('with', {}).get('repository'): + self.assertEqual(step['with']['persist-credentials'], 'false') + + def test_reserved_path_guard_rejects_seeded_or_symlinked_trusted_paths(self): + if not BASH: + self.skipTest('bash required') + script = step_named(job_steps(REVIEW, 'openrouter-first-pass'), + 'Refuse reserved trusted paths in the reviewed checkout')['run'] + for setup in ('', 'mkdir .trusted-review-org', 'touch .trusted-review-action', 'mkdir elsewhere && ln -s elsewhere .trusted-review-org'): + with self.subTest(setup=setup), tempfile.TemporaryDirectory() as folder: + if setup: + subprocess.run([BASH, '-c', setup], cwd=folder, check=True) + result = subprocess.run([BASH, '-c', script], cwd=folder, capture_output=True, text=True) + self.assertEqual(result.returncode == 0, setup == '', result.stdout + result.stderr) + + +@unittest.skipUnless(BASH, 'bash required to exercise the workflow shell') +class PullRequestContextStepTests(unittest.TestCase): + SCRIPT = next(step['run'] for step in REVIEW['jobs']['review-config']['steps'] if step.get('id') == 'pr') + + def resolve(self, **env): + with tempfile.TemporaryDirectory() as folder: + output, summary = Path(folder) / 'output', Path(folder) / 'summary' + result = subprocess.run( + [BASH, '-c', self.SCRIPT], + env={**os.environ, 'GITHUB_OUTPUT': str(output), 'GITHUB_STEP_SUMMARY': str(summary), + 'GITHUB_SHA': 'b' * 40, **env}, + capture_output=True, text=True, + ) + values = dict(line.split('=', 1) for line in output.read_text().splitlines()) if output.exists() else {} + return result, values + + def test_pull_request_events_bind_the_triggering_pr_and_pass(self): + for event in ('pull_request', 'pull_request_target'): + for action, expected in (('opened', 'first-pass'), ('ready_for_review', 'first-pass'), ('synchronize', 'follow-up')): + with self.subTest(event=event, action=action): + result, values = self.resolve(EVENT_NAME=event, EVENT_ACTION=action, EVENT_PR_NUMBER='7', + INPUT_PR_NUMBER='7', EVENT_HEAD_SHA='a' * 40) + self.assertEqual(result.returncode, 0, result.stdout) + self.assertEqual((values['pr_number'], values['pass'], values['event_head_sha']), ('7', expected, 'a' * 40)) + + def test_forged_or_missing_pr_numbers_fail_closed(self): + for env in ( + {'EVENT_NAME': 'pull_request_target', 'EVENT_ACTION': 'opened', 'EVENT_PR_NUMBER': '7', 'INPUT_PR_NUMBER': '8'}, + {'EVENT_NAME': 'repository_dispatch', 'EVENT_ACTION': 'openrouter-review'}, + {'EVENT_NAME': 'repository_dispatch', 'INPUT_PR_NUMBER': '7/../../x'}, + {'EVENT_NAME': 'repository_dispatch', 'INPUT_PR_NUMBER': '07'}, + {'EVENT_NAME': 'workflow_dispatch', 'INPUT_PR_NUMBER': '-1'}, + {'EVENT_NAME': 'push', 'INPUT_PR_NUMBER': '7'}, + {'EVENT_NAME': 'repository_dispatch', 'INPUT_PR_NUMBER': '7', 'EXPECTED_HEAD_SHA': 'A' * 40}, + {'EVENT_NAME': 'repository_dispatch', 'INPUT_PR_NUMBER': '7', 'EXPECTED_HEAD_SHA': 'main'}, + ): + with self.subTest(env=env): + result, values = self.resolve(**env) + self.assertNotEqual(result.returncode, 0) + self.assertNotIn('pr_number', values) + + def test_dispatches_are_first_passes_named_by_inputs(self): + result, values = self.resolve(EVENT_NAME='repository_dispatch', EVENT_ACTION='synchronize', + INPUT_PR_NUMBER='12', EXPECTED_HEAD_SHA='c' * 40) + self.assertEqual(result.returncode, 0, result.stdout) + self.assertEqual((values['pr_number'], values['pass']), ('12', 'first-pass')) + # repository_dispatch never falls back to unmapped payload fields. + result, _ = self.resolve(EVENT_NAME='repository_dispatch', DISPATCH_PR_NUMBER='12') + self.assertNotEqual(result.returncode, 0) + # workflow_dispatch keeps its github.event.inputs fallback. + result, values = self.resolve(EVENT_NAME='workflow_dispatch', DISPATCH_PR_NUMBER='12') + self.assertEqual((result.returncode, values.get('pr_number')), (0, '12')) + + +@unittest.skipUnless(BASH, 'bash required to exercise the workflow shell') +class GateOutputShellTests(unittest.TestCase): + """The gate records the evaluated head and its conclusion for check publishing.""" + + SCRIPT = textwrap.dedent(step_named(job_steps(REVIEW, 'openrouter-first-pass-gate'), + 'Evaluate OpenRouter first-pass gate')['run']) + + def evaluate(self, *, live_head='a' * 40, repository='RetireGolden/example', **env): + with tempfile.TemporaryDirectory() as folder: + bin_dir, output = Path(folder) / 'bin', Path(folder) / 'output' + bin_dir.mkdir() + fake = bin_dir / 'gh' + fake.write_text('#!/bin/bash\nprintf "%s\\n" "$FAKE_LIVE_HEAD"\n', newline='\n') + fake.chmod(0o755) + result = subprocess.run( + [BASH, '-c', f'export PATH="$(cygpath -u "{bin_dir}" 2>/dev/null || echo "{bin_dir}"):$PATH"; ' + self.SCRIPT], + env={**os.environ, 'GITHUB_OUTPUT': str(output), 'GITHUB_REPOSITORY': repository, + 'FAKE_LIVE_HEAD': live_head, 'PR_NUMBER': '7', 'IS_DRAFT': 'false', 'EVENT_ACTION': '', + 'EVENT_HEAD_SHA': '', 'EXPECTED_HEAD_SHA': '', 'ACTION_OUTCOME': 'failure', 'VERDICT': '', + 'REVIEW_URL': '', 'FIRST_PASS_RESULT': 'failure', 'RUN_URL': 'https://example.test/run', **env}, + capture_output=True, text=True, + ) + lines = output.read_text().splitlines() if output.exists() else [] + return result, dict(line.split('=', 1) for line in lines), lines + + def test_failed_fresh_first_pass_publishes_failure_for_the_live_head(self): + result, values, lines = self.evaluate() + self.assertEqual(result.returncode, 1) + self.assertEqual(values, {'pr_number': '7', 'head_sha': 'a' * 40, 'conclusion': 'failure'}) + self.assertEqual(lines[-1], 'conclusion=failure') + + def test_stale_dispatch_head_fails_for_the_live_head(self): + result, values, _ = self.evaluate(EXPECTED_HEAD_SHA='c' * 40, ACTION_OUTCOME='success', VERDICT='clean') + self.assertEqual(result.returncode, 1) + self.assertIn('not the dispatched', result.stdout) + self.assertEqual((values['head_sha'], values['conclusion']), ('a' * 40, 'failure')) + + def test_invalid_inputs_never_name_a_head(self): + for env in ({'PR_NUMBER': '7/../x'}, {'IS_DRAFT': 'true'}, {'live_head': 'not-a-sha'}): + with self.subTest(env=env): + result, values, _ = self.evaluate(**env) + self.assertEqual(result.returncode, 1) + self.assertNotIn('head_sha', values) + self.assertEqual(values['conclusion'], 'failure') + + def test_no_scan_repository_succeeds_without_a_head(self): + result, values, _ = self.evaluate(repository='RetireGolden/.github') + self.assertEqual(result.returncode, 0) + self.assertEqual(values, {'conclusion': 'success'}) + + if __name__ == '__main__': unittest.main() diff --git a/tests/workflow-wakeup.test.mjs b/tests/workflow-wakeup.test.mjs index 764fd55..4b93808 100644 --- a/tests/workflow-wakeup.test.mjs +++ b/tests/workflow-wakeup.test.mjs @@ -53,3 +53,16 @@ test('wrong workflow path and disabled workflows fail closed', async () => { assert.deepEqual(f.calls, []); } }); +test('bot-sent repository_dispatch reviews also wake the default-branch validator', async () => { + const f = fixture({ eventName: 'repository_dispatch' }); + await dispatchWorkflowWake(f.github, f.core, f.context, 'openrouter-profile-completion.yml'); + assert.deepEqual(f.calls, [{ owner: 'RetireGolden', repo: 'example', workflow_id: 'openrouter-profile-completion.yml', ref: 'main', inputs: { source_run_id: '42' } }]); + for (const overrides of [{ eventName: 'repository_dispatch', actor: 'maintainer' }, { eventName: 'pull_request_target' }]) { + const other = fixture(overrides); + await dispatchWorkflowWake(other.github, other.core, other.context, 'openrouter-profile-completion.yml'); + assert.deepEqual(other.calls, []); + } + const offDefault = fixture({ eventName: 'repository_dispatch', ref: 'refs/heads/topic' }); + await assert.rejects(dispatchWorkflowWake(offDefault.github, offDefault.core, offDefault.context, 'openrouter-profile-completion.yml')); + assert.deepEqual(offDefault.calls, []); +});