diff --git a/changelog.d/893-release-write-guard.security.md b/changelog.d/893-release-write-guard.security.md new file mode 100644 index 00000000..4bfea728 --- /dev/null +++ b/changelog.d/893-release-write-guard.security.md @@ -0,0 +1 @@ +Publishing a release, from the release form or from the readiness page's tag button, now needs a fresh GitHub confirmation and is paced by the destructive class limit like the other privileged writes, and its preflight refuses a target commit the default branch does not contain instead of tagging it. The containment check reads `compare/{defaultBranch}...{target}`, where `behind` and `identical` mean the default branch contains the target; a target that is `ahead` of the default branch or `diverged` from it is `target_not_on_default`, and a compare that cannot be read is refused rather than assumed. A tag push runs the workflows committed in the tagged tree, so the ancestry check is what keeps "this release was built from this repository at this commit" checkable. The previous-version scan walks the tags newest-first and stops at the first one reachable from the target, so a release cut from a commit older than the newest tags still sees its real previous version instead of skipping the "nothing to release" and "not higher" refusals. diff --git a/docs/architecture.md b/docs/architecture.md index a4d1ec00..7d1aef75 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -2623,12 +2623,39 @@ version tag is the highest SemVer tag whose commit is an ancestor of the target order), so "nothing to release" and "not higher than what shipped" are decidable from the repository's own history. -The preflight is read-only (five GETs) and checks, in this order: the version -parses; the confirmed SHA is a commit in the repository; the default branch is -protected by required checks (the gate onboarding of #543); a tag-triggered -`.github/workflows/release.yml` exists at the target commit; the tag does not -exist; there is something to release; the version is higher than the previous -tag. A not-higher refusal carries the next legal version, and the page shows it. +The preflight is read-only — every call is a GET — and checks, in this order: the +version parses; the confirmed SHA is a commit in the repository; the default +branch contains that commit; the default branch is protected by required checks +(the gate onboarding of #543); a tag-triggered `.github/workflows/release.yml` +exists at the target commit; the tag does not exist; there is something to +release; the version is higher than the previous tag. A not-higher refusal +carries the next legal version, and the page shows it. + +The containment check reads `compare/{defaultBranch}...{target}`, so `behind` +means the target is an ancestor of the default branch — the branch contains it — +and `identical` means the same commit; only those two are accepted. `ahead` means +the target carries commits the default branch lacks, which is the unmerged branch +this check exists to stop, and `diverged` shares no base with it; both are +`target_not_on_default`, and a compare that cannot be read is +`ancestry_unreadable` rather than a pass on an assumption. A tag push runs the +workflows committed in the tagged tree, so a target the default branch never +contained would make "this release was built from this repository at this commit" +uncheckable. The previous-version scan decides ancestry first: it walks the +SemVer tags newest-first and stops at the first one the target is ahead of or +equal to, because that is the highest reachable tag. A target older than the +newest tags therefore still knows its real previous release; capping the walk to +the ten newest tags before the ancestry test did not, and it silently skipped +both "nothing to release" and "not higher" for such a target, so a downgrade +passed. The walk costs one compare per tag newer than the previous release, and +the destructive class limit on the route is what paces repeats. Both routes that +write a tag — this release POST and the readiness page's tag button — take the +destructive class limit and a fresh GitHub confirmation; the release POST is +filed under the destructive route class, beside the other ref writes. On the +readiness route the confirmation is checked before the branch is read +(`src/app.ts:2508-2509`). The release POST parses its own form body — version and +SHA, no GitHub read — and only then requires the confirmation +(`src/app.ts:2554-2559`), so on neither route does a GitHub read or a token +precede it. A tag-triggered workflow means a `tags:` filter directly under the `push:` event. The filter's depth is read from the block instead of assumed to be two spaces, so diff --git a/docs/security.md b/docs/security.md index ff74a56e..0d4cddce 100644 --- a/docs/security.md +++ b/docs/security.md @@ -135,9 +135,13 @@ therefore require a GitHub confirmation inside `RECENT_AUTH_MINUTES` (default 15 tracked as `sessions.recent_auth_at`: - Gated actions: repository delete, the repository settings POST, the repository - role POST, quota changes, API-token creation and revocation, admin - approve/reject, stopping a FlyBot instance, promoting a user's platform role, - stopping the platform, and deleting a model provider. The settings POST is + role POST, publishing a release tag — both the release POST and the + release-readiness tag POST, audited as `repo.release` and `repo.release.tag` — + quota changes, API-token creation and + revocation, admin approve/reject, stopping a FlyBot instance, promoting a + user's platform role, stopping the platform, and deleting a model provider. Both + tag-writing routes are also paced by the destructive class limit, because a tag + is a ref write and its preflight reads tags. The settings POST is gated on either of two paths: turning a repository's auto-merge on or off, audited as `repo.auto_merge`, and changing the pre-merge policy — branch protection, the stage gate, the allowed and denied paths, the target branch and diff --git a/src/app.ts b/src/app.ts index 057ed458..b2120b2c 100644 --- a/src/app.ts +++ b/src/app.ts @@ -2496,11 +2496,17 @@ export async function buildApp(options: BuildOptions): Promise { return ok(`已冻结候选 v${String(frozen.version)}(${frozen.hash.slice(0, 12)});stable 未改动。 / froze candidate v${String(frozen.version)} (${frozen.hash.slice(0, 12)}); stable was not changed`) }) - app.post('/repos/:id/release-readiness/tag', async (request, reply) => { + // #893: this route writes the same ref as the release POST below, through the + // same preflight, so it takes the same two guards. The maintainer check answers + // first because it is the permission boundary; a maintainer whose session has + // not confirmed recently is asked to confirm before any version, head or token + // is read. + app.post('/repos/:id/release-readiness/tag', { config: { rateLimit: destructiveClassLimit } }, async (request, reply) => { const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true) const back = `/repos/${repo.id}/release-readiness` const fail = (message: string) => reply.redirect(`${back}?error=${encodeURIComponent(message)}`) if (repo.repo_role !== 'maintainer') return fail('只有上游仓库的 maintainer 可以打标签。 / Only a maintainer of the upstream repository can tag it') + if (requireRecentAuth(request, reply, viewer, 'repo.release.tag', back)) return reply const body = form(request) const version = String(body.version ?? '').trim() const headSha = String(body.head ?? '').trim().toLowerCase() @@ -2537,12 +2543,20 @@ export async function buildApp(options: BuildOptions): Promise { // #546: a maintainer-supplied version and a confirmed full SHA. The preflight // is read-only; only a plan that passes every check reaches the tag write, and // the tag is annotated and created through the repository's installation token. - app.post('/repos/:id/release', async (request, reply) => { + // #893: publishing a release writes a tag ref, and a tag push runs the + // workflows in the tagged tree. It therefore carries the destructive class + // budget — `destructiveClassLimit` is that class read from config, the shape + // #708 added so the ceiling is an operator setting rather than a literal, and + // it defaults to the same 60 a minute as `destructiveLimit` — and it proves + // presence with `requireRecentAuth` before it resolves a token or compares a + // single tag. + app.post('/repos/:id/release', { config: { rateLimit: destructiveClassLimit } }, async (request, reply) => { const { viewer, repo } = ownedRepo(request, String((request.params as Record).id), true, true) const body = form(request) const version = String(body.version ?? '').trim() const targetSha = String(body.sha ?? '').trim().toLowerCase() const back = `/repos/${repo.id}?release=1` + if (requireRecentAuth(request, reply, viewer, 'repo.release', back)) return reply if (!/^[0-9a-f]{40}$/.test(targetSha)) return reply.redirect(`${back}&refused=${encodeURIComponent('confirm the full 40-character commit SHA')}`) if (body.confirm !== '1') return reply.redirect(`${back}&refused=${encodeURIComponent('the release must be confirmed')}`) const owner = repo.upstream_owner || repo.owner diff --git a/src/lib/routeClasses.ts b/src/lib/routeClasses.ts index 77578026..71bd594a 100644 --- a/src/lib/routeClasses.ts +++ b/src/lib/routeClasses.ts @@ -48,6 +48,9 @@ const DESTRUCTIVE_ROUTE_LIST = [ // already takes the destructive window; the class follows the window. 'POST /repos/:id/rules', 'POST /repos/:id/role', + // #893: a release writes a tag ref, so it takes the destructive window and it + // is filed here with the other ref writes rather than with the work starters. + 'POST /repos/:id/release', 'POST /repos/:id/release-readiness/tag', 'POST /repos/:id/security-findings/:findingId/dismiss', 'POST /admin/deployments/promote', @@ -78,7 +81,6 @@ const EXPENSIVE_ROUTE_LIST = [ // #544 slice 8: run-now starts a job the moment the maintainer asks, so it is // a start of real work like the schedule save beside it. 'POST /repos/:id/schedule/run-now', - 'POST /repos/:id/release', 'POST /repos/:id/releases/:releaseId/check', 'POST /repos/:id/gate/sessions', 'POST /repos/:id/gate/sessions/:sessionId/confirm', diff --git a/src/releases/release.ts b/src/releases/release.ts index 93b6432f..5201508c 100644 --- a/src/releases/release.ts +++ b/src/releases/release.ts @@ -92,6 +92,14 @@ export const releaseRefusals = { // The installation token is what writes the tag. Without Contents: write the // write is refused before anything exists, and the operator needs the name of // the permission rather than the upstream sentence GitHub returns. + // #893: a tag is a ref write, and pushing it runs the workflows committed in + // the tagged tree. A target the default branch never contained would make + // "this release was built from this repository at this commit" uncheckable, so + // ancestry is proven before anything is written. The status is the one + // `compare/{defaultBranch}...{target}` reports, where `ahead` means the target + // holds commits the default branch does not — the unmerged branch refused here. + targetNotOnDefault: (sha: string, branch: string, status: string): string => `${sha} is ${status === 'ahead' ? 'ahead of' : 'not contained in'} the default branch ${branch}; nothing was tagged, because a release is cut from a commit the default branch contains`, + ancestryUnreadable: (branch: string): string => `the default branch ${branch} could not be compared with the target commit; nothing was tagged, because ancestry is required before a ref write`, tagScopeMissing: (status: number): string => status === 404 // A 404 does not prove a missing permission: it also means the App cannot see // the repository any more. Both causes are named, neither is asserted. @@ -111,6 +119,10 @@ export interface ReleasePlanInput { export type ReleaseRefusalCode = | 'invalid_version' | 'target_missing' + // #893: the target exists but the default branch does not contain it, or the + // ancestry compare could not be read (fail closed). + | 'target_not_on_default' + | 'ancestry_unreadable' | 'missing_gate' | 'missing_release_workflow' | 'tag_exists' @@ -315,10 +327,10 @@ export interface ReleaseLookupClient { getBranchProtection(owner: string, name: string, branch: string): Promise<{ protected: boolean; requiredChecks: string[]; requiredApprovals: number } | null> } -// The preflight is read-only: five GETs decide whether a tag may be written, and -// the answer is the plan a maintainer confirms. Nothing here writes. The commit -// is checked first because a maintainer types that SHA by hand: a missing object -// must be a named refusal here, not a 404 from `compare` or a 422 from the write. +// The preflight is read-only: every call is a GET, and the answer is the plan a +// maintainer confirms. Nothing here writes. The commit is checked first because +// a maintainer types that SHA by hand: a missing object must be a named refusal +// here, not a 404 from `compare` or a 422 from the write. export async function releasePreflight( client: ReleaseLookupClient, input: { owner: string; name: string; defaultBranch: string; requestedVersion: string; targetSha: string }, @@ -327,16 +339,46 @@ export async function releasePreflight( if (!commit) { return { ok: false, code: 'target_missing', message: `${input.targetSha} is not a commit in this repository` } } + // #893: the commit exists, but that says nothing about which branch contains + // it. GitHub's compare is `base...head`, so on + // `compare/{defaultBranch}...{target}` `behind` means the target is an + // ancestor of the default branch — the branch contains it — and `identical` + // means the same commit; those two are the accepted answers. `ahead` is a + // target the branch does not contain (an unmerged branch) and `diverged` + // shares no base with it; both are refused, and a compare that cannot be read + // fails closed rather than passing on an assumption. + let ancestry: { status: string; aheadBy: number } | null = null + try { + ancestry = await client.compareCommits(input.owner, input.name, input.defaultBranch, input.targetSha) + } catch { + ancestry = null + } + if (ancestry === null) { + return { ok: false, code: 'ancestry_unreadable', message: releaseRefusals.ancestryUnreadable(input.defaultBranch) } + } + if (ancestry.status !== 'behind' && ancestry.status !== 'identical') { + return { ok: false, code: 'target_not_on_default', message: releaseRefusals.targetNotOnDefault(input.targetSha, input.defaultBranch, ancestry.status) } + } const tags = await client.listTags(input.owner, input.name) const candidates: ReleaseTag[] = [] - for (const tag of tags) { - if (parseVersion(tag.name) === null) continue + // #893: the previous version is the highest reachable SemVer tag, so + // reachability decides first and the walk stops at the first tag that + // qualifies: a tag the target is not ahead of is not an ancestor of it. The + // walk visits the tags newest-first, which is one compare per tag newer than + // the previous release — the destructive class limit on the route is what + // paces that. Capping to the ten newest tags *before* the test was wrong: a + // target older than them lost its real previous release, `previous` was + // undefined, and both "nothing to release" and "not higher" were skipped, so a + // downgrade passed. + const semverTags = tags + .filter((tag) => parseVersion(tag.name) !== null) + .sort((left, right) => compareVersions(right.name, left.name)) + for (const tag of semverTags) { const compare = await client.compareCommits(input.owner, input.name, tag.name, input.targetSha) - candidates.push({ - name: tag.name, - sha: tag.sha, - targetCommitsAhead: compare.status === 'ahead' || compare.status === 'identical' ? (compare.status === 'identical' ? 0 : compare.aheadBy) : null, - }) + const targetCommitsAhead = compare.status === 'identical' ? 0 : compare.status === 'ahead' ? compare.aheadBy : null + if (targetCommitsAhead === null) continue + candidates.push({ name: tag.name, sha: tag.sha, targetCommitsAhead }) + break } const workflow = await client.getRepoFile(input.owner, input.name, '.github/workflows/release.yml', input.targetSha) const protection = await client.getBranchProtection(input.owner, input.name, input.defaultBranch) diff --git a/test/recentAuth.test.ts b/test/recentAuth.test.ts index 9664ebeb..fc19749a 100644 --- a/test/recentAuth.test.ts +++ b/test/recentAuth.test.ts @@ -617,3 +617,31 @@ test('a fresh session does not render the stale-confirmation banner', async () = await built.close() } }) + +test('a stale session cannot publish a release without a fresh confirmation', async () => { + const { built, store } = await build() + try { + const user = makeUser(store, { login: 'stale-release', status: 'approved' }) + const repo = repoFor(store, user.id) + const { raw, cookie, csrf } = sessionFor(built, user) + clearRecentAuth(store, raw) + const refused = await built.app.inject({ + method: 'POST', + url: `/repos/${repo.id}/release`, + headers: { cookie, referer: `http://127.0.0.1:9999/repos/${repo.id}?release=1`, 'content-type': 'application/x-www-form-urlencoded' }, + payload: formBody({ csrf, version: 'v1.0.0', sha: 'a'.repeat(40), confirm: '1' }), + }) + assert.equal(refused.statusCode, 302) + assert.match(String(refused.headers.location), /^\/auth\/github\/reauthorize\?next=/, 'a release needs a fresh GitHub confirmation') + const audit = store.listAudit(20).find((row) => row.action === 'recent_auth_required') + assert.ok(audit !== undefined, 'the refusal must be audited') + assert.match(String(audit.detail), /repo\.release/, 'the audit must name the release action') + assert.equal( + store.listAudit(20).some((row) => row.action === 'release.tagged'), + false, + 'a refused confirmation must not have tagged anything', + ) + } finally { + await built.close() + } +}) diff --git a/test/releaseTag.test.ts b/test/releaseTag.test.ts index 32abb37b..a4a42b2c 100644 --- a/test/releaseTag.test.ts +++ b/test/releaseTag.test.ts @@ -178,7 +178,7 @@ test('only a tags: entry inside the on: block counts as a tag-triggered workflow const client = { async commitExists() { return true }, async listTags() { return [{ name: 'v1.0.0', sha: 'b'.repeat(40) }, { name: 'nightly', sha: 'd'.repeat(40) }] }, - async compareCommits() { return { status: 'ahead', aheadBy: 5 } }, + async compareCommits(_owner: string, _name: string, base: string) { return base === 'main' ? { status: 'behind', aheadBy: 0 } : { status: 'ahead', aheadBy: 5 } }, async getRepoFile() { return 'on:\n push:\n tags: [\'v*\']\n' }, async getBranchProtection() { return { protected: true, requiredChecks: ['ci-ok'], requiredApprovals: 1 } }, } @@ -205,6 +205,122 @@ test('a target SHA that is not a commit is refused by name, before any tag is wr assert.match((plan as { message: string }).message, /not a commit/) }) +function ancestryClient(options: { status: string | 'throw'; tagStatus?: string; tags?: number }): { client: never; compares: () => number } { + let compares = 0 + const tagStatus = options.tagStatus ?? 'ahead' + const count = options.tags ?? 1 + const client = { + async commitExists() { return true }, + async listTags() { + return Array.from({ length: count }, (_, index) => ({ name: `v1.${String(index)}.0`, sha: 'b'.repeat(40) })) + }, + async compareCommits(_owner: string, _name: string, base: string) { + compares += 1 + if (base === 'main') { + if (options.status === 'throw') throw new GithubError(500, 'compare unavailable') + return { status: options.status, aheadBy: options.status === 'ahead' ? 3 : 0 } + } + return { status: tagStatus, aheadBy: tagStatus === 'ahead' ? 2 : 0 } + }, + async getRepoFile() { return "on:\n push:\n tags: ['v*']\n" }, + async getBranchProtection() { return { protected: true, requiredChecks: ['ci-ok'], requiredApprovals: 1 } }, + } + return { client: client as never, compares: () => compares } +} + +// #893: GitHub's compare is `base...head`, so on +// `compare/{defaultBranch}...{target}` `behind` means the target is behind the +// default branch — an ancestor of it, which the default branch therefore +// contains — and `ahead` means the target carries commits the default branch +// lacks. Measured on this repository while this was reviewed: +// compare/3672754c...b3d5415a -> { status: 'behind', behind_by: 4 } +// compare/b3d5415a...3672754c -> { status: 'ahead', ahead_by: 4 } +// Those two readings are the fixtures below, so the direction cannot invert +// again silently: the same pair is one contained target and one unmerged one. +const LIVE_CONTAINED = { status: 'behind', aheadBy: 0 } // behind_by 4 in the live pair +const LIVE_UNMERGED = { status: 'ahead', aheadBy: 4 } // ahead_by 4 in the live pair + +function containmentClient(containment: { status: string; aheadBy: number }) { + return { + async commitExists() { return true }, + async listTags() { return [{ name: 'v1.0.0', sha: 'b'.repeat(40) }] }, + async compareCommits(_owner: string, _name: string, base: string) { + return base === 'main' ? containment : { status: 'ahead', aheadBy: 2 } + }, + async getRepoFile() { return "on:\n push:\n tags: ['v*']\n" }, + async getBranchProtection() { return { protected: true, requiredChecks: ['ci-ok'], requiredApprovals: 1 } }, + } +} + +// #893: a tag is a ref write, and the tagged tree's workflows run when the tag +// is pushed. A target the default branch never contained must be refused before +// anything is written, not after the tag exists. +test('a target the default branch does not contain is refused', async () => { + // `ahead` is the live reverse of the live `behind`: the target holds commits + // the default branch does not, which is the unmerged branch this guard stops. + for (const containment of [LIVE_UNMERGED, { status: 'diverged', aheadBy: 0 }]) { + const plan = await releasePreflight(containmentClient(containment) as never, { owner: 'acme', name: 'widget', defaultBranch: 'main', requestedVersion: 'v1.50.0', targetSha: target }) + assert.equal(plan.ok, false, `${containment.status} must be refused`) + assert.equal((plan as { code?: string }).code, 'target_not_on_default') + } +}) + +test('a target the default branch contains still releases', async () => { + for (const containment of [LIVE_CONTAINED, { status: 'identical', aheadBy: 0 }]) { + const plan = await releasePreflight(containmentClient(containment) as never, { owner: 'acme', name: 'widget', defaultBranch: 'main', requestedVersion: 'v1.50.0', targetSha: target }) + assert.equal(plan.ok, true, `${containment.status} is a legal release target`) + } +}) + +test('an ancestry compare that cannot be read refuses the release instead of passing it', async () => { + const { client } = ancestryClient({ status: 'throw' }) + const plan = await releasePreflight(client, { owner: 'acme', name: 'widget', defaultBranch: 'main', requestedVersion: 'v1.50.0', targetSha: target }) + assert.equal(plan.ok, false, 'an unreadable compare must fail closed') + assert.equal((plan as { code?: string }).code, 'ancestry_unreadable') +}) + +// #893 review: the previous release of an old target sits outside the newest +// tags. Here the target is at or just past v1.2.0's commit and v1.3.0..v1.20.0 +// are newer, so none of them is an ancestor of it. +const OLD_TARGET_TAGS = Array.from({ length: 21 }, (_, index) => `v1.${String(index)}.0`) + +function oldTargetClient(options: { commitsAfterPrevious: number }) { + const position = (name: string) => OLD_TARGET_TAGS.indexOf(name) + const targetPosition = position('v1.2.0') + return { + async commitExists() { return true }, + async listTags() { return OLD_TARGET_TAGS.map((name) => ({ name, sha: 'b'.repeat(40) })) }, + async compareCommits(_owner: string, _name: string, base: string) { + if (base === 'main') return { status: 'behind', aheadBy: 0 } + const distance = position(base) - targetPosition + if (distance > 0) return { status: 'behind', aheadBy: 0 } // newer than the target: not its ancestor + if (distance === 0) { + return options.commitsAfterPrevious === 0 + ? { status: 'identical', aheadBy: 0 } + : { status: 'ahead', aheadBy: options.commitsAfterPrevious } + } + return { status: 'ahead', aheadBy: 2 } // an older tag, an ancestor of the target + }, + async getRepoFile() { return "on:\n push:\n tags: ['v*']\n" }, + async getBranchProtection() { return { protected: true, requiredChecks: ['ci-ok'], requiredApprovals: 1 } }, + } +} + +test('a target older than the newest tags still refuses a downgrade', async () => { + const downgrade = await releasePreflight(oldTargetClient({ commitsAfterPrevious: 2 }) as never, { owner: 'acme', name: 'widget', defaultBranch: 'main', requestedVersion: 'v1.1.5', targetSha: target }) + assert.equal(downgrade.ok, false, 'the previous release is v1.2.0, which is not one of the ten newest tags') + assert.equal((downgrade as { code?: string }).code, 'not_higher') + const same = await releasePreflight(oldTargetClient({ commitsAfterPrevious: 0 }) as never, { owner: 'acme', name: 'widget', defaultBranch: 'main', requestedVersion: 'v1.2.1', targetSha: target }) + assert.equal(same.ok, false, 'the target already carries the previous release') + assert.equal((same as { code?: string }).code, 'no_new_commits') +}) + +test('the version scan stops at the newest reachable tag', async () => { + const { client, compares } = ancestryClient({ status: 'behind', tagStatus: 'ahead', tags: 25 }) + await releasePreflight(client, { owner: 'acme', name: 'widget', defaultBranch: 'main', requestedVersion: 'v2.0.0', targetSha: target }) + assert.equal(compares(), 2, 'one ancestry compare and one tag compare: the newest reachable tag is the previous release') +}) + test('a 422 from the tag-object write is a refusal value, never an exception', async () => { const plan = { ok: true as const, tagName: 'v1.5.0', version: 'v1.5.0', targetSha: target, prerelease: false, previousTag: null, commitsAfter: null, message: 'release v1.5.0' } const client = { @@ -262,7 +378,14 @@ async function releaseRouteHarness(options: ReleaseRouteOptions = {}) { return json(response, 200, { content: Buffer.from(ROUTE_WORKFLOW).toString('base64') }) } if (method === 'GET' && url.startsWith('/repos/o/r/tags')) return json(response, 200, options.tags ?? []) - if (method === 'GET' && url.startsWith('/repos/o/r/compare/')) return json(response, 200, { status: 'ahead', ahead_by: 3 }) + if (method === 'GET' && url.startsWith('/repos/o/r/compare/')) { + // compare/main...{target} is the containment read, and `behind` is what + // GitHub answers when the default branch contains the target. The tag + // reads put a tag on the left of the `...`. + return url.includes('compare/main...') + ? json(response, 200, { status: 'behind', behind_by: 3 }) + : json(response, 200, { status: 'ahead', ahead_by: 3 }) + } if (method === 'GET' && url.startsWith('/repos/o/r/releases/tags/')) { return options.existingRelease === undefined ? json(response, 404, { message: 'Not Found' }) diff --git a/test/releaseTagFromReadiness.test.ts b/test/releaseTagFromReadiness.test.ts index 9d8ab372..e4540e39 100644 --- a/test/releaseTagFromReadiness.test.ts +++ b/test/releaseTagFromReadiness.test.ts @@ -3,7 +3,7 @@ import assert from 'node:assert/strict' import { buildApp } from '../src/app.js' import { Store } from '../src/db.js' import { MockRunner } from '../src/jobs/mock.js' -import { encryptSecret } from '../src/lib/secrets.js' +import { encryptSecret, sha256Hex } from '../src/lib/secrets.js' import { planRelease, releaseRefusals } from '../src/releases/release.js' import { flashOf, formBody, json, makeUser, readBody, sessionFor, startFakeServer, testConfig } from './helpers.js' @@ -53,7 +53,13 @@ async function harness(options: HarnessOptions = {}) { return json(response, 200, options.tags ?? [{ name: 'v1.3.0', sha: TAG_SHA, commit: { sha: TAG_SHA } }]) } if (method === 'GET' && url.startsWith('/repos/o/r/compare/')) { - return json(response, 200, { status: 'ahead', ahead_by: 3 }) + // compare/main...{target} is the tag POST's containment read: `behind` is + // what GitHub answers when the default branch contains the target. The + // readiness page compares the previous tag with the head, so that one is + // `ahead`. + return url.includes('compare/main...') + ? json(response, 200, { status: 'behind', behind_by: 3 }) + : json(response, 200, { status: 'ahead', ahead_by: 3 }) } if (method === 'GET' && url.startsWith('/repos/o/r/commits/')) { return json(response, 200, { sha: TAG_SHA, commit: { committer: { date: TAG_DATE } } }) @@ -217,3 +223,26 @@ test('an existing tag is refused in the plan words, before any write', async () await h.close() } }) + +// #893: the readiness route writes the same ref as the release POST, so it asks +// the same question first. A stale session is refused before the version, the +// head or a token is read — the assertion is that GitHub was not called at all, +// not that some function ran. +test('a stale session cannot tag from the readiness page, and GitHub is never read', async () => { + const h = await harness() + try { + h.store.db.exec(`UPDATE sessions SET recent_auth_at = NULL WHERE id_hash = '${sha256Hex(h.session.raw)}'`) + const response = await h.submit() + assert.equal(response.statusCode, 302) + const location = String(response.headers.location) + assert.match(location, /^\/auth\/github\/reauthorize\?next=/, 'a tag needs a fresh GitHub confirmation') + assert.match(decodeURIComponent(location), /\/release-readiness/, 'the redirect must return to the readiness page') + assert.deepEqual(h.calls, [], 'a refused confirmation must not read the default branch, the tags or anything else from GitHub') + assert.equal(h.store.releaseByTag(h.repo.id, 'v1.4.0'), undefined, 'a refused confirmation recorded a release row') + const audit = h.store.listAudit(20).find((row) => row.action === 'recent_auth_required') + assert.ok(audit !== undefined, 'the refusal must be audited') + assert.match(String(audit.detail), /repo\.release\.tag/, 'the audit must name the readiness tag action') + } finally { + await h.close() + } +}) diff --git a/test/routeRateLimit.test.ts b/test/routeRateLimit.test.ts index 41edcf2e..e6c4a3e1 100644 --- a/test/routeRateLimit.test.ts +++ b/test/routeRateLimit.test.ts @@ -75,6 +75,13 @@ test('the paced state-changing POST routes refuse the request after their class { name: 'provider delete', url: '/settings/providers/nope/delete', cookie: ownerCookie, payload: formBody({ csrf: ownerCsrf }) }, { name: 'team stop', url: `/repos/${repo.id}/team/stop`, cookie: ownerCookie, payload: formBody({ csrf: ownerCsrf, target: 'chief' }) }, { name: 'job merge', url: `/repos/${repo.id}/jobs/nope/merge`, cookie: ownerCookie, payload: formBody({ csrf: ownerCsrf }) }, + // #893: publishing a release is a tag write, i.e. a ref write, and it + // scans tags behind one POST. It carries the same class limit as the + // routes around it, so a caller cannot turn it into a compare amplifier. + { name: 'release', url: `/repos/${repo.id}/release`, cookie: ownerCookie, payload: formBody({ csrf: ownerCsrf, version: 'v1.0.0', sha: 'a'.repeat(40), confirm: '1' }) }, + // #893: the readiness page's tag button writes the same ref through the + // same preflight, so it carries the same class limit. + { name: 'release readiness tag', url: `/repos/${repo.id}/release-readiness/tag`, cookie: ownerCookie, payload: formBody({ csrf: ownerCsrf, version: 'v1.4.0', head: 'a'.repeat(40), confirm: '1' }) }, ] for (const route of cases) {