admin.test.ts

6.2 KB · raw

1import { afterAll, beforeAll, describe, expect, setSystemTime, test } from "bun:test";2import type { Hono } from "hono";3import { Browser, type Instance, instance, PASSWORD } from "./browser.ts";4import { makeRepos, writeRelease } from "./fixture.ts";56// Every admin route with sample parameters, from the app's own route table.7function adminRoutes(app: Hono): { method: string; path: string }[] {8	return app.routes9		.filter((route) => route.path.startsWith("/admin") && route.method !== "ALL")10		.map((route) => ({11			method: route.method,12			path: route.path13				.replace(":repo", "app")14				.replace(/:n\{[^}]+\}/, "1")15				.replace(/:version(\{[^}]+\})?/, "1.0.0"),16		}));17}1819describe("admin sign-in, sessions and the guard", () => {20	let inst: Instance;21	let clock = Date.parse("2026-09-26T12:00:00Z");22	const tick = (seconds: number) => {23		clock += seconds * 1000;24		setSystemTime(new Date(clock));25	};2627	beforeAll(async () => {28		setSystemTime(new Date(clock));29		const repos = await makeRepos(["app"]);30		await writeRelease(repos.bucketDir, "app", {31			version: "1.0.0",32			save: repos.saves.app as string,33			files: [{ platform: "linux-x86_64", name: "app", bytes: new Uint8Array([1]) }],34		});35		inst = await instance(repos.bucketDir);36	});37	afterAll(() => setSystemTime());3839	test("the sign-in page sets a strict double-submit cookie and is never cached", async () => {40		const response = await new Browser(inst.app).request("/sign-in");41		expect(response.status).toBe(200);42		expect(response.headers.get("cache-control")).toBe("no-store");43		const cookie = response.headers.getSetCookie()[0] ?? "";44		expect(cookie).toMatch(45			/^kepr_sign_in=[0-9a-f]{64}; Path=\/; HttpOnly; Secure; SameSite=Strict$/,46		);47	});4849	test("the right password sets a 30-day strict session and opens the console", async () => {50		const browser = new Browser(inst.app);51		await browser.get("/sign-in");52		const response = await browser.post("/sign-in", { password: PASSWORD });53		expect(response.status).toBe(303);54		expect(response.headers.get("location")).toBe("/admin");55		const cookie = response.headers.getSetCookie().find((c) => c.startsWith("kepr_session="));56		expect(cookie).toMatch(57			/^kepr_session=[0-9a-f]{64}; Max-Age=2592000; Path=\/; HttpOnly; Secure; SameSite=Strict$/,58		);59		// Only the token's hash is stored.60		const token = browser.cookies.get("kepr_session") ?? "";61		const stored = inst.kepr62			.query<{ token_hash: string }, []>("SELECT token_hash FROM sessions")63			.all();64		expect(stored.some((row) => row.token_hash === token)).toBe(false);65		const admin = await browser.get("/admin");66		expect(admin.status).toBe(200);67		expect(admin.headers.get("cache-control")).toBe("no-store");68		const text = await admin.text();69		expect(text).toContain("Bucket reachable: 1 repo.");70		expect(text).toContain("format ok");71		expect(text).toMatch(/Running kepr 3\.0\.\d+: [\d,]+ lines of TypeScript/);72	});7374	test("a wrong password, a foreign origin or a missing sign-in cookie is refused", async () => {75		const browser = new Browser(inst.app, "198.51.100.1");76		expect((await browser.signIn("wrong")).status).toBe(401);77		expect(browser.cookies.has("kepr_session")).toBe(false);78		await browser.get("/sign-in");79		expect(80			(await browser.post("/sign-in", { password: PASSWORD }, "https://evil.example")).status,81		).toBe(403);82		expect((await browser.post("/sign-in", { password: PASSWORD }, "")).status).toBe(403);83		browser.cookies.delete("kepr_sign_in");84		expect((await browser.post("/sign-in", { password: PASSWORD })).status).toBe(403);85	});8687	test("five failures lock one address out for 15 minutes, even with the right password", async () => {88		const browser = new Browser(inst.app, "198.51.100.2");89		for (let i = 0; i < 5; i++) expect((await browser.signIn("nope")).status).toBe(401);90		const locked = await browser.signIn();91		expect(locked.status).toBe(429);92		expect(locked.headers.get("retry-after")).toBe("900");93		expect((await new Browser(inst.app, "198.51.100.3").signIn()).status).toBe(303);94		tick(901);95		expect((await browser.signIn()).status).toBe(303);96	});9798	test("failures are limited per address, with no global cap", async () => {99		for (let i = 0; i < 30; i++) {100			expect((await new Browser(inst.app, `192.0.2.${i}`).signIn("nope")).status).toBe(401);101		}102		expect((await new Browser(inst.app, "192.0.2.200").signIn()).status).toBe(303);103	});104105	test("every admin route: signed out is 401; a post needs the origin and the form token", async () => {106		const routes = adminRoutes(inst.app);107		expect(routes.length).toBeGreaterThan(1);108		const stranger = new Browser(inst.app);109		for (const { method, path } of routes) {110			const response =111				method === "GET" ? await stranger.get(path) : await stranger.post(path, { form: "x" });112			expect(`${method} ${path} ${response.status}`).toBe(`${method} ${path} 401`);113		}114		const browser = new Browser(inst.app);115		await browser.signIn();116		for (const { path } of routes.filter((route) => route.method === "POST")) {117			const foreign = await browser.post(path, {}, "https://evil.example");118			expect(`${path} ${foreign.status}`).toBe(`${path} 403`);119			const bare = await browser.post(path, {}, "");120			expect(`${path} ${bare.status}`).toBe(`${path} 403`);121			const tokenless = await browser.post(path, { form: "" });122			expect(`${path} ${tokenless.status}`).toBe(`${path} 403`);123			const other = new Browser(inst.app);124			await other.signIn();125			const foreignToken = await browser.post(path, { form: other.form });126			expect(`${path} ${foreignToken.status}`).toBe(`${path} 403`);127		}128	});129130	test("a session expires after 30 days", async () => {131		const browser = new Browser(inst.app);132		await browser.signIn();133		tick(30 * 86400 - 10);134		expect((await browser.get("/admin")).status).toBe(200);135		tick(11);136		expect((await browser.get("/admin")).status).toBe(401);137	});138139	test("signing out revokes the session on the server, not just the cookie", async () => {140		const browser = new Browser(inst.app);141		await browser.signIn();142		const token = browser.cookies.get("kepr_session") ?? "";143		const out = await browser.post("/admin/sign-out", {});144		expect(out.status).toBe(303);145		expect(browser.cookies.has("kepr_session")).toBe(false);146		browser.cookies.set("kepr_session", token);147		expect((await browser.get("/admin")).status).toBe(401);148	});149});