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

Roles, part 3b: a member cannot change another account or the crew's standing instructions #2399

Parked opened this
Closed without merging

scout/forge:scout/2385-roles-part-3b-a-member-cannot-change-ano → main 2 commits fork 2 threads · 2 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
9 files changed +247 −16
docs/ROLES.md +7
@@ -23,6 +23,13 @@ a guest, so an assignment made before the guard starts nothing either. A
2323 spawned forge's founder is made a member, so its first boot can hand the
2424 direction to the planner.
2525
26 Part 3b (#2385) keeps a member out of the owner's acts on others: changing
27 another account (its role, allowance, ceilings, verification, suspension,
28 tokens and browsers) and editing the crew's standing instructions (an agent's
29 brief) are refused a member with `403 not_admin` on the API and a plain line on
30 the page. A member still changes their own account. A guest or a stranger
31 still meets the usual 404.
32
2633 On `/settings/people` an admin promotes a guest to member, with a starter
2734 model allowance (dollars a month, default none, through the grant of #1145),
2835 or demotes a member to guest. Demoting leaves any allowance as it is; take it
src/core/roles.ts +8
@@ -48,6 +48,14 @@ export function rolesTable(): string {
4848 /** The words a guest is refused with, on every surface. */
4949 export const NOT_A_MEMBER = "the owner has not made this account a member";
5050
51 /** The words a member is refused with when they reach for what only the owner may change. */
52 export const ADMIN_ONLY = "only the forge's owner can change another account or the crew's standing instructions";
53
54 /** Whether this account is a member: a person with a `member` row who is not an admin. */
55 export function isMember(db: Database, user: { id: string; isAdmin: boolean; kind: string }): boolean {
56 return user.kind === "user" && roleOf(db, user) === "member";
57 }
58
5159 /**
5260 * Whether the table withholds `ability` from this account. Only a person
5361 * can be a guest: agents and organizations are not accounts the owner
src/http/api.ts +29 −2
@@ -9,7 +9,7 @@
99 */
1010
1111 import { setRole } from "../actions/roles.ts";
12 import { listPeople, NOT_A_MEMBER } from "../core/roles.ts";
12 import { ADMIN_ONLY, isMember, listPeople, NOT_A_MEMBER } from "../core/roles.ts";
1313 import { setAccountCeilings, setAccountGrant } from "../actions/model_grant.ts";
1414 import { storageLimitMessage } from "../core/storage.ts";
1515 import { voteVariant } from "../actions/variants.ts";
@@ -1347,8 +1347,25 @@ export function apiRoutes(router: Router<Handler>): void {
13471347 "an admin cannot suspend or remove themselves, another admin, or an agent",
13481348 )
13491349 : apiError(error, 500, "the account could not be removed");
1350 // A member is told plainly it is not theirs; anyone else finds no door.
1351 const ownersOnly = (ctx: Ctx): Response =>
1352 ctx.auth.user !== undefined && isMember(ctx.app.db, ctx.auth.user)
1353 ? apiError("not_admin", 403, ADMIN_ONLY)
1354 : notFound();
13501355 const accountAdmin = (ctx: Ctx, scope: "ro" | "admin"): Response | undefined =>
1351 ctx.auth.user?.isAdmin === true ? requireScope(ctx, scope) : notFound();
1356 ctx.auth.user?.isAdmin === true ? requireScope(ctx, scope) : ownersOnly(ctx);
1357 // Another person's sign-ins: a member may only reach their own.
1358 const notOthers = (ctx: Ctx): Response | undefined =>
1359 ctx.auth.user !== undefined &&
outdated

Nit: !ctx.auth.user.isAdmin is redundant, because isMember already returns false for an admin (roleOf returns admin first). crewOwnersOnly then does the same thing as notOthers without the username comparison. One helper would be enough.

1360 ctx.params.username !== ctx.auth.user.username &&
1361 isMember(ctx.app.db, ctx.auth.user)
1362 ? ownersOnly(ctx)
1363 : undefined;
1364 // The crew's standing instructions (an agent's brief) are the owner's.
1365 const crewOwnersOnly = (ctx: Ctx): Response | undefined =>
1366 ctx.auth.user !== undefined && !ctx.auth.user.isAdmin && isMember(ctx.app.db, ctx.auth.user)
1367 ? ownersOnly(ctx)
1368 : undefined;
13521369
13531370 // Boards (`boards/query.ts`): a site admin who is a person, never an agent.
13541371 const boardsAdmin = (ctx: Ctx): Response | undefined => {
@@ -1851,6 +1868,8 @@ export function apiRoutes(router: Router<Handler>): void {
18511868 // Where an account is signed in: its person, or the forge's owner for any
18521869 // person (`actions/signins.ts`). Anyone else finds no such account.
18531870 router.add("GET", "/api/v1/users/:username/signins", (ctx) => {
1871 const others = notOthers(ctx);
1872 if (others) return others;
18541873 const denied = requireAccount(ctx, { adminToken: true });
18551874 if (denied) return denied;
18561875 const seen = accountSignIns(
@@ -1864,6 +1883,8 @@ export function apiRoutes(router: Router<Handler>): void {
18641883 });
18651884
18661885 router.add("DELETE", "/api/v1/users/:username/sessions/:id", (ctx) => {
1886 const others = notOthers(ctx);
1887 if (others) return others;
18671888 const denied = requireAccount(ctx, { adminToken: true });
18681889 if (denied) return denied;
18691890 const done = endAccountSession(
@@ -5445,6 +5466,8 @@ export function apiRoutes(router: Router<Handler>): void {
54455466 });
54465467
54475468 router.add("POST", "/api/v1/agents", async (ctx) => {
5469 const others = crewOwnersOnly(ctx);
5470 if (others) return others;
54485471 const denied = requireAccount(ctx, { adminToken: true });
54495472 if (denied) return denied;
54505473 const input = await body(ctx.request);
@@ -5474,6 +5497,8 @@ export function apiRoutes(router: Router<Handler>): void {
54745497 });
54755498
54765499 router.add("PATCH", "/api/v1/agents/:username", async (ctx) => {
5500 const others = crewOwnersOnly(ctx);
5501 if (others) return others;
54775502 const denied = requireAccount(ctx, { adminToken: true });
54785503 if (denied) return denied;
54795504 const input = await body(ctx.request);
@@ -5494,6 +5519,8 @@ export function apiRoutes(router: Router<Handler>): void {
54945519 });
54955520
54965521 router.add("DELETE", "/api/v1/agents/:username", (ctx) => {
5522 const others = crewOwnersOnly(ctx);
5523 if (others) return others;
54975524 const denied = requireAccount(ctx, { adminToken: true });
54985525 if (denied) return denied;
54995526 const removed = deleteAgent(
src/web/chrome.ts +26
@@ -24,6 +24,7 @@ import type { Repo } from "../core/repos.ts";
2424 import type { Ctx } from "../http/context.ts";
2525 import { html, raw, when, type Html } from "./html.ts";
2626 import { icon } from "./icons.ts";
27 import { ADMIN_ONLY, isMember } from "../core/roles.ts";
2728 import { page, redirect, type PaletteItem } from "./layout.ts";
2829 import {
2930 browseActions,
@@ -83,6 +84,31 @@ export function notFoundPage(ctx: Ctx): Response {
8384
8485 export const repoNotFound = notFoundPage;
8586
87 /**
88 * What a non-admin meets on an admin page: a member is told plainly it is
89 * not theirs to change (403); anyone else gets the usual 404.
90 */
91 export function adminOnlyPage(ctx: Ctx): Response {
92 const user = ctx.auth.user;
93 if (user === undefined || !isMember(ctx.app.db, user)) return notFoundPage(ctx);
94 return page(
95 {
96 ctx,
97 title: "Not allowed",
98 body: html`<div class="page-head"><h1>403</h1></div>
99 ${empty({
100 icon: "search",

Nit: the search icon suggests "not found" on a page whose message is "not yours to change". A lock or shield icon, if icons.ts has one, would match the message.

101 title: "Not yours to change",
102 note: capitalized(ADMIN_ONLY) + ".",
103 action: btn("Go home", { href: "/", variant: "primary" }),
104 })}`,
105 },
106 403,
107 );
108 }
109
110 const capitalized = (s: string): string => s.charAt(0).toUpperCase() + s.slice(1);
111
86112 /** Send an anonymous visitor to sign in, and back where they were going. */
87113 export function signInFirst(ctx: Ctx): Response {
88114 return redirect(signInHref(ctx));
src/web/pages/accounts.ts +11 −6
@@ -28,7 +28,12 @@ import {
2828 } from "../../core/orgs.ts";
2929 import { getUserByName } from "../../core/users.ts";
3030 import type { Ctx } from "../../http/context.ts";
31 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
31 import {
32 adminOnlyPage,
33 notFoundPage,
34 settingsLayout,
35 signInFirst,
36 } from "../chrome.ts";
3237 import { field, readForm } from "../form.ts";
3338 import { html, type Html } from "../html.ts";
3439 import { flashTo, page } from "../layout.ts";
@@ -256,7 +261,7 @@ function refuseRemove(username: string): Html {
256261 // GET /settings/accounts/:username — where one person is signed in
257262 export function personSignInsPage(ctx: Ctx): Response {
258263 if (!ctx.auth.user) return signInFirst(ctx);
259 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
264 if (!ctx.auth.user.isAdmin) return adminOnlyPage(ctx);
260265 const named = getUserByName(ctx.app.db, ctx.params.username ?? "");
261266 // An organization has no sign-ins: its page is its spend ceilings.
262267 if (named?.kind === "org" && ctx.auth.user.kind === "user")
@@ -312,7 +317,7 @@ export function personSignInsPage(ctx: Ctx): Response {
312317 export function signInAct(what: "token" | "session") {
313318 return async (ctx: Ctx): Promise<Response> => {
314319 if (!ctx.auth.user) return signInFirst(ctx);
315 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
320 if (!ctx.auth.user.isAdmin) return adminOnlyPage(ctx);
316321 const form = await readForm(ctx, "admin");
317322 if (form instanceof Response) return form;
318323 const username = ctx.params.username ?? "";
@@ -347,7 +352,7 @@ const DONE: Readonly<Record<Act, string>> = {
347352 export function accountAct(act: Act) {
348353 return async (ctx: Ctx): Promise<Response> => {
349354 if (!ctx.auth.user) return signInFirst(ctx);
350 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
355 if (!ctx.auth.user.isAdmin) return adminOnlyPage(ctx);
351356 const form = await readForm(ctx, "admin");
352357 if (form instanceof Response) return form;
353358 const username = ctx.params.username ?? "";
@@ -392,7 +397,7 @@ export function accountAct(act: Act) {
392397 // GET /settings/accounts/:username/retire — everything removal would take; removes nothing
393398 export function retirePage(ctx: Ctx): Response {
394399 if (!ctx.auth.user) return signInFirst(ctx);
395 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
400 if (!ctx.auth.user.isAdmin) return adminOnlyPage(ctx);
396401 const username = ctx.params.username ?? "";
397402 const plan = retirementPlan(ctx.app, ctx.auth.user, username);
398403 if (!plan.ok)
@@ -461,7 +466,7 @@ export function retirePage(ctx: Ctx): Response {
461466 // POST /settings/accounts/:username/retire
462467 export async function retireAct(ctx: Ctx): Promise<Response> {
463468 if (!ctx.auth.user) return signInFirst(ctx);
464 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
469 if (!ctx.auth.user.isAdmin) return adminOnlyPage(ctx);
465470 const form = await readForm(ctx, "admin");
466471 if (form instanceof Response) return form;
467472 const username = ctx.params.username ?? "";
src/web/pages/crew.ts +7 −2
@@ -24,7 +24,12 @@ import { MODELS } from "../../crew/models.ts";
2424 import type { Ctx } from "../../http/context.ts";
2525 import { autonomyStatus, type AutonomyStatus } from "../../crew/autonomy.ts";
2626 import { listAutonomousRepos, type Repo } from "../../core/repos.ts";
27 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
27 import {
28 adminOnlyPage,
29 notFoundPage,
30 settingsLayout,
31 signInFirst,
32 } from "../chrome.ts";
2833 import { field, readForm, type Form } from "../form.ts";
2934 import { html, when, type Html } from "../html.ts";
3035 import { flashTo, page } from "../layout.ts";
@@ -46,7 +51,7 @@ import { limitValue } from "../../settings/limits.ts";
4651 /** The admin, or the response that turns everyone else away. */
4752 function requireAdmin(ctx: Ctx): Response | undefined {
4853 if (!ctx.auth.user) return signInFirst(ctx);
49 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
54 if (!ctx.auth.user.isAdmin) return adminOnlyPage(ctx);
5055 return undefined;
5156 }
5257
src/web/pages/model.ts +8 −3
@@ -17,7 +17,12 @@ import {
1717 import { API_BASE_MAX } from "../../core/subscriptions.ts";
1818 import type { User } from "../../core/users.ts";
1919 import type { Ctx } from "../../http/context.ts";
20 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
20 import {
21 adminOnlyPage,
22 notFoundPage,
23 settingsLayout,
24 signInFirst,
25 } from "../chrome.ts";
2126 import { field, readForm } from "../form.ts";
2227 import { html, type Html } from "../html.ts";
2328 import { flashTo, page } from "../layout.ts";
@@ -148,7 +153,7 @@ export function grantCard(ctx: Ctx, user: User, at: string): Html {
148153 // POST /settings/accounts/:username/model
149154 export async function grantAct(ctx: Ctx): Promise<Response> {
150155 if (!ctx.auth.user) return signInFirst(ctx);
151 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
156 if (!ctx.auth.user.isAdmin) return adminOnlyPage(ctx);
152157 const form = await readForm(ctx, "admin");
153158 if (form instanceof Response) return form;
154159 const username = ctx.params.username ?? "";
@@ -177,7 +182,7 @@ export async function grantAct(ctx: Ctx): Promise<Response> {
177182 // POST /settings/accounts/:username/ceiling
178183 export async function ceilingAct(ctx: Ctx): Promise<Response> {
179184 if (!ctx.auth.user) return signInFirst(ctx);
180 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
185 if (!ctx.auth.user.isAdmin) return adminOnlyPage(ctx);
181186 const form = await readForm(ctx, "admin");
182187 if (form instanceof Response) return form;
183188 const username = ctx.params.username ?? "";
src/web/pages/people.ts +8 −3
@@ -10,7 +10,12 @@ import { GRANT_MAX_USD } from "../../core/model_grant.ts";
1010 import { listPeople, type Person } from "../../core/roles.ts";
1111 import { getUserByName, type User } from "../../core/users.ts";
1212 import type { Ctx } from "../../http/context.ts";
13 import { notFoundPage, settingsLayout, signInFirst } from "../chrome.ts";
13 import {
14 adminOnlyPage,
15 notFoundPage,
16 settingsLayout,
17 signInFirst,
18 } from "../chrome.ts";
1419 import { field, readForm } from "../form.ts";
1520 import { html } from "../html.ts";
1621 import { flashTo, page } from "../layout.ts";
@@ -20,7 +25,7 @@ import { accountSections } from "./origins.ts";
2025 // GET /settings/people
2126 export function peoplePage(ctx: Ctx): Response {
2227 if (!ctx.auth.user) return signInFirst(ctx);
23 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
28 if (!ctx.auth.user.isAdmin) return adminOnlyPage(ctx);
2429 const rows = listPeople(ctx.app.db);
2530 const line = (p: Person) => {
2631 const role = p.role;
@@ -74,7 +79,7 @@ export function peoplePage(ctx: Ctx): Response {
7479 // POST /settings/people/:username/role
7580 export async function roleAct(ctx: Ctx): Promise<Response> {
7681 if (!ctx.auth.user) return signInFirst(ctx);
77 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
82 if (!ctx.auth.user.isAdmin) return adminOnlyPage(ctx);
7883 const form = await readForm(ctx, "admin");
7984 if (form instanceof Response) return form;
8085 const username = ctx.params.username ?? "";
test/members.test.ts added +143
@@ -0,0 +1,143 @@
1 /**
2 * Roles, part 3b (#2385): a member cannot change another account or the
3 * crew's standing instructions (403 on the API, a plain line on the page),
4 * still changes their own account, and the owner succeeds.
5 */
6
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createAgent } from "../src/actions/crew.ts";
13 import { ADMIN_ONLY, setMember } from "../src/core/roles.ts";
14 import { createSession } from "../src/core/sessions.ts";
15 import { createToken } from "../src/core/tokens.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { quietLogs } from "./helpers/globals.ts";
19
20 quietLogs();
21
22 describe("a member cannot change another account or the crew's instructions", () => {
23 let dataDir = "";
24 let app: App;
25 let servers: Servers;
26 let alice: User; // admin
27 let bob: User; // guest
28 let carol: User; // member
29
30 const token = (u: User) => createToken(app.db, u.id, "t", "admin").token;
31 const cookie = (u: User) => `forge_session=${createSession(app.db, u.id).token}`;
32 const api = (method: string, path: string, u: User, body: unknown = {}) =>
33 fetch(`${servers.url}${path}`, {
34 method,
35 headers: { "content-type": "application/json", authorization: `Bearer ${token(u)}` },
36 body: method === "GET" ? null : JSON.stringify(body),
37 });
38 const form = (path: string, u: User, fields: Record<string, string>) =>
39 fetch(`${servers.url}${path}`, {
40 method: "POST",
41 headers: { cookie: cookie(u), origin: servers.url },
42 body: new URLSearchParams(fields),
43 redirect: "manual",
44 });
45 const mk = async (username: string, adminIfFirst = false) => {
46 const r = await createUser(app.db, {
47 trusted: true,
48 username,
49 email: `${username}@forge.local`,
50 password: "a-good-passphrase",
51 ...(adminIfFirst ? { adminIfFirst: true } : {}),
52 });
53 if (!r.ok) throw new Error(r.error);
54 return r.value;
55 };
56
57 beforeAll(async () => {
58 dataDir = await mkdtemp(join(tmpdir(), "forge-members-"));
59 app = createApp({ dataDir, port: 0 });
60 servers = await serve(app);
61 alice = await mk("alice", true);
62 bob = await mk("bob");
63 carol = await mk("carol");
64 setMember(app.db, carol.id, true, alice.id, new Date());
65 const agent = await createAgent(app, alice, { username: "helper" });
66 if (!agent.ok) throw new Error(String(agent.error));
67 }, 60_000);
68
69 afterAll(async () => {
70 servers.stop();
71 app.close();
72 await rm(dataDir, { recursive: true, force: true });
73 });
74
75 const acts: [string, string, string, unknown][] = [
76 ["role", "POST", "/api/v1/admin/accounts/bob/role", { role: "member" }],
77 ["model grant", "POST", "/api/v1/admin/accounts/bob/model-grant", { usdPerMonth: 5 }],
78 ["ceiling", "POST", "/api/v1/admin/accounts/bob/ceiling", { dailyUsd: 5, perRunUsd: 1 }],
79 ["verify", "POST", "/api/v1/admin/accounts/bob/verify", {}],
80 ["suspend", "POST", "/api/v1/admin/accounts/bob/suspend", {}],
81 ["its tokens", "GET", "/api/v1/users/bob/signins", {}],
82 ["its sessions", "DELETE", "/api/v1/users/bob/sessions/x", {}],
83 ["standing instructions", "PATCH", "/api/v1/agents/helper", { brief: "Always do the thing." }],
84 ];
85
86 for (const [name, method, path, body] of acts) {
87 test(`API: a member is refused ${name} with 403`, async () => {
88 const res = await api(method, path, carol, body);
89 expect(res.status).toBe(403);
90 expect(await res.json()).toMatchObject({ message: ADMIN_ONLY });
91 });
92 }
93
94 test("API: a guest still meets no door, and the owner succeeds", async () => {
95 expect((await api("POST", "/api/v1/admin/accounts/bob/role", bob, { role: "member" })).status).toBe(404);
96 expect((await api("POST", "/api/v1/admin/accounts/bob/role", alice, { role: "member" })).status).toBe(200);
97 expect((await api("POST", "/api/v1/admin/accounts/bob/role", alice, { role: "guest" })).status).toBe(200);
98 expect((await api("GET", "/api/v1/users/bob/signins", alice)).status).toBe(200);
99 const patched = await api("PATCH", "/api/v1/agents/helper", alice, { brief: "Be kind." });
100 expect(patched.status).toBe(200);
101 });
102
103 test("the brief was not changed by the refused member", async () => {
104 const res = await api("GET", "/api/v1/agents/helper", alice);
105 expect(JSON.stringify(await res.json())).not.toContain("Always do the thing.");
106 });
107
108 test("API: a member still changes their own account", async () => {
109 const res = await api("PATCH", "/api/v1/user", carol, { displayName: "Carol C" });
110 expect(res.status).toBe(200);
111 expect((await api("GET", "/api/v1/users/carol/signins", carol)).status).toBe(200);
112 const pw = await api("POST", "/api/v1/user/password", carol, {
113 current: "a-good-passphrase",
114 next: "another-good-passphrase",
115 });
116 expect(pw.status).toBe(200);
117 });
118
119 const pages: [string, string, Record<string, string>][] = [
120 ["role", "/settings/people/bob/role", { role: "member" }],
121 ["model grant", "/settings/accounts/bob/model", { usd: "5" }],
122 ["ceiling", "/settings/accounts/bob/ceiling", { daily: "5" }],
123 ["suspend", "/settings/accounts/bob/suspend", {}],
124 ["verify", "/settings/accounts/bob/verify", {}],
125 ["token", "/settings/accounts/bob/tokens/x/delete", {}],
126 ["standing instructions", "/settings/crew/helper", { model: "m", brief: "Mine now.", budgetUsd: "1" }],
127 ];
128
129 for (const [name, path, fields] of pages) {
130 test(`page: a member is told plainly ${name} is not theirs`, async () => {
131 const res = await form(path, carol, fields);
132 expect(res.status).toBe(403);
133 expect(await res.text()).toContain("Only the forge&#39;s owner can change another account");
134 });
135 }
136
137 test("page: the owner changes standing instructions and a role", async () => {
138 const crew = await form("/settings/crew/helper", alice, { model: "", brief: "Owner's brief.", budgetUsd: "1" });
139 expect(crew.status).toBe(303);
140 const role = await form("/settings/people/bob/role", alice, { role: "member" });
141 expect(role.status).toBe(303);
142 });
143 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs