Public: anyone can read this; the crew can change it.
Removing an organization's last owner can retire the organization and its repositories with them, after a confirm page (destructive) #1435
scout/forge:scout/1069-removing-an-organization-s-last-owner-ca → main 4 commits fork
6 files
changed +436
−9
scripts/gate.ts +1
| @@ -193,6 +193,7 @@ export const GATE: readonly string[] = [ | ||
| 193 | 193 | "test/notify.test.ts", |
| 194 | 194 | "test/onboarding.test.ts", |
| 195 | 195 | "test/org-owners.test.ts", |
| 196 | "test/org-removal.test.ts", | |
| 196 | 197 | "test/origins-oauth.test.ts", |
| 197 | 198 | "test/origins-operator.test.ts", |
| 198 | 199 | "test/origins-reconnect.test.ts", |
src/actions/accounts.ts +104 −6
| @@ -12,7 +12,8 @@ | ||
| 12 | 12 | |
| 13 | 13 | import type { Database } from "bun:sqlite"; |
| 14 | 14 | import type { App } from "../app.ts"; |
| 15 | import { soleOwnedOrgs } from "../core/orgs.ts"; | |
| 15 | import { listTeams, soleOwnedOrgs } from "../core/orgs.ts"; | |
| 16 | import { appsForRepos } from "../core/apps.ts"; | |
| 16 | 17 | import { appsRuntime } from "../apps/runtime.ts"; |
| 17 | 18 | import { |
| 18 | 19 | dropCredentials, |
| @@ -21,7 +22,7 @@ import { | ||
| 21 | 22 | setSuspended, |
| 22 | 23 | type AccountRow, |
| 23 | 24 | } from "../core/accounts.ts"; |
| 24 | import { deleteRepo as destroyRepo, listReposOwnedBy } from "../core/repos.ts"; | |
| 25 | import { deleteRepo as destroyRepo, listReposOwnedBy, type Repo } from "../core/repos.ts"; | |
| 25 | 26 | import { listActive } from "../core/runs.ts"; |
| 26 | 27 | import { getUserByName, type User } from "../core/users.ts"; |
| 27 | 28 | import { markVerified } from "../core/verify.ts"; |
| @@ -123,11 +124,72 @@ export function unsuspendAccount( | ||
| 123 | 124 | return ok(getUserByName(app.db, username)!); |
| 124 | 125 | } |
| 125 | 126 | |
| 127 | /** What removing an account together with the organizations it alone owns would delete. */ | |
| 128 | export interface OrgRemovalPlan { | |
| 129 | orgs: { | |
| 130 | name: string; | |
| 131 | teams: string[]; | |
| 132 | repos: { name: string; app: string | null }[]; | |
| 133 | }[]; | |
| 134 | } | |
| 135 | ||
| 136 | /** The confirm page's list: nothing is changed by asking. */ | |
| 137 | export function planOrgRemoval( | |
| 138 | app: App, | |
| 139 | actor: User | undefined, | |
| 140 | username: string, | |
| 141 | ): Result<OrgRemovalPlan, AccountActionError> { | |
| 142 | const admin = requireForgeAdmin(actor); | |
| 143 | if (!admin.ok) return admin; | |
| 144 | const found = target(app, admin.value, username); | |
| 145 | if (!found.ok) return found; | |
| 146 | if (found.value.removedAt !== null) return err("not_found"); | |
| 147 | const orgs = soleOwnedOrgs(app.db, found.value.id).map((org) => { | |
| 148 | const repos = listReposOwnedBy(app.db, org.id); | |
| 149 | const apps = appsForRepos( | |
| 150 | app.db, | |
| 151 | repos.map((r) => r.id), | |
| 152 | ); | |
| 153 | return { | |
| 154 | name: org.username, | |
| 155 | teams: listTeams(app.db, org.id).map((t) => t.name), | |
| 156 | repos: repos.map((r) => ({ | |
| 157 | name: r.name, | |
| 158 | app: apps.get(r.id)?.slug ?? null, | |
| 159 | })), | |
| 160 | }; | |
| 161 | }); | |
| 162 | return ok({ orgs }); | |
| 163 | } | |
| 164 | ||
| 165 | /** Where a removal stopped: what it had finished, and the repository it could not remove. */ | |
| 166 | export interface RemovalStopped { | |
| 167 | readonly ok: false; | |
| 168 | readonly error: "delete_failed"; | |
| 169 | /** `owner/name` of each repository, and the name of each organization, already gone. */ | |
| 170 | readonly removed: string[]; | |
| 171 | readonly failed: string; | |
| 172 | } | |
| 173 | ||
| 174 | /** The sentence that says what a stopped removal did and did not do. */ | |
| 175 | export function describeStopped(stopped: Pick<RemovalStopped, "removed" | "failed">): string { | |
| 176 | const done = stopped.removed.length > 0 ? `Removed ${stopped.removed.join(", ")}; ` : "Nothing was removed; "; | |
| 177 | return `${done}${stopped.failed} could not be removed. Run it again to finish.`; | |
| 178 | } | |
| 179 | ||
| 180 | /** | |
| 181 | * Remove an account. `removeOrganizations` is the owner's word, given on the | |
| 182 | * confirm page, that the organizations it alone owns go too: their | |
| 183 | * repositories (apps first), then their teams and the organization, then the | |
| 184 | * account. A failure stops there and says what was already removed (the rest | |
| 185 | * is intact); running it again finishes. Without it such an account is refused as `last_owner`. | |
| 186 | */ | |
| 126 | 187 | export async function removeAccount( |
| 127 | 188 | app: App, |
| 128 | 189 | actor: User | undefined, |
| 129 | 190 | username: string, |
| 130 | ): Promise<Result<void, AccountActionError | "delete_failed" | "last_owner">> { | |
| 191 | options: { removeOrganizations?: boolean } = {}, | |
| 192 | ): Promise<Result<void, AccountActionError | "last_owner"> | RemovalStopped> { | |
| 131 | 193 | const admin = requireForgeAdmin(actor); |
| 132 | 194 | if (!admin.ok) return admin; |
| 133 | 195 | const found = target(app, admin.value, username); |
| @@ -137,16 +199,52 @@ export async function removeAccount( | ||
| 137 | 199 | // An organization this account alone owns would be left with nobody to |
| 138 | 200 | // administer it: someone else is made an owner first (`soleOwnedOrgs` |
| 139 | 201 | // names them), and nothing here has changed yet. |
| 140 | if (soleOwnedOrgs(app.db, user.id).length > 0) return err("last_owner"); | |
| 202 | const sole = soleOwnedOrgs(app.db, user.id); | |
| 203 | if (sole.length > 0 && options.removeOrganizations !== true) | |
| 204 | return err("last_owner"); | |
| 141 | 205 | // Stop it first, so nothing it owns is running while it is taken apart. |
| 142 | 206 | setSuspended(app.db, user.id, new Date().toISOString()); |
| 143 | 207 | dropCredentials(app.db, user.id); |
| 144 | 208 | await quiet(app, admin.value, user); |
| 145 | 209 | const runtime = appsRuntime(app); |
| 146 | for (const repo of listReposOwnedBy(app.db, user.id)) { | |
| 210 | const removed: string[] = []; | |
| 211 | const stopped = (repo: Repo, owner: string): RemovalStopped => ({ | |
| 212 | ok: false, | |
| 213 | error: "delete_failed", | |
| 214 | removed, | |
| 215 | failed: `${owner}/${repo.name}`, | |
| 216 | }); | |
| 217 | const byName = (a: Repo, b: Repo) => a.name.localeCompare(b.name); | |
| 218 | for (const org of sole) { | |
| 219 | await quiet(app, admin.value, org); | |
| 220 | for (const repo of listReposOwnedBy(app.db, org.id).sort(byName)) { | |
| 221 | if (runtime !== undefined) await runtime.teardownAll(repo.id); | |
| 222 | const deleted = await destroyRepo(app.db, app.reposRoot, repo); | |
| 223 | if (!deleted.ok) return stopped(repo, org.username); | |
| 224 | removed.push(`${org.username}/${repo.name}`); | |
| 225 | app.bus.append({ | |
| 226 | kind: "repo.deleted", | |
| 227 | actorId: admin.value.id, | |
| 228 | payload: { org: org.username, repo: repo.name }, | |
| 229 | }); | |
| 230 | } | |
| 231 | // Teams and the organization go together, with no pause between: the | |
| 232 | // organization is never left standing without its owners. | |
| 233 | const teams = listTeams(app.db, org.id); | |
| 234 | app.db.query("DELETE FROM team WHERE org_id = ?1").run(org.id); | |
| 235 | scrubAccount(app.db, org.id, new Date().toISOString()); | |
| 236 | app.bus.append({ | |
| 237 | kind: "org.removed", | |
| 238 | actorId: admin.value.id, | |
| 239 | payload: { org: org.username, teams: teams.map((t) => t.name) }, | |
| 240 | }); | |
| 241 | removed.push(org.username); | |
| 242 | } | |
| 243 | for (const repo of listReposOwnedBy(app.db, user.id).sort(byName)) { | |
| 147 | 244 | if (runtime !== undefined) await runtime.teardownAll(repo.id); |
| 148 | 245 | const deleted = await destroyRepo(app.db, app.reposRoot, repo); |
| 149 | if (!deleted.ok) return deleted; | |
| 246 | if (!deleted.ok) return stopped(repo, user.username); | |
| 247 | removed.push(`${user.username}/${repo.name}`); | |
| 150 | 248 | } |
| 151 | 249 | scrubAccount(app.db, user.id, new Date().toISOString()); |
| 152 | 250 | app.bus.append({ |
src/http/api.ts +24 −2
| @@ -26,6 +26,8 @@ import { | ||
| 26 | 26 | } from "../core/asked.ts"; |
| 27 | 27 | import { |
| 28 | 28 | listAccounts, |
| 29 | planOrgRemoval, | |
| 30 | describeStopped, | |
| 29 | 31 | removeAccount, |
| 30 | 32 | suspendAccount, |
| 31 | 33 | unsuspendAccount, |
| @@ -1305,10 +1307,20 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1305 | 1307 | : accountError(done.error); |
| 1306 | 1308 | }); |
| 1307 | 1309 | |
| 1310 | router.add("GET", "/api/v1/admin/accounts/:username/removal", (ctx) => { | |
| 1311 | const denied = accountAdmin(ctx, "ro"); | |
| 1312 | if (denied) return denied; | |
| 1313 | const plan = planOrgRemoval(ctx.app, ctx.auth.user, ctx.params.username!); | |
| 1314 | return plan.ok ? json(plan.value) : accountError(plan.error); | |
| 1315 | }); | |
| 1316 | ||
| 1308 | 1317 | router.add("DELETE", "/api/v1/admin/accounts/:username", async (ctx) => { |
| 1309 | 1318 | const denied = accountAdmin(ctx, "admin"); |
| 1310 | 1319 | if (denied) return denied; |
| 1311 | const done = await removeAccount(ctx.app, ctx.auth.user, ctx.params.username!); | |
| 1320 | const input = await body(ctx.request); | |
| 1321 | const done = await removeAccount(ctx.app, ctx.auth.user, ctx.params.username!, { | |
| 1322 | removeOrganizations: input.removeOrganizations === true, | |
| 1323 | }); | |
| 1312 | 1324 | if (!done.ok && done.error === "last_owner") { |
| 1313 | 1325 | const user = getUserByName(ctx.app.db, ctx.params.username!); |
| 1314 | 1326 | const orgs = |
| @@ -1318,9 +1330,19 @@ export function apiRoutes(router: Router<Handler>): void { | ||
| 1318 | 1330 | return apiError( |
| 1319 | 1331 | "last_owner", |
| 1320 | 1332 | 409, |
| 1321 | `${ctx.params.username} is the only person owning ${orgs.join(", ")}: make someone else an owner first`, | |
| 1333 | `${ctx.params.username} is the only person owning ${orgs.join(", ")}: make someone else an owner first, or send {"removeOrganizations": true} to remove the organization, its repositories and teams too`, | |
| 1322 | 1334 | ); |
| 1323 | 1335 | } |
| 1336 | if (!done.ok && done.error === "delete_failed" && "removed" in done) | |
| 1337 | return json( | |
| 1338 | { | |
| 1339 | error: "delete_failed", | |
| 1340 | message: describeStopped(done), | |
| 1341 | removed: done.removed, | |
| 1342 | failed: done.failed, | |
| 1343 | }, | |
| 1344 | 500, | |
| 1345 | ); | |
| 1324 | 1346 | return done.ok ? json({ removed: ctx.params.username }) : accountError(done.error); |
| 1325 | 1347 | }); |
| 1326 | 1348 |
src/http/server.ts +6
| @@ -15,6 +15,7 @@ import { | ||
| 15 | 15 | } from "./caller.ts"; |
| 16 | 16 | import { |
| 17 | 17 | accountAct, |
| 18 | removeOrganizationPage, | |
| 18 | 19 | accountsPage, |
| 19 | 20 | personSignInsPage, |
| 20 | 21 | signInAct, |
| @@ -684,6 +685,11 @@ export function buildRouter(): Router<Handler> { | ||
| 684 | 685 | "/settings/accounts/:username/unsuspend", |
| 685 | 686 | accountAct("unsuspend"), |
| 686 | 687 | ); |
| 688 | router.add( | |
| 689 | "GET", | |
| 690 | "/settings/accounts/:username/remove-organization", | |
| 691 | removeOrganizationPage, | |
| 692 | ); | |
| 687 | 693 | router.add("POST", "/settings/accounts/:username/remove", accountAct("remove")); |
| 688 | 694 | router.add("POST", "/settings/accounts/:username/verify", accountAct("verify")); |
| 689 | 695 | router.add("GET", "/settings/crew", crewPage); |
src/web/pages/accounts.ts +87 −1
| @@ -7,6 +7,8 @@ | ||
| 7 | 7 | |
| 8 | 8 | import { |
| 9 | 9 | listAccounts, |
| 10 | planOrgRemoval, | |
| 11 | describeStopped, | |
| 10 | 12 | removeAccount, |
| 11 | 13 | suspendAccount, |
| 12 | 14 | unsuspendAccount, |
| @@ -225,6 +227,75 @@ function confirmSuspend(username: string, orgs: readonly string[]): Html { | ||
| 225 | 227 | ); |
| 226 | 228 | } |
| 227 | 229 | |
| 230 | /** The refusal to remove the only owner: add an owner, or go on to the confirm page. */ | |
| 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 active owner of | |
| 236 | ${orgs.join(", ")}. Nothing was changed. Make someone else an owner | |
| 237 | first, or remove ${orgs.length === 1 ? "the organization" : "the organizations"} | |
| 238 | too. | |
| 239 | </p> | |
| 240 | <div class="form-actions"> | |
| 241 | ${orgs[0] === undefined | |
| 242 | ? null | |
| 243 | : btn("Add an owner first", { href: ownersTeam(orgs[0]), size: "sm" })} | |
| 244 | ${btn("Remove the organization too", { | |
| 245 | href: `${at}/remove-organization`, | |
| 246 | size: "sm", | |
| 247 | variant: "danger", | |
| 248 | })} | |
| 249 | ${btn("Keep them", { href: "/settings/accounts", size: "sm", variant: "ghost" })} | |
| 250 | </div>`, | |
| 251 | { tone: "attn" }, | |
| 252 | ); | |
| 253 | } | |
| 254 | ||
| 255 | // GET /settings/accounts/:username/remove-organization — what would go | |
| 256 | export function removeOrganizationPage(ctx: Ctx): Response { | |
| 257 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 258 | if (!ctx.auth.user.isAdmin) return notFoundPage(ctx); | |
| 259 | const username = ctx.params.username ?? ""; | |
| 260 | const plan = planOrgRemoval(ctx.app, ctx.auth.user, username); | |
| 261 | if (!plan.ok || plan.value.orgs.length === 0) return notFoundPage(ctx); | |
| 262 | const at = `/settings/accounts/${encodeURIComponent(username)}`; | |
| 263 | return shell( | |
| 264 | ctx, | |
| 265 | card( | |
| 266 | html`<p> | |
| 267 | Removing <strong>${username}</strong> also removes everything below. | |
| 268 | This deletes data and cannot be undone. Nothing is removed until you | |
| 269 | confirm. | |
| 270 | </p> | |
| 271 | ${plan.value.orgs.map( | |
| 272 | (o) => html`<h3>${o.name}</h3> | |
| 273 | <p class="muted"> | |
| 274 | Teams: ${o.teams.length === 0 ? "none" : o.teams.join(", ")} | |
| 275 | </p> | |
| 276 | ${o.repos.length === 0 | |
| 277 | ? html`<p class="muted">No repositories.</p>` | |
| 278 | : html`<ul> | |
| 279 | ${o.repos.map( | |
| 280 | (r) => | |
| 281 | html`<li> | |
| 282 | ${o.name}/${r.name}${r.app === null | |
| 283 | ? null | |
| 284 | : html` — app ${r.app}`} | |
| 285 | </li>`, | |
| 286 | )} | |
| 287 | </ul>`}`, | |
| 288 | )} | |
| 289 | <form method="post" action="${at}/remove" class="form-actions"> | |
| 290 | <input type="hidden" name="remove_organizations" value="1" /> | |
| 291 | ${btn("Remove them all", { type: "submit", size: "sm", variant: "danger" })} | |
| 292 | ${btn("Keep them", { href: "/settings/accounts", size: "sm", variant: "ghost" })} | |
| 293 | </form>`, | |
| 294 | { tone: "attn" }, | |
| 295 | ), | |
| 296 | ); | |
| 297 | } | |
| 298 | ||
| 228 | 299 | // GET /settings/accounts/:username — where one person is signed in |
| 229 | 300 | export function personSignInsPage(ctx: Ctx): Response { |
| 230 | 301 | if (!ctx.auth.user) return signInFirst(ctx); |
| @@ -321,9 +392,19 @@ export function accountAct(act: Act) { | ||
| 321 | 392 | ? unsuspendAccount(ctx.app, ctx.auth.user, username) |
| 322 | 393 | : act === "verify" |
| 323 | 394 | ? verifyAccount(ctx.app, ctx.auth.user, username) |
| 324 | : await removeAccount(ctx.app, ctx.auth.user, username); | |
| 395 | : await removeAccount(ctx.app, ctx.auth.user, username, { | |
| 396 | removeOrganizations: field(form, "remove_organizations") === "1", | |
| 397 | }); | |
| 325 | 398 | if (!done.ok) { |
| 326 | 399 | if (done.error === "not_found") return notFoundPage(ctx); |
| 400 | if (act === "remove" && done.error === "last_owner") { | |
| 401 | const user = getUserByName(ctx.app.db, username); | |
| 402 | const orgs = | |
| 403 | user === undefined | |
| 404 | ? [] | |
| 405 | : soleOwnedOrgs(ctx.app.db, user.id).map((o) => o.username); | |
| 406 | return accountsView(ctx, refuseRemove(username, orgs), 409); | |
| 407 | } | |
| 327 | 408 | if (act === "suspend" && done.error === "last_owner") { |
| 328 | 409 | const user = getUserByName(ctx.app.db, username); |
| 329 | 410 | const orgs = |
| @@ -332,6 +413,11 @@ export function accountAct(act: Act) { | ||
| 332 | 413 | : soleOwnedOrgs(ctx.app.db, user.id).map((o) => o.username); |
| 333 | 414 | return accountsView(ctx, confirmSuspend(username, orgs), 409); |
| 334 | 415 | } |
| 416 | if (act === "remove" && done.error === "delete_failed" && "removed" in done) | |
| 417 | return flashTo(ctx, "/settings/accounts", { | |
| 418 | message: describeStopped(done), | |
| 419 | tone: "danger", | |
| 420 | }); | |
| 335 | 421 | return flashTo(ctx, "/settings/accounts", { |
| 336 | 422 | message: |
| 337 | 423 | done.error === "not_allowed" |
test/org-removal.test.ts added +214
| @@ -0,0 +1,214 @@ | ||
| 1 | /** | |
| 2 | * Removing the only owner of an organization can take the organization with | |
| 3 | * it (#1069), after a confirm page that lists what goes. Nothing changes | |
| 4 | * without the confirm; with it the repositories, teams, organization and | |
| 5 | * account go and each is recorded in the outbox. Admin only. | |
| 6 | */ | |
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { mkdtemp, rename, rm } from "node:fs/promises"; | |
| 9 | import { tmpdir } from "node:os"; | |
| 10 | import { join } from "node:path"; | |
| 11 | import { describeStopped, removeAccount } from "../src/actions/accounts.ts"; | |
| 12 | import { createOrg } from "../src/actions/orgs.ts"; | |
| 13 | import { createRepo } from "../src/actions/repos.ts"; | |
| 14 | import { createApp, type App } from "../src/app.ts"; | |
| 15 | import { createSession } from "../src/core/sessions.ts"; | |
| 16 | import { createToken } from "../src/core/tokens.ts"; | |
| 17 | import { createUser, getUserByName, type User } from "../src/core/users.ts"; | |
| 18 | import { forgeHttp, type ForgeHttp } from "../src/http/server.ts"; | |
| 19 | ||
| 20 | describe("removing an organization with its last owner", () => { | |
| 21 | let dataDir: string; | |
| 22 | let app: App; | |
| 23 | let http: ForgeHttp; | |
| 24 | const base = "http://localhost"; | |
| 25 | let root: User; | |
| 26 | let bob: User; | |
| 27 | let rootToken = ""; | |
| 28 | let bobToken = ""; | |
| 29 | let rootCookie = ""; | |
| 30 | let bobCookie = ""; | |
| 31 | ||
| 32 | const make = async (name: string, first: boolean): Promise<User> => { | |
| 33 | const made = await createUser(app.db, { | |
| 34 | trusted: true, | |
| 35 | username: name, | |
| 36 | email: `${name}@forge.local`, | |
| 37 | password: "a-good-passphrase", | |
| 38 | adminIfFirst: first, | |
| 39 | }); | |
| 40 | if (!made.ok) throw new Error(made.error); | |
| 41 | return made.value; | |
| 42 | }; | |
| 43 | const events = (kind: string) => | |
| 44 | app.db.query("SELECT id FROM event WHERE kind = ?1").all(kind).length; | |
| 45 | const go = (url: string, init?: RequestInit) => | |
| 46 | http.handle(new Request(url, init)); | |
| 47 | const form = (cookie: string, path: string, data: Record<string, string>) => | |
| 48 | go(`${base}${path}`, { | |
| 49 | method: "POST", | |
| 50 | redirect: "manual", | |
| 51 | headers: { | |
| 52 | cookie, | |
| 53 | origin: base, | |
| 54 | "content-type": "application/x-www-form-urlencoded", | |
| 55 | }, | |
| 56 | body: new URLSearchParams(data).toString(), | |
| 57 | }); | |
| 58 | ||
| 59 | beforeAll(async () => { | |
| 60 | dataDir = await mkdtemp(join(tmpdir(), "forge-org-removal-")); | |
| 61 | app = createApp({ dataDir, port: 0 }); | |
| 62 | http = forgeHttp(app); | |
| 63 | root = await make("alice", true); | |
| 64 | bob = await make("bob", false); | |
| 65 | rootToken = createToken(app.db, root.id, "t", "admin").token; | |
| 66 | bobToken = createToken(app.db, bob.id, "t", "admin").token; | |
| 67 | rootCookie = `forge_session=${createSession(app.db, root.id).token}`; | |
| 68 | bobCookie = `forge_session=${createSession(app.db, bob.id).token}`; | |
| 69 | const org = createOrg(app, bob, "acme"); | |
| 70 | if (!org.ok) throw new Error(String(org.error)); | |
| 71 | for (const name of ["site", "docs"]) { | |
| 72 | const made = await createRepo(app, bob, { name, owner: "acme" }); | |
| 73 | if (!made.ok) throw new Error(made.error); | |
| 74 | } | |
| 75 | }, 60_000); | |
| 76 | ||
| 77 | afterAll(async () => { | |
| 78 | http.close(); | |
| 79 | await rm(dataDir, { recursive: true, force: true }); | |
| 80 | }); | |
| 81 | ||
| 82 | test("the refusal stands, and the confirm page lists the organization, repositories and teams without changing anything", async () => { | |
| 83 | const refused = await removeAccount(app, root, "bob"); | |
| 84 | expect(refused.ok).toBe(false); | |
| 85 | const res = await go(`${base}/settings/accounts/bob/remove-organization`, { | |
| 86 | headers: { cookie: rootCookie }, | |
| 87 | }); | |
| 88 | expect(res.status).toBe(200); | |
| 89 | const page = await res.text(); | |
| 90 | expect(page).toContain("acme"); | |
| 91 | expect(page).toContain("acme/site"); | |
| 92 | expect(page).toContain("acme/docs"); | |
| 93 | expect(page).toContain("Owners"); | |
| 94 | const plan = await go(`${base}/api/v1/admin/accounts/bob/removal`, { | |
| 95 | headers: { authorization: `Bearer ${rootToken}` }, | |
| 96 | }); | |
| 97 | expect(((await plan.json()) as any).orgs[0].repos).toHaveLength(2); | |
| 98 | expect(getUserByName(app.db, "acme")!.removedAt).toBeNull(); | |
| 99 | expect(getUserByName(app.db, "bob")!.removedAt).toBeNull(); | |
| 100 | }); | |
| 101 | ||
| 102 | test("the web removal without the confirm field changes nothing and points to the confirm page", async () => { | |
| 103 | const res = await form(rootCookie, "/settings/accounts/bob/remove", {}); | |
| 104 | expect(res.status).toBe(409); | |
| 105 | expect(await res.text()).toContain("remove-organization"); | |
| 106 | expect(getUserByName(app.db, "acme")!.removedAt).toBeNull(); | |
| 107 | }); | |
| 108 | ||
| 109 | test("a non-admin reaches neither page nor the API", async () => { | |
| 110 | const page = await go(`${base}/settings/accounts/bob/remove-organization`, { | |
| 111 | headers: { cookie: bobCookie }, | |
| 112 | }); | |
| 113 | expect(page.status).toBe(404); | |
| 114 | const post = await form(bobCookie, "/settings/accounts/bob/remove", { | |
| 115 | remove_organizations: "1", | |
| 116 | }); | |
| 117 | expect(post.status).toBe(404); | |
| 118 | const api = await go(`${base}/api/v1/admin/accounts/bob`, { | |
| 119 | method: "DELETE", | |
| 120 | headers: { | |
| 121 | authorization: `Bearer ${bobToken}`, | |
| 122 | "content-type": "application/json", | |
| 123 | }, | |
| 124 | body: JSON.stringify({ removeOrganizations: true }), | |
| 125 | }); | |
| 126 | expect(api.status).toBe(404); | |
| 127 | expect(getUserByName(app.db, "acme")!.removedAt).toBeNull(); | |
| 128 | }); | |
| 129 | ||
| 130 | test("the API refuses without the explicit field", async () => { | |
| 131 | const res = await go(`${base}/api/v1/admin/accounts/bob`, { | |
| 132 | method: "DELETE", | |
| 133 | headers: { authorization: `Bearer ${rootToken}` }, | |
| 134 | }); | |
| 135 | expect(res.status).toBe(409); | |
| 136 | expect(((await res.json()) as any).error).toBe("last_owner"); | |
| 137 | expect(getUserByName(app.db, "acme")!.removedAt).toBeNull(); | |
| 138 | }); | |
| 139 | ||
| 140 | test("a failure partway names what was removed, leaves the rest, and a second confirm finishes", async () => { | |
| 141 | const carol = await make("carol", false); | |
| 142 | const org = createOrg(app, carol, "zeta"); | |
| 143 | if (!org.ok) throw new Error(String(org.error)); | |
| 144 | for (const name of ["alpha", "beta"]) { | |
| 145 | const made = await createRepo(app, carol, { name, owner: "zeta" }); | |
| 146 | if (!made.ok) throw new Error(made.error); | |
| 147 | } | |
| 148 | // alpha goes first (by name); beta cannot be removed: its directory is no longer a repository. | |
| 149 | const head = join(app.reposRoot, "zeta", "beta.git", "HEAD"); | |
| 150 | await rename(head, `${head}.hidden`); | |
| 151 | const before = { repo: events("repo.deleted"), org: events("org.removed"), account: events("account.removed") }; | |
| 152 | const api = await go(`${base}/api/v1/admin/accounts/carol`, { | |
| 153 | method: "DELETE", | |
| 154 | headers: { authorization: `Bearer ${rootToken}`, "content-type": "application/json" }, | |
| 155 | body: JSON.stringify({ removeOrganizations: true }), | |
| 156 | }); | |
| 157 | expect(api.status).toBe(500); | |
| 158 | const out = (await api.json()) as any; | |
| 159 | expect(out.removed).toEqual(["zeta/alpha"]); | |
| 160 | expect(out.failed).toBe("zeta/beta"); | |
| 161 | expect(out.message).toContain("Removed zeta/alpha"); | |
| 162 | expect(out.message).toContain("zeta/beta could not be removed"); | |
| 163 | expect(out.message).not.toContain("nothing was lost"); | |
| 164 | expect(events("repo.deleted")).toBe(before.repo + 1); | |
| 165 | expect(getUserByName(app.db, "zeta")!.removedAt).toBeNull(); | |
| 166 | expect(getUserByName(app.db, "carol")!.removedAt).toBeNull(); | |
| 167 | expect(events("org.removed")).toBe(before.org); | |
| 168 | expect(events("account.removed")).toBe(before.account); | |
| 169 | // The web form says the same on the page, then finishes on the second confirm. | |
| 170 | const again = await form(rootCookie, "/settings/accounts/carol/remove", { remove_organizations: "1" }); | |
| 171 | expect(again.status).toBe(303); | |
| 172 | const jar = [rootCookie, ...again.headers.getSetCookie().map((c) => c.split(";")[0]!)].join("; "); | |
| 173 | const page = await go(`${base}${again.headers.get("location")}`, { headers: { cookie: jar } }); | |
| 174 | expect(await page.text()).not.toContain("nothing was lost"); | |
| 175 | expect(getUserByName(app.db, "carol")!.removedAt).not.toBeNull(); | |
| 176 | expect(getUserByName(app.db, "zeta")!.removedAt).not.toBeNull(); | |
| 177 | expect(events("org.removed")).toBe(before.org + 1); | |
| 178 | expect(events("account.removed")).toBe(before.account + 1); | |
| 179 | }); | |
| 180 | ||
| 181 | test("the sentence for a stopped removal names what went and what did not", () => { | |
| 182 | expect(describeStopped({ removed: ["acme/site"], failed: "acme/docs" })).toBe( | |
| 183 | "Removed acme/site; acme/docs could not be removed. Run it again to finish.", | |
| 184 | ); | |
| 185 | expect(describeStopped({ removed: [], failed: "acme/docs" })).toContain("Nothing was removed"); | |
| 186 | }); | |
| 187 | ||
| 188 | test("confirming removes the repositories, teams, organization and account, and records each", async () => { | |
| 189 | const before = { | |
| 190 | repo: events("repo.deleted"), | |
| 191 | org: events("org.removed"), | |
| 192 | account: events("account.removed"), | |
| 193 | }; | |
| 194 | const res = await form(rootCookie, "/settings/accounts/bob/remove", { | |
| 195 | remove_organizations: "1", | |
| 196 | }); | |
| 197 | expect(res.status).toBe(303); | |
| 198 | expect(getUserByName(app.db, "acme")!.removedAt).not.toBeNull(); | |
| 199 | expect(getUserByName(app.db, "bob")!.removedAt).not.toBeNull(); | |
| 200 | expect( | |
| 201 | app.db.query("SELECT 1 FROM repo WHERE owner_id = ?1").all( | |
| 202 | getUserByName(app.db, "acme")!.id, | |
| 203 | ), | |
| 204 | ).toHaveLength(0); | |
| 205 | expect( | |
| 206 | app.db.query("SELECT 1 FROM team WHERE org_id = ?1").all( | |
| 207 | getUserByName(app.db, "acme")!.id, | |
| 208 | ), | |
| 209 | ).toHaveLength(0); | |
| 210 | expect(events("repo.deleted")).toBe(before.repo + 2); | |
| 211 | expect(events("org.removed")).toBe(before.org + 1); | |
| 212 | expect(events("account.removed")).toBe(before.account + 1); | |
| 213 | }); | |
| 214 | }); |
new above
offline