Public: anyone can read this; the crew can change it.
The security page serves from a kept snapshot, not synchronous reads per request #17903
Merged 26h 48m ago, live in production
scout/forge:scout/17886-the-security-page-serves-from-a-kept-sna → main 0 commits fork
3 files
changed +63
−10
src/web/pages/security.ts +40 −7
| @@ -8,7 +8,7 @@ | ||
| 8 | 8 | |
| 9 | 9 | import { sshOn } from "../../settings/ssh.ts"; |
| 10 | 10 | import { upstreamBlob } from "../../core/upstream.ts"; |
| 11 | import { existsSync, readFileSync, statSync } from "node:fs"; | |
| 11 | import { readFileSync, statSync } from "node:fs"; | |
| 12 | 12 | import { join } from "node:path"; |
| 13 | 13 | import type { Database } from "bun:sqlite"; |
| 14 | 14 | import { changeShield, lastShieldChange, shieldState, SHIELD_DEFAULT, SHIELD_STATES, type ShieldState } from "../../actions/shield.ts"; |
| @@ -51,10 +51,19 @@ export interface SecurityReport { | ||
| 51 | 51 | |
| 52 | 52 | const isCount = (n: unknown): n is number => Number.isInteger(n) && (n as number) >= 0; |
| 53 | 53 | |
| 54 | export function readSecurityReport(dataDir: string): SecurityReport | null { | |
| 55 | const path = join(dataDir, "security-report.json"); | |
| 54 | /** The report file's stat, or undefined when it is missing or cannot be stat'd. */ | |
| 55 | function reportStat(path: string): ReturnType<typeof statSync> { | |
| 56 | 56 | try { |
| 57 | if (!existsSync(path) || statSync(path).size > REPORT_MAX_BYTES) return null; | |
| 57 | return statSync(path, { throwIfNoEntry: false }); | |
| 58 | } catch { | |
| 59 | return undefined; | |
| 60 | } | |
| 61 | } | |
| 62 | ||
| 63 | /** The report at `path`, of `size` bytes by its stat; null when too big or malformed. */ | |
| 64 | function parseReport(path: string, size: number): SecurityReport | null { | |
| 65 | try { | |
| 66 | if (size > REPORT_MAX_BYTES) return null; | |
| 58 | 67 | const r = JSON.parse(readFileSync(path, "utf8")) as Partial<SecurityReport> | null; |
| 59 | 68 | if (typeof r?.at !== "string" || Number.isNaN(Date.parse(r.at))) return null; |
| 60 | 69 | if (!isCount(r.secretScan?.findings) || !isCount(r.selfTest?.passed) || !isCount(r.selfTest?.failed)) return null; |
| @@ -64,6 +73,30 @@ export function readSecurityReport(dataDir: string): SecurityReport | null { | ||
| 64 | 73 | } |
| 65 | 74 | } |
| 66 | 75 | |
| 76 | export function readSecurityReport(dataDir: string): SecurityReport | null { | |
| 77 | const path = join(dataDir, "security-report.json"); | |
| 78 | const st = reportStat(path); | |
| 79 | return st === undefined ? null : parseReport(path, Number(st.size)); | |
| 80 | } | |
| 81 | ||
| 82 | /** The last report each forge read, with the mtime and size it was read at (#17886). */ | |
| 83 | const keptBy = new WeakMap<object, { key: string; report: SecurityReport | null }>(); | |
| 84 | ||
| 85 | /** | |
| 86 | * The report as `readSecurityReport` gives it, read again only when the file's mtime or size | |
| 87 | * moved: an unchanged file costs one stat per request, not a read and a parse. | |
| 88 | */ | |
| 89 | function keptSecurityReport(owner: object, dataDir: string): SecurityReport | null { | |
| 90 | const path = join(dataDir, "security-report.json"); | |
| 91 | const st = reportStat(path); | |
| 92 | const key = st === undefined ? "none" : `${st.mtimeMs}:${st.size}`; | |
| 93 | const held = keptBy.get(owner); | |
| 94 | if (held?.key === key) return held.report; | |
| 95 | const report = st === undefined ? null : parseReport(path, Number(st.size)); | |
| 96 | keptBy.set(owner, { key, report }); | |
| 97 | return report; | |
| 98 | } | |
| 99 | ||
| 67 | 100 | const SHIELD_WORDS: Record<ShieldState, { name: string; does: string }> = { |
| 68 | 101 | open: { |
| 69 | 102 | name: "Open", |
| @@ -226,8 +259,8 @@ function deletedRows(db: Database, since: string): (readonly (Html | string)[])[ | ||
| 226 | 259 | }); |
| 227 | 260 | } |
| 228 | 261 | |
| 229 | function reportRow(dataDir: string, nowMs: number): Html { | |
| 230 | const r = readSecurityReport(dataDir); | |
| 262 | function reportRow(owner: object, dataDir: string, nowMs: number): Html { | |
| 263 | const r = keptSecurityReport(owner, dataDir); | |
| 231 | 264 | if (r === null) |
| 232 | 265 | return statusRow( |
| 233 | 266 | "Secret scan and self-test", |
| @@ -320,7 +353,7 @@ export function securityPage(ctx: Ctx): Response { | ||
| 320 | 353 | ? html`${badge("Not run", { tone: "attn" })} No restore drill has run.` |
| 321 | 354 | : html`${drill.verdict === "green" ? badge("Passed", { tone: "success" }) : badge("Failed", { tone: "danger" })} Last ran ${time(drill.at)}.`, |
| 322 | 355 | )} |
| 323 | ${reportRow(dataDir, nowMs)} | |
| 356 | ${reportRow(ctx.app, dataDir, nowMs)} | |
| 324 | 357 | ${cspRow(db, nowMs)} |
| 325 | 358 | ${scriptErrorRow(db, nowMs)} |
| 326 | 359 | ${statusRow("Admin accounts", html`${admins.map((a, i) => html`${i > 0 ? ", " : ""}${a.username}${a.is_agent === 1 ? " (agent)" : ""}${a.suspended_at === null ? "" : " (suspended)"}`)}`)} |
test/request-path-sync.test.ts +2 −2
| @@ -46,8 +46,8 @@ const ALLOWED: Record<string, Partial<Record<SyncCall, Allowed>>> = { | ||
| 46 | 46 | appendFileSync: { count: 1, reason: "batched: one append per day file a flush, once a second on a timer, never one per request" }, |
| 47 | 47 | }, |
| 48 | 48 | "src/web/pages/security.ts": { |
| 49 | statSync: { count: 1, reason: "admin-only security page: one stat of security-report.json before it is read" }, | |
| 50 | readFileSync: { count: 1, reason: "admin-only security page: one read of security-report.json, refused past 64 KiB by the stat before it" }, | |
| 49 | statSync: { count: 1, reason: "admin-only security page: one stat of security-report.json, its mtime and size the key of the kept report (#17886)" }, | |
| 50 | readFileSync: { count: 1, reason: "admin-only security page: read once per change of security-report.json, refused past 64 KiB by the stat before it (#17886)" }, | |
| 51 | 51 | }, |
| 52 | 52 | }; |
| 53 | 53 |
test/shield.test.ts +21 −1
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | /** The Shield and /settings/security: admin only, three persistent states, origin-gated, evidence without values. */ |
| 2 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 2 | import { afterAll, beforeAll, expect, spyOn, test } from "bun:test"; | |
| 3 | import * as fs from "node:fs"; | |
| 3 | 4 | import { mkdtemp, rm, writeFile } from "node:fs/promises"; |
| 4 | 5 | import { tmpdir } from "node:os"; |
| 5 | 6 | import { join } from "node:path"; |
| @@ -113,6 +114,25 @@ test("a report missing or corrupt reads as not run; a good one shows its counts" | ||
| 113 | 114 | expect(page).toContain("7 checks passed"); |
| 114 | 115 | }); |
| 115 | 116 | |
| 117 | test("the report is read once per change, not once per request: 3 requests, 1 read; a rewrite is read again (#17886)", async () => { | |
| 118 | const path = join(dataDir, "security-report.json"); | |
| 119 | const write = (findings: number) => writeFile(path, JSON.stringify({ at: new Date().toISOString(), secretScan: { findings }, selfTest: { passed: 7, failed: 0 } })); | |
| 120 | await write(3); | |
| 121 | const reads = spyOn(fs, "readFileSync"); | |
| 122 | const ofReport = () => reads.mock.calls.filter((c) => String(c[0]) === path).length; | |
| 123 | try { | |
| 124 | for (let i = 0; i < 3; i++) expect(await (await get("/settings/security", { cookie })).text()).toContain("3 found"); | |
| 125 | expect(ofReport()).toBe(1); | |
| 126 | await write(12); // a longer file: a new size even when the mtime ties | |
| 127 | expect(await (await get("/settings/security", { cookie })).text()).toContain("12 found"); | |
| 128 | expect(ofReport()).toBe(2); | |
| 129 | await fs.promises.rm(path); | |
| 130 | expect(await (await get("/settings/security", { cookie })).text()).toContain("Not run"); | |
| 131 | } finally { | |
| 132 | reads.mockRestore(); | |
| 133 | } | |
| 134 | }); | |
| 135 | ||
| 116 | 136 | test("a change from another site is refused and changes nothing", async () => { |
| 117 | 137 | const res = await post("signin", { cookie, origin: "https://evil.example" }); |
| 118 | 138 | expect(res.status).toBe(403); |
new above
offline