diff --git a/.github/workflows/patch-provenance.yml b/.github/workflows/patch-provenance.yml index af77c266dbc..5affc3f20da 100644 --- a/.github/workflows/patch-provenance.yml +++ b/.github/workflows/patch-provenance.yml @@ -9,17 +9,19 @@ name: Patch provenance # Any other pull request into a stable line fails this check, and a maintainer reviews and merges it. # # It runs on pull_request, so each stable line runs its own copy of this file. It never checks out -# or runs the pull request's code: it only reads commits. A pull request that changes .github/ runs -# its own version of the checks there, this one included, so they vouch for nothing on it: a -# maintainer reviews it, and the release bot never merges a pull request that changes .github/. +# or runs the pull request's code: it only reads commits, anonymously with git, so it doesn't +# depend on GitHub's API, which can refuse requests from GitHub-hosted runners. A pull request that +# changes .github/ runs its own version of the checks there, this one included, so they vouch for +# nothing on it: a maintainer reviews it, and the release bot never merges a pull request that +# changes .github/. on: pull_request: types: [opened, synchronize, reopened, edited] branches: - 'stable/**' -permissions: - contents: read +# The repository is public and the check reads it anonymously, so its token needs no permissions. +permissions: {} concurrency: group: patch-provenance-${{ github.event.pull_request.number }} @@ -33,7 +35,6 @@ jobs: steps: - name: Check where the pull request's changes come from env: - GH_TOKEN: ${{ github.token }} PR_NUMBER: ${{ github.event.pull_request.number }} BASE_REF: ${{ github.event.pull_request.base.ref }} HEAD_REF: ${{ github.event.pull_request.head.ref }} @@ -65,11 +66,17 @@ jobs: return false } } + // The fetch below brings every commit and tree, so whether a commit has a path reads no file. + const hasFile = (commit, path) => gitSucceeds('rev-parse', '--verify', '--quiet', `${commit}:${path}`) + // A file's text at a commit, or undefined when the commit doesn't have it. Git fetches the + // text from GitHub on first read, and a failed fetch fails the check: it never reads as a + // missing file. const fileAt = (commit, path) => { + if (!hasFile(commit, path)) return undefined try { - return execFileSync('git', ['show', `${commit}:${path}`], {encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, stdio: ['ignore', 'pipe', 'ignore']}) - } catch { - return undefined + return run('git', ['cat-file', 'blob', `${commit}:${path}`]) + } catch (error) { + fail(`Reading ${path} at ${commit} failed: ${error.stderr?.toString().trim() || error.message}`) } } const summary = (text) => appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${text}\n`) @@ -85,23 +92,6 @@ jobs: summary(`### Patch provenance passed\n\n${text}`) process.exit(0) } - // Fetches more history until `commit` reaches `base`, so merge bases are found in a shallow repository. - function deepen(ref, base) { - for (const depth of [50, 200, 1000, 5000]) { - git('fetch', '--quiet', '--no-tags', `--depth=${depth}`, 'origin', ref) - if (base === undefined || gitSucceeds('merge-base', base, ref)) return - } - } - // Fetches main until its first-parent chain reaches `cut`, and returns main's head. A merge base - // alone isn't enough: a branch based before the cut and merged later reaches it sooner. - function fetchMainSince(cut) { - const main = 'refs/remotes/origin/main' - for (const depth of [50, 200, 1000, 5000]) { - git('fetch', '--quiet', '--no-tags', `--depth=${depth}`, 'origin', `+refs/heads/main:${main}`) - if (git('rev-list', '--first-parent', main).split('\n').includes(cut)) return git('rev-parse', main) - } - fail(`${BASE_REF}'s cut ${cut} isn't in the last 5000 commits of main's first-parent history, so this check can't tell which commits reached main after it.`) - } const changesetPath = (path) => /^\.changeset\/[^/]+\.md$/.test(path) && path !== '.changeset/README.md' // [{status, path, oldMode, newMode}] for base..head, without rename detection, and with paths // exactly as stored. @@ -116,22 +106,6 @@ jobs: } // " " for a path at a commit, or '' when it isn't there. const entryAt = (commit, path) => git('ls-tree', '--full-tree', commit, '--', path).split('\t')[0] - function api(path) { - try { - return JSON.parse(run('gh', ['api', path])) - } catch (error) { - fail(`Reading ${path} from GitHub failed: ${error.stderr?.toString().trim() || error.message}`) - } - } - // The commits, newest first, that changed `path` in the history of `ref`. - function commitsChanging(ref, path) { - const endpoint = `repos/${repository}/commits?sha=${ref}&path=${encodeURIComponent(path)}&per_page=100` - try { - return run('gh', ['api', '--paginate', endpoint, '--jq', '.[].sha']).split('\n').filter(Boolean) - } catch (error) { - fail(`Reading ${endpoint} from GitHub failed: ${error.stderr?.toString().trim() || error.message}`) - } - } // {name: {directory, version, manifest}} for the workspace packages at a commit. function packagesAt(commit) { const packages = {} @@ -160,14 +134,21 @@ jobs: } git('init', '--quiet', '.') - // Background maintenance after a fetch can hold the shallow lock while the next fetch starts. + // A fetch can start background maintenance, which would compete with the check's own git + // commands for locks. git('config', 'maintenance.auto', 'false') git('config', 'gc.auto', '0') git('remote', 'add', 'origin', `https://github.com/${repository}`) - const lineHead = git('ls-remote', 'origin', `refs/heads/${BASE_REF}`).split('\t')[0] - if (!/^[0-9a-f]{40}$/.test(lineHead)) fail(`Couldn't read the head of ${BASE_REF}.`) - deepen(lineHead) - deepen(HEAD_SHA, lineHead) + // ls-remote matches the end of ref names, so a branch such as a/refs/heads/ matches too: + // only the exact ref is the line's head. + const lineHead = git('ls-remote', 'origin', `refs/heads/${BASE_REF}`) + .split('\n') + .map((line) => line.split('\t')) + .find(([, ref]) => ref === `refs/heads/${BASE_REF}`)?.[0] + if (!/^[0-9a-f]{40}$/.test(lineHead ?? '')) fail(`Couldn't read the head of ${BASE_REF}.`) + // Every commit and tree of the line, the pull request and main, without file contents, so + // merge bases and histories are exact. + git('fetch', '--quiet', '--no-tags', '--filter=blob:none', 'origin', lineHead, HEAD_SHA, '+refs/heads/main:refs/remotes/origin/main') if (!gitSucceeds('merge-base', lineHead, HEAD_SHA)) fail(`${HEAD_SHA} doesn't share history with ${BASE_REF}.`) if (HEAD_REF === `changeset-release/${BASE_REF}`) { @@ -491,10 +472,6 @@ jobs: // twice, and it must change more than changesets, since a changeset alone doesn't say which // change it describes. function checkBackport() { - for (const depth of [50, 200, 1000, 5000]) { - if (gitSucceeds('merge-base', '--is-ancestor', lineHead, HEAD_SHA)) break - git('fetch', '--quiet', '--no-tags', `--depth=${depth}`, 'origin', HEAD_SHA) - } if (!gitSucceeds('merge-base', '--is-ancestor', lineHead, HEAD_SHA)) { fail(`${HEAD_SHA} doesn't build on ${BASE_REF}'s head ${lineHead}. Update the branch.`) } @@ -515,9 +492,14 @@ jobs: if (bump !== 'patch' || !fixed.has(name)) fail(`${path} bumps ${name} ${bump}; a backport carries only patch changesets for the fixed group.`) } } - const cut = api(`repos/${repository}/compare/main...${encodeURIComponent(BASE_REF)}`).merge_base_commit?.sha - if (!cut) fail(`Couldn't find where ${BASE_REF} was cut from main.`) - const mainHead = fetchMainSince(cut) + const mainHead = git('rev-parse', 'refs/remotes/origin/main') + const cut = spawnSync('git', ['merge-base', mainHead, lineHead], {encoding: 'utf8'}).stdout.trim() + if (!/^[0-9a-f]{40}$/.test(cut)) fail(`Couldn't find where ${BASE_REF} was cut from main.`) + // The line was cut from one of main's landings, so main's first-parent commits after the + // cut are the landings the line doesn't have. + if (!git('rev-list', '--first-parent', mainHead).split('\n').includes(cut)) { + fail(`${BASE_REF}'s cut ${cut} isn't on main's first-parent history, so this check can't tell which commits reached main after it.`) + } // The commit on main's first-parent chain since the cut that added each changeset: a landing, // compared with main before it. A merged pull request's own commits never count, because one // of them can carry a changeset its merge changed. One backport brings one change, so they @@ -527,7 +509,7 @@ jobs: for (const {path} of changesets) { const added = git('log', '--first-parent', '--reverse', '--format=%H', `${cut}..${mainHead}`, '--', path) .split('\n') - .filter((commit) => commit !== '' && fileAt(commit, path) !== undefined && fileAt(`${commit}^1`, path) === undefined) + .filter((commit) => commit !== '' && hasFile(commit, path) && !hasFile(`${commit}^1`, path)) const [origin] = added if (!origin) fail(`main hasn't added ${path} since ${BASE_REF} was cut from it at ${cut}, so this isn't a backport of a fix main has and the line lacks.`) additions.set(path, added) @@ -538,9 +520,7 @@ jobs: // A changeset the line has had since its cut came with an earlier backport of the fix, and a // release may have consumed it since: a second backport would release the fix again. for (const {path} of changesets) { - const sinceCut = commitsChanging(lineHead, path) - .reverse() - .find((commit) => !['behind', 'identical'].includes(api(`repos/${repository}/compare/${cut}...${commit}`).status)) + const [sinceCut] = git('log', '--full-history', '--reverse', '--format=%H', `${cut}..${lineHead}`, '--', path).split('\n').filter(Boolean) if (sinceCut) fail(`${BASE_REF} has had ${path} since ${sinceCut}, so the line already has this fix, and a release may have shipped it.`) } // main's commit applied to the line's head. @@ -613,7 +593,7 @@ jobs: function releaseConsuming(path, origin, mainHead) { const deletion = git('log', '--first-parent', '--reverse', '--format=%H', `${origin}..${mainHead}`, '--', path) .split('\n') - .find((commit) => commit !== '' && fileAt(commit, path) === undefined) + .find((commit) => commit !== '' && !hasFile(commit, path)) const cliKitVersion = (commit) => JSON.parse(fileAt(commit, 'packages/cli-kit/package.json') ?? '{}').version if (!deletion || cliKitVersion(deletion) === cliKitVersion(`${deletion}^1`)) { fail(`main removed ${path} in ${deletion} without a release, so this isn't a fix main still has.`)