Public: anyone can read this; the crew can change it.

Every route answers with the security headers and every mutation refuses a foreign origin, enumerated from routes.ts #269

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/deal-clock:mason/259-every-route-answers-with-the-security-he → main 2 commits fork 2 threads · 2 unresolved

  • Merged. mason/259-every-route-answers-with-the-security-he was merged into main as 7756f0c.

Review

Sign in to review this change.
2 files changed +115 −0
src/live.ts +3
@@ -7,6 +7,8 @@
77 * so the server `follow`s the database and speaks for writes made elsewhere.
88 */
99
10 import { SECURITY } from "./http.ts";
11
1012 export interface LiveEvent {
1113 readonly id: number;
1214 readonly type: string;
@@ -76,6 +78,7 @@ export function events(request: Request): Response {
7678 "content-type": "text/event-stream",
7779 "cache-control": "no-store",
7880 "x-accel-buffering": "no",
81 ...SECURITY,
7982 },
8083 });
8184 }
src/security.test.ts +112
@@ -8,10 +8,12 @@ import { tmpdir } from "node:os";
88 import { join } from "node:path";
99 import { readContract } from "./can.ts";
1010 import { openDb } from "./db.ts";
11 import { routes } from "./routes.ts";
1112 import {
1213 allow,
1314 door,
1415 doorOf,
16 forgetRationing,
1517 mayKnock,
1618 openToStrangers,
1719 STRANGERS,
@@ -170,3 +172,113 @@ test("strangers are rationed at the API, reads too", () => {
170172 expect(allow("k", { burst: 20, perSecond: 2 }, t)).toBe(false);
171173 expect(allow("k", { burst: 20, perSecond: 2 }, t + 1000)).toBe(true);
172174 });
175
176 // ---- The floor, enumerated from the route table -------------------------
177 // A page added later is covered here without anyone remembering: the tests
outdated

Move these two imports to the top import block with the others.

178 // read `routes`, fill each `:name` with a sample, and ask the running app.
179
180 const FLOOR = [
181 "content-security-policy",
182 "x-content-type-options",
183 "referrer-policy",
184 ] as const;
185 const admin = as("root", "admin");
186 // A GET route that never ends cannot be read to the end: its headers are
187 // read, then the body is cancelled. Each is named here with the reason.
outdated

SPECIAL is only used for an existence check; the loop below hard-codes label.startsWith("GET /events"). Make it drive the handling or remove it.

188 const STREAMS: readonly string[] = ["/events"]; // server-sent events
189 const sample = (path: string, id: number): string =>
190 path.replace(/:(\w+)/g, (_m, name: string) => (name === "file" ? "missing.css" : String(id)));
191 const answerFloor = (r: Response, label: string) => {
192 for (const h of FLOOR) expect(r.headers.get(h), `${label} lacks ${h}`).toBeTruthy();
193 };
194
195 async function seedDeal(): Promise<number> {
196 const form = new FormData();
197 for (const [k, v] of Object.entries({
198 address: "9 Floor Street",
199 buyer: "Ann Buyer",
200 seller: "Sam Seller",
201 contract_date: "2026-10-01",
202 closing_date: "2026-11-05",
203 }))
204 form.set(k, v);
205 const r = await fetch(`${base}/deals`, { method: "POST", body: form, redirect: "manual", headers: admin });
206 return Number(/\/deals\/(\d+)$/.exec(r.headers.get("location") ?? "")?.[1]);
207 }
208
209 test("every GET route, a missing row, an unknown path and a bad escape answer with the floor", async () => {
210 forgetRationing();
211 const id = await seedDeal();
212 expect(id).toBeGreaterThan(0);
213 const gets = routes.filter((r) => r.method === "GET");
214 expect(gets.length).toBeGreaterThan(10);
215 const asks: [string, string][] = [];
216 for (const r of gets) {
217 asks.push([`GET ${r.path} (row exists)`, sample(r.path, id)]);
218 if (r.path.includes(":")) asks.push([`GET ${r.path} (no such row)`, sample(r.path, 987654)]);
219 }
220 asks.push(["unknown path", "/no/such/page"], ["bad escape", "/deals/%ZZ"], ["bad escape in api", "/api/deals/%E0%A4%A"]);
221 for (const [label, path] of asks) {
222 forgetRationing();
223 for (const headers of [admin, {}]) {
224 const r = await fetch(base + path, { headers, redirect: "manual" });
225 answerFloor(r, `${label} ${path}`);
226 if (STREAMS.includes(path)) await r.body?.cancel();
227 else await r.arrayBuffer();
228 }
229 }
230 expect(STREAMS.every((p) => gets.some((r) => r.path === p))).toBe(true);
231 });
232
233 test("errors and refusals carry the floor too", async () => {
234 forgetRationing();
235 const cases: [string, RequestInit][] = [
236 ["/api/deals", { method: "POST", headers: { "content-type": "application/json", ...admin }, body: "{not json" }],
237 ["/api/deals", { method: "POST", headers: { "content-type": "application/json", ...admin }, body: "x".repeat(300_000) }],
238 ["/api/deals", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }],
239 ["/api/audit", { headers: as("u1", "user") }],
240 ["/deals", { method: "POST", headers: { origin: "https://evil.example" } }],
241 ["/mcp", { method: "POST", headers: { "content-type": "application/json", ...admin }, body: "nope" }],
242 ["/deals/1", { method: "DELETE", headers: admin }],
243 ];
244 for (const [path, init] of cases) {
245 forgetRationing();
246 const r = await fetch(base + path, init);
247 answerFloor(r, `${init.method ?? "GET"} ${path} -> ${r.status}`);
248 await r.arrayBuffer();
249 }
250 });
251
252 test("every mutating route refuses a foreign origin and changes nothing", async () => {
253 forgetRationing();
254 const id = await seedDeal();
255 const snapshot = async () => {
256 forgetRationing();
257 const book = await fetch(`${base}/deals/export.json`, { headers: admin });
258 const one = await fetch(`${base}/api/deals/${id}`, { headers: admin });
259 return `${(await book.text()).replace(/"exported_at":\s*"[^"]*"/, "")}\n${await one.text()}`;
260 };
261 const before = await snapshot();
262 const writes = routes.filter((r) => r.method !== "GET");
263 expect(writes.length).toBeGreaterThan(30);
264 for (const r of writes) {
265 for (const foreign of [
266 { origin: "https://evil.example" },
267 { "sec-fetch-site": "cross-site" },
268 { "sec-fetch-site": "same-site", origin: "https://evil.example" },
269 ]) {
270 forgetRationing();
271 const json = r.path.startsWith("/api/") || r.path === "/mcp";
272 const res = await fetch(base + sample(r.path, id), {
273 method: r.method,
274 headers: { ...admin, ...foreign, ...(json ? { "content-type": "application/json" } : {}) },
275 body: r.method === "DELETE" ? undefined : json ? "{}" : new FormData(),
276 redirect: "manual",
277 });
278 expect(res.status, `${r.method} ${r.path} with ${JSON.stringify(foreign)}`).toBe(403);
279 answerFloor(res, `${r.method} ${r.path}`);
280 await res.arrayBuffer();
281 }
282 }
283 expect(await snapshot()).toBe(before);
284 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs