Unverified Commit fca0fea5 authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

[ci] Fix create_release_branch for new repo permissions (#96641)

### What

Fixes the **Create Release Branch** workflow, which currently fails on
every run.

1. Drop `permission-environments: write` from the GitHub App token
request.
- The release App installation no longer grants it, and
`actions/create-github-app-token` fails hard on an ungranted permission.
2. Drop the runtime `deployment-branch-policies` API call (and its 5s
sleep) from `scripts/create-release-branch.js`.
- No longer needed: the `release-stable` environment now statically
allows branches conforming to `next-NN` / `next-NN-*`. This is what the
permission above existed for.
3. Create the setup commit as a GitHub-signed commit via
`scripts/github-utils/signed-commit.js` instead of `git push`.
- Branch protection requires signed commits; `git push` pushed an
unsigned one. Uses the same `createSignedCommit` + `upsertBranchRef`
pattern as `scripts/automated-update-workflow.js`.

### Why

The most recent run
([30923742579](https://github.com/vercel/next.js/actions/runs/30923742579/job/92040655448))
dies at the first step, `Create GitHub App token`, with a 422 — so the
job never even clones the repo.

### Note for review

Release tags are **annotated** tag objects, so `git rev-parse v16.0.0`
returns the tag object SHA, not the commit. `createSignedCommit` passes
`baseSha` straight into `parents: [...]`, so the base is dereferenced
with `^{commit}`. Its internal `^{tree}` lookup happens to resolve
either way, so this would otherwise only have failed at commit-creation
time during a real release.

The static patterns cover `next-16-2`-style names but not a single-digit
major like `next-9-5`. Not a concern for current or future releases, but
noting it since the previous code created the policy for any branch
name.

### Verification

The workflow is `workflow_dispatch`-only and writes to the real repo, so
it can't be run end-to-end from a PR. Verified locally against the real
`v16.0.0` tag in a throwaway clone:

- `git reset --hard v16.0.0` leaves HEAD exactly at `v16.0.0^{commit}`,
confirming the base SHA is right.
- Replaying the lerna.json / `build_and_deploy.yml` /
`build_and_test.yml` mutations produces exactly those 3 changed files
and nothing else.
- Driving `createTreeFromLocalCommit` with a mocked `request` (no
network) uploads 3 blobs with correct `100644` modes and a `base_tree`
that matches the tag's tree.
- `node --check`, prettier, and eslint all clean.

Still needs a real `workflow_dispatch` run after merge to confirm the
token step succeeds and the resulting commit shows as **Verified**.
parent 47939786
...@@ -42,7 +42,6 @@ jobs: ...@@ -42,7 +42,6 @@ jobs:
owner: ${{ github.repository_owner }} owner: ${{ github.repository_owner }}
repositories: next.js repositories: next.js
permission-contents: write permission-contents: write
permission-environments: write
permission-workflows: write permission-workflows: write
- name: Get GitHub App user ID - name: Get GitHub App user ID
......
...@@ -6,8 +6,51 @@ const { ...@@ -6,8 +6,51 @@ const {
configureGitHubAuth, configureGitHubAuth,
getGitHubToken, getGitHubToken,
getGitHubTokenMissingMessage, getGitHubTokenMissingMessage,
verifyGitHubApiAccess,
} = require('./release-github-auth') } = require('./release-github-auth')
const {
githubRequest,
createSignedCommit,
upsertBranchRef,
} = require('./github-utils/signed-commit')
const REPO_OWNER = 'vercel'
const REPO_NAME = 'next.js'
/**
* Fail fast, before any file mutation, if the branch already exists.
*
* This doubles as the API preflight: it exercises the same git-data path the
* script later writes to (blobs/trees/commits/refs), so a token missing those
* grants fails here rather than midway through creating objects. A plain
* repository GET would succeed with any valid installation token and so could
* never catch that.
*/
async function verifyBranchIsAvailable(token, branch) {
let existing
try {
existing = await githubRequest(
token,
'GET',
`/repos/${REPO_OWNER}/${REPO_NAME}/git/ref/heads/${branch}`
)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
// A 404 is the expected, successful outcome: the branch is available.
if (message.includes('failed (404)')) {
console.log(`Verified GitHub API access; branch ${branch} is available`)
return
}
throw error
}
throw new Error(
`Branch ${branch} already exists (at ${existing.object?.sha}). ` +
`Delete it or choose a different branch name before re-running.`
)
}
async function main() { async function main() {
const args = process.argv const args = process.argv
...@@ -30,23 +73,16 @@ async function main() { ...@@ -30,23 +73,16 @@ async function main() {
} }
await configureGitHubAuth(githubToken) await configureGitHubAuth(githubToken)
await verifyGitHubApiAccess( await verifyBranchIsAvailable(githubToken, branchName)
githubToken,
'/repos/vercel/next.js/environments/release-stable/deployment-branch-policies?per_page=1',
'release-stable deployment branch policies'
)
await execa(`git checkout -b "${branchName}"`, { await execa('git', ['checkout', '-b', branchName], {
stdio: 'inherit', stdio: 'inherit',
shell: true,
}) })
await execa(`git fetch origin ${tagName} --tags`, { await execa('git', ['fetch', 'origin', tagName, '--tags'], {
stdio: 'inherit', stdio: 'inherit',
shell: true,
}) })
await execa(`git reset --hard ${tagName}`, { await execa('git', ['reset', '--hard', tagName], {
stdio: 'inherit', stdio: 'inherit',
shell: true,
}) })
const lernaPath = path.join(__dirname, '..', 'lerna.json') const lernaPath = path.join(__dirname, '..', 'lerna.json')
const existingLerna = JSON.parse( const existingLerna = JSON.parse(
...@@ -89,44 +125,47 @@ async function main() { ...@@ -89,44 +125,47 @@ async function main() {
await fs.promises.writeFile(buildAndTestPath, buildAndTest) await fs.promises.writeFile(buildAndTestPath, buildAndTest)
await execa(`git add .`, { const commitMessage = 'setup release branch'
await execa('git', ['add', '.'], {
stdio: 'inherit', stdio: 'inherit',
shell: true,
}) })
await execa(`git commit -m "setup release branch"`, { await execa('git', ['commit', '-m', commitMessage], {
stdio: 'inherit', stdio: 'inherit',
shell: true,
}) })
await execa(`git push origin "${branchName}"`, { // Branch protection requires signed commits, so create the commit on the
stdio: 'inherit', // remote as a GitHub-signed commit via the REST API instead of running
shell: true, // `git push` (which would push the unsigned local commit).
//
// Release tags are annotated tag objects, so dereference to the underlying
// commit -- the tag object's SHA is not valid as a commit parent.
const { stdout: baseSha } = await execa('git', [
'rev-parse',
`${tagName}^{commit}`,
])
const { stdout: localCommitSha } = await execa('git', ['rev-parse', 'HEAD'])
const signedCommit = await createSignedCommit({
token: githubToken,
owner: REPO_OWNER,
repo: REPO_NAME,
baseSha: baseSha.trim(),
localCommitSha: localCommitSha.trim(),
message: commitMessage,
}) })
console.log(`Waiting 5s before updating branch rules`) await upsertBranchRef({
await new Promise((resolve) => setTimeout(resolve, 5_000)) token: githubToken,
owner: REPO_OWNER,
const updateEnvironmentRes = await fetch( repo: REPO_NAME,
'https://api.github.com/repos/vercel/next.js/environments/release-stable/deployment-branch-policies', branch: branchName,
{ sha: signedCommit.sha,
method: 'POST', })
headers: {
Accept: 'application/vnd.github+json',
Authorization: `Bearer ${githubToken}`,
'X-GitHub-Api-Version': '2022-11-28',
},
body: JSON.stringify({ name: branchName }),
}
)
if (!updateEnvironmentRes.ok) { console.log(
console.error( `Created branch ${branchName} at signed commit ${signedCommit.sha}`
{ status: updateEnvironmentRes.status },
await updateEnvironmentRes.text()
) )
throw new Error(`Failed to update environment branch rules`)
}
console.log(`Successfully updated deployment environment branch rules`)
} }
main() main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment