tarball.test.ts

13.8 KB · raw

1import { beforeAll, describe, expect, test } from "bun:test";2import { chmod, mkdir, mkdtemp, readFile, writeFile } from "node:fs/promises";3import { tmpdir } from "node:os";4import { join } from "node:path";5import { fileURLToPath } from "node:url";6import { gunzipSync } from "node:zlib";7import type { Hono } from "hono";8import { type Bucket, openBucket } from "../src/bucket/reader.ts";9import { type SyncTarget, syncAll, syncRepo } from "../src/bucket/sync.ts";10import { openMirror } from "../src/mirror/store.ts";11import { createApp } from "../src/server/app.ts";12import { openKeprDb } from "../src/server/db.ts";13import { cachedTarball } from "../src/tarball/cache.ts";14import { buildTarball, isStripped } from "../src/tarball/tar.ts";15import { type Fixture, KOH_BIN, makeKohBucket } from "./fixture.ts";1617let fx: Fixture;18let app: Hono;19let target: SyncTarget;20let head: string;21let dataDir: string;22const get = (path: string) => app.request(path);23// A kept tarball redirects to the folder bucket's own file, which is the bytes it serves.24const bytesOf = async (path: string) => {25	const response = await get(path);26	const location = response.headers.get("Location");27	return new Uint8Array(28		location ? await readFile(fileURLToPath(location)) : await response.arrayBuffer(),29	);30};31// Whether a tarball of HEAD is kept in the folder bucket under this many strips.32const kept = (strips: number) =>33	[34		...new Bun.Glob(`${strips}-*/${head}.tar.gz`).scanSync(35			join(fx.bucketDir, ".kepr/tarballs/tarry"),36		),37	].length > 0;3839// Every root-level file on Kepr 2's strip list, the .agent folder, and the look-alikes that must stay.40const EXTRA: Record<string, string> = {41	"AGENTS.md": "agents\n",42	"CONTINUITY.md": "notes\n",43	"Cargo.lock": "lock\n",44	"koh.build": "build\n",45	".gitignore": "x\n",46	".agent/CONTINUITY.md": "state\n",47	".agentry/keep.txt": "kept\n",48	"flake.nix": "{ outputs = _: { }; }\n",49	"flake.lock": "{}\n",50	"build.zig.zon": ".{}\n",51	"nested/go.sum": "kept\n",52	"run.sh": "#!/bin/sh\necho run\n",53};5455beforeAll(async () => {56	fx = await makeKohBucket("tarry");57	for (const [path, text] of Object.entries(EXTRA)) {58		await mkdir(join(fx.repoDir, path, ".."), { recursive: true });59		await writeFile(join(fx.repoDir, path), text);60	}61	await chmod(join(fx.repoDir, "run.sh"), 0o755);62	const home = join(fx.repoDir, "../../home");63	const env = { PATH: process.env.PATH, HOME: home, NO_COLOR: "1" };64	const save = Bun.spawnSync([KOH_BIN, "save", "add build files"], { cwd: fx.repoDir, env });65	expect(save.exitCode).toBe(0);66	const log = Bun.spawnSync([KOH_BIN, "view", "--json"], { cwd: fx.repoDir, env });67	head = JSON.parse(log.stdout.toString()).head_id;68	dataDir = await mkdtemp(join(tmpdir(), "kepr-tarball-"));69	const kepr = openKeprDb(dataDir);70	target = {71		bucket: openBucket({ kind: "folder", path: fx.bucketDir }),72		kepr,73		mirrorDir: join(dataDir, "mirror"),74	};75	await syncAll(target);76	kepr.run("UPDATE repos SET public = 1");77	app = createApp(78		{79			domain: "kepr.example",80			dataDir,81			adminPasswordHash: "$argon2id$x",82			bucket: { kind: "folder", path: fx.bucketDir },83		},84		kepr,85	);86});8788function tar(args: string[], input: Uint8Array): string {89	const result = Bun.spawnSync(["tar", ...args], { stdin: input });90	expect(result.exitCode).toBe(0);91	return result.stdout.toString();92}9394describe("the tar format", () => {95	const header = (tarBytes: Uint8Array, index: number) =>96		tarBytes.subarray(index * 512, index * 512 + 512);97	const field = (h: Uint8Array, from: number, to: number) =>98		new TextDecoder().decode(h.subarray(from, to));99100	test("writes Kepr 2's headers: root directory, then files with zero owners and times", () => {101		const gz = buildTarball("r-12345678", [102			{ path: "b.txt", bytes: new TextEncoder().encode("hello source") },103			{ path: "a.sh", bytes: new Uint8Array() },104		]);105		expect([...gz.subarray(0, 10)]).toEqual([0x1f, 0x8b, 8, 0, 0, 0, 0, 0, 0, 3]);106		const t = gunzipSync(gz);107		const [root, a, b] = [header(t, 0), header(t, 1), header(t, 2)];108		expect(field(root, 0, 12)).toBe("r-12345678/\0");109		expect(field(root, 100, 156)).toBe(110			`0000755\0${"0000000\0".repeat(2)}${"\0".repeat(12)}00000000000\0${field(root, 148, 156)}`,111		);112		expect(field(root, 156, 157)).toBe("5");113		expect(field(root, 257, 265)).toBe("ustar\u000000");114		expect(field(a, 0, 16)).toBe("r-12345678/a.sh\0");115		// Every file is 0644, executable or not, exactly as Kepr 2 wrote them (§22.3).116		expect(field(a, 100, 108)).toBe("0000644\0");117		expect(field(b, 100, 108)).toBe("0000644\0");118		expect(field(b, 124, 136)).toBe("00000000014\0");119		expect(field(b, 156, 157)).toBe("0");120		for (const h of [root, a, b]) {121			let sum = 0;122			for (const [i, byte] of h.entries()) sum += i >= 148 && i < 156 ? 32 : byte;123			expect(field(h, 148, 156)).toBe(`${sum.toString(8).padStart(6, "0")}\0 `);124		}125		expect(field(t, 3 * 512, 3 * 512 + 12)).toBe("hello source");126		expect(t.length).toBe(6 * 512);127	});128129	test("writes executable archives at 0755 and plain archives at 0644", () => {130		const executableTar = gunzipSync(131			buildTarball(132				"r",133				[{ path: "run.sh", bytes: new TextEncoder().encode("#!/bin/sh\n") }],134				0o755,135			),136		);137		const plainTar = gunzipSync(138			buildTarball("r", [{ path: "README.md", bytes: new TextEncoder().encode("read me\n") }]),139		);140		expect(field(header(executableTar, 1), 100, 108)).toBe("0000755\0");141		expect(field(header(plainTar, 1), 100, 108)).toBe("0000644\0");142	});143144	test("splits a long path into the ustar prefix, and refuses one that can't be split", () => {145		const long = `${"d".repeat(40)}/${"x".repeat(85)}`;146		const t = gunzipSync(buildTarball("r", [{ path: long, bytes: new Uint8Array() }]));147		const h = header(t, 1);148		expect(field(h, 345, 500).replace(/\0+$/, "")).toBe(`r/${"d".repeat(40)}`);149		expect(field(h, 0, 100).replace(/\0+$/, "")).toBe("x".repeat(85));150		expect(151			tar(["-tzf", "-"], buildTarball("r", [{ path: long, bytes: new Uint8Array() }])),152		).toContain(`r/${long}`);153		expect(() => buildTarball("r", [{ path: "y".repeat(120), bytes: new Uint8Array() }])).toThrow(154			"path too long",155		);156	});157158	test("the strip list matches the repo root only", () => {159		for (const path of [160			"koh.build",161			"kepr.build",162			"go.sum",163			"LOG.md",164			".agent",165			".agent/a/b.md",166			".gitignore",167		])168			expect(isStripped(path)).toBe(true);169		for (const path of [170			"flake.lock",171			"build.zig.zon",172			"nested/go.sum",173			"docs/AGENTS.md",174			".agentry/x",175			"log.md",176		])177			expect(isStripped(path)).toBe(false);178	});179});180181describe("the archive routes", () => {182	test("HEAD.tar.gz redirects uncached to the current save, naming it as the immutable link", async () => {183		const response = await get("/tarry/archive/HEAD.tar.gz");184		expect(response.status).toBe(302);185		expect(response.headers.get("location")).toBe(`/tarry/archive/${head}.tar.gz`);186		expect(response.headers.get("cache-control")).toBe("no-cache");187		expect(response.headers.get("link")).toBe(188			`<https://kepr.example/tarry/archive/${head}.tar.gz>; rel="immutable"`,189		);190	});191192	test("a prefix redirects to the full ID; unknown, malformed or private is a 404", async () => {193		const short = await get(`/tarry/archive/${head.slice(0, 7)}.tar.gz`);194		expect(short.status).toBe(302);195		expect(short.headers.get("location")).toBe(`/tarry/archive/${head}.tar.gz`);196		expect((await get("/tarry/archive/abcdef.tar.gz")).status).toBe(404);197		expect((await get("/tarry/archive/abc.tar.gz")).status).toBe(404);198		target.kepr.run("UPDATE repos SET public = 0");199		const hidden = [200			await get("/tarry/archive/HEAD.tar.gz"),201			await get(`/tarry/archive/${head}.tar.gz`),202		];203		target.kepr.run("UPDATE repos SET public = 1");204		expect(hidden.map((r) => r.status)).toEqual([404, 404]);205	});206207	test("serves the save's files under <repo>-<id8>/ minus the strip list", async () => {208		const response = await get(`/tarry/archive/${head}.tar.gz`);209		expect(response.status).toBe(200);210		expect(response.headers.get("content-type")).toBe("application/gzip");211		expect(response.headers.get("cache-control")).toBe("private, max-age=31536000");212		expect(response.headers.get("content-disposition")).toBe(213			`attachment; filename="tarry-${head.slice(0, 8)}.tar.gz"`,214		);215		const gz = new Uint8Array(await response.arrayBuffer());216		const root = `tarry-${head.slice(0, 8)}`;217		const listed = tar(["-tzf", "-"], gz).trim().split("\n");218		expect(listed).toEqual([219			`${root}/`,220			...[221				".agentry/keep.txt",222				"README.md",223				"build.zig.zon",224				"docs/guide.md",225				"docs/logo.png",226				"flake.lock",227				"flake.nix",228				"nested/go.sum",229				"run.sh",230				"secret.txt",231				"src/lib/deep/util.ts",232				"src/main.ts",233				"vendor/big.c",234			].map((path) => `${root}/${path}`),235		]);236		const out = await mkdtemp(join(tmpdir(), "kepr-untar-"));237		Bun.spawnSync(["tar", "-xzf", "-", "-C", out], { stdin: gz });238		expect(await readFile(join(out, root, "src/main.ts"), "utf8")).toContain("hello");239		expect(await readFile(join(out, root, "docs/logo.png"))).toEqual(240			await readFile(join(fx.repoDir, "docs/logo.png")),241		);242		expect(tar(["-tvzf", "-"], gz)).toMatch(/-rwxr-xr-x .* tarry-[0-9a-f]{8}\/run\.sh/);243	});244245	test("is the same bytes when rebuilt, and in another process", async () => {246		const first = await bytesOf(`/tarry/archive/${head}.tar.gz`);247		const { dropTarballs } = await import("../src/tarball/cache.ts");248		await dropTarballs(target.bucket, "tarry");249		expect(kept(0)).toBe(false);250		expect(await bytesOf(`/tarry/archive/${head}.tar.gz`)).toEqual(first);251		// Every path the other process touches is a fresh temp dir, its working directory included,252		// so nothing it writes can land in the repo.253		const script = `import { cachedTarball } from "${join(import.meta.dir, "../src/tarball/cache.ts")}";254import { openBucket } from "${join(import.meta.dir, "../src/bucket/reader.ts")}";255import { openMirror } from "${join(import.meta.dir, "../src/mirror/store.ts")}";256const { BUCKET_DIR, MIRROR_DIR, SAVE_ID } = process.env;257const bucket = openBucket({ kind: "folder", path: BUCKET_DIR });258const name = "tarry-" + SAVE_ID.slice(0, 8) + ".tar.gz";259const tarball = await cachedTarball(bucket, openMirror(MIRROR_DIR, "tarry"), "tarry", SAVE_ID, name);260process.stdout.write(tarball.bytes);`;261		const scratch = await mkdtemp(join(tmpdir(), "kepr-tb-"));262		const other = Bun.spawnSync(["bun", "-e", script], {263			cwd: scratch,264			env: {265				PATH: process.env.PATH,266				BUCKET_DIR: join(scratch, "bucket"),267				MIRROR_DIR: target.mirrorDir,268				SAVE_ID: head,269			},270		});271		expect(other.stderr.toString()).toBe("");272		expect(new Uint8Array(other.stdout)).toEqual(first);273	});274275	test("after a strip, an old cached tarball is never served, even if its cleanup never ran", async () => {276		await get(`/tarry/archive/${head}.tar.gz`);277		expect(kept(0)).toBe(true);278		await fx.strip("secret.txt");279		// syncRepo lands the strip without syncAll's cleanup: a crash between the two.280		await syncRepo(target.bucket, openMirror(target.mirrorDir, "tarry"), "tarry");281		expect(kept(0)).toBe(true);282		const listed = tar(["-tzf", "-"], await bytesOf(`/tarry/archive/${head}.tar.gz`));283		expect(listed).not.toContain("secret.txt");284		expect(listed).toContain("src/main.ts");285		expect(kept(1)).toBe(true);286	});287288	test("a sync that lands a strip clears the repo's old cached tarballs", async () => {289		await get(`/tarry/archive/${head}.tar.gz`);290		await fx.strip("vendor/big.c");291		await syncAll(target);292		expect(kept(1)).toBe(false);293		expect(tar(["-tzf", "-"], await bytesOf(`/tarry/archive/${head}.tar.gz`))).not.toContain(294			"big.c",295		);296	});297298	test("a strip landing while a kept tarball is fetched is not served", async () => {299		const mirror = openMirror(target.mirrorDir, "tarry");300		await get(`/tarry/archive/${head}.tar.gz`);301		let struck = false;302		const racing: Bucket = {303			...target.bucket,304			async get(key) {305				const bytes = await target.bucket.get(key);306				if (!struck) {307					struck = true;308					await fx.strip("docs/guide.md");309					await syncRepo(target.bucket, mirror, "tarry");310				}311				return bytes;312			},313		};314		const tarball = await cachedTarball(racing, mirror, "tarry", head, "tarry.tar.gz");315		const listed = tar(316			["-tzf", "-"],317			tarball && "bytes" in tarball ? tarball.bytes : new Uint8Array(),318		);319		expect(listed).not.toContain("guide.md");320		expect(listed).toContain("src/main.ts");321	});322});323324describe("the archives panel", () => {325	test("lists HEAD and recent saves with tarball links, and nix lines where there is a flake", async () => {326		const response = await get("/tarry/archives");327		expect(response.status).toBe(200);328		expect(response.headers.get("cache-control")).toBe("public, max-age=60");329		const page = await response.text();330		const ids = [...page.matchAll(/class="history-id"[^>]*>([0-9a-f]{12})</g)].map((m) => m[1]);331		expect(ids).toEqual([head, fx.saveIds[0], fx.saveIds[2], fx.saveIds[3]]);332		expect(page).toContain('<span class="archive-head mono">HEAD</span>');333		expect(page).toContain('class="archive-row archive-row--head"');334		expect(page).toContain(`data-copy="${head}"`);335		expect(page).toContain('data-copy="koh steal kepr.example/tarry"');336		expect(page).toContain(337			'data-copy="curl -fL https://kepr.example/tarry/archive/HEAD.tar.gz | tar xz"',338		);339		expect(page).toContain('href="/tarry/archive/HEAD.tar.gz">↓ tarry-HEAD.tar.gz</a>');340		expect(page).toContain(341			'data-copy="nix profile add https://kepr.example/tarry/archive/HEAD.tar.gz"',342		);343		// Only HEAD has flake.nix; older saves get a tarball link but no nix line.344		expect(page.match(/nix profile add/g)?.length).toBe(2);345		const older = fx.saveIds[0] as string;346		expect(page).toContain(347			`href="/tarry/archive/${older}.tar.gz">↓ tarry-${older.slice(0, 8)}.tar.gz</a>`,348		);349		expect(page).not.toContain(fx.saveIds[1] as string);350	});351352	test("a private repo's panel is a 404", async () => {353		target.kepr.run("UPDATE repos SET public = 0");354		const status = (await get("/tarry/archives")).status;355		target.kepr.run("UPDATE repos SET public = 1");356		expect(status).toBe(404);357	});358});