Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions .github/actions/dependabot/action.yml
Original file line number Diff line number Diff line change
@@ -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})
101 changes: 101 additions & 0 deletions .github/actions/dependabot/dependabot.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
// 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 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 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)];
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 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 text = String(message);
const names = [...text.matchAll(/^- dependency-name: "?([^"\s]+)"?$/gm)].map(match => match[1]);
const steps = [
...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).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'};
});
}

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.');

// 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.');
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 skip(`${pull.base.ref} does not require ${missing.join(' and ')}.`);

// 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;
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 skip('it changes .github, which a person reviews.');

const list = updates(commits.at(-1).commit.message);
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 skip(`a major update: ${[...new Set(majors)].join(', ')}. Checks do not catch visual changes.`);

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} 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)) {
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;
29 changes: 28 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. 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

# 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@<sha>
with:
app-client-id: ${{ vars.RELEASE_APP_CLIENT_ID }}
app-private-key: ${{ secrets.RELEASE_APP_PRIVATE_KEY }}
```
143 changes: 143 additions & 0 deletions tests/dependabot.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
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',
'',
...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']);
const signed = msg => ({login: 'dependabot[bot]', committer: 'web-flow', verified: true, message: msg});

// 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 calls = [];
const merges = [];
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}, committer: {login: commit.committer},
commit: {message: commit.message, verification: {verified: commit.verified}}}))}),
listFiles: 'listFiles',
get: async () => ({data: {state: 'open', draft: false, 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 calls.push(['off', variables.id]);
if (refuse) throw new Error(refuse);
assert.match(query, /mergeMethod: SQUASH/);
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', 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, calls, merges};
}

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');
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, 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.
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 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, calls} = await run({rules});
assert.match(notices[0], /does not require/);
assert.deepEqual(calls, []);
}
});

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: [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: [signed('Bump things')]}, /names no updates/],
[{current: {head: {sha: 'newer'}}}, /newer run decides/],
];
for (const [options, reason] of cases) {
const {notices, calls, merges} = await run(options);
assert.match(notices[0], reason);
assert.deepEqual([calls, merges], [[], []]);
}
});

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'}};
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']);
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('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'});
assert.match(refused.failures[0], /could not be turned on: Auto merge is not allowed/);
});
Loading