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

Every cloud's boot config is plain ASCII: strings are written as escaped YAML, and anything else is refused #17113

opened this

Merged 41h 1m ago, live in production

fix/boot-config-ascii → main 0 commits

  • Merged. fix/boot-config-ascii was merged into main as 4a4be72.

Review

Sign in to review this change.
5 files changed +115 −13
src/cloud/boot_ascii.ts added +29
@@ -0,0 +1,29 @@
1 /**
2 * Every cloud's boot config is plain ASCII (#17112). One leaf both builders import: the forge's
3 * (`machine.ts`) and the game box's (`games/boot.ts`).
4 */
5
6 /**
7 * A string as a YAML double-quoted scalar made only of ASCII: JSON's escapes, and every character
8 * past 0x7f as `\\uXXXX` (or `\\UXXXXXXXX` past the basic plane), which YAML reads back as the same
9 * text. A cloud's user-data is not always read as UTF-8: a game box's cloud-init dropped its whole
10 * config when a "…" arrived as U+0080 (#17112).
11 */
12 export function yamlString(value: string): string {
13 let out = "";
14 for (const ch of JSON.stringify(value)) {
15 const cp = ch.codePointAt(0)!;
16 out += cp < 0x80 ? ch : cp <= 0xffff ? `\\u${cp.toString(16).padStart(4, "0")}` : `\\U${cp.toString(16).padStart(8, "0")}`;
17 }
18 return out;
19 }
20
21 /**
22 * The one door every driver's user-data goes through: refused, in plain words, when anything in it
23 * is not ASCII, so a byte a cloud reads as another never reaches cloud-init.
24 */
25 export function asciiBoot(config: string): string {
26 const at = config.search(/[^\x00-\x7f]/);
27 if (at >= 0) throw new Error(`this machine's boot config holds a character that is not plain ASCII (at ${at}); escape it before the boot is sent`);
28 return config;
29 }
src/cloud/machine.ts +8 −7
@@ -18,6 +18,7 @@
1818 * a failure half-way leaves a row a retry can finish, never an orphan.
1919 */
2020
21 import { asciiBoot, yamlString } from "./boot_ascii.ts";
2122 import { BUN_PIN } from "../kernel/bun_pin.ts";
2223 import type { Fetch } from "./providers.ts";
2324 import { firstAdminSeed, readSeed } from "../core/first_admin.ts";
@@ -100,7 +101,7 @@ export const proxyConfig = (p: Booted, dataDir: string): string =>
100101 * mounted.
101102 */
102103 const proxyFiles = (p: Booted, dataDir: string): string => ` - path: /etc/caddy/Caddyfile
103 content: ${JSON.stringify(proxyConfig(p, dataDir))}
104 content: ${yamlString(proxyConfig(p, dataDir))}
104105 - path: /etc/systemd/system/caddy.service.d/forge.conf
105106 content: |
106107 [Unit]
@@ -126,7 +127,7 @@ const proxyCommands = (dataDir: string): string => ` - install -d -m 0700 -o ca
126127 * is `harden.ts`. What the boot sets is written after the config, the data directory last.
127128 */
128129 export function bootConfig(p: Booted, dataDir: string, early: readonly string[] = []): string {
129 if (p.game !== undefined) return gameBootConfig(p.game, dataDir);
130 if (p.game !== undefined) return asciiBoot(gameBootConfig(p.game, dataDir));
130131 // A row from before `checkConfig` refused these names may still hold one: it is dropped, so what
131132 // the boot sets is said once and in its own place.
132133 const settings = Object.fromEntries(Object.entries(p.config).filter(([k]) => !BOOT_NAMES.includes(k)));
@@ -135,29 +136,29 @@ export function bootConfig(p: Booted, dataDir: string, early: readonly string[]
135136 .join("\n");
136137 // Every interpolated value is validated in core/pinned.ts (version, source, config, host) or by
137138 // NAME; the seed is checked in servedEnv; dataDir is the driver's own.
138 return `#cloud-config
139 return asciiBoot(`#cloud-config
139140 ${hardenHead()}write_files:
140141 - path: /etc/forge/env
141142 permissions: "0600"
142 content: ${JSON.stringify(env + "\n")}
143 content: ${yamlString(env + "\n")}
143144 ${proxyFiles(p, dataDir)}
144145 - path: ${BUN_INSTALLER}
145146 permissions: "0755"
146 content: ${JSON.stringify(bunInstallScript(BUN_VERSION))}
147 content: ${yamlString(bunInstallScript(BUN_VERSION))}
147148 - path: /etc/systemd/system/forge.service
148149 content: |
149150 ${serviceUnit(p.name, p.version, dataDir).replace(/^(?=.)/gm, " ")}
150151 ${hardenFiles()}
151152 runcmd:
152153 ${hardenEarly()}
153 ${early.map((c) => ` - ${JSON.stringify(c)}\n`).join("")} - ${BUN_INSTALLER}
154 ${early.map((c) => ` - ${yamlString(c)}\n`).join("")} - ${BUN_INSTALLER}
154155 - 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
155156 - git -C ${CHECKOUT} checkout -q --detach FETCH_HEAD
156157 ${hardenLate()}
157158 - npm install -g @anthropic-ai/claude-code || logger -t forge-boot crew not installed, the forge starts without it
158159 - systemctl enable --now forge.service
159160 ${proxyCommands(dataDir)}
160 `;
161 `);
161162 }
162163
163164 /** A machine or volume at the provider that carries a forge's label: its id and its name. */
src/games/boot.ts +6 −5
@@ -9,6 +9,7 @@
99
1010 import agentScript from "./agent.sh" with { type: "text" };
1111 import { hardenFiles } from "../cloud/harden.ts";
12 import { yamlString } from "../cloud/boot_ascii.ts";
1213
1314 /** The one port a game box opens to the world: Velocity's, in front of every backend. */
1415 export const GAME_PORT = 25565;
@@ -65,16 +66,16 @@ disable_root: true
6566 write_files:
6667 - path: ${GAME_DIR}/agent.env
6768 permissions: "0600"
68 content: ${JSON.stringify(env)}
69 content: ${yamlString(env)}
6970 - path: ${GAME_DIR}/agent.sh
7071 permissions: "0755"
71 content: ${JSON.stringify(AGENT_SH)}
72 content: ${yamlString(AGENT_SH)}
7273 - path: /etc/systemd/system/forge-game-agent.service
7374 permissions: "0644"
74 content: ${JSON.stringify(AGENT_UNIT)}
75 content: ${yamlString(AGENT_UNIT)}
7576 - path: /etc/docker/daemon.json
7677 permissions: "0644"
77 content: ${JSON.stringify(daemon + "\n")}
78 content: ${yamlString(daemon + "\n")}
7879 ${hardenFiles()}
7980 runcmd:
8081 - ufw default deny incoming
@@ -83,7 +84,7 @@ runcmd:
8384 - ufw --force enable
8485 - fallocate -l ${SWAP_GIB}G /swapfile && chmod 600 /swapfile && mkswap /swapfile && swapon /swapfile && echo '/swapfile none swap sw 0 0' >> /etc/fstab
8586 - mkdir -p ${dataDir}/docker
86 - ${JSON.stringify(INSTALL)}
87 - ${yamlString(INSTALL)}
8788 - systemctl restart docker || true
8889 - systemctl daemon-reload
8990 - systemctl enable --now forge-game-agent.service
test/boot-config-ascii.test.ts added +70
@@ -0,0 +1,70 @@
1 /**
2 * Every cloud's boot config is plain ASCII (#17112): a game box's cloud-init dropped its whole
3 * user-data when a "…" in it arrived as U+0080, its UTF-8 bytes read as Latin-1 somewhere between
4 * the forge and the cloud. Each driver's config goes through `bootConfig` (`cloud/machine.ts`),
5 * which writes every string as an ASCII-escaped YAML scalar and refuses anything else.
6 */
7 import { describe, expect, test } from "bun:test";
8 import { bootConfig as dropletBoot } from "../src/cloud/droplet.ts";
9 import { bootConfig as hetznerBoot } from "../src/cloud/hetzner.ts";
10 import { asciiBoot, yamlString } from "../src/cloud/boot_ascii.ts";
11 import type { Booted } from "../src/cloud/machine.ts";
12 import { bootConfig as ovhBoot } from "../src/cloud/ovh.ts";
13 import { AGENT_SH } from "../src/games/boot.ts";
14
15 /** A forge whose owner's name and greeting are not ASCII, as a person may set them. */
16 const OWNER = "Zoë Ångström";
17 const GREETING = "Bienvenue… 🙂";
18 const forge: Booted = {
19 name: "acme",
20 source: "https://forge.example.org/trevato/forge",
21 version: "a".repeat(40),
22 config: { FORGE_OWNER_NAME: OWNER, FORGE_GREETING: GREETING },
23 host: "acme.forges.example.com",
24 claimHash: "",
25 claimExpires: "",
26 };
27
28 type Doc = { write_files: { path: string; content: string }[]; runcmd: unknown[] };
29
30 const drivers: [string, () => string][] = [
31 ["DigitalOcean", () => dropletBoot(forge)],
32 ["Hetzner", () => hetznerBoot(forge, "100000001")],
33 ["OVHcloud", () => ovhBoot(forge, "0123456789abcdef0123456789abcdef")],
34 ];
35
36 describe("each cloud's boot config", () => {
37 for (const [cloud, render] of drivers)
38 test(`${cloud}: plain ASCII, and YAML reads the owner's name back as it was set`, () => {
39 const text = render();
40 expect(text).toMatch(/^[\x00-\x7f]*$/);
41 const doc = Bun.YAML.parse(text) as Doc;
42 const env = doc.write_files.find((f) => f.path === "/etc/forge/env")!.content;
43 expect(env).toContain(`FORGE_OWNER_NAME=${OWNER}\n`);
44 expect(env).toContain(`FORGE_GREETING=${GREETING}\n`);
45 });
46 });
47
48 test("a game box's boot, whose agent script says \"…\", is ASCII too and YAML reads the script back whole", () => {
49 const box: Booted = { ...forge, game: { forgeUrl: "https://forge.example.org", token: `fgb_${"a".repeat(43)}` } };
50 const text = dropletBoot(box);
51 expect(text).toMatch(/^[\x00-\x7f]*$/);
52 expect(AGENT_SH).toContain("…");
53 const doc = Bun.YAML.parse(text) as Doc;
54 expect(doc.write_files.some((f) => f.content === AGENT_SH)).toBe(true);
55 });
56
57 describe("the ASCII door", () => {
58 test("a string becomes an ASCII scalar YAML reads back the same, past the basic plane too", () => {
59 for (const s of [OWNER, GREETING, 'quote " and backslash \\', "line\nbreak", ""]) {
60 const scalar = yamlString(s);
61 expect(scalar).toMatch(/^[\x00-\x7f]*$/);
62 expect((Bun.YAML.parse(`v: ${scalar}`) as { v: string }).v).toBe(s);
63 }
64 });
65
66 test("a config with anything not ASCII left in it is refused in plain words, never sent", () => {
67 expect(asciiBoot("#cloud-config\nruncmd:\n - echo ok\n")).toBe("#cloud-config\nruncmd:\n - echo ok\n");
68 expect(() => asciiBoot("#cloud-config\nruncmd:\n - echo …\n")).toThrow("not plain ASCII");
69 });
70 });
test/game-box.test.ts +2 −1
@@ -6,6 +6,7 @@
66 * and the env file (mode 600), brings the project up, runs an rcon command, and sends its result
77 * on the next sync.
88 */
9 import { yamlString } from "../src/cloud/boot_ascii.ts";
910 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
1011 import { chmodSync, existsSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
1112 import { rm } from "node:fs/promises";
@@ -29,7 +30,7 @@ describe("the boot config", () => {
2930
3031 test("carries the agent and its unit, Docker with compose, and swap", () => {
3132 expect(cfg.startsWith("#cloud-config\n")).toBe(true);
32 expect(cfg).toContain(`path: /opt/forge-game/agent.sh\n permissions: "0755"\n content: ${JSON.stringify(AGENT_SH)}`);
33 expect(cfg).toContain(`path: /opt/forge-game/agent.sh\n permissions: "0755"\n content: ${yamlString(AGENT_SH)}`);
3334 expect(cfg).toContain("path: /etc/systemd/system/forge-game-agent.service");
3435 expect(cfg).toContain("systemctl enable --now forge-game-agent.service");
3536 for (const pkg of ["docker.io", "docker-compose-v2", "jq", "curl", "ufw"]) expect(INSTALL).toContain(` ${pkg}`);

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

Keyboard shortcuts

Docs