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

The security page serves from a kept snapshot, not synchronous reads per request #17903

opened this

Merged 26h 48m ago, live in production

scout/forge:scout/17886-the-security-page-serves-from-a-kept-sna → main 0 commits fork

  • Merged. scout/17886-the-security-page-serves-from-a-kept-sna was merged into main as 281b77e.

Review

Sign in to review this change.
3 files changed +63 −10
src/web/pages/security.ts +40 −7
@@ -8,7 +8,7 @@
88
99 import { sshOn } from "../../settings/ssh.ts";
1010 import { upstreamBlob } from "../../core/upstream.ts";
11 import { existsSync, readFileSync, statSync } from "node:fs";
11 import { readFileSync, statSync } from "node:fs";
1212 import { join } from "node:path";
1313 import type { Database } from "bun:sqlite";
1414 import { changeShield, lastShieldChange, shieldState, SHIELD_DEFAULT, SHIELD_STATES, type ShieldState } from "../../actions/shield.ts";
@@ -51,10 +51,19 @@ export interface SecurityReport {
5151
5252 const isCount = (n: unknown): n is number => Number.isInteger(n) && (n as number) >= 0;
5353
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> {
5656 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;
5867 const r = JSON.parse(readFileSync(path, "utf8")) as Partial<SecurityReport> | null;
5968 if (typeof r?.at !== "string" || Number.isNaN(Date.parse(r.at))) return null;
6069 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 {
6473 }
6574 }
6675
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
67100 const SHIELD_WORDS: Record<ShieldState, { name: string; does: string }> = {
68101 open: {
69102 name: "Open",
@@ -226,8 +259,8 @@ function deletedRows(db: Database, since: string): (readonly (Html | string)[])[
226259 });
227260 }
228261
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);
231264 if (r === null)
232265 return statusRow(
233266 "Secret scan and self-test",
@@ -320,7 +353,7 @@ export function securityPage(ctx: Ctx): Response {
320353 ? html`${badge("Not run", { tone: "attn" })} No restore drill has run.`
321354 : html`${drill.verdict === "green" ? badge("Passed", { tone: "success" }) : badge("Failed", { tone: "danger" })} Last ran ${time(drill.at)}.`,
322355 )}
323 ${reportRow(dataDir, nowMs)}
356 ${reportRow(ctx.app, dataDir, nowMs)}
324357 ${cspRow(db, nowMs)}
325358 ${scriptErrorRow(db, nowMs)}
326359 ${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>>> = {
4646 appendFileSync: { count: 1, reason: "batched: one append per day file a flush, once a second on a timer, never one per request" },
4747 },
4848 "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)" },
5151 },
5252 };
5353
test/shield.test.ts +21 −1
@@ -1,5 +1,6 @@
11 /** 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";
34 import { mkdtemp, rm, writeFile } from "node:fs/promises";
45 import { tmpdir } from "node:os";
56 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"
113114 expect(page).toContain("7 checks passed");
114115 });
115116
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
116136 test("a change from another site is refused and changes nothing", async () => {
117137 const res = await post("signin", { cookie, origin: "https://evil.example" });
118138 expect(res.status).toBe(403);

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs