Public: anyone can read this; the crew can change it.
A deploy never makes two machines for one forge, a forge can be retired, and… #16558
Check · Review · Land · Live — Its check is red.
mason/forge:mason/16219-a-deploy-never-makes-two-machines-for-on → main 2 commits fork
20 files
changed +685
−66
- docs/features/pinned-forge.md
- src/actions/pinned.ts
- src/cloud/bun_install.ts
- src/cloud/droplet.ts
- src/cloud/gate.ts
- src/cloud/hetzner.ts
- src/cloud/machine.ts
- src/cloud/sale_source.ts
- src/http/mcp/tools/pinned_forge.ts
- src/spawn/cloud_placement.ts
- test/helpers/recorded-cloud.ts
- test/one-door.test.ts
- test/order-cloud.test.ts
- test/pinned-ceiling.test.ts
- test/pinned-detach.test.ts
- test/pinned-forge-recovery.test.ts
- test/pinned-forge.test.ts
- test/pinned-harden.test.ts
- test/pinned-hetzner.test.ts
- test/pinned-one-machine.test.ts
docs/features/pinned-forge.md +10 −1
| @@ -92,7 +92,7 @@ With a **Cloudflare** cloud account attached and writes allowed, the forge then | ||
| 92 | 92 | An admin chooses where **paid forges run** on Pinned forges (`/pinned`; the terminal's `p`; `PATCH /api/v1/admin/settings` with `{"paidPlacement": "digitalocean/main"}`, `"hosted"` or `null` for the default; `GET` answers it as `paidPlacement`). It is a forge setting (`settings/paid_placement.ts`, `paid.placement`, every change kept with who and when). `hosted`, the default, is today's: a bought forge runs inside this one. A cloud account (one a pinned forge can be deployed to, with writes allowed) makes each paid order a pinned forge of its own (`src/spawn/cloud_placement.ts`). Free forges always stay hosted. |
| 93 | 93 | |
| 94 | 94 | - **Told before paying.** `/pricing` (and the terminal's pricing screen) asks the cloud placement's `room` before the checkout is made: no domain for deployed forges, a catalog never read, a default place that cannot be ordered, or a deploy the account's ceiling would refuse, each is said in the deploy's own sentence, and nothing is held or charged. |
| 95 | - **Deployed as the order.** Once paid, the forge is deployed at the catalog's default place for the plan, with no hostname (it is served on `<name>.<domain>`), running the forge's own source repository (public, cloned from this forge over https) at the commit this forge runs (`FORGE_COMMIT`; the release tag when the build names none; a forge run from source refuses). The deploy acts as the order, never a borrowed admin: the row's history says `order:<id>`, its events carry `order` and no actor, and the token reads name the order in their run. Every refusal an admin's deploy has (target, catalog, place, ceiling) applies. | |
| 95 | - **Deployed as the order.** Once paid, the forge is deployed at the catalog's default place for the plan, with no hostname (it is served on `<name>.<domain>`), running the forge's own source repository (public) at the commit this forge runs (`FORGE_COMMIT`; a forge run from source refuses, and so does one that knows only a release tag: a sale takes a commit). The source is where the owner says (see *Money and trust* below), never this forge's own address. The deploy acts as the order, never a borrowed admin: the row's history says `order:<id>`, its events carry `order` and no actor, and the token reads name the order in their run. Every refusal an admin's deploy has (target, catalog, place, ceiling) applies. | |
| 96 | 96 | - **Making, then the link.** A machine takes minutes, so the order is `making` (`/pricing/done` says so and refreshes) until the forge answers on its name: the pinned check, asked as the order at most every 15 seconds by the order's row, by the page and by this process for 15 minutes after the deploy. The claim link is the pinned one, issued with the machine: kept sealed as a forge secret (`ORDER_CLAIM_<id>`, each read audited) until the order is `spawned`, then mailed (when the forge can mail) and shown once on the done page, after which it is deleted. |
| 97 | 97 | - **Never two machines, never hosted instead.** A restart while making only asks again. A spawn lost to a restart after its machine was recorded issues a new claim instead (the machine replaced on its own volume); one lost before is deployed again on its volume. A refused deploy leaves the order `failed` with the sentence, for an admin to retry or refund; it is never made hosted. |
| 98 | 98 | - **Not yet.** Lapse and cancel do nothing to a cloud forge; `/pricing/resend` cannot issue a new link for one (it would replace the machine); the crew credit a paid plan lends is lent over loopback to hosted forges and does not reach a cloud one (the plan rows on `/pricing` still state it); the after-payment steps, the lapse words, the key note and the `<name>--<parent>` address on `/pricing` still describe a hosted forge. |
| @@ -162,3 +162,12 @@ The name defaults to `canary-<date>-<time>`, so a second run the same day does n | ||
| 162 | 162 | Not run yet. It needs a DigitalOcean token an owner has put in Settings → Cloud accounts; none was available to the agent that wrote the script. Paste the table the script prints here, with the date, and close #8746. |
| 163 | 163 | |
| 164 | 164 | This is an operator script, not a feature: it has no screen in `src/tui/` and no MCP verb because it drives the doors that exist (the HTTP admin API, the same actions the terminal and `pinned_forge` use); a second door to a one-off paid test would be one more thing to keep honest. It is small, touches no `src/`, and was written so the owner's run is one command; it does not displace the pipeline list. The pull refers to #8746 and does not close it: the issue closes when the table above is real. |
| 165 | ||
| 166 | ## Money and trust (#16219) | |
| 167 | ||
| 168 | - **One forge, one machine, one volume.** Before a volume or machine is created the provider is asked for one with the forge's name (and, on Hetzner, its label; on DigitalOcean its tag), and one found is adopted. A create whose answer was lost (the call times out at 20 s) is therefore never repeated by the retry (`findVolume`, `findMachine` in `src/cloud/machine.ts`, one per driver). An answer without a usable id is an error, never a machine recorded as "". | |
| 169 | - **Retire** deletes the machine; the volume only when asked again with its data (`withData`), on the page, the tool and the API, and each is recorded as a `pinned.retired` event. **Strays**: the tool's `strays` verb (`target`, `account`) lists the machines and volumes at the provider that carry a forge's label and belong to no row. It deletes nothing. | |
| 170 | - **Ids and addresses.** Hetzner ids are digits (`numericId`: `""` is not 0) and reach a path only so. The address read back from the provider is kept only if it is a public IPv4: private, loopback, link-local (metadata), carrier-grade, benchmarking, multicast and reserved ranges are refused, since the forge probes it. | |
| 171 | - **Bun** is installed by `/usr/local/sbin/forge-install-bun`, which downloads the release's own package from the npm registry and installs it only if its sha512 equals the one pinned in `src/cloud/bun_install.ts` (one per architecture; a test fails when `.bun-version` moves without them). `bun.sh/install` is no longer piped into a shell. | |
| 172 | - **What a sale runs.** A paid order takes a full 40-hex commit only (a tag can be moved by whoever holds the source), from a host in `FORGE_SALE_SOURCES` (comma-separated DNS names; empty means no sale deploys), never the selling forge's own host: a machine with no credential cannot read a private repository here, and its boot and later updates (`FORGE_UPSTREAM`) must not wait for this forge. `FORGE_SALE_SOURCE` is the one https git address sold forges are booted from and follow. An admin's own deploy keeps the wider rule above. | |
| 173 | - **The selling account is not a run's.** A run reaches a cloud token only through `bar` in `src/cloud/gate.ts`. The account named by "paid forges run on", and any account a pinned forge's row records, is refused there whatever `cloud.json` declares (audited as `hand-out:selling`). Hosted forges are children and get no cloud token through any other path. |
src/actions/pinned.ts +38 −1
| @@ -29,7 +29,8 @@ import type { App } from "../app.ts"; | ||
| 29 | 29 | import { gatedFetch } from "../cloud/gate.ts"; |
| 30 | 30 | import { capped, CeilingRefusal, priced, refusalAt, rowCents } from "../cloud/ceiling.ts"; |
| 31 | 31 | import { driverOf } from "../cloud/drivers.ts"; |
| 32 | import { fileIn, orderable, provision, read, replace, retire } from "../cloud/machine.ts"; | |
| 32 | import { fileIn, orderable, provision, read, replace, retire, strays, type Labelled } from "../cloud/machine.ts"; | |
| 33 | import { saleCode } from "../cloud/sale_source.ts"; | |
| 33 | 34 | import { dollars } from "../cloud/prices.ts"; |
| 34 | 35 | import { chooseDefault, isPlan, meets, type Chosen, type Place, type PlanName } from "../cloud/places.ts"; |
| 35 | 36 | import { inFlight } from "../billing/orders.ts"; |
| @@ -754,6 +755,28 @@ export function retireWords(v: Retired): string { | ||
| 754 | 755 | return `${v.name} is retired: its machine is deleted${dns}. ${data}`; |
| 755 | 756 | } |
| 756 | 757 | |
| 758 | /** | |
| 759 | * What the provider holds under the forge's label that no row owns (#16219): machines and volumes | |
| 760 | * that bill and belong to nothing here. Asked of one cloud account, read-only; nothing is deleted, | |
| 761 | * so a person looks at each and removes it at the provider, or has the row that should own it. | |
| 762 | */ | |
| 763 | export async function strayCloud(app: App, actor: User | undefined, target: string, account: string): Promise<Result<Labelled, string>> { | |
| 764 | const who = admin(actor); | |
| 765 | if (!who.ok) return who; | |
| 766 | if (!targetOf(target)) return err("That is not a target the forge knows."); | |
| 767 | const rows = listPinned(app.db).filter((p) => p.target === target && p.account === account); | |
| 768 | const owned = { machines: new Set(rows.map((p) => p.remote).filter((x) => x !== "")), volumes: new Set(rows.map((p) => p.volume).filter((x) => x !== "")) }; | |
| 769 | const anchor = { target, account } as Pinned; | |
| 770 | return withCloud(app, who.value, anchor, "strays", (f, token) => strays(driverOf(target), f, token, owned), false); | |
| 771 | } | |
| 772 | ||
| 773 | /** What the strays are, in the one sentence every door says. */ | |
| 774 | export function strayWords(s: Labelled): string { | |
| 775 | if (s.machines.length === 0 && s.volumes.length === 0) return "Nothing at the provider carries a forge's label without a row: no machine or volume is billing for nothing."; | |
| 776 | const list = (kind: string, xs: Labelled["machines"]) => xs.map((x) => `${kind} ${x.id} (${x.name})`).join(", "); | |
| 777 | return `At the provider, owned by no row: ${[list("machine", s.machines), list("volume", s.volumes)].filter((x) => x !== "").join("; ")}. Each bills until it is deleted there.`; | |
| 778 | } | |
| 779 | ||
| 757 | 780 | export type Checked = PinnedView & { readonly healthy: boolean; readonly waiting: Waiting; readonly claim: ClaimState }; |
| 758 | 781 | |
| 759 | 782 | /** What a check found, in the one sentence every door says. */ |
| @@ -861,6 +884,12 @@ const NOT_THE_ORDERS = "A pinned forge has that name already."; | ||
| 861 | 884 | export async function deployForOrder(app: App, orderId: string, input: DeployInput): Promise<Result<Issued, string>> { |
| 862 | 885 | const who = orderWho(orderId); |
| 863 | 886 | const old = getPinned(app.db, input.name); |
| 887 | if (old === undefined || old.remote === "") { | |
| 888 | // A forge sold to someone runs a commit from a source the owner listed | |
| 889 | // (`cloud/sale_source.ts`). | |
| 890 | const sold = saleCodeOf(app, input); | |
| 891 | if (!sold.ok) return sold; | |
| 892 | } | |
| 864 | 893 | if (old === undefined) return deployAs(app, who, input); |
| 865 | 894 | if (!madeBy(app, input.name, who)) return err(NOT_THE_ORDERS); |
| 866 | 895 | if (old.state === "retired") return err(RETIRED_REFUSAL); |
| @@ -869,6 +898,14 @@ export async function deployForOrder(app: App, orderId: string, input: DeployInp | ||
| 869 | 898 | return deployAs(app, who, input); |
| 870 | 899 | } |
| 871 | 900 | |
| 901 | /** | |
| 902 | * The code a paid order would boot, held to what a sale may run: asked again before a buyer pays. | |
| 903 | */ | |
| 904 | export function saleCodeOf(app: App, input: { source?: string; version?: string }): Result<{ source: string; version: string }, string> { | |
| 905 | const code = ownCode(app, input); | |
| 906 | return code.ok ? saleCode(code.value, app.config.url) : code; | |
| 907 | } | |
| 908 | ||
| 872 | 909 | /** Check a paid order's forge, as the order: refused for one it did not deploy. */ |
| 873 | 910 | export function checkForOrder(app: App, orderId: string, name: string): Promise<Result<Checked, string>> { |
| 874 | 911 | const who = orderWho(orderId); |
src/cloud/bun_install.ts added +52
| @@ -0,0 +1,52 @@ | ||
| 1 | /** | |
| 2 | * How a machine gets Bun, verified (#16219). It used to pipe `https://bun.sh/install` into a root | |
| 3 | * shell, which trusts whatever that address serves that day. Now the boot downloads the release's | |
| 4 | * own package from the npm registry (`@oven/bun-linux-<arch>`, the same binary), computes its | |
| 5 | * sha512 and installs it only when it equals the integrity pinned here, one per architecture. A | |
| 6 | * version with no entry cannot be booted: `.bun-version` and this table move together, and a test | |
| 7 | * holds them to it. Add an entry with `npm view @oven/bun-linux-x64@<v> dist.integrity` (and | |
| 8 | * `-aarch64`). | |
| 9 | */ | |
| 10 | ||
| 11 | import { BUN_HOME } from "./harden.ts"; | |
| 12 | ||
| 13 | /** Subresource-integrity (sha512, base64) of each Bun release's linux package, by version. */ | |
| 14 | export const BUN_INTEGRITY: Readonly<Record<string, { readonly x64: string; readonly aarch64: string }>> = { | |
| 15 | "1.4.4": { | |
| 16 | x64: "sha512-CHbbkmHVM28T1GFq+6GL4Ao4ujwwYwj1CxFFwEFzLanPfNsId9AhbIP0Q4reWuWBkGimUkoQygrK7Rgjtj3vog==", | |
| 17 | aarch64: "sha512-ZTVtpf9zmHSBVPX1sBwe5agGb/rN34yPGg/Hby8e2Ax2uCUA2URZKlZH7qLntK7qaFJCMXh9v0GWNYN2zINz1w==", | |
| 18 | }, | |
| 19 | }; | |
| 20 | ||
| 21 | /** Where the boot script is written on the machine. */ | |
| 22 | export const BUN_INSTALLER = "/usr/local/sbin/forge-install-bun"; | |
| 23 | ||
| 24 | /** | |
| 25 | * The script that installs Bun `version` under `BUN_HOME`, stopping before anything is installed | |
| 26 | * when the download is not the pinned bytes. Every interpolated value is a pinned constant or a | |
| 27 | * dotted version checked against the table. | |
| 28 | */ | |
| 29 | export function bunInstallScript(version: string): string { | |
| 30 | const pin = Object.hasOwn(BUN_INTEGRITY, version) ? BUN_INTEGRITY[version] : undefined; | |
| 31 | if (pin === undefined) throw new Error(`Bun ${version} has no pinned checksum: add it to cloud/bun_install.ts before a machine is booted with it`); | |
| 32 | const get = (pkg: string, want: string) => | |
| 33 | `fetch ${pkg} "${want}"`; | |
| 34 | return `#!/bin/sh | |
| 35 | set -eu | |
| 36 | fetch() { | |
| 37 | tmp=$(mktemp -d) | |
| 38 | curl -fsSL --retry 5 --retry-delay 5 -o "$tmp/bun.tgz" "https://registry.npmjs.org/@oven/$1/-/$1-${version}.tgz" | |
| 39 | got="sha512-$(openssl dgst -sha512 -binary "$tmp/bun.tgz" | base64 -w0)" | |
| 40 | if [ "$got" != "$2" ]; then echo "bun: checksum mismatch, nothing installed" >&2; exit 1; fi | |
| 41 | tar -xzf "$tmp/bun.tgz" -C "$tmp" | |
| 42 | install -D -m 0755 "$tmp/package/bin/bun" ${BUN_HOME}/bin/bun | |
| 43 | ln -sf bun ${BUN_HOME}/bin/bunx | |
| 44 | rm -rf "$tmp" | |
| 45 | } | |
| 46 | case "$(uname -m)" in | |
| 47 | x86_64) ${get("bun-linux-x64", pin.x64)} ;; | |
| 48 | aarch64|arm64) ${get("bun-linux-aarch64", pin.aarch64)} ;; | |
| 49 | *) echo "bun: no build for $(uname -m)" >&2; exit 1 ;; | |
| 50 | esac | |
| 51 | `; | |
| 52 | } |
src/cloud/droplet.ts +24 −1
| @@ -9,7 +9,7 @@ | ||
| 9 | 9 | */ |
| 10 | 10 | |
| 11 | 11 | import { dropThrowawayKey, makeThrowawayKey } from "./throwaway_key.ts"; |
| 12 | import { bootConfig as boot, forgeTag, ipv4, volumeName, type Booted, type Driver } from "./machine.ts"; | |
| 12 | import { bootConfig as boot, forgeTag, ipv4, volumeName, type Booted, type Driver, type Found } from "./machine.ts"; | |
| 13 | 13 | |
| 14 | 14 | export { BUN_VERSION } from "./machine.ts"; |
| 15 | 15 | |
| @@ -21,6 +21,16 @@ export const bootConfig = (p: Booted): string => boot(p, dataDir(p.name)); | ||
| 21 | 21 | /** DigitalOcean's collection of account SSH keys. */ |
| 22 | 22 | const KEYS = "/account/keys"; |
| 23 | 23 | |
| 24 | /** What a list answers, as ids and names; an entry without a usable id is dropped. */ | |
| 25 | const foundIn = (list: unknown): Found[] => | |
| 26 | (Array.isArray(list) ? list : []).flatMap((x: any) => { | |
| 27 | const id = typeof x?.id === "number" ? String(x.id) : typeof x?.id === "string" ? x.id : ""; | |
| 28 | return /^[A-Za-z0-9-]{1,64}$/.test(id) && typeof x.name === "string" ? [{ id, name: x.name }] : []; | |
| 29 | }); | |
| 30 | ||
| 31 | /** Whether a listed thing carries a forge's tag. */ | |
| 32 | const tagged = (x: any, tag: (t: string) => boolean): boolean => Array.isArray(x?.tags) && x.tags.some((t: unknown) => typeof t === "string" && tag(t)); | |
| 33 | ||
| 24 | 34 | /** Both the volume and the droplet are made in the row's datacenter, at its size (`machine.ts`). */ |
| 25 | 35 | export const digitalocean: Driver = { |
| 26 | 36 | api: "https://api.digitalocean.com/v2", |
| @@ -28,6 +38,19 @@ export const digitalocean: Driver = { | ||
| 28 | 38 | const v = await call("POST", "/volumes", { name: volumeName(p.name), region: p.datacenter, size_gigabytes: 10, filesystem_type: "ext4", tags: [forgeTag(p.name)] }); |
| 29 | 39 | return String(v.volume?.id ?? ""); |
| 30 | 40 | }, |
| 41 | async findVolume(call, p) { | |
| 42 | const all: any[] = (await call("GET", `/volumes?name=${encodeURIComponent(volumeName(p.name))}®ion=${encodeURIComponent(p.datacenter)}`)).volumes ?? []; | |
| 43 | return foundIn(all.filter((v) => v?.region?.slug === p.datacenter && v?.name === volumeName(p.name)))[0]?.id ?? ""; | |
| 44 | }, | |
| 45 | async findMachine(call, p) { | |
| 46 | const all = (await call("GET", `/droplets?tag_name=${encodeURIComponent(forgeTag(p.name))}&per_page=200`)).droplets; | |
| 47 | return foundIn(all).find((d) => d.name === `forge-${p.name}`)?.id ?? ""; | |
| 48 | }, | |
| 49 | async listForges(call) { | |
| 50 | const droplets = (await call("GET", `/droplets?tag_name=forge-pinned&per_page=200`)).droplets; | |
| 51 | const volumes: any[] = (await call("GET", `/volumes?per_page=200`)).volumes ?? []; | |
| 52 | return { machines: foundIn(droplets), volumes: foundIn(volumes.filter((v) => tagged(v, (t) => t.startsWith("forge:")))) }; | |
| 53 | }, | |
| 31 | 54 | async createMachine(call, p, volume) { |
| 32 | 55 | // A droplet made with no SSH key is sent a root password by email; see throwaway_key.ts. |
| 33 | 56 | const key = await makeThrowawayKey(call, KEYS, p.name); |
src/cloud/gate.ts +24 −3
| @@ -10,6 +10,8 @@ import type { Database } from "bun:sqlite"; | ||
| 10 | 10 | import type { CloudDeclaration } from "../apps/manifest.ts"; |
| 11 | 11 | import { accountOfSecret } from "../core/cloud_account.ts"; |
| 12 | 12 | import { recordAudit } from "../core/cloud_audit.ts"; |
| 13 | import { listPinned } from "../core/pinned.ts"; | |
| 14 | import { getPaidPlacement } from "../settings/paid_placement.ts"; | |
| 13 | 15 | import { VENDOR_OF, isProvider, type Fetch } from "./providers.ts"; |
| 14 | 16 | |
| 15 | 17 | export interface Who { |
| @@ -48,6 +50,18 @@ function bytesOf(init: RequestInit | undefined): number { | ||
| 48 | 50 | return 0; |
| 49 | 51 | } |
| 50 | 52 | |
| 53 | /** | |
| 54 | * Whether the account is one this forge deploys forges with: the one forges are sold on | |
| 55 | * (`paid.placement`), or any a pinned forge's row records. Such a token can create and delete | |
| 56 | * machines that bill the owner, and is for the forge's own deploys only (#16219): never handed to | |
| 57 | * a run, whatever a `cloud.json` declares. | |
| 58 | */ | |
| 59 | export function sellingAccount(db: Database, who: Who): boolean { | |
| 60 | const placed = getPaidPlacement(db); | |
| 61 | if (placed.where === "cloud" && placed.provider === who.provider && placed.account === who.account) return true; | |
| 62 | return listPinned(db).some((p) => p.target === who.provider && p.account === who.account); | |
| 63 | } | |
| 64 | ||
| 51 | 65 | /** |
| 52 | 66 | * A hand-out of a token to a run: allowed when `cloud.json` declares the |
| 53 | 67 | * provider's vendor (`VENDOR_OF`) for any use, audited either way. Returns |
| @@ -64,11 +78,12 @@ export function handOut( | ||
| 64 | 78 | vendor === undefined |
| 65 | 79 | ? undefined |
| 66 | 80 | : declared?.find((d) => d.vendor === vendor)?.use; |
| 67 | const ok = use !== undefined; | |
| 81 | const selling = use !== undefined && sellingAccount(db, who); | |
| 82 | const ok = use !== undefined && !selling; | |
| 68 | 83 | recordAudit(db, { |
| 69 | 84 | provider: who.provider, |
| 70 | 85 | account: who.account, |
| 71 | purpose: `hand-out:${use ?? "undeclared"}`, | |
| 86 | purpose: `hand-out:${selling ? "selling" : (use ?? "undeclared")}`, | |
| 72 | 87 | target: `run ${runId}`, |
| 73 | 88 | bytesOut: 0, |
| 74 | 89 | allowed: ok, |
| @@ -91,9 +106,15 @@ export function bar<T extends { names: readonly string[]; refused: readonly stri | ||
| 91 | 106 | const a = accountOfSecret(n); |
| 92 | 107 | return a !== undefined && !handOut(db, { provider: a.provider, account: a.name }, runId, declared); |
| 93 | 108 | }); |
| 109 | const why = (n: string): string => { | |
| 110 | const a = accountOfSecret(n)!; | |
| 111 | return sellingAccount(db, { provider: a.provider, account: a.name }) | |
| 112 | ? "it is the account this forge deploys forges with, which no run is given" | |
| 113 | : "its vendor is not declared in cloud.json"; | |
| 114 | }; | |
| 94 | 115 | return { |
| 95 | 116 | ...asked, |
| 96 | 117 | names: asked.names.filter((n) => !barred.includes(n)), |
| 97 | refused: [...asked.refused, ...barred.map((n) => `${n}: its vendor is not declared in cloud.json`)], | |
| 118 | refused: [...asked.refused, ...barred.map((n) => `${n}: ${why(n)}`)], | |
| 98 | 119 | }; |
| 99 | 120 | } |
src/cloud/hetzner.ts +22 −6
| @@ -11,7 +11,7 @@ | ||
| 11 | 11 | */ |
| 12 | 12 | |
| 13 | 13 | import { dropThrowawayKey, makeThrowawayKey } from "./throwaway_key.ts"; |
| 14 | import { bootConfig as boot, ipv4, volumeName, type Booted, type Driver } from "./machine.ts"; | |
| 14 | import { bootConfig as boot, ipv4, numericId, volumeName, type Booted, type Driver, type Found } from "./machine.ts"; | |
| 15 | 15 | |
| 16 | 16 | const IMAGE = "ubuntu-24.04"; |
| 17 | 17 | |
| @@ -23,6 +23,10 @@ export const bootConfig = (p: Booted, volume: string): string => boot(p, dataDir | ||
| 23 | 23 | /** Hetzner's collection of project SSH keys. */ |
| 24 | 24 | const KEYS = "/ssh_keys"; |
| 25 | 25 | |
| 26 | /** What a list answers, as ids and names: a malformed entry is dropped, never guessed at. */ | |
| 27 | const foundIn = (list: unknown): Found[] => | |
| 28 | (Array.isArray(list) ? list : []).flatMap((x: any) => (typeof x?.id === "number" && typeof x.name === "string" ? [{ id: String(x.id), name: x.name }] : [])); | |
| 29 | ||
| 26 | 30 | /** The volume and the server are made at the row's location, the server of its type (`machine.ts`). */ |
| 27 | 31 | export const hetzner: Driver = { |
| 28 | 32 | api: "https://api.hetzner.cloud/v1", |
| @@ -30,13 +34,25 @@ export const hetzner: Driver = { | ||
| 30 | 34 | const v = await call("POST", "/volumes", { name: volumeName(p.name), location: p.datacenter, size: 10, format: "ext4", automount: false, labels: { "forge-pinned": "true", forge: p.name } }); |
| 31 | 35 | return String(v.volume?.id ?? ""); |
| 32 | 36 | }, |
| 37 | async findVolume(call, p) { | |
| 38 | const all: any[] = (await call("GET", `/volumes?name=${encodeURIComponent(volumeName(p.name))}`)).volumes ?? []; | |
| 39 | return foundIn(all.filter((v) => v?.location?.name === p.datacenter))[0]?.id ?? ""; | |
| 40 | }, | |
| 41 | async findMachine(call, p) { | |
| 42 | const all = (await call("GET", `/servers?name=${encodeURIComponent(`forge-${p.name}`)}`)).servers; | |
| 43 | return foundIn(all).find((s) => s.name === `forge-${p.name}`)?.id ?? ""; | |
| 44 | }, | |
| 45 | async listForges(call) { | |
| 46 | const q = `?label_selector=${encodeURIComponent("forge-pinned=true")}&per_page=50`; | |
| 47 | return { machines: foundIn((await call("GET", `/servers${q}`)).servers), volumes: foundIn((await call("GET", `/volumes${q}`)).volumes) }; | |
| 48 | }, | |
| 33 | 49 | async createMachine(call, p, volume) { |
| 34 | 50 | // A server made with no SSH key is sent a root password by email; see throwaway_key.ts. |
| 35 | 51 | const key = await makeThrowawayKey(call, KEYS, p.name); |
| 36 | 52 | try { |
| 37 | 53 | const s = await call("POST", "/servers", { |
| 38 | 54 | name: `forge-${p.name}`, server_type: p.size, location: p.datacenter, image: IMAGE, |
| 39 | volumes: [Number(volume)], automount: true, user_data: bootConfig(p, volume), ssh_keys: [Number(key)], | |
| 55 | volumes: [numericId(volume, "volume")], automount: true, user_data: bootConfig(p, volume), ssh_keys: [numericId(key, "throwaway key")], | |
| 40 | 56 | public_net: { enable_ipv4: true, enable_ipv6: true }, start_after_create: true, labels: { "forge-pinned": "true", forge: p.name }, |
| 41 | 57 | }); |
| 42 | 58 | return String(s.server?.id ?? ""); |
| @@ -45,17 +61,17 @@ export const hetzner: Driver = { | ||
| 45 | 61 | } |
| 46 | 62 | }, |
| 47 | 63 | async deleteMachine(call, remote) { |
| 48 | await call("DELETE", `/servers/${remote}`); | |
| 64 | await call("DELETE", `/servers/${numericId(remote, "machine")}`); | |
| 49 | 65 | }, |
| 50 | 66 | async deleteVolume(call, volume) { |
| 51 | await call("DELETE", `/volumes/${volume}`); | |
| 67 | await call("DELETE", `/volumes/${numericId(volume, "volume")}`); | |
| 52 | 68 | }, |
| 53 | 69 | async volumeFree(call, volume) { |
| 54 | const v = (await call("GET", `/volumes/${volume}`)).volume; | |
| 70 | const v = (await call("GET", `/volumes/${numericId(volume, "volume")}`)).volume; | |
| 55 | 71 | return v?.server === null || v?.server === undefined; |
| 56 | 72 | }, |
| 57 | 73 | async readMachine(call, remote) { |
| 58 | const s = (await call("GET", `/servers/${remote}`)).server; | |
| 74 | const s = (await call("GET", `/servers/${numericId(remote, "machine")}`)).server; | |
| 59 | 75 | return { status: String(s?.status ?? ""), address: ipv4(s?.public_net?.ipv4?.ip) }; |
| 60 | 76 | }, |
| 61 | 77 | }; |
src/cloud/machine.ts +92 −9
| @@ -23,7 +23,8 @@ import type { Fetch } from "./providers.ts"; | ||
| 23 | 23 | import { firstAdminSeed, readSeed } from "../core/first_admin.ts"; |
| 24 | 24 | import { BOOT_NAMES, portOf, validHost, validSource, type Pinned } from "../core/pinned.ts"; |
| 25 | 25 | import { OWN_FORGE_REPO } from "../spawn/own_forge.ts"; |
| 26 | import { BUN_HOME, CHECKOUT, hardenEarly, hardenFiles, hardenHead, hardenLate, mount, proxyStore, serviceUnit } from "./harden.ts"; | |
| 26 | import { BUN_INSTALLER, bunInstallScript } from "./bun_install.ts"; | |
| 27 | import { CHECKOUT, hardenEarly, hardenFiles, hardenHead, hardenLate, mount, proxyStore, serviceUnit } from "./harden.ts"; | |
| 27 | 28 | |
| 28 | 29 | /** |
| 29 | 30 | * The Bun the machine installs: it moves only when `.bun-version` does, in a pull, so the runtime |
| @@ -134,13 +135,16 @@ ${hardenHead()}write_files: | ||
| 134 | 135 | permissions: "0600" |
| 135 | 136 | content: ${JSON.stringify(env + "\n")} |
| 136 | 137 | ${proxyFiles(p, dataDir)} |
| 138 | - path: ${BUN_INSTALLER} | |
| 139 | permissions: "0755" | |
| 140 | content: ${JSON.stringify(bunInstallScript(BUN_VERSION))} | |
| 137 | 141 | - path: /etc/systemd/system/forge.service |
| 138 | 142 | content: | |
| 139 | 143 | ${serviceUnit(p.name, p.version, dataDir).replace(/^(?=.)/gm, " ")} |
| 140 | 144 | ${hardenFiles()} |
| 141 | 145 | runcmd: |
| 142 | 146 | ${hardenEarly()} |
| 143 | - curl -fsSL https://bun.sh/install | BUN_INSTALL=${BUN_HOME} bash -s "bun-v${BUN_VERSION}" | |
| 147 | - ${BUN_INSTALLER} | |
| 144 | 148 | - for try in 1 2 3 4 5; do rm -rf ${CHECKOUT} && git init -q ${CHECKOUT} && git -C ${CHECKOUT} fetch -q --depth 1 ${p.source} ${p.version} && break; sleep 15; done |
| 145 | 149 | - git -C ${CHECKOUT} checkout -q --detach FETCH_HEAD |
| 146 | 150 | ${hardenLate()} |
| @@ -150,6 +154,16 @@ ${proxyCommands(dataDir)} | ||
| 150 | 154 | `; |
| 151 | 155 | } |
| 152 | 156 | |
| 157 | /** A machine or volume at the provider that carries a forge's label: its id and its name. */ | |
| 158 | export interface Found { | |
| 159 | readonly id: string; | |
| 160 | readonly name: string; | |
| 161 | } | |
| 162 | export interface Labelled { | |
| 163 | readonly machines: Found[]; | |
| 164 | readonly volumes: Found[]; | |
| 165 | } | |
| 166 | ||
| 153 | 167 | /** One request to the cloud's fixed host; the driver's calls are made through it. */ |
| 154 | 168 | export type Call = (method: string, path: string, body?: unknown) => Promise<any>; |
| 155 | 169 | |
| @@ -169,6 +183,15 @@ export interface Driver { | ||
| 169 | 183 | createVolume(call: Call, p: Pinned): Promise<string>; |
| 170 | 184 | /** Make the machine with the volume attached; returns its id. */ |
| 171 | 185 | createMachine(call: Call, p: Pinned, volume: string): Promise<string>; |
| 186 | /** | |
| 187 | * The id of the machine already made for this forge (its name `forge-<name>` and its label), or | |
| 188 | * empty: asked before every create, so a create whose answer was lost is adopted, never repeated. | |
| 189 | */ | |
| 190 | findMachine(call: Call, p: Pinned): Promise<string>; | |
| 191 | /** The id of the data volume already made for this forge, in the row's datacenter, or empty. */ | |
| 192 | findVolume(call: Call, p: Pinned): Promise<string>; | |
| 193 | /** Every machine and volume at the provider that carries a forge's label, whoever made it. */ | |
| 194 | listForges(call: Call): Promise<Labelled>; | |
| 172 | 195 | deleteMachine(call: Call, remote: string): Promise<void>; |
| 173 | 196 | /** Delete the data volume: nothing of the forge's data is left once this answers. */ |
| 174 | 197 | deleteVolume(call: Call, volume: string): Promise<void>; |
| @@ -218,15 +241,38 @@ export async function provision( | ||
| 218 | 241 | const project = await projectOf(d, call, hooks.project); |
| 219 | 242 | let volume = hooks.have ?? ""; |
| 220 | 243 | if (volume === "") { |
| 221 | volume = await d.createVolume(call, p); | |
| 222 | if (volume === "") throw new Error(`${new URL(d.api).host} made no volume`); | |
| 244 | // One forge, one volume: a volume an earlier try made whose answer was lost is adopted. | |
| 245 | volume = await found(d.findVolume(call, p)); | |
| 246 | if (volume === "") volume = await d.createVolume(call, p); | |
| 247 | if (!VOLUME.test(volume)) throw new Error(`${new URL(d.api).host} made no volume`); | |
| 223 | 248 | hooks.onVolume(volume); |
| 224 | 249 | } |
| 225 | const remote = await d.createMachine(call, p, volume); | |
| 250 | const remote = await machineOf(d, call, p, volume); | |
| 226 | 251 | await file(d, call, project, remote, volume, hooks.onUnfiled); |
| 227 | 252 | return { remote, volume }; |
| 228 | 253 | } |
| 229 | 254 | |
| 255 | /** | |
| 256 | * An id the provider answered with, or empty: anything else is not an id this forge will put in a | |
| 257 | * path. | |
| 258 | */ | |
| 259 | const found = async (ask: Promise<string>): Promise<string> => { | |
| 260 | const id = await ask; | |
| 261 | return ID.test(id) || VOLUME.test(id) ? id : ""; | |
| 262 | }; | |
| 263 | ||
| 264 | /** | |
| 265 | * One forge, one machine: the machine already made for it is adopted, and one is created only when | |
| 266 | * the provider has none. An answer with no usable id is an error, and the machine it made is found | |
| 267 | * by name on the next try. | |
| 268 | */ | |
| 269 | async function machineOf(d: Driver, call: Call, p: Pinned, volume: string): Promise<string> { | |
| 270 | const have = await found(d.findMachine(call, p)); | |
| 271 | const remote = have !== "" ? have : await d.createMachine(call, p, volume); | |
| 272 | if (!ID.test(remote)) throw new Error(`${new URL(d.api).host} made no machine the forge can name`); | |
| 273 | return remote; | |
| 274 | } | |
| 275 | ||
| 230 | 276 | async function projectOf(d: Driver, call: Call, name: string | undefined): Promise<string> { |
| 231 | 277 | return name && d.projectId ? d.projectId(call, name) : ""; |
| 232 | 278 | } |
| @@ -280,7 +326,7 @@ export async function replace( | ||
| 280 | 326 | hooks.onDeleted(); |
| 281 | 327 | await untilFree(d, call, p.volume); |
| 282 | 328 | } |
| 283 | const remote = await d.createMachine(call, p, p.volume); | |
| 329 | const remote = await machineOf(d, call, p, p.volume); | |
| 284 | 330 | await file(d, call, project, remote, p.volume, hooks.onUnfiled); |
| 285 | 331 | return { remote }; |
| 286 | 332 | } |
| @@ -313,6 +359,15 @@ export async function orderable(d: Driver, p: Pinned): Promise<void> { | ||
| 313 | 359 | /** What a volume's id may look like on the way into a path: DigitalOcean's are UUIDs, Hetzner's numbers. */ |
| 314 | 360 | const VOLUME = /^[A-Za-z0-9-]{1,64}$/; |
| 315 | 361 | |
| 362 | /** | |
| 363 | * A number a provider takes in a body or a path (Hetzner's ids), checked as digits, never converted | |
| 364 | * blind: `Number("")` is 0 and `Number("1e3")` is 1000. | |
| 365 | */ | |
| 366 | export function numericId(v: string, what: string): number { | |
| 367 | if (!/^[1-9]\d{0,15}$/.test(v)) throw new Error(`this forge's ${what} has no numeric id`); | |
| 368 | return Number(v); | |
| 369 | } | |
| 370 | ||
| 316 | 371 | /** A delete that finds the thing already gone is a delete that is done. */ |
| 317 | 372 | async function gone(go: () => Promise<void>): Promise<void> { |
| 318 | 373 | try { |
| @@ -343,12 +398,40 @@ export async function retire( | ||
| 343 | 398 | hooks.onVolumeGone(); |
| 344 | 399 | } |
| 345 | 400 | |
| 346 | const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)$/; | |
| 347 | /** Only a well-formed IPv4 address is ever kept. */ | |
| 348 | export const ipv4 = (v: unknown): string => (typeof v === "string" && IPV4.test(v) ? v : ""); | |
| 401 | const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/; | |
| 402 | ||
| 403 | /** | |
| 404 | * Whether a well-formed IPv4 is outside every range that is not the public internet: "this" | |
| 405 | * network, private (10/8, 172.16/12, 192.168/16), carrier-grade (100.64/10), loopback, link-local | |
| 406 | * (169.254/16, where metadata endpoints live), benchmarking (198.18/15), multicast and reserved | |
| 407 | * (224/3). The forge probes the address from here, so it must never name one of ours. | |
| 408 | */ | |
| 409 | function isPublic(a: string): boolean { | |
| 410 | const [o1 = 0, o2 = 0] = a.split(".").map(Number); | |
| 411 | if (o1 === 0 || o1 === 10 || o1 === 127 || o1 >= 224) return false; | |
| 412 | if (o1 === 100 && o2 >= 64 && o2 <= 127) return false; | |
| 413 | if (o1 === 169 && o2 === 254) return false; | |
| 414 | if (o1 === 172 && o2 >= 16 && o2 <= 31) return false; | |
| 415 | if (o1 === 192 && o2 === 168) return false; | |
| 416 | if (o1 === 198 && (o2 === 18 || o2 === 19)) return false; | |
| 417 | return true; | |
| 418 | } | |
| 419 | ||
| 420 | /** Only a well-formed, public IPv4 address is ever kept. */ | |
| 421 | export const ipv4 = (v: unknown): string => (typeof v === "string" && IPV4.test(v) && isPublic(v) ? v : ""); | |
| 349 | 422 | |
| 350 | 423 | /** Read the machine back: its status and public IPv4 (empty while none is assigned). */ |
| 351 | 424 | export async function read(d: Driver, f: Fetch, token: string, remote: string): Promise<{ status: string; address: string }> { |
| 352 | 425 | if (!ID.test(remote)) throw new Error("this forge has no machine to read"); |
| 353 | 426 | return d.readMachine(caller(d, f, token), remote); |
| 354 | 427 | } |
| 428 | ||
| 429 | /** | |
| 430 | * What the provider holds under a forge's label that no row owns: the machines and volumes a lost | |
| 431 | * create, a deleted row or a hand at the console left behind, each one billing. Asked of the | |
| 432 | * provider only; nothing is changed. `owned` is every id the rows record. | |
| 433 | */ | |
| 434 | export async function strays(d: Driver, f: Fetch, token: string, owned: { machines: ReadonlySet<string>; volumes: ReadonlySet<string> }): Promise<Labelled> { | |
| 435 | const all = await d.listForges(caller(d, f, token)); | |
| 436 | return { machines: all.machines.filter((m) => !owned.machines.has(m.id)), volumes: all.volumes.filter((v) => !owned.volumes.has(v.id)) }; | |
| 437 | } |
src/cloud/sale_source.ts added +38
| @@ -0,0 +1,38 @@ | ||
| 1 | /** | |
| 2 | * What a forge sold to someone may be booted from (#16219). A machine made for a buyer runs | |
| 3 | * whatever its boot fetches, as root's neighbour, for as long as it lives: so a sale takes only a | |
| 4 | * commit (a 40-hex id, which no host can move; a tag can be moved by whoever holds the source) and | |
| 5 | * only from the hosts the owner listed in `FORGE_SALE_SOURCES` (comma-separated DNS names, none | |
| 6 | * listed means no sale deploys). `FORGE_SALE_SOURCE` is the one address a sold forge is booted | |
| 7 | * from and follows for its updates. Neither may be on the selling forge's own host: the buyer's | |
| 8 | * boot, and every later update, must not wait for the seller to be up, nor can a machine with no | |
| 9 | * credential read a private repository here. An admin's own deploy is not held to this. | |
| 10 | */ | |
| 11 | ||
| 12 | import { validHost, validSource } from "../core/pinned.ts"; | |
| 13 | import { err, ok, type Result } from "../kernel/result.ts"; | |
| 14 | ||
| 15 | /** | |
| 16 | * The hosts the owner allows a sale's source to be on; names that are not DNS names are dropped. | |
| 17 | */ | |
| 18 | export function saleHosts(env: Record<string, string | undefined> = process.env): string[] { | |
| 19 | return (env["FORGE_SALE_SOURCES"] ?? "").split(",").map((h) => h.trim().toLowerCase()).filter(validHost); | |
| 20 | } | |
| 21 | ||
| 22 | /** The address a sold forge is booted from, or empty when the owner set none. */ | |
| 23 | export function saleSource(env: Record<string, string | undefined> = process.env): string { | |
| 24 | return (env["FORGE_SALE_SOURCE"] ?? "").trim(); | |
| 25 | } | |
| 26 | ||
| 27 | /** Whether `code` may be sold: a commit, from a listed host, which is not this forge's own. */ | |
| 28 | export function saleCode<T extends { source: string; version: string }>(code: T, ownUrl: string | undefined, env: Record<string, string | undefined> = process.env): Result<T, string> { | |
| 29 | const hosts = saleHosts(env); | |
| 30 | if (hosts.length === 0) return err("The owner has listed no source hosts for sold forges (FORGE_SALE_SOURCES), so none can be deployed."); | |
| 31 | if (!/^[0-9a-f]{40}$/.test(code.version)) return err("A sold forge runs a full 40-character commit id: a tag can be moved by its source, a commit cannot."); | |
| 32 | if (!validSource(code.source)) return err("The source is an https git address."); | |
| 33 | const host = new URL(code.source).hostname.toLowerCase(); | |
| 34 | if (!hosts.includes(host)) return err(`${host} is not one of the source hosts the owner listed for sold forges (${hosts.join(", ")}).`); | |
| 35 | const own = URL.canParse(ownUrl ?? "") ? new URL(ownUrl!).hostname.toLowerCase() : ""; | |
| 36 | if (host === own) return err("A sold forge cannot be booted from the selling forge: its boot and its updates must not wait for this forge. Name a source elsewhere (FORGE_SALE_SOURCE)."); | |
| 37 | return ok(code); | |
| 38 | } |
src/http/mcp/tools/pinned_forge.ts +9 −5
| @@ -1,4 +1,4 @@ | ||
| 1 | import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, updatePinned } from "../../../actions/pinned.ts"; | |
| 1 | import { DOMAIN_WORDS, changeBaseDomain, checkPinned, checkWords, claimPinned, claimWords, deployPinned, fileForge, pinnedForges, readBaseDomain, retirePinned, retireWords, rollbackPinned, strayCloud, strayWords, updatePinned } from "../../../actions/pinned.ts"; | |
| 2 | 2 | import { TARGETS } from "../../../cloud/targets.ts"; |
| 3 | 3 | import { scopeAllows } from "../../../core/tokens.ts"; |
| 4 | 4 | import { good, bad, type Tool, str } from "../shared.ts"; |
| @@ -6,7 +6,7 @@ import { good, bad, type Tool, str } from "../shared.ts"; | ||
| 6 | 6 | export const tool: Tool = { |
| 7 | 7 | name: "pinned_forge", |
| 8 | 8 | listedTo: "admin", |
| 9 | doc: "`{ verb, name?, host?, domain?, withData?, despiteClaim?, target?, account?, app?, source?, version?, place?, config? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link while unclaimed. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set the domain. `check`: `waiting` or `url`, `healthy`, `claim`. `retire`: delete the machine, keep the data (`withData` deletes it). `file`: put its machine and volume in its cloud account's project (a forge made before the project was set). `list`: all, with changes. A forge admin with an admin-scope token", | |
| 9 | doc: "`{ verb, name?, host?, domain?, withData?, despiteClaim?, target?, account?, app?, source?, version?, place?, config? }`: a forge on the owner's cloud. `deploy`: `app` from `source` at `version` on a writable `account`, at `place` (default: the small plan's), on `host` (default `<name>.<domain>`; Cloudflare writes the record); answers once with `claim.link` and `dns`. `claim`: a fresh link while unclaimed. `update`: change `version` or `config`. `rollback`: back one. `domain`: read or set the domain. `check`: `waiting` or `url`, `healthy`, `claim`. `retire`: delete the machine, keep the data (`withData` deletes it). `strays` (`target`, `account`): the machines and volumes at the provider that carry a forge's label and belong to no row. `file`: put its machine and volume in its cloud account's project (a forge made before the project was set). `list`: all, with changes. A forge admin with an admin-scope token", | |
| 10 | 10 | description: "Pinned forges on your cloud: list, deploy, claim, update, rollback, check, retire (admin).", |
| 11 | 11 | tier: "delete", |
| 12 | 12 | deletes: (args) => args["verb"] === "retire" && args["withData"] === true, |
| @@ -14,7 +14,7 @@ export const tool: Tool = { | ||
| 14 | 14 | inputSchema: { |
| 15 | 15 | type: "object", |
| 16 | 16 | properties: { |
| 17 | verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain", "retire", "file"] }, | |
| 17 | verb: { type: "string", enum: ["list", "deploy", "claim", "update", "rollback", "check", "domain", "retire", "file", "strays"] }, | |
| 18 | 18 | withData: { type: "boolean", description: "Retire: delete the data too; no undo." }, |
| 19 | 19 | despiteClaim: { type: "boolean", description: "Retire a forge its buyer claimed." }, |
| 20 | 20 | domain: { type: "string", maxLength: 253, description: "Domain for deployed forges; empty clears." }, |
| @@ -34,7 +34,7 @@ export const tool: Tool = { | ||
| 34 | 34 | writes: true, |
| 35 | 35 | // Its listing is a read: the forge's agent is never held on it; a read-only token is still |
| 36 | 36 | // refused. |
| 37 | heldNotWhen: (args) => args["verb"] === "list", | |
| 37 | heldNotWhen: (args) => args["verb"] === "list" || args["verb"] === "strays", | |
| 38 | 38 | async run(ctx, user, args) { |
| 39 | 39 | if (!user.isAdmin) return bad("not_found", "no such tool here"); |
| 40 | 40 | const verb = str(args["verb"]); |
| @@ -70,6 +70,10 @@ export const tool: Tool = { | ||
| 70 | 70 | const done = await retirePinned(ctx.app, user, name, { withData: args["withData"] === true, despiteClaim: args["despiteClaim"] === true }); |
| 71 | 71 | return done.ok ? good({ says: retireWords(done.value), forge: done.value }) : bad("refused", done.error); |
| 72 | 72 | } |
| 73 | if (verb === "strays") { | |
| 74 | const seen = await strayCloud(ctx.app, user, str(args["target"]), str(args["account"])); | |
| 75 | return seen.ok ? good({ says: strayWords(seen.value), ...seen.value }) : bad("refused", seen.error); | |
| 76 | } | |
| 73 | 77 | if (verb === "file") { |
| 74 | 78 | const filed = await fileForge(ctx.app, user, name); |
| 75 | 79 | return filed.ok ? good({ says: filed.value }) : bad("refused", filed.error); |
| @@ -87,7 +91,7 @@ export const tool: Tool = { | ||
| 87 | 91 | : verb === "rollback" |
| 88 | 92 | ? await rollbackPinned(ctx.app, user, name) |
| 89 | 93 | : undefined; |
| 90 | if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check, retire, file or domain"); | |
| 94 | if (done === undefined) return bad("bad_verb", "verb is list, deploy, claim, update, rollback, check, retire, file, strays or domain"); | |
| 91 | 95 | if (!done.ok) return bad("refused", done.error); |
| 92 | 96 | return good({ says: `${verb} ${name}: now ${done.value.version}, ${done.value.state}${done.value.url ? ` at ${done.value.url}` : ""}.`, forge: done.value }); |
| 93 | 97 | }, |
src/spawn/cloud_placement.ts +6 −1
| @@ -15,7 +15,9 @@ import { | ||
| 15 | 15 | deployRoom, |
| 16 | 16 | ownCode, |
| 17 | 17 | retireForOrder, |
| 18 | saleCodeOf, | |
| 18 | 19 | } from "../actions/pinned.ts"; |
| 20 | import { saleSource } from "../cloud/sale_source.ts"; | |
| 19 | 21 | import { isPlan, type PlanName } from "../cloud/places.ts"; |
| 20 | 22 | import { getRepo } from "../core/repos.ts"; |
| 21 | 23 | import { err, ok, type Result } from "../kernel/result.ts"; |
| @@ -38,7 +40,8 @@ export const catalogPlan = (size: string): PlanName => | ||
| 38 | 40 | export function ownSource( |
| 39 | 41 | app: App, |
| 40 | 42 | ): Result<{ app: string; source: string; version: string }, string> { |
| 41 | const code = ownCode(app, {}); | |
| 43 | const named = saleSource(); | |
| 44 | const code = ownCode(app, named === "" ? {} : { source: named }); | |
| 42 | 45 | if (!code.ok) return code; |
| 43 | 46 | const [owner = "", name = ""] = (forgeSource(app.db, app.config.forgeRepo) ?? "").split("/"); |
| 44 | 47 | const repo = getRepo(app.db, owner, name); |
| @@ -63,6 +66,8 @@ export function cloudPlacement( | ||
| 63 | 66 | room() { |
| 64 | 67 | const own = ownSource(app); |
| 65 | 68 | if (!own.ok) return refused(own.error); |
| 69 | const sold = saleCodeOf(app, own.value); | |
| 70 | if (!sold.ok) return refused(sold.error); | |
| 66 | 71 | const no = deployRoom(app, at.provider, at.account, o.plan, o.place ?? "", o.dearer === true, o.orderId); |
| 67 | 72 | return no === undefined ? undefined : { reason: "quota", message: no }; |
| 68 | 73 | }, |
test/helpers/recorded-cloud.ts +69 −23
| @@ -9,8 +9,12 @@ | ||
| 9 | 9 | export type Provider = "digitalocean" | "hetzner"; |
| 10 | 10 | export type Kind = "volume" | "key" | "machine"; |
| 11 | 11 | export type Call = { method: string; host: string; path: string; kind: Kind | undefined; auth: string | null; body: any }; |
| 12 | /** A refusal: the cloud answers `status`, or the connection is cut ("throw"). */ | |
| 13 | export type Fault = { method?: string; kind?: Kind; read?: boolean; status?: number | "throw"; times?: number }; | |
| 12 | /** | |
| 13 | * A refusal: the cloud answers `status`, or the connection is cut ("throw"). With `lost` the cloud | |
| 14 | * does the work and then the answer never arrives: a create that timed out after it was made. A | |
| 15 | * fault on a GET touches the read of one thing, never a lookup of a collection, unless `lookup`. | |
| 16 | */ | |
| 17 | export type Fault = { method?: string; kind?: Kind; read?: boolean; status?: number | "throw"; times?: number; lost?: boolean; lookup?: boolean }; | |
| 14 | 18 | |
| 15 | 19 | const KEY = 4242; |
| 16 | 20 | const SHAPES = { |
| @@ -27,11 +31,12 @@ const SHAPES = { | ||
| 27 | 31 | /** The calls a driver makes for one operation, in order, as `METHOD path`. */ |
| 28 | 32 | export const sequence = { |
| 29 | 33 | /** |
| 30 | * A deploy: the volume, a throwaway key around the machine, then the machine's address read back. | |
| 34 | * A deploy: look for the volume and make it, look for the machine, a throwaway key around it, | |
| 35 | * then the machine's address read back. | |
| 31 | 36 | */ |
| 32 | 37 | create(p: Provider, machine: number | string): string[] { |
| 33 | 38 | const s = SHAPES[p]; |
| 34 | return [`POST ${s.volumes}`, `POST ${s.keys}`, `POST ${s.machines}`, `DELETE ${s.keys}/${KEY}`, `GET ${s.machines}/${machine}`]; | |
| 39 | return [`GET ${s.volumes}`, `POST ${s.volumes}`, `GET ${s.machines}`, `POST ${s.keys}`, `POST ${s.machines}`, `DELETE ${s.keys}/${KEY}`, `GET ${s.machines}/${machine}`]; | |
| 35 | 40 | }, |
| 36 | 41 | /** |
| 37 | 42 | * An Update or a new claim link: read the old machine, delete it, wait for the volume, make the |
| @@ -43,6 +48,7 @@ export const sequence = { | ||
| 43 | 48 | `GET ${s.machines}/${old}`, |
| 44 | 49 | `DELETE ${s.machines}/${old}`, |
| 45 | 50 | `GET ${s.volumes}/${volume}`, |
| 51 | `GET ${s.machines}`, | |
| 46 | 52 | `POST ${s.keys}`, |
| 47 | 53 | `POST ${s.machines}`, |
| 48 | 54 | `DELETE ${s.keys}/${KEY}`, |
| @@ -59,6 +65,8 @@ export function recordCloud(opts: { firstMachine?: number; address?: string } = | ||
| 59 | 65 | /** The body of every machine asked for, newest last. */ |
| 60 | 66 | const machines: any[] = []; |
| 61 | 67 | const faults: Required<Fault>[] = []; |
| 68 | /** What the cloud holds, as it would list it: made by a POST, gone by a DELETE. */ | |
| 69 | const holds = { machines: [] as { id: number; body: any }[], volumes: [] as { id: number | string; body: any }[] }; | |
| 62 | 70 | let machine = (opts.firstMachine ?? 501) - 1; |
| 63 | 71 | const address = opts.address ?? "203.0.113.9"; |
| 64 | 72 | const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status }); |
| @@ -78,38 +86,76 @@ export function recordCloud(opts: { firstMachine?: number; address?: string } = | ||
| 78 | 86 | : undefined; |
| 79 | 87 | const body = init?.body ? JSON.parse(String(init.body)) : undefined; |
| 80 | 88 | calls.push({ method, host: u.host, path: u.pathname, kind, auth: new Headers(init?.headers).get("authorization"), body }); |
| 89 | const isCollection = u.pathname === s.volumes || u.pathname === s.machines; | |
| 81 | 90 | const fault = faults.find( |
| 82 | (f) => f.times > 0 && (!f.method || f.method === method) && (!f.kind || f.kind === kind) && (!f.read || method === "GET"), | |
| 91 | (f) => f.times > 0 && (!f.method || f.method === method) && (!f.kind || f.kind === kind) && (!f.read || method === "GET") && (f.lookup || method !== "GET" || !isCollection), | |
| 83 | 92 | ); |
| 93 | if (fault?.lost) { | |
| 94 | fault.times--; | |
| 95 | await answer(); | |
| 96 | throw new Error("timed out after the cloud did the work"); | |
| 97 | } | |
| 84 | 98 | if (fault) { |
| 85 | 99 | fault.times--; |
| 86 | 100 | if (fault.status === "throw") throw new Error("socket closed"); |
| 87 | 101 | return json({}, fault.status); |
| 88 | 102 | } |
| 89 | const created = method === "POST"; | |
| 90 | if (kind === "key") return created ? json({ ssh_key: { id: KEY } }, 201) : new Response(null, { status: 204 }); | |
| 91 | if (kind === "volume") { | |
| 92 | if (created) return json({ volume: { id: s.volume } }, 201); | |
| 93 | if (method === "GET") return json({ volume: provider === "hetzner" ? { id: s.volume, server: null } : { id: s.volume } }); | |
| 103 | return answer(); | |
| 104 | ||
| 105 | async function answer(): Promise<Response> { | |
| 106 | const created = method === "POST"; | |
| 107 | const last = u.pathname.split("/").at(-1)!; | |
| 108 | const collection = isCollection; | |
| 109 | const hz = provider === "hetzner"; | |
| 110 | if (kind === "key") return created ? json({ ssh_key: { id: KEY } }, 201) : new Response(null, { status: 204 }); | |
| 111 | if (kind === "volume") { | |
| 112 | if (created) { | |
| 113 | holds.volumes.push({ id: s.volume, body }); | |
| 114 | return json({ volume: { id: s.volume } }, 201); | |
| 115 | } | |
| 116 | if (method === "GET" && collection) { | |
| 117 | const name = u.searchParams.get("name"); | |
| 118 | const listed = holds.volumes | |
| 119 | .filter((v) => name === null || v.body.name === name) | |
| 120 | .map((v) => (hz ? { id: v.id, name: v.body.name, location: { name: v.body.location }, labels: v.body.labels } : { id: v.id, name: v.body.name, region: { slug: v.body.region }, tags: v.body.tags })); | |
| 121 | return json({ volumes: listed }); | |
| 122 | } | |
| 123 | if (method === "GET") return json({ volume: hz ? { id: s.volume, server: null } : { id: s.volume } }); | |
| 124 | if (method === "DELETE") holds.volumes = holds.volumes.filter((v) => String(v.id) !== last); | |
| 125 | } | |
| 126 | if (method === "DELETE") { | |
| 127 | if (kind === "machine") holds.machines = holds.machines.filter((m) => String(m.id) !== last); | |
| 128 | return hz ? json({ action: {} }) : new Response(null, { status: 204 }); | |
| 129 | } | |
| 130 | if (kind === "machine") { | |
| 131 | if (method === "GET" && collection) { | |
| 132 | const name = u.searchParams.get("name"); | |
| 133 | const tag = u.searchParams.get("tag_name"); | |
| 134 | const listed = holds.machines | |
| 135 | .filter((m) => (name === null || m.body.name === name) && (tag === null || (m.body.tags ?? []).includes(tag))) | |
| 136 | .map((m) => ({ id: m.id, name: m.body.name, tags: m.body.tags, labels: m.body.labels })); | |
| 137 | return json(hz ? { servers: listed } : { droplets: listed }); | |
| 138 | } | |
| 139 | if (created) machines.push(body); | |
| 140 | const id = created ? ++machine : Number(last); | |
| 141 | if (created) holds.machines.push({ id, body }); | |
| 142 | if (hz) | |
| 143 | return json( | |
| 144 | created ? { server: { id } } : { server: { status: "running", public_net: { ipv4: { ip: address } } } }, | |
| 145 | created ? 201 : 200, | |
| 146 | ); | |
| 147 | return json({ droplet: { id, status: "active", networks: { v4: [{ type: "public", ip_address: address }] } } }, created ? 202 : 200); | |
| 148 | } | |
| 149 | return json({}, 404); | |
| 94 | 150 | } |
| 95 | if (method === "DELETE") return provider === "hetzner" ? json({ action: {} }) : new Response(null, { status: 204 }); | |
| 96 | if (kind === "machine") { | |
| 97 | if (created) machines.push(body); | |
| 98 | const id = created ? ++machine : Number(u.pathname.split("/").at(-1)); | |
| 99 | if (provider === "hetzner") | |
| 100 | return json( | |
| 101 | created ? { server: { id } } : { server: { status: "running", public_net: { ipv4: { ip: address } } } }, | |
| 102 | created ? 201 : 200, | |
| 103 | ); | |
| 104 | return json({ droplet: { id, status: "active", networks: { v4: [{ type: "public", ip_address: address }] } } }, created ? 202 : 200); | |
| 105 | } | |
| 106 | return json({}, 404); | |
| 107 | 151 | }; |
| 108 | 152 | |
| 109 | 153 | return { |
| 110 | 154 | fetch, |
| 111 | 155 | calls, |
| 112 | 156 | machines, |
| 157 | /** What the cloud holds now: machines and volumes made and not deleted. */ | |
| 158 | holds, | |
| 113 | 159 | /** The id of the last machine made. */ |
| 114 | 160 | get machine() { |
| 115 | 161 | return machine; |
| @@ -120,7 +166,7 @@ export function recordCloud(opts: { firstMachine?: number; address?: string } = | ||
| 120 | 166 | clear: (): void => void (calls.length = 0), |
| 121 | 167 | /** The cloud refuses the next `times` calls that match (once, by default). */ |
| 122 | 168 | fail(f: Fault): void { |
| 123 | faults.push({ method: "", kind: undefined as never, read: false, status: 500, times: 1, ...f } as Required<Fault>); | |
| 169 | faults.push({ method: "", kind: undefined as never, read: false, status: 500, times: 1, lost: false, lookup: false, ...f } as Required<Fault>); | |
| 124 | 170 | }, |
| 125 | 171 | /** Stop refusing. */ |
| 126 | 172 | mend: (): void => void (faults.length = 0), |
test/one-door.test.ts +5
| @@ -110,6 +110,9 @@ describe("one door for making a forge", () => { | ||
| 110 | 110 | |
| 111 | 111 | beforeAll(async () => { |
| 112 | 112 | process.env["FORGE_COMMIT"] = COMMIT; |
| 113 | // A sold forge boots from a listed host (cloud/sale_source.ts), never from this forge's own. | |
| 114 | process.env["FORGE_SALE_SOURCES"] = "mirror.example.test"; | |
| 115 | process.env["FORGE_SALE_SOURCE"] = "https://mirror.example.test/alice/forge.git"; | |
| 113 | 116 | dataDir = await mkdtemp(join(tmpdir(), "forge-one-door-")); |
| 114 | 117 | app = createApp({ |
| 115 | 118 | dataDir, |
| @@ -211,6 +214,8 @@ describe("one door for making a forge", () => { | ||
| 211 | 214 | }, 30_000); |
| 212 | 215 | |
| 213 | 216 | afterAll(async () => { |
| 217 | delete process.env["FORGE_SALE_SOURCES"]; | |
| 218 | delete process.env["FORGE_SALE_SOURCE"]; | |
| 214 | 219 | if (before === undefined) delete process.env["FORGE_COMMIT"]; |
| 215 | 220 | else process.env["FORGE_COMMIT"] = before; |
| 216 | 221 | closeHostedChildren(app); |
test/order-cloud.test.ts +6 −1
| @@ -126,6 +126,9 @@ describe("a paid order on a cloud account", () => { | ||
| 126 | 126 | |
| 127 | 127 | beforeAll(async () => { |
| 128 | 128 | process.env["FORGE_COMMIT"] = COMMIT; |
| 129 | // A sold forge boots from a listed host (cloud/sale_source.ts), never from this forge's own. | |
| 130 | process.env["FORGE_SALE_SOURCES"] = "mirror.example.test"; | |
| 131 | process.env["FORGE_SALE_SOURCE"] = "https://mirror.example.test/alice/forge.git"; | |
| 129 | 132 | dataDir = await mkdtemp(join(tmpdir(), "forge-order-cloud-")); |
| 130 | 133 | app = await open(dataDir); |
| 131 | 134 | await seedPlaces(app.db); |
| @@ -195,6 +198,8 @@ describe("a paid order on a cloud account", () => { | ||
| 195 | 198 | }, 30_000); |
| 196 | 199 | |
| 197 | 200 | afterAll(async () => { |
| 201 | delete process.env["FORGE_SALE_SOURCES"]; | |
| 202 | delete process.env["FORGE_SALE_SOURCE"]; | |
| 198 | 203 | if (before === undefined) delete process.env["FORGE_COMMIT"]; |
| 199 | 204 | else process.env["FORGE_COMMIT"] = before; |
| 200 | 205 | closeHostedChildren(app); |
| @@ -290,7 +295,7 @@ describe("a paid order on a cloud account", () => { | ||
| 290 | 295 | target: "digitalocean", |
| 291 | 296 | account: "main", |
| 292 | 297 | app: "alice/forge", |
| 293 | source: "https://forge.test/alice/forge.git", | |
| 298 | source: "https://mirror.example.test/alice/forge.git", | |
| 294 | 299 | version: COMMIT, |
| 295 | 300 | size: "s-1vcpu-2gb", |
| 296 | 301 | datacenter: "nyc3", |
test/pinned-ceiling.test.ts +4 −4
| @@ -342,13 +342,13 @@ describe("cloud account ceiling", () => { | ||
| 342 | 342 | if (/^import\b[^\n]*$/.test(text.slice(text.lastIndexOf("\n", m.index) + 1, m.index))) continue; |
| 343 | 343 | uses++; |
| 344 | 344 | const before = text.slice(Math.max(0, m.index - 80), m.index); |
| 345 | if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire)\($/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`); | |
| 345 | if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire|strays)\($/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`); | |
| 346 | 346 | } |
| 347 | 347 | } |
| 348 | 348 | expect(bare).toEqual([]); |
| 349 | // Deploy, update or rollback (asked, then made), a new claim link, the read and the retire: the | |
| 350 | // and filing in a project (#16340): the seven there are. | |
| 351 | expect(uses).toBe(7); | |
| 349 | // Deploy, update or rollback (asked, then made), a new claim link, the read, the retire and the | |
| 350 | // strays: the and filing in a project (#16340): the seven there are. | |
| 351 | expect(uses).toBe(8); | |
| 352 | 352 | }); |
| 353 | 353 | }); |
| 354 | 354 |
test/pinned-detach.test.ts +1
| @@ -10,6 +10,7 @@ function cloud(heldFor: number) { | ||
| 10 | 10 | const d: Driver = { |
| 11 | 11 | api: "https://api.example.test", |
| 12 | 12 | async createVolume() { return "vol"; }, |
| 13 | async findMachine() { return ""; }, | |
| 13 | 14 | async createMachine() { seen.push("create"); return "2"; }, |
| 14 | 15 | async deleteMachine() { seen.push("delete"); }, |
| 15 | 16 | async deleteVolume() {}, |
test/pinned-forge-recovery.test.ts +8 −3
| @@ -3,6 +3,7 @@ | ||
| 3 | 3 | * after the delete, a failed first deploy, and a volume made before the droplet |
| 4 | 4 | * all leave a row a retry finishes. The terminal door reaches the same actions. |
| 5 | 5 | */ |
| 6 | import { BUN_INTEGRITY } from "../src/cloud/bun_install.ts"; | |
| 6 | 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; |
| 7 | 8 | import { mkdtemp, rm } from "node:fs/promises"; |
| 8 | 9 | import { tmpdir } from "node:os"; |
| @@ -81,7 +82,7 @@ describe("pinned forge recovery", () => { | ||
| 81 | 82 | calls.length = 0; |
| 82 | 83 | const again = await deployPinned(app, admin(), input()); |
| 83 | 84 | expect(again.ok).toBe(true); |
| 84 | expect(calls).toEqual(["POST /v2/account/keys", "POST /v2/droplets", "DELETE /v2/account/keys/4242", "GET /v2/droplets/2002"]); | |
| 85 | expect(calls).toEqual(["GET /v2/droplets", "POST /v2/account/keys", "POST /v2/droplets", "DELETE /v2/account/keys/4242", "GET /v2/droplets/2003"]); | |
| 85 | 86 | expect(getPinned(app.db, "acme")).toMatchObject({ state: "running", volume: "vol-9" }); |
| 86 | 87 | // A running forge still owns its name. |
| 87 | 88 | expect(await deployPinned(app, admin(), input())).toMatchObject({ ok: false, error: "A pinned forge has that name already." }); |
| @@ -95,7 +96,7 @@ describe("pinned forge recovery", () => { | ||
| 95 | 96 | // The old droplet is not deleted a second time. |
| 96 | 97 | const back = await rollbackPinned(app, admin(), "acme"); |
| 97 | 98 | expect(back.ok).toBe(true); |
| 98 | expect(calls).toEqual(["POST /v2/account/keys", "POST /v2/droplets", "DELETE /v2/account/keys/4242"]); | |
| 99 | expect(calls).toEqual(["GET /v2/droplets", "POST /v2/account/keys", "POST /v2/droplets", "DELETE /v2/account/keys/4242"]); | |
| 99 | 100 | expect(getPinned(app.db, "acme")).toMatchObject({ state: "running", version: V1 }); |
| 100 | 101 | }); |
| 101 | 102 | |
| @@ -114,7 +115,11 @@ describe("pinned forge recovery", () => { | ||
| 114 | 115 | |
| 115 | 116 | test("the boot script installs the Bun version it names, not whatever is latest", () => { |
| 116 | 117 | const script = bootConfig({ name: "acme", source: SOURCE, version: V1, config: {}, host: "acme.forge.test", claimHash: "", claimExpires: "" }); |
| 117 | expect(script).toContain(`bash -s "bun-v${BUN_VERSION}"`); | |
| 118 | // The version is named in the download and checked against a pinned checksum before it is | |
| 119 | // installed. | |
| 120 | expect(script).toContain(`/-/$1-${BUN_VERSION}.tgz`); | |
| 121 | expect(script).toContain(BUN_INTEGRITY[BUN_VERSION]!.x64); | |
| 122 | expect(script).not.toContain("bun.sh/install"); | |
| 118 | 123 | expect(BUN_VERSION).toMatch(/^\d+\.\d+\.\d+$/); |
| 119 | 124 | }); |
| 120 | 125 |
test/pinned-forge.test.ts +3 −3
| @@ -78,7 +78,7 @@ describe("pinned forge", () => { | ||
| 78 | 78 | expect(r.ok).toBe(true); |
| 79 | 79 | expect(cloud.seen()).toEqual(sequence.create("digitalocean", 1001)); |
| 80 | 80 | expect(calls.every((c) => c.auth === `Bearer ${TOKEN}`)).toBe(true); |
| 81 | const droplet = calls[2]!.body; | |
| 81 | const droplet = calls[4]!.body; | |
| 82 | 82 | expect(droplet.volumes).toEqual(["vol-1"]); |
| 83 | 83 | expect(JSON.stringify(calls.map((c) => c.body))).not.toContain(TOKEN); |
| 84 | 84 | expect(droplet.user_data).toContain(`--depth 1 ${SOURCE} ${V1}`); |
| @@ -128,8 +128,8 @@ describe("pinned forge", () => { | ||
| 128 | 128 | expect(r.ok).toBe(true); |
| 129 | 129 | // The machine's address is read first, to ask the forge there whether it was claimed. |
| 130 | 130 | expect(cloud.seen()).toEqual(sequence.replace("digitalocean", before)); |
| 131 | expect(calls[4]!.body.volumes).toEqual(["vol-1"]); | |
| 132 | expect(calls[4]!.body.user_data).toContain(`--depth 1 ${SOURCE} ${V2}`); | |
| 131 | expect(calls[5]!.body.volumes).toEqual(["vol-1"]); | |
| 132 | expect(calls[5]!.body.user_data).toContain(`--depth 1 ${SOURCE} ${V2}`); | |
| 133 | 133 | const [latest] = changesOf(app.db, getPinned(app.db, "acme")!.id); |
| 134 | 134 | expect(latest).toMatchObject({ kind: "update", fromVersion: V1, toVersion: V2, by: admin().id }); |
| 135 | 135 | expect(Date.parse(latest!.at)).toBeGreaterThan(0); |
test/pinned-harden.test.ts +6 −4
| @@ -69,9 +69,11 @@ describe.each(Object.entries(boots))("the %s machine", (_name, boot) => { | ||
| 69 | 69 | c.endsWith(" forge"), |
| 70 | 70 | ), |
| 71 | 71 | ).toBe(true); |
| 72 | expect(doc.runcmd.find((c) => c.includes("bun.sh/install"))).toContain( | |
| 73 | "BUN_INSTALL=/opt/bun", | |
| 74 | ); | |
| 72 | // Bun is installed by a script that checks the download's sha512 against a pinned one first. | |
| 73 | expect(doc.runcmd).toContain("/usr/local/sbin/forge-install-bun"); | |
| 74 | const installer = file(doc, "/usr/local/sbin/forge-install-bun"); | |
| 75 | expect(installer).toContain("/opt/bun/bin/bun"); | |
| 76 | expect(installer.indexOf("checksum mismatch")).toBeLessThan(installer.indexOf("install -D")); | |
| 75 | 77 | expect(doc.runcmd).toContain("chown -R forge:forge /opt/forge"); |
| 76 | 78 | // The checkout is made before it is handed over, and the service starts last. |
| 77 | 79 | const at = (s: string) => doc.runcmd.findIndex((c) => c.includes(s)); |
| @@ -164,7 +166,7 @@ describe.each(Object.entries(boots))("the %s machine", (_name, boot) => { | ||
| 164 | 166 | // Nothing is opened before the rules are in: the firewall precedes the Bun download and the |
| 165 | 167 | // clone. |
| 166 | 168 | expect(doc.runcmd.indexOf("ufw --force enable")).toBeLessThan( |
| 167 | doc.runcmd.findIndex((c) => c.includes("bun.sh")), | |
| 169 | doc.runcmd.indexOf("/usr/local/sbin/forge-install-bun"), | |
| 168 | 170 | ); |
| 169 | 171 | }); |
| 170 | 172 |
test/pinned-hetzner.test.ts +1 −1
| @@ -67,7 +67,7 @@ describe("hetzner target", () => { | ||
| 67 | 67 | expect(seen()).toEqual(sequence.create("hetzner", 501)); |
| 68 | 68 | expect(calls.every((c) => c.auth === `Bearer ${TOKEN}`)).toBe(true); |
| 69 | 69 | expect(JSON.stringify(calls.map((c) => c.body))).not.toContain(TOKEN); |
| 70 | const [volume, server] = [calls[0]!.body, calls[2]!.body]; | |
| 70 | const [volume, server] = [calls[1]!.body, calls[4]!.body]; | |
| 71 | 71 | expect(volume.location).toBe("nbg1"); |
| 72 | 72 | expect(server).toMatchObject({ server_type: "cx23", location: volume.location, volumes: [77], automount: true }); |
| 73 | 73 | expect(server.user_data).toContain("FORGE_DATA=/mnt/HC_Volume_77"); |
test/pinned-one-machine.test.ts added +267
| @@ -0,0 +1,267 @@ | ||
| 1 | /** | |
| 2 | * One forge, one machine, one volume (#16219): a create whose answer was lost is adopted by its | |
| 3 | * name on the next try, never repeated; a retire deletes what the row holds; the provider is asked | |
| 4 | * for what carries the forge's label and no row owns; an address that is not the public internet, | |
| 5 | * or an id that is not digits, is refused; a forge for sale runs a commit from a listed host only; | |
| 6 | * and the account forges are sold on is never handed to a run. A recorded fetch stands in for both | |
| 7 | * clouds. | |
| 8 | */ | |
| 9 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 10 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 11 | import { tmpdir } from "node:os"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { createApp, type App } from "../src/app.ts"; | |
| 14 | import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts"; | |
| 15 | import { checkPinned, deployForOrder, deployPinned, net, retirePinned, strayCloud, strayWords } from "../src/actions/pinned.ts"; | |
| 16 | import { BUN_INTEGRITY, bunInstallScript } from "../src/cloud/bun_install.ts"; | |
| 17 | import { BUN_PIN } from "../src/kernel/bun_pin.ts"; | |
| 18 | import { bar, sellingAccount } from "../src/cloud/gate.ts"; | |
| 19 | import { digitalocean } from "../src/cloud/droplet.ts"; | |
| 20 | import { hetzner } from "../src/cloud/hetzner.ts"; | |
| 21 | import { ipv4, numericId, provision } from "../src/cloud/machine.ts"; | |
| 22 | import { saleCode } from "../src/cloud/sale_source.ts"; | |
| 23 | import { secretNameOf } from "../src/core/cloud_account.ts"; | |
| 24 | import { getPinned } from "../src/core/pinned.ts"; | |
| 25 | import { createUser, getUserByName } from "../src/core/users.ts"; | |
| 26 | import { changePaidPlacement } from "../src/actions/pinned.ts"; | |
| 27 | import { quietLogs } from "./helpers/globals.ts"; | |
| 28 | import { recordCloud } from "./helpers/recorded-cloud.ts"; | |
| 29 | import { seedPlaces } from "./helpers/places-fixture.ts"; | |
| 30 | ||
| 31 | quietLogs(); | |
| 32 | ||
| 33 | const V1 = "a".repeat(40); | |
| 34 | const SOURCE = "https://mirror.example.org/trevato/forge"; | |
| 35 | const PLACES = { digitalocean: undefined, hetzner: "hetzner:nbg1:cx23" } as const; | |
| 36 | const ACCOUNTS = { digitalocean: "dop_v1_9Zq4TxLm7Kp2Vb8nWcR5", hetzner: "hcloud_Zq4TxLm7Kp2Vb8nWcR5Yd3Fg6Hj9" } as const; | |
| 37 | ||
| 38 | describe.each(["digitalocean", "hetzner"] as const)("%s: one forge, one machine", (target) => { | |
| 39 | let dataDir = ""; | |
| 40 | let app: App; | |
| 41 | const cloud = recordCloud(); | |
| 42 | const admin = () => getUserByName(app.db, "alice")!; | |
| 43 | const input = (name: string) => ({ | |
| 44 | name, host: `${name}.forge.test`, target, account: "main", app: "alice/shop", source: SOURCE, version: V1, config: {}, ...(PLACES[target] ? { place: PLACES[target] } : {}), | |
| 45 | }); | |
| 46 | ||
| 47 | beforeAll(async () => { | |
| 48 | dataDir = await mkdtemp(join(tmpdir(), "forge-one-machine-")); | |
| 49 | app = createApp({ dataDir, port: 0 }); | |
| 50 | await seedPlaces(app.db); | |
| 51 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 52 | if (!made.ok) throw new Error(made.error); | |
| 53 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" }, servers: [], meta: { pagination: { total_entries: 0 } } }), { status: 200 }); | |
| 54 | const added = await addAccount(app, admin(), target, "main", ACCOUNTS[target]); | |
| 55 | if (!added.ok) throw new Error(String(added.error)); | |
| 56 | allowWrite(app, admin(), target, "main", true); | |
| 57 | net.resolve = async () => []; | |
| 58 | net.probe = async () => new Response("ok", { status: 200 }); | |
| 59 | net.fetch = cloud.fetch; | |
| 60 | }, 30_000); | |
| 61 | ||
| 62 | afterAll(async () => { | |
| 63 | app.close(); | |
| 64 | await rm(dataDir, { recursive: true, force: true }); | |
| 65 | }); | |
| 66 | ||
| 67 | test("a machine made whose answer was lost is adopted on the retry: one machine", async () => { | |
| 68 | // The cloud makes the machine, and the answer never arrives. | |
| 69 | cloud.fail({ method: "POST", kind: "machine", lost: true }); | |
| 70 | const first = await deployPinned(app, admin(), input("lost")); | |
| 71 | expect(first.ok).toBe(false); | |
| 72 | expect(getPinned(app.db, "lost")).toMatchObject({ state: "failed", remote: "" }); | |
| 73 | expect(cloud.holds.machines).toHaveLength(1); | |
| 74 | const made = cloud.holds.machines[0]!.id; | |
| 75 | const again = await deployPinned(app, admin(), input("lost")); | |
| 76 | expect(again.ok).toBe(true); | |
| 77 | // Adopted, not made twice: the cloud holds the one machine, and the row names it. | |
| 78 | expect(cloud.holds.machines).toHaveLength(1); | |
| 79 | expect(getPinned(app.db, "lost")).toMatchObject({ state: "running", remote: String(made) }); | |
| 80 | expect(cloud.holds.volumes).toHaveLength(1); | |
| 81 | }); | |
| 82 | ||
| 83 | test("a volume made whose answer was lost is adopted too: one volume, one machine", async () => { | |
| 84 | cloud.fail({ method: "POST", kind: "volume", lost: true }); | |
| 85 | const first = await deployPinned(app, admin(), input("vol")); | |
| 86 | expect(first.ok).toBe(false); | |
| 87 | expect(getPinned(app.db, "vol")).toMatchObject({ state: "failed", remote: "", volume: "" }); | |
| 88 | const before = cloud.holds.volumes.length; | |
| 89 | expect((await deployPinned(app, admin(), input("vol"))).ok).toBe(true); | |
| 90 | expect(cloud.holds.volumes).toHaveLength(before); | |
| 91 | expect(cloud.holds.machines.filter((m) => m.body.name === "forge-vol")).toHaveLength(1); | |
| 92 | }); | |
| 93 | ||
| 94 | test("retire deletes the machine and, only when asked again with its data, the volume", async () => { | |
| 95 | const machines = cloud.holds.machines.length; | |
| 96 | const volumes = cloud.holds.volumes.length; | |
| 97 | expect(volumes).toBeGreaterThan(0); | |
| 98 | const kept = await retirePinned(app, admin(), "vol", {}); | |
| 99 | expect(kept.ok && kept.value.state).toBe("retired"); | |
| 100 | expect(cloud.holds.machines).toHaveLength(machines - 1); | |
| 101 | expect(cloud.holds.volumes).toHaveLength(volumes); | |
| 102 | const gone = await retirePinned(app, admin(), "vol", { withData: true }); | |
| 103 | expect(gone.ok && gone.value.volume).toBe(""); | |
| 104 | // (The recorded cloud gives every volume one id, so the delete takes the other forge's too.) | |
| 105 | expect(cloud.holds.volumes.some((v) => v.body.name === "forge-vol-data")).toBe(false); | |
| 106 | }); | |
| 107 | ||
| 108 | test("the provider is asked for what carries the forge's label and no row owns", async () => { | |
| 109 | // A machine and a volume made by hand under the label, which no row records. | |
| 110 | cloud.holds.machines.push({ id: 9001, body: { name: "forge-stray", tags: ["forge-pinned", "forge:stray"], labels: { "forge-pinned": "true", forge: "stray" } } }); | |
| 111 | cloud.holds.volumes.push({ id: target === "hetzner" ? 9002 : "vol-stray", body: { name: "forge-stray-data", location: "nbg1", region: "nyc1", tags: ["forge:stray"], labels: { "forge-pinned": "true" } } }); | |
| 112 | const seen = await strayCloud(app, admin(), target, "main"); | |
| 113 | expect(seen.ok).toBe(true); | |
| 114 | if (!seen.ok) return; | |
| 115 | expect(seen.value.machines.map((m) => m.id)).toEqual(["9001"]); | |
| 116 | expect(seen.value.volumes.map((v) => v.id)).toEqual([target === "hetzner" ? "9002" : "vol-stray"]); | |
| 117 | expect(strayWords(seen.value)).toContain("machine 9001 (forge-stray)"); | |
| 118 | expect(await strayCloud(app, undefined, target, "main")).toMatchObject({ ok: false }); | |
| 119 | }); | |
| 120 | }); | |
| 121 | ||
| 122 | describe("addresses and ids", () => { | |
| 123 | test("only a public IPv4 is kept: private, loopback, link-local, carrier-grade and reserved are refused", () => { | |
| 124 | for (const a of ["10.0.0.5", "172.16.0.1", "172.31.255.255", "192.168.1.1", "127.0.0.1", "169.254.169.254", "100.64.0.1", "100.127.255.255", "0.0.0.0", "198.18.0.1", "224.0.0.1", "255.255.255.255", "010.1.1.1"]) | |
| 125 | expect(ipv4(a), a).toBe(""); | |
| 126 | for (const a of ["203.0.113.9", "8.8.8.8", "172.32.0.1", "100.63.0.1", "100.128.0.1", "1.1.1.1"]) expect(ipv4(a), a).toBe(a); | |
| 127 | expect(ipv4(5)).toBe(""); | |
| 128 | }); | |
| 129 | ||
| 130 | test("a private address read back from the provider is never recorded", async () => { | |
| 131 | const dir = await mkdtemp(join(tmpdir(), "forge-private-addr-")); | |
| 132 | const app = createApp({ dataDir: dir, port: 0 }); | |
| 133 | try { | |
| 134 | await seedPlaces(app.db); | |
| 135 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 136 | if (!made.ok) throw new Error(made.error); | |
| 137 | const alice = getUserByName(app.db, "alice")!; | |
| 138 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 }); | |
| 139 | await addAccount(app, alice, "digitalocean", "main", ACCOUNTS.digitalocean); | |
| 140 | allowWrite(app, alice, "digitalocean", "main", true); | |
| 141 | net.resolve = async () => []; | |
| 142 | net.fetch = recordCloud({ address: "169.254.169.254" }).fetch; | |
| 143 | const r = await deployPinned(app, alice, { name: "meta", host: "meta.forge.test", target: "digitalocean", account: "main", app: "alice/shop", source: SOURCE, version: V1, config: {} }); | |
| 144 | expect(r.ok).toBe(true); | |
| 145 | expect(getPinned(app.db, "meta")?.address).toBe(""); | |
| 146 | const checked = await checkPinned(app, alice, "meta"); | |
| 147 | expect(checked.ok && checked.value.address).toBe(""); | |
| 148 | } finally { | |
| 149 | app.close(); | |
| 150 | await rm(dir, { recursive: true, force: true }); | |
| 151 | } | |
| 152 | }); | |
| 153 | ||
| 154 | test("a Hetzner id is digits: an empty string is not 0, and no other string reaches a path", () => { | |
| 155 | expect(numericId("77", "volume")).toBe(77); | |
| 156 | for (const bad of ["", "0", "-1", "1e3", "1/../2", "07", "7 ", "99999999999999999999"]) expect(() => numericId(bad, "volume"), bad).toThrow("numeric id"); | |
| 157 | }); | |
| 158 | ||
| 159 | test("a volume the provider answers without an id is refused before a machine is asked for", async () => { | |
| 160 | const calls: string[] = []; | |
| 161 | const f = async (url: string, init?: RequestInit) => { | |
| 162 | calls.push(`${init?.method ?? "GET"} ${new URL(url).pathname}`); | |
| 163 | return new Response(JSON.stringify(init?.method === "POST" ? { volume: {} } : { volumes: [] }), { status: 200 }); | |
| 164 | }; | |
| 165 | const p = { name: "x", datacenter: "nbg1", size: "cx23", remote: "", volume: "" } as any; | |
| 166 | await expect(provision(hetzner, f as any, "t", p, { onVolume() {} })).rejects.toThrow("made no volume"); | |
| 167 | expect(calls.some((c) => c.includes("/servers"))).toBe(false); | |
| 168 | await expect(provision(digitalocean, f as any, "t", { ...p, datacenter: "nyc1" }, { onVolume() {} })).rejects.toThrow("made no volume"); | |
| 169 | }); | |
| 170 | }); | |
| 171 | ||
| 172 | describe("what a sale may run", () => { | |
| 173 | const env = { FORGE_SALE_SOURCES: "mirror.example.org, git.example.net" }; | |
| 174 | const code = { source: SOURCE, version: V1 }; | |
| 175 | ||
| 176 | test("a tag is refused for a sale, a commit from a listed host is not", () => { | |
| 177 | expect(saleCode(code, "https://forge.test", env).ok).toBe(true); | |
| 178 | expect(saleCode({ ...code, version: "v1.2.3" }, "https://forge.test", env)).toMatchObject({ ok: false, error: expect.stringContaining("40-character commit") }); | |
| 179 | expect(saleCode({ ...code, version: V1.slice(1) }, "https://forge.test", env).ok).toBe(false); | |
| 180 | }); | |
| 181 | ||
| 182 | test("only the hosts the owner listed, and never the selling forge's own", () => { | |
| 183 | expect(saleCode({ ...code, source: "https://evil.example.com/trevato/forge" }, "https://forge.test", env)).toMatchObject({ ok: false, error: expect.stringContaining("not one of the source hosts") }); | |
| 184 | expect(saleCode({ ...code, source: "https://forge.test/trevato/forge" }, "https://forge.test", { FORGE_SALE_SOURCES: "forge.test" })).toMatchObject({ ok: false, error: expect.stringContaining("cannot be booted from the selling forge") }); | |
| 185 | expect(saleCode(code, "https://forge.test", {})).toMatchObject({ ok: false, error: expect.stringContaining("FORGE_SALE_SOURCES") }); | |
| 186 | }); | |
| 187 | ||
| 188 | test("an order's deploy refuses a tag and an unlisted host before anything is made", async () => { | |
| 189 | const dir = await mkdtemp(join(tmpdir(), "forge-sale-")); | |
| 190 | const app = createApp({ dataDir: dir, port: 0 }); | |
| 191 | const before = { ...process.env }; | |
| 192 | process.env["FORGE_SALE_SOURCES"] = "mirror.example.org"; | |
| 193 | try { | |
| 194 | const calls: string[] = []; | |
| 195 | net.fetch = async (u) => (calls.push(String(u)), new Response("{}", { status: 500 })); | |
| 196 | const base = { name: "bought", host: "", target: "digitalocean", account: "main", app: "alice/shop", config: {} }; | |
| 197 | const tag = await deployForOrder(app, "ord_1", { ...base, source: SOURCE, version: "v1.2.3" }); | |
| 198 | expect(tag).toMatchObject({ ok: false, error: expect.stringContaining("40-character commit") }); | |
| 199 | const host = await deployForOrder(app, "ord_1", { ...base, source: "https://elsewhere.example.com/a/b", version: V1 }); | |
| 200 | expect(host).toMatchObject({ ok: false, error: expect.stringContaining("not one of the source hosts") }); | |
| 201 | expect(calls).toEqual([]); | |
| 202 | expect(getPinned(app.db, "bought")).toBeUndefined(); | |
| 203 | } finally { | |
| 204 | process.env["FORGE_SALE_SOURCES"] = before["FORGE_SALE_SOURCES"] ?? ""; | |
| 205 | if (before["FORGE_SALE_SOURCES"] === undefined) delete process.env["FORGE_SALE_SOURCES"]; | |
| 206 | app.close(); | |
| 207 | await rm(dir, { recursive: true, force: true }); | |
| 208 | } | |
| 209 | }); | |
| 210 | }); | |
| 211 | ||
| 212 | describe("the selling account is for the forge's own deploys", () => { | |
| 213 | const declared = [{ vendor: "digitalocean", use: "read", why: "an app reads droplets" }] as any; | |
| 214 | const asked = (name: string) => ({ names: [secretNameOf("digitalocean", name)], refused: [] as string[] }); | |
| 215 | let dir = ""; | |
| 216 | let app: App; | |
| 217 | ||
| 218 | beforeAll(async () => { | |
| 219 | dir = await mkdtemp(join(tmpdir(), "forge-selling-")); | |
| 220 | app = createApp({ dataDir: dir, port: 0 }); | |
| 221 | await seedPlaces(app.db); | |
| 222 | const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }); | |
| 223 | if (!made.ok) throw new Error(made.error); | |
| 224 | const alice = getUserByName(app.db, "alice")!; | |
| 225 | cloudNet.fetch = async () => new Response(JSON.stringify({ account: { email: "[email protected]", status: "active" } }), { status: 200 }); | |
| 226 | for (const name of ["main", "other"]) { | |
| 227 | await addAccount(app, alice, "digitalocean", name, ACCOUNTS.digitalocean); | |
| 228 | allowWrite(app, alice, "digitalocean", name, true); | |
| 229 | } | |
| 230 | }); | |
| 231 | afterAll(async () => { | |
| 232 | app.close(); | |
| 233 | await rm(dir, { recursive: true, force: true }); | |
| 234 | }); | |
| 235 | ||
| 236 | test("an account the repository declares is handed to a run, until it is the one forges are sold on", async () => { | |
| 237 | const alice = getUserByName(app.db, "alice")!; | |
| 238 | expect(bar(app.db, asked("main"), "run_1", declared).names).toEqual([secretNameOf("digitalocean", "main")]); | |
| 239 | expect(changePaidPlacement(app, alice, "digitalocean/main").ok).toBe(true); | |
| 240 | const held = bar(app.db, asked("main"), "run_2", declared); | |
| 241 | expect(held.names).toEqual([]); | |
| 242 | expect(held.refused[0]).toContain("no run is given"); | |
| 243 | // Another account, declared the same way, is still the repository's to use. | |
| 244 | expect(bar(app.db, asked("other"), "run_3", declared).names).toEqual([secretNameOf("digitalocean", "other")]); | |
| 245 | expect(sellingAccount(app.db, { provider: "digitalocean", account: "other" })).toBe(false); | |
| 246 | const audited = app.db.query("SELECT purpose, allowed FROM cloud_audit WHERE target = 'run run_2'").all(); | |
| 247 | expect(audited).toEqual([{ purpose: "hand-out:selling", allowed: 0 }]); | |
| 248 | }); | |
| 249 | ||
| 250 | test("an account a pinned forge was deployed with is refused to a run too", async () => { | |
| 251 | const alice = getUserByName(app.db, "alice")!; | |
| 252 | expect(changePaidPlacement(app, alice, "hosted").ok).toBe(true); | |
| 253 | net.fetch = recordCloud().fetch; | |
| 254 | net.resolve = async () => []; | |
| 255 | const r = await deployPinned(app, alice, { name: "mine", host: "mine.forge.test", target: "digitalocean", account: "other", app: "alice/shop", source: SOURCE, version: V1, config: {} }); | |
| 256 | expect(r.ok).toBe(true); | |
| 257 | expect(bar(app.db, asked("other"), "run_4", declared).names).toEqual([]); | |
| 258 | }); | |
| 259 | }); | |
| 260 | ||
| 261 | describe("the Bun a machine installs", () => { | |
| 262 | test("the repository's pinned Bun has a checksum for each architecture, so a bump cannot boot unchecked", () => { | |
| 263 | const pin = BUN_PIN ?? Bun.version; | |
| 264 | for (const arch of ["x64", "aarch64"] as const) expect(BUN_INTEGRITY[pin]?.[arch], `${pin} ${arch}`).toMatch(/^sha512-[A-Za-z0-9+/]{86}==$/); | |
| 265 | expect(() => bunInstallScript("9.9.9")).toThrow("no pinned checksum"); | |
| 266 | }); | |
| 267 | }); |
new above
offline