Public: anyone can read this; the crew can change it.
Spend 2: plan a Stop or Delete from the cost row, refused on a read-only account, audited #18170
Merged 14h 58m ago, live in production
scout/forge:scout/18102-spend-2-plan-a-stop-or-delete-from-the-c → main 0 commits fork 3 threads · 3 unresolved
23 files
changed +623
−11
- docs/features/cloud-end.md
- src/actions/cloud_end.ts
- src/cloud/droplet.ts
- src/cloud/hetzner.ts
- src/cloud/machine.ts
- src/cloud/ovh.ts
- src/core/account_purge.ts
- src/core/cloud_audit.ts
- src/core/migration-pins/20261204103000-cloud-audit-actions.pin
- src/core/migrations/20261204103000-cloud-audit-actions.ts
- src/http/infra_routes.ts
- src/http/lazy_lists.ts
- src/tui/screens/cloud_end.ts
- src/tui/screens/cloudtree.ts
- src/web/pages/cloud.ts
- src/web/pages/cloud_end.ts
- src/web/pages/cloud_tree.ts
- test/cloud-end-drivers.test.ts
- test/cloud-end.test.ts
- test/no-polling.test.ts
- test/pages-budget.test.ts
- test/pinned-ceiling.test.ts
- test/security-floor-routes.test.ts
docs/features/cloud-end.md added +12
| @@ -0,0 +1,12 @@ | ||
| 1 | --- | |
| 2 | topic: Hosting forges for others, and getting paid | |
| 3 | row: Stop or delete a cloud resource | |
| 4 | --- | |
| 5 | ||
| 6 | # Stop or delete a machine or volume (#18102) | |
| 7 | ||
| 8 | On a machine's or a volume's page under /infra, an account the forge may write to offers **Stop…** (machines) and **Delete…**. Each opens a plan, in the same words on every door: what will stop or go, its cost now, what is lost (a volume's data, a machine's own disk and public address), and what is kept. A stop is one confirm; a delete asks for the resource's name typed back. A read-only account is offered neither, and the server refuses both with "read-only"; so is a resource that is a pinned forge's own machine or volume (end that forge instead), an attached volume, and a cloud whose driver has no such call. Every attempt, refused or done, writes a cloud audit row with who asked and the confirmed plan (Cloud accounts → Audit). | |
| 9 | ||
| 10 | - **Web:** `/infra/end/<stop|delete>/<cloud>/<account>/<project>/<id>` (`src/web/pages/cloud_end.ts`, `src/http/infra_routes.ts`). | |
| 11 | - **Terminal:** Cloud resources (`src/tui/screens/cloud_end.ts`): `x` plans a stop, `X` a delete, on the selected resource. | |
| 12 | - **Rules:** `src/actions/cloud_end.ts`. A stopped machine is still billed by DigitalOcean, Hetzner and OVHcloud, and the plan says so. |
src/actions/cloud_end.ts added +188
| @@ -0,0 +1,188 @@ | ||
| 1 | /** | |
| 2 | * Stop or delete one machine or volume from the cost table (#18102): planned first, in words the | |
| 3 | * page and the terminal both show, then confirmed. The plan is not kept anywhere: it carries a | |
| 4 | * digest of what it said, and a confirm that no longer matches what the cloud was last read as is | |
| 5 | * refused. A read-only account is refused here, not only hidden on the page. Every attempt writes a | |
| 6 | * cloud audit row: who, what, and the plan as confirmed. | |
| 7 | */ | |
| 8 | ||
| 9 | import type { App } from "../app.ts"; | |
| 10 | import { driverOf } from "../cloud/drivers.ts"; | |
| 11 | import type { Driver } from "../cloud/machine.ts"; | |
| 12 | import type { CloudResource } from "../cloud/projects.ts"; | |
| 13 | import { caller, gone } from "../cloud/machine.ts"; | |
| 14 | import { dollars } from "../cloud/prices.ts"; | |
| 15 | import { cloudName, nodeAt } from "../cloud/tree.ts"; | |
| 16 | import { getCloudAccount, NO_ACCOUNT, READ_ONLY } from "../core/cloud_account.ts"; | |
| 17 | import { recordAudit } from "../core/cloud_audit.ts"; | |
| 18 | import { listPinned } from "../core/pinned.ts"; | |
| 19 | import type { User } from "../core/users.ts"; | |
| 20 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 21 | import { cloudResources } from "./infra.ts"; | |
| 22 | import { admin, withCloud } from "./pinned.ts"; | |
| 23 | ||
| 24 | export interface EndLine { | |
| 25 | readonly label: "Will" | "Cost now" | "Lost" | "Kept"; | |
| 26 | readonly value: string; | |
| 27 | } | |
| 28 | ||
| 29 | export type EndAct = "stop" | "delete"; | |
| 30 | ||
| 31 | export const endActOf = (s: string | undefined): EndAct | undefined => (s === "stop" || s === "delete" ? s : undefined); | |
| 32 | ||
| 33 | export interface EndPlan { | |
| 34 | readonly act: EndAct; | |
| 35 | readonly path: readonly string[]; | |
| 36 | readonly provider: string; | |
| 37 | readonly account: string; | |
| 38 | readonly kind: "machine" | "volume"; | |
| 39 | /** The provider's own id, without the kind. */ | |
| 40 | readonly id: string; | |
| 41 | readonly name: string; | |
| 42 | /** What it is and where, one line. */ | |
| 43 | readonly what: string; | |
| 44 | /** Its cost now, in words. */ | |
| 45 | readonly cost: string; | |
| 46 | /** Will, Cost now, Lost, Kept: one fact each, a label and its value. */ | |
| 47 | readonly lines: readonly EndLine[]; | |
| 48 | /** Why it cannot be done; empty when it can. A read-only account is always here. */ | |
| 49 | readonly refusal: string; | |
| 50 | /** A digest of what the plan said: the confirm must bring it back. */ | |
| 51 | readonly digest: string; | |
| 52 | } | |
| 53 | ||
| 54 | /** | |
| 55 | * The three calls an end may make, and how to reach the vendor: it narrows a driver to them, so an | |
| 56 | * end cannot provision. | |
| 57 | */ | |
| 58 | interface EndCalls extends Pick<Driver, "api"> { | |
| 59 | readonly signed?: Driver["signed"] | undefined; | |
| 60 | readonly stopMachine: Driver["stopMachine"]; | |
| 61 | readonly deleteMachine: Driver["deleteMachine"]; | |
| 62 | readonly deleteVolume: Driver["deleteVolume"]; | |
| 63 | } | |
| 64 | ||
| 65 | const endView = (d: Driver): EndCalls => ({ api: d.api, signed: d.signed, stopMachine: d.stopMachine?.bind(d), deleteMachine: d.deleteMachine.bind(d), deleteVolume: d.deleteVolume.bind(d) }); | |
| 66 | ||
| 67 | /** The one place an end takes a driver; none for a vendor the forge has no driver for. */ | |
| 68 | function endDriver(provider: string): EndCalls | undefined { | |
| 69 | try { | |
| 70 | return endView(driverOf(provider)); | |
| 71 | } catch { | |
| 72 | return undefined; | |
| 73 | } | |
| 74 | } | |
| 75 | ||
| 76 | const ID = /^[A-Za-z0-9-]{1,64}$/; | |
| 77 | ||
| 78 | const MACHINE_KEEPS = "These clouds bill a stopped machine for its disk and address, so the cost stays what it is now."; | |
| 79 | ||
| 80 | /** | |
| 81 | * The plan for `act` on the resource at `path`, read from the last read of the accounts; no cloud | |
| 82 | * is called. | |
| 83 | */ | |
| 84 | export function planEnd(app: App, actor: User | undefined, act: EndAct, path: readonly string[]): Result<EndPlan, string> { | |
| 85 | const who = admin(actor); | |
| 86 | if (!who.ok) return who; | |
| 87 | const view = cloudResources(app, actor, ""); | |
| 88 | if (!view.ok) return view; | |
| 89 | const r = nodeAt(view.value.whole, path)?.resource; | |
| 90 | if (r === undefined) return err("No such resource."); | |
| 91 | return ok(planOf(app, act, path, r)); | |
| 92 | } | |
| 93 | ||
| 94 | /** | |
| 95 | * What a resource's page offers: the acts its account lets the forge do, never one on a read-only | |
| 96 | * account. | |
| 97 | */ | |
| 98 | export function offeredEnds(app: App, path: readonly string[], r: CloudResource | undefined): readonly { act: EndAct; href: string }[] { | |
| 99 | if (r === undefined || (r.kind !== "machine" && r.kind !== "volume") || getCloudAccount(app.db, r.provider, r.account)?.writeAllowed !== true) return []; | |
| 100 | if (endDriver(r.provider) === undefined) return []; | |
| 101 | const acts: EndAct[] = r.kind === "machine" ? ["stop", "delete"] : ["delete"]; | |
| 102 | return acts.map((act) => ({ act, href: `/infra/end/${act}/${path.map(encodeURIComponent).join("/")}` })); | |
| 103 | } | |
| 104 | ||
| 105 | function planOf(app: App, act: EndAct, path: readonly string[], r: CloudResource): EndPlan { | |
| 106 | const kind = r.kind === "machine" || r.kind === "volume" ? r.kind : undefined; | |
| 107 | const id = r.id.slice(r.id.indexOf(":") + 1); | |
| 108 | const where = `${cloudName(r.provider)} / ${r.account}${r.region === "" ? "" : `, ${r.region}`}`; | |
| 109 | const cost = r.cents === null ? "its cost is not known" : `${dollars(r.cents)} a month${r.costFrom === "billed" ? " billed" : " at list price"}`; | |
| 110 | const base = { act, path, provider: r.provider, account: r.account, kind: kind ?? "machine", id, name: r.name, what: `${kind ?? r.kind} ${r.name} (${id}) on ${where}`, cost } as const; | |
| 111 | const refuse = (refusal: string, lines: readonly EndLine[] = []): EndPlan => ({ ...base, lines, refusal, digest: digestOf(act, r.id, r.provider, r.account, lines) }); | |
| 112 | ||
| 113 | if (kind === undefined) return refuse(`The forge cannot ${act} a ${r.kind}: only machines and volumes.`); | |
| 114 | const driver = endDriver(r.provider); | |
| 115 | if (driver === undefined) return refuse(`The forge has no way to ${act} things on ${cloudName(r.provider)} yet.`); | |
| 116 | const acct = getCloudAccount(app.db, r.provider, r.account); | |
| 117 | if (acct === undefined) return refuse(NO_ACCOUNT); | |
| 118 | if (!acct.writeAllowed) return refuse(READ_ONLY); | |
| 119 | if (!ID.test(id)) return refuse("Its id is not one the forge will send to a cloud."); | |
| 120 | const attached = r.attachedTo ?? []; | |
| 121 | const lines: EndLine[] = []; | |
| 122 | if (act === "stop") { | |
| 123 | if (kind === "volume") return refuse("A volume cannot be stopped: delete it, or leave it."); | |
| 124 | if (driver.stopMachine === undefined) return refuse(`The forge cannot stop a machine on ${cloudName(r.provider)} yet.`); | |
| 125 | if (/^(off|stopped)$/.test(r.state)) return refuse(`${r.name} is already ${r.state}.`); | |
| 126 | lines.push( | |
| 127 | { label: "Will", value: `Stop ${base.what}, now ${r.state === "" ? "in a state not read" : r.state}.` }, | |
| 128 | { label: "Cost now", value: `${cost}.` }, | |
| 129 | { label: "Lost", value: "It is powered off and answers nothing until it is started again at the cloud; nothing is deleted." }, | |
| 130 | { label: "Kept", value: MACHINE_KEEPS }, | |
| 131 | ); | |
| 132 | } else { | |
| 133 | lines.push({ label: "Will", value: `Delete ${base.what}.` }, { label: "Cost now", value: `${cost}; it stops billing once deleted.` }); | |
| 134 | if (kind === "volume") lines.push({ label: "Lost", value: "Every byte on the volume, for good. The forge keeps no copy of it." }); | |
| 135 | else | |
| 136 | lines.push( | |
| 137 | { label: "Lost", value: "The machine and everything on its own disk, and its public address, which is released and cannot be got back." }, | |
| 138 | { label: "Kept", value: attached.length === 0 ? "Nothing is attached to it." : `${attached.join(", ")} stay at the cloud, with their data and their bill.` }, | |
| 139 | ); | |
| 140 | } | |
| 141 | const held = listPinned(app.db).find((p) => p.target === r.provider && p.account === r.account && (p.remote === id || p.volume === id)); | |
| 142 | if (held !== undefined) return refuse(`It is the ${kind} of the forge ${held.name}: end that forge from Infrastructure instead, so its row follows.`, lines); | |
| 143 | if (act === "delete" && kind === "volume" && attached.length > 0) return refuse(`It is attached to ${attached.join(", ")}: delete that first, or the cloud refuses.`, lines); | |
| 144 | return { ...base, lines, refusal: "", digest: digestOf(act, r.id, r.provider, r.account, lines) }; | |
| 145 | } | |
| 146 | ||
| 147 | const digestOf = (act: string, id: string, provider: string, account: string, lines: readonly EndLine[]): string => | |
| 148 | new Bun.CryptoHasher("sha256").update(JSON.stringify([act, provider, account, id, lines])).digest("hex").slice(0, 16); | |
| 149 | ||
| 150 | /** The plan as one text: what the page shows and the audit row keeps. */ | |
| 151 | export const planText = (p: EndPlan): string => p.lines.map((l) => `${l.label}: ${l.value}`).join(" "); | |
| 152 | ||
| 153 | /** | |
| 154 | * Do it. `digest` is the plan's, brought back by the confirm; a delete also needs the resource's | |
| 155 | * name typed back. Refused attempts are audited as refused, and an attempt is audited before the | |
| 156 | * cloud is called, so a failed call still leaves its row. | |
| 157 | */ | |
| 158 | export async function performEnd(app: App, actor: User | undefined, act: EndAct, path: readonly string[], confirm: { digest: string; typed: string }): Promise<Result<string, string>> { | |
| 159 | const who = admin(actor); | |
| 160 | if (!who.ok) return who; | |
| 161 | const planned = planEnd(app, actor, act, path); | |
| 162 | if (!planned.ok) return planned; | |
| 163 | const p = planned.value; | |
| 164 | const row = (allowed: boolean, why = ""): void => | |
| 165 | recordAudit(app.db, { provider: p.provider, account: p.account, purpose: `${act}:${p.kind}`, target: `${p.kind}:${p.id}`.slice(0, 200), bytesOut: 0, allowed, actor: who.value.id ?? "", plan: `${why}${planText(p)}` }); | |
| 166 | if (p.refusal !== "") { | |
| 167 | row(false, `Refused: ${p.refusal} `); | |
| 168 | return err(p.refusal); | |
| 169 | } | |
| 170 | if (confirm.digest !== p.digest) return err(`What ${p.name} is changed since it was planned: review the plan again.`); | |
| 171 | if (act === "delete" && confirm.typed.trim() !== p.name) return err(`Type ${p.name} to delete it: it cannot be undone.`); | |
| 172 | row(true); | |
| 173 | const d = endDriver(p.provider)!; | |
| 174 | const done = await withCloud( | |
| 175 | app, | |
| 176 | who.value, | |
| 177 | { target: p.provider, account: p.account }, | |
| 178 | `${act}-${p.kind}`, | |
| 179 | async (f, token) => { | |
| 180 | const call = caller(d, f, token); | |
| 181 | if (act === "stop") await d.stopMachine!(call, p.id); | |
| 182 | else await gone(() => (p.kind === "machine" ? d.deleteMachine(call, p.id) : d.deleteVolume(call, p.id))); | |
| 183 | }, | |
| 184 | false, | |
| 185 | ); | |
| 186 | if (!done.ok) return done; | |
| 187 | return ok(act === "stop" ? `Stopping ${p.name}: it shows as stopped at the next read.` : `Deleted ${p.name}. It shows until the next read.`); | |
| 188 | } |
src/cloud/droplet.ts +3
| @@ -107,6 +107,9 @@ export const digitalocean: Driver = { | ||
| 107 | 107 | await call("DELETE", `/snapshots/${encodeURIComponent(id)}`); |
| 108 | 108 | }, |
| 109 | 109 | }, |
| 110 | async stopMachine(call, remote) { | |
| 111 | await call("POST", `/droplets/${remote}/actions`, { type: "power_off" }); | |
| 112 | }, | |
| 110 | 113 | async deleteMachine(call, remote) { |
| 111 | 114 | await call("DELETE", `/droplets/${remote}`); |
| 112 | 115 | }, |
src/cloud/hetzner.ts +3
| @@ -94,6 +94,9 @@ export const hetzner: Driver = { | ||
| 94 | 94 | await call("DELETE", `/images/${numericId(id, "snapshot")}`); |
| 95 | 95 | }, |
| 96 | 96 | }, |
| 97 | async stopMachine(call, remote) { | |
| 98 | await call("POST", `/servers/${numericId(remote, "machine")}/actions/poweroff`); | |
| 99 | }, | |
| 97 | 100 | async deleteMachine(call, remote) { |
| 98 | 101 | await call("DELETE", `/servers/${numericId(remote, "machine")}`); |
| 99 | 102 | }, |
src/cloud/machine.ts +6 −1
| @@ -229,6 +229,11 @@ export interface Driver { | ||
| 229 | 229 | /** Every machine and volume at the provider that carries a forge's label, whoever made it. */ |
| 230 | 230 | listForges(call: Call): Promise<Labelled>; |
| 231 | 231 | deleteMachine(call: Call, remote: string): Promise<void>; |
| 232 | /** | |
| 233 | * Power the machine off, keeping it and its disk (#18102): a stopped machine is still billed by | |
| 234 | * these clouds. Absent where the forge has no such call. | |
| 235 | */ | |
| 236 | stopMachine?(call: Call, remote: string): Promise<void>; | |
| 232 | 237 | /** Delete the data volume: nothing of the forge's data is left once this answers. */ |
| 233 | 238 | deleteVolume(call: Call, volume: string): Promise<void>; |
| 234 | 239 | /** Whether the volume is attached to no machine: a cloud detaches it after a delete answers, and refuses a new machine with it until then. */ |
| @@ -288,7 +293,7 @@ export interface FirewallCalls { | ||
| 288 | 293 | /** The tag or label that names a forge on everything the forge makes for it (#16340). */ |
| 289 | 294 | export const forgeTag = (name: string) => `forge:${name}`; |
| 290 | 295 | |
| 291 | export function caller(d: Driver, f: Fetch, token: string): Call { | |
| 296 | export function caller(d: { api: string; signed?: Driver["signed"] | undefined }, f: Fetch, token: string): Call { | |
| 292 | 297 | if (d.signed) return d.signed(f, token); |
| 293 | 298 | const host = new URL(d.api).host; |
| 294 | 299 | return async (method, path, body) => { |
src/cloud/ovh.ts +3
src/core/account_purge.ts +3
| @@ -59,6 +59,9 @@ export const COVERED: Readonly<Record<string, Coverage>> = { | ||
| 59 | 59 | // The !forge audit keeps what was said and what came of it; who said it becomes a former member. |
| 60 | 60 | "game_chat.user_id": FORMER, |
| 61 | 61 | "account_ceiling.set_by": FORMER, |
| 62 | // The cloud audit is shared history of what was called and by whom: it keeps the line, as the | |
| 63 | // former account. | |
| 64 | "cloud_audit.actor": FORMER, | |
| 62 | 65 | "repo_account_order.set_by": FORMER, |
| 63 | 66 | "allocation_entry.actor_id": FORMER, |
| 64 | 67 | "allocation_weekly.set_by": FORMER, |
src/core/cloud_audit.ts +16 −3
| @@ -19,18 +19,25 @@ export interface AuditRow { | ||
| 19 | 19 | readonly target: string; |
| 20 | 20 | readonly bytesOut: number; |
| 21 | 21 | readonly allowed: boolean; |
| 22 | /** Who asked, for a stop or a delete (#18102); empty for a vendor call or a hand-out. */ | |
| 23 | readonly actor: string; | |
| 24 | /** The plan that was confirmed, in the words the page showed; empty for a call or a hand-out. */ | |
| 25 | readonly plan: string; | |
| 22 | 26 | } |
| 23 | 27 | |
| 28 | /** What `recordAudit` takes: a stop or a delete also says who and the plan. */ | |
| 29 | export type AuditInput = Omit<AuditRow, "id" | "at" | "actor" | "plan"> & { readonly actor?: string; readonly plan?: string }; | |
| 30 | ||
| 24 | 31 | const iso = (ms: number) => new Date(ms).toISOString(); |
| 25 | 32 | |
| 26 | 33 | export function recordAudit( |
| 27 | 34 | db: Database, |
| 28 | row: Omit<AuditRow, "id" | "at">, | |
| 35 | row: AuditInput, | |
| 29 | 36 | now: number = Date.now(), |
| 30 | 37 | ): void { |
| 31 | 38 | db.query( |
| 32 | `INSERT INTO cloud_audit (at, provider, account, purpose, target, bytes_out, allowed) | |
| 33 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`, | |
| 39 | `INSERT INTO cloud_audit (at, provider, account, purpose, target, bytes_out, allowed, actor, plan) | |
| 40 | VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`, | |
| 34 | 41 | ).run( |
| 35 | 42 | iso(now), |
| 36 | 43 | row.provider, |
| @@ -39,6 +46,8 @@ export function recordAudit( | ||
| 39 | 46 | row.target.slice(0, 200), |
| 40 | 47 | Math.max(0, Math.floor(row.bytesOut)), |
| 41 | 48 | row.allowed ? 1 : 0, |
| 49 | (row.actor ?? "").slice(0, 80), | |
| 50 | (row.plan ?? "").slice(0, 2000), | |
| 42 | 51 | ); |
| 43 | 52 | pruneAudit(db, now); |
| 44 | 53 | } |
| @@ -68,6 +77,8 @@ export function auditToday( | ||
| 68 | 77 | target: string; |
| 69 | 78 | bytes_out: number; |
| 70 | 79 | allowed: number; |
| 80 | actor: string; | |
| 81 | plan: string; | |
| 71 | 82 | }, |
| 72 | 83 | [string, number] |
| 73 | 84 | >( |
| @@ -83,5 +94,7 @@ export function auditToday( | ||
| 83 | 94 | target: r.target, |
| 84 | 95 | bytesOut: r.bytes_out, |
| 85 | 96 | allowed: r.allowed === 1, |
| 97 | actor: r.actor, | |
| 98 | plan: r.plan, | |
| 86 | 99 | })); |
| 87 | 100 | } |
src/core/migration-pins/20261204103000-cloud-audit-actions.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | 54b4d5e7c69d620cf9e4adc158447ec4bc2a802ce3030d7440b575aa1592ab07 |
src/core/migrations/20261204103000-cloud-audit-actions.ts added +7
| @@ -0,0 +1,7 @@ | ||
| 1 | // A stop or delete asked of a cloud resource from the cost table (#18102) is a row in the cloud | |
| 2 | // audit with who asked and the plan that was confirmed. Additive: two columns, empty for the rows | |
| 3 | // of vendor calls and hand-outs. | |
| 4 | export default ` | |
| 5 | ALTER TABLE cloud_audit ADD COLUMN actor TEXT NOT NULL DEFAULT ''; | |
| 6 | ALTER TABLE cloud_audit ADD COLUMN plan TEXT NOT NULL DEFAULT ''; | |
| 7 | `; |
src/http/infra_routes.ts +22 −1
| @@ -8,6 +8,8 @@ | ||
| 8 | 8 | import { cloudFactsAll } from "../actions/cloud_says.ts"; |
| 9 | 9 | import { infraCode } from "../cloud/infra_read.ts"; |
| 10 | 10 | import { buildOf, cloudResources, machineOf, providerConsole, readProjectsNow, type ComposeChoices, composeChoices, domainOf, infraOf, nameFor, planCompose, planRecord, pointsOf, rebuild, recordAccounts, startBuild } from "../actions/infra.ts"; |
| 11 | import { endActOf, offeredEnds, performEnd, planEnd } from "../actions/cloud_end.ts"; | |
| 12 | import { endPage } from "../web/pages/cloud_end.ts"; | |
| 11 | 13 | import { dropRecord } from "../actions/dns_record.ts"; |
| 12 | 14 | import { deleteSnapshot, endWithSnapshot, restoreSnapshot } from "../actions/infra_snapshot.ts"; |
| 13 | 15 | import { deployWords, clearPinned, endsWords, keepPinned, retirePinned, retireWords } from "../actions/pinned.ts"; |
| @@ -100,7 +102,8 @@ async function infraResource(ctx: Ctx): Promise<Response> { | ||
| 100 | 102 | // A container's live reader needs a role on its box; without one its last synced lines are shown, read only when asked. |
| 101 | 103 | const logs = tab === "logs" && node.container !== undefined && game === undefined ? logsOfContainer(ctx.app.db, node.container) : undefined; |
| 102 | 104 | const view = logs !== undefined ? { ...tree, logs } : tab !== "file" ? tree : { ...tree, files: await timePhaseAsync(ctx.request, "files", () => filesByNode(ctx.app, ctx.auth.user, tree.whole, tree.now)) }; |
| 103 | const pane = timePhase(ctx.request, "render", () => cloudPane(view, node, tab, game)); | |
| 105 | const ends = offeredEnds(ctx.app, node.path, node.resource); | |
| 106 | const pane = timePhase(ctx.request, "render", () => cloudPane(view, node, tab, game, ends)); | |
| 104 | 107 | if (part === "1") return fragment(pane, { request: ctx.request }); |
| 105 | 108 | return page({ ctx, title: `${node.name} · Infrastructure`, wide: true, scriptJs: game === undefined ? SCRIPT : CONTAINER_SCRIPT, styleCss: game === undefined ? INFRA_CSS : INFRA_CSS + LOG_READER_CSS, body: resourcesPage(tree, node.path, pane), noDock: true }); |
| 106 | 109 | } |
| @@ -372,7 +375,25 @@ async function infraSnapshot(ctx: Ctx): Promise<Response> { | ||
| 372 | 375 | return page({ ctx, title: `Bring back ${name}? · forge`, body: restoringPage(id, name, deployWords(made.error), made.error.points) }, 409); |
| 373 | 376 | } |
| 374 | 377 | |
| 378 | // GET /infra/end/:act/<path>: the plan of a stop or a delete. POST: the confirm. | |
| 379 | async function infraEnd(ctx: Ctx): Promise<Response> { | |
| 380 | const denied = guard(ctx); | |
| 381 | if (denied) return denied; | |
| 382 | const act = endActOf(ctx.params.act); | |
| 383 | const path = placeOf(`/infra/-/${ctx.url.pathname.split("/").slice(4).join("/")}`); | |
| 384 | if (act === undefined || path === undefined) return notFoundPage(ctx); | |
| 385 | const planned = planEnd(ctx.app, ctx.auth.user, act, path); | |
| 386 | if (!planned.ok) return notFoundPage(ctx); | |
| 387 | if (ctx.request.method !== "POST") return page({ ctx, title: `${act === "stop" ? "Stop" : "Delete"} ${planned.value.name}? · Infrastructure`, body: endPage(planned.value), noDock: true }); | |
| 388 | const form = await readForm(ctx, "admin"); | |
| 389 | if (form instanceof Response) return form; | |
| 390 | const done = await performEnd(ctx.app, ctx.auth.user, act, path, { digest: field(form, "plan"), typed: field(form, "confirm") }); | |
| 391 | return flashTo(ctx, done.ok ? `/infra/-/${path.map(encodeURIComponent).join("/")}` : `/infra/end/${act}/${path.map(encodeURIComponent).join("/")}`, done.ok ? { tone: "success", message: done.value } : { tone: "danger", message: done.error }); | |
| 392 | } | |
| 393 | ||
| 375 | 394 | export function infraRoutes(router: Router<Handler>): void { |
| 395 | router.add("GET", "/infra/end/:act/*path", infraEnd); | |
| 396 | router.add("POST", "/infra/end/:act/*path", infraEnd); | |
| 376 | 397 | router.add("GET", "/infra", infraGet); |
| 377 | 398 | router.add("GET", "/infra/build", infraBuild); |
| 378 | 399 | router.add("GET", "/infra/live", infraLive); |
src/http/lazy_lists.ts +2
| @@ -628,6 +628,8 @@ export const OPERATIONS_ROUTES = [ | ||
| 628 | 628 | ["POST", "/pinned/:name/:act"], |
| 629 | 629 | ["GET", "/deploy-to"], |
| 630 | 630 | ["POST", "/deploy-to"], |
| 631 | ["GET", "/infra/end/:act/*path"], | |
| 632 | ["POST", "/infra/end/:act/*path"], | |
| 631 | 633 | ["GET", "/infra"], |
| 632 | 634 | ["GET", "/infra/build"], |
| 633 | 635 | ["GET", "/infra/live"], |
src/tui/screens/cloud_end.ts added +32
| @@ -0,0 +1,32 @@ | ||
| 1 | /** | |
| 2 | * Stop or delete the selected cloud resource from the terminal (#18102): the plan the page shows, | |
| 3 | * a confirm, and for a delete the resource's name typed back (`actions/cloud_end.ts`). | |
| 4 | */ | |
| 5 | ||
| 6 | import { performEnd, planEnd, type EndAct } from "../../actions/cloud_end.ts"; | |
| 7 | import type { CloudNode } from "../../cloud/tree.ts"; | |
| 8 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 9 | import type { Session } from "../session.ts"; | |
| 10 | import { confirmScreen, later, promptScreen } from "./common.ts"; | |
| 11 | ||
| 12 | export function askEnd(f: Session, ctx: Ctx, parent: Screen, act: EndAct, n: CloudNode, say: (words: string) => void): void { | |
| 13 | const planned = planEnd(f.app, f.user, act, n.path); | |
| 14 | if (!planned.ok) return say(planned.error === "not_found" ? "Cloud resources are a forge admin's." : planned.error); | |
| 15 | const p = planned.value; | |
| 16 | if (p.refusal !== "") return say(p.refusal); | |
| 17 | const verb = act === "stop" ? "Stop" : "Delete"; | |
| 18 | const run = (typed: string): void => void performEnd(f.app, f.user, act, n.path, { digest: p.digest, typed }).then((r) => say(r.ok ? r.value : r.error)); | |
| 19 | ctx.push( | |
| 20 | confirmScreen(ctx, parent, { | |
| 21 | title: `${verb} ${p.name}?`, | |
| 22 | body: [p.what, ...p.lines.map((l) => `${l.label}: ${l.value}`)], | |
| 23 | width: 96, | |
| 24 | actions: [act === "delete" ? { label: verb, variant: "danger" as const } : { label: verb }, { label: "Cancel" }], | |
| 25 | onChoose: (i) => { | |
| 26 | if (i !== 0) return; | |
| 27 | if (act === "stop") return run(""); | |
| 28 | ctx.push(promptScreen(ctx, parent, { title: `Delete ${p.name}`, label: `type ${p.name} to delete it`, onSubmit: (typed) => later(ctx, () => (run(typed), parent)) })); | |
| 29 | }, | |
| 30 | }), | |
| 31 | ); | |
| 32 | } |
src/tui/screens/cloudtree.ts +13 −1
| @@ -19,6 +19,7 @@ import { style } from "../term/style.ts"; | ||
| 19 | 19 | import { truncate, wrap } from "../term/width.ts"; |
| 20 | 20 | import { fill, len, split } from "../ui/layout.ts"; |
| 21 | 21 | import { tableLines } from "../ui/list.ts"; |
| 22 | import { askEnd } from "./cloud_end.ts"; | |
| 22 | 23 | import { accountScreen } from "./cloud_account.ts"; |
| 23 | 24 | import { Filter, ListState, Scroll, ago, drawLines, hitList, openOnWeb } from "./common.ts"; |
| 24 | 25 | import type { PaletteEntry } from "./entries.ts"; |
| @@ -153,7 +154,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 153 | 154 | if (!isBranch(n)) focus = "pane"; |
| 154 | 155 | }; |
| 155 | 156 | |
| 156 | return { | |
| 157 | const screen: Screen = { | |
| 157 | 158 | title: "Cloud resources", |
| 158 | 159 | keys: [ |
| 159 | 160 | binding(["enter", "l"], "open / expand"), |
| @@ -164,6 +165,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 164 | 165 | binding(["[", "]"], "facts / file"), |
| 165 | 166 | binding(["a"], "check the account: what was not read, and the fix"), |
| 166 | 167 | binding(["w"], "open on the web"), |
| 168 | binding(["x", "X"], "plan a stop (x) or a delete (X) of the machine or volume"), | |
| 167 | 169 | binding(["P"], "read every account now"), |
| 168 | 170 | ], |
| 169 | 171 | render(area, s) { |
| @@ -282,6 +284,15 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 282 | 284 | ctx.push(accountScreen(f, ctx, account[0]!, account[1]!)); |
| 283 | 285 | return true; |
| 284 | 286 | } |
| 287 | if (e.key === "x" || e.key === "X") { | |
| 288 | const at = (focus === "pane" && opened !== undefined ? nodeAt(v.root, opened) : undefined) ?? n; | |
| 289 | if (at.resource === undefined) return false; | |
| 290 | askEnd(f, ctx, screen, e.key === "x" ? "stop" : "delete", at, (words) => { | |
| 291 | note = words; | |
| 292 | ctx.invalidate(); | |
| 293 | }); | |
| 294 | return true; | |
| 295 | } | |
| 285 | 296 | if (e.key === "w") { |
| 286 | 297 | openOnWeb(f, ctx, `/infra/-/${n.path.map(encodeURIComponent).join("/")}`, n.name); |
| 287 | 298 | return true; |
| @@ -302,6 +313,7 @@ export function cloudTreeScreen(f: Session, ctx: Ctx): Screen { | ||
| 302 | 313 | return false; |
| 303 | 314 | }, |
| 304 | 315 | }; |
| 316 | return screen; | |
| 305 | 317 | } |
| 306 | 318 | |
| 307 | 319 | /** Every cloud resource, as /infra has it: a forge admin. */ |
src/web/pages/cloud.ts +4 −1
| @@ -28,6 +28,7 @@ import { warmOf } from "../../cloud/warm_pool.ts"; | ||
| 28 | 28 | import { dollars } from "../../cloud/prices.ts"; |
| 29 | 29 | import { accountReads, type AccountRead } from "../../cloud/projects.ts"; |
| 30 | 30 | import { readFixes } from "../../cloud/tree.ts"; |
| 31 | import { getUsersByIds } from "../../core/users.ts"; | |
| 31 | 32 | import { auditToday } from "../../core/cloud_audit.ts"; |
| 32 | 33 | import { |
| 33 | 34 | getCloudAccount, |
| @@ -332,6 +333,7 @@ export function cloudAuditPage(ctx: Ctx): Response { | ||
| 332 | 333 | const denied = requireAdmin(ctx); |
| 333 | 334 | if (denied) return timePhase(ctx.request, "render", () => denied); |
| 334 | 335 | const rows = timePhase(ctx.request, "audit", () => auditToday(ctx.app.db)); |
| 336 | const people = getUsersByIds(ctx.app.db, rows.map((r) => r.actor).filter((a) => a !== "")); | |
| 335 | 337 | return timePhase(ctx.request, "render", () => page({ |
| 336 | 338 | ctx, |
| 337 | 339 | title: "Cloud audit", |
| @@ -348,7 +350,8 @@ export function cloudAuditPage(ctx: Ctx): Response { | ||
| 348 | 350 | lead: icon(r.allowed ? "eye" : "x"), |
| 349 | 351 | title: html`${r.allowed ? "Allowed" : "Refused"}: ${isProvider(r.provider) ? LABEL[r.provider] : r.provider} / |
| 350 | 352 | <span class="mono">${r.account}</span> for ${r.purpose}`, |
| 351 | meta: html`<span class="mono">${r.target}</span> · ${r.bytesOut} bytes out · ${time(r.at)}`, | |
| 353 | meta: html`<span class="mono">${r.target}</span> · ${r.bytesOut} bytes out · ${time(r.at)}${r.actor === "" ? null : html` · by ${people.get(r.actor)?.displayName || people.get(r.actor)?.username || "someone removed"}`}`, | |
| 354 | ...(r.plan === "" ? {} : { facts: [{ label: "Plan", value: r.plan }] }), | |
| 352 | 355 | }), |
| 353 | 356 | )} |
| 354 | 357 | </ul>`} |
src/web/pages/cloud_end.ts added +31
| @@ -0,0 +1,31 @@ | ||
| 1 | /** | |
| 2 | * The plan of a stop or a delete (#18102): what will stop or go, its cost now, what is lost. A | |
| 3 | * delete asks for the resource's name typed back; a refused plan shows why and offers nothing. | |
| 4 | */ | |
| 5 | ||
| 6 | import type { EndPlan } from "../../actions/cloud_end.ts"; | |
| 7 | import { pageHead } from "../chrome.ts"; | |
| 8 | import { html, type Html } from "../html.ts"; | |
| 9 | import { btn, field as input } from "../ui.ts"; | |
| 10 | import { cloudHref } from "./cloud_tree.ts"; | |
| 11 | import { parseCloudQuery } from "../../cloud/tree.ts"; | |
| 12 | ||
| 13 | export function endPage(p: EndPlan): Html { | |
| 14 | const back = cloudHref(p.path, parseCloudQuery("")); | |
| 15 | const verb = p.act === "stop" ? "Stop" : "Delete"; | |
| 16 | return html`<div class="narrow-wide" data-cloud-end="${p.act}"> | |
| 17 | ${pageHead(`${verb} ${p.name}?`, { sub: p.what })} | |
| 18 | <dl class="row-facts">${p.lines.map((l) => html`<div><dt>${l.label}</dt><dd>${l.value}</dd></div>`)}</dl> | |
| 19 | ${p.refusal === "" | |
| 20 | ? html`<form method="post" action="/infra/end/${p.act}/${p.path.map(encodeURIComponent).join("/")}"> | |
| 21 | <input type="hidden" name="plan" value="${p.digest}" /> | |
| 22 | ${p.act === "delete" ? input({ label: `Type ${p.name} to delete it`, name: "confirm", required: true, mono: true, autocomplete: "off", spellcheck: false, autocorrect: false }) : null} | |
| 23 | <div class="form-actions"> | |
| 24 | ${btn(`${verb} ${p.name}`, { variant: p.act === "delete" ? "danger" : "primary" })} | |
| 25 | ${btn("Cancel", { href: back, variant: "ghost" })} | |
| 26 | </div> | |
| 27 | </form>` | |
| 28 | : html`<p class="muted" data-refused>${p.refusal}</p> | |
| 29 | <div class="form-actions">${btn("Back", { href: back, variant: "ghost" })}</div>`} | |
| 30 | </div>`; | |
| 31 | } |
src/web/pages/cloud_tree.ts +2 −2
| @@ -281,7 +281,7 @@ function billLine(n: CloudNode): Html { | ||
| 281 | 281 | } |
| 282 | 282 | |
| 283 | 283 | /** What is open beside the tree: a branch's costliest resources, or one resource's facts or file. */ |
| 284 | export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, null), game?: { readonly power: Html | null; readonly logs: Html }): Html { | |
| 284 | export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, null), game?: { readonly power: Html | null; readonly logs: Html }, endActs: readonly { act: string; href: string }[] = []): Html { | |
| 285 | 285 | const r = n.resource; |
| 286 | 286 | if (r === undefined && n.container === undefined) { |
| 287 | 287 | return html`<section id="code-pane" data-path="${n.name}" data-cloud-pane="${n.level}"> |
| @@ -316,7 +316,7 @@ export function cloudPane(v: CloudView, n: CloudNode, tab: NodeTab = tabOf(n, nu | ||
| 316 | 316 | <thead><tr>${CONTAINER_COLUMNS.map((k) => html`<th scope="col">${k.label}</th>`)}</tr></thead> |
| 317 | 317 | <tbody>${n.children.map((c) => html`<tr>${CONTAINER_COLUMNS.map((k) => html`<td>${k.field === "name" ? html`<a href="${cloudHref(c.path, v.q)}">${c.name}</a>` : containerCell(c.container!, k.field, v.now)}</td>`)}</tr>`)}</tbody> |
| 318 | 318 | </table></div>`} |
| 319 | <div class="form-actions">${btn("Ask about this", { href: `/talk?about=${encodeURIComponent(`cloud:${n.path.join("/")}`)}` })}</div> | |
| 319 | <div class="form-actions">${endActs.map((e) => btn(e.act === "stop" ? "Stop…" : "Delete…", { href: e.href, variant: e.act === "delete" ? "danger" : "ghost", label: `Plan to ${e.act} ${n.name}` }))}${btn("Ask about this", { href: `/talk?about=${encodeURIComponent(`cloud:${n.path.join("/")}`)}` })}</div> | |
| 320 | 320 | </section>`; |
| 321 | 321 | } |
| 322 | 322 |
test/cloud-end-drivers.test.ts added +25
| @@ -0,0 +1,25 @@ | ||
| 1 | /** The stand-in call each vendor's stopMachine makes (#18102): method, path, body. */ | |
| 2 | import { describe, expect, test } from "bun:test"; | |
| 3 | import { digitalocean } from "../src/cloud/droplet.ts"; | |
| 4 | import { hetzner } from "../src/cloud/hetzner.ts"; | |
| 5 | import { ovh } from "../src/cloud/ovh.ts"; | |
| 6 | ||
| 7 | const asked = async (stop: (call: (m: string, p: string, b?: unknown) => Promise<unknown>) => Promise<void>) => { | |
| 8 | const seen: unknown[][] = []; | |
| 9 | await stop(async (...a) => (seen.push(a), {})); | |
| 10 | return seen; | |
| 11 | }; | |
| 12 | ||
| 13 | describe("stopMachine per vendor", () => { | |
| 14 | test("Hetzner powers the server off by its number", async () => { | |
| 15 | // A hard power-off, as the plan says ("powered off"); a clean shutdown is not what it promises. | |
| 16 | expect(await asked((c) => hetzner.stopMachine!(c, "42"))).toEqual([["POST", "/servers/42/actions/poweroff"]]); | |
| 17 | await expect(hetzner.stopMachine!(async () => ({}), "../x")).rejects.toThrow(); | |
| 18 | }); | |
| 19 | test("OVHcloud stops the instance under the project", async () => { | |
| 20 | expect(await asked((c) => ovh.stopMachine!(c, "i-1"))).toEqual([["POST", "/instance/i-1/stop"]]); | |
| 21 | }); | |
| 22 | test("DigitalOcean powers the droplet off", async () => { | |
| 23 | expect(await asked((c) => digitalocean.stopMachine!(c, "7"))).toEqual([["POST", "/droplets/7/actions", { type: "power_off" }]]); | |
| 24 | }); | |
| 25 | }); |
test/cloud-end.test.ts added +242
| @@ -0,0 +1,242 @@ | ||
| 1 | /** | |
| 2 | * Stop and delete from the cost table (#18102), against a stand-in vendor: planned first, refused | |
| 3 | * on a read-only account (by the server, not only the page), done only after the confirm, and | |
| 4 | * audited with who and the confirmed plan. | |
| 5 | */ | |
| 6 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 7 | import { mkdtempSync } from "node:fs"; | |
| 8 | import { 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 { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 13 | import { offeredEnds, performEnd, planEnd, planText } from "../src/actions/cloud_end.ts"; | |
| 14 | import { cloudResources } from "../src/actions/infra.ts"; | |
| 15 | import { net } from "../src/actions/pinned.ts"; | |
| 16 | import { costliestOf } from "../src/cloud/tree.ts"; | |
| 17 | import { READ_ONLY } from "../src/core/cloud_account.ts"; | |
| 18 | import { auditToday } from "../src/core/cloud_audit.ts"; | |
| 19 | import { createSession } from "../src/core/sessions.ts"; | |
| 20 | import { createUser, type User } from "../src/core/users.ts"; | |
| 21 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 22 | import { createForgeApp } from "../src/tui/forge.ts"; | |
| 23 | import { cloudTreeScreen } from "../src/tui/screens/cloudtree.ts"; | |
| 24 | import { headlessTerminal } from "../src/tui/term/terminal.ts"; | |
| 25 | import { settleApp } from "./helpers/tui.ts"; | |
| 26 | ||
| 27 | let dir = ""; | |
| 28 | let app: App; | |
| 29 | let servers: Servers; | |
| 30 | let admin: User; | |
| 31 | let plain: User; | |
| 32 | const AT = new Date().toISOString(); | |
| 33 | /** What the stand-in vendor was asked, one line each. */ | |
| 34 | const asked: string[] = []; | |
| 35 | const saved = { fetch: net.fetch, cloud: cloudNet.fetch }; | |
| 36 | ||
| 37 | const resource = (account: string, id: string, title: string, cents: number, state: string, on: string[] = []): void => { | |
| 38 | app.db.run( | |
| 39 | "INSERT INTO cloud_resource (cloud_provider, cloud_account_id, cloud_resource_id, cloud_project_id, kind, name, cloud_region, host_type, label, made_by, cents, created_at, read_at, state, attached_to, made_from) VALUES ('digitalocean',?,?,'default',?,?,'nyc3','','','found',?,'2026-01-02T00:00:00Z',?,?,?,'')", | |
| 40 | [account, id, id.split(":")[0]!, title, cents, AT, state, on.length === 0 ? "" : JSON.stringify(on)], | |
| 41 | ); | |
| 42 | }; | |
| 43 | const nodeOf = (id: string): readonly string[] => { | |
| 44 | const v = cloudResources(app, admin, ""); | |
| 45 | if (!v.ok) throw new Error(v.error); | |
| 46 | const n = costliestOf(v.value.whole).find((x) => x.resource?.id === id); | |
| 47 | if (n === undefined) throw new Error(`no ${id}`); | |
| 48 | return n.path; | |
| 49 | }; | |
| 50 | const resourceOf = (id: string) => { | |
| 51 | const v = cloudResources(app, admin, ""); | |
| 52 | return v.ok ? costliestOf(v.value.whole).find((x) => x.resource?.id === id)?.resource : undefined; | |
| 53 | }; | |
| 54 | const calls = (): string[] => asked.splice(0); | |
| 55 | ||
| 56 | beforeAll(async () => { | |
| 57 | dir = mkdtempSync(join(tmpdir(), "forge-cloud-end-")); | |
| 58 | app = createApp({ dataDir: dir, port: 0, url: "https://forge.example.net" }); | |
| 59 | servers = await serve(app); | |
| 60 | const mk = async (username: string, isAdmin: boolean): Promise<User> => { | |
| 61 | const u = await createUser(app.db, { username, email: `${username}@f.test`, password: "a-good-passphrase", origin: "seed", isAdmin, trusted: true }); | |
| 62 | if (!u.ok) throw new Error(u.error); | |
| 63 | return u.value; | |
| 64 | }; | |
| 65 | admin = await mk("ada", true); | |
| 66 | plain = await mk("bob", false); | |
| 67 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 }); | |
| 68 | for (const name of ["rw", "ro"]) { | |
| 69 | const a = await addAccount(app, admin, "digitalocean", name, "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5"); | |
| 70 | if (!a.ok) throw new Error(String(a.error)); | |
| 71 | app.db.run("INSERT INTO cloud_project (cloud_provider, cloud_account_id, cloud_project_id, name, is_default, read_at) VALUES ('digitalocean',?,'default','default',1,?)", [name, AT]); | |
| 72 | } | |
| 73 | allowWrite(app, admin, "digitalocean", "rw", true); | |
| 74 | resource("rw", "machine:111", "web", 1200, "active"); | |
| 75 | resource("rw", "volume:vol-9", "web-data", 100, "unattached"); | |
| 76 | resource("rw", "volume:vol-8", "busy-data", 100, "attached", ["machine:111"]); | |
| 77 | resource("ro", "machine:222", "locked", 600, "active"); | |
| 78 | resource("ro", "volume:vol-7", "locked-data", 100, "unattached"); | |
| 79 | net.fetch = async (url, init) => { | |
| 80 | asked.push(`${init?.method ?? "GET"} ${new URL(url).pathname}${typeof init?.body === "string" ? ` ${init.body}` : ""}`); | |
| 81 | return new Response(null, { status: 204 }); | |
| 82 | }; | |
| 83 | }, 30_000); | |
| 84 | afterAll(async () => { | |
| 85 | Object.assign(net, { fetch: saved.fetch }); | |
| 86 | cloudNet.fetch = saved.cloud; | |
| 87 | servers.stop(); | |
| 88 | app.close(); | |
| 89 | await rm(dir, { recursive: true, force: true }); | |
| 90 | }); | |
| 91 | ||
| 92 | describe("the plan", () => { | |
| 93 | test("a stop names what stops, its cost now, and that billing goes on; a delete names what is lost", () => { | |
| 94 | const stop = planEnd(app, admin, "stop", nodeOf("machine:111")); | |
| 95 | if (!stop.ok) throw new Error(stop.error); | |
| 96 | expect(stop.value.refusal).toBe(""); | |
| 97 | expect(planText(stop.value)).toContain("web"); | |
| 98 | expect(planText(stop.value)).toContain("$12.00 a month"); | |
| 99 | expect(planText(stop.value)).toContain("bill a stopped machine"); | |
| 100 | const del = planEnd(app, admin, "delete", nodeOf("volume:vol-9")); | |
| 101 | if (!del.ok) throw new Error(del.error); | |
| 102 | expect(del.value.refusal).toBe(""); | |
| 103 | expect(planText(del.value)).toContain("Every byte on the volume"); | |
| 104 | expect(calls()).toEqual([]); | |
| 105 | }); | |
| 106 | ||
| 107 | test("a volume cannot be stopped, an attached one cannot be deleted, a stranger sees nothing", () => { | |
| 108 | const vol = planEnd(app, admin, "stop", nodeOf("volume:vol-9")); | |
| 109 | expect(vol.ok && vol.value.refusal).toContain("cannot be stopped"); | |
| 110 | const busy = planEnd(app, admin, "delete", nodeOf("volume:vol-8")); | |
| 111 | expect(busy.ok && busy.value.refusal).toContain("attached to machine:111"); | |
| 112 | expect(planEnd(app, plain, "delete", nodeOf("volume:vol-9"))).toEqual({ ok: false, error: "not_found" }); | |
| 113 | }); | |
| 114 | }); | |
| 115 | ||
| 116 | describe("a read-only account", () => { | |
| 117 | test("is refused both, by the server, with a refused audit row and no call to the vendor", async () => { | |
| 118 | expect(offeredEnds(app, nodeOf("machine:222"), resourceOf("machine:222"))).toEqual([]); | |
| 119 | expect(offeredEnds(app, nodeOf("machine:111"), resourceOf("machine:111")).map((e) => e.act)).toEqual(["stop", "delete"]); | |
| 120 | const stop = await performEnd(app, admin, "stop", nodeOf("machine:222"), { digest: "", typed: "" }); | |
| 121 | expect(stop).toEqual({ ok: false, error: READ_ONLY }); | |
| 122 | const del = await performEnd(app, admin, "delete", nodeOf("volume:vol-7"), { digest: "", typed: "locked-data" }); | |
| 123 | expect(del).toEqual({ ok: false, error: READ_ONLY }); | |
| 124 | expect(calls()).toEqual([]); | |
| 125 | const rows = auditToday(app.db).filter((r) => r.purpose.startsWith("stop:") || r.purpose.startsWith("delete:")); | |
| 126 | expect(rows.map((r) => [r.purpose, r.allowed, r.actor])).toEqual([["delete:volume", false, admin.id], ["stop:machine", false, admin.id]]); | |
| 127 | }); | |
| 128 | ||
| 129 | test("the page shows the refusal and no form", async () => { | |
| 130 | const path = nodeOf("volume:vol-7").map(encodeURIComponent).join("/"); | |
| 131 | const res = await fetch(`${servers.url}/infra/end/delete/${path}`, { headers: { cookie: `forge_session=${createSession(app.db, admin.id).token}` } }); | |
| 132 | const text = await res.text(); | |
| 133 | expect(res.status).toBe(200); | |
| 134 | expect(text).toContain("read-only"); | |
| 135 | expect(text).not.toContain('name="confirm"'); | |
| 136 | }); | |
| 137 | }); | |
| 138 | ||
| 139 | describe("a write-allowed account", () => { | |
| 140 | test("a stop is done only with the plan's digest, and audited with who and the plan", async () => { | |
| 141 | const path = nodeOf("machine:111"); | |
| 142 | const p = planEnd(app, admin, "stop", path); | |
| 143 | if (!p.ok) throw new Error(p.error); | |
| 144 | const stale = await performEnd(app, admin, "stop", path, { digest: "0".repeat(16), typed: "" }); | |
| 145 | expect(stale.ok).toBe(false); | |
| 146 | expect(calls()).toEqual([]); | |
| 147 | const done = await performEnd(app, admin, "stop", path, { digest: p.value.digest, typed: "" }); | |
| 148 | expect(done.ok).toBe(true); | |
| 149 | expect(calls().filter((c) => !c.startsWith("GET"))).toEqual(['POST /v2/droplets/111/actions {"type":"power_off"}']); | |
| 150 | const row = auditToday(app.db).find((r) => r.purpose === "stop:machine" && r.allowed); | |
| 151 | expect(row).toMatchObject({ provider: "digitalocean", account: "rw", actor: admin.id, target: "machine:111" }); | |
| 152 | expect(row?.plan).toBe(planText(p.value)); | |
| 153 | }); | |
| 154 | ||
| 155 | test("a delete needs the name typed back, then deletes and is audited", async () => { | |
| 156 | const path = nodeOf("volume:vol-9"); | |
| 157 | const p = planEnd(app, admin, "delete", path); | |
| 158 | if (!p.ok) throw new Error(p.error); | |
| 159 | const wrong = await performEnd(app, admin, "delete", path, { digest: p.value.digest, typed: "yes" }); | |
| 160 | expect(wrong.ok).toBe(false); | |
| 161 | expect(calls()).toEqual([]); | |
| 162 | const done = await performEnd(app, admin, "delete", path, { digest: p.value.digest, typed: "web-data" }); | |
| 163 | expect(done.ok).toBe(true); | |
| 164 | expect(calls()).toEqual(["DELETE /v2/volumes/vol-9"]); | |
| 165 | const row = auditToday(app.db).find((r) => r.purpose === "delete:volume" && r.allowed); | |
| 166 | expect(row).toMatchObject({ actor: admin.id, target: "volume:vol-9" }); | |
| 167 | expect(row?.plan).toContain("Every byte on the volume"); | |
| 168 | }); | |
| 169 | ||
| 170 | test("over HTTP: the confirm is same-origin checked, an admin's, and a delete is not one tap", async () => { | |
| 171 | const path = nodeOf("machine:111").map(encodeURIComponent).join("/"); | |
| 172 | const p = planEnd(app, admin, "delete", nodeOf("machine:111")); | |
| 173 | if (!p.ok) throw new Error(p.error); | |
| 174 | const url = `${servers.url}/infra/end/delete/${path}`; | |
| 175 | const h = { cookie: `forge_session=${createSession(app.db, admin.id).token}`, "content-type": "application/x-www-form-urlencoded" }; | |
| 176 | const page = await (await fetch(url, { headers: h })).text(); | |
| 177 | expect(page).toContain("Type web to delete it"); | |
| 178 | const body = new URLSearchParams({ plan: p.value.digest, confirm: "web" }); | |
| 179 | const cross = await fetch(url, { method: "POST", headers: { ...h, origin: "https://evil.example" }, body, redirect: "manual" }); | |
| 180 | expect(cross.status).toBeGreaterThanOrEqual(400); | |
| 181 | const other = await fetch(url, { method: "POST", headers: { cookie: `forge_session=${createSession(app.db, plain.id).token}`, "content-type": h["content-type"] }, body, redirect: "manual" }); | |
| 182 | expect(other.status).toBeGreaterThanOrEqual(400); | |
| 183 | const bare = await fetch(url, { method: "POST", headers: h, body: new URLSearchParams({ plan: p.value.digest }), redirect: "manual" }); | |
| 184 | expect(bare.status).toBe(303); | |
| 185 | expect(calls()).toEqual([]); | |
| 186 | const ok = await fetch(url, { method: "POST", headers: h, body, redirect: "manual" }); | |
| 187 | expect(ok.status).toBe(303); | |
| 188 | expect(calls()).toEqual(["DELETE /v2/droplets/111"]); | |
| 189 | }); | |
| 190 | }); | |
| 191 | ||
| 192 | describe("the terminal", () => { | |
| 193 | test("X on a resource shows the same plan, and a read-only account says why", async () => { | |
| 194 | const terminal = headlessTerminal(160, 40); | |
| 195 | const { app: tui, session } = createForgeApp(app, { sshUsername: "ada", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin }, { terminal, exitHooks: false }); | |
| 196 | tui.start(); | |
| 197 | tui.ctx.push(cloudTreeScreen(session, tui.ctx)); | |
| 198 | await settleApp(tui); | |
| 199 | for (const k of ["/", ..."locked-data", "\r", "j", "j", "j"]) terminal.feed(k); | |
| 200 | await settleApp(tui); | |
| 201 | terminal.feed("X"); | |
| 202 | await settleApp(tui); | |
| 203 | expect(tui.screen.toText()).toContain(READ_ONLY); | |
| 204 | }); | |
| 205 | ||
| 206 | test("x on a write-allowed machine shows the plan to stop it", async () => { | |
| 207 | const terminal = headlessTerminal(160, 40); | |
| 208 | const { app: tui, session } = createForgeApp(app, { sshUsername: "ada", remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: admin }, { terminal, exitHooks: false }); | |
| 209 | tui.start(); | |
| 210 | tui.ctx.push(cloudTreeScreen(session, tui.ctx)); | |
| 211 | await settleApp(tui); | |
| 212 | for (const k of ["/", ..."kind:machine web", "\r", "j", "j", "j", "x"]) terminal.feed(k); | |
| 213 | await settleApp(tui); | |
| 214 | const text = tui.screen.toText(); | |
| 215 | expect(text).toContain("Stop web?"); | |
| 216 | expect(text).toContain("$12.00 a month"); | |
| 217 | expect(calls()).toEqual([]); | |
| 218 | }); | |
| 219 | }); | |
| 220 | ||
| 221 | describe("the plan as facts", () => { | |
| 222 | test("the page shows Will, Cost now, Lost and Kept as dl rows, and the audit names the person", async () => { | |
| 223 | const p = planEnd(app, admin, "delete", nodeOf("volume:vol-9")); | |
| 224 | if (!p.ok) throw new Error(p.error); | |
| 225 | expect(p.value.lines.map((l) => l.label)).toEqual(["Will", "Cost now", "Lost"]); | |
| 226 | const { endPage } = await import("../src/web/pages/cloud_end.ts"); | |
| 227 | const out = String(endPage(p.value)); | |
| 228 | expect(out).toContain("<dt>Will</dt>"); | |
| 229 | expect(out).toContain("<dt>Cost now</dt>"); | |
| 230 | expect(out).not.toContain("<p>Will"); | |
| 231 | }); | |
| 232 | }); | |
| 233 | ||
| 234 | describe("the audit page", () => { | |
| 235 | test("shows who by name and the plan as its own Plan row, not the user id", async () => { | |
| 236 | const res = await fetch(`${servers.url}/settings/cloud/audit`, { headers: { cookie: `forge_session=${createSession(app.db, admin.id).token}` } }); | |
| 237 | const text = await res.text(); | |
| 238 | expect(text).toContain("<dt>Plan</dt>"); | |
| 239 | expect(text).not.toContain(`by <span class="mono">${admin.id}</span>`); | |
| 240 | expect(text).toContain(`by ${admin.displayName || admin.username}`); | |
| 241 | }); | |
| 242 | }); |
test/no-polling.test.ts +1
| @@ -305,6 +305,7 @@ const ORIGIN = "needs a connected origin account; the seed connects none"; | ||
| 305 | 305 | const NOT_WALKED: Record<string, string> = { |
| 306 | 306 | "/talk/dev/:token": "a frame proxied from a running dev cell, not a page; the seed starts none", |
| 307 | 307 | "/talk/dev/:token/*path": "a file proxied from a running dev cell, not a page; the seed starts none", |
| 308 | "/infra/end/:act/*path": "the plan of a stop or delete, a page for a cloud resource the seed does not have; the action word is not in the seed", | |
| 308 | 309 | "/tab/v/:hash/:file": "a content-hashed browser-tab bundle file, JS or wasm, not a page; the hash is one the seed cannot guess", |
| 309 | 310 | "/edge/config/:file": "a published config file for the edge, JSON or a key, not a page; the seed publishes none", |
| 310 | 311 | "/:owner/-/teams/:team": "needs an organization and a team", |
test/pages-budget.test.ts +1
| @@ -218,6 +218,7 @@ beforeAll(async () => { | ||
| 218 | 218 | [id, kind, new Date().toISOString(), on], |
| 219 | 219 | ); |
| 220 | 220 | FIXTURE["/infra/-/*path"] = "/infra/-/aws/main/us-east-1/volume%3Avol-1"; // a bare ":" reads as unfilled |
| 221 | FIXTURE["/infra/end/:act/*path"] = "/infra/end/delete/aws/main/us-east-1/volume%3Avol-1"; | |
| 221 | 222 | servers = await serve(app); |
| 222 | 223 | const signin = await fetch(`${servers.url}/signin`, { |
| 223 | 224 | method: "POST", |
test/pinned-ceiling.test.ts +5 −2
| @@ -353,7 +353,7 @@ describe("cloud account ceiling", () => { | ||
| 353 | 353 | if (/^import\b[^\n]*$/.test(text.slice(text.lastIndexOf("\n", m.index) + 1, m.index))) continue; |
| 354 | 354 | uses++; |
| 355 | 355 | const before = text.slice(Math.max(0, m.index - 80), m.index); |
| 356 | if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire|strays|ensureFirewall|removeFirewall|snapshotKind|takeSnapshot|readSnapshot|dropSnapshot|viewOf|bootRefusal)\((?:app, )?$/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`); | |
| 356 | if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire|strays|ensureFirewall|removeFirewall|snapshotKind|takeSnapshot|readSnapshot|dropSnapshot|viewOf|bootRefusal|endView)\((?:app, )?$/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`); | |
| 357 | 357 | } |
| 358 | 358 | } |
| 359 | 359 | expect(bare).toEqual([]); |
| @@ -366,7 +366,10 @@ describe("cloud account ceiling", () => { | ||
| 366 | 366 | // view of a machine (#17151), handed to `viewOf`. A bare driverOf still fails the pattern |
| 367 | 367 | // above; only those call names are let through. |
| 368 | 368 | // And the size of a boot config, measured in the plan and sent nowhere. |
| 369 | expect(uses).toBe(17); | |
| 369 | // And one to stop or delete a machine or volume (actions/cloud_end.ts `endDriver`, handed to | |
| 370 | // `endView`, which narrows the driver to stopMachine, deleteMachine and deleteVolume: an end | |
| 371 | // cannot provision, so it takes money out of the bill, never in). | |
| 372 | expect(uses).toBe(18); | |
| 370 | 373 | }); |
| 371 | 374 | }); |
| 372 | 375 |
test/security-floor-routes.test.ts +1
| @@ -71,6 +71,7 @@ const SHOT = "needs a pin with a picture kept by refs/shots; the seed pins nothi | ||
| 71 | 71 | const CART = "the seed pins no build with a cart (test/build-cart.test.ts covers its headers)"; |
| 72 | 72 | const UNSEEDED: Record<string, string> = { |
| 73 | 73 | "/tab/v/:hash/:file": "a vendored file of the browser-tab forge, named by its content hash, which the seed does not hold (test/tab.test.ts covers it)", |
| 74 | "/infra/end/:act/*path": "the plan of a stop or delete for a cloud resource, which the seed does not have (test/cloud-end.test.ts covers it)", | |
| 74 | 75 | "/games/:box": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 75 | 76 | "/games/:box/:service": "a game box, which the seed does not make (test/games.test.ts covers it)", |
| 76 | 77 | "/games/:box/@shell/stream": "a game box's shell output for its owner, which the seed does not make (test/game-console.test.ts covers it)", |
new above
offline
No test for this call (and none for OVH's stopMachine). Add driver tests; and say whether a hard
poweroffor a gracefulshutdownis meant.