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

Edges: firewalls for DigitalOcean and Hetzner as an infra kind, with plan steps and drift (#16696) #17092

opened this

Merged 43h 22m ago, live in production

mason/forge:mason/17070-edges-firewalls-for-digitalocean-and-het → main 0 commits fork

  • Merged. mason/17070-edges-firewalls-for-digitalocean-and-het was merged into main as 2214c84.

Review

Sign in to review this change.
24 files changed +648 −54
docs/features/infra.md +6
@@ -14,6 +14,12 @@ What runs on your own cloud, what it's for, what it costs, and when it ends; and
1414 - **API:** `GET /api/v1/admin/infra` (`?plan=<id>` adds a build's steps), `POST /api/v1/admin/infra/plan`, `POST /api/v1/admin/infra/apply` (202). Keep is `POST /api/v1/admin/pinned/:name/keep`.
1515 - **Agents:** the `infra` MCP tool, in Talk's slot where `experiments` was: `list` (first `says`: one paragraph naming what runs, the dead rows, what ended in the last 30 days with each one's billing sentence, and the total, at most ten names a group then "and N more", so a reader of `says` alone misses no machine; then everything `experiments` listed, plus each machine's end and what it bills for, and `ended`: what retired in the last 30 days or still bills, so a question about one is answered from its row; a dead row's `clear` sentence), `show` (an experiment, a plan id's build, or a machine by name, running or ended, with its billing sentence; a name with no row says "nothing called … has existed here" only when no event ever named it), `plan` a `want`, `apply` a plan id (a plan of dead row `names` clears them; Talk offers it, the person allows it), `keep`, `begin`, `attach`, `record_result`. Only `apply` spends money, so the forge asks the person first.
1616
17 ## Firewalls (#17070)
18
19 A cloud firewall around a machine that stands: DigitalOcean's and Hetzner's, free at both, opening ports 80 and 443 to the world and nothing else inbound (the machine's own firewall stays; this is the second layer, outside it). It is a kind in the plan (`src/cloud/plan.ts`): one `firewall` step, no monthly change, refused when the machine is not there, the account is another or read-only, an orphan stands on it, or the cloud (OVHcloud) has none. It applies by the forge's tag or label, so a machine an Update replaces is behind it too. Its lifetime is the machine's: retiring a forge, by hand or when its end comes, deletes it. Ask for it through the `infra` tool: `plan` with `want: {firewall: "<machine name>"}`, then `apply` its id. The terminal and web compose forms do not offer it yet.
20
21 The hourly watch reads each account's firewalls too: one named `forge-<name>` that no live forge records is an orphan, raised like an orphan machine and shown on /infra as "At DigitalOcean, not in your infrastructure: 1 firewall". A firewall named any other way is the person's and is not read.
22
1723 All four read `infraOf` and plan through `planCompose` in `src/actions/infra.ts`, which plans with `src/cloud/plan.ts`; only a forge admin sees them.
1824
1925 ## Snapshots (#17072)
src/actions/infra.ts +15 −4
@@ -16,7 +16,7 @@
1616 import type { App } from "../app.ts";
1717 import { billingSentence, billsOf, existsAtProvider, type Bills } from "../cloud/billing.ts";
1818 import { experiments, type Experiments } from "../cloud/experiments.ts";
19 import { apply, DNS_BY_HAND, plan, readInfra, type DatabaseWant, type MachineWant, type Plan, type Reads, type Refusal, type Want } from "../cloud/plan.ts";
19 import { apply, DNS_BY_HAND, plan, readInfra, type DatabaseWant, type FirewallWant, type MachineWant, type Plan, type Reads, type Refusal, type Want } from "../cloud/plan.ts";
2020 import { DATABASE_SIZES, databaseCents, databaseShape, DEFAULT_DATABASE_SIZE } from "../cloud/database.ts";
2121 import { DATABASE_NAME, DEFAULT_SECRET, listDatabases } from "../core/managed_database.ts";
2222 import { keptPlaces } from "../cloud/places_read.ts";
@@ -288,8 +288,9 @@ function reckon(app: App, now: Date): { view: InfraView; rows: Map<string, Runni
288288 const orphans = lastReading(db, a.provider, a.name)?.resources.filter((r) => r.verdict === "orphan") ?? [];
289289 if (orphans.length === 0) return [];
290290 const machines = orphans.filter((r) => r.kind === "machine").length;
291 const volumes = orphans.length - machines;
292 const what = [machines > 0 ? plural(machines, MACHINE_WORD[a.provider] ?? "machine") : "", volumes > 0 ? plural(volumes, "volume") : ""]
291 const firewalls = orphans.filter((r) => r.kind === "firewall").length;
292 const volumes = orphans.length - machines - firewalls;
293 const what = [machines > 0 ? plural(machines, MACHINE_WORD[a.provider] ?? "machine") : "", volumes > 0 ? plural(volumes, "volume") : "", firewalls > 0 ? plural(firewalls, "firewall") : ""]
293294 .filter(Boolean)
294295 .join(" and ");
295296 const account = `${a.provider}/${a.name}`;
@@ -501,6 +502,15 @@ export function gameWant(g: { readonly name: string; readonly where: string; rea
501502 return ok({ kind: "machine", game: true, name: g.name, account, place, app: repo, source: "", ...(g.host ? { host: g.host } : {}) });
502503 }
503504
505 /**
506 * The want of a firewall around the pinned forge `name` (#17070): on the account its machine is on.
507 */
508 export function firewallWant(app: App, name: string): Result<FirewallWant, string> {
509 const p = getPinned(app.db, name);
510 if (p === undefined) return err(`Nothing called ${name} to put a firewall around.`);
511 return ok({ kind: "firewall", name: p.name, account: `${p.target}/${p.account}` });
512 }
513
504514 /** A managed database as every door sends it: plain strings, read by `databaseWantOf`. */
505515 export interface DatabaseCompose {
506516 readonly app: string;
@@ -591,6 +601,7 @@ export function summaryOf(p: Plan): string {
591601 const adds = [
592602 count("machine") > 0 ? `+ ${plural(count("machine"), "machine")}` : "",
593603 count("disk") > 0 ? `+ ${plural(count("disk"), "disk")}` : "",
604 count("firewall") > 0 ? `+ ${plural(count("firewall"), "firewall")}` : "",
594605 count("database") > 0 ? `+ ${plural(count("database"), "database")}` : "",
595606 count("retire") > 0 ? `− ${plural(count("retire"), "machine")}` : "",
596607 count("clear") > 0 ? `clear ${plural(count("clear"), "dead row")}` : "",
@@ -624,7 +635,7 @@ function fixOf(r: Refusal, wants: readonly Want[]): { why: string; href: string;
624635 }
625636
626637 /** What a plan of no wants reads: nothing at all. */
627 const NOTHING: Reads = { account: () => undefined, price: () => undefined, closed: () => undefined, host: () => "", dnsAuto: false, experiment: () => undefined, where: () => undefined };
638 const NOTHING: Reads = { firewalls: () => false, account: () => undefined, price: () => undefined, closed: () => undefined, host: () => "", dnsAuto: false, experiment: () => undefined, where: () => undefined };
628639
629640 /** Plan a compose against what exists now. */
630641 export async function planCompose(app: App, actor: User | undefined, c: Compose, choices?: ComposeChoices): Promise<Result<Planned, string>> {
src/actions/pinned.ts +39 −6
@@ -30,7 +30,9 @@ import type { GameBoot } from "../games/boot.ts";
3030 import type { App } from "../app.ts";
3131 import { gatedFetch } from "../cloud/gate.ts";
3232 import { capped, CeilingRefusal, priced, refusalAt, rowCents } from "../cloud/ceiling.ts";
33 import { driverOf } from "../cloud/drivers.ts";
33 import { driverOf, firewallCloud } from "../cloud/drivers.ts";
34 import { ensureFirewall, NO_FIREWALL, removeFirewall } from "../cloud/firewall.ts";
35 import { clearFirewall, firewallOf, setFirewall } from "../core/pinned_firewall.ts";
3436 import { fileIn, orderable, provision, read, replace, retire, strays, type Labelled, type Restore } from "../cloud/machine.ts";
3537 import { saleCode } from "../cloud/sale_source.ts";
3638 import { dollars } from "../cloud/prices.ts";
@@ -762,7 +764,8 @@ async function retireNow(app: App, who: Who, name: string, o: { withData?: boole
762764 if (!before) return err("No such pinned forge.");
763765 const withData = o.withData === true;
764766 const done = (p: Pinned, dnsRemoved: Retired["dnsRemoved"]): Result<Retired, string> => ok({ ...view(app, p), dnsRemoved });
765 if (before.state === "retired" && (before.volume === "" || !withData)) return done(before, "none");
767 const walled = firewallOf(app.db, before.id) !== undefined;
768 if (before.state === "retired" && !walled && (before.volume === "" || !withData)) return done(before, "none");
766769 if (o.despiteClaim !== true) {
767770 if (before.claimedAt !== "") return err(RETIRE_CLAIMED);
768771 if (before.state !== "retired") {
@@ -771,12 +774,19 @@ async function retireNow(app: App, who: Who, name: string, o: { withData?: boole
771774 }
772775 }
773776 const p = getPinned(app.db, name)!;
774 const gone = await withCloud(app, who, p, "retire", (f, token) =>
775 retire(driverOf(p.target), f, token, p, { withData }, {
777 const gone = await withCloud(app, who, p, "retire", async (f, token) => {
778 await retire(driverOf(p.target), f, token, p, { withData }, {
776779 onMachineGone: () => setRemote(app.db, name, { remote: "", address: "", state: "retired" }),
777780 onVolumeGone: () => setRemote(app.db, name, { volume: "" }),
778 }),
779 );
781 });
782 // The firewall lives as long as the machine it is around (#17070): it goes with it, free to
783 // keep but never left standing at the provider for the watch to call an orphan.
784 const wall = firewallOf(app.db, p.id);
785 if (wall !== undefined) {
786 await removeFirewall(driverOf(p.target), f, token, p.name, wall);
787 clearFirewall(app.db, p.id);
788 }
789 });
780790 if (!gone.ok) {
781791 // The machine went and the volume's delete was refused: the forge is retired, its data kept.
782792 const now = getPinned(app.db, name)!;
@@ -787,6 +797,29 @@ async function retireNow(app: App, who: Who, name: string, o: { withData?: boole
787797 return done(getPinned(app.db, name)!, dnsRemoved);
788798 }
789799
800 /**
801 * Put a cloud firewall around a running forge's machine (#17070): web ports in, nothing else, free.
802 * The machine must exist and the cloud must have one the forge can make. Made once: a forge that
803 * has one keeps it, and a firewall a lost answer left is adopted by name. An admin's, at every
804 * door.
805 */
806 export function firewallPinned(app: App, actor: User | undefined, name: string): Promise<Result<string, string>> {
807 const who = admin(actor);
808 if (!who.ok) return Promise.resolve(who);
809 return oneChange(app, name, async () => {
810 const p = getPinned(app.db, name);
811 if (!p) return err("No such pinned forge.");
812 if (p.state === "retired" || p.remote === "") return err(`${name} has no machine to put a firewall around.`);
813 if (!firewallCloud(p.target)) return err(NO_FIREWALL);
814 if (firewallOf(app.db, p.id) !== undefined) return ok(`${name} already has a firewall.`);
815 const made = await withCloud(app, who.value, p, "firewall", (f, token) => ensureFirewall(driverOf(p.target), f, token, p.name));
816 if (!made.ok) return made;
817 setFirewall(app.db, p.id, made.value);
818 app.bus.append({ kind: "pinned.firewalled", actorId: who.value.id, payload: { name, account: `${p.target}/${p.account}`, ...orderOf(who.value) } });
819 return ok(`${name} is behind a firewall: only ports 80 and 443 are open to the world.`);
820 });
821 }
822
790823 const DAY_MS = 86_400_000;
791824 /** The refusal of a lifetime that is not a whole number of days in range, at every door. */
792825 export const LIFETIME_WORDS = `A lifetime is a whole number of days, 1 to ${MAX_LIFETIME_DAYS}.`;
src/cloud/drivers.ts +3
@@ -16,3 +16,6 @@ export function driverOf(id: string): Driver {
1616 if (!d) throw new Error(`No driver deploys to ${id}.`);
1717 return d;
1818 }
19
20 /** Whether the forge makes firewalls on a target's cloud: its driver has the calls. */
21 export const firewallCloud = (id: string): boolean => DRIVERS[id]?.firewall !== undefined;
src/cloud/droplet.ts +2
@@ -9,6 +9,7 @@
99 * POST /volumes/{id}/snapshots, GET and DELETE /snapshots/{id} (#17072).
1010 */
1111
12 import { digitaloceanFirewall } from "./firewall.ts";
1213 import { dropThrowawayKey, makeThrowawayKey } from "./throwaway_key.ts";
1314 import { bootConfig as boot, forgeTag, ipv4, paged, volumeName, type Booted, type Driver, type Found } from "./machine.ts";
1415
@@ -38,6 +39,7 @@ const tagged = (x: any, tag: (t: string) => boolean): boolean => Array.isArray(x
3839 /** Both the volume and the droplet are made in the row's datacenter, at its size (`machine.ts`). */
3940 export const digitalocean: Driver = {
4041 api: "https://api.digitalocean.com/v2",
42 firewall: digitaloceanFirewall,
4143 async createVolume(call, p, snapshot) {
4244 // From a snapshot the volume keeps the filesystem it holds: DigitalOcean refuses to format one.
4345 const v = await call("POST", "/volumes", {
src/cloud/firewall.ts added +108
@@ -0,0 +1,108 @@
1 /**
2 * The cloud firewall of a pinned forge (#17070, #16696): DigitalOcean's and Hetzner's firewalls,
3 * free at both, opening the two ports the machine's proxy listens on (80 and 443) to the world and
4 * nothing else inbound. The machine already firewalls itself (`harden.ts`); this is the second
5 * layer, outside it, so a mistake inside the machine does not open a port. It is named
6 * `forge-<name>` and applies by the forge's tag (DigitalOcean) or label (Hetzner), so it follows a
7 * machine an Update replaces. Its lifetime is the machine's: retiring the forge deletes it.
8 *
9 * Calls: DigitalOcean `GET/POST /firewalls`, `DELETE /firewalls/{id}`; Hetzner `GET/POST
10 * /firewalls`, `POST /firewalls/{id}/actions/remove_from_resources`, `DELETE /firewalls/{id}`.
11 */
12
13 import { caller, forgeTag, gone, numericId, type Driver, type FirewallCalls } from "./machine.ts";
14 import type { Fetch } from "./providers.ts";
15
16 /** The ports open to the world: the proxy's. */
17 const OPEN_PORTS: readonly number[] = [80, 443];
18 const EVERYWHERE = ["0.0.0.0/0", "::/0"];
19 const ID = /^[A-Za-z0-9-]{1,64}$/;
20
21 /** The firewall's name at the provider. */
22 const firewallName = (name: string): string => `forge-${name}`;
23
24 /** DigitalOcean's body: web in, everything out, applied to droplets tagged for the forge. */
25 const digitaloceanBody = (name: string): object => ({
26 name: firewallName(name),
27 inbound_rules: OPEN_PORTS.map((port) => ({ protocol: "tcp", ports: String(port), sources: { addresses: EVERYWHERE } })),
28 outbound_rules: [
29 { protocol: "tcp", ports: "all", destinations: { addresses: EVERYWHERE } },
30 { protocol: "udp", ports: "all", destinations: { addresses: EVERYWHERE } },
31 { protocol: "icmp", destinations: { addresses: EVERYWHERE } },
32 ],
33 tags: [forgeTag(name)],
34 });
35
36 /** Hetzner's body: web in (outbound is open when no rule says otherwise), applied by label. */
37 const hetznerBody = (name: string): object => ({
38 name: firewallName(name),
39 labels: { "forge-pinned": "true", forge: name },
40 rules: OPEN_PORTS.map((port) => ({ direction: "in", protocol: "tcp", port: String(port), source_ips: EVERYWHERE })),
41 apply_to: [{ type: "label_selector", label_selector: { selector: `forge=${name}` } }],
42 });
43
44 const idIn = (list: unknown, name: string): string => {
45 const hit = (Array.isArray(list) ? list : []).find((x: any) => x?.name === firewallName(name));
46 const id = hit === undefined ? "" : String(hit.id ?? "");
47 return ID.test(id) ? id : "";
48 };
49
50 const PER_PAGE = 200;
51 const FIND_PAGES = 25;
52
53 export const digitaloceanFirewall: FirewallCalls = {
54 async find(call, name) {
55 // Paged, so an account of many firewalls still finds its own and never makes a duplicate.
56 for (let page = 1; page <= FIND_PAGES; page++) {
57 const list = (await call("GET", `/firewalls?per_page=${PER_PAGE}&page=${page}`)).firewalls;
58 const id = idIn(list, name);
59 if (id !== "" || !Array.isArray(list) || list.length < PER_PAGE) return id;
60 }
61 return "";
62 },
63 async create(call, name) {
64 return String((await call("POST", "/firewalls", digitaloceanBody(name))).firewall?.id ?? "");
65 },
66 async remove(call, id) {
67 await call("DELETE", `/firewalls/${id}`);
68 },
69 };
70
71 export const hetznerFirewall: FirewallCalls = {
72 async find(call, name) {
73 return idIn((await call("GET", `/firewalls?name=${encodeURIComponent(firewallName(name))}`)).firewalls, name);
74 },
75 async create(call, name) {
76 return String((await call("POST", "/firewalls", hetznerBody(name))).firewall?.id ?? "");
77 },
78 async remove(call, id, name) {
79 const n = numericId(id, "firewall");
80 // A firewall applied to resources by label is let go first, or Hetzner refuses the delete.
81 await gone(async () => void (await call("POST", `/firewalls/${n}/actions/remove_from_resources`, { remove_from: [{ type: "label_selector", label_selector: { selector: `forge=${name}` } }] })));
82 await call("DELETE", `/firewalls/${n}`);
83 },
84 };
85
86 /** Why a cloud has none. */
87 export const NO_FIREWALL = "The forge does not make firewalls on this cloud.";
88
89 /**
90 * Make the forge's firewall, or adopt the one a lost answer left (found by name), and return its
91 * id. Asked of the provider, never repeated.
92 */
93 export async function ensureFirewall(d: Driver, f: Fetch, token: string, name: string): Promise<string> {
94 if (d.firewall === undefined) throw new Error(NO_FIREWALL);
95 const call = caller(d, f, token);
96 const have = await d.firewall.find(call, name);
97 const id = have !== "" ? have : await d.firewall.create(call, name);
98 if (!ID.test(id)) throw new Error(`${new URL(d.api).host} made no firewall the forge can name`);
99 return id;
100 }
101
102 /** Delete the firewall; one already gone is done. */
103 export async function removeFirewall(d: Driver, f: Fetch, token: string, name: string, id: string): Promise<void> {
104 if (d.firewall === undefined) return;
105 if (!ID.test(id)) throw new Error("this forge's firewall has no id the forge can delete");
106 const call = caller(d, f, token);
107 await gone(() => d.firewall!.remove(call, id, name));
108 }
src/cloud/hetzner.ts +2
@@ -11,6 +11,7 @@
1111 * /images/{id} (a snapshot of the server's disk, #17072).
1212 */
1313
14 import { hetznerFirewall } from "./firewall.ts";
1415 import { dropThrowawayKey, makeThrowawayKey } from "./throwaway_key.ts";
1516 import { bootConfig as boot, ipv4, numericId, paged, volumeName, type Booted, type Driver, type Found } from "./machine.ts";
1617
@@ -34,6 +35,7 @@ const foundIn = (list: unknown): Found[] =>
3435 /** The volume and the server are made at the row's location, the server of its type (`machine.ts`). */
3536 export const hetzner: Driver = {
3637 api: "https://api.hetzner.cloud/v1",
38 firewall: hetznerFirewall,
3739 async createVolume(call, p) {
3840 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 } });
3941 return String(v.volume?.id ?? "");
src/cloud/machine.ts +20 −2
@@ -243,6 +243,11 @@ export interface Driver {
243243 * belongs to one project.
244244 */
245245 projectId?(call: Call, name: string): Promise<string>;
246 /**
247 * The cloud firewall around a forge's machine (#17070), where the cloud has one the forge can
248 * make: `cloud/firewall.ts` drives it. A cloud without it has no firewall step.
249 */
250 readonly firewall?: FirewallCalls;
246251 /** File the machine and the volume in the project `projectId` named. */
247252 assign?(call: Call, project: string, things: { machine: string; volume: string }): Promise<void>;
248253 /**
@@ -268,10 +273,23 @@ export interface Restore {
268273 readonly what: SnapshotWhat;
269274 }
270275
276 /**
277 * A cloud's firewall calls. The firewall is found by its name `forge-<name>` and applies to the
278 * machines carrying the forge's tag or label, so a machine that replaces this one is behind it too.
279 */
280 export interface FirewallCalls {
281 /** The id of the forge's firewall, or empty. */
282 find(call: Call, name: string): Promise<string>;
283 /** Make it, opening only the web ports to the world, and return its id. */
284 create(call: Call, name: string): Promise<string>;
285 /** Let go of the machines it applies to, then delete it. */
286 remove(call: Call, id: string, name: string): Promise<void>;
287 }
288
271289 /** The tag or label that names a forge on everything the forge makes for it (#16340). */
272290 export const forgeTag = (name: string) => `forge:${name}`;
273291
274 function caller(d: Driver, f: Fetch, token: string): Call {
292 export function caller(d: Driver, f: Fetch, token: string): Call {
275293 if (d.signed) return d.signed(f, token);
276294 const host = new URL(d.api).host;
277295 return async (method, path, body) => {
@@ -430,7 +448,7 @@ export function numericId(v: string, what: string): number {
430448 }
431449
432450 /** A delete that finds the thing already gone is a delete that is done. */
433 async function gone(go: () => Promise<void>): Promise<void> {
451 export async function gone(go: () => Promise<void>): Promise<void> {
434452 try {
435453 await go();
436454 } catch (e) {
src/cloud/plan.ts +98 −7
@@ -19,24 +19,28 @@
1919 * exists. The forge has no generic job queue (timers call apps over HTTP), so this is the job: the
2020 * plan is the intent, reality is the progress, the outbox is the record.
2121 *
22 * Kinds: a machine with its disk, and a managed Postgres database (#17074) bound to an app. `Want`
23 * is a union on `kind`, so a firewall, a DNS record or a bucket is one more member with its own
24 * steps and refusals. A database's want and what exists of it (`DatabaseHave`) travel beside the
25 * machines', in `plan`'s options and `Reads.database`, so the machine plan is untouched by them.
22 * Kinds: a machine with its disk, a firewall around one (#17070), and a managed Postgres database
23 * (#17074) bound to an app. `Want` is a union on `kind`, so a DNS record or a bucket is one more
24 * member with its own steps and refusals. A database's want and what exists of it (`DatabaseHave`)
25 * travel beside the machines', in `plan`'s options and `Reads.database`, so the machine plan is
26 * untouched by them.
2627 */
2728
2829 import type { App } from "../app.ts";
29 import { clearPinned, deployPinned, LIFETIME_DAYS, LIFETIME_WORDS, MAX_LIFETIME_DAYS, retirePinned } from "../actions/pinned.ts";
30 import { clearPinned, deployPinned, firewallPinned, LIFETIME_DAYS, LIFETIME_WORDS, MAX_LIFETIME_DAYS, retirePinned } from "../actions/pinned.ts";
3031 import { stuckWords, WATCH } from "../actions/pinned_watch.ts";
3132 import { bindDatabase, createDatabase, ONLY_DIGITALOCEAN, pollDatabase } from "../actions/database.ts";
3233 import { getRepo } from "../core/repos.ts";
3334 import { getCloudAccount, listCloudAccounts, NO_ACCOUNT, READ_ONLY } from "../core/cloud_account.ts";
3435 import { DATABASE_NAME, DEFAULT_SECRET, databaseNamed, listDatabases } from "../core/managed_database.ts";
3536 import { dnsOf, getPinned, HOST_NEEDED, listPinned, NAME_TAKEN, placeIdOf, type Pinned } from "../core/pinned.ts";
37 import { firewallOf } from "../core/pinned_firewall.ts";
3638 import { watchOf } from "../core/pinned_watch.ts";
3739 import type { User } from "../core/users.ts";
3840 import { err, ok, type Result } from "../kernel/result.ts";
3941 import { getBaseDomain } from "../settings/pinned_domain.ts";
42 import { firewallCloud } from "./drivers.ts";
43 import { NO_FIREWALL } from "./firewall.ts";
4044 import { accountCents, priced, refusalOf, rowCents } from "./ceiling.ts";
4145 import { attachMachine, beginExperiment, EXPERIMENT_WORDS, experiments } from "./experiments.ts";
4246 import { isAppEnvName, isReservedAppEnvName } from "../core/app_env.ts";
@@ -83,6 +87,18 @@ export interface MachineWant {
8387 readonly game?: boolean | undefined;
8488 }
8589
90 /**
91 * A cloud firewall around a machine (#17070): the web ports open and nothing else inbound, free,
92 * living and ending with the machine. Its identity is the machine's name, one firewall a machine.
93 */
94 export interface FirewallWant {
95 readonly kind: "firewall";
96 /** The machine it is around: a pinned forge that exists, or a machine wanted in the same plan. */
97 readonly name: string;
98 /** The cloud account the machine is on, `provider/name`. */
99 readonly account: string;
100 }
101
86102 /** A managed Postgres cluster on a DigitalOcean account, its URL given to an app as a secret. */
87103 export interface DatabaseWant {
88104 readonly kind: "database";
@@ -100,7 +116,7 @@ export interface DatabaseWant {
100116 readonly secret?: string | undefined;
101117 }
102118
103 export type Want = MachineWant | DatabaseWant;
119 export type Want = MachineWant | FirewallWant | DatabaseWant;
104120
105121 /** A machine the forge made (a pinned row), as the plan needs it. */
106122 export interface MachineHave {
@@ -119,6 +135,8 @@ export interface MachineHave {
119135 readonly machine: boolean;
120136 readonly dns: boolean;
121137 readonly answered: boolean;
138 /** Whether a cloud firewall is around it (`pinned_firewall`). */
139 readonly firewall: boolean;
122140 /** The experiment it is on now, and its question; empty for none. */
123141 readonly experiment: string;
124142 readonly question: string;
@@ -171,6 +189,8 @@ export interface Reads {
171189 closed(place: string): string | undefined;
172190 /** The name a forge called `name` would be served on, `asked` winning; empty when there is none. */
173191 host(name: string, asked: string): string;
192 /** Whether the forge makes firewalls on a provider's cloud. */
193 firewalls(provider: string): boolean;
174194 /** Whether an attached Cloudflare account that allows writes can write the DNS record. */
175195 readonly dnsAuto: boolean;
176196 /** Where a place is and what its size gives, in people's words; undefined when the catalog has no such place. */
@@ -181,7 +201,7 @@ export interface Reads {
181201 readonly database?: DatabaseReads | undefined;
182202 }
183203
184 export type StepKind = "disk" | "machine" | "attach" | "dns" | "ready" | "address" | "retire" | "clear" | "database" | "online" | "bind";
204 export type StepKind = "disk" | "machine" | "attach" | "dns" | "ready" | "address" | "retire" | "clear" | "firewall" | "database" | "online" | "bind";
185205
186206 export interface Step {
187207 readonly index: number;
@@ -295,6 +315,8 @@ export function plan(
295315 const accounts = new Map<string, { before: number; after: number; ceiling: number; held: number; refused: boolean }>();
296316 const boots: number[] = [];
297317 const seen = new Set<string>();
318 const walls: FirewallWant[] = [];
319 const refused = new Set<string>();
298320 let calls = 0;
299321
300322 const ledger = (account: string, a: AccountRead) => {
@@ -308,6 +330,7 @@ export function plan(
308330 };
309331 const refuse = (name: string, why: string, account?: string): void => {
310332 refusals.push({ name, why });
333 refused.add(name);
311334 const l = account === undefined ? undefined : accounts.get(account);
312335 if (l) l.refused = true;
313336 };
@@ -374,6 +397,10 @@ export function plan(
374397 };
375398
376399 for (const w of wants) {
400 if (w.kind === "firewall") {
401 walls.push(w);
402 continue;
403 }
377404 if (seen.has(w.name)) {
378405 refuse(w.name, NAME_TAKEN);
379406 continue;
@@ -507,6 +534,54 @@ export function plan(
507534 }
508535 }
509536
537 // A firewall is planned after the machines, so one wanted in this same plan is behind it too.
538 const around = new Set<string>();
539 for (const w of walls) {
540 if (around.has(w.name)) {
541 refuse(w.name, NAME_TAKEN);
542 continue;
543 }
544 around.add(w.name);
545 const a = reads.account(w.account);
546 if (a === undefined) {
547 refuse(w.name, NO_ACCOUNT);
548 continue;
549 }
550 // Called bare for its side effect: it opens the account's row in the ledger, which a refusal
551 // below then marks; a firewall adds no cost to it.
552 ledger(w.account, a);
553 if (!a.writable) {
554 refuse(w.name, READ_ONLY, w.account);
555 continue;
556 }
557 const provider = providerOf(w.account);
558 if (!reads.firewalls(provider)) {
559 refuse(w.name, `${NO_FIREWALL} ${isProvider(provider) ? LABEL[provider] : provider} has none to make.`, w.account);
560 continue;
561 }
562 const h = byName.get(w.name);
563 const coming = wants.some((x) => x.kind === "machine" && x.name === w.name && x.account === w.account) && !refused.has(w.name);
564 const there = h !== undefined && h.account === w.account && h.state !== "retired" && h.machine;
565 if (!coming && !there) {
566 refuse(w.name, `${w.name} has no machine on ${w.account} to put a firewall around.`, w.account);
567 continue;
568 }
569 // Firewalls are free, but a standing orphan refuses every create on the account, this one too.
570 if (a.orphan !== undefined) {
571 refuse(w.name, a.orphan, w.account);
572 continue;
573 }
574 if (h?.firewall === true) continue;
575 step(creates, {
576 kind: "firewall",
577 name: w.name,
578 account: w.account,
579 cents: 0,
580 says: `Put ${w.name} behind a ${isProvider(provider) ? LABEL[provider] : provider} firewall: only ports 80 and 443 open, no charge`,
581 });
582 calls += 1;
583 }
584
510585 if (complete)
511586 for (const h of have) {
512587 if (seen.has(h.name) || h.state === "retired") continue;
@@ -574,6 +649,8 @@ export interface Facts {
574649 readonly address: boolean;
575650 readonly dns: boolean;
576651 readonly answered: boolean;
652 /** A cloud firewall is around the machine. */
653 readonly firewall: boolean;
577654 /** The watch gave up (`stuckWords`); empty while it still waits. */
578655 readonly stuck: string;
579656 /** The experiment it is on now, and its question; empty for none. */
@@ -598,6 +675,8 @@ export interface Hands {
598675 /** What a database want's steps do; absent, a plan with databases is not built here. */
599676 readonly database?: DatabaseHands | undefined;
600677 retire(name: string): Promise<Result<unknown, string>>;
678 /** Put a cloud firewall around the machine. */
679 firewall(name: string): Promise<Result<unknown, string>>;
601680 /** Clear a dead row: failed, nothing at its provider. */
602681 clear(name: string): Result<unknown, string>;
603682 /** Put the want's machine on its experiment, or begin the experiment its new question asks. */
@@ -642,6 +721,8 @@ const doneBy = (s: Step, w: MachineWant | undefined, f: Facts | undefined): bool
642721 if (s.kind === "clear") return f === undefined;
643722 if (f === undefined) return false;
644723 switch (s.kind) {
724 case "firewall":
725 return f.firewall;
645726 case "disk":
646727 return f.volume;
647728 case "machine":
@@ -750,6 +831,12 @@ export async function apply(
750831 if (!r.ok) return failed(s, r.error);
751832 say(s, "done");
752833 done.push(s.index);
834 } else if (s.kind === "firewall") {
835 say(s, "started");
836 const r = await hands.firewall(s.name);
837 if (!finished(s)) return failed(s, r.ok ? `The cloud answered, and ${s.name} has no firewall yet.` : r.error);
838 say(s, "done");
839 done.push(s.index);
753840 } else if (s.kind === "clear") {
754841 say(s, "started");
755842 const r = hands.clear(s.name);
@@ -824,6 +911,7 @@ export function readInfra(app: App): { have: Have[]; reads: Reads; databases: Da
824911 machine: f.machine,
825912 dns: f.dns,
826913 answered: f.answered,
914 firewall: f.firewall,
827915 experiment: f.experiment,
828916 question: f.question,
829917 cents: rowCents(p, prices),
@@ -863,6 +951,7 @@ export function readInfra(app: App): { have: Have[]; reads: Reads; databases: Da
863951 price: (place) => prices.forge(place),
864952 closed: (place) => prices.closed(place),
865953 host: (name, asked) => asked.trim().toLowerCase() || (base === "" ? "" : `${name}.${base}`),
954 firewalls: firewallCloud,
866955 dnsAuto: listCloudAccounts(db).some((a) => a.provider === "cloudflare" && a.writeAllowed),
867956 where: (place) => {
868957 const p = places.get(place);
@@ -888,6 +977,7 @@ function factsOf(app: App, p: Pinned, exps = experiments(app.db).items): Facts {
888977 address: p.address !== "",
889978 dns: (w?.dnsAt ?? "") !== "" || (kept !== undefined && kept.host === p.host && kept.address === p.address && p.address !== ""),
890979 answered: (w?.answeredAt ?? "") !== "",
980 firewall: firewallOf(app.db, p.id) !== undefined,
891981 stuck: w === undefined || w.gaveUpAt === "" ? "" : stuckWords(p.name, w.addressAt !== "", w.dnsAt !== ""),
892982 experiment: on?.id ?? "",
893983 question: on?.question ?? "",
@@ -926,6 +1016,7 @@ function handsOf(app: App, actor: User | undefined): Hands {
9261016 });
9271017 },
9281018 retire: (name) => retirePinned(app, actor, name),
1019 firewall: (name) => firewallPinned(app, actor, name),
9291020 clear: (name) => clearPinned(app, actor, name),
9301021 join: (w) => {
9311022 const r = w.experimentId !== undefined ? attachMachine(app, actor!.id, w.experimentId, w.name) : beginExperiment(app, actor!.id, w.question ?? "", [w.name]);
src/cloud/watch.ts +24 −8
@@ -1,11 +1,12 @@
11 /**
22 * The hourly watch of a cloud account (#16329). The ceiling (`ceiling.ts`) counts only what the
33 * forge's own rows say it made; this reads what the provider shows (DigitalOcean droplets and
4 * volumes, Hetzner servers and volumes: read-only GETs), sorts each thing as the forge's, an
5 * orphan, outside or acknowledged, and prices what is there from the Places catalog beside the
6 * forge's own reckoning and the ceiling.
4 * volumes and firewalls, Hetzner servers, volumes and firewalls: read-only GETs), sorts each thing
5 * as the forge's, an orphan, outside or acknowledged, and prices what is there from the Places
6 * catalog beside the forge's own reckoning and the ceiling.
77 *
8 * - forge's: its id is on a live pinned row (a machine of a row not retired; a volume of any row).
8 * - forge's: its id is on a live pinned row (a machine of a row not retired; a volume of any row; a
9 * firewall the forge recorded, #17070).
910 * - orphan: named as the forge names things (`forge-<name>`, `forge-<name>-data`) with no live row.
1011 * - outside: not named so, and not acknowledged by an admin as not the forge's.
1112 * - acknowledged: an admin said so (`ackWatch`); it is priced but raises nothing.
@@ -16,6 +17,7 @@
1617
1718 import type { Database } from "bun:sqlite";
1819 import { listPinned } from "../core/pinned.ts";
20 import { firewallIds } from "../core/pinned_firewall.ts";
1921 import { getCloudAccount } from "../core/cloud_account.ts";
2022 import { accountCents, priced, type Priced } from "./ceiling.ts";
2123 import { VOLUME_GIB } from "./places.ts";
@@ -51,28 +53,41 @@ async function pages(f: Fetch, token: string, base: string, key: string, per: nu
5153 throw new Error(`more than ${MAX_PAGES * per} ${key}: not read whole`);
5254 }
5355
54 /** Every machine and volume the account shows. Throws when any read fails: nothing is guessed. */
56 /**
57 * A firewall is read only when it is named as the forge names its own (`forge-<name>`): one made by
58 * hand is the person's, and is neither the forge's nor a stray it should raise.
59 */
60 const forgeFirewalls = (list: any[]): any[] => list.filter((x) => FORGE_NAMED.test(String(x.name)));
61
62 /**
63 * Every machine, volume and forge-named firewall the account shows. Throws when any read fails:
64 * nothing is guessed.
65 */
5566 export async function readLive(provider: string, f: Fetch, token: string): Promise<Seen[]> {
5667 const per = PER_PAGE[provider];
5768 if (per === undefined) throw new Error(`${provider} is not watched`);
5869 if (provider === "digitalocean") {
5970 const api = "https://api.digitalocean.com/v2";
60 const [d, v] = [await pages(f, token, `${api}/droplets`, "droplets", per), await pages(f, token, `${api}/volumes`, "volumes", per)];
71 const [d, v, w] = [await pages(f, token, `${api}/droplets`, "droplets", per), await pages(f, token, `${api}/volumes`, "volumes", per), await pages(f, token, `${api}/firewalls`, "firewalls", per)];
6172 return [
6273 ...d.map((x): Seen => ({ kind: "machine", id: text(x.id), name: text(x.name), createdAt: text(x.created_at), datacenter: text(x.region?.slug), size: text(x.size_slug), gib: 0 })),
6374 ...v.map((x): Seen => ({ kind: "volume", id: text(x.id), name: text(x.name), createdAt: text(x.created_at), datacenter: text(x.region?.slug), size: "", gib: Number(x.size_gigabytes) || VOLUME_GIB })),
75 ...forgeFirewalls(w).map((x): Seen => ({ kind: "firewall", id: text(x.id), name: text(x.name), createdAt: text(x.created_at), datacenter: "", size: "", gib: 0 })),
6476 ];
6577 }
6678 const api = "https://api.hetzner.cloud/v1";
67 const [s, v] = [await pages(f, token, `${api}/servers`, "servers", per), await pages(f, token, `${api}/volumes`, "volumes", per)];
79 const [s, v, w] = [await pages(f, token, `${api}/servers`, "servers", per), await pages(f, token, `${api}/volumes`, "volumes", per), await pages(f, token, `${api}/firewalls`, "firewalls", per)];
6880 return [
6981 ...s.map((x): Seen => ({ kind: "machine", id: text(x.id), name: text(x.name), createdAt: text(x.created), datacenter: text(x.datacenter?.location?.name), size: text(x.server_type?.name), gib: 0 })),
7082 ...v.map((x): Seen => ({ kind: "volume", id: text(x.id), name: text(x.name), createdAt: text(x.created), datacenter: text(x.location?.name), size: "", gib: Number(x.size) || VOLUME_GIB })),
83 ...forgeFirewalls(w).map((x): Seen => ({ kind: "firewall", id: text(x.id), name: text(x.name), createdAt: text(x.created), datacenter: "", size: "", gib: 0 })),
7184 ].filter((x) => x.id !== "");
7285 }
7386
7487 /** What a thing costs a month at list price, cents rounded up; null when the catalog has none. */
7588 export function priceOf(provider: string, s: Seen, prices: Priced): number | null {
89 // Firewalls are free at both clouds the forge makes them on.
90 if (s.kind === "firewall") return 0;
7691 if (s.kind === "volume") {
7792 const per = prices.volume(provider);
7893 return per === undefined ? null : Math.ceil((per * s.gib) / VOLUME_GIB);
@@ -96,6 +111,7 @@ export function judge(db: Database, provider: string, account: string, seen: rea
96111 const rows = listPinned(db).filter((p) => p.target === provider && p.account === account);
97112 const machines = new Set(rows.filter((p) => p.state !== "retired" && p.remote !== "").map((p) => p.remote));
98113 const volumes = new Set(rows.filter((p) => p.volume !== "").map((p) => p.volume));
114 const walls = firewallIds(db, provider, account);
99115 // A deploy in flight has its machine at the provider before its row holds the id: a forge-named
100116 // thing of a row not retired, or one made within the grace, is the forge's own.
101117 const named = new Set(rows.filter((p) => p.state !== "retired").flatMap((p) => [`forge-${p.name}`, `forge-${p.name}-data`]));
@@ -105,7 +121,7 @@ export function judge(db: Database, provider: string, account: string, seen: rea
105121 };
106122 const acked = ackedIds(db, provider, account);
107123 return seen.map((s) => {
108 const mine = (s.kind === "machine" ? machines.has(s.id) : volumes.has(s.id)) || (FORGE_NAMED.test(s.name) && (named.has(s.name) || young(s)));
124 const mine = (s.kind === "machine" ? machines.has(s.id) : s.kind === "firewall" ? walls.has(s.id) : volumes.has(s.id)) || (FORGE_NAMED.test(s.name) && (named.has(s.name) || young(s)));
109125 const verdict: Verdict = mine ? "forge" : acked.has(`${s.kind}:${s.id}`) ? "acknowledged" : FORGE_NAMED.test(s.name) ? "orphan" : "outside";
110126 return { ...s, verdict, cents: priceOf(provider, s, prices) };
111127 });
src/cloud/watch_read.ts +2 −2
@@ -10,9 +10,9 @@ export const CLOUD_PAGE = "/settings/cloud";
1010
1111 export type Verdict = "forge" | "orphan" | "outside" | "acknowledged";
1212
13 /** One machine or volume as the provider shows it. */
13 /** One machine, volume or firewall as the provider shows it. */
1414 export interface Seen {
15 readonly kind: "machine" | "volume";
15 readonly kind: "machine" | "volume" | "firewall";
1616 readonly id: string;
1717 readonly name: string;
1818 readonly createdAt: string;
src/core/migration-pins/20261201150000-pinned-firewall.pin added +1
@@ -0,0 +1,1 @@
1 b4bb78826fdebdc6d70082f55d09851bf1715c49b1d4663edeaef002e54a39de
src/core/migrations/20261201150000-pinned-firewall.ts added +9
@@ -0,0 +1,9 @@
1 // The cloud firewall the forge made around a pinned machine (#17070, #16696): its id at the
2 // provider, one row a forge, gone when the forge retires and the firewall is deleted. Additive.
3 export default `
4 CREATE TABLE pinned_firewall (
5 pinned_id TEXT PRIMARY KEY,
6 remote TEXT NOT NULL,
7 created_at TEXT NOT NULL
8 );
9 `;
src/core/pinned_firewall.ts added +27
@@ -0,0 +1,27 @@
1 /**
2 * The firewall of a pinned forge (#17070): the id the provider gave it, kept so a retire deletes it
3 * and the hourly watch knows it is the forge's. Plain rows; the calls are `cloud/firewall.ts`.
4 */
5
6 import type { Database } from "bun:sqlite";
7
8 /** The provider's id of a forge's firewall; undefined when it has none. */
9 export const firewallOf = (db: Database, pinnedId: string): string | undefined =>
10 db.query<{ remote: string }, [string]>("SELECT remote FROM pinned_firewall WHERE pinned_id = ?1").get(pinnedId)?.remote;
11
12 export function setFirewall(db: Database, pinnedId: string, remote: string, at = new Date().toISOString()): void {
13 db.query("INSERT INTO pinned_firewall (pinned_id, remote, created_at) VALUES (?1, ?2, ?3) ON CONFLICT(pinned_id) DO UPDATE SET remote = excluded.remote").run(pinnedId, remote, at);
14 }
15
16 export const clearFirewall = (db: Database, pinnedId: string): void => void db.query("DELETE FROM pinned_firewall WHERE pinned_id = ?1").run(pinnedId);
17
18 /** Every firewall id the forge holds for the account's rows, for the watch to call its own. */
19 export const firewallIds = (db: Database, provider: string, account: string): Set<string> =>
20 new Set(
21 db
22 .query<{ remote: string }, [string, string]>(
23 "SELECT f.remote FROM pinned_firewall f JOIN pinned_forge p ON p.id = f.pinned_id WHERE p.target = ?1 AND p.account = ?2",
24 )
25 .all(provider, account)
26 .map((r) => r.remote),
27 );
src/generated/migrations.ts +4 −2
@@ -450,7 +450,8 @@ import m445 from "../core/migrations/20261201130000-game-box-boot.ts";
450450 import m446 from "../core/migrations/20261201140000-app-registry-item.ts";
451451 import m447 from "../core/migrations/20261201140000-infra-snapshot.ts";
452452 import m448 from "../core/migrations/20261201140000-scan-finding-excerpt.ts";
453 import m449 from "../core/migrations/20261201170000-managed-database.ts";
453 import m449 from "../core/migrations/20261201150000-pinned-firewall.ts";
454 import m450 from "../core/migrations/20261201170000-managed-database.ts";
454455
455456 /** Each migration file's name and its default export, in name order. */
456457 export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
@@ -903,5 +904,6 @@ export const MIGRATION_MODULES: readonly (readonly [string, unknown])[] = [
903904 ["20261201140000-app-registry-item.ts", m446],
904905 ["20261201140000-infra-snapshot.ts", m447],
905906 ["20261201140000-scan-finding-excerpt.ts", m448],
906 ["20261201170000-managed-database.ts", m449],
907 ["20261201150000-pinned-firewall.ts", m449],
908 ["20261201170000-managed-database.ts", m450],
907909 ];
src/http/mcp/tools/infra.ts +12 −3
@@ -1,4 +1,4 @@
1 import { buildOf, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
1 import { buildOf, firewallWant, gameWant, planDatabase, goneWords, infraOf, infraSays, machineOf, nameFor, planById, planCompose, planWants, startBuild } from "../../../actions/infra.ts";
22 import { bindBucket, readBucket } from "../../../actions/bucket.ts";
33 import { endsWords, keepPinned } from "../../../actions/pinned.ts";
44 import { EXPERIMENT_WORDS, attachMachine, beginExperiment, findExperiment, recordResult } from "../../../cloud/experiments.ts";
@@ -15,8 +15,8 @@ const s = (v: unknown, max: number): string => str(v).slice(0, max);
1515 export const tool: Tool = {
1616 name: "infra",
1717 listedTo: "admin",
18 doc: "`{ action, id?, want?, question?, names?, result?, bucket? }`: `list` (its `says` names every machine), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a game box `{game: true, where, name?, repo?, host?}` or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `keep`, `begin`, `attach`, `record_result`; `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
19 description: "Machines and spend.",
18 doc: "`{ action, id?, want?, question?, names?, result?, bucket? }`: `list` (its `says` names every machine), `show` an `id` (a plan, an experiment or a machine's name), `plan` a `want` `{app, where, question?, experiment?, days?}` or a firewall `{firewall: name}` or a game box `{game: true, where, name?, repo?, host?}` or Postgres `{database: true, app, where: account@region, size?, secret?}` or dead `names`, `apply` its `id`, `keep`, `begin`, `attach`, `record_result`; `price`/`bind` a `bucket` `{region, name, repo?, stored_gib?, out_gib?}`.",
19 description: "Cloud machines and spend.",
2020 inputSchema: {
2121 type: "object",
2222 properties: {
@@ -68,6 +68,15 @@ export const tool: Tool = {
6868 }
6969 if (action === "plan") {
7070 const w = (typeof args["want"] === "object" && args["want"] !== null ? args["want"] : {}) as Record<string, unknown>;
71 // A firewall around a machine that exists: free, so its plan moves no money.
72 if (typeof w["firewall"] === "string") {
73 const want = firewallWant(ctx.app, s(w["firewall"], 40));
74 if (!want.ok) return bad("incomplete", want.error);
75 const planned = planWants(ctx.app, user, [want.value]);
76 if (!planned.ok) return bad("not_found", "no such tool here");
77 const p = planned.value;
78 return good({ id: p.plan.id, says: p.summary, steps: p.plan.steps.map((x) => x.says), refusals: p.fixes, deltaCents: p.plan.deltaCents });
79 }
7180 // A managed Postgres database (#17074): its URL becomes the app's secret once it is online.
7281 if (w["database"] === true) {
7382 const planned = planDatabase(ctx.app, user, { app: s(w["app"], 140), where: s(w["where"], 260), size: s(w["size"], 40), name: s(w["name"], 40), secret: s(w["secret"], 128) });
test/cloud-watch.test.ts +29 −1
@@ -10,10 +10,12 @@ import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
1111 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
1212 import { acknowledgeWatch, setCeiling } from "../src/actions/cloud_ceiling.ts";
13 import { deployPinned, net } from "../src/actions/pinned.ts";
13 import { deployPinned, firewallPinned, net, retirePinned } from "../src/actions/pinned.ts";
14 import { infraOf } from "../src/actions/infra.ts";
1415 import { cloudOverview } from "../src/cloud/overview.ts";
1516 import { watchNeeds, watchLine, watchAccount, GRACE_MS } from "../src/cloud/watch.ts";
1617 import { getPinned } from "../src/core/pinned.ts";
18 import { firewallOf } from "../src/core/pinned_firewall.ts";
1719 import { createUser, getUserByName } from "../src/core/users.ts";
1820 import { duty } from "../src/maintain/duties/cloud_watch.ts";
1921 import { duties } from "../src/maintain/registry.ts";
@@ -35,6 +37,7 @@ describe("cloud watch", () => {
3537 // What the provider shows besides the forge's own machine, and whether it answers.
3638 let extraDroplets: object[] = [];
3739 let extraVolumes: object[] = [];
40 let extraFirewalls: object[] = [];
3841 let down = false;
3942 const admin = () => getUserByName(app.db, "alice")!;
4043 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
@@ -43,6 +46,7 @@ describe("cloud watch", () => {
4346 const u = new URL(url);
4447 if (down) return json({ message: "boom" }, 500);
4548 const mine = getPinned(app.db, "shop");
49 if (u.pathname === "/v2/firewalls") return json({ firewalls: [...(mine && firewallOf(app.db, mine.id) ? [{ id: "fw-1", name: "forge-shop", created_at: ago(1) }] : []), ...extraFirewalls] });
4650 if (u.pathname === "/v2/droplets") return json({ droplets: [...(mine ? [{ id: Number(mine.remote), name: "forge-shop", size_slug: "s-1vcpu-2gb", region: { slug: "nyc3" }, created_at: ago(5) }] : []), ...extraDroplets] });
4751 return json({ volumes: [...(mine ? [{ id: mine.volume, name: "forge-shop-data", size_gigabytes: 10, region: { slug: "nyc3" }, created_at: ago(5) }] : []), ...extraVolumes] });
4852 };
@@ -62,6 +66,7 @@ describe("cloud watch", () => {
6266 net.fetch = async (url, init) => {
6367 const u = new URL(url);
6468 calls.push(`${init?.method ?? "GET"} ${u.pathname}`);
69 if (u.pathname === "/v2/firewalls") return (init?.method ?? "GET") === "POST" ? json({ firewall: { id: "fw-1" } }, 202) : json({ firewalls: [] });
6570 if ((init?.method ?? "GET") === "GET" && (u.pathname === "/v2/volumes" || u.pathname === "/v2/droplets")) return shown(url);
6671 if (u.pathname === "/v2/volumes") return json({ volume: { id: ++seq } }, 201);
6772 if (u.pathname === "/v2/account/keys") return json({ ssh_key: { id: 4242 } }, 201);
@@ -203,4 +208,27 @@ describe("cloud watch", () => {
203208 extraDroplets = [];
204209 await watch();
205210 });
211
212 test("a firewall (#17070): the forge's own is quiet, a forge-named one with no row is an orphan, one made by hand is not read, and retiring deletes it", async () => {
213 expect(await firewallPinned(app, admin(), "shop")).toMatchObject({ ok: true });
214 expect(await firewallPinned(app, admin(), "shop")).toEqual({ ok: true, value: "shop already has a firewall." });
215 extraFirewalls = [
216 { id: "fw-9", name: "forge-ghost", created_at: ago(3) },
217 { id: "fw-8", name: "office", created_at: ago(30) },
218 ];
219 const r = await watch();
220 const verdict = (id: string) => r.resources.find((x) => x.id === id)?.verdict;
221 expect(verdict("fw-1")).toBe("forge");
222 expect(verdict("fw-9")).toBe("orphan");
223 expect(verdict("fw-8")).toBeUndefined();
224 expect(r.resources.find((x) => x.id === "fw-9")).toMatchObject({ kind: "firewall", cents: 0 });
225 expect(watchNeeds(app.db, NOW.getTime())[0]!.sentence).toContain("orphan: firewall forge-ghost (id fw-9");
226 expect(infraOf(app, admin(), NOW)).toMatchObject({ ok: true, value: { drift: [{ says: "At DigitalOcean, not in your infrastructure: 1 firewall" }] } });
227 // Its lifetime is the machine's: retire deletes it at the provider and forgets its id.
228 calls.length = 0;
229 expect((await retirePinned(app, admin(), "shop")).ok).toBe(true);
230 expect(calls).toContain("DELETE /v2/firewalls/fw-1");
231 expect(firewallOf(app.db, getPinned(app.db, "shop")!.id)).toBeUndefined();
232 extraFirewalls = [];
233 });
206234 });
test/firewall.test.ts added +88
@@ -0,0 +1,88 @@
1 /**
2 * The cloud firewall (#17070): what each cloud is asked for, that an existing one is adopted and
3 * never repeated, that a delete finds the thing gone and is done, and that the retire's delete on
4 * Hetzner lets go of the machines first. The cloud is a recorded fetch.
5 */
6 import { describe, expect, test } from "bun:test";
7 import { digitalocean } from "../src/cloud/droplet.ts";
8 import { ensureFirewall, NO_FIREWALL, removeFirewall } from "../src/cloud/firewall.ts";
9 import { hetzner } from "../src/cloud/hetzner.ts";
10 import { ovh } from "../src/cloud/ovh.ts";
11
12 type Seen = { method: string; path: string; body: any };
13 function cloud(api: string, listed: object[], status = 200) {
14 const seen: Seen[] = [];
15 const f = async (url: string, init?: RequestInit): Promise<Response> => {
16 const u = new URL(url);
17 const method = init?.method ?? "GET";
18 seen.push({ method, path: u.pathname + u.search, body: typeof init?.body === "string" ? JSON.parse(init.body) : undefined });
19 if (status !== 200) return new Response("{}", { status });
20 if (method === "GET") return Response.json({ firewalls: listed });
21 if (method === "POST" && u.pathname.endsWith("/firewalls")) return Response.json({ firewall: { id: api.includes("hetzner") ? 4321 : "fw-new" } }, { status: 201 });
22 return new Response(null, { status: 204 });
23 };
24 return { f, seen };
25 }
26
27 describe("firewall", () => {
28 test("DigitalOcean: web in, everything out, applied by the forge's tag", async () => {
29 const c = cloud(digitalocean.api, []);
30 expect(await ensureFirewall(digitalocean, c.f, "tok", "shop")).toBe("fw-new");
31 const post = c.seen.find((s) => s.method === "POST")!;
32 expect(post.path).toBe("/v2/firewalls");
33 expect(post.body.name).toBe("forge-shop");
34 expect(post.body.tags).toEqual(["forge:shop"]);
35 expect(post.body.inbound_rules.map((r: any) => r.ports)).toEqual(["80", "443"]);
36 expect(post.body.inbound_rules.every((r: any) => r.protocol === "tcp" && r.sources.addresses.includes("0.0.0.0/0"))).toBe(true);
37 expect(post.body.outbound_rules.map((r: any) => r.protocol)).toEqual(["tcp", "udp", "icmp"]);
38 });
39
40 test("Hetzner: web in only, labelled, applied by the forge's label", async () => {
41 const c = cloud(hetzner.api, []);
42 expect(await ensureFirewall(hetzner, c.f, "tok", "shop")).toBe("4321");
43 expect(c.seen[0]!.path).toBe("/v1/firewalls?name=forge-shop");
44 const post = c.seen.find((s) => s.method === "POST")!;
45 expect(post.body.rules.map((r: any) => `${r.direction}:${r.port}`)).toEqual(["in:80", "in:443"]);
46 expect(post.body.apply_to).toEqual([{ type: "label_selector", label_selector: { selector: "forge=shop" } }]);
47 expect(post.body.labels).toEqual({ "forge-pinned": "true", forge: "shop" });
48 });
49
50 test("one the cloud already has under the name is adopted, not made again", async () => {
51 const c = cloud(digitalocean.api, [{ id: "fw-old", name: "forge-shop" }, { id: "fw-x", name: "forge-shop2" }]);
52 expect(await ensureFirewall(digitalocean, c.f, "tok", "shop")).toBe("fw-old");
53 expect(c.seen.map((s) => s.method)).toEqual(["GET"]);
54 });
55
56 test("a cloud's refusal is thrown in its own words; a cloud without firewalls says so", async () => {
57 await expect(ensureFirewall(hetzner, cloud(hetzner.api, [], 403).f, "tok", "shop")).rejects.toThrow("api.hetzner.cloud answered 403");
58 await expect(ensureFirewall(ovh, cloud("https://ca.api.ovh.com", []).f, "tok", "shop")).rejects.toThrow(NO_FIREWALL);
59 });
60
61 test("Hetzner lets go of the machines, then deletes; DigitalOcean deletes; a missing id or one already gone is no error", async () => {
62 const h = cloud(hetzner.api, []);
63 await removeFirewall(hetzner, h.f, "tok", "shop", "4321");
64 expect(h.seen.map((s) => `${s.method} ${s.path}`)).toEqual(["POST /v1/firewalls/4321/actions/remove_from_resources", "DELETE /v1/firewalls/4321"]);
65 const d = cloud(digitalocean.api, []);
66 await removeFirewall(digitalocean, d.f, "tok", "shop", "fw-old");
67 expect(d.seen.map((s) => `${s.method} ${s.path}`)).toEqual(["DELETE /v2/firewalls/fw-old"]);
68 await removeFirewall(digitalocean, cloud(digitalocean.api, [], 404).f, "tok", "shop", "fw-old");
69 await expect(removeFirewall(digitalocean, d.f, "tok", "shop", "../x")).rejects.toThrow("no id the forge can delete");
70 await removeFirewall(ovh, d.f, "tok", "shop", "whatever");
71 });
72 });
73
74 describe("firewall lookup on DigitalOcean", () => {
75 test("finds its own firewall on a later page rather than making a duplicate", async () => {
76 const seen: string[] = [];
77 const f = async (url: string, init?: RequestInit): Promise<Response> => {
78 const u = new URL(url);
79 seen.push(`${init?.method ?? "GET"} ${u.pathname}${u.search}`);
80 const page = Number(u.searchParams.get("page"));
81 const rows = page === 1 ? Array.from({ length: 200 }, (_, i) => ({ id: `x${i}`, name: `hand-${i}` })) : [{ id: "fw-late", name: "forge-shop" }];
82 return Response.json({ firewalls: rows });
83 };
84 expect(await ensureFirewall(digitalocean, f, "tok", "shop")).toBe("fw-late");
85 expect(seen.some((s) => s.startsWith("POST"))).toBe(false);
86 expect(seen).toHaveLength(2);
87 });
88 });
test/helpers/recorded-cloud.ts +24 −6
@@ -7,7 +7,7 @@
77 */
88
99 export type Provider = "digitalocean" | "hetzner";
10 export type Kind = "volume" | "key" | "machine";
10 export type Kind = "volume" | "key" | "machine" | "firewall";
1111 export type Call = { method: string; host: string; path: string; kind: Kind | undefined; auth: string | null; body: any };
1212 /**
1313 * A refusal: the cloud answers `status`, or the connection is cut ("throw"). With `lost` the cloud
@@ -22,10 +22,11 @@ const SHAPES = {
2222 host: "api.digitalocean.com",
2323 volumes: "/v2/volumes",
2424 keys: "/v2/account/keys",
25 firewalls: "/v2/firewalls",
2526 machines: "/v2/droplets",
2627 volume: "vol-1",
2728 },
28 hetzner: { host: "api.hetzner.cloud", volumes: "/v1/volumes", keys: "/v1/ssh_keys", machines: "/v1/servers", volume: 77 },
29 hetzner: { host: "api.hetzner.cloud", volumes: "/v1/volumes", keys: "/v1/ssh_keys", firewalls: "/v1/firewalls", machines: "/v1/servers", volume: 77 },
2930 };
3031
3132 /** The calls a driver makes for one operation, in order, as `METHOD path`. */
@@ -66,7 +67,8 @@ export function recordCloud(opts: { firstMachine?: number; address?: string } =
6667 const machines: any[] = [];
6768 const faults: Required<Fault>[] = [];
6869 /** 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 }[] };
70 const holds = { machines: [] as { id: number; body: any }[], volumes: [] as { id: number | string; body: any }[], firewalls: [] as { id: number | string; body: any }[] };
71 let wall = 0;
7072 let machine = (opts.firstMachine ?? 501) - 1;
7173 const address = opts.address ?? "203.0.113.9";
7274 const json = (o: unknown, status = 200) => new Response(JSON.stringify(o), { status });
@@ -81,9 +83,11 @@ export function recordCloud(opts: { firstMachine?: number; address?: string } =
8183 ? "volume"
8284 : u.pathname.startsWith(s.keys)
8385 ? "key"
84 : u.pathname.startsWith(s.machines)
85 ? "machine"
86 : undefined;
86 : u.pathname.startsWith(s.firewalls)
87 ? "firewall"
88 : u.pathname.startsWith(s.machines)
89 ? "machine"
90 : undefined;
8791 const body = init?.body ? JSON.parse(String(init.body)) : undefined;
8892 calls.push({ method, host: u.host, path: u.pathname, kind, auth: new Headers(init?.headers).get("authorization"), body });
8993 const isCollection = u.pathname === s.volumes || u.pathname === s.machines;
@@ -107,6 +111,20 @@ export function recordCloud(opts: { firstMachine?: number; address?: string } =
107111 const last = u.pathname.split("/").at(-1)!;
108112 const collection = isCollection;
109113 const hz = provider === "hetzner";
114 if (kind === "firewall") {
115 if (last === "remove_from_resources") return json({ actions: [] });
116 if (created) {
117 const id = hz ? 900 + ++wall : `fw-${++wall}`;
118 holds.firewalls.push({ id, body });
119 return json({ firewall: { id } }, 201);
120 }
121 if (method === "GET") {
122 const name = u.searchParams.get("name");
123 return json({ firewalls: holds.firewalls.filter((x) => name === null || x.body.name === name).map((x) => ({ id: x.id, name: x.body.name })) });
124 }
125 holds.firewalls = holds.firewalls.filter((x) => String(x.id) !== last);
126 return hz ? json({}) : new Response(null, { status: 204 });
127 }
110128 if (kind === "key") return created ? json({ ssh_key: { id: KEY } }, 201) : new Response(null, { status: 204 });
111129 if (kind === "volume") {
112130 if (created) {
test/infra-page.test.ts +15
@@ -25,6 +25,7 @@ import { createRepo } from "../src/core/repos.ts";
2525 import { createSession } from "../src/core/sessions.ts";
2626 import { createUser, type User } from "../src/core/users.ts";
2727 import type { Ctx } from "../src/http/context.ts";
28 import { firewallOf } from "../src/core/pinned_firewall.ts";
2829 import { tool } from "../src/http/mcp/tools/infra.ts";
2930 import { serve, type Servers } from "../src/http/server.ts";
3031 import { setBaseDomain } from "../src/settings/pinned_domain.ts";
@@ -404,6 +405,20 @@ describe("infrastructure", () => {
404405 expect(listEvents(app.db, { kind: "pinned.cleared", limit: 5 }).map((e) => e.payload["name"])).toContain("canary");
405406 });
406407
408 test("the MCP plans and applies a firewall around a machine that stands, and says so when there is none (#17070)", async () => {
409 const call = (args: Record<string, unknown>) => tool.run(mcpCtx(), admin, args) as Promise<any>;
410 expect((await call({ action: "plan", want: { firewall: "nothing-here" } })).error).toBeDefined();
411 const planned = await call({ action: "plan", want: { firewall: "shop-test" } });
412 expect(planned.value).toMatchObject({ says: expect.stringContaining("+ 1 firewall"), refusals: [], deltaCents: 0 });
413 expect(planned.value.steps).toEqual(["Put shop-test behind a DigitalOcean firewall: only ports 80 and 443 open, no charge"]);
414 expect((await call({ action: "apply", id: planned.value.id })).ok).toBe(true);
415 await settled(planned.value.id);
416 expect(buildOf(app, admin, planned.value.id)).toMatchObject({ state: "done" });
417 expect(firewallOf(app.db, getPinned(app.db, "shop-test")!.id)).toBe("fw-1");
418 // Planned again, everything exists: nothing to build.
419 expect((await call({ action: "plan", want: { firewall: "shop-test" } })).value.steps).toEqual([]);
420 });
421
407422 test("what ended a month ago and bills nothing is counted in one line, not listed", async () => {
408423 const d = await deployPinned(app, admin, { name: "ancient", host: "", target: "digitalocean", account: "main", app: "ada/shop", source: "https://forge.example.net/ada/shop.git", version: "a".repeat(40), place: "digitalocean:nyc3:s-1vcpu-2gb" });
409424 if (!d.ok) throw new Error(d.error);
test/infra-plan-apply.test.ts +36 −4
@@ -10,11 +10,12 @@ import { tmpdir } from "node:os";
1010 import { join } from "node:path";
1111 import { createApp, type App } from "../src/app.ts";
1212 import { addAccount, allowWrite, net as cloudNet } from "../src/actions/cloud.ts";
13 import { net } from "../src/actions/pinned.ts";
13 import { net, retirePinned } from "../src/actions/pinned.ts";
1414 import { WATCH } from "../src/actions/pinned_watch.ts";
1515 import { beginExperiment } from "../src/cloud/experiments.ts";
16 import { apply, DNS_BY_HAND, plan, readInfra, type MachineWant } from "../src/cloud/plan.ts";
16 import { apply, DNS_BY_HAND, plan, readInfra, type FirewallWant, type MachineWant } from "../src/cloud/plan.ts";
1717 import { getPinned } from "../src/core/pinned.ts";
18 import { firewallOf } from "../src/core/pinned_firewall.ts";
1819 import { markStep, startWatchRow } from "../src/core/pinned_watch.ts";
1920 import { createUser, getUserByName } from "../src/core/users.ts";
2021 import { quietLogs } from "./helpers/globals.ts";
@@ -133,13 +134,44 @@ describe("infrastructure plan on a forge", () => {
133134 expect(plan(p.wants, after.have, after.reads).steps).toEqual([]);
134135 });
135136
137 test("a firewall for the machine that stands (#17070): planned free, applied through the pinned action, adopted not repeated, and gone with the machine", async () => {
138 const { have, reads } = readInfra(app);
139 const wall: FirewallWant = { kind: "firewall", name: "shop", account: "digitalocean/main" };
140 const p = plan([wall], have, reads);
141 expect(p.steps.map((s) => s.kind)).toEqual(["firewall"]);
142 expect(p.deltaCents).toBe(0);
143 expect(await apply(app, admin(), p)).toEqual({ ok: true, value: { planId: p.id, done: [0], skipped: [] } });
144 expect(cloud.holds.firewalls).toHaveLength(1);
145 expect(firewallOf(app.db, getPinned(app.db, "shop")!.id)).toBe("fw-1");
146 expect(app.db.query("SELECT 1 FROM event WHERE kind = 'pinned.firewalled'").all()).toHaveLength(1);
147 // Planned afresh there is nothing left to do, and the same plan applied again asks nothing.
148 const after = readInfra(app);
149 expect(plan([wall], after.have, after.reads).steps).toEqual([]);
150 const calls = cloud.calls.length;
151 expect((await apply(app, admin(), p)).ok).toBe(true);
152 expect(cloud.calls.length).toBe(calls);
153 });
154
136155 test("a complete set retires what is not in it through the pinned retire, keeping its data", async () => {
137156 const { have, reads } = readInfra(app);
138157 const p = plan([], have, reads, { complete: true });
139158 expect(p.steps.map((s) => `${s.kind}:${s.name}`)).toEqual(["retire:shop"]);
140 const r = await apply(app, admin(), p);
141 expect(r.ok && r.value.done).toEqual([0]);
159 // The provider refuses the firewall's delete once: the machine is gone and the forge retired,
160 // the firewall's id kept so a second retire can finish.
161 cloud.fail({ method: "DELETE", kind: "firewall" });
162 const first = await apply(app, admin(), p);
163 expect(first.ok).toBe(true);
164 expect(getPinned(app.db, "shop")).toMatchObject({ state: "retired", remote: "" });
165 const id = firewallOf(app.db, getPinned(app.db, "shop")!.id);
166 expect(id).toBe("fw-1");
167 expect(cloud.holds.firewalls).toHaveLength(1);
168 cloud.mend();
169 const again = await retirePinned(app, admin(), "shop");
170 expect(again.ok).toBe(true);
142171 expect(getPinned(app.db, "shop")).toMatchObject({ state: "retired", remote: "" });
143172 expect(getPinned(app.db, "shop")!.volume).not.toBe("");
173 // The firewall went with the machine, at the provider and in the row.
174 expect(cloud.holds.firewalls).toEqual([]);
175 expect(firewallOf(app.db, getPinned(app.db, "shop")!.id)).toBeUndefined();
144176 });
145177 });
test/infra-plan.test.ts +71
@@ -5,6 +5,8 @@
55 * step that stops the run, and a rerun that skips what exists. No database, no network.
66 */
77 import { describe, expect, test } from "bun:test";
8 import { firewallCloud } from "../src/cloud/drivers.ts";
9 import { NO_FIREWALL } from "../src/cloud/firewall.ts";
810 import { refusalOf } from "../src/cloud/ceiling.ts";
911 import { EXPERIMENT_WORDS } from "../src/cloud/experiments.ts";
1012 import {
@@ -13,6 +15,7 @@ import {
1315 plan,
1416 type Facts,
1517 type Hands,
18 type FirewallWant,
1619 type Have,
1720 type MachineWant,
1821 type Plan,
@@ -39,6 +42,7 @@ function reads(accounts: Record<string, Acct> = { "digitalocean/main": {}, "hetz
3942 ? undefined
4043 : { writable: x.writable ?? true, ceilingDollars: x.ceilingDollars ?? 50, monthlyCents: x.monthlyCents ?? 0, orphan: x.orphan };
4144 },
45 firewalls: (provider) => provider === "digitalocean" || provider === "hetzner",
4246 price: (p) => PRICES[p],
4347 closed: () => undefined,
4448 host: (name, asked) => asked || `${name}.forges.test`,
@@ -78,12 +82,14 @@ const have = (name: string, over: Partial<Have> = {}): Have => ({
7882 machine: true,
7983 dns: true,
8084 answered: true,
85 firewall: false,
8186 experiment: "",
8287 question: "",
8388 cents: 1300,
8489 keptCents: 100,
8590 ...over,
8691 });
92 const wall = (name: string, account = "digitalocean/main"): FirewallWant => ({ kind: "firewall", name, account });
8793 const kinds = (p: Plan) => p.steps.map((s) => `${s.kind}:${s.name}`);
8894
8995 describe("plan", () => {
@@ -323,6 +329,7 @@ describe("apply", () => {
323329 address: false,
324330 dns: false,
325331 answered: false,
332 firewall: false,
326333 stuck: "",
327334 experiment: "",
328335 question: "",
@@ -348,6 +355,11 @@ describe("apply", () => {
348355 rows.set(name, fact({ ...rows.get(name), state: "retired", machine: false }));
349356 return ok({});
350357 },
358 firewall: async (name) => {
359 calls.push(`firewall ${name}`);
360 rows.set(name, { ...rows.get(name)!, firewall: true });
361 return ok({});
362 },
351363 join: (w) => {
352364 const id = w.experimentId ?? "new";
353365 calls.push(`attach ${w.name} ${id}`);
@@ -415,6 +427,7 @@ describe("apply", () => {
415427 address: false,
416428 dns: false,
417429 answered: false,
430 firewall: false,
418431 stuck: "",
419432 experiment: "",
420433 question: "",
@@ -489,4 +502,62 @@ describe("apply", () => {
489502 expect(w.calls).toEqual([]);
490503 expect(w.events).toEqual([]);
491504 });
505
506 test("apply puts it up, skips it when it stands, and stops on the cloud's refusal", async () => {
507 const w = world();
508 w.rows.set("shop", w.fact());
509 const p = plan([wall("shop")], [have("shop")], reads());
510 const r = await apply(APP, ADMIN, p, w.hands);
511 expect(r).toEqual(ok({ planId: p.id, done: [0], skipped: [] }));
512 expect(w.calls).toEqual(["firewall shop"]);
513 expect(w.events.map((e) => e.state)).toEqual(["started", "done"]);
514 const again = await apply(APP, ADMIN, p, w.hands);
515 expect(again).toEqual(ok({ planId: p.id, done: [], skipped: [0] }));
516
517 const bad = world();
518 bad.rows.set("shop", bad.fact());
519 bad.hands.firewall = async () => err("The cloud refused: api.digitalocean.com answered 422");
520 const stopped = await apply(APP, ADMIN, p, bad.hands);
521 expect(stopped).toEqual(ok({ planId: p.id, done: [], skipped: [], failed: { index: 0, why: "The cloud refused: api.digitalocean.com answered 422" } }));
522 });
523 });
524
525 describe("firewall", () => {
526
527 test("a firewall for an existing machine is one free step that moves no money", () => {
528 const p = plan([wall("shop")], [have("shop")], reads());
529 expect(kinds(p)).toEqual(["firewall:shop"]);
530 expect(p.steps[0]!.says).toBe("Put shop behind a DigitalOcean firewall: only ports 80 and 443 open, no charge");
531 expect(p.steps[0]!.cents).toBe(0);
532 expect(p.deltaCents).toBe(0);
533 expect(p.refusals).toEqual([]);
534 expect(p.byAccount[0]).toMatchObject({ beforeCents: 0, afterCents: 0, fits: true });
535 expect(p.etaSeconds).toBe(20);
536 });
537
538 test("a machine that has one gets no second", () => {
539 expect(plan([wall("shop")], [have("shop", { firewall: true })], reads()).steps).toEqual([]);
540 });
541
542 test("a machine planned in the same plan is behind it too, after its steps", () => {
543 const p = plan([want("shop"), wall("shop")], [], reads());
544 expect(kinds(p).filter((k) => k.startsWith("firewall") || k.startsWith("machine"))).toEqual(["machine:shop", "firewall:shop"]);
545 expect(p.deltaCents).toBe(1300);
546 });
547
548 test("refused: no machine, a retired one, another account, a read-only account, an orphan, a cloud without firewalls", () => {
549 const why = (w: FirewallWant, h: Have[], r = reads()) => plan([w], h, r).refusals.map((x) => x.why);
550 expect(why(wall("shop"), [])).toEqual(["shop has no machine on digitalocean/main to put a firewall around."]);
551 expect(why(wall("shop"), [have("shop", { state: "retired", machine: false })])).toHaveLength(1);
552 expect(why(wall("shop", "hetzner/main"), [have("shop")])).toHaveLength(1);
553 expect(why(wall("shop"), [have("shop")], reads({ "digitalocean/main": { writable: false } }))).toEqual([READ_ONLY]);
554 expect(why(wall("shop"), [have("shop")], reads({ "digitalocean/main": { orphan: "an orphan stands" } }))).toEqual(["an orphan stands"]);
555 expect(why(wall("shop", "ovh/main"), [have("shop", { account: "ovh/main" })], reads({ "ovh/main": {} }))).toEqual([`${NO_FIREWALL} OVHcloud US has none to make.`]);
556 expect(why(wall("shop", "nowhere/x"), [have("shop")])).toEqual([NO_ACCOUNT]);
557 expect(plan([wall("shop"), wall("shop")], [have("shop")], reads()).refusals.map((x) => x.why)).toEqual([NAME_TAKEN]);
558 });
559
560 test("the drivers that can make one are DigitalOcean's and Hetzner's", () => {
561 expect(["digitalocean", "hetzner", "ovh"].map(firewallCloud)).toEqual([true, true, false]);
562 });
492563 });
test/managed-database.test.ts +2 −1
@@ -49,6 +49,7 @@ function reads(over: { writable?: boolean; ceilingDollars?: number; monthlyCents
4949 ? { writable: true, ceilingDollars: 50, monthlyCents: 0 }
5050 : undefined,
5151 price: () => undefined,
52 firewalls: () => false,
5253 closed: () => undefined,
5354 host: () => "",
5455 dnsAuto: true,
@@ -128,7 +129,7 @@ describe("planning a database", () => {
128129 // A name a machine already holds is not given to a database.
129130 const machine: Have = {
130131 kind: "machine", name: "shop-db", account: "digitalocean/main", place: "x", app: "", source: "", version: "", host: "", state: "running",
131 volume: true, machine: true, dns: false, answered: true, experiment: "", question: "", cents: 0, keptCents: 0,
132 volume: true, machine: true, dns: false, answered: true, firewall: false, experiment: "", question: "", cents: 0, keptCents: 0,
132133 };
133134 expect(why(plan([want()], [machine], reads()))).toEqual([NAME_TAKEN]);
134135 // Refused for a reason that is not the ceiling: no create is planned.
test/pinned-ceiling.test.ts +11 −8
@@ -335,9 +335,10 @@ describe("cloud account ceiling", () => {
335335 });
336336
337337 test("every use of a cloud driver that can make something is held to the ceiling", () => {
338 // A driver is only ever taken through `capped`, or handed to `read`, `retire` or a snapshot
339 // call (#17072), which make no machine; a snapshot's few cents are not counted against the
340 // ceiling. A new call site that provisions or replaces with a bare driver fails here.
338 // A driver is only ever taken through `capped`, or handed to `read`, `retire`, a snapshot call
339 // (#17072) or a firewall (free: it moves no money, and its plan still refuses on an orphan,
340 // #17070), which make no machine; a snapshot's few cents are not counted against the ceiling.
341 // A new call site that provisions or replaces with a bare driver fails here.
341342 const files = (dir: string): string[] =>
342343 readdirSync(dir, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? files(join(dir, e.name)) : e.name.endsWith(".ts") ? [join(dir, e.name)] : []));
343344 const src = join(import.meta.dir, "../src");
@@ -350,16 +351,18 @@ describe("cloud account ceiling", () => {
350351 if (/^import\b[^\n]*$/.test(text.slice(text.lastIndexOf("\n", m.index) + 1, m.index))) continue;
351352 uses++;
352353 const before = text.slice(Math.max(0, m.index - 80), m.index);
353 if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire|strays|snapshotKind|takeSnapshot|readSnapshot|dropSnapshot)\($/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`);
354 if (!/\bcapped\(app, [\w.]+, $/.test(before) && !/\b(?:read|retire|strays|ensureFirewall|removeFirewall|snapshotKind|takeSnapshot|readSnapshot|dropSnapshot)\($/.test(before)) bare.push(`${file.slice(src.length + 1)}: …${before.slice(-40)}driverOf(`);
354355 }
355356 }
356357 expect(bare).toEqual([]);
357358 // Deploy, update or rollback (asked, then made), a new claim link, the read, the retire and the
358 // strays and filing in a project (#16340): the seven there are, and the five of snapshots
359 // strays and filing in a project (#16340): the seven there are; the five of snapshots
359360 // (#17072), all in actions/infra_snapshot.ts: snapshotKind twice (the offer, and the check
360 // before one is taken), takeSnapshot, readSnapshot and dropSnapshot. A bare driverOf still
361 // fails the pattern above; only those five call names are let through.
362 expect(uses).toBe(13);
361 // before one is taken), takeSnapshot, readSnapshot and dropSnapshot; and the firewall made and
362 // removed (#17070): neither can spend, as a firewall is free at both clouds and each only
363 // finds, makes or deletes that one firewall, never a machine or a volume. A bare driverOf still
364 // fails the pattern above; only those call names are let through.
365 expect(uses).toBe(15);
363366 });
364367 });
365368

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs