diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..d48c220 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,14 @@ +# Keeps every pinned `uses:` (action.yml and .github/workflows, each pinned to a +# commit SHA with its version in a `# vX.Y.Z` comment) current: Dependabot +# reads the comment, finds the newer release and opens a PR that bumps the SHA +# and the comment together — the update arrives as a reviewable diff instead of +# a tag that moved underneath us. +version: 2 +updates: + - package-ecosystem: github-actions + directory: / + schedule: + interval: weekly + groups: + actions: + patterns: ["*"] diff --git a/.github/workflows/deprecate.yml b/.github/workflows/deprecate.yml index 051669e..d8370ca 100644 --- a/.github/workflows/deprecate.yml +++ b/.github/workflows/deprecate.yml @@ -50,9 +50,9 @@ jobs: VERSIONS: ${{ inputs.versions }} MESSAGE: ${{ inputs.message }} steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: "20" registry-url: "https://registry.npmjs.org" diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 482d135..590af59 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -17,10 +17,9 @@ # closed if any of it is off. # # NOTE: this workflow deliberately creates no git tags. The npm package version -# and the action's own `v1.x` release tags are SEPARATE version lines (the -# action is on v1.4.x while the CLI starts at 1.0.0). Tagging `v1.0.0` here -# would collide with the action's tag series and could move consumers' -# `uses: ...@v1` onto the wrong commit. Action tags stay manual — see RELEASE.md. +# and the action's own `v1.x` release tags are SEPARATE version lines, and +# action release tags are created by hand, once, and never moved — see +# RELEASE.md. name: Publish @@ -42,11 +41,11 @@ jobs: contents: read id-token: write # provenance attestation; not used for auth steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 with: - fetch-depth: 0 # the v1 tag check below needs the tag objects + fetch-depth: 0 # the pinned-commit check below needs ACTION_SHA's commit and its ACTION_VERSION tag - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: "20" registry-url: "https://registry.npmjs.org" @@ -90,29 +89,39 @@ jobs: exit 1 fi - # The installers generate a workflow pinned to `@v1`. If that tag predates - # scripts/settings.mjs and scripts/report.mjs, every new user gets working - # reviews with a silently inert Settings tab and empty Analytics — no - # error, just two dead console tabs. Refuse to ship an installer into that. - - name: Verify the v1 tag can serve what the installer generates + # The installers generate a workflow pinned to ACTION_SHA (with + # ACTION_VERSION in a comment) — never to a movable tag. Refuse to ship an + # installer that pins a commit which is not a tagged release, or which + # predates scripts/settings.mjs and scripts/report.mjs (every new user + # would get working reviews with a silently inert Settings tab and empty + # Analytics). + - name: Verify the pinned action commit can serve what the installer generates if: steps.check.outputs.needed == 'true' run: | set -euo pipefail - if ! git rev-parse -q --verify refs/tags/v1 >/dev/null; then - echo "::error::No v1 tag. The generated workflow pins @v1 — see RELEASE.md." + SHA=$(node --input-type=module -e 'const m = await import("./bin/orcacode-review.mjs"); console.log(m.ACTION_SHA)') + VER=$(node --input-type=module -e 'const m = await import("./bin/orcacode-review.mjs"); console.log(m.ACTION_VERSION)') + if ! git cat-file -e "$SHA^{commit}" 2>/dev/null; then + echo "::error::ACTION_SHA $SHA is not a commit in this repository — see RELEASE.md." + exit 1 + fi + if [ "$(git rev-parse -q --verify "refs/tags/$VER^{commit}" || true)" != "$SHA" ]; then + echo "::error::ACTION_SHA $SHA is not the commit tagged $VER — tag the release first (RELEASE.md)." exit 1 fi for f in scripts/settings.mjs scripts/report.mjs; do - if ! git cat-file -e "v1:$f" 2>/dev/null; then - echo "::error::v1 is missing $f. Move the v1 tag before publishing (RELEASE.md)." + if ! git cat-file -e "$SHA:$f" 2>/dev/null; then + echo "::error::the pinned commit $SHA is missing $f (RELEASE.md)." exit 1 fi done - echo "v1 = $(git rev-parse --short v1), ships settings.mjs and report.mjs" + echo "installer pins $VER = $SHA, which ships settings.mjs and report.mjs" - name: Test if: steps.check.outputs.needed == 'true' - run: node --test scripts/*.test.mjs + run: | + npm ci --ignore-scripts --no-audit --no-fund + node --test scripts/*.test.mjs # A tarball that omits bin/ or skills/ still publishes cleanly and then # fails on the user's first `npx`. Assert the payload before shipping it. @@ -150,6 +159,18 @@ jobs: console.log("tarball ok — " + files.length + " files"); ' + # WHAT THE TARBALL SAYS ABOUT THE ACTION MUST BE TRUE OF THE PINNED RELEASE. + # The installer and the skill hand out ACTION_SHA; a README or skill page + # that names a newer action version (other than as the "from v1.x.y + # (unreleased)" marker the test suite holds unreleased behaviour to) would + # tell every npm user about behaviour their workflow does not have. + - name: Verify the published docs name no action version newer than the pin + if: steps.check.outputs.needed == 'true' + run: | + set -euo pipefail + npm pack --dry-run --json > "$RUNNER_TEMP/pack-docs.json" + node scripts/doc-pins.mjs --pack "$RUNNER_TEMP/pack-docs.json" + # Install the real tarball and run it through npm's real `.bin` shim. # # This exists because 1.0.0 shipped a CLI that did nothing. npm installs a diff --git a/.github/workflows/self-review.yml b/.github/workflows/self-review.yml index bb18c80..94cf452 100644 --- a/.github/workflows/self-review.yml +++ b/.github/workflows/self-review.yml @@ -45,7 +45,7 @@ jobs: # Required so the local `uses: ./` action definition is present in the # workspace. On pull_request, the default checkout is the PR merge ref, so # `./` resolves to the action code being changed by the PR. - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - uses: ./ with: orcarouter-api-key: ${{ secrets.ORCAROUTER_API_KEY }} diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fcc164f..df47121 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -29,12 +29,19 @@ jobs: matrix: node-version: ["20", "24"] steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: node-version: ${{ matrix.node-version }} + # Dev-only, exact-pinned: the YAML parser the structural tests read + # action.yml and the shipped workflows with, and the CommonMark + GFM + # renderer (micromark) the sanitizer is judged by. The action itself never + # installs them. `npm ci` installs exactly the lockfile (with its integrity + # hashes) and --ignore-scripts runs no install hook. + - run: npm ci --ignore-scripts --no-audit --no-fund + # Unquoted on purpose: the shell expands the glob into an explicit file # list. `node --test` only gained native glob support in Node 21, so a # quoted pattern would be read as a literal filename on the Node 20 leg. diff --git a/README.md b/README.md index 12b5de3..ec37acb 100644 --- a/README.md +++ b/README.md @@ -140,14 +140,47 @@ Configure your models, review mode, severity rules, merge policy, and other sett [**Install OrcaCode Review from GitHub Marketplace →**](https://github.com/marketplace/actions/orca-code-review) -Add the Action to your repository: +Add this workflow as `.github/workflows/orca-code-review.yml` (or let `npx @orcarouter/code-review` write it). Use the whole file, not just the `uses:` step: the job's `if:` is what keeps the paid `/orcacode-review` command to maintainers, and the concurrency block is what stops any commenter from cancelling a running review. The action also refuses an outsider's command on its own, but the workflow is the first gate. ```yaml -- uses: Continuum-AI-Corp/orca-code-review@v1 - with: - orcarouter-api-key: ${{ secrets.ORCAROUTER_API_KEY }} +name: OrcaCode Review + +on: + pull_request_target: + types: [opened, synchronize, reopened, ready_for_review, edited] + issue_comment: + types: [created] + +permissions: + contents: read + pull-requests: write + issues: write + statuses: write # used from v1.7.0 (unreleased): the verdict on the PR head + +jobs: + review: + runs-on: ubuntu-latest + concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'issue_comment' && 'comment' || 'pr' }}-${{ github.event.pull_request.number || github.event.issue.number }} + cancel-in-progress: ${{ github.event_name != 'issue_comment' }} + if: | + (github.event_name == 'pull_request_target' && + (github.event.action != 'edited' || github.event.changes.base)) || + (github.event_name == 'issue_comment' && + github.event.issue.pull_request && + (startsWith(github.event.comment.body, '/orcacode-review') || + startsWith(github.event.comment.body, '/orcacode review') || + startsWith(github.event.comment.body, '@orcacode-review') || + startsWith(github.event.comment.body, '@orcacode review')) && + contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association)) + steps: + - uses: Continuum-AI-Corp/orca-code-review@6d253e0399c84848fedc8801176d6bea77817762 # v1.6.0 + with: + orcarouter-api-key: ${{ secrets.ORCAROUTER_API_KEY }} ``` +The action is pinned to a release **commit**, with its version in the comment, rather than to a tag that can be moved: enable Dependabot's `github-actions` updates and each new release arrives as a reviewable PR. The full example, with every optional input, is [`workflows/orca-code-review.yml`](workflows/orca-code-review.yml). + ### 3. Add your API key Create or copy a key from [**OrcaRouter → API Keys**](https://www.orcarouter.ai/console/token). @@ -216,7 +249,9 @@ Comment on any PR: /orcacode-review ``` -to request another review. +to request another review. Only an **owner, member or collaborator** can: the workflow's `if:` ignores the command from anyone else. + +From v1.7.0 (unreleased) the action itself ignores an outsider's command too, whatever the workflow says, and the verdict lands on the PR's head commit as the `OrcaCode Review` status. On a PR **from a fork**, name the commit you looked at — `/orcacode-review `, at least 7 characters of it: the action reviews exactly that commit, and only while it is still the PR's head, so the fork cannot push something else in between. A bare command there, or a commit that is no longer the head, gets a reply with the current head and the command to use. Same-repository PRs keep the bare command. --- @@ -226,13 +261,41 @@ To make P0/P1 findings actually prevent merging: **GitHub → Settings → Branches / Rulesets → Require status checks to pass** -Add the **`review`** check as required. +Add the **`review`** check (the workflow's job) as required. An oversized diff fails it by default (`on-oversized-diff: "pass"` makes that advisory); a skipped review — on-demand mode, auto-review off, a draft, an author outside `auto-review-authors` — passes it with a notice on the PR. + +From v1.7.0 (unreleased), the action also writes an **`OrcaCode Review`** commit status on the PR's head commit at the end of every run (grant `statuses: write`). It is green only when a review actually ran on that commit and the gate passed; a skipped review reads **"Not reviewed: …"**. Require that status instead of the `review` job once your workflow pins the release that writes it: it is the only check an on-demand `/orcacode-review` run can update on the PR (GitHub reports that run's own job check on the default branch), and it keeps an unreviewed PR from merging while the job stays green. `on-skipped-review: "fail"` fails the job on a skip too. + +--- + +## Upgrading: what changes from v1.7.0 (unreleased) + +Security hardening that changes what you may see. The installer, the example workflow and the quickstart above still pin **v1.6.0**, so none of this applies until you pin the release that ships it. Inputs are unchanged except for three new ones; defaults that close a hole are new. + +| What changed | What you will notice | To keep the old behaviour | +| --- | --- | --- | +| `auto-review-authors` unset on a **public** repo now means `OWNER,MEMBER,COLLABORATOR` (private repos: everyone, as before) | Fork PRs from outsiders are no longer auto-reviewed on your wallet; a maintainer can `/orcacode-review` them | `auto-review-authors: "OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR,FIRST_TIME_CONTRIBUTOR,FIRST_TIMER,MANNEQUIN,NONE"` (`"*"` works too from v1.7.0 (unreleased), but v1.6.0 reads it as nobody) | +| New `status-context` (default `"OrcaCode Review"`) | A commit status on the PR head after every run, on-demand runs included: green only for a reviewed head whose gate passed; a skipped review is **"Not reviewed"**. Grant `statuses: write`; require this status instead of the `review` job | `status-context: ""` | +| New `on-skipped-review` (default `"pass"`) | Nothing, by default: a skipped review still passes the job. `"fail"` fails the job on a skip too | — | +| New `bot-login` (default `""`) | Only for a custom GitHub App token: name its login (`"my-app[bot]"`) so the action recognises its earlier notices and edits them instead of posting new ones | — | +| Comment commands are checked by the action | `/orcacode-review` from anyone but an owner, member or collaborator, or any other comment, is a no-op | — | +| The pusher is checked, not only the author | A push to a fork PR by someone other than its author, who cannot write to your repository, is not auto-reviewed (the status says "Not reviewed"); a maintainer can `/orcacode-review` it | `auto-review-authors: "*"` | +| An allowlist of events | The action runs only on `pull_request` / `pull_request_target` (opened, synchronize, reopened, ready_for_review, a retargeting edit) and `issue_comment` (created); anything else — `pull_request_review`, `pull_request_review_comment`, a push — is a no-op that says why | — | +| A settings fetch that gets no settings — a 4xx (an ordinary, non-CI key gets one on every run) or an outage | The workflow's inputs apply for that run, exactly as with `settings: "false"`, and the log names the cause. `block-on` in the workflow is the outage floor: set it to what the dashboard enforces if an outage must not loosen the gate | — | +| The gate fails closed | A result the gate cannot read now fails the check instead of passing | — | +| `engine-version` must be pinned | Only versions with checksums in `scripts/engine-pins.json` install; anything else fails the run | — | +| `orcarouter-url` must be https | A plain-http gateway URL fails the run at its first step, with an error naming `orcarouter-url` and the fix (put TLS in front of a self-hosted gateway). Plain http stays allowed to this machine — `localhost`, `127.0.0.0/8`, `[::1]`. The settings fetch and the run report no longer send the key over plain http either | — | +| What is posted is sanitised | @mentions don't ping, HTML is shown as text, off-site links are shown as code, at most 50 findings are posted per review, guardrail details are hidden on public repos | — | +| The checkout is hardened | Symlinks are removed, the PR's `.gitattributes` cannot hide the diff, the base `.gitignore` applies; the summary lists changed files the engine skips. Lockfiles (`package-lock.json`, `yarn.lock`, `pnpm-lock.yaml`, `bun.lockb`, `go.sum`, `Cargo.lock`, `poetry.lock`, `composer.lock`, `Gemfile.lock`, by file name) are not counted toward `max-diff-kb` / `max-diff-files`, so a dependency bump does not skip a PR; the summary lists them | — | +| Severity is never lowered | Duplicates keep the most severe tag; the judge cannot drop a P0 or a security finding | — | +| Shipped workflows | Per-job concurrency (a comment cannot cancel a running review; a newer comment replaces only a comment run still pending), re-run on `reopened` and on a retargeted base (`edited`), `statuses: write`, the action pinned to a commit SHA | Update your copy from [`workflows/orca-code-review.yml`](workflows/orca-code-review.yml) | + +Self-hosted runners need git 2.31 or newer for private-repository fetches (the token travels in `GIT_CONFIG_*` environment variables, not on git's command line). --- ## Security & Privacy -OrcaCode reads the PR diff and repository files required for review. **It does not execute PR code.** +OrcaCode reads the PR diff and repository files required for review. **It does not execute PR code.** From v1.7.0 (unreleased), **the review engine never holds your API key** — an in-job proxy adds it on the way to OrcaRouter — and everything posted to the PR is sanitised and has your key and token redacted. Optional run reporting sends only review metadata — repository, PR, commit SHA, tier, severity counts, gate result, and engine version. diff --git a/RELEASE.md b/RELEASE.md index 77f046f..6a5727b 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,51 +1,106 @@ # Releasing -## The `@v1` tag must track the endpoints it depends on - -The setup-generated workflow and the README quickstart pin -`uses: Continuum-AI-Corp/orca-code-review@v1`. The `settings`, `report`, -`on-oversized-diff`, `auto-review-authors`, and diff-guard features depend on -gateway control-plane endpoints (`/api/code_review/settings`, -`/api/code_review/report`) **and** on the `scripts/settings.mjs` / -`scripts/report.mjs` this action ships. - -**Release order matters.** If `@v1` points at a commit that predates these -scripts, a user who follows the quickstart gets working reviews but a -silently inert Settings tab (settings never fetched) and empty Analytics -(runs never reported) — no error, just two dead console tabs. - -When cutting a release from a merged feature branch: - -1. Merge the feature branch to `main` (the branch that includes - `scripts/settings.mjs`, `scripts/report.mjs`, and the current - `action.yml`). -2. Deploy the gateway (OrcaRouter-O2) so the control-plane endpoints are live. -3. Tag the merged commit and **move the floating `v1` tag to it**: +## Release tags + +Whatever commit a tag points at runs, with the customer's OrcaRouter key, in +every repository that references the tag. A tag that can be re-pointed is a way +to run new code in every customer's CI without a single customer-side change. +So: + +- **`v1..` tags are immutable.** A release is a new tag on a merged + commit of `main`, created once and never moved, re-created or deleted. A bad + release is fixed by the next one, never by re-pointing the old tag. +- **The floating `v1` major MAY be advanced — only by the release step below.** + It moves forward to the commit of the release just tagged, by an administrator + through the ruleset's administrator-only bypass, as a fast-forward-only ref + update: GitHub refuses a `force=false` update unless the new commit descends + from the old one, so `v1` can never be pointed sideways or back. Nothing else + ever moves it. +- **Customers should pin a full commit SHA with the version in a comment** + (`uses: Continuum-AI-Corp/orca-code-review@ # v1.x.y`), not `@v1`. + That is what we hand out: the installer (`ACTION_SHA` / `ACTION_VERSION` in + `bin/orcacode-review.mjs`), the example workflow + (`workflows/orca-code-review.yml`), the skill's asset + (`skills/orca-review-action/assets/workflow.yml`) and the README quickstart. + `scripts/release-pin.test.mjs` fails if any of the four diverges from the + installer's constants. Customers' Dependabot (`package-ecosystem: + github-actions`) reads the `# v1.x.y` comment and offers each release as a pull + request that changes the SHA and the comment together. + +### Docs say what the pinned release does + +`main` runs ahead of the pin, so its docs can describe behaviour no customer has +yet. Every doc line about such behaviour carries `from v1. (unreleased)` +(`MARKER` in `scripts/doc-pins.mjs`), and `scripts/pinned-release.test.mjs` holds +README, SECURITY.md, the skill and the shipped workflows to that: its terms are +every input `action.yml` has that the pinned release does not, plus the listed +behaviours. A value the installer or the skill writes into a workflow must mean +the same to the pinned release as to `main` (the test runs it through both +releases' gates). The publish workflow refuses a tarball whose docs name an +action version newer than the pin anywhere but in that marker. + +### Cutting a release + +1. Merge to `main`. The gateway control-plane endpoints the action calls + (`/api/code_review/settings`, `/api/code_review/report`) must already be live + for the version you are releasing — deploy OrcaRouter-O2 first. +2. Create the release tag on the merged commit and push **only that new tag**: ``` - git tag -f v1. # immutable release - git tag -f v1 # floating major that the workflow pins - git push --force origin v1 v1. + git tag -a v1..

-m "v1..

" + git push origin refs/tags/v1..

``` -4. Verify: `git ls-tree v1 scripts/` lists `settings.mjs` and `report.mjs`, - and `git show v1:action.yml` contains the "Fetch review settings" and + Publish a GitHub Release for it; with immutable releases enabled (below) the + tag and its assets are locked from then on. +3. Advance the floating major to the same commit — an administrator, through the + ruleset bypass, fast-forward only: + ``` + gh api -X PATCH repos/Continuum-AI-Corp/orca-code-review/git/refs/tags/v1 -f sha= -F force=false + ``` + A refusal ("Update is not a fast forward") means `` does not + descend from the current `v1`: stop and find out why; never force it. +4. In a follow-up PR, bump the pin and the docs together: + - `ACTION_SHA` / `ACTION_VERSION` in `bin/orcacode-review.mjs`, and the same + `uses:` line in `workflows/orca-code-review.yml`, + `skills/orca-review-action/assets/workflow.yml` and the README quickstart + (the suite fails until all four agree); + - `PINNED` in `scripts/pinned-release.test.mjs` to the new release (its + inputs and allowlist gate; the suite fails until it matches); + - every `from v1. (unreleased)` marker the release made true: drop the + marker and the "v1.6.0 does otherwise" text beside it, then set + `UNRELEASED` in `scripts/doc-pins.mjs` to the next version (the suite + refuses a marker for a version the pin has reached). + Bump `package.json` in the same PR when the installer should ship it (see + Installers below). +5. Verify: `git ls-tree scripts/` lists `settings.mjs` and `report.mjs`, and + `git show :action.yml` contains the "Fetch review settings" and "Report run" steps. -Until the tag is moved, do not advertise the new inputs under `@v1`. For -pre-release dogfooding, pin an immutable commit SHA (as OrcaRouter-O2's own -`.github/workflows/orca-code-review.yml` does) rather than `@v1`. +### Repository settings (administrator, one-time) + +These are settings, not code, so no commit can turn them on. Until an +administrator does, the rules above are a convention only: + +- **Tag ruleset** (Settings → Rules → Rulesets → New tag ruleset), targeting + `v*`: restrict updates, restrict deletions, block force pushes; no bypass for + `v*.*.*`, and an administrator-only bypass on `v1` for step 3. +- **Immutable releases** (Settings → General → Releases → "Enable release + immutability"), so a published release's tag and assets cannot be changed. +- **Dependabot** for this repository's own pinned actions is configured in + `.github/dependabot.yml`. ## Marketplace -Publish/refresh the GitHub Marketplace listing from the same merged commit as -a verified publisher; the listing's default install snippet must match the -README quickstart (including `@v1` once moved). +Publish/refresh the GitHub Marketplace listing from a release tag's commit as a +verified publisher; the listing's install snippet must match the README +quickstart, pinned SHA included. ## Installers Two one-command installers ship from this repo, and both generate a workflow -that pins `@v1`. **Release them only after the `v1` tag has been moved** — an -installer that writes `@v1` against a stale tag hands every new user the dead -Settings/Analytics tabs described above, on their very first run. +pinned to `ACTION_SHA`. **Release them only after that commit carries a release +tag** — the publish workflow refuses otherwise, and checks that the pinned +commit ships `scripts/settings.mjs` and `scripts/report.mjs` (an older commit +would hand every new user dead Settings/Analytics tabs on their first run). ### npm — `npx @orcarouter/code-review` @@ -133,8 +188,8 @@ Five gates run before the point of no return, and each one fails the job: 1. `package.json`, `.claude-plugin/plugin.json`, and `.claude-plugin/marketplace.json` all carry the same version. -2. The `v1` tag exists and ships `scripts/settings.mjs` + `scripts/report.mjs`, - because the installer generates a workflow pinned to `@v1`. +2. The commit the installer pins (`ACTION_SHA`) exists, is tagged + `ACTION_VERSION`, and ships `scripts/settings.mjs` + `scripts/report.mjs`. 3. The full test suite passes. 4. The tarball actually contains `bin/` and the skill — a tarball missing them publishes cleanly and only fails on the user's first `npx`. @@ -202,10 +257,9 @@ to this one package**, not a classic automation token — a leaked classic token can publish anything in the account. Rotate with `gh secret set NPM_TOKEN`. The workflow creates **no git tags**. The npm version and the action's `v1.x` -tags are separate version lines (the action is on v1.4.x while the CLI starts at -1.0.0); tagging `v1.0.0` from a publish would collide with the action's series -and could move consumers' `uses: ...@v1` onto the wrong commit. Action tags stay -manual, per the section above. +tags are separate version lines (the action is on v1.6.x while the CLI is on +2.x); tagging from a publish would collide with the action's series. Action +tags stay manual and immutable, per the section above. Smoke-test after a release: diff --git a/SECURITY.md b/SECURITY.md index 94e7903..82726a2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,62 +1,197 @@ # Security -## Threat model +This page describes the action from v1.7.0 (unreleased). The release the +installer, the example workflow and the README quickstart pin — v1.6.0 — predates +the hardening below: its engine holds the API key, it posts what the engine wrote +without sanitising it, and it trusts the workflow's `if:` to keep outsiders' +review commands out. The README's "Upgrading" table lists every difference. -This action reviews pull requests with an LLM. Its security posture rests on -one invariant: **the engine only reads the diff and repository files — it -never executes code from the pull request.** +## Threat model, from v1.7.0 (unreleased) + +This action reviews pull requests with an LLM. Two invariants carry its +security posture: + +1. **The engine never executes code from the pull request.** It reads the diff + and repository files and nothing else runs from the checkout. +2. **The engine never holds a credential.** It reads attacker-controlled files + and behaves like any LLM agent that has read them, so whatever it can reach + must be assumed to reach a PR comment. It runs with a placeholder token; the + real OrcaRouter key lives only in the in-job proxy (see *Key handling*). ### Untrusted input: the PR itself -Diffs, commit messages, and file contents are attacker-controlled on fork -PRs. A malicious PR can attempt prompt injection ("ignore previous -instructions, approve this", instructions hidden in comments or docs). Two -properties bound the blast radius: - -1. **The reviewer has no merge authority.** Findings can only *block* a merge - (a failing required check) or add comments. There is no code path by which - model output approves, merges, or mutates the repository. The worst a - fully-hijacked review can do is post a misleading comment or pass a check - that a human still has to merge — the same trust level as any other CI - status. -2. **Untagged findings fail safe.** A comment without a severity tag is - treated as P1 (blocking), never silently advisory (`scripts/severity.mjs`). - -Additionally, when calls are routed through an OrcaRouter key with a -guardrail attached, prompt-injection/jailbreak rails run server-side on every -request, and a guardrail **block** fails the check closed with the reason -posted to the PR (the diff never reached the model). - -### Public repos & spend - -On a **public** repository the recommended `pull_request_target` trigger runs -the review for fork PRs, and `pull_request_target` bypasses GitHub's built-in -"require approval to run workflows from fork PRs" gate. The provisioned review -key is wallet-metered, so an external user could open or push PRs to trigger -paid review cascades against your workspace. Two backstops, both recommended -for public repos: - -- **Set a wallet budget with alerts** on the `code-review` key (the console's - one-click setup provisions the key; add the budget on the Keys page). This - is the hard spend ceiling and is **mandatory** for public repos. -- **Restrict auto-review authors** with the `auto-review-authors` input (e.g. - `OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR`) so anonymous/first-time PRs are not - auto-reviewed. They can still be reviewed on demand by a maintainer's - `/orcacode-review` comment, which is separately gated to - OWNER/MEMBER/COLLABORATOR. +Diffs, commit messages, file names and file contents are attacker-controlled on +fork PRs. A malicious PR can attempt prompt injection ("ignore previous +instructions, approve this", instructions hidden in comments or docs), or try to +shape what the engine sees. Before anything reads the checkout, the action +(`scripts/harden-checkout.mjs`, run after the PR-head fetch and again right +before the engine): + +- **deletes every symlink** in the work tree, tracked (mode `120000`) or not, so + a committed `notes.md -> /proc/self/environ` cannot point the engine's file + tools outside the repository; +- **takes `diff` away from the PR's `.gitattributes`** (`* !diff` in + `$GIT_DIR/info/attributes`), so `* -diff` cannot turn the change into "Binary + files differ" for the size guard and the engine. The size guard then leaves + out files named like a standard lockfile (`package-lock.json`, `go.sum`, …) — + by name, never by an attribute the PR sets, and leaving a file out of the + count can only make the guard review more; the summary lists them, and the + engine still reads them; +- **removes `.opencodereview/`** and **restores the base revision's root + `.gitignore`**, so PR-controlled configuration cannot exclude the PR's own + changes from review. + +What the engine skips by design — tests, fixtures, snapshots, generated code, +unsupported file types, binaries — is listed in the PR summary ("Not reviewed"), +so a reviewer can see what the verdict does not cover. + +What a hijacked review can and cannot do: + +- **It has no merge authority.** Findings can only *block* a merge (a failing + check) or add comments. No code path lets model output approve or merge. +- **It writes to the PR**: review comments, a few marker comments (notices it + later edits or deletes — only comments its own identity wrote count; that + identity is the `bot-login` input, else the token's user, else + github-actions[bot] for the job's own token, else learned from the action's + first post in the run — never assumed), a + commit status on the head SHA, and a **summary region inside the PR + description**, which the action rewrites on every run (the author's own text + outside the marked region is preserved). +- **What it posts is sanitised** (`scripts/publish-guard.mjs`, used by every + posting step): @mentions are neutralised, HTML is escaped and HTML comments + removed (so a finding cannot forge the action's own markers), links other + than this repository and the OrcaRouter docs host are defanged, forged + headings are demoted, each finding is length-capped and at most 50 findings + are posted per review (the gate and the summary still count all of them). + File paths are shown only as inline code that cannot break out. +- **It cannot lower a severity or talk a blocker away.** Untagged findings count + as P1. Deduplication (L1 and the exhaustive merge) keeps the most severe tag + among duplicates, and the L2 judge may re-rank and annotate but cannot drop a + P0 or a security finding, nor demote one by clustering it under a lesser + representative. +- **It can still mislead.** A hijacked engine can omit findings or write + misleading ones; the precision filter and the judge are heuristics, not + proof. Treat the review as one reviewer, not as the merge decision. + +When calls are routed through an OrcaRouter key with a guardrail attached, +prompt-injection/jailbreak rails run server-side on every request, and a +guardrail **block** fails the check closed. On a **public** repository the PR +only gets a generic "blocked by a guardrail policy" notice — the policy's name +and the text it matched describe your workspace's security configuration and +are not published there (see the OrcaRouter dashboard); private repositories +get the sanitised detail. + +### Who can make the action spend + +On a **public** repository the recommended `pull_request_target` trigger runs the +review for fork PRs, and `pull_request_target` bypasses GitHub's "require +approval to run workflows from fork PRs" gate. The review key is wallet-metered. + +- **Events**: the action runs only on `pull_request` / `pull_request_target` + (`opened`, `synchronize`, `reopened`, `ready_for_review`, and `edited` when the + base changed) and `issue_comment` (`created`). Any other event a workflow + wires it to — `pull_request_review`, `pull_request_review_comment`, a push, a + label — exits successfully without a review and says why, so a reviewer's + comment cannot start a paid review of someone else's PR. +- **Automatic reviews**: when `auto-review-authors` is not set, a public + repository (or one whose visibility the event does not state) auto-reviews + only `OWNER`, `MEMBER` and `COLLABORATOR` authors; a private repository + reviews everyone. Set your own list, or `"*"` to review everyone on a public + repository deliberately. Everyone else is reviewed on demand. +- **Pushes to a fork PR**: `author_association` is the PR author's, not the + pusher's. On a `synchronize` whose head lives in another repository and was + pushed by someone other than the PR's author, the action asks GitHub whether + that pusher can write to this repository (write, maintain or admin) and + auto-reviews only if so — otherwise it is a skip, which the commit status + reports as "Not reviewed". Not asked when `auto-review-authors` lets everyone + through anyway (`"*"`, or unset on a private repository). +- **On-demand reviews** (`/orcacode-review`, `@orcacode review`, …): the action + itself refuses a comment-triggered run unless the comment is on a pull + request, is the review command, and its author is `OWNER`, `MEMBER` or + `COLLABORATOR` — whatever the workflow's `if:` says. The shipped workflows + gate the same way in their `if:`, which also saves the runner. On a PR whose + head lives in a fork, the command must name the commit + (`/orcacode-review `, 7+ hex characters): the action reviews exactly + that commit and only while it is still the head, so a fork cannot push + between the maintainer's reading and the review; otherwise it replies with + the current head and runs nothing. +- **Cancelling**: concurrency is per job in the shipped workflows, and comment + runs have their own group with `cancel-in-progress` off, so a comment cannot + cancel an in-flight review. GitHub keeps one running and one pending job per + group: a newer `/orcacode-review` replaces a comment run that is still + pending, never one that is running. +- **Set a wallet budget with alerts** on the review key. This is the hard spend + ceiling, and it is mandatory for public repositories. ### `pull_request_target` and secrets -The recommended workflow uses `pull_request_target` so `ORCAROUTER_API_KEY` -is available on fork PRs. This is safe **only because no PR code is -executed**: the action checks out the PR head solely as data for the engine -to read. Consumers MUST NOT add build, test, or install steps that execute -PR-controlled code to this workflow. If you need to run PR code, do it in a -separate `pull_request`-triggered workflow with no secrets. - -The comment trigger (`/orcacode-review`) is gated to -OWNER/MEMBER/COLLABORATOR in the shipped workflow so arbitrary commenters -cannot spend your quota. +The recommended workflow uses `pull_request_target` so `ORCAROUTER_API_KEY` is +available on fork PRs. This is safe **only because no PR code is executed**: the +action checks out the PR head solely as data. Consumers MUST NOT add build, +test, or install steps that execute PR-controlled code to this workflow. If you +need to run PR code, do it in a separate `pull_request`-triggered workflow with +no secrets. + +### The merge gate + +Make the **`OrcaCode Review`** commit status required (input `status-context`; +the workflow needs `statuses: write`). The action writes it on the PR's head SHA +at the end of every run, including on-demand runs, whose own job check GitHub +reports on the default branch. It is `success` only when a review ran on that +commit and the gate passed — or when you made an oversized-diff skip advisory +on purpose. +Failure modes are closed: + +- A **skipped** review (dashboard auto-review off, on-demand mode, a draft, an + author outside `auto-review-authors`) is a failing status, "Not reviewed", + whatever the job does (the job passes unless `on-skipped-review: "fail"`); + an **oversized** diff fails both unless `on-oversized-diff: "pass"`. +- If the gate cannot read the result (or crashes), the check fails. +- If the dashboard settings cannot be read (5xx, timeout, network), or the key + has none (a 4xx — what an ordinary, non-CI key gets), the run uses the + workflow's inputs exactly as with `settings: "false"`, and the log names the + cause. **The workflow's `block-on` is the outage floor**: an outage never + goes below it, and never above it either. If an outage must not loosen a + stricter dashboard policy, write that policy into the workflow's `block-on`. +- A missing judge (L2) fails the run rather than posting unjudged findings + (`precision-filter: "false"` is the supported way to run without one). +- Retargeting a PR to another base re-runs the review (shipped workflows + trigger on `edited` when the base changed, and on `reopened`). + +### Key handling + +- The key is a repository secret and reaches the action as an input. GitHub + masks it in logs. +- **The engine never receives it.** A step that runs nothing from the PR writes + the key to a `0600` file; the in-job proxy (`scripts/fact-proxy.mjs`) reads + and deletes that file before the engine starts, and injects + `Authorization: Bearer ` on the way to the gateway, replacing whatever + the client sent. The engine and the judge hold a placeholder. The proxy takes + the key from a file rather than its environment because a same-user process + can read `/proc//environ`. +- **The proxy forwards to one place only**: the configured endpoint's exact + path, on its exact origin, over https (plain http only to this machine: + `localhost`, `127.0.0.0/8`, `[::1]`). Absolute-form, scheme-relative and + backslash request targets are refused. The same judge + (`scripts/gateway-url.mjs`) is asked before the settings fetch and the run + report send the key, and by the first step that reads `orcarouter-url`, which + fails the run with an error naming the input and the fix. +- **Nothing the action posts can carry it.** Every posting call redacts the key + and the GitHub token — raw, base64 at any alignment, base64url, + URL-encoded, hex in either letter case, as the Basic-auth value, and split + by zero-width or other invisible characters. +- Helper scripts take the key from the environment, never from argv, so it + does not surface in `/proc//cmdline` or `ps`; the PR-head fetch passes + the GitHub token in `GIT_CONFIG_*` environment variables (git >= 2.31), not + on git's command line; and no `run:` script contains a `${{ }}` expression, + which GitHub would expand into the script file it writes to disk. +- Use a dedicated workspace key for review (the console's one-click setup + provisions one named `code-review`): attach a guardrail, set a monthly budget + with alerts, scope it to nothing else, rotate it from the Keys page. + +**Residual risk on self-hosted runners:** the proxy process holds the key in +memory for the job's duration, and anything running as the runner's user with +ptrace rights could read it. Prefer ephemeral runners for reviews. ### What leaves your repository @@ -64,29 +199,29 @@ cannot spend your quota. repository context the engine selects, as LLM requests. - **Run report-back (optional, `report: true` by default):** severity counts, repo name, PR number, head SHA, tier, gate result, engine version — sent to - your own gateway's control plane for the analytics dashboard. **No code, no - diff content, no findings text.** Disable with `report: false`. -- Nothing is sent to any third party other than the gateway you configure. - -### Key hygiene - -Use a dedicated workspace API key for review (the console's one-click setup -provisions one named `code-review` with `environment=ci`): attach a guardrail, -set a monthly budget with alerts, and scope it to nothing else. Rotate from -the Keys page; the key is a repository secret and never appears in logs or -comments. Internally the action passes it to its helper scripts through the -environment, never as a command-line argument, so it does not surface in -`/proc//cmdline` or `ps` output on shared/self-hosted runners. + your own gateway's control plane. **No code, no diff content, no finding + text.** Disable with `report: false`. +- Nothing is sent to any third party other than the gateway you configure; the + engine is downloaded from the npm registry and its GitHub release (below). ### Supply chain -- The review engine (`@alibaba-group/open-code-review`, Apache-2.0) is - **pinned** by exact version in `action.yml` (`engine-version` input); bumps - are deliberate and gated by contract tests on its JSON output shape. -- The action itself is a composite of auditable `.mjs` scripts in this - repository — no compiled artifacts, no postinstall hooks of its own. -- Pin your `uses:` reference to a tag (`@v1`) or commit SHA per your - organization's policy. +- **The review engine** (`@alibaba-group/open-code-review`, Apache-2.0) is an + npm wrapper plus a platform binary. Both are pinned per version in + `scripts/engine-pins.json`: the npm tarball by its sha512 integrity, each + binary by its sha256. `scripts/install-engine.mjs` verifies both before use, + installs the tarball with `--ignore-scripts` (its postinstall, which would + download the binary and check it only against a checksum file from the same + release, never runs) into a prefix under `$RUNNER_TEMP`, and refuses any + `engine-version` without pins. The engine's self-update is disabled. +- **Actions this action uses** are pinned to commit SHAs with their version in a + comment, and kept current by Dependabot. +- **This action** is a composite of auditable `.mjs` scripts in this repository — + no compiled artifacts, no install hooks of its own. Pin it to a **commit SHA** + (the installer, the example workflow and the README do, with the release + version in a comment for Dependabot). Release tags are created once and never + moved — see `RELEASE.md`; enforcing that with a tag ruleset and immutable + releases is a repository setting an administrator must turn on. ## Reporting a vulnerability diff --git a/action.yml b/action.yml index 1b15546..749c1d1 100644 --- a/action.yml +++ b/action.yml @@ -29,6 +29,22 @@ # pinned at the top, replaced in place on every push; and a best-effort per-tier run report # (scripts/report.mjs) posts severity counts — never code — to the OrcaRouter # control plane after the gate. +# +# Security posture (SECURITY.md has the detail): the action runs on an +# allowlist of events; a comment trigger runs only for a maintainer's review +# command, checked here and not only in the workflow, and on a fork PR only for +# the commit it names while that is still the head; a push to a fork PR is +# auto-reviewed only if its pusher (not just its author) passes; the action's +# own comments are recognised by one identity funnel (scripts/identity.mjs); +# the key goes in clear only to this machine (scripts/gateway-url.mjs); the +# checkout is hardened before anything reads it (scripts/harden-checkout.mjs); +# the engine is installed from pinned, verified bytes (scripts/install-engine.mjs) +# and never holds the API key — the proxy injects it; everything posted goes +# through one sanitising, redacting funnel (scripts/publish-guard.mjs); and the +# merge gate fails closed — an undecidable gate fails, a settings outage never +# loosens block_on — with the verdict also written as a commit status on the PR +# head (scripts/review-status.mjs), where a skip reads "Not reviewed" whatever +# `on-skipped-review` does to the job. name: "OrcaCode Review" description: "AI code review for every pull request, powered by OrcaRouter" @@ -47,9 +63,20 @@ inputs: required: false default: "https://api.orcarouter.ai/v1/chat/completions" github-token: - description: "Token used to fetch the PR head, post review comments, and react to a /orcacode-review command." + description: "Token used to fetch the PR head, post review comments, write the commit status on the PR head, and react to a /orcacode-review command." required: false default: ${{ github.token }} + bot-login: + description: >- + The login the action posts as, when github-token is a GitHub App's + installation token other than the job's own (e.g. "my-app[bot]"). The + action recognises its earlier notices by this login; without it, such a + token's identity is learned only from the first comment the action posts + in a run, so a notice from an earlier run is posted again instead of + edited. Not needed for the default github.token (github-actions[bot]) or + a personal token (its user). + required: false + default: "" brand: description: "Name shown on PR comments." required: false @@ -78,15 +105,17 @@ inputs: auto-review-authors: description: >- Comma-separated GitHub author-association allowlist for AUTOMATIC - reviews (pull_request events). Empty = review everyone (default). On a - PUBLIC repo, pull_request_target bypasses GitHub's fork-approval gate - and the review key is wallet-metered, so an external user can trigger - paid reviews by opening PRs — set e.g. - "OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR" to auto-review only known - contributors (others can still be reviewed on demand via - /orcacode-review). Also set a wallet budget + alert on the key. - Case-insensitive; values: OWNER, MEMBER, COLLABORATOR, CONTRIBUTOR, - FIRST_TIME_CONTRIBUTOR, FIRST_TIMER, MANNEQUIN, NONE. + reviews (pull_request events). Unset (empty) depends on the repository: + on a PUBLIC repository (or when visibility is unknown) it means + "OWNER,MEMBER,COLLABORATOR" — pull_request_target bypasses GitHub's + fork-approval gate and the review key is wallet-metered, so without this + any outsider's fork PR would spend your workspace's balance; on a + PRIVATE repository it means everyone, as before. "*" reviews everyone on + any repository (the explicit opt-out). Authors outside the list can + still be reviewed on demand by a maintainer's /orcacode-review comment. + Also set a wallet budget + alert on the key. Case-insensitive; values: + OWNER, MEMBER, COLLABORATOR, CONTRIBUTOR, FIRST_TIME_CONTRIBUTOR, + FIRST_TIMER, MANNEQUIN, NONE, or "*". required: false default: "" max-diff-kb: @@ -128,6 +157,29 @@ inputs: the skip notice posts and the check stays green. required: false default: "fail" + on-skipped-review: + description: >- + What a settings skip (auto-review off in the dashboard, on-demand mode, + a draft under ready_for_review, an author outside auto-review-authors) + does to the JOB. "pass" (default, as in every earlier release): the + notice posts and the job stays green. "fail": the job fails too. Either + way the `status-context` commit status on the PR head reports the skip + as a failure ("Not reviewed: "), so a branch rule that requires + that status cannot be satisfied by an unreviewed PR; a maintainer's + /orcacode-review then reviews the head and its verdict replaces it. + required: false + default: "pass" + status-context: + description: >- + Name (context) of the commit status the action writes on the PR's head + SHA at the end of every run: success only when a review ran on that head + and the severity gate passed (or an oversized diff was made advisory with + on-oversized-diff: "pass"); a settings skip is a failure, "Not reviewed". + It is the one check an on-demand /orcacode-review run can update on the + PR — that run's own job check is reported on the default branch — so make + THIS the required check. Needs `statuses: write`. Empty disables it. + required: false + default: "OrcaCode Review" settings: description: >- Fetch per-repo review settings from the OrcaRouter dashboard at the @@ -144,7 +196,12 @@ inputs: required: false default: "true" engine-version: - description: "Pinned @alibaba-group/open-code-review version (the review engine). Bump deliberately after testing — the later steps parse its JSON output shape." + description: >- + Pinned @alibaba-group/open-code-review version (the review engine). Only + versions whose checksums this release of the action pins + (scripts/engine-pins.json: the npm tarball's sha512 and each platform + binary's sha256) can be installed — any other value fails the run. Bump + deliberately after testing; the later steps parse its JSON output shape. required: false default: "1.3.13" timeout-minutes: @@ -244,37 +301,210 @@ runs: "$RUNNER_TEMP/result-merged.json" \ "$RUNNER_TEMP/cr-settings.json" "$RUNNER_TEMP/cr-rubric.md" \ "$RUNNER_TEMP/cr-facts.json" "$RUNNER_TEMP/proxy.out" "$RUNNER_TEMP/proxy.err" \ + "$RUNNER_TEMP/cr-upstream-key" "$RUNNER_TEMP/cr-excluded.json" \ "$RUNNER_TEMP/policy-block.json" \ "$RUNNER_TEMP/pr.diff" "$RUNNER_TEMP/diff-guard.json" "$RUNNER_TEMP/prev-summary.md" \ "$RUNNER_TEMP/wallclock-timeout" "$RUNNER_TEMP/judge-unavailable" \ "$RUNNER_TEMP/cr-usage.jsonl" \ - "$RUNNER_TEMP/cr-clean" \ + "$RUNNER_TEMP/cr-clean" "$RUNNER_TEMP/cr-identity" "$RUNNER_TEMP/cr-lockfiles.json" \ "$RUNNER_TEMP/result.l1.json" "$RUNNER_TEMP/result.l2.json" \ "$RUNNER_TEMP/result-extra.l1.json" "$RUNNER_TEMP/result-extra.l2.json" \ "$RUNNER_TEMP/result.l2.log" "$RUNNER_TEMP/result-extra.l2.log" + rm -rf "$RUNNER_TEMP/ocr-engine" + # Which event this is, whether the action acts on it at all, and the PR it + # is about. `run` is the verdict every later step is gated on. + # + # IT RUNS ON AN ALLOWLIST OF EVENTS: pull_request / pull_request_target + # (opened, synchronize, reopened, ready_for_review, edited) and issue_comment + # (created). Anything else — a review, a review comment, a push, a label — is + # a successful no-op that says why. + # + # THE ACTION CHECKS A COMMENT TRIGGER ITSELF. The shipped workflows gate the + # /orcacode-review command in their `if:`, but a workflow written by hand + # (or the bare `uses:` a quickstart shows) may not, and then ANY comment by + # ANYONE would run a paid review with the key. So an issue_comment run is + # refused unless it is on a pull request, the comment is the review command, + # and the commenter is OWNER, MEMBER or COLLABORATOR. A refusal is a quiet + # no-op (run=false), not a failure: nothing was spent and nothing attaches + # to the PR. An `edited` PR event runs only when the BASE changed (a + # retarget re-reviews against the new base; a title edit does not). - name: Resolve PR refs id: pr - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 + env: + IDENTITY: ${{ github.action_path }}/scripts/identity.mjs + BRAND: ${{ inputs.brand }} + # A refused fork-PR command is answered with a comment, through the one + # posting funnel like everything else the action posts. + PUBLISH_GUARD: ${{ github.action_path }}/scripts/publish-guard.mjs + CR_REDACT_API_KEY: ${{ inputs.orcarouter-api-key }} + CR_REDACT_GITHUB_TOKEN: ${{ inputs.github-token }} + BOT_LOGIN_INPUT: ${{ inputs.bot-login }} + # "true" when github-token is the job's own GITHUB_TOKEN — the one + # installation token whose author (github-actions[bot]) is known. + TOKEN_IS_JOB_TOKEN: ${{ inputs.github-token == github.token }} with: github-token: ${{ inputs.github-token }} script: | - let base, headSha, num, isDraft, authorAssoc; + const COMMANDS = ['/orcacode-review', '/orcacode review', '@orcacode-review', '@orcacode review']; + const TRUSTED = ['OWNER', 'MEMBER', 'COLLABORATOR']; + const payload = context.payload || {}; + const stop = (why) => { + core.setOutput('run', 'false'); + core.setOutput('stop_reason', why); + core.notice(`OrcaCode Review: not running — ${why}.`); + }; + // THE EVENTS THE ACTION RUNS ON — an allowlist. Anything that was not + // an issue_comment used to fall into the pull_request* auto-review + // gate, which is keyed on the PR's AUTHOR: a workflow listening to + // pull_request_review(_comment) ran a paid review on a maintainer's + // PR whenever anyone left a review comment. Everything else is a + // successful no-op that says why. + const PR_ACTIONS = ['opened', 'synchronize', 'reopened', 'ready_for_review', 'edited']; + const ALLOWED_EVENTS = { + pull_request: PR_ACTIONS, + pull_request_target: PR_ACTIONS, + issue_comment: ['created'], + }; + const allowed = Object.prototype.hasOwnProperty.call(ALLOWED_EVENTS, context.eventName) + ? ALLOWED_EVENTS[context.eventName] : null; + if (!allowed || !allowed.includes(payload.action)) { + return stop( + `it does not run on ${context.eventName}${payload.action ? ` (${payload.action})` : ''} — only on ` + + `pull_request / pull_request_target (${PR_ACTIONS.join(', ')}) and issue_comment (created)`, + ); + } + let commandArg = ''; + if (context.eventName === 'issue_comment') { + const c = payload.comment || {}; + const body = String(c.body || '').toLowerCase(); + const assoc = String(c.author_association || 'NONE').toUpperCase(); + // The command, then the end of the comment or whitespace — so + // "/orcacode-reviewer" is not the command. + const used = COMMANDS.find((cmd) => body.startsWith(cmd) && /^(\s|$)/.test(body.slice(cmd.length))); + const isCommand = Boolean(used); + // The word after it: the commit a fork PR's command must name. + if (used) commandArg = body.slice(used.length).trim().split(/\s+/)[0] || ''; + if (!payload.issue || !payload.issue.pull_request) return stop('the comment is not on a pull request'); + if (!isCommand) return stop('the comment is not the review command'); + if (!TRUSTED.includes(assoc)) { + return stop(`only OWNER, MEMBER or COLLABORATOR may request a review (commenter is ${assoc})`); + } + } else if (payload.action === 'edited' && !(payload.changes && payload.changes.base)) { + return stop('the pull request was edited without changing its base'); + } + + let base, headSha, num, isDraft, authorAssoc, prData; if (context.eventName === 'pull_request_target') { - base = context.payload.pull_request.base.ref; - headSha = context.payload.pull_request.head.sha; - num = context.payload.pull_request.number; - isDraft = context.payload.pull_request.draft === true; - authorAssoc = context.payload.pull_request.author_association || 'NONE'; + prData = payload.pull_request; + base = payload.pull_request.base.ref; + headSha = payload.pull_request.head.sha; + num = payload.pull_request.number; + isDraft = payload.pull_request.draft === true; + authorAssoc = payload.pull_request.author_association || 'NONE'; } else { num = context.issue.number; const { data: pr } = await github.rest.pulls.get({ owner: context.repo.owner, repo: context.repo.repo, pull_number: num, }); + prData = pr; base = pr.base.ref; headSha = pr.head.sha; isDraft = pr.draft === true; authorAssoc = pr.author_association || 'NONE'; } + const headRepo = prData && prData.head && prData.head.repo ? prData.head.repo.full_name : null; + const baseRepo = `${context.repo.owner}/${context.repo.repo}`; + const fromFork = String(headRepo || '').toLowerCase() !== baseRepo.toLowerCase(); + + // A COMMAND REVIEWS THE COMMIT THE MAINTAINER SAW. A fork's owner can + // push between a maintainer reading the change and the run starting, + // so on a fork PR the command must name the head commit + // (`/orcacode-review `), and it is reviewed only while it + // is still the head — the checkout below pins that exact SHA. A + // same-repository PR keeps the bare command; a commit it names is held + // to the same check. A refusal answers on the PR and runs nothing. + if (context.eventName === 'issue_comment') { + const named = /^[0-9a-f]{7,40}$/.test(commandArg) ? commandArg : ''; + const now = String(headSha).slice(0, 7); + let refusal = ''; + let why = ''; + if (fromFork && !named) { + why = 'the pull request comes from a fork, and the command did not name the commit to review'; + refusal = + `This pull request's head is in another repository (a fork), so a review on demand has to ` + + `name the commit it is for — the fork can push between your comment and the review.\n\n` + + `The head is now \`${now}\`. Check that it is the code you mean, then comment:\n\n` + + `\`/orcacode-review ${now}\``; + } else if (named && !String(headSha).toLowerCase().startsWith(named)) { + why = `the command named ${named}, which is no longer the pull request's head (${now})`; + refusal = + `\`/orcacode-review ${named}\` names a commit that is no longer this pull request's head, so ` + + `nothing was reviewed. The head is now \`${now}\`. Check the new commits, then comment:\n\n` + + `\`/orcacode-review ${now}\``; + } + if (refusal) { + try { + const guard = await import(require('url').pathToFileURL(process.env.PUBLISH_GUARD).href); + await guard.guardGithub(github).rest.issues.createComment({ + owner: context.repo.owner, repo: context.repo.repo, issue_number: num, + body: `## 🐳 ${process.env.BRAND || 'OrcaCode Review'}\n\n${refusal}`, + }); + } catch (e) { + core.warning(`OrcaCode Review: could not post the refusal (${e.status || e.message}).`); + } + return stop(why); + } + } + core.setOutput('run', 'true'); + + // THE AUTHOR IS NOT THE PUSHER. author_association is the PR author's, + // so on a maintainer's PR whose head lives in an outsider's fork every + // push the outsider makes passes the author gate. On `synchronize` + // from a fork, when someone other than the author pushed, ask GitHub + // whether THEY can write here; the settings gate auto-reviews only if + // so (unless auto-review-authors lets everyone through anyway). + // "n/a" = nothing to ask; "false" also when GitHub cannot say. + let pusher = ''; + let pusherTrusted = 'n/a'; + const author = prData && prData.user ? prData.user.login : ''; + const sender = payload.sender ? payload.sender.login : ''; + if (context.eventName !== 'issue_comment' && payload.action === 'synchronize' && fromFork && sender !== author) { + pusher = sender || '(unknown)'; + pusherTrusted = 'false'; + if (sender) { + try { + const { data: level } = await github.rest.repos.getCollaboratorPermissionLevel({ + owner: context.repo.owner, repo: context.repo.repo, username: sender, + }); + const can = ['admin', 'maintain', 'write']; + if (can.includes(level.permission) || can.includes(level.role_name)) pusherTrusted = 'true'; + } catch (e) { + core.warning(`OrcaCode Review: could not read ${sender}'s permission on this repository (${e.status || e.message}) — treating the push as untrusted.`); + } + } + } + core.setOutput('pusher', pusher); + core.setOutput('pusher_trusted', pusherTrusted); + // WHO THE ACTION POSTS AS — scripts/identity.mjs, the one funnel. The + // marker lookups in later steps () only + // count a comment this identity wrote. Never a guess: an App token + // that is not the job's own is "unknown" until the action's first + // post in this run reports its author (or bot-login names it). + const identity = await import(require('url').pathToFileURL(process.env.IDENTITY).href); + const me = await identity.resolveIdentity({ + github, + botLogin: process.env.BOT_LOGIN_INPUT, + tokenIsJobToken: process.env.TOKEN_IS_JOB_TOKEN === 'true', + }); + if (!me.login) { + core.notice( + 'OrcaCode Review: github-token is an App installation token that is not this job\'s own, and ' + + 'bot-login is not set — the action will learn its identity from its first post in this run, ' + + 'so a notice from an earlier run is posted again rather than edited. Set bot-login: "[bot]".', + ); + } + core.setOutput('bot_login', me.login); core.setOutput('base', base); core.setOutput('head_sha', headSha); core.setOutput('number', String(num)); @@ -291,10 +521,12 @@ runs: core.setOutput('is_draft', String(isDraft)); // PR author's association gates auto-review spend on public repos: // pull_request_target bypasses GitHub's fork-approval gate, so the - // `auto-review-authors` allowlist can restrict which associations - // trigger a paid auto-review (comment commands stay maintainer-gated - // in the workflow `if:`). + // `auto-review-authors` allowlist restricts which associations + // trigger a paid auto-review. core.setOutput('author_association', authorAssoc); + // "true" only for a repository the payload says is private; anything + // else (public, or no answer) is treated as public by every consumer. + core.setOutput('repo_private', String((payload.repository || {}).private === true)); # Lightweight 👀 acknowledgement so the requester sees the bot noticed the @@ -303,6 +535,7 @@ runs: # Reaction outages are non-fatal: the review must never be blocked by a # UI-affordance failure. - name: React 👀 to acknowledge review request + if: steps.pr.outputs.run == 'true' shell: bash env: GH_TOKEN: ${{ inputs.github-token }} @@ -319,7 +552,7 @@ runs: # Checked once here rather than inside react(), so a token that cannot be # identified costs one API call, not two. # ONLY AN EXPLICIT "User" DECLINES. `gh api user` needs a user-scoped - # token, and github-token defaults to ${{ github.token }} — an + # token, and github-token defaults to the job's github.token — an # installation token, for which that endpoint returns no user. The old # `|| echo "Bot"` fallback was meant to cover that and did not: the call # can exit 0 with no `.type`, so ME_TYPE came back empty, `!= "Bot"` held, @@ -370,19 +603,26 @@ runs: # setup-node runs BEFORE checkout (it never reads the workspace) so the # settings fetch below has node available even on a bare self-hosted runner. - - uses: actions/setup-node@v4 + - uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 + if: steps.pr.outputs.run == 'true' with: node-version: "20" # Dashboard-driven behavior, fetched from the gateway BEFORE anything is # cloned or installed: a settings-skip should cost nothing. settings.mjs - # always exits 0 and falls back to the built-in defaults on any outage - # (fail-open — a settings hiccup must never kill reviews); this step's own - # parsing falls back the same way, so `decision` is always review|skip. + # always exits 0 and says why when it could not fetch: "no_settings" (a 4xx + # — an ordinary, non-CI key gets 403 on every run) or "unavailable" (5xx, + # timeout, network). Either way THE WORKFLOW'S INPUTS are used for the run, + # exactly as with `settings: "false"`, and never anything stricter: the + # workflow's block-on is the outage floor (README, SECURITY.md). - name: Fetch review settings id: settings + if: steps.pr.outputs.run == 'true' shell: bash env: + # The one judge of where the key may go (https, or http to this + # machine), asked before anything sends it. + GATEWAY_URL_CHECK: ${{ github.action_path }}/scripts/gateway-url.mjs SETTINGS_SCRIPT: ${{ github.action_path }}/scripts/settings.mjs SETTINGS_ENABLED: ${{ inputs.settings }} ORCAROUTER_URL: ${{ inputs.orcarouter-url }} @@ -396,7 +636,20 @@ runs: IS_DRAFT: ${{ steps.pr.outputs.is_draft }} AUTHOR_ASSOC: ${{ steps.pr.outputs.author_association }} AUTO_REVIEW_AUTHORS: ${{ inputs.auto-review-authors }} + REPO_PRIVATE: ${{ steps.pr.outputs.repo_private }} + # Who pushed to a fork PR, if not its author, and whether they can + # write here (Resolve PR refs): "true", "false", or "n/a". + PUSHER: ${{ steps.pr.outputs.pusher }} + PUSHER_TRUSTED: ${{ steps.pr.outputs.pusher_trusted }} + BRAND: ${{ inputs.brand }} run: | + # THE FIRST STEP THAT READS orcarouter-url judges it, for every run: the + # key would go there as a Bearer header (this fetch, the review proxy, + # the run report), and in clear it may go only to this machine. A + # refusal names the input and the fix (scripts/gateway-url.mjs). + # (`:?` — an unset path must fail, not run `node ""`, which exits 0.) + node "${GATEWAY_URL_CHECK:?}" || exit 1 + # The auto-event gate is defined UP FRONT — before the settings-disabled # short-circuit — so BOTH the settings-disabled (workflow-file- # authoritative) and settings-enabled (dashboard) paths share the exact @@ -410,13 +663,14 @@ runs: # code). Both sides are space-trimmed the way the JS list parsers are, # so "OWNER, MEMBER" still anchors on ",MEMBER,"; the comma wrapping # keeps the match a whole-token one (MEMBER never matches inside - # FIRST_TIME_CONTRIBUTOR). An empty (or all-space) allowlist allows - # everyone (default, preserves behavior). echoes allow|deny. + # FIRST_TIME_CONTRIBUTOR). "*" (and, for this pure function, an empty + # list) allows everyone; what an UNSET input means is decided in + # gate_decision, by repository visibility. echoes allow|deny. author_allowed() { local list assoc list=$(printf '%s' "$1" | tr -d ' ') assoc=$(printf '%s' "$2" | tr -d ' ') - if [ -z "$list" ]; then echo allow; return; fi + if [ -z "$list" ] || [ "$list" = "*" ]; then echo allow; return; fi if printf '%s' ",$list," | grep -qi ",$assoc,"; then echo allow; else echo deny; fi } @@ -432,6 +686,15 @@ runs: gate_decision() { DECISION=review REASON="" + # UNSET auto-review-authors is not "everyone" on a public repository: + # there any outsider's fork PR would spend the workspace's wallet, so + # it means the maintainers. Private repos keep "everyone". "*" is the + # explicit opt-out. Unknown visibility counts as public. + local authors + authors=$(printf '%s' "$AUTO_REVIEW_AUTHORS" | tr -d ' ') + if [ -z "$authors" ]; then + if [ "${REPO_PRIVATE:-}" = "true" ]; then authors="*"; else authors="OWNER,MEMBER,COLLABORATOR"; fi + fi case "$EVENT_NAME" in pull_request*) if [ "$1" = "false" ]; then @@ -440,27 +703,33 @@ runs: DECISION=skip; REASON="on-demand mode" elif [ "$2" = "ready_for_review" ] && [ "$3" = "true" ]; then DECISION=skip; REASON="draft PR" - elif [ "$(author_allowed "$AUTO_REVIEW_AUTHORS" "$AUTHOR_ASSOC")" = deny ]; then - # Maintainer comment commands are unaffected (gated in the workflow `if:`). - DECISION=skip; REASON="author association $AUTHOR_ASSOC not in auto-review-authors" + elif [ "$(author_allowed "$authors" "$AUTHOR_ASSOC")" = deny ]; then + # Maintainer comment commands are unaffected (gated in the + # Resolve PR refs step and the workflow `if:`). + DECISION=skip; REASON="author association $AUTHOR_ASSOC not in auto-review-authors ($authors)" + elif [ "${PUSHER_TRUSTED:-}" = "false" ] && [ "$authors" != "*" ]; then + # The author passed, but someone else pushed this head into a + # fork PR and cannot write here. Where the allowlist lets + # everyone through, they could have opened a PR of their own. + DECISION=skip; REASON="pushed to a fork PR by ${PUSHER:-someone} without write access to this repository (auto-review-authors gates the pusher too)" fi ;; esac } - # `settings: "false"` makes the workflow FILE authoritative: skip the - # fetch entirely, so inputs (or their documented defaults) apply as-is - # and no dashboard value can override them. (With the fetch on, an - # input left AT its documented default defers to the server — see the - # precedence rule below — so e.g. a deliberate `block-on: "P0,P1"` pin - # could still be overridden from the dashboard.) auto_review/trigger are - # fixed on (true/every_push) in this mode, so gate_decision can only skip - # via the author allowlist — a fork author still can't spend on a public - # repo just because the dashboard fetch is off. - if [ "$SETTINGS_ENABLED" = "false" ]; then - echo "settings: disabled via the 'settings' input — the workflow file is authoritative." + # THE WORKFLOW FILE AS THE WHOLE CONFIGURATION: inputs (or their + # documented defaults) apply as-is and no dashboard value overrides them. + # Used by `settings: "false"`, and by a fetch that got no settings — a + # 4xx or an outage — so a run without dashboard values behaves exactly + # like one that asked for none. (With the fetch on and answered, an input + # left AT its documented default defers to the server — see the + # precedence rule below.) auto_review/trigger are fixed on + # (true/every_push) here, so gate_decision can only skip via the author + # allowlist — a fork author still can't spend on a public repo just + # because the dashboard did not answer. $1 = why, for the log. + workflow_authoritative() { gate_decision true every_push false - echo "settings: workflow-file-authoritative -> $DECISION ${REASON:+($REASON)}" + echo "settings: workflow-file-authoritative ($1) -> $DECISION ${REASON:+($REASON)}" { echo "auto_review=true" echo "trigger=every_push" @@ -468,7 +737,7 @@ runs: echo "quiet=false" echo "fix_first=$INPUT_FIX_FIRST" echo "block_on=$INPUT_BLOCK_ON" - # Every severity: with the dashboard off there is no report_on to + # Every severity: with no dashboard value there is no report_on to # honour and the workflow file has no input for it, so display must # not narrow on its own. echo "report_on=P0,P1,P2,P3" @@ -476,12 +745,44 @@ runs: echo "decision=$DECISION" echo "reason=$REASON" } >> "$GITHUB_OUTPUT" + } + + if [ "$SETTINGS_ENABLED" = "false" ]; then + echo "settings: disabled via the 'settings' input — the workflow file is authoritative." + workflow_authoritative "settings: false" exit 0 fi node "$SETTINGS_SCRIPT" --url "$ORCAROUTER_URL" \ --repo "$REPO" --out "$SETTINGS_JSON" + # Did the fetch get settings? settings.mjs classifies a failure; a file + # it could not write at all is an outage too. + FETCH_STATUS=$(node -pe 'JSON.parse(require("fs").readFileSync(process.env.SETTINGS_JSON, "utf8")).status || "ok"' 2>/dev/null) \ + || FETCH_STATUS="unavailable" + FETCH_CAUSE=$(node -pe 'String(JSON.parse(require("fs").readFileSync(process.env.SETTINGS_JSON, "utf8")).cause || "")' 2>/dev/null) \ + || FETCH_CAUSE="settings.mjs wrote no readable settings file" + case "$FETCH_STATUS" in + ok) ;; + no_settings) + # ORDINARY, not an outage: a key that is not a CI key has no + # dashboard settings and gets a 4xx on every run. + echo "::notice::$BRAND: the OrcaRouter dashboard has no settings for this key ($FETCH_CAUSE) — using this workflow's inputs, as with settings: \"false\" (set that to skip the fetch)." + workflow_authoritative "no dashboard settings: $FETCH_CAUSE" + exit 0 + ;; + *) + # AN OUTAGE NEVER ESCALATES PAST THE WORKFLOW. Blocking on every + # severity here (the first cut of the CR-16 fix) blocked every run of + # every key the endpoint refuses. The hole CR-16 named — an outage + # loosening a stricter dashboard block_on — is closed by the + # workflow: its block-on is the outage floor, documented as such. + echo "::warning::$BRAND: the OrcaRouter dashboard settings could not be read ($FETCH_CAUSE) — using this workflow's inputs for this run. Its block-on (\"$INPUT_BLOCK_ON\") is the outage floor: set block-on in the workflow to what the dashboard enforces." + workflow_authoritative "dashboard unavailable: $FETCH_CAUSE" + exit 0 + ;; + esac + # Read one validated field from the settings file; $2 is the fallback # if the file itself is missing/unreadable (settings.mjs already # defaulted and validated every field it wrote). @@ -507,11 +808,23 @@ runs: REPORT_ON=$(setting report_on "P0,P1") RUBRIC=$(setting rubric "") + # Which values are stand-ins for ones the dashboard did not give us + # (a field it answered with an invalid value): settings.mjs names them. + UNRESOLVED=$(node -pe 'const s=JSON.parse(require("fs").readFileSync(process.env.SETTINGS_JSON,"utf8")); (Array.isArray(s.unresolved)?s.unresolved:[]).join(",")' 2>/dev/null) \ + || UNRESOLVED="" + # PRECEDENCE (documented in the README): an explicit `with:` input that # DIFFERS from the action's documented default ("P0,P1") wins over the # server settings; an input left at the default defers to the server. if [ "$INPUT_FIX_FIRST" != "P0,P1" ]; then FIX_FIRST="$INPUT_FIX_FIRST"; fi - if [ "$INPUT_BLOCK_ON" != "P0,P1" ]; then BLOCK_ON="$INPUT_BLOCK_ON"; fi + if [ "$INPUT_BLOCK_ON" != "P0,P1" ]; then + BLOCK_ON="$INPUT_BLOCK_ON" + elif printf ',%s,' "$UNRESOLVED" | grep -q ',block_on,'; then + # The dashboard answered, but not with a usable block_on: the + # workflow's own value stands in, never a guess stricter or looser. + BLOCK_ON="$INPUT_BLOCK_ON" + echo "::warning::$BRAND: the OrcaRouter dashboard's block_on was not a valid severity list — using this workflow's block-on (\"$INPUT_BLOCK_ON\") for this run." + fi # A non-empty server rubric REPLACES rules/severity-instruction.md as # the --background content; it is exposed as a file path only when set. @@ -522,7 +835,7 @@ runs: echo "Using the server-side rubric ($(wc -c < "$RUBRIC_FILE") bytes) instead of the built-in one." fi - # Settings gate — composable with the diff guard's `decision != 'skip'`. + # Settings gate — composable with the diff guard's `decision == 'review'`. # Same gate_decision as the settings-disabled path (defined at the top of # this step): the dashboard-fetched auto_review/trigger feed it here, # while the author-allowlist spend guard inside it is identical in both @@ -544,21 +857,54 @@ runs: # On a settings-skip: leave ONE small marker comment (created if absent, # edited only when the reason changes — repeated pushes must not spam the - # timeline or its edit history), then PASS. No later step runs the engine - # or the gate, so the job (and a required check) goes green. + # timeline or its edit history), then apply `on-skipped-review` to the JOB. + # No later step runs the engine or the gate either way. Default "pass": the + # job stays green, as in every earlier release; the commit status on the + # head (Publish the review status) says "Not reviewed", which is what holds + # a merge for a customer who requires it. "fail" fails the job too. - name: Skip review (settings) if: steps.settings.outputs.decision == 'skip' - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 env: + # Only comments this identity wrote count as the action's own (markers). + BOT_LOGIN: ${{ steps.pr.outputs.bot_login }} BRAND: ${{ inputs.brand }} PR_NUMBER: ${{ steps.pr.outputs.number }} REASON: ${{ steps.settings.outputs.reason }} + ON_SKIPPED: ${{ inputs.on-skipped-review }} + # Named in the notice when it is on: the status that reports the skip. + STATUS_CONTEXT: ${{ inputs.status-context }} + # Every post goes through scripts/publish-guard.mjs: `gh` redacts these + # two values (in every encoding) from whatever it sends. + PUBLISH_GUARD: ${{ github.action_path }}/scripts/publish-guard.mjs + CR_REDACT_API_KEY: ${{ inputs.orcarouter-api-key }} + CR_REDACT_GITHUB_TOKEN: ${{ inputs.github-token }} with: github-token: ${{ inputs.github-token }} script: | + // THE ONE POSTING FUNNEL (scripts/publish-guard.mjs): every comment, + // review, description and status goes out through `gh`, which redacts + // the OrcaRouter key and the GitHub token from what it sends. + const guard = await import(require('url').pathToFileURL(process.env.PUBLISH_GUARD).href); + const gh = guard.guardGithub(github); + // A marker counts only in a comment the action's own identity wrote + // (guard.isOwn — scripts/identity.mjs). Unknown identity matches + // nothing: post anew, edit and delete nothing. + const mine = guard.isOwn; const brand = process.env.BRAND; const num = Number(process.env.PR_NUMBER); const repo = { owner: context.repo.owner, repo: context.repo.repo }; + // The JOB fails only on an explicit "fail"; the default and any other + // value pass it, as every earlier release did. What protects a merge + // is the commit status, which reports every settings skip as "Not + // reviewed" (scripts/review-status.mjs) — a skip that failed jobs by + // default turned on-demand, draft and outsider PRs red for everyone. + const onSkipped = String(process.env.ON_SKIPPED || '').trim().toLowerCase(); + const fail = onSkipped === 'fail'; + if (onSkipped && onSkipped !== 'pass' && !fail) { + core.warning(`${brand}: on-skipped-review is "${process.env.ON_SKIPPED}", which is neither "pass" nor "fail" — passing the job.`); + } + const statusName = String(process.env.STATUS_CONTEXT || '').trim(); // Own marker (distinct from the summary and oversized-skip ones). const MARKER = ''; const footer = @@ -566,29 +912,42 @@ runs: `Route Smarter. Ship Safer. Spend Less.`; const body = `${MARKER}\n## 🐳 ${brand}\n\n` + - `⏸️ **Automatic review is off for this PR** (${process.env.REASON}).\n\n` + - `The check **passes** — this never blocks your merge. A maintainer can still ` + - `run a review on demand by commenting \`/orcacode-review\` ` + - `(\`@orcacode review\` works too), or change the ` + + `⏸️ **Automatic review is off for this PR** (${guard.sanitizeUntrusted(process.env.REASON, { atLineStart: false, maxChars: 300 })}).\n\n` + + (fail + ? `The check **fails** (\`on-skipped-review: "fail"\`): this PR has not been reviewed. ` + : `This skip does not fail the job. `) + + (statusName + ? `The ${guard.codeSpan(statusName, 100)} commit status on the head commit reports it as ` + + `**not reviewed**, so a branch rule that requires that status holds the merge until a review runs. ` + : '') + + `A maintainer can run a review on demand by commenting \`/orcacode-review\` ` + + `(\`@orcacode review\` works too) — its verdict replaces this one — or change the ` + `repo's review settings in the OrcaRouter dashboard.` + footer; const comments = await github.paginate(github.rest.issues.listComments, { ...repo, issue_number: num, per_page: 100, }); - const existing = comments.find((c) => c.body && c.body.includes(MARKER)); + const existing = comments.find((c) => mine(c) && c.body.includes(MARKER)); if (!existing) { - await github.rest.issues.createComment({ ...repo, issue_number: num, body }); + await gh.rest.issues.createComment({ ...repo, issue_number: num, body }); } else if (existing.body !== body) { // Only when the reason changed (e.g. on_demand -> draft). - await github.rest.issues.updateComment({ ...repo, comment_id: existing.id, body }); + await gh.rest.issues.updateComment({ ...repo, comment_id: existing.id, body }); } await core.summary.addRaw(`skipped: ${process.env.REASON}`).write(); - core.notice(`${brand}: review skipped — ${process.env.REASON}`); + if (!fail) { + core.notice(`${brand}: review skipped — ${process.env.REASON}`); + } else { + core.setFailed( + `${brand}: review skipped — ${process.env.REASON}. Failing the job (on-skipped-review: "fail"): ` + + `a maintainer can comment /orcacode-review to review the head.`, + ); + } - - uses: actions/checkout@v4 - if: steps.settings.outputs.decision != 'skip' + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + if: steps.settings.outputs.decision == 'review' with: fetch-depth: 0 # full history for the merge-base diff ref: ${{ steps.pr.outputs.head_sha }} @@ -598,27 +957,55 @@ runs: persist-credentials: false - name: Fetch PR head (covers fork PRs) - if: steps.settings.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' shell: bash env: GH_TOKEN: ${{ inputs.github-token }} PR_NUMBER: ${{ steps.pr.outputs.number }} run: | - # Authenticate this one fetch with a command-scoped header (works for - # private repos) so the token is never written to disk for later steps. + # Authenticate this one fetch (works for private repos) without writing + # the token to disk for later steps AND without putting it on git's + # command line: `git -c http.extraheader=…` is argv, which any process + # on a shared runner can read from /proc//cmdline or `ps`. The + # GIT_CONFIG_COUNT/KEY/VALUE environment form (git >= 2.31) carries the + # same config through the environment instead, and the header is scoped + # to the server's URL so it cannot follow a redirect elsewhere. AUTH=$(printf 'x-access-token:%s' "$GH_TOKEN" | base64 | tr -d '\n') - git -c "http.extraheader=Authorization: Basic $AUTH" \ - fetch origin "pull/${PR_NUMBER}/head" + GIT_CONFIG_COUNT=1 \ + GIT_CONFIG_KEY_0="http.${GITHUB_SERVER_URL:-https://github.com}/.extraheader" \ + GIT_CONFIG_VALUE_0="AUTHORIZATION: basic $AUTH" \ + git fetch origin "pull/${PR_NUMBER}/head" + + # BEFORE ANYTHING READS THE CHECKOUT (the size guard below, then the + # engine): delete every symlink, take the `diff` attribute away from the + # PR's .gitattributes, drop PR-controlled engine config and restore the base + # revision's .gitignore — see scripts/harden-checkout.mjs. Then list the + # changed files the engine will skip, for the summary. + - name: Harden the checkout + id: harden + if: steps.settings.outputs.decision == 'review' + shell: bash + env: + HARDEN: ${{ github.action_path }}/scripts/harden-checkout.mjs + EXCLUDED: ${{ github.action_path }}/scripts/excluded-files.mjs + BASE: origin/${{ steps.pr.outputs.base }} + HEAD: ${{ steps.pr.outputs.head_sha }} + EXCLUDED_FILE: ${{ runner.temp }}/cr-excluded.json + run: | + node "$HARDEN" --base "$BASE" + node "$EXCLUDED" --base "$BASE" --head "$HEAD" --out "$EXCLUDED_FILE" > /dev/null - name: Oversized-diff guard id: guard - if: steps.settings.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' shell: bash env: BRAND: ${{ inputs.brand }} BASE: origin/${{ steps.pr.outputs.base }} HEAD: ${{ steps.pr.outputs.head_sha }} GUARD: ${{ github.action_path }}/scripts/diff-guard.mjs + GUARD_DIFF: ${{ github.action_path }}/scripts/guard-diff.mjs + LOCKFILES_FILE: ${{ runner.temp }}/cr-lockfiles.json MAX_KB: ${{ inputs.max-diff-kb }} MAX_FILES: ${{ inputs.max-diff-files }} DIFF_FILE: ${{ runner.temp }}/pr.diff @@ -626,20 +1013,24 @@ runs: run: | # Size-check the SAME range the engine reviews (merge-base diff), # BEFORE anything is installed or run: an oversized PR should cost - # nothing. `--merge-base` needs git >= 2.30; fall back to the - # equivalent three-dot form, then fail OPEN (empty file -> "review") - # if no diff can be produced — a guard glitch must never kill the job. - git diff --merge-base "$BASE" "$HEAD" > "$DIFF_FILE" 2>/dev/null \ - || git diff "$BASE...$HEAD" > "$DIFF_FILE" 2>/dev/null \ - || { echo "::warning::$BRAND: diff generation failed — size guard failing open."; : > "$DIFF_FILE"; } + # nothing — minus the files named like a standard lockfile, which the + # hardened checkout's `* !diff` would otherwise count in full (see + # scripts/guard-diff.mjs; they are listed in the summary). The engine + # still reads the full diff. Fails OPEN (empty file -> "review") if no + # diff can be produced — a guard glitch must never kill the job. + node "$GUARD_DIFF" --base "$BASE" --head "$HEAD" --out "$DIFF_FILE" --lockfiles "$LOCKFILES_FILE" node "$GUARD" --diff "$DIFF_FILE" --max-kb "$MAX_KB" --max-files "$MAX_FILES" > "$GUARD_JSON" cat "$GUARD_JSON" node -e ' const fs = require("fs"); const g = JSON.parse(fs.readFileSync(process.env.GUARD_JSON, "utf8")); + let lockfiles = 0; + try { + lockfiles = JSON.parse(fs.readFileSync(process.env.LOCKFILES_FILE, "utf8")).lockfiles.length; + } catch {} fs.appendFileSync( process.env.GITHUB_OUTPUT, - `decision=${g.decision}\nreason=${g.reason}\nsize_kb=${g.size_kb}\nfiles=${g.files}\n`, + `decision=${g.decision}\nreason=${g.reason}\nsize_kb=${g.size_kb}\nfiles=${g.files}\nlockfiles=${lockfiles}\n`, ); ' @@ -651,8 +1042,10 @@ runs: # "pass" restores the advisory behavior (notice + green check). - name: Skip review (diff too large) if: steps.guard.outputs.decision == 'skip' - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 env: + # Only comments this identity wrote count as the action's own (markers). + BOT_LOGIN: ${{ steps.pr.outputs.bot_login }} BRAND: ${{ inputs.brand }} PR_NUMBER: ${{ steps.pr.outputs.number }} SIZE_KB: ${{ steps.guard.outputs.size_kb }} @@ -661,9 +1054,23 @@ runs: MAX_KB: ${{ inputs.max-diff-kb }} MAX_FILES: ${{ inputs.max-diff-files }} ON_OVERSIZED: ${{ inputs.on-oversized-diff }} + # Every post goes through scripts/publish-guard.mjs: `gh` redacts these + # two values (in every encoding) from whatever it sends. + PUBLISH_GUARD: ${{ github.action_path }}/scripts/publish-guard.mjs + CR_REDACT_API_KEY: ${{ inputs.orcarouter-api-key }} + CR_REDACT_GITHUB_TOKEN: ${{ inputs.github-token }} with: github-token: ${{ inputs.github-token }} script: | + // THE ONE POSTING FUNNEL (scripts/publish-guard.mjs): every comment, + // review, description and status goes out through `gh`, which redacts + // the OrcaRouter key and the GitHub token from what it sends. + const guard = await import(require('url').pathToFileURL(process.env.PUBLISH_GUARD).href); + const gh = guard.guardGithub(github); + // A marker counts only in a comment the action's own identity wrote + // (guard.isOwn — scripts/identity.mjs). Unknown identity matches + // nothing: post anew, edit and delete nothing. + const mine = guard.isOwn; const brand = process.env.BRAND; const num = Number(process.env.PR_NUMBER); const repo = { owner: context.repo.owner, repo: context.repo.repo }; @@ -682,10 +1089,10 @@ runs: `diff cannot slip through a required merge gate.`; const body = `${MARKER}\n## 🐳 ${brand}\n\n` + - `⏭️ **Review skipped — this PR's diff is too large** (${process.env.REASON}).\n\n` + + `⏭️ **Review skipped — this PR's diff is too large** (${guard.sanitizeUntrusted(process.env.REASON, { atLineStart: false, maxChars: 300 })}).\n\n` + `| | This PR | Limit |\n|---|---|---|\n` + - `| Diff size | ${process.env.SIZE_KB} KB | ${process.env.MAX_KB} KB |\n` + - `| Files touched | ${process.env.FILES} | ${process.env.MAX_FILES} |\n\n` + + `| Diff size | ${Number(process.env.SIZE_KB)} KB | ${Number(process.env.MAX_KB)} KB |\n` + + `| Files touched | ${Number(process.env.FILES)} | ${Number(process.env.MAX_FILES)} |\n\n` + `The review engine was **not** run — reviews of very large diffs truncate and ` + `lose signal — ${outcome}\n\n` + `**What now?** Split the PR (smaller diffs get much higher-signal reviews), raise ` + @@ -696,11 +1103,11 @@ runs: const comments = await github.paginate(github.rest.issues.listComments, { ...repo, issue_number: num, per_page: 100, }); - const existing = comments.find((c) => c.body && c.body.includes(MARKER)); + const existing = comments.find((c) => mine(c) && c.body.includes(MARKER)); if (existing) { - await github.rest.issues.updateComment({ ...repo, comment_id: existing.id, body }); + await gh.rest.issues.updateComment({ ...repo, comment_id: existing.id, body }); } else { - await github.rest.issues.createComment({ ...repo, issue_number: num, body }); + await gh.rest.issues.createComment({ ...repo, issue_number: num, body }); } await core.summary.addRaw(`skipped: diff too large (${process.env.REASON})`).write(); @@ -714,16 +1121,49 @@ runs: ); } + # FROM PINNED, VERIFIED BYTES, WITH NO INSTALL SCRIPTS. A plain + # `npm install -g` pinned only the top-level version, ran the package's + # postinstall (which downloads the Go engine binary and checks it against a + # checksum file from the same release — no independent pin) and checked no + # integrity. scripts/install-engine.mjs verifies the npm tarball against + # the sha512 pinned in scripts/engine-pins.json, installs it with + # --ignore-scripts into a prefix under $RUNNER_TEMP, and verifies the + # binary against its pinned sha256. An engine-version without pins fails. - name: Install review engine - if: steps.settings.outputs.decision != 'skip' && steps.guard.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' shell: bash env: ENGINE_VERSION: ${{ inputs.engine-version }} - run: npm install -g "@alibaba-group/open-code-review@${ENGINE_VERSION}" + INSTALLER: ${{ github.action_path }}/scripts/install-engine.mjs + ENGINE_PREFIX: ${{ runner.temp }}/ocr-engine + run: | + ENGINE_BIN=$(node "$INSTALLER" --version "$ENGINE_VERSION" --prefix "$ENGINE_PREFIX") + echo "$ENGINE_BIN" >> "$GITHUB_PATH" + + # THE KEY GOES TO THE PROXY, NEVER TO THE ENGINE. The engine reads the PR + # checkout — fork-controlled files written to steer an LLM agent — so + # anything it can read is one prompt injection away from a PR comment: its + # own environment, its parent shell's (/proc//environ is readable by + # the same user), or a file. So the Review step's env carries no secret at + # all. This step, which runs nothing from the PR, writes the key to a + # 0600 file; the proxy reads and UNLINKS it before it announces its URL, + # i.e. before the engine can start, and injects it on the way out. The + # engine and the judge only ever hold a placeholder. + - name: Stage the gateway key for the proxy + id: stage-key + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' + shell: bash + env: + ORCAROUTER_API_KEY: ${{ inputs.orcarouter-api-key }} + UPSTREAM_KEY_FILE: ${{ runner.temp }}/cr-upstream-key + run: | + umask 077 + rm -f "$UPSTREAM_KEY_FILE" + printf '%s' "$ORCAROUTER_API_KEY" > "$UPSTREAM_KEY_FILE" - name: Review id: review - if: steps.settings.outputs.decision != 'skip' && steps.guard.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' shell: bash env: ROUTER: ${{ inputs.router }} @@ -759,6 +1199,7 @@ runs: GATE: ${{ github.action_path }}/scripts/gate.mjs CHECK: ${{ github.action_path }}/scripts/check-result.mjs PROXY: ${{ github.action_path }}/scripts/fact-proxy.mjs + HARDEN: ${{ github.action_path }}/scripts/harden-checkout.mjs BRAND: ${{ inputs.brand }} # The real OrcaRouter endpoint. OCR does NOT talk to it directly: the # in-job proxy stamps the routing facts as headers and forwards here. @@ -767,7 +1208,11 @@ runs: # Nothing is written to the shared ~/.opencodereview, so we neither leak a # token to disk nor clobber a self-hosted runner's existing OCR config. # The model is the router alias; the router's DSL picks the real model. - OCR_LLM_TOKEN: ${{ inputs.orcarouter-api-key }} + # + # A PLACEHOLDER, not the key: the proxy replaces it with the real key + # (staged by the step above) on the way to the gateway. See there. + OCR_LLM_TOKEN: "placeholder-the-proxy-injects-the-key" + UPSTREAM_KEY_FILE: ${{ runner.temp }}/cr-upstream-key OCR_LLM_AUTH_HEADER: authorization OCR_LLM_MODEL: ${{ inputs.router }} OCR_USE_ANTHROPIC: "false" @@ -805,8 +1250,10 @@ runs: # so never let PR-controlled config weaken the review. A fork could commit # `.opencodereview/rule.json` to exclude its own changed files or replace # the built-in checks, yielding an empty result that passes as - # clean. Drop it so OCR uses system defaults + our --background instruction. - rm -rf .opencodereview + # clean, or a symlink that points the engine's file tools outside the + # repository. The Harden step already did this; it runs again here, right + # before the engine, so nothing between the two can leave one behind. + node "$HARDEN" --base "$BASE" > /dev/null # Clear any stale block file before the proxy can write a fresh one. On a # self-hosted runner $RUNNER_TEMP may be reused, and the always()-step @@ -827,9 +1274,15 @@ runs: CR_USAGE_FILE="" if [ "$METER" = "true" ]; then CR_USAGE_FILE="$USAGE_FILE"; fi export CR_USAGE_FILE - CR_FACTS_FILE="$FACTS_FILE" CR_POLICY_BLOCK_FILE="$POLICY_BLOCK" node "$PROXY" > "$RUNNER_TEMP/proxy.out" 2> "$RUNNER_TEMP/proxy.err" & + # The proxy reads the staged key file and unlinks it before printing + # PROXY_URL; the engine starts only after that line appears. + if [ ! -s "$UPSTREAM_KEY_FILE" ]; then + echo "::error::$BRAND: the gateway key was not staged for the proxy."; exit 1 + fi + CR_UPSTREAM_KEY_FILE="$UPSTREAM_KEY_FILE" CR_FACTS_FILE="$FACTS_FILE" CR_POLICY_BLOCK_FILE="$POLICY_BLOCK" \ + node "$PROXY" > "$RUNNER_TEMP/proxy.out" 2> "$RUNNER_TEMP/proxy.err" & PROXY_PID=$! - trap 'kill "$PROXY_PID" 2>/dev/null || true' EXIT + trap 'kill "$PROXY_PID" 2>/dev/null || true; rm -f "$UPSTREAM_KEY_FILE"' EXIT for _ in $(seq 1 50); do OCR_LLM_URL=$(sed -n 's/^PROXY_URL=//p' "$RUNNER_TEMP/proxy.out" 2>/dev/null || true) [ -n "$OCR_LLM_URL" ] && break @@ -838,6 +1291,10 @@ runs: if [ -z "$OCR_LLM_URL" ]; then echo "::error::$BRAND: fact proxy failed to start."; cat "$RUNNER_TEMP/proxy.err" || true; exit 1 fi + # Belt and braces: never start the engine while the key is on disk. + if [ -e "$UPSTREAM_KEY_FILE" ]; then + echo "::error::$BRAND: the staged gateway key is still on disk — refusing to start the engine."; exit 1 + fi export OCR_LLM_URL # Set the raw facts the DSL routes on for the NEXT review pass. @@ -1213,15 +1670,33 @@ runs: # The guard condition also keeps a STALE block file from being posted on a # skipped run (the review step's own cleanup never ran on a skip). - name: Surface guardrail / firewall block - if: always() && steps.settings.outputs.decision != 'skip' && steps.guard.outputs.decision != 'skip' - uses: actions/github-script@v7 + if: always() && steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 env: + # Only comments this identity wrote count as the action's own (markers). + BOT_LOGIN: ${{ steps.pr.outputs.bot_login }} BRAND: ${{ inputs.brand }} PR_NUMBER: ${{ steps.pr.outputs.number }} POLICY_BLOCK: ${{ runner.temp }}/policy-block.json + # "true" only on a private repository; anything else is treated as public. + REPO_PRIVATE: ${{ github.event.repository.private }} + # Every post goes through scripts/publish-guard.mjs: `gh` redacts these + # two values (in every encoding) from whatever it sends. + PUBLISH_GUARD: ${{ github.action_path }}/scripts/publish-guard.mjs + CR_REDACT_API_KEY: ${{ inputs.orcarouter-api-key }} + CR_REDACT_GITHUB_TOKEN: ${{ inputs.github-token }} with: github-token: ${{ inputs.github-token }} script: | + // THE ONE POSTING FUNNEL (scripts/publish-guard.mjs): every comment, + // review, description and status goes out through `gh`, which redacts + // the OrcaRouter key and the GitHub token from what it sends. + const guard = await import(require('url').pathToFileURL(process.env.PUBLISH_GUARD).href); + const gh = guard.guardGithub(github); + // A marker counts only in a comment the action's own identity wrote + // (guard.isOwn — scripts/identity.mjs). Unknown identity matches + // nothing: post anew, edit and delete nothing. + const mine = guard.isOwn; const fs = require('fs'); let block; try { @@ -1238,14 +1713,25 @@ runs: // it once a clean review posts. const MARKER = ''; const layer = block.kind === 'firewall' ? 'firewall' : 'guardrail'; - const policyLine = block.policyName - ? `\n\n**Policy:** \`${String(block.policyName).slice(0, 120)}\`` + // ON A PUBLIC REPOSITORY THE NOTICE IS GENERIC. The policy's name and + // the text it matched describe the workspace's security configuration + // (and may quote what it caught); on a public PR anyone can read them, + // including the author probing which rule to evade. Private repos keep + // the detail, sanitised. Unknown visibility counts as public. + const isPrivate = process.env.REPO_PRIVATE === 'true'; + const policyLine = isPrivate && block.policyName + ? `\n\n**Policy:** ${guard.codeSpan(block.policyName, 120)}` + : ''; + const detail = isPrivate && block.detail + ? guard.sanitizeUntrusted(String(block.detail), { atLineStart: false, maxChars: 300 }) : ''; - const detail = block.detail ? String(block.detail).slice(0, 300) : ''; const matchedLine = detail ? `\n\n**Matched:** ${detail}` : ''; - const idTag = block.requestId - ? ` · request id \`${String(block.requestId).slice(0, 80)}\`` + const idTag = isPrivate && block.requestId + ? ` · request id ${guard.codeSpan(block.requestId, 80)}` : ''; + if (!isPrivate) { + console.log(`${layer} block (details withheld from the public PR; see the OrcaRouter dashboard)`); + } const footer = `\n\n[OrcaCode Review](https://www.orcarouter.ai/code-review) — ` + `Route Smarter. Ship Safer. Spend Less.${idTag}`; @@ -1269,11 +1755,11 @@ runs: const existingComments = await github.paginate(github.rest.issues.listComments, { ...repo, issue_number: num, per_page: 100, }); - const existing = existingComments.find((c) => c.body && c.body.includes(MARKER)); + const existing = existingComments.find((c) => mine(c) && c.body.includes(MARKER)); if (!existing) { - await github.rest.issues.createComment({ ...repo, issue_number: num, body }); + await gh.rest.issues.createComment({ ...repo, issue_number: num, body }); } else if (existing.body !== body) { - await github.rest.issues.updateComment({ ...repo, comment_id: existing.id, body }); + await gh.rest.issues.updateComment({ ...repo, comment_id: existing.id, body }); } # What gets POSTED is decoupled from what gets ENFORCED: this step always @@ -1297,7 +1783,7 @@ runs: # THE SUMMARY IS DISPLAY, so it reads the filtered copy — it did not, and the # pinned description contradicted the review three lines below it. - name: report_on severity filter - if: steps.settings.outputs.decision != 'skip' && steps.guard.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' shell: bash env: REPORT_FILTER: ${{ github.action_path }}/scripts/report-filter.mjs @@ -1322,7 +1808,7 @@ runs: --show "$REPORT_ON" --block-on "$BLOCK_ON" --out "$RESULT_REPORTED" - name: Quiet mode filter - if: steps.settings.outputs.decision != 'skip' && steps.guard.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' shell: bash env: QUIET: ${{ steps.settings.outputs.quiet }} @@ -1338,8 +1824,8 @@ runs: fi - name: Post review comments - if: steps.settings.outputs.decision != 'skip' && steps.guard.outputs.decision != 'skip' - uses: actions/github-script@v7 + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 env: BRAND: ${{ inputs.brand }} PR_NUMBER: ${{ steps.pr.outputs.number }} @@ -1352,9 +1838,19 @@ runs: # to declare a run clean put "No findings" and a 👍 on a pull request # whose own summary listed the findings three lines above. RESULT_FOUND: ${{ runner.temp }}/result-reported.json + # Every post goes through scripts/publish-guard.mjs: `gh` redacts these + # two values (in every encoding) from whatever it sends. + PUBLISH_GUARD: ${{ github.action_path }}/scripts/publish-guard.mjs + CR_REDACT_API_KEY: ${{ inputs.orcarouter-api-key }} + CR_REDACT_GITHUB_TOKEN: ${{ inputs.github-token }} with: github-token: ${{ inputs.github-token }} script: | + // THE ONE POSTING FUNNEL (scripts/publish-guard.mjs): every comment, + // review, description and status goes out through `gh`, which redacts + // the OrcaRouter key and the GitHub token from what it sends. + const guard = await import(require('url').pathToFileURL(process.env.PUBLISH_GUARD).href); + const gh = guard.guardGithub(github); const fs = require('fs'); const brand = process.env.BRAND; const num = Number(process.env.PR_NUMBER); @@ -1430,13 +1926,13 @@ runs: `## 🐳 ${brand}\n\n` + `✅ **No findings** — nothing to flag in this PR. Great work!`; try { - await github.rest.pulls.createReview({ + await gh.rest.pulls.createReview({ ...repo, pull_number: num, commit_id: sha, body: cleanBody + footer, event: 'COMMENT', }); } catch (e) { console.log('Clean review failed, posting as a comment:', e.message); - await github.rest.issues.createComment({ + await gh.rest.issues.createComment({ ...repo, issue_number: num, body: cleanBody + footer, }); } @@ -1463,13 +1959,29 @@ runs: // lowercase fragments). So we split on just two reliable signals: a // model-written **bold** lead, or a short first sentence (which keeps the // body starting on a fresh, capitalized sentence). Anything else: whole. + // + // EVERY FRAGMENT OF FINDING TEXT IS SANITISED, AFTER THE SPLIT. The text + // comes from an engine that read the fork's files, so it may carry + // @mentions, HTML, links, forged headings or a fake "No findings"; + // guard.sanitizeUntrusted neutralises all of those. It runs on the + // title and the body SEPARATELY, after splitting them: splitting + // sanitised text could cut a code span in two and leave half of it, + // unescaped, outside code. + const S = (t, o = {}) => + guard.sanitizeUntrusted(t, { repo, serverUrl: process.env.GITHUB_SERVER_URL, ...o }); const decorate = (c) => { const text = String(c.content || ''); const m = text.match(tagRe); const sev = m ? m[1].toUpperCase() : 'P1'; const badge = `${SEV[sev]} **${sev}**`; const raw = (m ? text.slice(m[0].length) : text).trim(); - const mk = (t) => t.replace(/\*\*/g, '').replace(/[.!?]+$/, '').trim(); + // A title is one line: whitespace collapsed, its own bold markup and + // closing punctuation removed, then sanitised as the continuation of + // the badge's line. + const mk = (t) => + S(t.replace(/\*\*/g, '').replace(/[.!?]+$/, '').replace(/\s+/g, ' ').trim(), { + atLineStart: false, maxChars: 200, + }); // 1) The model sometimes writes its own **bold** lead — use it verbatim. const lead = raw.match(/^\*\*(.+?)\*\*\s+([\s\S]+)$/); if (lead) { @@ -1478,16 +1990,16 @@ runs: // for a bold title on all of them, so every explanation would pass // through it — and `x ** 2` or `src/**/*.js` in a finding came out // corrupted. Only the title's own markup is removed, by mk(). - return `${badge} **${mk(lead[1])}**\n\n${lead[2].trim()}`; + return `${badge} **${mk(lead[1])}**\n\n${S(lead[2].trim())}`; } // 2) Else split only when the first sentence is short enough to title. const rest = raw.replace(/\*\*/g, ''); const end = rest.search(/(?<=[.!?])\s/); if (end > 0 && end <= 72) { - return `${badge} **${mk(rest.slice(0, end))}**\n\n${rest.slice(end).trim()}`; + return `${badge} **${mk(rest.slice(0, end))}**\n\n${S(rest.slice(end).trim())}`; } - // 3) Hard to separate cleanly — keep the finding whole. - return `${badge} ${rest}`; + // 3) Hard to separate cleanly — keep the finding whole, on the badge's line. + return `${badge} ${S(rest, { atLineStart: false })}`; }; const counts = {}; for (const c of comments) counts[sevOf(c)] = (counts[sevOf(c)] || 0) + 1; @@ -1496,28 +2008,48 @@ runs: .map((s) => `${SEV[s]} ${counts[s]} ${s}`) .join(' · '); const n = comments.length; + // BOUNDED. At most guard.MAX_POSTED_FINDINGS findings are posted, the + // most severe first; the rest are counted here (the gate and the PR + // summary still see every one of them). The review body itself is + // kept under GitHub's size limit by joinWithinLimit. + const rank = { P0: 0, P1: 1, P2: 2, P3: 3 }; + const ordered = comments + .map((c, i) => ({ c, i })) + .sort((a, b) => rank[sevOf(a.c)] - rank[sevOf(b.c)] || a.i - b.i) + .map((x) => x.c); + const shown = ordered.slice(0, guard.MAX_POSTED_FINDINGS); + const notShown = n - shown.length; const summary = `## 🐳 ${brand}\n\n` + - `Found **${n}** issue${n === 1 ? '' : 's'} in this PR: ${breakdown}.`; + `Found **${n}** issue${n === 1 ? '' : 's'} in this PR: ${breakdown}.` + + (notShown > 0 + ? `\n\n${notShown} more finding${notShown === 1 ? ' is' : 's are'} not posted here ` + + `(at most ${guard.MAX_POSTED_FINDINGS} per review); the PR summary counts all of them.` + : ''); const inline = []; const rest = []; - for (const c of comments) { + for (const c of shown) { const line = c.end_line >= 1 ? c.end_line : c.start_line >= 1 ? c.start_line : 0; if (line >= 1 && c.path) { - inline.push({ path: c.path, line, side: 'RIGHT', body: decorate(c) }); + inline.push({ path: String(c.path), line: Number(line), side: 'RIGHT', body: decorate(c) }); } else { rest.push(c); } } - let body = summary; - for (const c of rest) body += `\n\n---\n\`${c.path}\`: ${decorate(c)}`; + // File paths are the fork's own: shown only as inline code that + // cannot break out (guard.codeSpan). + const body = guard.joinWithinLimit( + summary, + rest.map((c) => `${guard.codeSpan(c.path || '(no file)')}: ${decorate(c)}`), + { tail: footer }, + ); try { - await github.rest.pulls.createReview({ + await gh.rest.pulls.createReview({ ...repo, pull_number: num, commit_id: sha, - body: body + footer, event: 'COMMENT', + body, event: 'COMMENT', comments: inline, }); } catch (e) { @@ -1525,11 +2057,12 @@ runs: // The inline batch carries the actual findings; if GitHub rejects it // (uncommentable line, batch too large) append them as text so users // still see the details instead of bare counts. - let fallback = body; - for (const c of inline) { - fallback += `\n\n---\n\`${c.path}\` (line ${c.line}): ${c.body}`; - } - await github.rest.issues.createComment({ ...repo, issue_number: num, body: fallback + footer }); + const fallback = guard.joinWithinLimit( + body.slice(0, body.length - footer.length), + inline.map((c) => `${guard.codeSpan(c.path)} (line ${Number(c.line)}): ${c.body}`), + { tail: footer }, + ); + await gh.rest.issues.createComment({ ...repo, issue_number: num, body: fallback }); } # ONE summary per PR, written into the PR DESCRIPTION body (the only element @@ -1539,9 +2072,11 @@ runs: # the gate verdict. The author's own description text is preserved untouched. # Runs BEFORE the enforce step so a blocked run still updates the summary. - name: Summary (PR description) - if: steps.settings.outputs.decision != 'skip' && steps.guard.outputs.decision != 'skip' - uses: actions/github-script@v7 + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 env: + # Only comments this identity wrote count as the action's own (markers). + BOT_LOGIN: ${{ steps.pr.outputs.bot_login }} PR_NUMBER: ${{ steps.pr.outputs.number }} # THE FILTERED COPY, the same one the inline comments come from. # @@ -1563,9 +2098,27 @@ runs: BLOCK_ON: ${{ steps.settings.outputs.block_on }} QUIET: ${{ steps.settings.outputs.quiet }} PASSES: ${{ steps.review.outputs.passes }} + # Changed files the engine skips (excluded-files.mjs, Harden step). + EXCLUDED_FILE: ${{ runner.temp }}/cr-excluded.json + # Lockfiles the size guard did not count (guard-diff.mjs). + LOCKFILES_FILE: ${{ runner.temp }}/cr-lockfiles.json + # Every post goes through scripts/publish-guard.mjs: `gh` redacts these + # two values (in every encoding) from whatever it sends. + PUBLISH_GUARD: ${{ github.action_path }}/scripts/publish-guard.mjs + CR_REDACT_API_KEY: ${{ inputs.orcarouter-api-key }} + CR_REDACT_GITHUB_TOKEN: ${{ inputs.github-token }} with: github-token: ${{ inputs.github-token }} script: | + // THE ONE POSTING FUNNEL (scripts/publish-guard.mjs): every comment, + // review, description and status goes out through `gh`, which redacts + // the OrcaRouter key and the GitHub token from what it sends. + const guard = await import(require('url').pathToFileURL(process.env.PUBLISH_GUARD).href); + const gh = guard.guardGithub(github); + // A marker counts only in a comment the action's own identity wrote + // (guard.isOwn — scripts/identity.mjs). Unknown identity matches + // nothing: post anew, edit and delete nothing. + const mine = guard.isOwn; const fs = require('fs'); const { execFileSync } = require('child_process'); const { pathToFileURL } = require('url'); @@ -1586,7 +2139,7 @@ runs: ...repo, issue_number: num, per_page: 100, }); for (const stale of ['', '', '', MARKER]) { - const notice = comments.find((c) => c.body && c.body.includes(stale)); + const notice = comments.find((c) => mine(c) && c.body.includes(stale)); if (!notice) continue; try { await github.rest.issues.deleteComment({ ...repo, comment_id: notice.id }); @@ -1611,13 +2164,16 @@ runs: } } - // Mirror the enforce step's verdict: gate.mjs on the final result - // (exit 0 = a BLOCK_ON severity is present). - let blocked; + // Mirror the enforce step's verdict: gate.mjs on the final result. + // Only exit 10 ("no BLOCK_ON finding") is a pass; a match (0) and a + // gate that could not decide (any other code) are what the enforce + // step fails on, so the summary must not announce a pass for them. + let blocked = true; try { execFileSync('node', [process.env.GATE, process.env.RESULT, '--has', process.env.BLOCK_ON], { stdio: 'pipe' }); - blocked = true; - } catch { blocked = false; } + } catch (e) { + if (e && e.status === 10) blocked = false; + } // One tier, one name. This used to report `strong`, from when a cheap // pass could escalate to a strong one; with a single pass the label was // a leftover that made per-tier figures meaningless. @@ -1642,16 +2198,25 @@ runs: } catch (e) { return true; } // unreadable: keep the old behaviour })(); if (process.env.QUIET === 'true' && summaryHasP2) args.push('--quiet'); + // What this verdict does not cover: the changed files the engine skips. + if (process.env.EXCLUDED_FILE && fs.existsSync(process.env.EXCLUDED_FILE)) { + args.push('--excluded', process.env.EXCLUDED_FILE); + } + // And the lockfiles the size limit did not count. + if (process.env.LOCKFILES_FILE && fs.existsSync(process.env.LOCKFILES_FILE)) { + args.push('--lockfiles', process.env.LOCKFILES_FILE); + } const summaryMd = execFileSync('node', args, { encoding: 'utf8' }); // Preserve the author's description text; only the marker region changes. const newBody = injectSummary(pr.body, summaryMd); if (newBody !== (pr.body || '')) { - await github.rest.pulls.update({ ...repo, pull_number: num, body: newBody }); + await gh.rest.pulls.update({ ...repo, pull_number: num, body: newBody }); } - name: Enforce severity gate - if: steps.settings.outputs.decision != 'skip' && steps.guard.outputs.decision != 'skip' + id: enforce + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' shell: bash env: BRAND: ${{ inputs.brand }} @@ -1661,11 +2226,28 @@ runs: # ALWAYS the unfiltered result — quiet mode never weakens the gate. RESULT: ${{ runner.temp }}/result.json run: | - if node "$GATE" "$RESULT" --has "$BLOCK_ON"; then - echo "::error::$BRAND: blocking — found $BLOCK_ON severity finding(s)." - exit 1 - fi - echo "$BRAND: no $BLOCK_ON findings — gate passed." + # gate.mjs answers 0 (a blocking finding) or 10 (none). ANYTHING ELSE is + # a gate that could not decide — a crash exits 1, an unreadable result 3, + # a killed process 128+n — and none of those is evidence of a clean + # review, so the merge gate fails closed on them. + GATE_RC=0 + node "$GATE" "$RESULT" --has "$BLOCK_ON" || GATE_RC=$? + case "$GATE_RC" in + 0) + echo "verdict=blocked" >> "${GITHUB_OUTPUT:-/dev/null}" + echo "::error::$BRAND: blocking — found $BLOCK_ON severity finding(s)." + exit 1 + ;; + 10) + echo "verdict=pass" >> "${GITHUB_OUTPUT:-/dev/null}" + echo "$BRAND: no $BLOCK_ON findings — gate passed." + ;; + *) + echo "verdict=error" >> "${GITHUB_OUTPUT:-/dev/null}" + echo "::error::$BRAND: the severity gate could not decide (gate.mjs exited $GATE_RC) — failing closed." + exit 1 + ;; + esac # Best-effort run counters to the OrcaRouter control plane — severity # counts and the gate verdict only, never code (see README "Run @@ -1673,7 +2255,7 @@ runs: # a blocked gate fails the job above, and blocked runs must report too. # report.mjs itself exits 0 on any error, so these steps can't fail the job. - name: Report run - if: always() && inputs.report == 'true' && steps.settings.outputs.decision != 'skip' && steps.guard.outputs.decision != 'skip' + if: always() && inputs.report == 'true' && steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' shell: bash env: REPORT: ${{ github.action_path }}/scripts/report.mjs @@ -1687,16 +2269,93 @@ runs: ORCAROUTER_API_KEY: ${{ inputs.orcarouter-api-key }} ENGINE_VERSION: ${{ inputs.engine-version }} run: | - # The verdict re-uses gate.mjs on the snapshot - # (exit 0 = a BLOCK_ON severity is present = blocked). - GATE_RESULT=pass - if node "$GATE" "$RESULT_FINAL" --has "$BLOCK_ON"; then GATE_RESULT=blocked; fi + # The verdict re-uses gate.mjs on the snapshot. Only its "no match" + # answer (exit 10) is a pass; a match (0) and a gate that could not + # decide (anything else) are both what the enforce step blocked on. + GATE_RESULT=blocked + GATE_RC=0 + node "$GATE" "$RESULT_FINAL" --has "$BLOCK_ON" || GATE_RC=$? + if [ "$GATE_RC" = "10" ]; then GATE_RESULT=pass; fi node "$REPORT" "$RESULT_FINAL" \ --repo "$REPO" --pr "$PR_NUMBER" --sha "$HEAD_SHA" \ --tier standard --gate "$GATE_RESULT" \ --url "$ORCAROUTER_URL" \ --engine-version "$ENGINE_VERSION" + # THE VERDICT ON THE PR HEAD, on every ending. An on-demand review is an + # issue_comment run, and GitHub attaches that run's job check to the DEFAULT + # branch, so before this a red verdict from /orcacode-review never reached + # the PR. This status does, for every run: success only when a review ran + # on this head and the gate passed (or a skip was made advisory on purpose) + # — see scripts/review-status.mjs. Make the `status-context` status the + # required check. Needs `statuses: write`; without it this warns and the + # job check is the only verdict. + - name: Publish the review status + id: status + if: always() && steps.pr.outputs.run == 'true' + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 + env: + STATUS_SCRIPT: ${{ github.action_path }}/scripts/review-status.mjs + STATUS_CONTEXT: ${{ inputs.status-context }} + HEAD_SHA: ${{ steps.pr.outputs.head_sha }} + DECISION: ${{ steps.settings.outputs.decision }} + REASON: ${{ steps.settings.outputs.reason }} + GUARD_DECISION: ${{ steps.guard.outputs.decision }} + GUARD_REASON: ${{ steps.guard.outputs.reason }} + ON_SKIPPED: ${{ inputs.on-skipped-review }} + ON_OVERSIZED: ${{ inputs.on-oversized-diff }} + REVIEW_OUTCOME: ${{ steps.review.outcome }} + ENFORCE_OUTCOME: ${{ steps.enforce.outcome }} + VERDICT: ${{ steps.enforce.outputs.verdict }} + BLOCK_ON: ${{ steps.settings.outputs.block_on }} + # Every post goes through scripts/publish-guard.mjs: `gh` redacts these + # two values (in every encoding) from whatever it sends. + PUBLISH_GUARD: ${{ github.action_path }}/scripts/publish-guard.mjs + CR_REDACT_API_KEY: ${{ inputs.orcarouter-api-key }} + CR_REDACT_GITHUB_TOKEN: ${{ inputs.github-token }} + with: + github-token: ${{ inputs.github-token }} + script: | + // THE ONE POSTING FUNNEL (scripts/publish-guard.mjs): every comment, + // review, description and status goes out through `gh`, which redacts + // the OrcaRouter key and the GitHub token from what it sends. + const guard = await import(require('url').pathToFileURL(process.env.PUBLISH_GUARD).href); + const gh = guard.guardGithub(github); + const context_ = (process.env.STATUS_CONTEXT || '').trim(); + if (!context_) { + console.log('status-context is empty — not writing a commit status'); + return; + } + const { decideStatus } = await import(require('url').pathToFileURL(process.env.STATUS_SCRIPT).href); + const { state, description } = decideStatus({ + decision: process.env.DECISION || '', + reason: process.env.REASON || '', + guardDecision: process.env.GUARD_DECISION || '', + guardReason: process.env.GUARD_REASON || '', + onSkipped: process.env.ON_SKIPPED || '', + onOversized: process.env.ON_OVERSIZED || '', + reviewOutcome: process.env.REVIEW_OUTCOME || '', + enforceOutcome: process.env.ENFORCE_OUTCOME || '', + verdict: process.env.VERDICT || '', + blockOn: process.env.BLOCK_ON || '', + }); + const server = process.env.GITHUB_SERVER_URL || 'https://github.com'; + try { + await gh.rest.repos.createCommitStatus({ + owner: context.repo.owner, repo: context.repo.repo, + sha: process.env.HEAD_SHA, state, context: context_, + description, + target_url: `${server}/${context.repo.owner}/${context.repo.repo}/actions/runs/${process.env.GITHUB_RUN_ID}`, + }); + console.log(`status ${context_}: ${state} — ${description}`); + } catch (e) { + core.warning( + `Could not write the "${context_}" commit status (${e.status || e.message}). Grant the workflow ` + + `\`statuses: write\` so the verdict reaches the PR head — without it, an on-demand ` + + `(/orcacode-review) verdict does not appear on the pull request.`, + ); + } + # The 👀 said "I am looking at this". Once the review has been posted — or # has failed and said so — that is no longer true, and a reaction nobody # removes stops carrying information: every PR the reviewer has ever touched @@ -1714,9 +2373,12 @@ runs: # dependency, because failing a run over a leftover emoji would trade a # cosmetic problem for a real one. - name: Settle the review reactions - if: always() + if: always() && steps.pr.outputs.run == 'true' shell: bash env: + # Who the action is (scripts/identity.mjs): resolved, or recorded from + # its first post in this run. Only that login's 👀 is ours to clear. + BOT_LOGIN: ${{ steps.pr.outputs.bot_login }} GH_TOKEN: ${{ inputs.github-token }} REPO: ${{ github.repository }} PR_NUMBER: ${{ steps.pr.outputs.number }} @@ -1736,7 +2398,7 @@ runs: # # The review body and the summary say everything the reactions would. # ONLY AN EXPLICIT "User" DECLINES. `gh api user` needs a user-scoped - # token, and github-token defaults to ${{ github.token }} — an + # token, and github-token defaults to the job's github.token — an # installation token, for which that endpoint returns no user. The old # `|| echo "Bot"` fallback was meant to cover that and did not: the call # can exit 0 with no `.type`, so ME_TYPE came back empty, `!= "Bot"` held, @@ -1751,20 +2413,22 @@ runs: echo "github-token belongs to a user, not an app; leaving reactions alone" exit 0 fi - # SAME TRAP AS THE TYPE PROBE, and it survived the fix to that one: with an - # installation token `gh api user` can exit 0 and print nothing, so - # `|| echo` never fires and ME came back EMPTY. The delete filter then read - # `select(.user.login=="")`, matched nothing, and the 👀 stayed on the PR - # for ever while the step reported success. Observed on a clean run that - # placed both 👀 and 👍 and cleared neither. - # - # Test the VALUE, not the exit status. - ME=$(gh api user --jq .login 2>/dev/null) || ME="" - [ -n "$ME" ] || ME="github-actions[bot]" + # WHOSE 👀: the identity funnel's answer (scripts/identity.mjs) — the + # login "Resolve PR refs" resolved, else the one recorded from the + # action's first post in this run. This used to fall back to + # github-actions[bot] for any installation token, which for a custom App + # cleared nothing of its own (and would have cleared the workflow bot's). + # Unknown clears nothing. + ME="${BOT_LOGIN:-}" + if [ -z "$ME" ] && [ -s "$RUNNER_TEMP/cr-identity" ]; then ME=$(cat "$RUNNER_TEMP/cr-identity"); fi + case "$ME" in + ""|*[!A-Za-z0-9\[\]-]*) ME="" ;; + esac # ------------------------------------------------------------------ # 👀 — it said "I am looking at this", and the run has stopped looking. clear_eyes() { + [ -n "$ME" ] || { echo "identity unknown — leaving 👀 at $1"; return 0; } ids=$(gh api "$1" --paginate \ --jq '.[] | select(.content=="eyes") | select(.user.login=="'"$ME"'") | .id' \ 2>/dev/null || true) @@ -1832,11 +2496,13 @@ runs: "$RUNNER_TEMP/result-merged.json" \ "$RUNNER_TEMP/cr-settings.json" "$RUNNER_TEMP/cr-rubric.md" \ "$RUNNER_TEMP/cr-facts.json" "$RUNNER_TEMP/proxy.out" "$RUNNER_TEMP/proxy.err" \ + "$RUNNER_TEMP/cr-upstream-key" "$RUNNER_TEMP/cr-excluded.json" \ "$RUNNER_TEMP/policy-block.json" \ "$RUNNER_TEMP/pr.diff" "$RUNNER_TEMP/diff-guard.json" "$RUNNER_TEMP/prev-summary.md" \ "$RUNNER_TEMP/wallclock-timeout" "$RUNNER_TEMP/judge-unavailable" \ "$RUNNER_TEMP/cr-usage.jsonl" \ - "$RUNNER_TEMP/cr-clean" \ + "$RUNNER_TEMP/cr-clean" "$RUNNER_TEMP/cr-identity" "$RUNNER_TEMP/cr-lockfiles.json" \ "$RUNNER_TEMP/result.l1.json" "$RUNNER_TEMP/result.l2.json" \ "$RUNNER_TEMP/result-extra.l1.json" "$RUNNER_TEMP/result-extra.l2.json" \ "$RUNNER_TEMP/result.l2.log" "$RUNNER_TEMP/result-extra.l2.log" + rm -rf "$RUNNER_TEMP/ocr-engine" diff --git a/bin/orcacode-review.mjs b/bin/orcacode-review.mjs index 605d5b1..4f6640c 100755 --- a/bin/orcacode-review.mjs +++ b/bin/orcacode-review.mjs @@ -46,7 +46,15 @@ const HERE = path.dirname(fileURLToPath(import.meta.url)); const PKG_ROOT = path.resolve(HERE, ".."); const WORKFLOW_REL = ".github/workflows/orca-code-review.yml"; const SECRET = "ORCAROUTER_API_KEY"; -const ACTION_REF = "Continuum-AI-Corp/orca-code-review@v1"; +// The action is pinned to ONE RELEASE COMMIT, never to a tag. A tag can be moved +// by whoever controls the repository, and whatever it points at runs with the +// customer's OrcaRouter key in every repository that pins it. The version rides +// along as a `# vX.Y.Z` comment, which is what Dependabot (github-actions +// ecosystem) reads to offer the next release as a reviewed PR. Bumped at release +// time (RELEASE.md); scripts/release-pin.test.mjs holds every copy to these two. +export const ACTION_SHA = "6d253e0399c84848fedc8801176d6bea77817762"; +export const ACTION_VERSION = "v1.6.0"; +const ACTION_REF = `Continuum-AI-Corp/orca-code-review@${ACTION_SHA}`; const CONSOLE_TOKENS = "https://www.orcarouter.ai/console/token"; const CONSOLE_APPS = "https://www.orcarouter.ai/"; // Two skills ship in this package and the bare command installs both. @@ -342,6 +350,28 @@ const INPUT_NOTES = { "auto-review-authors": "author allowlist for AUTOMATIC reviews", }; +// The answers to "who gets an automatic review?" on a public repository, as +// values EVERY release reads the same way. Both are written out in full: +// - left unset, the pinned release (ACTION_VERSION) reviews everyone, while +// the next one reviews only OWNER,MEMBER,COLLABORATOR on a public repo — +// so "" would change meaning on the upgrade; +// - "*" is everyone to the next release and, to the pinned one, a list +// holding only "*" — no automatic review at all. +// The explicit list of every association is everyone to both. +// scripts/pinned-release.test.mjs runs each value through both releases' gates. +export const EVERY_ASSOCIATION = "OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR,FIRST_TIME_CONTRIBUTOR,FIRST_TIMER,MANNEQUIN,NONE"; +export function authorChoices(t) { + return [ + { + label: t("config.authorsKnown"), + value: "OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR", + recommended: true, + detail: t("config.authorsKnownDetail"), + }, + { label: t("config.authorsAll"), value: EVERY_ASSOCIATION, detail: t("config.authorsAllDetail") }, + ]; +} + export function renderWorkflow(overrides) { const lines = Object.entries(overrides) .filter(([k, v]) => v !== undefined && v !== DEFAULTS[k]) @@ -355,32 +385,42 @@ export function renderWorkflow(overrides) { return `# OrcaCode Review — https://github.com/Continuum-AI-Corp/orca-code-review # # Generated by \`npx orcacode-review\`. The review logic lives in the published -# action, so this file never copies scripts or config — bump the version tag to -# update. Add one repository secret, ${SECRET}, and enable the app at +# action, so this file never copies scripts or config. The action is pinned to a +# release commit (version in the comment); let Dependabot's github-actions +# updates bump it. Add one repository secret, ${SECRET}, and enable the app at # OrcaRouter -> Apps -> OrcaCode Review. name: OrcaCode Review -concurrency: - group: \${{ github.workflow }}-\${{ github.event.pull_request.number || github.event.issue.number || github.ref }} - cancel-in-progress: true - on: - # \`synchronize\` re-reviews on every new push. \`ready_for_review\` makes the - # dashboard's trigger=ready_for_review mode fire when a draft becomes ready. + # \`synchronize\` re-reviews on every new push and \`reopened\` reviews a PR that + # comes back. \`edited\` re-reviews a PR RETARGETED to another base branch (the + # job's \`if:\` ignores title and description edits). \`ready_for_review\` makes + # the dashboard's trigger=ready_for_review mode fire when a draft is ready. pull_request_target: - types: [opened, synchronize, ready_for_review] + types: [opened, synchronize, reopened, ready_for_review, edited] issue_comment: types: [created] permissions: contents: read pull-requests: write - issues: write # tier state label + clean/fallback PR comments + issues: write # clean/fallback PR comments + statuses: write # used from v1.7.0 (unreleased): the verdict on the PR head jobs: review: runs-on: ubuntu-latest + # Concurrency is PER JOB, in two groups. A workflow-level group with + # cancel-in-progress let ANY comment on the PR cancel an in-flight review: + # every comment starts a run in the same group, which then skips. Push runs + # share one group per PR and a newer push supersedes an older one; comment + # runs (/orcacode-review) get their own group and never cancel a running + # review. GitHub keeps one running and one pending job per group, so a newer + # comment does replace a comment run still pending — the latest one runs. + concurrency: + group: \${{ github.workflow }}-\${{ github.event_name == 'issue_comment' && 'comment' || 'pr' }}-\${{ github.event.pull_request.number || github.event.issue.number }} + cancel-in-progress: \${{ github.event_name != 'issue_comment' }} # Run on PR events, or when a trusted user comments the review command on a # PR. All four spellings are accepted — either prefix (\`/\` or \`@\`) with # either separator (hyphen or space). The command runs this privileged @@ -388,7 +428,8 @@ jobs: # maintainers may trigger it — otherwise any participant could burn paid # quota and spam reviews without pushing new commits. if: | - github.event_name == 'pull_request_target' || + (github.event_name == 'pull_request_target' && + (github.event.action != 'edited' || github.event.changes.base)) || (github.event_name == 'issue_comment' && github.event.issue.pull_request && (startsWith(github.event.comment.body, '/orcacode-review') || @@ -397,7 +438,7 @@ jobs: startsWith(github.event.comment.body, '@orcacode review')) && contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association)) steps: - - uses: ${ACTION_REF} + - uses: ${ACTION_REF} # ${ACTION_VERSION} with: ${withBlock} `; @@ -456,18 +497,7 @@ async function askConfig(state, current = DEFAULTS) { if (state.visibility === "PUBLIC") { say(); warn(t("config.publicWarning", CONSOLE_TOKENS)); - out["auto-review-authors"] = await select( - t("config.authorsQ"), - [ - { - label: t("config.authorsKnown"), - value: "OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR", - recommended: true, - detail: t("config.authorsKnownDetail"), - }, - { label: t("config.authorsAll"), value: "", detail: t("config.authorsAllDetail") }, - ], - ); + out["auto-review-authors"] = await select(t("config.authorsQ"), authorChoices(t)); } else if (current["auto-review-authors"]) { out["auto-review-authors"] = current["auto-review-authors"]; } diff --git a/package-lock.json b/package-lock.json index 277f116..d6847f2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,9 +11,710 @@ "bin": { "orcacode-review": "bin/orcacode-review.mjs" }, + "devDependencies": { + "micromark": "4.0.2", + "micromark-extension-gfm": "3.0.0", + "yaml": "2.9.1" + }, "engines": { "node": ">=18.17" } + }, + "node_modules/@types/debug": { + "version": "4.1.13", + "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.13.tgz", + "integrity": "sha512-KSVgmQmzMwPlmtljOomayoR89W4FynCAi3E8PPs7vmDVPe84hT+vGPKkJfThkmXs0x0jAaa9U8uW8bbfyS2fWw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/ms": "*" + } + }, + "node_modules/@types/ms": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", + "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", + "dev": true, + "license": "MIT" + }, + "node_modules/character-entities": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz", + "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==", + "dev": true, + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decode-named-character-reference": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.3.0.tgz", + "integrity": "sha512-GtpQYB283KrPp6nRw50q3U9/VfOutZOe103qlN7BPP6Ad27xYnOIWv4lPzo8HCAL+mMZofJ9KEy30fq6MfaK6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "character-entities": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/dequal": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/dequal/-/dequal-2.0.3.tgz", + "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/devlop": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/devlop/-/devlop-1.1.0.tgz", + "integrity": "sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==", + "dev": true, + "license": "MIT", + "dependencies": { + "dequal": "^2.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wooorm" + } + }, + "node_modules/micromark": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/micromark/-/micromark-4.0.2.tgz", + "integrity": "sha512-zpe98Q6kvavpCr1NPVSCMebCKfD7CA2NqZ+rykeNhONIJBpc1tFKt9hucLGwha3jNTNI8lHpctWJWoimVF4PfA==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "@types/debug": "^4.0.0", + "debug": "^4.0.0", + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-decode-numeric-character-reference": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-core-commonmark": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/micromark-core-commonmark/-/micromark-core-commonmark-2.0.4.tgz", + "integrity": "sha512-wxEeE8v8XVvOrxn1TZj74qYhAtTQsSqufHVS3uNVyT1MupXxhyaHk8/9xDNPh9BmL77QNDgWTkZ3RsYHB2ry7w==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "decode-named-character-reference": "^1.0.0", + "devlop": "^1.0.0", + "micromark-factory-destination": "^2.0.0", + "micromark-factory-label": "^2.0.0", + "micromark-factory-space": "^2.1.0", + "micromark-factory-title": "^2.0.0", + "micromark-factory-whitespace": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-edit-map": "^1.0.0", + "micromark-util-html-tag-name": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-subtokenize": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.3" + } + }, + "node_modules/micromark-extension-gfm": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm/-/micromark-extension-gfm-3.0.0.tgz", + "integrity": "sha512-vsKArQsicm7t0z2GugkCKtZehqUm31oeGBV/KVSorWSy8ZlNAv7ytjFhvaryUiCUJYqs+NoE6AFhpQvBTM6Q4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "micromark-extension-gfm-autolink-literal": "^2.0.0", + "micromark-extension-gfm-footnote": "^2.0.0", + "micromark-extension-gfm-strikethrough": "^2.0.0", + "micromark-extension-gfm-table": "^2.0.0", + "micromark-extension-gfm-tagfilter": "^2.0.0", + "micromark-extension-gfm-task-list-item": "^2.0.0", + "micromark-util-combine-extensions": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-autolink-literal": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-autolink-literal/-/micromark-extension-gfm-autolink-literal-2.1.0.tgz", + "integrity": "sha512-oOg7knzhicgQ3t4QCjCWgTmfNhvQbDDnJeVu9v81r7NltNCVmhPy1fJRX27pISafdjL+SVc4d3l48Gb6pbRypw==", + "dev": true, + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-footnote": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-footnote/-/micromark-extension-gfm-footnote-2.1.0.tgz", + "integrity": "sha512-/yPhxI1ntnDNsiHtzLKYnE3vf9JZ6cAisqVDauhp4CEHxlb4uoOTxOCJ+9s51bIB8U1N1FJ1RXOKTIlD5B/gqw==", + "dev": true, + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-core-commonmark": "^2.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-normalize-identifier": "^2.0.0", + "micromark-util-sanitize-uri": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-strikethrough": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-strikethrough/-/micromark-extension-gfm-strikethrough-2.1.0.tgz", + "integrity": "sha512-ADVjpOOkjz1hhkZLlBiYA9cR2Anf8F4HqZUO6e5eDcPQd0Txw5fxLzzxnEkSkfnD0wziSGiv7sYhk/ktvbf1uw==", + "dev": true, + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-classify-character": "^2.0.0", + "micromark-util-resolve-all": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-table": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-table/-/micromark-extension-gfm-table-2.1.2.tgz", + "integrity": "sha512-pRzm4kDTu0MjlmBkxmS9yYhw60nncfcEwu9NNdPFSQEFXS95ZKyIIyTSHu/o3ReBUrLKYEq+7YaXCRn/bPB4MA==", + "dev": true, + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-tagfilter": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-tagfilter/-/micromark-extension-gfm-tagfilter-2.0.0.tgz", + "integrity": "sha512-xHlTOmuCSotIA8TW1mDIM6X2O1SiX5P9IuDtqGonFhEK0qgRI4yeC6vMxEV2dgyr2TiD+2PQ10o+cOhdVAcwfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-extension-gfm-task-list-item": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-extension-gfm-task-list-item/-/micromark-extension-gfm-task-list-item-2.1.0.tgz", + "integrity": "sha512-qIBZhqxqI6fjLDYFTBIa4eivDMnP+OZqsNwmQ3xNLE4Cxwc+zfQEfbs6tzAo2Hjq+bh6q5F+Z8/cksrLFYWQQw==", + "dev": true, + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/unified" + } + }, + "node_modules/micromark-factory-destination": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-destination/-/micromark-factory-destination-2.0.1.tgz", + "integrity": "sha512-Xe6rDdJlkmbFRExpTOmRj9N3MaWmbAgdpSrBQvCFqhezUn4AHqJHbaEnfbVYYiexVSs//tqOdY/DxhjdCiJnIA==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-label": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-label/-/micromark-factory-label-2.0.1.tgz", + "integrity": "sha512-VFMekyQExqIW7xIChcXn4ok29YE3rnuyveW3wZQWWqF4Nv9Wk5rgJ99KzPvHjkmPXF93FXIbBp6YdW3t71/7Vg==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-space": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-factory-space/-/micromark-factory-space-2.1.0.tgz", + "integrity": "sha512-fS8hnLIjnjvdQIj39Geug8wWsR0HrYZ43KShKxNfwT7t2LOHo/LbWZEzEaSOjwtjdCsjoE6syHhonEzW0zv0+Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-title": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-title/-/micromark-factory-title-2.0.1.tgz", + "integrity": "sha512-5bZ+3CjhAd9eChYTHsjy6TGxpOFSKgKKJPJxr293jTbfry2KDoWkhBb6TcPVB4NmzaPhMs1Frm9AZH7OD4Cjzw==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-factory-whitespace": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-factory-whitespace/-/micromark-factory-whitespace-2.0.1.tgz", + "integrity": "sha512-Ob0nuZ3PKt/n0hORHyvoD9uZhr+Za8sFoP+OnMcnWK5lngSzALgQYKMr9RJVOWLqQYuyn6ulqGWSXdwf6F80lQ==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-factory-space": "^2.0.0", + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-character": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/micromark-util-character/-/micromark-util-character-2.1.1.tgz", + "integrity": "sha512-wv8tdUTJ3thSFFFJKtpYKOYiGP2+v96Hvk4Tu8KpCAsTMs6yi+nVmGh1syvSCsaxz45J6Jbw+9DD6g97+NV67Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-chunked": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-chunked/-/micromark-util-chunked-2.0.1.tgz", + "integrity": "sha512-QUNFEOPELfmvv+4xiNg2sRYeS/P84pTW0TCgP5zc9FpXetHY0ab7SxKyAQCNCc1eK0459uoLI1y5oO5Vc1dbhA==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-classify-character": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-classify-character/-/micromark-util-classify-character-2.0.1.tgz", + "integrity": "sha512-K0kHzM6afW/MbeWYWLjoHQv1sgg2Q9EccHEDzSkxiP/EaagNzCm7T/WMKZ3rjMbvIpvBiZgwR3dKMygtA4mG1Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-combine-extensions": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-combine-extensions/-/micromark-util-combine-extensions-2.0.1.tgz", + "integrity": "sha512-OnAnH8Ujmy59JcyZw8JSbK9cGpdVY44NKgSM7E9Eh7DiLS2E9RNQf0dONaGDzEG9yjEl5hcqeIsj4hfRkLH/Bg==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-chunked": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-decode-numeric-character-reference": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/micromark-util-decode-numeric-character-reference/-/micromark-util-decode-numeric-character-reference-2.0.2.tgz", + "integrity": "sha512-ccUbYk6CwVdkmCQMyr64dXz42EfHGkPQlBj5p7YVGzq8I7CtjXZJrubAYezf7Rp+bjPseiROqe7G6foFd+lEuw==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-edit-map": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/micromark-util-edit-map/-/micromark-util-edit-map-1.0.0.tgz", + "integrity": "sha512-Pa2ljlsEL6sVwFaYeyrOLSYbQt73JvGbPOYFq+9AElXiSnfI5Q4465RRZ1sHv7lDjDOnGRDDaqPXqClqWK/q1Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-encode": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-encode/-/micromark-util-encode-2.0.1.tgz", + "integrity": "sha512-c3cVx2y4KqUnwopcO9b/SCdo2O67LwJJ/UyqGfbigahfegL9myoEFoDYZgkT7f36T0bLrM9hZTAaAyH+PCAXjw==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-html-tag-name": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-html-tag-name/-/micromark-util-html-tag-name-2.0.1.tgz", + "integrity": "sha512-2cNEiYDhCWKI+Gs9T0Tiysk136SnR13hhO8yW6BGNyhOC4qYFnwF1nKfD3HFAIXA5c45RrIG1ub11GiXeYd1xA==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-normalize-identifier": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-normalize-identifier/-/micromark-util-normalize-identifier-2.0.1.tgz", + "integrity": "sha512-sxPqmo70LyARJs0w2UclACPUUEqltCkJ6PhKdMIDuJ3gSf/Q+/GIe3WKl0Ijb/GyH9lOpUkRAO2wp0GVkLvS9Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-resolve-all": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-resolve-all/-/micromark-util-resolve-all-2.0.1.tgz", + "integrity": "sha512-VdQyxFWFT2/FGJgwQnJYbe1jjQoNTS4RjglmSjTUlpUMa95Htx9NHeYW4rGDJzbjvCsl9eLjMQwGeElsqmzcHg==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-sanitize-uri": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-sanitize-uri/-/micromark-util-sanitize-uri-2.0.1.tgz", + "integrity": "sha512-9N9IomZ/YuGGZZmQec1MbgxtlgougxTodVwDzzEouPKo3qFWvymFHWcnDi2vzV1ff6kas9ucW+o3yzJK9YB1AQ==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "micromark-util-character": "^2.0.0", + "micromark-util-encode": "^2.0.0", + "micromark-util-symbol": "^2.0.0" + } + }, + "node_modules/micromark-util-subtokenize": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/micromark-util-subtokenize/-/micromark-util-subtokenize-2.1.0.tgz", + "integrity": "sha512-XQLu552iSctvnEcgXw6+Sx75GflAPNED1qx7eBJ+wydBb2KCbRZe+NwvIEEMM83uml1+2WSXpBAcp9IUCgCYWA==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT", + "dependencies": { + "devlop": "^1.0.0", + "micromark-util-chunked": "^2.0.0", + "micromark-util-symbol": "^2.0.0", + "micromark-util-types": "^2.0.0" + } + }, + "node_modules/micromark-util-symbol": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/micromark-util-symbol/-/micromark-util-symbol-2.0.1.tgz", + "integrity": "sha512-vs5t8Apaud9N28kgCrRUdEed4UJ+wWNvicHLPxCa9ENlYuAY31M0ETy5y1vA33YoNPDFTghEbnh6efaE8h4x0Q==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/micromark-util-types": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/micromark-util-types/-/micromark-util-types-2.0.3.tgz", + "integrity": "sha512-oxB2Ik03hI0gv+VNn9tnh1t1YEe9MDPptViAEgfdf3YQHsn0pzGTgCdlSCJXcwhqm8phaEuM7zeEu3QQzVBrPg==", + "dev": true, + "funding": [ + { + "type": "GitHub Sponsors", + "url": "https://github.com/sponsors/unifiedjs" + }, + { + "type": "OpenCollective", + "url": "https://opencollective.com/unified" + } + ], + "license": "MIT" + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/yaml": { + "version": "2.9.1", + "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz", + "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==", + "dev": true, + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14.6" + }, + "funding": { + "url": "https://github.com/sponsors/eemeli" + } } } } diff --git a/package.json b/package.json index a6d3b07..8aa8aa2 100644 --- a/package.json +++ b/package.json @@ -42,5 +42,10 @@ "license": "MIT", "publishConfig": { "access": "public" + }, + "devDependencies": { + "micromark": "4.0.2", + "micromark-extension-gfm": "3.0.0", + "yaml": "2.9.1" } } diff --git a/scripts/action-hygiene.test.mjs b/scripts/action-hygiene.test.mjs new file mode 100644 index 0000000..e03c91d --- /dev/null +++ b/scripts/action-hygiene.test.mjs @@ -0,0 +1,83 @@ +// Hygiene invariants for action.yml's own scripts: what GitHub writes into the +// step script on disk, and what a credential may appear in. +// +// GitHub expands every `${{ … }}` in a `run:` (and in a github-script +// `script:`) BEFORE the shell or node sees it — comments included, since the +// expander does not know bash. A comment that merely NAMES `${{ github.token }}` +// therefore writes the live token into the step script under $RUNNER_TEMP. So +// the rule is absolute: expressions reach code only through `env:`. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { actionSteps, step, shellCommentLines, runBashStep, stub } from "./test-helpers/action-yaml.mjs"; + +const bodyOf = (s) => s.run ?? s.with?.script ?? ""; + +describe("action.yml: no ${{ }} expression inside step code", () => { + test("no comment line of any run: script carries ${{", () => { + const offenders = []; + for (const s of actionSteps()) { + if (!s.run) continue; + for (const { n, line } of shellCommentLines(s.run)) { + if (line.includes("${{")) offenders.push(`${s.name || s.id}: line ${n}: ${line.trim()}`); + } + } + assert.deepEqual(offenders, [], "a comment naming an expression gets it expanded onto disk"); + }); + + test("no run: or script: body carries ${{ at all — expressions arrive through env:", () => { + const steps = actionSteps().filter((s) => bodyOf(s)); + assert.ok(steps.length > 10, "the parser found almost no step bodies — is this test hollow?"); + const offenders = steps.filter((s) => bodyOf(s).includes("${{")).map((s) => s.name || s.id); + assert.deepEqual(offenders, []); + }); +}); + +describe("action.yml: the PR-head fetch keeps the token off argv", () => { + const TOKEN = "ghs_FAKEtoken0123456789abcdefABCDEF"; + + function runFetch() { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fetch-step-")); + try { + const log = path.join(dir, "git.log"); + // The stub records argv one per line, then every GIT_CONFIG_* variable + // and the whole environment, so the test can tell where the header went. + stub( + dir, + "git", + `{ echo "ARGV"; for a in "$@"; do printf '%s\\n' "$a"; done; echo "ENV"; env | grep '^GIT_CONFIG_' | sort; } >> "${log}"`, + ); + const r = runBashStep(step("Fetch PR head (covers fork PRs)").run, { + env: { GH_TOKEN: TOKEN, PR_NUMBER: "42", GITHUB_SERVER_URL: "https://github.com" }, + stubDir: dir, + }); + assert.equal(r.status, 0, r.stderr); + return fs.readFileSync(log, "utf8"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + } + + test("git's argv holds neither the token nor its Basic-auth encoding", () => { + const out = runFetch(); + const argv = out.slice(out.indexOf("ARGV"), out.indexOf("ENV")); + const basic = Buffer.from(`x-access-token:${TOKEN}`).toString("base64"); + assert.ok(argv.includes("fetch"), "the stub never saw a fetch — is the test hollow?"); + assert.ok(!argv.includes(TOKEN), "the raw token is on git's command line"); + assert.ok(!argv.includes(basic), "the encoded token is on git's command line"); + assert.ok(!/extraheader/i.test(argv), "an extraheader is still passed with -c"); + }); + + test("the auth header travels in GIT_CONFIG_* env, scoped to the server", () => { + const out = runFetch(); + const env = out.slice(out.indexOf("ENV")); + const basic = Buffer.from(`x-access-token:${TOKEN}`).toString("base64"); + assert.match(env, /^GIT_CONFIG_COUNT=1$/m); + assert.match(env, /^GIT_CONFIG_KEY_0=http\.https:\/\/github\.com\/\.extraheader$/m); + assert.ok(env.includes(`GIT_CONFIG_VALUE_0=AUTHORIZATION: basic ${basic}`), env); + }); +}); diff --git a/scripts/comment-sha.test.mjs b/scripts/comment-sha.test.mjs new file mode 100644 index 0000000..e89845a --- /dev/null +++ b/scripts/comment-sha.test.mjs @@ -0,0 +1,147 @@ +// CR-12: a maintainer's /orcacode-review reviewed whatever head the PR had when +// the run started. On a fork PR the fork's owner can push between the +// maintainer reading the change and the review running — the maintainer +// approves spend on code they never saw, and the verdict lands on it. +// +// Now, when the PR's head lives in another repository (a fork, or a fork that +// was deleted), the command must name the commit: `/orcacode-review ` +// with at least 7 hex characters. The action reviews exactly that commit, and +// only if it is still the PR's head; otherwise it refuses with a comment that +// says what the head is now and how to re-run. A same-repository PR keeps the +// bare command (only people with push access can move its head); a commit it +// names is held to the same check. + +import path from "node:path"; +import { describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { step, runGithubScript, fakeCore, ROOT } from "./test-helpers/action-yaml.mjs"; + +const HEAD = "a1b2c3d4e5f60718293a4b5c6d7e8f9012345678"; +const OLD = "ffffeeee11112222333344445555666677778888"; + +async function command(body, { head = "outsider/widgets", sha = HEAD, assoc = "MEMBER" } = {}) { + const posted = []; + const github = { + rest: { + pulls: { + get: async () => ({ + data: { + number: 7, + user: { login: "outsider" }, + author_association: "NONE", + draft: false, + base: { ref: "main", repo: { full_name: "acme/widgets" } }, + head: { sha, repo: head ? { full_name: head } : null }, + }, + }), + }, + users: { getAuthenticated: async () => { throw Object.assign(new Error("no"), { status: 403 }); } }, + issues: { createComment: async (a) => (posted.push(a), { data: { user: { login: "github-actions[bot]" } } }) }, + }, + }; + const { core, rec } = fakeCore(); + await runGithubScript(step("pr").with.script, { + github, + core, + context: { + eventName: "issue_comment", + payload: { + action: "created", + issue: { number: 7, pull_request: { url: "x" } }, + comment: { id: 1, body, author_association: assoc }, + repository: { default_branch: "main", private: false }, + }, + repo: { owner: "acme", repo: "widgets" }, + issue: { number: 7 }, + }, + env: { + IDENTITY: path.join(ROOT, "scripts", "identity.mjs"), + PUBLISH_GUARD: path.join(ROOT, "scripts", "publish-guard.mjs"), + TOKEN_IS_JOB_TOKEN: "true", + BOT_LOGIN_INPUT: "", + BRAND: "OrcaCode Review", + }, + }); + return { rec, posted }; +} + +describe("a same-repository PR keeps the bare command", () => { + test("bare -> reviews the head", async () => { + const { rec, posted } = await command("/orcacode-review", { head: "acme/widgets" }); + assert.equal(rec.outputs.run, "true"); + assert.equal(rec.outputs.head_sha, HEAD); + assert.equal(posted.length, 0); + }); + + test("words after the command are not a commit", async () => { + assert.equal((await command("@orcacode review please", { head: "acme/widgets" })).rec.outputs.run, "true"); + }); + + test("a commit it names must still be the head", async () => { + assert.equal((await command(`/orcacode-review ${HEAD.slice(0, 7)}`, { head: "acme/widgets" })).rec.outputs.run, "true"); + const stale = await command(`/orcacode-review ${OLD.slice(0, 9)}`, { head: "acme/widgets" }); + assert.equal(stale.rec.outputs.run, "false"); + assert.equal(stale.posted.length, 1); + }); +}); + +describe("a fork PR's command must name the commit, and it must still be the head", () => { + for (const given of [HEAD.slice(0, 7), HEAD.slice(0, 12).toUpperCase(), HEAD]) { + test(`/orcacode-review ${given} -> reviews exactly ${HEAD.slice(0, 7)}…`, async () => { + const { rec, posted } = await command(`/orcacode-review ${given}`); + assert.equal(rec.outputs.run, "true"); + assert.equal(rec.outputs.head_sha, HEAD, "the full SHA the checkout pins"); + assert.equal(posted.length, 0); + }); + } + + test("every spelling of the command takes the commit", async () => { + for (const cmd of ["/orcacode review", "@orcacode-review", "@orcacode review"]) { + assert.equal((await command(`${cmd} ${HEAD.slice(0, 8)}`)).rec.outputs.run, "true", cmd); + } + }); + + test("the bare command -> refused, with a comment naming the head and the command to use", async () => { + const { rec, posted } = await command("/orcacode-review"); + assert.equal(rec.outputs.run, "false"); + assert.equal(rec.failed, null, "a refusal is not a failed job"); + assert.match(rec.outputs.stop_reason, /fork/); + assert.equal(posted.length, 1); + assert.match(posted[0].body, new RegExp(`/orcacode-review ${HEAD.slice(0, 7)}`)); + assert.match(posted[0].body, /fork/i); + }); + + test("a commit that is no longer the head -> refused, saying what the head is now", async () => { + const { rec, posted } = await command(`/orcacode-review ${OLD.slice(0, 7)}`); + assert.equal(rec.outputs.run, "false"); + assert.match(posted[0].body, /no longer/i); + assert.match(posted[0].body, new RegExp(OLD.slice(0, 7))); + assert.match(posted[0].body, new RegExp(`/orcacode-review ${HEAD.slice(0, 7)}`)); + }); + + for (const arg of [HEAD.slice(0, 6), "please", "a1b2c3d!", `${HEAD}0`]) { + test(`"${arg}" is not a commit -> refused`, async () => { + assert.equal((await command(`/orcacode-review ${arg}`)).rec.outputs.run, "false"); + }); + } + + test("a deleted fork counts as a fork", async () => { + assert.equal((await command("/orcacode-review", { head: null })).rec.outputs.run, "false"); + assert.equal((await command(`/orcacode-review ${HEAD.slice(0, 7)}`, { head: null })).rec.outputs.run, "true"); + }); + + test("an outsider's command is still refused before any of this (and nothing is posted)", async () => { + const { rec, posted } = await command(`/orcacode-review ${HEAD.slice(0, 7)}`, { assoc: "NONE" }); + assert.equal(rec.outputs.run, "false"); + assert.equal(posted.length, 0); + }); + + test("the refusal is posted through the publish funnel", () => { + const env = step("pr").env; + assert.equal(env.PUBLISH_GUARD, "${{ github.action_path }}/scripts/publish-guard.mjs"); + assert.equal(env.CR_REDACT_API_KEY, "${{ inputs.orcarouter-api-key }}"); + assert.equal(env.CR_REDACT_GITHUB_TOKEN, "${{ inputs.github-token }}"); + assert.match(step("pr").with.script, /guard\.guardGithub\(github\)/); + }); +}); diff --git a/scripts/doc-drift.test.mjs b/scripts/doc-drift.test.mjs new file mode 100644 index 0000000..39ddb2c --- /dev/null +++ b/scripts/doc-drift.test.mjs @@ -0,0 +1,117 @@ +// Docs that restate what the code does, held to the code. +// +// - skills/orca-review-action/references/inputs.md lists every input with its +// default; the skill tells agents to read it "before answering a question +// about behavior — do not guess a default". Its judge-model default named a +// model the action has not defaulted to for several releases. Every row is +// now compared with action.yml. +// - the github-token row left out what the token is used for from v1.7.0: +// writing the commit status on the PR head. +// - publish.yml's fetch-depth comment named a "v1 tag check" that no longer +// exists; what needs the history is the pinned-commit check. +// - "comment runs never cancel anything": GitHub keeps at most one RUNNING and +// one PENDING job per concurrency group, and a newly queued job cancels the +// pending one even with cancel-in-progress off. So a comment never cancels a +// running review, but a third comment replaces a second one still waiting. +// Every place that says "never cancel" has to say that. + +import { describe, test } from "node:test"; +import assert from "node:assert/strict"; +import YAML from "yaml"; + +import { loadAction, readText, shippedWorkflows } from "./test-helpers/action-yaml.mjs"; +import { docUnits } from "./doc-pins.mjs"; + +const INPUTS_MD = "skills/orca-review-action/references/inputs.md"; + +// Every `| \`name\` | default | what |` row of inputs.md's input tables. +function inputRows() { + const rows = new Map(); + for (const line of readText(INPUTS_MD).split("\n")) { + const m = line.match(/^\|\s*`([a-z-]+)`\s*\|\s*(.*?)\s*\|\s*(.*)\|\s*$/); + if (m) rows.set(m[1], { def: m[2], what: m[3] }); + } + return rows; +} + +describe("inputs.md matches action.yml", () => { + const inputs = loadAction().inputs; + + test("every input has a row (and every row is an input)", () => { + const rows = inputRows(); + const dashboardOnly = new Set(["auto_review", "trigger", "exhaustive", "quiet", "rubric"]); + assert.deepEqual([...rows.keys()].filter((k) => !dashboardOnly.has(k)).sort(), Object.keys(inputs).sort()); + }); + + test("every default a row states as a value is action.yml's default", () => { + const rows = inputRows(); + let compared = 0; + for (const [name, spec] of Object.entries(inputs)) { + const { def } = rows.get(name); + const code = def.match(/^`([^`]*)`(?: \(engine default\))?$/); + const actual = spec.default === undefined ? undefined : String(spec.default); + if (def === "—") { + assert.equal(spec.required, true, `${name}: inputs.md says there is no default`); + } else if (code) { + const stated = code[1] === '""' ? "" : code[1]; + assert.equal(stated, actual, `${name}: inputs.md says ${def}, action.yml says ${JSON.stringify(actual)}`); + compared += 1; + } + } + assert.ok(compared >= 15, `only ${compared} defaults compared — the row parser is not reading the tables`); + }); + + test("judge-model: the default is empty — the router's recipe picks the judge", () => { + assert.equal(inputs["judge-model"].default, ""); + assert.match(inputRows().get("judge-model").def, /^`""`$/); + }); + + test("github-token: the row says it also writes the commit status (statuses: write)", () => { + assert.match(inputs["github-token"].description, /commit status/); + const { what } = inputRows().get("github-token"); + assert.match(what, /commit status/); + assert.match(what, /statuses: write/); + }); +}); + +describe("publish.yml says why it fetches the full history", () => { + test("the fetch-depth comment names the pinned-commit check, not a v1 tag check", () => { + const doc = YAML.parseDocument(readText(".github/workflows/publish.yml")); + let comment = null; + YAML.visit(doc, { + Pair(_, pair) { + if (YAML.isScalar(pair.key) && pair.key.value === "fetch-depth") comment = String(pair.value.comment || ""); + }, + }); + assert.ok(comment, "no fetch-depth comment"); + assert.doesNotMatch(comment, /v1 tag/); + assert.match(comment, /ACTION_SHA|pinned/); + }); +}); + +describe('"never cancel" is said precisely', () => { + const claims = async () => { + const out = []; + const docs = [ + ["README.md", readText("README.md")], + ["SECURITY.md", readText("SECURITY.md")], + ...(await shippedWorkflows()).map((w) => [w.name, w.text]), + ]; + for (const [name, text] of docs) { + for (const u of docUnits(name.endsWith(".md") ? name : `${name}.yml`, text)) { + if (/never cancel|cannot cancel/i.test(u.text)) out.push({ name, line: u.line, text: u.text }); + } + } + return out; + }; + + test("the docs make the claim (the check is not hollow)", async () => { + assert.ok((await claims()).length >= 4); + }); + + test("every such claim says a newer comment replaces a PENDING one", async () => { + for (const c of await claims()) { + assert.match(c.text, /pending/i, `${c.name}:${c.line}: ${c.text.slice(0, 160)}`); + } + }); +}); diff --git a/scripts/doc-pins.mjs b/scripts/doc-pins.mjs new file mode 100644 index 0000000..61a24b2 --- /dev/null +++ b/scripts/doc-pins.mjs @@ -0,0 +1,198 @@ +#!/usr/bin/env node +// Keep what we publish true of the release we pin. +// +// Everything this repository hands a customer pins ONE release of the action +// (ACTION_SHA / ACTION_VERSION in bin/orcacode-review.mjs). main moves ahead of +// it, so a doc on main can describe behaviour the pinned release does not have. +// Two rules, used by scripts/pinned-release.test.mjs on every PR and by the +// publish workflow on the packed tarball: +// +// 1. A doc unit (a paragraph, list item, table row, code line, or a YAML +// comment block) that describes unreleased behaviour carries MARKER, or +// sits under a heading that does. +// 2. No published doc names an action version newer than the pin, except as +// that marker. +// +// node scripts/doc-pins.mjs --pack +// checks rule 2 over every README / skills file in the tarball, exits 1 +// (with ::error:: annotations) if any names a newer version. + +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +// The next release. Bump with the release that ships it: once ACTION_VERSION +// reaches it, scripts/pinned-release.test.mjs refuses the marker everywhere. +export const UNRELEASED = "v1.7.0"; +export const MARKER = `from ${UNRELEASED} (unreleased)`; + +// The docs the npm tarball carries that describe the action. +export const PUBLISHED_DOCS = [ + "README.md", + "skills/orca-review-action/SKILL.md", + "skills/orca-review-action/references/inputs.md", + "skills/orca-review-action/references/troubleshooting.md", + "skills/orca-review-action/assets/workflow.yml", + "skills/orca-review/SKILL.md", + "skills/orca-review/references/contract.md", +]; + +const parse = (v) => { + const m = String(v).match(/^v?(\d+)\.(\d+)\.(\d+)$/); + if (!m) throw new Error(`not a version: ${v}`); + return m.slice(1).map(Number); +}; + +export function compareVersions(a, b) { + const [x, y] = [parse(a), parse(b)]; + for (let i = 0; i < 3; i += 1) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1; + return 0; +} + +// --------------------------------------------------------------------- units + +function markdownUnits(text) { + const units = []; + const headings = []; + let cur = null; + let fence = null; + const flush = () => { + if (cur) units.push(cur); + cur = null; + }; + const unit = (line, n) => ({ text: line, line: n, headings: headings.map((h) => h.text) }); + text.split("\n").forEach((line, i) => { + const n = i + 1; + if (fence) { + if (new RegExp(`^ {0,3}${fence}`).test(line)) fence = null; + else units.push(unit(line, n)); // every code line is a unit of its own + return; + } + const open = line.match(/^ {0,3}(`{3,}|~{3,})/); + if (open) { + flush(); + fence = open[1][0] === "`" ? "`{3,}" : "~{3,}"; + return; + } + const h = line.match(/^ {0,3}(#{1,6})\s+(.*)$/); + if (h) { + flush(); + while (headings.length && headings[headings.length - 1].level >= h[1].length) headings.pop(); + headings.push({ level: h[1].length, text: h[2] }); + units.push(unit(line, n)); + return; + } + if (!line.trim()) return flush(); + if (/^\s*\|/.test(line)) { + flush(); + units.push(unit(line, n)); // a table row + return; + } + if (/^\s*([-*+]|\d+[.)])\s+/.test(line)) { + flush(); + cur = unit(line, n); // a list item, with its continuation lines + return; + } + if (cur) cur.text += `\n${line}`; + else cur = unit(line, n); + }); + flush(); + return units; +} + +function yamlUnits(text) { + const units = []; + let cur = null; + const flush = () => { + if (cur) units.push(cur); + cur = null; + }; + text.split("\n").forEach((line, i) => { + const n = i + 1; + if (/^\s*#/.test(line)) { + if (/^\s*#\s*$/.test(line)) return flush(); // a blank comment line ends a block + if (cur) cur.text += `\n${line}`; + else cur = { text: line, line: n, headings: [] }; + return; + } + flush(); + if (line.trim()) units.push({ text: line, line: n, headings: [] }); // with its trailing comment + }); + flush(); + return units; +} + +/** A doc split into the units rule 1 is applied to (`text` folded to one line). */ +export function docUnits(name, text) { + return (/\.md$/i.test(name) ? markdownUnits(text) : yamlUnits(text)).map((u) => ({ ...u, text: flat(u.text) })); +} + +// The marker, at the start of a sentence too ("From v1.7.0 (unreleased)"). +const hasMarker = (t) => t.toLowerCase().includes(MARKER); + +// A unit as one line of prose: comment markers and line breaks folded, so a +// phrase or the marker broken across lines is still found. +const flat = (t) => t.replace(/\n[ \t]*(#[ \t]?)?/g, " ").replace(/^[ \t]*#[ \t]?/, "").replace(/[ \t]+/g, " "); + +/** Units that mention one of `terms` ([RegExp, label] pairs) without the marker. */ +export function unmarkedMentions(name, text, terms) { + const out = []; + for (const u of docUnits(name, text)) { + const line = flat(u.text); + const hit = terms.find(([re]) => re.test(line)); + if (!hit) continue; + if (hasMarker(line) || u.headings.some(hasMarker)) continue; + out.push(`${name}:${u.line}: ${hit[1]} — ${u.text.split("\n")[0].trim().slice(0, 100)}`); + } + return out; +} + +/** Action versions newer than `pin` that `text` names other than as MARKER. */ +export function newerVersionRefs(text, pin) { + const out = []; + for (const m of String(text).matchAll(/\bv1\.\d+\.\d+\b/g)) { + if (compareVersions(m[0], pin) <= 0) continue; + const start = m.index - "from ".length; + if (start >= 0 && text.slice(start, start + MARKER.length).toLowerCase() === MARKER) continue; + out.push(m[0]); + } + return out; +} + +// ----------------------------------------------------------------------- CLI + +const HERE = path.dirname(fileURLToPath(import.meta.url)); + +async function main() { + const argv = process.argv.slice(2); + const i = argv.indexOf("--pack"); + if (i < 0 || !argv[i + 1]) { + console.error("usage: node scripts/doc-pins.mjs --pack "); + process.exit(2); + } + const root = path.resolve(HERE, ".."); + const { ACTION_VERSION } = await import(pathToFileURL(path.join(root, "bin", "orcacode-review.mjs")).href); + const pack = JSON.parse(fs.readFileSync(argv[i + 1], "utf8")); + const files = pack[0].files + .map((f) => f.path) + .filter((p) => (p === "README.md" || p.startsWith("skills/")) && /\.(md|ya?ml)$/i.test(p)); + if (!files.includes("README.md")) { + console.error("::error::the tarball has no README.md — the doc check would be checking nothing"); + process.exit(1); + } + let bad = 0; + for (const p of files) { + const refs = newerVersionRefs(fs.readFileSync(path.join(root, p), "utf8"), ACTION_VERSION); + if (refs.length) { + bad += 1; + console.log( + `::error file=${p}::names ${[...new Set(refs)].join(", ")}, newer than the pinned ${ACTION_VERSION}. ` + + `Mark unreleased behaviour "${MARKER}", or release and bump the pin first (RELEASE.md).`, + ); + } + } + if (bad) process.exit(1); + console.log(`docs ok — ${files.length} published doc(s) name nothing newer than ${ACTION_VERSION} outside "${MARKER}"`); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) await main(); diff --git a/scripts/engine-pins.json b/scripts/engine-pins.json new file mode 100644 index 0000000..4529734 --- /dev/null +++ b/scripts/engine-pins.json @@ -0,0 +1,23 @@ +{ + "1.3.13": { + "integrity": "sha512-XAWyBlKOcf/wIspLc2FHo4iVV9XF2lxpSI/jGhOkXxFOmYnw+mnL5nXc0U+QyJBfVi9vmvTirQ0/Y3NfyrXwjQ==", + "binaries": { + "linux-x64": { + "url": "https://github.com/alibaba/open-code-review/releases/download/v1.3.13/opencodereview-linux-amd64", + "sha256": "6d51ce0b18236e6c13ab24f38f70e861052439d2c675311f58fbd85e0194fd81" + }, + "linux-arm64": { + "url": "https://github.com/alibaba/open-code-review/releases/download/v1.3.13/opencodereview-linux-arm64", + "sha256": "e78b69718554ff3c4db7a90e30705ddb4100a2541025e384566dfc0b092fd5b3" + }, + "darwin-x64": { + "url": "https://github.com/alibaba/open-code-review/releases/download/v1.3.13/opencodereview-darwin-amd64", + "sha256": "61aa4d18b5acaa7a9624ee3f4c6200806ceee0cf11d6141789ebeaeb48fb30b9" + }, + "darwin-arm64": { + "url": "https://github.com/alibaba/open-code-review/releases/download/v1.3.13/opencodereview-darwin-arm64", + "sha256": "27b2a821d5ed633cf20565d97f126da9a08274eddc039c2bfdb8c5408f439077" + } + } + } +} diff --git a/scripts/events.test.mjs b/scripts/events.test.mjs new file mode 100644 index 0000000..f49f0ee --- /dev/null +++ b/scripts/events.test.mjs @@ -0,0 +1,277 @@ +// Which events the action acts on, who may spend the key, and what the shipped +// workflows trigger on — run through the YAML parser, with the action's own +// code executed against GitHub doubles. +// +// CR-12 The action used to trust the workflow's `if:` to keep outsiders' +// comments out; the README quickstart showed a bare `uses:` with no +// such `if:`. "Resolve PR refs" now refuses an issue_comment run +// unless it is on a pull request, its body is the review command, and +// the commenter is OWNER/MEMBER/COLLABORATOR — whatever the workflow. +// CR-2 auto-review-authors defaulted to everyone, so on a PUBLIC repo any +// fork PR spent the workspace's wallet. Unset now means +// OWNER,MEMBER,COLLABORATOR on a public repo (and when visibility is +// unknown); private repos keep "everyone"; "*" opts back in to everyone. +// CR-5 An `edited` PR event runs only when the base changed (a retarget +// re-reviews; a title edit does not) — see workflows.test.mjs for the +// triggers the shipped workflows add. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { step, actionSteps, runBashStep, runGithubScript, fakeCore, ROOT } from "./test-helpers/action-yaml.mjs"; + +let dir; +before(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "events-")); +}); +after(() => fs.rmSync(dir, { recursive: true, force: true })); + +// ------------------------------------------------------------ Resolve PR refs + +async function resolve(eventName, payload) { + const { core, rec } = fakeCore(); + const github = { + rest: { + pulls: { + // A same-repository PR: a fork's command must name its commit + // (comment-sha.test.mjs). + get: async () => ({ + data: { base: { ref: "main" }, head: { sha: "headsha", repo: { full_name: "acme/widgets" } }, draft: false, author_association: "NONE" }, + }), + }, + }, + }; + const context = { + eventName, + payload: { repository: { default_branch: "main", private: false }, ...payload }, + repo: { owner: "acme", repo: "widgets" }, + issue: { number: payload.issue?.number ?? payload.pull_request?.number ?? 0 }, + }; + await runGithubScript(step("pr").with.script, { + github, + context, + core, + env: { IDENTITY: path.join(ROOT, "scripts", "identity.mjs"), TOKEN_IS_JOB_TOKEN: "true", BOT_LOGIN_INPUT: "" }, + }); + return rec; +} + +const prEvent = (action, extra = {}) => ({ + action, + pull_request: { + number: 7, + base: { ref: "main" }, + head: { sha: "headsha" }, + draft: false, + author_association: "CONTRIBUTOR", + }, + ...extra, +}); +const commentEvent = (body, association, onPr = true) => ({ + action: "created", + issue: { number: 7, ...(onPr ? { pull_request: { url: "x" } } : {}) }, + comment: { id: 1, body, author_association: association }, +}); + +describe("Resolve PR refs: only a maintainer's review command on a PR runs a comment-triggered review", () => { + for (const cmd of ["/orcacode-review", "/orcacode review", "@orcacode-review", "@orcacode review please"]) { + test(`MEMBER "${cmd}" -> runs`, async () => { + const rec = await resolve("issue_comment", commentEvent(cmd, "MEMBER")); + assert.equal(rec.outputs.run, "true"); + assert.equal(rec.outputs.head_sha, "headsha"); + }); + } + + for (const assoc of ["NONE", "CONTRIBUTOR", "FIRST_TIME_CONTRIBUTOR", "FIRST_TIMER", "MANNEQUIN", ""]) { + test(`${assoc || "(missing)"} "/orcacode-review" -> refused`, async () => { + const rec = await resolve("issue_comment", commentEvent("/orcacode-review", assoc)); + assert.equal(rec.outputs.run, "false"); + assert.equal(rec.failed, null, "a refusal is a no-op, not a failed job"); + }); + } + + test("a maintainer's ordinary comment -> no run", async () => { + assert.equal((await resolve("issue_comment", commentEvent("LGTM, merging", "OWNER"))).outputs.run, "false"); + }); + + test("a near-miss command (/orcacode-reviewer) -> no run", async () => { + assert.equal((await resolve("issue_comment", commentEvent("/orcacode-reviewer", "OWNER"))).outputs.run, "false"); + }); + + test("the command on a plain issue (not a PR) -> no run", async () => { + assert.equal((await resolve("issue_comment", commentEvent("/orcacode-review", "OWNER", false))).outputs.run, "false"); + }); +}); + +describe("Resolve PR refs: pull_request_target events", () => { + for (const action of ["opened", "synchronize", "reopened", "ready_for_review"]) { + test(`${action} -> runs`, async () => { + assert.equal((await resolve("pull_request_target", prEvent(action))).outputs.run, "true"); + }); + } + + test("edited without a base change (title, body) -> no run", async () => { + const rec = await resolve("pull_request_target", prEvent("edited", { changes: { title: { from: "x" } } })); + assert.equal(rec.outputs.run, "false"); + }); + + test("edited with a base change (retargeted) -> runs against the new base", async () => { + const rec = await resolve("pull_request_target", prEvent("edited", { changes: { base: { ref: { from: "old" } } } })); + assert.equal(rec.outputs.run, "true"); + assert.equal(rec.outputs.base, "main"); + }); + + test("repository visibility is passed on ('true' only for a private repo)", async () => { + assert.equal((await resolve("pull_request_target", prEvent("opened"))).outputs.repo_private, "false"); + const priv = await resolve("pull_request_target", { ...prEvent("opened"), repository: { default_branch: "main", private: true } }); + assert.equal(priv.outputs.repo_private, "true"); + }); +}); + +// CR-10: only issue_comment went through the comment refusal; every other event +// fell into the pull_request* auto-review gate, keyed on the PR AUTHOR — so a +// workflow listening to pull_request_review_comment or pull_request_review ran +// a paid review on a maintainer's PR whenever anyone commented a review. The +// action now runs on an explicit allowlist and refuses everything else as a +// successful no-op that says why. +describe("Resolve PR refs: an explicit allowlist of events", () => { + const ALLOWED = []; + for (const ev of ["pull_request", "pull_request_target"]) { + for (const action of ["opened", "synchronize", "reopened", "ready_for_review"]) ALLOWED.push([ev, prEvent(action)]); + } + for (const [ev, payload] of ALLOWED) { + test(`${ev}/${payload.action} -> runs`, async () => { + assert.equal((await resolve(ev, payload)).outputs.run, "true"); + }); + } + + const reviewPayload = { + action: "submitted", + review: { id: 9, body: "LGTM", user: { login: "outsider" }, author_association: "NONE" }, + pull_request: prEvent("x").pull_request, + }; + const reviewCommentPayload = { + action: "created", + comment: { id: 9, body: "nit", user: { login: "outsider" }, author_association: "NONE" }, + pull_request: prEvent("x").pull_request, + }; + const REFUSED = [ + ["pull_request_review", reviewPayload], + ["pull_request_review_comment", reviewCommentPayload], + ["pull_request_target", prEvent("closed")], + ["pull_request_target", prEvent("labeled")], + ["pull_request_target", prEvent("assigned")], + ["pull_request", prEvent("converted_to_draft")], + ["issue_comment", { ...commentEvent("/orcacode-review", "OWNER"), action: "edited" }], + ["issue_comment", { ...commentEvent("/orcacode-review", "OWNER"), action: "deleted" }], + ["push", { ref: "refs/heads/main" }], + ["workflow_dispatch", {}], + ["schedule", {}], + ["merge_group", {}], + ]; + for (const [ev, payload] of REFUSED) { + test(`${ev}${payload.action ? `/${payload.action}` : ""} -> refused, successfully, saying why`, async () => { + const rec = await resolve(ev, payload); + assert.equal(rec.outputs.run, "false"); + assert.equal(rec.failed, null, "a refusal is a no-op, not a failed job"); + assert.match(rec.outputs.stop_reason, new RegExp(ev)); + assert.ok(rec.notices.some((n) => n.includes(ev)), rec.notices.join("\n")); + }); + } +}); + +describe("every step after the ref resolver is gated on its verdict", () => { + test("nothing runs when Resolve PR refs says run=false (no reaction, no settings fetch, no spend)", () => { + const steps = actionSteps(); + const after = steps.slice(steps.findIndex((s) => s.id === "pr") + 1); + for (const s of after) { + const cond = String(s.if || ""); + if (s.name === "Clean up engine output" || s.name === "Token accounting") continue; + assert.ok( + // The guard runs only after a settings `review`, so gating on its + // decision is gating on the resolver's verdict transitively. + /steps\.pr\.outputs\.run == 'true'/.test(cond) || + /steps\.(settings|guard)\.outputs\.decision == '(review|skip)'/.test(cond), + `${s.name || s.uses}: if: ${cond || "(none)"}`, + ); + } + }); + + test("no step is gated on `decision != 'skip'` (an absent decision must run nothing)", () => { + for (const s of actionSteps()) { + assert.doesNotMatch(String(s.if || ""), /!= 'skip'/, `${s.name}: ${s.if}`); + } + }); +}); + +// ------------------------------------------------------- auto-review-authors + +function settingsDecision({ authors = "", assoc = "NONE", isPrivate = "false", event = "pull_request_target" }) { + const out = path.join(dir, `out-${Math.random().toString(36).slice(2)}`); + fs.writeFileSync(out, ""); + const r = runBashStep(step("settings").run, { + env: { + GATEWAY_URL_CHECK: path.join(ROOT, "scripts", "gateway-url.mjs"), + ORCAROUTER_URL: "https://api.orcarouter.ai/v1/chat/completions", + SETTINGS_ENABLED: "false", + INPUT_FIX_FIRST: "P0,P1", + INPUT_BLOCK_ON: "P0,P1", + EVENT_NAME: event, + IS_DRAFT: "false", + AUTHOR_ASSOC: assoc, + AUTO_REVIEW_AUTHORS: authors, + REPO_PRIVATE: isPrivate, + BRAND: "OrcaCode Review", + GITHUB_OUTPUT: out, + }, + }); + assert.equal(r.status, 0, r.stderr); + return Object.fromEntries( + fs + .readFileSync(out, "utf8") + .split("\n") + .filter((l) => l.includes("=")) + .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), + ); +} + +describe("auto-review-authors: unset is safe on a public repository", () => { + test("public + unset + an outsider (NONE) -> skip", () => { + const o = settingsDecision({ assoc: "NONE" }); + assert.equal(o.decision, "skip"); + assert.match(o.reason, /auto-review-authors/); + }); + + for (const assoc of ["OWNER", "MEMBER", "COLLABORATOR"]) { + test(`public + unset + ${assoc} -> review`, () => { + assert.equal(settingsDecision({ assoc }).decision, "review"); + }); + } + + test("public + unset + CONTRIBUTOR -> skip (a past contributor is still not a maintainer)", () => { + assert.equal(settingsDecision({ assoc: "CONTRIBUTOR" }).decision, "skip"); + }); + + test("unknown visibility is treated as public", () => { + assert.equal(settingsDecision({ assoc: "NONE", isPrivate: "" }).decision, "skip"); + }); + + test("private + unset + NONE -> review (private repos keep today's default)", () => { + assert.equal(settingsDecision({ assoc: "NONE", isPrivate: "true" }).decision, "review"); + }); + + test('"*" opts a public repo back in to reviewing everyone', () => { + assert.equal(settingsDecision({ authors: "*", assoc: "NONE" }).decision, "review"); + }); + + test("an explicit list still wins", () => { + assert.equal(settingsDecision({ authors: "OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR", assoc: "CONTRIBUTOR" }).decision, "review"); + }); + + test("a maintainer's comment command is never stopped by the allowlist", () => { + assert.equal(settingsDecision({ assoc: "NONE", event: "issue_comment" }).decision, "review"); + }); +}); diff --git a/scripts/excluded-files.mjs b/scripts/excluded-files.mjs new file mode 100644 index 0000000..58d43b3 --- /dev/null +++ b/scripts/excluded-files.mjs @@ -0,0 +1,79 @@ +#!/usr/bin/env node +// Which changed files the review engine does NOT review, and why. +// +// node excluded-files.mjs --base --head --out +// (run inside the checkout) +// +// The engine silently skips tests, fixtures, snapshots, generated code, +// unsupported file types, binaries and anything the root .gitignore matches. +// That is a sensible default for review quality and a blind spot for a merge +// gate: a PR that moves its interesting change into `fixtures/` or a +// `*.generated.*` file is reviewed as if it had none. This lists them so the +// summary can say so — the reader decides whether that is fine. +// +// The rules are the engine's own, from the vendored data and its JavaScript +// port in bin/selection.mjs (the same port the local review uses). Writes +// {"excluded":[{"path","code","reason"}...], "omitted": } +// Always exits 0 with a (possibly empty) list: this is a disclosure, and a +// failure to compute it must not fail the review — it is reported on stderr +// and the file then carries `"error"`. + +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const CAP = 200; + +const argv = process.argv.slice(2); +const opts = {}; +for (let i = 0; i < argv.length; i += 1) { + if (argv[i] === "--base") opts.base = argv[++i]; + else if (argv[i] === "--head") opts.head = argv[++i]; + else if (argv[i] === "--out") opts.out = argv[++i]; +} + +const write = (obj) => { + const json = JSON.stringify(obj); + if (opts.out) fs.writeFileSync(opts.out, json); + process.stdout.write(`${json}\n`); +}; + +const git = (...args) => + spawnSync("git", ["-c", "core.quotepath=false", ...args], { encoding: "utf8", maxBuffer: 1 << 28 }); + +// The same range the engine reviews: merge-base diff, falling back to the +// three-dot form on a git without --merge-base. +function diff(...flags) { + let r = git("diff", ...flags, "--merge-base", opts.base, opts.head); + if (r.status !== 0) r = git("diff", ...flags, `${opts.base}...${opts.head}`); + if (r.status !== 0) throw new Error(r.stderr.trim() || "git diff failed"); + return r.stdout.split("\0"); +} + +try { + if (!opts.base || !opts.head) throw new Error("usage: --base --head --out "); + const { partition } = await import(pathToFileURL(path.join(HERE, "..", "bin", "selection.mjs")).href); + + // --name-status -z: "\0\0" pairs (renames off, so one path). + const files = new Map(); + const ns = diff("--name-status", "--no-renames", "-z"); + for (let i = 0; i + 1 < ns.length; i += 2) { + if (!ns[i]) continue; + files.set(ns[i + 1], { path: ns[i + 1], deleted: ns[i].startsWith("D") }); + } + // --numstat -z: "\t\t\0"; "-\t-" marks a binary. + for (const rec of diff("--numstat", "--no-renames", "-z")) { + const m = rec.match(/^(-|\d+)\t(-|\d+)\t([\s\S]+)$/); + if (m && m[1] === "-" && files.has(m[3])) files.get(m[3]).binary = true; + } + + const { excluded } = partition([...files.values()], process.cwd()); + // Deleted files leave nothing to review; listing them says nothing useful. + const shown = excluded.filter((e) => e.code !== "deleted"); + write({ excluded: shown.slice(0, CAP), omitted: Math.max(0, shown.length - CAP) }); +} catch (e) { + console.error(`excluded-files: could not list skipped files (${e.message})`); + write({ excluded: [], omitted: 0, error: "could not list skipped files" }); +} diff --git a/scripts/exhaustive-merge.mjs b/scripts/exhaustive-merge.mjs index 771217d..bb61ebf 100644 --- a/scripts/exhaustive-merge.mjs +++ b/scripts/exhaustive-merge.mjs @@ -28,6 +28,7 @@ // wiring bug in action.yml and must be loud. import fs from "node:fs"; +import { severityOf, moreSevere, withSeverity } from "./severity.mjs"; const usage = () => { console.error("usage: node exhaustive-merge.mjs --base --new --out "); @@ -80,16 +81,30 @@ if (!base && !fresh) { } else if (!fresh) { merged = base; // fresh pass unusable — keep what we have, stop the loop } else { - const seen = new Set(base.comments.map(keyOf)); - const appended = []; + // A repeat of a finding already in hand is not new — but if this pass rates + // it MORE severe, the kept copy takes the higher tag. The key ignores the tag + // on purpose (a re-run re-tags), so without this a P0 that the first pass + // called P3 would be discarded as a duplicate of the P3. + const all = [...base.comments]; + const index = new Map(all.map((c, i) => [keyOf(c), i])); + let upgraded = 0; for (const c of fresh.comments) { const key = keyOf(c); - if (seen.has(key)) continue; - seen.add(key); // dupes INSIDE the fresh pass collapse too - appended.push(c); + if (index.has(key)) { + const i = index.get(key); + const sev = moreSevere(severityOf(all[i]), severityOf(c)); + if (sev !== severityOf(all[i])) { + all[i] = withSeverity(all[i], sev); + upgraded += 1; + } + continue; + } + index.set(key, all.length); // dupes INSIDE the fresh pass collapse too + all.push(c); + newFindings += 1; } - newFindings = appended.length; - merged = { ...base, comments: [...base.comments, ...appended] }; + if (upgraded) console.error(`exhaustive-merge: ${upgraded} finding(s) raised to a more severe tag by this pass`); + merged = { ...base, comments: all }; } fs.writeFileSync(opts.out, JSON.stringify(merged)); diff --git a/scripts/exhaustive-merge.test.mjs b/scripts/exhaustive-merge.test.mjs index 024101a..ed18ffc 100644 --- a/scripts/exhaustive-merge.test.mjs +++ b/scripts/exhaustive-merge.test.mjs @@ -22,6 +22,8 @@ import { fileURLToPath } from "node:url"; import { after, before, describe, test } from "node:test"; import assert from "node:assert/strict"; +import { cleanEnv } from "./test-helpers/action-yaml.mjs"; + const MERGE = join(dirname(fileURLToPath(import.meta.url)), "exhaustive-merge.mjs"); let dir; @@ -74,13 +76,25 @@ describe("dedup key: file + line + normalized content", () => { assert.equal(r.merged.comments.length, 1); }); - test("severity-tag variants collapse (tag stripped before hashing) — the base's tag wins", () => { + // This used to pin "the base's tag wins", which let a P0 from an extra pass + // be discarded as a duplicate of the first pass's P2 — the merge lowered a + // blocker. The variants still collapse into one finding; it now carries the + // more severe of the two tags, and a LESS severe repeat changes nothing. + test("severity-tag variants collapse (tag stripped before hashing) — the more severe tag wins", () => { const r = runMerge( { comments: [comment("a.js", 3, "[P2] null deref on user")] }, { comments: [comment("a.js", 3, "[P0] null deref on user")] }, ); assert.deepEqual(r.counts, { new_findings: 0 }); - assert.equal(r.merged.comments[0].content, "[P2] null deref on user"); + assert.equal(r.merged.comments[0].content, "[P0] null deref on user"); + }); + + test("a less severe repeat never lowers the base's tag", () => { + const r = runMerge( + { comments: [comment("a.js", 3, "[P0] null deref on user")] }, + { comments: [comment("a.js", 3, "[P3] null deref on user")] }, + ); + assert.equal(r.merged.comments[0].content, "[P0] null deref on user"); }); test("a genuinely-new finding is counted and appended AFTER the base (order preserved)", () => { @@ -228,7 +242,7 @@ node() { const r = spawnSync("bash", ["-c", script], { encoding: "utf8", env: { - ...process.env, + ...cleanEnv(), EXHAUSTIVE: "true", BRAND: "TestBrand", RESULT, RESULT_EXTRA, RESULT_MERGED, POLICY_BLOCK, diff --git a/scripts/fact-proxy-pinning.test.mjs b/scripts/fact-proxy-pinning.test.mjs new file mode 100644 index 0000000..997eab5 --- /dev/null +++ b/scripts/fact-proxy-pinning.test.mjs @@ -0,0 +1,247 @@ +// fact-proxy.mjs: where a request may go, and whose credential it carries. +// +// The proxy is the one process in the job that holds the real OrcaRouter key +// (the engine that reads the PR checkout gets a placeholder). That makes two +// things load-bearing: +// +// 1. The request target is PINNED. Only an origin-form path (`/v1/...`) equal +// to the configured endpoint's path is forwarded, and only to the one +// configured origin. Before this, `new URL(req.url, upstream)` resolved an +// absolute-form target (`http://elsewhere/...`), a scheme-relative one +// (`//elsewhere/...`) or a backslash variant to ANOTHER host and sent the +// client's Authorization there. +// 2. The upstream is https. Plain http is accepted only for a loopback host, +// which is what these tests use. +// +// And the key is the proxy's own: it comes from CR_UPSTREAM_KEY_FILE (read, +// then unlinked before the proxy announces PROXY_URL — so before the engine can +// start), never from the client, and replaces whatever Authorization the client +// sent. + +import http from "node:http"; +import { spawn } from "node:child_process"; +import { mkdtempSync, writeFileSync, rmSync, existsSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { createProxyServer } from "./fact-proxy.mjs"; + +const PROXY_SCRIPT = join(dirname(fileURLToPath(import.meta.url)), "fact-proxy.mjs"); +let dir; +before(() => { + dir = mkdtempSync(join(tmpdir(), "fact-proxy-pin-")); +}); +after(() => rmSync(dir, { recursive: true, force: true })); + +const listen = (server) => + new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server.address().port))); + +async function recorder() { + const seen = []; + const server = http.createServer((req, res) => { + req.resume(); + req.on("end", () => { + seen.push({ url: req.url, headers: req.headers }); + res.writeHead(200, { "content-type": "application/json" }); + res.end('{"ok":true}'); + }); + }); + const port = await listen(server); + return { port, seen, close: () => new Promise((r) => server.close(r)) }; +} + +async function proxyFor(upstreamPort, extra = {}) { + const server = createProxyServer({ + upstreamUrl: `http://127.0.0.1:${upstreamPort}/v1/chat/completions`, + sleep: () => Promise.resolve(), + ...extra, + }); + const port = await listen(server); + return { port, close: () => new Promise((r) => server.close(r)) }; +} + +function send(port, path, headers = {}) { + return new Promise((resolve) => { + const req = http.request({ host: "127.0.0.1", port, path, method: "POST", headers }, (res) => { + res.resume(); + res.on("end", () => resolve({ status: res.statusCode })); + }); + req.on("error", (e) => resolve({ status: null, error: e.message })); + req.end("{}"); + }); +} + +describe("the request target is pinned to the configured origin and path", () => { + for (const [label, target] of [ + ["absolute-form to another host", (p) => `http://127.0.0.1:${p}/v1/chat/completions`], + ["scheme-relative //host", (p) => `//127.0.0.1:${p}/v1/chat/completions`], + ["backslash //host variant", (p) => `/\\127.0.0.1:${p}/v1/chat/completions`], + ]) { + test(`${label}: never forwarded, the client's Authorization goes nowhere`, async () => { + const upstream = await recorder(); + const elsewhere = await recorder(); + const proxy = await proxyFor(upstream.port); + try { + const r = await send(proxy.port, target(elsewhere.port), { authorization: "Bearer client-secret" }); + assert.notEqual(r.status, 200); + assert.equal(elsewhere.seen.length, 0, "the request reached a host other than the configured one"); + assert.equal(upstream.seen.length, 0, "a refused target must not be forwarded anywhere"); + } finally { + await proxy.close(); + await upstream.close(); + await elsewhere.close(); + } + }); + } + + test("a path other than the configured endpoint is refused, not forwarded", async () => { + const upstream = await recorder(); + const proxy = await proxyFor(upstream.port); + try { + const r = await send(proxy.port, "/api/code_review/settings?repo=a/b"); + assert.equal(r.status, 404); + assert.equal(upstream.seen.length, 0); + } finally { + await proxy.close(); + await upstream.close(); + } + }); + + test("the configured path is forwarded, to the configured origin (query kept)", async () => { + const upstream = await recorder(); + const proxy = await proxyFor(upstream.port); + try { + const r = await send(proxy.port, "/v1/chat/completions?x=1"); + assert.equal(r.status, 200); + assert.equal(upstream.seen.length, 1); + assert.equal(upstream.seen[0].url, "/v1/chat/completions?x=1"); + } finally { + await proxy.close(); + await upstream.close(); + } + }); +}); + +describe("the upstream must be https (http only for loopback)", () => { + test("a plain-http, non-loopback upstream is refused", () => { + assert.throws( + () => createProxyServer({ upstreamUrl: "http://api.orcarouter.ai/v1/chat/completions" }), + /https/i, + ); + }); + + test("https is accepted", () => { + assert.doesNotThrow(() => createProxyServer({ upstreamUrl: "https://api.orcarouter.ai/v1/chat/completions" })); + }); + + for (const host of ["127.0.0.1", "localhost", "[::1]"]) { + test(`http to loopback ${host} is accepted (local test upstreams)`, () => { + assert.doesNotThrow(() => createProxyServer({ upstreamUrl: `http://${host}:8080/v1/chat/completions` })); + }); + } + + test("a non-http(s) upstream is refused", () => { + assert.throws(() => createProxyServer({ upstreamUrl: "file:///etc/passwd" })); + }); +}); + +describe("the proxy injects its own key", () => { + test("upstreamKey replaces the client's Authorization and drops x-api-key", async () => { + const upstream = await recorder(); + const proxy = await proxyFor(upstream.port, { upstreamKey: "real-orcarouter-key" }); + try { + const r = await send(proxy.port, "/v1/chat/completions", { + authorization: "Bearer placeholder", + "x-api-key": "placeholder", + }); + assert.equal(r.status, 200); + assert.equal(upstream.seen[0].headers.authorization, "Bearer real-orcarouter-key"); + assert.equal(upstream.seen[0].headers["x-api-key"], undefined); + } finally { + await proxy.close(); + await upstream.close(); + } + }); + + test("the CLI reads CR_UPSTREAM_KEY_FILE, unlinks it before announcing PROXY_URL, and injects it", async () => { + const upstream = await recorder(); + const keyFile = join(dir, "key"); + writeFileSync(keyFile, "real-key-from-file\n", { mode: 0o600 }); + const child = spawn(process.execPath, [PROXY_SCRIPT], { + env: { + ...process.env, + ORCAROUTER_URL: `http://127.0.0.1:${upstream.port}/v1/chat/completions`, + CR_UPSTREAM_KEY_FILE: keyFile, + }, + stdio: ["ignore", "pipe", "pipe"], + }); + try { + const url = await new Promise((resolve, reject) => { + let out = ""; + const timer = setTimeout(() => reject(new Error("no PROXY_URL within 5s")), 5000); + child.stdout.on("data", (c) => { + out += c; + const m = out.match(/^PROXY_URL=(.+)$/m); + if (m) { + clearTimeout(timer); + resolve(m[1]); + } + }); + child.on("exit", (code) => reject(new Error(`proxy exited early (${code})`))); + }); + assert.equal(existsSync(keyFile), false, "the key file must be gone once PROXY_URL is announced"); + const u = new URL(url); + const r = await send(Number(u.port), u.pathname, { authorization: "Bearer placeholder" }); + assert.equal(r.status, 200); + assert.equal(upstream.seen[0].headers.authorization, "Bearer real-key-from-file"); + } finally { + child.kill(); + await upstream.close(); + } + }); + + test("the CLI refuses to start when CR_UPSTREAM_KEY_FILE is set but unreadable", async () => { + const code = await new Promise((resolve) => { + const child = spawn(process.execPath, [PROXY_SCRIPT], { + env: { + ...process.env, + ORCAROUTER_URL: "http://127.0.0.1:9/v1/chat/completions", + CR_UPSTREAM_KEY_FILE: join(dir, "no-such-key"), + }, + stdio: ["ignore", "pipe", "pipe"], + }); + const timer = setTimeout(() => { + child.kill(); + resolve("still running"); + }, 5000); + child.on("exit", (c) => { + clearTimeout(timer); + resolve(c); + }); + }); + assert.notEqual(code, 0); + assert.notEqual(code, "still running"); + }); + + test("the CLI refuses a plain-http non-loopback ORCAROUTER_URL", async () => { + const code = await new Promise((resolve) => { + const child = spawn(process.execPath, [PROXY_SCRIPT], { + env: { ...process.env, ORCAROUTER_URL: "http://example.com/v1/chat/completions" }, + stdio: ["ignore", "pipe", "pipe"], + }); + const timer = setTimeout(() => { + child.kill(); + resolve("still running"); + }, 5000); + child.on("exit", (c) => { + clearTimeout(timer); + resolve(c); + }); + }); + assert.notEqual(code, 0); + assert.notEqual(code, "still running"); + }); +}); diff --git a/scripts/fact-proxy.mjs b/scripts/fact-proxy.mjs index d1fe438..e0e026f 100644 --- a/scripts/fact-proxy.mjs +++ b/scripts/fact-proxy.mjs @@ -67,15 +67,34 @@ // flat on a multi-MB completion. Extraction and the append are fully soft-fail: // metering must never alter, delay, or break a review. // +// Pinning and credentials. The proxy is the one process in the job that holds +// the real OrcaRouter key: the engine that reads the (possibly hostile) PR +// checkout is given a placeholder, and the proxy replaces the client's +// Authorization with its own key on the way out. Which makes WHERE a request +// may go load-bearing: +// - only an origin-form request target (`/path?query`) is accepted — never +// absolute-form (`http://host/…`), scheme-relative (`//host/…`) or a +// backslash spelling of either, all of which `new URL(target, base)` +// would resolve to another host; +// - only the configured endpoint's own path is forwarded (anything else is +// answered 404 and goes nowhere), and only to the configured origin; +// - the upstream must be https; plain http is accepted for a loopback host +// only (local test doubles). +// // Env: // ORCAROUTER_URL full upstream chat-completions URL (origin + path forwarded) +// CR_UPSTREAM_KEY_FILE file holding the OrcaRouter key; read and UNLINKED at +// startup, before PROXY_URL is printed, so nothing started +// after the proxy can read it from disk. The key is then +// sent as `authorization: Bearer ` on every upstream +// request, replacing the client's. Unset: the client's +// Authorization is forwarded (local harness use). // CR_FACTS_FILE path to the JSON facts file the driver rewrites per pass // CR_UPSTREAM_TIMEOUT_MS optional per-attempt upstream timeout (ms; default 120000) // CR_USAGE_FILE optional JSONL path for per-call token accounting (off when unset) // CR_MAX_RPM optional client-side request ceiling (requests/min; unset = no limit) // On listen it prints `PROXY_URL=http://127.0.0.1:` to -// stdout; the driver sets OCR_LLM_URL to that. Auth is forwarded untouched and -// never logged. +// stdout; the driver sets OCR_LLM_URL to that. Credentials are never logged. // // Exported for tests: createProxyServer({ upstreamUrl, factsFile, // policyBlockFile, sleep, maxRetries, maxBufferBytes, usageFile }) returns an @@ -85,6 +104,7 @@ import http from "node:http"; import https from "node:https"; +import { checkedGatewayUrl } from "./gateway-url.mjs"; import fs from "node:fs"; import { URL, pathToFileURL } from "node:url"; @@ -304,8 +324,37 @@ function retryDelayMs(retryIndex, retryAfter) { return BACKOFF_MS[Math.min(retryIndex, BACKOFF_MS.length - 1)]; } +// The one upstream this proxy may talk to: what scripts/gateway-url.mjs (the +// one judge of where the key may go) accepts — https, or http to this machine. +export function pinnedUpstream(upstreamUrl) { + try { + return checkedGatewayUrl(upstreamUrl); + } catch (e) { + throw new Error(`fact-proxy: refusing the upstream — ${e.message}`); + } +} + +// The forwarding URL for one client request target, or null when the target +// is anything but an origin-form path equal to the configured endpoint's. +export function pinnedTarget(rawTarget, upstream) { + const t = String(rawTarget || ""); + // Origin-form only: one leading "/", no second "/" or "\" after it (both + // make `new URL` read an authority), nothing that is not a plain path char. + if (!t.startsWith("/") || t.startsWith("//") || t.includes("\\")) return null; + let resolved; + try { + resolved = new URL(t, upstream.origin); + } catch { + return null; + } + if (resolved.origin !== upstream.origin) return null; + if (resolved.pathname !== upstream.pathname) return null; + return new URL(`${upstream.origin}${resolved.pathname}${resolved.search}`); +} + export function createProxyServer({ upstreamUrl, + upstreamKey = "", factsFile = "", policyBlockFile = "", sleep = defaultSleep, @@ -316,7 +365,7 @@ export function createProxyServer({ maxRpm = 0, now = () => Date.now(), } = {}) { - const upstream = new URL(upstreamUrl); + const upstream = pinnedUpstream(upstreamUrl); const upstreamLib = upstream.protocol === "http:" ? http : https; // Shared across every in-flight request: the ceiling is per-proxy (i.e. per // job), not per-connection. @@ -327,9 +376,27 @@ export function createProxyServer({ let callSeq = 0; return http.createServer((req, res) => { + // Pin the target FIRST: a refused target is answered here and never dials + // anything, so neither the client's headers nor ours leave the runner. + const target = pinnedTarget(req.url, upstream); + if (!target) { + console.error("fact-proxy: refused a request target that is not the configured endpoint"); + req.resume(); + res.writeHead(404, { "content-type": "text/plain" }); + res.end("not the configured endpoint\n"); + return; + } const mySeq = usageFile ? ++callSeq : 0; const headers = { ...req.headers }; delete headers.host; // must match upstream, not the loopback proxy + // The proxy's own key, when it has one, is the ONLY credential that leaves: + // whatever the client sent (the engine holds a placeholder) is dropped. + if (upstreamKey) { + delete headers.authorization; + delete headers["x-api-key"]; + delete headers["proxy-authorization"]; + headers.authorization = `Bearer ${upstreamKey}`; + } // The metering tap reads raw response bytes, so a gzip/br body would leave // every token field null. This is the DEFAULT path rather than an edge case: // Go's net/http adds `Accept-Encoding: gzip` on its own and decompresses @@ -339,7 +406,6 @@ export function createProxyServer({ // silently measures nothing. if (usageFile) headers["accept-encoding"] = "identity"; Object.assign(headers, readFacts(factsFile)); - const target = new URL(req.url, upstream); // The upstream request currently in flight for THIS client request (the // buffered attempt or the streaming variant), so a client disconnect can @@ -635,6 +701,37 @@ export function createProxyServer({ // ---- CLI entry (contract unchanged): env-driven, prints PROXY_URL on listen. if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + // Configuration is validated BEFORE the backstop below exists: a refusal + // to start must end the process, which the backstop deliberately never does. + let upstream; + try { + upstream = pinnedUpstream(process.env.ORCAROUTER_URL || "https://api.orcarouter.ai/v1/chat/completions"); + } catch (e) { + console.error(e.message); + process.exit(1); + } + // The key comes from a file that is unlinked the moment it is read — before + // PROXY_URL is printed, so before the driver can start the engine. Not from + // the environment: a same-user process can read /proc//environ. + let upstreamKey = ""; + if (process.env.CR_UPSTREAM_KEY_FILE) { + try { + upstreamKey = fs.readFileSync(process.env.CR_UPSTREAM_KEY_FILE, "utf8").trim(); + } catch (e) { + console.error(`fact-proxy: cannot read CR_UPSTREAM_KEY_FILE (${e.code || e.message}) — refusing to start`); + process.exit(1); + } + try { + fs.unlinkSync(process.env.CR_UPSTREAM_KEY_FILE); + } catch (e) { + console.error(`fact-proxy: cannot remove CR_UPSTREAM_KEY_FILE (${e.code || e.message}) — refusing to start`); + process.exit(1); + } + if (!upstreamKey) { + console.error("fact-proxy: CR_UPSTREAM_KEY_FILE is empty — refusing to start"); + process.exit(1); + } + } // Backstop: one misbehaving client (a mid-write EPIPE, a socket destroyed // under us) must NEVER take the whole proxy down mid-job — every request // already fails closed on its own path. Log and keep serving; do NOT exit. @@ -644,12 +741,10 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) console.error(`fact-proxy: uncaught exception (kept alive): ${e && e.stack ? e.stack : e}`); }); - const upstream = new URL( - process.env.ORCAROUTER_URL || "https://api.orcarouter.ai/v1/chat/completions", - ); const envTimeout = Number(process.env.CR_UPSTREAM_TIMEOUT_MS); const server = createProxyServer({ upstreamUrl: upstream.href, + upstreamKey, factsFile: process.env.CR_FACTS_FILE || "", policyBlockFile: process.env.CR_POLICY_BLOCK_FILE || "", usageFile: process.env.CR_USAGE_FILE || "", diff --git a/scripts/gate-wiring.test.mjs b/scripts/gate-wiring.test.mjs new file mode 100644 index 0000000..5318f3b --- /dev/null +++ b/scripts/gate-wiring.test.mjs @@ -0,0 +1,158 @@ +// How action.yml READS gate.mjs's verdict. +// +// gate.mjs answers with distinct exit codes (0 = a blocking finding, 10 = none, +// anything else = it could not decide). Every step that turns that into a merge +// decision must take only those two codes as answers and fail closed on the +// rest — a crash (node exits 1), an unreadable result (3) or a killed process +// (137) is not evidence of a clean review. Before this, the enforce step read +// "any non-zero exit" as "gate passed". + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { step, runBashStep, runGithubScript, fakeCore, ROOT } from "./test-helpers/action-yaml.mjs"; + +let dir; +before(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "gate-wiring-")); +}); +after(() => fs.rmSync(dir, { recursive: true, force: true })); + +// A stand-in gate.mjs that exits with whatever STUB_RC says. +function stubGate(rc) { + const file = path.join(dir, `gate-${rc}.mjs`); + fs.writeFileSync(file, `process.exit(${rc});\n`); + return file; +} + +const RESULT = () => { + const file = path.join(dir, "result.json"); + fs.writeFileSync(file, JSON.stringify({ comments: [] })); + return file; +}; + +describe("Enforce severity gate", () => { + const run = (gate, result = RESULT()) => + runBashStep(step("Enforce severity gate").run, { + env: { BRAND: "OrcaCode Review", BLOCK_ON: "P0,P1", GATE: gate, RESULT: result }, + }); + + test("exit 0 (a blocking finding) fails the step", () => { + assert.notEqual(run(stubGate(0)).status, 0); + }); + + test("exit 10 (no blocking finding) passes", () => { + const r = run(stubGate(10)); + assert.equal(r.status, 0, r.stdout + r.stderr); + }); + + for (const rc of [1, 2, 3, 137]) { + test(`exit ${rc} (the gate could not decide) fails closed`, () => { + const r = run(stubGate(rc)); + assert.notEqual(r.status, 0, `rc=${rc} passed the merge gate`); + assert.match(r.stdout + r.stderr, /could not (decide|read)/i); + }); + } + + test("the real gate on an unreadable result fails the step", () => { + const r = run(path.join(ROOT, "scripts", "gate.mjs"), path.join(dir, "missing.json")); + assert.notEqual(r.status, 0); + }); + + test("the real gate on a clean result passes the step", () => { + const r = run(path.join(ROOT, "scripts", "gate.mjs")); + assert.equal(r.status, 0, r.stdout + r.stderr); + }); +}); + +describe("Report run", () => { + function report(rc) { + const log = path.join(dir, `report-${rc}.log`); + const stubReport = path.join(dir, "report.mjs"); + fs.writeFileSync( + stubReport, + `import fs from "node:fs";\nfs.writeFileSync(process.env.LOG, process.argv.slice(2).join(" "));\n`, + ); + const r = runBashStep(step("Report run").run, { + env: { + REPORT: stubReport, + GATE: stubGate(rc), + RESULT_FINAL: RESULT(), + BLOCK_ON: "P0,P1", + REPO: "o/r", + PR_NUMBER: "1", + HEAD_SHA: "abc", + ORCAROUTER_URL: "http://127.0.0.1:9/v1/chat/completions", + ORCAROUTER_API_KEY: "k", + ENGINE_VERSION: "1.3.13", + LOG: log, + }, + }); + assert.equal(r.status, 0, r.stderr); + return fs.readFileSync(log, "utf8"); + } + + test("only exit 10 reports a pass", () => { + assert.match(report(10), /--gate pass/); + }); + + for (const rc of [0, 1, 3]) { + test(`exit ${rc} reports blocked, never pass`, () => { + assert.match(report(rc), /--gate blocked/); + }); + } +}); + +describe("Summary (PR description)", () => { + async function summaryGate(rc) { + const summaryStub = path.join(dir, "summary.mjs"); + fs.writeFileSync(summaryStub, "process.stdout.write('ARGS ' + process.argv.slice(2).join(' '));\n"); + const result = path.join(dir, "reported.json"); + fs.writeFileSync(result, JSON.stringify({ comments: [] })); + let updated = null; + const github = { + paginate: async () => [], + rest: { + issues: { listComments: () => {}, deleteComment: async () => {} }, + pulls: { + get: async () => ({ data: { body: "author text" } }), + update: async (args) => { + updated = args.body; + }, + }, + }, + }; + const { core } = fakeCore(); + await runGithubScript(step("Summary (PR description)").with.script, { + github, + core, + context: { repo: { owner: "o", repo: "r" }, payload: {} }, + env: { + PR_NUMBER: "1", + RESULT: result, + PREV_BODY: path.join(dir, "prev.md"), + SUMMARY_SCRIPT: summaryStub, + INJECT_SCRIPT: path.join(ROOT, "scripts", "inject-summary.mjs"), + PUBLISH_GUARD: path.join(ROOT, "scripts", "publish-guard.mjs"), + GATE: stubGate(rc), + BLOCK_ON: "P0,P1", + QUIET: "false", + PASSES: "1", + }, + }); + return updated; + } + + test("exit 10 renders a pass", async () => { + assert.match(await summaryGate(10), /--gate pass/); + }); + + for (const rc of [0, 1, 3]) { + test(`exit ${rc} renders blocked, never pass`, async () => { + assert.match(await summaryGate(rc), /--gate blocked/); + }); + } +}); diff --git a/scripts/gate.mjs b/scripts/gate.mjs index b3d0988..3720244 100644 --- a/scripts/gate.mjs +++ b/scripts/gate.mjs @@ -6,8 +6,14 @@ // "does any finding carry a severity in the given set?" // // node gate.mjs --has P0,P1 -// exit 0 -> at least one finding matches (escalate / block) -// exit 1 -> none match (converged / pass) +// exit 0 -> at least one finding matches (escalate / block) +// exit 10 -> none match (converged / pass) +// exit 2 -> usage error +// exit 3 -> the result could not be read as a review result +// +// "No match" is deliberately NOT 1: node exits 1 on any uncaught exception, so +// a caller that read 1 as "pass" let a crashed gate clear the merge. Callers +// take 0 and 10 as the only answers and fail closed on everything else. // // The model is instructed to tag every comment; if one is still untagged we // default it to P1 (fail-safe) so a missing tag escalates for a second look @@ -17,11 +23,13 @@ import fs from "node:fs"; import { SEVERITIES, severityOf } from "./severity.mjs"; +const EXIT = Object.freeze({ MATCH: 0, NO_MATCH: 10, USAGE: 2, UNREADABLE: 3 }); + const [file, flag, listRaw] = process.argv.slice(2); if (!file || flag !== "--has") { console.error("usage: node gate.mjs --has P0,P1"); - process.exit(2); + process.exit(EXIT.USAGE); } const wanted = new Set( @@ -31,14 +39,16 @@ const wanted = new Set( .filter(Boolean), ); -let comments = []; +let comments; try { const parsed = JSON.parse(fs.readFileSync(file, "utf8")); - comments = Array.isArray(parsed.comments) ? parsed.comments : []; + if (!Array.isArray(parsed?.comments)) throw new Error("no `comments` array"); + comments = parsed.comments; } catch (e) { - // No parseable output (engine error / empty) — nothing to gate on. + // No readable review result. That is NOT a clean review: the caller decides + // what an undecidable gate means, and the merge gate fails closed on it. console.error(`gate: could not read findings from ${file} (${e.message})`); - process.exit(1); + process.exit(EXIT.UNREADABLE); } // Severity comes from the shared severity.mjs (leading-tag-only parsing plus @@ -63,4 +73,4 @@ console.error( `gate: ${comments.length} finding(s) [${breakdown}] · match(${[...wanted].join(",") || "-"}) = ${matched}`, ); -process.exit(matched ? 0 : 1); +process.exit(matched ? EXIT.MATCH : EXIT.NO_MATCH); diff --git a/scripts/gate.test.mjs b/scripts/gate.test.mjs index c60a76f..7d94cb7 100644 --- a/scripts/gate.test.mjs +++ b/scripts/gate.test.mjs @@ -9,6 +9,16 @@ // // So the exit code IS the policy, and reading it backwards inverts both. Run // these before changing anything about severity behaviour. +// +// THE EXIT CODES ARE DISTINCT, AND "NO MATCH" IS NOT 1. Node exits 1 on any +// uncaught exception, and the enforce step used to read every non-zero exit +// as "gate passed" — so a gate that crashed, or a result it could not read, +// passed the merge gate. Now: +// 0 a finding matches --has (block / stop adding passes) +// 10 no finding matches (pass) +// 2 usage error +// 3 the result could not be read as a review result +// and the enforce step fails closed on anything but 0 or 10. import { execFileSync } from "node:child_process"; import { mkdtempSync, writeFileSync, rmSync } from "node:fs"; @@ -29,7 +39,7 @@ after(() => { }); // Runs the gate against a result with the given comment bodies and returns the -// exit code (0 = at least one finding matches --has, 1 = none match / no input). +// exit code (0 = at least one finding matches --has, 10 = none match). function gate(contents, has) { const file = join(dir, `${Math.random().toString(36).slice(2)}.json`); const comments = contents.map((content) => ({ content })); @@ -44,6 +54,7 @@ function gate(contents, has) { const FIX_FIRST = "P0,P1"; // severities the exhaustive loop stops on const BLOCK_ON = "P0"; // severities that block the merge +const NO_MATCH = 10; describe("exhaustive early-stop decision (--has FIX_FIRST)", () => { test("P0 present -> match (stop adding passes; fix that first)", () => { @@ -55,11 +66,11 @@ describe("exhaustive early-stop decision (--has FIX_FIRST)", () => { }); test("P2-only -> no match (extra depth may still find something)", () => { - assert.equal(gate(["[P2] use const", "[P2] dead code"], FIX_FIRST), 1); + assert.equal(gate(["[P2] use const", "[P2] dead code"], FIX_FIRST), NO_MATCH); }); test("clean (no findings) -> no match (extra depth may still find something)", () => { - assert.equal(gate([], FIX_FIRST), 1); + assert.equal(gate([], FIX_FIRST), NO_MATCH); }); test("untagged finding -> treated as P1 (stop, fail-safe)", () => { @@ -73,16 +84,19 @@ describe("merge gate (--has BLOCK_ON)", () => { }); test("P1-only -> no match (gate passes)", () => { - assert.equal(gate(["[P1] race condition"], BLOCK_ON), 1); + assert.equal(gate(["[P1] race condition"], BLOCK_ON), NO_MATCH); }); test("untagged (P1 fail-safe) does not block on P0", () => { - assert.equal(gate(["untagged bug"], BLOCK_ON), 1); + assert.equal(gate(["untagged bug"], BLOCK_ON), NO_MATCH); }); }); describe("robustness", () => { - test("missing / unparseable file -> no match (exit 1), never crashes", () => { + // This used to pin "missing / unparseable file -> no match (exit 1)", i.e. + // an unreadable result PASSED the merge gate. That was the fail-open: a + // result nobody could read is not evidence of a clean review. + test("missing file -> exit 3 (unreadable), never the pass code", () => { assert.throws( () => execFileSync( @@ -90,7 +104,32 @@ describe("robustness", () => { [GATE, join(dir, "does-not-exist.json"), "--has", "P0"], { stdio: "pipe" }, ), - (e) => e.status === 1, + (e) => e.status === 3, + ); + }); + + test("unparseable file -> exit 3 (unreadable)", () => { + const file = join(dir, "garbage.json"); + writeFileSync(file, "{not json"); + assert.throws( + () => execFileSync("node", [GATE, file, "--has", "P0"], { stdio: "pipe" }), + (e) => e.status === 3, + ); + }); + + test("a result with no comments array -> exit 3, not a clean pass", () => { + const file = join(dir, "no-comments.json"); + writeFileSync(file, JSON.stringify({ summary: "looks fine" })); + assert.throws( + () => execFileSync("node", [GATE, file, "--has", "P0"], { stdio: "pipe" }), + (e) => e.status === 3, + ); + }); + + test("usage error -> exit 2", () => { + assert.throws( + () => execFileSync("node", [GATE], { stdio: "pipe" }), + (e) => e.status === 2, ); }); diff --git a/scripts/gateway-url.mjs b/scripts/gateway-url.mjs new file mode 100644 index 0000000..625cc67 --- /dev/null +++ b/scripts/gateway-url.mjs @@ -0,0 +1,55 @@ +#!/usr/bin/env node +// Where the OrcaRouter key may go: the one judge. +// +// The key travels as a Bearer header to `orcarouter-url` (the review proxy) and +// to the control plane derived from it (settings.mjs, report.mjs). In clear it +// may go only to this machine — the rule OrcaRouter's own gateway keeps for +// every credential it hands out: https anywhere; plain http only to localhost, +// 127.0.0.0/8 or [::1]. Asked where the URL is first read (the action's +// settings step, which fails the run with the message below) and again +// wherever the key meets it. +// +// node scripts/gateway-url.mjs judges $ORCAROUTER_URL; on a refusal prints +// a ::error:: naming the input and the fix +// and exits 1. + +import { pathToFileURL } from "node:url"; + +const FIX = + "Use an https:// URL — put TLS in front of a self-hosted gateway — or plain http only to " + + "this machine (localhost, 127.0.0.0/8 or [::1]): over any other network the key would travel in clear."; + +const isLoopback = (hostname) => { + const h = hostname.toLowerCase(); + if (h === "localhost" || h === "[::1]") return true; + // WHATWG URL has already normalised IPv4 forms (127.1, 2130706433, 0x7f.1). + return /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(h); +}; + +/** null when the key may be sent to `raw`; otherwise why not, and what to do. */ +export function gatewayUrlProblem(raw) { + let u; + try { + u = new URL(String(raw ?? "")); + } catch { + return `orcarouter-url is not a URL (${JSON.stringify(String(raw ?? "").slice(0, 100))}). ${FIX}`; + } + if (u.protocol === "https:") return null; + if (u.protocol === "http:" && isLoopback(u.hostname)) return null; + return `orcarouter-url must be https: ${u.protocol}//${u.host} would carry your OrcaRouter key. ${FIX}`; +} + +/** The URL, or a thrown Error carrying the judge's message. */ +export function checkedGatewayUrl(raw) { + const problem = gatewayUrlProblem(raw); + if (problem) throw new Error(problem); + return new URL(raw); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const problem = gatewayUrlProblem(process.env.ORCAROUTER_URL); + if (problem) { + console.log(`::error::${problem.replace(/[\r\n]+/g, " ")}`); + process.exit(1); + } +} diff --git a/scripts/gateway-url.test.mjs b/scripts/gateway-url.test.mjs new file mode 100644 index 0000000..3575447 --- /dev/null +++ b/scripts/gateway-url.test.mjs @@ -0,0 +1,176 @@ +// Where the OrcaRouter key may be sent in clear: nowhere but this machine. +// +// The proxy refused a plain-http gateway with a message that named neither the +// input to change nor how — and it was the only place that looked: the settings +// fetch (settings.mjs) and the run report (report.mjs) sent the same key, as a +// Bearer header, to whatever orcarouter-url said, http included, before the +// proxy ever ran. A self-hosted gateway on plain http therefore leaked the key +// across the network on every run and then failed with an unhelpful error. +// +// Now one judge (scripts/gateway-url.mjs, the rule OrcaRouter's own gateway +// keeps: credentials in clear only to this machine) is asked where the URL is +// resolved — the first step that reads it, which fails the run naming the +// input and the fix — and again wherever the key meets it: the proxy, the +// settings fetch and the run report. https anywhere; plain http only to +// localhost, 127.0.0.0/8 or [::1]. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawn } from "node:child_process"; +import { after, before, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { gatewayUrlProblem } from "./gateway-url.mjs"; +import { createProxyServer } from "./fact-proxy.mjs"; +import { step, runBashStep, ROOT } from "./test-helpers/action-yaml.mjs"; + +let dir; +before(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "gateway-url-")); +}); +after(() => fs.rmSync(dir, { recursive: true, force: true })); + +const OK = [ + "https://api.orcarouter.ai/v1/chat/completions", + "https://gateway.internal:8443/orca/v1/chat/completions", + "http://localhost:8080/v1/chat/completions", + "http://LOCALHOST:8080/v1/chat/completions", + "http://127.0.0.1:8080/v1/chat/completions", + "http://127.5.6.7/v1/chat/completions", + "http://127.1/v1/chat/completions", + "http://[::1]:8080/v1/chat/completions", +]; +const REFUSED = [ + "http://gateway.internal/v1/chat/completions", + "http://10.0.0.5/v1/chat/completions", + "http://192.168.1.10:3000/v1/chat/completions", + "http://localhost.evil.example/v1/chat/completions", + "http://127.0.0.1.nip.io/v1/chat/completions", + "http://[::ffff:a00:5]/v1/chat/completions", + "http://0.0.0.0/v1/chat/completions", + "ftp://api.orcarouter.ai/v1", + "file:///etc/passwd", + "not a url", + "", +]; + +describe("the judge", () => { + for (const url of OK) test(`accepts ${url}`, () => assert.equal(gatewayUrlProblem(url), null)); + for (const url of REFUSED) { + test(`refuses ${JSON.stringify(url)}, naming the input and the fix`, () => { + const p = gatewayUrlProblem(url); + assert.ok(p, "accepted"); + assert.match(p, /orcarouter-url/); + assert.match(p, /https:\/\//); + assert.match(p, /localhost|127\.0\.0\.0\/8|\[::1\]/); + }); + } +}); + +describe("everything that sends the key asks it", () => { + test("the proxy refuses with the judge's message", () => { + assert.throws( + () => createProxyServer({ upstreamUrl: "http://gateway.internal/v1/chat/completions" }), + (e) => /orcarouter-url/.test(e.message) && /127\.0\.0\.0\/8/.test(e.message), + ); + assert.doesNotThrow(() => createProxyServer({ upstreamUrl: "http://127.9.9.9:1/v1/chat/completions" })); + }); + + // 203.0.113.0/24 is TEST-NET-3: nothing answers there, so an attempt to send + // would sit out the connect timeout. A refusal returns at once. + const run = (script, args, env) => + new Promise((resolve) => { + const t0 = Date.now(); + const child = spawn(process.execPath, [path.join(ROOT, "scripts", script), ...args], { + env: { ...process.env, ORCAROUTER_API_KEY: "k-secret", ...env }, + stdio: ["ignore", "pipe", "pipe"], + }); + let out = ""; + let err = ""; + child.stdout.on("data", (d) => (out += d)); + child.stderr.on("data", (d) => (err += d)); + child.on("close", (status) => resolve({ status, out, err, ms: Date.now() - t0 })); + }); + + test("the settings fetch does not send the key to a plain-http gateway", async () => { + const out = path.join(dir, "settings.json"); + const r = await run("settings.mjs", ["--url", "http://203.0.113.7/v1/chat/completions", "--repo", "a/b", "--out", out], { + CR_SETTINGS_TIMEOUT_MS: "4000", + }); + assert.equal(r.status, 0); + assert.ok(r.ms < 2500, `took ${r.ms}ms — it tried to connect`); + const got = JSON.parse(fs.readFileSync(out, "utf8")); + assert.equal(got.status, "unavailable"); + assert.match(got.cause, /orcarouter-url/); + }); + + test("the run report does not send the key to a plain-http gateway", async () => { + const result = path.join(dir, "result.json"); + fs.writeFileSync(result, JSON.stringify({ comments: [] })); + const r = await run("report.mjs", [ + result, "--repo", "a/b", "--pr", "1", "--sha", "s", "--tier", "standard", "--gate", "pass", + "--url", "http://203.0.113.7/v1/chat/completions", + ]); + assert.equal(r.status, 0); + assert.ok(r.ms < 2500, `took ${r.ms}ms — it tried to connect`); + assert.match(r.err, /orcarouter-url/); + }); +}); + +describe("the action fails at once, naming the input and the fix", () => { + const settingsEnv = (url, enabled = "true") => { + const out = path.join(dir, `out-${Math.random().toString(36).slice(2)}`); + fs.writeFileSync(out, ""); + return { + out, + env: { + GATEWAY_URL_CHECK: path.join(ROOT, "scripts", "gateway-url.mjs"), + SETTINGS_SCRIPT: path.join(ROOT, "scripts", "settings.mjs"), + SETTINGS_ENABLED: enabled, + ORCAROUTER_URL: url, + ORCAROUTER_API_KEY: "k", + CR_SETTINGS_TIMEOUT_MS: "300", + REPO: "o/r", + SETTINGS_JSON: path.join(dir, "s.json"), + RUBRIC_FILE: path.join(dir, "r.md"), + INPUT_FIX_FIRST: "P0,P1", + INPUT_BLOCK_ON: "P0,P1", + EVENT_NAME: "pull_request_target", + IS_DRAFT: "false", + AUTHOR_ASSOC: "OWNER", + AUTO_REVIEW_AUTHORS: "", + REPO_PRIVATE: "true", + BRAND: "OrcaCode Review", + GITHUB_OUTPUT: out, + }, + }; + }; + + for (const enabled of ["true", "false"]) { + test(`a plain-http, non-loopback orcarouter-url fails the first step that reads it (settings: ${enabled})`, () => { + const { env } = settingsEnv("http://gateway.internal/v1/chat/completions", enabled); + const r = runBashStep(step("settings").run, { env }); + assert.notEqual(r.status, 0); + assert.match(r.stdout, /^::error::.*orcarouter-url.*https:\/\//m); + }); + } + + test("a loopback gateway on plain http is fine", () => { + const { env, out } = settingsEnv("http://127.0.0.1:9/v1/chat/completions", "false"); + const r = runBashStep(step("settings").run, { env }); + assert.equal(r.status, 0, r.stdout + r.stderr); + assert.match(fs.readFileSync(out, "utf8"), /decision=review/); + }); + + test("a step not handed the judge fails rather than skipping it (`node \"\"` would exit 0)", () => { + const { env } = settingsEnv("http://gateway.internal/v1/chat/completions", "false"); + delete env.GATEWAY_URL_CHECK; + const r = runBashStep(step("settings").run, { env }); + assert.notEqual(r.status, 0); + }); + + test("the step is handed the judge", () => { + assert.equal(step("settings").env.GATEWAY_URL_CHECK, "${{ github.action_path }}/scripts/gateway-url.mjs"); + }); +}); diff --git a/scripts/guard-diff.mjs b/scripts/guard-diff.mjs new file mode 100644 index 0000000..8319514 --- /dev/null +++ b/scripts/guard-diff.mjs @@ -0,0 +1,93 @@ +#!/usr/bin/env node +// The diff the oversized-diff guard measures. +// +// node guard-diff.mjs --base --head --out --lockfiles +// (run inside the hardened checkout) +// +// The merge-base diff of the PR — the range the engine reviews — WITHOUT the +// files whose name is a standard lockfile's. Hardening the checkout (`* !diff`) +// stopped a fork's .gitattributes from hiding its change, and with it stopped +// the `-diff` most repositories put on their lockfiles: a dependency bump +// regenerates megabytes of lockfile, which then counted toward max-diff-kb and +// skipped ordinary PRs. Matching by NAME, never by an attribute the PR could +// set, and leaving a file out of the count can only make the guard review more. +// The engine is unaffected: it reads the hardened checkout's own full diff. +// +// Writes the diff to --out and {"lockfiles": [paths]} to --lockfiles. Fails +// OPEN: if no diff can be produced it writes an empty one (the guard then +// reviews) and says so on stdout as a ::warning:: — a guard glitch must never +// kill the review. Always exits 0. + +import fs from "node:fs"; +import { spawnSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; + +export const LOCKFILE_NAMES = Object.freeze([ + "package-lock.json", + "yarn.lock", + "pnpm-lock.yaml", + "bun.lockb", + "go.sum", + "Cargo.lock", + "poetry.lock", + "composer.lock", + "Gemfile.lock", +]); + +// At any depth, by exact file name: `:(glob)**/` matches `` at the +// root too. +const lockPathspecs = (mode) => LOCKFILE_NAMES.map((n) => `:(${mode}glob)**/${n}`); + +const git = (args, outFd) => + spawnSync("git", ["-c", "core.quotepath=false", ...args], { + encoding: "utf8", + maxBuffer: 1 << 26, + stdio: ["ignore", outFd ?? "pipe", "pipe"], + }); + +// The merge-base range (git >= 2.30), else the equivalent three-dot form. +function diff(base, head, extra, outFd) { + let r = git(["diff", ...extra.flags, "--merge-base", base, head, "--", ...extra.paths], outFd); + if (r.status !== 0) r = git(["diff", ...extra.flags, `${base}...${head}`, "--", ...extra.paths], outFd); + return r; +} + +function main() { + const argv = process.argv.slice(2); + const opts = {}; + for (let i = 0; i < argv.length; i += 1) { + if (argv[i] === "--base") opts.base = argv[++i]; + else if (argv[i] === "--head") opts.head = argv[++i]; + else if (argv[i] === "--out") opts.out = argv[++i]; + else if (argv[i] === "--lockfiles") opts.lockfiles = argv[++i]; + } + let lockfiles = []; + let ok = false; + if (opts.base && opts.head && opts.out) { + const fd = fs.openSync(opts.out, "w"); + try { + ok = diff(opts.base, opts.head, { flags: [], paths: [".", ...lockPathspecs("exclude,")] }, fd).status === 0; + } finally { + fs.closeSync(fd); + } + if (ok) { + const names = diff(opts.base, opts.head, { flags: ["--name-only", "-z", "--no-renames"], paths: lockPathspecs("") }); + if (names.status === 0) lockfiles = names.stdout.split("\0").filter(Boolean).sort(); + } + } + if (!ok) { + if (opts.out) fs.writeFileSync(opts.out, ""); + console.log("::warning::OrcaCode Review: diff generation failed — size guard failing open."); + } + if (opts.lockfiles) fs.writeFileSync(opts.lockfiles, JSON.stringify({ lockfiles })); + console.log(`guard diff: ${lockfiles.length} lockfile(s) not counted${lockfiles.length ? ` (${lockfiles.join(", ")})` : ""}`); +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + try { + main(); + } catch (e) { + console.log(`::warning::OrcaCode Review: the guard diff failed (${e.message}) — size guard failing open.`); + } + process.exit(0); +} diff --git a/scripts/guard-diff.test.mjs b/scripts/guard-diff.test.mjs new file mode 100644 index 0000000..a0b466c --- /dev/null +++ b/scripts/guard-diff.test.mjs @@ -0,0 +1,171 @@ +// The diff the oversized-diff guard measures, and the lockfiles it leaves out. +// +// The checkout hardening writes `* !diff` so a fork's `.gitattributes` cannot +// turn its change into "Binary files differ". That also took away what most +// repositories mark `-diff` on purpose: their lockfiles. A PR bumping one +// dependency regenerates package-lock.json or go.sum, and the whole lockfile +// diff — megabytes — now counted toward max-diff-kb, so ordinary PRs started +// skipping (and, by default, failing) on size. +// +// The guard now measures the merge-base diff WITHOUT files whose name is a +// standard lockfile's (by name, not by any attribute a PR could set — leaving a +// file out of the count can only make the guard review MORE). The engine still +// reads the hardened checkout's full diff. The lockfiles left out are listed in +// the PR summary. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { after, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { step, runBashStep, ROOT } from "./test-helpers/action-yaml.mjs"; +import { makeRepo, cleanupReviewHarness } from "./test-helpers/review-harness.mjs"; +import { LOCKFILE_NAMES } from "./guard-diff.mjs"; + +after(cleanupReviewHarness); + +const big = (kb) => `${"x".repeat(1023)}\n`.repeat(kb); + +function prWithLockfiles(name) { + return makeRepo(name, (repo) => { + fs.writeFileSync(path.join(repo, "app.js"), "export const a = 2;\n"); + fs.writeFileSync(path.join(repo, "package-lock.json"), big(6000)); // over the 5000 KB default alone + fs.mkdirSync(path.join(repo, "web")); + fs.writeFileSync(path.join(repo, "web", "yarn.lock"), big(300)); + fs.writeFileSync(path.join(repo, "Cargo.lock"), "lock\n"); + // Look-alikes are counted: the match is the exact file name. + fs.writeFileSync(path.join(repo, "package-lock.json.bak"), "bak\n"); + fs.writeFileSync(path.join(repo, "my-go.sum"), "sum\n"); + // A repository that marked its lockfile -diff, as many do. + fs.writeFileSync(path.join(repo, ".gitattributes"), "package-lock.json -diff\n"); + }); +} + +describe("the standard lockfile names", () => { + test("are exactly these", () => { + assert.deepEqual( + [...LOCKFILE_NAMES].sort(), + ["Cargo.lock", "Gemfile.lock", "bun.lockb", "composer.lock", "go.sum", "package-lock.json", "pnpm-lock.yaml", "poetry.lock", "yarn.lock"], + ); + }); +}); + +function runGuardStep(repo, sha, { maxKb = "5000" } = {}) { + const temp = fs.mkdtempSync(path.join(os.tmpdir(), "guard-step-")); + const out = path.join(temp, "out"); + fs.writeFileSync(out, ""); + const harden = runBashStep(step("harden").run, { + cwd: repo, + env: { + HARDEN: path.join(ROOT, "scripts", "harden-checkout.mjs"), + EXCLUDED: path.join(ROOT, "scripts", "excluded-files.mjs"), + BASE: "origin/main", + HEAD: sha, + EXCLUDED_FILE: path.join(temp, "cr-excluded.json"), + GITHUB_OUTPUT: out, + }, + }); + assert.equal(harden.status, 0, harden.stderr); + const r = runBashStep(step("guard").run, { + cwd: repo, + env: { + BRAND: "OrcaCode Review", + BASE: "origin/main", + HEAD: sha, + GUARD: path.join(ROOT, "scripts", "diff-guard.mjs"), + GUARD_DIFF: path.join(ROOT, "scripts", "guard-diff.mjs"), + MAX_KB: maxKb, + MAX_FILES: "2000", + DIFF_FILE: path.join(temp, "pr.diff"), + GUARD_JSON: path.join(temp, "diff-guard.json"), + LOCKFILES_FILE: path.join(temp, "cr-lockfiles.json"), + GITHUB_OUTPUT: out, + }, + }); + assert.equal(r.status, 0, r.stdout + r.stderr); + const outputs = Object.fromEntries( + fs.readFileSync(out, "utf8").split("\n").filter((l) => l.includes("=")).map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), + ); + return { outputs, temp, log: r.stdout + r.stderr }; +} + +describe("the guard step on a hardened checkout", () => { + test("a PR whose only large change is a lockfile is reviewed, not skipped", () => { + const { repo, sha } = prWithLockfiles("big-lockfile"); + const { outputs, temp } = runGuardStep(repo, sha); + assert.equal(outputs.decision, "review", outputs.reason); + const diff = fs.readFileSync(path.join(temp, "pr.diff"), "utf8"); + assert.match(diff, /^diff --git a\/app\.js /m); + assert.match(diff, /^diff --git a\/package-lock\.json\.bak /m, "a look-alike name still counts"); + assert.match(diff, /^diff --git a\/my-go\.sum /m); + assert.doesNotMatch(diff, /^diff --git a\/(package-lock\.json|web\/yarn\.lock|Cargo\.lock) /m); + }); + + test("the lockfiles left out are written down, for the summary", () => { + const { repo, sha } = prWithLockfiles("listed"); + const { temp, outputs } = runGuardStep(repo, sha); + const listed = JSON.parse(fs.readFileSync(path.join(temp, "cr-lockfiles.json"), "utf8")); + assert.deepEqual(listed.lockfiles, ["Cargo.lock", "package-lock.json", "web/yarn.lock"]); + assert.equal(outputs.lockfiles, "3"); + }); + + test("everything else still counts: a large non-lockfile change skips as before", () => { + const { repo, sha } = makeRepo("big-code", (r) => fs.writeFileSync(path.join(r, "gen.js"), big(6000))); + assert.equal(runGuardStep(repo, sha).outputs.decision, "skip"); + }); + + test("the engine's view is untouched: the checkout keeps `* !diff`, and the full diff shows the lockfile", () => { + const { repo, sha } = prWithLockfiles("engine-view"); + runGuardStep(repo, sha); + const attrs = fs.readFileSync(path.join(repo, ".git", "info", "attributes"), "utf8"); + assert.match(attrs, /^\* !diff$/m); + const full = spawnSync("git", ["diff", "--stat", "origin/main", sha], { cwd: repo, encoding: "utf8" }).stdout; + assert.match(full, /package-lock\.json\s+\|\s+6000 \+/, "the engine-side diff still carries the lockfile's lines"); + const engine = step("review").run.match(/ocr review --from[\s\S]*?--format json/); + assert.ok(engine, "the engine invocation moved"); + assert.doesNotMatch(engine[0], /:\(|\s--\s|lock/i, "the engine's diff takes no exclusions"); + }); + + test("an unreadable range fails open to an empty diff (review), with a warning", () => { + const { repo } = makeRepo("no-range"); + const { outputs, log } = runGuardStep(repo, "0000000000000000000000000000000000000000"); + assert.equal(outputs.decision, "review"); + assert.match(log, /::warning::/); + }); +}); + +describe("the summary lists the lockfiles left out of the size count", () => { + const summary = (lockfiles) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "summary-lock-")); + const result = path.join(dir, "r.json"); + fs.writeFileSync(result, JSON.stringify({ comments: [] })); + const lf = path.join(dir, "lf.json"); + fs.writeFileSync(lf, JSON.stringify({ lockfiles })); + const r = spawnSync(process.execPath, [path.join(ROOT, "scripts", "summary-comment.mjs"), result, "--tier", "standard", "--push", "1", "--gate", "pass", "--lockfiles", lf], { encoding: "utf8" }); + assert.equal(r.status, 0, r.stderr); + return r.stdout; + }; + + test("each, as a code span that cannot break out", () => { + const md = summary(["package-lock.json", "web/yarn.lock", "evil`|\n## x/go.sum"]); + assert.match(md, /not counted toward the diff-size limit/i); + assert.match(md, /`package-lock\.json`/); + assert.match(md, /`web\/yarn\.lock`/); + assert.doesNotMatch(md, /^## x/m); + }); + + test("nothing when there are none", () => { + assert.doesNotMatch(summary([]), /not counted toward/i); + }); + + test("the summary step hands it the list, and the run files are cleared", () => { + const s = step("Summary (PR description)"); + assert.equal(s.env.LOCKFILES_FILE, "${{ runner.temp }}/cr-lockfiles.json"); + assert.match(s.with.script, /'--lockfiles', process\.env\.LOCKFILES_FILE/); + for (const name of ["Clear stale run files", "Clean up engine output"]) { + assert.match(step(name).run, /"\$RUNNER_TEMP\/cr-lockfiles\.json"/, name); + } + }); +}); diff --git a/scripts/harden-checkout.mjs b/scripts/harden-checkout.mjs new file mode 100644 index 0000000..ed38584 --- /dev/null +++ b/scripts/harden-checkout.mjs @@ -0,0 +1,132 @@ +#!/usr/bin/env node +// Neutralise what a PR checkout could use to steer the review without changing +// a line of reviewed code. Run on the checkout BEFORE anything reads it (the +// size guard and the engine both do). +// +// node harden-checkout.mjs [--dir ] [--base ] +// +// 1. Every symlink in the work tree is deleted — tracked (`git ls-files -s` +// mode 120000) and untracked alike, files and directories. A committed +// `notes.md -> /proc/self/environ` would otherwise let an engine whose +// tools read "files in the repo" read outside it. Only the link goes; its +// target is never touched. +// 2. Repository attributes lose their say over `diff`: `* !diff` is written +// to $GIT_DIR/info/attributes, which outranks every .gitattributes in the +// tree. `!diff` means UNSPECIFIED, so git goes back to sniffing content — +// a fork's `* -diff` (or the `binary` macro) can no longer turn code into +// "Binary files differ", while a real binary stays binary. Works on any +// git; GIT_ATTR_SOURCE would need git 2.40. +// 3. PR-controlled engine configuration goes: `.opencodereview/` is removed, +// and the root `.gitignore` — which the engine reads to decide what to +// skip — is replaced by the base revision's (or removed when the base has +// none), so a PR cannot ignore its own changes. +// +// Prints a JSON report to stdout. Exits 1 if any step fails: a checkout that +// could not be hardened must not be reviewed as if it had been. + +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; + +const argv = process.argv.slice(2); +const opts = { dir: process.cwd(), base: "" }; +for (let i = 0; i < argv.length; i += 1) { + if (argv[i] === "--dir") opts.dir = argv[++i]; + else if (argv[i] === "--base") opts.base = argv[++i]; +} + +const fail = (msg) => { + console.error(`harden-checkout: ${msg}`); + process.exit(1); +}; + +const git = (...args) => + spawnSync("git", ["-c", "core.quotepath=false", ...args], { + cwd: opts.dir, + encoding: "utf8", + maxBuffer: 1 << 28, + }); + +const top = git("rev-parse", "--show-toplevel"); +if (top.status !== 0) fail(`not a git checkout: ${opts.dir}`); +const workTree = top.stdout.trim(); + +// ---- 1. symlinks --------------------------------------------------------- +const removed = []; +const unlinkLink = (abs) => { + let st; + try { + st = fs.lstatSync(abs); + } catch { + return; // already gone + } + if (!st.isSymbolicLink()) return; + fs.unlinkSync(abs); + removed.push(path.relative(workTree, abs)); +}; + +try { + // Tracked links first, by mode — the index is the authority on what the PR + // committed, whatever the work tree looks like. + const ls = git("ls-files", "-s", "-z"); + if (ls.status !== 0) throw new Error(ls.stderr.trim() || "git ls-files failed"); + for (const rec of ls.stdout.split("\0")) { + if (!rec.startsWith("120000 ")) continue; + const rel = rec.slice(rec.indexOf("\t") + 1); + unlinkLink(path.join(workTree, rel)); + } + // Then everything else on disk, untracked included. lstat-based: a link to a + // directory is removed, never descended into. + const walk = (d) => { + for (const e of fs.readdirSync(d, { withFileTypes: true })) { + const abs = path.join(d, e.name); + if (d === workTree && e.name === ".git") continue; + if (e.isSymbolicLink()) unlinkLink(abs); + else if (e.isDirectory()) walk(abs); + } + }; + walk(workTree); +} catch (e) { + fail(`could not remove symlinks (${e.message})`); +} + +// ---- 2. attributes ------------------------------------------------------- +const attrPath = (() => { + const r = git("rev-parse", "--git-path", "info/attributes"); + if (r.status !== 0) fail("cannot locate $GIT_DIR/info/attributes"); + return path.resolve(workTree, r.stdout.trim()); +})(); +try { + fs.mkdirSync(path.dirname(attrPath), { recursive: true }); + const prior = fs.existsSync(attrPath) ? fs.readFileSync(attrPath, "utf8") : ""; + if (!/^\* !diff$/m.test(prior)) { + fs.writeFileSync(attrPath, `${prior}${prior && !prior.endsWith("\n") ? "\n" : ""}* !diff\n`); + } +} catch (e) { + fail(`could not neutralise repository attributes (${e.message})`); +} + +// ---- 3. PR-controlled engine config ---------------------------------------- +try { + fs.rmSync(path.join(workTree, ".opencodereview"), { recursive: true, force: true }); +} catch (e) { + fail(`could not remove .opencodereview (${e.message})`); +} +let gitignore = "unchanged"; +if (opts.base) { + const ignorePath = path.join(workTree, ".gitignore"); + const atBase = git("show", `${opts.base}:.gitignore`); + try { + fs.rmSync(ignorePath, { force: true, recursive: true }); + if (atBase.status === 0) { + fs.writeFileSync(ignorePath, atBase.stdout); + gitignore = "base"; + } else { + gitignore = "removed"; + } + } catch (e) { + fail(`could not restore the base .gitignore (${e.message})`); + } +} + +process.stdout.write(`${JSON.stringify({ removed_symlinks: removed, attributes: attrPath, gitignore })}\n`); diff --git a/scripts/harden-checkout.test.mjs b/scripts/harden-checkout.test.mjs new file mode 100644 index 0000000..2dec4ba --- /dev/null +++ b/scripts/harden-checkout.test.mjs @@ -0,0 +1,220 @@ +// harden-checkout.mjs — what the action does to the PR checkout before +// anything reads it, and excluded-files.mjs — what it tells the reader the +// engine did NOT review. +// +// The checkout is fork-controlled, and three things in it could steer the +// review without touching a line of reviewed code: +// - SYMLINKS. A link committed as `notes.md -> /proc/self/environ` (or to a +// runner credential file) lets an engine whose tools read "files in the +// repo" read outside it. Every symlink — tracked (mode 120000) or not — is +// deleted before the engine runs. +// - .gitattributes. `* -diff` turns every changed file into "Binary files +// differ", so both the size guard and the engine see no code. Repository +// attributes are neutralised for `diff` with `* !diff` in +// $GIT_DIR/info/attributes, which outranks every .gitattributes and puts +// git back on content sniffing (works on any git version, unlike +// GIT_ATTR_SOURCE, which needs 2.40). +// - the root .gitignore, which the engine reads to decide what to skip. It is +// restored from the base revision, so a PR cannot ignore its own changes. +// And what the engine skips by default (tests, fixtures, generated code, +// unsupported file types) is listed, so a reviewer sees what was not reviewed. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { after, before, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +const SCRIPTS = path.dirname(new URL(import.meta.url).pathname); +const HARDEN = path.join(SCRIPTS, "harden-checkout.mjs"); +const EXCLUDED = path.join(SCRIPTS, "excluded-files.mjs"); + +let root; +before(() => { + root = fs.mkdtempSync(path.join(os.tmpdir(), "harden-")); +}); +after(() => fs.rmSync(root, { recursive: true, force: true })); + +const ENV = { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }; +const git = (cwd, ...args) => { + const r = spawnSync("git", args, { cwd, encoding: "utf8", env: ENV }); + assert.equal(r.status, 0, `git ${args.join(" ")}: ${r.stderr}`); + return r.stdout; +}; + +let n = 0; +function repo(base, head) { + n += 1; + const dir = path.join(root, `r${n}`); + fs.mkdirSync(dir); + git(dir, "init", "-q", "-b", "main"); + base(dir); + git(dir, "add", "-A"); + git(dir, "commit", "-q", "-m", "base"); + const baseSha = git(dir, "rev-parse", "HEAD").trim(); + head(dir); + git(dir, "add", "-A"); + git(dir, "commit", "-q", "-m", "head"); + return { dir, base: baseSha, head: git(dir, "rev-parse", "HEAD").trim() }; +} + +const write = (dir, rel, text) => { + fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true }); + fs.writeFileSync(path.join(dir, rel), text); +}; + +const harden = (dir, base) => + spawnSync("node", [HARDEN, "--dir", dir, ...(base ? ["--base", base] : [])], { encoding: "utf8" }); + +function symlinksIn(dir) { + const out = []; + const walk = (d) => { + for (const e of fs.readdirSync(d, { withFileTypes: true })) { + if (e.name === ".git") continue; + const p = path.join(d, e.name); + if (e.isSymbolicLink()) out.push(path.relative(dir, p)); + else if (e.isDirectory()) walk(p); + } + }; + walk(dir); + return out.sort(); +} + +describe("symlinks in the checkout are removed", () => { + test("tracked, untracked and directory symlinks are all deleted; regular files stay", () => { + const r = repo( + (d) => write(d, "app.js", "export const a = 1;\n"), + (d) => { + fs.symlinkSync("/proc/self/environ", path.join(d, "notes.md")); // tracked (mode 120000) + fs.mkdirSync(path.join(d, "docs")); + fs.symlinkSync("/etc", path.join(d, "docs", "etc")); // tracked, to a directory + }, + ); + fs.symlinkSync("/root", path.join(r.dir, "untracked-link")); // never committed + assert.match(git(r.dir, "ls-files", "-s"), /^120000 /m, "fixture: a tracked symlink exists"); + assert.equal(symlinksIn(r.dir).length, 3); + + const res = harden(r.dir, r.base); + assert.equal(res.status, 0, res.stderr); + assert.deepEqual(symlinksIn(r.dir), []); + assert.ok(fs.existsSync(path.join(r.dir, "app.js"))); + }); +}); + +describe("repository attributes cannot hide the diff", () => { + test("`* -diff` in a PR's .gitattributes no longer turns code into 'Binary files differ'", () => { + const r = repo( + (d) => write(d, "app.js", "export const a = 1;\n"), + (d) => { + write(d, ".gitattributes", "* -diff\n"); + write(d, "app.js", "export const a = 2; // eval(userInput)\n"); + }, + ); + const before = git(r.dir, "diff", r.base, r.head); + assert.match(before, /Binary files .* differ/, "fixture: the attribute hides the change"); + + const res = harden(r.dir, r.base); + assert.equal(res.status, 0, res.stderr); + const afterDiff = git(r.dir, "diff", r.base, r.head); + assert.doesNotMatch(afterDiff, /Binary files .*app\.js.* differ/); + assert.match(afterDiff, /\+export const a = 2; \/\/ eval\(userInput\)/); + }); + + test("the `binary` macro is neutralised too, while real binary content stays binary", () => { + const r = repo( + (d) => write(d, "a.js", "x\n"), + (d) => { + write(d, "sub/.gitattributes", "*.js binary\n"); + write(d, "sub/b.js", "const evil = 1;\n"); + fs.writeFileSync(path.join(d, "img.bin"), Buffer.from([0, 1, 2, 0, 255, 0])); + }, + ); + assert.equal(harden(r.dir, r.base).status, 0); + const d = git(r.dir, "diff", r.base, r.head); + assert.match(d, /\+const evil = 1;/); + assert.match(d, /Binary files \/dev\/null and b\/img\.bin differ/); + }); +}); + +describe("the root .gitignore is the base revision's", () => { + test("a PR cannot ignore its own change from the engine", () => { + const r = repo( + (d) => { + write(d, ".gitignore", "node_modules/\n"); + write(d, "auth.js", "check()\n"); + }, + (d) => { + write(d, ".gitignore", "node_modules/\nauth.js\n"); + write(d, "auth.js", "/* removed the check */\n"); + }, + ); + assert.equal(harden(r.dir, r.base).status, 0); + assert.equal(fs.readFileSync(path.join(r.dir, ".gitignore"), "utf8"), "node_modules/\n"); + }); + + test("a .gitignore the base did not have is removed", () => { + const r = repo( + (d) => write(d, "a.js", "x\n"), + (d) => write(d, ".gitignore", "*.js\n"), + ); + assert.equal(harden(r.dir, r.base).status, 0); + assert.equal(fs.existsSync(path.join(r.dir, ".gitignore")), false); + }); + + test("PR-controlled engine config (.opencodereview/) is removed", () => { + const r = repo( + (d) => write(d, "a.js", "x\n"), + (d) => write(d, ".opencodereview/rule.json", '{"exclude":["**"]}'), + ); + assert.equal(harden(r.dir, r.base).status, 0); + assert.equal(fs.existsSync(path.join(r.dir, ".opencodereview")), false); + }); +}); + +describe("excluded-files.mjs lists what the engine skips", () => { + test("tests, fixtures, generated code, binaries and unsupported types are listed with a reason; reviewed code is not", () => { + const r = repo( + (d) => write(d, "src/a.js", "a\n"), + (d) => { + write(d, "src/a.js", "b\n"); + write(d, "src/a.test.js", "test\n"); + write(d, "fixtures/data.json", "{}\n"); + write(d, "api.pb.go", "package x\n"); + fs.writeFileSync(path.join(d, "logo.png"), Buffer.from([0x89, 0x50, 0x4e, 0x47, 0, 0, 0, 0])); + }, + ); + const out = path.join(root, `excluded-${n}.json`); + const res = spawnSync("node", [EXCLUDED, "--base", r.base, "--head", r.head, "--out", out], { + cwd: r.dir, + encoding: "utf8", + }); + assert.equal(res.status, 0, res.stderr); + const got = JSON.parse(fs.readFileSync(out, "utf8")); + const paths = Object.fromEntries(got.excluded.map((e) => [e.path, e.code])); + assert.equal(paths["src/a.js"], undefined, "reviewed code must not be listed"); + assert.equal(paths["src/a.test.js"], "default_path"); + assert.equal(paths["fixtures/data.json"], "default_path"); + assert.equal(paths["api.pb.go"], "default_path"); + assert.equal(paths["logo.png"], "binary"); + for (const e of got.excluded) assert.ok(e.reason, `${e.path} has no reason`); + }); + + test("a long list is capped and says how many it left out", () => { + const r = repo( + (d) => write(d, "a.js", "a\n"), + (d) => { + for (let i = 0; i < 260; i += 1) write(d, `fixtures/f${i}.json`, "{}\n"); + }, + ); + const out = path.join(root, `excluded-cap-${n}.json`); + const res = spawnSync("node", [EXCLUDED, "--base", r.base, "--head", r.head, "--out", out], { + cwd: r.dir, + encoding: "utf8", + }); + assert.equal(res.status, 0, res.stderr); + const got = JSON.parse(fs.readFileSync(out, "utf8")); + assert.equal(got.excluded.length, 200); + assert.equal(got.omitted, 60); + }); +}); diff --git a/scripts/identity.mjs b/scripts/identity.mjs new file mode 100644 index 0000000..026ec2b --- /dev/null +++ b/scripts/identity.mjs @@ -0,0 +1,85 @@ +// WHO THE ACTION POSTS AS — the one funnel that decides which comments are the +// action's own. +// +// The action finds its earlier comments by an HTML marker () to edit a notice in place or delete a stale one. A marker +// counts only in a comment its own identity wrote; otherwise anyone could plant +// one and have the action edit or delete THEIR comment. So the identity must be +// right, and must never be a guess: +// +// 1. the `bot-login` input, when the workflow sets it (a custom GitHub App: +// "my-app[bot]"); +// 2. else the token's user (users.getAuthenticated — a personal token); +// 3. else github-actions[bot], but ONLY when github-token is the job's own +// GITHUB_TOKEN — the one installation token whose author we know; +// 4. else unknown, until the action's first comment or review in this run: +// GitHub reports its author back, and that login is recorded in +// $RUNNER_TEMP/cr-identity for the rest of the run. +// Unknown matches nothing — post anew, edit and delete nothing. +// +// Steps 1-3 run once ("Resolve PR refs", resolveIdentity) and reach every later +// step as BOT_LOGIN; step 4 is recorded by guardGithub (publish-guard.mjs) on +// the way back from every comment or review it creates. + +import fs from "node:fs"; +import path from "node:path"; + +export const JOB_TOKEN_LOGIN = "github-actions[bot]"; +const FILE = "cr-identity"; + +// A GitHub login (alphanumerics and single hyphens, up to 39) or an App's bot +// login (the same with "[bot]"). +const LOGIN = /^[A-Za-z0-9](?:[A-Za-z0-9]|-(?=[A-Za-z0-9])){0,38}(?:\[bot\])?$/; +const valid = (l) => typeof l === "string" && LOGIN.test(l); + +const recordPath = () => (process.env.RUNNER_TEMP ? path.join(process.env.RUNNER_TEMP, FILE) : null); + +/** Steps 1-3. `{ login: "" }` when only step 4 can tell. */ +export async function resolveIdentity({ github, botLogin = "", tokenIsJobToken = false } = {}) { + const explicit = String(botLogin || "").trim(); + if (explicit) { + if (!valid(explicit)) throw new Error(`bot-login ${JSON.stringify(explicit)} is not a GitHub login`); + return { login: explicit, source: "the bot-login input" }; + } + try { + const { data } = await github.rest.users.getAuthenticated(); + if (valid(data?.login)) return { login: data.login, source: "the token's user" }; + } catch { + // An installation token has no user: fall through. + } + if (tokenIsJobToken) return { login: JOB_TOKEN_LOGIN, source: "the job's GITHUB_TOKEN" }; + return { login: "", source: "unknown until the action posts in this run (set bot-login)" }; +} + +/** The identity for this step: the resolved one, else the one recorded this run. */ +export function ownLogin() { + const resolved = String(process.env.BOT_LOGIN || "").trim(); + if (resolved) return resolved; + const p = recordPath(); + if (!p) return ""; + try { + const l = fs.readFileSync(p, "utf8").trim(); + return valid(l) ? l : ""; + } catch { + return ""; + } +} + +/** Step 4: learn the identity from what GitHub says the action just created. */ +export function recordIdentity(response) { + if (ownLogin()) return; + const login = response?.data?.user?.login; + const p = recordPath(); + if (!p || !valid(login)) return; + try { + fs.writeFileSync(p, login, { flag: "wx", mode: 0o600 }); // the first one wins + } catch { + // Already recorded (or RUNNER_TEMP is not writable): nothing to learn. + } +} + +/** Is this comment the action's own? False whenever the identity is unknown. */ +export function isOwn(comment) { + const login = ownLogin(); + return Boolean(login) && Boolean(comment?.body) && comment?.user?.login === login; +} diff --git a/scripts/install-engine.mjs b/scripts/install-engine.mjs new file mode 100644 index 0000000..161393b --- /dev/null +++ b/scripts/install-engine.mjs @@ -0,0 +1,158 @@ +#!/usr/bin/env node +// Install the review engine (@alibaba-group/open-code-review) from pinned, +// verified bytes, with no install scripts. +// +// node install-engine.mjs --version --prefix

+// [--pins ] (default: next to this script) +// [--tarball ] (default: `npm pack` from the registry) +// [--binary ] (default: download the pinned URL) +// +// The engine is two artifacts: an npm package that is only a node wrapper +// (bin/ocr.js) plus a postinstall, and a ~40 MB Go binary the postinstall +// downloads from the GitHub release and checks against a checksum file fetched +// from that SAME release — no independent pin. So both are pinned here, in +// scripts/engine-pins.json, per version: +// 1. the npm tarball is fetched (`npm pack --ignore-scripts`) and its sha512 +// compared with the pinned SRI integrity BEFORE anything is unpacked; +// 2. it is installed with `npm install -g --ignore-scripts --offline` from +// that local file into --prefix (the package has no dependencies, so +// nothing else is fetched and no lifecycle script runs); +// 3. the platform's binary is downloaded from the pinned URL and its sha256 +// compared with the pinned value, then placed where the wrapper looks. +// Any mismatch, missing pin or failure exits 1 and removes --prefix: there is +// no "install anyway". Prints the directory to put on PATH (/bin). +// +// A version not in the pins file is refused. Bumping the engine means adding +// its pins (registry `dist.integrity`, and the release's sha256 for each +// binary, verified by downloading them) in the same change as the bump. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import crypto from "node:crypto"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; + +const HERE = path.dirname(fileURLToPath(import.meta.url)); +const PKG = "@alibaba-group/open-code-review"; + +const argv = process.argv.slice(2); +const opts = { pins: path.join(HERE, "engine-pins.json") }; +for (let i = 0; i < argv.length; i += 1) { + const k = argv[i]; + if (["--version", "--prefix", "--pins", "--tarball", "--binary"].includes(k)) opts[k.slice(2)] = argv[++i]; +} + +let prefixCreated = false; +const fail = (msg) => { + console.error(`install-engine: ${msg}`); + if (prefixCreated) fs.rmSync(opts.prefix, { recursive: true, force: true }); + process.exit(1); +}; + +if (!opts.version || !opts.prefix) fail("usage: --version --prefix [--pins f] [--tarball f] [--binary f]"); + +let pins; +try { + pins = JSON.parse(fs.readFileSync(opts.pins, "utf8")); +} catch (e) { + fail(`cannot read the pinned checksums (${e.message})`); +} +const pin = pins[opts.version]; +if (!pin || typeof pin.integrity !== "string" || !pin.binaries) { + fail( + `engine-version ${opts.version} has no pinned checksums in this release of the action ` + + `(pinned: ${Object.keys(pins).join(", ") || "none"}). Use a pinned version, or upgrade the action.`, + ); +} +const key = `${process.platform}-${process.arch}`; +const binPin = pin.binaries[key]; +if (!binPin || !/^[0-9a-f]{64}$/.test(binPin.sha256 || "") || !/^https:\/\//.test(binPin.url || "")) { + fail(`engine ${opts.version} has no pinned binary for ${key} (pinned: ${Object.keys(pin.binaries).join(", ")})`); +} + +const work = fs.mkdtempSync(path.join(os.tmpdir(), "ocr-engine-")); +const cleanupWork = () => fs.rmSync(work, { recursive: true, force: true }); +process.on("exit", cleanupWork); + +// ---- 1. the npm tarball, verified before use ------------------------------- +let tarball = opts.tarball; +if (!tarball) { + const r = spawnSync( + "npm", + ["pack", `${PKG}@${opts.version}`, "--ignore-scripts", "--pack-destination", work, "--json"], + { encoding: "utf8" }, + ); + if (r.status !== 0) fail(`npm pack ${PKG}@${opts.version} failed: ${(r.stderr || "").trim().split("\n").pop()}`); + let name; + try { + name = JSON.parse(r.stdout)[0].filename; + } catch { + fail("npm pack printed no filename"); + } + tarball = path.join(work, path.basename(name)); +} +let tgz; +try { + tgz = fs.readFileSync(tarball); +} catch (e) { + fail(`cannot read the engine tarball (${e.message})`); +} +const [algo, expected] = pin.integrity.split(/-(.+)/); +if (algo !== "sha512" || !expected) fail(`pinned integrity for ${opts.version} is not a sha512 SRI`); +const actual = crypto.createHash("sha512").update(tgz).digest("base64"); +if (actual !== expected) { + fail(`the ${PKG}@${opts.version} tarball does not match its pinned integrity (got sha512-${actual}) — refusing to install it`); +} + +// ---- 2. the engine binary, verified before anything is installed ----------- +let binary; +if (opts.binary) { + try { + binary = fs.readFileSync(opts.binary); + } catch (e) { + fail(`cannot read the engine binary (${e.message})`); + } +} else { + // curl, not fetch: it honours a self-hosted runner's proxy settings, and + // --proto keeps every hop of GitHub's release redirect on https. + const dest = path.join(work, "opencodereview"); + const r = spawnSync( + "curl", + ["-fsSL", "--proto", "=https", "--proto-redir", "=https", "--retry", "3", "-o", dest, binPin.url], + { encoding: "utf8" }, + ); + if (r.error) fail(`curl is needed to download the engine binary (${r.error.message})`); + if (r.status !== 0) fail(`downloading ${binPin.url} failed: ${(r.stderr || "").trim()}`); + binary = fs.readFileSync(dest); +} +const binSha = crypto.createHash("sha256").update(binary).digest("hex"); +if (binSha !== binPin.sha256) { + fail(`the engine binary for ${key} does not match its pinned sha256 (got ${binSha}) — refusing to install it`); +} + +// ---- 3. install, scripts off, nothing else fetched ---------------------------- +fs.rmSync(opts.prefix, { recursive: true, force: true }); +fs.mkdirSync(opts.prefix, { recursive: true }); +prefixCreated = true; +const local = path.join(work, "engine.tgz"); +fs.writeFileSync(local, tgz); // exactly the bytes that were verified +const r = spawnSync( + "npm", + ["install", "-g", "--prefix", opts.prefix, "--ignore-scripts", "--offline", "--no-audit", "--no-fund", local], + { encoding: "utf8" }, +); +if (r.status !== 0) fail(`npm install from the verified tarball failed: ${(r.stderr || "").trim().split("\n").pop()}`); + +const pkgDir = path.join(opts.prefix, "lib", "node_modules", ...PKG.split("/")); +const wrapper = path.join(opts.prefix, "bin", "ocr"); +if (!fs.existsSync(path.join(pkgDir, "package.json")) || !fs.existsSync(wrapper)) { + fail("the installed package is missing its wrapper (bin/ocr)"); +} +const binDest = path.join(pkgDir, "bin", "opencodereview"); +fs.mkdirSync(path.dirname(binDest), { recursive: true }); +fs.writeFileSync(binDest, binary, { mode: 0o755 }); +fs.chmodSync(binDest, 0o755); + +console.error(`install-engine: ${PKG}@${opts.version} (${key}) installed from verified bytes into ${opts.prefix}`); +process.stdout.write(`${path.join(opts.prefix, "bin")}\n`); diff --git a/scripts/install-engine.test.mjs b/scripts/install-engine.test.mjs new file mode 100644 index 0000000..83f200a --- /dev/null +++ b/scripts/install-engine.test.mjs @@ -0,0 +1,200 @@ +// CR-9: the review engine's supply chain. +// +// The action used to run `npm install -g "@alibaba-group/open-code-review@1.3.13"`: +// the version pin covered the top-level package only, install scripts ran (the +// package's postinstall downloads a 40 MB Go binary and checks it against a +// checksum file fetched from the SAME release — no independent pin), and +// nothing checked the tarball's integrity. Its own `uses:` steps were tags. +// +// scripts/install-engine.mjs now: refuses any engine-version without pinned +// checksums in scripts/engine-pins.json; verifies the npm tarball against the +// pinned sha512 SRI before installing it with --ignore-scripts into a prefix +// under $RUNNER_TEMP; downloads the platform binary itself and verifies it +// against the pinned sha256. Every failure fails closed, and nothing is left +// installed. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import crypto from "node:crypto"; +import { spawnSync } from "node:child_process"; +import { after, before, describe, test } from "node:test"; +import assert from "node:assert/strict"; +import YAML from "yaml"; + +import { step, readText, actionSteps } from "./test-helpers/action-yaml.mjs"; + +const SCRIPTS = path.dirname(new URL(import.meta.url).pathname); +const INSTALLER = path.join(SCRIPTS, "install-engine.mjs"); +const PINS = JSON.parse(fs.readFileSync(path.join(SCRIPTS, "engine-pins.json"), "utf8")); + +let dir; +before(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "install-engine-")); +}); +after(() => fs.rmSync(dir, { recursive: true, force: true })); + +const sri = (buf) => `sha512-${crypto.createHash("sha512").update(buf).digest("base64")}`; +const sha256 = (buf) => crypto.createHash("sha256").update(buf).digest("hex"); +const platformKey = `${process.platform}-${process.arch}`; + +let n = 0; +// A stand-in engine package whose postinstall would leave a marker if it ran. +function fakeEngine() { + n += 1; + const root = path.join(dir, `pkg${n}`); + const pkg = path.join(root, "package"); + fs.mkdirSync(path.join(pkg, "bin"), { recursive: true }); + const marker = path.join(root, "postinstall-ran"); + fs.writeFileSync( + path.join(pkg, "package.json"), + JSON.stringify({ + name: "@alibaba-group/open-code-review", + version: "9.9.9", + bin: { ocr: "bin/ocr.js" }, + scripts: { postinstall: `node -e "require('fs').writeFileSync('${marker}','ran')"` }, + }), + ); + fs.writeFileSync(path.join(pkg, "bin", "ocr.js"), "#!/usr/bin/env node\nconsole.log('ocr wrapper');\n"); + const tgz = path.join(root, "engine.tgz"); + const r = spawnSync("tar", ["-czf", tgz, "-C", root, "package"]); + assert.equal(r.status, 0, String(r.stderr)); + const binary = path.join(root, "opencodereview"); + fs.writeFileSync(binary, `#!/bin/sh\necho engine ${n}\n`); + const pins = path.join(root, "pins.json"); + const tgzBuf = fs.readFileSync(tgz); + fs.writeFileSync( + pins, + JSON.stringify({ + "9.9.9": { + integrity: sri(tgzBuf), + binaries: { [platformKey]: { url: "https://example.invalid/opencodereview", sha256: sha256(fs.readFileSync(binary)) } }, + }, + }), + ); + return { root, tgz, binary, pins, marker }; +} + +const install = (args) => spawnSync("node", [INSTALLER, ...args], { encoding: "utf8" }); + +describe("the pinned checksums", () => { + test("1.3.13 (the default engine-version) is pinned to the published tarball and release binaries", () => { + const p = PINS["1.3.13"]; + assert.equal(p.integrity, "sha512-XAWyBlKOcf/wIspLc2FHo4iVV9XF2lxpSI/jGhOkXxFOmYnw+mnL5nXc0U+QyJBfVi9vmvTirQ0/Y3NfyrXwjQ=="); + assert.equal(p.binaries["linux-x64"].sha256, "6d51ce0b18236e6c13ab24f38f70e861052439d2c675311f58fbd85e0194fd81"); + assert.equal(p.binaries["linux-arm64"].sha256, "e78b69718554ff3c4db7a90e30705ddb4100a2541025e384566dfc0b092fd5b3"); + for (const b of Object.values(p.binaries)) assert.match(b.url, /^https:\/\/github\.com\/alibaba\/open-code-review\/releases\/download\/v1\.3\.13\//); + }); + + test("the action's engine-version default has pins", () => { + const def = YAML.parse(readText("action.yml")).inputs["engine-version"].default; + assert.ok(PINS[def], `engine-version default ${def} has no pinned checksums`); + }); +}); + +describe("install-engine.mjs", () => { + test("a verified tarball installs WITHOUT running its install scripts, and the verified binary lands next to the wrapper", () => { + const e = fakeEngine(); + const prefix = path.join(e.root, "prefix"); + const r = install(["--version", "9.9.9", "--prefix", prefix, "--pins", e.pins, "--tarball", e.tgz, "--binary", e.binary]); + assert.equal(r.status, 0, r.stderr); + assert.equal(fs.existsSync(e.marker), false, "the package's postinstall ran"); + assert.equal(r.stdout.trim(), path.join(prefix, "bin")); + assert.ok(fs.existsSync(path.join(prefix, "bin", "ocr"))); + const placed = path.join(prefix, "lib", "node_modules", "@alibaba-group", "open-code-review", "bin", "opencodereview"); + assert.deepEqual(fs.readFileSync(placed), fs.readFileSync(e.binary)); + assert.ok(fs.statSync(placed).mode & 0o100, "the engine binary is not executable"); + }); + + test("an engine-version with no pins is refused (fail closed)", () => { + const e = fakeEngine(); + const prefix = path.join(e.root, "prefix"); + const r = install(["--version", "1.0.0", "--prefix", prefix, "--pins", e.pins, "--tarball", e.tgz, "--binary", e.binary]); + assert.notEqual(r.status, 0); + assert.match(r.stderr, /no pinned checksums/i); + assert.equal(fs.existsSync(path.join(prefix, "bin", "ocr")), false); + }); + + test("a tarball that does not match the pinned integrity is refused before anything is installed", () => { + const e = fakeEngine(); + fs.appendFileSync(e.tgz, Buffer.from([0])); + const prefix = path.join(e.root, "prefix"); + const r = install(["--version", "9.9.9", "--prefix", prefix, "--pins", e.pins, "--tarball", e.tgz, "--binary", e.binary]); + assert.notEqual(r.status, 0); + assert.match(r.stderr, /integrity/i); + assert.equal(fs.existsSync(path.join(prefix, "bin", "ocr")), false); + }); + + test("a binary that does not match the pinned sha256 is refused and nothing is left installed", () => { + const e = fakeEngine(); + fs.appendFileSync(e.binary, "tampered"); + const prefix = path.join(e.root, "prefix"); + const r = install(["--version", "9.9.9", "--prefix", prefix, "--pins", e.pins, "--tarball", e.tgz, "--binary", e.binary]); + assert.notEqual(r.status, 0); + assert.match(r.stderr, /sha256/i); + assert.equal(fs.existsSync(path.join(prefix, "bin", "ocr")), false); + }); + + test("a platform with no pinned binary is refused", () => { + const e = fakeEngine(); + const pins = JSON.parse(fs.readFileSync(e.pins, "utf8")); + pins["9.9.9"].binaries = { "plan9-mips": { url: "https://x.invalid/b", sha256: "0".repeat(64) } }; + fs.writeFileSync(e.pins, JSON.stringify(pins)); + const r = install(["--version", "9.9.9", "--prefix", path.join(e.root, "p"), "--pins", e.pins, "--tarball", e.tgz, "--binary", e.binary]); + assert.notEqual(r.status, 0); + assert.match(r.stderr, new RegExp(platformKey)); + }); +}); + +describe("action.yml installs the engine through the verifier", () => { + test("the install step runs install-engine.mjs and puts its prefix on PATH", () => { + const s = step("Install review engine"); + assert.match(s.env.INSTALLER, /scripts\/install-engine\.mjs$/); + assert.match(s.env.ENGINE_PREFIX, /runner\.temp/); + assert.match(s.run, /node "\$INSTALLER" --version "\$ENGINE_VERSION" --prefix "\$ENGINE_PREFIX"/); + assert.match(s.run, /GITHUB_PATH/); + }); + + test("no step installs an npm package with its scripts enabled", () => { + for (const st of actionSteps()) { + for (const line of String(st.run || "").split("\n")) { + if (/^\s*#/.test(line)) continue; + if (/\bnpm\s+(install|i|ci)\b/.test(line)) { + assert.match(line, /--ignore-scripts/, `${st.name}: ${line.trim()}`); + } + } + } + }); +}); + +describe("every uses: is pinned to a commit SHA with its version in a comment", () => { + // Comments are read through the parser's document model (a trailing comment + // belongs to the scalar it follows), not by matching lines of text. + function usesNodes(rel) { + const doc = YAML.parseDocument(readText(rel)); + const out = []; + YAML.visit(doc, { + Pair(_, pair) { + if (YAML.isScalar(pair.key) && pair.key.value === "uses" && YAML.isScalar(pair.value)) out.push(pair.value); + }, + }); + return out; + } + + for (const rel of [ + "action.yml", + ".github/workflows/test.yml", + ".github/workflows/self-review.yml", + ".github/workflows/publish.yml", + ".github/workflows/deprecate.yml", + ]) { + test(rel, () => { + const nodes = usesNodes(rel).filter((v) => !String(v.value).startsWith("./")); + assert.ok(nodes.length > 0 || rel !== "action.yml", "found no uses: in action.yml — is the parser blind?"); + for (const v of nodes) { + assert.match(String(v.value), /^[\w.-]+\/[\w.-]+@[0-9a-f]{40}$/, `${rel}: ${v.value} is not pinned to a full SHA`); + assert.match(String(v.comment || ""), /^\s*v\d+\.\d+\.\d+\s*$/, `${rel}: ${v.value} has no "# vX.Y.Z" comment`); + } + }); + } +}); diff --git a/scripts/installer.test.mjs b/scripts/installer.test.mjs index b0b7efa..9b92206 100644 --- a/scripts/installer.test.mjs +++ b/scripts/installer.test.mjs @@ -65,7 +65,9 @@ test("importing the CLI runs nothing", () => { { encoding: "utf8" }, ); assert.equal(r.status, 0, r.stderr); - assert.equal(r.stdout.trim(), "DEFAULTS,parseOverrides,readOverrides,renderWorkflow"); + // ACTION_SHA / ACTION_VERSION joined the exports: the release the generated + // workflow pins is read by release-pin.test.mjs and by publish.yml's gate. + assert.equal(r.stdout.trim(), "ACTION_SHA,ACTION_VERSION,DEFAULTS,EVERY_ASSOCIATION,authorChoices,parseOverrides,readOverrides,renderWorkflow"); }); test("the published version matches package.json", () => { @@ -294,7 +296,7 @@ const section = (yaml, key) => { return [lines[start], ...(end === -1 ? rest : rest.slice(0, end))].join("\n"); }; -for (const key of ["permissions", "on", "concurrency"]) { +for (const key of ["permissions", "on"]) { test(`the example workflow and the skill template agree on \`${key}:\``, () => { const a = section(EXAMPLE, key); const b = section(TEMPLATE, key); @@ -303,6 +305,24 @@ for (const key of ["permissions", "on", "concurrency"]) { }); } +// Concurrency moved from the workflow to the job (a workflow-level group let +// any comment cancel an in-flight review), so this compares the PARSED job +// blocks — of all three copies, the installer's rendered one included — rather +// than a top-level `concurrency:` section that must no longer exist. +test("all three workflow copies agree on the review job's concurrency, if and permissions", async () => { + const YAML = (await import("yaml")).default; + const docs = [EXAMPLE, TEMPLATE, renderWorkflow({ ...DEFAULTS })].map((t) => YAML.parse(t)); + for (const d of docs) assert.equal(d.concurrency, undefined, "no workflow-level concurrency"); + const shape = (d) => ({ + on: d.on, + permissions: d.permissions, + concurrency: d.jobs.review.concurrency, + if: d.jobs.review.if, + }); + assert.deepEqual(shape(docs[1]), shape(docs[0]), "skill template drifted from the example"); + assert.deepEqual(shape(docs[2]), shape(docs[0]), "the installer's workflow drifted from the example"); +}); + test("neither workflow copy mentions a tier label that no longer exists", () => { // There is no add/remove-label step in action.yml. `issues: write` is still // required — for PR comments and the /orcacode-review reaction — so the @@ -440,3 +460,22 @@ test("an unknown --mode is refused by name, with the choices", (t) => { assert.match(r.stderr, /Unknown mode "remote"/); assert.match(r.stderr, /both \| local \| action/); }); + +// ------------------------------------------------- public-repo author default --- + +// "Everyone" must mean everyone to the release the generated workflow PINS as +// well as to the next one: unset means everyone to v1.6.0 but maintainers-only +// on a public repo to the next release, and "*" means everyone to the next +// release but nobody to v1.6.0. So it is written as the full association list +// (scripts/pinned-release.test.mjs runs every answer through both gates). +test('the public-repo "Everyone" answer writes every association, not "*" and not the default', async () => { + const { authorChoices, EVERY_ASSOCIATION } = await import(CLI); + const choices = authorChoices((k) => k); + const everyone = choices.find((c) => c.label === "config.authorsAll"); + assert.equal(everyone.value, EVERY_ASSOCIATION); + const yaml = renderWorkflow({ ...DEFAULTS, "auto-review-authors": everyone.value }); + assert.match(yaml, new RegExp(`^\\s+auto-review-authors: "${EVERY_ASSOCIATION}"`, "m")); + assert.equal(parseOverrides(yaml)["auto-review-authors"], EVERY_ASSOCIATION); + const known = choices.find((c) => c.recommended); + assert.notEqual(known.value, "", "the recommended answer must be written, not left to a default"); +}); diff --git a/scripts/judge.mjs b/scripts/judge.mjs index 22f1c92..b854649 100644 --- a/scripts/judge.mjs +++ b/scripts/judge.mjs @@ -20,6 +20,7 @@ import fs from "node:fs"; import os from "node:os"; +import { severityOf, moreSevere, withSeverity, isSecurityFinding } from "./severity.mjs"; // A STABLE FIRST LINE, WHATEVER HAPPENS. action.yml lifts the first line of // this script's stderr into the job's user-facing L2 failure reason, so an @@ -257,6 +258,12 @@ for (const g of groups) for (const id of g.member_ids || []) covered.add(id); for (let i = 0; i < findings.length; i += 1) if (!covered.has(i)) groups.push({ member_ids: [i], representative_id: i, confidence: 1.0, keep: true, root_cause: "(uncovered)", reason: "not classified by judge; kept fail-open above any threshold" }); +// THE JUDGE MAY RE-RANK AND ANNOTATE; IT MAY NOT LOSE A P0 OR A SECURITY +// FINDING. Its verdict comes from a model reading text the PR shaped, so a P0 +// (or anything about security) it would drop is kept anyway and the log says +// so. And whichever member represents a cluster, the kept finding carries the +// MOST SEVERE tag in that cluster — clustering a P0 under a P3 must not demote it. +const isProtected = (c) => severityOf(c) === "P0" || isSecurityFinding(c); const kept = []; const dropped = []; for (const g of groups) { @@ -303,11 +310,33 @@ for (const g of groups) { ? g.member_ids.filter((id) => id !== repId) : []; const line = `[conf ${Number.isFinite(boundedConf) ? boundedConf.toFixed(2) : "?"}] ${(rep?.content || "").match(/\[(P[0-3])\]/)?.[0] || ""} ${rep?.path ?? "?"} :: ${g.root_cause} ${others.length ? "(merged " + others.length + ")" : ""}`; + // Every valid member of the cluster, the representative included. + const members = [...new Set([repId, ...(Array.isArray(g.member_ids) ? g.member_ids : [])])] + .filter((id) => Number.isInteger(id) && id >= 0 && id < comments.length && comments[id]) + .map((id) => comments[id]); + const worst = members.reduce((acc, c) => moreSevere(acc, severityOf(c)), "P3"); if (surv) { if (!rep) { console.error("skip malformed judge group (no valid rep): " + JSON.stringify(g).slice(0, 120)); continue; } - kept.push(rep); - console.error("KEEP " + line); - } else { dropped.push(g); console.error("drop " + line + " — " + (g.reason || "")); } + kept.push(severityOf(rep) === worst ? rep : withSeverity(rep, worst)); + console.error("KEEP " + line + (severityOf(rep) === worst ? "" : ` (raised to ${worst}, the cluster's most severe)`)); + continue; + } + const guarded = members.filter(isProtected); + if (guarded.length) { + // Prefer the judge's own representative when it is protected; otherwise + // the most severe protected member. One per cluster, as for a kept group. + const keepRep = isProtected(rep) + ? rep + : guarded.reduce((a, c) => (moreSevere(severityOf(a), severityOf(c)) === severityOf(a) ? a : c)); + kept.push(severityOf(keepRep) === worst ? keepRep : withSeverity(keepRep, worst)); + console.error( + "KEEP* " + line + " — the judge would drop it, but a P0 or security finding cannot be dropped by the judge" + + (g.reason ? ` (judge: ${g.reason})` : ""), + ); + continue; + } + dropped.push(g); + console.error("drop " + line + " — " + (g.reason || "")); } if (out) fs.writeFileSync(out, JSON.stringify({ ...data, comments: kept }, null, 1)); diff --git a/scripts/marker-ownership.test.mjs b/scripts/marker-ownership.test.mjs new file mode 100644 index 0000000..97b3ce3 --- /dev/null +++ b/scripts/marker-ownership.test.mjs @@ -0,0 +1,332 @@ +// CR-15: the action finds its own earlier comments by an HTML marker +// () — to edit a notice in place, or to delete a +// stale one once a review posts. It used to match the marker in ANY comment, so +// anyone who could comment on the PR could plant the marker and have the action +// edit or DELETE that comment (or leave the real notice stale). Now a marker +// counts only in a comment authored by the token's own identity. +// +// That identity was resolved with a guess: when users.getAuthenticated failed +// it ASSUMED github-actions[bot]. It fails for every installation token, so a +// custom GitHub App never matched its own markers (a new notice every push) +// and would have treated github-actions[bot]'s as its own. Now ONE funnel +// (scripts/identity.mjs, used through scripts/publish-guard.mjs) decides: +// 1. the `bot-login` input, when set; +// 2. else the token's user (users.getAuthenticated: a personal token); +// 3. else github-actions[bot] only when github-token IS the job's own token; +// 4. else unknown — until the action's first comment or review in this run, +// whose author GitHub reports back; that login is recorded for the run. +// Unknown matches nothing: post anew, edit and delete nothing. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { step, actionSteps, loadAction, runBashStep, stub, runGithubScript, fakeCore, ROOT } from "./test-helpers/action-yaml.mjs"; + +let dir; +before(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "markers-")); +}); +after(() => fs.rmSync(dir, { recursive: true, force: true })); + +const BOT = "github-actions[bot]"; +const comment = (id, login, body) => ({ id, user: { login, type: login.endsWith("[bot]") ? "Bot" : "User" }, body }); + +function fakeGithub(comments) { + const calls = []; + const rec = (name) => async (args) => { + calls.push({ name, args }); + return { data: {} }; + }; + const github = { + paginate: async () => comments, + rest: { + issues: { + listComments: () => {}, + createComment: rec("createComment"), + updateComment: rec("updateComment"), + deleteComment: rec("deleteComment"), + }, + pulls: { get: async () => ({ data: { body: "" } }), update: rec("pullsUpdate") }, + }, + }; + return { github, calls }; +} + +const BASE_ENV = { + BRAND: "OrcaCode Review", + PR_NUMBER: "7", + BOT_LOGIN: BOT, + PUBLISH_GUARD: path.join(ROOT, "scripts", "publish-guard.mjs"), +}; +const CONTEXT = { repo: { owner: "acme", repo: "widgets" }, payload: { repository: { private: true } } }; + +async function run(name, comments, env) { + const { github, calls } = fakeGithub(comments); + await runGithubScript(step(name).with.script, { github, core: fakeCore().core, context: CONTEXT, env: { ...BASE_ENV, ...env } }); + return calls; +} + +const NOTICES = [ + ["Skip review (settings)", "", { REASON: "on-demand mode", ON_SKIPPED: "pass" }], + [ + "Skip review (diff too large)", + "", + { REASON: "too big", SIZE_KB: "1", FILES: "1", MAX_KB: "1", MAX_FILES: "1", ON_OVERSIZED: "pass" }, + ], +]; + +describe("notice upserts only edit the action's own comment", () => { + for (const [name, marker, env] of NOTICES) { + test(`${name}: a marker planted by another user is never edited`, async () => { + const calls = await run(name, [comment(11, "mallory", `${marker}\nplanted`)], env); + assert.ok(!calls.some((c) => c.name === "updateComment"), "the action edited someone else's comment"); + assert.ok(calls.some((c) => c.name === "createComment"), "the action must post its own notice instead"); + }); + + test(`${name}: its own earlier notice is edited in place`, async () => { + const calls = await run(name, [comment(12, BOT, `${marker}\nold`)], env); + const upd = calls.find((c) => c.name === "updateComment"); + assert.ok(upd, "its own notice was not updated"); + assert.equal(upd.args.comment_id, 12); + }); + } + + test("Surface guardrail / firewall block: a planted marker is never edited", async () => { + const block = path.join(dir, "block.json"); + fs.writeFileSync(block, JSON.stringify({ kind: "guardrail", policyName: "p", detail: "d" })); + const calls = await run("Surface guardrail / firewall block", [comment(13, "mallory", "")], { + POLICY_BLOCK: block, + REPO_PRIVATE: "true", + }); + assert.ok(!calls.some((c) => c.name === "updateComment")); + assert.ok(calls.some((c) => c.name === "createComment")); + }); + + test("no resolved identity matches nothing (fail safe: post anew, edit nothing)", async () => { + const [name, marker, env] = NOTICES[0]; + const calls = await run(name, [comment(14, BOT, marker)], { ...env, BOT_LOGIN: "" }); + assert.ok(!calls.some((c) => c.name === "updateComment")); + }); +}); + +describe("the stale-notice sweep only deletes the action's own comments", () => { + test("planted markers survive; the action's own stale notices go", async () => { + const reported = path.join(dir, "reported.json"); + fs.writeFileSync(reported, JSON.stringify({ comments: [] })); + const comments = [ + comment(21, "mallory", " mine"), + comment(22, "mallory", " mine too"), + comment(23, BOT, " stale"), + ]; + const calls = await run("Summary (PR description)", comments, { + RESULT: reported, + PREV_BODY: path.join(dir, "prev.md"), + SUMMARY_SCRIPT: path.join(ROOT, "scripts", "summary-comment.mjs"), + INJECT_SCRIPT: path.join(ROOT, "scripts", "inject-summary.mjs"), + GATE: path.join(ROOT, "scripts", "gate.mjs"), + BLOCK_ON: "P0,P1", + QUIET: "false", + PASSES: "1", + }); + const deleted = calls.filter((c) => c.name === "deleteComment").map((c) => c.args.comment_id); + assert.deepEqual(deleted, [23]); + }); +}); + +describe("Resolve PR refs resolves the token's identity once", () => { + async function resolveWith(getAuthenticated, env = { TOKEN_IS_JOB_TOKEN: "true", BOT_LOGIN_INPUT: "" }) { + const { core, rec } = fakeCore(); + const github = { + rest: { + users: { getAuthenticated }, + pulls: { get: async () => ({ data: {} }) }, + }, + }; + const context = { + eventName: "pull_request_target", + payload: { + action: "opened", + repository: { default_branch: "main", private: false }, + pull_request: { number: 1, base: { ref: "main" }, head: { sha: "s" }, author_association: "OWNER" }, + }, + repo: { owner: "acme", repo: "widgets" }, + issue: { number: 1 }, + }; + await runGithubScript(step("pr").with.script, { + github, + core, + context, + env: { IDENTITY: path.join(ROOT, "scripts", "identity.mjs"), ...env }, + }); + return rec.outputs.bot_login; + } + const refused = async () => { + const e = new Error("Resource not accessible by integration"); + e.status = 403; + throw e; + }; + + test("the job's own GITHUB_TOKEN (no user behind it) is github-actions[bot]", async () => { + assert.equal(await resolveWith(refused, { TOKEN_IS_JOB_TOKEN: "true" }), BOT); + }); + + test("a personal token is its user's login", async () => { + assert.equal(await resolveWith(async () => ({ data: { login: "octo-maintainer" } })), "octo-maintainer"); + }); + + test("another App's installation token is NOT assumed to be github-actions[bot]: unknown", async () => { + assert.equal(await resolveWith(refused, { TOKEN_IS_JOB_TOKEN: "false", BOT_LOGIN_INPUT: "" }), ""); + }); + + test("the bot-login input names it, ahead of everything else", async () => { + assert.equal(await resolveWith(refused, { TOKEN_IS_JOB_TOKEN: "false", BOT_LOGIN_INPUT: "my-app[bot]" }), "my-app[bot]"); + assert.equal( + await resolveWith(async () => ({ data: { login: "someone" } }), { TOKEN_IS_JOB_TOKEN: "false", BOT_LOGIN_INPUT: " my-app[bot] " }), + "my-app[bot]", + ); + }); + + test("the bot-login input exists, empty by default, and the step is handed it and the job-token test", () => { + assert.equal(loadAction().inputs["bot-login"].default, ""); + const env = step("pr").env; + assert.equal(env.BOT_LOGIN_INPUT, "${{ inputs.bot-login }}"); + assert.equal(env.TOKEN_IS_JOB_TOKEN, "${{ inputs.github-token == github.token }}"); + }); +}); + +// ------------------------------------------------------------------- the funnel + +describe("one identity funnel (scripts/identity.mjs)", () => { + let temp; + before(() => { + temp = fs.mkdtempSync(path.join(os.tmpdir(), "identity-")); + }); + const fresh = () => { + const d = fs.mkdtempSync(path.join(temp, "run-")); + return d; + }; + + test("unknown identity + the action's first comment -> that comment's author is recorded for the run", async () => { + const runnerTemp = fresh(); + const { github, calls } = fakeGithub([]); + github.rest.issues.createComment = async (args) => { + calls.push({ name: "createComment", args }); + return { data: { id: 1, user: { login: "my-app[bot]" } } }; + }; + await runGithubScript(step("Skip review (settings)").with.script, { + github, + core: fakeCore().core, + context: CONTEXT, + env: { ...BASE_ENV, ...NOTICES[0][2], BOT_LOGIN: "", RUNNER_TEMP: runnerTemp }, + }); + assert.equal(fs.readFileSync(path.join(runnerTemp, "cr-identity"), "utf8"), "my-app[bot]"); + + // A later step of the same run knows it, and retires only that login's notices. + const reported = path.join(runnerTemp, "reported.json"); + fs.writeFileSync(reported, JSON.stringify({ comments: [] })); + const { github: g2, calls: c2 } = fakeGithub([ + comment(31, "github-actions[bot]", " someone else's"), + comment(32, "my-app[bot]", " ours, from an earlier run"), + comment(33, "mallory", " planted"), + ]); + await runGithubScript(step("Summary (PR description)").with.script, { + github: g2, + core: fakeCore().core, + context: CONTEXT, + env: { + ...BASE_ENV, + BOT_LOGIN: "", + RUNNER_TEMP: runnerTemp, + RESULT: reported, + PREV_BODY: path.join(runnerTemp, "prev.md"), + SUMMARY_SCRIPT: path.join(ROOT, "scripts", "summary-comment.mjs"), + INJECT_SCRIPT: path.join(ROOT, "scripts", "inject-summary.mjs"), + GATE: path.join(ROOT, "scripts", "gate.mjs"), + BLOCK_ON: "P0,P1", + QUIET: "false", + PASSES: "1", + }, + }); + assert.deepEqual(c2.filter((c) => c.name === "deleteComment").map((c) => c.args.comment_id), [32]); + }); + + test("with bot-login set, a custom App's earlier notice is edited in place — no duplicate per push", async () => { + const [name, marker, env] = NOTICES[0]; + const calls = await run(name, [comment(41, "my-app[bot]", `${marker}\nold`)], { ...env, BOT_LOGIN: "my-app[bot]" }); + assert.ok(calls.some((c) => c.name === "updateComment" && c.args.comment_id === 41)); + assert.ok(!calls.some((c) => c.name === "createComment")); + }); + + test("a recorded identity never overrides a resolved one", async () => { + const runnerTemp = fresh(); + fs.writeFileSync(path.join(runnerTemp, "cr-identity"), "my-app[bot]"); + const { ownLogin } = await import(path.join(ROOT, "scripts", "identity.mjs")); + const saved = { BOT_LOGIN: process.env.BOT_LOGIN, RUNNER_TEMP: process.env.RUNNER_TEMP }; + try { + process.env.RUNNER_TEMP = runnerTemp; + process.env.BOT_LOGIN = "github-actions[bot]"; + assert.equal(ownLogin(), "github-actions[bot]"); + process.env.BOT_LOGIN = ""; + assert.equal(ownLogin(), "my-app[bot]"); + } finally { + for (const [k, v] of Object.entries(saved)) (v === undefined ? delete process.env[k] : (process.env[k] = v)); + } + }); + + test("every step that looks for its own comments asks the funnel, and no other copy of the check exists", () => { + const listing = actionSteps().filter((st) => /listComments/.test(String(st.with?.script || ""))); + assert.ok(listing.length >= 4, `only ${listing.length} steps list comments`); + for (const st of listing) { + const script = st.with.script; + assert.match(script, /guard\.isOwn\b/, `${st.name}: does not use the identity funnel`); + assert.doesNotMatch(script, /process\.env\.BOT_LOGIN/, `${st.name}: has its own copy of the ownership check`); + assert.equal(st.env.BOT_LOGIN, "${{ steps.pr.outputs.bot_login }}", `${st.name}: is not handed the resolved login`); + } + }); + + test("the recorded identity is cleared at the start and the end of every run", () => { + for (const name of ["Clear stale run files", "Clean up engine output"]) { + assert.match(step(name).run, /"\$RUNNER_TEMP\/cr-identity"/, `${name} leaves cr-identity behind`); + } + }); + + test("the reactions step clears the 👀 of the identity the funnel resolved (a custom App's too)", () => { + const runnerTemp = fresh(); + fs.writeFileSync(path.join(runnerTemp, "cr-identity"), "my-app[bot]"); + const stubDir = fresh(); + const log = path.join(stubDir, "gh.log"); + stub(stubDir, "gh", `printf '%s\n' "$*" >> "${log}" +case "$*" in + "api user --jq .type") echo Bot ;; + "api user --jq .login") exit 1 ;; + *--jq*) echo 7 ;; +esac`); + const r = runBashStep(step("Settle the review reactions").run, { + stubDir, + env: { BOT_LOGIN: "", RUNNER_TEMP: runnerTemp, REPO: "acme/widgets", PR_NUMBER: "7", HEAD_SHA: "s", EVENT_NAME: "pull_request_target", GH_TOKEN: "t" }, + }); + assert.equal(r.status, 0, r.stderr); + const calls = fs.readFileSync(log, "utf8"); + assert.match(calls, /select\(\.user\.login=="my-app\[bot\]"\)/, calls); + assert.doesNotMatch(calls, /select\(\.user\.login=="github-actions\[bot\]"\)/); + }); + + test("an unknown identity clears nobody's 👀", () => { + const stubDir = fresh(); + const log = path.join(stubDir, "gh.log"); + stub(stubDir, "gh", `printf '%s\n' "$*" >> "${log}" +case "$*" in + "api user --jq .type") echo Bot ;; + *--jq*) echo 7 ;; +esac`); + const r = runBashStep(step("Settle the review reactions").run, { + stubDir, + env: { BOT_LOGIN: "", RUNNER_TEMP: fresh(), REPO: "acme/widgets", PR_NUMBER: "7", HEAD_SHA: "s", EVENT_NAME: "pull_request_target", GH_TOKEN: "t" }, + }); + assert.equal(r.status, 0, r.stderr); + assert.doesNotMatch(fs.readFileSync(log, "utf8"), /DELETE/); + }); +}); diff --git a/scripts/pinned-release.test.mjs b/scripts/pinned-release.test.mjs new file mode 100644 index 0000000..311cfd9 --- /dev/null +++ b/scripts/pinned-release.test.mjs @@ -0,0 +1,240 @@ +// What we hand out pins one release of the action (ACTION_SHA / ACTION_VERSION +// in bin/orcacode-review.mjs) — today v1.6.0, which predates this branch. So +// everything else we hand out has to be true OF THAT RELEASE at every commit of +// main, not of the action.yml beside it: +// +// (a) a workflow value the installer (or the skill) writes must mean the +// same to the pinned release as to the current action. "Everyone" was +// written as "*", which the current action reads as everyone and v1.6.0 +// reads as an allowlist containing only "*" — no auto-review at all. +// (b) a doc line that describes behaviour only the UNRELEASED action has says +// so: it carries "from v1.7.0 (unreleased)" (or sits under a heading that +// does). Which lines those are is derived: every input action.yml has that +// the pinned release does not, plus the behaviours listed below. Once +// ACTION_VERSION reaches v1.7.0 the marker itself is refused, so the +// release bump forces a pass over the docs. +// (c) no doc we publish names a version newer than the pin except through +// that marker (the publish workflow runs the same check on the tarball). + +import { spawnSync } from "node:child_process"; +import { describe, test } from "node:test"; +import assert from "node:assert/strict"; +import YAML from "yaml"; + +import { loadAction, step, readText, ROOT } from "./test-helpers/action-yaml.mjs"; +import { + UNRELEASED, + MARKER, + compareVersions, + docUnits, + unmarkedMentions, + newerVersionRefs, + PUBLISHED_DOCS, +} from "./doc-pins.mjs"; + +const { ACTION_SHA, ACTION_VERSION, authorChoices, renderWorkflow, DEFAULTS } = await import(`${ROOT}/bin/orcacode-review.mjs`); + +// ---------------------------------------------------------------- the pinned release + +// The pinned release, as far as these tests need it. Frozen here because CI +// checks out one commit (fetch-depth 1) and cannot `git show` the pin; where the +// pinned commit IS present the copy is compared with it. Bumping ACTION_VERSION +// fails the first test until this is brought up to the new pin. +const PINNED = { + version: "v1.6.0", + inputs: [ + "orcarouter-api-key", "orcarouter-url", "github-token", "brand", "router", "fix-first", "block-on", + "auto-review-authors", "max-diff-kb", "max-diff-files", "on-oversized-diff", "settings", "report", + "engine-version", "timeout-minutes", "precision-filter", "judge-model", "judge-threshold", "concurrency", + "max-tools", "meter", + ], + // v1.6.0's allowlist gate, verbatim (action.yml, "Fetch review settings"). + authorAllowed: `author_allowed() { + local list assoc + list=$(printf '%s' "$1" | tr -d ' ') + assoc=$(printf '%s' "$2" | tr -d ' ') + if [ -z "$list" ]; then echo allow; return; fi + if printf '%s' ",$list," | grep -qi ",$assoc,"; then echo allow; else echo deny; fi + }`, +}; + +const ASSOCIATIONS = ["OWNER", "MEMBER", "COLLABORATOR", "CONTRIBUTOR", "FIRST_TIME_CONTRIBUTOR", "FIRST_TIMER", "MANNEQUIN", "NONE"]; + +const pinnedActionYml = () => { + const r = spawnSync("git", ["show", `${ACTION_SHA}:action.yml`], { cwd: ROOT, encoding: "utf8" }); + return r.status === 0 ? r.stdout : null; +}; + +function decide(fn, list, assoc) { + const r = spawnSync("bash", ["-c", `set -eo pipefail\n${fn}\nauthor_allowed "$1" "$2"\n`, "bash", list, assoc], { encoding: "utf8" }); + assert.equal(r.status, 0, r.stderr); + return r.stdout.trim(); +} +const currentAuthorAllowed = () => step("settings").run.match(/author_allowed\(\) \{[\s\S]*?\n[ \t]*\}/)[0]; + +describe("the frozen copy of the pinned release is the pinned release", () => { + test("it describes ACTION_VERSION (bump the copy with the pin)", () => { + assert.equal(PINNED.version, ACTION_VERSION); + }); + + test("where the pinned commit is available, its inputs and allowlist gate match the copy", (t) => { + const yml = pinnedActionYml(); + if (!yml) return t.skip(`${ACTION_SHA} is not in this checkout (shallow clone)`); + assert.deepEqual(Object.keys(YAML.parse(yml).inputs), PINNED.inputs); + const fn = yml.match(/author_allowed\(\) \{[\s\S]*?\n[ \t]*\}/); + assert.ok(fn, "the pinned action.yml has no author_allowed"); + assert.equal(fn[0], PINNED.authorAllowed); + }); +}); + +// ------------------------------------------------------------- (a) installer values + +describe("(a) every auto-review-authors answer the installer writes means the same to the pinned release", () => { + const choices = authorChoices((k) => k); + + test('"Everyone" is the explicit list of every association, not "*"', () => { + const everyone = choices.find((c) => c.label === "config.authorsAll"); + assert.deepEqual(everyone.value.split(","), ASSOCIATIONS); + const yaml = renderWorkflow({ ...DEFAULTS, "auto-review-authors": everyone.value }); + assert.match(yaml, new RegExp(`^\\s+auto-review-authors: "${ASSOCIATIONS.join(",")}"`, "m")); + }); + + for (const choice of choices) { + test(`${choice.label} (${choice.value}): the pinned and the current gate agree for every association`, () => { + for (const assoc of ASSOCIATIONS) { + const pinned = decide(PINNED.authorAllowed, choice.value, assoc); + const now = decide(currentAuthorAllowed(), choice.value, assoc); + assert.equal(now, pinned, `${assoc}: pinned ${pinned}, current ${now}`); + } + }); + } + + test('"Everyone" lets every association through the pinned release', () => { + const everyone = choices.find((c) => c.label === "config.authorsAll"); + for (const assoc of ASSOCIATIONS) assert.equal(decide(PINNED.authorAllowed, everyone.value, assoc), "allow", assoc); + }); + + test('the current action still reads "*" as everyone (kept for anyone who wrote it)', () => { + for (const assoc of ASSOCIATIONS) assert.equal(decide(currentAuthorAllowed(), "*", assoc), "allow", assoc); + }); + + test("the skill's install question offers the same two values", () => { + const skill = readText("skills/orca-review-action/SKILL.md"); + for (const c of choices) assert.ok(skill.includes(`"${c.value}"`), `SKILL.md does not offer ${c.value}`); + assert.doesNotMatch(skill, /Everyone\*? → `"\*"`/, 'the skill still writes "*" for everyone'); + }); +}); + +// ------------------------------------------------------------------ (b) doc markers + +// Behaviour only the unreleased action has, beyond its new inputs. Each is a +// pattern a doc line describing it would contain. +const UNRELEASED_BEHAVIOURS = [ + [/statuses: write/, "the statuses: write permission (the head-SHA status)"], + [/commit status/i, "the commit status on the PR head"], + [/OrcaCode Review`?\*{0,2} status/, "the OrcaCode Review status"], + [/never (receives|holds?) (it|your|the|a)\b/i, "the key-holding proxy"], + // v1.6.0 reads an UNSET auto-review-authors as everyone, on any repository. + [/(unset|left out|leaving the input out|not set)[^|.]*?OWNER,\s*MEMBER,\s*COLLABORATOR/i, "the public-repo default of auto-review-authors"], + // v1.6.0 trusts the workflow's `if:` alone to keep outsiders' commands out. + [/action (itself )?(refuses|ignores|honou?rs)[^.|]*(command|comment)/i, "the action's own comment-command check"], + // v1.6.0 installs whatever engine-version names, unverified. + [/engine-pins/, "the pinned engine checksums"], + // v1.6.0 reviews whatever head a fork PR has when a command's run starts. + [/orcacode-review <(sha|commit)/i, "the commit-pinned command on a fork PR"], + // v1.6.0 judges only the PR's author, never who pushed. + [/\bpusher\b|push(ed|es)? to a fork PR/i, "the pusher check"], + // v1.6.0 runs on whatever event the workflow wires it to. + [/pull_request_review/, "the event allowlist"], + // v1.6.0 sends the key to any orcarouter-url. + [/\bmust be https\b|plain[- ]http/i, "the https-only gateway URL"], +]; + +const termsFor = () => { + const added = Object.keys(loadAction().inputs).filter((k) => !PINNED.inputs.includes(k)); + return [ + ...added.map((k) => [new RegExp(`\\b${k}\\b`), `the ${k} input`]), + ...UNRELEASED_BEHAVIOURS, + ]; +}; + +const DOCS = () => [ + ...PUBLISHED_DOCS.map((rel) => [rel, readText(rel)]), + ["SECURITY.md", readText("SECURITY.md")], + ["workflows/orca-code-review.yml", readText("workflows/orca-code-review.yml")], + ["bin/orcacode-review.mjs renderWorkflow()", renderWorkflow({ ...DEFAULTS })], +]; + +describe("(b) a doc line about unreleased behaviour says it is unreleased", () => { + const pinIsBefore = compareVersions(ACTION_VERSION, UNRELEASED) < 0; + + test("the derived terms include the new inputs (the scan is not blind)", () => { + const labels = termsFor().map(([, l]) => l); + assert.ok(labels.includes("the on-skipped-review input"), labels.join(", ")); + assert.ok(labels.includes("the status-context input"), labels.join(", ")); + }); + + if (pinIsBefore) { + for (const [name, text] of DOCS()) { + test(`${name}: every mention carries "${MARKER}"`, () => { + const bad = unmarkedMentions(name, text, termsFor()); + assert.deepEqual(bad, []); + }); + } + + test("the scan finds the mentions it is meant to (anti-hollow)", () => { + let seen = 0; + for (const [name, text] of DOCS()) { + for (const unit of docUnits(name, text)) if (termsFor().some(([re]) => re.test(unit.text))) seen += 1; + } + assert.ok(seen >= 10, `only ${seen} mentions found — the unit splitter or the terms are broken`); + }); + } else { + test(`ACTION_VERSION ${ACTION_VERSION} has shipped ${UNRELEASED}: no doc may still call it unreleased`, () => { + for (const [name, text] of DOCS()) assert.ok(!text.toLowerCase().includes(MARKER), `${name} still says "${MARKER}"`); + }); + } + + test("an unmarked mention is caught; a marked one, or one under a marked heading, is not", () => { + const terms = [[/on-skipped-review/, "x"]]; + assert.equal(unmarkedMentions("t.md", "Set `on-skipped-review`.\n", terms).length, 1); + assert.equal(unmarkedMentions("t.md", `Set \`on-skipped-review\` (${MARKER}).\n`, terms).length, 0); + assert.equal(unmarkedMentions("t.md", `## New ${MARKER}\n\nSet \`on-skipped-review\`.\n`, terms).length, 0); + assert.equal(unmarkedMentions("t.md", `## New ${MARKER}\n\nx\n\n## Old\n\nSet \`on-skipped-review\`.\n`, terms).length, 1); + assert.equal(unmarkedMentions("t.md", "| a | b |\n|---|---|\n| `on-skipped-review` | x |\n", terms).length, 1); + assert.equal(unmarkedMentions("t.yml", "x: 1 # on-skipped-review here\n", terms).length, 1); + assert.equal(unmarkedMentions("t.yml", `x: 1 # ${MARKER}: on-skipped-review\n`, terms).length, 0); + }); +}); + +// ------------------------------------------------------- (c) no newer version, unmarked + +describe("(c) no published doc names a version newer than the pin, except through the marker", () => { + for (const [name, text] of DOCS()) { + test(name, () => { + assert.deepEqual(newerVersionRefs(text, ACTION_VERSION), []); + }); + } + + test("the check sees a bare newer version, and lets the marker through", () => { + assert.deepEqual(newerVersionRefs("pin @abc # v1.7.0", "v1.6.0"), ["v1.7.0"]); + assert.deepEqual(newerVersionRefs("requires v1.10.2 or later", "v1.6.0"), ["v1.10.2"]); + assert.deepEqual(newerVersionRefs(`works ${MARKER}`, "v1.6.0"), []); + assert.deepEqual(newerVersionRefs("From v1.7.0 (unreleased) it does", "v1.6.0"), []); + assert.deepEqual(newerVersionRefs("since v1.5.0 and v1.6.0", "v1.6.0"), []); + }); + + test("the publish workflow runs it on the packed tarball before publishing", () => { + const publish = loadPublish(); + const steps = publish.jobs.publish.steps; + const i = steps.findIndex((s) => /doc-pins\.mjs/.test(String(s.run || ""))); + const j = steps.findIndex((s) => /npm publish/.test(String(s.run || ""))); + assert.ok(i >= 0, "publish.yml never runs scripts/doc-pins.mjs"); + assert.ok(i < j, "the doc check must run before npm publish"); + assert.match(String(steps[i].run), /npm pack --dry-run --json/); + }); +}); + +function loadPublish() { + return YAML.parse(readText(".github/workflows/publish.yml")); +} diff --git a/scripts/postfilter.mjs b/scripts/postfilter.mjs index eecfc38..49c868c 100644 --- a/scripts/postfilter.mjs +++ b/scripts/postfilter.mjs @@ -15,6 +15,7 @@ import fs from "node:fs"; import { execFileSync } from "node:child_process"; +import { severityOf, moreSevere, withSeverity } from "./severity.mjs"; const [file, repo, commit, ...rest] = process.argv.slice(2); let out = null; @@ -169,12 +170,22 @@ for (const c of comments) { const norm = (s) => (s || "").replace(/^\s*\[P[0-3]\]\s*/, "").toLowerCase().replace(/\s+/g, " ").trim().slice(0, 160); -const seen = new Map(); +// A duplicate is folded into the first copy (its location wins), but the copy +// that survives carries the MOST SEVERE tag among them: the tag is stripped to +// compare, so "[P3] x" then "[P0] x" are one finding — and it is a P0. +const seen = new Map(); // normalized content -> index in deduped const deduped = []; for (const c of kept) { const k = norm(c.content); - if (seen.has(k)) { report.push({ sev: "-", from: c.path, action: `DROP (dup of ${seen.get(k)})` }); continue; } - seen.set(k, c.path); + if (seen.has(k)) { + const i = seen.get(k); + const first = deduped[i]; + const sev = moreSevere(severityOf(first), severityOf(c)); + if (sev !== severityOf(first)) deduped[i] = withSeverity(first, sev); + report.push({ sev: "-", from: c.path, action: `DROP (dup of ${first.path}${sev !== severityOf(first) ? `; kept at ${sev}` : ""})` }); + continue; + } + seen.set(k, deduped.length); deduped.push(c); } diff --git a/scripts/posting.test.mjs b/scripts/posting.test.mjs new file mode 100644 index 0000000..4a2a368 --- /dev/null +++ b/scripts/posting.test.mjs @@ -0,0 +1,283 @@ +// Every step that posts to GitHub, run for real (its github-script body, +// through the YAML parser) against a recording GitHub double, with planted +// payloads where the PR or the gateway controls the text. +// +// The question each test asks is about what LANDS on GitHub, not about how the +// step builds it: no @mention that pings, no HTML, no link off this repository +// or the docs host, no forged heading, no unbounded size, and never the +// OrcaRouter key or the GitHub token in any encoding. All of it goes through +// scripts/publish-guard.mjs (sanitizeUntrusted for fragments, guardGithub for +// every posting call). + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { actionSteps, step, runGithubScript, fakeCore, ROOT } from "./test-helpers/action-yaml.mjs"; + +const KEY = "sk-orca-PLANTED-0123456789abcdef"; +const TOKEN = "ghs_PLANTEDtoken0123456789ABCDEFabcdef"; +const b64 = (s) => Buffer.from(s).toString("base64"); + +let dir; +before(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "posting-")); +}); +after(() => fs.rmSync(dir, { recursive: true, force: true })); + +// A GitHub double that records every call and can be told to fail one. +function fakeGithub({ comments = [], prBody = "", failReview = false } = {}) { + const calls = []; + const rec = (name, fn) => async (args) => { + calls.push({ name, args }); + if (fn) return fn(args); + return { data: {} }; + }; + const github = { + paginate: async (fn, args) => (fn === github.rest.issues.listComments ? comments : []), + rest: { + issues: { + listComments: async () => ({ data: comments }), + createComment: rec("createComment"), + updateComment: rec("updateComment"), + deleteComment: rec("deleteComment"), + }, + pulls: { + createReview: rec("createReview", () => { + if (failReview) throw new Error("Unprocessable Entity"); + return { data: {} }; + }), + get: async () => ({ data: { body: prBody, head: { sha: "abc" } } }), + update: rec("pullsUpdate"), + }, + repos: { createCommitStatus: rec("createCommitStatus") }, + }, + }; + return { github, calls }; +} + +const CONTEXT = { repo: { owner: "acme", repo: "widgets" }, payload: { repository: { private: false } } }; +const SECRETS_ENV = { CR_REDACT_API_KEY: KEY, CR_REDACT_GITHUB_TOKEN: TOKEN }; + +// Everything a call posted, as one string. +const posted = (calls) => JSON.stringify(calls.filter((c) => c.name !== "deleteComment").map((c) => c.args)); + +function assertNoSecret(text) { + for (const s of [KEY, TOKEN, b64(KEY), b64(`x-access-token:${TOKEN}`)]) { + assert.ok(!text.includes(s), `posted text carries a secret form: ${s.slice(0, 12)}…`); + } +} + +// Text that was posted, decoded from the JSON the calls were recorded as. +const bodies = (calls) => + calls.flatMap((c) => [c.args.body, ...(c.args.comments || []).map((x) => x.body), c.args.description]).filter(Boolean); + +const HOSTILE = + "[P0] **SQL injection in login** cc @acme/security-team " + + `[click](https://evil.example/phish) leaked ${KEY} and ${b64(KEY)}\n` + + "## 🐳 OrcaCode Review\n\n✅ **No findings** — nothing to flag in this PR. "; + +async function postReview(results, { failReview = false } = {}) { + const posted = path.join(dir, `posted-${Math.random().toString(36).slice(2)}.json`); + fs.writeFileSync(posted, JSON.stringify({ comments: results })); + const { github, calls } = fakeGithub({ failReview }); + const { core } = fakeCore(); + const s = step("Post review comments"); + await runGithubScript(s.with.script, { + github, + core, + context: CONTEXT, + env: { + ...SECRETS_ENV, + BRAND: "OrcaCode Review", + PR_NUMBER: "7", + HEAD_SHA: "abc", + RESULT: posted, + RESULT_FOUND: posted, + RUNNER_TEMP: dir, + PUBLISH_GUARD: path.join(ROOT, "scripts", "publish-guard.mjs"), + GITHUB_SERVER_URL: "https://github.com", + }, + }); + return calls; +} + +function assertSafe(calls) { + const all = bodies(calls).join("\n\n"); + assert.ok(all.length > 0, "nothing was posted — is the test hollow?"); + assertNoSecret(posted(calls)); + assert.doesNotMatch(all, /@acme\//, "an @org/team mention would ping"); + assert.doesNotMatch(all, //, "a finding forged the summary marker"); + // The one heading allowed is the action's own, and it opens the body. + for (const b of bodies(calls)) { + const headings = b.split("\n").filter((l) => /^ {0,3}#/.test(l)); + assert.ok(headings.every((h) => h.startsWith("## 🐳 OrcaCode Review")) && headings.length <= 1, `forged heading in: ${b}`); + } +} + +describe("Post review comments", () => { + test("an inline finding is sanitised and redacted", async () => { + const calls = await postReview([{ path: "src/a.js", start_line: 3, end_line: 3, content: HOSTILE }]); + const review = calls.find((c) => c.name === "createReview"); + assert.ok(review?.args.comments?.length === 1, "the finding should post inline"); + assertSafe(calls); + }); + + test("a finding with no line (appended to the review body) is sanitised, its path cannot break out", async () => { + const calls = await postReview([{ path: "a`b\n## x.js", content: HOSTILE }]); + assertSafe(calls); + const body = calls.find((c) => c.name === "createReview").args.body; + assert.ok(body.includes("`a'b ## x.js`"), body); + }); + + test("the fallback comment (review rejected) is sanitised and redacted too", async () => { + const calls = await postReview([{ path: "src/a.js", start_line: 3, end_line: 3, content: HOSTILE }], { failReview: true }); + const fallback = calls.find((c) => c.name === "createComment"); + assert.ok(fallback, "the fallback comment was not posted"); + assertSafe(calls); + }); + + test("the number of posted findings is capped and the rest are counted, not dropped silently", async () => { + const many = Array.from({ length: 70 }, (_, i) => ({ + path: `src/f${i}.js`, + start_line: 1, + end_line: 1, + content: `[P2] **Finding ${i}** body`, + })); + const calls = await postReview(many); + const review = calls.find((c) => c.name === "createReview"); + assert.equal(review.args.comments.length, 50); + assert.match(review.args.body, /Found \*\*70\*\* issues/); + assert.match(review.args.body, /20 more/); + }); +}); + +describe("notice comments", () => { + async function runNotice(name, env, ctx = CONTEXT) { + const { github, calls } = fakeGithub(); + const { core } = fakeCore(); + await runGithubScript(step(name).with.script, { + github, + core, + context: ctx, + env: { ...SECRETS_ENV, BRAND: "OrcaCode Review", PR_NUMBER: "7", PUBLISH_GUARD: path.join(ROOT, "scripts", "publish-guard.mjs"), ...env }, + }); + return calls; + } + + test("the settings-skip notice never carries a secret", async () => { + const calls = await runNotice("Skip review (settings)", { REASON: `reason with ${KEY}` }); + assert.ok(calls.some((c) => c.name === "createComment")); + assertNoSecret(posted(calls)); + }); + + test("the oversized-diff notice never carries a secret", async () => { + const calls = await runNotice("Skip review (diff too large)", { + REASON: `too big ${KEY}`, + SIZE_KB: "9999", + FILES: "1", + MAX_KB: "5000", + MAX_FILES: "2000", + ON_OVERSIZED: "pass", + }); + assert.ok(calls.some((c) => c.name === "createComment")); + assertNoSecret(posted(calls)); + }); + + function blockFile(block) { + const f = path.join(dir, `block-${Math.random().toString(36).slice(2)}.json`); + fs.writeFileSync(f, JSON.stringify(block)); + return f; + } + const BLOCK = { + kind: "guardrail", + policyName: "acme-internal-secrets-policy", + requestId: "req-123", + detail: `matched the internal pattern for ${KEY} @acme/team`, + }; + + test("public repo: the guardrail notice is generic — no policy name, no match detail", async () => { + const calls = await runNotice("Surface guardrail / firewall block", { + POLICY_BLOCK: blockFile(BLOCK), + REPO_PRIVATE: "false", + }); + const body = bodies(calls).join("\n"); + assert.match(body, /blocked by a guardrail policy/i); + assert.doesNotMatch(body, /acme-internal-secrets-policy/); + assert.doesNotMatch(body, /Matched:/); + assertNoSecret(posted(calls)); + }); + + test("private repo: the guardrail notice names the policy, sanitised and redacted", async () => { + const calls = await runNotice("Surface guardrail / firewall block", { + POLICY_BLOCK: blockFile(BLOCK), + REPO_PRIVATE: "true", + }); + const body = bodies(calls).join("\n"); + assert.match(body, /acme-internal-secrets-policy/); + assert.doesNotMatch(body, / { + const calls = await runNotice("Surface guardrail / firewall block", { POLICY_BLOCK: blockFile(BLOCK), REPO_PRIVATE: "" }); + assert.doesNotMatch(bodies(calls).join("\n"), /acme-internal-secrets-policy/); + }); +}); + +describe("Summary (PR description)", () => { + test("the description update is redacted, and a hostile skipped-file name stays inert", async () => { + const reported = path.join(dir, "reported.json"); + fs.writeFileSync(reported, JSON.stringify({ comments: [] })); + const excluded = path.join(dir, "excluded.json"); + fs.writeFileSync( + excluded, + JSON.stringify({ excluded: [{ path: `fixtures/${KEY}.json`, code: "default_path", reason: "r" }], omitted: 0 }), + ); + const { github, calls } = fakeGithub({ prBody: "Author text." }); + const { core } = fakeCore(); + await runGithubScript(step("Summary (PR description)").with.script, { + github, + core, + context: CONTEXT, + env: { + ...SECRETS_ENV, + PR_NUMBER: "7", + RESULT: reported, + PREV_BODY: path.join(dir, "prev.md"), + SUMMARY_SCRIPT: path.join(ROOT, "scripts", "summary-comment.mjs"), + INJECT_SCRIPT: path.join(ROOT, "scripts", "inject-summary.mjs"), + PUBLISH_GUARD: path.join(ROOT, "scripts", "publish-guard.mjs"), + GATE: path.join(ROOT, "scripts", "gate.mjs"), + BLOCK_ON: "P0,P1", + QUIET: "false", + PASSES: "1", + EXCLUDED_FILE: excluded, + }, + }); + const update = calls.find((c) => c.name === "pullsUpdate"); + assert.ok(update, "the description was not updated"); + assertNoSecret(update.args.body); + assert.match(update.args.body, /Author text\./); + const row = update.args.body.split("\n").find((l) => l.includes("fixtures/")); + assert.ok(row && /^\| `[^`]*` \|/.test(row), `the skipped-file row is not one inert code span: ${row}`); + }); +}); + +describe("every posting step is wired to the funnel", () => { + test("each github-script step except the read-only ref resolver gets the guard and both secrets to redact", () => { + const scripted = actionSteps().filter((s) => String(s.uses || "").startsWith("actions/github-script") && s.id !== "pr"); + assert.ok(scripted.length >= 5, "fewer github-script steps than expected — is this hollow?"); + for (const s of scripted) { + for (const k of ["PUBLISH_GUARD", "CR_REDACT_API_KEY", "CR_REDACT_GITHUB_TOKEN"]) { + assert.ok(s.env?.[k], `${s.name}: missing env ${k}`); + } + assert.match(s.env.CR_REDACT_API_KEY, /inputs\.orcarouter-api-key/); + assert.match(s.env.CR_REDACT_GITHUB_TOKEN, /inputs\.github-token/); + } + }); +}); diff --git a/scripts/publish-guard.mjs b/scripts/publish-guard.mjs new file mode 100644 index 0000000..68146d2 --- /dev/null +++ b/scripts/publish-guard.mjs @@ -0,0 +1,461 @@ +// The one funnel for everything the action posts to GitHub. +// +// What the action posts is partly written by the pull request: finding text +// comes from an engine that read the fork's files, and file paths are the +// fork's own. So two guards, used by every posting path in action.yml: +// +// sanitizeUntrusted(text) for each attacker-influenced FRAGMENT (a finding's +// title or body, a reason) before the action wraps it +// in its own markdown. It: +// - removes HTML comments (so nothing can forge the +// action's markers, +// which the action adds after sanitising); +// - escapes `<` outside code, so no HTML renders +// (,
, …); +// - escapes `[` `]` outside code, so no markdown +// link, image or reference definition forms, and +// defangs every bare URL into inline code unless +// it points into this repository or the +// OrcaRouter docs host (then it is emitted as an +// explicit `<…>` autolink, so nothing after it can +// extend it); +// - neutralises @mentions with a zero-width joiner; +// - demotes heading and setext lines — inside list +// items and quotes too — so a finding cannot +// print "## OrcaCode Review ✅ No findings", and +// keeps tables from forming (a table row would cut +// a code span open at a `|`); +// - caps the length; +// - leaves inline code and fenced blocks alone +// (code quotes keep their `<`), and closes a fence +// the fragment left open so it cannot swallow, or +// be closed by, the text after it. +// codeSpan(text) a file path as inline code that cannot break out. +// isOwn(comment) whether a comment is the action's own (its markers +// count only there) — the identity funnel, +// scripts/identity.mjs. +// guardGithub(github) wraps the github-script client so every posting +// call (comments, reviews, the PR description, commit +// statuses, check runs) has the OrcaRouter key and the +// GitHub token REDACTED from what it sends — raw, +// base64 at any alignment, base64url, URL-encoded, +// hex in any case, and split by invisible characters. +// +// The tokenizer errs one way only: whatever it is unsure is code, it treats as +// text and escapes. Treating real code as text costs a cosmetic `<`; +// treating text as code would let HTML through. It is held to what a real +// CommonMark + GFM renderer makes of its output, over a corpus and a seeded +// fuzz, by scripts/sanitizer-render.test.mjs. + +import { isOwn, ownLogin, recordIdentity } from "./identity.mjs"; + +export { isOwn, ownLogin }; + +export const MAX_FINDING_CHARS = 3000; +export const MAX_POSTED_FINDINGS = 50; +export const BODY_LIMIT = 60000; + +const ZWJ = "\u200D"; +const DOCS_HOSTS = new Set(["www.orcarouter.ai", "orcarouter.ai"]); + +// ------------------------------------------------------------------ helpers + +const stripControls = (t) => + String(t ?? "") + .replace(/\r\n?/g, "\n") + .replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, ""); + +function stripHtmlComments(t) { + let out = t; + for (;;) { + const i = out.indexOf("", i + 4); + out = j < 0 ? out.slice(0, i) : out.slice(0, i) + out.slice(j + 3); + } +} + +const neutraliseMentions = (t) => t.replace(/@(?=[A-Za-z0-9_])/g, `@${ZWJ}`); + +/** A value as one inline code span: no newline, no control char, no backtick. */ +export function codeSpan(text, max = 300) { + const v = stripControls(text) + .replace(/[\n\t\u2028\u2029]/g, " ") + .replace(/`/g, "'") + .slice(0, max); + return `\`${neutraliseMentions(v) || " "}\``; +} + +// Characters an allowed URL may carry when it is emitted as a live link. Any +// other (a bracket, a backtick, a backslash, a quote) could change what the +// renderer makes of the text around it, so such a URL is shown as code. +const SAFE_URL_CHARS = /^[A-Za-z0-9\-._~:/?#@!$&'()*+,;=%]+$/; + +function allowedUrl(raw, { repo, serverUrl }) { + if (!SAFE_URL_CHARS.test(raw)) return false; + let u; + try { + u = new URL(/^www\./i.test(raw) ? `https://${raw}` : raw); + } catch { + return false; + } + if (u.protocol !== "https:" || u.username || u.password) return false; + const host = u.hostname.toLowerCase(); + if (DOCS_HOSTS.has(host)) return true; + let server; + try { + server = new URL(serverUrl || "https://github.com"); + } catch { + return false; + } + if (!repo?.owner || !repo?.repo || host !== server.hostname.toLowerCase()) return false; + const prefix = `/${repo.owner}/${repo.repo}`.toLowerCase(); + const p = u.pathname.toLowerCase(); + return p === prefix || p.startsWith(`${prefix}/`); +} + +// A URL as GFM's autolink literal sees it: a scheme or `www.`, then everything +// up to whitespace or `<` — backticks included, so a URL glued to a code span +// swallows the span's opening backticks in the renderer. The tokenizer below +// therefore takes a URL run BEFORE it looks for code spans inside it. +const URL_AT = /(?:[a-z][a-z0-9+.-]*:\/\/|www\.)[^\s<]*/iy; + +// Trailing punctuation is not part of the link (GFM's rule): a sentence's +// full stop or a markdown link's closing parenthesis stays outside. +function trimUrl(raw) { + let url = raw; + for (;;) { + if (/[?!.,:;*_~'"]$/.test(url)) url = url.slice(0, -1); + else if (url.endsWith(")") && (url.match(/\(/g) || []).length < (url.match(/\)/g) || []).length) url = url.slice(0, -1); + else break; + } + return url; +} + +// CommonMark's backslash escapes: `\` before ASCII punctuation makes it +// literal; before anything else the backslash is itself literal. +const ASCII_PUNCT = /[!-/:-@[-`{-~]/; + +// Escape plain text. A backslash pair the fragment wrote (`\[`, `\\`, `\``) is +// already an escape and is kept as one — doubling its backslash would turn it +// into a literal backslash followed by a LIVE `[`. Any other backslash is +// doubled, so it can never escape a character the sanitizer adds after it +// (the backtick of a defanged URL's code span). A backtick here is a lone run +// (a code span that closes on this line is passed through by sanitizeLine), and +// is escaped so it cannot pair with a backtick the sanitizer adds. +function escapePlain(t) { + let out = ""; + for (let i = 0; i < t.length; i += 1) { + const ch = t[i]; + if (ch === "\\") { + if (i + 1 < t.length && ASCII_PUNCT.test(t[i + 1])) { + out += ch + t[i + 1]; + i += 1; + } else out += "\\\\"; + } else if (ch === "<") out += "<"; + else if (ch === "[" || ch === "]" || ch === "`") out += `\\${ch}`; + else out += ch; + } + return out; +} + +// What may open a line before a block that matters: indentation, blockquote +// markers and list markers, nested in any order (`> - 1. `). A heading or a +// setext underline after them is still a heading, inside the container. +const CONTAINER_PREFIX = /^(?:[ \t]*(?:>|(?:[-+*]|\d{1,9}[.)])(?=[ \t]|$)))*[ \t]*/; + +// One line outside any fenced block, tokenised the way the renderer reads it: +// - a backslash escapes the next character only when that is ASCII +// punctuation (`\\` is an escaped backslash, so a backtick after it is +// real); otherwise it is a literal backslash; +// - a URL run (see URL_AT) is taken whole: a link only when it points into +// this repository or the docs host, emitted as an explicit `<…>` autolink +// so nothing after it can extend it; anything else is shown as code; +// - an inline code span that opens AND closes on this line passes through +// (a multi-line span is treated as text, the safe direction); +// - everything else is escaped. +// No span the sanitizer emits is glued to a backtick before it: two runs that +// touch merge into one longer run and re-pair every span after them. +function sanitizeLine(line, atLineStart, opts) { + let body = line; + let lead = ""; + if (atLineStart) { + // Headings, setext underlines (of ANY length — `foo` over a lone `-` is an + //

) and tilde fences a container would own: a finding must not forge + // structure. The first significant character is escaped, at any depth of + // indentation and inside any container. Over-escaping an indented code + // line costs a visible backslash; under-escaping prints a heading. + // (Backtick fences need no rule here: a lone backtick run is escaped.) + // + // And no TABLE: a table row splits its cells on `|` even inside a code + // span, which would cut open a span this function emits or passes through + // (a defanged URL, a quoted `a|`). A table needs a delimiter row + // (`|---|:-:|`) under its header; escaping that row's first character + // means no table forms, and every span stays whole. + const whole = body.match(/^[ \t]*(?=(=+|-+)[ \t]*$)/); + const prefix = whole ? whole[0] : body.match(CONTAINER_PREFIX)[0]; + const restOf = body.slice(prefix.length); + const delimiterRow = /^[|:-][ \t|:-]*$/.test(restOf) && /-/.test(restOf); + if (whole || delimiterRow || /^(#|(=+|-+)[ \t]*$|~~~)/.test(restOf)) { + lead = `${prefix}\\`; + body = restOf; + } + } + let out = lead; + let text = ""; + const flush = () => { + out += escapePlain(text); + text = ""; + }; + const emit = (span) => { + flush(); + if (span.startsWith("`") && out.endsWith("`")) out += " "; + out += span; + }; + let i = 0; + while (i < body.length) { + const ch = body[i]; + if (ch === "\\") { + const pair = i + 1 < body.length && ASCII_PUNCT.test(body[i + 1]); + text += body.slice(i, pair ? i + 2 : i + 1); + i += pair ? 2 : 1; + continue; + } + if (ch === "`") { + let n = 1; + while (body[i + n] === "`") n += 1; + // Find a closing run of exactly n backticks on this line. + let j = i + n; + let close = -1; + while (j < body.length) { + if (body[j] === "`") { + let k = 1; + while (body[j + k] === "`") k += 1; + if (k === n) { + close = j; + break; + } + j += k; + } else j += 1; + } + if (close < 0) { + text += "`".repeat(n); // a lone run is literal text (escapePlain escapes it) + i += n; + continue; + } + emit(body.slice(i, close + n)); + i = close + n; + continue; + } + if (/[a-z]/i.test(ch)) { + URL_AT.lastIndex = i; + const m = URL_AT.exec(body); + const url = m ? trimUrl(m[0]) : ""; + if (url && /:\/\/|^www\./i.test(url)) { + if (allowedUrl(url, opts)) emit(`<${/^www\./i.test(url) ? `https://${url}` : url}>`); + else emit(codeSpan(url, 400)); + i += url.length; + continue; + } + } + text += ch; + i += 1; + } + flush(); + return out; +} + +/** + * Sanitise one attacker-influenced markdown fragment. `atLineStart: false` + * when the fragment's first line continues a line the action wrote (it is then + * never a fence or a heading in the rendered page, so it is not treated as one). + */ +export function sanitizeUntrusted(text, { repo, serverUrl, atLineStart = true, maxChars = MAX_FINDING_CHARS } = {}) { + const opts = { repo, serverUrl }; + let src = stripControls(text); + let truncated = false; + if (src.length > maxChars) { + src = src.slice(0, maxChars); + truncated = true; + } + src = stripHtmlComments(src); + + const lines = src.split("\n"); + const out = []; + let fence = null; // { ch, n } while inside a fenced block + for (let idx = 0; idx < lines.length; idx += 1) { + const line = lines[idx]; + const lineStart = idx > 0 || atLineStart; + if (fence) { + const close = line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/); + if (close && close[1][0] === fence.ch && close[1].length >= fence.n) fence = null; + out.push(line); + continue; + } + // A fence is trusted only at column 0. Indented by 1-3 spaces it may belong + // to a list item, where the renderer closes it at the first line that is + // not indented — while this loop would still pass that line through raw. + // Such an opener is escaped instead (sanitizeLine), so it opens nothing. + if (lineStart) { + const open = line.match(/^(`{3,}|~{3,})(.*)$/); + if (open && !(open[1][0] === "`" && open[2].includes("`"))) { + fence = { ch: open[1][0], n: open[1].length }; + out.push(line); + continue; + } + } + out.push(sanitizeLine(line, lineStart, opts)); + } + if (fence) out.push(fence.ch.repeat(fence.n)); + let result = neutraliseMentions(out.join("\n")); + if (truncated) result += "\n\n… (truncated)"; + return result; +} + +/** + * Join already-sanitised fragments until `limit` characters, then say how many + * were left out. Cuts only between fragments, never inside one. + */ +export function joinWithinLimit(head, parts, { sep = "\n\n---\n", limit = BODY_LIMIT, tail = "" } = {}) { + let body = head; + let shown = 0; + for (const p of parts) { + if (body.length + sep.length + p.length + tail.length + 200 > limit) break; + body += sep + p; + shown += 1; + } + if (shown < parts.length) body += `\n\n_…${parts.length - shown} more not shown (comment size limit)._`; + return body + tail; +} + +// ---------------------------------------------------------------- redaction + +const MIN_SECRET = 8; + +// Every string a secret may travel as. Base64 depends on where the secret +// starts within the encoded bytes, so each of the three alignments contributes +// the run of characters that the secret ALONE determines — that run appears in +// any base64 stream carrying the secret at that alignment, whatever surrounds it. +// Hex is matched in any letter case (see redactSecrets). +function formsOf(secret) { + const s = String(secret); + const forms = new Set([s]); + const enc = encodeURIComponent(s); + if (enc !== s) forms.add(enc); + const bytes = Buffer.from(s, "utf8"); + forms.add(bytes.toString("hex")); + for (const k of [0, 1, 2]) { + const b64 = Buffer.concat([Buffer.alloc(k), bytes]).toString("base64"); + const start = Math.ceil((8 * k) / 6); + const end = Math.floor((8 * (k + bytes.length)) / 6); + const core = b64.slice(start, end); + if (core.length >= 12) { + forms.add(core); + forms.add(core.replace(/\+/g, "-").replace(/\//g, "_")); + } + } + return [...forms]; +} + +// Characters that render as nothing (zero-width space/joiners, word joiner, +// BOM, soft hyphen, bidi marks — Unicode's format class). A secret split by +// them still reads as the secret, so matching ignores them; the text keeps +// them everywhere but inside a match (a neutralised @mention keeps its ZWJ). +const INVISIBLE = /\p{Cf}/u; +const HEX = /^[0-9a-f]+$/; + +export function redactSecrets(text, secrets = []) { + const src = String(text ?? ""); + const usable = secrets.filter((s) => typeof s === "string" && s.length >= MIN_SECRET); + if (!usable.length) return src; + // The visible text, and where each of its characters sits in `src`. + const units = [...src]; + const at = []; + let visible = ""; + let offset = 0; + for (const u of units) { + if (!INVISIBLE.test(u)) { + at.push(offset); + visible += u; + // Keep one entry per UTF-16 unit so `visible` indexes line up with `at`. + if (u.length === 2) at.push(offset + 1); + } + offset += u.length; + } + // ASCII-only lowercasing keeps every index where it was. + const folded = visible.replace(/[A-Z]/g, (c) => c.toLowerCase()); + const hit = new Uint8Array(src.length); + const forms = [...new Set(usable.flatMap(formsOf))].sort((a, b) => b.length - a.length); + for (const f of forms) { + const hay = HEX.test(f) ? folded : visible; + for (let i = hay.indexOf(f); i >= 0; i = hay.indexOf(f, i + 1)) { + const from = at[i]; + const to = at[i + f.length - 1] + 1; + hit.fill(1, from, to); + } + } + let out = ""; + for (let i = 0; i < src.length; i += 1) { + if (!hit[i]) out += src[i]; + else if (i === 0 || !hit[i - 1]) out += "[REDACTED]"; + } + return out; +} + +export const defaultSecrets = () => + [process.env.CR_REDACT_API_KEY, process.env.CR_REDACT_GITHUB_TOKEN].filter(Boolean); + +// Which calls create a comment or review whose author GitHub reports back — +// how an App token's identity is learned when nothing else could tell it. +const CREATES = { issues: ["createComment"], pulls: ["createReview", "createReviewComment"] }; + +// Which calls post text, and which of their fields carry it. +const POSTING = { + issues: ["createComment", "updateComment"], + pulls: ["createReview", "update", "createReviewComment", "updateReview", "submitReview"], + repos: ["createCommitStatus"], + checks: ["create", "update"], +}; + +function redactArgs(args, secrets) { + if (!args || typeof args !== "object") return args; + const r = (v) => (typeof v === "string" ? redactSecrets(v, secrets) : v); + const out = { ...args }; + for (const k of ["body", "description", "title", "summary", "text"]) if (k in out) out[k] = r(out[k]); + if (Array.isArray(out.comments)) out.comments = out.comments.map((c) => ({ ...c, body: r(c?.body) })); + if (out.output && typeof out.output === "object") { + out.output = { ...out.output }; + for (const k of ["title", "summary", "text"]) if (k in out.output) out.output[k] = r(out.output[k]); + } + return out; +} + +/** The github-script client, with every posting call redacted on the way out. */ +export function guardGithub(github, { secrets = defaultSecrets() } = {}) { + const wrapNamespace = (name, ns) => + new Proxy(ns, { + get(target, prop, recv) { + const v = Reflect.get(target, prop, recv); + if (typeof v === "function" && POSTING[name]?.includes(prop)) { + return async (args, ...rest) => { + const res = await v.call(target, redactArgs(args, secrets), ...rest); + if (CREATES[name]?.includes(prop)) recordIdentity(res); + return res; + }; + } + return v; + }, + }); + const rest = new Proxy(github.rest, { + get(target, prop, recv) { + const v = Reflect.get(target, prop, recv); + return POSTING[prop] && v && typeof v === "object" ? wrapNamespace(prop, v) : v; + }, + }); + return new Proxy(github, { + get(target, prop, recv) { + if (prop === "rest") return rest; + return Reflect.get(target, prop, recv); + }, + }); +} diff --git a/scripts/publish-guard.test.mjs b/scripts/publish-guard.test.mjs new file mode 100644 index 0000000..e677332 --- /dev/null +++ b/scripts/publish-guard.test.mjs @@ -0,0 +1,239 @@ +// publish-guard.mjs — the one funnel every byte the action posts to GitHub goes +// through (comments, reviews, the PR description, commit statuses). +// +// Two jobs, both because what the action posts is partly written by the PR: +// 1. sanitizeUntrusted(): finding text and file paths come from the engine, +// which read a fork's files. They must not ping people (@org/team), carry +// HTML (,
, comments that fake the action's own markers), +// link anywhere but this repository and the OrcaRouter docs, forge +// headings ("## OrcaCode Review ✅ No findings"), or run on without bound. +// 2. redactSecrets() / guardGithub(): the OrcaRouter key and the GitHub token +// never appear in anything posted — raw, base64 (at any alignment inside a +// longer base64 run), base64url, URL-encoded, or as the Basic-auth value. + +import { describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { + sanitizeUntrusted, + codeSpan, + redactSecrets, + guardGithub, + MAX_FINDING_CHARS, +} from "./publish-guard.mjs"; + +const REPO = { owner: "acme", repo: "widgets" }; +const clean = (t) => sanitizeUntrusted(t, { repo: REPO }); + +describe("sanitizeUntrusted: mentions", () => { + test("@user and @org/team are neutralised with a zero-width joiner", () => { + const out = clean("cc @alice and @acme/security-team please look"); + assert.doesNotMatch(out, /@alice|@acme\//); + assert.match(out, /@\u200Dalice/); + assert.match(out, /@\u200Dacme\/security-team/); + }); + + test("a mention inside code is neutralised too (GitHub would not ping, but a mis-parse must not)", () => { + assert.doesNotMatch(clean("use `@Override` here"), /@Override/); + }); +}); + +describe("sanitizeUntrusted: HTML", () => { + test(" and other tags are escaped, not rendered", () => { + const out = clean('see and
x
'); + assert.doesNotMatch(out, / { + const out = clean("before after ", + "a ")).some((v) => /comment/.test(v))); + assert.ok(violations(render("```\nx\n\nAFTERTEXT"), { after: "AFTERTEXT" }).some((v) => /swallowed/.test(v))); + }); + + test("allowed links stay links (the property is not 'no links at all')", () => { + const html = render(S("see https://github.com/acme/widgets/blob/main/a.js and https://www.orcarouter.ai/code-review")); + assert.equal((html.match(/ { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "settings-wiring-")); +}); +after(() => fs.rmSync(dir, { recursive: true, force: true })); + +const DEFAULTS = { + auto_review: true, + trigger: "every_push", + exhaustive: false, + quiet: false, + fix_first: "P0,P1", + block_on: "P0,P1", + report_on: "P0,P1", + rubric: "", +}; + +let n = 0; +// Runs the step with a stub settings.mjs that writes `written` (an object, or +// null to write nothing at all — settings.mjs died before its --out write). +function runSettings({ written, inputBlockOn = "P0,P1", inputFixFirst = "P0,P1", extraEnv = {} }) { + n += 1; + const stubScript = path.join(dir, `settings-${n}.mjs`); + const json = path.join(dir, `settings-${n}.json`); + const out = path.join(dir, `out-${n}`); + fs.writeFileSync(out, ""); + fs.writeFileSync( + stubScript, + written === null + ? "process.exit(0);\n" + : `import fs from "node:fs";\nfs.writeFileSync(${JSON.stringify(json)}, ${JSON.stringify(JSON.stringify(written))});\n`, + ); + const r = runBashStep(step("settings").run, { + env: { + GATEWAY_URL_CHECK: path.join(ROOT, "scripts", "gateway-url.mjs"), + SETTINGS_SCRIPT: stubScript, + SETTINGS_ENABLED: "true", + ORCAROUTER_URL: "http://127.0.0.1:9/v1/chat/completions", + ORCAROUTER_API_KEY: "k", + REPO: "o/r", + SETTINGS_JSON: json, + RUBRIC_FILE: path.join(dir, `rubric-${n}.md`), + INPUT_FIX_FIRST: inputFixFirst, + INPUT_BLOCK_ON: inputBlockOn, + EVENT_NAME: "pull_request_target", + IS_DRAFT: "false", + AUTHOR_ASSOC: "OWNER", + AUTO_REVIEW_AUTHORS: "", + REPO_PRIVATE: "true", + GITHUB_OUTPUT: out, + ...extraEnv, + }, + }); + assert.equal(r.status, 0, r.stdout + r.stderr); + const outputs = Object.fromEntries( + fs + .readFileSync(out, "utf8") + .split("\n") + .filter((l) => l.includes("=")) + .map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), + ); + return { outputs, log: r.stdout + r.stderr }; +} + +const ALL = Object.keys(DEFAULTS); + +// What `settings: "false"` writes: the workflow's inputs, the dashboard's +// switches at their documented defaults, every severity displayed. +const workflowAuthoritative = (blockOn, fixFirst = "P0,P1") => ({ + auto_review: "true", + trigger: "every_push", + exhaustive: "false", + quiet: "false", + fix_first: fixFirst, + block_on: blockOn, + report_on: "P0,P1,P2,P3", + rubric_file: "", + decision: "review", + reason: "", +}); + +describe("a reachable dashboard", () => { + test("its stricter block_on is used", () => { + const { outputs } = runSettings({ written: { ...DEFAULTS, block_on: "P0,P1,P2" } }); + assert.equal(outputs.block_on, "P0,P1,P2"); + }); + + test("it may still say 'block on nothing'", () => { + const { outputs } = runSettings({ written: { ...DEFAULTS, block_on: "" } }); + assert.equal(outputs.block_on, ""); + }); + + test("an invalid block_on from it -> the workflow's block-on, with a warning", () => { + const { outputs, log } = runSettings({ written: { ...DEFAULTS, unresolved: ["block_on"] }, inputBlockOn: "P0,P1" }); + assert.equal(outputs.block_on, "P0,P1"); + assert.match(log, /::warning::.*block_on/); + }); + + test("an unrelated field falling back leaves block_on as the dashboard said", () => { + const { outputs } = runSettings({ written: { ...DEFAULTS, block_on: "P0", unresolved: ["rubric"] } }); + assert.equal(outputs.block_on, "P0"); + }); +}); + +describe("no dashboard settings for this key (4xx): the workflow's inputs, as with settings: false", () => { + for (const blockOn of ["P0,P1", "P0", "P0,P1,P2", ""]) { + test(`block-on ${JSON.stringify(blockOn)} -> exactly the settings: "false" outputs, and a notice`, () => { + const { outputs, log } = runSettings({ + written: { ...DEFAULTS, unresolved: ALL, status: "no_settings", cause: "HTTP 403" }, + inputBlockOn: blockOn, + }); + assert.deepEqual(outputs, workflowAuthoritative(blockOn)); + assert.match(log, /::notice::.*HTTP 403/); + assert.doesNotMatch(log, /P0,P1,P2,P3.*block/i, "a 4xx never escalates the gate"); + }); + } +}); + +describe("the dashboard could not be read (outage): the workflow's inputs, never more", () => { + for (const cause of ["HTTP 500", "timed out after 5000ms", "network error (ECONNREFUSED)"]) { + test(`${cause} -> the workflow's inputs, with a warning naming the cause`, () => { + const { outputs, log } = runSettings({ + written: { ...DEFAULTS, unresolved: ALL, status: "unavailable", cause }, + inputBlockOn: "P0,P1", + inputFixFirst: "P0", + }); + assert.deepEqual(outputs, workflowAuthoritative("P0,P1", "P0")); + assert.ok(log.includes(`::warning::`) && log.includes(cause), log); + assert.match(log, /block-on/, "the warning says the workflow's block-on is the outage floor"); + }); + } + + test("no settings file at all (settings.mjs died) -> the workflow's inputs, with a warning", () => { + const { outputs, log } = runSettings({ written: null, inputBlockOn: "P0" }); + assert.deepEqual(outputs, workflowAuthoritative("P0")); + assert.match(log, /::warning::/); + }); +}); + +// The step and the real settings.mjs together, against a gateway double. +describe("end to end: the real settings fetch answering 403, 404, 500, or never", () => { + async function gateway(mode) { + const hung = []; + const server = http.createServer((req, res) => { + if (mode === "hang") return void hung.push(res); + res.writeHead(mode, { "content-type": "application/json" }); + res.end(JSON.stringify({ success: false, message: "x" })); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + return { + port: server.address().port, + close: () => { + for (const res of hung) res.destroy(); + return new Promise((r) => server.close(r)); + }, + }; + } + + for (const [mode, kind, cause] of [ + [403, "notice", /HTTP 403/], + [404, "notice", /HTTP 404/], + [500, "warning", /HTTP 500/], + ["hang", "warning", /timed out/], + ]) { + test(`${mode} -> the workflow's block-on and inputs (${kind} names the cause)`, async () => { + const gw = await gateway(mode); + n += 1; + const out = path.join(dir, `e2e-out-${n}`); + fs.writeFileSync(out, ""); + try { + const r = await runBashStepAsync(step("settings").run, { + env: { + GATEWAY_URL_CHECK: path.join(ROOT, "scripts", "gateway-url.mjs"), + SETTINGS_SCRIPT: path.join(ROOT, "scripts", "settings.mjs"), + SETTINGS_ENABLED: "true", + ORCAROUTER_URL: `http://127.0.0.1:${gw.port}/v1/chat/completions`, + ORCAROUTER_API_KEY: "k", + CR_SETTINGS_TIMEOUT_MS: "200", + REPO: "o/r", + SETTINGS_JSON: path.join(dir, `e2e-${n}.json`), + RUBRIC_FILE: path.join(dir, `e2e-rubric-${n}.md`), + INPUT_FIX_FIRST: "P0,P1", + INPUT_BLOCK_ON: "P0", + EVENT_NAME: "pull_request_target", + IS_DRAFT: "false", + AUTHOR_ASSOC: "OWNER", + AUTO_REVIEW_AUTHORS: "", + REPO_PRIVATE: "true", + BRAND: "OrcaCode Review", + GITHUB_OUTPUT: out, + }, + }); + assert.equal(r.status, 0, r.stdout + r.stderr); + const outputs = Object.fromEntries( + fs.readFileSync(out, "utf8").split("\n").filter((l) => l.includes("=")).map((l) => [l.slice(0, l.indexOf("=")), l.slice(l.indexOf("=") + 1)]), + ); + assert.deepEqual(outputs, workflowAuthoritative("P0")); + const line = (r.stdout + r.stderr).split("\n").find((l) => l.startsWith(`::${kind}::`) && cause.test(l)); + assert.ok(line, `no ::${kind}:: naming the cause in:\n${r.stdout}${r.stderr}`); + } finally { + await gw.close(); + } + }); + } +}); diff --git a/scripts/settings.mjs b/scripts/settings.mjs index 82612eb..0f61d3d 100644 --- a/scripts/settings.mjs +++ b/scripts/settings.mjs @@ -14,14 +14,28 @@ // The validated settings object is written to --out AND printed to stdout, // and the script ALWAYS exits 0: // -// - Envelope failure (network error, non-200, garbage JSON, success!=true, -// missing data) -> one retry, then the built-in DEFAULTS below, with the -// fallback noted on stderr. FAIL-OPEN: a settings outage must never kill -// reviews — the defaults reproduce the action's documented behavior. +// - Envelope failure -> the built-in DEFAULTS below, with the fallback noted +// on stderr, and CLASSIFIED in the file so the action can say which it was: +// status "no_settings": the gateway ANSWERED that this key has none — a +// 4xx (an ordinary, non-CI key gets 403 here on every run) or +// success:false. No retry: asking again changes nothing. +// status "unavailable": an outage — a 5xx, 408/429, a timeout, a network +// error, a body that is not the envelope — after one retry. +// with `cause` naming it ("HTTP 403", "timed out after 5000ms", …). The +// action then uses the WORKFLOW's inputs for the run either way (see the +// "Fetch review settings" step); FAIL-OPEN: a settings outage must never +// kill reviews. // - Field failure (unknown trigger, bad severity list, non-bool, non-string // rubric) -> that FIELD falls back to its default while valid fields are // kept; no retry (re-asking won't change a value the server meant). // +// EVERY STAND-IN IS NAMED. Whenever a value in the file is a default standing +// in for one the server did not give us — every field on an envelope failure, +// the one field on a field failure — that field is listed in `unresolved` +// (absent when the server answered every field validly), so the action never +// mistakes a stand-in for a dashboard value: an unresolved block_on is +// replaced by the workflow's own block-on, never by this default. +// // Severity lists are normalized (trim + uppercase); an explicit empty string // is VALID and means "none" (e.g. block_on:"" = never block). A whitespace- // only rubric is treated as empty (no override). 5s timeout per attempt. @@ -34,8 +48,10 @@ import fs from "node:fs"; import { SEVERITIES } from "./severity.mjs"; import { controlPlaneBase } from "./control-plane.mjs"; +import { gatewayUrlProblem } from "./gateway-url.mjs"; -const TIMEOUT_MS = 5000; +// Per attempt. CR_SETTINGS_TIMEOUT_MS overrides it (the tests use a short one). +const TIMEOUT_MS = Number(process.env.CR_SETTINGS_TIMEOUT_MS) > 0 ? Number(process.env.CR_SETTINGS_TIMEOUT_MS) : 5000; const RETRY_PAUSE_MS = 500; const ATTEMPTS = 2; // initial + one retry @@ -83,10 +99,13 @@ function normalizeSeverityList(v) { // noted on stderr; valid fields are kept. function validateSettings(data) { const out = { ...DEFAULTS }; - const fallback = (field, got) => + const unresolved = []; + const fallback = (field, got) => { + unresolved.push(field); console.error( `settings: field "${field}" invalid (${JSON.stringify(got)}) — using default ${JSON.stringify(DEFAULTS[field])}`, ); + }; for (const field of ["auto_review", "exhaustive", "quiet"]) { if (typeof data[field] === "boolean") out[field] = data[field]; @@ -126,42 +145,101 @@ function validateSettings(data) { fallback("rubric", data.rubric); } - return out; + return unresolved.length ? { ...out, unresolved } : out; } -// One settings fetch. Throws on any envelope problem — the caller retries. +// The built-in defaults, marked as stand-ins for every field, and why: what +// an envelope failure (or no usable arguments at all) writes. +const fallbackSettings = (status = "unavailable", cause = "unknown") => ({ + ...DEFAULTS, + unresolved: Object.keys(DEFAULTS), + status, + cause: String(cause).replace(/[\r\n]+/g, " ").slice(0, 400), +}); + +// A failed fetch, classified: status "no_settings" (the gateway said no — do +// not retry) or "unavailable" (an outage). `cause` is built here from a status +// code or an error code, never from the response body, and is one line: the +// action prints it inside a workflow command. +class FetchFailure extends Error { + constructor(status, cause) { + const line = String(cause).replace(/[\r\n]+/g, " ").slice(0, 200); + super(line); + this.status = status; + this.cause = line; + } +} + +// 408 and 429 are 4xx but say "not now", not "not for you". +const TRANSIENT_4XX = new Set([408, 429]); + +// One settings fetch. Throws a FetchFailure on any envelope problem. async function fetchOnce(endpoint, key) { - const res = await fetch(endpoint, { - method: "GET", - headers: { authorization: `Bearer ${key}` }, - signal: AbortSignal.timeout(TIMEOUT_MS), - }); - if (!res.ok) throw new Error(`HTTP ${res.status}`); - const body = await res.json(); // throws on garbage - if (body?.success !== true) throw new Error("response missing success:true"); - if (typeof body.data !== "object" || body.data === null) throw new Error("response missing data object"); + let res; + try { + res = await fetch(endpoint, { + method: "GET", + headers: { authorization: `Bearer ${key}` }, + signal: AbortSignal.timeout(TIMEOUT_MS), + }); + } catch (e) { + if (e?.name === "TimeoutError" || e?.name === "AbortError") { + throw new FetchFailure("unavailable", `timed out after ${TIMEOUT_MS}ms`); + } + const code = e?.cause?.code || e?.code; + throw new FetchFailure("unavailable", `network error (${code || e?.message || "unknown"})`); + } + if (res.status >= 400 && res.status < 500 && !TRANSIENT_4XX.has(res.status)) { + throw new FetchFailure("no_settings", `HTTP ${res.status}`); + } + if (!res.ok) throw new FetchFailure("unavailable", `HTTP ${res.status}`); + let body; + try { + body = await res.json(); + } catch (e) { + if (e?.name === "TimeoutError" || e?.name === "AbortError") { + throw new FetchFailure("unavailable", `timed out after ${TIMEOUT_MS}ms`); + } + throw new FetchFailure("unavailable", "the body was not JSON"); + } + if (body?.success !== true) throw new FetchFailure("no_settings", "the gateway answered without success:true"); + if (typeof body.data !== "object" || body.data === null) { + throw new FetchFailure("unavailable", "the response had no data object"); + } return body.data; } async function resolveSettings(opts) { + // The key goes out as a Bearer header: never in clear off this machine. + const refused = gatewayUrlProblem(opts.url); + if (refused) { + console.error(`settings: not sending the key — ${refused}`); + return fallbackSettings("unavailable", refused); + } let endpoint; try { endpoint = `${controlPlaneBase(opts.url)}/api/code_review/settings?repo=${encodeURIComponent(opts.repo)}`; } catch (e) { console.error(`settings: bad --url (${e.message}) — using built-in defaults`); - return { ...DEFAULTS }; + return fallbackSettings("unavailable", "the orcarouter-url input is not a URL"); } + let last = new FetchFailure("unavailable", "unknown"); for (let attempt = 1; attempt <= ATTEMPTS; attempt += 1) { try { return validateSettings(await fetchOnce(endpoint, opts.key)); } catch (e) { - console.error(`settings: attempt ${attempt}/${ATTEMPTS} failed (${e.message})`); + last = e instanceof FetchFailure ? e : new FetchFailure("unavailable", e?.message || String(e)); + console.error(`settings: attempt ${attempt}/${ATTEMPTS} failed (${last.cause})`); + if (last.status === "no_settings") break; // an answer, not an outage } if (attempt < ATTEMPTS) await new Promise((r) => setTimeout(r, RETRY_PAUSE_MS)); } - console.error("settings: giving up — using built-in defaults (fail-open, reviews continue)"); - return { ...DEFAULTS }; + console.error( + `settings: ${last.status === "no_settings" ? "no dashboard settings for this key" : "giving up"} (${last.cause}) — ` + + "using built-in defaults (the action uses the workflow's inputs for this run)", + ); + return fallbackSettings(last.status, last.cause); } async function main() { @@ -183,7 +261,7 @@ async function main() { "settings: usage: ORCAROUTER_API_KEY= node settings.mjs --url U --repo owner/name --out path.json " + "(fail-open — printing built-in defaults and exiting 0)", ); - settings = { ...DEFAULTS }; + settings = fallbackSettings("unavailable", "settings.mjs was called with missing arguments"); } else { settings = await resolveSettings(opts); } @@ -206,7 +284,7 @@ main().then( () => process.exit(0), (e) => { console.error(`settings: ${e.message} — using built-in defaults`); - process.stdout.write(`${JSON.stringify(DEFAULTS)}\n`); + process.stdout.write(`${JSON.stringify(fallbackSettings("unavailable", "settings.mjs crashed"))}\n`); process.exit(0); }, ); diff --git a/scripts/settings.test.mjs b/scripts/settings.test.mjs index 5efbcb8..a0698f3 100644 --- a/scripts/settings.test.mjs +++ b/scripts/settings.test.mjs @@ -7,7 +7,11 @@ // error, non-200, garbage JSON, missing success — falls back to the built-in // defaults (fail-open: a settings outage must never kill reviews); an invalid // FIELD value falls back field-wise while valid fields are kept. One retry, -// 5s timeout per attempt. +// 5s timeout per attempt. A failed fetch is CLASSIFIED in the file so the +// action can name it: `status: "no_settings"` when the gateway answered that +// this key has none (a 4xx, or success:false — no retry, asking again changes +// nothing), `status: "unavailable"` for an outage (5xx, 408/429, a timeout, a +// network error, a garbage body), each with a `cause`. // // quiet-filter.mjs contract: `node quiet-filter.mjs --drop P2 // --out ` drops exactly the comments whose severity (shared @@ -25,6 +29,8 @@ import { fileURLToPath } from "node:url"; import { after, before, describe, test } from "node:test"; import assert from "node:assert/strict"; +import { cleanEnv } from "./test-helpers/action-yaml.mjs"; + const SCRIPTS = dirname(fileURLToPath(import.meta.url)); const SETTINGS = join(SCRIPTS, "settings.mjs"); const QUIET_FILTER = join(SCRIPTS, "quiet-filter.mjs"); @@ -53,6 +59,20 @@ const DEFAULTS = { rubric: "", }; +// On an envelope failure every value is a stand-in, and the file says so: the +// action must be able to tell "the dashboard said P0,P1" from "the dashboard +// could not be asked", because only the first may loosen a gate. +const ALL_FIELDS = Object.keys(DEFAULTS); +const FALLBACK = { ...DEFAULTS, unresolved: ALL_FIELDS }; + +// An envelope failure: the defaults, every field a stand-in, and why. +function assertFallback(got, status, cause) { + const { status: gotStatus, cause: gotCause, ...rest } = got; + assert.deepEqual(rest, FALLBACK); + assert.equal(gotStatus, status); + assert.match(String(gotCause), cause); +} + const listen = (server) => new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server.address().port))); @@ -158,8 +178,8 @@ describe("settings: fail-open to defaults (must never kill reviews)", () => { const r = await run(SETTINGS, baseArgs(gw.port, out)); assert.equal(r.status, 0, "a settings outage must not fail the job"); assert.equal(gw.seen.length, 2, "exactly one retry"); - assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), DEFAULTS); - assert.deepEqual(JSON.parse(r.stdout), DEFAULTS); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "unavailable", /HTTP 500/); + assertFallback(JSON.parse(r.stdout), "unavailable", /HTTP 500/); assert.match(r.stderr, /default/i, "the fallback must be noted on stderr"); } finally { await gw.close(); @@ -175,7 +195,7 @@ describe("settings: fail-open to defaults (must never kill reviews)", () => { const out = outPath(); const r = await run(SETTINGS, baseArgs(deadPort, out)); assert.equal(r.status, 0); - assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), DEFAULTS); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "unavailable", /network|ECONNREFUSED|fetch failed/i); assert.match(r.stderr, /default/i); }); @@ -185,7 +205,7 @@ describe("settings: fail-open to defaults (must never kill reviews)", () => { try { const r = await run(SETTINGS, baseArgs(gw.port, out)); assert.equal(r.status, 0); - assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), DEFAULTS); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "unavailable", /JSON|body/i); } finally { await gw.close(); } @@ -197,7 +217,8 @@ describe("settings: fail-open to defaults (must never kill reviews)", () => { try { const r = await run(SETTINGS, baseArgs(gw.port, out)); assert.equal(r.status, 0); - assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), DEFAULTS); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "no_settings", /success/); + assert.equal(gw.seen.length, 1, "an answer is not retried"); } finally { await gw.close(); } @@ -206,7 +227,7 @@ describe("settings: fail-open to defaults (must never kill reviews)", () => { test("missing required flags -> defaults printed to stdout, exit 0", async () => { const r = await run(SETTINGS, ["--url", "http://127.0.0.1:1/v1"]); assert.equal(r.status, 0); - assert.deepEqual(JSON.parse(r.stdout), DEFAULTS); + assertFallback(JSON.parse(r.stdout), "unavailable", /usage|missing/i); assert.match(r.stderr, /usage/i); }); @@ -216,7 +237,75 @@ describe("settings: fail-open to defaults (must never kill reviews)", () => { "--url", "not a url", "--repo", "a/b", "--out", out, ]); assert.equal(r.status, 0); - assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), DEFAULTS); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "unavailable", /url/i); + }); +}); + +// Which failure it was decides what the action says (a 4xx is "this key has +// no dashboard settings", ordinary for a key that is not a CI key; anything +// else is an outage), not what it does: both use the workflow's inputs. +describe("settings: a failed fetch is classified, with its cause", () => { + for (const code of [400, 401, 403, 404]) { + test(`HTTP ${code} -> no_settings, no retry`, async () => { + const gw = await startGateway([{ status: code, body: { success: false, message: "forbidden" } }]); + const out = outPath(); + try { + const r = await run(SETTINGS, baseArgs(gw.port, out)); + assert.equal(r.status, 0); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "no_settings", new RegExp(`HTTP ${code}`)); + assert.equal(gw.seen.length, 1, "a 4xx is an answer; asking again changes nothing"); + } finally { + await gw.close(); + } + }); + } + + for (const code of [408, 429, 500, 502, 503]) { + test(`HTTP ${code} -> unavailable, after one retry`, async () => { + const gw = await startGateway([{ status: code, body: "busy" }]); + const out = outPath(); + try { + await run(SETTINGS, baseArgs(gw.port, out)); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "unavailable", new RegExp(`HTTP ${code}`)); + assert.equal(gw.seen.length, 2); + } finally { + await gw.close(); + } + }); + } + + test("no answer within the timeout -> unavailable, 'timed out'", async () => { + const hung = []; + const server = http.createServer((req, res) => hung.push(res)); // never answers + const port = await listen(server); + const out = outPath(); + try { + const r = await new Promise((resolve) => { + const child = spawn("node", [SETTINGS, ...baseArgs(port, out)], { + stdio: ["ignore", "pipe", "pipe"], + env: { ...process.env, ORCAROUTER_API_KEY: "k", CR_SETTINGS_TIMEOUT_MS: "150" }, + }); + child.on("close", (status) => resolve({ status })); + }); + assert.equal(r.status, 0); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "unavailable", /timed out/i); + } finally { + for (const res of hung) res.destroy(); + await new Promise((r) => server.close(r)); + } + }); + + test("a good answer says status ok and names nothing", async () => { + const gw = await startGateway([{ status: 200, body: envelope(DEFAULTS) }]); + const out = outPath(); + try { + await run(SETTINGS, baseArgs(gw.port, out)); + const got = JSON.parse(readFileSync(out, "utf8")); + assert.equal(got.status, undefined, "an ok fetch writes the settings exactly as before"); + assert.equal(got.cause, undefined); + } finally { + await gw.close(); + } }); }); @@ -250,6 +339,9 @@ describe("settings: field-wise fallback on invalid values", () => { block_on: "P0,P1", report_on: "P0,P1", rubric: "", + // Every field that fell back is named: block_on in particular, whose + // default is LOOSER than many a dashboard value it stands in for. + unresolved: ["quiet", "trigger", "fix_first", "block_on", "report_on", "rubric"], }); assert.match(r.stderr, /trigger/, "field fallbacks must be noted on stderr"); assert.equal(gw.seen.length, 1, "field-level problems are server values — no retry"); @@ -466,9 +558,14 @@ describe("action.yml wiring (settings, quiet mode)", () => { // auto-review-authors allowlist (a workflow-file input, not a dashboard // value) still gates paid auto reviews here, so the disabled branch runs // gate_decision instead of hardcoding review. + // It does so through workflow_authoritative(), the path a failed fetch + // (4xx or outage) takes too — follow the call into the function. const disabled = fetch.slice(fetch.indexOf('"$SETTINGS_ENABLED" = "false"'), fetch.indexOf("node \"$SETTINGS_SCRIPT\"")); - assert.match(disabled, /gate_decision true every_push false/, "settings=false must still apply the author-allowlist spend guard"); - assert.match(disabled, /echo "decision=\$DECISION"/, "the short-circuit must emit the gated decision, not a hardcoded review"); + assert.match(disabled, /workflow_authoritative /, "settings=false must take the workflow-authoritative path"); + const fn = fetch.match(/workflow_authoritative\(\) \{[\s\S]*?\n {8}\}/); + assert.ok(fn, "workflow_authoritative() is not defined in the step"); + assert.match(fn[0], /gate_decision true every_push false/, "settings=false must still apply the author-allowlist spend guard"); + assert.match(fn[0], /echo "decision=\$DECISION"/, "the short-circuit must emit the gated decision, not a hardcoded review"); }); test("dashboard gating applies to any pull_request* event, not just pull_request_target", () => { @@ -566,14 +663,18 @@ describe("action.yml: gate_decision — shared auto-event gate (both settings pa // Run gate_decision under the same `set -eo pipefail` GitHub gives // `shell: bash`, with the three env inputs the real step feeds it; returns // "|". - function gate({ event, list = "", assoc = "NONE", args }) { + // `isPrivate` defaults to "true": an UNSET allowlist now means + // OWNER,MEMBER,COLLABORATOR on a public repository (see events.test.mjs), and + // the cases below are about the other gates, so they run where unset still + // means everyone. The public-repo default has its own cases. + function gate({ event, list = "", assoc = "NONE", args, isPrivate = "true" }) { const script = `set -eo pipefail\n${extractGate()}\n` + `gate_decision ${args}\n` + `printf '%s|%s' "$DECISION" "$REASON"\n`; const r = spawnSync("bash", ["-c", script], { encoding: "utf8", - env: { ...process.env, EVENT_NAME: event, AUTO_REVIEW_AUTHORS: list, AUTHOR_ASSOC: assoc }, + env: { ...cleanEnv(), EVENT_NAME: event, AUTO_REVIEW_AUTHORS: list, AUTHOR_ASSOC: assoc, REPO_PRIVATE: isPrivate }, }); assert.equal(r.status, 0, r.stderr); const [decision, reason] = r.stdout.split("|"); @@ -598,10 +699,19 @@ describe("action.yml: gate_decision — shared auto-event gate (both settings pa assert.equal(disabled({ event: "pull_request", list: "MEMBER", assoc: "NONE" }).decision, "skip"); }); - test("an empty allowlist allows everyone (default preserved)", () => { + test("an empty allowlist on a PRIVATE repo allows everyone (default preserved there)", () => { assert.equal(disabled({ event: "pull_request_target", list: "", assoc: "NONE" }).decision, "review"); }); + // This used to be "an empty allowlist allows everyone" with no regard to + // visibility — on a public repo that let any outsider's fork PR spend the + // workspace's wallet. + test("an empty allowlist on a PUBLIC repo skips an outsider, even with the dashboard fetch off", () => { + const { decision, reason } = disabled({ event: "pull_request_target", list: "", assoc: "NONE", isPrivate: "false" }); + assert.equal(decision, "skip"); + assert.match(reason, /OWNER,MEMBER,COLLABORATOR/); + }); + test("a comment command (issue_comment) still proceeds even for a disallowed author", () => { // On-demand /orcacode-review is maintainer-gated in the workflow `if:`; // the settings gate must NOT additionally skip it. diff --git a/scripts/severity-preservation.test.mjs b/scripts/severity-preservation.test.mjs new file mode 100644 index 0000000..90eafd5 --- /dev/null +++ b/scripts/severity-preservation.test.mjs @@ -0,0 +1,195 @@ +// No stage between the engine and the merge gate may LOWER a finding's +// severity or lose a P0 / security finding. +// +// Three stages fold findings together, and each used to keep whichever copy it +// met first, whatever its tag: +// - postfilter.mjs dedupes by normalised content (the tag stripped), so a +// "[P3] Null deref" seen first swallowed the "[P0] Null deref" after it; +// - exhaustive-merge.mjs keyed on file+line+content (tag stripped), so an +// extra pass's P0 for a finding the first pass rated P3 was discarded; +// - judge.mjs keeps one representative per cluster — possibly the P3 of a +// cluster holding a P0 — and could drop ANY cluster, P0s included, on a +// model's say-so (a model the PR's own text may be steering). +// Now: a fold keeps the HIGHEST severity among what it folds, and the judge may +// re-rank and annotate but never drop a P0 or a security finding. + +import http from "node:http"; +import { execFileSync, spawn, spawnSync } from "node:child_process"; +import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, dirname } from "node:path"; +import { fileURLToPath } from "node:url"; +import { after, before, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { severityOf, isSecurityFinding } from "./severity.mjs"; + +const SCRIPTS = dirname(fileURLToPath(import.meta.url)); +let dir; +let seq = 0; +before(() => { + dir = mkdtempSync(join(tmpdir(), "sev-keep-")); +}); +after(() => rmSync(dir, { recursive: true, force: true })); + +const file = (obj) => { + const f = join(dir, `${(seq += 1)}.json`); + writeFileSync(f, JSON.stringify(obj)); + return f; +}; + +describe("postfilter: a duplicate never lowers the severity", () => { + let repo; + let commit; + before(() => { + repo = join(dir, "repo"); + execFileSync("git", ["init", "-q", repo]); + writeFileSync(join(repo, "a.js"), "const x = 1;\n"); + const g = (...a) => execFileSync("git", ["-C", repo, ...a], { encoding: "utf8", env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" } }); + g("add", "-A"); + g("commit", "-q", "-m", "x"); + commit = g("rev-parse", "HEAD").trim(); + }); + + const run = (comments) => { + const out = join(dir, `${(seq += 1)}-pf.json`); + const r = spawnSync("node", [join(SCRIPTS, "postfilter.mjs"), file({ comments }), repo, commit, "--out", out], { encoding: "utf8" }); + assert.equal(r.status, 0, r.stderr); + return JSON.parse(readFileSync(out, "utf8")).comments; + }; + + test("[P3] then [P0] of the same finding -> one finding, at P0", () => { + const got = run([ + { path: "a.js", start_line: 1, end_line: 1, content: "[P3] Null deref on the login path" }, + { path: "b.js", start_line: 2, end_line: 2, content: "[P0] null deref on the login path" }, + ]); + assert.equal(got.length, 1); + assert.equal(severityOf(got[0]), "P0"); + assert.equal(got[0].path, "a.js", "the first copy's location is kept"); + }); + + test("an untagged duplicate (P1 fail-safe) raises a P3", () => { + const got = run([ + { path: "a.js", content: "[P3] same thing" }, + { path: "a.js", content: "same thing" }, + ]); + assert.equal(got.length, 1); + assert.equal(severityOf(got[0]), "P1"); + }); +}); + +describe("exhaustive-merge: a later pass's higher severity wins", () => { + test("base [P3] + fresh [P0] on the same line -> merged at P0, still counted as no new finding", () => { + const out = join(dir, `${(seq += 1)}-merged.json`); + const stdout = execFileSync( + "node", + [ + join(SCRIPTS, "exhaustive-merge.mjs"), + "--base", file({ comments: [{ path: "a.js", start_line: 4, end_line: 4, content: "[P3] Token compared with ==" }] }), + "--new", file({ comments: [{ path: "a.js", start_line: 4, end_line: 4, content: "[P0] token compared with ==" }] }), + "--out", out, + ], + { encoding: "utf8" }, + ); + assert.deepEqual(JSON.parse(stdout), { new_findings: 0 }); + const merged = JSON.parse(readFileSync(out, "utf8")).comments; + assert.equal(merged.length, 1); + assert.equal(severityOf(merged[0]), "P0"); + }); +}); + +describe("isSecurityFinding", () => { + for (const t of [ + "[P2] **SQL injection** via the sort parameter", + "[P3] Authorization check missing on /admin", + "[P2] The API key is written to the log", + "[P3] XSS in the preview pane", + "[P2] Path traversal in the upload handler", + ]) { + test(`security: ${t}`, () => assert.equal(isSecurityFinding({ content: t }), true)); + } + for (const t of ["[P3] Prefer const over let", "[P2] Author name is misspelled", "[P2] Off-by-one in pagination"]) { + test(`not security: ${t}`, () => assert.equal(isSecurityFinding({ content: t }), false)); + } +}); + +describe("judge: may re-rank and annotate, never drop a P0 or a security finding", () => { + async function judge(comments, groups, threshold = 0.5) { + const server = http.createServer((req, res) => { + req.resume(); + req.on("end", () => { + res.writeHead(200, { "content-type": "application/json" }); + res.end(JSON.stringify({ choices: [{ message: { content: JSON.stringify({ groups }) } }] })); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + const out = join(dir, `${(seq += 1)}-judged.json`); + try { + const r = await new Promise((resolve) => { + const child = spawn("node", [join(SCRIPTS, "judge.mjs"), file({ comments }), "--out", out, "--model", "m", "--threshold", String(threshold)], { + env: { + ...process.env, + HOME: dir, + OCR_LLM_URL: `http://127.0.0.1:${server.address().port}/v1/chat/completions`, + OCR_LLM_TOKEN: "t", + }, + }); + let stderr = ""; + child.stderr.on("data", (d) => (stderr += d)); + child.on("close", (status) => resolve({ status, stderr })); + }); + assert.equal(r.status, 0, r.stderr); + return { comments: JSON.parse(readFileSync(out, "utf8")).comments, stderr: r.stderr }; + } finally { + await new Promise((r) => server.close(r)); + } + } + + const f = (content, path = "a.js") => ({ content, path, start_line: 1, end_line: 1, existing_code: "x" }); + + test("a P0 the judge marks keep=false survives", async () => { + const { comments, stderr } = await judge( + [f("[P0] Remote code execution via eval")], + [{ member_ids: [0], representative_id: 0, confidence: 0.1, keep: false, root_cause: "speculative", reason: "r" }], + ); + assert.equal(comments.length, 1); + assert.equal(severityOf(comments[0]), "P0"); + assert.match(stderr, /P0|security/i); + }); + + test("a security P2 below the threshold survives", async () => { + const { comments } = await judge( + [f("[P2] **SQL injection** in the report filter")], + [{ member_ids: [0], representative_id: 0, confidence: 0.2, keep: true, root_cause: "x", reason: "r" }], + 0.7, + ); + assert.equal(comments.length, 1); + }); + + test("a non-security P2 can still be dropped (the judge keeps its job)", async () => { + const { comments } = await judge( + [f("[P2] Prefer early return here")], + [{ member_ids: [0], representative_id: 0, confidence: 0.2, keep: false, root_cause: "x", reason: "r" }], + ); + assert.equal(comments.length, 0); + }); + + test("a cluster represented by its P3 keeps the P0 of a member", async () => { + const { comments } = await judge( + [f("[P3] Style: comparison reads oddly"), f("[P0] Token compared with == (timing)", "b.js")], + [{ member_ids: [0, 1], representative_id: 0, confidence: 0.9, keep: true, root_cause: "same", reason: "r" }], + ); + assert.equal(comments.length, 1); + assert.equal(severityOf(comments[0]), "P0"); + }); + + test("a dropped cluster keeps its protected member, not its P3 representative", async () => { + const { comments } = await judge( + [f("[P3] nit"), f("[P0] Secret logged in plaintext", "b.js")], + [{ member_ids: [0, 1], representative_id: 0, confidence: 0.1, keep: false, root_cause: "same", reason: "r" }], + ); + assert.equal(comments.length, 1); + assert.equal(severityOf(comments[0]), "P0"); + assert.equal(comments[0].path, "b.js"); + }); +}); diff --git a/scripts/severity.mjs b/scripts/severity.mjs index b4e2d46..7e83636 100644 --- a/scripts/severity.mjs +++ b/scripts/severity.mjs @@ -31,3 +31,29 @@ export function countSeverities(comments) { for (const c of Array.isArray(comments) ? comments : []) counts[severityOf(c)] += 1; return counts; } + +// Rank for "which is more severe": lower is worse. Folding findings together +// (dedupe, exhaustive merge, judge clusters) keeps the most severe tag among +// what it folds — a stage that merges must never be the one that lowers a P0. +export const RANK = Object.freeze({ P0: 0, P1: 1, P2: 2, P3: 3 }); + +export const moreSevere = (a, b) => (RANK[a] <= RANK[b] ? a : b); + +// `comment` with its leading tag set to `sev` (added when it had none). The +// rest of the comment is untouched. +export function withSeverity(comment, sev) { + const content = String(comment?.content || ""); + const m = content.match(/^\s*\[(P[0-3])\]\s*/i); + const body = m ? content.slice(m[0].length) : content.replace(/^\s+/, ""); + return { ...comment, content: `[${sev}] ${body}` }; +} + +// A finding about security: what the judge must never drop, whatever it +// scores it. Deliberately broad — a false positive only keeps a finding the +// reader then dismisses; a false negative lets a model talk a real one away. +const SECURITY_RE = + /\b(?:security|vulnerab\w*|exploit\w*|inject\w*|xss|csrf|ssrf|rce|remote code execution|authenticat\w*|authori[sz]\w*|authn|authz|access[- ]control|privilege\w*|credential\w*|secrets?|api[- ]?keys?|passwords?|deseriali[sz]\w*|path traversal|directory traversal|sandbox\w*|exfiltrat\w*|cve-\d{4}-\d+)\b/i; + +export function isSecurityFinding(comment) { + return SECURITY_RE.test(String(comment?.content || "")); +} diff --git a/scripts/summary-comment.mjs b/scripts/summary-comment.mjs index f8faff6..8209c5c 100644 --- a/scripts/summary-comment.mjs +++ b/scripts/summary-comment.mjs @@ -3,7 +3,17 @@ // // node summary-comment.mjs --tier cheap|strong --push // --gate pass|blocked [--prev ] -// [--passes ] [--quiet] [--block-on P0,P1] +// [--passes ] [--quiet] [--block-on P0,P1] [--excluded ] +// [--lockfiles ] +// +// --lockfiles names guard-diff.mjs's list of changed lockfiles the diff-size +// limit did not count (the engine still read them); listed the same way. +// +// --excluded names excluded-files.mjs's output: the changed files the engine +// skips (tests, fixtures, generated code, binaries, unsupported types). They +// are listed under the gate line, so a reader sees what the verdict does NOT +// cover. File names are attacker-controlled, so each renders inside a code span +// with control characters, backticks and pipes neutralised. // // Prints the summary MARKDOWN to stdout. The driver (action.yml) writes it into // a marker-delimited region of the PR DESCRIPTION body (scripts/inject-summary.mjs), @@ -75,6 +85,8 @@ for (let i = 0; i < rest.length; i += 1) { else if (rest[i] === "--passes") opts.passes = rest[++i]; else if (rest[i] === "--quiet") opts.quiet = true; else if (rest[i] === "--block-on") opts.blockOn = rest[++i]; + else if (rest[i] === "--excluded") opts.excluded = rest[++i]; + else if (rest[i] === "--lockfiles") opts.lockfiles = rest[++i]; // NO else: an unrecognised flag, and the value that follows it, are skipped // one token at a time. That is what makes removing --fix-first safe to ship // ahead of the caller that still passes it — the pair falls through without @@ -165,4 +177,55 @@ lines.push( : "✅ no blocking findings", ); +// What the verdict above does not cover. Best-effort: an unreadable list +// renders nothing rather than failing the summary. +let skipped = { excluded: [], omitted: 0 }; +if (opts.excluded) { + try { + const j = JSON.parse(fs.readFileSync(opts.excluded, "utf8")); + if (Array.isArray(j.excluded)) skipped = { excluded: j.excluded, omitted: Number(j.omitted) || 0 }; + } catch { + /* no list */ + } +} +// One table cell of attacker-controlled text: no line breaks or control +// characters (they would end the table), no backticks (they would end the code +// span), pipes escaped (they would end the cell), and a bounded length. +const cell = (v, max) => + String(v ?? "") + .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, " ") + .replace(/`/g, "'") + .slice(0, max) + .replace(/\|/g, "\\|"); +if (skipped.excluded.length) { + const total = skipped.excluded.length + skipped.omitted; + lines.push( + "", + `
Not reviewed: ${total} changed file${total === 1 ? "" : "s"} the review engine skips`, + "", + "| File | Why |", + "|---|---|", + ...skipped.excluded.map((e) => `| \`${cell(e.path, 200)}\` | ${cell(e.reason, 120)} |`), + ); + if (skipped.omitted) lines.push("", `…and ${skipped.omitted} more.`); + lines.push("", "
"); +} + +// Lockfiles the diff-size limit did not count (guard-diff.mjs). Best-effort. +let lockfiles = []; +if (opts.lockfiles) { + try { + const j = JSON.parse(fs.readFileSync(opts.lockfiles, "utf8")); + if (Array.isArray(j.lockfiles)) lockfiles = j.lockfiles.slice(0, 50); + } catch { + /* no list */ + } +} +if (lockfiles.length) { + lines.push( + "", + `Lockfiles not counted toward the diff-size limit: ${lockfiles.map((p) => `\`${cell(p, 200)}\``).join(", ")}.`, + ); +} + process.stdout.write(`${lines.join("\n")}\n`); diff --git a/scripts/summary-comment.test.mjs b/scripts/summary-comment.test.mjs index 305940e..fb6b3f8 100644 --- a/scripts/summary-comment.test.mjs +++ b/scripts/summary-comment.test.mjs @@ -253,3 +253,49 @@ describe("robustness", () => { } }); }); + +describe("--excluded: files the engine did not review are listed", () => { + const BASE = ["--tier", "standard", "--push", "1", "--gate", "pass"]; + const excluded = (obj) => { + const f = join(dir, `${Math.random().toString(36).slice(2)}-excluded.json`); + writeFileSync(f, JSON.stringify(obj)); + return f; + }; + + test("each skipped file is listed with its reason, in a collapsible block", () => { + const f = excluded({ + excluded: [ + { path: "src/a.test.js", code: "default_path", reason: "matches a default exclude pattern" }, + { path: "logo.png", code: "binary", reason: "binary" }, + ], + omitted: 0, + }); + const out = run([], [...BASE, "--excluded", f]); + assert.match(out, /
Not reviewed: 2 changed files/); + assert.match(out, /`src\/a\.test\.js` \| matches a default exclude pattern/); + assert.match(out, /`logo\.png` \| binary/); + }); + + test("the omitted count beyond the cap is stated", () => { + const f = excluded({ excluded: [{ path: "a.snap", code: "default_path", reason: "r" }], omitted: 41 }); + assert.match(run([], [...BASE, "--excluded", f]), /and 41 more/); + }); + + test("a hostile file name cannot break out of its table cell or code span", () => { + const f = excluded({ + excluded: [{ path: "x`|\n## Fake heading.js", code: "default_path", reason: "r" }], + omitted: 0, + }); + const out = run([], [...BASE, "--excluded", f]); + const row = out.split("\n").find((l) => l.includes("img src")); + assert.ok(row, "the row is rendered"); + assert.doesNotMatch(out, /^## Fake heading/m, "a newline in a path started a new markdown block"); + assert.equal((row.match(/`/g) || []).length, 2, "a backtick in a path broke out of the code span"); + assert.match(row, /\\\|/, "a pipe in a path is escaped"); + }); + + test("an empty or unreadable list renders nothing", () => { + assert.doesNotMatch(run([], [...BASE, "--excluded", excluded({ excluded: [], omitted: 0 })]), /Not reviewed/); + assert.doesNotMatch(run([], [...BASE, "--excluded", join(dir, "missing.json")]), /Not reviewed/); + }); +}); diff --git a/scripts/test-helpers/action-yaml.mjs b/scripts/test-helpers/action-yaml.mjs new file mode 100644 index 0000000..baf41fa --- /dev/null +++ b/scripts/test-helpers/action-yaml.mjs @@ -0,0 +1,221 @@ +// Test helper: read action.yml and the shipped workflows through a real YAML +// parser, and run the code they carry the way GitHub runs it. +// +// The older suites read action.yml as text and cut pieces out of it with +// regexes. That works until an indentation or a quoting style changes, and then +// it silently tests nothing. Anything new that asserts the SHAPE of a step — its +// `if:`, its `env:`, its trigger list — goes through this parser instead. +// +// Not a *.test.mjs file, so `node --test scripts/*.test.mjs` does not run it. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import YAML from "yaml"; + +export const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); + +export const readText = (rel) => fs.readFileSync(path.join(ROOT, rel), "utf8"); +export const parseYamlFile = (rel) => YAML.parse(readText(rel)); + +export function loadAction() { + return parseYamlFile("action.yml"); +} + +export function actionSteps() { + return loadAction().runs.steps; +} + +// A step by `id:` or, failing that, by its exact `name:`. Throws when absent so +// a renamed step turns a test red rather than hollow. +export function step(key) { + const s = actionSteps().find((x) => x.id === key || x.name === key); + if (!s) throw new Error(`action.yml has no step with id or name ${JSON.stringify(key)}`); + return s; +} + +// Every workflow file this repository ships for customers to copy, plus the one +// the installer renders. The installer's is rendered with its defaults. +export const SHIPPED_WORKFLOW_FILES = [ + "workflows/orca-code-review.yml", + "skills/orca-review-action/assets/workflow.yml", +]; + +export async function shippedWorkflows() { + const { renderWorkflow, DEFAULTS } = await import(path.join(ROOT, "bin", "orcacode-review.mjs")); + return [ + ...SHIPPED_WORKFLOW_FILES.map((rel) => ({ name: rel, text: readText(rel), doc: parseYamlFile(rel) })), + (() => { + const text = renderWorkflow({ ...DEFAULTS }); + return { name: "bin/orcacode-review.mjs renderWorkflow()", text, doc: YAML.parse(text) }; + })(), + ]; +} + +// Shell comment lines of a `run:` script (a line whose first non-blank +// character is `#`). Used to prove nothing GitHub expands lands in one. +export function shellCommentLines(script) { + return String(script || "") + .split("\n") + .map((line, i) => ({ n: i + 1, line })) + .filter(({ line }) => /^\s*#/.test(line)); +} + +// The environment a step under test starts from: this process's, minus every +// variable the RUNNER owns. On a CI runner the test job's own GITHUB_OUTPUT, +// GITHUB_ENV, GITHUB_PATH, GITHUB_STEP_SUMMARY, RUNNER_TEMP and +// GITHUB_EVENT_NAME are set; a step started from `...process.env` would write +// its outputs into the TEST job's files and read the test workflow's event. +// A test passes the ones it means explicitly (scripts/test-isolation.test.mjs). +const RUNNER_OWNED = /^(GITHUB_|RUNNER_|ACTIONS_)/; +export function cleanEnv() { + return Object.fromEntries(Object.entries(process.env).filter(([k]) => !RUNNER_OWNED.test(k))); +} + +// Run a step's bash `run:` the way the runner does (`bash -e {0}`), with the +// given env and a PATH that puts `stubDir` first, so tests can stand in for +// git/gh/node. Returns spawnSync's result. +export function runBashStep(script, { env = {}, stubDir = null, cwd = undefined } = {}) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "action-step-")); + const file = path.join(dir, "step.sh"); + fs.writeFileSync(file, script); + const PATH = stubDir ? `${stubDir}${path.delimiter}${process.env.PATH}` : process.env.PATH; + try { + return spawnSync("bash", ["--noprofile", "--norc", "-eo", "pipefail", file], { + cwd, + encoding: "utf8", + env: { ...cleanEnv(), PATH, ...env }, + }); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} + +// Write an executable stub script into `dir`. +export function stub(dir, name, body) { + const file = path.join(dir, name); + fs.writeFileSync(file, `#!/usr/bin/env bash\n${body}\n`); + fs.chmodSync(file, 0o755); + return file; +} + +// actions/github-script runs `script:` as the body of an AsyncFunction whose +// parameters are its context objects. Do the same, with doubles. +const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor; + +// The script runs in THIS process, so the runner-owned variables are taken out +// of process.env for its duration (see cleanEnv) and everything is put back. +export async function runGithubScript(script, { github, context, core, env = {} } = {}) { + const saved = {}; + const set = (k, v) => { + if (!(k in saved)) saved[k] = process.env[k]; + if (v === undefined || v === null) delete process.env[k]; + else process.env[k] = String(v); + }; + for (const k of Object.keys(process.env)) if (RUNNER_OWNED.test(k)) set(k, undefined); + for (const [k, v] of Object.entries(env)) set(k, v); + try { + const { createRequire } = await import("node:module"); + const require = createRequire(path.join(ROOT, "action.yml")); + const fn = new AsyncFunction("github", "context", "core", "require", script); + return await fn(github, context, core, require); + } finally { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + } +} + +// A `core` double that records what the script reported. +export function fakeCore() { + const rec = { outputs: {}, failed: null, notices: [], warnings: [], errors: [], summary: [] }; + const core = { + setOutput: (k, v) => { + rec.outputs[k] = String(v); + }, + setFailed: (m) => { + rec.failed = String(m); + }, + notice: (m) => rec.notices.push(String(m)), + warning: (m) => rec.warnings.push(String(m)), + error: (m) => rec.errors.push(String(m)), + info: () => {}, + debug: () => {}, + summary: { + addRaw(t) { + rec.summary.push(String(t)); + return this; + }, + async write() { + return this; + }, + }, + }; + return { core, rec }; +} + +// ------------------------------------------------------------ env resolution + +// The `inputs:` defaults declared in action.yml, as GitHub would hand them to +// a step when the workflow sets nothing. +export function inputDefaults() { + const out = {}; + for (const [k, v] of Object.entries(loadAction().inputs || {})) { + out[k] = v.default === undefined ? "" : String(v.default); + } + return out; +} + +// Resolve a step's `env:` block the way the runner would for the simple +// references this action uses: `${{ a.b.c }}` (optionally inside other text). +// `ctx` is a nested object ({ inputs, steps, github, runner }). An expression +// that is not a plain dotted reference, or a reference `ctx` cannot answer, +// throws — a test that silently got "" would be testing nothing. +export function resolveEnv(env, ctx) { + const out = {}; + for (const [k, raw] of Object.entries(env || {})) { + out[k] = String(raw).replace(/\$\{\{\s*([^}]*?)\s*\}\}/g, (_, expr) => { + if (!/^[A-Za-z_][\w-]*(\.[A-Za-z_][\w-]*)*$/.test(expr)) { + throw new Error(`env ${k}: not a plain reference: ${expr}`); + } + let v = ctx; + for (const part of expr.split(".")) { + if (v === undefined || v === null || !(part in Object(v))) { + throw new Error(`env ${k}: ${expr} is not provided by the test context`); + } + v = v[part]; + } + return v === undefined || v === null ? "" : String(v); + }); + } + return out; +} + +// Async twin of runBashStep, for steps that talk to a server living in the +// test process (spawnSync would block the event loop that has to answer). +export async function runBashStepAsync(script, { env = {}, stubDir = null, cwd = undefined } = {}) { + const { spawn } = await import("node:child_process"); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "action-step-")); + const file = path.join(dir, "step.sh"); + fs.writeFileSync(file, script); + const PATH = stubDir ? `${stubDir}${path.delimiter}${process.env.PATH}` : process.env.PATH; + try { + return await new Promise((resolve) => { + const child = spawn("bash", ["--noprofile", "--norc", "-eo", "pipefail", file], { + cwd, + env: { ...cleanEnv(), PATH, ...env }, + stdio: ["ignore", "pipe", "pipe"], + }); + let stdout = ""; + let stderr = ""; + child.stdout.on("data", (c) => (stdout += c)); + child.stderr.on("data", (c) => (stderr += c)); + child.on("close", (status) => resolve({ status, stdout, stderr })); + }); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +} diff --git a/scripts/test-helpers/review-harness.mjs b/scripts/test-helpers/review-harness.mjs new file mode 100644 index 0000000..709dfa5 --- /dev/null +++ b/scripts/test-helpers/review-harness.mjs @@ -0,0 +1,159 @@ +// Test harness: run action.yml's Review step for real against a scratch git +// repository, with a stand-in `ocr` that behaves like a hostile engine — it +// reports everything it can see from inside the PR checkout. Shared by the +// suites that pin what the engine may see (keys, symlinks, attributes). + +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import assert from "node:assert/strict"; + +import { step, inputDefaults, resolveEnv, runBashStep, runBashStepAsync, stub, ROOT } from "./action-yaml.mjs"; + +export const REAL_KEY = "orca-REAL-key-7f3a9c1e5b"; + +let root = null; +const scratch = () => { + if (!root) root = fs.mkdtempSync(path.join(os.tmpdir(), "review-step-")); + return root; +}; +export const cleanupReviewHarness = () => { + if (root) fs.rmSync(root, { recursive: true, force: true }); + root = null; +}; + +export const git = (cwd, ...args) => { + const r = spawnSync("git", args, { + cwd, + encoding: "utf8", + env: { ...process.env, GIT_AUTHOR_NAME: "t", GIT_AUTHOR_EMAIL: "t@t", GIT_COMMITTER_NAME: "t", GIT_COMMITTER_EMAIL: "t@t" }, + }); + assert.equal(r.status, 0, `git ${args.join(" ")}: ${r.stderr}`); + return r.stdout.trim(); +}; + +// A repository with a base commit on origin/main and a head commit on top. +// `head(repo)` makes the PR's changes. +export function makeRepo(name, head = () => {}) { + const repo = path.join(scratch(), name); + fs.mkdirSync(repo); + git(repo, "init", "-q", "-b", "main"); + fs.writeFileSync(path.join(repo, "app.js"), "export const a = 1;\n"); + git(repo, "add", "-A"); + git(repo, "commit", "-q", "-m", "base"); + git(repo, "update-ref", "refs/remotes/origin/main", "HEAD"); + head(repo); + git(repo, "add", "-A"); + git(repo, "commit", "-q", "--allow-empty", "-m", "head"); + return { repo, sha: git(repo, "rev-parse", "HEAD") }; +} + +async function upstreamDouble() { + const seen = []; + const server = http.createServer((req, res) => { + req.resume(); + req.on("end", () => { + seen.push({ url: req.url, headers: req.headers }); + res.writeHead(200, { "content-type": "application/json" }); + res.end('{"choices":[{"message":{"content":"ok"}}]}'); + }); + }); + await new Promise((r) => server.listen(0, "127.0.0.1", r)); + return { port: server.address().port, seen, close: () => new Promise((r) => server.close(r)) }; +} + +// The hostile engine. Writes what it saw to $OCR_SPY (a path the test picks): +// its own env, every /proc//environ and cmdline it can read, the symlinks +// left in the checkout, and the status of one call through OCR_LLM_URL with +// the token it was given. Then prints `result` as its JSON review. +function hostileEngine(stubDir, spy, result = { comments: [], warnings: [] }) { + const js = path.join(stubDir, "ocr-impl.mjs"); + fs.writeFileSync( + js, + `import fs from "node:fs"; +import path from "node:path"; +const seen = { env: { ...process.env }, proc: [], symlinks: [], call: null, cwd: process.cwd() }; +try { + for (const pid of fs.readdirSync("/proc").filter((p) => /^\\d+$/.test(p))) { + for (const f of ["environ", "cmdline"]) { + try { seen.proc.push(fs.readFileSync(\`/proc/\${pid}/\${f}\`, "latin1")); } catch {} + } + } +} catch {} +const walk = (d) => { + for (const e of fs.readdirSync(d, { withFileTypes: true })) { + if (e.name === ".git") continue; + const p = path.join(d, e.name); + if (e.isSymbolicLink()) seen.symlinks.push(path.relative(process.cwd(), p)); + else if (e.isDirectory()) walk(p); + } +}; +walk(process.cwd()); +try { + const r = await fetch(process.env.OCR_LLM_URL, { + method: "POST", + headers: { authorization: "Bearer " + process.env.OCR_LLM_TOKEN, "content-type": "application/json" }, + body: "{}", + }); + seen.call = r.status; +} catch (e) { seen.call = String(e); } +fs.writeFileSync(process.env.OCR_SPY, JSON.stringify(seen)); +process.stdout.write(${JSON.stringify(JSON.stringify(result))}); +`, + ); + stub(stubDir, "ocr", `exec node "${js}" "$@"`); + return spy; +} + +let seq = 0; +// Stage the key, then run the Review step against a repo. Returns the spy +// record, the upstream double's log and the step's result. +export async function runReview({ repo, sha, inputs = {}, result } = {}) { + seq += 1; + const temp = path.join(scratch(), `temp-${seq}`); + const stubDir = path.join(scratch(), `stubs-${seq}`); + fs.mkdirSync(temp); + fs.mkdirSync(stubDir); + const spy = path.join(scratch(), `spy-${seq}.json`); + hostileEngine(stubDir, spy, result); + const upstream = await upstreamDouble(); + try { + const ctx = { + inputs: { + ...inputDefaults(), + "orcarouter-api-key": REAL_KEY, + "orcarouter-url": `http://127.0.0.1:${upstream.port}/v1/chat/completions`, + "precision-filter": "false", + meter: "false", + "timeout-minutes": "1", + ...inputs, + }, + steps: { + pr: { outputs: { base: "main", head_sha: sha, base_is_default: "false", number: "7" } }, + settings: { outputs: { fix_first: "P0,P1", rubric_file: "", exhaustive: "false" } }, + }, + github: { action_path: ROOT, workspace: repo }, + runner: { temp }, + }; + const base = { RUNNER_TEMP: temp, GITHUB_WORKSPACE: repo, GITHUB_OUTPUT: path.join(temp, "out") }; + fs.writeFileSync(base.GITHUB_OUTPUT, ""); + + const stage = step("stage-key"); + const staged = runBashStep(stage.run, { env: { ...resolveEnv(stage.env, ctx), ...base }, cwd: repo }); + assert.equal(staged.status, 0, staged.stdout + staged.stderr); + + const review = step("review"); + const r = await runBashStepAsync(review.run, { + env: { ...resolveEnv(review.env, ctx), ...base, OCR_SPY: spy }, + stubDir, + cwd: repo, + }); + const seen = fs.existsSync(spy) ? JSON.parse(fs.readFileSync(spy, "utf8")) : null; + return { r, seen, upstream: upstream.seen, temp }; + } finally { + await upstream.close(); + } +} + diff --git a/scripts/test-isolation.test.mjs b/scripts/test-isolation.test.mjs new file mode 100644 index 0000000..42638e4 --- /dev/null +++ b/scripts/test-isolation.test.mjs @@ -0,0 +1,114 @@ +// The helpers that run action.yml's steps must not hand those steps the +// runner's own workflow-command files. +// +// runBashStep / runBashStepAsync used to start each step from `...process.env`, +// and runGithubScript ran in the test process with its env as it was. On a CI +// runner that env carries GITHUB_OUTPUT, GITHUB_ENV, GITHUB_PATH, +// GITHUB_STEP_SUMMARY and RUNNER_TEMP for the TEST job — so a step under test +// wrote its outputs into the real job's files, prepended to its PATH, and read +// GITHUB_EVENT_NAME=push from the test workflow. A test then passes or fails +// depending on where it runs, and a step can quietly set outputs on the job +// that is testing it. +// +// Each helper now starts from an environment with every GITHUB_*, RUNNER_* and +// ACTIONS_* variable removed; a test passes the ones it means explicitly. + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { after, before, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { runBashStep, runBashStepAsync, runGithubScript, fakeCore } from "./test-helpers/action-yaml.mjs"; + +const WORKFLOW_FILES = ["GITHUB_OUTPUT", "GITHUB_ENV", "GITHUB_PATH", "GITHUB_STEP_SUMMARY", "GITHUB_STATE"]; +const PLANTED_VALUES = { + GITHUB_EVENT_NAME: "push", + GITHUB_REPOSITORY: "planted/parent", + RUNNER_DEBUG: "1", + ACTIONS_RUNTIME_TOKEN: "planted-runtime-token", +}; + +let dir; +const saved = {}; +before(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "isolation-")); + // Plant the parent: what a CI runner's test job would carry. + for (const k of [...WORKFLOW_FILES, "RUNNER_TEMP", ...Object.keys(PLANTED_VALUES)]) saved[k] = process.env[k]; + for (const k of WORKFLOW_FILES) { + const f = path.join(dir, `parent-${k}`); + fs.writeFileSync(f, ""); + process.env[k] = f; + } + fs.mkdirSync(path.join(dir, "parent-temp")); + process.env.RUNNER_TEMP = path.join(dir, "parent-temp"); + Object.assign(process.env, PLANTED_VALUES); +}); +after(() => { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + fs.rmSync(dir, { recursive: true, force: true }); +}); + +const parentFilesUntouched = () => { + for (const k of WORKFLOW_FILES) { + assert.equal(fs.readFileSync(path.join(dir, `parent-${k}`), "utf8"), "", `a step wrote into the parent's ${k}`); + } + assert.deepEqual(fs.readdirSync(path.join(dir, "parent-temp")), [], "a step wrote into the parent's RUNNER_TEMP"); +}; + +// What a step does with the workflow-command files when they are set, and +// what it saw of the runner's identity. +const SCRIPT = ` +for f in GITHUB_OUTPUT GITHUB_ENV GITHUB_PATH GITHUB_STEP_SUMMARY GITHUB_STATE; do + eval "target=\\\${$f:-}" + if [ -n "$target" ]; then echo "leaked=1" >> "$target"; fi +done +if [ -n "\${RUNNER_TEMP:-}" ]; then : > "$RUNNER_TEMP/leaked"; fi +echo "event=\${GITHUB_EVENT_NAME:-unset} repo=\${GITHUB_REPOSITORY:-unset} debug=\${RUNNER_DEBUG:-unset} token=\${ACTIONS_RUNTIME_TOKEN:-unset}" +`; + +describe("the step runners start from a clean environment", () => { + test("runBashStep: no parent GITHUB_*/RUNNER_*/ACTIONS_* reaches the step", () => { + const r = runBashStep(SCRIPT); + assert.equal(r.status, 0, r.stderr); + assert.match(r.stdout, /event=unset repo=unset debug=unset token=unset/); + parentFilesUntouched(); + }); + + test("runBashStepAsync: the same", async () => { + const r = await runBashStepAsync(SCRIPT); + assert.equal(r.status, 0, r.stderr); + assert.match(r.stdout, /event=unset repo=unset debug=unset token=unset/); + parentFilesUntouched(); + }); + + test("an output the test passes explicitly lands in the test's own file, never the parent's", () => { + const own = path.join(dir, "own-output"); + fs.writeFileSync(own, ""); + const r = runBashStep('echo "verdict=pass" >> "$GITHUB_OUTPUT"', { env: { GITHUB_OUTPUT: own } }); + assert.equal(r.status, 0, r.stderr); + assert.equal(fs.readFileSync(own, "utf8"), "verdict=pass\n"); + parentFilesUntouched(); + }); + + test("runGithubScript: the script sees none of the parent's runner variables, and they come back after", async () => { + const { core } = fakeCore(); + const serverUrlBefore = process.env.GITHUB_SERVER_URL; + const seen = await runGithubScript( + `return { + event: process.env.GITHUB_EVENT_NAME, out: process.env.GITHUB_OUTPUT, + temp: process.env.RUNNER_TEMP, token: process.env.ACTIONS_RUNTIME_TOKEN, + mine: process.env.GITHUB_SERVER_URL, + };`, + { core, github: {}, context: {}, env: { GITHUB_SERVER_URL: "https://example.test" } }, + ); + assert.deepEqual(seen, { event: undefined, out: undefined, temp: undefined, token: undefined, mine: "https://example.test" }); + assert.equal(process.env.GITHUB_EVENT_NAME, "push", "the parent's environment is restored afterwards"); + assert.equal(process.env.GITHUB_OUTPUT, path.join(dir, "parent-GITHUB_OUTPUT")); + assert.equal(process.env.GITHUB_SERVER_URL, serverUrlBefore, "a variable the test passed does not outlive the run"); + parentFilesUntouched(); + }); +}); diff --git a/scripts/workflows.test.mjs b/scripts/workflows.test.mjs new file mode 100644 index 0000000..9c87e38 --- /dev/null +++ b/scripts/workflows.test.mjs @@ -0,0 +1,60 @@ +// The workflows this repository ships for customers (the example, the skill's +// asset, and the one the installer renders), read through the YAML parser. +// +// CR-5 Retargeting a PR's base did not re-run the review, and a reopened PR +// was not reviewed: add `reopened` and `edited` (the job's `if:` lets +// `edited` through only when the base changed). `statuses: write` lets +// the action put its verdict on the PR head for comment runs too. +// CR-6 A workflow-level concurrency group with cancel-in-progress let ANY +// comment cancel an in-flight review (each comment starts a run in the +// same group, which then skips). Concurrency is per job now, and +// comment runs have a group of their own that never cancels a running +// job (GitHub still replaces a PENDING one with a newer comment's — +// doc-drift.test.mjs holds the docs to saying so). + +import { describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { shippedWorkflows } from "./test-helpers/action-yaml.mjs"; + +describe("the shipped workflows", () => { + test("there are three, and the parser read each", async () => { + const wfs = await shippedWorkflows(); + assert.equal(wfs.length, 3); + for (const w of wfs) assert.ok(w.doc?.jobs?.review, `${w.name}: no review job`); + }); + + test("re-run on reopened and on a retargeted base (edited), not only opened/synchronize", async () => { + for (const w of await shippedWorkflows()) { + const types = w.doc.on.pull_request_target.types; + for (const t of ["opened", "synchronize", "reopened", "ready_for_review", "edited"]) { + assert.ok(types.includes(t), `${w.name}: pull_request_target.types lacks ${t}`); + } + const cond = w.doc.jobs.review.if; + assert.match(cond, /github\.event\.action != 'edited'/, `${w.name}: edited must be filtered`); + assert.match(cond, /github\.event\.changes\.base/, `${w.name}: edited runs only on a base change`); + } + }); + + test("no workflow-level concurrency; the job's group separates comment runs, which never cancel", async () => { + for (const w of await shippedWorkflows()) { + assert.equal(w.doc.concurrency, undefined, `${w.name}: workflow-level concurrency lets any comment cancel a review`); + const c = w.doc.jobs.review.concurrency; + assert.ok(c && c.group, `${w.name}: the review job needs its own concurrency group`); + assert.match(c.group, /github\.event_name == 'issue_comment'/, `${w.name}: comment runs need their own group`); + assert.match(String(c["cancel-in-progress"]), /github\.event_name != 'issue_comment'/, `${w.name}: a comment run must never cancel`); + } + }); + + test("they grant statuses: write, so the verdict lands on the PR head for comment runs too", async () => { + for (const w of await shippedWorkflows()) { + assert.equal(w.doc.permissions.statuses, "write", w.name); + } + }); + + test("the comment gate is still there (defence in depth with the action's own check)", async () => { + for (const w of await shippedWorkflows()) { + assert.match(w.doc.jobs.review.if, /\["OWNER", "MEMBER", "COLLABORATOR"\]/, w.name); + } + }); +}); diff --git a/skills/orca-review-action/SKILL.md b/skills/orca-review-action/SKILL.md index d02f671..1ddf978 100644 --- a/skills/orca-review-action/SKILL.md +++ b/skills/orca-review-action/SKILL.md @@ -80,7 +80,12 @@ private repo, and asking it there is noise. **Q4 — public repos only — "Who gets an automatic review?"** (`auto-review-authors`) - *Known contributors only (recommended)* → `"OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR"`. -- *Everyone* → `""`. +- *Everyone* → `"OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR,FIRST_TIME_CONTRIBUTOR,FIRST_TIMER,MANNEQUIN,NONE"`. + +Write the list out either way, never leave it unset and never write `"*"`: the +release the shipped workflow pins (v1.6.0) reads unset as everyone and `"*"` as +nobody, while from v1.7.0 (unreleased) unset means `OWNER,MEMBER,COLLABORATOR` on +a public repo. An explicit list means the same to both. Say plainly why Q4 exists: the workflow runs on `pull_request_target` with your OrcaRouter secret, so on a public repo a stranger's PR can spend from your wallet. @@ -160,13 +165,23 @@ gh pr create --fill && gh run watch A passing check blocks nothing until it is required. Walk the user through **Settings → Branches / Rulesets → Require status checks to pass** and adding the -**`review`** check, or offer to do it: +**`review`** check (the workflow's job), or offer to do it: ```bash gh api -X PATCH repos///branches//protection/required_status_checks \ -f 'checks[][context]=review' ``` +Require exactly that while the workflow pins v1.6.0: it writes no other check, and +a required check that never reports blocks every PR for ever. + +From v1.7.0 (unreleased) the action also writes an **`OrcaCode Review`** commit +status on the PR head after every run. Once the workflow pins the release that writes it, +require that status instead of the `review` job: it is the only check an on-demand +`/orcacode-review` run can update on the PR (GitHub reports that run's own job on +the default branch), and a skipped review leaves it "Not reviewed", so an +unreviewed PR cannot merge. + Confirm before running — branch protection changes affect everyone on the repo. ### 8. Report, and close on what they still owe @@ -223,18 +238,26 @@ gh run list --workflow orca-code-review.yml --limit 5 gh run view --log-failed ``` -`references/troubleshooting.md` maps each symptom to its cause and fix. The four that +`references/troubleshooting.md` maps each symptom to its cause and fix. The ones that account for most reports: -- **No run at all** — the PR is a draft and `trigger` is `ready_for_review`, the author - is outside `auto-review-authors`, or the app is off in the dashboard. +- **"Review skipped" notice** — the PR is a draft and `trigger` is + `ready_for_review`, the author is outside `auto-review-authors`, or the app is off in + the dashboard. The job passes; a maintainer's `/orcacode-review` reviews the head. + From v1.7.0 (unreleased) the `OrcaCode Review` status reads "Not reviewed" until a + review runs, and `on-skipped-review: "fail"` fails the job too. +- **`/orcacode-review` answered with "name the commit"** — from v1.7.0 (unreleased), on + a PR from a fork the command must name the head commit (`/orcacode-review `) + and that commit must still be the head. Read the new commits, then use the command + the reply gives. - **Run fails immediately, auth error** — `ORCAROUTER_API_KEY` is missing, misnamed, or scoped to an environment the job cannot read. - **"Diff too large" notice and a red check** — expected behavior with `on-oversized-diff: "fail"`. Split the PR, or raise `max-diff-kb` / `max-diff-files`. -- **Reviews work but the console's Settings/Analytics tabs are empty** — `@v1` points at - a commit older than `scripts/settings.mjs` / `scripts/report.mjs`. There is no error - for this; verify with `git ls-tree v1 scripts/` against the action repo. +- **Reviews work but the console's Settings/Analytics tabs are empty** — the pinned + action commit (or an old `@v1` tag) predates `scripts/settings.mjs` / + `scripts/report.mjs`. There is no error for this; verify with + `git ls-tree scripts/` against the action repo and pin a newer release commit. Report the actual failing output, not a paraphrase of it. @@ -242,8 +265,9 @@ Report the actual failing output, not a paraphrase of it. Confirm with the user first, then in this order: -1. **Drop the required check** — remove `review` from branch protection *before* deleting - the workflow. A required check whose workflow no longer exists never reports, and every +1. **Drop the required check** — remove `review` (and the `OrcaCode Review` status, + if it was required — from v1.7.0 (unreleased)) from branch protection *before* + deleting the workflow. A required check whose workflow no longer exists never reports, and every PR blocks forever with no way to clear it. 2. **Delete the workflow** — `rm .github/workflows/orca-code-review.yml`, commit, push. 3. **Leave the secret** — say that `ORCAROUTER_API_KEY` is harmless to keep and is worth diff --git a/skills/orca-review-action/assets/workflow.yml b/skills/orca-review-action/assets/workflow.yml index 2483e51..dd99efd 100644 --- a/skills/orca-review-action/assets/workflow.yml +++ b/skills/orca-review-action/assets/workflow.yml @@ -1,21 +1,20 @@ # OrcaCode Review — https://github.com/Continuum-AI-Corp/orca-code-review # # The review logic lives in the published action, so this file never copies -# scripts or config — bump the version tag to update. Add one repository +# scripts or config. The action is pinned to a release commit (version in the +# comment); let Dependabot's github-actions updates bump it. Add one repository # secret, ORCAROUTER_API_KEY, and enable the app at # OrcaRouter -> Apps -> OrcaCode Review. name: OrcaCode Review -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.event.issue.number || github.ref }} - cancel-in-progress: true - on: - # `synchronize` re-reviews on every new push. `ready_for_review` makes the - # dashboard's trigger=ready_for_review mode fire when a draft becomes ready. + # `synchronize` re-reviews on every new push and `reopened` reviews a PR that + # comes back. `edited` re-reviews a PR RETARGETED to another base branch (the + # job's `if:` ignores title and description edits). `ready_for_review` makes + # the dashboard's trigger=ready_for_review mode fire when a draft is ready. pull_request_target: - types: [opened, synchronize, ready_for_review] + types: [opened, synchronize, reopened, ready_for_review, edited] issue_comment: types: [created] @@ -23,10 +22,21 @@ permissions: contents: read pull-requests: write issues: write # clean/fallback PR comments + statuses: write # used from v1.7.0 (unreleased): the verdict on the PR head jobs: review: runs-on: ubuntu-latest + # Concurrency is PER JOB, in two groups. A workflow-level group with + # cancel-in-progress let ANY comment on the PR cancel an in-flight review: + # every comment starts a run in the same group, which then skips. Push runs + # share one group per PR and a newer push supersedes an older one; comment + # runs (/orcacode-review) get their own group and never cancel a running + # review. GitHub keeps one running and one pending job per group, so a newer + # comment does replace a comment run still pending — the latest one runs. + concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'issue_comment' && 'comment' || 'pr' }}-${{ github.event.pull_request.number || github.event.issue.number }} + cancel-in-progress: ${{ github.event_name != 'issue_comment' }} # Run on PR events, or when a trusted user comments the review command on a # PR. All four spellings are accepted — either prefix (`/` or `@`) with # either separator (hyphen or space). The command runs this privileged @@ -34,7 +44,8 @@ jobs: # maintainers may trigger it — otherwise any participant could burn paid # quota and spam reviews without pushing new commits. if: | - github.event_name == 'pull_request_target' || + (github.event_name == 'pull_request_target' && + (github.event.action != 'edited' || github.event.changes.base)) || (github.event_name == 'issue_comment' && github.event.issue.pull_request && (startsWith(github.event.comment.body, '/orcacode-review') || @@ -43,7 +54,7 @@ jobs: startsWith(github.event.comment.body, '@orcacode review')) && contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association)) steps: - - uses: Continuum-AI-Corp/orca-code-review@v1 + - uses: Continuum-AI-Corp/orca-code-review@6d253e0399c84848fedc8801176d6bea77817762 # v1.6.0 with: orcarouter-api-key: ${{ secrets.ORCAROUTER_API_KEY }} # Everything below is optional. Keep only the lines you actually diff --git a/skills/orca-review-action/references/inputs.md b/skills/orca-review-action/references/inputs.md index fb52b59..9a7d11d 100644 --- a/skills/orca-review-action/references/inputs.md +++ b/skills/orca-review-action/references/inputs.md @@ -1,6 +1,7 @@ # Action inputs -Every input of `Continuum-AI-Corp/orca-code-review@v1`. Read the row before +Every input of `Continuum-AI-Corp/orca-code-review` (pinned to a release commit +in the shipped workflow). Read the row before answering a question about behavior — do not guess a default. **These rows describe this action.** The hosted OrcaCode Review GitHub App runs a @@ -19,11 +20,12 @@ about the App from this file. | Input | Default | What it does | | --- | --- | --- | -| `orcarouter-url` | `https://api.orcarouter.ai/v1/chat/completions` | Chat-completions endpoint. Change only for a self-hosted gateway. | -| `github-token` | `${{ github.token }}` | Fetches the PR head, posts review comments, and reacts to a `/orcacode-review` command. | +| `orcarouter-url` | `https://api.orcarouter.ai/v1/chat/completions` | Chat-completions endpoint. Change only for a self-hosted gateway. From v1.7.0 (unreleased) it must be https; plain http is accepted only to this machine (`localhost`, `127.0.0.0/8`, `[::1]`), and anything else fails the run naming this input. | +| `github-token` | `${{ github.token }}` | Fetches the PR head, posts review comments, and reacts to a `/orcacode-review` command. From v1.7.0 (unreleased) it also writes the commit status on the PR head, which needs `statuses: write`. | +| `bot-login` | `""` | From v1.7.0 (unreleased). The login the action posts as when `github-token` is a GitHub App's installation token other than the job's own (e.g. `my-app[bot]`); it recognises its earlier notices by it. Not needed for the default `github.token` or a personal token. | | `brand` | `OrcaCode Review` | Name shown on PR comments. | | `router` | `orcarouter/orcacode-review` | Router alias that owns model selection. The action names no models: it injects raw facts (`x-cr-prev-tier`, `x-cr-prev-p0p1`) and this router's DSL recipe maps them to a concrete model. | -| `engine-version` | `1.3.13` | Pinned `@alibaba-group/open-code-review` version. Bump deliberately — later steps parse its JSON output shape. | +| `engine-version` | `1.3.13` | Pinned `@alibaba-group/open-code-review` version. From v1.7.0 (unreleased), only versions whose checksums the action pins (`scripts/engine-pins.json`) install — any other value fails the run. | ## Severity and merge gate @@ -39,18 +41,23 @@ empty string is valid and means "none". | Input | Default | What it does | | --- | --- | --- | -| `auto-review-authors` | `""` (everyone) | Author-association allowlist for **automatic** reviews. Others can still be reviewed on demand via `/orcacode-review`. Values: `OWNER`, `MEMBER`, `COLLABORATOR`, `CONTRIBUTOR`, `FIRST_TIME_CONTRIBUTOR`, `FIRST_TIMER`, `MANNEQUIN`, `NONE`. | +| `auto-review-authors` | unset: everyone (v1.6.0) | Author-association allowlist for **automatic** reviews. Others can still be reviewed on demand via `/orcacode-review`. Values: `OWNER`, `MEMBER`, `COLLABORATOR`, `CONTRIBUTOR`, `FIRST_TIME_CONTRIBUTOR`, `FIRST_TIMER`, `MANNEQUIN`, `NONE`. Write the list out: it means the same to every release. | +| | | From v1.7.0 (unreleased): unset means `OWNER,MEMBER,COLLABORATOR` on a public repo (everyone on a private one), and `"*"` means everyone — v1.6.0 reads `"*"` as nobody. Unless it lets everyone through, a push to a fork PR by someone other than its author is auto-reviewed only if that pusher can write to the repository. | +| `on-skipped-review` | `pass` | From v1.7.0 (unreleased). What a settings skip (auto-review off, on-demand mode, a draft, an author outside the allowlist) does to the **job**: `pass` keeps it green, as every release did; `fail` fails it. The `status-context` status reports a skip as "Not reviewed" either way. | +| `status-context` | `OrcaCode Review` | From v1.7.0 (unreleased). Commit status written on the PR head after every run (on-demand runs included): success only when a review ran on that head and the gate passed; a settings skip is "Not reviewed". Make it the required check; needs `statuses: write`. `""` turns it off. | On a **public** repo this is a spend control, not a preference. The workflow runs on `pull_request_target`, which bypasses GitHub's fork-approval gate, and the key is -wallet-metered — so any stranger opening a PR can trigger paid reviews. Set the -allowlist and put a budget + alert on the key. +wallet-metered. Put a budget + alert on the key either way. The shipped workflow's +`if:` honours the `/orcacode-review` command only from `OWNER`, `MEMBER` or +`COLLABORATOR`; from v1.7.0 (unreleased) the action itself refuses anyone else's +command too, and an unset allowlist means maintainers only on a public repo. ## Oversized-diff guard | Input | Default | What it does | | --- | --- | --- | -| `max-diff-kb` | `5000` | Skip the review when the merge-base diff exceeds this size. Raised from 512 so large PRs are reviewed rather than refused; the real ceiling is the model context window, which this cannot see. | +| `max-diff-kb` | `5000` | Skip the review when the merge-base diff exceeds this size. Raised from 512 so large PRs are reviewed rather than refused; the real ceiling is the model context window, which this cannot see. From v1.7.0 (unreleased), files named like a standard lockfile (`package-lock.json`, `yarn.lock`, `go.sum`, `Cargo.lock`, …) are not counted here or in `max-diff-files`; the summary lists them. | | `max-diff-files` | `2000` | Skip when the diff touches more files than this. Raised from 300. | | `on-oversized-diff` | `fail` | What a skip does to the check. `fail` means a diff padded past the limits cannot bypass a required gate. `pass` restores advisory behavior. | @@ -64,7 +71,7 @@ an error keeps the prior stage's findings and never aborts the review. | Input | Default | What it does | | --- | --- | --- | | `precision-filter` | `true` | L1 verifies each finding's `existing_code` snippet against the reviewed commit and re-homes or drops mismatches; L2 is an LLM judge that clusters by root cause and drops low-confidence findings. `false` posts the engine's raw findings. | -| `judge-model` | `deepseek/deepseek-v4-pro` | Model for the L2 judge. Should differ from the reviewer model so it acts as an independent second opinion. Ignored when `precision-filter` is `false`. | +| `judge-model` | `""` | Model for the L2 judge. Empty sends the `router` alias, and the router's recipe picks the judge model (its judge rule). Set a model id to pin one; it should differ from the reviewer model so it acts as an independent second opinion. Ignored when `precision-filter` is `false`. | | `judge-threshold` | `0.5` | Keep-threshold (0–1) for the judge's per-cluster confidence. Lower keeps more findings; raise to be stricter. | ## Throughput @@ -93,8 +100,13 @@ input wins **only when it differs from its documented default** — writing To make the file unambiguously authoritative, set `settings: "false"`. The fetch is skipped entirely and no server value can apply. -The settings fetch fails **open**: a control-plane outage falls back to built-in -defaults rather than killing the review. +The settings fetch fails **open**. When it gets no settings — a 4xx (an ordinary, +non-CI key gets one on every run) or an outage (5xx, timeout, network) — the run +uses this file's inputs rather than killing the review, and **`block-on` in the +workflow is the outage floor**: if an outage must not loosen a stricter dashboard +policy, write that policy here. From v1.7.0 (unreleased) the log names which +failure it was, and the run is exactly a `settings: "false"` run (every severity +displayed). ## Dashboard-only settings diff --git a/skills/orca-review-action/references/troubleshooting.md b/skills/orca-review-action/references/troubleshooting.md index e915dc8..9d97bd7 100644 --- a/skills/orca-review-action/references/troubleshooting.md +++ b/skills/orca-review-action/references/troubleshooting.md @@ -57,21 +57,24 @@ Working as configured. The guard runs before the engine, so nothing was spent. | Nothing was found | A clean run posts a summary, not inline comments. Check the job log's severity counts. | | Quiet mode | P2 findings are muted at posting time. The gate and report still counted them — the log will show a nonzero P2. | | Precision filter dropped them | L1 drops findings whose `existing_code` snippet does not match the reviewed commit; L2 drops low-confidence clusters. Lower `judge-threshold`, or set `precision-filter: "false"` to see raw output. | -| Missing permissions | The job needs `pull-requests: write` and `issues: write`. | +| Missing permissions | The job needs `pull-requests: write` and `issues: write` — and, from v1.7.0 (unreleased), `statuses: write` for the `OrcaCode Review` status. | ## Reviews work, but the console's Settings and Analytics tabs are empty -`@v1` points at a commit that predates `scripts/settings.mjs` and -`scripts/report.mjs`. Settings are never fetched and runs are never reported — -**with no error message**. Two dead tabs and working reviews is the signature. +The workflow pins an action commit (or, in an old workflow, the `@v1` tag) that +predates `scripts/settings.mjs` and `scripts/report.mjs`. Settings are never +fetched and runs are never reported — **with no error message**. Two dead tabs and +working reviews is the signature. -Verify against the action repo: +Verify against the action repo, with the SHA from the workflow's `uses:` line: ```bash -git ls-tree v1 scripts/ | grep -E 'settings|report' +git ls-tree scripts/ | grep -E 'settings|report' ``` -Fix by pinning a newer tag or an immutable commit SHA instead of `@v1`. +Fix by pinning a newer release commit (the version is in the `# v1.x.y` comment; +Dependabot's github-actions updates do this for you). Do not switch to `@v1`: a +tag can be moved, a commit cannot. ## Findings look wrong or noisy @@ -113,3 +116,26 @@ fails closed with a distinct "wall-clock timeout" error, separate from "no usable result" — the log says which. Raise it for very large diffs or slow-per-call models, or lower `concurrency` if the model is rate-limiting and the retries are what is eating the clock. + +## The check is red but nothing was reviewed + +An oversized diff fails the `review` job by default, so a PR padded past the +limits cannot slip through (`on-oversized-diff: "pass"` makes it advisory). A +settings skip — on-demand mode, auto-review off in the dashboard, a draft under +`ready_for_review`, an author outside `auto-review-authors` — passes the job with +a notice; a maintainer's `/orcacode-review` reviews the head. + +From v1.7.0 (unreleased) a settings skip also leaves the `OrcaCode Review` commit +status failing with "Not reviewed: " until a review runs, and +`on-skipped-review: "fail"` fails the job too. A red `OrcaCode Review` status on a +green job is that. + +## `/orcacode-review` did nothing + +From v1.7.0 (unreleased) the action itself honours the command only on a pull +request, only as the start of the comment, and only from `OWNER`, `MEMBER` or +`COLLABORATOR`, whatever the workflow's `if:` says. Anyone else's command is a +logged no-op. On a PR from a fork the command must also name the head commit — +`/orcacode-review ` (7+ hex characters) — and that commit must still be the +head; otherwise the action replies on the PR with the current head and the +command to use. diff --git a/workflows/orca-code-review.yml b/workflows/orca-code-review.yml index 6055c30..91437a5 100644 --- a/workflows/orca-code-review.yml +++ b/workflows/orca-code-review.yml @@ -2,25 +2,28 @@ # # Copy this file into your repo at `.github/workflows/` and add one secret, # `ORCAROUTER_API_KEY`. The review logic lives in the published action, so you -# never copy scripts or config — just bump the version tag to update. +# never copy scripts or config. The action is pinned to a release COMMIT (its +# version in the comment) rather than a movable tag; let Dependabot's +# github-actions updates bump it. # # One review per push: findings post as inline PR comments, and a severity gate -# can fail the -# check to block the merge — mark it "required" in branch protection. +# can fail the check to block the merge. Make the `review` check required in +# branch protection. +# +# From v1.7.0 (unreleased) the action also writes an "OrcaCode Review" commit +# status on the PR head; once you pin the release that writes it, require that status +# instead — it is the one verdict an on-demand /orcacode-review run can also +# update on the PR head. name: OrcaCode Review -concurrency: - group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.event.issue.number || github.ref }} - cancel-in-progress: true - on: - # `synchronize` re-reviews on every new push — the per-commit review loop. The - # re-run needed — and a GITHUB_TOKEN label change can't trigger one anyway). - # `ready_for_review` makes the dashboard's trigger=ready_for_review mode fire - # when a draft PR becomes ready (drafts are skipped in that mode). + # `synchronize` re-reviews on every new push and `reopened` reviews a PR that + # comes back. `edited` re-reviews a PR RETARGETED to another base branch (the + # job's `if:` ignores title and description edits). `ready_for_review` makes + # the dashboard's trigger=ready_for_review mode fire when a draft is ready. pull_request_target: - types: [opened, synchronize, ready_for_review] + types: [opened, synchronize, reopened, ready_for_review, edited] issue_comment: types: [created] @@ -28,10 +31,21 @@ permissions: contents: read pull-requests: write issues: write # clean/fallback PR comments + statuses: write # used from v1.7.0 (unreleased): the verdict on the PR head jobs: review: runs-on: ubuntu-latest + # Concurrency is PER JOB, in two groups. A workflow-level group with + # cancel-in-progress let ANY comment on the PR cancel an in-flight review: + # every comment starts a run in the same group, which then skips. Push runs + # share one group per PR and a newer push supersedes an older one; comment + # runs (/orcacode-review) get their own group and never cancel a running + # review. GitHub keeps one running and one pending job per group, so a newer + # comment does replace a comment run still pending — the latest one runs. + concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'issue_comment' && 'comment' || 'pr' }}-${{ github.event.pull_request.number || github.event.issue.number }} + cancel-in-progress: ${{ github.event_name != 'issue_comment' }} # Run on PR events, or when a trusted user comments the review command on a # PR. All four spellings are accepted — either prefix (`/` or `@`) with # either separator (hyphen or space) — which is the same set the OrcaCode @@ -42,7 +56,8 @@ jobs: # (owner/member/collaborator) may trigger it — otherwise any participant # could burn paid quota and spam reviews without pushing new commits. if: | - github.event_name == 'pull_request_target' || + (github.event_name == 'pull_request_target' && + (github.event.action != 'edited' || github.event.changes.base)) || (github.event_name == 'issue_comment' && github.event.issue.pull_request && (startsWith(github.event.comment.body, '/orcacode-review') || @@ -51,7 +66,7 @@ jobs: startsWith(github.event.comment.body, '@orcacode review')) && contains(fromJSON('["OWNER", "MEMBER", "COLLABORATOR"]'), github.event.comment.author_association)) steps: - - uses: Continuum-AI-Corp/orca-code-review@v1 + - uses: Continuum-AI-Corp/orca-code-review@6d253e0399c84848fedc8801176d6bea77817762 # v1.6.0 with: orcarouter-api-key: ${{ secrets.ORCAROUTER_API_KEY }} # All optional — uncomment to override the defaults: