kohsteal.test.ts

15.4 KB · raw

1/**2 * The joint public-steal contract (addendum A2, item 8d): one machine publishes a repo to a bucket,3 * Kepr serves it read-only over HTTP in Koh's own layout, a second `koh` steals it — and later,4 * once that machine has signed in, offers its work back to the bucket.5 *6 * There is no S3 on a test host, so the bucket is a fake one served here; koh is run as the real7 * installed binary (`koh` on PATH, the same one this suite is pinned to). The account of what the8 * fake bucket accepts is in its own class: signatures are ignored rather than verified, which is9 * the one way this test is easier than the real thing.10 */11import { describe, expect, test } from "bun:test";12import { mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";13import { tmpdir } from "node:os";14import { join } from "node:path";15import type { Hono } from "hono";16import { openBucket } from "../src/bucket/reader.ts";17import { syncAll } from "../src/bucket/sync.ts";18import { createApp } from "../src/server/app.ts";19import { openKeprDb } from "../src/server/db.ts";20import { Browser, PASSWORD } from "./browser.ts";21import { platform, stripPath } from "./fixture.ts";2223const REPO = "shipped";24const PRIVATE_REPO = "kept";25const BUCKET = "kohbucket";26const ACCESS = "fake-access";27const SECRET = "fake-secret";28/** The command deadline: two koh runs talk to a local server, so this is generous. */29const RUN = 60_000;3031/**32 * The fake bucket runs as its own process: the koh calls below are synchronous (`koh` blocks the33 * event loop), so an in-process server would never answer them. `tests/fake-s3.ts` prints its34 * endpoint on stdout.35 */36async function startBucket(): Promise<{ endpoint: string; stop: () => void }> {37	const proc = Bun.spawn(["bun", "run", join(import.meta.dir, "fake-s3.ts")], {38		stdout: "pipe",39		stderr: "inherit",40	});41	const reader = proc.stdout.getReader();42	const first = await reader.read();43	const endpoint =44		new TextDecoder()45			.decode(first.value ?? new Uint8Array())46			.trim()47			.split("\n")[0] ?? "";48	reader.releaseLock();49	expect(endpoint).toStartWith("http://127.0.0.1:");50	return { endpoint, stop: () => proc.kill() };51}5253type Ran = { code: number; out: string; err: string };5455/** The real koh, with a throwaway HOME so no test ever touches the operator's config. */56async function koh(57	cwd: string,58	home: string,59	args: string[],60	env: Record<string, string> = {},61): Promise<Ran> {62	const proc = Bun.spawn(["koh", ...args], {63		cwd,64		env: { PATH: process.env.PATH, HOME: home, NO_COLOR: "1", ...env },65		stdout: "pipe",66		stderr: "pipe",67	});68	const [out, err, code] = await Promise.all([69		new Response(proc.stdout).text(),70		new Response(proc.stderr).text(),71		proc.exited,72	]);73	return { code, out, err };74}7576/** The whole line, every field of every save: what a stolen copy must reproduce exactly. */77async function line(repo: string, home: string): Promise<unknown> {78	return JSON.parse((await koh(repo, home, ["view", "--json"])).out).saves;79}8081describe.serial("stealing a public repo from Kepr over HTTP", () => {82	test(83		"a stolen copy comes over the wire, stays read-only, and follows its source",84		async () => {85			const root = await mkdtemp(join(tmpdir(), "kepr-steal-"));86			const bucketServer = await startBucket();87			const endpoint = bucketServer.endpoint;88			const keys = { KOH_ACCESS_KEY: ACCESS, KOH_SECRET_KEY: SECRET };89			try {90				// The owner: a small repo in a bucket, offered on every save.91				const ownerHome = join(root, "owner-home");92				const ownerDir = join(root, "owner");93				const repoDir = join(ownerDir, REPO);94				const keptDir = join(ownerDir, PRIVATE_REPO);95				await mkdir(ownerHome, { recursive: true });96				await mkdir(repoDir, { recursive: true });97				await mkdir(keptDir, { recursive: true });98				expect((await koh(repoDir, ownerHome, ["init"], keys)).code).toBe(0);99				expect(100					(await koh(repoDir, ownerHome, ["remote", "s3", endpoint, BUCKET, "fr-par"], keys)).code,101				).toBe(0);102				await writeFile(join(repoDir, "README.md"), "# shipped\n\nA repo to steal.\n");103				await writeFile(join(repoDir, "src.v"), "fn main() {}\n");104				expect((await koh(repoDir, ownerHome, ["save", "first save"])).code).toBe(0);105				await writeFile(join(repoDir, "README.md"), "# shipped\n\nA repo to steal, edited.\n");106				expect((await koh(repoDir, ownerHome, ["save", "second save"])).code).toBe(0);107				// A second repo, never made public on Kepr: only a signed-in machine may have it.108				expect((await koh(keptDir, ownerHome, ["init"], keys)).code).toBe(0);109				expect(110					(await koh(keptDir, ownerHome, ["remote", "s3", endpoint, BUCKET, "fr-par"], keys)).code,111				).toBe(0);112				await writeFile(join(keptDir, "secret.txt"), "kept in the bucket\n");113				expect((await koh(keptDir, ownerHome, ["save", "a private repo"])).code).toBe(0);114115				// Kepr, reading that bucket: the shipped repo is public, the kept one is not.116				const dataDir = await mkdtemp(join(tmpdir(), "kepr-steal-kepr-"));117				const kepr = openKeprDb(dataDir);118				const bucket = {119					kind: "s3" as const,120					endpoint,121					name: BUCKET,122					region: "fr-par",123					accessKeyId: ACCESS,124					secretAccessKey: SECRET,125				};126				/** Kepr syncs on its own loop in production; here each new save is synced by hand. */127				const sync = () =>128					syncAll({129						bucket: openBucket(bucket),130						kepr,131						mirrorDir: join(dataDir, "mirror"),132					});133				await sync();134				kepr.query("UPDATE repos SET public = 1 WHERE name = ?").run(REPO);135				let app: Hono;136				const server = Bun.serve({137					port: 0,138					fetch: (request) => app.fetch(request),139				});140				app = createApp(141					{142						domain: `127.0.0.1:${server.port}`,143						dataDir,144						adminPasswordHash: await Bun.password.hash(PASSWORD, "argon2id"),145						bucket: { ...bucket, write: { accessKeyId: ACCESS, secretAccessKey: SECRET } },146					},147					kepr,148				);149				const host = `http://127.0.0.1:${server.port}`;150151				// The second machine: nothing but a HOME and the address it was told.152				const thiefHome = join(root, "thief-home");153				const thiefDir = join(root, "thief");154				await mkdir(thiefHome, { recursive: true });155				await mkdir(thiefDir, { recursive: true });156				const stolen = await koh(thiefDir, thiefHome, ["steal", `${host}/${REPO}`]);157				expect(stolen.code, stolen.err + stolen.out).toBe(0);158				const copy = join(thiefDir, REPO);159				expect(await readFile(join(copy, "README.md"), "utf8")).toContain("edited");160				expect((await koh(copy, thiefHome, ["doctor"])).code).toBe(0);161				// Save for save, the copy is the line the owner published.162				expect(await line(copy, thiefHome)).toEqual(await line(repoDir, ownerHome));163				// The source is remembered, and shown above the machine's remote.164				expect((await koh(copy, thiefHome, ["remote"])).out).toContain(`${host}/${REPO}`);165				// And it cannot be offered: it has no bucket of its own.166				const refused = await koh(copy, thiefHome, ["offer"]);167				expect(refused.code).toBe(1);168				expect(refused.err + refused.out).toContain("which is read-only");169170				// A later public save arrives on a bare `koh steal`.171				await writeFile(join(repoDir, "README.md"), "# shipped\n\nA third save.\n");172				expect((await koh(repoDir, ownerHome, ["save", "third save"])).code).toBe(0);173				await sync();174				expect((await koh(copy, thiefHome, ["steal"])).code).toBe(0);175				expect(await readFile(join(copy, "README.md"), "utf8")).toContain("A third save");176177				// A strip on the source side reaches the mirror, and is honoured: history no longer178				// holds the path, so a fresh steal never sees the file at all. On the machine that179				// already had it the file stays on disk — a strip is not a delete — but it is banned:180				// not unsaved work, and never saved again.181				await stripPath(repoDir, ownerHome, "src.v");182				// The strip wrote `/src.v` into `.kohignore`; the next save carries the rule everywhere.183				expect(await readFile(join(repoDir, ".kohignore"), "utf8")).toContain("/src.v\n");184				expect((await koh(repoDir, ownerHome, ["save", "ignore the stripped src.v"])).code).toBe(0);185				await sync();186				expect((await koh(copy, thiefHome, ["steal"])).code).toBe(0);187				expect((await koh(copy, thiefHome, ["doctor"])).code).toBe(0);188				expect(await Bun.file(join(copy, "src.v")).exists()).toBe(true);189				// Not listed as a change; the status line may still quote a save message naming it.190				const status = (await koh(copy, thiefHome, ["status"])).out;191				expect(status).not.toContain("+ src.v");192				expect(status).toContain("no changes");193				const fresh = join(root, "thief-again");194				await mkdir(fresh, { recursive: true });195				expect((await koh(fresh, thiefHome, ["steal", `${host}/${REPO}`])).code).toBe(0);196				expect(await Bun.file(join(fresh, REPO, "src.v")).exists()).toBe(false);197				// A third copy stays stolen to the end, for `offer --json` to upgrade.198				const third = join(root, "thief-three");199				await mkdir(third, { recursive: true });200				expect((await koh(third, thiefHome, ["steal", `${host}/${REPO}`])).code).toBe(0);201				// And a fourth, for `offer --builds --json` to upgrade.202				const fourth = join(root, "thief-four");203				await mkdir(fourth, { recursive: true });204				expect((await koh(fourth, thiefHome, ["steal", `${host}/${REPO}`])).code).toBe(0);205206				// Signing in: a code from the connect page, read the way `koh` reads it.207				// This Kepr's domain is the loopback address it is served on, so the same-origin208				// checks want that origin, not the Browser's default.209				const origin = `https://127.0.0.1:${server.port}`;210				const browser = new Browser(app);211				const signInPage = await browser.get("/sign-in");212				const form = /name="form" value="([^"]+)"/.exec(await signInPage.text())?.[1] ?? "";213				const signed = await browser.request("/sign-in", {214					method: "POST",215					headers: { origin },216					body: new URLSearchParams({ form, password: PASSWORD }),217				});218				expect(signed.status).toBe(303);219				const machine = "thief-machine";220				expect((await browser.get(`/connect?machine=${machine}`)).status).toBe(200);221				const shown = await browser.post("/connect", { machine }, origin);222				const code = /class="mono code">([^<]+)</.exec(await shown.text())?.[1]?.trim() ?? "";223				expect(code).toMatch(/^[A-Z2-9]{4}-[A-Z2-9]{4}$/);224				const signedIn = await koh(thiefDir, thiefHome, ["remote", host, "--code", code]);225				expect(signedIn.code, signedIn.err + signedIn.out).toBe(0);226227				// A save made before the upgrade is local work and nothing else: it must not write to228				// the bucket, and it must not quietly drop the source on its own.229				await writeFile(join(copy, "local.txt"), "work in progress\n");230				const local = await koh(copy, thiefHome, ["save", "local only"]);231				expect(local.code, local.err + local.out).toBe(0);232				expect(local.out + local.err).not.toContain("offered");233				expect((await koh(copy, thiefHome, ["remote"])).out).toContain(`${host}/${REPO}`);234235				// The next offer drops the source: the repo is this machine's own work now; offer is236				// the path the addendum names for the owner case.237				const upgraded = await koh(copy, thiefHome, ["offer"]);238				expect(upgraded.code, upgraded.err + upgraded.out).toBe(0);239				expect(upgraded.out + upgraded.err).toContain("now syncs with your bucket");240				// The owner can read what that offer published, before anything else is saved: the241				// local save the copy was carrying went up with it.242				expect((await koh(repoDir, ownerHome, ["revert", "--yes"])).code).toBe(0);243				expect((await koh(repoDir, ownerHome, ["steal"])).code).toBe(0);244				expect(await readFile(join(repoDir, "local.txt"), "utf8")).toContain("work in progress");245				expect(JSON.parse((await koh(repoDir, ownerHome, ["view", "--json"])).out).saves).toEqual(246					JSON.parse((await koh(copy, thiefHome, ["view", "--json"])).out).saves,247				);248				await writeFile(join(copy, "README.md"), "# shipped\n\nThe thief's edit.\n");249				expect((await koh(copy, thiefHome, ["save", "from the thief"])).code).toBe(0);250				expect((await koh(repoDir, ownerHome, ["steal"])).code).toBe(0);251				expect(await readFile(join(repoDir, "README.md"), "utf8")).toContain("The thief's edit");252253				// The other copy still rides its source. When both sides changed the same file,254				// offer without a terminal refuses as steal would, and never picks a side itself:255				// the file is named, steal is where to choose, and the source stays.256				const other = join(fresh, REPO);257				await writeFile(join(repoDir, "README.md"), "# shipped\n\nThe owner's edit.\n");258				expect((await koh(repoDir, ownerHome, ["save", "owner edits the readme"])).code).toBe(0);259				await writeFile(join(other, "README.md"), "# shipped\n\nThe other copy's edit.\n");260				expect((await koh(other, thiefHome, ["save", "other copy edits"])).code).toBe(0);261				const clashed = await koh(other, thiefHome, ["offer"]);262				expect(clashed.code).toBe(1);263				expect(clashed.err).toContain(264					'README.md changed on both machines — run "koh steal" to choose, then offer',265				);266				expect(await readFile(join(other, "README.md"), "utf8")).toContain("other copy's edit");267				expect((await koh(other, thiefHome, ["remote"])).out).toContain(`${host}/${REPO}`);268				// Choosing there upgrades the copy, and says where the version it gave up lives.269				const chosen = await koh(other, thiefHome, ["steal", "--theirs"]);270				expect(chosen.code, chosen.err + chosen.out).toBe(0);271				expect(chosen.out + chosen.err).toContain("now syncs with your bucket");272				expect(chosen.out + chosen.err).toContain("your README.md is in");273				expect(await readFile(join(other, "README.md"), "utf8")).toContain("The owner's edit");274275				// A repo the public side never serves is stolen from the bucket once signed in.276				const second = join(root, "thief-two");277				await mkdir(second, { recursive: true });278				const kept = await koh(second, thiefHome, ["steal", `${host}/${PRIVATE_REPO}`]);279				expect(kept.code, kept.err + kept.out).toBe(0);280				expect(await readFile(join(second, PRIVATE_REPO, "secret.txt"), "utf8")).toContain("kept");281				// And it is a normal repo: the machine's own remote is untouched by any of this.282				expect((await koh(second, thiefHome, ["remote"])).out).toContain(`s3 ${endpoint}`);283284				// Saves that come in flagged during offer's upgrade are named in its JSON, as steal's are.285				expect((await koh(repoDir, ownerHome, ["steal"])).code).toBe(0);286				await writeFile(join(repoDir, "risky.txt"), "risky\n");287				// The same save brings a build file, so the fourth copy can publish a release.288				await writeFile(join(repoDir, "VERSION"), "1.0.0\n");289				await writeFile(290					join(repoDir, "koh.build"),291					[292						`command = mkdir -p out && printf built > out/app-1.0.0-${platform()}`,293						"output = out/app-{version}-{platform}",294						`platforms = ${platform()}`,295						"",296					].join("\n"),297				);298				const risky = JSON.parse(299					(await koh(repoDir, ownerHome, ["save", "risky", "--json"])).out,300				).id;301				const flag = await koh(repoDir, ownerHome, ["flag", risky, "--reason", "broke the build"]);302				expect(flag.code, flag.err + flag.out).toBe(0);303				expect((await koh(repoDir, ownerHome, ["offer"])).code).toBe(0);304				const flaggedOffer = await koh(join(third, REPO), thiefHome, ["offer", "--json"]);305				expect(flaggedOffer.code, flaggedOffer.err + flaggedOffer.out).toBe(0);306				expect(JSON.parse(flaggedOffer.out).flagged).toEqual([risky]);307				const flaggedBuilds = await koh(join(fourth, REPO), thiefHome, [308					"offer",309					"--builds",310					"--json",311				]);312				expect(flaggedBuilds.code, flaggedBuilds.err + flaggedBuilds.out).toBe(0);313				expect(JSON.parse(flaggedBuilds.out).flagged).toEqual([risky]);314			} finally {315				bucketServer.stop();316			}317		},318		RUN,319	);320});