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
1 change: 1 addition & 0 deletions changelog.d/893-release-write-guard.security.md
Original file line number Diff line number Diff line change
@@ -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.
39 changes: 33 additions & 6 deletions docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
10 changes: 7 additions & 3 deletions docs/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 16 additions & 2 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2496,11 +2496,17 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
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<string, string>).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()
Expand Down Expand Up @@ -2537,12 +2543,20 @@ export async function buildApp(options: BuildOptions): Promise<BuiltApp> {
// #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<string, string>).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
Expand Down
4 changes: 3 additions & 1 deletion src/lib/routeClasses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down Expand Up @@ -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',
Expand Down
64 changes: 53 additions & 11 deletions src/releases/release.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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'
Expand Down Expand Up @@ -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 },
Expand All @@ -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)
Expand Down
28 changes: 28 additions & 0 deletions test/recentAuth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}
})
Loading
Loading