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

Access 3b: MCP, pages, the terminal, games and infrastructure ask may(), one door per pull #18186

opened this

Merged 6h 5m ago, live in production

scout/forge:scout/18092-access-3b-mcp-pages-the-terminal-games-a → main 0 commits fork

  • Merged. scout/18092-access-3b-mcp-pages-the-terminal-games-a was merged into main as 5a3de44.

Review

Sign in to review this change.
12 files changed +237 −21
docs/features/may.md +6 −1
@@ -12,7 +12,7 @@ A client asks the forge what it may do instead of reading a role. One function,
1212 - **`forbidden`**: you are known, and it is not yours to do (or your token's scope is too low: `ro` reads, `rw` changes things).
1313
1414 Actions are named in one registry (`ACTIONS`), each with one sentence: `repo.read`, `repo.write`, `repo.admin` (over a
15 repository), `forge.read`, `forge.comment`, `forge.contribute`, `forge.make_it_yours`, `forge.run_crew`,
15 repository), `forge.read`, `forge.write` (any change at all, as your account: a session, or a token of scope `rw`), `forge.comment`, `forge.contribute`, `forge.make_it_yours`, `forge.run_crew`,
1616 `forge.administer`, and `account.manage` (the account itself, never a token).
1717
1818 **API.** `GET /api/v1/user` carries `can`: the forge-wide actions you may take.
@@ -39,3 +39,8 @@ While the routes move behind `may`, each is also worked out the way it was befor
3939 forge counts it, by route, action and kind of caller, with no account, token or repository named. Whoever keeps the
4040 forge reads the count with `SELECT * FROM access_disagreement ORDER BY seen DESC` in its database. An empty table is
4141 the evidence that moving the door changed nobody's access.
42
43 **The MCP tools ask it.** A tool only an admin is shown asks `forge.administer` of your account; a tool that changes
44 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.
scripts/gate.ts +11
@@ -670,6 +670,16 @@ export function repoRouteRefusal(root = "."): string[] {
670670 return repoRouteRefusalAt(root);
671671 }
672672
673 /**
674 * The MCP door asks `may` (#18092): no inline `isAdmin` or `rw` scope check in the dispatch's
675 * files (`src/kernel/mcp_door_checks.ts`).
676 */
677 export function mcpDoorRefusal(root = "."): string[] {
678 if (!existsSync(join(root, "src/kernel/mcp_door_checks.ts"))) return [];
679 const { mcpDoorRefusalAt } = require("../src/kernel/mcp_door_checks.ts") as typeof import("../src/kernel/mcp_door_checks.ts");
680 return mcpDoorRefusalAt(root);
681 }
682
673683 /**
674684 * Tests wait for a signal, not a clock (#14321): each file under `test/` held
675685 * to its committed count of fixed waits, `mock.module` calls and raised
@@ -1072,6 +1082,7 @@ export const GATE_RULES: readonly GateRule[] = [
10721082 { name: "billing never deletes", kind: "refusal", file: "src/kernel/destroy_reach.ts", satisfy: "no call path from the billing webhook deletes a forge, an app or a child", run: billingDeletesRefusal },
10731083 { name: "tls peer", kind: "refusal", file: "src/kernel/tls_peer.ts", satisfy: "open client TLS sockets with connectPeer, or list the file in scripts/tls-peer-allow.json with a reason", run: tlsPeerRefusal },
10741084 { name: "repository routes ask mayRepo", kind: "refusal", file: "src/kernel/repo_route_checks.ts", satisfy: "ask mayRepo (src/http/repo_may.ts) in a /api/v1/repos/ route, not isAdmin, scopeAllows, !ctx.auth.user or ctx.auth.user.kind; a forge-wide check is named in INLINE_ALLOWED by route with why", run: repoRouteRefusal },
1085 { name: "MCP tools ask may", kind: "refusal", file: "src/kernel/mcp_door_checks.ts", satisfy: "ask adminAccount or mayToolWrite (src/http/mcp/tool_may.ts) in src/http/mcp.ts and src/http/mcp/shared.ts, not isAdmin or scopeAllows(…, \"rw\")", run: mcpDoorRefusal },
10751086 { name: "test honesty", kind: "refusal", file: "scripts/test_honesty.ts", satisfy: "wait on a signal (test/helpers/poll.ts), not Bun.sleep(<n>), mock.module or a raised timeout; counts only shrink", run: testHonestyRefusal },
10761087 { name: "comment width", kind: "note", file: "src/kernel/comment_wrap.ts", satisfy: "bun scripts/gate.ts --fix, and commit what it rewraps", run: (c) => wrapNote(c) },
10771088 { name: "before/after looks", kind: "note", file: "src/kernel/look_rule.ts", satisfy: "a commit line `Looks: <path>` naming a page of app.looks in forge.json, or `No look: <why>`", run: lookNote },
src/contract/openapi/routes/getApiV1User.ts +1 −1
@@ -5,7 +5,7 @@ export const route: Route = {
55 method: "get",
66 path: "/api/v1/user",
77 summary: "Read your own profile: the public fields, emailVerified and what you may do",
8 detail: "The public fields, emailVerified, and `can`: the forge-wide actions this caller may take, by the names GET /api/v1/may takes (forge.read, forge.comment, forge.contribute, forge.make_it_yours, forge.run_crew, forge.administer, account.manage). A client asks `can` instead of reading a role; the forge enforces either way.",
8 detail: "The public fields, emailVerified, and `can`: the forge-wide actions this caller may take, by the names GET /api/v1/may takes (forge.read, forge.write, forge.comment, forge.contribute, forge.make_it_yours, forge.run_crew, forge.administer, account.manage). A client asks `can` instead of reading a role; the forge enforces either way.",
99 response: obj({ id: str, username: str, displayName: str, isAdmin: bool, commitEmail: str, emailVerified: bool, can: list(str) }),
1010 auth: true,
1111 role: "member",
src/core/may.ts +3
@@ -44,6 +44,7 @@ export const ACTIONS = {
4444 "repo.write": { says: "Change a repository: push, merge, label, close", over: "repo", scope: "rw" },
4545 "repo.admin": { says: "Administer a repository: its settings, webhooks, protection and deletion", over: "repo", scope: "rw" },
4646 "forge.read": forgeAction("read"),
47 "forge.write": { says: "Change something as your account: any write, by a session or a token of scope rw", over: "forge", scope: "rw" },
4748 "forge.comment": forgeAction("comment"),
4849 "forge.contribute": forgeAction("contribute"),
4950 "forge.make_it_yours": forgeAction("make_it_yours"),
@@ -95,6 +96,8 @@ function forgeRuleHolds(db: Database, action: Action, p: Principal): boolean {
9596 const user = userOf(p);
9697 if (user === undefined) return false;
9798 if (ability === "administer") return user.isAdmin;
99 // `forge.write`: any account may change what is its own to change; the scope says the rest.
100 if (action === "forge.write") return true;
98101 if (ability !== undefined) return !lacks(db, user, ability);
99102 // `account.manage`: the account itself is asking, by a browser identity (a session cookie, or
100103 // the platform edge behind its headers) or the password, never by a token.
src/http/mcp.ts +10 −9
@@ -22,6 +22,7 @@ import { readSource, SOURCE_PREFIX, SOURCE_TEMPLATE } from "./mcp/source_resourc
2222 import { CARD_KINDS, CARD_MIME, CARD_OF_TOOL, CARD_RESOURCE_META, CARD_SHELL, CARD_URI, cardFor } from "../web/studio/cards.ts";
2323 import { getRepo } from "../core/repos.ts";
2424 import { scopeAllows } from "../core/tokens.ts";
25 import { adminAccount, mayToolWrite } from "./mcp/tool_may.ts";
2526 import type { User } from "../core/users.ts";
2627 import type { Ctx, Handler } from "./context.ts";
2728 import { announcedOr } from "../kernel/version.ts";
@@ -141,7 +142,7 @@ const roleNote = (role: Role): string =>
141142 * as admin, and the person's everyday account is where daily work belongs.
142143 */
143144 function adminNote(ctx: Ctx, user: User): string {
144 if (!user.isAdmin) return "";
145 if (!adminAccount(ctx.app.db, user)) return "";
145146 const daily = everydayOf(ctx.app.db, user);
146147 return ` Note: this token belongs to ${user.username}, the forge's admin, so what you do here acts as admin.${
147148 daily === undefined
@@ -155,7 +156,7 @@ function adminNote(ctx: Ctx, user: User): string {
155156 * it hides, and the two deliberate ways to them. Empty for anyone else.
156157 */
157158 export function hiddenAdminNote(ctx: Ctx, user: User): string {
158 if (!user.isAdmin || scopeAllows(ctx.auth.scope ?? "ro", "admin")) return "";
159 if (!adminAccount(ctx.app.db, user) || scopeAllows(ctx.auth.scope ?? "ro", "admin")) return "";
159160 const hidden = TOOLS.filter((t) => t.needsAdminScope === true).map((t) => t.name);
160161 return `Hidden from this token, as admin-scope tools: ${hidden.join(", ")}; reach them with an admin-scope token, or as the forge's agent by a confirm the person answers in the conversation.`;
161162 }
@@ -249,7 +250,7 @@ function rpcOne(
249250 ? listed.filter((t) => GUEST_TOOLS.includes(t.name))
250251 : ctx.auth.through === undefined
251252 ? listed.filter((t) => DEFAULT_TOOLS.includes(t.name))
252 : listed.filter((t) => talkLists(t.name, user.isAdmin)).map(forTalk);
253 : listed.filter((t) => talkLists(t.name, adminAccount(ctx.app.db, user))).map(forTalk);
253254 // The cursor is the name of the last tool of the page before, so a tool
254255 // added between two requests moves nothing.
255256 const cursor = params["cursor"];
@@ -312,13 +313,13 @@ function rpcOne(
312313 : {};
313314 // An admin's tool stays out of an everyday account's list, and a call to
314315 // it by name is told how to reach it before anything is held or asked (#11818).
315 if (tool?.adminOnly === true && !user.isAdmin) return refuse(-32602, notAdminTool(tool.name, adminRefusal(ctx.app.db, user)), NO_TOOL_HINT);
316 if (tool?.adminOnly === true && !adminAccount(ctx.app.db, user)) return refuse(-32602, notAdminTool(tool.name, adminRefusal(ctx.app.db, user)), NO_TOOL_HINT);
316317 // Before the scope floor, so an admin tool the forge's agent was
317318 // steered to is held as a confirm too, not merely refused (#7649), and
318319 // one the person asked for waits for their yes (#7650).
319320 // What the forge's own agent may never do is refused to it at once: never held, never a yes.
320321 const never =
321 ctx.auth.through === undefined || tool === undefined ? undefined : (tool.refusedToAgent?.(args) ?? destroysTo(user, tool, args));
322 ctx.auth.through === undefined || tool === undefined ? undefined : (tool.refusedToAgent?.(args) ?? destroysTo(ctx.app.db, user, tool, args));
322323 if (never !== undefined)
323324 return reply({ content: [{ type: "text", text: `forbidden: ${never}` }], isError: true, hint: hintForCode("forbidden") });
324325 // Every argument is held to the tool's own schema, a read as a write, before anything is
@@ -328,7 +329,7 @@ function rpcOne(
328329 const shapeRead =
329330 tool !== undefined &&
330331 visible(tool, ctx, user) &&
331 !(tool.writes && !plansOnly(tool, args) && !scopeAllows(ctx.auth.scope ?? "ro", "rw"));
332 !(tool.writes && !plansOnly(tool, args) && !mayToolWrite(ctx, tool.name));
332333 const wrongArg = shapeRead ? badArgument(tool.inputSchema, args) : undefined;
333334 if (tool !== undefined && wrongArg !== undefined)
334335 return reply({
@@ -339,7 +340,7 @@ function rpcOne(
339340 // A write the tool would refuse this person anyway is answered as refused now, in its own
340341 // words, and never held for a yes that could only fail.
341342 const askable =
342 tool !== undefined && visible(tool, ctx, user) && !plansOnly(tool, args) && scopeAllows(ctx.auth.scope ?? "ro", "rw");
343 tool !== undefined && visible(tool, ctx, user) && !plansOnly(tool, args) && mayToolWrite(ctx, tool.name);
343344 const refused = askable ? tool.refusesFirst?.(ctx, user, args) : undefined;
344345 // A tool listed to admins alone refuses everyone else in `run`: it runs to that refusal,
345346 // unheld.
@@ -356,7 +357,7 @@ function rpcOne(
356357 if (held !== undefined) return reply(held);
357358 if (tool === undefined || !visible(tool, ctx, user))
358359 return refuse(-32602, noToolNamed(String(params["name"])), NO_TOOL_HINT);
359 if (tool.writes && !plansOnly(tool, args) && !scopeAllows(ctx.auth.scope ?? "ro", "rw"))
360 if (tool.writes && !plansOnly(tool, args) && !mayToolWrite(ctx, tool.name))
360361 return reply({
361362 content: [
362363 { type: "text", text: READ_ONLY_REFUSAL },
@@ -613,7 +614,7 @@ async function gatedShortcut(ctx: Ctx, user: User, id: unknown, tool: ToolShape,
613614 const reply = (result: unknown) => ({ jsonrpc: "2.0", id, result });
614615 const held = askedFirst(ctx, user, tool, args) ?? heldWrite(ctx, user, tool, args);
615616 if (held !== undefined) return reply(held);
616 if (!scopeAllows(ctx.auth.scope ?? "ro", "rw"))
617 if (!mayToolWrite(ctx, tool.name))
617618 return reply({ content: [{ type: "text", text: READ_ONLY_REFUSAL }], isError: true, hint: hintForCode("forbidden") });
618619 const via = ctx.auth.through;
619620 if (via !== undefined) {
src/http/mcp/shared.ts +6 −5
@@ -9,6 +9,7 @@ import { canRead, canWrite, getRepo, type Repo } from "../../core/repos.ts";
99 import { readableRepoNamed } from "../../core/search.ts";
1010 import { nearRepos } from "../../core/near_repos.ts";
1111 import { scopeAllows } from "../../core/tokens.ts";
12 import { adminAccount } from "./tool_may.ts";
1213 import { getUserByName, type User } from "../../core/users.ts";
1314 import { applyFleetIds, previewFleetIds } from "../../actions/fleet.ts";
1415 import { KIND_CHIPS, parseChipArgs } from "../../core/feed_chips.ts";
@@ -175,12 +176,12 @@ export const notAdminTool = (name: string, why: string = SIGN_IN_AS_ADMIN): stri
175176 * Whether this caller is shown the tool and may call it: one rule for the manifest and dispatch.
176177 */
177178 export const visible = (tool: Tool, ctx: Ctx, user: User): boolean =>
178 (tool.adminOnly !== true || user.isAdmin) &&
179 (tool.adminOnly !== true || adminAccount(ctx.app.db, user)) &&
179180 (tool.needsSwitch === undefined || sshOn(ctx.app.db)) &&
180181 (tool.needsAdminScope !== true || scopeAllows(ctx.auth.scope ?? "ro", "admin"));
181182
182183 /** Whether this caller is offered the tool: visible, and not one only an admin is listed. */
183 export const listable = (tool: Tool, ctx: Ctx, user: User): boolean => visible(tool, ctx, user) && (tool.listedTo !== "admin" || user.isAdmin);
184 export const listable = (tool: Tool, ctx: Ctx, user: User): boolean => visible(tool, ctx, user) && (tool.listedTo !== "admin" || adminAccount(ctx.app.db, user));
184185
185186 /** Whether this call only plans or reads, so a read-only token may make it. */
186187 export const plansOnly = (tool: ToolShape, args: Args): boolean =>
@@ -198,8 +199,8 @@ const destroys = (tool: ToolShape, args: Args): boolean => tool.writes && !plans
198199 * asked first or held. What the person may not do stays unknown to their agent: an admin-scope
199200 * tool of someone who is no admin is left to the refusal every caller meets. Undefined: go on.
200201 */
201 export const destroysTo = (user: User, tool: ToolShape, args: Args): string | undefined =>
202 destroys(tool, args) && !(tool.needsAdminScope === true && !user.isAdmin) ? destroysSentence(tool) : undefined;
202 export const destroysTo = (db: Database, user: User, tool: ToolShape, args: Args): string | undefined =>
203 destroys(tool, args) && !(tool.needsAdminScope === true && !adminAccount(db, user)) ? destroysSentence(tool) : undefined;
203204
204205 /** What a held write tells the forge's agent, beside the confirm's id. */
205206 export const NEEDS_CONFIRM =
@@ -374,7 +375,7 @@ export function askedFirst(ctx: Ctx, user: User, tool: ToolShape, args: Args): R
374375 if (via === undefined) return undefined;
375376 // What the person may not do stays unknown to their agent.
376377 // An admin-only tool is refused before this, in mcp.ts (#11818).
377 if (tool.needsAdminScope === true && !user.isAdmin) return undefined;
378 if (tool.needsAdminScope === true && !adminAccount(ctx.app.db, user)) return undefined;
378379 const short = tool.needsAdminScope === true && !scopeAllows(ctx.auth.scope ?? "ro", "admin");
379380 if (destroys(tool, args)) return undefined;
380381 if (!short && (!tool.writes || plansOnly(tool, args) || tool.heldNotWhen?.(args) === true || !asksFirst(tool.name, args))) return undefined;
src/http/mcp/tool_may.ts added +33
@@ -0,0 +1,33 @@
1 /**
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.
4 *
5 * - `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.
8 * - `writes`: `forge.write`, asked with the credential the call carries: a token whose scope is
9 * `ro` may not, as before.
10 *
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`).
14 */
15
16 import type { Database } from "bun:sqlite";
17 import { noteDisagreement } from "../../core/access_disagreement.ts";
18 import { holds } from "../../core/may.ts";
19 import { principalOf, principalOfUser } from "../../core/principal.ts";
20 import { scopeAllows } from "../../core/tokens.ts";
21 import type { User } from "../../core/users.ts";
22 import type { Ctx } from "../context.ts";
23
24 /** Is this account the forge's admin? What `adminOnly` and `listedTo: "admin"` ask. */
25 export const adminAccount = (db: Database, user: User): boolean => holds(db, principalOfUser(user), "forge.administer");
26
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 const asking = principalOf(ctx.auth);
30 const said = holds(ctx.app.db, asking, "forge.write");
31 if (said !== scopeAllows(ctx.auth.scope ?? "ro", "rw")) noteDisagreement(ctx.app.db, `mcp ${door}`, "forge.write", asking.kind, said);
32 return said;
33 }
src/kernel/mcp_door_checks.ts added +41
@@ -0,0 +1,41 @@
1 /**
2 * The MCP door asks `may` (#18092): who sees and calls a tool is said by `adminAccount` and
3 * `mayToolWrite` (`http/mcp/tool_may.ts`), never by reading the account or the token's `rw` scope
4 * inline in the dispatch. This is the scan the gate holds the dispatch's files to: an inline
5 * `isAdmin`, or a `scopeAllows(…, "rw")`, in `src/http/mcp.ts` or `src/http/mcp/shared.ts` is
6 * refused, but on a line `MCP_INLINE_ALLOWED` names with why. `scopeAllows(…, "admin")` stays:
7 * `needsAdminScope` is how far a token reaches, a scope and not a role.
8 */
9
10 import { existsSync, readFileSync } from "node:fs";
11 import { join } from "node:path";
12
13 const DOOR_FILES = ["src/http/mcp.ts", "src/http/mcp/shared.ts"] as const;
14
15 const INLINE = [/\bisAdmin\b/, /\bscopeAllows\([^)]*"rw"\s*\)/] as const;
16
17 /** A line that may keep its check, by what it starts with, and why. Only shrinks. */
18 const MCP_INLINE_ALLOWED: readonly { readonly file: string; readonly starts: string; readonly why: string }[] = [
19 {
20 file: "src/http/mcp/shared.ts",
21 starts: "export const mayBoards",
22 why: "a tool's own rule (a forge admin who is a person), asked inside the tool, not the door",
23 },
24 ];
25
26 /** Each inline check in the MCP door's files, as `file:line: text`; empty when there are none. */
27 export function mcpDoorRefusalAt(root: string): string[] {
28 const found: string[] = [];
29 for (const file of DOOR_FILES) {
30 const path = join(root, file);
31 if (!existsSync(path)) continue;
32 readFileSync(path, "utf8")
33 .split("\n")
34 .forEach((text, i) => {
35 if (!INLINE.some((re) => re.test(text))) return;
36 if (MCP_INLINE_ALLOWED.some((a) => a.file === file && text.trimStart().startsWith(a.starts))) return;
37 found.push(`${file}:${i + 1}: an inline access check in the MCP door: ask adminAccount or mayToolWrite (src/http/mcp/tool_may.ts): ${text.trim()}`);
38 });
39 }
40 return found;
41 }
test/may.test.ts +3 −3
@@ -154,8 +154,8 @@ test("a token is not a person: account.manage is the account itself", () => {
154154 test("the forge-wide actions follow the roles table", () => {
155155 const can = (who: string | undefined, scope?: "ro" | "rw" | "admin") => capabilities(app.db, scope === undefined ? principalOfUser(as(who)) : bearer(as(who), scope));
156156 expect(can(undefined)).toEqual(["forge.read"]);
157 expect(can("gina")).toEqual(["forge.read", "forge.comment", "forge.contribute"]);
158 expect(can("nina")).toEqual(["forge.read", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew"]);
157 expect(can("gina")).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute"]);
158 expect(can("nina")).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew"]);
159159 expect(can("boss")).toContain("forge.administer");
160160 expect(can("nina")).not.toContain("forge.administer");
161161 expect(can("boss", "ro")).toEqual(["forge.read"]);
@@ -171,7 +171,7 @@ const get = async (path: string, who?: string) => {
171171
172172 test("GET /api/v1/user lists what the caller may do, by the registry's names", async () => {
173173 const rw = await get("/api/v1/user", "wes:rw");
174 expect(rw.body["can"]).toEqual(["forge.read", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew"]);
174 expect(rw.body["can"]).toEqual(["forge.read", "forge.write", "forge.comment", "forge.contribute", "forge.make_it_yours", "forge.run_crew"]);
175175 expect((await get("/api/v1/user", "wes:ro")).body["can"]).toEqual(["forge.read"]);
176176 });
177177
test/mcp-shared-gate.test.ts +1 −1
@@ -11,7 +11,7 @@ const tool = (over: Partial<Tool> = {}): Tool => ({
1111 run: () => ({ ok: true, value: null }),
1212 ...over,
1313 });
14 const ctxOf = (scope: "ro" | "rw" | "admin"): Ctx => ({ auth: { scope } }) as unknown as Ctx;
14 const ctxOf = (scope: "ro" | "rw" | "admin"): Ctx => ({ app: { db: undefined }, auth: { scope } }) as unknown as Ctx;
1515 const userOf = (isAdmin: boolean): User => ({ isAdmin }) as unknown as User;
1616
1717 describe("visible", () => {
test/mcp-tools-may.test.ts added +121
@@ -0,0 +1,121 @@
1 /**
2 * 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.
8 */
9 import { afterAll, beforeAll, expect, test } from "bun:test";
10 import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { createRepo } from "../src/actions/repos.ts";
14 import { createApp, type App } from "../src/app.ts";
15 import { mintContribute } from "../src/core/contribute_token.ts";
16 import { mintProposalToken } from "../src/core/proposal_token.ts";
17 import type { Repo } from "../src/core/repos.ts";
18 import { mintRunToken } from "../src/core/run_token.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import { createToken } from "../src/core/tokens.ts";
21 import { createUser, type User } from "../src/core/users.ts";
22 import { mintViaToken } from "../src/core/via_token.ts";
23 import type { Ctx } from "../src/http/context.ts";
24 import { adminAccount, mayToolWrite } from "../src/http/mcp/tool_may.ts";
25 import { resolveAuth } from "../src/http/server.ts";
26 import { mcpDoorRefusalAt } from "../src/kernel/mcp_door_checks.ts";
27 import { GATE_RULES, mcpDoorRefusal } from "../scripts/gate.ts";
28 import { quietLogs } from "./helpers/globals.ts";
29 import { promote } from "./helpers/members.ts";
30
31 quietLogs();
32
33 const HOST = "forge.test";
34 let dataDir = "";
35 let app: App;
36 let repo: Repo;
37 const users = {} as Record<"boss" | "gina" | "nina", User>;
38
39 beforeAll(async () => {
40 dataDir = await mkdtemp(join(tmpdir(), "forge-mcp-may-"));
41 app = createApp({ dataDir, port: 0, host: HOST });
42 for (const name of ["boss", "gina", "nina"] as const) {
43 const made = await createUser(app.db, {
44 origin: "seed", trusted: true, username: name, email: `${name}@forge.local`,
45 password: "a-good-passphrase", adminIfFirst: name === "boss",
46 });
47 if (!made.ok) throw new Error(String(made.error));
48 users[name] = made.value;
49 }
50 promote(app.db, users.boss, users.nina); // gina stays a guest
51 const made = await createRepo(app, users.nina, { name: "notes", visibility: "public" });
52 if (!made.ok) throw new Error(String(made.error));
53 repo = made.value;
54 });
55
56 afterAll(async () => {
57 app.close();
58 await rm(dataDir, { recursive: true, force: true });
59 });
60
61 const until = (ms: number): string => new Date(Date.now() + ms).toISOString();
62 const bearer = (token: string): Record<string, string> => ({ authorization: `Bearer ${token}` });
63
64 /** Each caller by its credential, and what it is answered: [admin's tools, writes]. */
65 const CALLERS: readonly [string, () => Record<string, string>, boolean, boolean][] = [
66 ["gina session (guest)", () => ({ cookie: `forge_session=${createSession(app.db, users.gina.id).token}` }), false, true],
67 ["nina session (member)", () => ({ cookie: `forge_session=${createSession(app.db, users.nina.id).token}` }), false, true],
68 ["boss session (admin)", () => ({ cookie: `forge_session=${createSession(app.db, users.boss.id).token}` }), true, true],
69 ["nina ro token", () => bearer(createToken(app.db, users.nina.id, "ro", "ro").token), false, false],
70 ["nina rw token", () => bearer(createToken(app.db, users.nina.id, "rw", "rw").token), false, true],
71 ["boss ro token", () => bearer(createToken(app.db, users.boss.id, "ro", "ro").token), true, false],
72 ["boss admin token", () => bearer(createToken(app.db, users.boss.id, "admin", "admin").token), true, true],
73 ["nina via token", () => {
74 const via = mintViaToken(app.db, users.nina.id, "conversation:abc123", "hello", until(1_800_000));
75 if (!via.ok) throw new Error(via.error);
76 return bearer(via.value.token);
77 }, false, true],
78 ["nina proposal token", () => {
79 const p = mintProposalToken(app.db, users.nina.id, repo.id, { child: "kid", origin: "https://kid.example/" });
80 if (!p.ok) throw new Error(p.error);
81 return bearer(p.value.token);
82 }, false, true],
83 ["nina run token", () => bearer(mintRunToken(app.db, users.nina.id, `run${Math.random()}`, { repoId: repo.id, forkId: repo.id }, until(3_600_000)).token), false, true],
84 ["gina contribute token", () =>
85 bearer(mintContribute(app.db, { userId: users.gina.id, repoId: repo.id, agent: "codex", origin: "claimed", source: "s1" }, new Date()).token), false, true],
86 ];
87
88 test("an admin's tools and a write are answered by may, for each kind of caller, with no disagreement", async () => {
89 const got: string[] = [];
90 const want: string[] = [];
91 for (const [label, headers, admin, writes] of CALLERS) {
92 const auth = await resolveAuth(app, new Request(`http://${HOST}/mcp`, { method: "POST", headers: { origin: `http://${HOST}`, ...headers() } }));
93 expect(auth.user, label).toBeDefined();
94 const ctx = { app, auth } as unknown as Ctx;
95 got.push(`${label}: admin ${adminAccount(app.db, auth.user!)}, writes ${mayToolWrite(ctx, "test")}`);
96 want.push(`${label}: admin ${admin}, writes ${writes}`);
97 }
98 expect(got).toEqual(want);
99 expect(app.db.query("SELECT * FROM access_disagreement WHERE door LIKE 'mcp %'").all()).toEqual([]);
100 });
101
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.
104 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 ]);
109 });
110
111 test("the gate holds the MCP door's files: an inline isAdmin or rw scope check is refused", async () => {
112 expect(GATE_RULES.some((r) => r.name === "MCP tools ask may")).toBe(true);
113 expect(mcpDoorRefusal(".")).toEqual([]);
114 const root = await mkdtemp(join(tmpdir(), "forge-mcp-gate-"));
115 await mkdir(join(root, "src/http/mcp"), { recursive: true });
116 await writeFile(join(root, "src/http/mcp.ts"), 'if (!user.isAdmin) return x;\nif (!scopeAllows(s, "rw")) return y;\nif (!scopeAllows(s, "admin")) return z;\n');
117 await writeFile(join(root, "src/http/mcp/shared.ts"), "export const mayBoards = (user: User): boolean => user.isAdmin;\n");
118 const found = mcpDoorRefusalAt(root);
119 expect(found.map((f) => f.split(": ")[0])).toEqual(["src/http/mcp.ts:1", "src/http/mcp.ts:2"]);
120 await rm(root, { recursive: true, force: true });
121 });
test/tui-can.test.ts +1 −1
@@ -66,7 +66,7 @@ describe("what I can do in the terminal", () => {
6666 expect(guest).toContain("You are guest here.");
6767 expect(guest).toContain("Create a repository or copy an app: no");
6868 // the same list GET /api/v1/user gives a session, with the account's own `account.manage` on it
69 expect(guest).toContain("You may: forge.read, forge.comment, forge.contribute, account.manage");
69 expect(guest).toContain("You may: forge.read, forge.write, forge.comment, forge.contribute, account.manage");
7070 setMember(forge.db, getUserByName(forge.db, "bob")!.id, true, "x", new Date());
7171 const member = await shown("bob");
7272 expect(member).toContain("You are member here.");

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

Keyboard shortcuts

Docs