feat(potato): add native poisonous potato throws and releases
This commit is contained in:
commit
6b07d3bf87
37 files changed
+2730
No files matched your search
Executable
+24
@@ -0,0 +1,24 @@
|
||||
#!/bin/sh
|
||||
# Git consumes this protocol over a pipe; never run interactively with a real credential.
|
||||
# semantic-release forces GIT_ASKPASS=echo, but still honors credential helpers.
|
||||
set +x
|
||||
[ "${1-}" = get ] || exit 0
|
||||
protocol= host= path= username=
|
||||
while IFS= read -r line && [ -n "$line" ]; do
|
||||
case "$line" in
|
||||
protocol=*) protocol=${line#protocol=} ;;
|
||||
host=*) host=${line#host=} ;;
|
||||
path=*) path=${line#path=} ;;
|
||||
username=*) username=${line#username=} ;;
|
||||
esac
|
||||
done
|
||||
[ "$protocol" = https ] || exit 1
|
||||
[ "$host" = git.garvis.dev ] || exit 1
|
||||
[ "$path" = dmg/purpur-potato.git ] || exit 1
|
||||
[ -z "$username" ] || [ "$username" = dmg ] || exit 1
|
||||
[ -n "${RELEASE_CREDENTIAL-}" ] || exit 1
|
||||
LC_ALL=C
|
||||
export LC_ALL
|
||||
case "$RELEASE_CREDENTIAL" in *[![:graph:]]*) exit 1 ;; esac
|
||||
printf '%s\n' 'username=dmg'
|
||||
printf 'password=%s\n\n' "$RELEASE_CREDENTIAL"
|
||||
@@ -0,0 +1,59 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { resolve } from "node:path";
|
||||
import { test } from "node:test";
|
||||
|
||||
const fixture = "synthetic-git-protocol-fixture";
|
||||
const helper = resolve("scripts/git-credential.sh");
|
||||
const request = "protocol=https\nhost=git.garvis.dev\npath=dmg/purpur-potato.git\n\n";
|
||||
const environment = {
|
||||
PATH: process.env.PATH, RELEASE_CREDENTIAL: fixture, LC_ALL: "C",
|
||||
GIT_ASKPASS: "echo", GIT_TERMINAL_PROMPT: "0",
|
||||
GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null",
|
||||
};
|
||||
|
||||
test("real Git obtains the credential even when semantic-release forces GIT_ASKPASS=echo", () => {
|
||||
const child = spawnSync("git", [
|
||||
"-c", "credential.helper=", "-c", `credential.helper=${helper}`,
|
||||
"-c", "credential.useHttpPath=true", "credential", "fill",
|
||||
], { encoding: "utf8", input: request, env: environment });
|
||||
assert.equal(child.status, 0);
|
||||
assert.ok(child.stdout.split("\n").includes("username=dmg"));
|
||||
assert.ok(child.stdout.split("\n").includes(`password=${fixture}`));
|
||||
assert.equal(child.stderr, "");
|
||||
});
|
||||
|
||||
for (const input of [
|
||||
request.replace("https", "http"), request.replace("git.garvis.dev", "evil.invalid"),
|
||||
request.replace("purpur-potato.git", "another-project.git"),
|
||||
request.replace("\n\n", "\nusername=other\n\n"),
|
||||
]) {
|
||||
test(`refuses mismatched credential scope: ${JSON.stringify(input)}`, () => {
|
||||
const child = spawnSync("/bin/sh", [helper, "get"], { encoding: "utf8", input, env: environment });
|
||||
assert.notEqual(child.status, 0);
|
||||
assert.equal(child.stdout, "");
|
||||
assert.equal(child.stderr, "");
|
||||
});
|
||||
}
|
||||
|
||||
for (const action of ["store", "erase"]) {
|
||||
test(`ignores ${action} without emitting or persisting credentials`, () => {
|
||||
const child = spawnSync("/bin/sh", [helper, action], {
|
||||
encoding: "utf8", input: request, env: environment,
|
||||
});
|
||||
assert.equal(child.status, 0);
|
||||
assert.equal(child.stdout, "");
|
||||
assert.equal(child.stderr, "");
|
||||
});
|
||||
}
|
||||
|
||||
for (const value of ["", "bad\npassword=injected", "trailing-space "]) {
|
||||
test(`rejects absent or malformed credential input of length ${value.length}`, () => {
|
||||
const child = spawnSync("/bin/sh", [helper, "get"], {
|
||||
encoding: "utf8", input: request, env: { ...environment, RELEASE_CREDENTIAL: value },
|
||||
});
|
||||
assert.notEqual(child.status, 0);
|
||||
assert.equal(child.stdout, "");
|
||||
assert.equal(child.stderr, "");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { test } from "node:test";
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
const fixture = "synthetic-cli-fixture";
|
||||
const entrypoint = resolve("build/release-tools/publish-release.js");
|
||||
|
||||
function runPublication(mode: "success" | "transport" | "missing") {
|
||||
const dir = mkdtempSync(join(tmpdir(), "potato-cli-"));
|
||||
try {
|
||||
mkdirSync(join(dir, "build/libs"), { recursive: true });
|
||||
if (mode !== "missing") writeFileSync(join(dir, "build/libs/purpur-potato-1.2.3.jar"), Buffer.from([80, 75, 3, 4]));
|
||||
// A process-local fake at the HTTP boundary: these tests must never contact Gitea.
|
||||
const preload = join(dir, "http-fixture.mjs");
|
||||
writeFileSync(preload, `
|
||||
import assert from 'node:assert/strict';
|
||||
let calls = 0;
|
||||
globalThis.fetch = async (url, init) => {
|
||||
calls++;
|
||||
assert.equal(new Headers(init.headers).get('authorization'), 'token ' + process.env.RELEASE_CREDENTIAL);
|
||||
assert.equal(init.redirect, 'error');
|
||||
assert.ok(!url.includes(process.env.RELEASE_CREDENTIAL));
|
||||
if (process.env.FIXTURE_MODE === 'transport') throw new Error(process.env.RELEASE_CREDENTIAL);
|
||||
if (calls === 1) {
|
||||
const body = JSON.parse(init.body);
|
||||
assert.equal(body.target_commitish, 'a'.repeat(40));
|
||||
assert.equal(body.body, 'Fixture notes');
|
||||
assert.equal(body.draft, true);
|
||||
} else if (calls === 2) {
|
||||
assert.deepEqual(new Uint8Array(init.body), new Uint8Array([80, 75, 3, 4]));
|
||||
assert.ok(url.endsWith('/42/assets?name=purpur-potato-1.2.3.jar'));
|
||||
} else {
|
||||
assert.equal(calls, 3);
|
||||
assert.equal(init.method, 'PATCH');
|
||||
}
|
||||
return Response.json({id:42, draft: calls !== 3, tag_name:'v1.2.3', name:'purpur-potato-1.2.3.jar', size:4});
|
||||
};
|
||||
if (process.env.FIXTURE_MODE === 'success') process.on('exit', () => assert.equal(calls, 3));
|
||||
`);
|
||||
return spawnSync(process.execPath, ["--import", preload, entrypoint], {
|
||||
cwd: dir, encoding: "utf8", env: {
|
||||
VERSION: "1.2.3", RELEASE_COMMIT: "a".repeat(40), RELEASE_CREDENTIAL: fixture,
|
||||
RELEASE_NOTES: "Fixture notes", FIXTURE_MODE: mode,
|
||||
},
|
||||
});
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
test("CLI reads only the exact versioned JAR and reports completed publication", () => {
|
||||
const child = runPublication("success");
|
||||
assert.equal(child.status, 0, child.stderr);
|
||||
assert.equal(child.stdout, "Published purpur-potato v1.2.3.\n");
|
||||
assert.equal(child.stderr, "");
|
||||
});
|
||||
|
||||
for (const mode of ["transport", "missing"] as const) {
|
||||
test(`CLI sanitizes ${mode} failures and never claims publication`, () => {
|
||||
const child = runPublication(mode);
|
||||
assert.equal(child.status, 1);
|
||||
assert.equal(child.stdout, "");
|
||||
assert.equal(child.stderr, "Release publication failed; inspect the release state before retrying.\n");
|
||||
});
|
||||
}
|
||||
|
||||
for (const environment of [
|
||||
{ VERSION: "1.2.3", RELEASE_COMMIT: "a".repeat(40) },
|
||||
{ VERSION: "../../outside", RELEASE_CREDENTIAL: "synthetic-cli-fixture", RELEASE_COMMIT: "a".repeat(40) },
|
||||
]) {
|
||||
test(`CLI fails closed on invalid input without echoing environment: ${Object.keys(environment)}`, () => {
|
||||
const child = spawnSync(process.execPath, ["build/release-tools/publish-release.js"], {
|
||||
encoding: "utf8", env: environment,
|
||||
});
|
||||
assert.equal(child.status, 1);
|
||||
assert.equal(child.stdout, "");
|
||||
assert.equal(child.stderr, "Release publication failed; inspect the release state before retrying.\n");
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { publishRelease } from "./release-client.js";
|
||||
|
||||
try {
|
||||
const version = process.env.VERSION ?? "";
|
||||
const credential = process.env.RELEASE_CREDENTIAL ?? "";
|
||||
const commit = process.env.RELEASE_COMMIT ?? "";
|
||||
// Check path components and required inputs before opening an artifact or contacting Gitea.
|
||||
if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(version)
|
||||
|| !credential || !/^[a-f0-9]{40}$/.test(commit)) throw new Error("Invalid input");
|
||||
const jar = await readFile(`build/libs/purpur-potato-${version}.jar`);
|
||||
await publishRelease({
|
||||
credential, version, commit, jar,
|
||||
notes: process.env.RELEASE_NOTES ?? "See the source history for changes.",
|
||||
}, fetch);
|
||||
console.log(`Published purpur-potato v${version}.`);
|
||||
} catch {
|
||||
// Never echo credentials, upstream error bodies, transport diagnostics or the environment.
|
||||
console.error("Release publication failed; inspect the release state before retrying.");
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { test } from "node:test";
|
||||
import { publishRelease, type ReleaseInput } from "./release-client.js";
|
||||
|
||||
const input: ReleaseInput = {
|
||||
credential: "synthetic-test-value-not-a-real-credential",
|
||||
version: "1.2.3",
|
||||
commit: "a".repeat(40),
|
||||
notes: "Verified changes",
|
||||
jar: new Uint8Array([0x50, 0x4b, 0x03, 0x04]),
|
||||
};
|
||||
|
||||
function success(init: RequestInit): Response {
|
||||
return Response.json({
|
||||
id: 42, draft: init.method !== "PATCH", tag_name: "v1.2.3",
|
||||
name: "purpur-potato-1.2.3.jar", size: input.jar.length,
|
||||
});
|
||||
}
|
||||
|
||||
test("creates a draft on the fixed repository and exact source commit, without following redirects", async () => {
|
||||
const calls: { url: string; init: RequestInit }[] = [];
|
||||
const id = await publishRelease(input, async (url, init) => {
|
||||
calls.push({ url, init });
|
||||
return success(init);
|
||||
});
|
||||
assert.ok(calls.length >= 1);
|
||||
const first = calls[0]!;
|
||||
assert.equal(first.url, "https://git.garvis.dev/api/v1/repos/dmg/purpur-potato/releases");
|
||||
assert.equal(first.init.method, "POST");
|
||||
assert.equal(first.init.redirect, "error");
|
||||
assert.equal(new Headers(first.init.headers).get("authorization"), `token ${input.credential}`);
|
||||
assert.deepEqual(JSON.parse(String(first.init.body)), {
|
||||
tag_name: "v1.2.3", target_commitish: input.commit, name: "v1.2.3",
|
||||
body: input.notes, draft: true, prerelease: false,
|
||||
});
|
||||
assert.equal(id, 42);
|
||||
});
|
||||
|
||||
test("uploads the exact versioned bytes before publishing the draft", async () => {
|
||||
const calls: { url: string; init: RequestInit }[] = [];
|
||||
await publishRelease(input, async (url, init) => {
|
||||
calls.push({ url, init });
|
||||
return success(init);
|
||||
});
|
||||
assert.equal(calls.length, 3);
|
||||
assert.equal(calls[1]!.url,
|
||||
"https://git.garvis.dev/api/v1/repos/dmg/purpur-potato/releases/42/assets?name=purpur-potato-1.2.3.jar");
|
||||
assert.equal(calls[1]!.init.method, "POST");
|
||||
assert.deepEqual(new Uint8Array(await new Response(calls[1]!.init.body).arrayBuffer()), input.jar);
|
||||
assert.equal(new Headers(calls[1]!.init.headers).get("content-type"), "application/octet-stream");
|
||||
assert.equal(calls[2]!.init.method, "PATCH");
|
||||
assert.equal(calls[2]!.url, "https://git.garvis.dev/api/v1/repos/dmg/purpur-potato/releases/42");
|
||||
assert.deepEqual(JSON.parse(String(calls[2]!.init.body)), { draft: false });
|
||||
for (const call of calls) {
|
||||
assert.equal(call.init.redirect, "error");
|
||||
assert.equal(new Headers(call.init.headers).get("authorization"), `token ${input.credential}`);
|
||||
assert.ok(!call.url.includes(input.credential));
|
||||
}
|
||||
});
|
||||
|
||||
for (const failureStep of [1, 2, 3]) {
|
||||
for (const status of [302, 401, 409, 500]) {
|
||||
test(`stops at step ${failureStep} on HTTP ${status} without leaking API error bodies`, async () => {
|
||||
let calls = 0;
|
||||
await assert.rejects(publishRelease(input, async (_url, init) => {
|
||||
calls++;
|
||||
if (calls === failureStep) return new Response(input.credential, { status });
|
||||
return success(init);
|
||||
}), (error: unknown) => {
|
||||
assert.ok(error instanceof Error);
|
||||
assert.ok(error.message.includes(String(status)));
|
||||
assert.ok(!error.message.includes(input.credential));
|
||||
return true;
|
||||
});
|
||||
assert.equal(calls, failureStep, "Do not retry, overwrite an asset or publish after a failed step");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test("sanitizes transport errors and does not follow a redirect with the credential", async () => {
|
||||
await assert.rejects(publishRelease(input, async () => {
|
||||
throw new Error(`diagnostic containing ${input.credential}`);
|
||||
}), { message: "Release API request failed." });
|
||||
});
|
||||
|
||||
for (const invalid of [
|
||||
{ credential: "" }, { credential: "header\r\ninjection" }, { version: "../../latest" },
|
||||
{ version: "1.0.0-SNAPSHOT" }, { commit: "main" }, { jar: new Uint8Array() },
|
||||
]) {
|
||||
test(`rejects invalid ${Object.keys(invalid)[0]} before any network request`, async () => {
|
||||
let calls = 0;
|
||||
await assert.rejects(publishRelease({ ...input, ...invalid }, async () => {
|
||||
calls++;
|
||||
return Response.json({ id: 42 });
|
||||
}), { message: "Invalid release input." });
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
}
|
||||
|
||||
for (const body of ["not JSON", "null", JSON.stringify({ id: -1 }), JSON.stringify({ id: "../other" }),
|
||||
JSON.stringify({ id: 42, draft: false, tag_name: "v1.2.3" })]) {
|
||||
test(`rejects malformed or already-public draft response: ${body}`, async () => {
|
||||
let calls = 0;
|
||||
await assert.rejects(publishRelease(input, async () => {
|
||||
calls++;
|
||||
return new Response(body);
|
||||
}), { message: "Invalid draft release response." });
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
}
|
||||
|
||||
for (const [failureStep, body] of [
|
||||
[2, {}], [2, { name: "other.jar", size: 4 }],
|
||||
[2, { name: "purpur-potato-1.2.3.jar", size: 0 }],
|
||||
[3, { id: 42, draft: true, tag_name: "v1.2.3" }],
|
||||
[3, { id: 77, draft: false, tag_name: "v1.2.3" }],
|
||||
[3, { id: 42, draft: false, tag_name: "v8.8.8" }],
|
||||
] as const) {
|
||||
test(`requires a matching asset and completed publication: ${JSON.stringify(body)}`, async () => {
|
||||
let calls = 0;
|
||||
await assert.rejects(publishRelease(input, async (_url, init) => {
|
||||
calls++;
|
||||
return calls === failureStep ? Response.json(body) : success(init);
|
||||
}), { message: failureStep === 2 ? "Invalid release asset response." : "Invalid published release response." });
|
||||
assert.equal(calls, failureStep);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
export interface ReleaseInput {
|
||||
credential: string;
|
||||
version: string;
|
||||
commit: string;
|
||||
notes: string;
|
||||
jar: Uint8Array;
|
||||
}
|
||||
export type Request = (url: string, init: RequestInit) => Promise<Response>;
|
||||
const releases = "https://git.garvis.dev/api/v1/repos/dmg/purpur-potato/releases";
|
||||
|
||||
export async function publishRelease(input: ReleaseInput, request: Request): Promise<number> {
|
||||
if (!/^[\x21-\x7e]+$/.test(input.credential)
|
||||
|| !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(input.version)
|
||||
|| !/^[a-f0-9]{40}$/.test(input.commit) || input.jar.length === 0) {
|
||||
throw new Error("Invalid release input.");
|
||||
}
|
||||
const send: Request = async (url, init) => {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await request(url, { ...init, signal: AbortSignal.timeout(60_000) });
|
||||
} catch {
|
||||
throw new Error("Release API request failed.");
|
||||
}
|
||||
if (!response.ok) throw new Error(`Release API request failed (HTTP ${response.status}).`);
|
||||
return response;
|
||||
};
|
||||
const response = await send(releases, {
|
||||
method: "POST", redirect: "error",
|
||||
headers: { authorization: `token ${input.credential}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
tag_name: `v${input.version}`, target_commitish: input.commit, name: `v${input.version}`,
|
||||
body: input.notes, draft: true, prerelease: false,
|
||||
}),
|
||||
});
|
||||
const release = await readObject(response, "Invalid draft release response.");
|
||||
if (typeof release.id !== "number" || !Number.isSafeInteger(release.id) || release.id <= 0
|
||||
|| release.draft !== true || release.tag_name !== `v${input.version}`) {
|
||||
throw new Error("Invalid draft release response.");
|
||||
}
|
||||
const assetResponse = await send(`${releases}/${release.id}/assets?name=purpur-potato-${input.version}.jar`, {
|
||||
method: "POST", redirect: "error",
|
||||
headers: { authorization: `token ${input.credential}`, "content-type": "application/octet-stream" },
|
||||
body: new Uint8Array(input.jar).buffer,
|
||||
});
|
||||
const asset = await readObject(assetResponse, "Invalid release asset response.");
|
||||
if (asset.name !== `purpur-potato-${input.version}.jar` || asset.size !== input.jar.length) {
|
||||
throw new Error("Invalid release asset response.");
|
||||
}
|
||||
const publishedResponse = await send(`${releases}/${release.id}`, {
|
||||
method: "PATCH", redirect: "error",
|
||||
headers: { authorization: `token ${input.credential}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({ draft: false }),
|
||||
});
|
||||
const published = await readObject(publishedResponse, "Invalid published release response.");
|
||||
if (published.id !== release.id || published.draft !== false || published.tag_name !== `v${input.version}`) {
|
||||
throw new Error("Invalid published release response.");
|
||||
}
|
||||
return release.id;
|
||||
}
|
||||
|
||||
async function readObject(response: Response, message: string): Promise<Record<string, unknown>> {
|
||||
let value: unknown;
|
||||
try {
|
||||
value = await response.json();
|
||||
} catch {
|
||||
throw new Error(message);
|
||||
}
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(message);
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { closeSync, chmodSync, mkdtempSync, openSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { test } from "node:test";
|
||||
import { planSecretInput } from "./secret-input.js";
|
||||
|
||||
const fixture = "synthetic-provisioning-value-not-a-real-secret";
|
||||
function protectedInput(body: (dir: string, file: string) => void) {
|
||||
const dir = realpathSync(mkdtempSync(join(tmpdir(), "potato-secret-contract-")));
|
||||
const file = join(dir, "release-token");
|
||||
try {
|
||||
chmodSync(dir, 0o700);
|
||||
writeFileSync(file, fixture, { mode: 0o600 });
|
||||
body(dir, file);
|
||||
} finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
}
|
||||
|
||||
for (const invalid of ["public-file", "public-directory", "symlink", "relative", "repository", "missing", "directory", "empty", "login"] as const) {
|
||||
test(`protected provisioning plan refuses ${invalid} input without reading or echoing it`, () => protectedInput((dir, file) => {
|
||||
let path = file;
|
||||
let root = resolve(".");
|
||||
let login = "fixture-login";
|
||||
if (invalid === "public-file") chmodSync(file, 0o644);
|
||||
if (invalid === "public-directory") chmodSync(dir, 0o755);
|
||||
if (invalid === "symlink") { path = join(dir, "link"); symlinkSync(file, path); }
|
||||
if (invalid === "relative") path = "relative-token";
|
||||
if (invalid === "repository") root = dir;
|
||||
if (invalid === "missing") path = join(dir, "missing");
|
||||
if (invalid === "directory") path = dir;
|
||||
if (invalid === "empty") writeFileSync(file, "");
|
||||
if (invalid === "login") login = "--debug";
|
||||
assert.throws(() => planSecretInput(login, path, "file", root), {
|
||||
message: "Invalid protected secret input; no provisioning was performed.",
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
for (const mode of ["file", "stdin"] as const) {
|
||||
test(`protected ${mode} plan follows tea contract without credential argv, logs or actual provisioning`, () => protectedInput((dir, file) => {
|
||||
const plan = planSecretInput("fixture-login", file, mode, resolve("."));
|
||||
assert.equal(plan.command, "tea");
|
||||
assert.deepEqual(plan.args, ["actions", "secrets", "create", "--login", "fixture-login", "--repo", "dmg/purpur-potato",
|
||||
...(mode === "file" ? ["--file", file] : ["--stdin"]), "RELEASE_TOKEN"]);
|
||||
assert.equal(plan.stdinFile, mode === "stdin" ? file : undefined);
|
||||
assert.ok(!JSON.stringify(plan).includes(fixture));
|
||||
// Execute only an isolated local fake, NEVER the installed tea command.
|
||||
const fake = join(dir, "fake-tea.cjs");
|
||||
writeFileSync(fake, `
|
||||
const fs = require('node:fs');
|
||||
const args = process.argv.slice(2);
|
||||
const bytes = args.includes('--stdin') ? fs.readFileSync(0, 'utf8') : fs.readFileSync(args[args.indexOf('--file') + 1], 'utf8');
|
||||
if (bytes !== ${JSON.stringify(fixture)} || args.join(' ').includes(bytes)) process.exit(1);
|
||||
process.stdout.write('Accepted protected input for RELEASE_TOKEN.\\n');
|
||||
`, { mode: 0o600 });
|
||||
const fd = plan.stdinFile ? openSync(plan.stdinFile, "r") : undefined;
|
||||
try {
|
||||
const child = spawnSync(process.execPath, [fake, ...plan.args], {
|
||||
env: {}, encoding: "utf8", stdio: [fd ?? "ignore", "pipe", "pipe"],
|
||||
});
|
||||
assert.equal(child.status, 0, child.stderr);
|
||||
assert.equal(child.stdout, "Accepted protected input for RELEASE_TOKEN.\n");
|
||||
assert.equal(child.stderr, "");
|
||||
} finally { if (fd !== undefined) closeSync(fd); }
|
||||
}));
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { lstatSync, realpathSync } from "node:fs";
|
||||
import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
|
||||
|
||||
export interface SecretInputPlan {
|
||||
command: "tea";
|
||||
args: string[];
|
||||
stdinFile?: string;
|
||||
}
|
||||
|
||||
// Plan only: never reads secret bytes, spawns tea, or provisions a secret.
|
||||
// This is an inspectable contract, not upload authorization or a race-free open.
|
||||
// An operator must recheck metadata and approve the actual upload separately.
|
||||
export function planSecretInput(login: string, file: string, mode: "file" | "stdin", repositoryRoot: string): SecretInputPlan {
|
||||
try {
|
||||
if (!/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(login) || !isAbsolute(file)
|
||||
|| (mode !== "file" && mode !== "stdin")) throw new Error();
|
||||
const canonical = realpathSync(file);
|
||||
const local = relative(realpathSync(repositoryRoot), canonical);
|
||||
if (canonical !== resolve(file) || !(local === ".." || local.startsWith(`..${sep}`) || isAbsolute(local))) throw new Error();
|
||||
const metadata = lstatSync(file);
|
||||
const directory = lstatSync(dirname(file));
|
||||
const owner = process.getuid?.();
|
||||
if (owner === undefined || !metadata.isFile() || metadata.isSymbolicLink() || metadata.size === 0
|
||||
|| metadata.uid !== owner || (metadata.mode & 0o777) !== 0o600
|
||||
|| !directory.isDirectory() || directory.uid !== owner || (directory.mode & 0o777) !== 0o700) throw new Error();
|
||||
} catch {
|
||||
throw new Error("Invalid protected secret input; no provisioning was performed.");
|
||||
}
|
||||
return {
|
||||
command: "tea",
|
||||
args: ["actions", "secrets", "create", "--login", login, "--repo", "dmg/purpur-potato",
|
||||
...(mode === "file" ? ["--file", file] : ["--stdin"]), "RELEASE_TOKEN"],
|
||||
...(mode === "stdin" ? { stdinFile: file } : {}),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { test } from "node:test";
|
||||
|
||||
const root = resolve(".");
|
||||
const sha = "a".repeat(40);
|
||||
const fixture = "synthetic-workflow-credential";
|
||||
function workflow(name: string): string { return readFileSync(join(root, `.gitea/workflows/${name}.yml`), "utf8"); }
|
||||
function step(name: string, title: string): string {
|
||||
const value = workflow(name).split(" - name: ").find(block => block.startsWith(title + "\n"));
|
||||
assert.ok(value, `Missing workflow step: ${title}`);
|
||||
return value;
|
||||
}
|
||||
function script(name: string, title: string): string {
|
||||
const block = step(name, title);
|
||||
const run = block.split(" run: ")[1];
|
||||
assert.ok(run, `Missing run body: ${title}`);
|
||||
return run.startsWith("|\n") ? run.slice(2).split("\n").map(line => line.replace(/^ /, "")).join("\n") : run.trim();
|
||||
}
|
||||
function sandbox(body: (dir: string) => void): void {
|
||||
const dir = mkdtempSync(join(tmpdir(), "potato-workflow-"));
|
||||
try { body(dir); } finally { rmSync(dir, { recursive: true, force: true }); }
|
||||
}
|
||||
function fake(dir: string, command: string, source: string): void {
|
||||
mkdirSync(join(dir, "bin"), { recursive: true });
|
||||
writeFileSync(join(dir, "bin", command), `#!${process.execPath}\n${source}`, { mode: 0o700 });
|
||||
}
|
||||
function shell(dir: string, source: string, env: NodeJS.ProcessEnv = {}) {
|
||||
return spawnSync("/bin/sh", ["-eu", "-c", source], { cwd: dir, encoding: "utf8", env: {
|
||||
PATH: `${join(dir, "bin")}:${process.env.PATH}`, HOME: dir, GIT_CONFIG_NOSYSTEM: "1",
|
||||
GIT_CONFIG_GLOBAL: "/dev/null", GITHUB_WORKSPACE: root, GITHUB_OUTPUT: join(dir, "output"), ...env,
|
||||
} });
|
||||
}
|
||||
|
||||
test("CI runs the full check and commitlint with inert SHA arguments and SHA-named artifacts", () => {
|
||||
sandbox(dir => {
|
||||
writeFileSync(join(dir, "build-args"), "");
|
||||
writeFileSync(join(dir, "gradlew"), '#!/bin/sh\nprintf "%s\\n" "$@" > build-args\n', { mode: 0o700 });
|
||||
assert.equal(shell(dir, script("ci", "Build and test")).status, 0);
|
||||
assert.equal(readFileSync(join(dir, "build-args"), "utf8"), "clean\ncheck\njar\n");
|
||||
fake(dir, "npx", `require('node:fs').writeFileSync('lint-args', JSON.stringify(process.argv.slice(2)));`);
|
||||
const child = shell(dir, script("ci", "Validate conventional commits"), { BASE_SHA: "b".repeat(40), HEAD_SHA: sha });
|
||||
assert.equal(child.status, 0, child.stderr);
|
||||
const args = JSON.parse(readFileSync(join(dir, "lint-args"), "utf8"));
|
||||
assert.deepEqual(args.slice(-6), ["--from", "b".repeat(40), "--to", sha, "--extends", "@commitlint/config-conventional"]);
|
||||
assert.match(step("ci", "Validate conventional commits"), /if: github.event_name == 'pull_request'/);
|
||||
assert.match(step("ci", "Upload development artifact"), /name: purpur-potato-\$\{\{ github.sha \}\}/);
|
||||
assert.match(step("ci", "Upload development artifact"), /path: build\/libs\/purpur-potato-\*\.jar/);
|
||||
assert.match(step("ci", "Upload development artifact"), /if-no-files-found: error/);
|
||||
assert.match(workflow("ci"), /java-version: 25/);
|
||||
assert.match(workflow("ci"), /node-version: 20/);
|
||||
});
|
||||
});
|
||||
|
||||
test("release performs full snapshot and versioned checks and gates versioned artifacts on a new release", () => sandbox(dir => {
|
||||
writeFileSync(join(dir, "build-args"), "");
|
||||
writeFileSync(join(dir, "gradlew"), '#!/bin/sh\nprintf "%s\\n" "$@" > build-args\n', { mode: 0o700 });
|
||||
assert.equal(shell(dir, script("release", "Build and test before release")).status, 0);
|
||||
assert.equal(readFileSync(join(dir, "build-args"), "utf8"), "clean\ncheck\njar\n");
|
||||
assert.equal(shell(dir, script("release", "Verify versioned plugin and release tooling"), { VERSION: "1.2.3" }).status, 0);
|
||||
assert.equal(readFileSync(join(dir, "build-args"), "utf8"), "clean\ncheck\njar\n-PreleaseVersion=1.2.3\n");
|
||||
for (const title of ["Verify versioned plugin and release tooling", "Upload release workflow artifact"]) {
|
||||
assert.match(step("release", title), /if: steps.release.outputs.created == 'true'/);
|
||||
}
|
||||
const release = workflow("release");
|
||||
assert.ok(release.indexOf("Build and test before release") < release.indexOf("Compute and push"));
|
||||
assert.ok(release.indexOf("Capture previous tag") < release.indexOf("Compute and push"));
|
||||
assert.ok(release.indexOf("Verify versioned") < release.indexOf("Upload release workflow artifact"));
|
||||
assert.match(release, /branches: \[main\]/);
|
||||
assert.match(release, /group: potato-release\n cancel-in-progress: false/);
|
||||
assert.match(step("release", "Upload release workflow artifact"), /path: build\/libs\/purpur-potato-\$\{\{ steps.release.outputs.version \}\}\.jar/);
|
||||
}));
|
||||
|
||||
for (const scenario of ["new", "none", "unchanged", "wrong-source", "invalid-tag"] as const) {
|
||||
test(`release resolution proves exact source and does not claim no-release publication: ${scenario}`, () => sandbox(dir => {
|
||||
const init = shell(dir, "git init -q; git -c user.name=Fixture -c user.email=fixture@example.invalid commit --allow-empty -qm 'feat: fixture'");
|
||||
assert.equal(init.status, 0, init.stderr);
|
||||
if (scenario === "unchanged") assert.equal(shell(dir, "git tag v1.2.3").status, 0);
|
||||
writeFileSync(join(dir, "output"), "");
|
||||
const previous = shell(dir, script("release", "Capture previous tag"));
|
||||
assert.equal(previous.status, 0, previous.stderr);
|
||||
const previousOutput = readFileSync(join(dir, "output"), "utf8");
|
||||
assert.equal(previousOutput, scenario === "unchanged" ? "tag=v1.2.3\n" : "tag=\n");
|
||||
writeFileSync(join(dir, "output"), "");
|
||||
if (scenario === "new" || scenario === "wrong-source") assert.equal(shell(dir, "git tag v1.2.3").status, 0);
|
||||
if (scenario === "invalid-tag") assert.equal(shell(dir, "git tag v01.2.3-unsupported").status, 0);
|
||||
const head = shell(dir, "git rev-parse HEAD").stdout.trim();
|
||||
const child = shell(dir, script("release", "Resolve newly created exact-source release"), {
|
||||
PREVIOUS_TAG: scenario === "unchanged" ? "v1.2.3" : "", EXPECTED_COMMIT: scenario === "wrong-source" ? sha : head,
|
||||
});
|
||||
const output = readFileSync(join(dir, "output"), "utf8");
|
||||
if (scenario === "wrong-source" || scenario === "invalid-tag") {
|
||||
assert.notEqual(child.status, 0);
|
||||
assert.ok(!output.includes("created=true"));
|
||||
} else {
|
||||
assert.equal(child.status, 0, child.stderr);
|
||||
assert.equal(output, scenario === "new" ? "created=true\nversion=1.2.3\n" : "created=false\n");
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
const forbiddenEnv = [
|
||||
"GIT_CREDENTIALS", "GH_TOKEN", "GITHUB_TOKEN", "GL_TOKEN", "GITLAB_TOKEN", "BB_TOKEN", "BITBUCKET_TOKEN",
|
||||
"BB_TOKEN_BASIC_AUTH", "BITBUCKET_TOKEN_BASIC_AUTH", "DEBUG", "NODE_DEBUG", "GIT_TRACE", "GIT_TRACE_CURL",
|
||||
"GIT_CURL_VERBOSE", "GIT_TRACE_PACKET", "GIT_TRACE_SETUP", "GIT_TRACE2", "GIT_TRACE2_EVENT", "GIT_TRACE2_PERF",
|
||||
];
|
||||
|
||||
test("publication invokes only the in-process publisher with no secret argv or tracing", () => sandbox(dir => {
|
||||
assert.equal(shell(dir, "git init -q; git -c user.name=Fixture -c user.email=fixture@example.invalid commit --allow-empty -qm 'feat: fixture'").status, 0);
|
||||
writeFileSync(join(dir, "publish-command"), "null");
|
||||
fake(dir, "node", `
|
||||
const assert = require('node:assert/strict');
|
||||
for (const key of ${JSON.stringify(forbiddenEnv)}) assert.equal(process.env[key], undefined, key);
|
||||
assert.equal(process.env.RELEASE_CREDENTIAL, ${JSON.stringify(fixture)});
|
||||
assert.match(process.env.RELEASE_NOTES, /feat: fixture/);
|
||||
require('node:fs').writeFileSync('publish-command', JSON.stringify(process.argv.slice(2)));
|
||||
`);
|
||||
const child = shell(dir, script("release", "Publish verified JAR through a draft release"), {
|
||||
RELEASE_CREDENTIAL: fixture, PREVIOUS_TAG: "",
|
||||
...Object.fromEntries(forbiddenEnv.map(key => [key, key.includes("TOKEN") ? fixture : "1"])),
|
||||
});
|
||||
assert.equal(child.status, 0, child.stderr);
|
||||
assert.deepEqual(JSON.parse(readFileSync(join(dir, "publish-command"), "utf8")), ["build/release-tools/publish-release.js"]);
|
||||
assert.ok(![child.stdout, child.stderr].join("").includes(fixture));
|
||||
assert.match(step("release", "Publish verified JAR through a draft release"), /if: steps.release.outputs.created == 'true'/);
|
||||
assert.ok(workflow("release").indexOf("Verify versioned") < workflow("release").indexOf("Publish verified"));
|
||||
assert.doesNotMatch(workflow("release"), /curl|secrets\.RELEASE_TOKEN[^\n]*(?:curl|git|node)/);
|
||||
}));
|
||||
|
||||
test("semantic tagging keeps the dummy credential only in helper environment, never argv, URLs or diagnostics", () => {
|
||||
sandbox(dir => {
|
||||
assert.equal(shell(dir, "git init -q").status, 0);
|
||||
writeFileSync(join(dir, "tag-command"), "null");
|
||||
fake(dir, "npx", `
|
||||
const assert = require('node:assert/strict');
|
||||
for (const key of ${JSON.stringify(forbiddenEnv)}) assert.equal(process.env[key], undefined, key);
|
||||
assert.equal(process.env.RELEASE_CREDENTIAL, ${JSON.stringify(fixture)});
|
||||
assert.equal(process.env.GIT_TERMINAL_PROMPT, '0');
|
||||
require('node:fs').writeFileSync('tag-command', JSON.stringify(process.argv.slice(2)));
|
||||
`);
|
||||
const child = shell(dir, script("release", "Compute and push semantic release tag"), {
|
||||
RELEASE_CREDENTIAL: fixture, REPOSITORY: "dmg/purpur-potato",
|
||||
...Object.fromEntries(forbiddenEnv.map(key => [key, key.includes("TOKEN") ? fixture : "1"])),
|
||||
});
|
||||
assert.equal(child.status, 0, child.stderr);
|
||||
const args = JSON.parse(readFileSync(join(dir, "tag-command"), "utf8"));
|
||||
assert.ok(Array.isArray(args), "Must actually invoke semantic-release");
|
||||
assert.ok(args.includes("semantic-release@24.2.9"));
|
||||
assert.ok(args.includes("@semantic-release/commit-analyzer@13.0.1"));
|
||||
assert.ok(args.includes("@semantic-release/release-notes-generator@14.1.0"));
|
||||
assert.equal(args[args.indexOf("--repository-url") + 1], "https://git.garvis.dev/dmg/purpur-potato.git");
|
||||
const config = shell(dir, "git config --local --list");
|
||||
assert.match(config.stdout, /credential.usehttppath=true/);
|
||||
assert.match(config.stdout, /http.followredirects=false/);
|
||||
assert.ok(config.stdout.includes(`credential.helper=${root}/scripts/git-credential.sh`));
|
||||
assert.ok(![JSON.stringify(args), config.stdout, child.stdout, child.stderr].join("").includes(fixture));
|
||||
});
|
||||
});
|
||||
|
||||
for (const env of [{ RELEASE_CREDENTIAL: "", REPOSITORY: "dmg/purpur-potato" },
|
||||
{ RELEASE_CREDENTIAL: fixture, REPOSITORY: "evil/purpur-potato" }]) {
|
||||
test(`tagging refuses missing credential or wrong repository: ${env.REPOSITORY}`, () => sandbox(dir => {
|
||||
fake(dir, "npx", "process.exit(90);");
|
||||
const child = shell(dir, script("release", "Compute and push semantic release tag"), env);
|
||||
assert.notEqual(child.status, 0);
|
||||
assert.notEqual(child.status, 90);
|
||||
assert.ok(!child.stderr.includes(fixture));
|
||||
}));
|
||||
}
|
||||
|
||||
for (const name of ["ci", "release"]) {
|
||||
test(`${name} rejects multiline source SHAs before invoking Git`, () => sandbox(dir => {
|
||||
writeFileSync(join(dir, "calls"), "");
|
||||
fake(dir, "git", `require('node:fs').appendFileSync('calls', 'called');`);
|
||||
const child = shell(dir, script(name, "Checkout public source without a credential"), { SOURCE_SHA: `${sha}\nmalformed` });
|
||||
assert.notEqual(child.status, 0);
|
||||
assert.equal(readFileSync(join(dir, "calls"), "utf8"), "");
|
||||
}));
|
||||
}
|
||||
|
||||
for (const name of ["ci", "release"]) test(`${name} anonymously fetches full history and exact source without credentials or redirects`, () => {
|
||||
sandbox(dir => {
|
||||
writeFileSync(join(dir, "calls"), "");
|
||||
fake(dir, "git", `require('node:fs').appendFileSync('calls', JSON.stringify(process.argv.slice(2))+'\\n');`);
|
||||
const child = shell(dir, script(name, "Checkout public source without a credential"), { SOURCE_SHA: sha });
|
||||
assert.equal(child.status, 0, child.stderr);
|
||||
const calls = readFileSync(join(dir, "calls"), "utf8").trim().split("\n").filter(Boolean).map(line => JSON.parse(line));
|
||||
assert.ok(calls.some(args => JSON.stringify(args) === JSON.stringify(["remote", "add", "origin", "https://git.garvis.dev/dmg/purpur-potato.git"])));
|
||||
for (const [key, value] of [["credential.helper", ""], ["http.extraHeader", ""], ["http.followRedirects", "false"]]) {
|
||||
assert.ok(calls.some(args => JSON.stringify(args) === JSON.stringify(["config", "--local", key, value])));
|
||||
}
|
||||
assert.ok(calls.some(args => JSON.stringify(args) === JSON.stringify(["fetch", "--force", "--tags", "origin", "+refs/heads/*:refs/remotes/origin/*"])));
|
||||
assert.deepEqual(calls.at(-1), name === "ci" ? ["checkout", "--detach", sha] : ["checkout", "-B", "main", sha]);
|
||||
assert.doesNotMatch(step(name, "Checkout public source without a credential"), /secrets\.|token:/);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user