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

A game box's boot token is spent at its first sync #17649

opened this

Merged 20h 28m ago, live in production

sold/game-token → main 0 commits

  • Merged. sold/game-token was merged into main as 6e291aa.

Review

Sign in to review this change.
6 files changed +284 −6
docs/features/games.md +2
@@ -91,6 +91,8 @@ A name in chat is trusted only because players reach the backends through Veloci
9191
9292 ## Secrets
9393
94 The token a box boots with is spent at its first sync: the box makes its own, sends only its sha256, and keeps it in `agent.env` and, with the one before, in `.tokens` (both mode 600). Refused, the box tries the others, one a sync, and keeps the one the forge answers. So a forge restored from a backup made before the swap answers the boot's token again until the box's own is taken anew, and a boot config written again on the same machine does no harm. A forge restored from before the machine itself knows neither: that box needs a new machine (Replace).
95
9496 The Velocity forwarding secret (`forwarding.env`) and an RCON password a service (`rcon-<service>.env`) are generated once, sealed like every forge secret and sent only in the sync's `env`, never committed. A box token is shown once and stored hashed. An uploaded jar is kept by the forge at `/games/jar/<id>/<name>`; the compose a box gets carries it signed for 6 hours, and only for the box that uploaded it. A jar must be a `.jar` (a zip), at most 64 MiB, and a box keeps at most 20 jars and 256 MiB.
9597
9698 The environment editor refuses a key that looks like a secret (`PASSWORD`, `SECRET`, `TOKEN`, `KEY` in its name): a secret belongs in the sealed `.env` the forge writes to the box, never in the repository. An env or plugin change is a commit by the person who asks, so it needs write access to the compose repository; without it the forge says to ask the repository's owner.
src/games/agent.sh +63 −4
@@ -28,8 +28,58 @@ umask 077
2828 mkdir -p "$DIR"
2929 cd "$DIR" || exit 1
3030 AUTH="$DIR/.auth"
31 printf 'Authorization: Bearer %s\n' "$FORGE_GAME_TOKEN" >"$AUTH"
31 TOKEN="$FORGE_GAME_TOKEN"
3232 unset FORGE_GAME_TOKEN
33 auth_as() { printf 'Authorization: Bearer %s\n' "$1" >"$AUTH.$$" && mv -f "$AUTH.$$" "$AUTH"; }
34 printf 'Authorization: Bearer %s\n' "$TOKEN" >"$AUTH"
35
36 # ---- the box's own token. The one it booted with stays readable in the machine's boot config, so the
37 # box makes its own, has it on disk, and sends its sha256 until the forge has taken it in the boot's
38 # place. `.tokens` (mode 600) keeps two: the box's own, then the one before. Refused (401), the box
39 # goes through agent.env's and those, one a sync; the one answered goes into agent.env, where any
40 # version of this agent reads it. So a lost answer, a forge restored from before the swap and a boot
41 # config written again each cost a sync or two, not the box. ----
42
43 TOKENS="$DIR/.tokens"
44 ENV_TOKEN="$TOKEN"
45 AT=0
46 sha_of() { printf '%s' "$1" | sha256sum | cut -d' ' -f1; }
47 # Put stdin in place of a file, whole, and on the disk itself: a power cut must not lose a token.
48 keep_file() { cat >"$1.next" && [ -s "$1.next" ] && { command sync "$1.next" 2>/dev/null; mv -f "$1.next" "$1"; }; }
49 # A new token of the box's own, and the one it goes with now as the one before.
50 tokens_new() {
51 local own
52 own="fgb_$(head -c 32 /dev/urandom | base64 | tr '+/' '-_' | tr -d '=\n')"
53 [[ "$own" =~ ^fgb_[A-Za-z0-9_-]{43}$ ]] && printf '%s\n%s\n' "$own" "$TOKEN" | keep_file "$TOKENS"
54 }
55 # The sha256 this sync offers: the box's own, while it goes with the one before. Nothing where no env file keeps it.
56 token_offer() {
57 grep -q '^FORGE_GAME_TOKEN=' "$DIR/agent.env" 2>/dev/null || return 0
58 [ -s "$TOKENS" ] || tokens_new || return 0
59 [ "$(sed -n 2p "$TOKENS")" = "$TOKEN" ] && sha_of "$(head -n 1 "$TOKENS")"
60 }
61 # The forge refused the token (401): the next one, round and round.
62 token_refused() {
63 local t all=("$ENV_TOKEN")
64 while IFS= read -r t; do [ -n "$t" ] && [ "$t" != "$ENV_TOKEN" ] && all+=("$t"); done < <(cat "$TOKENS" 2>/dev/null)
65 AT=$(((AT + 1) % ${#all[@]}))
66 TOKEN="${all[AT]}"
67 auth_as "$TOKEN"
68 }
69 # The forge answered a sync: the token it went with, or the own one the forge says it took, is agent.env's.
70 token_answered() {
71 [ -s "$TOKENS" ] || return 0
72 if [ "$(jq -r '.tokenSha // ""' <<<"$1" 2>/dev/null)" = "$(sha_of "$(head -n 1 "$TOKENS")")" ]; then
73 TOKEN="$(head -n 1 "$TOKENS")"
74 auth_as "$TOKEN"
75 fi
76 # One from a newer boot config: the two kept are another's, and a new one is offered.
77 grep -qxF -- "$TOKEN" "$TOKENS" || tokens_new
78 [ "$TOKEN" = "$ENV_TOKEN" ] && return 0
79 { grep -v '^FORGE_GAME_TOKEN=' "$DIR/agent.env"; printf 'FORGE_GAME_TOKEN=%s\n' "$TOKEN"; } | keep_file "$DIR/agent.env" || return 0
80 ENV_TOKEN="$TOKEN"
81 AT=0
82 }
3383
3484 SAFE='^[A-Za-z0-9._-]{1,64}$'
3585 WAKER=forge-waker
@@ -990,7 +1040,7 @@ export -f world_job world_steps world_cid world_sh world_level world_index world
9901040 export WORLDS HELPER
9911041
9921042 sync() {
993 local next answer
1043 local next answer code
9941044 next="$(now)"
9951045 # Each part through a file, checked as JSON on the way: a sync can pass the 128 KB one argument
9961046 # may hold (200 log lines from each of several servers), and then curl would never run.
@@ -1020,6 +1070,7 @@ sync() {
10201070 --slurpfile chat "$DIR/.sync.chat" \
10211071 --argjson retry "$([ -f "$DIR/.sync.retry" ] && echo true || echo false)" \
10221072 --arg lend "$(lend_has)" \
1073 --arg tokenSha "$(token_offer)" \
10231074 'def sect: {"0":"r","1":"l","4":"n","22":"r","24":"r","39":"r","30":"0","31":"4","32":"2","33":"6","34":"1","35":"5","36":"3","37":"7","90":"8","91":"c","92":"a","93":"e","94":"9","95":"d","96":"b","97":"f"} as $t
10241075 | ["30","31","32","33","34","35","36","37","90","91","92","93","94","95","96","97"] as $sixteen
10251076 # 38;5;n is one of the sixteen colours by its number; a background (48) and the other
@@ -1031,13 +1082,21 @@ sync() {
10311082 (if . == "" then ["0"] else split(";") end) | [codes[] | $t[.] // empty | "\u00a7" + .] | join("");
10321083 def plain: gsub("\u001b\\[(?<p>[0-9;]*)m"; (.p // "" | sect)) | gsub("^(\u00a7r)+|(\u00a7r)+$"; "") | gsub("(\u00a7r)+"; "\u00a7r") | gsub("\u001b\\[[0-9;?]*[ -/]*[@-~]"; "") | gsub("\u001b[@-_]?"; "") | gsub("[\u0001-\u0008\u000b\u000c\u000e-\u001f\u007f]"; "");
10331084 {agent: 1, composeSha: $sha, services: $services[0], logs: $logs[0], results: $results[0], host: $host[0], diag: $diag[0], people: $people[0], metrics: $metrics[0], snapshots: $snapshots[0], chat: $chat[0].lines, chatId: $chat[0].id, lend: $lend, retry: $retry}
1085 + (if $tokenSha == "" then {} else {tokenSha: $tokenSha} end)
10341086 | walk(if type == "string" then plain else . end)' >"$DIR/.sync.body" || return 1
1035 answer="$(curl -fsS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" "${FORGE_URL%/}/api/v1/games/agent/sync")" || {
1087 # The answer is never a file: it can carry a world's signed link. Its status is its last line.
1088 answer="$(curl -sS -m 20 -H "@$AUTH" -H 'content-type: application/json' --data-binary "@$DIR/.sync.body" -w '\n%{http_code}' "${FORGE_URL%/}/api/v1/games/agent/sync")" || answer=$'\nnothing'
1089 code="${answer##*$'\n'}"
1090 answer="${answer%$'\n'*}"
1091 if [[ "$code" != 2?? ]]; then
1092 echo "forge-game-agent: the forge answered the sync $code" >&2
1093 [ "$code" = 401 ] && token_refused
10361094 # The forge may have kept this body before the answer was lost: the next says so, and it
10371095 # skips the log lines it already holds, so a console never shows a line twice.
10381096 : >"$DIR/.sync.retry"
10391097 return 1
1040 }
1098 fi
1099 token_answered "$answer"
10411100 rm -f "$DIR/.sync.retry"
10421101 # Delivered: the results and the log lines are the forge's now.
10431102 echo '[]' >"$DIR/.results"
src/games/boot.ts +2 −1
@@ -4,7 +4,8 @@
44 * forge's (no password or root login, updates, `harden.ts`); then a firewall that lets in only the
55 * game's port (25565/tcp; no SSH, as a forge has none), swap for the JVMs, Docker with its compose
66 * plugin (Ubuntu's own packages) keeping its data on the box's volume, and the agent (`agent.sh`) under systemd. The token
7 * is in one place only: `/opt/forge-game/agent.env`, mode 600, which the unit reads.
7 * is in one place only: `/opt/forge-game/agent.env`, mode 600, which the unit reads. The boot's is spent at
8 * the first sync: the box makes its own and keeps it there (`agent.sh`).
89 */
910
1011 import agentScript from "./agent.sh" with { type: "text" };
src/games/store.ts +15
@@ -142,6 +142,19 @@ export function rotateGameBoxToken(db: Database, id: string): string {
142142 return token;
143143 }
144144
145 /**
146 * The box's own token in place of the one it came with, by its hash (the box never sends it). Only
147 * for the token still in use, and a hash no other box has; whether it is the box's hash now.
148 */
149 export function swapGameBoxToken(db: Database, id: string, presented: string, sha: unknown): boolean {
150 if (typeof sha !== "string" || !/^[0-9a-f]{64}$/.test(sha)) return false;
151 return (
152 db
153 .query("UPDATE game_box SET token_hash = ?3 WHERE id = ?1 AND token_hash = ?2 AND NOT EXISTS (SELECT 1 FROM game_box o WHERE o.token_hash = ?3 AND o.id <> ?1)")
154 .run(id, sha256(presented), sha).changes === 1
155 );
156 }
157
145158 export const listBoxes = (db: Database): GameBox[] => db.query<BoxRow, []>("SELECT * FROM game_box ORDER BY name").all().map(toBox);
146159 export const boxNamed = (db: Database, name: string): GameBox | undefined => {
147160 const r = db.query<BoxRow, [string]>("SELECT * FROM game_box WHERE name = ?1").get(name);
@@ -471,6 +484,8 @@ export interface SyncBody {
471484 readonly lend?: unknown;
472485 /** The box's word about its boot, sent without jq when a tool is missing or by the boot's report. */
473486 readonly boot?: string;
487 /** The sha256 of the token the box made for itself, until the forge has taken it. */
488 readonly tokenSha?: unknown;
474489 /** What the box sees of itself, about 8 KB (`diag.ts`): kept, replacing the last. */
475490 readonly diag?: unknown;
476491 /** Each service's world snapshots (`worlds.ts`). */
src/http/games_routes.ts +3 −1
@@ -14,7 +14,7 @@ import { packChecks } from "../games/pack_check.ts";
1414 import { lendAnswer } from "../games/lend.ts";
1515 import { recordProxyEvents, tellRefused } from "../games/player_events.ts";
1616 import { proxyOf, sleeping } from "../games/sleep.ts";
17 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, type SyncBody } from "../games/store.ts";
17 import { boxByToken, envFiles, markAsleep, recordSync, signJarUrls, swapGameBoxToken, type SyncBody } from "../games/store.ts";
1818 import { BODY_CAPS } from "../kernel/body_caps.ts";
1919 import {
2020 gameBoxPage, gameCommandSubmit, gameCrashShare, gameEnvSubmit, gameGrantSubmit, gameLendSubmit, gameServersSubmit, gameJarDownload, gameJarSubmit, gameModInstall, gameModPack, gameModRemove, gameModUpdate, gamePeopleSubmit, gameHead, gameWorldSubmit, gamePowerSubmit, gameSleepSubmit, gameServicePage, gameSettingsSubmit, gameServiceStream, gameShellStream, gameShellSubmit, gamesPage,
@@ -78,6 +78,8 @@ export async function gameAgentSync(ctx: Ctx): Promise<Response> {
7878 // The runner token of "Run checks while servers sleep", once; or the word to drop it.
7979 const lend = lendAnswer(ctx.app.db, box, body.lend);
8080 if (lend !== undefined) reply["lend"] = lend;
81 // The box's own token takes the boot's place, last: whatever failed above changed nothing.
82 if (body.tokenSha !== undefined && swapGameBoxToken(ctx.app.db, box.id, auth.slice(7).trim(), body.tokenSha)) reply["tokenSha"] = body.tokenSha;
8183 return json(reply);
8284 }
8385
test/game-token.test.ts added +199
@@ -0,0 +1,199 @@
1 /**
2 * A game box's boot token is spent at its first sync: the box makes its own, sends only the hash, and
3 * the forge takes that in place of the boot's. The new token is on the box's disk before the forge
4 * hears of it, so an answer that is lost, or an agent stopped in between, never cuts the box off.
5 */
6 import { afterEach, expect, test } from "bun:test";
7 import { chmodSync, mkdirSync, mkdtempSync, readFileSync, statSync, writeFileSync } from "node:fs";
8 import { rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp } from "../src/app.ts";
12 import { boxByToken, createGameBox, rotateGameBoxToken, swapGameBoxToken } from "../src/games/store.ts";
13 import { forgeHttp } from "../src/http/server.ts";
14 import { sha256 } from "../src/kernel/hash.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { pollUntil } from "./helpers/poll.ts";
17
18 quietLogs();
19
20 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
21 const lacks = ["bash", "curl", "jq", "sha256sum"].filter((t) => Bun.which(t) === null);
22 const cleanups: (() => Promise<void>)[] = [];
23 afterEach(async () => {
24 for (const c of cleanups.splice(0)) await c();
25 });
26
27 /** A box with its boot's env file, and the forge; `meddle` may change or lose what a sync is answered. */
28 function made(meddle: (n: number, answer: Response) => Response | Promise<Response> = (_n, a) => a) {
29 const root = mkdtempSync(join(tmpdir(), "forge-game-token-"));
30 const dir = join(root, "game");
31 mkdirSync(dir);
32 const app = createApp({ dataDir: join(root, "data"), port: 0 });
33 const http = forgeHttp(app);
34 const { id, token: boot } = createGameBox(app.db, { name: "mc" });
35 let n = 0;
36 const bodies: string[] = [];
37 const forge = Bun.serve({
38 port: 0,
39 hostname: "127.0.0.1",
40 async fetch(req) {
41 bodies.push(await req.clone().text());
42 const answer = await http.handle(req);
43 n += 1;
44 if (!answer.ok) return answer;
45 // The agent under test stays itself: no update is offered.
46 const body = { ...((await answer.json()) as object), agentSha: "" };
47 return meddle(n, Response.json(body));
48 },
49 });
50 const url = `http://127.0.0.1:${String(forge.port)}`;
51 const env = join(dir, "agent.env");
52 writeFileSync(env, `FORGE_URL=${url}\nFORGE_GAME_TOKEN=${boot}\nFORGE_GAME_DATA=\n`, { mode: 0o600 });
53 writeFileSync(join(root, "docker"), "#!/usr/bin/env bash\nexit 0\n");
54 chmodSync(join(root, "docker"), 0o755);
55 cleanups.push(async () => {
56 forge.stop(true);
57 app.close();
58 await rm(root, { recursive: true, force: true });
59 });
60 const kept = (): string => /^FORGE_GAME_TOKEN=(.*)$/m.exec(readFileSync(env, "utf8"))![1]!;
61 /** One sync of the agent, or a run `until` so, its environment read from the file as systemd does. */
62 const run = async (until?: () => boolean): Promise<void> => {
63 const p = Bun.spawn(["bash", AGENT], {
64 env: {
65 PATH: process.env["PATH"] ?? "",
66 FORGE_GAME_DIR: dir,
67 FORGE_GAME_DOCKER: join(root, "docker"),
68 FORGE_GAME_DIAG_S: "0",
69 FORGE_GAME_VOLUME_CHECK: "0",
70 FORGE_GAME_ONCE: until === undefined ? "1" : "0",
71 FORGE_GAME_EVERY: "0.2",
72 },
73 stdout: "ignore",
74 stderr: "ignore",
75 });
76 if (until !== undefined) {
77 await pollUntil(until, "the agent to get there", 30_000);
78 p.kill();
79 }
80 await p.exited;
81 };
82 const knows = (token: string): boolean => boxByToken(app.db, token) !== undefined;
83 return { app, id, boot, dir, env, bodies, kept, run, knows };
84 }
85
86 const agentTest = test.skipIf(lacks.length > 0);
87
88 agentTest("the boot's token stops at the first sync; the box's own is kept in its env file, mode 600, and never sent", async () => {
89 const b = made();
90 await b.run();
91 const own = b.kept();
92 expect(own).toMatch(/^fgb_[A-Za-z0-9_-]{43}$/);
93 expect(own).not.toBe(b.boot);
94 expect(b.knows(b.boot)).toBe(false);
95 expect(b.knows(own)).toBe(true);
96 expect(statSync(b.env).mode & 0o777).toBe(0o600);
97 expect(readFileSync(b.env, "utf8")).toContain("FORGE_URL=http://127.0.0.1:");
98 expect(b.bodies.join()).not.toContain(own);
99 // Once: the next runs keep it.
100 await b.run();
101 expect(b.kept()).toBe(own);
102 expect(b.knows(own)).toBe(true);
103 }, 60_000);
104
105 agentTest("an answer that is lost, and an agent that stopped there, cost a sync and not the box", async () => {
106 const b = made((n, a) => (n === 1 ? new Response("", { status: 502 }) : a));
107 await b.run();
108 // The forge took the new token; the box did not hear so.
109 expect(b.knows(b.boot)).toBe(false);
110 expect(b.kept()).toBe(b.boot);
111 // Refused with the old one, it goes on with the new one, and keeps it once that is answered.
112 await b.run(() => b.kept() !== b.boot);
113 expect(b.knows(b.kept())).toBe(true);
114 // The next start needs nothing else.
115 const before = b.bodies.length;
116 await b.run();
117 expect(b.bodies.length).toBe(before + 1);
118 expect(b.knows(b.kept())).toBe(true);
119 }, 60_000);
120
121 agentTest("a forge that does not know of it leaves the box on its boot token", async () => {
122 const b = made(async (_n, a) => {
123 const { tokenSha: _gone, ...rest } = (await a.json()) as Record<string, unknown>;
124 return Response.json(rest);
125 });
126 // As an older forge: the hash is neither taken nor answered.
127 b.app.db.exec("CREATE TRIGGER older BEFORE UPDATE OF token_hash ON game_box BEGIN SELECT RAISE(IGNORE); END");
128 await b.run();
129 await b.run();
130 expect(b.kept()).toBe(b.boot);
131 expect(b.knows(b.boot)).toBe(true);
132 }, 60_000);
133
134 /** What the forge knows a box by. */
135 const known = (b: ReturnType<typeof made>): string => b.app.db.query<{ h: string }, [string]>("SELECT token_hash AS h FROM game_box WHERE id = ?1").get(b.id)!.h;
136
137 agentTest("a forge restored from before the swap answers the boot's token, and takes the box's own again", async () => {
138 const b = made();
139 await b.run();
140 const own = b.kept();
141 expect(own).not.toBe(b.boot);
142 b.app.db.query("UPDATE game_box SET token_hash = ?2 WHERE id = ?1").run(b.id, sha256(b.boot));
143 await b.run(() => known(b) !== sha256(b.boot) && sha256(b.kept()) === known(b));
144 expect(b.knows(b.boot)).toBe(false);
145 expect(statSync(b.env).mode & 0o777).toBe(0o600);
146 expect(statSync(join(b.dir, ".tokens")).mode & 0o777).toBe(0o600);
147 }, 60_000);
148
149 agentTest("a boot config written again on the machine leaves the box on its own token", async () => {
150 const b = made();
151 await b.run();
152 const own = b.kept();
153 writeFileSync(b.env, readFileSync(b.env, "utf8").replace(own, b.boot));
154 await b.run(() => b.kept() === own);
155 expect(known(b)).toBe(sha256(own));
156 }, 60_000);
157
158 agentTest("a newer boot config's token is followed by a new own one, never the one kept from before", async () => {
159 const b = made();
160 await b.run();
161 const own = b.kept();
162 const newer = rotateGameBoxToken(b.app.db, b.id);
163 writeFileSync(b.env, readFileSync(b.env, "utf8").replace(own, newer));
164 await b.run(() => b.kept() !== newer);
165 expect([own, b.boot, newer]).not.toContain(b.kept());
166 expect(known(b)).toBe(sha256(b.kept()));
167 }, 60_000);
168
169 agentTest("refused with every token, it goes on asking at its pace and keeps them all", async () => {
170 const b = made();
171 await b.run();
172 const files = (): string[] => [b.env, join(b.dir, ".tokens")].map((f) => readFileSync(f, "utf8"));
173 const before = files();
174 b.app.db.query("UPDATE game_box SET token_hash = 'none' WHERE id = ?1").run(b.id);
175 const from = b.bodies.length;
176 const began = Date.now();
177 await b.run(() => b.bodies.length >= from + 5);
178 // No faster than its pace, 0.2 s here.
179 expect(Date.now() - began).toBeGreaterThan(800);
180 expect(files()).toEqual(before);
181 // Known again, it needs nobody.
182 b.app.db.query("UPDATE game_box SET token_hash = ?2 WHERE id = ?1").run(b.id, sha256(b.kept()));
183 await b.run();
184 expect(files()).toEqual(before);
185 }, 60_000);
186
187 test("only the token in use is swapped, for a hash no other box has", () => {
188 const b = made();
189 const other = createGameBox(b.app.db, { name: "other" });
190 const want = sha256("fgb_new");
191 expect(swapGameBoxToken(b.app.db, b.id, b.boot, "not a hash")).toBe(false);
192 expect(swapGameBoxToken(b.app.db, b.id, b.boot, sha256(other.token))).toBe(false);
193 // A machine made meanwhile has a newer token: the old one changes nothing.
194 const newer = rotateGameBoxToken(b.app.db, b.id);
195 expect(swapGameBoxToken(b.app.db, b.id, b.boot, want)).toBe(false);
196 expect(b.knows(newer)).toBe(true);
197 expect(swapGameBoxToken(b.app.db, b.id, newer, want)).toBe(true);
198 expect(b.knows(newer)).toBe(false);
199 });

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

Keyboard shortcuts

Docs