Files
Denis AfonsoandClaude Opus 5.5 34c8bda1a8 ci: use backport app token in cherry-pick workflow (#32803)
The cherry-pick workflow can no longer open PRs. Since
coder/github-org-terraform#76 (Nov 17), the org disables "Allow GitHub
Actions to create and approve pull requests", so `gh pr create` with
`GITHUB_TOKEN` fails:

```
GraphQL: GitHub Actions is not permitted to create or approve pull requests (createPullRequest)
```

Example: [run
45991857596](https://github.com/coder/coder/actions/runs/45991857596/job/140481380335)
for #32793. That run had already pushed `backport/32793-to-<version>`,
and because the workflow exits as soon as the branch exists, re-running
it can't open the PR.

`backport.yaml` already opens its PRs with the backporter App token
(#32352). This brings `cherry-pick.yaml` in line with it.

**App token**

- Runs the job in `environment: main` with only `contents: read` and
`id-token: write` for the job token.
- Mints the token with the same pinned `coder/github-app-token-action`
step and `BACKPORT_APP_*` inputs (contents, pull_requests, workflows and
issues write on coder/coder).
- Uses the App token for both `git push` and `gh`, and commits as the
App bot, as backport does.

**Recovery on re-runs, as in `backport.yaml`**

- Checks for an existing PR first (`--state all`) and exits only if
there is one.
- If the branch already exists, reuses it and goes on to open the PR. If
its tip is the conflict placeholder commit, the PR keeps the `
(conflicts)` title suffix.
- Otherwise cherry-picks and pushes as before.

**Best-effort extras, as in `backport.yaml`**

- `gh pr create` only sets base, head, title and body. Label, assignee
and reviewer are added afterwards with separate `gh pr edit` calls that
warn instead of failing.
- `gh label create` warns instead of failing.

Branch naming, the conflict placeholder, the PR body and the comment on
the original PR are unchanged.

**Side effects**

- Cherry-pick PRs are now opened by the App, not `github-actions[bot]`,
so they trigger CI like any other PR.
- They also trigger `pr-cherry-pick-check.yaml`, which comments when a
title doesn't start with `fix:`. Conflicts are therefore marked with a `
(conflicts)` suffix, as in `backport.yaml`, instead of a `[CONFLICT]`
prefix.
- With `workflows: write`, cherry-picks that touch `.github/workflows/`
can now be pushed too.
- Approvals: the requester is still asked to review the cherry-pick, so
they can approve and merge their own cherry-pick. That isn't new, and
backport works the same way. The proposal to require a
`release-managers` approval on bot-opened release PRs isn't in
`coder.yaml` yet
([discussion](https://codercom.slack.com/archives/C0CHP8J479T/p1795510371505229)).

> [!IMPORTANT]
> The backporter App's Cloud KMS key only signs for
`/.github/workflows/backport.yaml@refs/heads/main`
(`coder-backporter-app` in coder/gcp
`projects/production/coder-github-apps/apps.tf`). coder/gcp#497 adds
`/.github/workflows/cherry-pick.yaml@refs/heads/main`; merge and apply
it first, or the token step fails to sign.

Validated with `actionlint` (with shellcheck) and `zizmor --offline` (no
findings). I also ran the script locally with a stubbed `gh` against a
local remote: existing PR → skip; fresh run → PR opened, failing
label/reviewer calls only warn; stranded placeholder branch → reused and
opened with the ` (conflicts)` suffix.

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:14:06 +00:00

223 lines
9.6 KiB
YAML

# Automatically cherry-pick merged PRs to the latest release branch when the
# "cherry-pick" label is applied. Works whether the label is added before or
# after the PR is merged.
#
# Usage:
# 1. Add the "cherry-pick" label to a PR targeting main.
# 2. When the PR merges (or if already merged), the workflow detects the
# latest release/* branch and opens a cherry-pick PR against it.
#
# The created PRs follow existing repo conventions:
# - Branch: backport/<pr>-to-<version>
# - Title: <original PR title> (#<pr>)
# - Body: links back to the original PR and merge commit
# - Label: cherry-pick/v<version> to identify the target release
name: Cherry-pick to release
on:
pull_request_target:
branches:
- main
types:
- closed
- labeled
permissions: {}
# Prevent duplicate runs for the same PR when both 'closed' and 'labeled'
# fire in quick succession.
concurrency:
group: cherry-pick-${{ github.event.pull_request.number }}
jobs:
cherry-pick:
name: Cherry-pick to latest release
# Writes go through the backport GitHub App token below, so the job
# token only needs to read the repository for checkout.
permissions:
contents: read
id-token: write # Cloud KMS signs the backporter App's JWT
if: >
github.event.pull_request.merged == true &&
contains(github.event.pull_request.labels.*.name, 'cherry-pick')
runs-on: ubuntu-latest
environment: main
env:
PR_NUMBER: ${{ github.event.pull_request.number }}
PR_TITLE: ${{ github.event.pull_request.title }}
PR_URL: ${{ github.event.pull_request.html_url }}
MERGE_SHA: ${{ github.event.pull_request.merge_commit_sha }}
SENDER: ${{ github.event.sender.login }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
# Full history required for cherry-pick and branch discovery.
fetch-depth: 0
persist-credentials: false
# The org disables "Allow GitHub Actions to create and approve pull
# requests", so GITHUB_TOKEN can't open the cherry-pick PR. GITHUB_TOKEN
# can also never be granted the workflows permission, so GitHub rejects
# pushes of branches whose .github/workflows/ contents differ from main.
# The backport App token covers both, and lets the opened PRs trigger CI.
- name: Generate backport App token
id: app-token
# The App's key is a non-exportable Cloud KMS key; only this workflow, in this environment,
# may sign with it.
uses: coder/github-app-token-action@00eaec58ee1bfea9c8b48655b7ab7470b07739e5 # main 2026-11-17
with:
client-id: ${{ secrets.BACKPORT_APP_ID }}
kms-key: ${{ secrets.BACKPORT_APP_KMS_KEY }}
workload-identity-provider: ${{ secrets.APP_KEYS_WORKLOAD_ID_PROVIDER }}
owner: coder
repositories: coder
# issues: write creates the release-specific cherry-pick label if it's missing.
permissions: |
contents: write
pull_requests: write
workflows: write
issues: write
- name: Cherry-pick and open PR
env:
GH_TOKEN: ${{ steps.app-token.outputs.token }}
APP_SLUG: ${{ steps.app-token.outputs.app-slug }}
run: |
set -euo pipefail
# Configure git to authenticate pushes with the App token
# since persist-credentials is disabled on checkout.
git remote set-url origin "https://x-access-token:${GH_TOKEN}@github.com/${GITHUB_REPOSITORY}.git"
# Find the latest release branch matching the exact release/2.X
# pattern (no suffixes like release/2.31_hotfix).
RELEASE_BRANCH=$(
git branch -r \
| grep -E '^\s*origin/release/2\.[0-9]+$' \
| sed 's|.*origin/||' \
| sort -t. -k2 -n -r \
| head -1
)
if [ -z "$RELEASE_BRANCH" ]; then
echo "::error::No release branch found."
exit 1
fi
# Strip the release/ prefix for naming.
VERSION="${RELEASE_BRANCH#release/}"
BACKPORT_BRANCH="backport/${PR_NUMBER}-to-${VERSION}"
# Label applied to the cherry-pick PR so PRs for a specific
# release can be filtered easily (e.g. cherry-pick/v2.31).
CHERRY_PICK_LABEL="cherry-pick/v${VERSION}"
echo "Target branch: $RELEASE_BRANCH"
echo "Backport branch: $BACKPORT_BRANCH"
BOT_LOGIN="${APP_SLUG}[bot]"
BOT_ID=$(gh api "/users/${BOT_LOGIN}" --jq .id)
git config user.name "$BOT_LOGIN"
git config user.email "${BOT_ID}+${BOT_LOGIN}@users.noreply.github.com"
# Idempotency: if a cherry-pick PR already exists for this branch
# (open, closed, or merged), there is nothing to do. This is the
# primary guard so a re-run that previously pushed a branch but
# failed before opening the PR still recovers below.
EXISTING_PR=$(gh pr list --head "$BACKPORT_BRANCH" --base "$RELEASE_BRANCH" --state all --json number --jq '.[0].number // empty')
if [ -n "$EXISTING_PR" ]; then
echo "PR #${EXISTING_PR} already exists for ${BACKPORT_BRANCH}, skipping."
exit 0
fi
CONFLICT=false
CONFLICT_SUBJECT="cherry-pick of #${PR_NUMBER} failed: resolve conflicts manually"
if git ls-remote --exit-code origin "refs/heads/${BACKPORT_BRANCH}" >/dev/null 2>&1; then
# The branch exists from an earlier run that failed before opening
# the PR. Reuse it as-is and fall through to PR creation rather
# than starting over or bailing out.
echo "Backport branch ${BACKPORT_BRANCH} already exists; reusing it to open the PR."
# Keep the (conflicts) title if the earlier run pushed the
# conflict placeholder commit.
git fetch origin "+refs/heads/${BACKPORT_BRANCH}:refs/remotes/origin/${BACKPORT_BRANCH}"
if [ "$(git log -1 --format=%s "origin/${BACKPORT_BRANCH}")" = "$CONFLICT_SUBJECT" ]; then
CONFLICT=true
fi
else
# Create the backport branch from the target release branch.
git checkout -b "$BACKPORT_BRANCH" "origin/${RELEASE_BRANCH}"
# Cherry-pick the merge commit. Use -x to record provenance and
# -m1 to pick the first parent (the main branch side).
if ! git cherry-pick -x -m1 "$MERGE_SHA"; then
CONFLICT=true
echo "::warning::Cherry-pick to ${RELEASE_BRANCH} had conflicts."
# Abort the failed cherry-pick and create an empty commit with
# instructions so the PR can still be opened.
git cherry-pick --abort
git commit --allow-empty -m "${CONFLICT_SUBJECT}
Cherry-pick of ${MERGE_SHA} onto ${RELEASE_BRANCH} had conflicts.
To resolve:
git fetch origin ${BACKPORT_BRANCH}
git checkout ${BACKPORT_BRANCH}
git cherry-pick -x -m1 ${MERGE_SHA}
# resolve conflicts
git push origin ${BACKPORT_BRANCH}"
fi
git push origin "$BACKPORT_BRANCH"
fi
BODY=$(cat <<EOF
Cherry-pick of ${PR_URL}
Original PR: #${PR_NUMBER} — ${PR_TITLE}
Merge commit: ${MERGE_SHA}
Requested by: @${SENDER}
EOF
)
TITLE="${PR_TITLE} (#${PR_NUMBER})"
# Mark conflicts with a suffix, as backport.yaml does, so the title
# still starts with fix: for pr-cherry-pick-check.yaml.
if [ "$CONFLICT" = true ]; then
TITLE="${TITLE} (conflicts)"
fi
# Ensure the release-specific label exists. --force updates the label
# in place if it already exists, so re-runs and concurrent runs stay
# idempotent. Best-effort: label problems must never prevent the PR
# from being opened.
gh label create "$CHERRY_PICK_LABEL" \
--description "Cherry-pick PR targeting ${RELEASE_BRANCH}" \
--color "D93F0B" \
--force || echo "::warning::Could not create label ${CHERRY_PICK_LABEL}."
# Create the PR first, then attach label/assignee/reviewer
# separately. Requesting a review from (or assigning) the PR author
# is rejected by GitHub, and doing it inline with `gh pr create`
# under `set -e` would abort the job and leave no PR. Attaching them
# afterwards as best-effort guarantees the PR always gets created.
NEW_PR_URL=$(
gh pr create \
--base "$RELEASE_BRANCH" \
--head "$BACKPORT_BRANCH" \
--title "$TITLE" \
--body "$BODY"
)
gh pr edit "$NEW_PR_URL" --add-label "$CHERRY_PICK_LABEL" || echo "::warning::Could not add label ${CHERRY_PICK_LABEL} to ${NEW_PR_URL}."
gh pr edit "$NEW_PR_URL" --add-assignee "$SENDER" || echo "::warning::Could not assign @${SENDER} to ${NEW_PR_URL}."
gh pr edit "$NEW_PR_URL" --add-reviewer "$SENDER" || echo "::warning::Could not request review from @${SENDER} on ${NEW_PR_URL}."
# Comment on the original PR to notify the author.
COMMENT="Cherry-pick PR created: ${NEW_PR_URL}"
if [ "$CONFLICT" = true ]; then
COMMENT="${COMMENT} (⚠️ conflicts need manual resolution)"
fi
# Don't fail the job if commenting fails (e.g. the original PR is locked).
gh pr comment "$PR_NUMBER" --body "$COMMENT" || echo "::warning::Failed to comment on #${PR_NUMBER} (PR may be locked)."