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

Access 4: one view of every grant, and a page that says who may do what #18062

opened this in answer to

Merged 7h 59m ago, live in production

mason/forge:mason/18050-access-4-one-view-of-every-grant-and-a-p → main 0 commits fork 4 threads · 4 unresolved

  • Merged. mason/18050-access-4-one-view-of-every-grant-and-a-p was merged into main as 5ba07c8.

Review

Sign in to review this change.
18 files changed +618 −41
docs/design/audit.md +1
@@ -166,6 +166,7 @@ Machine routes are not pages and have no entry: `/audit.csv`,
166166 - `/settings/cloud/audit` — `pages/cloud.ts` · what the cloud connection did · `/audit` (different subject, same word) · none seen.
167167 - `/cloud/connect` — `pages/cloud.ts` · connect a cloud in a minute, guided, one provider at a time · `/settings/cloud` (every key; this is the front door) · none seen.
168168 - `/settings/access` — `pages/access.ts` · who may reach the forge · `/settings/people`, `/settings/accounts` · none seen.
169 - `/settings/who-can` — `pages/who-can.ts` · every grant that lets someone do something, in one read-only list, by person or by app · `/settings/access`, `/settings/grants` · none seen.
169170 - `/settings/captain` — `pages/captain.ts` · what Talk remembers and the check-ins it posts · `/talk` · none seen.
170171
171172 ### Sign-in and account
docs/features/who-can.md added +16
@@ -0,0 +1,16 @@
1 ---
2 topic: Every setting, by topic
3 row: Who may do what
4 ---
5 # Who may do what
6
7 One read over every table that holds a grant, in one shape: who, what they may do (an action or a role), on what, who granted it and when, and the page where it is changed. A table that does not record who granted it, or when, says "not recorded". It reads `member`, `team_member`, `app_member`, `game_grant`, `model_grant`, `subscription_grant`, `secret_grant`, `egress_grant`, `device_grant`, `child_reach_grant`, `origin_read_grant`, `pull_run_grant`, `telemetry_grant`, `client_cloud_member`, `crew_team_member` and `share` (`src/core/grants_view.ts`, the one reader). It changes no access: nothing here grants or revokes.
8
9 - **Web:** Settings → Who may do what (`/settings/who-can`). A person sees their role, what the role alone lets them do, and every grant they hold. A forge admin sees every grant, and can look up a person (all they can reach, with their role) or a resource (everyone who reaches it; an app is `owner/name`, and what that app itself is granted is listed too). Each row links to where it is changed.
10 - **MCP:** the `access` tool with `action: "grants"` and optional `person` or `resource` (a forge admin's).
11 - **Terminal:** `forge tui`, the palette entry "Who may do what": your own, or as an admin `p` a person, `r` a resource, `c` clear.
12 - Rules (`src/actions/grants_view.ts`): anyone else asking for another person's or a resource's answers `not_found`.
13 - A new table named `*_grant` or `*_member` that the view does not read fails `test/grants-view.test.ts`: add its entry to `MAPPINGS` in `src/core/grants_view.ts`, with the names and the page to change it.
14 - Try it: sign in, open `/settings/who-can`; as admin add `?person=<name>` or `?resource=<owner>/<app>`.
15 - A person's own view, and a resource look-up, are filtered in the database and each table is capped at 2000 rows. A link that is not a path on this forge is shown as `/settings`.
outdated

Names test/grants-view.test.ts and SOURCES in grants_view.ts, but this page reads grants_read.ts and is tested in test/grants-read.test.ts. Make it true once there is one reader.

16 - Tests: `test/grants-view.test.ts` (the view and the gate), `test/who-can.test.ts` (the rules, and the same rows on every door).
scripts/unreached-allow.json +1 −2
@@ -1,6 +1,5 @@
11 [
22 "src/apps/room.ts",
33 "src/spawn/pod.ts",
4 "src/maintain/lockfiles.ts",
5 "src/core/grants_view.ts"
4 "src/maintain/lockfiles.ts"
65 ]
scripts/unused-exports-allow.json +1 −2
@@ -185,6 +185,5 @@
185185 "src/spawn/machines.ts forgetMachines",
186186 "src/spawn/machines.ts registerMachine",
187187 "src/spawn/routes.ts forgetRoutes",
188 "src/maintain/lockfiles.ts lockfileDependencies",
189 "src/core/grants_view.ts everyGrant"
188 "src/maintain/lockfiles.ts lockfileDependencies"
190189 ]
src/actions/grants_view.ts added +56
@@ -0,0 +1,56 @@
1 /**
2 * Who may do what (#18050): one read over every grant table (`core/grants_view.ts`) and the role
3 * baseline (`core/roles.ts`). A forge admin reads anyone's, or everything on one resource, or all
4 * of it; every other account, an agent included, reads only its own, and asking for more answers
5 * `not_found`, as a missing account does. Reads only: nothing here grants or revokes.
6 */
7
8 import type { App } from "../app.ts";
9 import { everyGrant, type Grant } from "../core/grants_view.ts";
10 import { ABILITIES, CAN, roleOf, type Role } from "../core/roles.ts";
11 import { getUserByName, type User } from "../core/users.ts";
12 import { err, ok, type Result } from "../kernel/result.ts";
13
14 /** An account and what its role gives it before any grant. */
15 export interface Standing {
16 readonly name: string;
17 readonly role: Role;
18 /** What the role lets it do, in words. */
19 readonly can: readonly string[];
20 }
21
22 export interface GrantsView {
23 /** "self", "person" and "resource" narrow it; "all" is every grant, an admin's. */
24 readonly scope: "self" | "person" | "resource" | "all";
25 readonly standing?: Standing;
26 readonly grants: readonly Grant[];
27 }
28
29 export interface GrantsQuery {
30 readonly person?: string;
31 readonly resource?: string;
32 }
33
34 const MAX_NAME = 200;
35
36 function standingOf(app: App, user: { id: string; username: string; isAdmin: boolean }): Standing {
37 const role = roleOf(app.db, user);
38 return { name: user.username, role, can: CAN[role].map((a) => ABILITIES[a]) };
39 }
40
41 const isAdmin = (u: User): boolean => u.isAdmin && u.kind !== "agent";
42
43 export function whoMayDoWhat(app: App, actor: User | undefined, query: GrantsQuery = {}): Result<GrantsView, "not_found"> {
44 if (actor === undefined) return err("not_found");
45 const person = (query.person ?? "").trim().slice(0, MAX_NAME);
46 const resource = (query.resource ?? "").trim().slice(0, MAX_NAME);
47 const own = (): GrantsView => ({ scope: "self", standing: standingOf(app, actor), grants: everyGrant(app.db, actor.id) });
48 if (person === "" && resource === "") return ok(isAdmin(actor) ? { scope: "all", standing: standingOf(app, actor), grants: everyGrant(app.db) } : own());
49 if (!isAdmin(actor)) return person.toLowerCase() === actor.username.toLowerCase() && resource === "" ? ok(own()) : err("not_found");
50 if (person !== "") {
51 const found = getUserByName(app.db, person);
52 if (found === undefined) return err("not_found");
53 return ok({ scope: "person", standing: standingOf(app, found), grants: everyGrant(app.db, found.id) });
54 }
55 return ok({ scope: "resource", grants: everyGrant(app.db, undefined, resource) });
56 }
src/core/grants_view.ts +110 −36
@@ -10,10 +10,13 @@
1010 * was deleted, or the column was empty). A table that does not exist yet (`client_cloud_member` is
1111 * made on first use) lists nothing.
1212 *
13 * Each row also carries what a person reads: `who` and `on` by name (a username, `owner/app`),
14 * `byName`, and `href`, the page where the grant is changed. The "Who may do what" page, MCP tool
15 * and terminal screen (#18050) read this and nothing else.
16 *
1317 * `GRANT_TABLES` is the whole list; `test/grants-view.test.ts` fails when a table whose name ends
14 * in `_grant` or `_member` is declared under `src/` and is not in it. Changes no access. Its
15 * readers are the "Who may do what" page (#18105) and its MCP tool and terminal screen (#18106),
16 * not yet built; until then nothing under `src/` imports this module.
18 * in `_grant` or `_member` is declared under `src/` and is not in it. Changes no access. Filters
19 * (an account, a resource) and the row cap are in the SQL, so a narrow ask reads only its rows.
1720 */
1821
1922 import type { Database } from "bun:sqlite";
@@ -29,6 +32,14 @@ export interface Grant {
2932 resource: { kind: string; id: string };
3033 grantedBy: string | null | NotRecorded;
3134 at: string | null | NotRecorded;
35 /** The principal by name; "someone who is gone" when it no longer exists. */
36 who: string;
37 /** The resource by name; "something that is gone" when it no longer exists. */
38 on: string;
39 /** The granter by name (or the raw id when it is not an account). */
40 byName: string | null | NotRecorded;
41 /** The page where the grant is changed: a path on this forge, never another host. */
42 href: string;
3243 }
3344
3445 /**
@@ -46,39 +57,78 @@ interface Mapping {
4657 by?: string;
4758 at?: string;
4859 account?: string;
60 /** Names for a person: the principal, the resource, and the page where it is changed. */
61 who: string;
62 on: string;
63 href: string;
4964 }
5065
66 const NAME = (id: string): string => `(SELECT username FROM user WHERE id = ${id})`;
67 const REPO = (id: string): string =>
68 `(SELECT o.username || '/' || r.name FROM repo r JOIN user o ON o.id = r.owner_id WHERE r.id = ${id})`;
69 const APP = (id: string): string =>
70 `(SELECT o.username || '/' || r.name FROM app a JOIN repo r ON r.id = a.repo_id JOIN user o ON o.id = r.owner_id WHERE a.id = ${id})`;
71 const TEAM = (what: string): string => `(SELECT ${what} FROM team t WHERE t.id = team_id)`;
72 const PULL = (between: string): string =>
73 `(SELECT ${REPO("i.repo_id")} || '${between}' || i.number FROM issue i WHERE i.id = issue_id)`;
74 const OR = (name: string, fallback: string): string => `COALESCE(${name}, ${fallback})`;
75
5176 const text = (word: string): string => `'${word}'`;
5277
5378 const MAPPINGS: readonly Mapping[] = [
54 { table: "member", principalKind: text("user"), principalId: "user_id", action: text("member"), resourceKind: text("forge"), resourceId: "''", by: "promoted_by", at: "promoted_at", account: "user_id" },
55 { table: "team_member", principalKind: text("user"), principalId: "user_id", action: "role", resourceKind: text("team"), resourceId: "team_id", account: "user_id" },
56 { table: "app_member", principalKind: text("user"), principalId: "user_id", action: text("enter"), resourceKind: text("app"), resourceId: "app_id", by: "added_by", at: "added_at", account: "user_id" },
57 { table: "game_grant", principalKind: text("user"), principalId: "user_id", action: "role", resourceKind: text("game box"), resourceId: "box_id || CASE WHEN service = '' THEN '' ELSE '/' || service END", account: "user_id" },
58 { table: "model_grant", principalKind: text("user"), principalId: "user_id", action: "'use models, $' || printf('%g', usd_per_month) || ' a month'", resourceKind: text("forge"), resourceId: "''", by: "granted_by", at: "granted_at", account: "user_id" },
59 { table: "subscription_grant", principalKind: "CASE WHEN agent_id = '' THEN 'scope' ELSE 'agent' END", principalId: "CASE WHEN agent_id = '' THEN scope_id ELSE agent_id END", action: text("spend"), resourceKind: text("subscription"), resourceId: "subscription_id", account: "NULLIF(agent_id, '')" },
60 { table: "secret_grant", principalKind: text("repo"), principalId: "repo_id", action: text("read secret"), resourceKind: "scope || ' secret'", resourceId: "CASE WHEN scope_id = '' THEN name ELSE scope_id || '/' || name END", by: "granted_by", at: "granted_at" },
61 { table: "egress_grant", principalKind: text("repo"), principalId: "repo_id", action: text("reach"), resourceKind: text("host"), resourceId: "destination", by: "granted_by", at: "granted_at" },
62 { table: "device_grant", principalKind: text("device"), principalId: "CAST(device_id AS TEXT)", action: "'post, ' || daily_cap || ' a day'", resourceKind: text("app"), resourceId: "app_id", by: "granted_by", at: "granted_at" },
63 { table: "child_reach_grant", principalKind: text("hosted forge"), principalId: "CASE WHEN child = '' THEN body_id ELSE child END", action: text("reach"), resourceKind: text("host"), resourceId: "host || ':' || port", by: "granted_by", at: "granted_at" },
64 { table: "origin_read_grant", principalKind: "kind", principalId: "grantee_id", action: text("read"), resourceKind: text("repo"), resourceId: "repo_id", by: "granted_by", at: "created_at", account: "CASE WHEN kind = 'crew' THEN grantee_id END" },
65 { table: "pull_run_grant", principalKind: text("pull"), principalId: "issue_id", action: text("run"), resourceKind: text("commit"), resourceId: "commit_oid", by: "user_id", at: "granted_at" },
66 { table: "telemetry_grant", principalKind: text("user"), principalId: "user_id", action: text("read telemetry"), resourceKind: text("forge"), resourceId: "''", by: "granted_by", at: "granted_at", account: "user_id" },
67 { table: "client_cloud_member", principalKind: text("user"), principalId: "user_id", action: text("look"), resourceKind: text("client cloud"), resourceId: "cloud_id", by: "granted_by", at: "granted_at", account: "user_id" },
68 { table: "crew_team_member", principalKind: text("user"), principalId: "user_id", action: text("member"), resourceKind: text("crew team"), resourceId: "team_slug", account: "user_id" },
69 { table: "share", principalKind: text("user"), principalId: "recipient_id", action: "'receive, ' || state", resourceKind: "kind", resourceId: "item_id", by: "sender_id", at: "created_at", account: "recipient_id" },
79 { table: "member", principalKind: text("user"), principalId: "user_id", action: text("member"), resourceKind: text("forge"), resourceId: "''", by: "promoted_by", at: "promoted_at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: text("this forge"), href: text("/settings/people") },
80 { table: "team_member", principalKind: text("user"), principalId: "user_id", action: "role", resourceKind: text("team"), resourceId: "team_id", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: OR(TEAM(`${NAME("t.org_id")} || '/' || t.name`), "team_id"), href: OR(TEAM(`'/' || ${NAME("t.org_id")} || '/-/teams/' || t.id`), text("/settings")) },
81 { table: "app_member", principalKind: text("user"), principalId: "user_id", action: text("enter"), resourceKind: text("app"), resourceId: "app_id", by: "added_by", at: "added_at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: OR(APP("app_id"), "app_id"), href: OR(`'/' || ${APP("app_id")} || '/settings'`, text("/settings")) },
82 { table: "game_grant", principalKind: text("user"), principalId: "user_id", action: "role", resourceKind: text("game box"), resourceId: "box_id || CASE WHEN service = '' THEN '' ELSE '/' || service END", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: `COALESCE((SELECT name FROM game_box WHERE id = box_id), box_id) || CASE WHEN service = '' THEN '' ELSE '/' || service END`, href: text("/games") },
83 { table: "model_grant", principalKind: text("user"), principalId: "user_id", action: "'use models, $' || printf('%g', usd_per_month) || ' a month'", resourceKind: text("forge"), resourceId: "''", by: "granted_by", at: "granted_at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: text("the forge''s models"), href: text("/settings/people") },
84 { table: "subscription_grant", principalKind: "CASE WHEN agent_id = '' THEN 'scope' ELSE 'agent' END", principalId: "CASE WHEN agent_id = '' THEN scope_id ELSE agent_id END", action: text("spend"), resourceKind: text("subscription"), resourceId: "subscription_id", account: "NULLIF(agent_id, '')", who: `CASE WHEN agent_id = '' THEN COALESCE(${REPO("scope_id")}, '@' || ${NAME("scope_id")}, 'a place that is gone') ELSE COALESCE(${NAME("agent_id")}, agent_id) END`, on: OR("(SELECT name FROM subscription WHERE id = subscription_id)", "subscription_id"), href: text("/settings/subscriptions") },
85 { table: "secret_grant", principalKind: text("repo"), principalId: "repo_id", action: text("read secret"), resourceKind: "scope || ' secret'", resourceId: "CASE WHEN scope_id = '' THEN name ELSE scope_id || '/' || name END", by: "granted_by", at: "granted_at", who: OR(REPO("repo_id"), "repo_id"), on: "name", href: text("/settings/secrets") },
86 { table: "egress_grant", principalKind: text("repo"), principalId: "repo_id", action: text("reach"), resourceKind: text("host"), resourceId: "destination", by: "granted_by", at: "granted_at", who: OR(REPO("repo_id"), "repo_id"), on: "destination", href: OR(`'/' || ${REPO("repo_id")} || '/settings'`, text("/settings")) },
87 { table: "device_grant", principalKind: text("device"), principalId: "CAST(device_id AS TEXT)", action: "'post, ' || daily_cap || ' a day'", resourceKind: text("app"), resourceId: "app_id", by: "granted_by", at: "granted_at", who: OR("(SELECT name FROM device WHERE id = device_id)", "CAST(device_id AS TEXT)"), on: OR(APP("app_id"), "app_id"), href: text("/settings/devices") },
88 { table: "child_reach_grant", principalKind: text("hosted forge"), principalId: "CASE WHEN child = '' THEN body_id ELSE child END", action: text("reach"), resourceKind: text("host"), resourceId: "host || ':' || port", by: "granted_by", at: "granted_at", who: "CASE WHEN child = '' THEN body_id ELSE child END", on: "host || ':' || port", href: text("/settings/crew") },
89 { table: "origin_read_grant", principalKind: "kind", principalId: "grantee_id", action: text("read"), resourceKind: text("repo"), resourceId: "repo_id", by: "granted_by", at: "created_at", account: "CASE WHEN kind = 'crew' THEN grantee_id END", who: `CASE WHEN kind = 'app' THEN COALESCE(${APP("grantee_id")}, grantee_id) ELSE COALESCE(${NAME("grantee_id")}, grantee_id) END`, on: OR(REPO("repo_id"), "repo_id"), href: OR(`'/' || ${REPO("repo_id")} || '/settings#read-grants'`, text("/settings")) },
90 { table: "pull_run_grant", principalKind: text("pull"), principalId: "issue_id", action: text("run"), resourceKind: text("commit"), resourceId: "commit_oid", by: "user_id", at: "granted_at", who: OR(PULL(" #"), "issue_id"), on: "'commit ' || substr(commit_oid, 1, 8)", href: OR(`'/' || ${PULL("/pulls/")}`, text("/settings")) },
91 { table: "telemetry_grant", principalKind: text("user"), principalId: "user_id", action: text("read telemetry"), resourceKind: text("forge"), resourceId: "''", by: "granted_by", at: "granted_at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: text("this forge''s telemetry"), href: text("/settings/telemetry") },
92 { table: "client_cloud_member", principalKind: text("user"), principalId: "user_id", action: text("look"), resourceKind: text("client cloud"), resourceId: "cloud_id", by: "granted_by", at: "granted_at", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: OR("(SELECT label FROM client_cloud WHERE id = cloud_id)", "cloud_id"), href: text("/settings/cloud") },
93 { table: "crew_team_member", principalKind: text("user"), principalId: "user_id", action: text("member"), resourceKind: text("crew team"), resourceId: "team_slug", account: "user_id", who: OR(NAME("user_id"), "user_id"), on: OR("(SELECT name FROM crew_team WHERE slug = team_slug)", "team_slug"), href: text("/settings/crew") },
94 { table: "share", principalKind: text("user"), principalId: "recipient_id", action: "'receive, ' || state", resourceKind: "kind", resourceId: "item_id", by: "sender_id", at: "created_at", account: "recipient_id", who: OR(NAME("recipient_id"), "recipient_id"), on: `kind || ' in ' || COALESCE(${REPO("repo_id")}, repo_id)`, href: "link" },
7095 ];
7196
7297 /** Every table this view reads, in the order it lists them. */
7398 export const GRANT_TABLES: readonly string[] = MAPPINGS.map((m) => m.table);
7499
75 function select(m: Mapping, forAccount: boolean): string {
76 const where = forAccount ? ` WHERE ${m.account ?? "NULL"} = ?1` : "";
77 return `SELECT '${m.table}' AS tbl, ${m.principalKind} AS p_kind, ${m.principalId} AS p_id, ${m.action} AS action,
100 /** Most rows read from one table: the view is for looking, not an export. */
101 const PER_TABLE = 2000;
102
103 /** A path on this forge: one leading `/`, not `//` or `/\`, and no control characters or spaces. */
104 export function forgePath(href: string | null): string {
105 return href !== null && /^\/(?![/\\])[^\x00-\x20\x7f]*$/.test(href) ? href : "/settings";
106 }
107
108 /** `needle` as a LIKE pattern that matches it literally, anywhere in the text. */
109 const contains = (needle: string): string => `%${needle.toLowerCase().replace(/[\\%_]/g, "\\$&")}%`;
110
111 interface Ask {
112 /** Only grants held by this account. */
113 account?: string;
114 /** Only grants on a resource whose name contains this (or held by a non-account that does). */
115 resource?: string;
116 }
117
118 function select(m: Mapping, ask: Ask, params: { account: number; resource: number }): string {
119 const where: string[] = [];
120 if (ask.account !== undefined) where.push(`${m.account ?? "NULL"} = ?${params.account}`);
121 if (ask.resource !== undefined) {
122 const like = `LIKE ?${params.resource} ESCAPE '\\'`;
123 where.push(`(lower(${m.on}) ${like} OR (${m.account ?? "NULL"} IS NULL AND lower(${m.who}) ${like}))`);
124 }
125 return `SELECT * FROM (SELECT '${m.table}' AS tbl, ${m.principalKind} AS p_kind, ${m.principalId} AS p_id, ${m.action} AS action,
78126 ${m.resourceKind} AS r_kind, ${m.resourceId} AS r_id,
79127 ${m.by ?? "NULL"} AS g_by, ${m.by === undefined ? 0 : 1} AS g_by_kept,
80 ${m.at ?? "NULL"} AS g_at, ${m.at === undefined ? 0 : 1} AS g_at_kept
81 FROM ${m.table}${where}`;
128 ${m.by === undefined ? "NULL" : `COALESCE(${NAME(m.by)}, NULLIF(${m.by}, ''))`} AS g_by_name,
129 ${m.at ?? "NULL"} AS g_at, ${m.at === undefined ? 0 : 1} AS g_at_kept,
130 ${m.who} AS who, ${m.on} AS "on", ${m.href} AS href
131 FROM ${m.table}${where.length === 0 ? "" : ` WHERE ${where.join(" AND ")}`} LIMIT ${PER_TABLE})`;
82132 }
83133
84134 interface Row {
@@ -90,28 +140,52 @@ interface Row {
90140 r_id: string;
91141 g_by: string | null;
92142 g_by_kept: number;
143 g_by_name: string | null;
93144 g_at: string | null;
94145 g_at_kept: number;
146 who: string | null;
147 on: string | null;
148 href: string | null;
95149 }
96150
97151 /**
98152 * Every grant on this forge, or, given `account`, only those whose principal is that account (a
99 * person, or an agent named by its user id). An account with no grants lists none.
153 * person, or an agent named by its user id), or, given `resource`, only those on a resource whose
154 * name contains it. An account with no grants lists none. Sorted by who, then table, then what.
100155 */
101 export function everyGrant(db: Database, account?: string): Grant[] {
156 export function everyGrant(db: Database, account?: string, resource?: string): Grant[] {
102157 const present = new Set(
103158 db.query<{ name: string }, []>("SELECT name FROM sqlite_master WHERE type = 'table'").all().map((r) => r.name),
104159 );
160 const ask: Ask = {
161 ...(account === undefined ? {} : { account }),
162 ...(resource === undefined ? {} : { resource: contains(resource) }),
163 };
164 const params = { account: 1, resource: account === undefined ? 1 : 2 };
165 const bound = [ask.account, ask.resource].filter((v): v is string => v !== undefined);
105166 const mappings = MAPPINGS.filter((m) => present.has(m.table) && (account === undefined || m.account !== undefined));
106167 if (mappings.length === 0) return [];
107 const sql = mappings.map((m) => select(m, account !== undefined)).join("\nUNION ALL\n");
108 const rows = account === undefined ? db.query<Row, []>(sql).all() : db.query<Row, [string]>(sql).all(account);
109 return rows.map((r) => ({
110 table: r.tbl,
111 principal: { kind: r.p_kind, id: r.p_id },
112 action: r.action,
113 resource: { kind: r.r_kind, id: r.r_id },
114 grantedBy: r.g_by_kept ? r.g_by : NOT_RECORDED,
115 at: r.g_at_kept ? r.g_at : NOT_RECORDED,
116 }));
168 const sql = mappings.map((m) => select(m, ask, params)).join("\nUNION ALL\n");
169 const rows = db.query<Row, string[]>(sql).all(...bound);
170 return rows
171 .map((r) => ({
172 table: r.tbl,
173 principal: { kind: r.p_kind, id: r.p_id },
174 action: r.action,
175 resource: { kind: r.r_kind, id: r.r_id },
176 grantedBy: r.g_by_kept ? r.g_by : NOT_RECORDED,
177 at: r.g_at_kept ? r.g_at : NOT_RECORDED,
178 who: r.who ?? "someone who is gone",
179 on: r.on ?? "something that is gone",
180 byName: r.g_by_kept ? r.g_by_name : NOT_RECORDED,
181 href: forgePath(r.href),
182 }))
183 .sort((a, b) => a.who.localeCompare(b.who) || a.table.localeCompare(b.table) || a.on.localeCompare(b.on));
184 }
185
186 /** Who granted it and when, as one muted line; "not recorded" where the table keeps no column. */
187 export function provenance(g: Grant): string {
188 const by = g.byName === NOT_RECORDED ? "granted by: not recorded" : g.byName === null ? "granted by: no one now" : `granted by ${g.byName}`;
189 const at = typeof g.at === "string" ? g.at.slice(0, 10) : g.at === null ? "no date" : "date not recorded";
190 return `${by} · ${at}`;
117191 }
src/generated/screens.ts +2
@@ -135,6 +135,7 @@ import * as s130 from "../tui/screens/waiting.ts";
135135 import * as s131 from "../tui/screens/waiting_for_me.ts";
136136 import * as s132 from "../tui/screens/wayback.ts";
137137 import * as s133 from "../tui/screens/weekcard.ts";
138 import * as s134 from "../tui/screens/whocan.ts";
138139
139140 /** Each screen file that declares palette entries: its module and the export names. */
140141 export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readonly string[]])[] = [
@@ -272,4 +273,5 @@ export const SCREEN_MODULES: readonly (readonly [Record<string, unknown>, readon
272273 [s131, ["entry"]],
273274 [s132, ["entry"]],
274275 [s133, ["entry"]],
276 [s134, ["entry"]],
275277 ];
src/http/lazy_lists.ts +1
@@ -115,6 +115,7 @@ export const SETTINGS_ROUTES = [
115115 ["POST", "/settings/cloud/rename"],
116116 ["POST", "/settings/cloud/remove"],
117117 ["GET", "/settings/access"],
118 ["GET", "/settings/who-can"],
118119 ["GET", "/settings/resilience"],
119120 ["GET", "/settings/hosted-forges"],
120121 ["POST", "/settings/hosted-forges/reach"],
src/http/marks/settings.json +1
@@ -19,6 +19,7 @@
1919 "/settings/runners/lending/:id/resume": "open",
2020 "/settings/telemetry": "admin",
2121 "/settings": "open",
22 "/settings/who-can": "open",
2223 "/settings/notify": "open",
2324 "/settings/focus": "open",
2425 "/settings/dotfiles": "open",
src/http/mcp/tools/access.ts +14 −1
@@ -1,15 +1,19 @@
11 import { listAccess } from "../../../actions/access_log.ts";
2 import { whoMayDoWhat } from "../../../actions/grants_view.ts";
23 import { good, bad, type Tool } from "../shared.ts";
34
45 export const tool: Tool = {
56 name: "access",
67 listedTo: "admin",
7 doc: "`{ since?, ua?, path? }`: what outside agents tried: the redacted log of non-browser requests to public paths, newest first; `since` an ISO time (default a day, at most 14 days), `ua` part of the user agent, `path` a prefix; a forge admin's",
8 doc: "`{ action?: \"grants\", person?, resource? }`: with `grants`, who may do what: every grant in every table, or one person's (with their role), or everyone who reaches a resource; else `{ since?, ua?, path? }`: what outside agents tried: the redacted log of non-browser requests to public paths, newest first; `since` an ISO time (default a day, at most 14 days), `ua` part of the user agent, `path` a prefix; a forge admin's",
89 description:
910 "Non-browser public-path requests, redacted, newest first (max 500). Forge admin.",
1011 inputSchema: {
1112 type: "object",
1213 properties: {
14 action: { type: "string", enum: ["log", "grants"] },
15 person: { type: "string", maxLength: 200 },
16 resource: { type: "string", maxLength: 200 },
1317 since: { type: "string", maxLength: 40 },
1418 ua: { type: "string", maxLength: 100 },
1519 path: { type: "string", maxLength: 200 },
@@ -19,6 +23,15 @@ export const tool: Tool = {
1923 run(ctx, user, args) {
2024 const text = (k: string): string | undefined =>
2125 typeof args[k] === "string" && args[k] !== "" ? (args[k] as string) : undefined;
26 if (args.action === "grants") {
27 const person = text("person");
28 const resource = text("resource");
29 const asked = whoMayDoWhat(ctx.app, user, {
30 ...(person === undefined ? {} : { person }),
31 ...(resource === undefined ? {} : { resource }),
32 });
33 return asked.ok ? good(asked.value) : bad("not_found", "no such person here");
34 }
2235 const since = text("since");
2336 const ua = text("ua");
2437 const path = text("path");
src/http/settings_routes.ts +2
@@ -14,6 +14,7 @@ import type { Handler } from "./context.ts";
1414 import type { Router } from "./router.ts";
1515 import { parentLinkStart } from "./rp.ts";
1616 import { accessPage } from "../web/pages/access.ts";
17 import { whoCanPage } from "../web/pages/who-can.ts";
1718 import { knobSet } from "../web/pages/knobs.ts";
1819 import { capacityPage, capacitySet } from "../web/pages/capacity.ts";
1920 import { teamPage, teamSet, teamsPage, teamsStream } from "../web/pages/teams.ts";
@@ -267,6 +268,7 @@ export function settingsRoutes(router: Router<Handler>, knownPatterns: () => rea
267268 router.add("POST", "/settings/cloud/rename", cloudRename);
268269 router.add("POST", "/settings/cloud/remove", cloudRemove);
269270 router.add("GET", "/settings/access", accessPage);
271 router.add("GET", "/settings/who-can", whoCanPage);
270272 router.add("GET", "/settings/resilience", domainsMoved);
271273 // What the forges hosted here may reach, and the asks they sent (`web/pages/hosted-forges.ts`).
272274 router.add("GET", "/settings/hosted-forges", hostedForgesPage);
src/tui/screens/whocan.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * Who may do what, in the terminal (#18050): `/settings/who-can`'s list from the same action
3 * (`actions/grants_view.ts`): your role and every grant you hold; a forge admin's `p` looks up a
4 * person, `r` everyone who reaches a resource, `c` clears back to all of it. Each row says who may
5 * do what on what, who granted it and when ("not recorded" where the table does not say), and the
6 * page where it is changed.
7 */
8
9 import { whoMayDoWhat, type GrantsView } from "../../actions/grants_view.ts";
10 import { provenance } from "../../core/grants_view.ts";
11 import type { Ctx, Screen } from "../app/app.ts";
12 import { binding } from "../app/keys.ts";
13 import type { Session } from "../session.ts";
14 import { style } from "../term/style.ts";
15 import { truncate } from "../term/width.ts";
16 import { fill, len, split } from "../ui/layout.ts";
17 import { ListState, drawList, promptScreen, type ListRow } from "./common.ts";
18 import type { PaletteEntry } from "./entries.ts";
19
20 const MAX = 200;
21
22 export function whoCanScreen(f: Session, ctx: Ctx): Screen {
23 const state = new ListState();
24 const filter: { person?: string; resource?: string } = {};
25 const admin = f.user?.isAdmin === true && f.user.kind !== "agent";
26
27 const view = (): GrantsView | undefined => {
28 const asked = whoMayDoWhat(f.app, f.user, filter);
29 return asked.ok ? asked.value : undefined;
30 };
31
32 const ask = (key: "person" | "resource"): void => {
33 ctx.push(
34 promptScreen(ctx, screen, {
35 title: key === "person" ? "A person" : "A resource",
36 label: key === "person" ? "username" : "owner/app, a host, a secret",
37 value: filter[key] ?? "",
38 onSubmit: (raw) => {
39 const value = raw.trim().slice(0, MAX);
40 if (key === "person") delete filter.resource;
41 else delete filter.person;
42 if (value === "") delete filter[key];
43 else filter[key] = value;
44 if (value !== "" && view() === undefined) {
45 delete filter[key];
46 return "no such person";
47 }
48 state.clamp(view()?.grants.length ?? 0);
49 ctx.invalidate();
50 return undefined;
51 },
52 }),
53 );
54 };
55
56 const screen: Screen = {
57 title: "Who may do what",
58 keys: [
59 binding(["j", "k"], "move cursor"),
60 ...(admin ? [binding(["p"], "a person"), binding(["r"], "a resource"), binding(["c"], "clear")] : []),
61 ],
62 render(area, s) {
63 const c = ctx.theme.c;
64 const [head, list] = split(area, "v", [len(2), fill(1)]);
65 const v = view();
66 const standing = v?.standing;
67 const said =
68 standing === undefined
69 ? "Everyone who reaches that resource."
70 : `${standing.name} is ${standing.role === "admin" ? "an admin" : `a ${standing.role}`}; the role alone lets them: ${standing.can.join("; ")}.`;
71 s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
72 const count = v?.grants.length ?? 0;
73 s.text(head!.x, head!.y + 1, truncate(count === 0 ? "No grants match." : `${count} grant${count === 1 ? "" : "s"}`, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
74 const rows: ListRow[] = (v?.grants ?? []).map((g) => ({
75 title: `${g.who} · ${g.action}`,
76 secondary: `${g.on} (${g.resource.kind})`,
77 meta: `${provenance(g)} · change at ${g.href}`,
78 }));
79 drawList(s, list!, c, state, rows);
80 },
81 key(e) {
82 if (state.key(e, view()?.grants.length ?? 0)) return true;
83 if (e.ctrl || e.alt || !admin) return false;
84 if (e.key === "p") ask("person");
85 else if (e.key === "r") ask("resource");
86 else if (e.key === "c") {
87 delete filter.person;
88 delete filter.resource;
89 ctx.invalidate();
90 } else return false;
91 return true;
92 },
93 };
94 return screen;
95 }
96
97 /**
98 * What the settings page "Who may do what" says, for anyone signed in: their own, or all as admin.
99 */
100 export const entry: PaletteEntry = {
101 rank: 352,
102 id: "who-can",
103 title: "Who may do what",
104 hint: "your role and every grant you hold",
105 after: ["access"],
106 offered: (session) => session.user !== undefined,
107 run: (session, ctx) => ctx.push(whoCanScreen(session, ctx)),
108 };
src/web/pages/access.ts +1
@@ -50,6 +50,7 @@ export function accessPage(ctx: Ctx): Response {
5050 Tokens, cookies and query strings are never kept; the hash stands for one
5151 caller for one day.
5252 </p>
53 <p class="small"><a href="/settings/who-can">Who may do what</a>: what each account and app can reach, and where to change it.</p>
5354 <form class="row-fields" method="get" action="/settings/access">
5455 <input
5556 class="input"
src/web/pages/who-can.ts added +67
@@ -0,0 +1,67 @@
1 /**

Design 1: the title, the h2 and two paragraphs say the same thing; keep one head and one sentence. Design 7: a six-column dense table with the table name beside every link is not rows over boxes. Design 8: plain words.

2 * Who may do what (#18050): every grant in one list (`core/grants_view.ts`), each row linking to
3 * where it is changed. A person sees their own role and grants; a forge admin may also look up a
4 * person, or everyone who reaches a resource. The rules are `actions/grants_view.ts`'s; this draws.
5 */
6
7 import { sshOn } from "../../settings/ssh.ts";
8 import { whoMayDoWhat, type GrantsView } from "../../actions/grants_view.ts";
9 import { provenance, type Grant } from "../../core/grants_view.ts";
10 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
11 import type { Ctx } from "../../http/context.ts";
12 import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts";
13 import { html, type Html } from "../html.ts";
14 import { page } from "../layout.ts";
15 import { btn, row as uiRow, rowList } from "../ui.ts";
16 import { accountSections } from "./origins.ts";
17
18 const row = (g: Grant): Html =>
19 uiRow({
20 nav: true,
21 href: g.href,
22 title: html`${g.who} · ${g.action}`,
23 meta: html`${g.on} (${g.resource.kind}) · ${provenance(g)}`,
24 });
25
26 /** The one sentence the page opens with. */
27 function said(view: GrantsView, resource: string): string {
28 const s = view.standing;
29 if (s !== undefined && view.scope !== "all") return `${s.name} is ${s.role === "admin" ? "an admin" : `a ${s.role}`}, which alone lets them: ${s.can.join("; ")}. Everything else is a grant below.`;
30 if (view.scope === "resource") return `Everyone who reaches ${resource}, and what that grants them.`;
31 return "Every grant on this forge, who holds it and where to change it.";
32 }
33
34 // GET /settings/who-can
35 export function whoCanPage(ctx: Ctx): Response {
36 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
37 if (!ctx.auth.user) return signInFirst(ctx);
38 const user = ctx.auth.user;
39 const person = ctx.url.searchParams.get("person")?.slice(0, 200) ?? "";
40 const resource = ctx.url.searchParams.get("resource")?.slice(0, 200) ?? "";
41 const asked = timePhase(ctx.request, "grants", () => whoMayDoWhat(ctx.app, user, { person, resource }));
42 if (!asked.ok) return notFoundPage(ctx);
43 const view = asked.value;
44 const admin = user.isAdmin && user.kind !== "agent";
45 const body = html`<section class="settings-block" id="who-can">
46 <p class="muted">${said(view, resource)}</p>
47 ${admin
48 ? html`<form class="row-fields" method="get" action="/settings/who-can">
49 <input class="input" name="person" value="${person}" placeholder="A person's username" aria-label="A person's username" />
50 <input class="input mono" name="resource" value="${resource}" placeholder="owner/app, a host, a secret…" aria-label="A resource" />
51 ${btn("Look up", { size: "sm", variant: "primary" })}
52 </form>`
53 : html``}
54 ${view.grants.length === 0
55 ? html`<p class="muted small" id="who-can-none">No grants match.</p>`
56 : html`<div id="who-can-list">${rowList(view.grants.map(row), { bare: true, label: "Grants" })}</div>`}
57 </section>`;
58 const rendering = performance.now();
59 const response = page({
60 ctx,
61 title: "Who may do what",
62 body: html`${pageHead("Who may do what")}
63 ${settingsLayout(accountSections("access", { admin, ssh: sshOn(ctx.app.db) }), body, "Account settings")}`,
64 });
65 notePhase(ctx.request, "render", performance.now() - rendering);
66 return response;
67 }
test/grants-view.test.ts +1
@@ -54,6 +54,7 @@ describe("the grants view", () => {
5454 expect(of("member")).toEqual({
5555 table: "member", principal: { kind: "user", id: "ann" }, action: "member",
5656 resource: { kind: "forge", id: "" }, grantedBy: "root", at: AT,
57 who: "ann", on: "this forge", byName: "root", href: "/settings/people",
5758 });
5859 expect(of("team_member")).toMatchObject({ action: "builder", resource: { kind: "team", id: "t1" }, grantedBy: notRecorded, at: notRecorded });
5960 expect(of("game_grant")).toMatchObject({ action: "player", resource: { kind: "game box", id: "box1/web" }, grantedBy: notRecorded });
test/keymap-terminal.test.ts +1
@@ -25,6 +25,7 @@ const OWN_R: Record<string, string> = {
2525 "src/tui/screens/about.ts": "make … the reviewer",
2626 "src/tui/screens/account_access.ts": "reset access",
2727 "src/tui/screens/agents.ts": "roles",
28 "src/tui/screens/whocan.ts": "a resource",
2829 "src/tui/screens/autonomy.ts": "reviewer",
2930 "src/tui/screens/cloud.ts": "rotate",
3031 "src/tui/screens/conflicts.ts": "look at the crew's proposal",
test/palette-roster.test.ts +3
@@ -182,6 +182,7 @@ test("a site-admin person is offered the whole roster", () => {
182182 ["stalled", "Stalled steps", "pulls whose check is red or was never asked for; enter re-runs"],
183183 ["file-holds", "Held files", "hold new work on a file, release it, or list the holds"],
184184 ["access", "Access", "what outside agents tried"],
185 ["who-can", "Who may do what", "your role and every grant you hold"],
185186 ["flags", "Flags", "declared flags and their live values"],
186187 ["secrets", "Secrets", "sealed secrets by name; set or remove one"],
187188 ["trusted-hosts", "Trusted hosts", "internal hosts an origin may reach"],
@@ -363,6 +364,7 @@ test("a site-admin agent is offered the roster without the person-only entries",
363364 ["traces", "Traces", "every crew run, newest first"],
364365 ["buckets", "Buckets", "an object bucket's price a month, and binding it to an app"],
365366 ["maintenance-runs", "Maintenance duty runs", "what each duty found, did and probed"],
367 ["who-can", "Who may do what", "your role and every grant you hold"],
366368 ["traffic-sources", "Traffic sources", "where people come from and where they go, for the forge"],
367369 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
368370 ["spend", "Spend", "what the crew's runs spent, by credential, app, agent, issue and kind"],
@@ -495,6 +497,7 @@ test("a member person is offered the signed-in roster without the admin entries"
495497 ["tell-undo", "Take a tell back", "a tell you sent in the last minute, while nobody has read it"],
496498 ["traces", "Traces", "every crew run, newest first"],
497499 ["buckets", "Buckets", "an object bucket's price a month, and binding it to an app"],
500 ["who-can", "Who may do what", "your role and every grant you hold"],
498501 ["audit", "Who can do what", "each app's doors from its contract.json: yes, own or no"],
499502 ["registry-items", "Component registry", "the forge's parts; install one into an app"],
500503 ["archived", "Archive", "what is put away, who put it there: open one or unarchive it"],
test/who-can.test.ts added +232
@@ -0,0 +1,232 @@
1 /**
2 * Who may do what (#18050): one grant in each of the sixteen tables, and the one view
3 * (`core/grants_view.ts`) lists them all, by person and by resource; an account with no grants
4 * shows only what its role gives; a person sees only their own; and the page, the MCP tool and the
5 * terminal give the same account the same rows. (That every grant table is read is
6 * `test/grants-view.test.ts`'s gate.)
7 */
8 import { afterAll, beforeAll, describe, 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 { createRepo } from "../src/actions/repos.ts";
14 import { whoMayDoWhat } from "../src/actions/grants_view.ts";
15 import { createApp as createAppRow } from "../src/core/apps.ts";
16 import { createClientCloud } from "../src/core/client_cloud.ts";
17 import { GRANT_TABLES, everyGrant, forgePath, provenance } from "../src/core/grants_view.ts";
18 import { createIssue } from "../src/core/issues.ts";
19 import { createSession } from "../src/core/sessions.ts";
20 import { getUserByName, createUser } from "../src/core/users.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { createForgeApp } from "../src/tui/forge.ts";
23 import { whoCanScreen } from "../src/tui/screens/whocan.ts";
24 import { headlessTerminal } from "../src/tui/term/terminal.ts";
25 import { seedAdmin } from "./helpers/admin.ts";
26 import { settleApp } from "./helpers/tui.ts";
27
28 describe("who may do what", () => {
29 let dir = "";
30 let app: App;
31 let servers: Servers;
32 let adminCookie = "";
33 let bobCookie = "";
34
35 const sql = (q: string, ...p: (string | number | null)[]) => app.db.query(q).run(...p);
36 const id = (name: string) => getUserByName(app.db, name)!.id;
37
38 beforeAll(async () => {
39 dir = await mkdtemp(join(tmpdir(), "forge-grants-"));
40 app = createApp({ dataDir: dir, port: 0 });
41 servers = await serve(app);
42 const alice = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "alice-login-secret" });
43 if (!alice.ok) throw new Error(alice.error);
44 for (const name of ["bob", "carol", "dave"]) {
45 const made = await createUser(app.db, { username: name, email: `${name}@forge.test`, password: `${name}-login-secret`, origin: "seed", trusted: true });
46 if (!made.ok) throw new Error(made.error);
47 }
48 adminCookie = `forge_session=${createSession(app.db, alice.value.id).token}`;
49 bobCookie = `forge_session=${createSession(app.db, id("bob")).token}`;
50
51 const repo = await createRepo(app, alice.value, { name: "yard", visibility: "private" });
52 if (!repo.ok) throw new Error(repo.error);
53 const row = createAppRow(app.db, { repoId: repo.value.id, slug: "yard", access: "private" });
54 if (!row.ok) throw new Error(row.error);
55 const issue = createIssue(app.db, { repoId: repo.value.id, authorId: id("alice"), title: "a pull", kind: "pull" });
56 if (!issue.ok) throw new Error(issue.error);
57
58 // One grant of each kind, every one to dave except where the table names an app or a place.
59 const dave = id("dave");
60 const at = "2026-12-01T10:00:00.000Z";
61 sql("INSERT INTO member (user_id, promoted_by, promoted_at) VALUES (?1, ?2, ?3)", dave, id("alice"), at);
62 sql("INSERT INTO team (id, org_id, name, permission) VALUES ('t1', ?1, 'builders', 'write')", id("alice"));
63 sql("INSERT INTO team_member (team_id, user_id) VALUES ('t1', ?1)", dave);
64 sql("INSERT INTO app_member (app_id, user_id, added_by, added_at) VALUES (?1, ?2, ?3, ?4)", row.value.id, dave, id("alice"), at);
65 sql("INSERT INTO game_grant (box_id, user_id, role, service) VALUES ('box1', ?1, 'operator', '')", dave);
66 sql("INSERT INTO model_grant (user_id, usd_per_month, granted_by, granted_at) VALUES (?1, 5, ?2, ?3)", dave, id("alice"), at);
67 sql("INSERT INTO subscription (id, name, kind, token_enc) VALUES ('s1', 'shared-plan', 'api_key', 'x')");
68 sql("INSERT INTO subscription_grant (scope_id, agent_id, subscription_id) VALUES (?1, '', 's1')", repo.value.id);
69 sql("INSERT INTO secret_grant (repo_id, name, scope, granted_by) VALUES (?1, 'STRIPE_KEY', 'forge', ?2)", repo.value.id, id("alice"));
70 sql("INSERT INTO egress_grant (repo_id, destination, granted_by) VALUES (?1, 'api.example.com', ?2)", repo.value.id, id("alice"));
71 sql("INSERT INTO device (id, name, kind, url) VALUES (1, 'label-printer', 'printer', 'http://10.0.0.5')");
72 sql("INSERT INTO device_grant (device_id, app_id, granted_by) VALUES (1, ?1, ?2)", row.value.id, id("alice"));
73 sql("INSERT INTO child_reach_grant (body_id, child, host, port, granted_by, granted_at) VALUES ('body1', 'kid', 'reach.example.org', 443, ?1, ?2)", id("alice"), at);
74 sql("INSERT INTO origin_read_grant (repo_id, kind, grantee_id, granted_by) VALUES (?1, 'crew', ?2, ?3)", repo.value.id, dave, id("alice"));
75 sql("INSERT INTO pull_run_grant (issue_id, commit_oid, user_id) VALUES (?1, 'abcdef0123456789', ?2)", issue.value.id, dave);
76 sql("INSERT INTO telemetry_grant (user_id, granted_by) VALUES (?1, ?2)", dave, id("alice"));
77 createClientCloud(app.db, dir, { provider: "aws", label: "client-aws", key: "k", days: 3, by: id("alice"), now: new Date(at) });
78 sql("INSERT INTO client_cloud_member (cloud_id, user_id, granted_by, granted_at) SELECT id, ?1, ?2, ?3 FROM client_cloud", dave, id("alice"), at);
79 sql("INSERT INTO crew_team_member (team_slug, user_id) VALUES ('design', ?1)", dave);
80 sql("INSERT INTO share (id, item_id, sender_id, recipient_id, repo_id, kind, link, what, state, created_at) VALUES ('sh1', 'i1', ?1, ?2, ?3, 'issue', '/alice/yard/issues/1', 'a thing', 'delivered', ?4)", id("alice"), dave, repo.value.id, at);
81 });
82
83 afterAll(async () => {
84 await servers.stop();
85 await rm(dir, { recursive: true, force: true });
86 });
87
88 const alice = () => getUserByName(app.db, "alice")!;
89
90 test("one grant in each table, and the view lists every one", () => {
91 const seen = new Set(everyGrant(app.db).map((g) => g.table));
92 expect([...GRANT_TABLES].filter((t) => !seen.has(t))).toEqual([]);
93 expect(GRANT_TABLES.length).toBe(16);
94 });
95
96 test("by person: everything dave can reach, with who granted it and where it is changed", () => {
97 const view = whoMayDoWhat(app, alice(), { person: "dave" });
98 expect(view.ok).toBe(true);
99 if (!view.ok) return;
100 const tables = view.value.grants.map((g) => g.table);
101 for (const t of ["member", "team_member", "app_member", "game_grant", "model_grant", "origin_read_grant", "telemetry_grant", "client_cloud_member", "crew_team_member", "share"])
102 expect(tables).toContain(t);
103 const model = view.value.grants.find((g) => g.table === "model_grant")!;
104 expect(model.byName).toBe("alice");
105 expect(model.who).toBe("dave");
106 expect(model.href.startsWith("/")).toBe(true);
107 expect(view.value.standing?.role).toBe("member");
108 });
109
110 test("a table that does not record who granted it says so", () => {
111 const game = everyGrant(app.db).find((g) => g.table === "game_grant")!;
112 expect(game.byName).toEqual({ notRecorded: true });
113 expect(provenance(game)).toBe("granted by: not recorded · date not recorded");
114 });
115
116 test("by resource: everyone who reaches the app, through whichever table", () => {
117 const tables = everyGrant(app.db, undefined, "alice/yard").map((g) => g.table);
118 for (const t of ["app_member", "secret_grant", "egress_grant", "device_grant", "origin_read_grant", "share", "subscription_grant"])
119 expect(tables).toContain(t);
120 // LIKE wildcards in the ask match themselves, not everything.
121 expect(everyGrant(app.db, undefined, "%")).toEqual([]);
122 expect(everyGrant(app.db, undefined, "alice_yard")).toEqual([]);
123 });
124
125 test("an account with no grants shows only what its role gives", () => {
126 const view = whoMayDoWhat(app, alice(), { person: "carol" });
127 expect(view.ok && view.value.grants).toEqual([]);
128 expect(view.ok && view.value.standing?.role).toBe("guest");
129 expect(view.ok && view.value.standing?.can.length).toBeGreaterThan(0);
130 });
131
132 test("a person reads only their own; anyone else's is not_found", () => {
133 const bob = getUserByName(app.db, "bob")!;
134 expect(whoMayDoWhat(app, bob, {}).ok).toBe(true);
135 expect(whoMayDoWhat(app, bob, { person: "BOB" }).ok).toBe(true);
136 expect(whoMayDoWhat(app, bob, { person: "dave" })).toEqual({ ok: false, error: "not_found" });
137 expect(whoMayDoWhat(app, bob, { resource: "alice/yard" })).toEqual({ ok: false, error: "not_found" });
138 expect(whoMayDoWhat(app, undefined, {})).toEqual({ ok: false, error: "not_found" });
139 const own = whoMayDoWhat(app, bob, {});
140 expect(own.ok && own.value.scope).toBe("self");
141 expect(own.ok && own.value.grants).toEqual([]);
142 });
143
144 test("the page: an admin looks up dave; bob sees his own and is refused dave", async () => {
145 const dave = await fetch(`${servers.url}/settings/who-can?person=dave`, { headers: { cookie: adminCookie } });
146 expect(dave.status).toBe(200);
147 const text = await dave.text();
148 expect(text).toContain("read telemetry");
149 expect(text).toContain("not recorded");
150 expect(text).toContain("/settings/telemetry");
151 const own = await fetch(`${servers.url}/settings/who-can`, { headers: { cookie: bobCookie } });
152 expect(own.status).toBe(200);
153 expect(await own.text()).toContain("No grants match.");
154 expect((await fetch(`${servers.url}/settings/who-can?person=dave`, { headers: { cookie: bobCookie } })).status).toBe(404);
155 expect((await fetch(`${servers.url}/settings/who-can`, { redirect: "manual" })).status).not.toBe(200);
156 });
157
158 test("a share's link is followed only when it is a path on this forge", () => {
159 for (const bad of ["//evil.example/x", "/\\evil.example", "/\t/evil.example", "https://evil.example", "", null])
160 expect(forgePath(bad)).toBe("/settings");
161 expect(forgePath("/alice/yard/issues/1")).toBe("/alice/yard/issues/1");
162 expect(everyGrant(app.db).every((g) => g.href.startsWith("/") && !g.href.startsWith("//"))).toBe(true);
163 });
164
165 test("a person's own read gives only their rows, from the database's own filter", () => {
166 const dave = id("dave");
167 const own = everyGrant(app.db, dave);
168 expect(own.length).toBeGreaterThan(5);
169 expect(own.every((g) => g.who === "dave")).toBe(true);
170 expect(everyGrant(app.db, id("bob"))).toEqual([]);
171 });
172
173 test("the same account gets the same rows on the page, the MCP tool and the terminal", async () => {
174 const { tool } = await import("../src/http/mcp/tools/access.ts");
175 const ctx = { app } as Parameters<typeof tool.run>[0];
176 for (const [name, cookie] of [["alice", adminCookie], ["bob", bobCookie]] as const) {
177 const user = getUserByName(app.db, name)!;
178 const asked = whoMayDoWhat(app, user, {});
179 expect(asked.ok).toBe(true);
180 const grants = asked.ok ? asked.value.grants : [];
181 const mcp = JSON.stringify(await tool.run(ctx, user, { action: "grants" }));
182 const terminal = headlessTerminal(200, 60);
183 const { app: tui, session } = createForgeApp(
184 app,
185 { sshUsername: name, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user },
186 { terminal, exitHooks: false },
187 );
188 tui.start();
189 tui.ctx.push(whoCanScreen(session, tui.ctx));
190 await settleApp(tui);
191 const shown = tui.screen.toText();
192 tui.stop?.();
193 const page = await (await fetch(`${servers.url}/settings/who-can`, { headers: { cookie } })).text();
194 // Every row the action returns is named by the MCP tool; the page and the terminal show the
195 // rows that fit the first view (the first of them) and agree on how many there are.
196 for (const g of grants) expect(mcp).toContain(g.table);
197 if (grants.length === 0) {
198 expect(page).toContain("No grants match.");
199 expect(shown).toContain("No grants match.");
200 } else {
201 expect(shown).toContain(`${grants.length} grants`);
202 expect((page.match(/class="row"/g) ?? []).length).toBe(grants.length);
203 expect(page).toContain(grants[0]!.href);
204 }
205 }
206 });
207
208 test("the MCP: the access tool's grants action answers the same", async () => {
209 const { tool } = await import("../src/http/mcp/tools/access.ts");
210 const ctx = { app } as Parameters<typeof tool.run>[0];
211 const out = await tool.run(ctx, alice(), { action: "grants", person: "dave" });
212 expect(JSON.stringify(out)).toContain("telemetry_grant");
213 const gone = await tool.run(ctx, alice(), { action: "grants", person: "nobody" });
214 expect(JSON.stringify(gone)).toContain("not_found");
215 });
216
217 test("the terminal shows what the page shows, for an admin and for a person", async () => {
218 for (const [name, expected] of [["alice", "read telemetry"], ["bob", "No grants match."]] as const) {
219 const terminal = headlessTerminal(160, 40);
220 const { app: tui, session } = createForgeApp(
221 app,
222 { sshUsername: name, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: getUserByName(app.db, name)! },
223 { terminal, exitHooks: false },
224 );
225 tui.start();
226 tui.ctx.push(whoCanScreen(session, tui.ctx));
227 await settleApp(tui);
228 expect(tui.screen.toText()).toContain(expected);
229 tui.stop?.();
230 }
231 });
232 });

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

Keyboard shortcuts

Docs