diff --git a/README.md b/README.md index 460cb12..74c767c 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,9 @@ The [October 27 incident correction and restricted mode-controller runbook](docs/zombies-recovery-and-modes.md) records the reproduced death/wave defects, qualification gates and root-only host -CLI. RCON activation remains disabled; production stays on the recovered Promod image. +CLI. The [authenticated bridge runbook](docs/authenticated-mode-bridge.md) documents +the new opt-in implementation. It remains uninstalled/disabled; production stays +on its current known-good image. See [master deployment and Zombies readiness](docs/zombies-readiness.md) for required GitHub checks, local evidence and real-client qualification blockers. @@ -323,6 +325,10 @@ authorize deployment or any production/homolog/Bard service action. ## Before the Dawn packaging and RCON switching design +The implemented, gated bridge is documented in +[authenticated-mode-bridge.md](docs/authenticated-mode-bridge.md). Historical +design decisions below retain their original qualification scope. + Status: private original-file packaging and master-based image preparation are supported; RCON activation remains disabled. A catalog entry is not an approved artifact. The companion engine command is an administrative **preflight only** and reports unavailable without submitting or executing a deployment request. diff --git a/docs/authenticated-mode-bridge.md b/docs/authenticated-mode-bridge.md new file mode 100644 index 0000000..9bf0774 --- /dev/null +++ b/docs/authenticated-mode-bridge.md @@ -0,0 +1,209 @@ +# Authenticated RCON production mode bridge + +Protected baselines: engine `701a7c5df46c5723705dad0408afa44fb89b0ad9`, +workspace `b77684d` (merged PR #17), configuration `9f0fa1a`. Workspace PR #15 +introduced the root host CLI. This change adds an **uninstalled, disabled-by-default** +RCON bridge and strengthens its shared locking, private-byte rollback and recovery. +No production/homologation service, approval record, credential or running image +was inspected remotely or changed. + +## Boundary and threat model + +Trusted components are the qualified native engine, plugins, installed GSC, +private authentication/configuration, Docker daemon, host root, reviewed scripts, +protected qualification records and external verifier. Credential/command-policy +administrators are authentication authorities. Operators must retire old unlocked +deployment entrypoints when installing the shared host lock. + +Attackers may send arbitrary unauthenticated game/RCON traffic, use low-permission +accounts, invoke generic GSC/console commands, forge logs/usernames/IP claims, +create another same-UID process, send malformed/replayed IPC, or disconnect the +requesting game process. None is accepted merely because its name, source address, +UID, numeric power claim, log line or writable-home file resembles an administrator. + +The native engine dispatches only an authenticated raw `change_mode` command with +power 100. Generic console/GSC dispatch never submits. The host checks kernel +`SO_PEERCRED` PID, current production container ID/running state/direct executable, +executable inode inside that container, cgroup membership, protocol label and an +exact read-only bridge-directory bind. The engine independently requires a UID-zero +host peer. No game credential or host signing key is shared over this channel. + +A compromised native process or malicious installed mod that steals/changes the +existing credential is an authentication-authority compromise, outside this +boundary. Host authority remains limited to two independently approved immutable +images. Classic UDP RCON is plaintext and has no cryptographic network-packet +anti-replay: host operation deduplication does not fix captured credentials or +replayed UDP commands. Protected administrative transport is an activation gate. + +## Protocol and asynchronous execution + +Fixed endpoint: `/run/cod4-mode-bridge/control.sock`, Linux `SOCK_SEQPACKET`. +Accepted packets are exactly: + +```text +C4M1 switch <32 lowercase random hex digits> promod +C4M1 switch <32 lowercase random hex digits> zombies +C4M1 status +``` + +No paths, image references, container names, ports, shell text, argv, URLs, account +names or environment settings are accepted. Oversized/truncated packets, extra +fields, NUL/control suffixes and other targets fail closed. Replies contain only +fixed codes, operation IDs, modes and phases. The native parser rejects malformed +or mismatched replies, and redacts mode request arguments in game logs. + +The engine submits without waiting for host preflight. The host daemon owns a +separate detached worker and durable request/transaction journals. Accepted IDs +cannot be reused. Lock contention returns busy. Already-active mode is a verified +no-op; it never recreates a container. Initial `submitted` is not acceptance. + +Under the host lease, the worker checks qualification, both image identities, +exact current baseline, startup/health/local and independent external UDP status, +and a recoverable private-home archive. It records pending before acceptance. +The engine queues a fixed player notice and acknowledges on the next game frame. +An alive engine that cannot acknowledge causes denial before mutation; a stopped +engine cannot cancel an already accepted durable job. + +The worker reuses `mode-controller.py`, `runtime.py adapt`, and the existing +`common.sh apply_runtime`. It recreates only production with `--pull never`, from +an already-local immutable Docker image content ID. No build, fetch, checkout, +load, download or homolog action is part of switching. Published UDP 28960, +private mounts/environment and network membership remain unchanged. + +Success follows Docker identity/startup/read-only/mount/environment/network/port +checks, correct fs_game/gametype/pure status, local UDP and the root-owned external +verifier. The verifier must query from a different machine and bind its result to +the operation. A same-host hairpin is not production external qualification. + +## Locking, rollback and failure + +`/opt/services/cod4/.production-transition.lock` is the shared host lease. Normal +production deployment keeps it via a fixed SSH coprocess. Before announcing the +lease, that process creates a restrictive host-only deployment marker. EOF, +workstation death, failed rollback or an uncertain exit leaves the marker; +controller/bridge refuse new work even if the advisory lock has become free. +Only explicit completion after a known-healthy target/rollback clears it. A failed +preflight that exits abruptly can conservatively leave the marker too. + +The bridge worker inherits the lock, and passes it to in-flight subprocesses. +Worker death cannot let another transition race a still-running apply. Once the +lease is free, daemon recovery restores only the saved previous image/config; +it never retries the target. Revoking the target or bridge activation cannot force +the target live or block an otherwise independently approved prior-image rollback. +Missing/revoked previous evidence/image, corrupt snapshots or rollback failure +records `recovery_required` and blocks follow-up. There is no automatic retry loop +for that state. + +Before mutation, private-home backup validates protected ancestry, a nonsymlink +home, same-filesystem restore, archive paths/links and absence of special files. +Only the home may be a writable persistent mount. Rollback stops only production, +restores archived home bytes through a validated staging directory and atomic +renames, preserves the failed home privately, recreates the previous exact Compose +configuration/image once, and verifies it locally/externally. This preserves +private configuration bytes as well as Compose mount descriptions. + +Host state remains root-only under `/opt/services/cod4/.mode-controller`. +Private snapshots, backups and child diagnostics stay out of public status. +Qualification/approval records are read, never rewritten by a request. Required +rollback and homolog approval writes now fail explicitly before progressing, even +when Bash caller conditionals suppress errexit. + +## Operator interface + +```text +/rcon change_mode zombies +/rcon change_mode promod +/rcon change_mode +``` + +The last command reports safe cached host status and refreshes it. After process +replacement, reconnect and poll again. UDP can receive an asynchronous response; +Source clients use status polling. Codes distinguish submitted, accepted, busy, +unsupported/invalid, denied, disabled, not_qualified, already_active, success, +rolled_back and recovery_required. No accepted/pending response claims completion. +Old cached status is explicitly labeled when the host is unavailable. + +The existing root CLI remains available for exceptional host operations: + +```sh +sudo python3 -I /opt/cod4-operations/scripts/mode-controller.py status +sudo python3 -I /opt/cod4-operations/scripts/mode-controller.py switch zombies +sudo python3 -I /opt/cod4-operations/scripts/mode-controller.py recover +``` + +An interrupted normal deployment marker requires operator reconciliation, not a +blind delete/retry. Preserve it and all journals, identify outstanding deployment +children, verify the exact current image/config/private state externally, then +archive the marker only with operator approval. Never change approval records to +make a denied transition pass. + +## Installation and activation gates — not performed + +1. Owner manually merges the engine/workspace PRs after mandatory CI and review. + Install reviewed scripts together in root-owned, nonwritable-ancestor paths. + Workers use isolated Python and compile verified private module source, avoiding + writable sibling bytecode-cache imports. Do not run a user-writable checkout + as root. +2. Prepare both actual mode images once through the existing reviewed workflow. + Both need the new engine and `io.cod4.rcon-mode-bridge=C4M1`. Older engines are + labeled disabled by preparation and cannot qualify for this bridge. +3. Independently qualify each exact image, including actual-client gameplay, + supervised Promod→Zombies→Promod, notification/reconnection, shared credential + and account continuity, private CFG search precedence, waves/bots/purity and + rollback. Establish real external UDP 28960 verification. The local fixture + tests below are not those approvals. +4. With explicit installation authorization, create the protected state (0700), + root-owned lock (0644), and `/run/cod4-mode-bridge` (root-owned 0755). Bind only + that directory read-only at the identical path in production. Do not mount the + Docker socket, host scripts, qualification records or credentials in the game. + Do not add the endpoint to homologation. Both runtime images remain read-only; + review container privileges and all credential-changing administrative roles. +5. Keep the existing registry `enabled`/mode evidence gates. Separately require + `rcon_bridge_enabled: true` only after explicit activation approval. Add + `rcon_security_review` and `rcon_activation_approval`, each with trusted `path`, + `sha256` and `images: {promod: EXACT_ID, zombies: EXACT_ID}`. Both mode records + must retain actual-client gameplay, independent review, CI and operator + approval tied to those exact image IDs. No template/evidence is auto-approved. +6. Start the reviewed host daemon with the existing operator process-management + approach: `python3 -I /opt/cod4-operations/scripts/mode-bridge.py serve`. + This repository neither installs/enables it nor introduces a service stack. + Routine authorized switching then requires only authenticated RCON. + +Production remains on its known-good mode throughout code review and qualification. +No merge, rollout or bridge activation is automatic. Rollback of the feature is a +reviewed code revert plus an authorized bridge stop/socket-mount removal; retain +host CLI recovery and authentication repairs. Runtime rollback needs the exact +previous approved artifact and operator authorization. + +## Reproducible local checks and limits + +```sh +python3 -m unittest discover -s tests -p 'test_*.py' +bash tests/operations.sh +python3 tests/run_mode_compose.py +``` + +The Compose runner verifies local Unix Docker context, refuses endpoint overrides, +checks ports are unused, and creates unique owned container/project/image names. +It uses authored static UDP responders and local cached base images, with no +networked build steps; builds occur only before transitions. The actual apply +primitive, escaping, recreation, Docker identity, separate-network published UDP, +private-byte rollback and untouched owned homolog sentinel are exercised. +A real Unix credential probe binds the sender PID to Docker and verifies executable +inode/cgroup identity. Cleanup checks ownership labels and removes only resources +created by that run. Existing local containers remain untouched. + +These fixture images are explicitly not games. Qualification/ownership policy is +substituted only inside the test namespace; no real approval record is created. +This is layered controller/IPC proof, not a complete live-game authenticated +RCON→root-daemon→qualified-image transition. Production activation remains blocked +on the actual-image/operator steps above. + +Local evidence (2026-10-27): 67 Python tests and existing mocked operations +suite passed. Disposable Compose fixture 12/12 checks passed; private local +summary `/tmp/c4-mode-test-56f39bbe23-ces3j3ij/results.json`. Fixture base image +was the locally cached `python:3.12-slim` image ID +`sha256:23b5dc88c7dd47fec3f960b51dc30d19df9875cfbfc60f3b62d3e5b88cbccf62`. +This image ID records a test dependency, not a qualified deployment artifact. +Protected workspace baseline: `b77684d`; engine baseline: +`701a7c5df46c5723705dad0408afa44fb89b0ad9`. No configuration repository changes. diff --git a/scripts/common.sh b/scripts/common.sh index 253417b..400eddf 100755 --- a/scripts/common.sh +++ b/scripts/common.sh @@ -134,7 +134,7 @@ confirm() { read -r -p "$1 Type yes: " answer [[ "$answer" == yes ]] || fail 'Confirmation declined' } -deploy_image() { +deploy_image_locked() { need docker need python3 local metadata identity image_revision platform host_platform previous candidate previous_mode startup_contract @@ -149,7 +149,7 @@ deploy_image() { mapfile -t startup_values <<< "$startup_contract" mode_fs_game=${startup_values[0]}; startup_map=${startup_values[1]}; mode_maps=${startup_values[2]}; mode_maxclients=${startup_values[3]} platform=$(python3 -c 'import json,sys; c=json.load(sys.stdin)[0]; print(c["Os"]+"/"+c["Architecture"])' <<< "$metadata") - host_platform=$(remote docker version --format '{{.Server.Os}}/{{.Server.Arch}}') + host_platform=$(remote docker version --format '{{.Server.Os}}/{{.Server.Arch}}') || fail 'Cannot verify the host platform' [[ "$platform" == "$host_platform" ]] || fail "Image platform $platform differs from host $host_platform" if [[ "$environment" == production ]]; then [[ "$(remote docker inspect --format '{{.Image}} {{.State.Running}}' cod4-homolog)" == "$identity true" ]] || fail 'Approved image is no longer running in homolog' @@ -165,14 +165,17 @@ deploy_image() { verify_homolog "$identity" || return 1 fi # Keep rollback evidence even if this process or SSH is interrupted. - image_config "$previous" > "$ROOT/.state/rollback-$environment.json" + image_config "$previous" > "$ROOT/.state/rollback-$environment.json" || fail 'Cannot persist the exact rollback configuration' # pipefail prevents applying an incomplete image transfer. docker image save "$identity" | remote docker image load >/dev/null || fail 'Image transfer failed; runtime was not changed' + host_runtime_safe=0 if apply_runtime <<< "$candidate" && check_health "$mode_fs_game" && [[ "$(remote docker inspect --format '{{.Image}}' "$container")" == "$identity" ]]; then + host_runtime_safe=1 printf 'Deployed %s revision %s to %s\n' "$identity" "$revision" "$environment" else printf 'Deployment failed for %s. Restoring previous image %s.\n' "$environment" "$previous" >&2 if apply_runtime <<< "$(image_config "$previous")" && check_health "$previous_mode" && [[ "$(remote docker inspect --format '{{.Image}}' "$container")" == "$previous" ]]; then + host_runtime_safe=1 printf 'Rollback healthy: %s\n' "$previous" >&2 else printf 'ROLLBACK FAILED: inspect %s immediately.\n' "$container" >&2 @@ -181,10 +184,46 @@ deploy_image() { fi if [[ "$environment" == homolog ]]; then confirm 'Health checks passed. Approve this exact artifact for production?' || return 1 - mkdir -p -- "$ROOT/.state" - write_artifact_record "$identity" > "$ROOT/.state/approved.next" - mv -- "$ROOT/.state/approved.next" "$ROOT/.state/approved" + mkdir -p -- "$ROOT/.state" || fail 'Cannot create approval directory' + write_artifact_record "$identity" > "$ROOT/.state/approved.next" || fail 'Cannot write complete approval record' + mv -- "$ROOT/.state/approved.next" "$ROOT/.state/approved" || fail 'Cannot commit approval record' + fi +} + +# Production deployment and the host mode controller share this host lease. +# Before bridge installation the absent file preserves the existing workflow. +# Installation creates a root-owned 0644 lock in a root-owned parent directory. +deploy_image() { + local lease_pid lease_read lease_write lease_state result=0 + if [[ "$environment" == production ]]; then + coproc MODE_LEASE { remote bash -c ' +set -euo pipefail +file=/opt/services/cod4/.production-transition.lock +if [[ ! -e "$file" ]]; then printf "legacy\n"; read -r release; exit; fi +[[ ! -L "$file" && "$(stat -c %u "$file")" == 0 && "$(stat -c %a "$file")" == 644 ]] || exit 1 +exec 9< "$file" +flock -n 9 || exit 2 +marker=/opt/services/cod4/.production-deployment.json +[[ ! -e "$marker" && ! -L "$marker" ]] || exit 2 +umask 077 +(set -o noclobber; printf "{\"phase\":\"deployment-in-progress-or-interrupted\"}\n" > "$marker") +printf "locked\n" +if read -r release && [[ "$release" == release ]]; then rm -- "$marker"; fi +' mode-deployment-lease; } + lease_pid=$MODE_LEASE_PID + lease_read=${MODE_LEASE[0]}; lease_write=${MODE_LEASE[1]} + IFS= read -r -t 15 lease_state <&"$lease_read" || fail 'Host production transition lock unavailable' + if [[ "$lease_state" == locked || "$lease_state" == legacy ]]; then + host_runtime_safe=1 + else fail 'Invalid production transition lock response'; fi + fi + deploy_image_locked "$@" || result=$? + if [[ "$environment" == production ]]; then + if [[ $host_runtime_safe == 1 ]]; then printf "release\n" >&"$lease_write" || true + else printf "hold\n" >&"$lease_write" || true; fi + wait "$lease_pid" || true fi + return "$result" } CONFIG_REPOSITORY=https://github.com/ghptc/cod4-config-server.git @@ -210,6 +249,8 @@ resolve_master() { select_mode local dependency_lock=bots/dependencies.json if [[ "$mode_fs_game" == mods/btd_alpha_001 ]]; then dependency_lock=tools/btd/dependencies.json; fi + bridge_protocol=disabled + if [[ -f "$stage/engine/src/sv_mode_bridge.c" ]]; then bridge_protocol=C4M1; fi asset_ref=$(sha256sum "$stage/engine/$dependency_lock") || fail 'Dependency lock missing' asset_ref=${asset_ref%% *} bot_revision=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["bot_warfare"]["commit"])' "$stage/engine/bots/dependencies.json") || fail 'Cannot read Bot Warfare revision' @@ -302,7 +343,7 @@ RUN chmod -R a+rX /opt/cod4-artifact && ln -s /home/user/cod4/main /opt/cod4-art USER 1000:1000 WORKDIR /opt/cod4-artifact ENTRYPOINT ["/opt/cod4-artifact/cod4x18_dedrun"] -LABEL org.opencontainers.image.source="$ENGINE_REPOSITORY" org.opencontainers.image.revision="$revision" io.cod4.assets.lock="$asset_ref" io.cod4.bot-warfare.revision="$bot_revision" io.cod4.config.revision="$config_revision" io.cod4.mode="$mode_id" io.cod4.config.hash="$config_hash" io.cod4.fs-game="$mode_fs_game" io.cod4.startup-map="$startup_map" io.cod4.maps="$mode_maps" io.cod4.maxclients="$mode_maxclients" +LABEL io.cod4.rcon-mode-bridge="$bridge_protocol" org.opencontainers.image.source="$ENGINE_REPOSITORY" org.opencontainers.image.revision="$revision" io.cod4.assets.lock="$asset_ref" io.cod4.bot-warfare.revision="$bot_revision" io.cod4.config.revision="$config_revision" io.cod4.mode="$mode_id" io.cod4.config.hash="$config_hash" io.cod4.fs-game="$mode_fs_game" io.cod4.startup-map="$startup_map" io.cod4.maps="$mode_maps" io.cod4.maxclients="$mode_maxclients" DOCKERFILE # Keep source and Git metadata out of the Docker context and runtime image. printf 'engine\nconfig\nbots\nfps333\n' > "$stage/.dockerignore" diff --git a/scripts/mode-bridge.py b/scripts/mode-bridge.py new file mode 100644 index 0000000..ca7ff91 --- /dev/null +++ b/scripts/mode-bridge.py @@ -0,0 +1,312 @@ +#!/usr/bin/env python3 +"""Root-owned local IPC bridge; disabled unless explicitly qualified and authorized. + +The kernel binds requests to the running production engine. The qualified native +engine's ingress-only dispatcher is trusted; native process compromise is outside +this boundary. No credentials, shell, image or container arguments are accepted. +""" +import argparse +import fcntl +import importlib.util +import json +import os +from pathlib import Path +import re +import select +import socket +import stat +import struct +import subprocess +import sys +import time + +SCRIPTS = Path(__file__).resolve().parent +c = None # Loaded from verified source only, never a sibling bytecode cache. +SOCKET = Path('/run/cod4-mode-bridge/control.sock') +REQUEST = re.compile(rb'C4M1 switch ([a-f0-9]{32}) (promod|zombies)') +TERMINAL = {'success', 'rolled_back', 'denied'} +PHASES = {'idle', 'denied', 'pending', 'verifying', 'success', 'rolling_back', 'rolled_back', 'recovery_required'} + + +def policy(registry): + c.qualification(registry) + if registry.get('rcon_bridge_enabled') is not True: + raise ValueError('RCON bridge disabled') + if any(record['labels'].get('io.cod4.rcon-mode-bridge') != 'C4M1' for record in registry['modes'].values()): + raise ValueError('Both images require the native bridge protocol') + for gate in ('rcon_security_review', 'rcon_activation_approval'): + item = registry[gate] + c.evidence(item) + if item.get('images') != {m: registry['modes'][m]['image'] for m in c.MODES}: + raise ValueError('RCON authorization belongs to different images') + + +def response(channel, code, operation='none', mode='none', phase='idle'): + if not re.fullmatch(r'(?:[a-f0-9]{32}|none)', operation): operation = 'none' + if mode not in c.MODES: mode = 'none' + if code not in PHASES | {'submitted','failed','accepted','busy','replay','already_active','not_qualified','disabled','invalid','unavailable'}: code = 'recovery_required' + if phase not in PHASES: phase = 'recovery_required' + try: channel.send(f'C4M1 {code} {operation} {mode} {phase}'.encode()) + except OSError: pass # The accepted host job outlives the game process. + + +def public_status(state=None): + state = state or c.STATE + path = state / 'active.json' + if not path.exists(): return 'idle', 'none', 'none' + data = json.loads(path.read_text()) + return data.get('phase', 'recovery_required'), data.get('operation', 'none'), data.get('target_mode', 'none') + + +def bridge_status(): + active = c.STATE / 'active.json' + latest = c.STATE / 'bridge-status.json' + tx = json.loads(active.read_text()) if active.exists() else {} + request = json.loads(latest.read_text()) if latest.exists() else {} + if tx.get('phase') not in TERMINAL | {None} or tx.get('updated_at', 0) >= request.get('updated_at', 0): + return tx + return request + + +def receipt(operation, mode, code, phase): + c.atomic(c.STATE / 'bridge-status.json', {'operation': operation, 'target_mode': mode, + 'code': code, 'phase': phase, 'updated_at': time.time()}) + + +def process_matches(pid, container_id): + try: + proc = Path('/proc') / str(pid) + executable = (proc/'exe').stat() + packaged = (proc/'root'/c.runtime.EXECUTABLE.lstrip('/')).stat() + return ((executable.st_dev, executable.st_ino) == (packaged.st_dev, packaged.st_ino) + and container_id in (proc/'cgroup').read_text()) + except OSError: return False + + +def peer_matches(credentials, inspection): + pid, uid, gid = credentials + return (pid > 0 and pid == inspection.get('State', {}).get('Pid') and + inspection.get('State', {}).get('Running') is True and + inspection.get('Name') == '/cod4-production' and + inspection.get('Path') == c.runtime.EXECUTABLE and + re.fullmatch(r'[a-f0-9]{64}', inspection.get('Id', '')) is not None and + inspection.get('Config', {}).get('Labels', {}).get('io.cod4.rcon-mode-bridge') == 'C4M1' and + [{k: m.get(k) for k in ('Type','Source','Destination','RW')} for m in inspection.get('Mounts', []) if m.get('Destination') == str(SOCKET.parent)] == + [{'Type': 'bind', 'Source': str(SOCKET.parent), 'Destination': str(SOCKET.parent), 'RW': False}] and + process_matches(pid, inspection['Id'])) + + +def registry(): + return json.loads(c.trusted(c.REGISTRY).read_text()) + + +def worker(operation, mode, peer_pid, container_id, descriptor, lock_fd): + c.LOCK_FD = lock_fd + channel = socket.socket(fileno=descriptor) if descriptor >= 0 else None + controller = c.Controller() + try: + rules = registry() + if mode == 'recover': + controller.recover(rules); return + policy(rules) + inspected = controller.inspect() + if not peer_matches((peer_pid, 0, 0), inspected) or inspected['Id'] != container_id: + response(channel, 'denied', operation, mode); return + request = c.STATE / (operation + '-request.json') + if request.exists(): + response(channel, 'replay', operation, mode); return + c.atomic(request, {'operation': operation, 'mode': mode, 'peer_pid': peer_pid, + 'container_id': container_id, 'requested_at': time.time()}) + + def ready(tx): + response(channel, 'accepted', operation, mode, 'pending') + # Engine acknowledges the fixed broadcast. Losing the engine/socket + # cannot cancel an accepted durable transaction: timeout then proceed. + try: + channel.settimeout(2) + data, _, flags, _ = channel.recvmsg(128) + notified = not flags & socket.MSG_TRUNC and data == f'C4M1 notified {operation}'.encode() + except OSError: notified = False + receipt(operation, mode, 'accepted', 'pending') + tx['players_notified'] = notified + controller.phase(tx, 'pending', players_notified=notified) + channel.close() + if not notified: + try: + current = controller.inspect() + if current['State']['Running'] and current['State']['Pid'] == peer_pid: return False + except Exception: return False + return True + controller.transition(mode, rules, operation=operation, on_ready=ready) + # Already-active is a successful no-op, not a completed transition. + phase, active_id, _ = public_status() + if active_id != operation: + receipt(operation, mode, 'already_active', 'success') + if channel.fileno() >= 0: response(channel, 'already_active', operation, mode, 'success') + else: receipt(operation, mode, phase, phase) + except Exception: + phase, active_id, active_mode = public_status() + if phase in ('rolling_back', 'pending', 'verifying', 'recovery_required') and active_id == operation: + # Startup reconciliation will restore only the previous exact runtime. + pass + if active_id != operation: + receipt(operation, mode, 'not_qualified', 'denied') + elif phase in TERMINAL | {'recovery_required'}: receipt(operation, mode, phase, phase) + if channel is not None and channel.fileno() >= 0: + response(channel, 'not_qualified', operation, mode, 'denied') + finally: + if channel is not None: channel.close() + + +class Bridge: + def __init__(self): + self.children = [] + self.inspection = {} + self.refreshed = 0 + + def refresh(self): + if time.monotonic() - self.refreshed < 1: return + self.refreshed = time.monotonic() + try: + result = subprocess.run(['docker', 'inspect', 'cod4-production'], capture_output=True, text=True, timeout=2, check=True) + self.inspection = json.loads(result.stdout)[0] + except Exception: self.inspection = {} + + def lock(self): + stream = c.trusted(c.DEPLOY_LOCK).open('r') + try: fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: stream.close(); return None + if c.DEPLOY_GUARD.exists() or c.DEPLOY_GUARD.is_symlink(): stream.close(); return None + return stream + + def spawn(self, operation, mode, connection=None, credentials=(0, 0, 0)): + lock = self.lock() + if lock is None: + if connection is not None: response(connection, 'busy', operation, mode, 'pending') + return + if mode != 'recover': receipt(operation, mode, 'submitted', 'pending') + log = c.STATE / ('bridge-worker-' + operation + '.log') + with log.open('ab') as output: + os.fchmod(output.fileno(), 0o600) + fd = connection.fileno() if connection is not None else -1 + process = subprocess.Popen([sys.executable, '-I', str(Path(__file__).resolve()), 'worker', + operation, mode, str(credentials[0]), self.inspection.get('Id', 'none'), str(fd), str(lock.fileno())], + stdin=subprocess.DEVNULL, stdout=output, stderr=output, start_new_session=True, + pass_fds=tuple(v for v in (fd, lock.fileno()) if v >= 0)) + self.children.append(process) + lock.close() # Worker owns the open-file lease, including subprocesses. + + def recover(self): + phase, operation, mode = public_status() + if phase not in TERMINAL | {'idle', 'recovery_required'}: + self.spawn(operation, 'recover') + else: + lock = self.lock() + if lock is not None: + status = bridge_status() + if status.get('code') in ('submitted', 'accepted'): + receipt(status['operation'], status['target_mode'], 'failed', 'denied') + lock.close() + + def handle(self, connection): + credentials = struct.unpack('3i', connection.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12)) + # Reject other processes before expensive trust/qualification operations. + if not peer_matches(credentials, self.inspection): + response(connection, 'denied'); return + connection.settimeout(.2) + data, _, flags, _ = connection.recvmsg(256) + if flags & socket.MSG_TRUNC: response(connection, 'invalid'); return + match = REQUEST.fullmatch(data) + if data != b'C4M1 status' and match is None: + response(connection, 'invalid'); return + operation = match[1].decode() if match else 'none' + mode = match[2].decode() if match else 'none' + try: rules = registry() + except Exception: + response(connection, 'disabled', operation, mode); return + if rules.get('rcon_bridge_enabled') is not True: + response(connection, 'disabled', operation, mode); return + try: c.qualification(rules) + except Exception: + response(connection, 'not_qualified', operation, mode); return + try: policy(rules) + except Exception: + response(connection, 'disabled', operation, mode); return + if data == b'C4M1 status': + status = bridge_status() + phase = status.get('phase', 'idle') + response(connection, status.get('code', phase), status.get('operation', 'none'), status.get('target_mode', 'none'), phase) + else: + operation, mode = (v.decode() for v in match.groups()) + phase, _, _ = public_status() + if phase == 'recovery_required': + response(connection, 'recovery_required', operation, mode, phase); return + self.spawn(operation, mode, connection, credentials) + + def serve(self): + c.trusted(SOCKET.parent, directory=True) + # Separate daemon lease allows stale socket cleanup only by one owner. + with (c.STATE / 'bridge.lock').open('a') as lease: + fcntl.flock(lease, fcntl.LOCK_EX | fcntl.LOCK_NB) + if SOCKET.exists() or SOCKET.is_symlink(): + if not stat.S_ISSOCK(SOCKET.lstat().st_mode) or SOCKET.lstat().st_uid != 0: + raise ValueError('Unexpected bridge socket entry') + SOCKET.unlink() + with socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) as listener: + listener.bind(str(SOCKET)); os.chmod(SOCKET, 0o666); listener.listen(8) + self.recover() + while True: + self.refresh() + self.children = [p for p in self.children if p.poll() is None] + if not self.children: self.recover() + if not select.select([listener], [], [], 1)[0]: continue + connection, _ = listener.accept() + with connection: + try: self.handle(connection) + except (OSError, ValueError, KeyError): response(connection, 'invalid') + + +def load_controller(): + import types + # This small bootstrap must precede execution of any adjacent private code. + for path in (Path(__file__).absolute(), SCRIPTS/'mode-controller.py'): + for item in (path, *path.parents): + metadata = item.lstat() + if stat.S_ISLNK(metadata.st_mode) or metadata.st_uid != 0 or metadata.st_mode & 0o022: + raise ValueError('Untrusted bridge installation') + module = types.ModuleType('mode_controller') + source = SCRIPTS/'mode-controller.py'; module.__file__ = str(source) + exec(compile(source.read_bytes(), str(source), 'exec'), module.__dict__) + return module + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('command', choices=('serve', 'worker')) + parser.add_argument('worker_args', nargs='*') + args = parser.parse_args() + if os.geteuid() != 0: parser.error('Host root authorization required') + os.umask(0o077) + global c + c = load_controller() + for path in (SCRIPTS, Path(__file__), SCRIPTS/'mode-controller.py', SCRIPTS/'common.sh', SCRIPTS/'runtime.py', c.STATE): + c.trusted(path, directory=path in (SCRIPTS, c.STATE)) + c.trusted(c.DEPLOY_LOCK) + if not c.DEPLOY_LOCK.is_file() or stat.S_IMODE(c.DEPLOY_LOCK.stat().st_mode) != 0o644: + parser.error('Root-owned shared deployment lock mode 0644 required') + c.load_runtime() + if args.command == 'serve': + if args.worker_args: parser.error('serve takes no arguments') + Bridge().serve() + else: + if len(args.worker_args) != 6: parser.error('Invalid internal worker arguments') + operation, mode, pid, container, descriptor, lock = args.worker_args + if not re.fullmatch(r'[a-f0-9]{32}', operation) or mode not in {*c.MODES, 'recover'}: + parser.error('Invalid internal worker') + # Workers are host-root children, never a container command API. + worker(operation, mode, int(pid), container, int(descriptor), int(lock)) + + +if __name__ == '__main__': + try: main() + except Exception: sys.exit('Mode bridge stopped; inspect private host diagnostics') diff --git a/scripts/mode-controller.py b/scripts/mode-controller.py index ee6f0ad..bd3fbc1 100644 --- a/scripts/mode-controller.py +++ b/scripts/mode-controller.py @@ -17,6 +17,7 @@ import time import tarfile import uuid +import shutil SCRIPTS = Path(__file__).resolve().parent MODES = {'promod': ('mods/pml220', 'sd'), 'zombies': ('mods/btd_alpha_001', 'war')} @@ -24,13 +25,19 @@ STATE = Path('/opt/services/cod4/.mode-controller') EXTERNAL_VERIFIER = Path('/etc/cod4-modes/external-verify') IMAGE_RE = __import__('re').compile(r'sha256:[0-9a-f]{64}') +DEPLOY_LOCK = Path('/opt/services/cod4/.production-transition.lock') +DEPLOY_GUARD = Path('/opt/services/cod4/.production-deployment.json') +LOCK_FD = None runtime = None def load_runtime(): global runtime - spec = importlib.util.spec_from_file_location('runtime', SCRIPTS / 'runtime.py') - runtime = importlib.util.module_from_spec(spec); spec.loader.exec_module(runtime) + import types + source = SCRIPTS / 'runtime.py' + runtime = types.ModuleType('runtime') + runtime.__file__ = str(source) + exec(compile(source.read_bytes(), str(source), 'exec'), runtime.__dict__) def trusted(path, directory=False): @@ -59,7 +66,8 @@ def atomic(path, value): def run(argv, payload=None, audit=None): # Child output can contain private configuration; never echo it on errors. - result = subprocess.run(argv, input=payload, text=True, capture_output=True, timeout=300) + result = subprocess.run(argv, input=payload, text=True, capture_output=True, timeout=300, + pass_fds=(() if LOCK_FD is None else (LOCK_FD,))) if audit is not None: atomic(audit, {'exit_code': result.returncode, 'stdout': result.stdout, 'stderr': result.stderr}) if result.returncode: @@ -78,6 +86,12 @@ def primitive(operation, payload=None, audit=None): class Controller: + container = 'cod4-production' + project = 'cod4-production' + udp_port = 28960 + private_home = Path('/opt/services/cod4/production/home') + readiness_timeout = 90 + def __init__(self, state=STATE): self.state = state self.current = None @@ -85,18 +99,21 @@ def __init__(self, state=STATE): self.operation = None def inspect(self): - return json.loads(run(['docker', 'inspect', 'cod4-production']))[0] + return json.loads(run(['docker', 'inspect', self.container]))[0] def snapshot(self): config = json.loads(primitive('snapshot')) - if config.get('name') != 'cod4-production' or set(config['services']) != {'cod4'}: + return self.validate_snapshot(config) + + def validate_snapshot(self, config): + if config.get('name') != self.project or set(config['services']) != {'cod4'}: raise ValueError('Unexpected production Compose project/services') service = config['services']['cod4'] - if service.get('container_name') != 'cod4-production' or service.get('build'): + if service.get('container_name') != self.container or service.get('build'): raise ValueError('Expected pinned prebuilt production service') if service.get('read_only') is not True: raise ValueError('Production root filesystem must be read-only') - if not any(p.get('protocol') == 'udp' and str(p.get('published')) == '28960' + if not any(p.get('protocol') == 'udp' and str(p.get('published')) == str(self.udp_port) and p.get('target') == 28960 for p in service.get('ports', [])): raise ValueError('Expected UDP 28960 mapping') return config @@ -127,7 +144,12 @@ def backup_private(self, config, operation): if len(homes) != 1 or homes[0].get('type') != 'bind': raise ValueError('Expected one explicit persistent home bind mount') source = Path(homes[0]['source']) - if source != Path('/opt/services/cod4/production/home') or not source.is_dir(): + trusted(source.parent, directory=True) + if source.is_symlink() or source.stat().st_dev != self.state.stat().st_dev: + raise ValueError('Private home must be a directory on the rollback filesystem') + if any(v.get('target') != runtime.PERSISTENT_HOME and v.get('type') != 'tmpfs' and v.get('read_only') is not True for v in volumes): + raise ValueError('Only the private home may be a writable persistent mount') + if source != self.private_home or not source.is_dir(): raise ValueError('Unexpected private home source') archive = self.state / (operation + '-private.tar.gz') with archive.open('xb') as stream: @@ -135,6 +157,7 @@ def backup_private(self, config, operation): with tarfile.open(fileobj=stream, mode='w:gz', dereference=False) as tar: tar.add(source, arcname='production/home') stream.flush(); os.fsync(stream.fileno()) + with tarfile.open(archive, 'r:gz') as tar: self.validate_members(tar.getmembers()) def apply(self, config): self.audit_sequence += 1 @@ -144,8 +167,9 @@ def apply(self, config): def query(self, host): with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.settimeout(4) - s.sendto(b'\xff' * 4 + b'getstatus\n', (host, 28960)) - data, _ = s.recvfrom(65535) + s.connect((host, self.udp_port)) + s.send(b'\xff' * 4 + b'getstatus\n') + data = s.recv(65535) if not data.startswith(b'\xff' * 4 + b'statusResponse\n'): raise ValueError('Invalid UDP status response') fields = data.split(b'\n')[1].split(b'\\') @@ -181,7 +205,7 @@ def verify(self, config, mode, record, operation): if observed['HostConfig'].get('PortBindings') != before['HostConfig'].get('PortBindings'): raise ValueError('Published ports changed') # Poll readiness only; this never repeats recreation. - deadline = time.monotonic() + 90 + deadline = time.monotonic() + self.readiness_timeout while True: try: local = self.query('127.0.0.1') @@ -217,7 +241,7 @@ def phase(self, tx, phase, **extra): atomic(self.state / (tx['operation'] + '.json'), tx) print(json.dumps({k: tx[k] for k in ('operation', 'phase', 'previous_mode', 'target_mode')}), flush=True) - def transition(self, mode, registry): + def transition(self, mode, registry, operation=None, on_ready=None): if mode not in MODES: raise ValueError('Only zombies and promod are allowed') active = self.state / 'active.json' @@ -241,16 +265,23 @@ def transition(self, mode, registry): target = json.loads(json.dumps(config)) runtime.adapt(target['services']['cod4'], records[mode]['image'], mode, labels['io.cod4.config.hash'], *contract) - tx = {'operation': uuid.uuid4().hex, 'previous_mode': previous, 'target_mode': mode, + operation = operation or uuid.uuid4().hex + if not __import__('re').fullmatch(r'[a-f0-9]{32}', operation): + raise ValueError('Invalid operation identifier') + tx = {'operation': operation, 'previous_mode': previous, 'target_mode': mode, 'previous_image': self.current['Image'], 'target_image': records[mode]['image'], 'operator_uid': os.getuid(), 'started_at': time.time()} # Exact private configuration stays in restrictive snapshots, outside the # journal and stdout. It is never reconstructed from mode defaults. atomic(self.state / (tx['operation'] + '-previous.json'), baseline) atomic(self.state / (tx['operation'] + '-target.json'), target) + atomic(self.state / (tx['operation'] + '-inspection.json'), self.current) self.operation = tx['operation'] self.backup_private(baseline, tx['operation']) self.phase(tx, 'pending') + if on_ready is not None and on_ready(tx) is False: + self.phase(tx, 'denied', failure='PlayerNotificationUnavailable') + return try: self.apply(target) self.phase(tx, 'verifying') @@ -260,6 +291,7 @@ def transition(self, mode, registry): # Keep private subprocess output out of the journal. self.phase(tx, 'rolling_back', failure=type(error).__name__, failure_detail=str(error)[:200]) try: + self.restore_private(baseline, tx['operation']) self.apply(baseline) self.verify(baseline, previous, registry, tx['operation']) except Exception as rollback: @@ -268,6 +300,91 @@ def transition(self, mode, registry): self.phase(tx, 'rolled_back') raise RuntimeError('Transition failed; exact previous runtime restored') from None + def restore_private(self, config, operation): + """Stop only production before atomically restoring the archived home. + + Keep the failed home privately for diagnosis. Never extract through links. + """ + if run(['docker', 'ps', '-a', '--filter', 'name=^/' + self.container + '$', '--format', '{{.ID}}']).strip(): + run(['docker', 'stop', '--time', '10', self.container]) + self.restore_home(config, operation) + + def restore_home(self, config, operation): + home = self.private_home + mounts = config['services']['cod4']['volumes'] + if [v.get('source') for v in mounts if v.get('target') == runtime.PERSISTENT_HOME] != [str(home)]: + raise ValueError('Unexpected rollback private home') + self.extract_home(home, operation) + + @staticmethod + def validate_members(members): + links = {m.name for m in members if m.issym() or m.islnk()} + by_name = {member.name: member for member in members} + if len(by_name) != len(members): raise ValueError('Duplicate private archive member') + for member in members: + name = Path(member.name) + if str(name) != member.name or name.is_absolute() or '..' in name.parts or name.parts[:2] != ('production', 'home'): + raise ValueError('Unsafe private archive member') + if any(str(parent) in links for parent in name.parents): + raise ValueError('Private archive traverses a link') + if not (member.isfile() or member.isdir() or member.issym() or member.islnk()): + raise ValueError('Special private archive member') + if member.islnk(): + link = Path(member.linkname) + if str(link) != member.linkname or link.is_absolute() or '..' in link.parts or link.parts[:2] != ('production', 'home') or str(link) in links or any(str(parent) in links for parent in link.parents): + raise ValueError('Unsafe archive hard link') + if str(link) not in by_name or not by_name[str(link)].isfile(): + raise ValueError('Archive hard link lacks a regular target') + + def extract_home(self, home, operation): + # Archive contents were produced locally before mutation. Validate again + # for crash recovery and reject special files or extraction through links. + stage = self.state / (operation + '-restore-' + uuid.uuid4().hex) + stage.mkdir(mode=0o700) + with tarfile.open(self.state / (operation + '-private.tar.gz'), 'r:gz') as tar: + members = tar.getmembers() + self.validate_members(members) + # All destinations and hardlinks are bounded; symlinks have no children. + tar.extractall(stage, members=members, **({'filter': 'fully_trusted'} if sys.version_info >= (3,12) else {})) + restored = stage / 'production/home' + if not restored.is_dir() or restored.is_symlink(): raise ValueError('Missing private archive root') + failed = self.state / (operation + '-failed-home-' + uuid.uuid4().hex) + if home.exists(): os.rename(home, failed) + os.rename(restored, home) + descriptor = os.open(home.parent, os.O_RDONLY | os.O_DIRECTORY) + try: os.fsync(descriptor) + finally: os.close(descriptor) + shutil.rmtree(stage) + + def recover(self, registry): + """Resume only the previous image; revoking the target cannot force it live.""" + active = self.state / 'active.json' + if not active.exists(): return + tx = None + try: + tx = json.loads(active.read_text()) + if tx['phase'] in ('success', 'rolled_back', 'denied'): return + operation = tx['operation'] + if not __import__('re').fullmatch(r'[a-f0-9]{32}', operation): raise ValueError('Invalid recovery operation') + record = rollback_qualification(registry, tx['previous_mode']) + baseline = json.loads((self.state / (operation + '-previous.json')).read_text()) + if record['image'] != baseline['services']['cod4']['image'] or record['image'] != tx['previous_image']: + raise ValueError('Recovery image is not qualified') + self.image(record, tx['previous_mode']) + self.current = json.loads((self.state / (operation + '-inspection.json')).read_text()) + self.operation = operation + self.phase(tx, 'rolling_back', failure='InterruptedWorker') + self.restore_private(baseline, operation) + self.apply(baseline) + self.verify(baseline, tx['previous_mode'], registry, operation) + self.phase(tx, 'rolled_back') + except Exception: + if not isinstance(tx, dict) or not __import__('re').fullmatch(r'[a-f0-9]{32}', str(tx.get('operation', ''))): + shutil.copyfile(active, self.state / ('corrupt-active-' + uuid.uuid4().hex + '.json')) + tx = {'operation':uuid.uuid4().hex, 'previous_mode':'unknown', 'target_mode':'unknown'} + self.phase(tx, 'recovery_required', rollback_failure='RecoveryFailed') + raise RuntimeError('Interrupted transition requires operator recovery') from None + def qualification(registry): if registry.get('enabled') is not True: @@ -291,6 +408,20 @@ def qualification(registry): return records +def rollback_qualification(registry, mode): + # Restoring a previously approved image does not require the failed target + # or RCON activation to remain approved. Its own evidence must remain valid. + if mode not in MODES: raise ValueError('Unknown rollback mode') + record = registry['modes'][mode] + if record.get('qualified') is not True: raise ValueError('Rollback image not qualified') + for gate in ('independent_review', 'mandatory_ci', 'operator_approval', 'gameplay'): + evidence(record['evidence'][gate]) + if record['evidence'][gate].get('image') != record['image']: raise ValueError('Rollback evidence image mismatch') + if record['evidence']['gameplay'].get('actual_client_session') is not True: + raise ValueError('Rollback image lacks actual-client qualification') + return record + + def evidence(record): path = trusted(Path(record['path'])) if hashlib.sha256(path.read_bytes()).hexdigest() != record['sha256']: @@ -299,7 +430,7 @@ def evidence(record): def main(): p = argparse.ArgumentParser(description=__doc__) - p.add_argument('command', choices=('switch', 'status')) + p.add_argument('command', choices=('switch', 'status', 'recover')) p.add_argument('mode', nargs='?', choices=tuple(MODES)) args = p.parse_args() if os.geteuid() != 0: @@ -310,12 +441,18 @@ def main(): trusted(path) trusted(STATE, directory=True) load_runtime() - with (STATE / 'transition.lock').open('a') as lock: + global LOCK_FD + with trusted(DEPLOY_LOCK).open('r') as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: p.exit(2, 'busy: another host transition is pending\n') + if DEPLOY_GUARD.exists() or DEPLOY_GUARD.is_symlink(): + p.exit(2, 'busy: production deployment active or interrupted; operator recovery required\n') + LOCK_FD = lock.fileno() if args.command == 'status': active = STATE / 'active.json' print(active.read_text() if active.exists() else '{"phase":"idle"}') + elif args.command == 'recover': + Controller().recover(json.loads(trusted(REGISTRY).read_text())) else: if args.mode is None: p.error('switch requires a mode') registry = json.loads(trusted(REGISTRY).read_text()) diff --git a/tests/mode_fixture.c b/tests/mode_fixture.c new file mode 100644 index 0000000..a0058ba --- /dev/null +++ b/tests/mode_fixture.c @@ -0,0 +1,36 @@ +/* Disposable UDP mode responder, not a game or a qualified artifact. */ +#include +#include +#include +#include +#include +#include +#include +#ifndef FAIL_START +#define FAIL_START 0 +#endif +int main(int argc,char **argv) { + const char *game="mods/pml220",*home="/home/user/.callofduty4"; + for(int i=1;i+20) { + sendto(fd,reply,size,0,(struct sockaddr*)&peer,length); + if(n==10 && !memcmp(query,"peer-probe",10)) { + int ipc=socket(AF_UNIX,SOCK_SEQPACKET,0);struct sockaddr_un endpoint={.sun_family=AF_UNIX}; + strcpy(endpoint.sun_path,"/run/cod4-mode-bridge/control.sock"); + if(!connect(ipc,(struct sockaddr*)&endpoint,sizeof(endpoint)))send(ipc,"fixture-peer-proof",18,0); + close(ipc); + } + }} +} diff --git a/tests/operations.sh b/tests/operations.sh index 7a94539..31daea7 100755 --- a/tests/operations.sh +++ b/tests/operations.sh @@ -269,6 +269,7 @@ apply_count=0 remote() { printf '%s\n' "$*" >> "$test_root/remote.log" case "$1 $2" in + 'bash -c') [[ "$*" == *mode-deployment-lease* ]] || return 1; printf "legacy\n"; read -r release ;; 'docker version') printf 'linux/amd64\n' ;; 'docker inspect') if [[ "$*" == *'{{.Image}} {{.State.Running}}'* ]]; then printf '%s true\n' "${homolog_id:-$artifact_id}" @@ -299,6 +300,10 @@ if grep -Eq 'docker image load|^apply |^confirm$' "$test_root/remote.log"; then deploy_image "$artifact_id" >/dev/null read -r approved approved_revision approved_assets approved_bots approved_config approved_mode approved_hash < "$ROOT/.state/approved" [[ "$approved" == "$artifact_id" && "$approved_revision" == "$expected" && "$approved_assets" == "$asset_ref" && "$approved_bots" == "$bot_revision" && "$approved_config" == "$expected_config" && "$approved_mode" == promod && "$approved_hash" == "$config_hash" ]] +cp "$ROOT/.state/approved" "$test_root/preserved-approval" +if (apply_count=0; write_artifact_record() { printf partial; return 1; }; deploy_image "$artifact_id") > "$test_root/approval-failure" 2>&1; then exit 1; fi +grep -q 'Cannot write complete approval record' "$test_root/approval-failure" +cmp "$ROOT/.state/approved" "$test_root/preserved-approval" grep -q 'canonical-shared.cfg' "$test_root/applied" grep -q '/opt/cod4-artifact/cod4x18_dedrun' "$test_root/applied" grep -q '"source": "/persist"' "$test_root/applied" diff --git a/tests/run_mode_compose.py b/tests/run_mode_compose.py new file mode 100644 index 0000000..4b980a0 --- /dev/null +++ b/tests/run_mode_compose.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python3 +"""Disposable local Compose transaction qualification; NO production activation. + +Uses static UDP fixture executables, not licensed games or qualification records. +Production defaults remain fixed. Only this test subclass selects owned names. +No image builds, pulls, Git operations or downloads occur during transitions. +""" +import contextlib +import copy +import importlib.util +import io +import json +import os +from pathlib import Path +import socket +import subprocess +import tempfile +import uuid +from unittest.mock import patch + +ROOT=Path(__file__).resolve().parents[1] +spec=importlib.util.spec_from_file_location('controller',ROOT/'scripts/mode-controller.py') +m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m);m.load_runtime() +project='c4-mode-test-'+uuid.uuid4().hex[:10] +root=Path(tempfile.mkdtemp(prefix=project+'-')) +state=root/'state';state.mkdir();home=root/'home';home.mkdir() +(root/'bridge').mkdir() +listener=socket.socket(socket.AF_UNIX,socket.SOCK_SEQPACKET) +listener.bind(str(root/'bridge/control.sock'));listener.listen(1);listener.settimeout(3) +(home/'private.cfg').write_text('private-fixture-original') +for part in ('main','zone'):(root/part).mkdir() + + +def command(args): + result=subprocess.run(args,text=True,capture_output=True,timeout=120) + if result.returncode:raise RuntimeError(f'{args[0:2]} failed; private fixture evidence: {root}') + return result.stdout + +endpoint=command(['docker','context','inspect','--format','{{.Endpoints.docker.Host}}']).strip() +assert endpoint=='unix:///var/run/docker.sock','Only the local Unix Docker context is allowed' +assert not os.environ.get('DOCKER_HOST') and not os.environ.get('DOCKER_CONTEXT'),'No Docker endpoint overrides permitted' +for port in (28960,28962): + with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as probe:probe.bind(('0.0.0.0',port)) +base=command(['docker','image','inspect','python:3.12-slim','--format','{{.Id}}']).strip() +records={};created_images=[];configs=[];checks={};public=io.StringIO() +(root/'runtime').mkdir() +common=root/'common-fixture.sh' +common.write_text((ROOT/'scripts/common.sh').read_text().replace('/opt/services/cod4',str(root/'runtime'))) + +def apply_config(value): + body='set -euo pipefail; source "$1"; remote() { "$@"; }; environment=production; project=$2; service=cod4; work=$3; apply_runtime' + m.run(['bash','-c',body,'compose-fixture',str(common),project,str(root/'runtime')],payload=json.dumps(value)) + +def compose(path):return ['docker','compose','-p',project,'-f',str(path)] + +def inspect(name):return json.loads(command(['docker','inspect',name]))[0] + +try: + # Preparation only. The switching methods below never invoke a builder. + for mode,fail in (('promod',False),('zombies',False),('broken',True)): + stage=root/mode;stage.mkdir() + command(['gcc','-static','-O2',f'-DFAIL_START={int(fail)}',str(ROOT/'tests/mode_fixture.c'),'-o',str(stage/'fixture')]) + selected='zombies' if mode=='broken' else mode + labels={'org.opencontainers.image.revision':'0'*40,'org.opencontainers.image.source':'test-only', + 'io.cod4.assets.lock':'0'*64,'io.cod4.bot-warfare.revision':'none','io.cod4.config.revision':'0'*40, + 'io.cod4.config.hash':'0'*64,'io.cod4.mode':selected,'io.cod4.fs-game':m.MODES[selected][0], + 'io.cod4.startup-map':'mp_crash','io.cod4.maps':'mp_crash','io.cod4.maxclients':'12', + 'io.cod4.disposable-fixture':project} + dockerfile=f'FROM {base}\nCOPY fixture {m.runtime.EXECUTABLE}\nWORKDIR {m.runtime.ARTIFACT_ROOT}\nUSER 1000:1000\n' + dockerfile+='LABEL '+' '.join(k+'='+json.dumps(v) for k,v in labels.items())+'\n' + (stage/'Dockerfile').write_text(dockerfile) + env={**os.environ,'DOCKER_BUILDKIT':'0'} + built=subprocess.run(['docker','build','--pull=false','--network=none','-q',str(stage)],env=env,text=True,capture_output=True,timeout=120) + (stage/'build.log').write_text(built.stdout+'\n'+built.stderr) + assert built.returncode==0,f'Local fixture build failed: {root}' + image=built.stdout.strip().splitlines()[-1];created_images.append(image) + records[mode]={'image':image,'labels':labels} + sentinel=project+'-homolog' + config={'name':project,'services':{'cod4':{'container_name':project+'-production','image':records['promod']['image'], + 'entrypoint':[m.runtime.EXECUTABLE],'working_dir':m.runtime.ARTIFACT_ROOT,'read_only':True, + 'environment':{'PRIVATE_CANARY':'fixture-$private'}, + 'volumes':[{'type':'bind','source':str(root/'main'),'target':'/home/user/cod4/main','read_only':True}, + {'type':'bind','source':str(root/'zone'),'target':'/home/user/cod4/zone','read_only':True}, + {'type':'bind','source':str(home),'target':m.runtime.PERSISTENT_HOME}, + {'type':'bind','source':str(root/'bridge'),'target':'/run/cod4-mode-bridge','read_only':True}], + 'labels':{'io.cod4.disposable-fixture':project}, + 'ports':[{'target':28960,'published':'28960','protocol':'udp'}], + 'command':['+set','fs_homepath',m.runtime.PERSISTENT_HOME,'+exec','private.cfg','+map','mp_crash']}}} + m.runtime.adapt(config['services']['cod4'],records['promod']['image'],'promod','0'*64,*m.runtime.startup_values(records['promod']['labels'])) + initial=root/'initial.json';initial.write_text(json.dumps(config));configs.append(initial) + apply_config(config) + command(['docker','run','-d','--name',sentinel,'--label','io.cod4.disposable-fixture='+project, + '--read-only','-p','28962:28960/udp','--entrypoint',m.runtime.EXECUTABLE,records['promod']['image']]) + sentinel_before=inspect(sentinel) + + class Fixture(m.Controller): + container=project+'-production';private_home=home;readiness_timeout=3 + def __init__(self):super().__init__(state);self.project=project;self.current_config=copy.deepcopy(config) + def snapshot(self):return self.validate_snapshot(copy.deepcopy(self.current_config)) + def apply(self,value): + self.current_config=copy.deepcopy(value) + path=root/('apply-'+uuid.uuid4().hex+'.json');path.write_text(json.dumps(value));configs.append(path) + apply_config(value) + def external(self,record,operation): + # Separate network namespace traverses the published host UDP port. + code="""import socket,json +s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM);s.settimeout(3);s.connect(('host.docker.internal',28960));s.send(b'\\xff'*4+b'getstatus\\n');data=s.recv(65535).split(b'\\n')[1].split(b'\\\\');print(json.dumps({k.decode():v.decode() for k,v in zip(data[1::2],data[2::2])}))""" + result=json.loads(command(['docker','run','--rm','--read-only','--add-host','host.docker.internal:host-gateway',base,'python3','-c',code])) + result.update(external=True,operation=operation);return result + controller=Fixture() + real_trusted=m.trusted + def fixture_trust(path,directory=False): + # Only ownership policy is substituted for this /tmp test namespace. + # Production root ownership remains separately enforced and tested. + if Path(path).is_relative_to(root):return Path(path) + return real_trusted(path,directory=directory) + qualified={key:records[key] for key in ('promod','zombies')} + with patch.object(m,'qualification',side_effect=lambda registry:qualified),patch.object(m,'trusted',side_effect=fixture_trust),contextlib.redirect_stdout(public): + controller.verify(config,'promod',{},'initial') + with socket.socket(socket.AF_INET,socket.SOCK_DGRAM) as udp: + udp.sendto(b'peer-probe',('127.0.0.1',28960)) + peer,_=listener.accept() + with peer: + import struct + credentials=struct.unpack('3i',peer.getsockopt(socket.SOL_SOCKET,socket.SO_PEERCRED,12)) + checks['kernel_peer_is_container_engine']=credentials[0]==controller.inspect()['State']['Pid'] + spec=importlib.util.spec_from_file_location('bridge_peer_test',ROOT/'scripts/mode-bridge.py') + bridge=importlib.util.module_from_spec(spec);spec.loader.exec_module(bridge);bridge.c=m + checks['peer_executable_and_cgroup_identity']=bridge.process_matches(credentials[0],controller.inspect()['Id']) + controller.transition('zombies',{}) + checks['promod_to_zombies']=controller.query('127.0.0.1')['fs_game']==m.MODES['zombies'][0] + controller.transition('promod',{}) + checks['zombies_to_promod']=controller.query('127.0.0.1')['fs_game']==m.MODES['promod'][0] + baseline=copy.deepcopy(controller.current_config) + qualified['zombies']=records['broken'] + try:controller.transition('zombies',{}) + except RuntimeError as exc:checks['failed_health_exact_rollback']='exact previous runtime restored' in str(exc) + else:checks['failed_health_exact_rollback']=False + checks['exact_image_rollback']=controller.inspect()['Image']==records['promod']['image'] + checks['private_bytes_rollback']=(home/'private.cfg').read_text()=='private-fixture-original' + checks['exact_runtime_rollback']=controller.current_config==baseline + checks['private_mounts_environment_ports']=('PRIVATE_CANARY=fixture-$private' in controller.inspect()['Config']['Env']) and all(controller.current_config['services']['cod4'][k]==config['services']['cod4'][k] for k in ('volumes','environment','ports')) + checks['external_udp_after_rollback']=controller.external({},'rollback')['fs_game']==m.MODES['promod'][0] + checks['homolog_isolation']=inspect(sentinel)['Id']==sentinel_before['Id'] and inspect(sentinel)['State']['Pid']==sentinel_before['State']['Pid'] + checks['no_private_canary_in_public_status']='fixture-$private' not in public.getvalue() + (root/'public-journal.log').write_text(public.getvalue()) +finally: + listener.close() + # Cleanup is bounded to names and images created by this invocation. + for name in (project+'-production',project+'-homolog'): + result=subprocess.run(['docker','inspect',name],text=True,capture_output=True) + if result.returncode==0: + data=json.loads(result.stdout)[0] + assert data['Config']['Labels'].get('io.cod4.disposable-fixture')==project + subprocess.run(['docker','rm','-f',name],capture_output=True) + if configs:subprocess.run(compose(configs[0])+['down','--remove-orphans'],capture_output=True) + for image in created_images:subprocess.run(['docker','image','rm',image],capture_output=True) +(root/'results.json').write_text(json.dumps({'evidence':str(root),'checks':checks,'real_game_qualification':False},indent=2)+'\n') +print(json.dumps({'evidence':str(root),'passed':sum(checks.values()),'failed':[k for k,v in checks.items() if not v]},indent=2)) +assert len(checks)==12 and all(checks.values()) diff --git a/tests/test_mode_bridge.py b/tests/test_mode_bridge.py new file mode 100644 index 0000000..2b40ccb --- /dev/null +++ b/tests/test_mode_bridge.py @@ -0,0 +1,193 @@ +"""Bridge authentication, framing, host leases and durable-job boundaries. + +All filesystem/process/socket fixtures are disposable. No Docker/SSH is invoked. +""" +import copy +import importlib.util +import json +import os +from pathlib import Path +import socket +import tempfile +import threading +import unittest +from unittest.mock import patch +from test_mode_controller import m, Fake, OLD, NEW + +ROOT=Path(__file__).resolve().parents[1] +spec=importlib.util.spec_from_file_location('bridge',ROOT/'scripts/mode-bridge.py') +b=importlib.util.module_from_spec(spec);spec.loader.exec_module(b);b.c=m +OP='a'*32 + +def inspection(): + return {'Id':'b'*64,'Name':'/cod4-production','Path':m.runtime.EXECUTABLE, + 'State':{'Pid':os.getpid(),'Running':True}, + 'Config':{'Labels':{'io.cod4.rcon-mode-bridge':'C4M1'}}, + 'Mounts':[{'Type':'bind','Source':str(b.SOCKET.parent),'Destination':str(b.SOCKET.parent),'RW':False}]} + +class BridgeSecurity(unittest.TestCase): + def setUp(self): + self.tmp=tempfile.TemporaryDirectory();self.addCleanup(self.tmp.cleanup) + self.state=Path(self.tmp.name);self.patch=patch.object(m,'STATE',self.state);self.patch.start();self.addCleanup(self.patch.stop) + + def test_peer_requires_production_pid_identity_and_readonly_endpoint(self): + good=inspection() + with patch.object(b,'process_matches',return_value=True): + self.assertTrue(b.peer_matches((os.getpid(),1000,1000),good)) + for key,value in [('Name','/cod4-homolog'),('Path','/bin/sh'),('Id','bad')]: + self.assertFalse(b.peer_matches((os.getpid(),1000,1000),{**good,key:value})) + for state in ({'Pid':os.getpid()+1,'Running':True},{'Pid':os.getpid(),'Running':False}): + self.assertFalse(b.peer_matches((os.getpid(),1000,1000),{**good,'State':state})) + bad=copy.deepcopy(good);bad['Mounts'][0]['RW']=True + self.assertFalse(b.peer_matches((os.getpid(),1000,1000),bad)) + with patch.object(b,'process_matches',return_value=False): + self.assertFalse(b.peer_matches((os.getpid(),1000,1000),good)) + + def exchange(self,payload,authorized=True,enabled=True): + client,server=socket.socketpair(socket.AF_UNIX,socket.SOCK_SEQPACKET) + with client,server: + client.send(payload);bridge=b.Bridge();bridge.inspection=inspection() + with patch.object(b,'process_matches',return_value=authorized),patch.object(b,'registry',return_value={'rcon_bridge_enabled':enabled}),patch.object(m,'qualification'),patch.object(b,'policy',side_effect=None if enabled else ValueError('disabled')),patch.object(bridge,'spawn') as spawn: + bridge.handle(server) + if spawn.called:return spawn.call_args + return client.recv(512) + + def test_valid_kernel_authenticated_request_and_status(self): + call=self.exchange(f'C4M1 switch {OP} zombies'.encode()) + self.assertEqual(call.args[:2],(OP,'zombies')) + self.assertEqual(call.args[3][0],os.getpid()) + self.assertEqual(self.exchange(b'C4M1 status'),b'C4M1 idle none none idle') + + def test_unrelated_process_or_disabled_policy_never_spawns(self): + self.assertIn(b'denied',self.exchange(f'C4M1 switch {OP} zombies'.encode(),authorized=False)) + self.assertIn(b'disabled',self.exchange(f'C4M1 switch {OP} zombies'.encode(),enabled=False)) + + def test_invalid_truncated_injected_or_extra_requests_never_spawn(self): + bad=[b'',b'{}',f'C4M1 switch {OP} hardcore'.encode(),f'C4M1 switch {OP} promod;quit'.encode(), + f'C4M1 switch {OP} promod extra'.encode(),f'C4M1 switch {OP} promod\0extra'.encode(), + f'C4M1 switch {OP} promod\n'.encode(),b'x'*300,b'C4M1 switch ../escape zombies'] + for value in bad: + with self.subTest(value=value):self.assertIn(b'invalid',self.exchange(value)) + + def test_explicit_activation_and_image_bound_evidence_required(self): + records={mode:{'image':image,'labels':{'io.cod4.rcon-mode-bridge':'C4M1'}} for mode,image in [('promod',OLD),('zombies',NEW)]} + rules={'modes':records,'rcon_bridge_enabled':True} + for gate in ('rcon_security_review','rcon_activation_approval'): + rules[gate]={'images':{mode:r['image'] for mode,r in records.items()}} + with patch.object(m,'qualification'),patch.object(m,'evidence'): + b.policy(rules) + with self.assertRaises(ValueError):b.policy({**rules,'rcon_bridge_enabled':False}) + changed=copy.deepcopy(rules);changed['rcon_activation_approval']['images']['zombies']=OLD + with self.assertRaises(ValueError):b.policy(changed) + changed=copy.deepcopy(rules);changed['modes']['promod']['labels']={} + with self.assertRaises(ValueError):b.policy(changed) + + def test_pending_and_failed_are_honest_status_codes(self): + client,server=socket.socketpair(socket.AF_UNIX,socket.SOCK_SEQPACKET) + with client,server: + for code in ('submitted','failed','rolled_back','accepted'): + b.response(server,code,OP,'zombies','pending') + self.assertIn((' '+code+' ').encode(),client.recv(512)) + + def test_shared_host_lock_and_orphan_marker_fail_closed(self): + import fcntl + lock=self.state/'lease';lock.touch();guard=self.state/'orphan' + bridge=b.Bridge() + with patch.object(m,'DEPLOY_LOCK',lock),patch.object(m,'DEPLOY_GUARD',guard),patch.object(m,'trusted',side_effect=lambda p,**kw:p): + with lock.open('r') as owned: + fcntl.flock(owned,fcntl.LOCK_EX|fcntl.LOCK_NB) + self.assertIsNone(bridge.lock()) + guard.write_text('interrupted-workstation') + self.assertIsNone(bridge.lock()) + guard.unlink();lease=bridge.lock();self.assertIsNotNone(lease);lease.close() + + def test_failed_recovery_is_not_retried_automatically(self): + m.atomic(self.state/'active.json',{'phase':'recovery_required','operation':OP,'target_mode':'zombies'}) + bridge=b.Bridge() + with patch.object(bridge,'lock',return_value=None),patch.object(bridge,'spawn') as spawn: + bridge.recover();spawn.assert_not_called() + + def test_untrusted_controller_is_not_executed_or_loaded_from_cache(self): + self.assertIsNone(b.__dict__.get('untrusted_code_executed')) + with self.assertRaises(ValueError):b.load_controller() + + def test_missing_recovery_evidence_records_blocked_terminal_state(self): + tx={'operation':OP,'previous_mode':'promod','target_mode':'zombies','previous_image':OLD,'phase':'pending'} + m.atomic(self.state/'active.json',tx) + with patch.object(m,'rollback_qualification',side_effect=ValueError('revoked')): + with self.assertRaises(RuntimeError):m.Controller(self.state).recover({}) + self.assertEqual(json.loads((self.state/'active.json').read_text())['phase'],'recovery_required') + + def test_accepted_host_job_survives_engine_socket_closure_and_replay_is_rejected(self): + records={'promod':{'image':OLD},'zombies':{'image':NEW}} + class Engine(Fake): + stopped=False + def inspect(self):return {'Id':'b'*64,'Image':self.config['services']['cod4']['image'],'State':{'Pid':os.getpid(),'Running':not self.stopped}} + controller=Engine(self.state) + client,server=socket.socketpair(socket.AF_UNIX,socket.SOCK_SEQPACKET) + received=[] + def engine(): + try: received.append(client.recv(512));controller.stopped=True + finally: client.close() + thread=threading.Thread(target=engine);thread.start() + with patch.object(b,'registry',return_value={}),patch.object(b,'policy'),patch.object(b,'peer_matches',return_value=True),patch.object(m,'Controller',return_value=controller),patch.object(m,'qualification',return_value=records): + b.worker(OP,'zombies',os.getpid(),'b'*64,server.detach(),-1) + thread.join(timeout=3);self.assertFalse(thread.is_alive());self.assertIn(b'accepted',received[0]);m.LOCK_FD=None + self.assertEqual(controller.config['services']['cod4']['image'],NEW) + self.assertEqual(json.loads((self.state/'active.json').read_text())['phase'],'success') + client,server=socket.socketpair(socket.AF_UNIX,socket.SOCK_SEQPACKET) + with client: + with patch.object(b,'registry',return_value={}),patch.object(b,'policy'),patch.object(b,'peer_matches',return_value=True),patch.object(m,'Controller',return_value=controller): + b.worker(OP,'zombies',os.getpid(),'b'*64,server.detach(),-1) + self.assertIn(b'replay',client.recv(512)) + self.assertEqual(len(controller.applied),1);m.LOCK_FD=None + +class DeploymentLeaseLifetime(unittest.TestCase): + def test_workstation_eof_keeps_guard_after_advisory_unlock(self): + import subprocess + text=(ROOT/'scripts/common.sh').read_text() + body=text.split("coproc MODE_LEASE { remote bash -c '\n",1)[1].split("\n' mode-deployment-lease; }",1)[0] + for release in (b'',b'hold\n',b'release\n'): + with self.subTest(release=release),tempfile.TemporaryDirectory() as d: + directory=Path(d);lock=directory/'lock';guard=directory/'guard';lock.touch();lock.chmod(0o644) + script=body.replace('/opt/services/cod4/.production-transition.lock',str(lock)).replace('/opt/services/cod4/.production-deployment.json',str(guard)) + script=script.replace('== 0 &&',f'== {os.getuid()} &&') + process=subprocess.Popen(['bash','-c',script],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE) + try: + self.assertEqual(process.stdout.readline(),b'locked\n') + if release:process.stdin.write(release);process.stdin.flush() + process.stdin.close();self.assertEqual(process.wait(timeout=3),0,process.stderr.read()) + self.assertEqual(guard.exists(),release!=b'release\n') + with patch.object(m,'DEPLOY_LOCK',lock),patch.object(m,'DEPLOY_GUARD',guard),patch.object(m,'trusted',side_effect=lambda p,**kw:p): + acquired=b.Bridge().lock() + self.assertEqual(acquired is None,guard.exists()) + if acquired:acquired.close() + finally: + if process.poll() is None:process.kill();process.wait() + process.stdout.close();process.stderr.close() + +class InheritedLease(unittest.TestCase): + def test_worker_death_does_not_release_an_inflight_child_lease(self): + import fcntl,subprocess,sys,time + with tempfile.TemporaryDirectory() as d: + root=Path(d);lock=root/'lock';ready=root/'ready';lock.touch() + code='''import importlib.util,sys,fcntl +from pathlib import Path +spec=importlib.util.spec_from_file_location("controller",Path(sys.argv[1])/"mode-controller.py") +m=importlib.util.module_from_spec(spec);spec.loader.exec_module(m) +with open(sys.argv[2],"r") as lock: + fcntl.flock(lock,fcntl.LOCK_EX);m.LOCK_FD=lock.fileno() + m.run([sys.executable,"-c","import sys,time;from pathlib import Path;Path(sys.argv[1]).write_text('ready');time.sleep(1)",sys.argv[3]]) +''' + worker=subprocess.Popen([sys.executable,'-c',code,str(ROOT/'scripts'),str(lock),str(ready)]) + try: + deadline=time.monotonic()+3 + while not ready.exists() and time.monotonic()