From b04fec07765474b9b8dad19d9c36c85b920eb815 Mon Sep 17 00:00:00 2001 From: Sil Veltman Date: Mon, 23 Nov 2026 22:19:42 +0100 Subject: [PATCH 1/2] ci: Dependabot's patch and minor updates merge by themselves once the checks pass A Dependabot action for each repository's pull_request_target workflow turns on GitHub's squash auto-merge with the organization's app token, only where the default branch requires Check / Check and Review, for npm PRs of patch and minor updates from 1.0 up with only Dependabot's commits and no .github change. It turns auto-merge off again when a PR stops qualifying. Co-Authored-By: Claude Opus 5.5 --- .github/actions/dependabot/action.yml | 43 +++++++ .github/actions/dependabot/dependabot.cjs | 102 +++++++++++++++++ README.md | 29 ++++- tests/dependabot.test.mjs | 132 ++++++++++++++++++++++ 4 files changed, 305 insertions(+), 1 deletion(-) create mode 100644 .github/actions/dependabot/action.yml create mode 100644 .github/actions/dependabot/dependabot.cjs create mode 100644 tests/dependabot.test.mjs diff --git a/.github/actions/dependabot/action.yml b/.github/actions/dependabot/action.yml new file mode 100644 index 0000000..fe43bce --- /dev/null +++ b/.github/actions/dependabot/action.yml @@ -0,0 +1,43 @@ +name: Dependabot auto-merge +description: >- + Turns on GitHub's auto-merge for a Dependabot npm PR with only patch and + minor updates, in a repository whose default branch requires Check / Check + and Review. GitHub merges it once those pass. Everything else stays for a + person. Call it from an `on: pull_request_target` workflow, so the default + branch's file runs, and never check out the PR. +inputs: + app-client-id: + description: The organization's GitHub App client ID (vars.RELEASE_APP_CLIENT_ID). + default: "" + app-private-key: + description: Its private key (secrets.RELEASE_APP_PRIVATE_KEY). The app's token makes the merge start the workflows on main, which GITHUB_TOKEN's would not. + default: "" +runs: + using: composite + steps: + - name: Require the app credentials + shell: bash + env: + CLIENT_ID: ${{ inputs.app-client-id }} + HAS_KEY: ${{ inputs.app-private-key != '' }} + run: | + if [ -z "$CLIENT_ID" ] || [ "$HAS_KEY" != "true" ]; then + echo "::error::Auto-merge needs the organization's RELEASE_APP_CLIENT_ID variable and RELEASE_APP_PRIVATE_KEY secret in this repository." + exit 1 + fi + - name: Create app token + id: token + uses: actions/create-github-app-token@f418cff399f7aef4c2f0ad47e25ca7a6abbdd6fc # v3.4.0 + with: + client-id: ${{ inputs.app-client-id }} + private-key: ${{ inputs.app-private-key }} + permission-contents: write + permission-pull-requests: write + - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8 + env: + ACTION_PATH: ${{ github.action_path }} + with: + github-token: ${{ steps.token.outputs.token }} + script: | + const dependabot = require(`${process.env.ACTION_PATH}/dependabot.cjs`) + await dependabot({github, context, core}) diff --git a/.github/actions/dependabot/dependabot.cjs b/.github/actions/dependabot/dependabot.cjs new file mode 100644 index 0000000..69f2ce0 --- /dev/null +++ b/.github/actions/dependabot/dependabot.cjs @@ -0,0 +1,102 @@ +// Dependabot auto-merge (action.yml). It runs on pull_request_target, so the +// base branch's workflow runs with the app token and the PR cannot change it. +// It turns on GitHub's auto-merge for a Dependabot npm PR with only patch and +// minor updates; GitHub then merges it once the required checks pass. Merged +// with the app token, the push to main starts its workflows, as a person's +// merge would. Anything else stays for a person and is only noted. +const REQUIRED = ['Check / Check', 'Review']; + +// The biggest change from one version to another: patch, minor or major. +// Below 1.0 a minor step can break, and a pre-release is never routine, so +// both count as major. Anything unreadable counts as major too. +function change(from, to) { + const parse = version => /^v?(\d+)\.(\d+)\.(\d+)$/.exec(String(version).trim())?.slice(1).map(Number); + const [a, b] = [parse(from), parse(to)]; + if (!a || !b) return 'major'; + if (a[0] !== b[0] || a[0] === 0 && (a[1] !== b[1] || a[1] === 0 && a[2] !== b[2])) return 'major'; + if (a[1] !== b[1]) return 'minor'; + return 'patch'; +} + +// Every update the commit names, with its versions. Security updates carry +// no update-type in their metadata, so the versions decide. +function updates(message) { + const names = [...String(message).matchAll(/^- dependency-name: (\S+)$/gm)].map(match => match[1]); + const steps = [ + ...String(message).matchAll(/^Updates `([^`]+)` from (\S+?) to (\S+?)\.?$/gm), + ...String(message).matchAll(/^Bumps \[([^\]]+)\]\([^)]*\) from (\S+?) to (\S+?)\.?$/gm), + ].map(([, name, from, to]) => ({name, from, to})); + return names.map(name => { + const own = steps.filter(step => step.name === name); + return {name, change: own.length ? own.map(step => change(step.from, step.to)) + .reduce((a, b) => ['patch', 'minor', 'major'].indexOf(a) >= ['patch', 'minor', 'major'].indexOf(b) ? a : b) : 'major'}; + }); +} + +module.exports = async ({github, context, core}) => { + const pull = context.payload.pull_request; + if (!pull) throw new Error('Dependabot auto-merge runs on pull_request_target events only.'); + const {owner, repo} = context.repo; + const skip = reason => core.notice(`Left for a person: ${reason}`); + + if (pull.user?.login !== 'dependabot[bot]') return skip('not a Dependabot PR.'); + if (pull.head.repo?.full_name !== `${owner}/${repo}`) return skip('the head is not in this repository.'); + + // A Dependabot PR that no longer qualifies, say after a person's push or a + // rebase onto a major, loses the auto-merge an earlier run turned on. + const {data: current} = await github.rest.pulls.get({owner, repo, pull_number: pull.number}); + if (current.state !== 'open' || current.head.sha !== pull.head.sha) return skip('the PR changed; its newer run decides.'); + const stop = async reason => { + if (current.auto_merge) { + await github.graphql(`mutation($id: ID!) { + disablePullRequestAutoMerge(input: {pullRequestId: $id}) { pullRequest { number } } + }`, {id: pull.node_id}); + reason += ' Auto-merge is off again.'; + } + skip(reason); + }; + + if (!pull.head.ref.startsWith('dependabot/npm_and_yarn/')) return stop('only npm updates merge by themselves.'); + if (pull.base.ref !== context.payload.repository?.default_branch) return stop('it does not target the default branch.'); + if (current.draft) return stop('it is a draft.'); + + // Without required checks, auto-merge would merge at once, even when red. + const rules = (await github.rest.repos.getBranchRules({owner, repo, branch: pull.base.ref})).data; + const required = rules.filter(rule => rule.type === 'required_status_checks') + .flatMap(rule => rule.parameters.required_status_checks.map(check => check.context)); + const missing = REQUIRED.filter(name => !required.includes(name)); + if (missing.length) return stop(`${pull.base.ref} does not require ${missing.join(' and ')}.`); + + // Only Dependabot's own commits: a person's push makes it a person's PR. + const commits = (await github.rest.pulls.listCommits({owner, repo, pull_number: pull.number, per_page: 100})).data; + if (!commits.length || commits.some(commit => commit.author?.login !== 'dependabot[bot]')) { + return stop('it has commits from someone other than Dependabot.'); + } + const files = await github.paginate(github.rest.pulls.listFiles, {owner, repo, pull_number: pull.number, per_page: 100}); + if (files.some(file => file.filename.startsWith('.github/'))) return stop('it changes .github, which a person reviews.'); + + const list = updates(commits.at(-1).commit.message); + if (!list.length) return stop('its commit names no updates.'); + const majors = list.filter(update => update.change === 'major').map(update => update.name); + if (majors.length) return stop(`a major update: ${[...new Set(majors)].join(', ')}. Checks do not catch visual changes.`); + + if (current.auto_merge) return core.info(`Auto-merge is already on as ${current.auto_merge.merge_method}.`); + try { + await github.graphql(`mutation($id: ID!, $sha: GitObjectID!) { + enablePullRequestAutoMerge(input: {pullRequestId: $id, expectedHeadOid: $sha, mergeMethod: SQUASH}) { + pullRequest { number } + } + }`, {id: pull.node_id, sha: pull.head.sha}); + core.info(`Auto-merge is on for ${list.length} patch and minor updates; GitHub merges once ${REQUIRED.join(' and ')} pass.`); + } catch (error) { + // GitHub refuses auto-merge when the PR can already merge. + if (!/clean status/i.test(error.message)) { + return core.setFailed(`Auto-merge could not be turned on: ${error.message}`); + } + await github.rest.pulls.merge({owner, repo, pull_number: pull.number, sha: pull.head.sha, merge_method: 'squash'}); + core.info('The required checks had passed, so it merged now.'); + } +}; + +module.exports.change = change; +module.exports.updates = updates; diff --git a/README.md b/README.md index fa397cb..b0add70 100644 --- a/README.md +++ b/README.md @@ -30,4 +30,31 @@ Jobs that mostly wait, such as Test, Test live and Review, run on Blacksmith's A Live URL tests run after deployment, outside the build command. Product scenarios and fixture writes stay on previews. A repository may pass `live-test-email` and `live-test-password` only from its trusted main workflow for one ordinary login/read/sign-out smoke with its own limited account; browser recordings and signed-in artifacts stay off. -Keep repository auto-merge disabled except for content publishers. For CloudCannon's Publish button, a same-repository `preview` PR from `cloudcannon[bot]`, Review turns on GitHub's auto-merge with a merge commit once its checks and previews pass, and fails when GitHub refuses it; its job needs `contents: write` and `pull-requests: write`, and the repository both settings. Fulldev Sites publishes a content PR by asking GitHub to merge it once its required checks pass. Code PRs are merged by their agent. +Keep repository auto-merge disabled except for content publishers and Dependabot. For CloudCannon's Publish button, a same-repository `preview` PR from `cloudcannon[bot]`, Review turns on GitHub's auto-merge with a merge commit once its checks and previews pass, and fails when GitHub refuses it; its job needs `contents: write` and `pull-requests: write`, and the repository both settings. Fulldev Sites publishes a content PR by asking GitHub to merge it once its required checks pass. Code PRs are merged by their agent. + +Dependabot's routine npm updates merge by themselves through [the Dependabot action](.github/actions/dependabot): websites and the Astro and Vite templates call it from a `Dependabot` workflow on `pull_request_target`, which runs the default branch's file and never checks out the PR. It turns on GitHub's squash auto-merge, so GitHub merges once the required checks pass, only when the default branch requires `Check / Check` and `Review` (without them auto-merge would merge at once, even when red), every update is a patch or minor step from 1.0 up, every commit is Dependabot's, and nothing under `.github/` changes. Majors, pre-releases, other ecosystems and anything else stay for a person, because checks do not catch visual changes. The organization's GitHub App token (`RELEASE_APP_CLIENT_ID`, `RELEASE_APP_PRIVATE_KEY`) turns it on, so the merge starts the workflows on main; without both in the repository the job fails and nothing merges. The repository needs Allow auto-merge. + +```yaml +name: Dependabot + +# Dependabot's patch and minor npm updates merge by themselves once the +# required checks pass. pull_request_target runs this file from main, so a PR +# cannot change it; the action never checks out the PR. +on: + pull_request_target: + types: [opened, reopened, synchronize] + +permissions: {} + +jobs: + auto-merge: + name: Auto-merge + if: ${{ github.event.pull_request.user.login == 'dependabot[bot]' }} + runs-on: ${{ vars.CI_RUNNER || (github.event.repository.private == false && 'ubuntu-24.04') || 'blacksmith-2vcpu-ubuntu-2404-arm' }} + timeout-minutes: 5 + steps: + - uses: fulldotdev/.github/.github/actions/dependabot@ + with: + app-client-id: ${{ vars.RELEASE_APP_CLIENT_ID }} + app-private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }} +``` diff --git a/tests/dependabot.test.mjs b/tests/dependabot.test.mjs new file mode 100644 index 0000000..4e38724 --- /dev/null +++ b/tests/dependabot.test.mjs @@ -0,0 +1,132 @@ +import assert from 'node:assert/strict'; +import {createRequire} from 'node:module'; +import test from 'node:test'; + +const dependabot = createRequire(import.meta.url)('../.github/actions/dependabot/dependabot.cjs'); + +const message = (lines, names) => [ + 'Bump the security group across 1 directory with 2 updates', + '', + ...lines, + '', + '---', + 'updated-dependencies:', + ...names.flatMap(name => [`- dependency-name: ${name}`, ' dependency-version: 1.0.0', ' dependency-type: indirect', ' dependency-group: security']), + '...', +].join('\n'); +const minor = message(['Updates `qs` from 6.16.0 to 6.17.1', 'Updates `undici` from 7.30.0 to 7.30.2'], ['qs', 'undici']); + +// One run against a canned PR: returns notices, failures and what it merged. +async function run({pull = {}, rules = ['Check / Check', 'Review'], commits = [{login: 'dependabot[bot]', message: minor}], + files = ['package.json', 'pnpm-lock.yaml'], current = {}, refuse, defaultBranch = 'main'} = {}) { + const notices = []; + const failures = []; + const autoMerges = []; + const merges = []; + const disabled = []; + const github = { + rest: { + repos: {getBranchRules: async () => ({data: rules === null ? [] : [{type: 'pull_request'}, + {type: 'required_status_checks', parameters: {required_status_checks: rules.map(context => ({context}))}}]})}, + pulls: { + listCommits: async () => ({data: commits.map(commit => ({author: {login: commit.login}, commit: {message: commit.message}}))}), + listFiles: 'listFiles', + get: async () => ({data: {state: 'open', head: {sha: 'head'}, auto_merge: null, ...current}}), + merge: async args => { merges.push(args); }, + }, + }, + paginate: async method => { + assert.equal(method, 'listFiles'); + return files.map(filename => ({filename})); + }, + graphql: async (query, variables) => { + if (/disablePullRequestAutoMerge/.test(query)) return disabled.push(variables); + if (refuse) throw new Error(refuse); + assert.match(query, /mergeMethod: SQUASH/); + autoMerges.push(variables); + }, + }; + await dependabot({ + github, + context: {repo: {owner: 'o', repo: 'r'}, payload: {repository: {default_branch: defaultBranch}, pull_request: { + number: 1, node_id: 'PR1', draft: false, state: 'open', user: {login: 'dependabot[bot]'}, + head: {sha: 'head', ref: 'dependabot/npm_and_yarn/security-1', repo: {full_name: 'o/r'}}, base: {ref: 'main'}, ...pull}}}, + core: {notice: message => notices.push(message), info: () => {}, setFailed: message => failures.push(message)}, + }); + return {notices, failures, autoMerges, merges, disabled}; +} + +test('a change is patch, minor or major, and below 1.0 or unreadable it is major', () => { + assert.equal(dependabot.change('7.30.0', '7.30.2'), 'patch'); + assert.equal(dependabot.change('6.16.0', '6.17.1'), 'minor'); + assert.equal(dependabot.change('5.15.7', '7.4.7'), 'major'); + assert.equal(dependabot.change('0.2.3', '0.3.0'), 'major'); + assert.equal(dependabot.change('0.0.1', '0.0.2'), 'major'); + assert.equal(dependabot.change('0.2.3', '0.2.9'), 'patch'); + assert.equal(dependabot.change('1.0.0', '2.0.0-beta.2'), 'major'); + assert.equal(dependabot.change('v1.2.3', 'v1.3.0'), 'minor'); + assert.equal(dependabot.change('64ab729', 'f418cff'), 'major'); +}); + +test('updates read every named dependency, from group and single-update commits', () => { + assert.deepEqual(dependabot.updates(minor), [{name: 'qs', change: 'minor'}, {name: 'undici', change: 'patch'}]); + const single = message(['Bumps [astro](https://github.com/withastro/astro) from 5.15.7 to 7.4.7.'], ['astro']); + assert.deepEqual(dependabot.updates(single), [{name: 'astro', change: 'major'}]); + // A dependency without its versions in the message counts as major. + assert.deepEqual(dependabot.updates(message(['Updates `qs` from 6.16.0 to 6.17.1'], ['qs', 'hono'])), + [{name: 'qs', change: 'minor'}, {name: 'hono', change: 'major'}]); +}); + +test('a Dependabot npm PR with patch and minor updates gets squash auto-merge', async () => { + const {notices, failures, autoMerges} = await run(); + assert.deepEqual([notices, failures], [[], []]); + assert.deepEqual(autoMerges, [{id: 'PR1', sha: 'head'}]); +}); + +test('without both required checks, nothing merges, because auto-merge would merge at once', async () => { + for (const rules of [null, ['Check / Check'], ['Review']]) { + const {notices, autoMerges} = await run({rules}); + assert.match(notices[0], /does not require/); + assert.deepEqual(autoMerges, []); + } +}); + +test('a major update, a person\'s commit, a .github change or another ecosystem stays for a person', async () => { + const major = message(['Updates `astro` from 5.15.7 to 7.4.7', 'Updates `qs` from 6.16.0 to 6.17.1'], ['astro', 'qs']); + const cases = [ + [{commits: [{login: 'dependabot[bot]', message: major}]}, /major update: astro/], + [{commits: [{login: 'dependabot[bot]', message: minor}, {login: 'silveltman', message: 'Fix'}]}, /someone other than Dependabot/], + [{files: ['package.json', '.github/workflows/check.yml']}, /changes \.github/], + [{pull: {head: {sha: 'head', ref: 'dependabot/github_actions/x', repo: {full_name: 'o/r'}}}}, /only npm updates/], + [{pull: {user: {login: 'someone'}}}, /not a Dependabot PR/], + [{pull: {head: {sha: 'head', ref: 'dependabot/npm_and_yarn/x', repo: {full_name: 'fork/r'}}}}, /not in this repository/], + [{pull: {base: {ref: 'other'}}}, /default branch/], + [{current: {draft: true}}, /draft/], + [{commits: [{login: 'dependabot[bot]', message: 'Bump things'}]}, /names no updates/], + [{current: {head: {sha: 'newer'}}}, /newer run decides/], + ]; + for (const [options, reason] of cases) { + const {notices, autoMerges, merges} = await run(options); + assert.match(notices[0], reason); + assert.deepEqual([autoMerges, merges], [[], []]); + } +}); + +test('a PR that no longer qualifies loses the auto-merge an earlier run turned on', async () => { + const on = {auto_merge: {merge_method: 'squash'}}; + const pushed = await run({current: on, commits: [{login: 'dependabot[bot]', message: minor}, {login: 'silveltman', message: 'Fix'}]}); + assert.match(pushed.notices[0], /someone other than Dependabot\. Auto-merge is off again/); + assert.deepEqual(pushed.disabled, [{id: 'PR1'}]); + const major = message(['Updates `astro` from 5.15.7 to 7.4.7'], ['astro']); + assert.deepEqual((await run({current: on, commits: [{login: 'dependabot[bot]', message: major}]})).disabled, [{id: 'PR1'}]); + // Without auto-merge on, there is nothing to turn off. + assert.deepEqual((await run({commits: [{login: 'dependabot[bot]', message: major}]})).disabled, []); +}); + +test('auto-merge that is on stays, a PR that can already merge merges now, and a refusal fails', async () => { + assert.deepEqual((await run({current: {auto_merge: {merge_method: 'squash'}}})).autoMerges, []); + const clean = await run({refuse: 'Pull request is in clean status'}); + assert.deepEqual(clean.merges, [{owner: 'o', repo: 'r', pull_number: 1, sha: 'head', merge_method: 'squash'}]); + const refused = await run({refuse: 'Auto merge is not allowed for this repository'}); + assert.match(refused.failures[0], /could not be turned on: Auto merge is not allowed/); +}); From 899192840b0218ff78a8c0f80caa04028dff6ccf Mon Sep 17 00:00:00 2001 From: Sil Veltman Date: Mon, 23 Nov 2026 22:44:15 +0100 Subject: [PATCH 2/2] ci: read quoted scoped names, decide afresh each run, require signed commits Dependabot quotes scoped names in its metadata, so "@hono/node-server" never matched its version line and most security PRs counted as major. Each run now turns earlier auto-merge off first and back on only while the head qualifies, and only Dependabot's commits signed by GitHub count. A real security-group commit is a test fixture. Co-Authored-By: Claude Opus 5.5 --- .github/actions/dependabot/dependabot.cjs | 77 ++++++------ README.md | 2 +- tests/dependabot.test.mjs | 79 +++++++------ tests/fixtures/dependabot-security-group.txt | 118 +++++++++++++++++++ 4 files changed, 202 insertions(+), 74 deletions(-) create mode 100644 tests/fixtures/dependabot-security-group.txt diff --git a/.github/actions/dependabot/dependabot.cjs b/.github/actions/dependabot/dependabot.cjs index 69f2ce0..4b76c5f 100644 --- a/.github/actions/dependabot/dependabot.cjs +++ b/.github/actions/dependabot/dependabot.cjs @@ -1,14 +1,16 @@ // Dependabot auto-merge (action.yml). It runs on pull_request_target, so the // base branch's workflow runs with the app token and the PR cannot change it. -// It turns on GitHub's auto-merge for a Dependabot npm PR with only patch and -// minor updates; GitHub then merges it once the required checks pass. Merged -// with the app token, the push to main starts its workflows, as a person's -// merge would. Anything else stays for a person and is only noted. +// It turns on GitHub's auto-merge for a Dependabot npm PR with only routine +// updates; GitHub then merges it once the required checks pass. Merged with +// the app token, the push to main starts its workflows, as a person's merge +// would. Anything else stays for a person and is only noted. const REQUIRED = ['Check / Check', 'Review']; +const ORDER = ['patch', 'minor', 'major']; // The biggest change from one version to another: patch, minor or major. -// Below 1.0 a minor step can break, and a pre-release is never routine, so -// both count as major. Anything unreadable counts as major too. +// Below 1.0 a minor step can break, and so can any step below 0.1; a +// pre-release is never routine. All of those count as major, and so does +// anything unreadable. function change(from, to) { const parse = version => /^v?(\d+)\.(\d+)\.(\d+)$/.exec(String(version).trim())?.slice(1).map(Number); const [a, b] = [parse(from), parse(to)]; @@ -18,18 +20,19 @@ function change(from, to) { return 'patch'; } -// Every update the commit names, with its versions. Security updates carry -// no update-type in their metadata, so the versions decide. +// Every update the commit names, with its biggest change. Security updates +// carry no update-type in their metadata, so the versions decide. Dependabot +// quotes scoped names, such as "@hono/node-server". function updates(message) { - const names = [...String(message).matchAll(/^- dependency-name: (\S+)$/gm)].map(match => match[1]); + const text = String(message); + const names = [...text.matchAll(/^- dependency-name: "?([^"\s]+)"?$/gm)].map(match => match[1]); const steps = [ - ...String(message).matchAll(/^Updates `([^`]+)` from (\S+?) to (\S+?)\.?$/gm), - ...String(message).matchAll(/^Bumps \[([^\]]+)\]\([^)]*\) from (\S+?) to (\S+?)\.?$/gm), + ...text.matchAll(/^Updates `([^`]+)` from (\S+?) to (\S+?)\.?$/gm), + ...text.matchAll(/^Bumps \[([^\]]+)\]\([^)]*\) from (\S+?) to (\S+?)\.?$/gm), ].map(([, name, from, to]) => ({name, from, to})); return names.map(name => { - const own = steps.filter(step => step.name === name); - return {name, change: own.length ? own.map(step => change(step.from, step.to)) - .reduce((a, b) => ['patch', 'minor', 'major'].indexOf(a) >= ['patch', 'minor', 'major'].indexOf(b) ? a : b) : 'major'}; + const own = steps.filter(step => step.name === name).map(step => change(step.from, step.to)); + return {name, change: own.length ? own.reduce((a, b) => ORDER.indexOf(a) >= ORDER.indexOf(b) ? a : b) : 'major'}; }); } @@ -42,52 +45,48 @@ module.exports = async ({github, context, core}) => { if (pull.user?.login !== 'dependabot[bot]') return skip('not a Dependabot PR.'); if (pull.head.repo?.full_name !== `${owner}/${repo}`) return skip('the head is not in this repository.'); - // A Dependabot PR that no longer qualifies, say after a person's push or a - // rebase onto a major, loses the auto-merge an earlier run turned on. + // Each run decides afresh: auto-merge from an earlier run goes off first and + // comes back only if this head still qualifies. GitHub keeps it on through + // pushes by Dependabot and by people with write access. const {data: current} = await github.rest.pulls.get({owner, repo, pull_number: pull.number}); + if (current.auto_merge) { + await github.graphql(`mutation($id: ID!) { + disablePullRequestAutoMerge(input: {pullRequestId: $id}) { pullRequest { number } } + }`, {id: pull.node_id}); + } if (current.state !== 'open' || current.head.sha !== pull.head.sha) return skip('the PR changed; its newer run decides.'); - const stop = async reason => { - if (current.auto_merge) { - await github.graphql(`mutation($id: ID!) { - disablePullRequestAutoMerge(input: {pullRequestId: $id}) { pullRequest { number } } - }`, {id: pull.node_id}); - reason += ' Auto-merge is off again.'; - } - skip(reason); - }; - - if (!pull.head.ref.startsWith('dependabot/npm_and_yarn/')) return stop('only npm updates merge by themselves.'); - if (pull.base.ref !== context.payload.repository?.default_branch) return stop('it does not target the default branch.'); - if (current.draft) return stop('it is a draft.'); + if (!pull.head.ref.startsWith('dependabot/npm_and_yarn/')) return skip('only npm updates merge by themselves.'); + if (pull.base.ref !== context.payload.repository?.default_branch) return skip('it does not target the default branch.'); + if (current.draft) return skip('it is a draft.'); // Without required checks, auto-merge would merge at once, even when red. const rules = (await github.rest.repos.getBranchRules({owner, repo, branch: pull.base.ref})).data; const required = rules.filter(rule => rule.type === 'required_status_checks') .flatMap(rule => rule.parameters.required_status_checks.map(check => check.context)); const missing = REQUIRED.filter(name => !required.includes(name)); - if (missing.length) return stop(`${pull.base.ref} does not require ${missing.join(' and ')}.`); + if (missing.length) return skip(`${pull.base.ref} does not require ${missing.join(' and ')}.`); - // Only Dependabot's own commits: a person's push makes it a person's PR. + // Only Dependabot's own commits, which GitHub signs: anyone can set + // Dependabot as a commit's author, and a person's push makes it their PR. const commits = (await github.rest.pulls.listCommits({owner, repo, pull_number: pull.number, per_page: 100})).data; - if (!commits.length || commits.some(commit => commit.author?.login !== 'dependabot[bot]')) { - return stop('it has commits from someone other than Dependabot.'); - } + const dependabot = commit => commit.author?.login === 'dependabot[bot]' && commit.committer?.login === 'web-flow' + && commit.commit.verification?.verified === true; + if (!commits.length || !commits.every(dependabot)) return skip('it has commits that are not Dependabot\'s signed commits.'); const files = await github.paginate(github.rest.pulls.listFiles, {owner, repo, pull_number: pull.number, per_page: 100}); - if (files.some(file => file.filename.startsWith('.github/'))) return stop('it changes .github, which a person reviews.'); + if (files.some(file => file.filename.startsWith('.github/'))) return skip('it changes .github, which a person reviews.'); const list = updates(commits.at(-1).commit.message); - if (!list.length) return stop('its commit names no updates.'); + if (!list.length) return skip('its commit names no updates.'); const majors = list.filter(update => update.change === 'major').map(update => update.name); - if (majors.length) return stop(`a major update: ${[...new Set(majors)].join(', ')}. Checks do not catch visual changes.`); + if (majors.length) return skip(`a major update: ${[...new Set(majors)].join(', ')}. Checks do not catch visual changes.`); - if (current.auto_merge) return core.info(`Auto-merge is already on as ${current.auto_merge.merge_method}.`); try { await github.graphql(`mutation($id: ID!, $sha: GitObjectID!) { enablePullRequestAutoMerge(input: {pullRequestId: $id, expectedHeadOid: $sha, mergeMethod: SQUASH}) { pullRequest { number } } }`, {id: pull.node_id, sha: pull.head.sha}); - core.info(`Auto-merge is on for ${list.length} patch and minor updates; GitHub merges once ${REQUIRED.join(' and ')} pass.`); + core.info(`Auto-merge is on for ${list.length} routine updates; GitHub merges once ${REQUIRED.join(' and ')} pass.`); } catch (error) { // GitHub refuses auto-merge when the PR can already merge. if (!/clean status/i.test(error.message)) { diff --git a/README.md b/README.md index b0add70..a4be5b0 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Live URL tests run after deployment, outside the build command. Product scenario Keep repository auto-merge disabled except for content publishers and Dependabot. For CloudCannon's Publish button, a same-repository `preview` PR from `cloudcannon[bot]`, Review turns on GitHub's auto-merge with a merge commit once its checks and previews pass, and fails when GitHub refuses it; its job needs `contents: write` and `pull-requests: write`, and the repository both settings. Fulldev Sites publishes a content PR by asking GitHub to merge it once its required checks pass. Code PRs are merged by their agent. -Dependabot's routine npm updates merge by themselves through [the Dependabot action](.github/actions/dependabot): websites and the Astro and Vite templates call it from a `Dependabot` workflow on `pull_request_target`, which runs the default branch's file and never checks out the PR. It turns on GitHub's squash auto-merge, so GitHub merges once the required checks pass, only when the default branch requires `Check / Check` and `Review` (without them auto-merge would merge at once, even when red), every update is a patch or minor step from 1.0 up, every commit is Dependabot's, and nothing under `.github/` changes. Majors, pre-releases, other ecosystems and anything else stay for a person, because checks do not catch visual changes. The organization's GitHub App token (`RELEASE_APP_CLIENT_ID`, `RELEASE_APP_PRIVATE_KEY`) turns it on, so the merge starts the workflows on main; without both in the repository the job fails and nothing merges. The repository needs Allow auto-merge. +Dependabot's routine npm updates merge by themselves through [the Dependabot action](.github/actions/dependabot): websites and the Astro and Vite templates call it from a `Dependabot` workflow on `pull_request_target`, which runs the default branch's file and never checks out the PR. Each run first turns off auto-merge from an earlier run, then turns on GitHub's squash auto-merge again only when the default branch requires `Check / Check` and `Review` (without them auto-merge would merge at once, even when red), every update is a patch step or a minor step from 1.0 up, every commit is Dependabot's and signed by GitHub, and nothing under `.github/` changes. GitHub then merges once the required checks pass. Majors, minors below 1.0, pre-releases, other ecosystems and anything else stay for a person, because checks do not catch visual changes. The organization's GitHub App token (`RELEASE_APP_CLIENT_ID`, `RELEASE_APP_PRIVATE_KEY`) turns it on, so the merge starts the workflows on main; without both in the repository, or without the app installed there, the job fails and nothing merges. The repository needs Allow auto-merge. Any workflow in a repository that gets the key can mint the app's tokens, so share it only with these repositories, or keep it in an environment that only `main` may use, which `pull_request_target` runs count as. ```yaml name: Dependabot diff --git a/tests/dependabot.test.mjs b/tests/dependabot.test.mjs index 4e38724..8a79b58 100644 --- a/tests/dependabot.test.mjs +++ b/tests/dependabot.test.mjs @@ -1,9 +1,13 @@ import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; import {createRequire} from 'node:module'; import test from 'node:test'; const dependabot = createRequire(import.meta.url)('../.github/actions/dependabot/dependabot.cjs'); +// A real security-group commit message (fulldotdev/thegymharen#69), with a quoted scoped name. +const real = readFileSync(new URL('./fixtures/dependabot-security-group.txt', import.meta.url), 'utf8'); + const message = (lines, names) => [ 'Bump the security group across 1 directory with 2 updates', '', @@ -15,23 +19,24 @@ const message = (lines, names) => [ '...', ].join('\n'); const minor = message(['Updates `qs` from 6.16.0 to 6.17.1', 'Updates `undici` from 7.30.0 to 7.30.2'], ['qs', 'undici']); +const signed = msg => ({login: 'dependabot[bot]', committer: 'web-flow', verified: true, message: msg}); -// One run against a canned PR: returns notices, failures and what it merged. -async function run({pull = {}, rules = ['Check / Check', 'Review'], commits = [{login: 'dependabot[bot]', message: minor}], +// One run against a canned PR: returns notices, failures and the auto-merge calls. +async function run({pull = {}, rules = ['Check / Check', 'Review'], commits = [signed(minor)], files = ['package.json', 'pnpm-lock.yaml'], current = {}, refuse, defaultBranch = 'main'} = {}) { const notices = []; const failures = []; - const autoMerges = []; + const calls = []; const merges = []; - const disabled = []; const github = { rest: { repos: {getBranchRules: async () => ({data: rules === null ? [] : [{type: 'pull_request'}, {type: 'required_status_checks', parameters: {required_status_checks: rules.map(context => ({context}))}}]})}, pulls: { - listCommits: async () => ({data: commits.map(commit => ({author: {login: commit.login}, commit: {message: commit.message}}))}), + listCommits: async () => ({data: commits.map(commit => ({author: {login: commit.login}, committer: {login: commit.committer}, + commit: {message: commit.message, verification: {verified: commit.verified}}}))}), listFiles: 'listFiles', - get: async () => ({data: {state: 'open', head: {sha: 'head'}, auto_merge: null, ...current}}), + get: async () => ({data: {state: 'open', draft: false, head: {sha: 'head'}, auto_merge: null, ...current}}), merge: async args => { merges.push(args); }, }, }, @@ -40,23 +45,23 @@ async function run({pull = {}, rules = ['Check / Check', 'Review'], commits = [{ return files.map(filename => ({filename})); }, graphql: async (query, variables) => { - if (/disablePullRequestAutoMerge/.test(query)) return disabled.push(variables); + if (/disablePullRequestAutoMerge/.test(query)) return calls.push(['off', variables.id]); if (refuse) throw new Error(refuse); assert.match(query, /mergeMethod: SQUASH/); - autoMerges.push(variables); + calls.push(['on', variables.id, variables.sha]); }, }; await dependabot({ github, context: {repo: {owner: 'o', repo: 'r'}, payload: {repository: {default_branch: defaultBranch}, pull_request: { - number: 1, node_id: 'PR1', draft: false, state: 'open', user: {login: 'dependabot[bot]'}, + number: 1, node_id: 'PR1', user: {login: 'dependabot[bot]'}, head: {sha: 'head', ref: 'dependabot/npm_and_yarn/security-1', repo: {full_name: 'o/r'}}, base: {ref: 'main'}, ...pull}}}, core: {notice: message => notices.push(message), info: () => {}, setFailed: message => failures.push(message)}, }); - return {notices, failures, autoMerges, merges, disabled}; + return {notices, failures, calls, merges}; } -test('a change is patch, minor or major, and below 1.0 or unreadable it is major', () => { +test('a change is patch, minor or major, and below 1.0 or unreadable it counts as major', () => { assert.equal(dependabot.change('7.30.0', '7.30.2'), 'patch'); assert.equal(dependabot.change('6.16.0', '6.17.1'), 'minor'); assert.equal(dependabot.change('5.15.7', '7.4.7'), 'major'); @@ -68,8 +73,12 @@ test('a change is patch, minor or major, and below 1.0 or unreadable it is major assert.equal(dependabot.change('64ab729', 'f418cff'), 'major'); }); -test('updates read every named dependency, from group and single-update commits', () => { - assert.deepEqual(dependabot.updates(minor), [{name: 'qs', change: 'minor'}, {name: 'undici', change: 'patch'}]); +test('updates read every named dependency, quoted scoped names included', () => { + const list = dependabot.updates(real); + assert.equal(list.length, 11); + assert.deepEqual(list.find(update => update.name === '@hono/node-server'), {name: '@hono/node-server', change: 'patch'}); + assert.deepEqual(list.find(update => update.name === 'astro'), {name: 'astro', change: 'minor'}); + assert.ok(list.every(update => update.change !== 'major')); const single = message(['Bumps [astro](https://github.com/withastro/astro) from 5.15.7 to 7.4.7.'], ['astro']); assert.deepEqual(dependabot.updates(single), [{name: 'astro', change: 'major'}]); // A dependency without its versions in the message counts as major. @@ -77,54 +86,56 @@ test('updates read every named dependency, from group and single-update commits' [{name: 'qs', change: 'minor'}, {name: 'hono', change: 'major'}]); }); -test('a Dependabot npm PR with patch and minor updates gets squash auto-merge', async () => { - const {notices, failures, autoMerges} = await run(); - assert.deepEqual([notices, failures], [[], []]); - assert.deepEqual(autoMerges, [{id: 'PR1', sha: 'head'}]); +test('a Dependabot npm PR with routine updates gets squash auto-merge, the real commit too', async () => { + for (const commits of [[signed(minor)], [signed(real)]]) { + const {notices, failures, calls} = await run({commits}); + assert.deepEqual([notices, failures], [[], []]); + assert.deepEqual(calls, [['on', 'PR1', 'head']]); + } }); test('without both required checks, nothing merges, because auto-merge would merge at once', async () => { for (const rules of [null, ['Check / Check'], ['Review']]) { - const {notices, autoMerges} = await run({rules}); + const {notices, calls} = await run({rules}); assert.match(notices[0], /does not require/); - assert.deepEqual(autoMerges, []); + assert.deepEqual(calls, []); } }); -test('a major update, a person\'s commit, a .github change or another ecosystem stays for a person', async () => { +test('a major update, someone else\'s or unsigned commit, a .github change or another ecosystem stays for a person', async () => { const major = message(['Updates `astro` from 5.15.7 to 7.4.7', 'Updates `qs` from 6.16.0 to 6.17.1'], ['astro', 'qs']); const cases = [ - [{commits: [{login: 'dependabot[bot]', message: major}]}, /major update: astro/], - [{commits: [{login: 'dependabot[bot]', message: minor}, {login: 'silveltman', message: 'Fix'}]}, /someone other than Dependabot/], + [{commits: [signed(major)]}, /major update: astro/], + [{commits: [signed(minor), {...signed('Fix'), login: 'silveltman'}]}, /not Dependabot's signed commits/], + [{commits: [{...signed(minor), committer: 'silveltman', verified: false}]}, /not Dependabot's signed commits/], + [{commits: [{...signed(minor), verified: false}]}, /not Dependabot's signed commits/], [{files: ['package.json', '.github/workflows/check.yml']}, /changes \.github/], [{pull: {head: {sha: 'head', ref: 'dependabot/github_actions/x', repo: {full_name: 'o/r'}}}}, /only npm updates/], [{pull: {user: {login: 'someone'}}}, /not a Dependabot PR/], [{pull: {head: {sha: 'head', ref: 'dependabot/npm_and_yarn/x', repo: {full_name: 'fork/r'}}}}, /not in this repository/], [{pull: {base: {ref: 'other'}}}, /default branch/], [{current: {draft: true}}, /draft/], - [{commits: [{login: 'dependabot[bot]', message: 'Bump things'}]}, /names no updates/], + [{commits: [signed('Bump things')]}, /names no updates/], [{current: {head: {sha: 'newer'}}}, /newer run decides/], ]; for (const [options, reason] of cases) { - const {notices, autoMerges, merges} = await run(options); + const {notices, calls, merges} = await run(options); assert.match(notices[0], reason); - assert.deepEqual([autoMerges, merges], [[], []]); + assert.deepEqual([calls, merges], [[], []]); } }); -test('a PR that no longer qualifies loses the auto-merge an earlier run turned on', async () => { +test('each run turns earlier auto-merge off first and back on only while the head qualifies', async () => { const on = {auto_merge: {merge_method: 'squash'}}; - const pushed = await run({current: on, commits: [{login: 'dependabot[bot]', message: minor}, {login: 'silveltman', message: 'Fix'}]}); - assert.match(pushed.notices[0], /someone other than Dependabot\. Auto-merge is off again/); - assert.deepEqual(pushed.disabled, [{id: 'PR1'}]); + assert.deepEqual((await run({current: on})).calls, [['off', 'PR1'], ['on', 'PR1', 'head']]); const major = message(['Updates `astro` from 5.15.7 to 7.4.7'], ['astro']); - assert.deepEqual((await run({current: on, commits: [{login: 'dependabot[bot]', message: major}]})).disabled, [{id: 'PR1'}]); - // Without auto-merge on, there is nothing to turn off. - assert.deepEqual((await run({commits: [{login: 'dependabot[bot]', message: major}]})).disabled, []); + for (const options of [{commits: [signed(major)]}, {commits: [signed(minor), {...signed('Fix'), login: 'silveltman'}]}, + {current: {...on, head: {sha: 'newer'}}}]) { + assert.deepEqual((await run({current: on, ...options})).calls, [['off', 'PR1']]); + } }); -test('auto-merge that is on stays, a PR that can already merge merges now, and a refusal fails', async () => { - assert.deepEqual((await run({current: {auto_merge: {merge_method: 'squash'}}})).autoMerges, []); +test('a PR that can already merge merges now, and any other refusal fails', async () => { const clean = await run({refuse: 'Pull request is in clean status'}); assert.deepEqual(clean.merges, [{owner: 'o', repo: 'r', pull_number: 1, sha: 'head', merge_method: 'squash'}]); const refused = await run({refuse: 'Auto merge is not allowed for this repository'}); diff --git a/tests/fixtures/dependabot-security-group.txt b/tests/fixtures/dependabot-security-group.txt new file mode 100644 index 0000000..50010a2 --- /dev/null +++ b/tests/fixtures/dependabot-security-group.txt @@ -0,0 +1,118 @@ +Bump the security group across 1 directory with 11 updates + +Bumps the security group with 11 updates in the / directory: + +| Package | From | To | +| --- | --- | --- | +| [astro](https://github.com/withastro/astro/tree/HEAD/packages/astro) | `7.3.8` | `7.4.7` | +| [@hono/node-server](https://github.com/honojs/node-server) | `2.1.4` | `2.1.11` | +| [body-parser](https://github.com/expressjs/body-parser) | `2.3.0` | `2.4.0` | +| [fast-uri](https://github.com/fastify/fast-uri) | `3.1.8` | `3.1.9` | +| [fast-xml-parser](https://github.com/NaturalIntelligence/fast-xml-parser) | `5.11.2` | `5.12.1` | +| [glob](https://github.com/isaacs/node-glob) | `13.0.6` | `13.0.7` | +| [ip-address](https://github.com/beaugunderson/ip-address) | `10.7.3` | `10.7.6` | +| [node-forge](https://github.com/digitalbazaar/forge) | `1.4.0` | `1.4.3` | +| [qs](https://github.com/ljharb/qs) | `6.16.0` | `6.17.1` | +| [systeminformation](https://github.com/sebhildebrandt/systeminformation) | `5.33.15` | `5.33.23` | +| [undici](https://github.com/nodejs/undici) | `7.30.0` | `7.30.2` | + + + +Updates `astro` from 7.3.8 to 7.4.7 +- [Release notes](https://github.com/withastro/astro/releases) +- [Changelog](https://github.com/withastro/astro/blob/main/packages/astro/CHANGELOG.md) +- [Commits](https://github.com/withastro/astro/commits/astro@7.4.7/packages/astro) + +Updates `@hono/node-server` from 2.1.4 to 2.1.11 +- [Release notes](https://github.com/honojs/node-server/releases) +- [Commits](https://github.com/honojs/node-server/compare/v2.1.4...v2.1.11) + +Updates `body-parser` from 2.3.0 to 2.4.0 +- [Release notes](https://github.com/expressjs/body-parser/releases) +- [Changelog](https://github.com/expressjs/body-parser/blob/master/HISTORY.md) +- [Commits](https://github.com/expressjs/body-parser/compare/v2.3.0...v2.4.0) + +Updates `fast-uri` from 3.1.8 to 3.1.9 +- [Release notes](https://github.com/fastify/fast-uri/releases) +- [Commits](https://github.com/fastify/fast-uri/compare/v3.1.8...v3.1.9) + +Updates `fast-xml-parser` from 5.11.2 to 5.12.1 +- [Release notes](https://github.com/NaturalIntelligence/fast-xml-parser/releases) +- [Changelog](https://github.com/NaturalIntelligence/fast-xml-parser/blob/master/CHANGELOG.md) +- [Commits](https://github.com/NaturalIntelligence/fast-xml-parser/compare/v5.11.2...v5.12.1) + +Updates `glob` from 13.0.6 to 13.0.7 +- [Release notes](https://github.com/isaacs/node-glob/releases) +- [Changelog](https://github.com/isaacs/node-glob/blob/main/changelog.md) +- [Commits](https://github.com/isaacs/node-glob/compare/v13.0.6...v13.0.7) + +Updates `ip-address` from 10.7.3 to 10.7.6 +- [Release notes](https://github.com/beaugunderson/ip-address/releases) +- [Commits](https://github.com/beaugunderson/ip-address/compare/v10.7.3...v10.7.6) + +Updates `node-forge` from 1.4.0 to 1.4.3 +- [Changelog](https://github.com/digitalbazaar/forge/blob/main/CHANGELOG.md) +- [Commits](https://github.com/digitalbazaar/forge/compare/v1.4.0...v1.4.3) + +Updates `qs` from 6.16.0 to 6.17.1 +- [Changelog](https://github.com/ljharb/qs/blob/main/CHANGELOG.md) +- [Commits](https://github.com/ljharb/qs/compare/v6.16.0...v6.17.1) + +Updates `systeminformation` from 5.33.15 to 5.33.23 +- [Release notes](https://github.com/sebhildebrandt/systeminformation/releases) +- [Changelog](https://github.com/sebhildebrandt/systeminformation/blob/master/CHANGELOG.md) +- [Commits](https://github.com/sebhildebrandt/systeminformation/compare/v5.33.15...v5.33.23) + +Updates `undici` from 7.30.0 to 7.30.2 +- [Release notes](https://github.com/nodejs/undici/releases) +- [Commits](https://github.com/nodejs/undici/compare/v7.30.0...v7.30.2) + +--- +updated-dependencies: +- dependency-name: astro + dependency-version: 7.4.7 + dependency-type: direct:production + dependency-group: security +- dependency-name: "@hono/node-server" + dependency-version: 2.1.11 + dependency-type: indirect + dependency-group: security +- dependency-name: body-parser + dependency-version: 2.4.0 + dependency-type: indirect + dependency-group: security +- dependency-name: fast-uri + dependency-version: 3.1.9 + dependency-type: indirect + dependency-group: security +- dependency-name: fast-xml-parser + dependency-version: 5.12.1 + dependency-type: indirect + dependency-group: security +- dependency-name: glob + dependency-version: 13.0.7 + dependency-type: indirect + dependency-group: security +- dependency-name: ip-address + dependency-version: 10.7.6 + dependency-type: indirect + dependency-group: security +- dependency-name: node-forge + dependency-version: 1.4.3 + dependency-type: indirect + dependency-group: security +- dependency-name: qs + dependency-version: 6.17.1 + dependency-type: indirect + dependency-group: security +- dependency-name: systeminformation + dependency-version: 5.33.23 + dependency-type: indirect + dependency-group: security +- dependency-name: undici + dependency-version: 7.30.2 + dependency-type: indirect + dependency-group: security +... + +Signed-off-by: dependabot[bot]