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

A new inline isAdmin check in a moved door fails the gate #18410

opened this

Merged 2h 14m ago, live in production

torque/forge:torque/18406-a-new-inline-isadmin-check-in-a-moved-do → main 0 commits fork

  • Merged. torque/18406-a-new-inline-isadmin-check-in-a-moved-do was merged into main as e472288.

Review

Sign in to review this change.
6 files changed +236 −4
docs/ROLES.md +14
@@ -110,6 +110,20 @@ The limits count accounts and addresses. Someone with many addresses is held
110110 only by the whole-forge ceilings. A push is capped by its compressed size, so a
111111 small pack that expands when git reads it still costs CPU and memory.
112112
113 ## Inline checks in a moved door
114
115 The repository routes under `src/http/api/` and the MCP tools (`src/http/mcp.ts`,
116 `src/http/mcp/`) have moved to `may` (Access 3, #18406), so a new line in them
117 that gates on `isAdmin`, on `scopeAllows(…, "rw")` or on `!ctx.auth.user` fails
118 `test/door-inline-checks.test.ts`, which names the file and line and the helper to
119 ask instead: `adminPage` or `mayBeside(ctx, door, "forge.administer", old)` for an
120 admin, `mayBeside(ctx, door, "forge.write", old)` (`mayToolWrite` in the MCP) for
121 a write, `signedInPage` for an account. Only gate shapes count: a role passed on
122 for display is a read, and `scopeAllows(…, "admin")` is a token's reach, not a
123 role. The lines that stay are listed in `DOOR_LINES` (`src/design/door_checks.ts`),
124 each with a reason; the list only shrinks, because an entry whose line is gone
125 fails too.
126
113127 ## Admin settings
114128
115129 Part 3a (#2384) enforces "Administer the forge" for admin settings and
scripts/design-lint.ts +9 −3
@@ -47,7 +47,8 @@
4747 *
4848 * The empty-words and width-read ratchets (#17521) are counted in `src/design/ratchets.ts`, the
4949 * module test/empty-words-all.test.ts and test/behaviors-rule.test.ts hold them with; see
50 * `ratchetFindings()`.
50 * `ratchetFindings()`. A new inline access check in a moved door (#18406) is printed beside them,
51 * from `src/design/door_checks.ts`; see `scanRatchets()`.
5152 *
5253 * `banner` (#10699) refuses a standing alert in the home and board builders; see `banner()`.
5354 *
@@ -82,6 +83,7 @@ import { motionFindings } from "../src/design/motion.ts";
8283 import { PHONE_PX, widthFindings } from "../src/design/width.ts";
8384 import { cssBlocksAt, scanOverlay, sourceFiles } from "../src/design/overlay.ts";
8485 import { bareNoFindings, type Source, tsSources, WIDTH_SKIP, widthReadsOver } from "../src/design/ratchets.ts";
86 import { doorChecks, doorFindings, doorSources } from "../src/design/door_checks.ts";
8587
8688 // The covered-page rule lives in src/design/ so the release preflight runs it too (#11916).
8789 export { motionFindings, type MotionFinding } from "../src/design/motion.ts";
@@ -681,9 +683,13 @@ export function scanRing(root: string): string[] {
681683 export function ratchetFindings(web: readonly Source[], src: readonly Source[]): string[] {
682684 return [...bareNoFindings(web), ...widthReadsOver(src)];
683685 }
684 /** Each over the files its test reads: every file under src/web, and src/ but for WIDTH_SKIP. */
686 /**
687 * Each over the files its test reads: every file under src/web, and src/ but for WIDTH_SKIP; and
688 * the moved doors' inline checks (#18406), as test/door-inline-checks.test.ts reads them.
689 */
685690 export function scanRatchets(root: string): string[] {
686 return ratchetFindings(tsSources(root, "src/web"), tsSources(root, "src", WIDTH_SKIP));
691 const doors = doorFindings(doorSources(root).flatMap(doorChecks));
692 return [...ratchetFindings(tsSources(root, "src/web"), tsSources(root, "src", WIDTH_SKIP)), ...doors];
687693 }
688694
689695 const BASELINE = "docs/design/baseline.json";
src/design/door_checks.ts added +132
@@ -0,0 +1,132 @@
1 /**
2 * The inline access check does not come back into a moved door (#18406, Access 3's last step). The
3 * repository routes under `src/http/api/` and the MCP tools (`src/http/mcp.ts`, `src/http/mcp/`)
4 * now ask `may`; this ratchet reads their source and finds each line that gates on the account
5 * inline: a refusal on `isAdmin` (`!user.isAdmin`, `isAdmin !== true`, or `isAdmin` in an `if`), a
6 * `scopeAllows(…, "rw")` write floor, or a signed-out test (`!ctx.auth.user`, `ctx.auth.user ===
7 * undefined` in a condition).
8 *
9 * Only gate shapes count: a role passed on for display (`familyView(app, user.isAdmin === true)`)
10 * is a read, not a door, and is not matched. `scopeAllows(…, "admin")` is how far a token reaches,
11 * a scope and not a role, and stays (as in `src/kernel/mcp_door_checks.ts`).
12 *
13 * A line found is allowed only when `DOOR_LINES` names its file and its exact trimmed text, with a
14 * reason in one phrase; an entry whose line is gone is refused too, so the list only shrinks.
15 * test/door-inline-checks.test.ts holds it.
16 */
17 import { tsSources, type Source } from "./ratchets.ts";
18
19 export type DoorCheck = "isAdmin" | "scopeAllows" | "signedOut";
20
21 /** One line found: its file, line number, which check, and the line's trimmed text. */
22 export interface DoorFound {
23 readonly file: string;
24 readonly line: number;
25 readonly check: DoorCheck;
26 readonly text: string;
27 }
28
29 /** What to ask instead, by the check found. */
30 const HELPER: Record<DoorCheck, string> = {
31 isAdmin: `adminPage(ctx, door, old) or mayBeside(ctx, door, "forge.administer", old)`,
32 scopeAllows: `mayBeside(ctx, door, "forge.write", old) (mayToolWrite in the MCP)`,
33 signedOut: "signedInPage(ctx, door)",
34 };
35
36 /** The fix that ends each finding: which helper, or which list line to delete. */
37 export const DOOR_FIX = {
38 newLine: (c: DoorCheck): string =>
39 `Fix: ask ${HELPER[c]} (src/http/page_may.ts, src/http/may_beside.ts); never add the line to DOOR_LINES in src/design/door_checks.ts.`,
40 gone: "Fix: the check is gone, so delete its entry from DOOR_LINES in src/design/door_checks.ts; lowering is the right move.",
41 } as const;
42
43 // Each shape is a gate: the line refuses or branches on it. A bare read (an argument, a ternary
44 // that picks what to show) matches none of them.
45 const SHAPES: readonly (readonly [DoorCheck, RegExp])[] = [
46 ["isAdmin", /!\s*[\w?.]*\bisAdmin\b|\bisAdmin\s*!==?\s*true\b|\bisAdmin\s*===?\s*false\b|\bif\s*\(.*\bisAdmin\b/],
47 ["scopeAllows", /\bscopeAllows\([^)]*"rw"\s*\)/],
48 ["signedOut", /!\s*ctx\.auth\.user\b(?!\s*\??\.)|(?:\bif\s*\(|\|\||&&)\s*ctx\.auth\.user\s*===?\s*(?:undefined|null)\b/],
49 ];
50
51 /** Every gate-shaped inline check in one file, a line at a time; comment lines are skipped. */
52 export function doorChecks(src: Source): DoorFound[] {
53 return src.text.split("\n").flatMap((raw, i) => {
54 const text = raw.trim();
55 if (text.startsWith("*") || text.startsWith("//") || text.startsWith("/*")) return [];
56 return SHAPES.filter(([, re]) => re.test(text)).map(([check]) => ({ file: src.path, line: i + 1, check, text }));
57 });
58 }
59
60 /** The files the moved doors live in: repository route modules under src/http/api, and the MCP. */
61 export function doorSources(root: string): Source[] {
62 const api = tsSources(root, "src/http/api").filter((f) => f.text.includes("/api/v1/repos/"));
63 const mcp = tsSources(root, "src/http").filter((f) => f.path === "src/http/mcp.ts");
64 return [...api, ...mcp, ...tsSources(root, "src/http/mcp")];
65 }
66
67 /** A line that keeps its inline check, by file and exact trimmed text, and why. Only shrinks. */
68 export interface DoorLine {
69 readonly file: string;
70 readonly text: string;
71 readonly why: string;
72 }
73
74 const NOT_ONLY_HERE = "an admin-only tool hidden as not found; moves when the tool's own rule asks may";
75 const ADMIN_READ = "an admin-only read refused by name; moves when the tool's own rule asks may";
76
77 export const DOOR_LINES: readonly DoorLine[] = [
78 { file: "src/http/api/issues.ts", text: "if (ctx.auth.user === undefined) {", why: "which door a stranger is shown, not whether they pass" },
79 { file: "src/http/api/statement.ts", text: "if (ctx.auth.user === undefined) return notFound();", why: "a stranger is never told a statement exists" },
80 { file: "src/http/api/cdn.ts", text: "if (!ctx.auth.user) {", why: "a rate by address, not a permission" },
81 { file: "src/http/mcp.ts", text: "if (!signedIn || ctx.auth.user === undefined || tool === undefined) return handler(ctx, m[\"id\"], args);", why: "skips the shadow count, refuses nobody" },
82 { file: "src/http/mcp/tool_may.ts", text: "return mayBeside(ctx, `mcp ${door}`, \"forge.write\", scopeAllows(ctx.auth.scope ?? \"ro\", \"rw\"));", why: "the old answer handed to mayBeside" },
83 { file: "src/http/mcp/tools/bet.ts", text: "if (!scopeAllows(ctx.auth.scope ?? \"ro\", \"rw\")) return bad(\"forbidden\", \"this needs a write token\");", why: "a tool's own write floor, before the door asked may" },
84 { file: "src/http/mcp/tools/notify.ts", text: "if (!scopeAllows(ctx.auth.scope ?? \"ro\", \"rw\")) return bad(\"forbidden\", \"setting a focus needs a token that can write\");", why: "a write action on a read tool" },
85 { file: "src/http/mcp/tools/features.ts", text: "if (spec?.writes === true && !scopeAllows(ctx.auth.scope ?? \"ro\", \"rw\")) return bad(\"forbidden\", \"a tool that writes needs an rw token\");", why: "a tool called through another, its writes floor" },
86 { file: "src/http/mcp/tools/infra.ts", text: 'if (!user.isAdmin) return bad("not_found", "no such tool here");', why: NOT_ONLY_HERE },
87 { file: "src/http/mcp/tools/maintenance.ts", text: 'if (!user.isAdmin) return bad("not_found", "no such tool here");', why: NOT_ONLY_HERE },
88 { file: "src/http/mcp/tools/cloud_accounts.ts", text: 'if (!user.isAdmin) return bad("not_found", "no such tool here");', why: NOT_ONLY_HERE },
89 { file: "src/http/mcp/tools/pinned_forge.ts", text: 'if (!user.isAdmin) return bad("not_found", "no such tool here");', why: NOT_ONLY_HERE },
90 { file: "src/http/mcp/tools/cloud_account.ts", text: 'if (!user.isAdmin) return bad("not_found", "no such tool here");', why: NOT_ONLY_HERE },
91 { file: "src/http/mcp/tools/snapshot_now.ts", text: 'if (!user.isAdmin) return bad("not_found", "no such tool here");', why: NOT_ONLY_HERE },
92 { file: "src/http/mcp/tools/cloud_end.ts", text: 'if (!user.isAdmin) return bad("not_found", "no such tool here");', why: NOT_ONLY_HERE },
93 { file: "src/http/mcp/tools/backups.ts", text: 'if (!user.isAdmin) return bad("not_found", "not found");', why: NOT_ONLY_HERE },
94 { file: "src/http/mcp/tools/knobs.ts", text: 'if (user?.isAdmin !== true || user.kind === "agent") return bad("not_found", "no such tool here");', why: NOT_ONLY_HERE },
95 { file: "src/http/mcp/tools/valves.ts", text: 'if (user?.isAdmin !== true || user.kind === "agent") return bad("not_found", "no such tool here");', why: NOT_ONLY_HERE },
96 { file: "src/http/mcp/tools/forges.ts", text: "if (!user.isAdmin)", why: ADMIN_READ },
97 { file: "src/http/mcp/tools/claim_link.ts", text: 'if (!user.isAdmin) return bad("forbidden", "only a site admin can end or bring back a claim link");', why: ADMIN_READ },
98 { file: "src/http/mcp/tools/flow.ts", text: 'if (!user.isAdmin || user.kind === "agent") return bad("forbidden", "Lane times are read across every repository: a forge admin\'s.");', why: ADMIN_READ },
99 { file: "src/http/mcp/tools/crew.ts", text: "if (user.isAdmin !== true) return bad(\"forbidden\", ADMIN_WORDS.scorecard);", why: ADMIN_READ },
100 { file: "src/http/mcp/tools/scorecard.ts", text: 'if (user.kind !== "user" || !user.isAdmin) return bad("forbidden", CHANGE_WORDS.person);', why: "a person, not an agent, changes a scorecard" },
101 { file: "src/http/mcp/tools/system.ts", text: 'if (!user.isAdmin) return bad("forbidden", "only an admin of this forge reads where its bottleneck is");', why: ADMIN_READ },
102 { file: "src/http/mcp/tools/system.ts", text: 'if (!user.isAdmin) return bad("forbidden", "only an admin of this forge reads its child forges across a restart");', why: ADMIN_READ },
103 { file: "src/http/mcp/tools/system.ts", text: 'if (!user.isAdmin) return bad("forbidden", "only an admin of this forge reads how far its hosted forges\' stream is behind");', why: ADMIN_READ },
104 { file: "src/http/mcp/tools/system.ts", text: 'if (!user.isAdmin) return bad("forbidden", "only an admin of this forge reads what it stands on");', why: ADMIN_READ },
105 { file: "src/http/mcp/tools/system.ts", text: 'if (!user.isAdmin) return bad("forbidden", "only an admin of this forge reads its off-site backup lane");', why: ADMIN_READ },
106 { file: "src/http/mcp/tools/system.ts", text: 'if (!user.isAdmin) return bad("forbidden", "only an admin of this forge reads its CSP violations");', why: ADMIN_READ },
107 ];
108
109 const key = (file: string, text: string): string => `${file}\n${text}`;
110
111 /**
112 * Each finding with its fix: a gate-shaped line DOOR_LINES does not name, and an entry whose line
113 * is gone. An entry allows one line, so a copy of a listed line elsewhere in its file is still new.
114 */
115 export function doorFindings(found: readonly DoorFound[], allowed: readonly DoorLine[] = DOOR_LINES): string[] {
116 const left = new Map<string, number>();
117 for (const a of allowed) left.set(key(a.file, a.text), (left.get(key(a.file, a.text)) ?? 0) + 1);
118 const out: string[] = [];
119 for (const f of found) {
120 const n = left.get(key(f.file, f.text)) ?? 0;
121 if (n > 0) left.set(key(f.file, f.text), n - 1);
122 else out.push(`${f.file}:${f.line}: a new inline ${f.check} check in a moved door: ${f.text} ${DOOR_FIX.newLine(f.check)}`);
123 }
124 for (const a of allowed) {
125 const k = key(a.file, a.text);
126 const n = left.get(k) ?? 0;
127 if (n === 0) continue;
128 left.set(k, n - 1);
129 out.push(`${a.file}: DOOR_LINES names a line that is gone: ${a.text} ${DOOR_FIX.gone}`);
130 }
131 return out;
132 }
test/door-inline-checks.test.ts added +72
@@ -0,0 +1,72 @@
1 /**
2 * Access 3's last step per door (#18406): the repository routes under `src/http/api/` and the MCP
3 * tools ask `may`, and a new inline `isAdmin`, `scopeAllows(…, "rw")` or `!ctx.auth.user` gate in
4 * their source fails here, named by file and line with the helper to use instead. The list of
5 * lines that stay (`DOOR_LINES`, src/design/door_checks.ts) only shrinks: an entry whose line is
6 * gone fails too.
7 */
8 import { expect, test } from "bun:test";
9 import { join } from "node:path";
10 import { DOOR_FIX, DOOR_LINES, doorChecks, doorFindings, doorSources } from "../src/design/door_checks.ts";
11
12 const ROOT = join(import.meta.dir, "..");
13
14 test("no moved door gains an inline isAdmin, scopeAllows or signed-out check (DOOR_LINES only shrinks)", () => {
15 const found = doorSources(ROOT).flatMap(doorChecks);
16 expect(doorFindings(found)).toEqual([]);
17 });
18
19 test("the scan reads the repository route modules and every MCP file", () => {
20 const paths = doorSources(ROOT).map((s) => s.path);
21 expect(paths).toContain("src/http/api/issues.ts");
22 expect(paths).toContain("src/http/mcp.ts");
23 expect(paths).toContain("src/http/mcp/shared.ts");
24 expect(paths).toContain("src/http/mcp/tools/system.ts");
25 // A forge-wide module with no repository route is the other door's.
26 expect(paths.every((p) => !p.startsWith("src/http/api/") || !p.endsWith("/admin.ts"))).toBe(true);
27 });
28
29 test("every entry says why in one phrase", () => {
30 for (const a of DOOR_LINES) {
31 expect(a.why.length).toBeGreaterThan(0);
32 expect(a.why).not.toContain(".");
33 }
34 });
35
36 const FIXTURE = [
37 "export async function handle(ctx, user) {",
38 " // if (!user.isAdmin) a comment is not a gate",
39 " const view = familyView(ctx.app, user.isAdmin === true);",
40 " if (!user.isAdmin) return bad(\"forbidden\", \"admins only\");",
41 " if (!scopeAllows(ctx.auth.scope ?? \"ro\", \"rw\")) return bad(\"forbidden\", \"write\");",
42 " if (!scopeAllows(ctx.auth.scope ?? \"ro\", \"admin\")) return bad(\"forbidden\", \"admin token\");",
43 " if (!ctx.auth.user) return bad(\"unauthorized\", \"sign in\");",
44 " return view;",
45 "}",
46 ].join("\n");
47
48 test("a fixture file with new inline checks fails, each named by file, line and helper", () => {
49 const found = doorChecks({ path: "src/http/mcp/tools/fixture.ts", text: FIXTURE });
50 expect(found.map((f) => [f.line, f.check])).toEqual([
51 [4, "isAdmin"],
52 [5, "scopeAllows"],
53 [7, "signedOut"],
54 ]);
55 const said = doorFindings(found, []);
56 expect(said).toHaveLength(3);
57 expect(said[0]).toStartWith("src/http/mcp/tools/fixture.ts:4: a new inline isAdmin check");
58 expect(said[0]).toContain("adminPage");
59 expect(said[1]).toContain("mayBeside");
60 expect(said[2]).toContain("signedInPage");
61 for (const s of said) expect(s).toEndWith(DOOR_FIX.newLine(found[said.indexOf(s)]!.check));
62 });
63
64 test("a listed line allows itself once; a copy of it is new, and a gone line is named to delete", () => {
65 const text = "if (!user.isAdmin) return no();";
66 const listed = [{ file: "f.ts", text, why: "a reason" }];
67 const one = doorChecks({ path: "f.ts", text });
68 expect(doorFindings(one, listed)).toEqual([]);
69 const twice = doorChecks({ path: "f.ts", text: `${text}\n${text}` });
70 expect(doorFindings(twice, listed)).toEqual([`f.ts:2: a new inline isAdmin check in a moved door: ${text} ${DOOR_FIX.newLine("isAdmin")}`]);
71 expect(doorFindings([], listed)).toEqual([`f.ts: DOOR_LINES names a line that is gone: ${text} ${DOOR_FIX.gone}`]);
72 });
test/pull-pipe.test.ts +4
@@ -4,6 +4,9 @@ import { pullPipe } from "../src/git/pull-pipe.ts";
44 const MB = 1024 * 1024;
55
66 test("a child writing 200 MB stays blocked while nobody reads, and memory stays bounded", async () => {
7 // Collect first and before each reading: garbage left by earlier files in the shard is not the
8 // pipe's.
9 Bun.gc(true);
710 const before = process.memoryUsage.rss();
811 const pipe = await pullPipe();
912 const proc = Bun.spawn(["head", "-c", String(200 * MB), "/dev/zero"], {
@@ -20,6 +23,7 @@ test("a child writing 200 MB stays blocked while nobody reads, and memory stays
2023 for await (const chunk of pipe.stream) total += chunk.length;
2124 expect(total).toBe(200 * MB);
2225 expect(await proc.exited).toBe(0);
26 Bun.gc(true);
2327 expect(process.memoryUsage.rss() - before).toBeLessThan(64 * MB);
2428 }, 30_000);
2529
test/trace-imported-open.test.ts +5 −1
@@ -46,15 +46,19 @@ test("a ~30 MiB session opens in under 500 ms and the parse holds the file once,
4646 const base = before.heapUsed + before.arrayBuffers;
4747 let peak = 0;
4848 let count = 0;
49 // The sampling below forces full collections; their time is the test's, not the parse's.
50 let sampling = 0;
4951 const source = importedLines(dir, id);
5052 Bun.gc(true);
5153 const watched: Iterable<string> = {
5254 *[Symbol.iterator]() {
5355 for (const l of source) {
5456 if (++count % 500 === 0) {
57 const s = performance.now();
5558 Bun.gc(true);
5659 const m = process.memoryUsage();
5760 peak = Math.max(peak, m.heapUsed + m.arrayBuffers - base);
61 sampling += performance.now() - s;
5862 }
5963 yield l;
6064 }
@@ -62,7 +66,7 @@ test("a ~30 MiB session opens in under 500 ms and the parse holds the file once,
6266 };
6367 const t = performance.now();
6468 const trace = parseSession(watched);
65 expect(performance.now() - t).toBeLessThan(500);
69 expect(performance.now() - t - sampling).toBeLessThan(500);
6670 expect(trace.id).toBe("sess-open");
6771 // Live set, collected at each sample: the inflated bytes once (30 MiB) and the steps. The read of
6872 // the whole text held them and the lines cut from it (about 60 MiB).

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

Keyboard shortcuts

Docs