1import { beforeAll, describe, expect, test } from "bun:test";2import { cp, writeFile } from "node:fs/promises";3import { join } from "node:path";4import { inflateSync } from "node:zlib";5import { openBucket } from "../src/bucket/reader.ts";6import {7 checkFormat,8 escapePath,9 listEventIds,10 listRepos,11 readEvent,12 readHead,13 readObject,14 readSave,15} from "../src/bucket/repo.ts";16import { type Fixture, makeKohBucket } from "./fixture.ts";1718let fx: Fixture;19beforeAll(async () => {20 fx = await makeKohBucket();21});2223const bucket = () => openBucket({ kind: "folder", path: fx.bucketDir });2425describe("reading a koh-produced folder remote", () => {26 test("lists the repo", async () => {27 expect(await listRepos(bucket())).toEqual([fx.repo]);28 });2930 test("a folder without a head, or Kepr's own, is not a repo", async () => {31 32 await cp(join(fx.bucketDir, fx.repo, "saves"), join(fx.bucketDir, "half", "saves"), {33 recursive: true,34 });35 await Bun.write(join(fx.bucketDir, ".kepr/hidden", fx.repo), "secret.txt\n");36 expect(await listRepos(bucket())).toEqual([fx.repo]);37 });3839 test("reads format, head, the save record and one verified object end to end", async () => {40 const b = bucket();41 await checkFormat(b, fx.repo);42 const head = await readHead(b, fx.repo);43 expect(head).toBe(fx.saveIds[0] as string);4445 const save = await readSave(b, fx.repo, head as string);46 expect(save.message).toBe("say hello");47 expect(save.is_checkpoint).toBe(false);48 const checkpoint = await readSave(b, fx.repo, save.parent);49 expect(checkpoint.is_checkpoint).toBe(true);50 const first = await readSave(b, fx.repo, checkpoint.parent);51 expect([first.agent, first.session]).toEqual(["test-agent", "fixture"]);5253 const main = save.files.find((file) => file.path === "src/main.ts");54 const { compressed, size } = await readObject(b, fx.repo, main?.hash as string);55 const text = "// Entry point.\nconsole.log('hello');\n";56 expect(new TextDecoder().decode(inflateSync(compressed))).toBe(text);57 expect(size).toBe(text.length);58 });5960 test("a missing key reads as null and a listing is prefix-scoped", async () => {61 const b = bucket();62 expect(await b.get(`${fx.repo}/nothing-here`)).toBeNull();63 const saves = await b.list(`${fx.repo}/saves/`);64 expect(saves.sort()).toEqual(fx.saveIds.map((id) => `${fx.repo}/saves/${id}`).sort());65 });66});6768test("the S3 reader pages through listings with sizes and reads a missing key as null", async () => {69 const pageSize = 2;70 const server = Bun.serve({71 port: 0,72 async fetch(req) {73 const url = new URL(req.url);74 const folder = bucket();75 if (url.searchParams.get("list-type") === "2") {76 const sizes = await folder.sizes(url.searchParams.get("prefix") ?? "");77 const all = [...sizes.keys()];78 const start = Number(url.searchParams.get("continuation-token") ?? 0);79 const page = all.slice(start, start + pageSize);80 const more = start + pageSize < all.length;81 const contents = page82 .map((key) => `<Contents><Key>${key}</Key><Size>${sizes.get(key)}</Size></Contents>`)83 .join("");84 const next = more85 ? `<NextContinuationToken>${start + pageSize}</NextContinuationToken>`86 : "";87 return new Response(88 `<ListBucketResult><IsTruncated>${more}</IsTruncated>${contents}${next}</ListBucketResult>`,89 );90 }91 const bytes = await folder.get(url.pathname.replace("/kohbucket/", ""));92 if (bytes) return new Response(bytes);93 return new Response("<Error><Code>NoSuchKey</Code></Error>", { status: 404 });94 },95 });96 try {97 const s3 = openBucket({98 kind: "s3",99 endpoint: `http://localhost:${server.port}`,100 name: "kohbucket",101 region: "fr-par",102 accessKeyId: "read",103 secretAccessKey: "only",104 });105 expect(await s3.list(`${fx.repo}/`)).toEqual(await bucket().list(`${fx.repo}/`));106 const sizes = await s3.sizes(`${fx.repo}/`);107 expect(sizes).toEqual(await bucket().sizes(`${fx.repo}/`));108 expect(sizes.get(`${fx.repo}/head`)).toBe(12);109 expect(await readHead(s3, fx.repo)).toBe(fx.saveIds[0] as string);110 111 112 const format = await s3.get(`${fx.repo}/format`);113 expect(format === null ? null : new TextDecoder().decode(format)).toBe("koh-remote 1");114 expect(await s3.get(`${fx.repo}/no-such-key`)).toBeNull();115 const url = new URL(116 s3.downloadUrl("demo/releases/1.0/android-arm64/a b.apk", "a b.apk", "t/x"),117 );118 expect(url.pathname).toBe("/kohbucket/demo/releases/1.0/android-arm64/a%20b.apk");119 expect(url.searchParams.get("X-Amz-Expires")).toBe("300");120 expect(url.searchParams.get("response-content-disposition")).toBe(121 'attachment; filename="a b.apk"',122 );123 expect(url.searchParams.get("response-content-type")).toBe("t/x");124 } finally {125 server.stop();126 }127});128129describe("the format rule", () => {130 test("accepts both remote formats and refuses anything else", async () => {131 const { bucketDir, repo } = await makeKohBucket("formatted");132 const b = openBucket({ kind: "folder", path: bucketDir });133 await writeFile(join(bucketDir, repo, "format"), "koh-remote 1");134 await checkFormat(b, repo);135 await writeFile(join(bucketDir, repo, "format"), "koh-remote 2");136 await checkFormat(b, repo);137 await writeFile(join(bucketDir, repo, "format"), "koh-remote 3");138 await expect(checkFormat(b, repo)).rejects.toThrow('remote format "koh-remote 3"');139 });140});141142describe("object verification", () => {143 test("refuses an object whose content does not match its key", async () => {144 const b = bucket();145 const save = await readSave(b, fx.repo, fx.saveIds[0] as string);146 const [one, two] = save.files;147 const swapped = {148 ...b,149 get: (key: string) => b.get(key.replace(one?.hash ?? "", two?.hash ?? "")),150 };151 await expect(readObject(swapped, fx.repo, one?.hash as string)).rejects.toThrow(152 "does not match its hash",153 );154 });155});156157describe("untrusted input", () => {158 159 async function readTampered(change: (record: Record<string, unknown>) => void) {160 const id = fx.saveIds[0] as string;161 const real = await bucket().get(`${fx.repo}/saves/${id}`);162 const record = JSON.parse(new TextDecoder().decode(real as Uint8Array));163 change(record);164 const bytes = new TextEncoder().encode(JSON.stringify(record));165 return readSave(166 {167 get: async () => bytes,168 list: async () => [],169 folders: async () => [],170 size: async () => 0,171 sizes: async () => new Map(),172 downloadUrl: () => "",173 viewUrl: () => null,174 put: async () => {},175 tag: async () => null,176 putIfTag: async () => false,177 remove: async () => {},178 copy: async () => {},179 removeRenamed: async () => {},180 repoKeys: async () => [],181 removeRepoKey: async () => {},182 },183 fx.repo,184 id,185 );186 }187 const withPath = (path: string) => (record: Record<string, unknown>) => {188 (record.files as { path: string }[])[0] = { ...(record.files as { path: string }[])[0], path };189 };190191 test("the genuine record is accepted", async () => {192 expect((await readTampered(() => {})).message).toBe("say hello");193 });194195 196 test.each([197 "",198 "/etc/passwd",199 "../escape",200 "src/../../escape",201 "./src/main.ts",202 "src//main.ts",203 "src/",204 "src\\main.ts",205 "src/ma\0in.ts",206 "src/ma\nin.ts",207 "Icon\r",208 "a\u0085b",209 ])("quarantines the file path %p", async (path) => {210 const save = await readTampered(withPath(path));211 expect(save.files.map((file) => file.path)).not.toContain(path);212 expect(save.files.length).toBeGreaterThan(0);213 expect(save.quarantined).toEqual([escapePath(path)]);214 });215216 test("quarantines bytes outside UTF-8 and unpaired surrogate escapes, and keeps a real U+FFFD", async () => {217 const id = fx.saveIds[0] as string;218 const real = await bucket().get(`${fx.repo}/saves/${id}`);219 const record = JSON.parse(new TextDecoder().decode(real as Uint8Array));220 record.files[0].path = "bad-X-name";221 record.files[1].path = "odd-\ufffd-name";222 record.files[2].path = "lead-\ud800";223 record.files[3].path = "pair-\ud83d\ude00";224 const bytes = Buffer.from(JSON.stringify(record));225 bytes[bytes.indexOf("bad-X-name") + 4] = 0xff;226 const save = await readSave(227 {228 get: async () => bytes,229 list: async () => [],230 folders: async () => [],231 size: async () => 0,232 sizes: async () => new Map(),233 downloadUrl: () => "",234 viewUrl: () => null,235 put: async () => {},236 tag: async () => null,237 putIfTag: async () => false,238 remove: async () => {},239 copy: async () => {},240 removeRenamed: async () => {},241 repoKeys: async () => [],242 removeRepoKey: async () => {},243 },244 fx.repo,245 id,246 );247 expect(save.quarantined.sort()).toEqual(["bad-\\xff-name", "lead-\\xed\\xa0\\x80"]);248 expect(save.files.map((file) => file.path)).toContain("odd-\ufffd-name");249 expect(save.files.map((file) => file.path)).toContain("pair-\ud83d\ude00");250 });251252 test("escapes a name as Koh's escape_path does", () => {253 expect(["Icon\r", "a\\b", "a\u0085", "\x7f", "plain/ok"].map(escapePath)).toEqual([254 "Icon\\x0d",255 "a\\\\b",256 "a\\u0085",257 "\\x7f",258 "plain/ok",259 ]);260 });261262 test("refuses duplicate paths in one record", async () => {263 const dupe = (record: Record<string, unknown>) => {264 const files = record.files as { path: string }[];265 files[1] = { ...files[1], path: (files[0] as { path: string }).path } as { path: string };266 };267 await expect(readTampered(dupe)).rejects.toThrow("Koh 3 schema");268 });269270 test("refuses a record whose manifest is not a manifest hash", async () => {271 for (const manifest of ["", "../../elsewhere", "A".repeat(64)]) {272 await expect(readTampered((record) => (record.manifest = manifest))).rejects.toThrow(273 "Koh 3 schema",274 );275 }276 });277278 test("accepts the six-character IDs that Koh 2's early saves keep through migration", async () => {279 expect((await readTampered((record) => (record.parent = "af96c8"))).parent).toBe("af96c8");280 });281282 test.each([283 ["parent", "not-an-id"],284 ["parent", "af96c"],285 ["parent", "af96c8a"],286 ["restores", "ABCDEF123456"],287 ["replayed_from", "../../../x"],288 ["created_at", -1],289 ["created_at", 1.5],290 ["size_bytes", -10],291 ["size_bytes", "12"],292 ])("refuses %s = %p", async (field, value) => {293 await expect(readTampered((record) => (record[field] = value))).rejects.toThrow("Koh 3 schema");294 });295296 test("refuses bad repo names and save IDs before building a key", async () => {297 const b = bucket();298 for (const repo of ["..", "a/b", "", "../demo"]) {299 await expect(checkFormat(b, repo)).rejects.toThrow("not a repo name");300 await expect(readHead(b, repo)).rejects.toThrow("not a repo name");301 await expect(readSave(b, repo, fx.saveIds[0] as string)).rejects.toThrow("not a repo name");302 await expect(readObject(b, repo, "0".repeat(64))).rejects.toThrow("not a repo name");303 }304 for (const id of ["../head", "abc", "ABCDEF123456", `${fx.saveIds[0]}0`]) {305 await expect(readSave(b, fx.repo, id)).rejects.toThrow("not a save ID");306 }307 });308});309310describe("event records", () => {311 test("reads a genuine koh flag event and refuses a tampered one", async () => {312 const b = bucket();313 const [id] = await listEventIds(b, fx.repo);314 const event = await readEvent(b, fx.repo, id as string);315 expect([event.kind, event.save_id, event.reason]).toEqual([316 "flag",317 fx.saveIds[3] as string,318 "holds a secret",319 ]);320 const stripAll = { kind: "strip", save_id: "", path: "secret.txt" };321 const accepted = new TextEncoder().encode(JSON.stringify({ ...event, ...stripAll }));322 const reader = {323 get: async () => accepted,324 list: async () => [],325 folders: async () => [],326 size: async () => 0,327 sizes: async () => new Map(),328 downloadUrl: () => "",329 viewUrl: () => null,330 put: async () => {},331 tag: async () => null,332 putIfTag: async () => false,333 remove: async () => {},334 copy: async () => {},335 removeRenamed: async () => {},336 repoKeys: async () => [],337 removeRepoKey: async () => {},338 };339 expect((await readEvent(reader, fx.repo, event.id)).kind).toBe("strip");340 for (const change of [341 { kind: "delete" },342 { path: "../x" },343 { save_id: "nope" },344 { kind: "flag", save_id: "" },345 { kind: "clear", save_id: "" },346 { kind: "flag", path: "secret.txt" },347 { kind: "clear", path: "secret.txt" },348 349 ]) {350 const bytes = new TextEncoder().encode(JSON.stringify({ ...event, ...change }));351 const tampered = {352 get: async () => bytes,353 list: async () => [],354 folders: async () => [],355 size: async () => 0,356 sizes: async () => new Map(),357 downloadUrl: () => "",358 viewUrl: () => null,359 put: async () => {},360 tag: async () => null,361 putIfTag: async () => false,362 remove: async () => {},363 copy: async () => {},364 removeRenamed: async () => {},365 repoKeys: async () => [],366 removeRepoKey: async () => {},367 };368 await expect(readEvent(tampered, fx.repo, event.id)).rejects.toThrow("Koh 3 schema");369 }370 });371});372373test("an S3 bucket's tag check sends the HEAD its URL is signed for", async () => {374 375 const methods: string[] = [];376 const stub = Bun.serve({377 port: 0,378 fetch(request) {379 methods.push(request.method);380 return new Response(null, { status: request.method === "HEAD" ? 404 : 403 });381 },382 });383 try {384 const bucket = openBucket({385 kind: "s3",386 endpoint: `http://127.0.0.1:${stub.port}`,387 name: "koh",388 region: "fr-par",389 accessKeyId: "KEY-ID",390 secretAccessKey: "KEY-SECRET",391 });392 expect(await bucket.tag(".kepr/tarballs/app/missing.tar.gz")).toBeNull();393 expect(methods).toEqual(["HEAD"]);394 } finally {395 stub.stop(true);396 }397});