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

The game agent puts the proxy's pinned jars in place before an up #17679

opened this

Merged 18h 37m ago, live in production

sold/game-jars → main 0 commits

  • Merged. sold/game-jars was merged into main as 2aa328e.

Review

Sign in to review this change.
2 files changed +238 −0
src/games/agent.sh +86
@@ -769,12 +769,97 @@ job_tick() {
769769 # shellcheck disable=SC2086,SC2016 # the verb and its words, each a safe name; the script is single-quoted on purpose
770770 if [ "${args%% *}" = world ]; then
771771 DOCKER="$DOCKER" DIR="$DIR" bash -c 'world_job "$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "$JOB_MARK" ${args#world } &
772 elif [ "${args%% *}" = up ]; then
773 DOCKER="$DOCKER" DIR="$DIR" bash -c 'up_job "$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "$JOB_MARK" $args &
772774 else
773775 DIR="$DIR" bash -c '"$@" >"$DIR/.up.log" 2>&1; echo $? >"$DIR/.job.rc"' "$JOB_MARK" "${COMPOSE[@]}" $args &
774776 fi
775777 echo $! >"$DIR/.job.pid"
776778 }
777779
780 # ---- the proxy's own jars: the answer's `jars` ({name, url, sha256}) come with its compose file, which
781 # mounts jars/ read-only at /forge-jars and names each file in the proxy's PLUGINS. They are fetched and
782 # checked before an up. When one is missing or wrong, the proxy is left as it is and the rest comes up. ----
783
784 # The AutoStopper the image fetches from Modrinth (games/sleep.ts): its project, and its jar's sha512.
785 AUTOSTOPPER_PROJECT="PG4gqnzX"
786 AUTOSTOPPER_SHA512="${FORGE_GAME_AUTOSTOPPER_SHA512:-066bbc8b7ac41d8f360cb28de41a78b260843cd0f10af328f49a51bf37e4c52c63b258bfd73c783d7c649e6fe233a1153f7f062aa8c2cf952bbc5192d265361c}"
787
788 # Every jar in place with its sha256, or 1. The image skips a file of the same name and size, so a name
789 # holds its sha256's first 12 characters. A link can be signed: it is never on a command line or said.
790 jars_ready() {
791 local name url sha next
792 jq -e 'type == "array" and length <= 8 and all(.[];
793 (.sha256 | test("\\A[0-9a-f]{64}\\z")) and (.url | test("\\Ahttps?://[^\\s\"\\\\]+\\z"))
794 and (.name | test("\\A[A-Za-z0-9][A-Za-z0-9._-]{0,99}[.]jar\\z")) and (.sha256[0:12] as $s | .name | contains($s)))' \
795 "$DIR/.jars.json" >/dev/null 2>&1 || { echo "the jars the forge named are not as they should be"; return 1; }
796 mkdir -p "$DIR/jars" && chmod 0755 "$DIR/jars" || return 1
797 while IFS=$'\t' read -r name url sha <&3; do
798 [ "$(sha256sum "$DIR/jars/$name" 2>/dev/null | cut -d' ' -f1)" = "$sha" ] && continue
799 next="$DIR/.jar.next"
800 printf 'url = "%s"\n' "$url" >"$DIR/.jar.curl"
801 curl -fsSL --proto '=https,http' --max-filesize 67108864 -m 120 --retry 3 -K "$DIR/.jar.curl" -o "$next" 2>/dev/null
802 rm -f "$DIR/.jar.curl"
803 if [ "$(sha256sum "$next" 2>/dev/null | cut -d' ' -f1)" != "$sha" ]; then
804 rm -f "$next"
805 echo "$name could not be fetched with sha256 $sha"
806 return 1
807 fi
808 chmod 0644 "$next" && mv "$next" "$DIR/jars/$name" || return 1
809 done 3< <(jq -r '.[] | [.name, .url, .sha256] | @tsv' "$DIR/.jars.json")
810 }
811 # Rename the AutoStopper the image fetched, in the proxy's plugins folder: from *$1 to what $2 makes of
812 # it. A helper container has the proxy's volumes, running or not; only a regular file moves.
813 autostopper_mv() {
814 local cid
815 cid="$(compose ps -a -q velocity 2>/dev/null | head -n 1)"
816 [ -n "$cid" ] || return 0
817 "$DOCKER" run --rm --network none --volumes-from "$cid" -w /server "$HELPER" sh -euc "[ ! -L plugins ] && cd plugins 2>/dev/null || exit 0
818 for f in *$1; do
819 [ -f \"\$f\" ] && [ ! -L \"\$f\" ] || continue
820 [ \"\$(sha512sum < \"\$f\" | cut -d' ' -f1)\" = '$AUTOSTOPPER_SHA512' ] || continue
821 mv \"\$f\" \"$2\"
822 echo \"$3: \$f sha512 $AUTOSTOPPER_SHA512\"
823 done"
824 }
825 # Ours and the image's have one id, and Velocity loads only one of them. While the compose file still
826 # names the project, the image would fetch its jar again, so it stays.
827 autostopper_aside() {
828 jq -e 'any(.[]; .name | startswith("AutoStopper-"))' "$DIR/.jars.json" >/dev/null 2>&1 || return 0
829 grep -q "$AUTOSTOPPER_PROJECT" "$DIR/compose.yml" && return 0
830 : >"$DIR/.jar.aside"
831 autostopper_mv .jar "\$f.aside" "moved aside"
832 }
833 # Only what this up moved (an interrupted one counts) comes back.
834 autostopper_back() {
835 [ -f "$DIR/.jar.aside" ] || return 0
836 autostopper_mv .jar.aside "\${f%.aside}" "put back" && rm -f "$DIR/.jar.aside"
837 }
838 # `compose up …`, with the jars first when the forge named any.
839 up_job() {
840 local rc rest
841 if [ ! -s "$DIR/.jars.json" ]; then
842 compose "$@"
843 return
844 fi
845 if jars_ready && autostopper_aside; then
846 compose "$@"
847 rc=$?
848 if [ "$rc" = 0 ]; then rm -f "$DIR/.jar.aside"; else autostopper_back; fi
849 return "$rc"
850 fi
851 autostopper_back
852 echo "the proxy is left as it is"
853 # An up of one service is a person's recreate: nothing else is touched for it.
854 [ "${*: -1}" = --remove-orphans ] || return 1
855 rest="$(compose config --services 2>/dev/null | grep -vx velocity)"
856 # shellcheck disable=SC2086 # service names, one word each
857 [ -z "$rest" ] || compose up -d --no-deps --remove-orphans $rest
858 return 1
859 }
860 export -f jars_ready autostopper_mv autostopper_aside autostopper_back up_job
861 export AUTOSTOPPER_PROJECT AUTOSTOPPER_SHA512
862
778863 # ---- the owner's shell (#17151 V4): `bash -lc` under `capped`, at most FORGE_GAME_SHELL_S
779864 # seconds (30) with no terminal and no input, so an interactive program ends at once; its output,
780865 # at most 16 KB, is the command's result at the next sync. Each runs beside the sync. ----
@@ -814,6 +899,7 @@ apply() {
814899 if jq -e 'has("compose") and (.compose | type == "string")' <<<"$answer" >/dev/null 2>&1 &&
815900 [ "$sha" != "$(cat "$DIR/.compose-sha" 2>/dev/null)" ] && [ "$sha" != "$(cat "$DIR/.up.failed" 2>/dev/null)" ]; then
816901 jq -j '.compose' <<<"$answer" >"$DIR/compose.yml.next" && mv "$DIR/compose.yml.next" "$DIR/compose.yml"
902 jq -c '.jars // empty' <<<"$answer" >"$DIR/.jars.json.next" && mv "$DIR/.jars.json.next" "$DIR/.jars.json"
817903 changed=1
818904 fi
819905 while IFS= read -r name <&3; do
test/game-jars.test.ts added +152
@@ -0,0 +1,152 @@
1 /**
2 * The proxy's own jars: pinned by sha256, fetched to a folder the proxy only reads, and checked before
3 * an `up` that starts the proxy. A jar that is missing or wrong holds back the proxy alone. The
4 * AutoStopper the image fetched is moved aside by its sha512, and comes back when the `up` fails.
5 * Docker here is a script that writes down what it was asked.
6 */
7 import { afterEach, expect, test } from "bun:test";
8 import { createHash } from "node:crypto";
9 import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
10 import { rm } from "node:fs/promises";
11 import { tmpdir } from "node:os";
12 import { join } from "node:path";
13 import { AUTOSTOPPER, AUTOSTOPPER_SHA512 } from "../src/games/sleep.ts";
14 import { pollUntil } from "./helpers/poll.ts";
15
16 const AGENT = join(import.meta.dir, "../src/games/agent.sh");
17 const cleanups: (() => Promise<void>)[] = [];
18 afterEach(async () => {
19 for (const c of cleanups.splice(0)) await c();
20 });
21 const sha = (kind: "sha256" | "sha512", text: string): string => createHash(kind).update(text).digest("hex");
22 const OLD = "the AutoStopper the image fetched";
23 const JAR = "our AutoStopper";
24 const NAME = `AutoStopper-${sha("sha256", JAR).slice(0, 12)}.jar`;
25
26 /** A box whose forge hands out `compose` and `jars`, and serves `served` as every jar. */
27 function made(o: { compose?: string; jars?: boolean; served?: string; upFails?: boolean; name?: string }) {
28 const root = mkdtempSync(join(tmpdir(), "forge-game-jars-"));
29 const dir = join(root, "game");
30 const plugins = join(root, "server/plugins");
31 mkdirSync(plugins, { recursive: true });
32 writeFileSync(join(plugins, "AutoStopper-3.0.0.jar"), OLD);
33 writeFileSync(join(plugins, "other.jar"), "another plugin");
34 const fake = join(root, "docker");
35 writeFileSync(
36 fake,
37 `#!/usr/bin/env bash
38 case "$*" in
39 *" config --services"*) printf 'velocity\\nhub\\nsurvival\\n' ;;
40 *" ps -a -q velocity"*) echo c1 ;;
41 "run "*"--volumes-from c1"*) cd "${root}/server" && exec sh -euc "\${@: -1}" ;;
42 *" up "*)
43 all="$*"
44 echo "up \${all#* up }" >>"${root}/ups"
45 ls "${plugins}" >"${root}/at-up"
46 ls "${dir}/jars" >"${root}/jars-at-up" 2>/dev/null
47 exit ${o.upFails === true ? "1" : "0"} ;;
48 esac
49 exit 0
50 `,
51 );
52 chmodSync(fake, 0o755);
53 const compose = o.compose ?? "services: {}\n";
54 const forge: ReturnType<typeof Bun.serve> = Bun.serve({
55 port: 0,
56 hostname: "127.0.0.1",
57 fetch(req): Response {
58 if (new URL(req.url).pathname === "/jar") return new Response(o.served ?? JAR);
59 const jars = [{ name: o.name ?? NAME, url: `http://127.0.0.1:${String(forge.port)}/jar?sig=secret`, sha256: sha("sha256", JAR) }];
60 return Response.json({ composeSha: sha("sha256", compose), compose, commands: [], ...(o.jars === false ? {} : { jars }) });
61 },
62 });
63 cleanups.push(async () => {
64 forge.stop(true);
65 await rm(root, { recursive: true, force: true });
66 });
67 /** Run the agent until its first job has ended and been reaped. */
68 const run = async (): Promise<void> => {
69 const p = Bun.spawn(["bash", AGENT], {
70 env: {
71 PATH: process.env["PATH"] ?? "",
72 FORGE_URL: `http://127.0.0.1:${String(forge.port)}`,
73 FORGE_GAME_TOKEN: "fgb_abcdefghijklmnopqrstuvwxyz0123456789ABCDEFG",
74 FORGE_GAME_DIR: dir,
75 FORGE_GAME_DOCKER: fake,
76 FORGE_GAME_AUTOSTOPPER_SHA512: sha("sha512", OLD),
77 FORGE_GAME_DIAG_S: "0",
78 FORGE_GAME_VOLUME_CHECK: "0",
79 FORGE_GAME_ONCE: "0",
80 },
81 stdout: "ignore",
82 stderr: "ignore",
83 });
84 try {
85 await pollUntil(() => existsSync(join(dir, ".job.last")), "the job to end", 30_000);
86 } finally {
87 p.kill();
88 await p.exited;
89 }
90 };
91 const read = (f: string): string => (existsSync(join(root, f)) ? readFileSync(join(root, f), "utf8") : "");
92 return { dir, plugins, run, read, log: () => readFileSync(join(dir, ".up.log"), "utf8") };
93 }
94
95 test("the agent moves aside the jar the forge pins, and no other", () => {
96 const agent = readFileSync(AGENT, "utf8");
97 expect(agent.includes(AUTOSTOPPER_SHA512)).toBe(true);
98 expect(agent.includes(`AUTOSTOPPER_PROJECT="${AUTOSTOPPER.split(":")[0]!}"`)).toBe(true);
99 });
100
101 test("without jars, an up is what it was", async () => {
102 const box = made({ jars: false });
103 await box.run();
104 expect(box.read("ups")).toBe("up -d --remove-orphans\n");
105 expect(existsSync(join(box.dir, "jars"))).toBe(false);
106 expect(readdirSync(box.plugins).sort()).toEqual(["AutoStopper-3.0.0.jar", "other.jar"]);
107 });
108
109 test("a jar is checked and in place before the up, readable, and the old AutoStopper is aside", async () => {
110 const box = made({});
111 await box.run();
112 expect(box.read("ups")).toBe("up -d --remove-orphans\n");
113 expect(box.read("jars-at-up")).toBe(`${NAME}\n`);
114 expect(readFileSync(join(box.dir, "jars", NAME), "utf8")).toBe(JAR);
115 expect(statSync(join(box.dir, "jars", NAME)).mode & 0o777).toBe(0o644);
116 expect(statSync(join(box.dir, "jars")).mode & 0o777).toBe(0o755);
117 expect(box.read("at-up").trim().split("\n").sort()).toEqual(["AutoStopper-3.0.0.jar.aside", "other.jar"]);
118 expect(readdirSync(box.plugins).sort()).toEqual(["AutoStopper-3.0.0.jar.aside", "other.jar"]);
119 expect(box.log()).toContain(`AutoStopper-3.0.0.jar sha512 ${sha("sha512", OLD)}`);
120 expect(box.log()).not.toContain("sig=secret");
121 });
122
123 test("an up that fails puts the old AutoStopper back", async () => {
124 const box = made({ upFails: true });
125 await box.run();
126 expect(box.read("at-up")).toContain("AutoStopper-3.0.0.jar.aside");
127 expect(readdirSync(box.plugins).sort()).toEqual(["AutoStopper-3.0.0.jar", "other.jar"]);
128 expect(readFileSync(join(box.dir, ".up.failed"), "utf8")).not.toBe("");
129 });
130
131 test("while the compose file still fetches AutoStopper, its jar stays", async () => {
132 const box = made({ compose: `# MODRINTH_PROJECTS: ${AUTOSTOPPER}\nservices: {}\n` });
133 await box.run();
134 expect(box.read("at-up")).toContain("AutoStopper-3.0.0.jar\n");
135 });
136
137 for (const [why, o] of [
138 ["whose sha256 differs", { served: "something else" }],
139 ["whose name lacks its sha256", { name: "AutoStopper-3.0.0-forge.1.jar" }],
140 ["whose name is a path", { name: `../${NAME}` }],
141 ] as const)
142 test(`a jar ${why} holds back the proxy alone, and nothing is moved`, async () => {
143 const box = made(o);
144 await box.run();
145 expect(box.read("ups")).toBe("up -d --no-deps --remove-orphans hub survival\n");
146 const jars = join(box.dir, "jars");
147 expect(existsSync(jars) ? readdirSync(jars) : []).toEqual([]);
148 expect(readdirSync(box.plugins).sort()).toEqual(["AutoStopper-3.0.0.jar", "other.jar"]);
149 expect(box.log()).toContain("the proxy is left as it is");
150 expect(existsSync(join(box.dir, ".compose-sha"))).toBe(false);
151 expect(readFileSync(join(box.dir, ".up.failed"), "utf8")).not.toBe("");
152 });

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

Keyboard shortcuts

Docs