Public: anyone can read this; the crew can change it.
Every Set-Cookie the app writes is HttpOnly, SameSite and Secure behind TLS, proven by one scan test #15178
Check · Review · Land · Live done — Landed and live in production.
scout/forge:scout/15155-every-set-cookie-the-app-writes-is-httpo → main 1 commit fork
1 file
changed +215
−0
test/cookie-floor.test.ts added +215
| @@ -0,0 +1,215 @@ | ||
| 1 | /** | |
| 2 | * The cookie floor (#15155): every Set-Cookie the forge writes is HttpOnly and | |
| 3 | * SameSite, and Secure behind TLS. One scan finds every place under src/ that | |
| 4 | * constructs a cookie: a `set-cookie` header written by `.append`/`.set` or as | |
| 5 | * an object key, and a script write (`document.cookie =`, `cookieStore.set`). | |
| 6 | * Each header write is traced from its value to `setCookie`/`expireCookie` in | |
| 7 | * src/auth/cookies.ts. The helper always adds HttpOnly and SameSite=Lax, and | |
| 8 | * adds Secure when told to, and the outputs below prove it. A script write can | |
| 9 | * never be HttpOnly, so it fails unless SCRIPT_READABLE names it with a reason. | |
| 10 | * test/cookie-flags.test.ts drives the doors; this file pins the floor. | |
| 11 | */ | |
| 12 | import { describe, expect, test } from "bun:test"; | |
| 13 | import { readFileSync } from "node:fs"; | |
| 14 | import { expireCookie, setCookie } from "../src/auth/cookies.ts"; | |
| 15 | ||
| 16 | /** | |
| 17 | * Cookies written on purpose so a page script can read them, keyed by | |
| 18 | * `file:what`, each with its reason. None today: the theme is painted by the | |
| 19 | * server, and no page script reads a cookie. | |
| 20 | */ | |
| 21 | const SCRIPT_READABLE: Record<string, string> = {}; | |
| 22 | ||
| 23 | /** | |
| 24 | * Header writes whose value is passed in from somewhere the trace cannot | |
| 25 | * follow, keyed by `file expression`, each naming where that value is built. | |
| 26 | */ | |
| 27 | const PASSED_IN: Record<string, string> = { | |
| 28 | "src/web/layout.ts o.cookie": "a page's `cookie` option; each caller passes a line from setCookie (the theme in src/web/pages/site.ts)", | |
| 29 | }; | |
| 30 | ||
| 31 | const HELPERS = new Set(["setCookie", "expireCookie"]); | |
| 32 | ||
| 33 | type Source = { file: string; text: string }; | |
| 34 | ||
| 35 | /** The expression starting at `at`, ending at a depth-0 `,` `;` `)` `}` `]` or line end. */ | |
| 36 | function expressionAt(text: string, at: number): string { | |
| 37 | let depth = 0; | |
| 38 | let quote = ""; | |
| 39 | for (let i = at; i < text.length; i++) { | |
| 40 | const c = text[i]!; | |
| 41 | if (quote) { | |
| 42 | if (c === "\\") i++; | |
| 43 | else if (c === quote) quote = ""; | |
| 44 | continue; | |
| 45 | } | |
| 46 | if (c === '"' || c === "'" || c === "`") quote = c; | |
| 47 | else if ("([{".includes(c)) depth++; | |
| 48 | else if (")]}".includes(c)) { | |
| 49 | if (depth === 0) return text.slice(at, i).trim(); | |
| 50 | depth--; | |
| 51 | } else if (depth === 0 && (c === "," || c === ";" || c === "\n")) return text.slice(at, i).trim(); | |
| 52 | } | |
| 53 | return text.slice(at).trim(); | |
| 54 | } | |
| 55 | ||
| 56 | /** The names called in `expr`, member calls (`x.get(`) left out. */ | |
| 57 | const callsIn = (expr: string): string[] => [...expr.matchAll(/(?<![.\w$])([A-Za-z_$][\w$]*)\s*\(/g)].map((m) => m[1]!); | |
| 58 | ||
| 59 | /** | |
| 60 | * The names each top-level function or arrow in `sources` calls, by its name. A top-level body ends | |
| 61 | * at the `}` that opens a line, or before the next line that starts flush left (a signature's | |
| 62 | * closing `)` excepted). | |
| 63 | */ | |
| 64 | function definitions(sources: Source[]): Map<string, string[]> { | |
| 65 | const calls = new Map<string, string[]>(); | |
| 66 | for (const { text } of sources) { | |
| 67 | for (const def of text.matchAll(/^(?:export )?(?:async )?(?:function\*? ([A-Za-z_$][\w$]*)|const ([A-Za-z_$][\w$]*)\s*=)/gm)) { | |
| 68 | const name = (def[1] ?? def[2])!; | |
| 69 | const rest = text.slice(def.index); | |
| 70 | const end = /\n(?:\}[^\n]*|(?=[^\s)]))/.exec(rest); | |
| 71 | const body = end === null ? rest : rest.slice(0, end.index + end[0].length); | |
| 72 | calls.set(name, [...(calls.get(name) ?? []), ...callsIn(body).filter((n) => n !== name)]); | |
| 73 | } | |
| 74 | } | |
| 75 | return calls; | |
| 76 | } | |
| 77 | ||
| 78 | /** Whether calling `name` reaches the helper, through the functions `defs` knows. */ | |
| 79 | function reaches(name: string, defs: Map<string, string[]>, memo: Map<string, boolean>): boolean { | |
| 80 | if (HELPERS.has(name)) return true; | |
| 81 | const known = memo.get(name); | |
| 82 | if (known !== undefined) return known; | |
| 83 | memo.set(name, false); // a cycle reaches nothing new | |
| 84 | const yes = (defs.get(name) ?? []).some((n) => reaches(n, defs, memo)); | |
| 85 | memo.set(name, yes); | |
| 86 | return yes; | |
| 87 | } | |
| 88 | ||
| 89 | /** | |
| 90 | * `expr`, with a bare variable or `map.get(…)` replaced by what the file assigns it, a few steps | |
| 91 | * deep. | |
| 92 | */ | |
| 93 | function resolve(expr: string, text: string, depth = 3): string { | |
| 94 | const next = resolveOnce(expr, text); | |
| 95 | return next === expr || depth === 0 ? next : resolve(next, text, depth - 1); | |
| 96 | } | |
| 97 | ||
| 98 | function resolveOnce(expr: string, text: string): string { | |
| 99 | const ident = /^[A-Za-z_$][\w$]*$/.exec(expr); | |
| 100 | if (ident) { | |
| 101 | const m = new RegExp(`\\b(?:const|let|var)\\s+${expr}\\s*=\\s*`).exec(text); | |
| 102 | if (m) return expressionAt(text, m.index + m[0].length); | |
| 103 | } | |
| 104 | const got = /^([A-Za-z_$][\w$]*)\.get\(/.exec(expr); | |
| 105 | if (got) { | |
| 106 | const m = new RegExp(`\\b${got[1]}\\.set\\(`).exec(text); | |
| 107 | if (m) { | |
| 108 | const args = text.slice(m.index + m[0].length); | |
| 109 | const first = expressionAt(args, 0); | |
| 110 | return expressionAt(args, first.length + 1); | |
| 111 | } | |
| 112 | } | |
| 113 | return expr; | |
| 114 | } | |
| 115 | ||
| 116 | interface Site { | |
| 117 | key: string; | |
| 118 | where: string; | |
| 119 | kind: "header" | "script"; | |
| 120 | ok: boolean; | |
| 121 | } | |
| 122 | ||
| 123 | /** Every cookie construction in `sources`, each said to reach the floor or not. */ | |
| 124 | function scan(sources: Source[]): Site[] { | |
| 125 | const sites: Site[] = []; | |
| 126 | const line = (text: string, at: number) => text.slice(0, at).split("\n").length; | |
| 127 | const defs = definitions(sources); | |
| 128 | const memo = new Map<string, boolean>(); | |
| 129 | for (const { file, text } of sources) { | |
| 130 | for (const m of text.matchAll(/(?:\.(?:append|set)\(\s*["']set-cookie["']\s*,|["']set-cookie["']\s*:)\s*/gi)) { | |
| 131 | const expr = expressionAt(text, m.index + m[0].length); | |
| 132 | const key = `${file} ${expr}`; | |
| 133 | const ok = PASSED_IN[key] !== undefined || callsIn(resolve(expr, text)).some((n) => reaches(n, defs, memo)); | |
| 134 | sites.push({ key, where: `${file}:${line(text, m.index)}`, kind: "header", ok }); | |
| 135 | } | |
| 136 | for (const m of text.matchAll(/\bdocument\.cookie\s*=(?!=)|\bcookieStore\.set\s*\(/g)) { | |
| 137 | const key = `${file}:${m[0].replace(/\s+/g, "")}`; | |
| 138 | sites.push({ key, where: `${file}:${line(text, m.index)}`, kind: "script", ok: SCRIPT_READABLE[key] !== undefined }); | |
| 139 | } | |
| 140 | } | |
| 141 | return sites; | |
| 142 | } | |
| 143 | ||
| 144 | /** | |
| 145 | * What a Set-Cookie line lacks of the floor: HttpOnly, SameSite Lax or Strict, Secure when `tls`. | |
| 146 | */ | |
| 147 | function lacks(cookie: string, tls: boolean): string[] { | |
| 148 | const flags = cookie.split(";").slice(1).map((f) => f.trim().toLowerCase()); | |
| 149 | const missing: string[] = []; | |
| 150 | if (!flags.includes("httponly")) missing.push("HttpOnly"); | |
| 151 | if (!flags.includes("samesite=lax") && !flags.includes("samesite=strict")) missing.push("SameSite"); | |
| 152 | if (tls && !flags.includes("secure")) missing.push("Secure"); | |
| 153 | return missing; | |
| 154 | } | |
| 155 | ||
| 156 | const sources: Source[] = [...new Bun.Glob("src/**/*.{ts,js,html}").scanSync(".")] | |
| 157 | .sort() | |
| 158 | .map((file) => ({ file, text: readFileSync(file, "utf8") })); | |
| 159 | ||
| 160 | describe("the cookie floor", () => { | |
| 161 | test("the helper's every line is HttpOnly and SameSite, and Secure behind TLS", () => { | |
| 162 | for (const tls of [true, false]) { | |
| 163 | for (const line of [ | |
| 164 | setCookie("forge_x", "v", { secure: tls }), | |
| 165 | setCookie("forge_x", "v", { path: "/pricing", maxAge: 60, secure: tls }), | |
| 166 | expireCookie("forge_x", { secure: tls }), | |
| 167 | ]) | |
| 168 | expect([line, lacks(line, tls)]).toEqual([line, []]); | |
| 169 | } | |
| 170 | expect(lacks(setCookie("forge_x", "v", { secure: false }), true)).toEqual(["Secure"]); | |
| 171 | }); | |
| 172 | ||
| 173 | test("every cookie constructed under src/ reaches the helper, or is named with its reason", () => { | |
| 174 | const sites = scan(sources); | |
| 175 | // The scan sees the forge's cookie sites, not none: a scan that finds nothing passes anything. | |
| 176 | expect(sites.filter((s) => s.kind === "header").length).toBeGreaterThan(20); | |
| 177 | expect(sites.filter((s) => !s.ok).map((s) => `${s.where}: ${s.key} does not reach setCookie in src/auth/cookies.ts`)).toEqual([]); | |
| 178 | }); | |
| 179 | ||
| 180 | test("every allow-list entry has a reason and a site", () => { | |
| 181 | const keys = new Set(scan(sources).map((s) => s.key)); | |
| 182 | for (const [key, why] of [...Object.entries(SCRIPT_READABLE), ...Object.entries(PASSED_IN)]) { | |
| 183 | expect([key, why.length > 20]).toEqual([key, true]); | |
| 184 | expect([key, keys.has(key)]).toEqual([key, true]); | |
| 185 | } | |
| 186 | }); | |
| 187 | ||
| 188 | test("the scan fails a hand-spelled cookie, a builder that skips the helper, and a script write", () => { | |
| 189 | const bad: Source[] = [ | |
| 190 | { file: "src/x/raw.ts", text: `res.headers.append("set-cookie", "sid=1; Path=/");\n` }, | |
| 191 | { file: "src/x/object.ts", text: `new Response("", { headers: { "Set-Cookie": \`sid=\${v}\` } });\n` }, | |
| 192 | { file: "src/x/builder.ts", text: `export function line(v: string): string {\n return \`sid=\${v}; Path=/\`;\n}\nh.set("set-cookie", line(v));\n` }, | |
| 193 | { file: "src/x/script.ts", text: `const js = "document.cookie = 'theme=dark'";\n` }, | |
| 194 | { file: "src/x/store.ts", text: `cookieStore.set("theme", "dark");\n` }, | |
| 195 | ]; | |
| 196 | expect(scan(bad).map((s) => [s.where, s.ok])).toEqual([ | |
| 197 | ["src/x/raw.ts:1", false], | |
| 198 | ["src/x/object.ts:1", false], | |
| 199 | ["src/x/builder.ts:4", false], | |
| 200 | ["src/x/script.ts:1", false], | |
| 201 | ["src/x/store.ts:1", false], | |
| 202 | ]); | |
| 203 | const good: Source[] = [ | |
| 204 | { file: "src/x/via.ts", text: `const made = (v: string) =>\n setCookie("sid", v, { secure });\nconst c = made(v);\nh.append("set-cookie", c);\n` }, | |
| 205 | ]; | |
| 206 | expect(scan(good).map((s) => [s.where, s.ok])).toEqual([["src/x/via.ts:4", true]]); | |
| 207 | }); | |
| 208 | ||
| 209 | test("a line without HttpOnly, SameSite, or Secure behind TLS is short of the floor", () => { | |
| 210 | expect(lacks("a=1; Path=/; SameSite=Lax; Secure", true)).toEqual(["HttpOnly"]); | |
| 211 | expect(lacks("a=1; Path=/; HttpOnly; SameSite=None; Secure", true)).toEqual(["SameSite"]); | |
| 212 | expect(lacks("a=1; Path=/; HttpOnly; SameSite=Strict", true)).toEqual(["Secure"]); | |
| 213 | expect(lacks("a=1; Path=/; HttpOnly; SameSite=Strict", false)).toEqual([]); | |
| 214 | }); | |
| 215 | }); |
new above
offline