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

Access 3, MCP: the scope floor is read from the disagreement count, then deleted #18418

opened this

Merged 1h 55m ago, live in production

mason/forge:mason/18405-access-3-mcp-the-scope-floor-is-read-fro → main 0 commits fork

  • Merged. mason/18405-access-3-mcp-the-scope-floor-is-read-fro was merged into main as e374d6c.

Review

Sign in to review this change.
7 files changed +135 −35
docs/ROLES.md +1 −1
@@ -117,7 +117,7 @@ The repository routes under `src/http/api/` and the MCP tools (`src/http/mcp.ts`
117117 that gates on `isAdmin`, on `scopeAllows(…, "rw")` or on `!ctx.auth.user` fails
118118 `test/door-inline-checks.test.ts`, which names the file and line and the helper to
119119 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
120 admin, `mayBeside(ctx, door, "forge.write", old)` (`mayToolWrite(ctx)` in the MCP) for
121121 a write, `signedInPage` for an account. Only gate shapes count: a role passed on
122122 for display is a read, and `scopeAllows(…, "admin")` is a token's reach, not a
123123 role. The lines that stay are listed in `DOOR_LINES` (`src/design/door_checks.ts`),
docs/features/may.md +2 −2
@@ -42,8 +42,8 @@ the evidence that moving the door changed nobody's access.
4242
4343 **The MCP tools ask it.** A tool only an admin is shown asks `forge.administer` of your account; a tool that changes
4444 something asks `forge.write` with the credential you send, so an `ro` token is told it may only read
45 (`src/http/mcp/tool_may.ts`). The old scope floor is worked out beside it, and where the two part the count's door is
46 `mcp <tool>`. The terminal's "What I can do" lists `forge.write` with the rest.
45 (`src/http/mcp/tool_may.ts`). The old scope floor was worked out beside it until the count under `mcp <tool>` held
46 nothing a request can make (#18405); `may`'s answer is now the only one. The terminal's "What I can do" lists `forge.write` with the rest.
4747
4848 **The web pages ask it.** A page only the admin sees asks `forge.administer`, and a page that needs you signed in asks
4949 by what the request does: `forge.read` to open it (GET), `forge.write` to change something (POST), both with the
src/design/door_checks.ts −1
@@ -79,7 +79,6 @@ export const DOOR_LINES: readonly DoorLine[] = [
7979 { file: "src/http/api/statement.ts", text: "if (ctx.auth.user === undefined) return notFound();", why: "a stranger is never told a statement exists" },
8080 { file: "src/http/api/cdn.ts", text: "if (!ctx.auth.user) {", why: "a rate by address, not a permission" },
8181 { 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" },
8382 { 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" },
8483 { 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" },
8584 { 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" },
src/http/mcp.ts +4 −4
@@ -329,7 +329,7 @@ function rpcOne(
329329 const shapeRead =
330330 tool !== undefined &&
331331 visible(tool, ctx, user) &&
332 !(tool.writes && !plansOnly(tool, args) && !mayToolWrite(ctx, tool.name));
332 !(tool.writes && !plansOnly(tool, args) && !mayToolWrite(ctx));
333333 const wrongArg = shapeRead ? badArgument(tool.inputSchema, args) : undefined;
334334 if (tool !== undefined && wrongArg !== undefined)
335335 return reply({
@@ -340,7 +340,7 @@ function rpcOne(
340340 // A write the tool would refuse this person anyway is answered as refused now, in its own
341341 // words, and never held for a yes that could only fail.
342342 const askable =
343 tool !== undefined && visible(tool, ctx, user) && !plansOnly(tool, args) && mayToolWrite(ctx, tool.name);
343 tool !== undefined && visible(tool, ctx, user) && !plansOnly(tool, args) && mayToolWrite(ctx);
344344 const refused = askable ? tool.refusesFirst?.(ctx, user, args) : undefined;
345345 // A tool listed to admins alone refuses everyone else in `run`: it runs to that refusal,
346346 // unheld.
@@ -357,7 +357,7 @@ function rpcOne(
357357 if (held !== undefined) return reply(held);
358358 if (tool === undefined || !visible(tool, ctx, user))
359359 return refuse(-32602, noToolNamed(String(params["name"])), NO_TOOL_HINT);
360 if (tool.writes && !plansOnly(tool, args) && !mayToolWrite(ctx, tool.name))
360 if (tool.writes && !plansOnly(tool, args) && !mayToolWrite(ctx))
361361 return reply({
362362 content: [
363363 { type: "text", text: READ_ONLY_REFUSAL },
@@ -614,7 +614,7 @@ async function gatedShortcut(ctx: Ctx, user: User, id: unknown, tool: ToolShape,
614614 const reply = (result: unknown) => ({ jsonrpc: "2.0", id, result });
615615 const held = limitedOut(ctx, tool, args) ?? askedFirst(ctx, user, tool, args) ?? heldWrite(ctx, user, tool, args);
616616 if (held !== undefined) return reply(held);
617 if (!mayToolWrite(ctx, tool.name))
617 if (!mayToolWrite(ctx))
618618 return reply({ content: [{ type: "text", text: READ_ONLY_REFUSAL }], isError: true, hint: hintForCode("forbidden") });
619619 const via = ctx.auth.through;
620620 if (via !== undefined) {
src/http/mcp/tool_may.ts +10 −15
@@ -1,30 +1,25 @@
11 /**
2 * The MCP door asks `may` (#18092): a tool's `adminOnly` and `writes` are actions, not inline
3 * reads of the account or the token's scope.
2 * The MCP door asks `may` (#18092, #18405): a tool's `adminOnly` and `writes` are actions, not
3 * inline reads of the account or the token's scope.
44 *
55 * - `adminOnly`: `forge.administer`, asked of the account (`principalOfUser`): an admin's token
6 * of any scope sees an admin's tool, as before; how far the token reaches is `needsAdminScope`'s
7 * to say, a scope and not a role.
6 * of any scope sees an admin's tool; how far the token reaches is `needsAdminScope`'s to say, a
7 * scope and not a role.
88 * - `writes`: `forge.write`, asked with the credential the call carries: a token whose scope is
9 * `ro` may not, as before.
9 * `ro` may not.
1010 *
11 * The scope floor it replaced (`scopeAllows(ctx.auth.scope ?? "ro", "rw")`) is still worked out
12 * beside `may`'s answer, and when the two part the tool's door is counted
13 * (`core/access_disagreement.ts`), as the repository routes are (`http/repo_may.ts`).
11 * The `rw` scope floor these replaced was asked beside `may` until its count of disagreements read
12 * nothing a request can make (#18405); `may`'s answer is now the only one.
1413 */
1514
1615 import type { Database } from "bun:sqlite";
1716 import { holds } from "../../core/may.ts";
18 import { principalOfUser } from "../../core/principal.ts";
19 import { scopeAllows } from "../../core/tokens.ts";
17 import { principalOf, principalOfUser } from "../../core/principal.ts";
2018 import type { User } from "../../core/users.ts";
2119 import type { Ctx } from "../context.ts";
22 import { mayBeside } from "../may_beside.ts";
2320
2421 /** Is this account the forge's admin? What `adminOnly` and `listedTo: "admin"` ask. */
2522 export const adminAccount = (db: Database, user: User): boolean => holds(db, principalOfUser(user), "forge.administer");
2623
27 /** May this call change something? What a tool's `writes` asks; `door` names it in the count. */
28 export function mayToolWrite(ctx: Ctx, door: string): boolean {
29 return mayBeside(ctx, `mcp ${door}`, "forge.write", scopeAllows(ctx.auth.scope ?? "ro", "rw"));
30 }
24 /** May this call change something? What a tool's `writes` asks. */
25 export const mayToolWrite = (ctx: Ctx): boolean => holds(ctx.app.db, principalOf(ctx.auth), "forge.write");
test/mcp-scope-floor-gone.test.ts added +106
@@ -0,0 +1,106 @@
1 /**
2 * Access 3, the MCP door's last step (#18405): `mayToolWrite` and `adminAccount` answer with
3 * `may` alone, the old `rw` scope floor deleted. Over HTTP, as a client calls: an `ro` token is
4 * refused a write in the read-only words and an `rw` token is not; an admin's token, of any scope,
5 * is shown and runs an admin's tool; an agent without the admin role is told no such tool exists.
6 * Each test fails if its check is dropped. No row is counted at any `mcp ` door.
7 */
8 import { afterAll, beforeAll, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { createApp, type App } from "../src/app.ts";
13 import { createAgentRow } from "../src/core/agents.ts";
14 import { createUser } from "../src/core/users.ts";
15 import { READ_ONLY_REFUSAL } from "../src/http/mcp/hints.ts";
16 import { serve, type Servers } from "../src/http/server.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18 import { tokenFor } from "./helpers/tokens.ts";
19
20 quietLogs();
21
22 let dataDir = "";
23 let app: App;
24 let servers: Servers;
25
26 beforeAll(async () => {
27 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-floor-"));
28 app = createApp({ dataDir, port: 0 });
29 servers = await serve(app);
30 for (const [username, admin] of [["boss", true], ["nina", false]] as const) {
31 const made = await createUser(app.db, {
32 origin: "seed", trusted: true, username, email: `${username}@forge.local`,
33 password: "a-good-passphrase", ...(admin ? { adminIfFirst: true } : {}),
34 });
35 if (!made.ok) throw new Error(String(made.error));
36 }
37 const bot = await createUser(app.db, { username: "bot", email: "[email protected]", agent: true, origin: "agent" });
38 if (!bot.ok) throw new Error(String(bot.error));
39 createAgentRow(app.db, { userId: bot.value.id, brief: "bot." });
40 }, 60_000);
41
42 afterAll(async () => {
43 servers.stop();
44 app.close();
45 await rm(dataDir, { recursive: true, force: true });
46 });
47
48 /** One JSON-RPC call to /mcp with a bearer token; the whole answer. */
49 async function rpc(token: string, method: string, params: Record<string, unknown>): Promise<any> {
50 const res = await fetch(`${servers.url}/mcp`, {
51 method: "POST",
52 headers: {
53 "content-type": "application/json",
54 accept: "application/json, text/event-stream",
55 authorization: `Bearer ${token}`,
56 },
57 body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
58 });
59 return res.json();
60 }
61
62 /** What a tools/call answers, as one line of text: its first content, or the error's message. */
63 const call = async (token: string, name: string, args: Record<string, unknown>): Promise<string> => {
64 const body = await rpc(token, "tools/call", { name, arguments: args });
65 return body.error?.message ?? body.result.content[0].text;
66 };
67
68 /** Every tool name tools/list offers this token, page after page. */
69 async function listed(token: string): Promise<string[]> {
70 const names: string[] = [];
71 let cursor: string | undefined;
72 do {
73 const body = await rpc(token, "tools/list", { all: true, ...(cursor === undefined ? {} : { cursor }) });
74 names.push(...body.result.tools.map((t: { name: string }) => t.name));
75 cursor = body.result.nextCursor;
76 } while (cursor !== undefined);
77 return names;
78 }
79
80 const DISMISS = { item: "no-such-item", kind: "dismissed" };
81
82 test("an ro token is refused a writing tool; an rw token reaches the tool itself", async () => {
83 expect(await call(tokenFor(app, "nina", "ro", "ro"), "feed_dismiss", DISMISS)).toBe(READ_ONLY_REFUSAL);
84 const rw = await call(tokenFor(app, "nina", "rw", "rw"), "feed_dismiss", DISMISS);
85 expect(rw).not.toBe(READ_ONLY_REFUSAL);
86 });
87
88 test("an admin's token of any scope sees and runs an admin's tool", async () => {
89 for (const scope of ["ro", "admin"] as const) {
90 const token = tokenFor(app, "boss", scope, `boss-${scope}`);
91 expect(await listed(token)).toContain("decider_shadow");
92 expect(await call(token, "decider_shadow", {})).not.toContain("no tool named");
93 }
94 });
95
96 test("an agent without the admin role, and a member, are neither shown nor let run an admin's tool", async () => {
97 for (const name of ["bot", "nina"]) {
98 const token = tokenFor(app, name, "rw", `${name}-rw`);
99 expect(await listed(token)).not.toContain("decider_shadow");
100 expect(await call(token, "decider_shadow", {})).toContain("no tool named decider_shadow");
101 }
102 });
103
104 test("no disagreement is counted at any mcp door: there is no second check to part from", () => {
105 expect(app.db.query("SELECT * FROM access_disagreement WHERE door LIKE 'mcp %'").all()).toEqual([]);
106 });
test/mcp-tools-may.test.ts +12 −12
@@ -1,10 +1,11 @@
11 /**
22 * Access 3b, the MCP door (#18092): a tool's `adminOnly` asks `may(account, "forge.administer")`
3 * and its `writes` asks `may(principal, "forge.write")` (`http/mcp/tool_may.ts`), with the old `rw`
4 * scope floor worked out beside it. Each kind of caller is resolved from a real credential, as a
5 * request would be: a guest, a member and the admin signed in, by an `ro`, `rw` and `admin` token,
6 * and by a via, proposal, run and contribute token. Their answers are pinned and no disagreement
7 * is counted. The gate (`src/kernel/mcp_door_checks.ts`) is shown to bite on a new inline check.
3 * and its `writes` asks `may(principal, "forge.write")` (`http/mcp/tool_may.ts`); the old `rw`
4 * scope floor once worked out beside it is gone (#18405). Each kind of caller is resolved from a
5 * real credential, as a request would be: a guest, a member and the admin signed in, by an `ro`,
6 * `rw` and `admin` token, and by a via, proposal, run and contribute token. Their answers are
7 * pinned and no disagreement is counted. The gate (`src/kernel/mcp_door_checks.ts`) is shown to
8 * bite on a new inline check.
89 */
910 import { afterAll, beforeAll, expect, test } from "bun:test";
1011 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
@@ -92,20 +93,19 @@ test("an admin's tools and a write are answered by may, for each kind of caller,
9293 const auth = await resolveAuth(app, new Request(`http://${HOST}/mcp`, { method: "POST", headers: { origin: `http://${HOST}`, ...headers() } }));
9394 expect(auth.user, label).toBeDefined();
9495 const ctx = { app, auth } as unknown as Ctx;
95 got.push(`${label}: admin ${adminAccount(app.db, auth.user!)}, writes ${mayToolWrite(ctx, "test")}`);
96 got.push(`${label}: admin ${adminAccount(app.db, auth.user!)}, writes ${mayToolWrite(ctx)}`);
9697 want.push(`${label}: admin ${admin}, writes ${writes}`);
9798 }
9899 expect(got).toEqual(want);
99100 expect(app.db.query("SELECT * FROM access_disagreement WHERE door LIKE 'mcp %'").all()).toEqual([]);
100101 });
101102
102 test("a write answered apart from the old scope floor is counted at the tool's door", () => {
103 // A signed-in account with no scope at all: the old floor read it as `ro`, `may` as the account.
103 test("a signed-in account with no scope writes as the account, and nothing is counted", () => {
104 // No HTTP request makes this: every signed-in Auth carries a scope. The old floor read it as
105 // `ro`; with the floor gone (#18405) `may` answers as the account, and there is no count.
104106 const ctx = { app, auth: { user: users.nina, scope: undefined, via: "session" } } as unknown as Ctx;
105 expect(mayToolWrite(ctx, "feed_dismiss")).toBe(true);
106 expect(app.db.query("SELECT door, action, may FROM access_disagreement WHERE door = 'mcp feed_dismiss'").all()).toEqual([
107 { door: "mcp feed_dismiss", action: "forge.write", may: 1 },
108 ]);
107 expect(mayToolWrite(ctx)).toBe(true);
108 expect(app.db.query("SELECT * FROM access_disagreement WHERE door LIKE 'mcp %'").all()).toEqual([]);
109109 });
110110
111111 test("the gate holds the MCP door's files: an inline isAdmin or rw scope check is refused", async () => {

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

Keyboard shortcuts

Docs