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
Merged 6h 5m ago, live in production
scout/forge:scout/18092-access-3b-mcp-pages-the-terminal-games-a → main 0 commits fork
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, | ||
| 12 | 12 | - **`forbidden`**: you are known, and it is not yours to do (or your token's scope is too low: `ro` reads, `rw` changes things). |
| 13 | 13 | |
| 14 | 14 | 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`, | |
| 16 | 16 | `forge.administer`, and `account.manage` (the account itself, never a token). |
| 17 | 17 | |
| 18 | 18 | **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 | ||
| 39 | 39 | forge counts it, by route, action and kind of caller, with no account, token or repository named. Whoever keeps the |
| 40 | 40 | forge reads the count with `SELECT * FROM access_disagreement ORDER BY seen DESC` in its database. An empty table is |
| 41 | 41 | 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[] { | ||
| 670 | 670 | return repoRouteRefusalAt(root); |
| 671 | 671 | } |
| 672 | 672 | |
| 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 | ||
| 673 | 683 | /** |
| 674 | 684 | * Tests wait for a signal, not a clock (#14321): each file under `test/` held |
| 675 | 685 | * to its committed count of fixed waits, `mock.module` calls and raised |
| @@ -1072,6 +1082,7 @@ export const GATE_RULES: readonly GateRule[] = [ | ||
| 1072 | 1082 | { 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 }, |
| 1073 | 1083 | { 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 }, |
| 1074 | 1084 | { 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 }, | |
| 1075 | 1086 | { 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 }, |
| 1076 | 1087 | { 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) }, |
| 1077 | 1088 | { 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 = { | ||
| 5 | 5 | method: "get", |
| 6 | 6 | path: "/api/v1/user", |
| 7 | 7 | 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.", | |
| 9 | 9 | response: obj({ id: str, username: str, displayName: str, isAdmin: bool, commitEmail: str, emailVerified: bool, can: list(str) }), |
| 10 | 10 | auth: true, |
| 11 | 11 | role: "member", |
src/core/may.ts +3
| @@ -44,6 +44,7 @@ export const ACTIONS = { | ||
| 44 | 44 | "repo.write": { says: "Change a repository: push, merge, label, close", over: "repo", scope: "rw" }, |
| 45 | 45 | "repo.admin": { says: "Administer a repository: its settings, webhooks, protection and deletion", over: "repo", scope: "rw" }, |
| 46 | 46 | "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" }, | |
| 47 | 48 | "forge.comment": forgeAction("comment"), |
| 48 | 49 | "forge.contribute": forgeAction("contribute"), |
| 49 | 50 | "forge.make_it_yours": forgeAction("make_it_yours"), |
| @@ -95,6 +96,8 @@ function forgeRuleHolds(db: Database, action: Action, p: Principal): boolean { | ||
| 95 | 96 | const user = userOf(p); |
| 96 | 97 | if (user === undefined) return false; |
| 97 | 98 | 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; | |
| 98 | 101 | if (ability !== undefined) return !lacks(db, user, ability); |
| 99 | 102 | // `account.manage`: the account itself is asking, by a browser identity (a session cookie, or |
| 100 | 103 | // 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 | ||
| 22 | 22 | import { CARD_KINDS, CARD_MIME, CARD_OF_TOOL, CARD_RESOURCE_META, CARD_SHELL, CARD_URI, cardFor } from "../web/studio/cards.ts"; |
| 23 | 23 | import { getRepo } from "../core/repos.ts"; |
| 24 | 24 | import { scopeAllows } from "../core/tokens.ts"; |
| 25 | import { adminAccount, mayToolWrite } from "./mcp/tool_may.ts"; | |
| 25 | 26 | import type { User } from "../core/users.ts"; |
| 26 | 27 | import type { Ctx, Handler } from "./context.ts"; |
| 27 | 28 | import { announcedOr } from "../kernel/version.ts"; |
| @@ -141,7 +142,7 @@ const roleNote = (role: Role): string => | ||
| 141 | 142 | * as admin, and the person's everyday account is where daily work belongs. |
| 142 | 143 | */ |
| 143 | 144 | function adminNote(ctx: Ctx, user: User): string { |
| 144 | if (!user.isAdmin) return ""; | |
| 145 | if (!adminAccount(ctx.app.db, user)) return ""; | |
| 145 | 146 | const daily = everydayOf(ctx.app.db, user); |
| 146 | 147 | return ` Note: this token belongs to ${user.username}, the forge's admin, so what you do here acts as admin.${ |
| 147 | 148 | daily === undefined |
| @@ -155,7 +156,7 @@ function adminNote(ctx: Ctx, user: User): string { | ||
| 155 | 156 | * it hides, and the two deliberate ways to them. Empty for anyone else. |
| 156 | 157 | */ |
| 157 | 158 | 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 ""; | |
| 159 | 160 | const hidden = TOOLS.filter((t) => t.needsAdminScope === true).map((t) => t.name); |
| 160 | 161 | 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.`; |
| 161 | 162 | } |
| @@ -249,7 +250,7 @@ function rpcOne( | ||
| 249 | 250 | ? listed.filter((t) => GUEST_TOOLS.includes(t.name)) |
| 250 | 251 | : ctx.auth.through === undefined |
| 251 | 252 | ? 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); | |
| 253 | 254 | // The cursor is the name of the last tool of the page before, so a tool |
| 254 | 255 | // added between two requests moves nothing. |
| 255 | 256 | const cursor = params["cursor"]; |
| @@ -312,13 +313,13 @@ function rpcOne( | ||
| 312 | 313 | : {}; |
| 313 | 314 | // An admin's tool stays out of an everyday account's list, and a call to |
| 314 | 315 | // 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); | |
| 316 | 317 | // Before the scope floor, so an admin tool the forge's agent was |
| 317 | 318 | // steered to is held as a confirm too, not merely refused (#7649), and |
| 318 | 319 | // one the person asked for waits for their yes (#7650). |
| 319 | 320 | // What the forge's own agent may never do is refused to it at once: never held, never a yes. |
| 320 | 321 | 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)); | |
| 322 | 323 | if (never !== undefined) |
| 323 | 324 | return reply({ content: [{ type: "text", text: `forbidden: ${never}` }], isError: true, hint: hintForCode("forbidden") }); |
| 324 | 325 | // Every argument is held to the tool's own schema, a read as a write, before anything is |
| @@ -328,7 +329,7 @@ function rpcOne( | ||
| 328 | 329 | const shapeRead = |
| 329 | 330 | tool !== undefined && |
| 330 | 331 | 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)); | |
| 332 | 333 | const wrongArg = shapeRead ? badArgument(tool.inputSchema, args) : undefined; |
| 333 | 334 | if (tool !== undefined && wrongArg !== undefined) |
| 334 | 335 | return reply({ |
| @@ -339,7 +340,7 @@ function rpcOne( | ||
| 339 | 340 | // A write the tool would refuse this person anyway is answered as refused now, in its own |
| 340 | 341 | // words, and never held for a yes that could only fail. |
| 341 | 342 | 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); | |
| 343 | 344 | const refused = askable ? tool.refusesFirst?.(ctx, user, args) : undefined; |
| 344 | 345 | // A tool listed to admins alone refuses everyone else in `run`: it runs to that refusal, |
| 345 | 346 | // unheld. |
| @@ -356,7 +357,7 @@ function rpcOne( | ||
| 356 | 357 | if (held !== undefined) return reply(held); |
| 357 | 358 | if (tool === undefined || !visible(tool, ctx, user)) |
| 358 | 359 | 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)) | |
| 360 | 361 | return reply({ |
| 361 | 362 | content: [ |
| 362 | 363 | { type: "text", text: READ_ONLY_REFUSAL }, |
| @@ -613,7 +614,7 @@ async function gatedShortcut(ctx: Ctx, user: User, id: unknown, tool: ToolShape, | ||
| 613 | 614 | const reply = (result: unknown) => ({ jsonrpc: "2.0", id, result }); |
| 614 | 615 | const held = askedFirst(ctx, user, tool, args) ?? heldWrite(ctx, user, tool, args); |
| 615 | 616 | if (held !== undefined) return reply(held); |
| 616 | if (!scopeAllows(ctx.auth.scope ?? "ro", "rw")) | |
| 617 | if (!mayToolWrite(ctx, tool.name)) | |
| 617 | 618 | return reply({ content: [{ type: "text", text: READ_ONLY_REFUSAL }], isError: true, hint: hintForCode("forbidden") }); |
| 618 | 619 | const via = ctx.auth.through; |
| 619 | 620 | if (via !== 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", () => { | ||
| 154 | 154 | test("the forge-wide actions follow the roles table", () => { |
| 155 | 155 | const can = (who: string | undefined, scope?: "ro" | "rw" | "admin") => capabilities(app.db, scope === undefined ? principalOfUser(as(who)) : bearer(as(who), scope)); |
| 156 | 156 | 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"]); | |
| 159 | 159 | expect(can("boss")).toContain("forge.administer"); |
| 160 | 160 | expect(can("nina")).not.toContain("forge.administer"); |
| 161 | 161 | expect(can("boss", "ro")).toEqual(["forge.read"]); |
| @@ -171,7 +171,7 @@ const get = async (path: string, who?: string) => { | ||
| 171 | 171 | |
| 172 | 172 | test("GET /api/v1/user lists what the caller may do, by the registry's names", async () => { |
| 173 | 173 | 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"]); | |
| 175 | 175 | expect((await get("/api/v1/user", "wes:ro")).body["can"]).toEqual(["forge.read"]); |
| 176 | 176 | }); |
| 177 | 177 |
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", () => { | ||
| 66 | 66 | expect(guest).toContain("You are guest here."); |
| 67 | 67 | expect(guest).toContain("Create a repository or copy an app: no"); |
| 68 | 68 | // 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"); | |
| 70 | 70 | setMember(forge.db, getUserByName(forge.db, "bob")!.id, true, "x", new Date()); |
| 71 | 71 | const member = await shown("bob"); |
| 72 | 72 | expect(member).toContain("You are member here."); |
new above
offline