-
Notifications
You must be signed in to change notification settings - Fork 0
ci: bind release writeback to verified source #19
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import { execFileSync } from "node:child_process"; | ||
| import fs from "node:fs"; | ||
| import path from "node:path"; | ||
| import { isDeepStrictEqual } from "node:util"; | ||
| import assert from "node:assert/strict"; | ||
|
|
||
| interface Context { | ||
| cwd: string; | ||
| env: NodeJS.ProcessEnv; | ||
| nextRelease: { version: string; gitHead: string }; | ||
| } | ||
|
|
||
| function record(value: unknown): Record<string, unknown> { | ||
| assert(value !== null && typeof value === "object" && !Array.isArray(value), "Expected object"); | ||
| return Object.fromEntries(Object.entries(value)); | ||
| } | ||
| function oid(value: unknown): string { | ||
| assert(typeof value === "string" && /^[a-f0-9]{40}$/.test(value), "Expected commit SHA"); | ||
| return value; | ||
| } | ||
|
|
||
| // npm's prepare runs first. Only its version edit may enter the signed commit. | ||
| export async function prepare(_config: unknown, context: Context): Promise<void> { | ||
| const { cwd, env, nextRelease } = context; | ||
| const expected = oid(env.GITHUB_SHA); | ||
| const repository = env.GITHUB_REPOSITORY; | ||
| assert.equal(repository, "uinaf/skillcheck"); | ||
| const token = env.GITHUB_TOKEN ?? env.GH_TOKEN; | ||
| assert(token, "Release token required"); | ||
| const git = (...args: string[]) => execFileSync("git", args, { cwd, encoding: "utf8" }).trim(); | ||
| if (git("rev-parse", "HEAD") !== expected || nextRelease.gitHead !== expected) | ||
| throw new Error("release checkout must match the verified event commit"); | ||
| if (git("diff", "--name-only", expected, "--", ".", ":(exclude)package.json")) | ||
| throw new Error("release preparation changed files other than package.json"); | ||
| const before = record(JSON.parse(git("show", `${expected}:package.json`))); | ||
| const content = fs.readFileSync(path.join(cwd, "package.json")); | ||
| const prepared = record(JSON.parse(content.toString("utf8"))); | ||
| if (!isDeepStrictEqual(prepared, { ...before, version: nextRelease.version })) | ||
| throw new Error("release preparation must change only the package version"); | ||
|
|
||
| // GitHub signs this commit and rejects a moved branch atomically. A preflight | ||
| // against main would leave a race between reading its head and writing it. | ||
| const response = await fetch("https://api.github.com/graphql", { | ||
| method: "POST", | ||
| signal: AbortSignal.timeout(30_000), | ||
| headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, | ||
| body: JSON.stringify({ | ||
| query: `mutation($input: CreateCommitOnBranchInput!) { | ||
| createCommitOnBranch(input: $input) { commit { oid } } | ||
| }`, | ||
| variables: { | ||
| input: { | ||
| branch: { repositoryNameWithOwner: repository, branchName: "main" }, | ||
| expectedHeadOid: expected, | ||
| message: { headline: `chore(release): ${nextRelease.version} [skip ci]` }, | ||
| fileChanges: { | ||
| additions: [{ path: "package.json", contents: content.toString("base64") }], | ||
| }, | ||
| }, | ||
| }, | ||
| }), | ||
| }); | ||
| if (!response.ok) throw new Error(`release writeback failed: GitHub HTTP ${response.status}`); | ||
| const result = record(await response.json()); | ||
| if (result.errors !== undefined) { | ||
| assert(Array.isArray(result.errors), "Expected GraphQL errors array"); | ||
| if (result.errors.length) { | ||
| const messages = result.errors.map((error) => { | ||
| const message = record(error).message; | ||
| assert.equal(typeof message, "string"); | ||
| return message; | ||
| }); | ||
| throw new Error(`release writeback rejected: ${messages.join("; ")}`); | ||
| } | ||
| } | ||
| const committed = oid(record(record(record(result.data).createCommitOnBranch).commit).oid); | ||
|
|
||
| // main may advance after the mutation. Fetch and tag the returned commit, | ||
| // never the moving branch. A failure here leaves writeback without a release. | ||
| git("fetch", "origin", committed); | ||
| if (git("show", "-s", "--format=%P", committed) !== expected) | ||
| throw new Error("release writeback has an unexpected parent"); | ||
| if (git("diff", "--name-only", expected, committed, "--", ".", ":(exclude)package.json")) | ||
| throw new Error("release writeback changed source outside package.json"); | ||
| if (!execFileSync("git", ["show", `${committed}:package.json`], { cwd }).equals(content)) | ||
| throw new Error("release writeback does not match the prepared package"); | ||
| git("reset", "--hard", committed); | ||
| nextRelease.gitHead = committed; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,159 @@ | ||
| import assert from "node:assert/strict"; | ||
| import { execFileSync } from "node:child_process"; | ||
| import fs from "node:fs"; | ||
| import os from "node:os"; | ||
| import path from "node:path"; | ||
| import { URL } from "node:url"; | ||
| import { test, vi } from "vite-plus/test"; | ||
| import { prepare } from "../scripts/release-commit.ts"; | ||
|
|
||
| const git = (cwd: string, ...args: string[]) => | ||
| execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim(); | ||
| const commit = (cwd: string) => { | ||
| git(cwd, "add", "."); | ||
| git( | ||
| cwd, | ||
| "-c", | ||
| "user.name=Fixture", | ||
| "-c", | ||
| "user.email=fixture@example.invalid", | ||
| "-c", | ||
| "commit.gpgsign=false", | ||
| "commit", | ||
| "-m", | ||
| "fixture", | ||
| ); | ||
| return git(cwd, "rev-parse", "HEAD"); | ||
| }; | ||
| for (const mode of [ | ||
| "normal", | ||
| "advanced-before", | ||
| "advanced-after", | ||
| "source-edit", | ||
| "manifest-edit", | ||
| "http-error", | ||
| "wrong-parent", | ||
| "fetch-failure", | ||
| "returned-source-edit", | ||
| "returned-manifest-edit", | ||
| "wrong-checkout", | ||
| "wrong-release-head", | ||
| ] as const) { | ||
| test(`signed release writeback: ${mode}`, async () => { | ||
| const root = fs.mkdtempSync(path.join(os.tmpdir(), "skillcheck-release-")); | ||
| const remote = path.join(root, "remote"); | ||
| const cwd = path.join(root, "checkout"); | ||
| fs.mkdirSync(remote, { recursive: true }); | ||
| git(remote, "init", "-b", "main"); | ||
| fs.writeFileSync(path.join(remote, "source.txt"), "verified source\n"); | ||
| fs.writeFileSync( | ||
| path.join(remote, "package.json"), | ||
| JSON.stringify({ name: "fixture", version: "1.0.0" }), | ||
| ); | ||
| const expected = commit(remote); | ||
| git(root, "clone", remote, cwd); | ||
| const content = JSON.stringify({ name: "fixture", version: "1.0.1" }); | ||
| fs.writeFileSync(path.join(cwd, "package.json"), content); | ||
| const context = { | ||
| cwd, | ||
| env: { GITHUB_SHA: expected, GITHUB_REPOSITORY: "uinaf/skillcheck", GITHUB_TOKEN: "fixture" }, | ||
| nextRelease: { version: "1.0.1", gitHead: expected }, | ||
| }; | ||
| if (mode === "wrong-checkout") context.env.GITHUB_SHA = "a".repeat(40); | ||
| if (mode === "wrong-release-head") context.nextRelease.gitHead = "a".repeat(40); | ||
| let created = ""; | ||
| if (mode === "advanced-before") { | ||
| fs.writeFileSync( | ||
| path.join(remote, "package.json"), | ||
| JSON.stringify({ name: "fixture", version: "1.0.0", newDependency: true }), | ||
| ); | ||
| commit(remote); | ||
| } | ||
| if (mode === "source-edit") fs.writeFileSync(path.join(cwd, "source.txt"), "unverified\n"); | ||
| if (mode === "manifest-edit") | ||
| fs.writeFileSync( | ||
| path.join(cwd, "package.json"), | ||
| JSON.stringify({ name: "other", version: "1.0.1" }), | ||
| ); | ||
| const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (url, options) => { | ||
| assert.equal(url, "https://api.github.com/graphql"); | ||
| assert(typeof options?.body === "string"); | ||
| const { | ||
| variables: { input }, | ||
| } = JSON.parse(options.body); | ||
| assert.equal(input.expectedHeadOid, expected); | ||
| assert.deepEqual(input.branch, { | ||
| repositoryNameWithOwner: "uinaf/skillcheck", | ||
| branchName: "main", | ||
| }); | ||
| assert.deepEqual(input.fileChanges.additions, [ | ||
| { path: "package.json", contents: Buffer.from(content).toString("base64") }, | ||
| ]); | ||
| if (mode === "http-error") return new Response("denied", { status: 403 }); | ||
| if (mode === "advanced-before") | ||
| return Response.json({ | ||
| data: null, | ||
| errors: [{ message: "expectedHeadOid does not match branch head" }], | ||
| }); | ||
| if (mode === "wrong-parent") { | ||
| fs.writeFileSync(path.join(remote, "source.txt"), "raced\n"); | ||
| commit(remote); | ||
| } | ||
| fs.writeFileSync(path.join(remote, "package.json"), content); | ||
| if (mode === "returned-source-edit") | ||
| fs.writeFileSync(path.join(remote, "source.txt"), "unverified\n"); | ||
| if (mode === "returned-manifest-edit") | ||
| fs.appendFileSync(path.join(remote, "package.json"), "\n"); | ||
| created = commit(remote); | ||
| if (mode === "advanced-after") { | ||
| fs.writeFileSync(path.join(remote, "source.txt"), "newer source\n"); | ||
| commit(remote); | ||
| } | ||
| return Response.json({ | ||
| data: { | ||
| createCommitOnBranch: { | ||
| commit: { oid: mode === "fetch-failure" ? "a".repeat(40) : created }, | ||
| }, | ||
| }, | ||
| }); | ||
| }); | ||
| try { | ||
| if (mode === "normal" || mode === "advanced-after") { | ||
| await prepare({}, context); | ||
| assert.equal(git(cwd, "rev-parse", "HEAD"), created); | ||
| assert.equal(context.nextRelease.gitHead, created); | ||
| assert.equal(git(cwd, "show", "-s", "--format=%P", "HEAD"), expected); | ||
| assert.equal(fs.readFileSync(path.join(cwd, "source.txt"), "utf8"), "verified source\n"); | ||
| assert.equal(fs.readFileSync(path.join(cwd, "package.json"), "utf8"), content); | ||
| if (mode === "advanced-after") assert.notEqual(git(remote, "rev-parse", "HEAD"), created); | ||
| } else { | ||
| await assert.rejects( | ||
| prepare({}, context), | ||
| /changed files|only the package version|expectedHeadOid|HTTP 403|unexpected parent|changed source|does not match|verified event commit|Command failed: git fetch/, | ||
| ); | ||
| assert.equal( | ||
| context.nextRelease.gitHead, | ||
| mode === "wrong-release-head" ? "a".repeat(40) : expected, | ||
| ); | ||
| assert.equal(git(cwd, "rev-parse", "HEAD"), expected); | ||
| if (mode === "fetch-failure") assert.equal(git(remote, "rev-parse", "HEAD"), created); | ||
| if (mode === "advanced-before") | ||
| assert.match(fs.readFileSync(path.join(remote, "package.json"), "utf8"), /newDependency/); | ||
| if (mode === "source-edit" || mode === "manifest-edit") | ||
| assert.equal(fetchMock.mock.calls.length, 0); | ||
| } | ||
| assert.equal(git(remote, "tag", "--list"), ""); | ||
| } finally { | ||
| fetchMock.mockRestore(); | ||
| fs.rmSync(root, { recursive: true, force: true }); | ||
| } | ||
| }); | ||
| } | ||
|
|
||
| test("release prepares npm before signed writeback, then publishes GitHub", () => { | ||
| const config = JSON.parse( | ||
| fs.readFileSync(new URL("../.releaserc.json", import.meta.url), "utf8"), | ||
| ); | ||
| assert.equal(config.plugins[2], "@semantic-release/npm"); | ||
| assert.equal(config.plugins[3], "./scripts/release-commit.ts"); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.