From 06cac609072c336a5f1d1da11c2c49c075fbb940 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 03:47:10 +0000 Subject: [PATCH 01/28] fix(action): keep github.token out of step scripts and off git's argv (CR-13) Two comments in run: blocks named the github.token expression with its braces, so GitHub expanded the live token into the step script it writes to disk. The PR-head fetch passed the Basic-auth header with `git -c http.extraheader=...`, which puts the token on argv where any process on a shared runner can read it from /proc//cmdline. The comments now name the expression without braces, and the fetch carries the header through GIT_CONFIG_COUNT/KEY/VALUE (git >= 2.31), scoped to the server URL. Adds the `yaml` parser as a dev-only dependency (exact pin, lockfile integrity, `npm ci --ignore-scripts` in CI) so structural tests read action.yml and the shipped workflows through a parser instead of regexes, and a helper that runs a step's bash or github-script body with doubles. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- .github/workflows/publish.yml | 4 +- .github/workflows/test.yml | 5 + action.yml | 19 ++-- package-lock.json | 19 ++++ package.json | 3 + scripts/action-hygiene.test.mjs | 83 ++++++++++++++++ scripts/test-helpers/action-yaml.mjs | 143 +++++++++++++++++++++++++++ 7 files changed, 269 insertions(+), 7 deletions(-) create mode 100644 scripts/action-hygiene.test.mjs create mode 100644 scripts/test-helpers/action-yaml.mjs diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 482d135..5a93a91 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -112,7 +112,9 @@ jobs: - 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. diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index fcc164f..21f77d6 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -35,6 +35,11 @@ jobs: with: node-version: ${{ matrix.node-version }} + # Dev-only: the YAML parser the structural tests read action.yml and the + # shipped workflows with. `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/action.yml b/action.yml index 1b15546..9ffb203 100644 --- a/action.yml +++ b/action.yml @@ -319,7 +319,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, @@ -604,11 +604,18 @@ runs: 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" - name: Oversized-diff guard id: guard @@ -1736,7 +1743,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, diff --git a/package-lock.json b/package-lock.json index 277f116..26dd0c1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,9 +11,28 @@ "bin": { "orcacode-review": "bin/orcacode-review.mjs" }, + "devDependencies": { + "yaml": "2.9.1" + }, "engines": { "node": ">=18.17" } + }, + "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..b2afbda 100644 --- a/package.json +++ b/package.json @@ -42,5 +42,8 @@ "license": "MIT", "publishConfig": { "access": "public" + }, + "devDependencies": { + "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/test-helpers/action-yaml.mjs b/scripts/test-helpers/action-yaml.mjs new file mode 100644 index 0000000..e815201 --- /dev/null +++ b/scripts/test-helpers/action-yaml.mjs @@ -0,0 +1,143 @@ +// 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)); +} + +// 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: { ...process.env, 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; + +export async function runGithubScript(script, { github, context, core, env = {} } = {}) { + const saved = {}; + for (const [k, v] of Object.entries(env)) { + saved[k] = process.env[k]; + if (v === undefined || v === null) delete process.env[k]; + else process.env[k] = String(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 }; +} From 4b4a0f72b200b505dfe1b2405457f0b9ec1b3e67 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 03:48:58 +0000 Subject: [PATCH 02/28] fix(gate): fail the merge gate closed when gate.mjs cannot decide (CR-16) The enforce step read every non-zero gate.mjs exit as "no blocking finding", and gate.mjs itself exited 1 on an unreadable result. Node also exits 1 on any uncaught exception, so a crashed gate, a missing or garbled result, or a killed process all passed the merge gate. gate.mjs now answers with distinct codes: 0 = a blocking finding, 10 = none, 2 = usage, 3 = the result could not be read (including a result with no comments array). The enforce step accepts only 0 and 10 as answers and fails closed on anything else; the summary and the run report treat anything but 10 as blocked, matching what the enforce step does. The old gate.test.mjs case "missing / unparseable file -> no match (exit 1)" pinned the fail-open behaviour and now expects exit 3. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- action.yml | 51 ++++++++---- scripts/gate-wiring.test.mjs | 157 +++++++++++++++++++++++++++++++++++ scripts/gate.mjs | 26 ++++-- scripts/gate.test.mjs | 53 ++++++++++-- 4 files changed, 258 insertions(+), 29 deletions(-) create mode 100644 scripts/gate-wiring.test.mjs diff --git a/action.yml b/action.yml index 9ffb203..89e1881 100644 --- a/action.yml +++ b/action.yml @@ -1618,13 +1618,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. @@ -1668,11 +1671,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 @@ -1694,10 +1714,13 @@ 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" \ diff --git a/scripts/gate-wiring.test.mjs b/scripts/gate-wiring.test.mjs new file mode 100644 index 0000000..1bcf6c8 --- /dev/null +++ b/scripts/gate-wiring.test.mjs @@ -0,0 +1,157 @@ +// 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"), + 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, ); }); From 9d4b913aea48e3cb274c96a9ad2bcf66e1d7b681 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 03:51:37 +0000 Subject: [PATCH 03/28] fix(settings): a dashboard outage can tighten block_on, never loosen it (CR-16) On any settings outage settings.mjs wrote its built-in defaults, and the action used block_on=P0,P1 from them whenever the workflow left block-on at its default. A workspace whose dashboard blocks on P2 silently lost that policy for the run. settings.mjs now names every stand-in value in `unresolved` (every field on an envelope failure, the one field on a field failure; absent when the server answered validly). The settings step reads it: an explicit workflow block-on stays authoritative, but a workflow that defers to the dashboard blocks on every severity (P0,P1,P2,P3) while the dashboard's block_on is unknown, with a warning annotation. A settings file that cannot be read at all counts as unresolved. settings.test.mjs expectations for the fallback file now include the `unresolved` marker (the shape changed; the fail-open-for-reviews behaviour it pins is unchanged). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- action.yml | 25 ++++++- scripts/settings-wiring.test.mjs | 122 +++++++++++++++++++++++++++++++ scripts/settings.mjs | 31 ++++++-- scripts/settings.test.mjs | 23 ++++-- 4 files changed, 184 insertions(+), 17 deletions(-) create mode 100644 scripts/settings-wiring.test.mjs diff --git a/action.yml b/action.yml index 89e1881..22136cf 100644 --- a/action.yml +++ b/action.yml @@ -377,8 +377,9 @@ runs: # 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. + # (a settings hiccup must never kill reviews), naming every stand-in in + # `unresolved`. Reviews stay fail-open; the merge gate does not: an + # unresolved block_on blocks on every severity unless the workflow pins it. - name: Fetch review settings id: settings shell: bash @@ -396,6 +397,7 @@ runs: IS_DRAFT: ${{ steps.pr.outputs.is_draft }} AUTHOR_ASSOC: ${{ steps.pr.outputs.author_association }} AUTO_REVIEW_AUTHORS: ${{ inputs.auto-review-authors }} + BRAND: ${{ inputs.brand }} run: | # The auto-event gate is defined UP FRONT — before the settings-disabled # short-circuit — so BOTH the settings-disabled (workflow-file- @@ -507,11 +509,28 @@ runs: REPORT_ON=$(setting report_on "P0,P1") RUBRIC=$(setting rubric "") + # Which values are stand-ins for ones the dashboard did not give us. + # settings.mjs names them in `unresolved`; a file that cannot be read at + # all (settings.mjs died before writing it) means every value is one. + 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="unreadable" + # 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 [ "$UNRESOLVED" = "unreadable" ] || printf ',%s,' "$UNRESOLVED" | grep -q ',block_on,'; then + # THE WORKFLOW DEFERS TO THE DASHBOARD AND THE DASHBOARD COULD NOT BE + # READ. Its block_on is unknown, and the built-in P0,P1 standing in for + # it may be looser than what the workspace set — an outage must never + # be the thing that lets a P2 through a gate configured to block it. + # So block on every severity for this run: an outage can only tighten + # the gate. Pin `block-on:` in the workflow to use your own value. + BLOCK_ON="P0,P1,P2,P3" + echo "::warning::$BRAND: the OrcaRouter dashboard settings could not be read, so its block-on is unknown — blocking on every severity (P0,P1,P2,P3) for this run. Set block-on in the workflow to choose the outage value yourself." + 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. diff --git a/scripts/settings-wiring.test.mjs b/scripts/settings-wiring.test.mjs new file mode 100644 index 0000000..6f874d5 --- /dev/null +++ b/scripts/settings-wiring.test.mjs @@ -0,0 +1,122 @@ +// The "Fetch review settings" step, run for real (bash, through the YAML +// parser) with settings.mjs stood in by a stub that writes a chosen file. +// +// What is pinned here is the merge gate's FAIL DIRECTION when the dashboard +// cannot be read. block_on's built-in default (P0,P1) is looser than plenty of +// dashboard values it may stand in for, so a settings outage used to replace a +// stricter dashboard policy with P0,P1 — silently. Now: +// - an explicit `block-on:` in the workflow is authoritative, outage or not; +// - a workflow that defers to the dashboard (block-on left at its default) +// blocks on EVERY severity while the dashboard's value is unknown, so an +// outage can only tighten the gate, never loosen it. + +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 } from "./test-helpers/action-yaml.mjs"; + +let dir; +before(() => { + 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", 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: { + 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: "P0,P1", + 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); + +describe("settings outage never loosens block_on", () => { + test("a reachable dashboard's stricter block_on is used", () => { + const { outputs } = runSettings({ written: { ...DEFAULTS, block_on: "P0,P1,P2" } }); + assert.equal(outputs.block_on, "P0,P1,P2"); + }); + + test("a reachable dashboard may still say 'block on nothing'", () => { + const { outputs } = runSettings({ written: { ...DEFAULTS, block_on: "" } }); + assert.equal(outputs.block_on, ""); + }); + + test("outage + workflow deferring to the dashboard -> block on every severity, loudly", () => { + const { outputs, log } = runSettings({ written: { ...DEFAULTS, unresolved: ALL } }); + assert.equal(outputs.block_on, "P0,P1,P2,P3"); + assert.match(log, /::warning::.*(could not|unavailable|unreachable)/i); + }); + + test("outage + an explicit workflow block-on -> the workflow's value", () => { + const { outputs } = runSettings({ written: { ...DEFAULTS, unresolved: ALL }, inputBlockOn: "P0" }); + assert.equal(outputs.block_on, "P0"); + }); + + test("an invalid block_on from the server is treated like an outage for that field", () => { + const { outputs } = runSettings({ written: { ...DEFAULTS, unresolved: ["block_on"] } }); + assert.equal(outputs.block_on, "P0,P1,P2,P3"); + }); + + 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"); + }); + + test("no settings file at all (settings.mjs died) -> every severity, never the P0,P1 fallback", () => { + const { outputs } = runSettings({ written: null }); + assert.equal(outputs.block_on, "P0,P1,P2,P3"); + }); +}); diff --git a/scripts/settings.mjs b/scripts/settings.mjs index 82612eb..7bfe13e 100644 --- a/scripts/settings.mjs +++ b/scripts/settings.mjs @@ -22,6 +22,14 @@ // 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). block_on's default +// (P0,P1) is LOOSER than many a dashboard value it may replace, so the action +// reads this list and refuses to let a stand-in loosen the merge gate: an +// unresolved block_on blocks on every severity unless the workflow pins one. +// // 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. @@ -83,10 +91,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,9 +137,13 @@ function validateSettings(data) { fallback("rubric", data.rubric); } - return out; + return unresolved.length ? { ...out, unresolved } : out; } +// The built-in defaults, marked as stand-ins for every field: what an envelope +// failure (or no usable arguments at all) writes. +const fallbackSettings = () => ({ ...DEFAULTS, unresolved: Object.keys(DEFAULTS) }); + // One settings fetch. Throws on any envelope problem — the caller retries. async function fetchOnce(endpoint, key) { const res = await fetch(endpoint, { @@ -149,7 +164,7 @@ async function resolveSettings(opts) { 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(); } for (let attempt = 1; attempt <= ATTEMPTS; attempt += 1) { @@ -160,8 +175,10 @@ async function resolveSettings(opts) { } 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: giving up — using built-in defaults (reviews continue; the action will not let them loosen block_on)", + ); + return fallbackSettings(); } async function main() { @@ -183,7 +200,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(); } else { settings = await resolveSettings(opts); } @@ -206,7 +223,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())}\n`); process.exit(0); }, ); diff --git a/scripts/settings.test.mjs b/scripts/settings.test.mjs index 5efbcb8..694dcd9 100644 --- a/scripts/settings.test.mjs +++ b/scripts/settings.test.mjs @@ -53,6 +53,12 @@ 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 }; + const listen = (server) => new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server.address().port))); @@ -158,8 +164,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); + assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), FALLBACK); + assert.deepEqual(JSON.parse(r.stdout), FALLBACK); assert.match(r.stderr, /default/i, "the fallback must be noted on stderr"); } finally { await gw.close(); @@ -175,7 +181,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); + assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), FALLBACK); assert.match(r.stderr, /default/i); }); @@ -185,7 +191,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); + assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), FALLBACK); } finally { await gw.close(); } @@ -197,7 +203,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); + assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), FALLBACK); } finally { await gw.close(); } @@ -206,7 +212,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); + assert.deepEqual(JSON.parse(r.stdout), FALLBACK); assert.match(r.stderr, /usage/i); }); @@ -216,7 +222,7 @@ 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); + assert.deepEqual(JSON.parse(readFileSync(out, "utf8")), FALLBACK); }); }); @@ -250,6 +256,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"); From f6f22f4da99fd62b318397e5e12ea80a7ed2297e Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 03:56:35 +0000 Subject: [PATCH 04/28] fix(proxy): pin the proxy to one https endpoint and keep the key out of the engine (CR-16, CR-4) fact-proxy resolved the client's request target with `new URL(req.url, upstream)`, so an absolute-form (`http://host/...`), scheme-relative (`//host/...`) or backslash target was forwarded to that other host with the client's Authorization; an http: upstream was accepted for any host. Meanwhile the engine that reads the fork checkout ran with the real OrcaRouter key in OCR_LLM_TOKEN, and its parent shell's environment (readable by the same user via /proc) held it too. The proxy now: - accepts only origin-form targets equal to the configured endpoint's path (anything else is answered 404 and dials nothing), always to the configured origin; - refuses a non-https upstream unless the host is loopback; - reads its key from CR_UPSTREAM_KEY_FILE, unlinks the file before it prints PROXY_URL, and replaces the client's Authorization (and drops x-api-key) with it. The key is deliberately not taken from the environment: /proc//environ is readable by the engine's user. action.yml stages the key in a 0600 file in a step that runs nothing from the PR; the Review step's env carries no secret, the engine and the judge get a placeholder token, and the step refuses to start the engine while the key file still exists. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- action.yml | 43 ++++- scripts/fact-proxy-pinning.test.mjs | 247 ++++++++++++++++++++++++ scripts/fact-proxy.mjs | 110 ++++++++++- scripts/review-step.test.mjs | 59 ++++++ scripts/test-helpers/action-yaml.mjs | 63 ++++++ scripts/test-helpers/review-harness.mjs | 159 +++++++++++++++ 6 files changed, 671 insertions(+), 10 deletions(-) create mode 100644 scripts/fact-proxy-pinning.test.mjs create mode 100644 scripts/review-step.test.mjs create mode 100644 scripts/test-helpers/review-harness.mjs diff --git a/action.yml b/action.yml index 22136cf..3d952c2 100644 --- a/action.yml +++ b/action.yml @@ -244,6 +244,7 @@ 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/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" \ @@ -747,6 +748,27 @@ runs: ENGINE_VERSION: ${{ inputs.engine-version }} run: npm install -g "@alibaba-group/open-code-review@${ENGINE_VERSION}" + # 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 != 'skip' && steps.guard.outputs.decision != 'skip' + 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' @@ -793,7 +815,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" @@ -853,9 +879,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 @@ -864,6 +896,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. @@ -1881,6 +1917,7 @@ 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/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" \ 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..1011d07 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 @@ -304,8 +323,39 @@ function retryDelayMs(retryIndex, retryAfter) { return BACKOFF_MS[Math.min(retryIndex, BACKOFF_MS.length - 1)]; } +const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]); + +// The one upstream this proxy may talk to. https, or http to a loopback host. +export function pinnedUpstream(upstreamUrl) { + const u = new URL(upstreamUrl); + if (u.protocol === "https:") return u; + if (u.protocol === "http:" && LOOPBACK_HOSTS.has(u.hostname)) return u; + throw new Error( + `fact-proxy: refusing upstream ${u.protocol}//${u.host} — the gateway must be https (plain http is allowed for a loopback host only)`, + ); +} + +// 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 +366,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 +377,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 +407,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 +702,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 +742,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/review-step.test.mjs b/scripts/review-step.test.mjs new file mode 100644 index 0000000..0f094ed --- /dev/null +++ b/scripts/review-step.test.mjs @@ -0,0 +1,59 @@ +// The Review step, run for real: action.yml's own bash (through the YAML +// parser, with its env: block resolved the way the runner resolves it), the +// real fact-proxy, and a stand-in `ocr` that behaves like a hostile engine. +// +// What the engine can see is the point. It reads the fork's files and follows +// the instructions in them as well as any LLM agent does, so whatever is in its +// environment, its parent's, or reachable through a symlink in the checkout is +// one prompt injection away from being quoted in a PR comment. + +import fs from "node:fs"; +import path from "node:path"; +import { after, describe, test } from "node:test"; +import assert from "node:assert/strict"; + +import { step } from "./test-helpers/action-yaml.mjs"; +import { REAL_KEY, makeRepo, runReview, cleanupReviewHarness } from "./test-helpers/review-harness.mjs"; + +after(cleanupReviewHarness); + +describe("the engine never holds the real OrcaRouter key", () => { + test("the Review step's env: names no secret input", () => { + const env = step("review").env; + for (const [k, v] of Object.entries(env)) { + assert.doesNotMatch(String(v), /inputs\.orcarouter-api-key|inputs\.github-token|secrets\./, `Review env ${k}`); + } + assert.doesNotMatch(String(env.OCR_LLM_TOKEN), /\$\{\{/, "OCR_LLM_TOKEN must be a literal placeholder"); + }); + + test("the engine sees a placeholder, the gateway gets the real key, and no process exposes it", async () => { + const { repo, sha } = makeRepo("key", (d) => fs.writeFileSync(path.join(d, "app.js"), "export const a = 2;\n")); + const { r, seen, upstream, temp } = await runReview({ repo, sha }); + assert.equal(r.status, 0, r.stdout + r.stderr); + assert.ok(seen, "the engine stand-in never ran"); + + assert.notEqual(seen.env.OCR_LLM_TOKEN, REAL_KEY); + for (const [k, v] of Object.entries(seen.env)) { + assert.ok(!String(v).includes(REAL_KEY), `the engine's env carries the key in ${k}`); + } + if (seen.proc.length) { + assert.ok( + !seen.proc.some((t) => t.includes(REAL_KEY)), + "some /proc//environ or cmdline the engine can read carries the key", + ); + } + + assert.equal(seen.call, 200, "the engine's call through the proxy failed"); + assert.equal(upstream.length, 1); + assert.equal(upstream[0].headers.authorization, `Bearer ${REAL_KEY}`); + + assert.deepEqual( + fs + .readdirSync(temp) + .filter((f) => fs.statSync(path.join(temp, f)).isFile()) + .filter((f) => fs.readFileSync(path.join(temp, f), "latin1").includes(REAL_KEY)), + [], + "a file under RUNNER_TEMP still holds the key after the proxy started", + ); + }); +}); diff --git a/scripts/test-helpers/action-yaml.mjs b/scripts/test-helpers/action-yaml.mjs index e815201..07dc58e 100644 --- a/scripts/test-helpers/action-yaml.mjs +++ b/scripts/test-helpers/action-yaml.mjs @@ -141,3 +141,66 @@ export function fakeCore() { }; 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: { ...process.env, 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(); + } +} + From d0529eca9dc64e00e0453af88cee33652898b3c4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 04:00:12 +0000 Subject: [PATCH 05/28] fix(action): harden the PR checkout before anything reads it (CR-4, CR-14) The engine read a fork checkout in which: - symlinks were left in place (only .opencodereview was removed), so a committed `notes.md -> /proc/self/environ` pointed its file tools outside the repository; - the PR's .gitattributes applied, so `* -diff` (or the `binary` macro) turned every change into "Binary files differ" for both the size guard and the engine; - the root .gitignore was the PR's, and the engine reads it to decide what to skip, so a PR could ignore its own changes; - files the engine skips by default (tests, fixtures, snapshots, generated code, unsupported types, binaries) vanished from the review without a word. New scripts/harden-checkout.mjs, run by a new "Harden the checkout" step after the PR-head fetch and again right before the engine: deletes every symlink (tracked mode 120000 and untracked, files and directories), writes `* !diff` to $GIT_DIR/info/attributes so repository attributes lose their say over diffing (works on any git, unlike GIT_ATTR_SOURCE), removes .opencodereview/, and restores the base revision's .gitignore. Exits 1 if any of that fails. New scripts/excluded-files.mjs lists the changed files the engine skips, with the engine's own rules (bin/selection.mjs over the vendored data), capped at 200; the summary renders them in a collapsible "Not reviewed" block with file names neutralised for markdown. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- action.yml | 36 ++++- scripts/excluded-files.mjs | 79 +++++++++++ scripts/harden-checkout.mjs | 132 +++++++++++++++++++ scripts/harden-checkout.test.mjs | 220 +++++++++++++++++++++++++++++++ scripts/review-step.test.mjs | 34 +++++ scripts/summary-comment.mjs | 43 +++++- scripts/summary-comment.test.mjs | 46 +++++++ 7 files changed, 585 insertions(+), 5 deletions(-) create mode 100644 scripts/excluded-files.mjs create mode 100644 scripts/harden-checkout.mjs create mode 100644 scripts/harden-checkout.test.mjs diff --git a/action.yml b/action.yml index 3d952c2..39446d4 100644 --- a/action.yml +++ b/action.yml @@ -244,7 +244,7 @@ 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-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" \ @@ -637,6 +637,25 @@ runs: 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 != 'skip' + 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' @@ -807,6 +826,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. @@ -857,8 +877,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 @@ -1625,6 +1647,8 @@ 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 with: github-token: ${{ inputs.github-token }} script: | @@ -1707,6 +1731,10 @@ 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); + } const summaryMd = execFileSync('node', args, { encoding: 'utf8' }); // Preserve the author's description text; only the marker region changes. @@ -1917,7 +1945,7 @@ 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-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" \ 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/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/review-step.test.mjs b/scripts/review-step.test.mjs index 0f094ed..587ea13 100644 --- a/scripts/review-step.test.mjs +++ b/scripts/review-step.test.mjs @@ -57,3 +57,37 @@ describe("the engine never holds the real OrcaRouter key", () => { ); }); }); + +describe("the engine sees no symlink and no PR-controlled config", () => { + test("tracked and untracked symlinks are gone before the engine starts", async () => { + const { repo, sha } = makeRepo("links", (d) => { + fs.symlinkSync("/proc/self/environ", path.join(d, "notes.md")); + fs.mkdirSync(path.join(d, ".opencodereview")); + fs.writeFileSync(path.join(d, ".opencodereview", "rule.json"), '{"exclude":["**"]}'); + }); + fs.symlinkSync("/root", path.join(repo, "untracked-link")); + const { r, seen } = await runReview({ repo, sha }); + assert.equal(r.status, 0, r.stdout + r.stderr); + assert.deepEqual(seen.symlinks, []); + assert.equal(fs.existsSync(path.join(repo, ".opencodereview")), false); + }); +}); + +describe("action.yml: the checkout is hardened before anything reads it", () => { + test("a Harden step runs after the PR-head fetch and before the size guard", async () => { + const { actionSteps } = await import("./test-helpers/action-yaml.mjs"); + const names = actionSteps().map((s) => s.id || s.name); + const fetch = names.indexOf("Fetch PR head (covers fork PRs)"); + const harden = names.indexOf("harden"); + const guard = names.indexOf("guard"); + assert.ok(harden > fetch && harden < guard, `order: fetch=${fetch} harden=${harden} guard=${guard}`); + assert.match(step("harden").run, /harden-checkout\.mjs|\$HARDEN/); + assert.match(step("harden").run, /excluded-files\.mjs|\$EXCLUDED/); + }); + + test("the summary is handed the list of skipped files", async () => { + const script = step("Summary (PR description)").with.script; + assert.match(script, /--excluded/); + assert.ok(step("Summary (PR description)").env.EXCLUDED_FILE, "the summary step needs EXCLUDED_FILE"); + }); +}); diff --git a/scripts/summary-comment.mjs b/scripts/summary-comment.mjs index f8faff6..ba0e3ce 100644 --- a/scripts/summary-comment.mjs +++ b/scripts/summary-comment.mjs @@ -3,7 +3,13 @@ // // 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 ] +// +// --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 +81,7 @@ 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]; // 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 +172,38 @@ 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("", "
"); +} + 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/); + }); +}); From 41251a73aee43a86ff5e0663ccf613509a2f9933 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 04:08:33 +0000 Subject: [PATCH 06/28] fix(posting): one sanitising, redacting funnel for everything the action posts (CR-7, CR-4, CR-20) Finding text and file paths were posted as raw markdown: a finding written under a fork's influence could @mention teams, render HTML (,
, comments forging the action's own markers), link anywhere, print a fake "## OrcaCode Review ... No findings" heading and run to any length; a path with a backtick broke out of its code span. Nothing redacted the OrcaRouter key or the GitHub token from what was posted. The guardrail-block comment published the workspace policy name and up to 300 characters of match detail on public PRs. New scripts/publish-guard.mjs, used by every github-script step that posts (review, fallback comment, notices, PR description): - sanitizeUntrusted() for each fragment of finding text: strips HTML comments, escapes HTML and link brackets outside code, defangs URLs not pointing into this repository or the OrcaRouter docs host, neutralises @mentions with a zero-width joiner, demotes forged headings, caps length, leaves code spans and fences intact and closes a fence a fragment left open. Errs only towards escaping. Applied to titles and bodies after they are split, so a split cannot cut a code span in half. - codeSpan() for file paths. - guardGithub() wraps the client so every posting call redacts the key and the token: raw, base64 at any alignment within a longer run, base64url, URL-encoded, and the Basic-auth value. - at most 50 findings are posted (most severe first; the rest counted in the review body) and bodies stay under GitHub's size limit. The guardrail/firewall notice is generic on public repositories (and when visibility is unknown); private repositories keep the sanitised policy name and detail. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- action.yml | 170 +++++++++++++---- scripts/gate-wiring.test.mjs | 1 + scripts/posting.test.mjs | 283 ++++++++++++++++++++++++++++ scripts/publish-guard.mjs | 325 +++++++++++++++++++++++++++++++++ scripts/publish-guard.test.mjs | 214 ++++++++++++++++++++++ 5 files changed, 958 insertions(+), 35 deletions(-) create mode 100644 scripts/posting.test.mjs create mode 100644 scripts/publish-guard.mjs create mode 100644 scripts/publish-guard.test.mjs diff --git a/action.yml b/action.yml index 39446d4..7ac527b 100644 --- a/action.yml +++ b/action.yml @@ -573,9 +573,19 @@ runs: BRAND: ${{ inputs.brand }} PR_NUMBER: ${{ steps.pr.outputs.number }} REASON: ${{ steps.settings.outputs.reason }} + # 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 brand = process.env.BRAND; const num = Number(process.env.PR_NUMBER); const repo = { owner: context.repo.owner, repo: context.repo.repo }; @@ -586,7 +596,7 @@ 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` + + `⏸️ **Automatic review is off for this PR** (${guard.sanitizeUntrusted(process.env.REASON, { atLineStart: false, maxChars: 300 })}).\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 ` + @@ -598,10 +608,10 @@ runs: }); const existing = comments.find((c) => c.body && 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(); @@ -707,9 +717,19 @@ 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); const brand = process.env.BRAND; const num = Number(process.env.PR_NUMBER); const repo = { owner: context.repo.owner, repo: context.repo.repo }; @@ -728,10 +748,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 ` + @@ -744,9 +764,9 @@ runs: }); const existing = comments.find((c) => c.body && 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(); @@ -1303,9 +1323,21 @@ runs: 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); const fs = require('fs'); let block; try { @@ -1322,14 +1354,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}`; @@ -1355,9 +1398,9 @@ runs: }); const existing = existingComments.find((c) => c.body && 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 @@ -1436,9 +1479,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); @@ -1514,13 +1567,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, }); } @@ -1547,13 +1600,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) { @@ -1562,16 +1631,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; @@ -1580,28 +1649,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) { @@ -1609,11 +1698,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 @@ -1649,9 +1739,19 @@ runs: PASSES: ${{ steps.review.outputs.passes }} # Changed files the engine skips (excluded-files.mjs, Harden step). EXCLUDED_FILE: ${{ runner.temp }}/cr-excluded.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 { execFileSync } = require('child_process'); const { pathToFileURL } = require('url'); @@ -1740,7 +1840,7 @@ runs: // 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 diff --git a/scripts/gate-wiring.test.mjs b/scripts/gate-wiring.test.mjs index 1bcf6c8..5318f3b 100644 --- a/scripts/gate-wiring.test.mjs +++ b/scripts/gate-wiring.test.mjs @@ -136,6 +136,7 @@ describe("Summary (PR description)", () => { 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", 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..c4608eb --- /dev/null +++ b/scripts/publish-guard.mjs @@ -0,0 +1,325 @@ +// 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; +// - neutralises @mentions with a zero-width joiner; +// - demotes heading and setext lines, so a finding +// cannot print "## OrcaCode Review ✅ No findings"; +// - 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. +// 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. +// +// 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. + +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) || " "}\``; +} + +function allowedUrl(raw, { repo, serverUrl }) { + 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}/`); +} + +const URL_RE = /(?:[a-z][a-z0-9+.-]*:\/\/|www\.)[^\s<]*/gi; + +// Escape one run of plain (non-code) text on ONE line. +function escapeText(t, opts) { + let out = ""; + let last = 0; + for (const m of t.matchAll(URL_RE)) { + // 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. + let url = m[0]; + 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; + } + out += escapePlain(t.slice(last, m.index)); + out += allowedUrl(url, opts) ? url : codeSpan(url, 400); + last = m.index + url.length; + } + return out + escapePlain(t.slice(last)); +} +const escapePlain = (t) => t.replace(/ 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; + } + if (lineStart) { + const open = line.match(/^ {0,3}(`{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. +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"); + 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].sort((a, b) => b.length - a.length); +} + +export function redactSecrets(text, secrets = []) { + let out = String(text ?? ""); + const usable = secrets.filter((s) => typeof s === "string" && s.length >= MIN_SECRET); + for (const s of usable) { + for (const f of formsOf(s)) { + if (f && out.includes(f)) out = out.split(f).join("[REDACTED]"); + } + } + return out; +} + +export const defaultSecrets = () => + [process.env.CR_REDACT_API_KEY, process.env.CR_REDACT_GITHUB_TOKEN].filter(Boolean); + +// 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 (args, ...rest) => v.call(target, redactArgs(args, secrets), ...rest); + } + 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..366b9b5 --- /dev/null +++ b/scripts/publish-guard.test.mjs @@ -0,0 +1,214 @@ +// 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 '; const footer = @@ -597,9 +681,12 @@ runs: const body = `${MARKER}\n## 🐳 ${brand}\n\n` + `⏸️ **Automatic review is off for this PR** (${guard.sanitizeUntrusted(process.env.REASON, { atLineStart: false, maxChars: 300 })}).\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 ` + + (pass + ? `The check **passes** (\`on-skipped-review: "pass"\`), so this skip does not block your merge. ` + : `The check **fails** (\`on-skipped-review: "fail"\`, the default): this PR has not been ` + + `reviewed, so it cannot satisfy a required merge gate. `) + + `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; @@ -615,10 +702,18 @@ runs: } await core.summary.addRaw(`skipped: ${process.env.REASON}`).write(); - core.notice(`${brand}: review skipped — ${process.env.REASON}`); + if (pass) { + core.notice(`${brand}: review skipped — ${process.env.REASON}`); + } else { + core.setFailed( + `${brand}: review skipped — ${process.env.REASON}. Failing the check so an unreviewed PR cannot ` + + `pass a required merge gate: a maintainer can comment /orcacode-review, or set ` + + `on-skipped-review: "pass" to make skips advisory.`, + ); + } - uses: actions/checkout@v4 - if: steps.settings.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' with: fetch-depth: 0 # full history for the merge-base diff ref: ${{ steps.pr.outputs.head_sha }} @@ -628,7 +723,7 @@ 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 }} @@ -654,7 +749,7 @@ runs: # changed files the engine will skip, for the summary. - name: Harden the checkout id: harden - if: steps.settings.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' shell: bash env: HARDEN: ${{ github.action_path }}/scripts/harden-checkout.mjs @@ -668,7 +763,7 @@ runs: - name: Oversized-diff guard id: guard - if: steps.settings.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' shell: bash env: BRAND: ${{ inputs.brand }} @@ -781,7 +876,7 @@ runs: } - 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 }} @@ -798,7 +893,7 @@ runs: # 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 != 'skip' && steps.guard.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' shell: bash env: ORCAROUTER_API_KEY: ${{ inputs.orcarouter-api-key }} @@ -810,7 +905,7 @@ runs: - 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 }} @@ -1317,7 +1412,7 @@ 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' + if: always() && steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' uses: actions/github-script@v7 env: BRAND: ${{ inputs.brand }} @@ -1424,7 +1519,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 @@ -1449,7 +1544,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 }} @@ -1465,7 +1560,7 @@ runs: fi - name: Post review comments - if: steps.settings.outputs.decision != 'skip' && steps.guard.outputs.decision != 'skip' + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' uses: actions/github-script@v7 env: BRAND: ${{ inputs.brand }} @@ -1713,7 +1808,7 @@ 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' + if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' uses: actions/github-script@v7 env: PR_NUMBER: ${{ steps.pr.outputs.number }} @@ -1844,7 +1939,8 @@ runs: } - 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 }} @@ -1883,7 +1979,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 @@ -1910,6 +2006,80 @@ runs: --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@v7 + 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 @@ -1927,7 +2097,7 @@ 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: GH_TOKEN: ${{ inputs.github-token }} diff --git a/scripts/events.test.mjs b/scripts/events.test.mjs new file mode 100644 index 0000000..a316e9c --- /dev/null +++ b/scripts/events.test.mjs @@ -0,0 +1,214 @@ +// 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 } 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: { + get: async () => ({ data: { base: { ref: "main" }, head: { sha: "headsha" }, 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 }); + 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"); + }); +}); + +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: { + 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/review-status.mjs b/scripts/review-status.mjs new file mode 100644 index 0000000..eb8214e --- /dev/null +++ b/scripts/review-status.mjs @@ -0,0 +1,54 @@ +// The commit status the action writes on the PR's head SHA at the end of every +// run — the merge-gate verdict that also reaches the PR from a comment- +// triggered (on-demand) run, whose own job check lands on the default branch. +// +// One pure function, so every ending is decided in one place and tested as a +// table. `success` means exactly one of two things: a review ran on this head +// and the severity gate passed it, or the run was skipped and the workflow made +// that kind of skip advisory on purpose (`on-skipped-review: "pass"`, +// `on-oversized-diff: "pass"`). Everything else — a skip under the default +// "fail", a blocked gate, a gate that could not decide, an engine failure, a +// cancelled run, a run that never reached a decision — is not success. +// +// Inputs are the raw strings the step reads from step outputs/outcomes, so an +// absent value (a step that never ran) is "" and lands on a failing branch. + +const MAX = 140; // GitHub's limit for a status description + +const clip = (s) => (s.length <= MAX ? s : `${s.slice(0, MAX - 1)}…`); + +export function decideStatus({ + decision = "", + reason = "", + guardDecision = "", + guardReason = "", + onSkipped = "", + onOversized = "", + reviewOutcome = "", + enforceOutcome = "", + verdict = "", + blockOn = "", +} = {}) { + const out = (state, description) => ({ state, description: clip(description) }); + + if (decision === "skip") { + return onSkipped === "pass" + ? out("success", `Review skipped (${reason}) — advisory`) + : out("failure", `Review skipped (${reason}) — not reviewed; a maintainer can comment /orcacode-review`); + } + if (decision !== "review") return out("error", "Review did not start"); + + if (guardDecision === "skip") { + return onOversized === "pass" + ? out("success", `Review skipped (${guardReason}) — advisory`) + : out("failure", `Review skipped (${guardReason}) — diff too large to review`); + } + if (guardDecision !== "review") return out("error", "Review did not start (size guard)"); + + if (reviewOutcome !== "success") return out("error", "Review did not complete — see the run"); + if (enforceOutcome === "success" && verdict === "pass") { + return out("success", `Reviewed — no ${blockOn || "blocking"} findings`); + } + if (verdict === "blocked") return out("failure", `Blocked — ${blockOn} finding(s)`); + return out("error", "Review did not complete — see the run"); +} diff --git a/scripts/review-status.test.mjs b/scripts/review-status.test.mjs new file mode 100644 index 0000000..2e16004 --- /dev/null +++ b/scripts/review-status.test.mjs @@ -0,0 +1,207 @@ +// CR-5: a merge gate that passes without a review. +// +// Every settings skip (author allowlist, on-demand mode, auto_review off, a +// draft) used to end the job green — the opposite of the oversized-diff rule, +// where a skip fails the check so an unreviewed diff cannot satisfy a required +// gate. And an on-demand review (an issue_comment run) reported its verdict on +// the DEFAULT BRANCH's check, so a red verdict never blocked the PR. +// +// Now: +// - `on-skipped-review` ("fail" by default, "pass" to make skips advisory) +// decides what a settings skip does to the job, exactly as +// `on-oversized-diff` does for an oversized one; +// - every run that resolves a PR writes a commit status (context +// `status-context`, default "OrcaCode Review") on the PR's HEAD SHA — the +// comment-triggered runs included — and it is `success` only when a review +// actually ran on that head and the gate passed, or when a skip was made +// advisory on purpose. + +import { describe, test } from "node:test"; +import assert from "node:assert/strict"; +import path from "node:path"; + +import { decideStatus } from "./review-status.mjs"; +import { step, loadAction, runGithubScript, fakeCore, ROOT } from "./test-helpers/action-yaml.mjs"; + +const base = { + decision: "review", + reason: "", + guardDecision: "review", + guardReason: "", + onSkipped: "fail", + onOversized: "fail", + reviewOutcome: "success", + enforceOutcome: "success", + verdict: "pass", + blockOn: "P0,P1", +}; + +describe("decideStatus", () => { + test("a review that ran and passed the gate -> success", () => { + assert.equal(decideStatus(base).state, "success"); + }); + + test("a gate that blocked -> failure", () => { + const s = decideStatus({ ...base, enforceOutcome: "failure", verdict: "blocked" }); + assert.equal(s.state, "failure"); + assert.match(s.description, /P0,P1/); + }); + + test("a gate that could not decide -> failure, never success", () => { + assert.notEqual(decideStatus({ ...base, enforceOutcome: "failure", verdict: "error" }).state, "success"); + }); + + for (const outcome of ["failure", "cancelled", "skipped", ""]) { + test(`the review step ${outcome || "never ran"} -> not success`, () => { + const s = decideStatus({ ...base, reviewOutcome: outcome, enforceOutcome: "skipped", verdict: "" }); + assert.ok(["error", "failure"].includes(s.state), s.state); + }); + } + + test("enforce succeeded but its verdict is missing -> not success", () => { + assert.notEqual(decideStatus({ ...base, verdict: "" }).state, "success"); + }); + + test("a settings skip fails by default, naming the reason", () => { + const s = decideStatus({ ...base, decision: "skip", reason: "on-demand mode" }); + assert.equal(s.state, "failure"); + assert.match(s.description, /on-demand mode/); + }); + + test('a settings skip with on-skipped-review: "pass" is advisory success', () => { + assert.equal(decideStatus({ ...base, decision: "skip", reason: "draft PR", onSkipped: "pass" }).state, "success"); + }); + + test("anything but an explicit pass fails a skip (fail-safe)", () => { + assert.equal(decideStatus({ ...base, decision: "skip", reason: "x", onSkipped: "PASS!" }).state, "failure"); + }); + + test("an oversized skip follows on-oversized-diff", () => { + assert.equal(decideStatus({ ...base, guardDecision: "skip", guardReason: "too big" }).state, "failure"); + assert.equal(decideStatus({ ...base, guardDecision: "skip", guardReason: "too big", onOversized: "pass" }).state, "success"); + }); + + test("no decision at all (the settings step never ran) -> error", () => { + assert.equal(decideStatus({ ...base, decision: "" }).state, "error"); + }); + + test("descriptions fit GitHub's 140-character limit", () => { + const s = decideStatus({ ...base, decision: "skip", reason: "x".repeat(500) }); + assert.ok(s.description.length <= 140); + }); +}); + +describe("action.yml: the status is published on the head SHA", () => { + const ENV = { + PUBLISH_GUARD: path.join(ROOT, "scripts", "publish-guard.mjs"), + STATUS_SCRIPT: path.join(ROOT, "scripts", "review-status.mjs"), + STATUS_CONTEXT: "OrcaCode Review", + HEAD_SHA: "headsha123", + DECISION: "review", + REASON: "", + GUARD_DECISION: "review", + GUARD_REASON: "", + ON_SKIPPED: "fail", + ON_OVERSIZED: "fail", + REVIEW_OUTCOME: "success", + ENFORCE_OUTCOME: "failure", + VERDICT: "blocked", + BLOCK_ON: "P0,P1", + GITHUB_SERVER_URL: "https://github.com", + GITHUB_RUN_ID: "99", + }; + + async function publish(env, { fail = null, eventName = "issue_comment" } = {}) { + const calls = []; + const github = { + rest: { + repos: { + createCommitStatus: async (args) => { + calls.push(args); + if (fail) { + const e = new Error("Resource not accessible by integration"); + e.status = fail; + throw e; + } + return { data: {} }; + }, + }, + }, + }; + const { core, rec } = fakeCore(); + await runGithubScript(step("status").with.script, { + github, + core, + context: { eventName, repo: { owner: "acme", repo: "widgets" }, payload: {} }, + env: { ...ENV, ...env }, + }); + return { calls, rec }; + } + + test("an on-demand (comment) run's blocked verdict lands on the PR head as failure", async () => { + const { calls } = await publish({}); + assert.equal(calls.length, 1); + assert.equal(calls[0].sha, "headsha123"); + assert.equal(calls[0].state, "failure"); + assert.equal(calls[0].context, "OrcaCode Review"); + assert.match(calls[0].target_url, /\/acme\/widgets\/actions\/runs\/99$/); + }); + + test("a missing statuses permission is a warning, not a failed run", async () => { + const { rec } = await publish({}, { fail: 403 }); + assert.equal(rec.failed, null); + assert.ok(rec.warnings.some((w) => /statuses: write/.test(w)), rec.warnings.join("\n")); + }); + + test("an empty status-context turns the status off", async () => { + const { calls } = await publish({ STATUS_CONTEXT: "" }); + assert.equal(calls.length, 0); + }); + + test("the step runs on every ending (always()) once the PR was resolved", () => { + const s = step("status"); + assert.match(s.if, /always\(\)/); + assert.match(s.if, /steps\.pr\.outputs\.run == 'true'/); + }); + + test("the inputs exist with fail-safe defaults", () => { + const inputs = loadAction().inputs; + assert.equal(inputs["on-skipped-review"].default, "fail"); + assert.equal(inputs["status-context"].default, "OrcaCode Review"); + }); +}); + +describe("action.yml: a settings skip follows on-skipped-review", () => { + async function skip(onSkipped) { + const { core, rec } = fakeCore(); + const github = { + paginate: async () => [], + rest: { issues: { listComments: () => {}, createComment: async () => ({}), updateComment: async () => ({}) } }, + }; + await runGithubScript(step("Skip review (settings)").with.script, { + github, + core, + context: { repo: { owner: "acme", repo: "widgets" }, payload: {} }, + env: { + BRAND: "OrcaCode Review", + PR_NUMBER: "7", + REASON: "on-demand mode", + ON_SKIPPED: onSkipped, + PUBLISH_GUARD: path.join(ROOT, "scripts", "publish-guard.mjs"), + }, + }); + return rec; + } + + test('default "fail": the job fails, so a required check cannot pass unreviewed', async () => { + assert.ok((await skip("fail")).failed); + }); + + test('"pass": advisory, the job stays green', async () => { + assert.equal((await skip("pass")).failed, null); + }); + + test("anything else fails (fail-safe)", async () => { + assert.ok((await skip("")).failed); + }); +}); diff --git a/scripts/settings.test.mjs b/scripts/settings.test.mjs index 694dcd9..a179229 100644 --- a/scripts/settings.test.mjs +++ b/scripts/settings.test.mjs @@ -575,14 +575,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: { ...process.env, 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("|"); @@ -607,10 +611,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. From b0f2fe5526004ce0addd0be1e7bd81c38b144470 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 04:18:28 +0000 Subject: [PATCH 09/28] fix(workflows): per-job concurrency, re-run on retarget/reopen, statuses: write (CR-6, CR-5) All three workflow copies (workflows/orca-code-review.yml, the skill's assets/workflow.yml, and the installer's renderWorkflow): - CR-6: drop the workflow-level concurrency group. With cancel-in-progress, every comment on the PR started a run in the same group and cancelled the in-flight review before its own job was skipped, so any commenter could cancel reviews. Concurrency is now on the job, with comment runs in a group of their own that never cancels; push runs still supersede each other per PR. - CR-5: pull_request_target also triggers on `reopened` and `edited`; the job's `if:` lets `edited` through only when github.event.changes.base is set, so retargeting a PR re-reviews it against the new base and a title edit does not. - `statuses: write`, so the action can put its verdict on the PR head for comment-triggered runs too. installer.test.mjs compared a top-level `concurrency:` section between the example and the skill template; that block must no longer exist, so the test now compares the parsed on/permissions/job concurrency/job if of all three copies, the installer's included. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- bin/orcacode-review.mjs | 26 ++++++--- scripts/installer.test.mjs | 20 ++++++- scripts/workflows.test.mjs | 58 +++++++++++++++++++ skills/orca-review-action/assets/workflow.yml | 23 +++++--- workflows/orca-code-review.yml | 25 +++++--- 5 files changed, 126 insertions(+), 26 deletions(-) create mode 100644 scripts/workflows.test.mjs diff --git a/bin/orcacode-review.mjs b/bin/orcacode-review.mjs index 605d5b1..67b3362 100755 --- a/bin/orcacode-review.mjs +++ b/bin/orcacode-review.mjs @@ -361,26 +361,33 @@ export function renderWorkflow(overrides) { 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 # the verdict on the PR head — the check to make required 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 anything. + 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 +395,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') || diff --git a/scripts/installer.test.mjs b/scripts/installer.test.mjs index b0b7efa..17b7c9a 100644 --- a/scripts/installer.test.mjs +++ b/scripts/installer.test.mjs @@ -294,7 +294,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 +303,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 diff --git a/scripts/workflows.test.mjs b/scripts/workflows.test.mjs new file mode 100644 index 0000000..041ec6c --- /dev/null +++ b/scripts/workflows.test.mjs @@ -0,0 +1,58 @@ +// 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. + +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/assets/workflow.yml b/skills/orca-review-action/assets/workflow.yml index 2483e51..77fbcc5 100644 --- a/skills/orca-review-action/assets/workflow.yml +++ b/skills/orca-review-action/assets/workflow.yml @@ -7,15 +7,14 @@ 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,19 @@ permissions: contents: read pull-requests: write issues: write # clean/fallback PR comments + statuses: write # the verdict on the PR head — the check to make required 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 anything. + 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 +42,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') || diff --git a/workflows/orca-code-review.yml b/workflows/orca-code-review.yml index 6055c30..2147f3a 100644 --- a/workflows/orca-code-review.yml +++ b/workflows/orca-code-review.yml @@ -10,17 +10,14 @@ 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 +25,19 @@ permissions: contents: read pull-requests: write issues: write # clean/fallback PR comments + statuses: write # the verdict on the PR head — the check to make required 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 anything. + 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 +48,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') || From 97a9e534283a1a45a2f7b6f84b38784839596ff9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 04:19:47 +0000 Subject: [PATCH 10/28] fix(action): only the action's own comments count as its marker comments (CR-15) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The upserts and the stale-notice sweep found the action's comments by an HTML marker () in ANY comment, so anyone able to comment on the PR could plant a marker and get the action to edit or delete their comment, or keep a real notice stale. "Resolve PR refs" resolves the token's identity once (the user of a personal token via users.getAuthenticated; github-actions[bot] for the default GITHUB_TOKEN, where that call is refused) and outputs bot_login. Every marker lookup — the settings-skip and oversized notices, the guardrail notice, and the summary step's sweep — now matches only comments authored by that login; with no login nothing matches (post anew, edit and delete nothing). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- action.yml | 50 ++++++++- scripts/marker-ownership.test.mjs | 163 ++++++++++++++++++++++++++++++ 2 files changed, 209 insertions(+), 4 deletions(-) create mode 100644 scripts/marker-ownership.test.mjs diff --git a/action.yml b/action.yml index 169d8c3..e13aca2 100644 --- a/action.yml +++ b/action.yml @@ -337,6 +337,20 @@ runs: authorAssoc = pr.author_association || 'NONE'; } core.setOutput('run', 'true'); + // WHO THE ACTION POSTS AS, resolved once. The marker lookups below + // () only count a comment this identity + // wrote — otherwise anyone could plant a marker and have the action + // edit or delete THEIR comment. A personal token names its user; the + // default GITHUB_TOKEN has no user (the call is refused) and posts as + // github-actions[bot]. + let botLogin = 'github-actions[bot]'; + try { + const { data: me } = await github.rest.users.getAuthenticated(); + if (me && me.login) botLogin = me.login; + } catch (e) { + // An installation token: keep github-actions[bot]. + } + core.setOutput('bot_login', botLogin); core.setOutput('base', base); core.setOutput('head_sha', headSha); core.setOutput('number', String(num)); @@ -651,6 +665,8 @@ runs: if: steps.settings.outputs.decision == 'skip' uses: actions/github-script@v7 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 }} @@ -668,6 +684,11 @@ runs: // 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. + // With no resolved identity nothing matches: post anew, edit nothing. + const mine = (c) => + Boolean(process.env.BOT_LOGIN) && Boolean(c && c.body) && + Boolean(c.user) && c.user.login === process.env.BOT_LOGIN; const brand = process.env.BRAND; const num = Number(process.env.PR_NUMBER); const repo = { owner: context.repo.owner, repo: context.repo.repo }; @@ -693,7 +714,7 @@ 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 gh.rest.issues.createComment({ ...repo, issue_number: num, body }); } else if (existing.body !== body) { @@ -804,6 +825,8 @@ runs: if: steps.guard.outputs.decision == 'skip' uses: actions/github-script@v7 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 }} @@ -825,6 +848,11 @@ runs: // 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. + // With no resolved identity nothing matches: post anew, edit nothing. + const mine = (c) => + Boolean(process.env.BOT_LOGIN) && Boolean(c && c.body) && + Boolean(c.user) && c.user.login === process.env.BOT_LOGIN; const brand = process.env.BRAND; const num = Number(process.env.PR_NUMBER); const repo = { owner: context.repo.owner, repo: context.repo.repo }; @@ -857,7 +885,7 @@ 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 gh.rest.issues.updateComment({ ...repo, comment_id: existing.id, body }); } else { @@ -1415,6 +1443,8 @@ runs: if: always() && steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' uses: actions/github-script@v7 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 @@ -1433,6 +1463,11 @@ runs: // 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. + // With no resolved identity nothing matches: post anew, edit nothing. + const mine = (c) => + Boolean(process.env.BOT_LOGIN) && Boolean(c && c.body) && + Boolean(c.user) && c.user.login === process.env.BOT_LOGIN; const fs = require('fs'); let block; try { @@ -1491,7 +1526,7 @@ 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 gh.rest.issues.createComment({ ...repo, issue_number: num, body }); } else if (existing.body !== body) { @@ -1811,6 +1846,8 @@ runs: if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' uses: actions/github-script@v7 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. # @@ -1847,6 +1884,11 @@ runs: // 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. + // With no resolved identity nothing matches: post anew, edit nothing. + const mine = (c) => + Boolean(process.env.BOT_LOGIN) && Boolean(c && c.body) && + Boolean(c.user) && c.user.login === process.env.BOT_LOGIN; const fs = require('fs'); const { execFileSync } = require('child_process'); const { pathToFileURL } = require('url'); @@ -1867,7 +1909,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 }); diff --git a/scripts/marker-ownership.test.mjs b/scripts/marker-ownership.test.mjs new file mode 100644 index 0000000..ed1b258 --- /dev/null +++ b/scripts/marker-ownership.test.mjs @@ -0,0 +1,163 @@ +// 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, resolved once +// by "Resolve PR refs" (github-actions[bot] for the default GITHUB_TOKEN). + +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, 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) { + 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 }); + return rec.outputs.bot_login; + } + + test("the default GITHUB_TOKEN (no user behind it) is github-actions[bot]", async () => { + const login = await resolveWith(async () => { + const e = new Error("Resource not accessible by integration"); + e.status = 403; + throw e; + }); + assert.equal(login, BOT); + }); + + test("a personal token is its user's login", async () => { + assert.equal(await resolveWith(async () => ({ data: { login: "octo-maintainer" } })), "octo-maintainer"); + }); +}); From 93a84b8627df248f75d5366de31de9ddee51c2d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 04:23:00 +0000 Subject: [PATCH 11/28] fix(supply-chain): install the engine from pinned, verified bytes; SHA-pin every action (CR-9) `npm install -g "@alibaba-group/open-code-review@${ENGINE_VERSION}"` pinned only the top-level version, ran the package's postinstall (which downloads the ~40 MB Go engine binary and checks it against a checksum file fetched from the same release, i.e. no independent pin) and checked no integrity. The composite's own steps used tags (github-script@v7, setup-node@v4, checkout@v4). - New scripts/engine-pins.json pins, per engine version, the npm tarball's sha512 SRI and each platform binary's URL and sha256. 1.3.13: integrity from `npm view ... dist.integrity`, re-computed locally from the packed tarball; linux-x64/arm64 sha256 computed from the downloaded release assets (they match the release's sha256sum.txt); darwin values from that sha256sum.txt. - New scripts/install-engine.mjs: refuses an unpinned version or platform; `npm pack --ignore-scripts`, verifies the tarball's sha512 before use; downloads the binary with curl (https-only, redirects included) and verifies its sha256; installs the verified tarball with `npm install -g --ignore-scripts --offline` into $RUNNER_TEMP/ocr-engine and places the binary beside the wrapper. Any failure exits 1 and removes the prefix. The install step puts /bin on GITHUB_PATH. - Every `uses:` in action.yml and .github/workflows is pinned to the commit its current major tag points at, with a `# vX.Y.Z` comment: github-script f28e40c7 (v7.1.0), setup-node 49933ea5 (v4.4.0), checkout 11d5960a (v4.4.0). Behaviour change: an engine-version without pins now fails the run. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- .github/workflows/deprecate.yml | 4 +- .github/workflows/publish.yml | 4 +- .github/workflows/self-review.yml | 2 +- .github/workflows/test.yml | 4 +- action.yml | 41 ++++-- scripts/engine-pins.json | 23 ++++ scripts/install-engine.mjs | 158 +++++++++++++++++++++++ scripts/install-engine.test.mjs | 200 ++++++++++++++++++++++++++++++ 8 files changed, 418 insertions(+), 18 deletions(-) create mode 100644 scripts/engine-pins.json create mode 100644 scripts/install-engine.mjs create mode 100644 scripts/install-engine.test.mjs 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 5a93a91..878d23f 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -42,11 +42,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 - - 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/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 21f77d6..51bd75f 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -29,9 +29,9 @@ 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 }} diff --git a/action.yml b/action.yml index e13aca2..65f4a85 100644 --- a/action.yml +++ b/action.yml @@ -168,7 +168,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: @@ -277,6 +282,7 @@ runs: "$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. @@ -292,7 +298,7 @@ runs: # 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 with: github-token: ${{ inputs.github-token }} script: | @@ -449,7 +455,7 @@ 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" @@ -663,7 +669,7 @@ runs: # diff). "pass" makes skips advisory. - 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 }} @@ -733,7 +739,7 @@ runs: ); } - - uses: actions/checkout@v4 + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 if: steps.settings.outputs.decision == 'review' with: fetch-depth: 0 # full history for the merge-base diff @@ -823,7 +829,7 @@ 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 }} @@ -903,12 +909,24 @@ 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 == '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 @@ -1441,7 +1459,7 @@ runs: # skipped run (the review step's own cleanup never ran on a skip). - name: Surface guardrail / firewall block if: always() && steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' - 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 }} @@ -1596,7 +1614,7 @@ runs: - name: Post review comments if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 env: BRAND: ${{ inputs.brand }} PR_NUMBER: ${{ steps.pr.outputs.number }} @@ -1844,7 +1862,7 @@ runs: # Runs BEFORE the enforce step so a blocked run still updates the summary. - name: Summary (PR description) if: steps.settings.outputs.decision == 'review' && steps.guard.outputs.decision == 'review' - 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 }} @@ -2059,7 +2077,7 @@ runs: - name: Publish the review status id: status if: always() && steps.pr.outputs.run == 'true' - uses: actions/github-script@v7 + uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 env: STATUS_SCRIPT: ${{ github.action_path }}/scripts/review-status.mjs STATUS_CONTEXT: ${{ inputs.status-context }} @@ -2266,3 +2284,4 @@ runs: "$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/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/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`); + } + }); + } +}); From 248d968a198c587c16c5d7bcb53362a5745a1fc2 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 04:26:25 +0000 Subject: [PATCH 12/28] fix(release): pin the action to a release commit everywhere; never move a version tag (CR-3, CR-12) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit RELEASE.md told maintainers to force-move v1 and to re-tag "immutable" v1. tags with a force push, and the installer, the example workflow, the skill's asset and the README all pinned @v1 — so whoever could move the tag decided what ran, with the customer's key, in every repository that pinned it. The README quickstart also showed a bare `uses:` step with no comment gate (CR-12). - bin/orcacode-review.mjs exports ACTION_SHA / ACTION_VERSION (the v1.6.0 release commit this branch builds on, 6d253e03) and renders `uses: Continuum-AI-Corp/orca-code-review@ # v1.6.0`; the example, the skill asset and the README quickstart carry the same line, held together by scripts/release-pin.test.mjs (comments read through the YAML document model). Customers' Dependabot reads the comment and offers new releases as PRs. - The README quickstart is now the complete gated workflow (triggers, permissions incl. statuses: write, job-level concurrency, the maintainer-only comment `if:`), and "Block merges" names the "OrcaCode Review" commit status as the check to require. - RELEASE.md: a release is a new annotated v1..

tag pushed once and never moved; the pins are bumped in a follow-up PR; `v1` is legacy and only advanced to an already-released descendant by an admin through a ruleset bypass; documents the tag ruleset and immutable releases as one-time administrator settings. - publish.yml's gate verifies the installer's pinned commit exists, is the commit tagged ACTION_VERSION, and ships settings.mjs/report.mjs, instead of inspecting the v1 tag. - .github/dependabot.yml: weekly github-actions updates for this repo's own pinned actions. installer.test.mjs pinned the module's export list; it now includes ACTION_SHA and ACTION_VERSION. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- .github/dependabot.yml | 14 +++ .github/workflows/publish.yml | 35 +++--- README.md | 45 ++++++- RELEASE.md | 115 +++++++++++------- bin/orcacode-review.mjs | 17 ++- scripts/installer.test.mjs | 4 +- scripts/release-pin.test.mjs | 95 +++++++++++++++ skills/orca-review-action/assets/workflow.yml | 6 +- workflows/orca-code-review.yml | 12 +- 9 files changed, 270 insertions(+), 73 deletions(-) create mode 100644 .github/dependabot.yml create mode 100644 scripts/release-pin.test.mjs 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/publish.yml b/.github/workflows/publish.yml index 878d23f..23f291b 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 @@ -90,25 +89,33 @@ 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' diff --git a/README.md b/README.md index 12b5de3..2582bab 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 # the verdict on the PR head — the check to make required + +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). @@ -226,7 +259,9 @@ 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 **`OrcaCode Review`** status as required. The action writes it on the PR's head commit at the end of every run, and it is green only when a review actually ran on that commit and the gate passed. It is also 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. (Requiring the **`review`** job check still works for push-triggered runs, but then an on-demand review can never turn a skipped PR green.) + +A PR the action did **not** review never passes: a skipped review (on-demand mode, auto-review off, a draft, an author outside `auto-review-authors`) and an oversized diff both fail the check by default — set `on-skipped-review: "pass"` / `on-oversized-diff: "pass"` to make them advisory. --- diff --git a/RELEASE.md b/RELEASE.md index 77f046f..d66e3ba 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,51 +1,85 @@ # 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 are never moved + +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 — with +`git tag -f` and a force push — is therefore a way to run new code in every +customer's CI without a single customer-side change. So: + +- **A release is a new tag on a merged commit of `main`: `v1..`.** + It is 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. +- **What we hand out pins the commit, not a tag.** 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 + all read `uses: Continuum-AI-Corp/orca-code-review@ # v1..

`. + `scripts/release-pin.test.mjs` holds all four to the installer's constants, + so a release that bumps one bumps all of them. Customers' Dependabot + (`package-ecosystem: github-actions`) reads the `# v1.x.y` comment and offers + each new release as a pull request that changes the SHA and the comment + together. +- **The `v1` major tag is legacy.** Workflows written before commit pinning + reference `@v1`, and only for them is it still advanced: only ever to a + descendant of its current commit that already carries an immutable + `v1..

` release tag, by an administrator through the ruleset bypass + below. It is the one tag update left that needs force, and it exists only so + those workflows still receive fixes. Nothing this repository generates or + documents references `@v1` any more; tell anyone still on it to pin a SHA. + +### 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. In a follow-up PR, bump `ACTION_SHA` and `ACTION_VERSION` in + `bin/orcacode-review.mjs` to that commit and tag, and the same `uses:` line in + `workflows/orca-code-review.yml`, `skills/orca-review-action/assets/workflow.yml` + and the README quickstart. The test suite fails until all four agree. Bump + `package.json` in the same PR when the installer should ship it (see + Installers below). +4. Only if legacy `@v1` users should get this release: an administrator advances + `v1` to the same commit (a descendant of its current one, through the ruleset + bypass). +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 the legacy fast-forward + in step 4. +- **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 +167,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 +236,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/bin/orcacode-review.mjs b/bin/orcacode-review.mjs index 67b3362..cffce44 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. @@ -355,8 +363,9 @@ 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 @@ -405,7 +414,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} `; diff --git a/scripts/installer.test.mjs b/scripts/installer.test.mjs index 17b7c9a..b15b5a3 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,parseOverrides,readOverrides,renderWorkflow"); }); test("the published version matches package.json", () => { diff --git a/scripts/release-pin.test.mjs b/scripts/release-pin.test.mjs new file mode 100644 index 0000000..64d945d --- /dev/null +++ b/scripts/release-pin.test.mjs @@ -0,0 +1,95 @@ +// CR-3 (repo side) and the README quickstart (CR-12). +// +// Every workflow this repository hands a customer — the installer's rendered +// one, the example, the skill's asset and the README quickstart — used to pin +// `Continuum-AI-Corp/orca-code-review@v1`, a tag RELEASE.md told maintainers to +// force-move (and to force-push "immutable" v1. tags). Whoever can move a tag +// decides what runs, with the customer's OrcaRouter key, in every repository +// that pins it. They now pin one full commit SHA with a `# v1.x.y` comment +// (bumped deliberately at release time), all four the same; the quickstart is a +// complete workflow with the maintainer gate, not a bare `uses:`; and +// RELEASE.md never moves or force-pushes a version tag. +// +// Comments are read through the YAML parser's document model. + +import { describe, test } from "node:test"; +import assert from "node:assert/strict"; +import YAML from "yaml"; + +import { readText, ROOT } from "./test-helpers/action-yaml.mjs"; + +const { ACTION_SHA, ACTION_VERSION, renderWorkflow, DEFAULTS } = await import(`${ROOT}/bin/orcacode-review.mjs`); + +// The `uses:` scalar nodes of a YAML document, comments attached. +function usesOf(text) { + const doc = YAML.parseDocument(text); + 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 { doc: doc.toJS(), uses: out }; +} + +// The README's quickstart is the ```yaml block that names this action. +function readmeQuickstart() { + const readme = readText("README.md"); + const blocks = [...readme.matchAll(/```ya?ml\n([\s\S]*?)```/g)].map((m) => m[1]); + const block = blocks.find((b) => b.includes("Continuum-AI-Corp/orca-code-review@")); + assert.ok(block, "the README has no yaml block using the action"); + return block; +} + +describe("the action is pinned to one commit everywhere it is handed out", () => { + test("the installer exports a full SHA and its release version", () => { + assert.match(ACTION_SHA, /^[0-9a-f]{40}$/); + assert.match(ACTION_VERSION, /^v1\.\d+\.\d+$/); + }); + + const copies = () => [ + ["installer", renderWorkflow({ ...DEFAULTS })], + ["workflows/orca-code-review.yml", readText("workflows/orca-code-review.yml")], + ["skill asset", readText("skills/orca-review-action/assets/workflow.yml")], + ["README quickstart", readmeQuickstart()], + ]; + + for (const [name] of [["installer"], ["workflows/orca-code-review.yml"], ["skill asset"], ["README quickstart"]]) { + test(`${name}: uses @ # ${""}`, () => { + const text = copies().find(([n]) => n === name)[1]; + const own = usesOf(text).uses.filter((u) => String(u.value).startsWith("Continuum-AI-Corp/orca-code-review@")); + assert.equal(own.length, 1, `${name}: expected one use of the action`); + assert.equal(own[0].value, `Continuum-AI-Corp/orca-code-review@${ACTION_SHA}`); + assert.equal(String(own[0].comment || "").trim(), ACTION_VERSION); + }); + } +}); + +describe("the README quickstart is a complete, gated workflow (CR-12)", () => { + test("it parses as a workflow whose comment trigger is limited to maintainers", () => { + const { doc } = usesOf(readmeQuickstart()); + assert.ok(doc.on?.pull_request_target, "the quickstart must be a whole workflow, not a bare step"); + assert.match(doc.jobs.review.if, /\["OWNER", "MEMBER", "COLLABORATOR"\]/); + assert.equal(doc.permissions.statuses, "write"); + assert.ok(doc.jobs.review.concurrency, "job-level concurrency (CR-6)"); + assert.equal(doc.concurrency, undefined); + }); +}); + +describe("release hygiene", () => { + test("Dependabot keeps the pinned actions current", () => { + const cfg = YAML.parse(readText(".github/dependabot.yml")); + const gha = cfg.updates.find((u) => u["package-ecosystem"] === "github-actions"); + assert.ok(gha, "no github-actions entry"); + assert.equal(gha.directory, "/"); + }); + + test("RELEASE.md never moves or force-pushes a version tag", () => { + const md = readText("RELEASE.md"); + const code = [...md.matchAll(/```[\w-]*\n([\s\S]*?)```/g)].map((m) => m[1]).join("\n"); + assert.doesNotMatch(code, /git tag (-f|--force)/, "a release step re-points a tag"); + assert.doesNotMatch(code, /git push[^\n]*(--force|-f\b)/, "a release step force-pushes"); + assert.match(md, /immutable/i, "the immutable-release setting is documented"); + assert.match(md, /ruleset/i, "the tag ruleset is documented"); + }); +}); diff --git a/skills/orca-review-action/assets/workflow.yml b/skills/orca-review-action/assets/workflow.yml index 77fbcc5..8a7c9dd 100644 --- a/skills/orca-review-action/assets/workflow.yml +++ b/skills/orca-review-action/assets/workflow.yml @@ -1,13 +1,13 @@ # 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 - on: # `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 @@ -52,7 +52,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/workflows/orca-code-review.yml b/workflows/orca-code-review.yml index 2147f3a..431ea10 100644 --- a/workflows/orca-code-review.yml +++ b/workflows/orca-code-review.yml @@ -2,15 +2,17 @@ # # 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 "OrcaCode Review" commit +# status required in branch protection — it is the one verdict an on-demand +# /orcacode-review run can also update on the PR head. name: OrcaCode Review - on: # `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 @@ -58,7 +60,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: From 5d0540c1f98d22fb6ad78dbf3abfb92d7450b8c0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 04:27:54 +0000 Subject: [PATCH 13/28] fix(installer): "Everyone" writes auto-review-authors: "*" (CR-2) With unset auto-review-authors now meaning OWNER,MEMBER,COLLABORATOR on a public repository, the installer's public-repo "Everyone" answer (value "") equalled the default, was omitted from the generated workflow, and would silently have meant maintainers only. It now writes the explicit "*" opt-out. The answers move into an exported authorChoices() so a test can hold them; the module's export-list test gains it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- bin/orcacode-review.mjs | 29 +++++++++++++++++------------ scripts/installer.test.mjs | 19 ++++++++++++++++++- 2 files changed, 35 insertions(+), 13 deletions(-) diff --git a/bin/orcacode-review.mjs b/bin/orcacode-review.mjs index cffce44..0a8d618 100755 --- a/bin/orcacode-review.mjs +++ b/bin/orcacode-review.mjs @@ -350,6 +350,22 @@ const INPUT_NOTES = { "auto-review-authors": "author allowlist for AUTOMATIC reviews", }; +// The answers to "who gets an automatic review?" on a public repository. The +// action reads an UNSET auto-review-authors there as OWNER,MEMBER,COLLABORATOR, +// so "Everyone" has to be written as the explicit opt-out "*" — written as "" +// it would equal the default, be omitted, and mean maintainers only. +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: "*", detail: t("config.authorsAllDetail") }, + ]; +} + export function renderWorkflow(overrides) { const lines = Object.entries(overrides) .filter(([k, v]) => v !== undefined && v !== DEFAULTS[k]) @@ -473,18 +489,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/scripts/installer.test.mjs b/scripts/installer.test.mjs index b15b5a3..701325b 100644 --- a/scripts/installer.test.mjs +++ b/scripts/installer.test.mjs @@ -67,7 +67,7 @@ test("importing the CLI runs nothing", () => { assert.equal(r.status, 0, r.stderr); // 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,parseOverrides,readOverrides,renderWorkflow"); + assert.equal(r.stdout.trim(), "ACTION_SHA,ACTION_VERSION,DEFAULTS,authorChoices,parseOverrides,readOverrides,renderWorkflow"); }); test("the published version matches package.json", () => { @@ -460,3 +460,20 @@ 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 --- + +// The action now reads an UNSET auto-review-authors as OWNER,MEMBER,COLLABORATOR +// on a public repository, so the installer's "Everyone" answer can no longer be +// written as the default (an omitted input): it must write the explicit opt-out. +test('the public-repo "Everyone" answer writes the explicit "*" opt-out, not the default', async () => { + const { authorChoices } = await import(CLI); + const choices = authorChoices((k) => k); + const everyone = choices.find((c) => c.label === "config.authorsAll"); + assert.equal(everyone.value, "*"); + const yaml = renderWorkflow({ ...DEFAULTS, "auto-review-authors": everyone.value }); + assert.match(yaml, /^\s+auto-review-authors: "\*"/m); + assert.equal(parseOverrides(yaml)["auto-review-authors"], "*"); + const known = choices.find((c) => c.recommended); + assert.notEqual(known.value, "", "the recommended answer must be written, not left to a default"); +}); From 04814f09ec2e2bf4e5d3a301939ab36f884d47f0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 04:30:47 +0000 Subject: [PATCH 14/28] docs: make SECURITY.md, README and the skill match the hardened behaviour (CR-20) SECURITY.md overstated engine pinning (only the top-level npm version was pinned), claimed the key "never appears in comments" with nothing enforcing it, and did not say the action rewrites the PR description. It now describes the code as it is after this series: the checkout hardening, the engine holding no credential and the proxy injecting the key, the pinned origin, the posting funnel (sanitising + redaction), the generic guardrail notice on public repos, who can make the action spend (public-repo author default, the action's own comment check, per-job concurrency), the fail-closed merge gate and the status to require, the verified engine install and SHA pins, the release-tag policy and the administrator settings it depends on, and the residual self-hosted risk. README: the "Block merges" section (in the release-pin commit) names the OrcaCode Review status; a new "Upgrading: behaviour changes" table lists every change a customer will notice and how to keep the old behaviour where that is safe; "Re-run a review" says only maintainers can. Skill references (inputs.md, troubleshooting.md, SKILL.md): new inputs on-skipped-review and status-context, the visibility-dependent auto-review-authors default and the "*" opt-out, the required status instead of the `review` job, pinned release commits instead of @v1, and the two new symptoms (red check on a skip, ignored command). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- README.md | 27 +- SECURITY.md | 231 ++++++++++++------ action.yml | 12 +- skills/orca-review-action/SKILL.md | 28 ++- .../orca-review-action/references/inputs.md | 16 +- .../references/troubleshooting.md | 34 ++- 6 files changed, 254 insertions(+), 94 deletions(-) diff --git a/README.md b/README.md index 2582bab..ba29f63 100644 --- a/README.md +++ b/README.md @@ -249,7 +249,7 @@ Comment on any PR: /orcacode-review ``` -to request another review. +to request another review. Only an **owner, member or collaborator** can: the action ignores the command from anyone else, whatever the workflow says. The verdict lands on the PR's head commit as the `OrcaCode Review` status. --- @@ -265,9 +265,32 @@ A PR the action did **not** review never passes: a skipped review (on-demand mod --- +## Upgrading: behaviour changes in this release + +Security hardening that changes what you may see. Inputs are unchanged except for two 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: "*"` | +| New `on-skipped-review` (default `"fail"`) | A skipped review (on-demand mode, auto-review off, a draft, an author outside the allowlist) **fails** the check instead of passing | `on-skipped-review: "pass"` | +| New `status-context` (default `"OrcaCode Review"`) | A commit status on the PR head after every run, on-demand runs included. Grant `statuses: write`; require this status instead of the `review` job | `status-context: ""` | +| 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 | — | +| Settings outage with `block-on` left at its default | That run blocks on **every** severity (an outage never loosens the gate) | Set `block-on` explicitly | +| 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 is refused (loopback excepted) | — | +| 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 | — | +| 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 review), 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, and the review engine never holds your API key** — an in-job proxy adds it on the way to OrcaRouter. 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/SECURITY.md b/SECURITY.md index 94e7903..327d8da 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -2,61 +2,154 @@ ## Threat model -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.** +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; +- **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), 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. + +- **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. +- **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. +- **Cancelling**: concurrency is per job in the shipped workflows, and comment + runs have their own group that never cancels, so a comment cannot cancel an + in-flight review. +- **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 a 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`) fails the check unless + `on-skipped-review: "pass"`; an **oversized** diff fails it unless + `on-oversized-diff: "pass"`. +- If the gate cannot read the result (or crashes), the check fails. +- If the dashboard settings cannot be read and the workflow leaves `block-on` + at its default, that run blocks on every severity: an outage can tighten the + gate, never loosen it. An explicit `block-on` in the workflow is used as is. +- 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 for a loopback host). + Absolute-form, scheme-relative and backslash request targets are refused. +- **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, and as the Basic-auth value. +- 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 +157,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 65f4a85..9b8a95c 100644 --- a/action.yml +++ b/action.yml @@ -29,6 +29,16 @@ # 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): a comment trigger runs only for +# a maintainer's review command, checked here and not only in the workflow; 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 — a skip fails per `on-skipped-review`, 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). name: "OrcaCode Review" description: "AI code review for every pull request, powered by OrcaRouter" @@ -47,7 +57,7 @@ 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 }} brand: diff --git a/skills/orca-review-action/SKILL.md b/skills/orca-review-action/SKILL.md index d02f671..0ec49bf 100644 --- a/skills/orca-review-action/SKILL.md +++ b/skills/orca-review-action/SKILL.md @@ -80,7 +80,8 @@ 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* → `"*"`. (Leaving the input out means `OWNER,MEMBER,COLLABORATOR` on a + public repo, so "everyone" has to be written explicitly.) 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 +161,18 @@ 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: +**`OrcaCode Review`** status, or offer to do it: ```bash gh api -X PATCH repos///branches//protection/required_status_checks \ - -f 'checks[][context]=review' + -f 'checks[][context]=OrcaCode Review' ``` +Require the status, not the `review` job: the action writes it on the PR head after +every run, and 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). A skipped or +oversized review leaves it failing by default, 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 @@ -226,15 +232,18 @@ gh run view --log-failed `references/troubleshooting.md` maps each symptom to its cause and fix. The four 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. +- **Red check, "review skipped" notice** — the PR is a draft and `trigger` is + `ready_for_review`, the author is outside `auto-review-authors` (unset means + maintainers only on a public repo), or the app is off in the dashboard. Skips fail by + default (`on-skipped-review`); a maintainer's `/orcacode-review` reviews the head. - **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,7 +251,8 @@ 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 +1. **Drop the required check** — remove `OrcaCode Review` (and `review`, on older + installs) 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. diff --git a/skills/orca-review-action/references/inputs.md b/skills/orca-review-action/references/inputs.md index fb52b59..8f4fd2c 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,11 @@ 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. | +| `orcarouter-url` | `https://api.orcarouter.ai/v1/chat/completions` | Chat-completions endpoint. Change only for a self-hosted gateway. Must be https. | | `github-token` | `${{ github.token }}` | Fetches the PR head, posts review comments, and reacts to a `/orcacode-review` command. | | `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. Only versions whose checksums this action release pins (`scripts/engine-pins.json`) install — any other value fails the run. | ## Severity and merge gate @@ -39,12 +40,15 @@ 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: `OWNER,MEMBER,COLLABORATOR` on a public repo, everyone on a private one | Author-association allowlist for **automatic** reviews. `"*"` reviews everyone on any repo. Others can still be reviewed on demand via `/orcacode-review`. Values: `OWNER`, `MEMBER`, `COLLABORATOR`, `CONTRIBUTOR`, `FIRST_TIME_CONTRIBUTOR`, `FIRST_TIMER`, `MANNEQUIN`, `NONE`, `*`. | +| `on-skipped-review` | `fail` | What a settings skip (auto-review off, on-demand mode, a draft, an author outside the allowlist) does to the check. `fail` keeps an unreviewed PR from passing a required gate; `pass` makes skips advisory. | +| `status-context` | `OrcaCode Review` | 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. 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 — which is why an unset allowlist means maintainers only there. Put +a budget + alert on the key either way. The `/orcacode-review` command is honoured +only from `OWNER`, `MEMBER` or `COLLABORATOR`, by the action itself. ## Oversized-diff guard diff --git a/skills/orca-review-action/references/troubleshooting.md b/skills/orca-review-action/references/troubleshooting.md index e915dc8..9938697 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`, plus `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,20 @@ 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 + +Expected when a review is skipped: on-demand mode, auto-review off in the +dashboard, a draft under `ready_for_review`, an author outside +`auto-review-authors` (on a public repo an unset allowlist means +`OWNER,MEMBER,COLLABORATOR`), or an oversized diff. An unreviewed PR fails by +default so it cannot pass a required gate. A maintainer's `/orcacode-review` +reviews the head and its verdict replaces the `OrcaCode Review` status — which is +why that status, not the `review` job, should be the required check. To make skips +advisory instead: `on-skipped-review: "pass"` / `on-oversized-diff: "pass"`. + +## `/orcacode-review` did nothing + +The action honours the command only on a pull request, only as the start of the +comment, and only from `OWNER`, `MEMBER` or `COLLABORATOR`. Anyone else's command +is a logged no-op. From e059b2983aedfd083c3379ba509c92b2472843e6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 06:25:53 +0000 Subject: [PATCH 15/28] test(helpers): run action steps from an environment without the runner's own variables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit runBashStep / runBashStepAsync started each step from ...process.env and runGithubScript ran with process.env as it was, so on a CI runner a step under test wrote its outputs into the TEST job's GITHUB_OUTPUT / GITHUB_ENV / GITHUB_PATH / step summary, wrote into its RUNNER_TEMP, and read GITHUB_EVENT_NAME=push from the test workflow. Every helper now starts from cleanEnv() — process.env minus GITHUB_*, RUNNER_*, ACTIONS_* — and a test passes what it means explicitly; runGithubScript removes them for the script's duration and restores them after. The two suites that run fragments of step bodies directly use cleanEnv() too. scripts/test-isolation.test.mjs plants a parent GITHUB_OUTPUT (and the other workflow-command files, RUNNER_TEMP and event/identity variables) and proves no step output or file reaches them. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- scripts/exhaustive-merge.test.mjs | 4 +- scripts/settings.test.mjs | 4 +- scripts/test-helpers/action-yaml.mjs | 25 ++++-- scripts/test-isolation.test.mjs | 114 +++++++++++++++++++++++++++ 4 files changed, 140 insertions(+), 7 deletions(-) create mode 100644 scripts/test-isolation.test.mjs diff --git a/scripts/exhaustive-merge.test.mjs b/scripts/exhaustive-merge.test.mjs index ec479f8..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; @@ -240,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/settings.test.mjs b/scripts/settings.test.mjs index a179229..a54b9e8 100644 --- a/scripts/settings.test.mjs +++ b/scripts/settings.test.mjs @@ -25,6 +25,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"); @@ -586,7 +588,7 @@ describe("action.yml: gate_decision — shared auto-event gate (both settings pa `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, REPO_PRIVATE: isPrivate }, + 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("|"); diff --git a/scripts/test-helpers/action-yaml.mjs b/scripts/test-helpers/action-yaml.mjs index 07dc58e..baf41fa 100644 --- a/scripts/test-helpers/action-yaml.mjs +++ b/scripts/test-helpers/action-yaml.mjs @@ -63,6 +63,17 @@ export function shellCommentLines(script) { .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. @@ -75,7 +86,7 @@ export function runBashStep(script, { env = {}, stubDir = null, cwd = undefined return spawnSync("bash", ["--noprofile", "--norc", "-eo", "pipefail", file], { cwd, encoding: "utf8", - env: { ...process.env, PATH, ...env }, + env: { ...cleanEnv(), PATH, ...env }, }); } finally { fs.rmSync(dir, { recursive: true, force: true }); @@ -94,13 +105,17 @@ export function stub(dir, name, body) { // 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 = {}; - for (const [k, v] of Object.entries(env)) { - saved[k] = process.env[k]; + 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")); @@ -191,7 +206,7 @@ export async function runBashStepAsync(script, { env = {}, stubDir = null, cwd = return await new Promise((resolve) => { const child = spawn("bash", ["--noprofile", "--norc", "-eo", "pipefail", file], { cwd, - env: { ...process.env, PATH, ...env }, + env: { ...cleanEnv(), PATH, ...env }, stdio: ["ignore", "pipe", "pipe"], }); let stdout = ""; 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(); + }); +}); From 096a63c43aedeffcdf027a7328216fe80294786c Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 06:39:22 +0000 Subject: [PATCH 16/28] fix(sanitizer): tokenize like the renderer; judge the output with a real CommonMark+GFM parser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sanitizer treated `\` + backtick as an escaped backtick even when the backslash was itself escaped, so \\`x` [Approve](https://evil/login) ` passed unchanged while GFM renders a live link and image. A setext underline of one `-` was not escaped either. A differential test (scripts/sanitizer-render.test.mjs) now renders every sanitised fragment, placed the way action.yml places finding text, with micromark + micromark-extension-gfm and asserts no raw HTML, no heading, no off-site link, and that the text after the fragment is not swallowed — over a corpus of tricks and a seeded fuzz. It found more of the same class, all fixed here: - backslashes: an escape is `\` + ASCII punctuation (CommonMark's rule); a fragment's own `\[` stays an escape (doubling it made `[` live) and any other backslash is doubled so it cannot escape a backtick we add; - lone backtick runs are escaped, so they cannot re-pair with the backticks of a defanged URL's code span; - URL runs are taken as GFM's autolink takes them (to whitespace or `<`, across backticks); an allowed URL is emitted as an explicit <...> autolink; a span is never glued to a preceding backtick (runs merge); - headings, setext underlines and tilde fences inside list items and quotes are escaped; a fence is trusted only at column 0 (indented, it may belong to a list item the renderer closes early); - no table can form (a table row cuts code spans open at `|`). An exploratory 100k-iteration fuzz with a wider alphabet was clean. micromark@4.0.2 and micromark-extension-gfm@3.0.0 are exact-pinned devDependencies (36 packages in the lockfile, none with install scripts); CI installs them with `npm ci --ignore-scripts`. The action never does. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- .github/workflows/test.yml | 8 +- package-lock.json | 682 ++++++++++++++++++++++++++++++ package.json | 2 + scripts/publish-guard.mjs | 170 ++++++-- scripts/sanitizer-render.test.mjs | 269 ++++++++++++ 5 files changed, 1085 insertions(+), 46 deletions(-) create mode 100644 scripts/sanitizer-render.test.mjs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 51bd75f..df47121 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -35,9 +35,11 @@ jobs: with: node-version: ${{ matrix.node-version }} - # Dev-only: the YAML parser the structural tests read action.yml and the - # shipped workflows with. `npm ci` installs exactly the lockfile (with its - # integrity hashes) and --ignore-scripts runs no install hook. + # 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 diff --git a/package-lock.json b/package-lock.json index 26dd0c1..d6847f2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,12 +12,694 @@ "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", diff --git a/package.json b/package.json index b2afbda..8aa8aa2 100644 --- a/package.json +++ b/package.json @@ -44,6 +44,8 @@ "access": "public" }, "devDependencies": { + "micromark": "4.0.2", + "micromark-extension-gfm": "3.0.0", "yaml": "2.9.1" } } diff --git a/scripts/publish-guard.mjs b/scripts/publish-guard.mjs index c4608eb..d3965de 100644 --- a/scripts/publish-guard.mjs +++ b/scripts/publish-guard.mjs @@ -16,10 +16,15 @@ // 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; +// 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, so a finding -// cannot print "## OrcaCode Review ✅ No findings"; +// - 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 @@ -34,7 +39,9 @@ // // 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. +// 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. export const MAX_FINDING_CHARS = 3000; export const MAX_POSTED_FINDINGS = 50; @@ -71,7 +78,13 @@ export function codeSpan(text, max = 300) { 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); @@ -93,55 +106,111 @@ function allowedUrl(raw, { repo, serverUrl }) { return p === prefix || p.startsWith(`${prefix}/`); } -const URL_RE = /(?:[a-z][a-z0-9+.-]*:\/\/|www\.)[^\s<]*/gi; +// 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; -// Escape one run of plain (non-code) text on ONE line. -function escapeText(t, opts) { +// 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 = ""; - let last = 0; - for (const m of t.matchAll(URL_RE)) { - // 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. - let url = m[0]; - 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; - } - out += escapePlain(t.slice(last, m.index)); - out += allowedUrl(url, opts) ? url : codeSpan(url, 400); - last = m.index + url.length; + 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 + escapePlain(t.slice(last)); + return out; } -const escapePlain = (t) => t.replace(/ - 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 and setext underlines: a finding must not forge structure. - if (/^ {0,3}#/.test(body)) { - const i = body.indexOf("#"); - lead = `${body.slice(0, i)}\\`; - body = body.slice(i); - } else if (/^ {0,3}(=+|-{2,})[ \t]*$/.test(body)) { - const i = body.search(/[=-]/); - lead = `${body.slice(0, i)}\\`; - body = body.slice(i); + // 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 = ""; + 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 === "\\" && body[i + 1] === "`") { - text += "\\`"; - i += 2; + 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 === "`") { @@ -162,19 +231,30 @@ function sanitizeLine(line, atLineStart, opts) { } else j += 1; } if (close < 0) { - text += "`".repeat(n); // a lone run is literal text + text += "`".repeat(n); // a lone run is literal text (escapePlain escapes it) i += n; continue; } - out += escapeText(text, opts) + body.slice(i, close + n); - text = ""; + 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; } - return lead + out + escapeText(text, opts); + flush(); + return out; } /** @@ -204,8 +284,12 @@ export function sanitizeUntrusted(text, { repo, serverUrl, atLineStart = true, m 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(/^ {0,3}(`{3,}|~{3,})(.*)$/); + 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); diff --git a/scripts/sanitizer-render.test.mjs b/scripts/sanitizer-render.test.mjs new file mode 100644 index 0000000..7c1b6dd --- /dev/null +++ b/scripts/sanitizer-render.test.mjs @@ -0,0 +1,269 @@ +// sanitizeUntrusted() judged by what a real CommonMark + GFM renderer makes of +// its output, not by what the output looks like as text. +// +// The sanitizer is a hand-written tokenizer, and a tokenizer that disagrees +// with the renderer about one character is a bypass: it treated `\` + backtick +// as an escaped backtick even when the backslash was itself escaped (`\\`), so +// +// \\`x` [Approve](https://evil/login) ` +// +// was taken for one long code span and passed through unchanged, while GFM +// renders a code span `x`, then a live link and a live image. A setext +// underline of one `-` was not escaped either, so `foo\n-` printed a heading. +// +// So every input below — a corpus of known tricks and a seeded fuzz over the +// characters markdown gives meaning to — is sanitised, placed the way the +// action places finding text, rendered with micromark + micromark-extension-gfm +// (exact-pinned devDependencies; the action itself never installs them), and +// the HTML is held to four properties: +// 1. no tag the fragment did not get from markdown itself (no , no +//
, no , nothing raw), and no HTML comment; +// 2. no heading; +// 3. every link points into this repository or the OrcaRouter docs host; +// 4. text the action writes after the fragment is still a paragraph of its +// own — the fragment cannot swallow it into code. +// +// micromark is not GitHub's renderer (cmark-gfm), but both implement the same +// two specs; a disagreement between them would be a bug report against one. + +import { describe, test } from "node:test"; +import assert from "node:assert/strict"; +import { micromark } from "micromark"; +import { gfm, gfmHtml } from "micromark-extension-gfm"; + +import { sanitizeUntrusted } from "./publish-guard.mjs"; +import { step } from "./test-helpers/action-yaml.mjs"; + +const REPO = { owner: "acme", repo: "widgets" }; +const S = (t, o = {}) => sanitizeUntrusted(t, { repo: REPO, serverUrl: "https://github.com", ...o }); + +// Raw HTML is let through on purpose: the point is to SEE any that survives. +const render = (md) => + micromark(md, { + extensions: [gfm()], + htmlExtensions: [gfmHtml()], + allowDangerousHtml: true, + allowDangerousProtocol: true, + }); + +// Tags markdown itself produces from the syntax a finding may legitimately use. +const MARKDOWN_TAGS = new Set([ + "p", "code", "pre", "em", "strong", "del", "ul", "ol", "li", "blockquote", "hr", "br", + "table", "thead", "tbody", "tr", "th", "td", "input", "a", +]); + +const decodeAttr = (v) => + v.replace(/"/g, '"').replace(/</g, "<").replace(/>/g, ">").replace(/&/g, "&"); + +function linkAllowed(href) { + let u; + try { + u = new URL(href); + } catch { + return false; // relative, scheme-relative-looking or garbage: not ours + } + if (u.protocol !== "https:" || u.username || u.password) return false; + const host = u.hostname.toLowerCase(); + if (host === "www.orcarouter.ai" || host === "orcarouter.ai") return true; + if (host !== "github.com") return false; + const p = u.pathname.toLowerCase(); + return p === "/acme/widgets" || p.startsWith("/acme/widgets/"); +} + +// The properties, as a list of violations (empty = fine). +function violations(html, { after = null } = {}) { + const bad = []; + if (/", + "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(/ Date: Sat, 31 Oct 2026 06:40:48 +0000 Subject: [PATCH 17/28] fix(redaction): catch hex copies and copies split by invisible characters MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit formsOf() covered raw, URL-encoded, base64 (every alignment) and base64url, but not hex, and a copy with zero-width characters between its letters reads as the secret and matched nothing. redactSecrets now adds the hex form (matched in any letter case) and matches against the text with Unicode format characters (\p{Cf}: ZWSP, ZWJ/ZWNJ, word joiner, BOM, soft hyphen, bidi marks) ignored, replacing the original span — invisible characters outside a match are kept, so a sanitised @mention stays neutralised. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- SECURITY.md | 3 ++- scripts/publish-guard.mjs | 49 +++++++++++++++++++++++++++++----- scripts/publish-guard.test.mjs | 25 +++++++++++++++++ 3 files changed, 70 insertions(+), 7 deletions(-) diff --git a/SECURITY.md b/SECURITY.md index 327d8da..6291aa3 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -137,7 +137,8 @@ Failure modes are closed: Absolute-form, scheme-relative and backslash request targets are refused. - **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, and as the Basic-auth value. + 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 diff --git a/scripts/publish-guard.mjs b/scripts/publish-guard.mjs index d3965de..5600851 100644 --- a/scripts/publish-guard.mjs +++ b/scripts/publish-guard.mjs @@ -35,7 +35,8 @@ // 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. +// 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 `<`; @@ -328,12 +329,14 @@ const MIN_SECRET = 8; // 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); @@ -344,17 +347,51 @@ function formsOf(secret) { forms.add(core.replace(/\+/g, "-").replace(/\//g, "_")); } } - return [...forms].sort((a, b) => b.length - a.length); + 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 = []) { - let out = String(text ?? ""); + const src = String(text ?? ""); const usable = secrets.filter((s) => typeof s === "string" && s.length >= MIN_SECRET); - for (const s of usable) { - for (const f of formsOf(s)) { - if (f && out.includes(f)) out = out.split(f).join("[REDACTED]"); + 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; } diff --git a/scripts/publish-guard.test.mjs b/scripts/publish-guard.test.mjs index 366b9b5..e677332 100644 --- a/scripts/publish-guard.test.mjs +++ b/scripts/publish-guard.test.mjs @@ -157,6 +157,31 @@ describe("redactSecrets", () => { test("short or empty secrets are ignored rather than shredding the text", () => { assert.equal(redactSecrets("a b c", ["", "a", undefined]), "a b c"); }); + + test("hex, lower, upper and mixed case", () => { + const hex = Buffer.from(KEY).toString("hex"); + const mixed = [...hex].map((c, i) => (i % 2 ? c.toUpperCase() : c)).join(""); + for (const form of [hex, hex.toUpperCase(), mixed]) { + const out = redactSecrets(`dump: ${form} end`, [KEY]); + assert.ok(!out.includes(form), `not redacted: ${form}`); + assert.match(out, /^dump: \[REDACTED\] end$/); + } + }); + + test("a copy split by invisible characters (zero-width, joiners, soft hyphen, bidi marks) is redacted", () => { + for (const z of ["​", "‌", "‍", "⁠", "", "­", "‎"]) { + const split = [...KEY].join(z); + const out = redactSecrets(`x ${split} y`, [KEY]); + assert.equal(out, "x [REDACTED] y", `split by U+${z.codePointAt(0).toString(16)}`); + } + const b64split = b64(KEY).replace(/(.{4})/g, "$1​"); + assert.ok(!redactSecrets(b64split, [KEY]).replace(/​/g, "").includes(b64(KEY).slice(4, 20))); + }); + + test("invisible characters elsewhere are left alone (a neutralised @‍mention stays neutralised)", () => { + const text = `ping @‍alice about ${KEY}`; + assert.equal(redactSecrets(text, [KEY]), "ping @‍alice about [REDACTED]"); + }); }); describe("guardGithub: every posting method is redacted on the way out", () => { From 328fc310e94ab42a8af7f6e5de5dfffa72d1558f Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 06:46:39 +0000 Subject: [PATCH 18/28] fix(skips): a settings skip passes the job again; the head-SHA status says "Not reviewed" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit on-skipped-review defaulted to "fail", so on-demand mode, auto-review off, drafts and (on public repos) outsiders' PRs turned the job red for every customer, and those who require the `review` job could no longer merge. The job conclusion for a skip is back to PASS by default, as in every earlier release; `on-skipped-review: "fail"` still fails it (case and spaces ignored; any other value passes and warns). The commit status on the PR head (status-context, needs statuses: write) reports every settings skip as a failure, "Not reviewed: ", whatever the job does — so a customer who makes that status required cannot merge an unreviewed PR, and nobody else regresses. The skip notice says so when the status is on. Docs (README, SECURITY.md, the skill's inputs/troubleshooting) describe the job/status split, marked as v1.7.0 (unreleased) behaviour where it is. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- README.md | 8 +- SECURITY.md | 9 +- action.yml | 73 +++++++++------- scripts/review-status.mjs | 22 +++-- scripts/review-status.test.mjs | 87 ++++++++++++------- skills/orca-review-action/SKILL.md | 9 +- .../orca-review-action/references/inputs.md | 4 +- .../references/troubleshooting.md | 18 ++-- 8 files changed, 141 insertions(+), 89 deletions(-) diff --git a/README.md b/README.md index ba29f63..2d55811 100644 --- a/README.md +++ b/README.md @@ -259,9 +259,9 @@ To make P0/P1 findings actually prevent merging: **GitHub → Settings → Branches / Rulesets → Require status checks to pass** -Add the **`OrcaCode Review`** status as required. The action writes it on the PR's head commit at the end of every run, and it is green only when a review actually ran on that commit and the gate passed. It is also 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. (Requiring the **`review`** job check still works for push-triggered runs, but then an on-demand review can never turn a skipped PR green.) +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. -A PR the action did **not** review never passes: a skipped review (on-demand mode, auto-review off, a draft, an author outside `auto-review-authors`) and an oversized diff both fail the check by default — set `on-skipped-review: "pass"` / `on-oversized-diff: "pass"` to make them advisory. +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 you pin v1.7.0 or later: 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. --- @@ -272,8 +272,8 @@ Security hardening that changes what you may see. Inputs are unchanged except fo | 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: "*"` | -| New `on-skipped-review` (default `"fail"`) | A skipped review (on-demand mode, auto-review off, a draft, an author outside the allowlist) **fails** the check instead of passing | `on-skipped-review: "pass"` | -| New `status-context` (default `"OrcaCode Review"`) | A commit status on the PR head after every run, on-demand runs included. Grant `statuses: write`; require this status instead of the `review` job | `status-context: ""` | +| 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 | — | | 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 | — | | Settings outage with `block-on` left at its default | That run blocks on **every** severity (an outage never loosens the gate) | Set `block-on` explicitly | | The gate fails closed | A result the gate cannot read now fails the check instead of passing | — | diff --git a/SECURITY.md b/SECURITY.md index 6291aa3..d14a06c 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -105,13 +105,14 @@ 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 a skip advisory on purpose. +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`) fails the check unless - `on-skipped-review: "pass"`; an **oversized** diff fails it unless - `on-oversized-diff: "pass"`. + 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 and the workflow leaves `block-on` at its default, that run blocks on every severity: an outage can tighten the diff --git a/action.yml b/action.yml index 9b8a95c..583de73 100644 --- a/action.yml +++ b/action.yml @@ -36,9 +36,10 @@ # 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 — a skip fails per `on-skipped-review`, 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). +# 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" @@ -144,22 +145,23 @@ inputs: 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 check. "fail" (default) fails the job and writes a failing - commit status on the PR head, so an unreviewed PR can never satisfy a - required merge gate — the same rule as on-oversized-diff. "pass" makes - skips advisory: the notice posts and the check stays green. A - maintainer's /orcacode-review then reviews the head and its verdict - replaces the status. + 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: "fail" + 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 a skip was made advisory). 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. + 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: @@ -672,11 +674,11 @@ 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 apply `on-skipped-review`. No later - # step runs the engine or the gate either way. Default "fail": the check - # goes RED and the commit status on the head says why — an unreviewed PR - # must not satisfy a required merge gate (the same rule as an oversized - # diff). "pass" makes skips advisory. + # 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@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 @@ -687,6 +689,8 @@ runs: 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 @@ -708,8 +712,17 @@ runs: const brand = process.env.BRAND; const num = Number(process.env.PR_NUMBER); const repo = { owner: context.repo.owner, repo: context.repo.repo }; - // Anything that is not an explicit "pass" fails the check (fail-safe). - const pass = process.env.ON_SKIPPED === 'pass'; + // 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 = @@ -718,10 +731,13 @@ runs: const body = `${MARKER}\n## 🐳 ${brand}\n\n` + `⏸️ **Automatic review is off for this PR** (${guard.sanitizeUntrusted(process.env.REASON, { atLineStart: false, maxChars: 300 })}).\n\n` + - (pass - ? `The check **passes** (\`on-skipped-review: "pass"\`), so this skip does not block your merge. ` - : `The check **fails** (\`on-skipped-review: "fail"\`, the default): this PR has not been ` + - `reviewed, so it cannot satisfy a required merge gate. `) + + (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.` + @@ -739,13 +755,12 @@ runs: } await core.summary.addRaw(`skipped: ${process.env.REASON}`).write(); - if (pass) { + if (!fail) { core.notice(`${brand}: review skipped — ${process.env.REASON}`); } else { core.setFailed( - `${brand}: review skipped — ${process.env.REASON}. Failing the check so an unreviewed PR cannot ` + - `pass a required merge gate: a maintainer can comment /orcacode-review, or set ` + - `on-skipped-review: "pass" to make skips advisory.`, + `${brand}: review skipped — ${process.env.REASON}. Failing the job (on-skipped-review: "fail"): ` + + `a maintainer can comment /orcacode-review to review the head.`, ); } diff --git a/scripts/review-status.mjs b/scripts/review-status.mjs index eb8214e..d2f868d 100644 --- a/scripts/review-status.mjs +++ b/scripts/review-status.mjs @@ -4,11 +4,17 @@ // // One pure function, so every ending is decided in one place and tested as a // table. `success` means exactly one of two things: a review ran on this head -// and the severity gate passed it, or the run was skipped and the workflow made -// that kind of skip advisory on purpose (`on-skipped-review: "pass"`, -// `on-oversized-diff: "pass"`). Everything else — a skip under the default -// "fail", a blocked gate, a gate that could not decide, an engine failure, a -// cancelled run, a run that never reached a decision — is not success. +// and the severity gate passed it, or the diff was oversized and the workflow +// made that skip advisory on purpose (`on-oversized-diff: "pass"`). Everything +// else — a settings skip, a blocked gate, a gate that could not decide, an +// engine failure, a cancelled run, a run that never reached a decision — is not +// success. +// +// A SETTINGS SKIP IS NEVER SUCCESS HERE, whatever `on-skipped-review` says. +// That input decides the JOB, and it passes by default: failing the job on +// every on-demand, auto-review-off, draft or outsider PR broke every customer +// who requires the `review` job. This status is what a customer who wants +// "unreviewed cannot merge" makes required, and it says "Not reviewed". // // Inputs are the raw strings the step reads from step outputs/outcomes, so an // absent value (a step that never ran) is "" and lands on a failing branch. @@ -22,7 +28,7 @@ export function decideStatus({ reason = "", guardDecision = "", guardReason = "", - onSkipped = "", + onSkipped = "", // the job's business only (see above); kept so callers pass one shape onOversized = "", reviewOutcome = "", enforceOutcome = "", @@ -32,9 +38,7 @@ export function decideStatus({ const out = (state, description) => ({ state, description: clip(description) }); if (decision === "skip") { - return onSkipped === "pass" - ? out("success", `Review skipped (${reason}) — advisory`) - : out("failure", `Review skipped (${reason}) — not reviewed; a maintainer can comment /orcacode-review`); + return out("failure", `Not reviewed: ${reason} — a maintainer can comment /orcacode-review`); } if (decision !== "review") return out("error", "Review did not start"); diff --git a/scripts/review-status.test.mjs b/scripts/review-status.test.mjs index 2e16004..ce098e6 100644 --- a/scripts/review-status.test.mjs +++ b/scripts/review-status.test.mjs @@ -7,14 +7,18 @@ // the DEFAULT BRANCH's check, so a red verdict never blocked the PR. // // Now: -// - `on-skipped-review` ("fail" by default, "pass" to make skips advisory) -// decides what a settings skip does to the job, exactly as -// `on-oversized-diff` does for an oversized one; // - every run that resolves a PR writes a commit status (context // `status-context`, default "OrcaCode Review") on the PR's HEAD SHA — the // comment-triggered runs included — and it is `success` only when a review -// actually ran on that head and the gate passed, or when a skip was made -// advisory on purpose. +// actually ran on that head and the gate passed (or an oversized diff was +// made advisory with `on-oversized-diff: "pass"`). A settings skip is never +// success there: it says "Not reviewed: ". +// - the JOB is another matter. Failing it on a skip by default (the first cut +// of this fix) turned on-demand mode, auto-review-off, drafts and outsiders' +// PRs red for every customer, and broke merges for those who require the +// `review` job. So a skip passes the job by default, as it always did, and +// `on-skipped-review: "fail"` fails it too. A customer who makes the +// status required is protected either way; nobody else regresses. import { describe, test } from "node:test"; import assert from "node:assert/strict"; @@ -62,19 +66,13 @@ describe("decideStatus", () => { assert.notEqual(decideStatus({ ...base, verdict: "" }).state, "success"); }); - test("a settings skip fails by default, naming the reason", () => { - const s = decideStatus({ ...base, decision: "skip", reason: "on-demand mode" }); - assert.equal(s.state, "failure"); - assert.match(s.description, /on-demand mode/); - }); - - test('a settings skip with on-skipped-review: "pass" is advisory success', () => { - assert.equal(decideStatus({ ...base, decision: "skip", reason: "draft PR", onSkipped: "pass" }).state, "success"); - }); - - test("anything but an explicit pass fails a skip (fail-safe)", () => { - assert.equal(decideStatus({ ...base, decision: "skip", reason: "x", onSkipped: "PASS!" }).state, "failure"); - }); + for (const onSkipped of ["pass", "fail", "", "PASS!"]) { + test(`a settings skip is "Not reviewed: ", never success (on-skipped-review: ${JSON.stringify(onSkipped)})`, () => { + const s = decideStatus({ ...base, decision: "skip", reason: "on-demand mode", onSkipped }); + assert.equal(s.state, "failure"); + assert.match(s.description, /^Not reviewed: on-demand mode/); + }); + } test("an oversized skip follows on-oversized-diff", () => { assert.equal(decideStatus({ ...base, guardDecision: "skip", guardReason: "too big" }).state, "failure"); @@ -164,19 +162,32 @@ describe("action.yml: the status is published on the head SHA", () => { assert.match(s.if, /steps\.pr\.outputs\.run == 'true'/); }); - test("the inputs exist with fail-safe defaults", () => { + test("a skip passes the job by default (as before); the status is on by default", () => { const inputs = loadAction().inputs; - assert.equal(inputs["on-skipped-review"].default, "fail"); + assert.equal(inputs["on-skipped-review"].default, "pass"); assert.equal(inputs["status-context"].default, "OrcaCode Review"); }); + + test("a settings skip's status lands on the head as failure even when the job passes", async () => { + const { calls } = await publish({ DECISION: "skip", REASON: "draft PR", ON_SKIPPED: "pass", REVIEW_OUTCOME: "", ENFORCE_OUTCOME: "", VERDICT: "" }); + assert.equal(calls[0].state, "failure"); + assert.match(calls[0].description, /^Not reviewed: draft PR/); + }); }); describe("action.yml: a settings skip follows on-skipped-review", () => { - async function skip(onSkipped) { + async function skip(onSkipped, extra = {}) { const { core, rec } = fakeCore(); + const posted = []; const github = { paginate: async () => [], - rest: { issues: { listComments: () => {}, createComment: async () => ({}), updateComment: async () => ({}) } }, + rest: { + issues: { + listComments: () => {}, + createComment: async (a) => posted.push(a.body), + updateComment: async (a) => posted.push(a.body), + }, + }, }; await runGithubScript(step("Skip review (settings)").with.script, { github, @@ -187,21 +198,39 @@ describe("action.yml: a settings skip follows on-skipped-review", () => { PR_NUMBER: "7", REASON: "on-demand mode", ON_SKIPPED: onSkipped, + STATUS_CONTEXT: "OrcaCode Review", PUBLISH_GUARD: path.join(ROOT, "scripts", "publish-guard.mjs"), + ...extra, }, }); - return rec; + return { rec, posted }; } - test('default "fail": the job fails, so a required check cannot pass unreviewed', async () => { - assert.ok((await skip("fail")).failed); + test('the default ("pass"): the job stays green, as it did before this branch', async () => { + const { rec } = await skip(loadAction().inputs["on-skipped-review"].default); + assert.equal(rec.failed, null); + }); + + test('"fail": the job fails too', async () => { + assert.ok((await skip("fail")).rec.failed); + assert.ok((await skip(" FAIL ")).rec.failed, "case and spaces do not matter"); + }); + + test("an unrecognised value passes the job, and says so", async () => { + const { rec } = await skip("fial"); + assert.equal(rec.failed, null); + assert.ok(rec.warnings.some((w) => /on-skipped-review/.test(w) && /fial/.test(w)), rec.warnings.join("\n")); }); - test('"pass": advisory, the job stays green', async () => { - assert.equal((await skip("pass")).failed, null); + test("the notice says the status reports the PR as not reviewed (so a required status still holds it)", async () => { + const { posted } = await skip("pass"); + assert.equal(posted.length, 1); + assert.match(posted[0], /OrcaCode Review/); + assert.match(posted[0], /not reviewed/i); }); - test("anything else fails (fail-safe)", async () => { - assert.ok((await skip("")).failed); + test("with the status turned off (status-context: \"\") the notice does not promise one", async () => { + const { posted } = await skip("pass", { STATUS_CONTEXT: "" }); + assert.doesNotMatch(posted[0], /commit status/i); }); }); diff --git a/skills/orca-review-action/SKILL.md b/skills/orca-review-action/SKILL.md index 0ec49bf..1dff13d 100644 --- a/skills/orca-review-action/SKILL.md +++ b/skills/orca-review-action/SKILL.md @@ -232,10 +232,11 @@ gh run view --log-failed `references/troubleshooting.md` maps each symptom to its cause and fix. The four that account for most reports: -- **Red check, "review skipped" notice** — the PR is a draft and `trigger` is - `ready_for_review`, the author is outside `auto-review-authors` (unset means - maintainers only on a public repo), or the app is off in the dashboard. Skips fail by - default (`on-skipped-review`); a maintainer's `/orcacode-review` reviews the head. +- **"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. - **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 diff --git a/skills/orca-review-action/references/inputs.md b/skills/orca-review-action/references/inputs.md index 8f4fd2c..8d22fd8 100644 --- a/skills/orca-review-action/references/inputs.md +++ b/skills/orca-review-action/references/inputs.md @@ -41,8 +41,8 @@ empty string is valid and means "none". | Input | Default | What it does | | --- | --- | --- | | `auto-review-authors` | unset: `OWNER,MEMBER,COLLABORATOR` on a public repo, everyone on a private one | Author-association allowlist for **automatic** reviews. `"*"` reviews everyone on any repo. Others can still be reviewed on demand via `/orcacode-review`. Values: `OWNER`, `MEMBER`, `COLLABORATOR`, `CONTRIBUTOR`, `FIRST_TIME_CONTRIBUTOR`, `FIRST_TIMER`, `MANNEQUIN`, `NONE`, `*`. | -| `on-skipped-review` | `fail` | What a settings skip (auto-review off, on-demand mode, a draft, an author outside the allowlist) does to the check. `fail` keeps an unreviewed PR from passing a required gate; `pass` makes skips advisory. | -| `status-context` | `OrcaCode Review` | 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. Make it the required check; needs `statuses: write`. `""` turns it off. | +| `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 diff --git a/skills/orca-review-action/references/troubleshooting.md b/skills/orca-review-action/references/troubleshooting.md index 9938697..503d279 100644 --- a/skills/orca-review-action/references/troubleshooting.md +++ b/skills/orca-review-action/references/troubleshooting.md @@ -119,14 +119,16 @@ retries are what is eating the clock. ## The check is red but nothing was reviewed -Expected when a review is skipped: on-demand mode, auto-review off in the -dashboard, a draft under `ready_for_review`, an author outside -`auto-review-authors` (on a public repo an unset allowlist means -`OWNER,MEMBER,COLLABORATOR`), or an oversized diff. An unreviewed PR fails by -default so it cannot pass a required gate. A maintainer's `/orcacode-review` -reviews the head and its verdict replaces the `OrcaCode Review` status — which is -why that status, not the `review` job, should be the required check. To make skips -advisory instead: `on-skipped-review: "pass"` / `on-oversized-diff: "pass"`. +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 1137527ba243ab5b06c1ca28cf9e26138e6a5e8d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 06:51:51 +0000 Subject: [PATCH 19/28] fix(settings): a 4xx means "no dashboard settings"; an outage uses the workflow's inputs, never more MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An ordinary (non-CI) key gets 403 from /api/code_review/settings on every run, and the action treated that as an outage and blocked on P0-P3 every time. settings.mjs now classifies a failed fetch in the file it writes: status "no_settings" — a 4xx (but 408/429) or success:false; no retry; status "unavailable" — 5xx, 408/429, timeout, network error, a body that is not the envelope; after one retry; with `cause` ("HTTP 403", "timed out after 5000ms", ...). The "Fetch review settings" step takes ONE workflow-authoritative path for `settings: "false"`, a 4xx (with a notice) and an outage (with a warning naming the cause): the workflow's inputs, exactly what settings: "false" writes. Nothing escalates past the workflow any more; the CR-16 hole (an outage loosening a stricter dashboard block_on) is closed by documenting the workflow's block-on as the outage floor. A dashboard that answered with an invalid block_on uses the workflow's block-on for that field. Tests: settings.mjs against 400/401/403/404 (no retry), 408/429/500/502/503 (one retry), a server that never answers (CR_SETTINGS_TIMEOUT_MS), a refused connection; the step with stubbed files; and the step plus the real settings.mjs end to end against 403, 404, 500 and a hung gateway. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- README.md | 2 +- SECURITY.md | 9 +- action.yml | 88 ++++++--- scripts/settings-wiring.test.mjs | 173 ++++++++++++++---- scripts/settings.mjs | 110 ++++++++--- scripts/settings.test.mjs | 106 ++++++++++- .../orca-review-action/references/inputs.md | 9 +- 7 files changed, 392 insertions(+), 105 deletions(-) diff --git a/README.md b/README.md index 2d55811..c93d48d 100644 --- a/README.md +++ b/README.md @@ -275,7 +275,7 @@ Security hardening that changes what you may see. Inputs are unchanged except fo | 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 | — | | 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 | — | -| Settings outage with `block-on` left at its default | That run blocks on **every** severity (an outage never loosens the gate) | Set `block-on` explicitly | +| 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 is refused (loopback excepted) | — | diff --git a/SECURITY.md b/SECURITY.md index d14a06c..3382aa1 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -114,9 +114,12 @@ Failure modes are closed: 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 and the workflow leaves `block-on` - at its default, that run blocks on every severity: an outage can tighten the - gate, never loosen it. An explicit `block-on` in the workflow is used as is. +- 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 diff --git a/action.yml b/action.yml index 583de73..a039c54 100644 --- a/action.yml +++ b/action.yml @@ -474,10 +474,11 @@ runs: # 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 - # (a settings hiccup must never kill reviews), naming every stand-in in - # `unresolved`. Reviews stay fail-open; the merge gate does not: an - # unresolved block_on blocks on every severity unless the workflow pins it. + # 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' @@ -561,19 +562,19 @@ runs: 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" @@ -581,7 +582,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" @@ -589,12 +590,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). @@ -620,11 +653,10 @@ runs: REPORT_ON=$(setting report_on "P0,P1") RUBRIC=$(setting rubric "") - # Which values are stand-ins for ones the dashboard did not give us. - # settings.mjs names them in `unresolved`; a file that cannot be read at - # all (settings.mjs died before writing it) means every value is one. + # 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="unreadable" + || UNRESOLVED="" # PRECEDENCE (documented in the README): an explicit `with:` input that # DIFFERS from the action's documented default ("P0,P1") wins over the @@ -632,15 +664,11 @@ runs: 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" - elif [ "$UNRESOLVED" = "unreadable" ] || printf ',%s,' "$UNRESOLVED" | grep -q ',block_on,'; then - # THE WORKFLOW DEFERS TO THE DASHBOARD AND THE DASHBOARD COULD NOT BE - # READ. Its block_on is unknown, and the built-in P0,P1 standing in for - # it may be looser than what the workspace set — an outage must never - # be the thing that lets a P2 through a gate configured to block it. - # So block on every severity for this run: an outage can only tighten - # the gate. Pin `block-on:` in the workflow to use your own value. - BLOCK_ON="P0,P1,P2,P3" - echo "::warning::$BRAND: the OrcaRouter dashboard settings could not be read, so its block-on is unknown — blocking on every severity (P0,P1,P2,P3) for this run. Set block-on in the workflow to choose the outage value yourself." + 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 diff --git a/scripts/settings-wiring.test.mjs b/scripts/settings-wiring.test.mjs index 6f874d5..fa780eb 100644 --- a/scripts/settings-wiring.test.mjs +++ b/scripts/settings-wiring.test.mjs @@ -1,14 +1,22 @@ // The "Fetch review settings" step, run for real (bash, through the YAML // parser) with settings.mjs stood in by a stub that writes a chosen file. // -// What is pinned here is the merge gate's FAIL DIRECTION when the dashboard -// cannot be read. block_on's built-in default (P0,P1) is looser than plenty of -// dashboard values it may stand in for, so a settings outage used to replace a -// stricter dashboard policy with P0,P1 — silently. Now: -// - an explicit `block-on:` in the workflow is authoritative, outage or not; -// - a workflow that defers to the dashboard (block-on left at its default) -// blocks on EVERY severity while the dashboard's value is unknown, so an -// outage can only tighten the gate, never loosen it. +// What is pinned here is what the step does when the dashboard does not answer. +// +// The first cut of the CR-16 fix escalated an unreadable block_on to every +// severity. An ordinary (non-CI) key gets a 403 from the settings endpoint on +// EVERY run, so that blocked on P0-P3 forever for every such customer. Now a +// failed fetch never escalates past the workflow: +// - a 4xx (or success:false) means "this key has no dashboard settings": the +// workflow's inputs are authoritative, exactly as with `settings: "false"`, +// and a notice says why; +// - a 5xx, a timeout or a network failure does the same, with a warning +// naming the cause. The hole CR-16 was about — an outage loosening a +// stricter dashboard block_on — is closed by the workflow, not by guessing: +// its `block-on` is the outage floor (documented), and the outage path +// never goes below it; +// - a dashboard that answered but with an invalid block_on uses the +// workflow's block-on for that field. import fs from "node:fs"; import os from "node:os"; @@ -16,7 +24,9 @@ import path from "node:path"; import { after, before, describe, test } from "node:test"; import assert from "node:assert/strict"; -import { step, runBashStep } from "./test-helpers/action-yaml.mjs"; +import http from "node:http"; + +import { step, runBashStep, runBashStepAsync, ROOT } from "./test-helpers/action-yaml.mjs"; let dir; before(() => { @@ -38,7 +48,7 @@ const DEFAULTS = { 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", extraEnv = {} }) { +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`); @@ -59,7 +69,7 @@ function runSettings({ written, inputBlockOn = "P0,P1", extraEnv = {} }) { REPO: "o/r", SETTINGS_JSON: json, RUBRIC_FILE: path.join(dir, `rubric-${n}.md`), - INPUT_FIX_FIRST: "P0,P1", + INPUT_FIX_FIRST: inputFixFirst, INPUT_BLOCK_ON: inputBlockOn, EVENT_NAME: "pull_request_target", IS_DRAFT: "false", @@ -83,40 +93,141 @@ function runSettings({ written, inputBlockOn = "P0,P1", extraEnv = {} }) { const ALL = Object.keys(DEFAULTS); -describe("settings outage never loosens block_on", () => { - test("a reachable dashboard's stricter block_on is used", () => { +// 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("a reachable dashboard may still say 'block on nothing'", () => { + test("it may still say 'block on nothing'", () => { const { outputs } = runSettings({ written: { ...DEFAULTS, block_on: "" } }); assert.equal(outputs.block_on, ""); }); - test("outage + workflow deferring to the dashboard -> block on every severity, loudly", () => { - const { outputs, log } = runSettings({ written: { ...DEFAULTS, unresolved: ALL } }); - assert.equal(outputs.block_on, "P0,P1,P2,P3"); - assert.match(log, /::warning::.*(could not|unavailable|unreachable)/i); - }); - - test("outage + an explicit workflow block-on -> the workflow's value", () => { - const { outputs } = runSettings({ written: { ...DEFAULTS, unresolved: ALL }, inputBlockOn: "P0" }); - assert.equal(outputs.block_on, "P0"); - }); - - test("an invalid block_on from the server is treated like an outage for that field", () => { - const { outputs } = runSettings({ written: { ...DEFAULTS, unresolved: ["block_on"] } }); - assert.equal(outputs.block_on, "P0,P1,P2,P3"); + 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"); + }); + } +}); - test("no settings file at all (settings.mjs died) -> every severity, never the P0,P1 fallback", () => { - const { outputs } = runSettings({ written: null }); - assert.equal(outputs.block_on, "P0,P1,P2,P3"); +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: { + 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 7bfe13e..0947975 100644 --- a/scripts/settings.mjs +++ b/scripts/settings.mjs @@ -14,10 +14,17 @@ // 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). @@ -25,10 +32,9 @@ // 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). block_on's default -// (P0,P1) is LOOSER than many a dashboard value it may replace, so the action -// reads this list and refuses to let a stand-in loosen the merge gate: an -// unresolved block_on blocks on every severity unless the workflow pins one. +// (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- @@ -43,7 +49,8 @@ import fs from "node:fs"; import { SEVERITIES } from "./severity.mjs"; import { controlPlaneBase } from "./control-plane.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 @@ -140,21 +147,64 @@ function validateSettings(data) { return unresolved.length ? { ...out, unresolved } : out; } -// The built-in defaults, marked as stand-ins for every field: what an envelope -// failure (or no usable arguments at all) writes. -const fallbackSettings = () => ({ ...DEFAULTS, unresolved: Object.keys(DEFAULTS) }); +// 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, 200), +}); + +// 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; + } +} -// One settings fetch. Throws on any envelope problem — the caller retries. +// 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; } @@ -164,21 +214,25 @@ async function resolveSettings(opts) { 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 fallbackSettings(); + 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 (reviews continue; the action will not let them loosen block_on)", + `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(); + return fallbackSettings(last.status, last.cause); } async function main() { @@ -200,7 +254,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 = fallbackSettings(); + settings = fallbackSettings("unavailable", "settings.mjs was called with missing arguments"); } else { settings = await resolveSettings(opts); } @@ -223,7 +277,7 @@ main().then( () => process.exit(0), (e) => { console.error(`settings: ${e.message} — using built-in defaults`); - process.stdout.write(`${JSON.stringify(fallbackSettings())}\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 a54b9e8..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 @@ -61,6 +65,14 @@ const DEFAULTS = { 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))); @@ -166,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")), FALLBACK); - assert.deepEqual(JSON.parse(r.stdout), FALLBACK); + 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(); @@ -183,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")), FALLBACK); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "unavailable", /network|ECONNREFUSED|fetch failed/i); assert.match(r.stderr, /default/i); }); @@ -193,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")), FALLBACK); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "unavailable", /JSON|body/i); } finally { await gw.close(); } @@ -205,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")), FALLBACK); + assertFallback(JSON.parse(readFileSync(out, "utf8")), "no_settings", /success/); + assert.equal(gw.seen.length, 1, "an answer is not retried"); } finally { await gw.close(); } @@ -214,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), FALLBACK); + assertFallback(JSON.parse(r.stdout), "unavailable", /usage|missing/i); assert.match(r.stderr, /usage/i); }); @@ -224,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")), FALLBACK); + 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(); + } }); }); @@ -477,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", () => { diff --git a/skills/orca-review-action/references/inputs.md b/skills/orca-review-action/references/inputs.md index 8d22fd8..2e1c6e9 100644 --- a/skills/orca-review-action/references/inputs.md +++ b/skills/orca-review-action/references/inputs.md @@ -97,8 +97,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 From 88e727fb3397f1280905dde2867a648fa1fe5f1d Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 06:56:18 +0000 Subject: [PATCH 20/28] fix(release): keep everything we hand out true of the pinned v1.6.0 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every pin (installer ACTION_SHA, example workflow, skill asset, README) is v1.6.0, which predates this branch. Main must stay consistent with it: (a) The installer's "Everyone" answer wrote "*", which v1.6.0's allowlist gate reads as a list holding only "*" — no automatic review at all (and the skill told agents to write the same). It now writes the full association list, which both releases read as everyone; "*" stays supported in action.yml. scripts/pinned-release.test.mjs runs every answer through v1.6.0's gate (a frozen copy, checked against the pinned commit where the checkout has it) and the current one. (b) Doc lines about behaviour only the unreleased action has carry "from v1.7.0 (unreleased)" (or sit under a heading that does). The test derives the terms — every input action.yml has that v1.6.0 does not, plus listed behaviours (the head-SHA status, statuses: write, the key proxy, the public-repo author default, the action's own command check, engine pins, https-only) — over README, SECURITY.md, the skill and the shipped workflows; once ACTION_VERSION reaches v1.7.0 the marker itself is refused, so the release bump forces a doc pass. Fixing the docs also fixed a live trap: the skill told agents to require the "OrcaCode Review" status, which v1.6.0 never writes, blocking every PR; it now requires the `review` job and describes the status as from v1.7.0. (c) RELEASE.md: v1..

tags are immutable; the floating v1 MAY be advanced, only by the release step, by an administrator through the ruleset bypass, as a fast-forward-only ref update (force=false); the recommended customer pin is a full SHA with `# v1.x`. The release step now bumps PINNED and the doc markers with the pin. The publish workflow runs scripts/doc-pins.mjs on the packed tarball and refuses docs that name an action version newer than the pin outside the marker. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- .github/workflows/publish.yml | 12 + README.md | 16 +- RELEASE.md | 91 ++++--- SECURITY.md | 8 +- bin/orcacode-review.mjs | 18 +- scripts/doc-pins.mjs | 198 +++++++++++++++ scripts/installer.test.mjs | 20 +- scripts/pinned-release.test.mjs | 234 ++++++++++++++++++ scripts/release-pin.test.mjs | 23 +- skills/orca-review-action/SKILL.md | 31 ++- skills/orca-review-action/assets/workflow.yml | 2 +- .../orca-review-action/references/inputs.md | 14 +- .../references/troubleshooting.md | 9 +- workflows/orca-code-review.yml | 12 +- 14 files changed, 602 insertions(+), 86 deletions(-) create mode 100644 scripts/doc-pins.mjs create mode 100644 scripts/pinned-release.test.mjs diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 23f291b..1909775 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -159,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/README.md b/README.md index c93d48d..e7a7a17 100644 --- a/README.md +++ b/README.md @@ -155,7 +155,7 @@ permissions: contents: read pull-requests: write issues: write - statuses: write # the verdict on the PR head — the check to make required + statuses: write # used from v1.7.0 (unreleased): the verdict on the PR head jobs: review: @@ -249,7 +249,9 @@ Comment on any PR: /orcacode-review ``` -to request another review. Only an **owner, member or collaborator** can: the action ignores the command from anyone else, whatever the workflow says. The verdict lands on the PR's head commit as the `OrcaCode Review` status. +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. --- @@ -261,17 +263,17 @@ To make P0/P1 findings actually prevent merging: 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 you pin v1.7.0 or later: 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. +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: behaviour changes in this release +## Upgrading: what changes from v1.7.0 (unreleased) -Security hardening that changes what you may see. Inputs are unchanged except for two new ones; defaults that close a hole are new. +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 two 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: "*"` | +| `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 | — | | 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 | — | @@ -290,7 +292,7 @@ Self-hosted runners need git 2.31 or newer for private-repository fetches (the t ## Security & Privacy -OrcaCode reads the PR diff and repository files required for review. **It does not execute PR code, and the review engine never holds your API key** — an in-job proxy adds it on the way to OrcaRouter. Everything posted to the PR is sanitised and has your key and token redacted. +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 d66e3ba..6a5727b 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,32 +1,43 @@ # Releasing -## Release tags are never moved +## 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 — with -`git tag -f` and a force push — is therefore a way to run new code in every -customer's CI without a single customer-side change. So: - -- **A release is a new tag on a merged commit of `main`: `v1..`.** - It is 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. -- **What we hand out pins the commit, not a tag.** 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 - all read `uses: Continuum-AI-Corp/orca-code-review@ # v1..

`. - `scripts/release-pin.test.mjs` holds all four to the installer's constants, - so a release that bumps one bumps all of them. Customers' Dependabot - (`package-ecosystem: github-actions`) reads the `# v1.x.y` comment and offers - each new release as a pull request that changes the SHA and the comment - together. -- **The `v1` major tag is legacy.** Workflows written before commit pinning - reference `@v1`, and only for them is it still advanced: only ever to a - descendant of its current commit that already carries an immutable - `v1..

` release tag, by an administrator through the ruleset bypass - below. It is the one tag update left that needs force, and it exists only so - those workflows still receive fixes. Nothing this repository generates or - documents references `@v1` any more; tell anyone still on it to pin a SHA. +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 @@ -40,15 +51,26 @@ customer's CI without a single customer-side change. So: ``` Publish a GitHub Release for it; with immutable releases enabled (below) the tag and its assets are locked from then on. -3. In a follow-up PR, bump `ACTION_SHA` and `ACTION_VERSION` in - `bin/orcacode-review.mjs` to that commit and tag, and the same `uses:` line in - `workflows/orca-code-review.yml`, `skills/orca-review-action/assets/workflow.yml` - and the README quickstart. The test suite fails until all four agree. Bump - `package.json` in the same PR when the installer should ship it (see +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). -4. Only if legacy `@v1` users should get this release: an administrator advances - `v1` to the same commit (a descendant of its current one, through the ruleset - bypass). 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. @@ -60,8 +82,7 @@ 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 the legacy fast-forward - in step 4. + `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 diff --git a/SECURITY.md b/SECURITY.md index 3382aa1..ae40af6 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,6 +1,12 @@ # 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. + +## Threat model, from v1.7.0 (unreleased) This action reviews pull requests with an LLM. Two invariants carry its security posture: diff --git a/bin/orcacode-review.mjs b/bin/orcacode-review.mjs index 0a8d618..dcd3bf9 100755 --- a/bin/orcacode-review.mjs +++ b/bin/orcacode-review.mjs @@ -350,10 +350,16 @@ const INPUT_NOTES = { "auto-review-authors": "author allowlist for AUTOMATIC reviews", }; -// The answers to "who gets an automatic review?" on a public repository. The -// action reads an UNSET auto-review-authors there as OWNER,MEMBER,COLLABORATOR, -// so "Everyone" has to be written as the explicit opt-out "*" — written as "" -// it would equal the default, be omitted, and mean maintainers only. +// 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 [ { @@ -362,7 +368,7 @@ export function authorChoices(t) { recommended: true, detail: t("config.authorsKnownDetail"), }, - { label: t("config.authorsAll"), value: "*", detail: t("config.authorsAllDetail") }, + { label: t("config.authorsAll"), value: EVERY_ASSOCIATION, detail: t("config.authorsAllDetail") }, ]; } @@ -400,7 +406,7 @@ permissions: contents: read pull-requests: write issues: write # clean/fallback PR comments - statuses: write # the verdict on the PR head — the check to make required + statuses: write # used from v1.7.0 (unreleased): the verdict on the PR head jobs: review: 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/installer.test.mjs b/scripts/installer.test.mjs index 701325b..9b92206 100644 --- a/scripts/installer.test.mjs +++ b/scripts/installer.test.mjs @@ -67,7 +67,7 @@ test("importing the CLI runs nothing", () => { assert.equal(r.status, 0, r.stderr); // 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,authorChoices,parseOverrides,readOverrides,renderWorkflow"); + assert.equal(r.stdout.trim(), "ACTION_SHA,ACTION_VERSION,DEFAULTS,EVERY_ASSOCIATION,authorChoices,parseOverrides,readOverrides,renderWorkflow"); }); test("the published version matches package.json", () => { @@ -463,17 +463,19 @@ test("an unknown --mode is refused by name, with the choices", (t) => { // ------------------------------------------------- public-repo author default --- -// The action now reads an UNSET auto-review-authors as OWNER,MEMBER,COLLABORATOR -// on a public repository, so the installer's "Everyone" answer can no longer be -// written as the default (an omitted input): it must write the explicit opt-out. -test('the public-repo "Everyone" answer writes the explicit "*" opt-out, not the default', async () => { - const { authorChoices } = await import(CLI); +// "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, "*"); + assert.equal(everyone.value, EVERY_ASSOCIATION); const yaml = renderWorkflow({ ...DEFAULTS, "auto-review-authors": everyone.value }); - assert.match(yaml, /^\s+auto-review-authors: "\*"/m); - assert.equal(parseOverrides(yaml)["auto-review-authors"], "*"); + 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/pinned-release.test.mjs b/scripts/pinned-release.test.mjs new file mode 100644 index 0000000..435bdea --- /dev/null +++ b/scripts/pinned-release.test.mjs @@ -0,0 +1,234 @@ +// 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 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/release-pin.test.mjs b/scripts/release-pin.test.mjs index 64d945d..21111cd 100644 --- a/scripts/release-pin.test.mjs +++ b/scripts/release-pin.test.mjs @@ -84,12 +84,31 @@ describe("release hygiene", () => { assert.equal(gha.directory, "/"); }); + const releaseCode = () => + [...readText("RELEASE.md").matchAll(/```[\w-]*\n([\s\S]*?)```/g)].map((m) => m[1]).join("\n"); + test("RELEASE.md never moves or force-pushes a version tag", () => { const md = readText("RELEASE.md"); - const code = [...md.matchAll(/```[\w-]*\n([\s\S]*?)```/g)].map((m) => m[1]).join("\n"); + const code = releaseCode(); assert.doesNotMatch(code, /git tag (-f|--force)/, "a release step re-points a tag"); - assert.doesNotMatch(code, /git push[^\n]*(--force|-f\b)/, "a release step force-pushes"); + assert.doesNotMatch(code, /git push[^\n]*(--force|-f\b|\+refs)/, "a release step force-pushes"); + assert.doesNotMatch(code, /force=true/, "a release step force-updates a ref"); assert.match(md, /immutable/i, "the immutable-release setting is documented"); assert.match(md, /ruleset/i, "the tag ruleset is documented"); }); + + test("the floating v1 is advanced only by the release step: a fast-forward-only update, by an administrator", () => { + const md = readText("RELEASE.md"); + const code = releaseCode(); + const advance = code.split("\n").filter((l) => /refs\/tags\/v1\b(?!\.)/.test(l)); + assert.equal(advance.length, 1, `exactly one documented way to move v1, got:\n${advance.join("\n")}`); + assert.match(advance[0], /gh api -X PATCH [^\n]*\/git\/refs\/tags\/v1 /); + assert.match(advance[0], /-F force=false\b/, "GitHub refuses a non-fast-forward when force=false"); + assert.match(md, /administrator-only bypass[^\n]*`v1`|`v1`[^\n]*administrator-only bypass/i); + assert.doesNotMatch(md, /\bv1\b[^\n]*\blegacy\b/i, "v1 is the documented floating major, not a legacy leftover"); + }); + + test("RELEASE.md recommends customers pin a full SHA with the version in a comment", () => { + assert.match(readText("RELEASE.md"), /pin a full (commit )?SHA[\s\S]{0,200}@ # v1\.x/i); + }); }); diff --git a/skills/orca-review-action/SKILL.md b/skills/orca-review-action/SKILL.md index 1dff13d..7b42ed1 100644 --- a/skills/orca-review-action/SKILL.md +++ b/skills/orca-review-action/SKILL.md @@ -80,8 +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* → `"*"`. (Leaving the input out means `OWNER,MEMBER,COLLABORATOR` on a - public repo, so "everyone" has to be written explicitly.) +- *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. @@ -161,17 +165,22 @@ 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 -**`OrcaCode Review`** status, 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]=OrcaCode Review' + -f 'checks[][context]=review' ``` -Require the status, not the `review` job: the action writes it on the PR head after -every run, and 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). A skipped or -oversized review leaves it failing by default, so an unreviewed PR cannot merge. +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. @@ -252,9 +261,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 `OrcaCode Review` (and `review`, on older - installs) 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 8a7c9dd..806c215 100644 --- a/skills/orca-review-action/assets/workflow.yml +++ b/skills/orca-review-action/assets/workflow.yml @@ -22,7 +22,7 @@ permissions: contents: read pull-requests: write issues: write # clean/fallback PR comments - statuses: write # the verdict on the PR head — the check to make required + statuses: write # used from v1.7.0 (unreleased): the verdict on the PR head jobs: review: diff --git a/skills/orca-review-action/references/inputs.md b/skills/orca-review-action/references/inputs.md index 2e1c6e9..8c63ead 100644 --- a/skills/orca-review-action/references/inputs.md +++ b/skills/orca-review-action/references/inputs.md @@ -20,11 +20,11 @@ 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. Must be https. | +| `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's loopback). | | `github-token` | `${{ github.token }}` | Fetches the PR head, posts review comments, and reacts to a `/orcacode-review` command. | | `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. Only versions whose checksums this action release pins (`scripts/engine-pins.json`) install — any other value fails the run. | +| `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 @@ -40,15 +40,17 @@ empty string is valid and means "none". | Input | Default | What it does | | --- | --- | --- | -| `auto-review-authors` | unset: `OWNER,MEMBER,COLLABORATOR` on a public repo, everyone on a private one | Author-association allowlist for **automatic** reviews. `"*"` reviews everyone on any repo. 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. | | `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 — which is why an unset allowlist means maintainers only there. Put -a budget + alert on the key either way. The `/orcacode-review` command is honoured -only from `OWNER`, `MEMBER` or `COLLABORATOR`, by the action itself. +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 diff --git a/skills/orca-review-action/references/troubleshooting.md b/skills/orca-review-action/references/troubleshooting.md index 503d279..888ccb3 100644 --- a/skills/orca-review-action/references/troubleshooting.md +++ b/skills/orca-review-action/references/troubleshooting.md @@ -57,7 +57,7 @@ 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`, plus `statuses: write` for the `OrcaCode Review` status. | +| 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 @@ -132,6 +132,7 @@ green job is that. ## `/orcacode-review` did nothing -The action honours the command only on a pull request, only as the start of the -comment, and only from `OWNER`, `MEMBER` or `COLLABORATOR`. Anyone else's command -is a logged no-op. +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. diff --git a/workflows/orca-code-review.yml b/workflows/orca-code-review.yml index 431ea10..3a3ed82 100644 --- a/workflows/orca-code-review.yml +++ b/workflows/orca-code-review.yml @@ -7,9 +7,13 @@ # 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. Make the "OrcaCode Review" commit -# status required in branch protection — it is the one verdict an on-demand -# /orcacode-review run can also update on the PR head. +# 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 @@ -27,7 +31,7 @@ permissions: contents: read pull-requests: write issues: write # clean/fallback PR comments - statuses: write # the verdict on the PR head — the check to make required + statuses: write # used from v1.7.0 (unreleased): the verdict on the PR head jobs: review: From 9776a530fccbaa71c3addac3f0fe9bc0a44526a5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 06:57:50 +0000 Subject: [PATCH 21/28] docs: hold inputs.md to action.yml; say precisely what a comment can cancel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - inputs.md's judge-model default named a model; the action's default is "" (the router's recipe picks the judge). A new test compares every input row of inputs.md with action.yml — every input present, every stated default equal — so the table the skill tells agents to trust cannot drift again. - inputs.md's github-token row now says it writes the commit status on the PR head from v1.7.0 (needs statuses: write). - publish.yml's fetch-depth comment named a "v1 tag check" that is gone; it names the pinned-commit check that needs the history. - "comment runs never cancel anything" (shipped workflows, the installer's template, SECURITY.md, README): GitHub keeps one running and one pending job per concurrency group, so a newer comment replaces a comment run still pending, never a running one. Every such claim must now say so. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- .github/workflows/publish.yml | 2 +- README.md | 2 +- SECURITY.md | 6 +- bin/orcacode-review.mjs | 4 +- scripts/doc-drift.test.mjs | 117 ++++++++++++++++++ scripts/workflows.test.mjs | 4 +- skills/orca-review-action/assets/workflow.yml | 4 +- .../orca-review-action/references/inputs.md | 4 +- workflows/orca-code-review.yml | 4 +- 9 files changed, 137 insertions(+), 10 deletions(-) create mode 100644 scripts/doc-drift.test.mjs diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 1909775..590af59 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -43,7 +43,7 @@ jobs: steps: - 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@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0 with: diff --git a/README.md b/README.md index e7a7a17..2fd6e6c 100644 --- a/README.md +++ b/README.md @@ -284,7 +284,7 @@ Security hardening that changes what you may see. The installer, the example wor | 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 | — | | 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 review), 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) | +| 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). diff --git a/SECURITY.md b/SECURITY.md index ae40af6..0e62dc0 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -91,8 +91,10 @@ approval to run workflows from fork PRs" gate. The review key is wallet-metered. `COLLABORATOR` — whatever the workflow's `if:` says. The shipped workflows gate the same way in their `if:`, which also saves the runner. - **Cancelling**: concurrency is per job in the shipped workflows, and comment - runs have their own group that never cancels, so a comment cannot cancel an - in-flight review. + 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. diff --git a/bin/orcacode-review.mjs b/bin/orcacode-review.mjs index dcd3bf9..4f6640c 100755 --- a/bin/orcacode-review.mjs +++ b/bin/orcacode-review.mjs @@ -415,7 +415,9 @@ jobs: # 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 anything. + # 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' }} 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/workflows.test.mjs b/scripts/workflows.test.mjs index 041ec6c..9c87e38 100644 --- a/scripts/workflows.test.mjs +++ b/scripts/workflows.test.mjs @@ -8,7 +8,9 @@ // 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. +// 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"; diff --git a/skills/orca-review-action/assets/workflow.yml b/skills/orca-review-action/assets/workflow.yml index 806c215..dd99efd 100644 --- a/skills/orca-review-action/assets/workflow.yml +++ b/skills/orca-review-action/assets/workflow.yml @@ -31,7 +31,9 @@ jobs: # 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 anything. + # 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' }} diff --git a/skills/orca-review-action/references/inputs.md b/skills/orca-review-action/references/inputs.md index 8c63ead..2da153c 100644 --- a/skills/orca-review-action/references/inputs.md +++ b/skills/orca-review-action/references/inputs.md @@ -21,7 +21,7 @@ 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. From v1.7.0 (unreleased) it must be https (plain http is accepted only to this machine's loopback). | -| `github-token` | `${{ github.token }}` | Fetches the PR head, posts review comments, and reacts to a `/orcacode-review` command. | +| `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`. | | `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. From v1.7.0 (unreleased), only versions whose checksums the action pins (`scripts/engine-pins.json`) install — any other value fails the run. | @@ -70,7 +70,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 diff --git a/workflows/orca-code-review.yml b/workflows/orca-code-review.yml index 3a3ed82..91437a5 100644 --- a/workflows/orca-code-review.yml +++ b/workflows/orca-code-review.yml @@ -40,7 +40,9 @@ jobs: # 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 anything. + # 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' }} From cfb2c3ac22c2cb59a92f5c24e056662447f4c219 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 07:02:12 +0000 Subject: [PATCH 22/28] fix(identity): one funnel decides who the action is; an App token is never assumed to be github-actions[bot] MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When users.getAuthenticated failed — every installation token — the action assumed github-actions[bot], so a custom App never matched its own markers (a new notice on every push) and would have treated the workflow bot's comments as its own. Four steps carried a copy of the check. scripts/identity.mjs is now the one funnel: 1. the new `bot-login` input; 2. else the token's user (getAuthenticated: a personal token); 3. else github-actions[bot], only when github-token IS the job's own token (TOKEN_IS_JOB_TOKEN: inputs.github-token == github.token) — so the default case keeps working; 4. else unknown until the action's first comment or review in this run: guardGithub records the author GitHub reports back in $RUNNER_TEMP/cr-identity (cleared at the start and end of every run). Unknown matches nothing. The four marker steps use guard.isOwn (a derived test refuses any step that lists comments without it), and the reactions step clears the 👀 of the funnel's identity, not a guessed one. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- README.md | 3 +- SECURITY.md | 5 +- action.yml | 113 ++++++---- scripts/events.test.mjs | 9 +- scripts/identity.mjs | 85 ++++++++ scripts/marker-ownership.test.mjs | 193 ++++++++++++++++-- scripts/publish-guard.mjs | 17 +- .../orca-review-action/references/inputs.md | 1 + 8 files changed, 364 insertions(+), 62 deletions(-) create mode 100644 scripts/identity.mjs diff --git a/README.md b/README.md index 2fd6e6c..dbe9991 100644 --- a/README.md +++ b/README.md @@ -269,13 +269,14 @@ From v1.7.0 (unreleased), the action also writes an **`OrcaCode Review`** commit ## 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 two new ones; defaults that close a hole are new. +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 | — | | 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 | — | diff --git a/SECURITY.md b/SECURITY.md index 0e62dc0..14bbf78 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -46,7 +46,10 @@ 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), a + 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). diff --git a/action.yml b/action.yml index a039c54..23ae3df 100644 --- a/action.yml +++ b/action.yml @@ -61,6 +61,17 @@ inputs: 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 @@ -290,7 +301,7 @@ runs: "$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/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" @@ -311,6 +322,12 @@ runs: - name: Resolve PR refs id: pr uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7.1.0 + env: + IDENTITY: ${{ github.action_path }}/scripts/identity.mjs + 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: | @@ -355,20 +372,25 @@ runs: authorAssoc = pr.author_association || 'NONE'; } core.setOutput('run', 'true'); - // WHO THE ACTION POSTS AS, resolved once. The marker lookups below - // () only count a comment this identity - // wrote — otherwise anyone could plant a marker and have the action - // edit or delete THEIR comment. A personal token names its user; the - // default GITHUB_TOKEN has no user (the call is refused) and posts as - // github-actions[bot]. - let botLogin = 'github-actions[bot]'; - try { - const { data: me } = await github.rest.users.getAuthenticated(); - if (me && me.login) botLogin = me.login; - } catch (e) { - // An installation token: keep github-actions[bot]. + // 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', botLogin); + core.setOutput('bot_login', me.login); core.setOutput('base', base); core.setOutput('head_sha', headSha); core.setOutput('number', String(num)); @@ -732,11 +754,10 @@ runs: // 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. - // With no resolved identity nothing matches: post anew, edit nothing. - const mine = (c) => - Boolean(process.env.BOT_LOGIN) && Boolean(c && c.body) && - Boolean(c.user) && c.user.login === process.env.BOT_LOGIN; + // 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 }; @@ -907,11 +928,10 @@ runs: // 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. - // With no resolved identity nothing matches: post anew, edit nothing. - const mine = (c) => - Boolean(process.env.BOT_LOGIN) && Boolean(c && c.body) && - Boolean(c.user) && c.user.login === process.env.BOT_LOGIN; + // 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 }; @@ -1534,11 +1554,10 @@ runs: // 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. - // With no resolved identity nothing matches: post anew, edit nothing. - const mine = (c) => - Boolean(process.env.BOT_LOGIN) && Boolean(c && c.body) && - Boolean(c.user) && c.user.login === process.env.BOT_LOGIN; + // 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 { @@ -1955,11 +1974,10 @@ runs: // 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. - // With no resolved identity nothing matches: post anew, edit nothing. - const mine = (c) => - Boolean(process.env.BOT_LOGIN) && Boolean(c && c.body) && - Boolean(c.user) && c.user.login === process.env.BOT_LOGIN; + // 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'); @@ -2213,6 +2231,9 @@ runs: 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 }} @@ -2247,20 +2268,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) @@ -2333,7 +2356,7 @@ runs: "$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/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" diff --git a/scripts/events.test.mjs b/scripts/events.test.mjs index a316e9c..99c8743 100644 --- a/scripts/events.test.mjs +++ b/scripts/events.test.mjs @@ -21,7 +21,7 @@ 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 } from "./test-helpers/action-yaml.mjs"; +import { step, actionSteps, runBashStep, runGithubScript, fakeCore, ROOT } from "./test-helpers/action-yaml.mjs"; let dir; before(() => { @@ -46,7 +46,12 @@ async function resolve(eventName, 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 }); + 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; } 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/marker-ownership.test.mjs b/scripts/marker-ownership.test.mjs index ed1b258..97b3ce3 100644 --- a/scripts/marker-ownership.test.mjs +++ b/scripts/marker-ownership.test.mjs @@ -3,8 +3,19 @@ // 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, resolved once -// by "Resolve PR refs" (github-actions[bot] for the default GITHUB_TOKEN). +// 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"; @@ -12,7 +23,7 @@ import path from "node:path"; import { after, before, describe, test } from "node:test"; import assert from "node:assert/strict"; -import { step, runGithubScript, fakeCore, ROOT } from "./test-helpers/action-yaml.mjs"; +import { step, actionSteps, loadAction, runBashStep, stub, runGithubScript, fakeCore, ROOT } from "./test-helpers/action-yaml.mjs"; let dir; before(() => { @@ -126,7 +137,7 @@ describe("the stale-notice sweep only deletes the action's own comments", () => }); describe("Resolve PR refs resolves the token's identity once", () => { - async function resolveWith(getAuthenticated) { + async function resolveWith(getAuthenticated, env = { TOKEN_IS_JOB_TOKEN: "true", BOT_LOGIN_INPUT: "" }) { const { core, rec } = fakeCore(); const github = { rest: { @@ -144,20 +155,178 @@ describe("Resolve PR refs resolves the token's identity once", () => { repo: { owner: "acme", repo: "widgets" }, issue: { number: 1 }, }; - await runGithubScript(step("pr").with.script, { github, core, context }); + 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 default GITHUB_TOKEN (no user behind it) is github-actions[bot]", async () => { - const login = await resolveWith(async () => { - const e = new Error("Resource not accessible by integration"); - e.status = 403; - throw e; - }); - assert.equal(login, BOT); + 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/publish-guard.mjs b/scripts/publish-guard.mjs index 5600851..68146d2 100644 --- a/scripts/publish-guard.mjs +++ b/scripts/publish-guard.mjs @@ -31,6 +31,9 @@ // 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 @@ -44,6 +47,10 @@ // 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; @@ -398,6 +405,10 @@ export function redactSecrets(text, secrets = []) { 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"], @@ -426,7 +437,11 @@ export function guardGithub(github, { secrets = defaultSecrets() } = {}) { get(target, prop, recv) { const v = Reflect.get(target, prop, recv); if (typeof v === "function" && POSTING[name]?.includes(prop)) { - return (args, ...rest) => v.call(target, redactArgs(args, secrets), ...rest); + 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; }, diff --git a/skills/orca-review-action/references/inputs.md b/skills/orca-review-action/references/inputs.md index 2da153c..ffe2d4a 100644 --- a/skills/orca-review-action/references/inputs.md +++ b/skills/orca-review-action/references/inputs.md @@ -22,6 +22,7 @@ about the App from this file. | --- | --- | --- | | `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's loopback). | | `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. From v1.7.0 (unreleased), only versions whose checksums the action pins (`scripts/engine-pins.json`) install — any other value fails the run. | From 697d29a6cdbcb1b05c723d3f8c8480ec1ffb4ca0 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 07:06:46 +0000 Subject: [PATCH 23/28] fix(gateway-url): one judge of where the key may go; a refusal names the input and the fix MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The proxy refused a plain-http gateway with a message naming neither the input nor the fix — and it was the only place that looked: settings.mjs and report.mjs sent the same key, as a Bearer header, to whatever orcarouter-url said, plain http included, before the proxy ever ran. scripts/gateway-url.mjs is now the one judge (OrcaRouter's own rule for credentials in clear: only to this machine): https anywhere; plain http only to localhost, 127.0.0.0/8 or [::1] (WHATWG-normalised, so 127.1 counts and 127.0.0.1.nip.io, 0.0.0.0, ::ffff:… do not). It is asked: - by the first step that reads the URL (Fetch review settings), on every run, which fails with "::error::orcarouter-url must be https: … 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])"; - by the proxy (pinnedUpstream), the settings fetch and the run report, none of which sends the key where it refuses. The step fails if it is not handed the judge at all (`node ""` exits 0). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- README.md | 2 +- SECURITY.md | 8 +- action.yml | 10 + scripts/events.test.mjs | 2 + scripts/fact-proxy.mjs | 17 +- scripts/gateway-url.mjs | 55 ++++++ scripts/gateway-url.test.mjs | 176 ++++++++++++++++++ scripts/report.mjs | 7 + scripts/settings-wiring.test.mjs | 2 + scripts/settings.mjs | 9 +- .../orca-review-action/references/inputs.md | 2 +- 11 files changed, 276 insertions(+), 14 deletions(-) create mode 100644 scripts/gateway-url.mjs create mode 100644 scripts/gateway-url.test.mjs diff --git a/README.md b/README.md index dbe9991..cb0c911 100644 --- a/README.md +++ b/README.md @@ -281,7 +281,7 @@ Security hardening that changes what you may see. The installer, the example wor | 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 is refused (loopback excepted) | — | +| `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 | — | | Severity is never lowered | Duplicates keep the most severe tag; the judge cannot drop a P0 or a security finding | — | diff --git a/SECURITY.md b/SECURITY.md index 14bbf78..6f62438 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -148,8 +148,12 @@ Failure modes are closed: 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 for a loopback host). - Absolute-form, scheme-relative and backslash request targets are refused. + 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 diff --git a/action.yml b/action.yml index 23ae3df..fc2e6e9 100644 --- a/action.yml +++ b/action.yml @@ -506,6 +506,9 @@ runs: 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 }} @@ -522,6 +525,13 @@ runs: REPO_PRIVATE: ${{ steps.pr.outputs.repo_private }} 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 diff --git a/scripts/events.test.mjs b/scripts/events.test.mjs index 99c8743..48ed0ea 100644 --- a/scripts/events.test.mjs +++ b/scripts/events.test.mjs @@ -158,6 +158,8 @@ function settingsDecision({ authors = "", assoc = "NONE", isPrivate = "false", e 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", diff --git a/scripts/fact-proxy.mjs b/scripts/fact-proxy.mjs index 1011d07..e0e026f 100644 --- a/scripts/fact-proxy.mjs +++ b/scripts/fact-proxy.mjs @@ -104,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"; @@ -323,16 +324,14 @@ function retryDelayMs(retryIndex, retryAfter) { return BACKOFF_MS[Math.min(retryIndex, BACKOFF_MS.length - 1)]; } -const LOOPBACK_HOSTS = new Set(["127.0.0.1", "localhost", "[::1]", "::1"]); - -// The one upstream this proxy may talk to. https, or http to a loopback host. +// 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) { - const u = new URL(upstreamUrl); - if (u.protocol === "https:") return u; - if (u.protocol === "http:" && LOOPBACK_HOSTS.has(u.hostname)) return u; - throw new Error( - `fact-proxy: refusing upstream ${u.protocol}//${u.host} — the gateway must be https (plain http is allowed for a loopback host only)`, - ); + 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 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/report.mjs b/scripts/report.mjs index ef82fae..7a45abb 100644 --- a/scripts/report.mjs +++ b/scripts/report.mjs @@ -24,6 +24,7 @@ import fs from "node:fs"; import { countSeverities } from "./severity.mjs"; import { controlPlaneBase } from "./control-plane.mjs"; +import { gatewayUrlProblem } from "./gateway-url.mjs"; const TIMEOUT_MS = 5000; const RETRY_PAUSE_MS = 500; @@ -76,6 +77,12 @@ async function main() { }; if (opts.engineVersion) payload.engine_version = opts.engineVersion; + // The key goes out as a Bearer header: never in clear off this machine. + const refused = gatewayUrlProblem(opts.url); + if (refused) { + console.error(`report: skipped — not sending the key: ${refused}`); + return; + } let endpoint; try { endpoint = `${controlPlaneBase(opts.url)}/api/code_review/report`; diff --git a/scripts/settings-wiring.test.mjs b/scripts/settings-wiring.test.mjs index fa780eb..49eb78d 100644 --- a/scripts/settings-wiring.test.mjs +++ b/scripts/settings-wiring.test.mjs @@ -62,6 +62,7 @@ function runSettings({ written, inputBlockOn = "P0,P1", inputFixFirst = "P0,P1", ); 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", @@ -199,6 +200,7 @@ describe("end to end: the real settings fetch answering 403, 404, 500, or never" 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`, diff --git a/scripts/settings.mjs b/scripts/settings.mjs index 0947975..0f61d3d 100644 --- a/scripts/settings.mjs +++ b/scripts/settings.mjs @@ -48,6 +48,7 @@ import fs from "node:fs"; import { SEVERITIES } from "./severity.mjs"; import { controlPlaneBase } from "./control-plane.mjs"; +import { gatewayUrlProblem } from "./gateway-url.mjs"; // 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; @@ -153,7 +154,7 @@ const fallbackSettings = (status = "unavailable", cause = "unknown") => ({ ...DEFAULTS, unresolved: Object.keys(DEFAULTS), status, - cause: String(cause).replace(/[\r\n]+/g, " ").slice(0, 200), + cause: String(cause).replace(/[\r\n]+/g, " ").slice(0, 400), }); // A failed fetch, classified: status "no_settings" (the gateway said no — do @@ -209,6 +210,12 @@ async function fetchOnce(endpoint, key) { } 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)}`; diff --git a/skills/orca-review-action/references/inputs.md b/skills/orca-review-action/references/inputs.md index ffe2d4a..05723ba 100644 --- a/skills/orca-review-action/references/inputs.md +++ b/skills/orca-review-action/references/inputs.md @@ -20,7 +20,7 @@ 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. From v1.7.0 (unreleased) it must be https (plain http is accepted only to this machine's loopback). | +| `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. | From 14205166579a5aac2a64b28b6603b069743d8020 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 07:10:14 +0000 Subject: [PATCH 24/28] fix(guard): standard lockfiles do not count toward the diff-size limit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The hardened checkout's `* !diff` stops a fork's .gitattributes from hiding its change — and with it the `-diff` most repositories put on their lockfiles, so a dependency bump's megabytes of package-lock.json / go.sum counted toward max-diff-kb and ordinary PRs skipped (and, by default, failed) on size. scripts/guard-diff.mjs now produces the diff the size guard measures: the same merge-base range, minus files whose NAME is a standard lockfile's (package-lock.json, yarn.lock, pnpm-lock.yaml, bun.lockb, go.sum, Cargo.lock, poetry.lock, composer.lock, Gemfile.lock, at any depth) — never by an attribute the PR could set, and leaving a file out of the count can only make the guard review more. It fails open as before. The engine still reads the hardened checkout's full diff. The lockfiles left out are written to cr-lockfiles.json (cleared with the other run files), counted in the guard's outputs, and listed in the PR summary. Tested through the real Harden and guard steps on a scratch repository whose only large change is a lockfile (reviewed, not skipped), with look-alike names still counted and the engine-side diff unchanged. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- README.md | 2 +- SECURITY.md | 6 +- action.yml | 30 ++- scripts/guard-diff.mjs | 93 ++++++++++ scripts/guard-diff.test.mjs | 171 ++++++++++++++++++ scripts/summary-comment.mjs | 22 +++ .../orca-review-action/references/inputs.md | 2 +- 7 files changed, 314 insertions(+), 12 deletions(-) create mode 100644 scripts/guard-diff.mjs create mode 100644 scripts/guard-diff.test.mjs diff --git a/README.md b/README.md index cb0c911..f84bc55 100644 --- a/README.md +++ b/README.md @@ -283,7 +283,7 @@ Security hardening that changes what you may see. The installer, the example wor | `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 | — | +| 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) | diff --git a/SECURITY.md b/SECURITY.md index 6f62438..03b127b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -32,7 +32,11 @@ before the engine): 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; + 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. diff --git a/action.yml b/action.yml index fc2e6e9..d288084 100644 --- a/action.yml +++ b/action.yml @@ -301,7 +301,7 @@ runs: "$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-identity" \ + "$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" @@ -881,6 +881,8 @@ runs: 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 @@ -888,20 +890,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`, ); ' @@ -1971,6 +1977,8 @@ runs: 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 @@ -2071,6 +2079,10 @@ runs: 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. @@ -2366,7 +2378,7 @@ runs: "$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-identity" \ + "$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" 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/summary-comment.mjs b/scripts/summary-comment.mjs index ba0e3ce..8209c5c 100644 --- a/scripts/summary-comment.mjs +++ b/scripts/summary-comment.mjs @@ -4,6 +4,10 @@ // node summary-comment.mjs --tier cheap|strong --push // --gate pass|blocked [--prev ] // [--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 @@ -82,6 +86,7 @@ for (let i = 0; i < rest.length; i += 1) { 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 @@ -206,4 +211,21 @@ if (skipped.excluded.length) { 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/skills/orca-review-action/references/inputs.md b/skills/orca-review-action/references/inputs.md index 05723ba..9a95486 100644 --- a/skills/orca-review-action/references/inputs.md +++ b/skills/orca-review-action/references/inputs.md @@ -57,7 +57,7 @@ command too, and an unset allowlist means maintainers only on a public repo. | 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. | From 04ed39165b44428fd75976d96d2b887efc2472cb Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 07:11:50 +0000 Subject: [PATCH 25/28] fix(events): run on an explicit allowlist of events; refuse the rest, successfully, saying why MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Only issue_comment went through the comment refusal; every other event fell into the pull_request* auto-review gate, which is keyed on the PR's 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 left a review comment (and push / workflow_dispatch reached pulls.get with no PR number). "Resolve PR refs" now runs only on pull_request / pull_request_target (opened, synchronize, reopened, ready_for_review, edited — edited still only on a base change) and issue_comment (created). Anything else, including an edited or deleted comment, is run=false with a notice naming the event and the allowlist; nothing later runs and the job stays green. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- README.md | 1 + SECURITY.md | 6 ++++ action.yml | 25 ++++++++++++++++ scripts/events.test.mjs | 52 +++++++++++++++++++++++++++++++++ scripts/pinned-release.test.mjs | 2 ++ 5 files changed, 86 insertions(+) diff --git a/README.md b/README.md index f84bc55..86a5ff0 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,7 @@ Security hardening that changes what you may see. The installer, the example wor | 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 | — | +| 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 | — | diff --git a/SECURITY.md b/SECURITY.md index 03b127b..cf3dd38 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -87,6 +87,12 @@ On a **public** repository the recommended `pull_request_target` trigger runs th 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 diff --git a/action.yml b/action.yml index d288084..956f063 100644 --- a/action.yml +++ b/action.yml @@ -310,6 +310,11 @@ runs: # 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 @@ -339,6 +344,26 @@ runs: 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)`, + ); + } if (context.eventName === 'issue_comment') { const c = payload.comment || {}; const body = String(c.body || '').toLowerCase(); diff --git a/scripts/events.test.mjs b/scripts/events.test.mjs index 48ed0ea..dac1cb6 100644 --- a/scripts/events.test.mjs +++ b/scripts/events.test.mjs @@ -127,6 +127,58 @@ describe("Resolve PR refs: pull_request_target events", () => { }); }); +// 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(); diff --git a/scripts/pinned-release.test.mjs b/scripts/pinned-release.test.mjs index 435bdea..10e4257 100644 --- a/scripts/pinned-release.test.mjs +++ b/scripts/pinned-release.test.mjs @@ -140,6 +140,8 @@ const UNRELEASED_BEHAVIOURS = [ [/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 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"], ]; From cc7f3c0bb17a1f5efef4c092087aa52d42c0bba3 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 07:17:35 +0000 Subject: [PATCH 26/28] fix(spend): on a push to a fork PR, judge the pusher, not only the author MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit author_association is the PR author's. On a maintainer-opened PR whose head lives in an outsider's fork, every push the outsider made was a `synchronize` the author gate waved through — an auto-review on the workspace's wallet, on a public repository, triggered by someone the gate never looked at. "Resolve PR refs" now, on `synchronize` from a head repository other than the base and pushed by someone other than the PR's author, asks GitHub that pusher's permission here (repos.getCollaboratorPermissionLevel) and outputs pusher / pusher_trusted (true | false | n/a; false when GitHub cannot say). The settings gate auto-reviews only a trusted pusher — unless auto-review-authors lets everyone through anyway ("*", or unset on a private repo), where the pusher could have opened a PR of their own. A refusal is a skip, reported on the head-SHA status as "Not reviewed"; the author pushing to their own fork, a same-repo head, and events that move no code are not asked. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- README.md | 1 + SECURITY.md | 7 + action.yml | 45 ++++- scripts/pinned-release.test.mjs | 2 + scripts/pusher.test.mjs | 185 ++++++++++++++++++ .../orca-review-action/references/inputs.md | 2 +- 6 files changed, 240 insertions(+), 2 deletions(-) create mode 100644 scripts/pusher.test.mjs diff --git a/README.md b/README.md index 86a5ff0..c901212 100644 --- a/README.md +++ b/README.md @@ -278,6 +278,7 @@ Security hardening that changes what you may see. The installer, the example wor | 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 | — | diff --git a/SECURITY.md b/SECURITY.md index cf3dd38..5d4db51 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -98,6 +98,13 @@ approval to run workflows from fork PRs" gate. The review key is wallet-metered. 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 diff --git a/action.yml b/action.yml index 956f063..ae3f15f 100644 --- a/action.yml +++ b/action.yml @@ -380,8 +380,9 @@ runs: return stop('the pull request was edited without changing its base'); } - let base, headSha, num, isDraft, authorAssoc; + let base, headSha, num, isDraft, authorAssoc, prData; if (context.eventName === 'pull_request_target') { + prData = payload.pull_request; base = payload.pull_request.base.ref; headSha = payload.pull_request.head.sha; num = payload.pull_request.number; @@ -392,11 +393,44 @@ runs: 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'; } 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 headRepo = prData && prData.head && prData.head.repo ? prData.head.repo.full_name : null; + const baseRepo = `${context.repo.owner}/${context.repo.repo}`; + const author = prData && prData.user ? prData.user.login : ''; + const sender = payload.sender ? payload.sender.login : ''; + if (context.eventName !== 'issue_comment' && payload.action === 'synchronize' && + String(headRepo || '').toLowerCase() !== baseRepo.toLowerCase() && 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 @@ -548,6 +582,10 @@ runs: 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 @@ -614,6 +652,11 @@ runs: # 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 diff --git a/scripts/pinned-release.test.mjs b/scripts/pinned-release.test.mjs index 10e4257..cb3745a 100644 --- a/scripts/pinned-release.test.mjs +++ b/scripts/pinned-release.test.mjs @@ -140,6 +140,8 @@ const UNRELEASED_BEHAVIOURS = [ [/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 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. diff --git a/scripts/pusher.test.mjs b/scripts/pusher.test.mjs new file mode 100644 index 0000000..954ce11 --- /dev/null +++ b/scripts/pusher.test.mjs @@ -0,0 +1,185 @@ +// CR-11: the author is not the pusher. +// +// author_association is the PR AUTHOR's. On a maintainer-opened PR whose head +// lives in an outsider's fork, every push the outsider makes is a +// `synchronize` the author gate waves through — the outsider spends the +// workspace's wallet on a public repository while the gate looks at the +// maintainer. +// +// Now, on `synchronize`, when the head repository is not the base repository +// and the push was made by someone other than the PR's author, "Resolve PR +// refs" asks GitHub that person's permission on this repository +// (repos.getCollaboratorPermissionLevel). The settings gate then auto-reviews +// only if they can write (write, maintain, admin) — unless auto-review-authors +// lets everyone through anyway, in which case nobody is spending more than +// they could by opening a PR of their own. A refusal is a skip, which the +// commit status reports as "Not reviewed". A maintainer's /orcacode-review +// still reviews the head (see comment-sha.test.mjs for how that is pinned). + +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(), "pusher-")); +}); +after(() => fs.rmSync(dir, { recursive: true, force: true })); + +const pr = ({ head = "outsider/widgets", author = "maint", assoc = "MEMBER" } = {}) => ({ + number: 7, + user: { login: author }, + author_association: assoc, + draft: false, + base: { ref: "main", repo: { full_name: "acme/widgets" } }, + head: { sha: "headsha", repo: head ? { full_name: head } : null }, +}); + +async function resolve({ action = "synchronize", sender = "outsider", prOpts, permission = "read", fail = false, event = "pull_request_target" } = {}) { + const asked = []; + const github = { + rest: { + pulls: { get: async () => ({ data: pr(prOpts) }) }, + users: { getAuthenticated: async () => { throw Object.assign(new Error("no"), { status: 403 }); } }, + repos: { + getCollaboratorPermissionLevel: async (args) => { + asked.push(args); + if (fail) throw Object.assign(new Error("Not Found"), { status: 404 }); + return { data: { permission, role_name: permission } }; + }, + }, + }, + }; + const { core, rec } = fakeCore(); + await runGithubScript(step("pr").with.script, { + github, + core, + context: { + eventName: event, + payload: { action, sender: sender ? { login: sender } : undefined, pull_request: pr(prOpts), repository: { default_branch: "main", private: false } }, + repo: { owner: "acme", repo: "widgets" }, + issue: { number: 7 }, + }, + env: { IDENTITY: path.join(ROOT, "scripts", "identity.mjs"), TOKEN_IS_JOB_TOKEN: "true", BOT_LOGIN_INPUT: "" }, + }); + return { rec, asked }; +} + +describe("Resolve PR refs: who pushed, and can they write here", () => { + test("an outsider's push to a maintainer's PR from the outsider's fork -> not trusted", async () => { + const { rec, asked } = await resolve({ sender: "outsider", permission: "read" }); + assert.equal(rec.outputs.run, "true"); + assert.equal(rec.outputs.pusher, "outsider"); + assert.equal(rec.outputs.pusher_trusted, "false"); + assert.deepEqual(asked, [{ owner: "acme", repo: "widgets", username: "outsider" }]); + }); + + for (const permission of ["write", "maintain", "admin"]) { + test(`a pusher with ${permission} -> trusted`, async () => { + assert.equal((await resolve({ sender: "maint2", permission })).rec.outputs.pusher_trusted, "true"); + }); + } + + for (const permission of ["read", "triage", "none"]) { + test(`a pusher with ${permission} -> not trusted`, async () => { + assert.equal((await resolve({ sender: "someone", permission })).rec.outputs.pusher_trusted, "false"); + }); + } + + test("GitHub cannot say -> not trusted (fail closed)", async () => { + assert.equal((await resolve({ sender: "someone", fail: true })).rec.outputs.pusher_trusted, "false"); + }); + + test("the author pushing to their own fork is the author's gate's business -> not asked", async () => { + const { rec, asked } = await resolve({ sender: "maint", prOpts: { author: "maint" } }); + assert.equal(rec.outputs.pusher_trusted, "n/a"); + assert.deepEqual(asked, []); + }); + + test("a same-repository head -> not asked (only people with push access can push there)", async () => { + const { rec, asked } = await resolve({ sender: "outsider", prOpts: { head: "acme/widgets" } }); + assert.equal(rec.outputs.pusher_trusted, "n/a"); + assert.deepEqual(asked, []); + }); + + test("a deleted head repository counts as a fork", async () => { + assert.equal((await resolve({ sender: "outsider", prOpts: { head: null } })).rec.outputs.pusher_trusted, "false"); + }); + + for (const action of ["opened", "reopened", "ready_for_review"]) { + test(`${action} moves no code -> not asked`, async () => { + const { rec, asked } = await resolve({ action, sender: "outsider" }); + assert.equal(rec.outputs.pusher_trusted, "n/a"); + assert.deepEqual(asked, []); + }); + } + + test("plain pull_request is judged the same", async () => { + assert.equal((await resolve({ event: "pull_request", sender: "outsider" })).rec.outputs.pusher_trusted, "false"); + }); +}); + +function gate({ trusted, pusher = "outsider", authors = "", isPrivate = "false", assoc = "MEMBER", 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, + PUSHER: pusher, + PUSHER_TRUSTED: trusted, + 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("the settings gate holds the pusher to the allowlist too", () => { + test("an untrusted pusher on a public repo -> skip, naming them", () => { + const o = gate({ trusted: "false" }); + assert.equal(o.decision, "skip"); + assert.match(o.reason, /outsider/); + assert.match(o.reason, /write/); + }); + + test("a trusted pusher, or no question asked -> review", () => { + assert.equal(gate({ trusted: "true" }).decision, "review"); + assert.equal(gate({ trusted: "n/a" }).decision, "review"); + assert.equal(gate({ trusted: "" }).decision, "review", "a step that never ran says nothing either way"); + }); + + test('auto-review-authors that lets everyone through ("*", or unset on a private repo) does not ask', () => { + assert.equal(gate({ trusted: "false", authors: "*" }).decision, "review"); + assert.equal(gate({ trusted: "false", isPrivate: "true" }).decision, "review"); + }); + + test("an explicit narrower list asks", () => { + assert.equal(gate({ trusted: "false", authors: "OWNER,MEMBER,COLLABORATOR,CONTRIBUTOR" }).decision, "skip"); + }); + + test("the comment command is not an automatic review: never asked here", () => { + assert.equal(gate({ trusted: "false", event: "issue_comment" }).decision, "review"); + }); + + test("the step is handed the pusher's verdict", () => { + const env = step("settings").env; + assert.equal(env.PUSHER, "${{ steps.pr.outputs.pusher }}"); + assert.equal(env.PUSHER_TRUSTED, "${{ steps.pr.outputs.pusher_trusted }}"); + }); +}); diff --git a/skills/orca-review-action/references/inputs.md b/skills/orca-review-action/references/inputs.md index 9a95486..9a7d11d 100644 --- a/skills/orca-review-action/references/inputs.md +++ b/skills/orca-review-action/references/inputs.md @@ -42,7 +42,7 @@ empty string is valid and means "none". | Input | Default | What it does | | --- | --- | --- | | `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. | +| | | 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. | From 37a139734064dd5b0a2f09756b7e8b08f0b68286 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 07:20:33 +0000 Subject: [PATCH 27/28] fix(comments): a fork PR's /orcacode-review must name the commit, and it must still be the head MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 — the maintainer approves spend on code they never saw, and the verdict lands on it. When the PR's head repository is not the base repository (a fork, or a deleted fork), "Resolve PR refs" now requires the command to name the head commit — `/orcacode-review `, 7 to 40 hex characters, any spelling of the command — and runs only while that commit is still the head; the checkout then pins the full SHA. Otherwise it answers on the PR, through the publish funnel, with the current head and the exact command to use, and runs nothing (a successful no-op). A same-repository PR keeps the bare command; a commit it names is held to the same check. The outsider refusal still comes first and posts nothing. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- README.md | 2 +- SECURITY.md | 7 +- action.yml | 60 ++++++- scripts/comment-sha.test.mjs | 147 ++++++++++++++++++ scripts/events.test.mjs | 6 +- scripts/pinned-release.test.mjs | 2 + skills/orca-review-action/SKILL.md | 4 + .../references/troubleshooting.md | 5 +- 8 files changed, 224 insertions(+), 9 deletions(-) create mode 100644 scripts/comment-sha.test.mjs diff --git a/README.md b/README.md index c901212..ec37acb 100644 --- a/README.md +++ b/README.md @@ -251,7 +251,7 @@ Comment on any PR: 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. +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. --- diff --git a/SECURITY.md b/SECURITY.md index 5d4db51..82726a2 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -109,7 +109,12 @@ approval to run workflows from fork PRs" gate. The review key is wallet-metered. 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. + 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 diff --git a/action.yml b/action.yml index ae3f15f..69f07a8 100644 --- a/action.yml +++ b/action.yml @@ -329,6 +329,12 @@ runs: 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. @@ -364,13 +370,17 @@ runs: `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 isCommand = COMMANDS.some((cmd) => body.startsWith(cmd) && /^(\s|$)/.test(body.slice(cmd.length))); + 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)) { @@ -398,6 +408,49 @@ runs: 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, @@ -409,12 +462,9 @@ runs: // "n/a" = nothing to ask; "false" also when GitHub cannot say. let pusher = ''; let pusherTrusted = 'n/a'; - const headRepo = prData && prData.head && prData.head.repo ? prData.head.repo.full_name : null; - const baseRepo = `${context.repo.owner}/${context.repo.repo}`; const author = prData && prData.user ? prData.user.login : ''; const sender = payload.sender ? payload.sender.login : ''; - if (context.eventName !== 'issue_comment' && payload.action === 'synchronize' && - String(headRepo || '').toLowerCase() !== baseRepo.toLowerCase() && sender !== author) { + if (context.eventName !== 'issue_comment' && payload.action === 'synchronize' && fromFork && sender !== author) { pusher = sender || '(unknown)'; pusherTrusted = 'false'; if (sender) { 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/events.test.mjs b/scripts/events.test.mjs index dac1cb6..f49f0ee 100644 --- a/scripts/events.test.mjs +++ b/scripts/events.test.mjs @@ -36,7 +36,11 @@ async function resolve(eventName, payload) { const github = { rest: { pulls: { - get: async () => ({ data: { base: { ref: "main" }, head: { sha: "headsha" }, draft: false, author_association: "NONE" } }), + // 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" }, + }), }, }, }; diff --git a/scripts/pinned-release.test.mjs b/scripts/pinned-release.test.mjs index cb3745a..311cfd9 100644 --- a/scripts/pinned-release.test.mjs +++ b/scripts/pinned-release.test.mjs @@ -140,6 +140,8 @@ const UNRELEASED_BEHAVIOURS = [ [/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. diff --git a/skills/orca-review-action/SKILL.md b/skills/orca-review-action/SKILL.md index 7b42ed1..110b928 100644 --- a/skills/orca-review-action/SKILL.md +++ b/skills/orca-review-action/SKILL.md @@ -246,6 +246,10 @@ account for most reports: 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 diff --git a/skills/orca-review-action/references/troubleshooting.md b/skills/orca-review-action/references/troubleshooting.md index 888ccb3..9d97bd7 100644 --- a/skills/orca-review-action/references/troubleshooting.md +++ b/skills/orca-review-action/references/troubleshooting.md @@ -135,4 +135,7 @@ green job is that. 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. +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. From 91ccf41c00da928966ab3614d771768fdbfd7725 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 31 Oct 2026 07:22:14 +0000 Subject: [PATCH 28/28] docs: the action's header and the skill's troubleshooting list match what changed action.yml's posture summary names the event allowlist, the fork-command commit pin, the pusher check, the identity funnel and the gateway-URL judge; the skill no longer counts its troubleshooting list ("the four") after a fifth entry joined it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_015vkCaUqAcSVZ9vVBuuYg3k --- action.yml | 9 +++++++-- skills/orca-review-action/SKILL.md | 2 +- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/action.yml b/action.yml index 69f07a8..749c1d1 100644 --- a/action.yml +++ b/action.yml @@ -30,8 +30,13 @@ # (scripts/report.mjs) posts severity counts — never code — to the OrcaRouter # control plane after the gate. # -# Security posture (SECURITY.md has the detail): a comment trigger runs only for -# a maintainer's review command, checked here and not only in the workflow; the +# 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 diff --git a/skills/orca-review-action/SKILL.md b/skills/orca-review-action/SKILL.md index 110b928..1ddf978 100644 --- a/skills/orca-review-action/SKILL.md +++ b/skills/orca-review-action/SKILL.md @@ -238,7 +238,7 @@ 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: - **"Review skipped" notice** — the PR is a draft and `trigger` is