Public: anyone can read this; the crew can change it.
A database guard's words reach the caller only when written for them #949
steward/723-guard-words → main 3 commits
9 files
changed +269
−17
CLAUDE.md +6
| @@ -86,6 +86,12 @@ bun run src/main.ts # boots on :3000, data in ./data | ||
| 86 | 86 | It runs the files in `GATE` (`scripts/gate.ts`), not the whole suite; every |
| 87 | 87 | other test file is in `EXCLUDED` with its reason and owning issue. Add a new |
| 88 | 88 | test file to `GATE`, or the check goes red. |
| 89 | - **A database guard's words are shown to whoever it refuses**, anonymous | |
| 90 | callers included (`src/http/refusal.ts`). A trigger's `RAISE(ABORT, …)` | |
| 91 | message that starts `forge: ` is shown without the prefix, so write it for | |
| 92 | anyone: what to do, no table or column names, no ids. Any other message is | |
| 93 | answered with a generic refusal and logged in full for the operator. Say | |
| 94 | so in a comment beside each `RAISE` in the repository. | |
| 89 | 95 | - **Every non-trivial change ships with a test.** Prefer protocol-level tests |
| 90 | 96 | that boot a real app (`createApp` + `serve`) over unit mocks. Adversarial |
| 91 | 97 | tests (can this be bypassed?) are worth more than happy-path ones. |
scripts/gate.ts +1
| @@ -103,6 +103,7 @@ export const GATE: readonly string[] = [ | ||
| 103 | 103 | "test/vitals.test.ts", |
| 104 | 104 | "test/version.test.ts", |
| 105 | 105 | "test/watches.test.ts", |
| 106 | "test/guard-words.test.ts", | |
| 106 | 107 | "test/guard.test.ts", |
| 107 | 108 | "test/asked.test.ts", |
| 108 | 109 | "test/asks.test.ts", |
src/core/schema.ts +21
| @@ -1540,4 +1540,25 @@ export const migrations: readonly string[] = [ | ||
| 1540 | 1540 | SELECT RAISE(ABORT, 'a sealed repository is never public'); |
| 1541 | 1541 | END; |
| 1542 | 1542 | `, |
| 1543 | // 71 — a guard's words are shown to whoever was refused, anonymous | |
| 1544 | // callers included (#723, `http/refusal.ts`): a message written for them | |
| 1545 | // starts `forge: `, and any other is answered with a generic refusal. The | |
| 1546 | // crew guards (62) are raised again with their words marked so, each | |
| 1547 | // dropped and made again at once: a rewrite, never a moment unguarded. | |
| 1548 | ` | |
| 1549 | DROP TRIGGER IF EXISTS repo_crew_agents_only; | |
| 1550 | CREATE TRIGGER repo_crew_agents_only BEFORE INSERT ON repo_crew | |
| 1551 | WHEN NOT EXISTS (SELECT 1 FROM user WHERE id = NEW.user_id AND is_agent = 1) | |
| 1552 | BEGIN | |
| 1553 | -- Shown to the caller, whoever they are: words for them, nothing internal. | |
| 1554 | SELECT RAISE(ABORT, 'forge: only an agent can be on a crew'); | |
| 1555 | END; | |
| 1556 | DROP TRIGGER IF EXISTS repo_crew_agents_only_update; | |
| 1557 | CREATE TRIGGER repo_crew_agents_only_update BEFORE UPDATE OF user_id ON repo_crew | |
| 1558 | WHEN NOT EXISTS (SELECT 1 FROM user WHERE id = NEW.user_id AND is_agent = 1) | |
| 1559 | BEGIN | |
| 1560 | -- Shown to the caller, whoever they are: words for them, nothing internal. | |
| 1561 | SELECT RAISE(ABORT, 'forge: only an agent can be on a crew'); | |
| 1562 | END; | |
| 1563 | `, | |
| 1543 | 1564 | ]; |
src/http/refusal.ts added +37
| @@ -0,0 +1,37 @@ | ||
| 1 | /** | |
| 2 | * A refusal a database guard raised (`RAISE(ABORT, '…')`): an operator's | |
| 3 | * trigger saying no (#723). It is the answer, not a fault, so the caller | |
| 4 | * gets a 403 — and the caller may be anyone, signed in or not, so only | |
| 5 | * words written for them are passed through. A guard says it wrote for the | |
| 6 | * caller by starting its message with `GUARD_PREFIX`; the prefix comes off | |
| 7 | * and the rest is shown. Any other message may name a table, a column or | |
| 8 | * an id, so the caller is told only that the forge refused, and the | |
| 9 | * operator's log keeps the original. | |
| 10 | */ | |
| 11 | ||
| 12 | /** What a guard's message starts with when its words are meant for the caller. */ | |
| 13 | export const GUARD_PREFIX = "forge: "; | |
| 14 | ||
| 15 | /** What a caller is told when a guard's words were not written for them. */ | |
| 16 | export const REFUSED_WORDS = "The forge refused this request."; | |
| 17 | ||
| 18 | export interface GuardRefusal { | |
| 19 | /** What the caller is shown. */ | |
| 20 | readonly shown: string; | |
| 21 | /** The guard's own words, for the operator's log only. */ | |
| 22 | readonly raw: string; | |
| 23 | } | |
| 24 | ||
| 25 | /** The refusal in `error`, when a database guard raised it. */ | |
| 26 | export function guardRefusal(error: unknown): GuardRefusal | undefined { | |
| 27 | if (!(error instanceof Error)) return undefined; | |
| 28 | const code = (error as { code?: unknown }).code; | |
| 29 | if (code !== "SQLITE_CONSTRAINT_TRIGGER") return undefined; | |
| 30 | const raw = error.message; | |
| 31 | return { | |
| 32 | raw, | |
| 33 | shown: raw.startsWith(GUARD_PREFIX) | |
| 34 | ? raw.slice(GUARD_PREFIX.length) | |
| 35 | : REFUSED_WORDS, | |
| 36 | }; | |
| 37 | } |
src/http/server.ts +8 −14
| @@ -5,6 +5,7 @@ | ||
| 5 | 5 | * verdict. Auth is resolved once per request and handed to handlers as data. |
| 6 | 6 | */ |
| 7 | 7 | |
| 8 | import { guardRefusal } from "./refusal.ts"; | |
| 8 | 9 | import { unsealReleased } from "../actions/sealed.ts"; |
| 9 | 10 | import { capacityPage, capacitySet } from "../web/pages/capacity.ts"; |
| 10 | 11 | import { |
| @@ -1500,17 +1501,6 @@ export interface Servers { | ||
| 1500 | 1501 | stop(): void; |
| 1501 | 1502 | } |
| 1502 | 1503 | |
| 1503 | /** | |
| 1504 | * A refusal a database trigger raised (`RAISE(ABORT, '…')`): an operator's | |
| 1505 | * guard saying no, in its own words. It is the answer, not a fault, so the | |
| 1506 | * person sees the reason and a 403 rather than "internal". | |
| 1507 | */ | |
| 1508 | function refusedByDatabase(error: unknown): string | undefined { | |
| 1509 | if (!(error instanceof Error)) return undefined; | |
| 1510 | const code = (error as { code?: unknown }).code; | |
| 1511 | return code === "SQLITE_CONSTRAINT_TRIGGER" ? error.message : undefined; | |
| 1512 | } | |
| 1513 | ||
| 1514 | 1504 | /** A response with one header set, copying it when its headers are frozen. */ |
| 1515 | 1505 | function withHeader(response: Response, name: string, value: string): Response { |
| 1516 | 1506 | try { |
| @@ -1652,10 +1642,14 @@ export async function serve(app: App): Promise<Servers> { | ||
| 1652 | 1642 | return withHeader(response, "connection", "close"); |
| 1653 | 1643 | }, |
| 1654 | 1644 | error(error) { |
| 1655 | const refused = refusedByDatabase(error); | |
| 1645 | // A guard's refusal, in words written for the caller or none | |
| 1646 | // (`refusal.ts`); the operator's log keeps the guard's own. | |
| 1647 | const refused = guardRefusal(error); | |
| 1656 | 1648 | if (refused !== undefined) { |
| 1657 | app.log.warn("refused by the database", { reason: refused }); | |
| 1658 | return securityFloor(json({ error: "refused", message: refused }, 403)); | |
| 1649 | app.log.warn("refused by the database", { reason: refused.raw }); | |
| 1650 | return securityFloor( | |
| 1651 | json({ error: "refused", message: refused.shown }, 403), | |
| 1652 | ); | |
| 1659 | 1653 | } |
| 1660 | 1654 | app.log.error("unhandled request error", { error: String(error) }); |
| 1661 | 1655 | return securityFloor(json({ error: "internal" }, 500)); |
src/kernel/migrate.ts +43 −2
| @@ -261,6 +261,34 @@ function quote(statement: string): string { | ||
| 261 | 261 | return `"${line.length > QUOTE_MAX ? `${line.slice(0, QUOTE_MAX)}…` : line}"`; |
| 262 | 262 | } |
| 263 | 263 | |
| 264 | /** | |
| 265 | * A name as one word: its letters' code points, lowercased as SQLite | |
| 266 | * compares names. It starts with a digit, which no unquoted name can, so | |
| 267 | * an encoded name is never mistaken for a written one. | |
| 268 | */ | |
| 269 | function quotedName(name: string): string { | |
| 270 | return `0q${[...name.toLowerCase()].map((c) => `_${c.codePointAt(0)!.toString(16)}`).join("")}`; | |
| 271 | } | |
| 272 | ||
| 273 | /** A name as SQLite compares it: written bare or in quotes, the same name is one. */ | |
| 274 | function sameName(name: string): string { | |
| 275 | return /^\d/.test(name) ? name : quotedName(name); | |
| 276 | } | |
| 277 | ||
| 278 | /** How many `DROP TRIGGER x;` are followed at once by `CREATE TRIGGER x`. */ | |
| 279 | function rewrites(code: string): number { | |
| 280 | const name = /((?:[\w$]+\.)?[\w$]+)/.source; | |
| 281 | const pair = new RegExp( | |
| 282 | `\\bDROP\\s+TRIGGER\\s+(?:IF\\s+EXISTS\\s+)?${name}\\s*;\\s*` + | |
| 283 | `CREATE\\s+(?:TEMP(?:ORARY)?\\s+)?TRIGGER\\s+(?:IF\\s+NOT\\s+EXISTS\\s+)?${name}\\b`, | |
| 284 | "gi", | |
| 285 | ); | |
| 286 | let count = 0; | |
| 287 | for (const m of code.matchAll(pair)) | |
| 288 | if (sameName(m[1]!) === sameName(m[2]!)) count++; | |
| 289 | return count; | |
| 290 | } | |
| 291 | ||
| 264 | 292 | function messageOf(error: unknown): string { |
| 265 | 293 | return (error instanceof Error ? error.message : String(error)) |
| 266 | 294 | .replace(/\s+/g, " ") |
| @@ -277,15 +305,27 @@ function messageOf(error: unknown): string { | ||
| 277 | 305 | * stopped reading it. This names each statement that breaks that, by what |
| 278 | 306 | * it does, so a test can refuse it before it ships. Values in quotes are |
| 279 | 307 | * data and are not read. |
| 308 | * | |
| 309 | * One drop is a rewrite, not a removal: `DROP TRIGGER` of a name whose very | |
| 310 | * next statement is `CREATE TRIGGER` of that same name. The migration is one | |
| 311 | * transaction, so the old process sees the old trigger or the new one, | |
| 312 | * never neither. A trigger dropped alone, or followed by anything else, | |
| 313 | * still drops a trigger. | |
| 280 | 314 | */ |
| 281 | 315 | export function notAdditive(sql: string): string[] { |
| 282 | 316 | // One pass, left to right, as SQLite reads it: a string is data, a quoted |
| 283 | 317 | // name is one word, and either kind of comment is whitespace — whichever |
| 284 | 318 | // starts first wins, so a quote inside a comment opens nothing. |
| 319 | // A quoted name keeps who it is, as letters that read as no keyword, so | |
| 320 | // a dropped trigger can be matched to the one made in its place. | |
| 285 | 321 | const code = sql.replace( |
| 286 | 322 | /'(?:[^']|'')*'|"(?:[^"]|"")*"|\/\*[\s\S]*?(?:\*\/|$)|--[^\n]*/g, |
| 287 | 323 | (token) => |
| 288 | token.startsWith("'") ? "''" : token.startsWith('"') ? "name" : " ", | |
| 324 | token.startsWith("'") | |
| 325 | ? "''" | |
| 326 | : token.startsWith('"') | |
| 327 | ? quotedName(token.slice(1, -1).replaceAll('""', '"')) | |
| 328 | : " ", | |
| 289 | 329 | ); |
| 290 | 330 | const found: string[] = []; |
| 291 | 331 | const say = (what: string, pattern: RegExp): void => { |
| @@ -293,7 +333,8 @@ export function notAdditive(sql: string): string[] { | ||
| 293 | 333 | }; |
| 294 | 334 | say("drops a table", /\bDROP\s+TABLE\b/i); |
| 295 | 335 | say("drops a view", /\bDROP\s+VIEW\b/i); |
| 296 | say("drops a trigger", /\bDROP\s+TRIGGER\b/i); | |
| 336 | const drops = code.match(/\bDROP\s+TRIGGER\b/gi)?.length ?? 0; | |
| 337 | if (drops > rewrites(code)) found.push("drops a trigger"); | |
| 297 | 338 | // `COLUMN` is optional after ALTER TABLE … DROP / RENAME / ADD. |
| 298 | 339 | const alter = /\bALTER\s+TABLE\s+\S+\s+/i.source; |
| 299 | 340 | say("drops a column", new RegExp(`${alter}DROP\\b`, "i")); |
test/accounts.test.ts +1 −1
| @@ -504,7 +504,7 @@ describe("accounts: the owner sees, suspends and removes", () => { | ||
| 504 | 504 | test("a refusal the database raises answers 403 with its reason, not 500", async () => { |
| 505 | 505 | // An operator's guard, the way production holds new accounts back. |
| 506 | 506 | app.db.exec( |
| 507 | "CREATE TRIGGER test_refuse BEFORE INSERT ON repo BEGIN SELECT RAISE(ABORT, 'new repositories are paused here'); END;", | |
| 507 | "CREATE TRIGGER test_refuse BEFORE INSERT ON repo BEGIN SELECT RAISE(ABORT, 'forge: new repositories are paused here'); END;", | |
| 508 | 508 | ); |
| 509 | 509 | try { |
| 510 | 510 | const res = await api("/api/v1/repos", { |
test/guard-words.test.ts added +123
| @@ -0,0 +1,123 @@ | ||
| 1 | /** | |
| 2 | * A database guard's refusal is shown to whoever asked, anonymous callers | |
| 3 | * included (#723), so only words written for them pass: a message that | |
| 4 | * starts `forge: ` is shown, without the prefix; any other is answered with | |
| 5 | * the generic refusal, and the operator's log keeps the original. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { createApp, type App } from "../src/app.ts"; | |
| 12 | import { createRepo } from "../src/actions/repos.ts"; | |
| 13 | import { createToken } from "../src/core/tokens.ts"; | |
| 14 | import { createUser, type User } from "../src/core/users.ts"; | |
| 15 | import { GUARD_PREFIX, REFUSED_WORDS } from "../src/http/refusal.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { quietLogs } from "./helpers/globals.ts"; | |
| 18 | import type { LogFields } from "../src/kernel/log.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | let dataDir: string; | |
| 23 | let app: App; | |
| 24 | let servers: Servers; | |
| 25 | let owner: User; | |
| 26 | let token = ""; | |
| 27 | const warned: { message: string; fields: unknown }[] = []; | |
| 28 | ||
| 29 | /** | |
| 30 | * Ask the forge for something a guard on `table` refuses with `words`: as | |
| 31 | * the owner, a new repository; as nobody, a report on a public one. | |
| 32 | */ | |
| 33 | async function guarded(words: string, who: "owner" | "nobody") { | |
| 34 | const table = who === "owner" ? "repo" : "report"; | |
| 35 | app.db.exec( | |
| 36 | `CREATE TRIGGER test_guard BEFORE INSERT ON ${table} BEGIN SELECT RAISE(ABORT, '${words}'); END;`, | |
| 37 | ); | |
| 38 | try { | |
| 39 | const res = | |
| 40 | who === "owner" | |
| 41 | ? await fetch(`${servers.url}/api/v1/repos`, { | |
| 42 | method: "POST", | |
| 43 | headers: { | |
| 44 | "content-type": "application/json", | |
| 45 | authorization: `Bearer ${token}`, | |
| 46 | }, | |
| 47 | body: JSON.stringify({ name: `g${Date.now()}` }), | |
| 48 | }) | |
| 49 | : await fetch(`${servers.url}/api/v1/repos/olive/open/reports`, { | |
| 50 | method: "POST", | |
| 51 | headers: { "content-type": "application/json" }, | |
| 52 | body: JSON.stringify({ title: "It breaks", body: "Here is how." }), | |
| 53 | }); | |
| 54 | return { status: res.status, body: (await res.json()) as unknown }; | |
| 55 | } finally { | |
| 56 | app.db.exec("DROP TRIGGER test_guard"); | |
| 57 | } | |
| 58 | } | |
| 59 | ||
| 60 | beforeAll(async () => { | |
| 61 | dataDir = await mkdtemp(join(tmpdir(), "forge-guard-words-")); | |
| 62 | app = createApp({ dataDir, port: 0 }); | |
| 63 | servers = await serve(app); | |
| 64 | const made = await createUser(app.db, { | |
| 65 | trusted: true, | |
| 66 | username: "olive", | |
| 67 | email: "[email protected]", | |
| 68 | password: "a-good-passphrase", | |
| 69 | adminIfFirst: true, | |
| 70 | }); | |
| 71 | if (!made.ok) throw new Error(made.error); | |
| 72 | owner = made.value; | |
| 73 | token = createToken(app.db, owner.id, "t", "admin").token; | |
| 74 | const open = await createRepo(app, owner, { name: "open", visibility: "public" }); | |
| 75 | if (!open.ok) throw new Error(String(open.error)); | |
| 76 | const warn = app.log.warn.bind(app.log); | |
| 77 | app.log.warn = (message: string, fields?: LogFields) => { | |
| 78 | warned.push({ message, fields }); | |
| 79 | warn(message, fields); | |
| 80 | }; | |
| 81 | }); | |
| 82 | ||
| 83 | afterAll(async () => { | |
| 84 | servers?.stop(); | |
| 85 | app?.close(); | |
| 86 | await rm(dataDir, { recursive: true, force: true }); | |
| 87 | }); | |
| 88 | ||
| 89 | describe("a guard's words reach the caller only when written for them", () => { | |
| 90 | test("a message that says it is for the caller is shown, without its mark", async () => { | |
| 91 | for (const who of ["owner", "nobody"] as const) | |
| 92 | expect(await guarded(`${GUARD_PREFIX}paused here for now`, who)).toEqual({ | |
| 93 | status: 403, | |
| 94 | body: { error: "refused", message: "paused here for now" }, | |
| 95 | }); | |
| 96 | }); | |
| 97 | ||
| 98 | test("any other message is the generic refusal, and the log keeps the original", async () => { | |
| 99 | warned.length = 0; | |
| 100 | const raw = | |
| 101 | "steward_guard_repo: owner_id=01m2 not in steward_trusted_owner"; | |
| 102 | for (const who of ["owner", "nobody"] as const) { | |
| 103 | const { status, body } = await guarded(raw, who); | |
| 104 | expect(status).toBe(403); | |
| 105 | expect(body).toEqual({ error: "refused", message: REFUSED_WORDS }); | |
| 106 | expect(JSON.stringify(body)).not.toContain("steward_"); | |
| 107 | } | |
| 108 | expect(JSON.stringify(warned)).toContain(raw); | |
| 109 | }); | |
| 110 | ||
| 111 | test("the forge's own guards speak to the caller: only an agent can be on a crew", async () => { | |
| 112 | const repo = await createRepo(app, owner, { | |
| 113 | name: "square", | |
| 114 | visibility: "public", | |
| 115 | }); | |
| 116 | if (!repo.ok) throw new Error(String(repo.error)); | |
| 117 | expect(() => | |
| 118 | app.db | |
| 119 | .query("INSERT INTO repo_crew (repo_id, user_id) VALUES (?1, ?2)") | |
| 120 | .run(repo.value.id, owner.id), | |
| 121 | ).toThrow(`${GUARD_PREFIX}only an agent can be on a crew`); | |
| 122 | }); | |
| 123 | }); |
test/schema-additive.test.ts +29
| @@ -59,6 +59,35 @@ describe("migrations are additive across a roll", () => { | ||
| 59 | 59 | expect(notAdditive(sql)).toEqual([]); |
| 60 | 60 | }); |
| 61 | 61 | |
| 62 | test("a trigger dropped and made again at once, under the same name, is a rewrite", () => { | |
| 63 | const body = "BEGIN SELECT RAISE(ABORT, 'forge: no'); END;"; | |
| 64 | for (const sql of [ | |
| 65 | `DROP TRIGGER IF EXISTS guard; CREATE TRIGGER guard BEFORE INSERT ON t ${body}`, | |
| 66 | `DROP TRIGGER guard;\n -- its words, marked\n CREATE TRIGGER IF NOT EXISTS guard BEFORE INSERT ON t ${body}`, | |
| 67 | `DROP TRIGGER "Guard"; CREATE TRIGGER guard BEFORE INSERT ON t ${body}`, | |
| 68 | `DROP TRIGGER a; CREATE TRIGGER a BEFORE INSERT ON t ${body} DROP TRIGGER b; CREATE TRIGGER b BEFORE UPDATE ON t ${body}`, | |
| 69 | ]) | |
| 70 | expect(notAdditive(sql)).toEqual([]); | |
| 71 | }); | |
| 72 | ||
| 73 | test("a trigger dropped alone, or made again under another name or later, still drops a trigger", () => { | |
| 74 | const body = "BEGIN SELECT RAISE(ABORT, 'no'); END;"; | |
| 75 | for (const sql of [ | |
| 76 | "DROP TRIGGER guard;", | |
| 77 | `DROP TRIGGER guard; CREATE TRIGGER guard_two BEFORE INSERT ON t ${body}`, | |
| 78 | `DROP TRIGGER guard; INSERT INTO t VALUES (1); CREATE TRIGGER guard BEFORE INSERT ON t ${body}`, | |
| 79 | // Two dropped, one made again: the other is gone. | |
| 80 | `DROP TRIGGER a; DROP TRIGGER b; CREATE TRIGGER b BEFORE INSERT ON t ${body}`, | |
| 81 | `DROP TRIGGER a; CREATE TRIGGER a BEFORE INSERT ON t ${body} DROP TRIGGER b;`, | |
| 82 | // A name in quotes is that name, not another that encodes the same way. | |
| 83 | `DROP TRIGGER "0q_61"; CREATE TRIGGER a BEFORE INSERT ON t ${body}`, | |
| 84 | `DROP TRIGGER main.guard; CREATE TRIGGER guard BEFORE INSERT ON t ${body}`, | |
| 85 | // A quoted string that reads like the rewrite is data, not a statement. | |
| 86 | `DROP TRIGGER guard; SELECT 'CREATE TRIGGER guard';`, | |
| 87 | ]) | |
| 88 | expect(notAdditive(sql)).toEqual(["drops a trigger"]); | |
| 89 | }); | |
| 90 | ||
| 62 | 91 | test("every migration newer than the releases still in play is additive", () => { |
| 63 | 92 | const counts = releases.releases.slice(0, 2).map((r) => r.migrations); |
| 64 | 93 | expect(counts.length).toBeGreaterThan(0); |
new above
offline