diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 971f9a6..1a2bfb7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -201,6 +201,12 @@ jobs: - name: Security alerting is honest in both directions run: python3 tests/test_security_alerts.py + # The sync edits the live whitelist from a list fullhearts.app sends. + # This holds it to never touching a player it did not add, and fails + # if compose ever turns on OVERRIDE_WHITELIST. + - name: FullHearts whitelist sync never touches hand-added players + run: python3 tests/test_fullhearts_sync.py + # The design role is what lets a non-op edit the world. Its argument # checks are the whole security boundary, so they are tested against # inputs built to escape them: command blocks, NBT, selectors, chained @@ -212,7 +218,7 @@ jobs: run: | for f in gitops/deploy.sh gitops/install_gitops.sh bootstrap_droplet.sh harden_sshd.sh \ add_admin_user.sh server-audit.sh tests/test_droplet_hardening.sh \ - alerts/security_alert.sh alerts/install_alerts.sh; do + alerts/security_alert.sh alerts/install_alerts.sh gitops/install_fullhearts_sync.sh; do [ -f "$f" ] && bash -n "$f" && echo "OK $f" done diff --git a/gitops/fullhearts-sync.service b/gitops/fullhearts-sync.service new file mode 100644 index 0000000..07f39b4 --- /dev/null +++ b/gitops/fullhearts-sync.service @@ -0,0 +1,27 @@ +[Unit] +Description=Sync website-managed whitelist entries from fullhearts.app +After=docker.service network-online.target +Wants=network-online.target + +[Service] +Type=oneshot +# Token, mode and URL. Root-only, mode 600, never in git (see install_fullhearts_sync.sh). +EnvironmentFile=/etc/educraft-sync.env +# Optional: problems go to the same Discord webhook as the security alerts. +EnvironmentFile=-/etc/minecraft-alerts.env +ExecStart=/usr/bin/python3 /root/minecraft/gitops/fullhearts_sync.py +TimeoutStartSec=120 + +# Needs root only for `docker exec`. It reads the server's data files and +# writes nothing but its own ledger and lock. +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=read-only +ReadWritePaths=/var/lib/educraft-sync /run +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +RestrictSUIDSGID=true +StateDirectory=educraft-sync +StateDirectoryMode=0700 diff --git a/gitops/fullhearts-sync.timer b/gitops/fullhearts-sync.timer new file mode 100644 index 0000000..289eb14 --- /dev/null +++ b/gitops/fullhearts-sync.timer @@ -0,0 +1,11 @@ +[Unit] +Description=Check fullhearts.app for whitelist changes + +[Timer] +OnBootSec=4min +OnUnitActiveSec=2min +RandomizedDelaySec=15 +Unit=fullhearts-sync.service + +[Install] +WantedBy=timers.target diff --git a/gitops/fullhearts_sync.py b/gitops/fullhearts_sync.py new file mode 100755 index 0000000..f3307e2 --- /dev/null +++ b/gitops/fullhearts_sync.py @@ -0,0 +1,359 @@ +#!/usr/bin/env python3 +"""Keep the whitelist in step with paid EduCraft families on fullhearts.app. + +Run by fullhearts-sync.timer every 2 minutes. Each run: + + pull the wanted list from FullHearts -> compare with data/whitelist.json + -> add / remove ONLY players this script added itself -> report back + +THE ONE RULE: never touch a player this script did not add. Anyone put on the +whitelist by hand (WHITELIST in compose, /whitelist in game, rcon-cli) stays +exactly as they are. The script keeps its own ledger of what it added +(/var/lib/educraft-sync/ledger.json) and only ever removes entries found there. + +Why pull and not push: the droplet keeps its no-inbound, no-RCON-exposed +design. The only secret here is a token that can read one realm's list of +website-managed usernames and post a report. It cannot change anything on +FullHearts and cannot reach this box. + +Fails safe in every direction that matters: + - FullHearts down, slow, wrong token, or a reply that doesn't validate: + change nothing. A kid who should be removed stays a little longer; nobody + who is playing gets kicked by mistake. + - The site says "paused": change nothing. An empty list is never read as + "remove everyone". + - More than REMOVAL_ALARM removals wanted at once: remove nobody, alert. + Below that, at most MAX_REMOVALS_PER_RUN go per run and the rest wait + for the next run, so a family cancelling three kids still gets removed. + - Someone removed a script-added player by hand: respect it, never re-add + while they stay on the wanted list. + - SYNC_MODE=dryrun (the default): only report what it would do. + +Standard library only, like world_info.py. Usernames reach rcon-cli as their +own argv element, never through a shell, and must match Minecraft's own +username pattern first. +""" +import fcntl +import json +import os +import re +import subprocess +import sys +import time +import urllib.error +import urllib.request + +NAME_RE = re.compile(r"^[A-Za-z0-9_]{3,16}$") +UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$") +SCHEMA = 1 +MAX_ENTRIES = 500 + + +class Invalid(Exception): + """The wanted list failed validation. Nothing may be changed on its say-so.""" + + +def env(name, default=None): + value = os.environ.get(name, default) + return value.strip() if isinstance(value, str) else value + + +def parse_wanted(raw, expect_realm=None): + if not isinstance(raw, dict) or raw.get("schema") != SCHEMA: + raise Invalid("unknown schema") + mode = raw.get("mode") + if mode not in ("apply", "paused"): + raise Invalid("unknown mode") + if expect_realm is not None and raw.get("realm_id") != expect_realm: + raise Invalid("list is for a different realm") + entries = raw.get("entries") + if not isinstance(entries, list) or len(entries) > MAX_ENTRIES: + raise Invalid("entries missing or too long") + wanted = {} + for e in entries: + if not isinstance(e, dict): + raise Invalid("entry is not an object") + uuid = str(e.get("uuid", "")).lower() + name = str(e.get("name", "")) + if not UUID_RE.match(uuid) or not NAME_RE.match(name): + raise Invalid("bad entry") + wanted[uuid] = name + return mode, wanted + + +def read_json_list(path): + try: + with open(path) as f: + data = json.load(f) + except FileNotFoundError: + return {} + out = {} + for e in data if isinstance(data, list) else []: + if isinstance(e, dict) and isinstance(e.get("uuid"), str): + out[e["uuid"].lower()] = str(e.get("name", "")) + return out + + +def empty_ledger(): + # added: uuid -> name, players THIS script put on the whitelist + # blocked: uuids someone removed by hand after we added them; not re-added + # until they drop off the wanted list + # seen_preexisting: wanted uuids that were already whitelisted by hand + return {"added": {}, "blocked": [], "seen_preexisting": []} + + +def load_ledger(path): + try: + with open(path) as f: + data = json.load(f) + except FileNotFoundError: + return empty_ledger() + ledger = empty_ledger() + ledger["added"] = {k.lower(): v for k, v in data.get("added", {}).items() if UUID_RE.match(k.lower())} + ledger["blocked"] = [u for u in data.get("blocked", []) if UUID_RE.match(u)] + ledger["seen_preexisting"] = [u for u in data.get("seen_preexisting", []) if UUID_RE.match(u)] + return ledger + + +def save_ledger(path, ledger): + os.makedirs(os.path.dirname(path), exist_ok=True) + tmp = path + ".tmp" + with open(tmp, "w") as f: + json.dump(ledger, f, indent=1, sort_keys=True) + f.flush() + os.fsync(f.fileno()) + os.replace(tmp, path) + + +def plan(wanted, whitelist, banned, ledger, max_removals, removal_alarm=5): + """Pure decision step. Nothing outside the script's own ledger is ever removed.""" + added = ledger["added"] + blocked = set(ledger["blocked"]) + p = { + "add": {}, "remove": {}, "present": [], "preexisting": [], + "removed_by_others": [], "forget": [], "unblock": [], "errors": [], + "removals_blocked": False, "deferred": [], + } + + for uuid, name in sorted(wanted.items()): + if uuid in whitelist: + if uuid in added: + p["present"].append(uuid) + else: + # On the list, but not by us: someone added them by hand. Theirs, forever. + p["preexisting"].append(uuid) + elif uuid in added: + # We added them, they're gone, and nobody told us: a person removed them. + p["removed_by_others"].append(uuid) + elif uuid in blocked: + p["removed_by_others"].append(uuid) + elif uuid in banned: + p["errors"].append({"uuid": uuid, "message": "player is banned on the server; not added"}) + else: + p["add"][uuid] = name + + for uuid, name in sorted(added.items()): + if uuid in wanted: + continue + if uuid in whitelist: + p["remove"][uuid] = whitelist[uuid] or name + else: + p["forget"].append(uuid) + + # Someone who left the wanted list can be added again later if they come back. + p["unblock"] = [u for u in blocked if u not in wanted] + + if len(p["remove"]) > removal_alarm: + p["removals_blocked"] = True + p["errors"].append({"message": f"{len(p['remove'])} removals wanted, alarm is {removal_alarm}; removed nobody"}) + p["remove"] = {} + elif len(p["remove"]) > max_removals: + now = sorted(p["remove"])[:max_removals] + p["deferred"] = sorted(u for u in p["remove"] if u not in now) + p["remove"] = {u: p["remove"][u] for u in now} + return p + + +def rcon(container, *args): + for a in args: + if not re.match(r"^[A-Za-z0-9_]+$", a): + raise ValueError("refusing an rcon argument outside [A-Za-z0-9_]") + return subprocess.run( + ["docker", "exec", "-i", container, "rcon-cli", *args], + capture_output=True, text=True, timeout=30, check=False, + ) + + +def container_running(container): + r = subprocess.run(["docker", "inspect", "-f", "{{.State.Running}}", container], + capture_output=True, text=True, timeout=15, check=False) + return r.returncode == 0 and r.stdout.strip() == "true" + + +def wait_for(path, predicate, tries=10): + for _ in range(tries): + if predicate(read_json_list(path)): + return True + time.sleep(0.5) + return False + + +def apply_plan(p, ledger, cfg, rcon_fn=rcon): + """Carry out a plan, saving the ledger after every change so a crash can't orphan an entry.""" + wl_path = cfg["whitelist_path"] + errors = list(p["errors"]) + done_add, done_remove = [], [] + + for uuid in p["forget"]: + ledger["added"].pop(uuid, None) + for uuid in p["removed_by_others"]: + ledger["added"].pop(uuid, None) + if uuid not in ledger["blocked"]: + ledger["blocked"].append(uuid) + ledger["blocked"] = [u for u in ledger["blocked"] if u not in set(p["unblock"])] + seen = set(ledger["seen_preexisting"]) | set(p["preexisting"]) + ledger["seen_preexisting"] = sorted(seen) + save_ledger(cfg["ledger_path"], ledger) + + for uuid, name in p["add"].items(): + rcon_fn(cfg["container"], "whitelist", "add", name) + if wait_for(wl_path, lambda wl, u=uuid: u in wl): + ledger["added"][uuid] = name + save_ledger(cfg["ledger_path"], ledger) + done_add.append(uuid) + continue + # The name resolved to a different account (renamed since the site + # checked it). Undo it, but only if that entry is new: never remove an + # account that was already on the list before this run. + before = cfg.get("before", {}) + now = read_json_list(wl_path) + if any(n.lower() == name.lower() and u not in before and u not in ledger["added"] for u, n in now.items()): + rcon_fn(cfg["container"], "whitelist", "remove", name) + errors.append({"uuid": uuid, "message": f"adding {name} did not whitelist the expected account; undone"}) + + for uuid, name in p["remove"].items(): + rcon_fn(cfg["container"], "whitelist", "remove", name) + if wait_for(wl_path, lambda wl, u=uuid: u not in wl): + ledger["added"].pop(uuid, None) + save_ledger(cfg["ledger_path"], ledger) + done_remove.append(uuid) + else: + errors.append({"uuid": uuid, "message": f"removing {name} did not take effect"}) + + return done_add, done_remove, errors + + +def fetch_wanted(base, token, timeout=15): + req = urllib.request.Request( + base.rstrip("/") + "/api/sync/v1/whitelist/", + headers={"Authorization": f"Bearer {token}", "Accept": "application/json", "User-Agent": "educraft-sync/1"}, + ) + with urllib.request.urlopen(req, timeout=timeout) as r: + if r.status != 200: + raise Invalid(f"HTTP {r.status}") + body = r.read(1_000_000) + return json.loads(body) + + +def post_report(base, token, report, timeout=15): + data = json.dumps(report).encode() + req = urllib.request.Request( + base.rstrip("/") + "/api/sync/v1/report/", data=data, method="POST", + headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json", "User-Agent": "educraft-sync/1"}, + ) + try: + urllib.request.urlopen(req, timeout=timeout).read() + except (urllib.error.URLError, OSError) as e: + print(f"report not delivered: {e}", file=sys.stderr) + + +def discord_alert(text): + """Problems only, through the existing alert webhook if installed. Routine runs stay silent.""" + hook = env("DISCORD_WEBHOOK") + if not hook or not hook.startswith(("https://discord.com/api/webhooks/", "https://discordapp.com/api/webhooks/")): + return + req = urllib.request.Request(hook, data=json.dumps({"content": f"[educraft-sync] {text}"[:1900]}).encode(), + headers={"Content-Type": "application/json", "User-Agent": "educraft-sync/1"}) + try: + urllib.request.urlopen(req, timeout=10).read() + except (urllib.error.URLError, OSError): + pass + + +def main(): + cfg = { + "base": env("FULLHEARTS_SYNC_URL", "https://fullhearts.app"), + "token": env("FULLHEARTS_SYNC_TOKEN", ""), + "mode": env("SYNC_MODE", "dryrun"), + "container": env("MC_CONTAINER", "minecraft-java"), + "whitelist_path": os.path.join(env("MC_DATA", "/root/minecraft/data"), "whitelist.json"), + "banned_path": os.path.join(env("MC_DATA", "/root/minecraft/data"), "banned-players.json"), + "ledger_path": env("LEDGER", "/var/lib/educraft-sync/ledger.json"), + "max_removals": int(env("MAX_REMOVALS_PER_RUN", "2")), + "removal_alarm": int(env("REMOVAL_ALARM", "5")), + "realm_id": int(env("REALM_ID")) if env("REALM_ID") else None, + } + if not cfg["token"]: + print("FULLHEARTS_SYNC_TOKEN is not set; nothing to do", file=sys.stderr) + return 1 + if cfg["mode"] not in ("dryrun", "apply"): + print("SYNC_MODE must be dryrun or apply", file=sys.stderr) + return 1 + + lock = open(env("LOCK_PATH", "/run/educraft-sync.lock"), "w") + try: + fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return 0 + + try: + mode, wanted = parse_wanted(fetch_wanted(cfg["base"], cfg["token"]), cfg["realm_id"]) + except urllib.error.HTTPError as e: + if e.code == 401: + discord_alert("FullHearts rejected the sync token. Nothing changed. Replace it in /etc/educraft-sync.env.") + print(f"could not fetch the wanted list (HTTP {e.code}); changed nothing", file=sys.stderr) + return 0 + except (urllib.error.URLError, OSError, ValueError, Invalid) as e: + print(f"could not fetch a valid wanted list ({e}); changed nothing", file=sys.stderr) + return 0 + + if mode == "paused": + print("FullHearts says paused; changed nothing") + return 0 + if not container_running(cfg["container"]): + print("server container is not running; changed nothing", file=sys.stderr) + return 0 + + whitelist = read_json_list(cfg["whitelist_path"]) + banned = read_json_list(cfg["banned_path"]) + ledger = load_ledger(cfg["ledger_path"]) + p = plan(wanted, whitelist, banned, ledger, cfg["max_removals"], cfg["removal_alarm"]) + + dry = cfg["mode"] != "apply" + if dry: + added, removed, errors = list(p["add"]), list(p["remove"]), p["errors"] + else: + cfg["before"] = whitelist + added, removed, errors = apply_plan(p, ledger, cfg) + + if p["removals_blocked"]: + discord_alert(f"{errors[-1]['message'] if errors else 'too many removals'}. Check the FullHearts admin page.") + + post_report(cfg["base"], cfg["token"], { + "schema": SCHEMA, + "dry_run": dry, + "present": p["present"], + "added": added, + "removed": removed, + "preexisting": p["preexisting"], + "removed_by_others": p["removed_by_others"], + "errors": errors, + }) + print(f"{'dry run: would add' if dry else 'added'} {len(added)}, " + f"{'would remove' if dry else 'removed'} {len(removed)}, {len(p['deferred'])} removals held for next run, " + f"{len(p['present'])} present, {len(p['preexisting'])} hand-added left alone, {len(errors)} errors") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/gitops/install_fullhearts_sync.sh b/gitops/install_fullhearts_sync.sh new file mode 100755 index 0000000..f6f1c40 --- /dev/null +++ b/gitops/install_fullhearts_sync.sh @@ -0,0 +1,61 @@ +#!/usr/bin/env bash +# Install the FullHearts whitelist sync on the droplet. Run as root: +# bash /root/minecraft/gitops/install_fullhearts_sync.sh +# +# Starts in dry-run: it only reports what it WOULD add or remove, and the +# FullHearts admin page shows that report. Switch to live after checking it: +# sed -i 's/^SYNC_MODE=.*/SYNC_MODE=apply/' /etc/educraft-sync.env +# +# The token is prompted for, never taken as an argument, because arguments +# land in shell history and /proc//cmdline. It can only read one realm's +# list of website-managed usernames and post a report back. +set -euo pipefail + +ENV_FILE=/etc/educraft-sync.env +REPO_DIR=/root/minecraft + +[ "$(id -u)" -eq 0 ] || { echo "run as root" >&2; exit 1; } +[ -r "$REPO_DIR/gitops/fullhearts_sync.py" ] || { echo "expected the repo at $REPO_DIR" >&2; exit 1; } +command -v python3 >/dev/null || { echo "python3 is required" >&2; exit 1; } + +if grep -Eq '^[[:space:]]*OVERRIDE_WHITELIST' "$REPO_DIR/docker-compose.yml" 2>/dev/null; then + echo "docker-compose.yml sets OVERRIDE_WHITELIST; that would wipe synced players on every deploy. Remove it first." >&2 + exit 1 +fi + +if [ -r "$ENV_FILE" ] && grep -q '^FULLHEARTS_SYNC_TOKEN=' "$ENV_FILE"; then + echo " token already configured in $ENV_FILE (leaving it alone)" +else + echo " Paste the sync token from the FullHearts admin page (Set up sync). It will not be echoed." + printf ' token: ' + read -r -s TOKEN + echo + case "$TOKEN" in + edusync_*) ;; + *) echo " that does not look like a FullHearts sync token" >&2; exit 1 ;; + esac + umask 077 + { + printf 'FULLHEARTS_SYNC_URL=https://fullhearts.app\n' + printf 'FULLHEARTS_SYNC_TOKEN=%s\n' "$TOKEN" + printf 'SYNC_MODE=dryrun\n' + printf 'MAX_REMOVALS_PER_RUN=2\n' + printf 'REMOVAL_ALARM=5\n' + } > "$ENV_FILE" + unset TOKEN + echo " wrote $ENV_FILE" +fi +chown root:root "$ENV_FILE" +chmod 600 "$ENV_FILE" + +install -m 644 "$REPO_DIR/gitops/fullhearts-sync.service" /etc/systemd/system/ +install -m 644 "$REPO_DIR/gitops/fullhearts-sync.timer" /etc/systemd/system/ +systemctl daemon-reload +systemctl enable --now fullhearts-sync.timer + +echo +echo "Installed in $(sed -n 's/^SYNC_MODE=//p' "$ENV_FILE") mode." +echo "Run once now: systemctl start fullhearts-sync.service" +echo "Watch it: journalctl -u fullhearts-sync.service -f" +echo "Pause it: systemctl stop fullhearts-sync.timer" +echo "Its own record: /var/lib/educraft-sync/ledger.json (players it added; nobody else is ever touched)" diff --git a/gitops/install_gitops.sh b/gitops/install_gitops.sh index 0f337c9..c3f7d69 100755 --- a/gitops/install_gitops.sh +++ b/gitops/install_gitops.sh @@ -16,9 +16,10 @@ # permanently dirty, which makes deploy.sh abort every run until it is untracked. # # After that, docker-compose.yml is the single source of truth for settings and -# rosters (WHITELIST / OPS env vars, with OVERRIDE_WHITELIST=true and -# OVERRIDE_OPS=true so the image SYNCHRONIZEs the json files from them). -# Adding a kid then becomes: edit compose, commit, push - the deploy applies it. +# the ops roster. The whitelist is NOT synchronized from compose: WHITELIST +# only merges names in, and OVERRIDE_WHITELIST must stay off, because +# gitops/fullhearts_sync.py adds paying families' kids to the live whitelist +# and a compose override would wipe them on every deploy. CI enforces this. set -euo pipefail REPO_DIR=/root/minecraft diff --git a/tests/test_fullhearts_sync.py b/tests/test_fullhearts_sync.py new file mode 100755 index 0000000..41fade1 --- /dev/null +++ b/tests/test_fullhearts_sync.py @@ -0,0 +1,171 @@ +#!/usr/bin/env python3 +"""gitops/fullhearts_sync.py must never touch a player it did not add. + +The script edits the live whitelist from a list another system sends it, so +every check here is about what it must NOT do: + +1. Hand-added players (compose WHITELIST, /whitelist, rcon-cli) are never + removed, even when they are missing from the wanted list. +2. A player already whitelisted by hand who is also on the wanted list is + recorded as pre-existing and still never removed later. +3. More removals than the alarm removes nobody; fewer go a few per run. +4. A reply that is paused, malformed, for another realm, or carries a name + that isn't a Minecraft username, changes nothing. +5. A player someone removed by hand is not added back behind their back. +6. A name that resolves to a different account is undone, and only if that + entry is new. +7. compose never turns on OVERRIDE_WHITELIST, which would rewrite the live + whitelist from compose on every deploy and wipe every site-added player. +8. Dry run is the default. +""" +import json +import os +import re +import sys +import tempfile + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, os.path.join(ROOT, "gitops")) +import fullhearts_sync as fs # noqa: E402 + +FAILS = [] + + +def check(cond, msg): + if not cond: + FAILS.append(msg) + + +def u(n): + return f"{n:08x}-0000-0000-0000-000000000000" + + +HAND = u(1) # added by the owner, never ours +KID_A = u(2) +KID_B = u(3) +KID_C = u(4) + + +def ledger(added=None, blocked=None): + lg = fs.empty_ledger() + lg["added"] = dict(added or {}) + lg["blocked"] = list(blocked or []) + return lg + + +# 1. a hand-added player missing from the wanted list stays +p = fs.plan(wanted={}, whitelist={HAND: "Owner"}, banned={}, ledger=ledger(), max_removals=2) +check(not p["remove"], "removed a hand-added player who was never in the ledger") + +# 2. hand-added AND wanted: pre-existing, and later still not removable +p = fs.plan(wanted={HAND: "Owner"}, whitelist={HAND: "Owner"}, banned={}, ledger=ledger(), max_removals=2) +check(p["preexisting"] == [HAND] and not p["add"], "hand-added wanted player not treated as pre-existing") +p = fs.plan(wanted={}, whitelist={HAND: "Owner"}, banned={}, ledger=ledger(), max_removals=2) +check(HAND not in p["remove"], "pre-existing player removed once they left the wanted list") + +# normal add / keep / remove of our own entries +p = fs.plan(wanted={KID_A: "KidA", KID_B: "KidB"}, whitelist={KID_B: "KidB", KID_C: "KidC"}, + banned={}, ledger=ledger(added={KID_B: "KidB", KID_C: "KidC"}), max_removals=2) +check(p["add"] == {KID_A: "KidA"}, "did not add a wanted, missing player") +check(p["present"] == [KID_B], "did not report our present player") +check(p["remove"] == {KID_C: "KidC"}, "did not remove our own unwanted player") + +# 3. removal limit: a family of three leaves over two runs, a mass removal is refused +three = {KID_A: "A", KID_B: "B", KID_C: "C"} +p = fs.plan(wanted={}, whitelist=dict(three), banned={}, ledger=ledger(added=dict(three)), max_removals=2) +check(len(p["remove"]) == 2 and not p["removals_blocked"], "did not remove two of three leaving players") +check(p["deferred"] == sorted(set(three) - set(p["remove"])), "did not hold the third removal for the next run") +left = {u: n for u, n in three.items() if u not in p["remove"]} +p = fs.plan(wanted={}, whitelist=left, banned={}, ledger=ledger(added=dict(left)), max_removals=2) +check(list(p["remove"]) == list(left) and not p["deferred"], "did not remove the held player on the next run") +many = {f"{i:08x}-0000-4000-8000-000000000000": f"P{i}" for i in range(6)} +p = fs.plan(wanted={}, whitelist=dict(many), banned={}, ledger=ledger(added=dict(many)), max_removals=2) +check(p["remove"] == {} and p["removals_blocked"], "removed players when more than the alarm wanted out") + +# 4. bad replies change nothing +for bad in ( + {"schema": 2, "mode": "apply", "entries": []}, + {"schema": 1, "mode": "wipe", "entries": []}, + {"schema": 1, "mode": "apply", "entries": "nope"}, + {"schema": 1, "mode": "apply", "entries": [{"uuid": KID_A, "name": "x; op Evil"}]}, + {"schema": 1, "mode": "apply", "entries": [{"uuid": "not-a-uuid", "name": "Fine"}]}, +): + try: + fs.parse_wanted(bad) + FAILS.append(f"accepted an invalid reply: {bad}") + except fs.Invalid: + pass +try: + fs.parse_wanted({"schema": 1, "mode": "apply", "realm_id": 2, "entries": []}, expect_realm=1) + FAILS.append("accepted a list for another realm") +except fs.Invalid: + pass +mode, wanted = fs.parse_wanted({"schema": 1, "mode": "paused", "entries": []}) +check(mode == "paused", "paused mode not recognised") +try: + fs.rcon("minecraft-java", "whitelist", "add", "bad name") + FAILS.append("rcon accepted an argument with a space") +except ValueError: + pass + +# 5. removed by hand: not re-added, and re-allowed once off the wanted list +p = fs.plan(wanted={KID_A: "KidA"}, whitelist={}, banned={}, ledger=ledger(added={KID_A: "KidA"}), max_removals=2) +check(not p["add"] and p["removed_by_others"] == [KID_A], "re-added a player someone removed by hand") +p = fs.plan(wanted={KID_A: "KidA"}, whitelist={}, banned={}, ledger=ledger(blocked=[KID_A]), max_removals=2) +check(not p["add"], "re-added a blocked player") +p = fs.plan(wanted={}, whitelist={}, banned={}, ledger=ledger(blocked=[KID_A]), max_removals=2) +check(p["unblock"] == [KID_A], "did not unblock a player who left the wanted list") + +# banned players are reported, not added +p = fs.plan(wanted={KID_A: "KidA"}, whitelist={}, banned={KID_A: "KidA"}, ledger=ledger(), max_removals=2) +check(not p["add"] and p["errors"], "added a banned player") + +# 6. apply against a real file with a fake rcon +with tempfile.TemporaryDirectory() as d: + wl = os.path.join(d, "whitelist.json") + cfg = {"container": "c", "whitelist_path": wl, "ledger_path": os.path.join(d, "l", "ledger.json")} + + def write(entries): + with open(wl, "w") as f: + json.dump([{"uuid": k, "name": v} for k, v in entries.items()], f) + + state = {HAND: "Owner"} + write(state) + cfg["before"] = dict(state) + + def fake_rcon(_container, _cmd, action, name): + if action == "add": + # "Renamed" resolves to a different account than the site expected. + state[KID_C if name == "Renamed" else KID_A] = name + else: + for k in [k for k, v in state.items() if v == name]: + del state[k] + write(state) + + fs.wait_for.__defaults__ = (1,) + lg = ledger() + p = fs.plan(wanted={KID_A: "KidA", KID_B: "Renamed"}, whitelist=dict(state), banned={}, ledger=lg, max_removals=2) + added, removed, errors = fs.apply_plan(p, lg, cfg, rcon_fn=fake_rcon) + check(added == [KID_A], "a confirmed add was not recorded") + check(KID_A in lg["added"] and KID_B not in lg["added"], "ledger wrong after adds") + check(KID_C not in state, "a wrong-account add was not undone") + check(HAND in state, "the hand-added player disappeared") + check(any("did not whitelist the expected account" in e["message"] for e in errors), "wrong-account add not reported") + with open(cfg["ledger_path"]) as f: + check(KID_A in json.load(f)["added"], "ledger not written to disk") + +# 7. OVERRIDE_WHITELIST must never be on +with open(os.path.join(ROOT, "docker-compose.yml")) as f: + compose = f.read() +check(not re.search(r'^\s*OVERRIDE_WHITELIST\s*:\s*"?(true|TRUE|True|1)"?', compose, re.M), + "docker-compose.yml sets OVERRIDE_WHITELIST; every deploy would wipe site-added players") + +# 8. dry run by default +with open(os.path.join(ROOT, "gitops", "fullhearts_sync.py")) as f: + check('env("SYNC_MODE", "dryrun")' in f.read(), "SYNC_MODE no longer defaults to dryrun") + +if FAILS: + for msg in FAILS: + print(f"FAIL: {msg}") + sys.exit(1) +print("fullhearts_sync: all checks passed")