bucket.test.ts

7.9 KB · raw

1import { beforeAll, describe, expect, test } from "bun:test";2import { writeFile } from "node:fs/promises";3import { join } from "node:path";4import { openBucket } from "../src/bucket/reader.ts";5import {6	checkFormat,7	listEventIds,8	listRepos,9	readEvent,10	readHead,11	readObject,12	readSave,13} from "../src/bucket/repo.ts";14import { type Fixture, makeKohBucket } from "./fixture.ts";1516let fx: Fixture;17beforeAll(async () => {18	fx = await makeKohBucket();19});2021const bucket = () => openBucket({ kind: "folder", path: fx.bucketDir });2223describe("reading a koh3-produced folder remote", () => {24	test("lists the repo", async () => {25		expect(await listRepos(bucket())).toEqual([fx.repo]);26	});2728	test("reads format, head, the save record and one verified object end to end", async () => {29		const b = bucket();30		await checkFormat(b, fx.repo);31		const head = await readHead(b, fx.repo);32		expect(head).toBe(fx.saveIds[0] as string);3334		const save = await readSave(b, fx.repo, head as string);35		expect(save.message).toBe("say hello");36		expect(save.is_checkpoint).toBe(false);37		const checkpoint = await readSave(b, fx.repo, save.parent);38		expect(checkpoint.is_checkpoint).toBe(true);39		const first = await readSave(b, fx.repo, checkpoint.parent);40		expect([first.agent, first.session]).toEqual(["test-agent", "fixture"]);4142		const main = save.files.find((file) => file.path === "src/main.ts");43		const { bytes } = await readObject(b, fx.repo, main?.hash as string);44		expect(new TextDecoder().decode(bytes)).toBe("// Entry point.\nconsole.log('hello');\n");45	});4647	test("a missing key reads as null and a listing is prefix-scoped", async () => {48		const b = bucket();49		expect(await b.get(`${fx.repo}/nothing-here`)).toBeNull();50		const saves = await b.list(`${fx.repo}/saves/`);51		expect(saves.sort()).toEqual(fx.saveIds.map((id) => `${fx.repo}/saves/${id}`).sort());52	});53});5455test("the S3 reader pages through listings and reads a missing key as null", async () => {56	const pageSize = 2;57	const server = Bun.serve({58		port: 0,59		async fetch(req) {60			const url = new URL(req.url);61			const folder = bucket();62			if (url.searchParams.get("list-type") === "2") {63				const all = await folder.list(url.searchParams.get("prefix") ?? "");64				const start = Number(url.searchParams.get("continuation-token") ?? 0);65				const page = all.slice(start, start + pageSize);66				const more = start + pageSize < all.length;67				const contents = page.map((key) => `<Contents><Key>${key}</Key></Contents>`).join("");68				const next = more69					? `<NextContinuationToken>${start + pageSize}</NextContinuationToken>`70					: "";71				return new Response(72					`<ListBucketResult><IsTruncated>${more}</IsTruncated>${contents}${next}</ListBucketResult>`,73				);74			}75			const bytes = await folder.get(url.pathname.replace("/kohbucket/", ""));76			if (bytes) return new Response(bytes);77			return new Response("<Error><Code>NoSuchKey</Code></Error>", { status: 404 });78		},79	});80	try {81		const s3 = openBucket({82			kind: "s3",83			endpoint: `http://localhost:${server.port}`,84			name: "kohbucket",85			region: "fr-par",86			accessKeyId: "read",87			secretAccessKey: "only",88		});89		expect(await s3.list(`${fx.repo}/`)).toEqual(await bucket().list(`${fx.repo}/`));90		expect(await readHead(s3, fx.repo)).toBe(fx.saveIds[0] as string);91		expect(await s3.get(`${fx.repo}/format`)).toBeNull();92	} finally {93		server.stop();94	}95});9697describe("the format rule", () => {98	test("accepts koh-remote 1 and refuses anything else", async () => {99		const { bucketDir, repo } = await makeKohBucket("formatted");100		const b = openBucket({ kind: "folder", path: bucketDir });101		await writeFile(join(bucketDir, repo, "format"), "koh-remote 1");102		await checkFormat(b, repo);103		await writeFile(join(bucketDir, repo, "format"), "koh-remote 2");104		await expect(checkFormat(b, repo)).rejects.toThrow('remote format "koh-remote 2"');105	});106});107108describe("object verification", () => {109	test("refuses an object whose content does not match its key", async () => {110		const b = bucket();111		const save = await readSave(b, fx.repo, fx.saveIds[0] as string);112		const [one, two] = save.files;113		const swapped = {114			...b,115			get: (key: string) => b.get(key.replace(one?.hash ?? "", two?.hash ?? "")),116		};117		await expect(readObject(swapped, fx.repo, one?.hash as string)).rejects.toThrow(118			"does not match its hash",119		);120	});121});122123describe("untrusted input", () => {124	// Starts from a genuine koh3 record and corrupts one field, as a tampered bucket would.125	async function readTampered(change: (record: Record<string, unknown>) => void) {126		const id = fx.saveIds[0] as string;127		const real = await bucket().get(`${fx.repo}/saves/${id}`);128		const record = JSON.parse(new TextDecoder().decode(real as Uint8Array));129		change(record);130		const bytes = new TextEncoder().encode(JSON.stringify(record));131		return readSave({ get: async () => bytes, list: async () => [] }, fx.repo, id);132	}133	const withPath = (path: string) => (record: Record<string, unknown>) => {134		(record.files as { path: string }[])[0] = { ...(record.files as { path: string }[])[0], path };135	};136137	test("the genuine record is accepted", async () => {138		expect((await readTampered(() => {})).message).toBe("say hello");139	});140141	test.each([142		"",143		"/etc/passwd",144		"../escape",145		"src/../../escape",146		"./src/main.ts",147		"src//main.ts",148		"src/",149		"src\\main.ts",150		"src/ma\0in.ts",151		"src/ma\nin.ts",152	])("refuses the file path %p", async (path) => {153		await expect(readTampered(withPath(path))).rejects.toThrow("Koh 3 schema");154	});155156	test("refuses duplicate paths in one record", async () => {157		const dupe = (record: Record<string, unknown>) => {158			const files = record.files as { path: string }[];159			files[1] = { ...files[1], path: (files[0] as { path: string }).path } as { path: string };160		};161		await expect(readTampered(dupe)).rejects.toThrow("Koh 3 schema");162	});163164	test.each([165		["parent", "not-an-id"],166		["restores", "ABCDEF123456"],167		["replayed_from", "../../../x"],168		["created_at", -1],169		["created_at", 1.5],170		["size_bytes", -10],171		["size_bytes", "12"],172	])("refuses %s = %p", async (field, value) => {173		await expect(readTampered((record) => (record[field] = value))).rejects.toThrow("Koh 3 schema");174	});175176	test("refuses bad repo names and save IDs before building a key", async () => {177		const b = bucket();178		for (const repo of ["..", "a/b", "", "../demo"]) {179			await expect(checkFormat(b, repo)).rejects.toThrow("not a repo name");180			await expect(readHead(b, repo)).rejects.toThrow("not a repo name");181			await expect(readSave(b, repo, fx.saveIds[0] as string)).rejects.toThrow("not a repo name");182			await expect(readObject(b, repo, "0".repeat(64))).rejects.toThrow("not a repo name");183		}184		for (const id of ["../head", "abc", "ABCDEF123456", `${fx.saveIds[0]}0`]) {185			await expect(readSave(b, fx.repo, id)).rejects.toThrow("not a save ID");186		}187	});188});189190describe("event records", () => {191	test("reads a genuine koh3 flag event and refuses a tampered one", async () => {192		const b = bucket();193		const [id] = await listEventIds(b, fx.repo);194		const event = await readEvent(b, fx.repo, id as string);195		expect([event.kind, event.save_id, event.reason]).toEqual([196			"flag",197			fx.saveIds[3] as string,198			"holds a secret",199		]);200		const stripAll = { kind: "strip", save_id: "", path: "secret.txt" };201		const accepted = new TextEncoder().encode(JSON.stringify({ ...event, ...stripAll }));202		const reader = { get: async () => accepted, list: async () => [] };203		expect((await readEvent(reader, fx.repo, event.id)).kind).toBe("strip");204		for (const change of [205			{ kind: "delete" },206			{ path: "../x" },207			{ save_id: "nope" },208			{ kind: "flag", save_id: "" },209			{ kind: "clear", save_id: "" },210			{ kind: "strip", path: "" },211			{ kind: "strip", save_id: "", path: "" },212		]) {213			const bytes = new TextEncoder().encode(JSON.stringify({ ...event, ...change }));214			const tampered = { get: async () => bytes, list: async () => [] };215			await expect(readEvent(tampered, fx.repo, event.id)).rejects.toThrow("Koh 3 schema");216		}217	});218});