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

The accounts page offers "remove the organization too" behind a confirm page that lists everything that will go #1579

Closed opened this
Closed without merging

scout/forge:scout/1488-the-accounts-page-offers-remove-the-orga → main 3 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
4 files changed +239 −4
README.md +3 −1
@@ -630,7 +630,9 @@ work here.
630630 do it: apps are stopped, repositories deleted, organizations retired (the
631631 name stays taken), then the account. If a repository will not go, the answer
632632 is 500 with `failed` and `removed`; what is left is intact and the same call
633 again finishes the job.
633 again finishes the job. The accounts page offers the same through a confirm
634 page at `/settings/accounts/:username/retire` that lists everything that
635 will go; the result is flashed back on the accounts page.
634636 - **Apps** — a repository that runs: production on the default branch, a
635637 preview per open pull with its own copy of the data, served by hostname
636638 from the forge's own port, every deploy a run and every run a check.
src/http/server.ts +4
@@ -16,6 +16,8 @@ import {
1616 import {
1717 accountAct,
1818 accountsPage,
19 retireAct,
20 retirePage,
1921 personSignInsPage,
2022 signInAct,
2123 } from "../web/pages/accounts.ts";
@@ -692,6 +694,8 @@ export function buildRouter(): Router<Handler> {
692694 accountAct("unsuspend"),
693695 );
694696 router.add("POST", "/settings/accounts/:username/remove", accountAct("remove"));
697 router.add("GET", "/settings/accounts/:username/retire", retirePage);
698 router.add("POST", "/settings/accounts/:username/retire", retireAct);
695699 router.add("POST", "/settings/accounts/:username/verify", accountAct("verify"));
696700 router.add("GET", "/settings/crew", crewPage);
697701 router.add("POST", "/settings/crew", agentCreate);
src/web/pages/accounts.ts +129 −3
@@ -8,6 +8,8 @@
88 import {
99 listAccounts,
1010 removeAccount,
11 retireAndRemoveAccount,
12 retirementPlan,
1113 suspendAccount,
1214 unsuspendAccount,
1315 verifyAccount,
@@ -225,6 +227,124 @@ function confirmSuspend(username: string, orgs: readonly string[]): Html {
225227 );
226228 }
227229
230 /** The refusal to remove a last owner, with the two ways forward. */
231 function refuseRemove(username: string, orgs: readonly string[]): Html {
232 const at = `/settings/accounts/${encodeURIComponent(username)}`;
233 return card(
234 html`<p>
235 <strong>${username}</strong> is the only person owning
236 ${orgs.join(", ")}. Make someone else an owner first, or remove the
237 organization too. Nothing was changed.
238 </p>
239 <div class="form-actions">
240 ${orgs[0] === undefined
241 ? null
242 : btn("Add an owner first", { href: ownersTeam(orgs[0]), size: "sm" })}
243 ${btn("Remove the organization too", {
244 href: `${at}/retire`,
245 size: "sm",
246 variant: "danger",
247 })}
248 </div>`,
249 { tone: "danger" },
250 );
251 }
252
253 // GET /settings/accounts/:username/retire — everything that would go; reads only
254 export function retirePage(ctx: Ctx): Response {
255 if (!ctx.auth.user) return signInFirst(ctx);
256 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
257 const username = ctx.params.username ?? "";
258 const plan = retirementPlan(ctx.app, ctx.auth.user, username);
259 if (!plan.ok) return notFoundPage(ctx);
260 if (plan.value.length === 0)
261 return flashTo(ctx, "/settings/accounts", {
262 message: `${username} owns no organization alone; nothing to retire.`,
263 });
264 const at = `/settings/accounts/${encodeURIComponent(username)}`;
265 return shell(
266 ctx,
267 card(
268 html`<ul class="rows">
269 ${plan.value.map(
270 (o) => html`<li class="row">
271 <div class="row-main">
272 <strong>${o.org}</strong> ${badge("organization")}
273 <div class="row-meta">
274 ${o.repos.length === 0
275 ? "no repositories"
276 : html`repositories:
277 ${o.repos.map(
278 (r, i) =>
279 html`${i > 0 ? ", " : ""}${r.name}${r.app === null
280 ? null
281 : html` (app ${r.app})`}`,
282 )}`}
283 </div>
284 <div class="row-meta">
285 teams: ${o.teams.length === 0 ? "none" : o.teams.join(", ")}
286 </div>
287 </div>
288 </li>`,
289 )}
290 </ul>
291 <p>Then the account <strong>${username}</strong> itself goes.</p>
292 <form method="post" action="${at}/retire" class="form-actions">
293 <input type="hidden" name="confirm" value="1" />
294 ${btn("Remove them all", { type: "submit", size: "sm", variant: "danger" })}
295 ${btn("Keep them", { href: "/settings/accounts", size: "sm", variant: "ghost" })}
296 </form>`,
297 {
298 tone: "attn",
299 head: html`<h2>Remove ${username} and what only they own</h2>
300 <p class="muted">
301 This deletes the organizations below with their repositories, apps
302 and teams, and cannot be undone. Nothing is removed until you
303 confirm.
304 </p>`,
305 },
306 ),
307 );
308 }
309
310 /** Names for a one-line message: the first few, then how many more. */
311 function some(names: readonly string[]): string {
312 return names.length <= 5
313 ? names.join(", ")
314 : `${names.slice(0, 5).join(", ")} and ${names.length - 5} more`;
315 }
316
317 // POST /settings/accounts/:username/retire
318 export async function retireAct(ctx: Ctx): Promise<Response> {
319 if (!ctx.auth.user) return signInFirst(ctx);
320 if (!ctx.auth.user.isAdmin) return notFoundPage(ctx);
321 const form = await readForm(ctx, "admin");
322 if (form instanceof Response) return form;
323 const username = ctx.params.username ?? "";
324 const done = await retireAndRemoveAccount(ctx.app, ctx.auth.user, username, {
325 confirmed: field(form, "confirm") === "1",
326 });
327 if (!done.ok) {
328 if (done.error === "not_found") return notFoundPage(ctx);
329 return flashTo(ctx, "/settings/accounts", {
330 message:
331 done.error === "not_allowed"
332 ? "You cannot do that to yourself, another admin, or an agent."
333 : "That needs your confirmation; nothing was changed.",
334 tone: "danger",
335 });
336 }
337 const { removed, failed } = done.value;
338 if (failed !== null)
339 return flashTo(ctx, "/settings/accounts", {
340 message: `${removed.length === 0 ? "Nothing was removed" : `Removed ${some(removed)}`}; ${failed} would not go. Try again to finish.`,

This partial-failure message, and the some() cut-off it relies on, is new web behaviour with no test. The API test covers the action, but not this text.

341 tone: "danger",
342 });
343 return flashTo(ctx, "/settings/accounts", {
344 message: removed.length === 0 ? `${username} was already removed.` : `Removed ${some(removed)}.`,
345 });
346 }
347
228348 // GET /settings/accounts/:username — where one person is signed in
229349 export function personSignInsPage(ctx: Ctx): Response {
230350 if (!ctx.auth.user) return signInFirst(ctx);
@@ -324,6 +444,14 @@ export function accountAct(act: Act) {
324444 : await removeAccount(ctx.app, ctx.auth.user, username);
325445 if (!done.ok) {
326446 if (done.error === "not_found") return notFoundPage(ctx);
447 if (act === "remove" && done.error === "last_owner") {
448 const user = getUserByName(ctx.app.db, username);
449 const orgs =
450 user === undefined
451 ? []
452 : soleOwnedOrgs(ctx.app.db, user.id).map((o) => o.username);
453 return accountsView(ctx, refuseRemove(username, orgs), 409);
454 }
327455 if (act === "suspend" && done.error === "last_owner") {
328456 const user = getUserByName(ctx.app.db, username);
329457 const orgs =
@@ -336,9 +464,7 @@ export function accountAct(act: Act) {
336464 message:
337465 done.error === "not_allowed"
338466 ? "You cannot do that to yourself, another admin, or an agent."
339 : done.error === "last_owner"
340 ? `${username} is the only person owning an organization (named in their row). Make someone else an owner first; nothing was changed.`
341 : "That did not finish; nothing was lost. Try again.",
467 : "That did not finish; nothing was lost. Try again.",
342468 tone: "danger",
343469 });
344470 }
test/accounts.test.ts +103
@@ -555,6 +555,109 @@ describe("accounts: the owner sees, suspends and removes", () => {
555555 expect(getUserByName(app.db, "sam")?.removedAt).not.toBeNull();
556556 });
557557
558 test("the accounts page offers a confirm page that lists what goes; only the confirmed POST removes it", async () => {
559 const { user: boss, token: bossToken } = await outsider("tess");
560 const org = createOrg(app.db, "tessco", boss.id);
561 if (!org.ok) throw new Error(org.error);
562 const made = await createRepo(app, org.value, { name: "ledger" });
563 if (!made.ok) throw new Error(made.error);
564 const bare = repoDir(app.reposRoot, "tessco", "ledger");
565 const auth = { authorization: `Bearer ${ownerToken}` };
566 const retire = "/settings/accounts/tess/retire";
567 const post = (headers: Record<string, string> = {}, body = "confirm=1", token = ownerToken) =>
568 fetch(`${base}${retire}`, {
569 method: "POST",
570 headers: {
571 authorization: `Bearer ${token}`,
572 "content-type": "application/x-www-form-urlencoded",
573 ...headers,
574 },
575 body,
576 redirect: "manual",
577 });
578 const flashOf = (res: Response) =>
579 decodeURIComponent(/forge_flash=([^;]*)/.exec(res.headers.get("set-cookie") ?? "")?.[1] ?? "");
580
581 // The refusal links to the confirm page.
582 const refused = await fetch(`${base}/settings/accounts/tess/remove`, {
583 method: "POST",
584 headers: { ...auth, "content-type": "application/x-www-form-urlencoded" },
585 });
586 expect(refused.status).toBe(409);
587 expect(await refused.text()).toContain(`href="${retire}"`);
588
589 // Reading the confirm page changes nothing.
590 const seen = await fetch(`${base}${retire}`, { headers: auth });
591 expect(seen.status).toBe(200);
592 const text = await seen.text();
593 expect(text).toContain("tessco/ledger");
594 expect(text).toContain("Owners");
595 expect(existsSync(bare)).toBe(true);
596 expect(getUserByName(app.db, "tess")?.removedAt).toBeNull();
597 expect(getUserByName(app.db, "tessco")?.removedAt).toBeNull();
598
599 // A non-admin gets neither page; a stranger's POST does nothing.
600 expect((await fetch(`${base}${retire}`, { headers: { authorization: `Bearer ${bossToken}` } })).status).toBe(404);
601 expect((await post({}, "confirm=1", bossToken)).status).toBe(404);
602 // Cross-origin is refused.
outdated

The same applies here: the 200 is the accounts page after the redirect. Assert the flash says the action needs confirmation, so a regression in the confirm_required branch of retireAct would fail this test.

603 expect((await post({ origin: "https://evil.example" })).status).toBe(403);
604 // Without the confirm field nothing happens either.
605 const unconfirmed = await post({}, "");
606 expect(unconfirmed.status).toBe(303);
607 expect(flashOf(unconfirmed)).toContain("needs your confirmation");
outdated

Only the status and the side effects are checked here. Send this with redirect: "manual" and assert that the forge_flash cookie names what went (Removed tessco/ledger, tessco, tess.). That message is what this pull adds, and right now nothing tests it.

608 expect(existsSync(bare)).toBe(true);
609 expect(getUserByName(app.db, "tess")?.removedAt).toBeNull();
610
611 // Confirmed: it goes.
612 const done = await post({}, "confirm=1");
613 expect(done.status).toBe(303);
614 expect(flashOf(done)).toContain("Removed tessco/ledger, tessco, tess.");
615 expect(existsSync(bare)).toBe(false);
616 expect(getUserByName(app.db, "tessco")?.removedAt).not.toBeNull();
617 expect(getUserByName(app.db, "tess")?.removedAt).not.toBeNull();
618 });
619
620 test("the confirm page's flash names a partial failure, and cuts a long list at five", async () => {
621 const flashOf = (res: Response) =>
622 decodeURIComponent(/forge_flash=([^;]*)/.exec(res.headers.get("set-cookie") ?? "")?.[1] ?? "");
623 const confirm = (name: string) =>
624 fetch(`${base}/settings/accounts/${name}/retire`, {
625 method: "POST",
626 headers: {
627 authorization: `Bearer ${ownerToken}`,
628 "content-type": "application/x-www-form-urlencoded",
629 },
630 body: "confirm=1",
631 redirect: "manual",
632 });
633
634 const { user: boss } = await outsider("pat");
635 const org = createOrg(app.db, "patco", boss.id);
636 if (!org.ok) throw new Error(org.error);
637 for (const name of ["one", "two"]) {
638 const made = await createRepo(app, org.value, { name });
639 if (!made.ok) throw new Error(made.error);
640 }
641 const [first, second] = listReposOwnedBy(app.db, org.value.id).map((r) => r.name) as [string, string];
642 const secondDir = repoDir(app.reposRoot, "patco", second);
643 renameSync(secondDir, `${secondDir}.parked`);
644 const partial = await confirm("pat");
645 expect(partial.status).toBe(303);
646 expect(flashOf(partial)).toContain(
647 `Removed patco/${first}; patco/${second} would not go. Try again to finish.`,
648 );
649
650 const { user: big } = await outsider("max");
651 const bigOrg = createOrg(app.db, "maxco", big.id);
652 if (!bigOrg.ok) throw new Error(bigOrg.error);
653 for (const name of ["a", "b", "c", "d", "e", "f"]) {
654 const made = await createRepo(app, bigOrg.value, { name });
655 if (!made.ok) throw new Error(made.error);
656 }
657 const long = flashOf(await confirm("max"));
658 expect(long).toContain("Removed maxco/a, maxco/b, maxco/c, maxco/d, maxco/e and 3 more.");
659 });
660
558661 test("an account with nothing in it can be removed too", async () => {
559662 await outsider("empty");
560663 const res = await api("/api/v1/admin/accounts/empty", {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs