Merge branch 'main' into codex/file-lock-reclaim-guard

This commit is contained in:
azizur100389 2026-09-09 10:06:33 +01:00 • committed by GitHub
commit f22905a488
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 742 additions and 107 deletions

View file

@ -0,0 +1,274 @@
// Resolve the open PR for a trusted workflow_run consumer.
//
// Shared by commit-fork-prebuilds.yml and pr-autofix-publish.yml.
// workflow_run.pull_requests[] is empty on fork PRs, and
// GET /repos/{base}/commits/{sha}/pulls is also empty because the fork head
// commit is not in the base repo's commit graph. The authoritative lookup is
// GET /repos/{base}/pulls?head={owner}:{branch}&state=open using
// workflow_run.head_repository + workflow_run.head_branch (server-controlled).
// That same query works for same-repo PRs (owner is the base repo owner).
//
// The current PR tip may have moved past the SHA the producer built; that is
// not an identity failure — the caller decides whether to lease-push or just
// comment. Two open PRs from the same fork head (same owner:branch into this
// repo) are an identity failure: artifact pr_number is untrusted and must not
// pick among them. Set SCHEMA_PATTERN to the artifact schema allowlist
// (defaults to the tree-sitter prebuild schema).
'use strict';
const fs = require('node:fs');
const { spawnSync } = require('node:child_process');
const SCHEMA_PATTERN = /^gitnexus\.ts-prebuild\/v[0-9]+$/;
const IDENTITY_PATTERNS = {
pr_number: /^[0-9]+$/,
head_sha: /^[0-9a-f]{40}$/,
head_ref: /^[A-Za-z0-9._/-]+$/,
repo: /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/,
};
function allowlistField(key, value, pattern) {
const text = value == null ? '' : String(value);
if (!text || !pattern.test(text)) {
throw new Error(`metadata.${key} failed allowlist (got: ${JSON.stringify(text)})`);
}
return text;
}
function forkHeadOwner(headRepo) {
const slash = headRepo.indexOf('/');
if (slash <= 0 || slash === headRepo.length - 1) {
throw new Error(`head_repo must be owner/name (got: ${JSON.stringify(headRepo)})`);
}
return headRepo.slice(0, slash);
}
function compileSchemaPattern(value) {
if (value instanceof RegExp) return value;
if (typeof value === 'string' && value.length > 0) {
try {
return new RegExp(value);
} catch {
throw new Error('SCHEMA_PATTERN is not a valid regular expression');
}
}
return SCHEMA_PATTERN;
}
function allowlistMetadata(raw, schemaPattern) {
const parsed = typeof raw === 'string' ? JSON.parse(raw) : raw;
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
throw new Error('metadata.json must be an object');
}
return {
schema: allowlistField('schema', parsed.schema, compileSchemaPattern(schemaPattern)),
pr_number: allowlistField('pr_number', parsed.pr_number, IDENTITY_PATTERNS.pr_number),
head_sha: allowlistField('head_sha', parsed.head_sha, IDENTITY_PATTERNS.head_sha),
head_ref: allowlistField('head_ref', parsed.head_ref, IDENTITY_PATTERNS.head_ref),
head_repo: allowlistField('head_repo', parsed.head_repo, IDENTITY_PATTERNS.repo),
base_repo: allowlistField('base_repo', parsed.base_repo, IDENTITY_PATTERNS.repo),
};
}
function allowlistAuthority(authority) {
return {
head_sha: allowlistField('head_sha', authority.head_sha, IDENTITY_PATTERNS.head_sha),
head_repo: allowlistField('head_repo', authority.head_repo, IDENTITY_PATTERNS.repo),
head_branch: allowlistField('head_ref', authority.head_branch, IDENTITY_PATTERNS.head_ref),
base_repo: allowlistField('base_repo', authority.base_repo, IDENTITY_PATTERNS.repo),
};
}
function verifyArtifactAgainstWorkflowRun(meta, authority) {
if (meta.head_sha !== authority.head_sha) {
throw new Error(
`Artifact head_sha (${meta.head_sha}) != workflow_run.head_sha (${authority.head_sha}) — refusing.`,
);
}
if (meta.head_repo !== authority.head_repo) {
throw new Error(
`Artifact head_repo (${meta.head_repo}) != workflow_run.head_repository (${authority.head_repo}) — refusing.`,
);
}
if (meta.base_repo !== authority.base_repo) {
throw new Error('Artifact base_repo does not match $GITHUB_REPOSITORY — refusing.');
}
if (meta.head_ref !== authority.head_branch) {
throw new Error(
`Artifact head_ref (${meta.head_ref}) != workflow_run.head_branch (${authority.head_branch}) — refusing.`,
);
}
}
function matchOpenPullsFromForkHead(pulls, { headRepo, headBranch, baseRepo }) {
if (!Array.isArray(pulls)) {
throw new Error('GitHub pulls?head= lookup returned a non-array');
}
return pulls.filter((pr) => {
return (
pr &&
pr.state === 'open' &&
Number.isInteger(pr.number) &&
pr.head &&
pr.head.repo &&
pr.head.repo.full_name === headRepo &&
pr.head.ref === headBranch &&
pr.base &&
pr.base.repo &&
pr.base.repo.full_name === baseRepo
);
});
}
function resolveVerifiedPullRequest({ meta, authority, pulls, schemaPattern }) {
const cleanMeta = allowlistMetadata(meta, schemaPattern);
const cleanAuthority = allowlistAuthority(authority);
verifyArtifactAgainstWorkflowRun(cleanMeta, cleanAuthority);
const matched = matchOpenPullsFromForkHead(pulls, {
headRepo: cleanAuthority.head_repo,
headBranch: cleanAuthority.head_branch,
baseRepo: cleanAuthority.base_repo,
});
if (matched.length === 0) {
throw new Error(
`No open PR from ${cleanAuthority.head_repo}:${cleanAuthority.head_branch} targeting ${cleanAuthority.base_repo} — refusing.`,
);
}
// Artifact pr_number is untrusted. Do not use it to pick among several open
// PRs that share this fork head (same owner:branch into this repo, different
// base branches). Fail closed unless GitHub-controlled fields leave exactly one.
if (matched.length !== 1) {
throw new Error(
`Ambiguous open PRs from ${cleanAuthority.head_repo}:${cleanAuthority.head_branch} targeting ${cleanAuthority.base_repo} (${matched
.map((pr) => pr.number)
.join(',')}) — refusing.`,
);
}
const chosen = matched[0];
const expected = Number(cleanMeta.pr_number);
if (chosen.number !== expected) {
throw new Error(
`Artifact pr_number (${cleanMeta.pr_number}) is not the open PR(s) from this fork head (${chosen.number}) — refusing.`,
);
}
const currentHeadSha = typeof chosen.head.sha === 'string' ? chosen.head.sha : '';
return {
pr_number: String(chosen.number),
head_ref: cleanAuthority.head_branch,
head_sha: cleanAuthority.head_sha,
head_repo: cleanAuthority.head_repo,
current_head_sha: currentHeadSha,
branch_moved: Boolean(currentHeadSha && currentHeadSha !== cleanAuthority.head_sha),
};
}
function flattenGhListPages(parsed) {
if (!Array.isArray(parsed)) {
throw new Error('GitHub pulls?head= lookup returned a non-array');
}
if (parsed.length === 0) return parsed;
if (parsed.every((page) => Array.isArray(page))) {
return parsed.flat();
}
return parsed;
}
function listOpenPullsByHead({ ghRepo, headOwner, headBranch, runGh }) {
const run = runGh || ((args) => spawnSync('gh', args, { encoding: 'utf8' }));
const result = run([
'api',
'--paginate',
'--slurp',
'-X',
'GET',
`repos/${ghRepo}/pulls`,
'-f',
'state=open',
'-f',
`head=${headOwner}:${headBranch}`,
]);
if (result.status !== 0) {
const err = (result.stderr || result.stdout || '').trim();
throw new Error(`GitHub pulls?head= lookup failed: ${err || `exit ${result.status}`}`);
}
const stdout = (result.stdout || '').trim();
if (!stdout) {
throw new Error('GitHub pulls?head= lookup returned an empty body');
}
let parsed;
try {
parsed = JSON.parse(stdout);
} catch {
throw new Error('GitHub pulls?head= lookup returned non-JSON');
}
return flattenGhListPages(parsed);
}
function main() {
const schemaPattern = compileSchemaPattern(process.env.SCHEMA_PATTERN);
const raw = fs.readFileSync(process.env.META_PATH, 'utf8');
const meta = allowlistMetadata(raw, schemaPattern);
const authority = allowlistAuthority({
head_sha: process.env.WF_HEAD_SHA,
head_repo: process.env.WF_HEAD_REPO,
head_branch: process.env.WF_HEAD_BRANCH,
base_repo: process.env.GH_REPO,
});
const pulls = listOpenPullsByHead({
ghRepo: authority.base_repo,
headOwner: forkHeadOwner(authority.head_repo),
headBranch: authority.head_branch,
});
const verified = resolveVerifiedPullRequest({ meta, authority, pulls, schemaPattern });
if (verified.branch_moved) {
console.log(
`PR head moved to ${verified.current_head_sha}; delivering against built SHA ${verified.head_sha} (lease will refuse if the branch moved).`,
);
}
console.log(
`Verified identity: PR=${verified.pr_number} head_sha=${verified.head_sha} head_repo=${verified.head_repo} head_ref=${verified.head_ref}.`,
);
const out = process.env.GITHUB_OUTPUT;
if (!out) {
throw new Error('GITHUB_OUTPUT is unset');
}
fs.appendFileSync(
out,
[
`pr_number=${verified.pr_number}`,
`head_ref=${verified.head_ref}`,
`head_sha=${verified.head_sha}`,
`head_repo=${verified.head_repo}`,
].join('\n') + '\n',
);
}
if (require.main === module) {
try {
main();
} catch (err) {
console.error(`::error::${err instanceof Error ? err.message : String(err)}`);
process.exit(1);
}
}
module.exports = {
SCHEMA_PATTERN,
IDENTITY_PATTERNS,
allowlistField,
compileSchemaPattern,
allowlistMetadata,
allowlistAuthority,
forkHeadOwner,
verifyArtifactAgainstWorkflowRun,
matchOpenPullsFromForkHead,
flattenGhListPages,
resolveVerifiedPullRequest,
listOpenPullsByHead,
main,
};

View file

@ -135,68 +135,53 @@ jobs:
# workflow_run event. The allowlist above only proves the fields are
# well-formed — not that they refer to the PR/SHA that actually triggered
# us. A fork-controlled build could mutate metadata.json to reference
# another PR/SHA and redirect our write-scoped push. Authority sources are
# all server-controlled: workflow_run.head_sha, head_repository.full_name,
# and pull_requests[].number (empty on forks -> commits/{sha}/pulls).
# another PR/SHA and redirect our write-scoped push.
#
# This job's `if:` already restricts to forks, so pull_requests[] is empty
# by design and GET /repos/{base}/commits/{sha}/pulls is also empty (the
# fork commit is not in the base graph). Authority is workflow_run.head_sha
# + head_repository.full_name + head_branch, resolved via
# pulls?head={owner}:{branch}. The script comes from THIS default-branch
# checkout (the same trust anchor as this workflow file).
- name: Checkout identity verifier
if: steps.meta.outputs.deliver == 'true'
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
sparse-checkout: .github/scripts/verify-workflow-run-pr-identity.cjs
sparse-checkout-cone-mode: false
path: trusted
- name: Verify metadata against workflow_run authority
id: verify
if: steps.meta.outputs.deliver == 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
META_PR_NUMBER: ${{ steps.meta.outputs.pr_number }}
META_HEAD_SHA: ${{ steps.meta.outputs.head_sha }}
META_HEAD_REPO: ${{ steps.meta.outputs.head_repo }}
META_PATH: meta-in/metadata.json
SCHEMA_PATTERN: '^gitnexus\.ts-prebuild/v[0-9]+$'
WF_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
WF_HEAD_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
WF_PR_NUMBERS: ${{ toJSON(github.event.workflow_run.pull_requests.*.number) }}
WF_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
shell: bash
run: |
set -euo pipefail
# 1) head_sha must match exactly — the commit GitHub ran the producer against.
if [ "${META_HEAD_SHA}" != "${WF_HEAD_SHA}" ]; then
echo "::error::Artifact head_sha (${META_HEAD_SHA}) != workflow_run.head_sha (${WF_HEAD_SHA}) — refusing."
exit 1
fi
# 2) head_repo must match exactly.
if [ "${META_HEAD_REPO}" != "${WF_HEAD_REPO}" ]; then
echo "::error::Artifact head_repo (${META_HEAD_REPO}) != workflow_run.head_repository (${WF_HEAD_REPO}) — refusing."
exit 1
fi
# 3) pr_number must reference an open PR with this head SHA. Forks have
# an empty pull_requests[] by design — fall back to commits/{sha}/pulls.
allowed_numbers=$(jq -c '.' <<< "${WF_PR_NUMBERS}")
if [ "${allowed_numbers}" = "[]" ]; then
echo "workflow_run.pull_requests empty (fork) — using commits/{sha}/pulls."
allowed_numbers=$(gh api "repos/${GH_REPO}/commits/${WF_HEAD_SHA}/pulls" \
--jq '[.[] | select(.state == "open") | .number]' 2>/dev/null || echo "[]")
if [ "${allowed_numbers}" = "[]" ]; then
echo "::error::No open PR for head ${WF_HEAD_SHA} — refusing."
exit 1
fi
fi
if ! jq -e --argjson n "${META_PR_NUMBER}" 'index($n) != null' <<< "${allowed_numbers}" >/dev/null; then
echo "::error::Artifact pr_number (${META_PR_NUMBER}) not in authoritative list (${allowed_numbers}) — refusing."
exit 1
fi
echo "Verified identity: PR=${META_PR_NUMBER} head_sha=${META_HEAD_SHA} head_repo=${META_HEAD_REPO}."
run: node trusted/.github/scripts/verify-workflow-run-pr-identity.cjs
# Pinned to v6.0.3 (same SHA used by build-tree-sitter-prebuilds.yml).
# persist-credentials: false — push auth is provided inline at push time,
# never written to .git/config on disk.
- name: Checkout fork PR head
if: steps.meta.outputs.deliver == 'true'
if: steps.meta.outputs.deliver == 'true' && steps.verify.outcome == 'success'
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
repository: ${{ steps.meta.outputs.head_repo }}
ref: ${{ steps.meta.outputs.head_sha }}
repository: ${{ steps.verify.outputs.head_repo }}
ref: ${{ steps.verify.outputs.head_sha }}
token: ${{ secrets.GITHUB_TOKEN }}
persist-credentials: false
fetch-depth: 0
path: pr-checkout
- name: Place prebuilds into the fork checkout
if: steps.meta.outputs.deliver == 'true'
if: steps.meta.outputs.deliver == 'true' && steps.verify.outcome == 'success'
env:
DL: prebuilds-in
CHECKOUT: pr-checkout
@ -238,12 +223,12 @@ jobs:
- name: Commit and push to the fork branch
id: push
if: steps.meta.outputs.deliver == 'true'
if: steps.meta.outputs.deliver == 'true' && steps.verify.outcome == 'success'
working-directory: pr-checkout
env:
HEAD_REF: ${{ steps.meta.outputs.head_ref }}
HEAD_REPO: ${{ steps.meta.outputs.head_repo }}
HEAD_SHA: ${{ steps.meta.outputs.head_sha }}
HEAD_REF: ${{ steps.verify.outputs.head_ref }}
HEAD_REPO: ${{ steps.verify.outputs.head_repo }}
HEAD_SHA: ${{ steps.verify.outputs.head_sha }}
# Push auth only — supplied via env, never interpolated into the command.
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: bash
@ -303,11 +288,11 @@ jobs:
fi
- name: Comment delivery outcome
if: always() && steps.meta.outputs.deliver == 'true' && steps.push.outcome != 'skipped'
if: always() && steps.meta.outputs.deliver == 'true' && steps.verify.outcome == 'success' && steps.push.outcome != 'skipped'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
PR: ${{ steps.meta.outputs.pr_number }}
PR: ${{ steps.verify.outputs.pr_number }}
RESULT: ${{ steps.push.outputs.result }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
shell: bash

View file

@ -121,64 +121,35 @@ jobs:
# metadata.json to reference another PR or SHA, redirecting our
# write-scoped sticky/check-run onto an attacker-chosen target.
#
# Authority sources are all server-controlled GitHub event fields:
# - workflow_run.head_sha
# - workflow_run.head_repository.full_name
# - workflow_run.pull_requests[].number (within-repo PRs only;
# empty array on fork PRs — fall back to commits/{sha}/pulls)
# Authority is workflow_run.head_sha + head_repository.full_name +
# head_branch, resolved via pulls?head={owner}:{branch}. That query
# works for same-repo PRs and forks; commits/{sha}/pulls is empty
# for fork SHAs. The script comes from THIS default-branch checkout
# (the same trust anchor as this workflow file).
#
# Always verify — including the changed_lines=0 path — so the
# check-run SHA cannot be an unverified artifact field.
# Mismatch => fail loud BEFORE any sticky/check-run side effect.
- name: Checkout identity verifier
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
with:
persist-credentials: false
sparse-checkout: .github/scripts/verify-workflow-run-pr-identity.cjs
sparse-checkout-cone-mode: false
path: trusted
- name: Verify metadata against workflow_run authority
id: verify
if: steps.meta.outputs.changed_lines != '0'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
META_PR_NUMBER: ${{ steps.meta.outputs.pr_number }}
META_HEAD_SHA: ${{ steps.meta.outputs.head_sha }}
META_HEAD_REPO: ${{ steps.meta.outputs.head_repo }}
META_PATH: autofix-in/metadata.json
SCHEMA_PATTERN: '^gitnexus\.pr-autofix/v[0-9]+$'
WF_HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
WF_HEAD_REPO: ${{ github.event.workflow_run.head_repository.full_name }}
WF_PR_NUMBERS: ${{ toJSON(github.event.workflow_run.pull_requests.*.number) }}
WF_HEAD_BRANCH: ${{ github.event.workflow_run.head_branch }}
shell: bash
run: |
set -euo pipefail
# 1) head_sha must match exactly. workflow_run.head_sha is the
# commit GitHub actually ran the producer against — definitive.
if [ "${META_HEAD_SHA}" != "${WF_HEAD_SHA}" ]; then
echo "::error::Artifact head_sha (${META_HEAD_SHA}) does not match workflow_run.head_sha (${WF_HEAD_SHA}) — refusing to publish."
exit 1
fi
# 2) head_repo must match exactly. Same authority anchor.
if [ "${META_HEAD_REPO}" != "${WF_HEAD_REPO}" ]; then
echo "::error::Artifact head_repo (${META_HEAD_REPO}) does not match workflow_run.head_repository (${WF_HEAD_REPO}) — refusing to publish."
exit 1
fi
# 3) pr_number must reference an open PR with this head SHA.
# Within-repo PRs: workflow_run.pull_requests[] is populated.
# Fork PRs: that array is empty by GitHub design — fall back
# to the REST commit-to-PRs lookup. Fail closed if the lookup
# finds no matching open PR (avoids attacker-forged PR ids).
allowed_numbers=$(jq -c '.' <<< "${WF_PR_NUMBERS}")
if [ "${allowed_numbers}" = "[]" ]; then
echo "workflow_run.pull_requests is empty (fork PR) — falling back to commits/{sha}/pulls."
allowed_numbers=$(gh api "repos/${GH_REPO}/commits/${WF_HEAD_SHA}/pulls" \
--jq '[.[] | select(.state == "open") | .number]' 2>/dev/null || echo "[]")
if [ "${allowed_numbers}" = "[]" ]; then
echo "::error::No open PR found for head ${WF_HEAD_SHA} via commits/{sha}/pulls — refusing to publish."
exit 1
fi
fi
if ! jq -e --argjson n "${META_PR_NUMBER}" 'index($n) != null' <<< "${allowed_numbers}" >/dev/null; then
echo "::error::Artifact pr_number (${META_PR_NUMBER}) is not in the authoritative PR list (${allowed_numbers}) — refusing to publish."
exit 1
fi
echo "Verified: metadata identity matches workflow_run authority (PR=${META_PR_NUMBER}, head_sha=${META_HEAD_SHA}, head_repo=${META_HEAD_REPO})."
run: node trusted/.github/scripts/verify-workflow-run-pr-identity.cjs
- name: Upsert sticky summary comment
# Only post when ci-quality found something fixable (= the
@ -187,14 +158,14 @@ jobs:
# so we skip it.
if: >-
always()
&& steps.meta.outputs.pr_number != ''
&& steps.verify.outcome == 'success'
&& steps.meta.outputs.changed_lines != '0'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
PR: ${{ steps.meta.outputs.pr_number }}
PR: ${{ steps.verify.outputs.pr_number }}
CHANGED: ${{ steps.meta.outputs.changed_lines }}
HEAD_SHA: ${{ steps.meta.outputs.head_sha }}
HEAD_SHA: ${{ steps.verify.outputs.head_sha }}
RUN_ID: ${{ github.run_id }}
shell: bash
run: |
@ -285,11 +256,11 @@ jobs:
# fixes-available → conclusion: neutral
# `neutral` does not block branch-protection required-checks but
# is visually distinct from a green pass.
if: always() && steps.meta.outputs.head_sha != ''
if: always() && steps.verify.outcome == 'success'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
HEAD_SHA: ${{ steps.meta.outputs.head_sha }}
HEAD_SHA: ${{ steps.verify.outputs.head_sha }}
CHANGED: ${{ steps.meta.outputs.changed_lines }}
shell: bash
run: |

11
.github/zizmor.yml vendored
View file

@ -18,9 +18,11 @@ rules:
# untrusted half (pr-autofix.yml) runs fork code with permissions:{}
# and produces only a diff artifact (data, not executable code). The
# publish job consumes the artifact, allowlist-validates every field
# of metadata.json before exporting to $GITHUB_OUTPUT, never checks
# out fork code, and never executes anything fork-controlled. Header
# comment in the file documents the split.
# of metadata.json, then cross-checks identity against
# workflow_run.head_sha / head_repository / head_branch via
# pulls?head=owner:branch (commits/{sha}/pulls is empty for fork SHAs).
# It never checks out fork code and never executes anything
# fork-controlled. Header comment in the file documents the split.
- pr-autofix-publish.yml
# workflow_run is the trusted half of the vendored-grammar prebuild
@ -29,7 +31,8 @@ rules:
# validates the .node prebuilds and uploads them as artifacts. This
# consumer downloads ONLY those artifacts + metadata.json,
# allowlist-validates every metadata field, cross-checks identity against
# the workflow_run authority (head_sha / head_repo / pr_number), and
# workflow_run.head_sha / head_repository / head_branch via
# pulls?head=owner:branch (commits/{sha}/pulls is empty for fork SHAs), and
# checks out the fork head pinned to that HEAD SHA solely to ADD prebuild
# files (never executes fork code) before pushing. Header comment in the
# file documents the split.

View file

@ -3440,9 +3440,9 @@
"license": "MIT"
},
"node_modules/hono": {
"version": "4.13.0",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.13.0.tgz",
"integrity": "sha512-jhunvfHWxd7J5EFfSgH4xsYJzSe/lfqbUCxiyyeaQasUsXeEHXtzVid+7EOGByc5JnFa23SSFL3Y2RV/z1T+eQ==",
"version": "4.13.7",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.13.7.tgz",
"integrity": "sha512-c8/gF9ac8Y78/agExVocyLevgR+JlpNB444Py0FSX8pJoPdYUfUzRcXtYEYGwt6l19qIlVZPN5Mfsw9jFShmQQ==",
"license": "MIT",
"engines": {
"node": ">=16.9.0"

View file

@ -0,0 +1,402 @@
import { describe, it, expect } from 'vitest';
import { createRequire } from 'node:module';
import { readFileSync } from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
/**
* Identity gate for commit-fork-prebuilds.yml and pr-autofix-publish.yml.
* The production failure on fork PR #3179 was: workflow_run.pull_requests[]
* is empty (GitHub design) and GET /repos/{base}/commits/{sha}/pulls is also
* empty (fork commit is not in the base graph). The verifier must use
* pulls?head=owner:branch and must not treat a gh failure as "no PR".
*/
const requireCjs = createRequire(import.meta.url);
const SCRIPT = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../../../.github/scripts/verify-workflow-run-pr-identity.cjs',
);
const WORKFLOW = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../../../.github/workflows/commit-fork-prebuilds.yml',
);
const AUTOFIX_WORKFLOW = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../../../.github/workflows/pr-autofix-publish.yml',
);
const AUTOFIX_SCHEMA = /^gitnexus\.pr-autofix\/v[0-9]+$/;
const mod = requireCjs(SCRIPT) as {
allowlistField: (key: string, value: unknown, pattern: RegExp) => string;
allowlistMetadata: (raw: unknown, schemaPattern?: RegExp) => Record<string, string>;
forkHeadOwner: (headRepo: string) => string;
resolveVerifiedPullRequest: (input: {
meta: unknown;
authority: {
head_sha: string;
head_repo: string;
head_branch: string;
base_repo: string;
};
pulls: unknown;
schemaPattern?: RegExp;
}) => {
pr_number: string;
head_ref: string;
head_sha: string;
head_repo: string;
current_head_sha: string;
branch_moved: boolean;
};
listOpenPullsByHead: (input: {
ghRepo: string;
headOwner: string;
headBranch: string;
runGh: (args: string[]) => { status: number; stdout?: string; stderr?: string };
}) => unknown[];
flattenGhListPages: (parsed: unknown) => unknown[];
IDENTITY_PATTERNS: { pr_number: RegExp; head_sha: RegExp; head_ref: RegExp; repo: RegExp };
};
const SHA = 'ee08b034ea90943e8b037c6224f1e0de41a65613';
const MOVED = '8a33525d9bb8617dfb08d426d4b2834581e1277a';
const META = {
schema: 'gitnexus.ts-prebuild/v1',
pr_number: 3179,
head_sha: SHA,
head_ref: 'objective-c_support',
head_repo: 'mengkaka/GitNexus',
base_repo: 'abhigyanpatwari/GitNexus',
};
const AUTHORITY = {
head_sha: SHA,
head_repo: 'mengkaka/GitNexus',
head_branch: 'objective-c_support',
base_repo: 'abhigyanpatwari/GitNexus',
};
function pull(overrides: Record<string, unknown> = {}) {
return {
number: 3179,
state: 'open',
head: {
sha: SHA,
ref: 'objective-c_support',
repo: { full_name: 'mengkaka/GitNexus' },
},
base: { repo: { full_name: 'abhigyanpatwari/GitNexus' } },
...overrides,
};
}
describe('allowlistField', () => {
it('rejects a newline that would inject a second GITHUB_OUTPUT line', () => {
expect(() =>
mod.allowlistField('head_ref', 'main\npr_number=1', mod.IDENTITY_PATTERNS.head_ref),
).toThrow(/failed allowlist/);
});
it('accepts a slashy branch name', () => {
expect(mod.allowlistField('head_ref', 'feat/objc', mod.IDENTITY_PATTERNS.head_ref)).toBe(
'feat/objc',
);
});
});
describe('forkHeadOwner', () => {
it('takes the owner from owner/name', () => {
expect(mod.forkHeadOwner('mengkaka/GitNexus')).toBe('mengkaka');
});
it('rejects a bare owner', () => {
expect(() => mod.forkHeadOwner('mengkaka')).toThrow(/owner\/name/);
});
});
describe('resolveVerifiedPullRequest', () => {
it('accepts the #3179 production shape even when the PR tip has moved', () => {
const verified = mod.resolveVerifiedPullRequest({
meta: META,
authority: AUTHORITY,
pulls: [
pull({
head: {
sha: MOVED,
ref: 'objective-c_support',
repo: { full_name: 'mengkaka/GitNexus' },
},
}),
],
});
expect(verified).toEqual({
pr_number: '3179',
head_ref: 'objective-c_support',
head_sha: SHA,
head_repo: 'mengkaka/GitNexus',
current_head_sha: MOVED,
branch_moved: true,
});
});
it('refuses an empty pulls list — the commits/{sha}/pulls miss', () => {
expect(() =>
mod.resolveVerifiedPullRequest({ meta: META, authority: AUTHORITY, pulls: [] }),
).toThrow(/No open PR from mengkaka\/GitNexus:objective-c_support/);
});
it('refuses a forged pr_number that is not the fork-head PR', () => {
expect(() =>
mod.resolveVerifiedPullRequest({
meta: { ...META, pr_number: 1 },
authority: AUTHORITY,
pulls: [pull()],
}),
).toThrow(/Artifact pr_number \(1\)/);
});
it('refuses a head_sha that does not match workflow_run', () => {
expect(() =>
mod.resolveVerifiedPullRequest({
meta: { ...META, head_sha: MOVED },
authority: AUTHORITY,
pulls: [pull()],
}),
).toThrow(/head_sha/);
});
it('refuses a head_repo that does not match workflow_run', () => {
expect(() =>
mod.resolveVerifiedPullRequest({
meta: { ...META, head_repo: 'evil/GitNexus' },
authority: AUTHORITY,
pulls: [pull()],
}),
).toThrow(/head_repo/);
});
it('refuses a head_ref that does not match workflow_run.head_branch', () => {
expect(() =>
mod.resolveVerifiedPullRequest({
meta: { ...META, head_ref: 'other-branch' },
authority: AUTHORITY,
pulls: [pull()],
}),
).toThrow(/head_ref/);
});
it('refuses a base_repo that does not match $GITHUB_REPOSITORY', () => {
expect(() =>
mod.resolveVerifiedPullRequest({
meta: { ...META, base_repo: 'evil/upstream' },
authority: AUTHORITY,
pulls: [pull()],
}),
).toThrow(/base_repo does not match/);
});
it('refuses two open PRs that share the same fork head', () => {
expect(() =>
mod.resolveVerifiedPullRequest({
meta: META,
authority: AUTHORITY,
pulls: [
pull(),
pull({
number: 4000,
base: { repo: { full_name: 'abhigyanpatwari/GitNexus' }, ref: 'release' },
}),
],
}),
).toThrow(/Ambiguous open PRs/);
});
it('refuses a closed PR for the same fork head', () => {
expect(() =>
mod.resolveVerifiedPullRequest({
meta: META,
authority: AUTHORITY,
pulls: [pull({ state: 'closed' })],
}),
).toThrow(/No open PR/);
});
it('accepts gitnexus.pr-autofix metadata when SCHEMA_PATTERN is the autofix schema', () => {
const verified = mod.resolveVerifiedPullRequest({
meta: { ...META, schema: 'gitnexus.pr-autofix/v1', changed_lines: 12 },
authority: AUTHORITY,
pulls: [pull()],
schemaPattern: AUTOFIX_SCHEMA,
});
expect(verified.pr_number).toBe('3179');
});
it('rejects an autofix schema against the default prebuild allowlist', () => {
expect(() =>
mod.resolveVerifiedPullRequest({
meta: { ...META, schema: 'gitnexus.pr-autofix/v1' },
authority: AUTHORITY,
pulls: [pull()],
}),
).toThrow(/metadata.schema failed allowlist/);
});
it('ignores a PR from the same owner that targets a different repo or branch', () => {
expect(() =>
mod.resolveVerifiedPullRequest({
meta: META,
authority: AUTHORITY,
pulls: [
pull({
number: 9,
head: { sha: SHA, ref: 'unrelated', repo: { full_name: 'mengkaka/GitNexus' } },
}),
],
}),
).toThrow(/No open PR/);
});
});
describe('listOpenPullsByHead', () => {
it('calls gh with state=open and head=owner:branch', () => {
let seen: string[] = [];
const pulls = [pull()];
const listed = mod.listOpenPullsByHead({
ghRepo: 'abhigyanpatwari/GitNexus',
headOwner: 'mengkaka',
headBranch: 'objective-c_support',
runGh: (args) => {
seen = args;
return { status: 0, stdout: JSON.stringify(pulls) };
},
});
expect(seen).toEqual([
'api',
'--paginate',
'--slurp',
'-X',
'GET',
'repos/abhigyanpatwari/GitNexus/pulls',
'-f',
'state=open',
'-f',
'head=mengkaka:objective-c_support',
]);
expect(listed).toEqual(pulls);
});
it('flattens gh --paginate --slurp page arrays', () => {
const page1 = [pull()];
const page2 = [
pull({
number: 4000,
head: {
sha: SHA,
ref: 'other',
repo: { full_name: 'mengkaka/GitNexus' },
},
}),
];
const listed = mod.listOpenPullsByHead({
ghRepo: 'abhigyanpatwari/GitNexus',
headOwner: 'mengkaka',
headBranch: 'objective-c_support',
runGh: () => ({ status: 0, stdout: JSON.stringify([page1, page2]) }),
});
expect(listed).toEqual([...page1, ...page2]);
});
it('throws on an empty body', () => {
expect(() =>
mod.listOpenPullsByHead({
ghRepo: 'abhigyanpatwari/GitNexus',
headOwner: 'mengkaka',
headBranch: 'objective-c_support',
runGh: () => ({ status: 0, stdout: '' }),
}),
).toThrow(/empty body/);
});
it('throws on a non-JSON success body', () => {
expect(() =>
mod.listOpenPullsByHead({
ghRepo: 'abhigyanpatwari/GitNexus',
headOwner: 'mengkaka',
headBranch: 'objective-c_support',
runGh: () => ({ status: 0, stdout: 'not-json' }),
}),
).toThrow(/non-JSON/);
});
it('throws on a gh failure instead of pretending there is no PR', () => {
expect(() =>
mod.listOpenPullsByHead({
ghRepo: 'abhigyanpatwari/GitNexus',
headOwner: 'mengkaka',
headBranch: 'objective-c_support',
runGh: () => ({ status: 1, stderr: 'HTTP 404' }),
}),
).toThrow(/pulls\?head= lookup failed: HTTP 404/);
});
it('throws on a non-array success body', () => {
expect(() =>
mod.listOpenPullsByHead({
ghRepo: 'abhigyanpatwari/GitNexus',
headOwner: 'mengkaka',
headBranch: 'objective-c_support',
runGh: () => ({ status: 0, stdout: '{"message":"Not Found"}' }),
}),
).toThrow(/non-array/);
});
});
describe('commit-fork-prebuilds.yml contract', () => {
const workflow = readFileSync(WORKFLOW, 'utf8');
it('runs the tested verifier and keys the fork lookup on workflow_run.head_branch', () => {
expect(workflow).toContain('.github/scripts/verify-workflow-run-pr-identity.cjs');
expect(workflow).toContain('github.event.workflow_run.head_branch');
expect(workflow).toContain('WF_HEAD_BRANCH');
});
it('does not call commits/{sha}/pulls (empty for fork SHAs; comments may name it)', () => {
expect(workflow).not.toMatch(/gh api .*commits\/[^/\s]+\/pulls/);
});
it('does not checkout, place, or push unless identity verify succeeded', () => {
expect(workflow).toContain('steps.verify.outputs.head_repo');
expect(workflow).toContain('steps.verify.outputs.head_sha');
expect(workflow).toContain('steps.verify.outputs.pr_number');
for (const step of [
'Checkout fork PR head',
'Place prebuilds into the fork checkout',
'Commit and push to the fork branch',
]) {
const chunk = workflow.split(`- name: ${step}`)[1]?.split('- name:')[0] ?? '';
expect(chunk, step).toMatch(/steps\.verify\.outcome == 'success'/);
}
});
});
describe('pr-autofix-publish.yml contract', () => {
const workflow = readFileSync(AUTOFIX_WORKFLOW, 'utf8');
it('runs the tested verifier and keys the lookup on workflow_run.head_branch', () => {
expect(workflow).toContain('.github/scripts/verify-workflow-run-pr-identity.cjs');
expect(workflow).toContain('github.event.workflow_run.head_branch');
expect(workflow).toContain('WF_HEAD_BRANCH');
expect(workflow).toContain('gitnexus\\.pr-autofix');
});
it('does not call commits/{sha}/pulls (empty for fork SHAs; comments may name it)', () => {
expect(workflow).not.toMatch(/gh api .*commits\/[^/\s]+\/pulls/);
});
it('does not post sticky comments or check runs unless identity verify succeeded', () => {
expect(workflow).toMatch(/steps\.verify\.outcome == 'success'/);
expect(workflow).toContain('steps.verify.outputs.pr_number');
expect(workflow).toContain('steps.verify.outputs.head_sha');
});
});