diff --git a/.github/workflows/pr-gate-test.yml b/.github/workflows/pr-gate-test.yml index 59eb3a1..fb5a7fa 100644 --- a/.github/workflows/pr-gate-test.yml +++ b/.github/workflows/pr-gate-test.yml @@ -11,6 +11,9 @@ concurrency: group: pr-gate-test-${{ github.ref }} cancel-in-progress: true +permissions: + contents: read + jobs: test: runs-on: ubuntu-latest @@ -20,4 +23,4 @@ jobs: - uses: actions/setup-node@v4 with: node-version: '22' - - run: node --test pr-gate/decide.test.mjs + - run: node --test pr-gate/*.test.mjs diff --git a/.github/workflows/pr-gate.yml b/.github/workflows/pr-gate.yml index df93a12..fe0aeb8 100644 --- a/.github/workflows/pr-gate.yml +++ b/.github/workflows/pr-gate.yml @@ -11,7 +11,7 @@ on: required: true type: string merge: - description: Squash-merge when every condition passes. False = report only. + description: Reserved for compatibility. True is refused; this gate is report-only. required: false type: boolean default: false @@ -19,43 +19,107 @@ on: description: Commit of Starlight-Intelligence/.github to load the gate from. Pin it to the same SHA as the uses line. required: false type: string - default: main + default: '' required-checks: description: Comma-separated check run names that must pass on the head commit, e.g. "test, build". required: true type: string wait-minutes: - description: How long to wait for running CI when it is the only thing outstanding. + description: Deprecated compatibility input. Reports are immediate and never poll. required: false type: number default: 8 jobs: + resolve-pr: + runs-on: ubuntu-latest + timeout-minutes: 2 + permissions: + contents: read + pull-requests: read + actions: read + outputs: + pr-number: ${{ steps.resolve.outputs.pr-number }} + steps: + - name: Require the same immutable resolver and reusable source + env: + GATE_REF: ${{ inputs.gate-ref }} + JOB_WORKFLOW_SHA: ${{ job.workflow_sha }} + JOB_WORKFLOW_REPOSITORY: ${{ job.workflow_repository }} + run: | + node <<'NODE' + // source-ref-validator:start + const e = process.env; + if (!/^[a-f0-9]{40}$/.test(e.GATE_REF || '') || e.GATE_REF !== e.JOB_WORKFLOW_SHA || (e.JOB_WORKFLOW_REPOSITORY || '').toLowerCase() !== 'starlight-intelligence/.github') process.exit(1); + // source-ref-validator:end + NODE + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + repository: Starlight-Intelligence/.github + ref: ${{ inputs.gate-ref }} + path: .pr-gate + persist-credentials: false + - name: Resolve only an API-authenticated current PR + id: resolve + env: + GITHUB_TOKEN: ${{ github.token }} + PR_NUMBER: ${{ inputs.pr-number }} + run: | + node --input-type=module <<'NODE' + import { appendFileSync } from 'node:fs'; + import { createClient, resolvePrNumber } from './.pr-gate/pr-gate/run.mjs'; + const number = await resolvePrNumber(process.env, createClient(process.env.GITHUB_TOKEN)); + appendFileSync(process.env.GITHUB_OUTPUT, `pr-number=${number ?? ''}\n`); + NODE + decide: + needs: resolve-pr + if: needs.resolve-pr.outputs.pr-number != '' + # Only eligible, resolved reports join this group. An unrelated comment + # cannot cancel a run, and all event types for the same PR serialize here. + concurrency: + group: starlight-pr-gate-${{ github.repository }}-${{ needs.resolve-pr.outputs.pr-number }} + cancel-in-progress: false runs-on: ubuntu-latest timeout-minutes: 15 permissions: - contents: write + contents: read pull-requests: write issues: write checks: read + actions: read steps: + - name: Require an immutable gate source + env: + GATE_REF: ${{ inputs.gate-ref }} + JOB_WORKFLOW_SHA: ${{ job.workflow_sha }} + JOB_WORKFLOW_REPOSITORY: ${{ job.workflow_repository }} + run: | + node <<'NODE' + // source-ref-validator:start + const e = process.env; + if (!/^[a-f0-9]{40}$/.test(e.GATE_REF || '') || e.GATE_REF !== e.JOB_WORKFLOW_SHA || (e.JOB_WORKFLOW_REPOSITORY || '').toLowerCase() !== 'starlight-intelligence/.github') process.exit(1); + // source-ref-validator:end + NODE - name: Load the gate - uses: actions/checkout@v4 + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: repository: Starlight-Intelligence/.github ref: ${{ inputs.gate-ref }} path: .pr-gate persist-credentials: false - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4 with: node-version: '22' - name: Decide env: GITHUB_TOKEN: ${{ github.token }} - PR_NUMBER: ${{ inputs.pr-number }} + PR_NUMBER: ${{ needs.resolve-pr.outputs.pr-number }} + # Resolve once before the per-PR lock; do not resolve a second time + # under a workflow_run event and accidentally select another PR. + PR_GATE_EVENT_RESOLVED: 'true' PR_GATE_MERGE: ${{ inputs.merge }} PR_GATE_WAIT_MINUTES: ${{ inputs.wait-minutes }} PR_GATE_REQUIRED_CHECKS: ${{ inputs.required-checks }} diff --git a/pr-gate/README.md b/pr-gate/README.md index d6a4d7b..2f3a3ff 100644 --- a/pr-gate/README.md +++ b/pr-gate/README.md @@ -1,39 +1,31 @@ # pr-gate -The estate merge gate, running on GitHub instead of a laptop. On the PR's current head commit it passes only when: - -- A review from a GitHub bot identity of a different harness than the author exists for that commit: `chatgpt-codex-connector[bot]` (Codex) or `claude[bot]` (Claude). The author is read from the branch prefix, because every harness pushes as the same GitHub account. -- That review is an approval, or a review whose body says it found no major issues. Dismissed and pending reviews are ignored. A bot review mentioning P0 or P1 blocks, and so does a bot comment that names a P0 or P1 against the head. Bot comments never sign off, because they carry no commit id. -- A renamed file is judged on both its old and new path. -- Every check named in the repo's `required-checks` has a latest attempt that succeeded, no other check failed, and nothing is still running. Commit statuses never count: anything holding a token can post one, which is how 20 PRs merged on 2026-10-19 with no check having run. -- All review threads are resolved (every page read; an unreadable answer blocks) and the full list of changed files was read. -- It is not a draft, carries no `hold` / `do-not-merge` / `blocked` / `wip` label, and its body links the intent it serves (an issue, board item or ruling). -- It touches none of Frank's paths: workflows, env files, dependencies, money, auth and middleware, `vercel.json`, or a new or deleted public page. No label overrides this. Labels prove nothing about who applied them on a shared account, so Frank merges those himself. - -In merge mode it decides again from fresh facts just before merging and merges with a head-SHA guard. - -## What does not count - -Typed lines (`starlight-signoff: ...` from the estate `tools/pr-gate.mjs`, `Checker: claude-cloud · head · verdict PASS`) are shown as advisory but never pass the gate: the author can type them. The estate `pr-gate.mjs` still honours them for a merge a human runs. - -So today, Claude-authored PRs pass once Codex reviews them. Codex- and Gemini-authored PRs pass only after a review from the Claude GitHub bot, or a human-run merge. - -Branch prefixes: `agent/claude/`, `claude/`, `ccr-` and `factory/` (Foreman, whose implementer is an Anthropic model) are Claude; `codex/`, `agent/codex/`, `agent/gpt*` are Codex; `agent/antigravity/`, `agent/gemini/`, Jules and `sentinel-` branches are Gemini. - -## Install in a repo - -1. Copy `caller.yml` to `.github/workflows/pr-gate.yml` and `poke.yml` to `.github/workflows/pr-gate-poke.yml`. Replace both `GATE_SHA` with a commit of this repo, list the repo's CI workflow names under `workflow_run`, and its check names in `required-checks`. -2. Turn on Codex code review and automatic reviews for the repo in Codex settings. -3. Add the section in `CODE-REVIEW-RULES.md` to the repo's `AGENTS.md`. -4. Start with `merge: false` (report only). Flip to `merge: true` where autonomous landing is ruled. - -Every trigger runs the caller from the default branch. Review events go through `pr-gate-poke`, which holds no permissions, and come back as `workflow_run`. - -## Known limits - -- Without branch protection nothing stops someone merging around the gate; the private repos on the free plan cannot have it. The gate is the merge path agents are told to use, not a lock. -- Between the final decision and the merge call a few milliseconds remain in which a review could be dismissed. Only a required status check under branch protection closes that. -- A same-repo PR's own workflows run with the repo token. The gate refuses to merge any PR that edits workflows, but cannot stop such a PR from posting a same-named check on itself. -- A squash merge made with the workflow token does not trigger push workflows on the base branch. Vercel's git integration still deploys. - -Tests: `node --test pr-gate/decide.test.mjs`. +Report-only PR diagnostics. This implementation cannot authorize a merge or +certify provider independence. `merge: true` is refused before any API request. + +The runner reads PR files, reviews, comments, threads and checks through GitHub's +API without executing PR source. It binds observations to a full head SHA, +checks current-attempt job membership, and rejects missing or ambiguous CI. +Typed receipts and clean prose never supply approval. A review bot identifies +the reviewer account; the maker's actual provider remains unverified because +all harnesses can push under the same human GitHub account and choose branch names. + +Call the reusable workflow at an immutable commit with `gate-ref` set to that +same commit. Required contexts use JSON, for example: + +```yaml +required-checks: >- + [{"name":"Starlight CI / release aggregate","appId":15368,"workflowPath":".github/workflows/ci.yml"}] +merge: false +``` + +Legacy comma-separated context names are diagnostic only and fail provenance +validation. Existing pinned consumers retain their old behavior until separately +reviewed. Do not change every consumer or enable required enforcement in a batch. + +Permissions: contents/checks/actions read; issues/pull-requests write for reports. +No contents write, secrets, id-token write or production credentials are needed. +The zero-permission review relay triggers a fresh API read and supplies no verdict. + +Tests: `node --test pr-gate/*.test.mjs`. +Threat model: `Review-threat-model-Codex-2026-11-03-v1.md`. diff --git a/pr-gate/Review-threat-model-Codex-2026-11-03-v1.md b/pr-gate/Review-threat-model-Codex-2026-11-03-v1.md new file mode 100644 index 0000000..7b8527e --- /dev/null +++ b/pr-gate/Review-threat-model-Codex-2026-11-03-v1.md @@ -0,0 +1,49 @@ +# pr-gate threat model, Codex, 3 November 2026, revision 1 + +Author: Codex. Source base: e3faf85affc49cc8b97a87bebdf20bd97833d6b4. +Review state: candidate, independent-provider review pending. Existing consumers remain pinned. + +Protect source, production, review evidence and write permissions. PR source, +branch names, comments, event titles, diffs and artifacts are untrusted. API +identities prove GitHub actors, not the model used by a human-account maker. +No trusted maker attestation exists, so different bot/harness names cannot +certify provider independence. + +Ten new regression tests failed against the old source. They cover abbreviated +SHAs, free-form clean prose, unauthenticated maker identity, ignored same-provider +P1s, absent app/workflow/head provenance, retry ordering, duplicate names and +missing thread data. Origin cases exercise the missing provenance contract; +they do not claim every existing configuration exposed an identical exploit. + +Repairs: full SHA equality; native APPROVED review state; blocking findings count +regardless of branch hint; app/workflow/repository/head/suite/current-attempt job +binding; failed newer attempts beat old success; incomplete data fails closed; +15-second API deadlines, at most three GET attempts, no retry of uncertain writes; +no private error-body printing; head re-read before report; only Actions Bot's +own sticky marker is updated; immutable gate checkout; no contents-write or +automatic merge; immediate reports replace billed idle polling. + +Provider independence remains unverified. Every candidate stays WAITING or +BLOCKED, and merge=true is refused. This is a diagnostic limit, not production +authorization. Human review can evaluate declared authorship separately; typed +comments do not become authenticated remote attestations. + +`pull_request_target` and `workflow_run` must load trusted default-branch callers. +Only pinned gate code is checked out; no PR executable, artifact or fork source +runs with reporting permissions. Relay numbers cause fresh API reads. Workflow +edits remain sensitive changes requiring security review and human authorization. + +The head or reviews can still change after the final API read. Reports identify +their exact head and confer no merge authority. Actions app identity alone cannot +prove immutable workflow logic. Current protection and independent review must +cover workflow changes; no stronger enforcement is claimed by this candidate. + +44 local tests pass: 17 reconciled existing tests, ten regression tests and 17 +runner/API tests covering spoofed comments, races, missing data, pagination, +partial GraphQL results, retry/denial behavior and malicious URLs. Fixtures do +not establish live GitHub integration or independent security review. + +Sources read 3 November 2026: GitHub required-status-check troubleshooting, +secure pull_request_target docs, REST check-runs/workflow-runs/jobs docs, and +the exact pinned source consumed by Starlight main. No existing app permission, +billing, default-branch rule, production deployment or PR finding is changed. diff --git a/pr-gate/Review-threat-model-Codex-2026-11-03-v2.md b/pr-gate/Review-threat-model-Codex-2026-11-03-v2.md new file mode 100644 index 0000000..d32a5e8 --- /dev/null +++ b/pr-gate/Review-threat-model-Codex-2026-11-03-v2.md @@ -0,0 +1,51 @@ +# pr-gate review reconciliation, Codex, 3 November 2026, revision 2 + +Author: Codex. Actual reviewer: Claude via the existing agentic-ops GitHub workflow. +Original candidate: 68cac61112403f68af7a9a6836d70899157a36e7. State: refined candidate; +the new head still requires exact-revision follow-up. Revision 1 is preserved. + +Review evidence: https://github.com/frankxai/agentic-ops/pull/439#issuecomment-6606894236 +The reviewer read all 13 supplied files in the combined source packet. It did not +recompute the hashes, fetch upstream source or review either complete product. +Its 2m16s workflow completion is supported by an actual substantive review comment, +not inferred from exit status. No specific model version or cash charge is asserted. + +Reconciliation: + +- Medium, self-attested aggregate code: protect .github/scripts and the aggregate + test path alongside workflows. This adds a human-gate reason in diagnostics; + report-only logic is still not server-side CODEOWNERS or required-workflow enforcement. +- Low-medium, fork relay/title: discard event titles and attached PR arrays. Read + the triggering workflow run and resolve its current PR from repository/head/fork + identity through the commits/pulls API. Reject unknown workflows or ambiguity. + Concurrency uses head SHA instead of title. Fork relay, stale and adversarial + title tests exercise this path directly. +- Low, source pin mismatch: use GitHub's documented job.workflow_sha and + job.workflow_repository (not github.job_workflow_sha) to compare the loaded gate + ref with the actual reusable job source before checkout. Missing context fails + closed. The actual inline validator is exercised in separate Node processes. + The privileged reusable workflow's existing checkout/setup-node v4 refs are now + pinned to their observed tag commits without changing major versions. +- Low, unused wait input/dead branch: mark the compatibility input deprecated + and remove the unreachable branch. Conservative free-text severity blocking + remains a diagnostic false-positive risk; it does not permit a merge. A trusted + structured finding protocol is required before this can become enforcement. +- Conditional medium, self-hosted fork code in the Starlight build: current + repository variable inventory returned no variables, including CI_RUNNER. + No self-hosted admission is observed. This remains a future configuration risk; + a later runner change must qualify untrusted-PR isolation and explicit approval. +- Low-medium, tested merge SHA/base: current Starlight logic relies on GitHub's + same-run needs and checkout semantics. It does not independently inspect merge + parents or enforce a current base. Do not claim those properties. Strict branch + protection or a qualified merge queue remains a separate release decision. + +57 focused tests pass after these repairs, including the 44 initial cases and +13 additional protected-path, event-routing and actual workflow-validator cases. +No consumer pin, live protection, billing, app grant, sensitive merge or deployment +has changed. New runtime contexts need actual integration proof before adoption. + +Primary sources checked 3 November 2026: +- https://docs.github.com/en/actions/reference/workflows-and-actions/contexts +- https://docs.github.com/en/rest/actions/workflow-runs +- Live Starlight pr-gate run 41656793060 referenced_workflows corroborates its + actual old reusable source pin; it does not qualify this new candidate. diff --git a/pr-gate/Review-threat-model-Codex-2026-11-03-v3.md b/pr-gate/Review-threat-model-Codex-2026-11-03-v3.md new file mode 100644 index 0000000..d54bf1c --- /dev/null +++ b/pr-gate/Review-threat-model-Codex-2026-11-03-v3.md @@ -0,0 +1,33 @@ +# pr-gate concurrency reconciliation, Codex, 3 November 2026, revision 3 + +Author: Codex. Reviewer: actual Claude GitHub workflow, follow-up comment +https://github.com/frankxai/agentic-ops/pull/439#issuecomment-6607435620. +State: refined source candidate; new exact-head follow-up and live reusable-source +qualification remain required. Earlier revisions and review limits are preserved. + +Claude read all seven v2 packet files and confirmed earlier protected-path, +title-routing and source-pin repairs in the report-only scope. It identified a +medium availability defect: workflow-level cancellation happened before the +comment authorization condition, so an ineligible comment could cancel a report. +Different event groups could also overwrite same-head diagnostics out of order. + +The caller now has no workflow concurrency. A read-only resolver in the pinned +reusable source obtains the actual PR before the report job. Only eligible, +resolved report jobs join one repository/PR group, with cancel-in-progress=false. +Every event type for that PR uses the same group. Main push completion is a no-op. +The report reloads current facts after it acquires its job slot; resolved identity +uses PR_GATE_EVENT_RESOLVED rather than attempting to override GITHUB_* variables. +Reports disclose observation time and run identity. This prevents overlapping +workflow reports; manual invocations outside that scheduler remain a limitation. + +Repository identity comparison follows GitHub's case-insensitive semantics. New +tests exercise the actual resolver, actual inline source validator, resolved +identity handoff, pinned checkout refs and the workflow's concurrency contract. +They do not simulate GitHub's scheduler or prove a live reusable workflow context. +62 focused tests pass. Same-head facts can change immediately after collection; +diagnostic comments are snapshots and never authorize merge or production. + +Remaining limits: app/workflow path does not prove immutable PR workflow content; +workflow changes still require the human gate. Conservative free-text severity +matching may block a clean bot comment. No authenticated maker-provider protocol +exists, so every report remains WAITING or BLOCKED. The gate stays report-only. diff --git a/pr-gate/caller.yml b/pr-gate/caller.yml index 62f486d..fc7c4d9 100644 --- a/pr-gate/caller.yml +++ b/pr-gate/caller.yml @@ -1,7 +1,7 @@ # Copy to .github/workflows/pr-gate.yml in a product repo, with poke.yml beside it. # Replace GATE_SHA (both places) with a commit of Starlight-Intelligence/.github, list the repo's CI -# workflow names under workflow_run and its check names in required-checks, and set merge to true -# only where autonomous landing is ruled. +# workflow names under workflow_run and authenticated contexts in required-checks. +# This gate remains report-only; merge=true is refused. # # Every trigger here runs this file from the default branch, never from the PR, so a PR cannot # rewrite the gate it is judged by. Reviews arrive through pr-gate-poke (no permissions) and come @@ -18,14 +18,11 @@ on: types: [completed] permissions: - contents: write + contents: read pull-requests: write issues: write checks: read - -concurrency: - group: pr-gate-${{ github.event.pull_request.number || github.event.issue.number || github.event.workflow_run.pull_requests[0].number || github.event.workflow_run.display_title }} - cancel-in-progress: true + actions: read jobs: pr-gate: @@ -39,9 +36,9 @@ jobs: (github.event.comment.body == '/gate' && contains(fromJSON('["OWNER","MEMBER"]'), github.event.comment.author_association)))) uses: Starlight-Intelligence/.github/.github/workflows/pr-gate.yml@GATE_SHA with: - # Reusable inputs are typed; the number is passed as a string. A relayed review with no PR - # attached falls back to the poke run title, which is the PR number. - pr-number: ${{ format('{0}', github.event.pull_request.number || github.event.issue.number || github.event.workflow_run.pull_requests[0].number || github.event.workflow_run.display_title) }} - required-checks: test + # workflow_run resolves its PR from API-authenticated run/repository/head data. + pr-number: ${{ format('{0}', github.event.pull_request.number || github.event.issue.number || 0) }} + required-checks: >- + [{"name":"test","appId":15368,"workflowPath":".github/workflows/ci.yml"}] merge: false gate-ref: GATE_SHA diff --git a/pr-gate/decide.mjs b/pr-gate/decide.mjs index 6a80dbd..9e7db15 100644 --- a/pr-gate/decide.mjs +++ b/pr-gate/decide.mjs @@ -26,17 +26,15 @@ export function harnessOfBranch(branch) { return 'unlabeled'; } -// Under 7 hex chars a "sha" is a typo or a forgery and must never match a future head. +// Prefixes are useful display labels, never exact-revision evidence. export function shaMatches(head, given) { const h = String(head || '').toLowerCase(); const g = String(given || '').toLowerCase(); - if (!/^[0-9a-f]{7,40}$/.test(h) || !/^[0-9a-f]{7,40}$/.test(g)) return false; - return g.length <= h.length ? h.startsWith(g) : g.startsWith(h); + return /^[0-9a-f]{40}$/.test(h) && /^[0-9a-f]{40}$/.test(g) && h === g; } const MARKER_RE = /^\s*starlight-signoff:\s*harness=(\S+)\s+verdict=(\S+)\s+sha=([0-9a-fA-F]{7,40})\b/i; const CHECKER_RE = /^\s*Checker:\s*([a-z0-9_-]+?)(?:-cloud)?\s*[·|-]\s*head\s+([0-9a-fA-F]{7,40})\s*[·|-]\s*verdict\s+(PASS|FAIL|BLOCK)\b/i; -const CODEX_CLEAN_RE = /didn'?t find any major issues/i; const SEVERE_RE = /\bp[01]\b|p[01] badge/i; // GitHub's own bot accounts are the only reviewer identity an agent cannot type its way into. @@ -72,7 +70,7 @@ export function collectSignoffs({ comments = [], reviews = [], headSha }) { const body = String(r.body || ''); let verdict = null; if (r.state === 'CHANGES_REQUESTED' || SEVERE_RE.test(body)) verdict = 'block'; - else if (r.state === 'APPROVED' || CODEX_CLEAN_RE.test(body)) verdict = 'pass'; + else if (r.state === 'APPROVED') verdict = 'pass'; // A COMMENTED review that neither approves nor says it is clean is not a verdict either way; // its inline findings surface as unresolved threads. if (verdict) out.push({ harness: h, verdict, sha: String(r.commitId || '').toLowerCase(), via: 'bot-review', trusted: true }); @@ -84,6 +82,8 @@ export function collectSignoffs({ comments = [], reviews = [], headSha }) { // dependencies, workflows (a PR that edits CI could edit this gate), and public route deletion. const FRANK_PATHS = [ [/^\.github\/workflows\//, 'edits CI workflows'], + [/^\.github\/scripts\//, 'edits CI implementation'], + [/^scripts\/tests\/ci-aggregate\.test\.mjs$/, 'edits the required CI aggregate contract'], [/(^|\/)\.env/, 'touches env files'], [/(^|\/)(package\.json|pnpm-lock\.yaml|package-lock\.json|yarn\.lock|uv\.lock|pyproject\.toml)$/, 'changes dependencies'], [/(checkout|billing|pricing|payment|payout|refund|stripe|polar|wallet)/i, 'touches a money path'], @@ -111,18 +111,39 @@ export function protectedReasons(files = []) { // CI counts only as check runs. Commit statuses are excluded on purpose: anything holding a token // can post `state=success`, which is how 20 PRs merged on 2026-10-19 with no check having run. // Each repo names the checks that must pass; one unrelated green check is not CI. -export function ciState(checkRuns = [], required = [], selfPrefix = 'pr-gate') { - const runs = checkRuns.filter((r) => !String(r.name || '').toLowerCase().startsWith(selfPrefix)); +export function ciState(checkRuns = [], required = [], selfPrefix = 'pr-gate', headSha) { + const candidates = checkRuns.filter((r) => !r.superseded && !String(r.name || '').toLowerCase().startsWith(selfPrefix)); + // Re-runs may leave several attempts in the API. Retain the newest run and + // attempt per workflow/app/name; never let API ordering choose an old success. + const groups = new Map(); + for (const r of candidates) { + const key = JSON.stringify([r.appId, r.workflowPath, r.name]); + const group = groups.get(key) || []; + group.push(r); groups.set(key, group); + } + const runs = [...groups.values()].flatMap(group => { + const latestRun = Math.max(...group.map(r => r.runId || 0)); + const latestAttempt = Math.max(...group.filter(r => (r.runId || 0) === latestRun).map(r => r.runAttempt || 0)); + return group.filter(r => (r.runId || 0) === latestRun && (r.runAttempt || 0) === latestAttempt); + }); const bad = runs.filter((r) => r.status === 'completed' && ['failure', 'cancelled', 'timed_out', 'action_required', 'stale', 'startup_failure'].includes(r.conclusion)); const pending = runs.filter((r) => r.status !== 'completed'); const missing = []; const notPassed = []; - for (const name of required) { - const r = runs.find((x) => x.name === name); - if (!r) missing.push(name); - else if (r.status === 'completed' && r.conclusion !== 'success') notPassed.push(`${name} (${r.conclusion})`); + const invalid = []; + for (const spec of required) { + const name = typeof spec === 'string' ? spec : spec?.name; + const named = runs.filter(x => x.name === name); + if (!named.length) { missing.push(name); continue; } + if (!spec || typeof spec !== 'object' || spec.appId !== 15368 || !/^\.github\/workflows\/[^/]+\.ya?ml$/.test(spec.workflowPath || '')) { + invalid.push(`${name}: app and workflow provenance must be configured`); continue; + } + const matches = named.filter(r => r.appId === spec.appId && r.workflowPath === spec.workflowPath && shaMatches(headSha, r.headSha) && Number.isSafeInteger(r.runId) && r.runId > 0 && Number.isSafeInteger(r.runAttempt) && r.runAttempt > 0); + if (matches.length !== 1 || named.length !== 1) { invalid.push(`${name}: missing, ambiguous or untrusted check origin/revision`); continue; } + const r = matches[0]; + if (r.status === 'completed' && r.conclusion !== 'success') notPassed.push(`${name} (${r.conclusion})`); } - return { bad, pending, missing, notPassed }; + return { bad, pending, missing, notPassed, invalid }; } const HOLD_LABELS = ['hold', 'do-not-merge', 'blocked', 'wip']; @@ -138,6 +159,12 @@ export function decide(f) { const reasons = []; const waiting = []; + if (!/^[0-9a-f]{40}$/.test(head)) reasons.push('full head SHA unavailable'); + // All harnesses use the same human GitHub account. A branch prefix is + // caller-controlled and the reviewer bot does not attest who implemented the + // change. Until a trusted maker attestation exists, this gate cannot certify + // provider independence, even when all observable checks/reviews are clean. + waiting.push('provider independence unverified: no authenticated implementation-provider attestation'); if (f.state && f.state !== 'open') reasons.push(`PR is ${f.state}`); if (f.draft) reasons.push('PR is a draft'); @@ -148,7 +175,7 @@ export function decide(f) { reasons.push('no linked intent: reference the issue, board item or ruling this PR serves'); } - const blocks = signoffs.filter((s) => (s.verdict === 'block' || s.verdict === 'fail') && onHead(s) && s.harness !== author); + const blocks = signoffs.filter((s) => (s.verdict === 'block' || s.verdict === 'fail') && onHead(s)); const valid = signoffs.filter((s) => s.verdict === 'pass' && onHead(s) && s.harness !== author); if (blocks.length) reasons.push(`blocked on this commit by ${[...new Set(blocks.map((b) => b.harness))].join(', ')}`); if (!valid.length) { @@ -158,15 +185,17 @@ export function decide(f) { } if (f.incomplete) reasons.push(`could not read the whole PR: ${f.incomplete}`); - if ((f.unresolvedThreads || 0) > 0) reasons.push(`${f.unresolvedThreads} unresolved review thread(s)`); + if (!Number.isSafeInteger(f.unresolvedThreads) || f.unresolvedThreads < 0) reasons.push('review-thread data unavailable'); + else if (f.unresolvedThreads > 0) reasons.push(`${f.unresolvedThreads} unresolved review thread(s)`); const required = f.requiredChecks || []; - const ci = ciState(f.checkRuns, required, f.selfPrefix); + const ci = ciState(f.checkRuns, required, f.selfPrefix, head); if (!required.length) reasons.push('no required CI checks are configured for this repo'); if (ci.bad.length) reasons.push(`CI failing: ${ci.bad.map((r) => r.name).join(', ')}`); if (ci.notPassed.length) reasons.push(`required check did not pass: ${ci.notPassed.join(', ')}`); + if (ci.invalid.length) reasons.push(`required check provenance invalid: ${ci.invalid.join(', ')}`); if (ci.pending.length) waiting.push(`CI still running: ${ci.pending.map((r) => r.name).join(', ')}`); - else if (ci.missing.length) reasons.push(`required check never ran on this commit: ${ci.missing.join(', ')} (commit statuses do not count)`); + if (ci.missing.length) reasons.push(`required check never ran on this commit: ${ci.missing.join(', ')} (commit statuses do not count)`); // No label can override this: every harness acts as the same account, so a label proves nothing // about who applied it. Protected changes are merged by Frank, outside this gate. diff --git a/pr-gate/decide.test.mjs b/pr-gate/decide.test.mjs index a440d77..cc69f77 100644 --- a/pr-gate/decide.test.mjs +++ b/pr-gate/decide.test.mjs @@ -6,8 +6,8 @@ const HEAD = 'a1b2c3d4e5f60718293a4b5c6d7e8f9012345678'; const codexBot = { login: 'chatgpt-codex-connector[bot]', type: 'Bot' }; const claudeBot = { login: 'claude[bot]', type: 'Bot' }; const human = { login: 'frankxai', type: 'User' }; -const greenCI = [{ name: 'test', status: 'completed', conclusion: 'success' }]; -const cleanReview = { user: codexBot, commitId: HEAD, state: 'COMMENTED', body: "Codex Review: Didn't find any major issues." }; +const greenCI = [{ id: 1, name: 'test', status: 'completed', conclusion: 'success', appId: 15368, workflowPath: '.github/workflows/ci.yml', headSha: HEAD, runId: 1, runAttempt: 1 }]; +const cleanReview = { user: codexBot, commitId: HEAD, state: 'APPROVED', body: '' }; const base = (over = {}) => ({ headRef: 'agent/claude/thing', @@ -20,14 +20,16 @@ const base = (over = {}) => ({ comments: [], reviews: [cleanReview], checkRuns: greenCI, - requiredChecks: ['test'], + requiredChecks: [{ name: 'test', appId: 15368, workflowPath: '.github/workflows/ci.yml' }], unresolvedThreads: 0, ...over, }); -test('clean Claude PR with a clean Codex bot review on head passes', () => { +test('clean observed checks and review still need authenticated maker-provider evidence', () => { const d = decide(base()); - assert.equal(d.ok, true, JSON.stringify(d)); + assert.equal(d.ok, false, JSON.stringify(d)); + assert.equal(d.reasons.length, 0, JSON.stringify(d)); + assert.match(d.waiting.join(), /provider independence unverified/); assert.deepEqual(d.signers, ['codex']); }); @@ -83,15 +85,16 @@ test('renames are judged on both ends', () => { assert.equal(decide(base({ files: [{ filename: 'app/new/page.tsx', previousFilename: 'app/about/page.tsx', status: 'renamed' }] })).ok, false); }); -test('Claude bot approval signs a Codex PR on the exact head', () => { +test('Claude bot approval is observed but cannot attest the maker provider', () => { const d = decide(base({ headRef: 'codex/x', reviews: [{ user: claudeBot, commitId: HEAD, state: 'APPROVED', body: '' }] })); - assert.equal(d.ok, true, JSON.stringify(d)); + assert.equal(d.ok, false, JSON.stringify(d)); + assert.deepEqual(d.signers, ['claude']); assert.equal(shaMatches(HEAD, 'a1b2'), false); }); test('required checks must exist and pass; skipped or unrelated green is not CI', () => { assert.match(decide(base({ checkRuns: [] })).reasons.join(), /never ran/); - assert.match(decide(base({ checkRuns: [{ name: 'docs', status: 'completed', conclusion: 'success' }, { name: 'test', status: 'completed', conclusion: 'skipped' }] })).reasons.join(), /did not pass: test \(skipped\)/); + assert.match(decide(base({ checkRuns: [{ name: 'docs', status: 'completed', conclusion: 'success' }, { ...greenCI[0], conclusion: 'skipped' }] })).reasons.join(), /did not pass: test \(skipped\)/); assert.match(decide(base({ requiredChecks: [] })).reasons.join(), /no required CI checks/); }); diff --git a/pr-gate/hardening.test.mjs b/pr-gate/hardening.test.mjs new file mode 100644 index 0000000..cab306b --- /dev/null +++ b/pr-gate/hardening.test.mjs @@ -0,0 +1,43 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { decide, shaMatches, ciState, collectSignoffs, protectedReasons } from './decide.mjs'; +const head = 'a'.repeat(40); +const bot = { login: 'chatgpt-codex-connector[bot]', type: 'Bot', id: 196283668 }; +const check = { id: 2, name: 'test', status: 'completed', conclusion: 'success', appId: 15368, headSha: head, workflowPath: '.github/workflows/ci.yml', runId: 2, runAttempt: 1 }; +const facts = () => ({ headRef: 'agent/claude/change', headSha: head, state: 'open', body: 'Serves #12', files: [], requiredChecks: [{ name: 'test', appId: 15368, workflowPath: '.github/workflows/ci.yml' }], checkRuns: [check], reviews: [{ user: bot, commitId: head, state: 'APPROVED', body: '' }], unresolvedThreads: 0 }); + +test('abbreviated SHA never satisfies exact-head binding', () => assert.equal(shaMatches(head, head.slice(0, 7)), false)); +test('free-form clean prose is not an authenticated approval', () => { + const s = collectSignoffs({ headSha: head, reviews: [{ user: bot, commitId: head, state: 'COMMENTED', body: 'Example output: "Didn\'t find any major issues."' }] }); + assert.equal(s.some(x => x.trusted && x.verdict === 'pass'), false); +}); +test('a branch prefix and reviewer bot cannot prove implementation-provider independence', () => { + const f = facts(); f.requiredChecks = ['test']; + assert.equal(decide(f).ok, false); +}); +test('same-provider P1 blocks even when another provider approved', () => { + const f = facts(); f.headRef = 'codex/change'; f.reviews.push({ user: { login: 'claude[bot]', type: 'Bot' }, commitId: head, state: 'APPROVED', body: '' }); f.reviews[0].state = 'CHANGES_REQUESTED'; + assert.match(decide(f).reasons.join(), /blocked on this commit/); +}); +test('a check from an arbitrary app is not CI', () => { + const r = ciState([{ ...check, appId: 999 }], [{ name: 'test', appId: 15368, workflowPath: '.github/workflows/ci.yml' }], 'pr-gate', head); + assert.ok(r.invalid?.length); +}); +test('the correct app on the wrong workflow is not CI', () => { + const r = ciState([{ ...check, workflowPath: '.github/workflows/fake.yml' }], [{ name: 'test', appId: 15368, workflowPath: '.github/workflows/ci.yml' }], 'pr-gate', head); + assert.ok(r.invalid?.length); +}); +test('a check from an older SHA cannot pass', () => { + const r = ciState([{ ...check, headSha: 'b'.repeat(40) }], [{ name: 'test', appId: 15368, workflowPath: '.github/workflows/ci.yml' }], 'pr-gate', head); + assert.ok(r.invalid?.length); +}); +test('a newer failing retry beats an older success regardless of API order', () => { + const r = ciState([check, { ...check, id: 3, runAttempt: 2, conclusion: 'failure' }], [{ name: 'test', appId: 15368, workflowPath: '.github/workflows/ci.yml' }], 'pr-gate', head); + assert.equal(r.notPassed.length, 1); +}); +test('duplicate check names within the latest attempt fail closed', () => { + const r = ciState([check, { ...check, id: 3 }], [{ name: 'test', appId: 15368, workflowPath: '.github/workflows/ci.yml' }], 'pr-gate', head); + assert.ok(r.invalid?.length); +}); +test('missing review-thread data never means zero unresolved threads', () => assert.match(decide({ ...facts(), unresolvedThreads: undefined }).reasons.join(), /thread.*unavailable/)); +for (const filename of ['.github/scripts/ci-aggregate.mjs', 'scripts/tests/ci-aggregate.test.mjs']) test(`${filename} cannot change the required-check implementation without the human gate`, () => assert.ok(protectedReasons([{ filename, status: 'modified' }]).length)); diff --git a/pr-gate/run.mjs b/pr-gate/run.mjs index 9f74f08..f6f8634 100644 --- a/pr-gate/run.mjs +++ b/pr-gate/run.mjs @@ -1,143 +1,159 @@ -// run.mjs: fetch the facts for one PR, decide, report, and merge on a clean pass. -// No dependencies: Node 20+ fetch against the GitHub API with the workflow's GITHUB_TOKEN. -// It never checks out or executes the PR's code. -import { appendFileSync } from 'node:fs'; +// Trusted default-branch report runner. Never checks out or executes PR source. +import { appendFileSync, readFileSync } from 'node:fs'; +import { pathToFileURL } from 'node:url'; import { decide } from './decide.mjs'; -const token = process.env.GITHUB_TOKEN; -const repo = process.env.GITHUB_REPOSITORY; -const rawNumber = String(process.env.PR_NUMBER || '').trim(); -const merge = process.env.PR_GATE_MERGE === 'true'; -const waitMinutes = Number(process.env.PR_GATE_WAIT_MINUTES || 8); -const selfPrefix = (process.env.PR_GATE_SELF_PREFIX || 'pr-gate').toLowerCase(); -const requiredChecks = String(process.env.PR_GATE_REQUIRED_CHECKS || '').split(',').map((s) => s.trim()).filter(Boolean); const STICKY = ''; - -if (!token || !repo) { console.error('GITHUB_TOKEN and GITHUB_REPOSITORY are required'); process.exit(2); } -// A CI run with no PR attached passes its own title here; that is not a PR to judge. -if (!/^[1-9][0-9]{0,8}$/.test(rawNumber)) { console.log(`no PR number in "${rawNumber.slice(0, 80)}"; nothing to judge`); process.exit(0); } -const number = Number(rawNumber); -const [owner, name] = repo.split('/'); - -async function api(path, init = {}) { - const res = await fetch(`https://api.github.com${path}`, { - ...init, - headers: { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28', ...(init.headers || {}) }, - }); - if (!res.ok) throw Object.assign(new Error(`${init.method || 'GET'} ${path} -> ${res.status} ${await res.text()}`), { status: res.status }); - return res.status === 204 ? null : res.json(); +const ACTIONS_BOT = 'github-actions[bot]'; +export function createClient(token, request = fetch, pause = ms => new Promise(r => setTimeout(r, ms))) { + return async function api(path, init = {}) { + const method = init.method || 'GET'; + for (let attempt = 0; attempt < 3; attempt++) { + const response = await request(`https://api.github.com${path}`, { + ...init, + headers: { authorization: `Bearer ${token}`, accept: 'application/vnd.github+json', 'x-github-api-version': '2022-11-28' }, + signal: AbortSignal.timeout(15_000), + }); + if (method === 'GET' && [429, 502, 503, 504].includes(response.status) && attempt < 2) { await pause(250 * 2 ** attempt); continue; } + // Do not echo private response bodies or retry uncertain writes. + if (!response.ok) throw new Error(`${method} ${path} -> HTTP ${response.status}`); + return response.status === 204 ? null : response.json(); + } + }; } -// Fails closed: running out of pages before running out of items is an error, never a short list. -async function all(path) { + +export async function all(api, path) { const out = []; for (let page = 1; page <= 50; page++) { - const sep = path.includes('?') ? '&' : '?'; - const batch = await api(`${path}${sep}per_page=100&page=${page}`); - const items = Array.isArray(batch) ? batch : batch.check_runs; + const batch = await api(`${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`); + const items = Array.isArray(batch) ? batch : batch?.check_runs ?? batch?.jobs; + if (!Array.isArray(items)) throw new Error('invalid paginated API response'); out.push(...items); if (items.length < 100) return out; } - throw new Error(`${path} has more than 5,000 items`); + throw new Error('API pagination exceeded 5,000 items'); } -// Every page, and a GraphQL error is a failure: a missing answer must never read as zero threads. -async function unresolvedThreads() { - const q = `query($o:String!,$n:String!,$p:Int!,$c:String){repository(owner:$o,name:$n){pullRequest(number:$p){reviewThreads(first:100,after:$c){nodes{isResolved}pageInfo{hasNextPage endCursor}}}}}`; - let count = 0; - let cursor = null; - for (let i = 0; i < 50; i++) { - const r = await api('/graphql', { method: 'POST', body: JSON.stringify({ query: q, variables: { o: owner, n: name, p: number, c: cursor } }) }); - const t = r.data?.repository?.pullRequest?.reviewThreads; - if (r.errors?.length || !t) throw new Error(`review threads unreadable: ${JSON.stringify(r.errors || 'no data').slice(0, 300)}`); - count += t.nodes.filter((n) => !n.isResolved).length; - if (!t.pageInfo.hasNextPage) return count; - cursor = t.pageInfo.endCursor; + +export async function resolvePrNumber(env, api) { + if (env.PR_GATE_EVENT_RESOLVED === 'true' || env.GITHUB_EVENT_NAME !== 'workflow_run') { + const raw = String(env.PR_NUMBER || '').trim(); + return /^[1-9][0-9]{0,8}$/.test(raw) ? Number(raw) : null; + } + const event = JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8')); + const id = event.workflow_run?.id; + if (!Number.isSafeInteger(id) || id < 1) throw new Error('workflow run identity unavailable'); + // The event title, relay output and attached PR array supply no authority. + // Re-read the run and resolve current open PRs by its actual repository/head. + const run = await api(`/repos/${env.GITHUB_REPOSITORY}/actions/runs/${id}`); + const allowed = String(env.PR_GATE_ALLOWED_WORKFLOWS || '.github/workflows/ci.yml,.github/workflows/pr-gate-poke.yml').split(','); + if (run.repository?.full_name !== env.GITHUB_REPOSITORY || !/^[a-f0-9]{40}$/.test(run.head_sha || '') || !allowed.includes(run.path?.split('@')[0])) throw new Error('untrusted workflow run relay'); + if (run.event === 'push') return null; // Main CI completion is not a PR review event. + if (!['pull_request', 'pull_request_review'].includes(run.event)) throw new Error('untrusted workflow run relay'); + const prs = await all(api, `/repos/${env.GITHUB_REPOSITORY}/commits/${run.head_sha}/pulls`); + const candidates = prs.filter(p => p.state === 'open' && p.head?.sha === run.head_sha && p.head?.repo?.full_name === run.head_repository?.full_name && p.base?.repo?.full_name === env.GITHUB_REPOSITORY); + if (candidates.length > 1) throw new Error('workflow head maps to multiple open PRs'); + return candidates[0]?.number ?? null; +} + +export async function unresolvedThreads(api, owner, name, number) { + const query = 'query($o:String!,$n:String!,$p:Int!,$c:String){repository(owner:$o,name:$n){pullRequest(number:$p){reviewThreads(first:100,after:$c){nodes{isResolved}pageInfo{hasNextPage endCursor}}}}}'; + let count = 0, cursor = null; + for (let page = 0; page < 50; page++) { + const r = await api('/graphql', { method: 'POST', body: JSON.stringify({ query, variables: { o: owner, n: name, p: number, c: cursor } }) }); + const threads = r?.data?.repository?.pullRequest?.reviewThreads; + if (r?.errors?.length || !Array.isArray(threads?.nodes) || typeof threads?.pageInfo?.hasNextPage !== 'boolean' || threads.nodes.some(n => typeof n?.isResolved !== 'boolean')) throw new Error('review threads unreadable'); + count += threads.nodes.filter(n => !n.isResolved).length; + if (!threads.pageInfo.hasNextPage) return count; + if (!threads.pageInfo.endCursor || threads.pageInfo.endCursor === cursor) throw new Error('review thread cursor did not advance'); + cursor = threads.pageInfo.endCursor; } - throw new Error('review threads exceed 5,000'); + throw new Error('review threads exceeded 5,000'); } -async function facts() { +export async function facts(api, repo, number, requiredChecks) { + const [owner, name] = repo.split('/'); const pr = await api(`/repos/${repo}/pulls/${number}`); + if (!/^[a-f0-9]{40}$/.test(pr?.head?.sha || '')) throw new Error('full PR head unavailable'); const head = pr.head.sha; - const [files, comments, reviews, checkRuns, threads] = await Promise.all([ - all(`/repos/${repo}/pulls/${number}/files`), - all(`/repos/${repo}/issues/${number}/comments`), - all(`/repos/${repo}/pulls/${number}/reviews`), - // filter=latest: only the newest attempt of each check counts, so a rerun that failed wins - // over an older success. - all(`/repos/${repo}/commits/${head}/check-runs?filter=latest`), - unresolvedThreads(), + const [files, comments, reviews, checks, threads] = await Promise.all([ + all(api, `/repos/${repo}/pulls/${number}/files`), + all(api, `/repos/${repo}/issues/${number}/comments`), + all(api, `/repos/${repo}/pulls/${number}/reviews`), + all(api, `/repos/${repo}/commits/${head}/check-runs?filter=all`), + unresolvedThreads(api, owner, name, number), ]); - // The files endpoint stops at 3,000; a protected path past that point must not go unseen. - const incomplete = files.length < pr.changed_files ? `saw ${files.length} of ${pr.changed_files} changed files` : ''; - return { - pr, - f: { - headRef: pr.head.ref, - headSha: head, - incomplete, - requiredChecks, - draft: pr.draft, - state: pr.state, - body: pr.body || '', - labels: pr.labels.map((l) => l.name), - files: files.map((x) => ({ filename: x.filename, status: x.status, previousFilename: x.previous_filename })), - comments: comments.filter((c) => !String(c.body || '').includes(STICKY)).map((c) => ({ body: c.body, user: c.user, createdAt: c.created_at })), - reviews: reviews.map((r) => ({ user: r.user, commitId: r.commit_id, state: r.state, body: r.body })), - checkRuns: checkRuns.map((r) => ({ name: r.name, status: r.status, conclusion: r.conclusion })), - unresolvedThreads: threads, - selfPrefix, - }, - }; + if (checks.length > 300) throw new Error('too many check runs for bounded provenance inspection'); + const runCache = new Map(); + const jobCache = new Map(); + const checkRuns = []; + // Only authenticated required contexts can earn CI credit. Never fetch an + // untrusted details_url: parse its run ID and use the selected repo's API. + for (const c of checks) { + let workflowPath, runId, runAttempt, superseded = false; + if (requiredChecks.some(s => (typeof s === 'string' ? s : s.name) === c.name) && c.app?.id === 15368) { + let url; + try { url = new URL(c.details_url); } catch { /* invalid origin stays untrusted */ } + const prefix = `/${repo}/actions/runs/`; + const match = url?.origin === 'https://github.com' && url.pathname.startsWith(prefix) ? /^(\d+)(?:\/job\/\d+)?$/.exec(url.pathname.slice(prefix.length)) : null; + if (match) { + const id = Number(match[1]); + if (!runCache.has(id)) runCache.set(id, await api(`/repos/${repo}/actions/runs/${id}`)); + const run = runCache.get(id); + if (run.head_sha === head && run.repository?.full_name === repo && run.check_suite_id === c.check_suite?.id) { + if (!Number.isSafeInteger(run.run_attempt) || run.run_attempt < 1) throw new Error('run attempt unavailable'); + if (!jobCache.has(id)) jobCache.set(id, await all(api, `/repos/${repo}/actions/runs/${id}/attempts/${run.run_attempt}/jobs`)); + const jobs = jobCache.get(id); + const job = jobs.find(j => j.check_run_url === `https://api.github.com/repos/${repo}/check-runs/${c.id}`); + if (job && job.name === c.name) { + workflowPath = run.path?.split('@')[0]; runId = run.id; runAttempt = run.run_attempt; + } else superseded = true; + } + } + } + checkRuns.push({ id: c.id, name: c.name, status: c.status, conclusion: c.conclusion, appId: c.app?.id, headSha: c.head_sha, workflowPath, runId, runAttempt, superseded }); + } + return { pr, f: { + headRef: pr.head.ref, headSha: head, requiredChecks, draft: pr.draft, state: pr.state, + body: pr.body || '', labels: pr.labels.map(l => l.name), + incomplete: !Number.isSafeInteger(pr.changed_files) || files.length !== pr.changed_files ? `saw ${files.length} of ${pr.changed_files} changed files` : '', + files: files.map(x => ({ filename: x.filename, status: x.status, previousFilename: x.previous_filename })), + comments: comments.filter(c => !(c.user?.type === 'Bot' && c.user?.login === ACTIONS_BOT && c.body?.includes(STICKY))), + reviews: reviews.map(r => ({ user: r.user, commitId: r.commit_id, state: r.state, body: r.body })), + checkRuns, unresolvedThreads: threads, selfPrefix: 'pr-gate', + } }; } -// Wait only when CI is the sole thing outstanding, so a PR that is otherwise clean lands in the -// same run instead of waiting for the next event. -let { pr, f } = await facts(); -let d = decide(f); -const deadline = Date.now() + waitMinutes * 60_000; -while (d.pending && d.waiting.every((w) => w.startsWith('CI still running')) && Date.now() < deadline) { - await new Promise((r) => setTimeout(r, 30_000)); - ({ pr, f } = await facts()); - d = decide(f); +export async function main(env = process.env, apiOverride) { + if (env.PR_GATE_MERGE === 'true') throw new Error('automatic merging disabled: gate qualification and authenticated maker evidence are missing'); + const repo = env.GITHUB_REPOSITORY; + if (!env.GITHUB_TOKEN || !/^[\w.-]+\/[\w.-]+$/.test(repo || '')) throw new Error('valid repository and token required'); + const api = apiOverride || createClient(env.GITHUB_TOKEN); + const number = await resolvePrNumber(env, api); + if (!number) { console.log('no current PR associated with this event; no report'); return 0; } + const raw = env.PR_GATE_REQUIRED_CHECKS || ''; + const requiredChecks = raw.startsWith('[') ? JSON.parse(raw) : raw.split(',').map(s => s.trim()).filter(Boolean); + if (!Array.isArray(requiredChecks) || requiredChecks.some(s => typeof s !== 'string' && (!s || typeof s.name !== 'string'))) throw new Error('invalid required-check policy'); + const { f } = await facts(api, repo, number, requiredChecks); + const d = decide(f); + // Do not overwrite a newer report with facts from an older head. + const current = await api(`/repos/${repo}/pulls/${number}`); + if (current.head?.sha !== f.headSha) throw new Error('head moved while collecting facts; wait for the synchronize event'); + const body = [STICKY, `**pr-gate report: ${d.reasons.length ? 'BLOCKED' : 'WAITING'}** on \`${d.head}\``, + `Branch routing hint: \`${d.author}\`; implementation-provider independence is **unverified**.`, + ...d.reasons.map(s => `- blocked: ${s}`), ...d.waiting.map(s => `- waiting: ${s}`), + '', `Observed at ${new Date().toISOString()}; run ${env.GITHUB_RUN_ID || 'local'}.`, + 'Report-only. No merge, production approval or independently authenticated maker receipt is supplied by this workflow.', + ].join('\n'); + const comments = await all(api, `/repos/${repo}/issues/${number}/comments`); + const own = comments.filter(c => c.user?.type === 'Bot' && c.user?.login === ACTIONS_BOT && c.body?.startsWith(STICKY)).sort((a, b) => b.id - a.id)[0]; + if (own) await api(`/repos/${repo}/issues/comments/${own.id}`, { method: 'PATCH', body: JSON.stringify({ body }) }); + else await api(`/repos/${repo}/issues/${number}/comments`, { method: 'POST', body: JSON.stringify({ body }) }); + if (env.GITHUB_STEP_SUMMARY) appendFileSync(env.GITHUB_STEP_SUMMARY, body + '\n'); + console.log(body); + return 1; } -let merged = null; -if (d.ok && merge) { - // Decide again from fresh facts immediately before merging, so a dismissal, hold label or failed - // rerun during the wait is seen. The window that remains is milliseconds, not minutes; only a - // required check under branch protection closes it fully. - ({ pr, f } = await facts()); - d = decide(f); -} -if (d.ok && merge) { - try { - // `sha` makes the merge refuse if the head moved after the decision was made. - const r = await api(`/repos/${repo}/pulls/${number}/merge`, { method: 'PUT', body: JSON.stringify({ merge_method: 'squash', sha: d.head }) }); - merged = r.sha; - } catch (e) { - d.ok = false; - d.reasons.push(`merge refused by GitHub: ${e.message.slice(0, 300)}`); - } +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { process.exitCode = await main(); } + catch (e) { console.error(`pr-gate failed closed: ${e.message}`); process.exitCode = 1; } } - -const verdict = merged ? 'MERGED' : d.ok ? 'PASS' : d.pending ? 'WAITING' : 'BLOCKED'; -const lines = [ - STICKY, - `**pr-gate: ${verdict}** on \`${d.head.slice(0, 7)}\` · author harness \`${d.author}\`${d.signers.length ? ` · reviewed by ${d.signers.join(', ')}` : ''}`, - d.advisory.length ? `- typed sign-off from ${d.advisory.join(', ')} noted; typed lines are unauthenticated and do not count here (use the estate pr-gate for a human-run merge)` : '', - ...d.reasons.map((r) => `- blocked: ${r}`), - ...d.waiting.map((w) => `- waiting: ${w}`), - merged ? `- squash-merged as \`${merged.slice(0, 7)}\`` : '', - d.ok && !merge ? '- this repo runs the gate in report-only mode; merge through `pr-gate merge`' : '', - '', - '_Re-evaluates on push, bot review, bot comment, label and CI completion. Comment `/gate` to re-run. A new push invalidates every review._', -].filter(Boolean); -const body = lines.join('\n'); - -const existing = (await all(`/repos/${repo}/issues/${number}/comments`)).find((c) => String(c.body || '').includes(STICKY)); -if (existing) await api(`/repos/${repo}/issues/comments/${existing.id}`, { method: 'PATCH', body: JSON.stringify({ body }) }); -else await api(`/repos/${repo}/issues/${number}/comments`, { method: 'POST', body: JSON.stringify({ body }) }); - -if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${body}\n`); -console.log(body); -process.exit(d.ok ? 0 : 1); diff --git a/pr-gate/run.test.mjs b/pr-gate/run.test.mjs new file mode 100644 index 0000000..725ffe5 --- /dev/null +++ b/pr-gate/run.test.mjs @@ -0,0 +1,91 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createClient, all, unresolvedThreads, facts, main } from './run.mjs'; + +const head = 'a'.repeat(40), repo = 'frankxai/example'; +const spec = [{ name: 'release aggregate', appId: 15368, workflowPath: '.github/workflows/ci.yml' }]; +const env = { GITHUB_TOKEN: 'fixture-not-a-credential', GITHUB_REPOSITORY: repo, PR_NUMBER: '12', PR_GATE_REQUIRED_CHECKS: JSON.stringify(spec) }; +const pr = { head: { sha: head, ref: 'codex/example' }, state: 'open', draft: false, changed_files: 1, body: 'Serves #1', labels: [] }; +const threads = { data: { repository: { pullRequest: { reviewThreads: { nodes: [], pageInfo: { hasNextPage: false } } } } } }; +function mock(options = {}) { + const writes = []; let prReads = 0, jobReads = 0; + const api = async (path, init = {}) => { + if (init.method && init.method !== 'GET' && path !== '/graphql') { writes.push({ path, ...init }); return {}; } + if (path === '/graphql') return options.threads ?? threads; + if (path === `/repos/${repo}/pulls/12`) { prReads++; return { ...pr, ...(options.pr ?? {}), head: { ...pr.head, sha: options.race && prReads > 1 ? 'b'.repeat(40) : head } }; } + if (path.includes('/pulls/12/files')) return [{ filename: 'src/x.mjs', status: 'modified' }]; + if (path.includes('/pulls/12/reviews')) return []; + if (path.includes('/issues/12/comments')) return options.comments ?? []; + if (path.includes('/check-runs?')) return { check_runs: options.checks ?? [{ id: 99, name: 'release aggregate', head_sha: head, status: 'completed', conclusion: 'success', app: { id: 15368 }, check_suite: { id: 7 }, details_url: `https://github.com/${repo}/actions/runs/77/job/100` }] }; + if (path.includes('/actions/runs/77/attempts/2/jobs')) { jobReads++; return { jobs: options.jobs ?? [{ name: 'release aggregate', check_run_url: `https://api.github.com/repos/${repo}/check-runs/99` }] }; } + if (path.endsWith('/actions/runs/77')) return { id: 77, head_sha: options.runHead ?? head, check_suite_id: 7, path: '.github/workflows/ci.yml', run_attempt: 2, repository: { full_name: repo } }; + throw new Error('unexpected endpoint ' + path); + }; + return { api, writes, jobReads: () => jobReads }; +} + +test('report mode never calls a merge endpoint', async () => { + const m = mock(); assert.equal(await main(env, m.api), 1); + assert.equal(m.writes.length, 1); assert.match(m.writes[0].path, /\/comments$/); + assert.match(JSON.parse(m.writes[0].body).body, /independence is \*\*unverified\*\*/); +}); +test('merge=true is refused before any API call', async () => { + let calls = 0; await assert.rejects(main({ ...env, PR_GATE_MERGE: 'true' }, async () => { calls++; }), /automatic merging disabled/); assert.equal(calls, 0); +}); +test('a forged sticky marker in a human comment is never edited', async () => { + const m = mock({ comments: [{ id: 1, body: ' forged', user: { type: 'User', login: 'frankxai' } }] }); + await main(env, m.api); assert.equal(m.writes[0].method, 'POST'); +}); +test('own sticky report is updated instead of duplicated on re-evaluation', async () => { + const m = mock({ comments: [{ id: 2, body: ' old', user: { type: 'Bot', login: 'github-actions[bot]' } }] }); + await main(env, m.api); assert.equal(m.writes[0].method, 'PATCH'); assert.match(m.writes[0].path, /comments\/2$/); +}); +test('head race prevents a stale report write', async () => { + const m = mock({ race: true }); await assert.rejects(main(env, m.api), /head moved/); assert.equal(m.writes.length, 0); +}); +test('missing checks still produce a blocked diagnostic', async () => { + const m = mock({ checks: [] }); await main(env, m.api); assert.match(m.writes[0].body, /never ran/); +}); +test('incomplete file lists are identified instead of certified', async () => { + const m = mock({ pr: { changed_files: 3001 } }); const r = await facts(m.api, repo, 12, spec); assert.equal(r.f.incomplete, 'saw 1 of 3001 changed files'); +}); +test('check provenance includes current-attempt job membership', async () => { + const m = mock(); const r = await facts(m.api, repo, 12, spec); + assert.equal(r.f.checkRuns[0].workflowPath, '.github/workflows/ci.yml'); assert.equal(r.f.checkRuns[0].runAttempt, 2); assert.equal(m.jobReads(), 1); +}); +test('older attempts are excluded using the current attempt job API', async () => { + const m = mock({ jobs: [] }); const r = await facts(m.api, repo, 12, spec); assert.equal(r.f.checkRuns[0].superseded, true); +}); +test('run metadata from a stale head is untrusted', async () => { + const m = mock({ runHead: 'b'.repeat(40) }); const r = await facts(m.api, repo, 12, spec); assert.equal(r.f.checkRuns[0].workflowPath, undefined); +}); +test('GraphQL errors with partial data fail closed', async () => { + const m = mock({ threads: { ...threads, errors: [{ message: 'partial result' }] } }); await assert.rejects(main(env, m.api), /unreadable/); assert.equal(m.writes.length, 0); +}); +test('unreadable thread state and repeated cursors fail closed', async () => { + await assert.rejects(unresolvedThreads(async () => ({}), 'x', 'y', 1), /unreadable/); + const data = { data: { repository: { pullRequest: { reviewThreads: { nodes: [], pageInfo: { hasNextPage: true, endCursor: 'same' } } } } } }; + await assert.rejects(unresolvedThreads(async () => data, 'x', 'y', 1), /did not advance/); +}); +test('pagination reads every page and rejects truncated or malformed responses', async () => { + let calls = 0; const result = await all(async () => ++calls === 1 ? Array(100).fill({}) : [{ last: true }], '/test'); assert.equal(result.length, 101); assert.equal(calls, 2); + await assert.rejects(all(async () => ({}), '/test'), /invalid paginated/); + await assert.rejects(all(async () => Array(100).fill({}), '/test'), /exceeded 5,000/); +}); +test('invalid PR numbers cannot inject shell, path or extra API requests', async () => { + for (const PR_NUMBER of ['12/merge', '12;echo hi', '-1', '1e2', '0']) assert.equal(await main({ ...env, PR_NUMBER }, () => { throw new Error('must not be called'); }), 0); +}); +test('GET retries are bounded; API denial does not retry or print response bodies', async () => { + let calls = 0; const client = createClient('fixture', async (_, init) => { assert.ok(init.signal); calls++; return { ok: false, status: 503 }; }, async () => {}); + await assert.rejects(client('/test'), /HTTP 503/); assert.equal(calls, 3); + calls = 0; const denied = createClient('fixture', async () => { calls++; return { ok: false, status: 403, text: () => { throw new Error('private body'); } }; }); + await assert.rejects(denied('/test'), /HTTP 403/); assert.equal(calls, 1); +}); +test('uncertain writes are never retried', async () => { + let calls = 0; const client = createClient('fixture', async () => { calls++; return { ok: false, status: 503 }; }); + await assert.rejects(client('/comments', { method: 'POST' }), /HTTP 503/); assert.equal(calls, 1); +}); +test('malicious check details URLs are not fetched', async () => { + const m = mock({ checks: [{ id: 99, name: 'release aggregate', app: { id: 15368 }, details_url: 'https://evil.invalid/actions/runs/77' }] }); + const r = await facts(m.api, repo, 12, spec); assert.equal(r.f.checkRuns[0].workflowPath, undefined); assert.equal(m.jobReads(), 0); +}); diff --git a/pr-gate/workflow.test.mjs b/pr-gate/workflow.test.mjs new file mode 100644 index 0000000..7c08c45 --- /dev/null +++ b/pr-gate/workflow.test.mjs @@ -0,0 +1,60 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs'; +import { spawnSync } from 'node:child_process'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { resolvePrNumber } from './run.mjs'; +const head = 'a'.repeat(40), repo = 'frankxai/example'; + +async function fixture(fn) { + const dir = mkdtempSync(join(tmpdir(), 'pr-gate-relay-')); + const path = join(dir, 'event.json'); + writeFileSync(path, JSON.stringify({ workflow_run: { id: 10, display_title: '999', pull_requests: [] } })); + const env = { GITHUB_EVENT_NAME: 'workflow_run', GITHUB_EVENT_PATH: path, GITHUB_REPOSITORY: repo, PR_NUMBER: '999' }; + try { await fn(env); } finally { rmSync(dir, { recursive: true, force: true }); } +} +function relay(over = {}, prs) { + return async path => { + if (path.endsWith('/actions/runs/10')) return { path: '.github/workflows/ci.yml', event: 'pull_request', head_sha: head, repository: { full_name: repo }, head_repository: { full_name: 'outside/fork' }, ...over }; + if (path.includes('/commits/')) return prs ?? [{ number: 12, state: 'open', head: { sha: head, repo: { full_name: 'outside/fork' } }, base: { repo: { full_name: repo } } }]; + throw new Error('untrusted title caused a request: '+path); + }; +} +test('fork CI completion resolves PR by API head and never uses a numeric title', () => fixture(async env => assert.equal(await resolvePrNumber(env, relay()), 12))); +test('stale completion does not select another PR', () => fixture(async env => assert.equal(await resolvePrNumber(env, relay({}, [])), null))); +test('untrusted workflow path is refused', () => fixture(env => assert.rejects(resolvePrNumber(env, relay({ path: '.github/workflows/fake.yml' })), /untrusted/))); +test('untrusted repository is refused', () => fixture(env => assert.rejects(resolvePrNumber(env, relay({ repository: { full_name: 'outside/fork' } })), /untrusted/))); +test('ambiguous current heads fail closed', () => fixture(env => { + const pr = { number: 12, state: 'open', head: { sha: head, repo: { full_name: 'outside/fork' } }, base: { repo: { full_name: repo } } }; + return assert.rejects(resolvePrNumber(env, relay({}, [pr, { ...pr, number: 13 }])), /multiple/); +})); +test('caller cannot use a PR title for routing or concurrency', () => { + const caller = readFileSync(new URL('./caller.yml', import.meta.url), 'utf8'); + assert.doesNotMatch(caller, /display_title/); assert.doesNotMatch(caller, /^concurrency:/m); +}); +const workflow = readFileSync(new URL('../.github/workflows/pr-gate.yml', import.meta.url), 'utf8'); +const validator = workflow.split('// source-ref-validator:start')[1].split('// source-ref-validator:end')[0]; +for (const [label, vars, status] of [ + ['same immutable reusable/code source', { GATE_REF: head, JOB_WORKFLOW_SHA: head, JOB_WORKFLOW_REPOSITORY: 'Starlight-Intelligence/.github' }, 0], + ['mismatched reusable/code source', { GATE_REF: head, JOB_WORKFLOW_SHA: 'b'.repeat(40), JOB_WORKFLOW_REPOSITORY: 'Starlight-Intelligence/.github' }, 1], + ['mutable ref', { GATE_REF: 'main', JOB_WORKFLOW_SHA: head, JOB_WORKFLOW_REPOSITORY: 'Starlight-Intelligence/.github' }, 1], + ['wrong reusable repository', { GATE_REF: head, JOB_WORKFLOW_SHA: head, JOB_WORKFLOW_REPOSITORY: 'outside/fork' }, 1], + ['missing runtime provenance', { GATE_REF: head }, 1], + ['case-insensitive GitHub repository identity', { GATE_REF: head, JOB_WORKFLOW_SHA: head, JOB_WORKFLOW_REPOSITORY: 'STARLIGHT-INTELLIGENCE/.github' }, 0], +]) test(`actual workflow validator: ${label}`, () => assert.equal(spawnSync(process.execPath, ['-e', validator], { env: vars }).status, status)); +test('main push completion is an explicit no-op', () => fixture(async env => assert.equal(await resolvePrNumber(env, relay({ event: 'push' })), null))); +test('resolved event types serialize under the same PR without cancellation', () => { + const decide = workflow.split('\n decide:')[1]; + assert.match(decide, /needs: resolve-pr/); + assert.match(decide, /if: needs\.resolve-pr\.outputs\.pr-number != ''/); + assert.match(decide, /\n concurrency:\n group: starlight-pr-gate-\$\{\{ github.repository \}\}-\$\{\{ needs.resolve-pr.outputs.pr-number \}\}\n cancel-in-progress: false/); + assert.match(decide, /PR_GATE_EVENT_RESOLVED: 'true'/); +}); +test('locked report uses the resolved PR and never resolves a different PR again', () => fixture(async env => assert.equal(await resolvePrNumber({ ...env, PR_NUMBER: '12', PR_GATE_EVENT_RESOLVED: 'true' }, () => { throw new Error('must not query another PR'); }), 12))); +test('privileged action pins and checkout ref stay bound to the validated input', () => { + const uses = [...workflow.matchAll(/uses: actions\/[\w-]+@([^\s]+)/g)].map(x => x[1]); + assert.ok(uses.length > 0); for (const ref of uses) assert.match(ref, /^[a-f0-9]{40}$/); + const checkouts = workflow.split(/- (?:name: Load the gate\n )?uses: actions\/checkout@/).slice(1); + for (const checkout of checkouts) assert.match(checkout.split(/\n - /)[0], /ref: \$\{\{ inputs.gate-ref \}\}/); +});