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

Access 4b-2: an admin sees who can reach what, by person and by resource #18179

opened this

Merged 6h 2m ago, live in production

torque/forge:torque/18159-access-4b-2-an-admin-sees-who-can-reach → main 0 commits fork

  • Merged. torque/18159-access-4b-2-an-admin-sees-who-can-reach was merged into main as a8d3bc8.

Review

Sign in to review this change.
7 files changed +244 −32
docs/features/who-can.md +5 −5
@@ -6,11 +6,11 @@ row: Who may do what
66
77 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.
88
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; in a person's own view, a grant only an admin changes (any page the route marks keep for admins: People, Crew, Cloud, Subscriptions, Secrets, Telemetry, Devices) says "an admin changes it" with that page named instead of linking to a page that would turn them away. The page is on every account's settings nav.
10 - **MCP:** `whoami_can` with `kind: "grants"`, for anyone: your role and the grants you hold, or every grant for a forge admin (`{ scope, standing, grants }`). A forge admin's `access` tool with `action: "grants"` takes `person` or `resource` too.
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`.
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). An admin's switch, Every grant · By person · By resource (`?by=person`, `?by=resource`, #18159), groups the list: one row per person (or per repository, device, pull that holds a grant) or per resource, with its kind and count, linking to that person's or resource's look-up, and its grants under it. Each row links to where it is changed; in a person's own view, a grant only an admin changes (any page the route marks keep for admins: People, Crew, Cloud, Subscriptions, Secrets, Telemetry, Devices) says "an admin changes it" with that page named instead of linking to a page that would turn them away. The page is on every account's settings nav.
10 - **MCP:** `whoami_can` with `kind: "grants"`, for anyone: your role and the grants you hold, or every grant for a forge admin (`{ scope, standing, grants }`). A forge admin's `access` tool with `action: "grants"` takes `person` or `resource` too, and `by: "person"` or `"resource"` adds `groups` (`{ name, kind, narrow?, grants }`).
11 - **Terminal:** `forge tui`, the palette entry "Who may do what": your own, or as an admin `p` a person, `r` a resource, `b` group by person, then by resource, then not, `c` clear.
12 - Rules (`src/actions/grants_view.ts`): anyone else asking for another person's, a resource's or a grouping (`by`) answers `not_found`, and the page answers them the same 404 it gives for a person who does not exist.
1313 - 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>`.
14 - Try it: sign in, open `/settings/who-can`; as admin add `?person=<name>`, `?resource=<owner>/<app>` or `?by=person`.
1515 - 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`.
1616 - 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).
src/actions/grants_view.ts +20 −3
@@ -1,12 +1,13 @@
11 /**
22 * Who may do what (#18050): one read over every grant table (`core/grants_view.ts`) and the role
33 * 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.
4 * of it, grouped by person or by resource when it asks (#18159); every other account, an agent
5 * included, reads only its own, and asking for more answers `not_found`, as a missing account does.
6 * Reads only: nothing here grants or revokes.
67 */
78
89 import type { App } from "../app.ts";
9 import { everyGrant, type Grant } from "../core/grants_view.ts";
10 import { everyGrant, groupGrants, type Grant, type GrantGroup, type GrantsBy } from "../core/grants_view.ts";
1011 import { ABILITIES, CAN, roleOf, type Role } from "../core/roles.ts";
1112 import { getUserByName, type User } from "../core/users.ts";
1213 import { isAdminRoute } from "../http/route_marks.ts";
@@ -25,13 +26,21 @@ export interface GrantsView {
2526 readonly scope: "self" | "person" | "resource" | "all";
2627 readonly standing?: Standing;
2728 readonly grants: readonly Grant[];
29 /** The same grants by person or by resource, when an admin asked for it (#18159). */
30 readonly by?: GrantsBy;
31 readonly groups?: readonly GrantGroup[];
2832 }
2933
3034 export interface GrantsQuery {
3135 readonly person?: string;
3236 readonly resource?: string;
37 /** Group the answer by person or by resource: a forge admin's; anyone else is `not_found`. */
38 readonly by?: GrantsBy;
3339 }
3440
41 /** `by` from outside (a query string, a tool's argument): one of the two, or undefined. */
42 export const grantsBy = (raw: unknown): GrantsBy | undefined => (raw === "person" || raw === "resource" ? raw : undefined);
43
3544 const MAX_NAME = 200;
3645
3746 function standingOf(app: App, user: { id: string; username: string; isAdmin: boolean }): Standing {
@@ -59,6 +68,14 @@ const reachableBy = (g: Grant): Grant => {
5968
6069 export function whoMayDoWhat(app: App, actor: User | undefined, query: GrantsQuery = {}): Result<GrantsView, "not_found"> {
6170 if (actor === undefined) return err("not_found");
71 // Grouping is the admin's whole view: anyone else asking gets what a missing account gets.
72 if (query.by !== undefined && !isAdmin(actor)) return err("not_found");
73 const asked = narrowed(app, actor, query);
74 if (!asked.ok || query.by === undefined) return asked;
75 return ok({ ...asked.value, by: query.by, groups: groupGrants(asked.value.grants, query.by) });
76 }
77
78 function narrowed(app: App, actor: User, query: GrantsQuery): Result<GrantsView, "not_found"> {
6279 const person = (query.person ?? "").trim().slice(0, MAX_NAME);
6380 const resource = (query.resource ?? "").trim().slice(0, MAX_NAME);
6481 const own = (): GrantsView => ({ scope: "self", standing: standingOf(app, actor), grants: everyGrant(app.db, actor.id).map(reachableBy) });
src/core/grants_view.ts +44
@@ -194,3 +194,47 @@ export function provenance(g: Grant): string {
194194 const at = typeof g.at === "string" ? g.at.slice(0, 10) : g.at === null ? "no date" : "date not recorded";
195195 return `${by} · ${at}`;
196196 }
197
198 /** The two ways an admin's whole list is grouped (#18159). */
199 export type GrantsBy = "person" | "resource";
200
201 /** One principal's grants, or one resource's, and the look-up that narrows the page to it. */
202 export interface GrantGroup {
203 /** The principal's name (`who`) or the resource's (`on`). */
204 readonly name: string;
205 /** Its kind: "user", "repo", "app", "host"… */
206 readonly kind: string;
207 /**
208 * The query that narrows the view to it: `person` for an account, `resource` for the rest;
209 * undefined for a principal that is not an account (a repository, a device), whose name a
210 * resource look-up would not find as a holder.
211 */
212 readonly narrow?: { readonly key: GrantsBy; readonly value: string };
213 readonly grants: readonly Grant[];
214 }
215
216 /** Principal kinds that are accounts, so `?person=` finds them. */
217 const ACCOUNT_KINDS = new Set(["user", "agent", "crew"]);
218
219 /**
220 * `grants` grouped by who holds them or by what they are on, in name order; each group keeps the
221 * grants' own order. Pure: the same grants give the same groups on the page, the MCP tool and the
222 * terminal.
223 */
224 export function groupGrants(grants: readonly Grant[], by: GrantsBy): GrantGroup[] {
225 const groups = new Map<string, { name: string; kind: string; grants: Grant[] }>();
226 for (const g of grants) {
227 const name = by === "person" ? g.who : g.on;
228 const kind = by === "person" ? g.principal.kind : g.resource.kind;
229 const key = `${kind}\u0000${name}`;
230 const found = groups.get(key);
231 if (found === undefined) groups.set(key, { name, kind, grants: [g] });
232 else found.grants.push(g);
233 }
234 return [...groups.values()]
235 .sort((a, b) => a.name.localeCompare(b.name) || a.kind.localeCompare(b.kind))
236 .map((g) => {
237 const narrow = by === "resource" ? { key: by, value: g.name } : ACCOUNT_KINDS.has(g.kind) ? { key: by, value: g.name } : undefined;
238 return narrow === undefined ? g : { ...g, narrow };
239 });
240 }
src/http/mcp/tools/access.ts +6 −2
@@ -1,11 +1,11 @@
11 import { listAccess } from "../../../actions/access_log.ts";
2 import { whoMayDoWhat } from "../../../actions/grants_view.ts";
2 import { grantsBy, whoMayDoWhat } from "../../../actions/grants_view.ts";
33 import { good, bad, type Tool } from "../shared.ts";
44
55 export const tool: Tool = {
66 name: "access",
77 listedTo: "admin",
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",
8 doc: "`{ action?: \"grants\", person?, resource?, by? }`: with `grants`, who may do what: every grant in every table, or one person's (with their role), or everyone who reaches a resource; `by: \"person\"` or `\"resource\"` adds `groups`, the same grants grouped; 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",
99 description:
1010 "Non-browser public-path requests, redacted, newest first (max 500). Forge admin.",
1111 inputSchema: {
@@ -14,6 +14,7 @@ export const tool: Tool = {
1414 action: { type: "string", enum: ["log", "grants"] },
1515 person: { type: "string", maxLength: 200 },
1616 resource: { type: "string", maxLength: 200 },
17 by: { type: "string", enum: ["person", "resource"] },
1718 since: { type: "string", maxLength: 40 },
1819 ua: { type: "string", maxLength: 100 },
1920 path: { type: "string", maxLength: 200 },
@@ -26,9 +27,12 @@ export const tool: Tool = {
2627 if (args.action === "grants") {
2728 const person = text("person");
2829 const resource = text("resource");
30 const by = grantsBy(args.by);
31 if (args.by !== undefined && by === undefined) return bad("invalid", "by is one of: person, resource");
2932 const asked = whoMayDoWhat(ctx.app, user, {
3033 ...(person === undefined ? {} : { person }),
3134 ...(resource === undefined ? {} : { resource }),
35 ...(by === undefined ? {} : { by }),
3236 });
3337 return asked.ok ? good(asked.value) : bad("not_found", "no such person here");
3438 }
src/tui/screens/whocan.ts +44 −15
@@ -1,13 +1,14 @@
11 /**
22 * Who may do what, in the terminal (#18050): `/settings/who-can`'s list from the same action
33 * (`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.
4 * person, `r` everyone who reaches a resource, `b` groups the list by person, then by resource,
5 * then not (#18159), as the page's switch does, and `c` clears back to all of it. Each row says who
6 * may do what on what, who granted it and when ("not recorded" where the table does not say), and
7 * the page where it is changed.
78 */
89
910 import { whoMayDoWhat, type GrantsView } from "../../actions/grants_view.ts";
10 import { provenance } from "../../core/grants_view.ts";
11 import { provenance, type Grant, type GrantsBy } from "../../core/grants_view.ts";
1112 import type { Ctx, Screen } from "../app/app.ts";
1213 import { binding } from "../app/keys.ts";
1314 import type { Session } from "../session.ts";
@@ -19,9 +20,16 @@ import type { PaletteEntry } from "./entries.ts";
1920
2021 const MAX = 200;
2122
23 /** Where a grant is changed, as the page's row says it. */
24 const changedAt = (g: Grant): string =>
25 g.href === "" ? `an admin changes it${g.adminPage === undefined ? "" : ` (${g.adminPage})`}` : `change at ${g.href}`;
26
27 /** The page's switch, one key: none, by person, by resource, none. */
28 const NEXT_BY: Record<GrantsBy | "none", GrantsBy | undefined> = { none: "person", person: "resource", resource: undefined };
29
2230 export function whoCanScreen(f: Session, ctx: Ctx): Screen {
2331 const state = new ListState();
24 const filter: { person?: string; resource?: string } = {};
32 const filter: { person?: string; resource?: string; by?: GrantsBy } = {};
2533 const admin = f.user?.isAdmin === true && f.user.kind !== "agent";
2634
2735 const view = (): GrantsView | undefined => {
@@ -45,7 +53,8 @@ export function whoCanScreen(f: Session, ctx: Ctx): Screen {
4553 delete filter[key];
4654 return "no such person";
4755 }
48 state.clamp(view()?.grants.length ?? 0);
56 const v = view();
57 state.clamp(v?.groups?.length ?? v?.grants.length ?? 0);
4958 ctx.invalidate();
5059 return undefined;
5160 },
@@ -57,7 +66,7 @@ export function whoCanScreen(f: Session, ctx: Ctx): Screen {
5766 title: "Who may do what",
5867 keys: [
5968 binding(["j", "k"], "move cursor"),
60 ...(admin ? [binding(["p"], "a person"), binding(["r"], "a resource"), binding(["c"], "clear")] : []),
69 ...(admin ? [binding(["p"], "a person"), binding(["r"], "a resource"), binding(["b"], "group by person / resource"), binding(["c"], "clear")] : []),
6170 ],
6271 render(area, s) {
6372 const c = ctx.theme.c;
@@ -70,22 +79,42 @@ export function whoCanScreen(f: Session, ctx: Ctx): Screen {
7079 : `${standing.name} is ${standing.role === "admin" ? "an admin" : `a ${standing.role}`}; the role alone lets them: ${standing.can.join("; ")}.`;
7180 s.text(head!.x, head!.y, truncate(said, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
7281 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)} · ${g.href === "" ? `an admin changes it${g.adminPage === undefined ? "" : ` (${g.adminPage})`}` : `change at ${g.href}`}`,
78 }));
82 const groups = v?.groups;
83 const counted =
84 count === 0
85 ? "No grants match."
86 : `${count} grant${count === 1 ? "" : "s"}${groups === undefined ? "" : `, by ${v?.by}: ${groups.length}`}`;
87 s.text(head!.x, head!.y + 1, truncate(counted, head!.w), style(c.mutedFg, c.bg), head!.x + head!.w);
88 const rows: ListRow[] =
89 groups !== undefined
90 ? groups.map((g) => ({
91 title: g.name,
92 secondary: `${g.kind} · ${g.grants.length} grant${g.grants.length === 1 ? "" : "s"}`,
93 below: g.grants.map((x) => `${x.who} · ${x.action} · ${x.on} (${x.resource.kind}) · ${provenance(x)} · ${changedAt(x)}`),
94 }))
95 : (v?.grants ?? []).map((g) => ({
96 title: `${g.who} · ${g.action}`,
97 secondary: `${g.on} (${g.resource.kind})`,
98 meta: `${provenance(g)} · ${changedAt(g)}`,
99 }));
79100 drawList(s, list!, c, state, rows);
80101 },
81102 key(e) {
82 if (state.key(e, view()?.grants.length ?? 0)) return true;
103 const v = view();
104 if (state.key(e, v?.groups?.length ?? v?.grants.length ?? 0)) return true;
83105 if (e.ctrl || e.alt || !admin) return false;
84106 if (e.key === "p") ask("person");
85107 else if (e.key === "r") ask("resource");
86 else if (e.key === "c") {
108 else if (e.key === "b") {
109 const next = NEXT_BY[filter.by ?? "none"];
110 if (next === undefined) delete filter.by;
111 else filter.by = next;
112 state.clamp(0);
113 ctx.invalidate();
114 } else if (e.key === "c") {
87115 delete filter.person;
88116 delete filter.resource;
117 delete filter.by;
89118 ctx.invalidate();
90119 } else return false;
91120 return true;
src/web/pages/who-can.ts +43 −7
@@ -1,18 +1,20 @@
11 /**
22 * Who may do what (#18050): every grant in one list (`core/grants_view.ts`), each row linking to
33 * 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.
4 * person, or everyone who reaches a resource, and switch the list to every person or every resource
5 * (`?by=`, #18159), each group linking to its own look-up. The rules are
6 * `actions/grants_view.ts`'s; this draws.
57 */
68
79 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 { grantsBy, whoMayDoWhat, type GrantsView } from "../../actions/grants_view.ts";
11 import { provenance, type Grant, type GrantGroup, type GrantsBy } from "../../core/grants_view.ts";
1012 import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts";
1113 import type { Ctx } from "../../http/context.ts";
1214 import { notFoundPage, pageHead, settingsLayout, signInFirst } from "../chrome.ts";
1315 import { html, type Html } from "../html.ts";
1416 import { page } from "../layout.ts";
15 import { btn, row as uiRow, rowList } from "../ui.ts";
17 import { btn, row as uiRow, rowList, seg } from "../ui.ts";
1618 import { accountSections } from "./origins.ts";
1719
1820 const row = (g: Grant): Html =>
@@ -28,6 +30,32 @@ const row = (g: Grant): Html =>
2830 meta: html`${g.on} (${g.resource.kind}) · ${provenance(g)}`,
2931 });
3032
33 const PAGE = "/settings/who-can";
34
35 /** The page narrowed to one group: its person's or its resource's look-up. */
36 const groupRow = (g: GrantGroup): Html => {
37 const n = g.grants.length;
38 const meta = html`${g.kind} · ${n} grant${n === 1 ? "" : "s"}`;
39 const children = g.grants.map(row);
40 return g.narrow === undefined
41 ? uiRow({ title: g.name, meta, children })
42 : uiRow({ nav: true, href: `${PAGE}?${new URLSearchParams({ [g.narrow.key]: g.narrow.value })}`, title: g.name, meta, children });
43 };
44
45 /** The admin's switch: every grant as one list, by person, or by resource. */
46 function switcher(by: GrantsBy | undefined, person: string, resource: string): Html {
47 const keep = { ...(person === "" ? {} : { person }), ...(resource === "" ? {} : { resource }) };
48 const href = (b?: GrantsBy): string => {
49 const q = new URLSearchParams({ ...keep, ...(b === undefined ? {} : { by: b }) }).toString();
50 return q === "" ? PAGE : `${PAGE}?${q}`;
51 };
52 return html`<nav aria-label="Group the grants">${seg([
53 { label: "Every grant", href: href(), current: by === undefined },
54 { label: "By person", href: href("person"), current: by === "person" },
55 { label: "By resource", href: href("resource"), current: by === "resource" },
56 ])}</nav>`;
57 }
58
3159 /** The one sentence the page opens with. */
3260 function said(view: GrantsView, resource: string): string {
3361 const s = view.standing;
@@ -43,7 +71,11 @@ export function whoCanPage(ctx: Ctx): Response {
4371 const user = ctx.auth.user;
4472 const person = ctx.url.searchParams.get("person")?.slice(0, 200) ?? "";
4573 const resource = ctx.url.searchParams.get("resource")?.slice(0, 200) ?? "";
46 const asked = timePhase(ctx.request, "grants", () => whoMayDoWhat(ctx.app, user, { person, resource }));
74 const rawBy = ctx.url.searchParams.get("by");
75 const by = grantsBy(rawBy);
76 // An unknown grouping is not a page: the same answer as anything else that is not here.
77 if (rawBy !== null && rawBy !== "" && by === undefined) return notFoundPage(ctx);
78 const asked = timePhase(ctx.request, "grants", () => whoMayDoWhat(ctx.app, user, { person, resource, ...(by === undefined ? {} : { by }) }));
4779 if (!asked.ok) return notFoundPage(ctx);
4880 const view = asked.value;
4981 const admin = user.isAdmin && user.kind !== "agent";
@@ -53,12 +85,16 @@ export function whoCanPage(ctx: Ctx): Response {
5385 ? html`<form class="row-fields" method="get" action="/settings/who-can">
5486 <input class="input" name="person" value="${person}" placeholder="A person's username" aria-label="A person's username" />
5587 <input class="input mono" name="resource" value="${resource}" placeholder="owner/app, a host, a secret…" aria-label="A resource" />
88 ${by === undefined ? null : html`<input type="hidden" name="by" value="${by}" />`}
5689 ${btn("Look up", { size: "sm", variant: "primary" })}
57 </form>`
90 </form>
91 ${switcher(by, person, resource)}`
5892 : html``}
5993 ${view.grants.length === 0
6094 ? html`<p class="muted small" id="who-can-none">No grants match.</p>`
61 : html`<div id="who-can-list">${rowList(view.grants.map(row), { bare: true, label: "Grants" })}</div>`}
95 : view.groups !== undefined
96 ? html`<div id="who-can-list">${rowList(view.groups.map(groupRow), { bare: true, label: by === "person" ? "Grants by person" : "Grants by resource" })}</div>`
97 : html`<div id="who-can-list">${rowList(view.grants.map(row), { bare: true, label: "Grants" })}</div>`}
6298 </section>`;
6399 const rendering = performance.now();
64100 const response = page({
test/who-can.test.ts +82
@@ -269,4 +269,86 @@ describe("who may do what", () => {
269269 tui.stop?.();
270270 }
271271 });
272
273 test("an admin sees every grant by person and by resource, each row linking to where it changes (#18159)", async () => {
274 const byPerson = whoMayDoWhat(app, alice(), { by: "person" });
275 expect(byPerson.ok).toBe(true);
276 if (!byPerson.ok) return;
277 const dave = byPerson.value.groups!.find((g) => g.name === "dave" && g.kind === "user")!;
278 expect(dave.narrow).toEqual({ key: "person", value: "dave" });
279 expect(dave.grants.map((g) => g.table)).toContain("telemetry_grant");
280 // Every grant is in exactly one group.
281 expect(byPerson.value.groups!.reduce((n, g) => n + g.grants.length, 0)).toBe(byPerson.value.grants.length);
282 // A repository holding a grant is not an account: no person look-up for it.
283 expect(byPerson.value.groups!.find((g) => g.kind === "repo")!.narrow).toBeUndefined();
284
285 const byResource = whoMayDoWhat(app, alice(), { by: "resource" });
286 const yard = byResource.ok ? byResource.value.groups!.find((g) => g.name === "alice/yard" && g.kind === "app")! : undefined;
287 expect(yard?.narrow).toEqual({ key: "resource", value: "alice/yard" });
288 expect(yard?.grants.some((g) => g.table === "app_member" && g.who === "dave")).toBe(true);
289
290 const personPage = await fetch(`${servers.url}/settings/who-can?by=person`, { headers: { cookie: adminCookie } });
291 expect(personPage.status).toBe(200);
292 const personText = await personPage.text();
293 expect(personText).toContain('href="/settings/who-can?person=dave"');
294 expect(personText).toContain('href="/settings/telemetry"');
295 expect(personText).toContain('aria-label="Grants by person"');
296 expect(personText).toMatch(/href="\/settings\/who-can\?by=person"\s*aria-current="page"/);
297 const resourceText = await (await fetch(`${servers.url}/settings/who-can?by=resource`, { headers: { cookie: adminCookie } })).text();
298 expect(resourceText).toContain('href="/settings/who-can?resource=alice%2Fyard"');
299 expect(resourceText).toContain('href="/alice/yard/settings"');
300 // A grouping that is not one of the two is not a page.
301 expect((await fetch(`${servers.url}/settings/who-can?by=everyone`, { headers: { cookie: adminCookie } })).status).toBe(404);
302 });
303
304 test("a non-admin asking for another person's view gets what a missing person gets (#18159)", async () => {
305 const bob = getUserByName(app.db, "bob")!;
306 for (const by of ["person", "resource"] as const) expect(whoMayDoWhat(app, bob, { by })).toEqual({ ok: false, error: "not_found" });
307 const answer = async (q: string): Promise<[number, string]> => {
308 const res = await fetch(`${servers.url}/settings/who-can?${q}`, { headers: { cookie: bobCookie } });
309 // Each response carries its own request id; the rest is the answer.
310 return [res.status, (await res.text()).replace(/Quote <code>[^<]*<\/code>/g, "")];
311 };
312 const missing = await answer("person=nobody-here");
313 expect(missing[0]).toBe(404);
314 for (const q of ["person=dave", "by=person", "by=resource", "person=dave&by=person", "resource=alice%2Fyard"]) {
315 const got = await answer(q);
316 expect(got[0]).toBe(404);
317 expect(got[1]).toBe(missing[1]);
318 expect(got[1]).not.toContain("telemetry");
319 }
320 // An admin asking for someone who is not here gets the same not-found.
321 expect((await fetch(`${servers.url}/settings/who-can?person=nobody-here`, { headers: { cookie: adminCookie } })).status).toBe(404);
322 });
323
324 test("names are escaped in the grouped view (#18159)", async () => {
325 sql("INSERT INTO egress_grant (repo_id, destination, granted_by) VALUES ((SELECT id FROM repo WHERE name = 'yard'), '<img src=x onerror=1>.example', ?1)", id("alice"));
326 const text = await (await fetch(`${servers.url}/settings/who-can?by=resource`, { headers: { cookie: adminCookie } })).text();
327 expect(text).not.toContain("<img src=x");
328 expect(text).toContain("&lt;img src=x onerror=1&gt;.example");
329 sql("DELETE FROM egress_grant WHERE destination LIKE '<img%'");
330 });
331
332 test("the terminal's b groups as the page's switch does (#18159)", async () => {
333 const terminal = headlessTerminal(200, 60);
334 const { app: tui, session } = createForgeApp(
335 app,
336 { sshUsername: "alice", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice() },
337 { terminal, exitHooks: false },
338 );
339 tui.start();
340 const screen = whoCanScreen(session, tui.ctx);
341 tui.ctx.push(screen);
342 screen.key!({ key: "b", ctrl: false, alt: false, shift: false } as Parameters<NonNullable<typeof screen.key>>[0]);
343 await settleApp(tui);
344 const byPerson = tui.screen.toText();
345 screen.key!({ key: "b", ctrl: false, alt: false, shift: false } as Parameters<NonNullable<typeof screen.key>>[0]);
346 await settleApp(tui);
347 const byResource = tui.screen.toText();
348 tui.stop?.();
349 const groups = whoMayDoWhat(app, alice(), { by: "person" });
350 expect(byPerson).toContain(`by person: ${groups.ok ? groups.value.groups!.length : -1}`);
351 expect(byResource).toContain("by resource:");
352 expect(byResource).toContain("alice/yard");
353 });
272354 });

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

Keyboard shortcuts

Docs