From 7bc75e91da2c6c86c206f54244ecde220910c4c4 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 18:46:45 -0600 Subject: [PATCH 1/5] Add guest verification phases for the install-to-uninstall battery (#663) Co-Authored-By: Claude Code --- tests/e2e-docs-guest.sh | 272 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 258 insertions(+), 14 deletions(-) diff --git a/tests/e2e-docs-guest.sh b/tests/e2e-docs-guest.sh index d7764b40..13e61bb8 100755 --- a/tests/e2e-docs-guest.sh +++ b/tests/e2e-docs-guest.sh @@ -2,7 +2,7 @@ set -Eeuo pipefail usage() { - echo "usage: $0 " >&2 + echo "usage: $0 " >&2 exit 2 } @@ -31,6 +31,22 @@ OS_RELEASE_FILE="${E2E_OS_RELEASE_FILE:-/etc/os-release}" SHARE_TIMEOUT="${E2E_SHARE_TIMEOUT:-180}" SHARE_INTERVAL="${E2E_SHARE_INTERVAL:-5}" ACTIVE_TIMEOUT="${E2E_ACTIVE_TIMEOUT:-60}" +CONTROL_PORT="${E2E_CONTROL_PORT:-8082}" +CONTROL_TIMEOUT="${E2E_CONTROL_TIMEOUT:-300}" +CONTROL_INTERVAL="${E2E_CONTROL_INTERVAL:-5}" +CONTROL_TOKEN="${E2E_CONTROL_TOKEN:-}" +CONTROL_STATE_DIR="${E2E_CONTROL_STATE_DIR:-/var/lib/rigforge-control-upgrade}" +CONTROL_PROBE_TAG="${E2E_CONTROL_PROBE_TAG:-v99.99.99}" +UPGRADE_LEG="${E2E_UPGRADE_LEG:-}" +EXPECTED_HEAD="${E2E_EXPECTED_HEAD:-}" +RESTORED_SHA256="${E2E_RESTORED_CONFIG_SHA256:-}" +ALLOW_NS="${E2E_ALLOWLIST_NS:-rfg-docs-allow}" +ALLOW_HOST_IF="${E2E_ALLOWLIST_HOST_IF:-rfgdocs-h}" +ALLOW_PEER_IF="${E2E_ALLOWLIST_PEER_IF:-rfgdocs-p}" +ALLOW_TARGET="${E2E_ALLOWLIST_TARGET:-169.254.241.1}" +ALLOW_REFUSED_SOURCE="${E2E_ALLOWLIST_REFUSED_SOURCE:-169.254.241.2}" +ALLOW_ALLOWED_SOURCE="${E2E_ALLOWLIST_ALLOWED_SOURCE:-169.254.241.3}" +ALLOW_NET="${E2E_ALLOWLIST_NET:-169.254.241.0/29}" read_file() { [ -f "$1" ] && cat "$1" || printf '\n' @@ -201,7 +217,7 @@ phase_baseline() { grep -qw avx2 "${E2E_CPUINFO_FILE:-/proc/cpuinfo}" || fail "guest CPU does not expose AVX2" [ "$(ps -p 1 -o comm= | tr -d ' ')" = systemd ] || fail "systemd is not PID 1" systemctl is-system-running --wait >/dev/null 2>&1 || fail "systemd is not running" - for tool in curl getent ip jq nft pgrep sha256sum ss systemctl; do + for tool in curl getent git ip jq nft pgrep sha256sum ss systemctl; do command -v "$tool" >/dev/null 2>&1 || fail "required guest tool is missing: $tool" done snapshot "$BASELINE" @@ -217,10 +233,8 @@ phase_dry_run_check() { done } -phase_installed() { - local peer summary accepted rejected waited=0 code active=0 nft_state - [ -d "$BASELINE" ] || fail "baseline is missing" - [ "$(cat "$BOOT_ID_FILE")" != "$(cat "$BASELINE/boot-id")" ] || fail "guest did not reboot after setup" +_assert_enabled_active() { + local waited=0 active=0 systemctl is-enabled --quiet xmrig.service || fail "xmrig is not enabled" while [ "$waited" -lt "$ACTIVE_TIMEOUT" ]; do if systemctl is-active --quiet xmrig.service; then @@ -231,18 +245,20 @@ phase_installed() { waited=$((waited + SHARE_INTERVAL)) done [ "$active" = 1 ] || fail "xmrig did not autostart within ${ACTIVE_TIMEOUT}s" - read_live_config +} + +_assert_donation_zero_config() { [ "$(jq -r '."donate-level"' "$GENERATED_CONFIG")" = 0 ] || fail "donate-level is not zero" [ "$(jq -r '."donate-over-proxy"' "$GENERATED_CONFIG")" = 0 ] || fail "donate-over-proxy is not zero" [ "$(jq -r '.http.restricted' "$GENERATED_CONFIG")" = true ] || fail "base API is not restricted" +} + +_assert_expected_peers() { + local peer waited=0 resolve_pool >"$STATE_DIR/pool-addresses" [ -s "$STATE_DIR/pool-addresses" ] || fail "pool host did not resolve" printf '%s\n' "$POOL_PORT" >"$STATE_DIR/pool-port" printf '%s\n' "$API_PORT" >"$STATE_DIR/api-port" - printf '%s\n' "$(cat "$BOOT_ID_FILE")" >"$STATE_DIR/installed-boot-id" - nft_state="$(nft_table)" || fail "nft inventory failed during installed verification" - [ "$nft_state" != '[]' ] || fail "API allowlist nft table is missing" - waited=0 while [ "$waited" -lt "$ACTIVE_TIMEOUT" ]; do peer="$(xmrig_peers)" [ -n "$peer" ] && break @@ -251,8 +267,16 @@ phase_installed() { done [ -n "$peer" ] || fail "xmrig has no established pool peer within ${ACTIVE_TIMEOUT}s" while IFS= read -r peer; do peer_is_pool "$peer" || fail "xmrig has an unexpected peer"; done <<<"$peer" - waited=0 - summary="" +} + +_assert_nft_table_present() { + local nft_state + nft_state="$(nft_table)" || fail "nft inventory failed during installed verification" + [ "$nft_state" != '[]' ] || fail "API allowlist nft table is missing" +} + +_assert_accepted_shares() { + local summary accepted rejected waited=0 while [ "$waited" -lt "$ACTIVE_TIMEOUT" ]; do summary="$(api_summary 2>/dev/null)" || summary="" if jq -e '.donate_level == 0 and ((.hashrate.total[0] // 0) > 0)' >/dev/null 2>&1 <<<"$summary"; then break; fi @@ -264,7 +288,6 @@ phase_installed() { accepted="$(jq -er '.connection.accepted // 0' <<<"$summary")" || fail "base API omitted accepted shares" rejected="$(jq -er '.connection.rejected // 0' <<<"$summary")" || fail "base API omitted rejected shares" [ "$rejected" = 0 ] || fail "base API reports rejected shares" - waited=0 while [ "$waited" -lt "$SHARE_TIMEOUT" ]; do sleep "$SHARE_INTERVAL" summary="$(api_summary)" || fail "base API summary transport failed" @@ -274,10 +297,223 @@ phase_installed() { waited=$((waited + SHARE_INTERVAL)) done [ "$(jq -r '.connection.accepted // 0' <<<"$summary")" -gt "$accepted" ] || fail "accepted shares did not rise within ${SHARE_TIMEOUT}s" +} + +_assert_read_only_api() { + local code code="$(curl -sS --noproxy '*' -o /dev/null -w '%{http_code}' --max-time 5 -H 'Content-Type: application/json' -X PUT --data '{}' "$API_URL/1/config")" || fail "base API write probe transport failed" [ "$code" = 403 ] || fail "base API write probe did not return HTTP 403" } +phase_installed() { + [ -d "$BASELINE" ] || fail "baseline is missing" + [ "$(cat "$BOOT_ID_FILE")" != "$(cat "$BASELINE/boot-id")" ] || fail "guest did not reboot after setup" + _assert_enabled_active + read_live_config + _assert_donation_zero_config + _assert_expected_peers + printf '%s\n' "$(cat "$BOOT_ID_FILE")" >"$STATE_DIR/installed-boot-id" + _assert_nft_table_present + _assert_accepted_shares + _assert_read_only_api +} + +phase_upgraded() { + [ -d "$BASELINE" ] || fail "baseline is missing" + [[ "$EXPECTED_HEAD" =~ ^[0-9a-f]{40}$ ]] || fail "expected candidate commit is missing" + [ "$(git -C "$CLONE_ROOT" rev-parse HEAD)" = "$EXPECTED_HEAD" ] || fail "checkout is not at the candidate commit" + [ -s "$CLONE_ROOT/VERSION" ] || fail "candidate VERSION is missing" + _assert_enabled_active + read_live_config + _assert_donation_zero_config + _assert_expected_peers + _assert_nft_table_present + _assert_accepted_shares + _assert_read_only_api +} + +_control_curl() { + local method="$1" url="$2" payload="${3:-}" file="" rc=0 + if [ -n "$payload" ]; then + file="$(mktemp "$STATE_DIR/.control-payload.XXXXXX")" + printf '%s' "$payload" >"$file" + fi + { + printf 'silent\nshow-error\nnoproxy = "*"\nconnect-timeout = 2\nmax-time = 8\nrequest = "%s"\nurl = "%s"\n' "$method" "$url" + [ -z "$CONTROL_TOKEN" ] || printf 'header = "Authorization: Bearer %s"\n' "$CONTROL_TOKEN" + [ -z "$payload" ] || printf 'header = "Content-Type: application/json"\ndata = "@%s"\n' "$file" + } | curl --config - 2>/dev/null || rc=$? + [ -z "$file" ] || rm -f "$file" + return "$rc" +} + +_control_post_and_poll() { + local endpoint="$1" payload="$2" want="$3" resp cid waited=0 status="" + [ -n "$CONTROL_TOKEN" ] || fail "control token is missing" + systemctl is-active --quiet rigforge-control.service || fail "control receiver is not active" + resp="$(_control_curl POST "http://127.0.0.1:$CONTROL_PORT/$endpoint" "$payload")" || fail "control $endpoint request failed" + cid="$(jq -er 'select(.status == "accepted") | .change_id' <<<"$resp" 2>/dev/null)" || fail "control $endpoint request was not accepted" + [[ "$cid" =~ ^[0-9a-f]{16}$ ]] || fail "control change id was malformed" + while [ "$waited" -lt "$CONTROL_TIMEOUT" ]; do + status="$(_control_curl GET "http://127.0.0.1:$CONTROL_PORT/status?change_id=$cid" | jq -r '.status // empty' 2>/dev/null || true)" + case "$status" in + applied | rejected | rolled_back | failed | noop | busy | throttled) break ;; + esac + sleep "$CONTROL_INTERVAL" + waited=$((waited + CONTROL_INTERVAL)) + done + [ "$status" = "$want" ] || fail "control $endpoint ended '$status' (expected $want)" +} + +_assert_runtime_donation() { + local want="$1" waited=0 summary="" + read_live_config + [ "$(jq -r '."donate-level"' "$GENERATED_CONFIG")" = "$want" ] || fail "generated config did not follow the control change" + while [ "$waited" -lt "$ACTIVE_TIMEOUT" ]; do + summary="$(api_summary 2>/dev/null)" || summary="" + [ "$(jq -r '.donate_level // empty' <<<"$summary" 2>/dev/null)" = "$want" ] && break + sleep "$SHARE_INTERVAL" + waited=$((waited + SHARE_INTERVAL)) + done + [ "$(jq -r '.donate_level // empty' <<<"$summary" 2>/dev/null)" = "$want" ] || fail "runtime donation level did not follow the control change" + systemctl is-active --quiet xmrig.service || fail "xmrig is not active after the control change" +} + +phase_control_apply() { + _control_post_and_poll apply '{"DONATION":1}' applied + _assert_runtime_donation 1 +} + +phase_control_revert() { + _control_post_and_poll apply '{"DONATION":0}' applied + _assert_runtime_donation 0 +} + +phase_upgrade_leg() { + local before_head before_version payload + case "$UPGRADE_LEG" in + noop | refused) ;; + *) fail "upgrade leg is not selected" ;; + esac + systemctl is-active --quiet rigforge-control.service || fail "control receiver is not active" + before_head="$(git -C "$CLONE_ROOT" rev-parse HEAD)" || fail "checkout inventory failed" + before_version="$(cat "$CLONE_ROOT/VERSION")" + if [ "$UPGRADE_LEG" = noop ]; then + payload="{\"version\":\"v$(tr -d '[:space:]' <"$CLONE_ROOT/VERSION")\"}" + _control_post_and_poll upgrade "$payload" noop + else + payload="{\"version\":\"$CONTROL_PROBE_TAG\"}" + _control_post_and_poll upgrade "$payload" rolled_back + [ -n "$(ls -A "$CONTROL_STATE_DIR" 2>/dev/null)" ] || fail "no throttle stamp after the refused leg" + fi + [ "$(git -C "$CLONE_ROOT" rev-parse HEAD)" = "$before_head" ] || fail "checkout moved during the $UPGRADE_LEG leg" + [ "$(cat "$CLONE_ROOT/VERSION")" = "$before_version" ] || fail "VERSION changed during the $UPGRADE_LEG leg" + systemctl is-active --quiet xmrig.service || fail "xmrig is not active after the $UPGRADE_LEG leg" +} + +_drop_counter() { + nft -j list chain inet rigforge api 2>/dev/null | jq -r --argjson port "$1" ' + [.nftables[].rule + | select(.family == "inet" and .table == "rigforge" and .chain == "api") + | select(any(.expr[]?; has("drop"))) + | [.expr[]? | .counter?.packets // empty] + | select(length == 1) | .[0]] + | if length == 1 then .[0] else error("expected one API drop counter") end' +} + +_allow_netns_setup() { + ip netns list 2>/dev/null | awk '{print $1}' | grep -Fxq "$ALLOW_NS" || + ip netns add "$ALLOW_NS" || fail "allowlist namespace could not be created" + if ! ip link show "$ALLOW_HOST_IF" >/dev/null 2>&1; then + ip link add "$ALLOW_HOST_IF" type veth peer name "$ALLOW_PEER_IF" || fail "allowlist veth pair could not be created" + ip link set "$ALLOW_PEER_IF" netns "$ALLOW_NS" || fail "allowlist veth peer could not move into the namespace" + fi + ip address show dev "$ALLOW_HOST_IF" | grep -q "${ALLOW_TARGET}/" || + ip address add "${ALLOW_TARGET}/${ALLOW_NET##*/}" dev "$ALLOW_HOST_IF" || fail "allowlist target address could not be added" + ip link set "$ALLOW_HOST_IF" up || fail "allowlist host link could not be raised" + ip -n "$ALLOW_NS" address show dev "$ALLOW_PEER_IF" | grep -q "${ALLOW_REFUSED_SOURCE}/" || + ip -n "$ALLOW_NS" address add "${ALLOW_REFUSED_SOURCE}/${ALLOW_NET##*/}" dev "$ALLOW_PEER_IF" || + fail "refused source address could not be added" + ip -n "$ALLOW_NS" address show dev "$ALLOW_PEER_IF" | grep -q "${ALLOW_ALLOWED_SOURCE}/" || + ip -n "$ALLOW_NS" address add "${ALLOW_ALLOWED_SOURCE}/${ALLOW_NET##*/}" dev "$ALLOW_PEER_IF" || + fail "allowed source address could not be added" + ip -n "$ALLOW_NS" link set lo up || fail "namespace loopback could not be raised" + ip -n "$ALLOW_NS" link set "$ALLOW_PEER_IF" up || fail "namespace veth peer could not be raised" + ip -n "$ALLOW_NS" route show default | grep -q "$ALLOW_TARGET" || + ip -n "$ALLOW_NS" route add default via "$ALLOW_TARGET" || fail "namespace default route could not be added" +} + +_allow_probe() { + ip netns exec "$ALLOW_NS" curl -sS --noproxy '*' -o /dev/null -w '%{http_code}' \ + --connect-timeout 2 --max-time 5 --interface "$1" "http://$ALLOW_TARGET:$API_PORT/2/summary" +} + +phase_allowlist_refuse() { + local before after rc=0 + read_live_config + _allow_netns_setup + before="$(_drop_counter "$API_PORT")" || fail "API drop counter is unreadable before the probe" + _allow_probe "$ALLOW_REFUSED_SOURCE" >/dev/null 2>&1 || rc=$? + case "$rc" in + 7 | 28) ;; + *) fail "second source was not refused (curl exit $rc)" ;; + esac + after="$(_drop_counter "$API_PORT")" || fail "API drop counter is unreadable after the probe" + [ "$after" -gt "$before" ] || fail "API drop counter did not rise for the refused source" + printf '%s\n' "$ALLOW_REFUSED_SOURCE" >"$STATE_DIR/allowlist-refused" +} + +phase_allowlist_accept() { + local code + read_live_config + [ -f "$STATE_DIR/allowlist-refused" ] || fail "the refused-source leg has not run" + _allow_netns_setup + code="$(_allow_probe "$ALLOW_ALLOWED_SOURCE")" || fail "allowed second source probe transport failed" + [ "$code" = 200 ] || fail "allowed second source did not receive HTTP 200 (got $code)" + api_summary >/dev/null || fail "loopback API probe failed after the allowlist widened" + ip netns del "$ALLOW_NS" 2>/dev/null || true + ip link del "$ALLOW_HOST_IF" 2>/dev/null || true + rm -f "$STATE_DIR/allowlist-refused" +} + +phase_restored() { + local digest + [ -n "$RESTORED_SHA256" ] || fail "expected config digest is missing" + if command -v sha256sum >/dev/null 2>&1; then + digest="$(sha256sum "$CLONE_ROOT/config.json" 2>/dev/null | awk '{print $1}')" + else + digest="$(shasum -a 256 "$CLONE_ROOT/config.json" 2>/dev/null | awk '{print $1}')" + fi + [ -n "$digest" ] || fail "config digest is unreadable" + [ "$digest" = "$RESTORED_SHA256" ] || fail "restored config differs from the backup" + ls "$CLONE_ROOT"/backups/rigforge-backup-*.tar.gz >/dev/null 2>&1 || fail "backup archive is missing" +} + +phase_appliance() { + local fragment persistent + [ -d "$BASELINE" ] || fail "baseline is missing" + fragment="$(systemctl show -p FragmentPath --value xmrig.service | tr -d '[:space:]')" + case "$fragment" in + /run/systemd/system/*) ;; + *) fail "xmrig is not a runtime unit" ;; + esac + persistent="$(find /etc/systemd/system -maxdepth 1 \( -name 'xmrig-*' -o -name 'rigforge-*' \) -print -quit 2>/dev/null || true)" + [ -z "$persistent" ] || fail "appliance mode wrote persistent units" + cmp -s "$BASELINE/fstab" <(read_file "$FSTAB_FILE") || fail "appliance mode changed fstab" + cmp -s "$BASELINE/limits" <(read_file "$LIMITS_FILE") || fail "appliance mode changed limits" + cmp -s "$BASELINE/modules" <(read_file "$MODULES_FILE") || fail "appliance mode changed modules" + cmp -s "$BASELINE/msr-load" <(read_file "$MSR_LOAD_FILE") || fail "appliance mode changed the MSR module config" + cmp -s "$BASELINE/grub-default" <(read_file "$GRUB_DEFAULT_FILE") || fail "appliance mode changed GRUB defaults" + cmp -s "$BASELINE/grub-config" <(read_file "$(grub_config)") || fail "appliance mode changed the generated GRUB config" + cmp -s "$BASELINE/grub-dropins" <(directory_state "$GRUB_DROPIN_DIR") || fail "appliance mode changed GRUB drop-ins" + cmp -s "$BASELINE/cmdline" <(read_file "$CMDLINE_FILE") || fail "appliance mode changed the kernel command line" + mount 2>/dev/null | grep -q hugetlbfs || fail "hugetlbfs is not mounted at runtime" + systemctl is-enabled --quiet --runtime xmrig.service || fail "xmrig is not enabled at runtime" + systemctl is-active --quiet xmrig.service || fail "xmrig is not active under appliance mode" + read_live_config + [ "$(jq -r '."donate-level"' "$GENERATED_CONFIG")" = 0 ] || fail "donate-level is not zero" +} + phase_removed() { local peer port address remaining [ -f "$STATE_DIR/installed-boot-id" ] || fail "installed state is missing" @@ -316,6 +552,14 @@ case "$PHASE" in baseline) phase_baseline ;; dry-run-check) phase_dry_run_check ;; installed) phase_installed ;; +allowlist-refuse) phase_allowlist_refuse ;; +allowlist-accept) phase_allowlist_accept ;; +control-apply) phase_control_apply ;; +control-revert) phase_control_revert ;; +upgrade-leg) phase_upgrade_leg ;; +upgraded) phase_upgraded ;; +restored) phase_restored ;; +appliance) phase_appliance ;; removed) phase_removed ;; *) usage ;; esac From 2d49176c244ce10b7465b74087525b5b66edb10d Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:21:00 -0600 Subject: [PATCH 2/5] WIP: candidate-mode guest battery driver and fixtures (#663) docs_replay.py sequences allowlist/control/upgrade/backup/appliance with comma-list allowlist validation; fixtures extended for the new phases. Guest-verification fixtures still failing seven negative controls. Co-Authored-By: Claude Code --- tests/docs_replay.py | 75 +++++++++++++++++++++++++- tests/test-docs-replay.py | 92 +++++++++++++++++++++++++------ tests/test-e2e-docs-guest.sh | 102 +++++++++++++++++++++++++++++++++-- 3 files changed, 249 insertions(+), 20 deletions(-) diff --git a/tests/docs_replay.py b/tests/docs_replay.py index 81662303..5a1feb60 100644 --- a/tests/docs_replay.py +++ b/tests/docs_replay.py @@ -12,6 +12,10 @@ from xml.etree import ElementTree +PROBE_TAG = "v99.99.99" +ALLOWED_SECOND_SOURCE = "169.254.241.3" + + class ReplayError(Exception): pass @@ -103,8 +107,20 @@ def reboot(self, script, timeout=300): raise PlatformError("guest failed to return with a new boot ID") +def candidate(root): + result = subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"], + capture_output=True, text=True) + sha = result.stdout.strip() + if result.returncode != 0 or not re.fullmatch(r"[0-9a-f]{40}", sha): + raise ReplayError("candidate commit of the driver checkout is unavailable") + return sha + + def replay(root, guest, config): commands = recipes(root) + commit = candidate(root) + allow_from = json.loads(config)["api_allow_from"] + token = uuid.uuid4().hex info = guest.virsh("dominfo", guest.domain) if not re.search(r"^Persistent:\s+no\s*$", info, re.MULTILINE): raise ReplayError("docs replay requires a transient disposable domain") @@ -116,6 +132,7 @@ def replay(root, guest, config): if not re.fullmatch(r"/var/tmp/rigforge-docs\.[A-Za-z0-9]+", work): raise ReplayError("invalid guest scratch directory") quoted = shlex.quote(work) + clone = f"{quoted}/rigforge" helper = base64.b64encode((root / "tests/e2e-docs-guest.sh").read_bytes()).decode() prepared = base64.b64encode(config).decode() guest.run(f"chmod 755 {quoted}\ncd {quoted}\nprintf %s {helper} | base64 -d >check.sh\n" @@ -131,10 +148,64 @@ def replay(root, guest, config): guest.reboot(commands["reboot"]) guest.run(f"{check} installed {args}\n", timeout=600) print("PASS: reboot autostart, donation, pool, shares and read-only API", flush=True) + guest.run(f"E2E_ALLOWLIST_ALLOWED_SOURCE={ALLOWED_SECOND_SOURCE} {check} allowlist-refuse {args}\n", timeout=300) + guest.run("cd " + clone + "\njq --arg source " + shlex.quote(ALLOWED_SECOND_SOURCE) + + " '.api_allow_from += \", \" + $source' config.json >config.tmp && mv config.tmp config.json\n" + "sudo ./rigforge.sh apply\n", timeout=300) + guest.run(f"E2E_ALLOWLIST_ALLOWED_SOURCE={ALLOWED_SECOND_SOURCE} {check} allowlist-accept {args}\n", timeout=180) + guest.run("cd " + clone + "\njq --arg original " + shlex.quote(allow_from) + + " '.api_allow_from = $original' config.json >config.tmp && mv config.tmp config.json\n" + "sudo ./rigforge.sh apply\n", timeout=300) + print("PASS: API allowlist refused a second source and accepted an allowed source", flush=True) + guest.run("cd " + clone + "\njq --arg token " + shlex.quote(token) + + " '.control = \"enabled\" | .control_upgrade = \"enabled\" | .ACCESS_TOKEN = $token'" + " config.json >config.tmp && mv config.tmp config.json\n" + "sudo ./rigforge.sh apply\n", timeout=600) + guest.run(f"E2E_CONTROL_TOKEN={token} {check} control-apply {args}\n", timeout=480) + guest.run(f"E2E_CONTROL_TOKEN={token} {check} control-revert {args}\n", timeout=480) + print("PASS: writable control path applied one change and rolled back one change", flush=True) + guest.run("cd " + clone + "\nprobe=$(git -c user.name=docs-replay -c user.email=docs-replay@localhost" + " commit-tree 'HEAD^{tree}' -p HEAD -m 'docs replay upgrade probe')\n" + "git tag " + PROBE_TAG + " \"$probe\"\n", timeout=120) + guest.run(f"E2E_CONTROL_TOKEN={token} E2E_UPGRADE_LEG=noop E2E_CONTROL_PROBE_TAG={PROBE_TAG} " + f"{check} upgrade-leg {args}\n", timeout=480) + guest.run(f"E2E_CONTROL_TOKEN={token} E2E_UPGRADE_LEG=refused E2E_CONTROL_PROBE_TAG={PROBE_TAG} " + f"{check} upgrade-leg {args}\n", timeout=900) + print("PASS: remote-upgrade chain reached noop and refused a forged tag with the checkout intact", flush=True) + guest.run(f"cd {quoted}/rigforge\ngit fetch --quiet --tags origin\n" + f"git fetch --quiet origin {commit}\ngit checkout --quiet --force FETCH_HEAD\n" + "sudo ./rigforge.sh upgrade\n", timeout=2400) + guest.run(f"E2E_EXPECTED_HEAD={commit} {check} upgraded {args}\n", timeout=900) + print("PASS: remote upgrade from the previous release to the candidate kept shares landing", flush=True) + digest = guest.run(f"cd {quoted}/rigforge\nsha256sum config.json | awk '{{print $1}}'\n").strip() + if not re.fullmatch(r"[0-9a-f]{64}", digest): + raise ReplayError("config digest is unreadable") + archive = guest.run(f"cd {quoted}/rigforge\nsudo ./rigforge.sh backup --yes\n" + "ls -1 backups/rigforge-backup-*.tar.gz | sort | tail -1\n", + timeout=300).strip().splitlines()[-1] + if not re.fullmatch(r"backups/rigforge-backup-[0-9]{8}-[0-9]{6}\.tar\.gz", archive): + raise ReplayError("backup archive path is invalid") + guest.run(f"cd {quoted}/rigforge\njq '.DONATION = 1' config.json >config.tmp && mv config.tmp config.json\n") + guest.run(f"cd {quoted}/rigforge\nsudo ./rigforge.sh restore --yes {shlex.quote(archive)}\n", timeout=300) + guest.run(f"E2E_RESTORED_CONFIG_SHA256={digest} {check} restored {args}\n", timeout=120) + print("PASS: backup and restore round-tripped the config", flush=True) guest.run(f"cd {quoted}/rigforge\nsudo ./rigforge.sh uninstall --yes\n", timeout=120) guest.reboot(commands["reboot"]) guest.run(f"{check} removed {args}\n") print("PASS: uninstall remained complete after reboot", flush=True) + guest.run(f"cd {quoted}/rigforge\numask 077\nprintf %s {prepared} | base64 -d >config.json\n") + guest.run(f"cd {quoted}/rigforge\nsudo env RIGFORGE_APPLIANCE=1 LC_ALL=C ./rigforge.sh\n", timeout=3600) + guest.run(f"{check} appliance {args}\n", timeout=300) + print("PASS: appliance mode ran with runtime-only units on the stock systemd guest", flush=True) + guest.run(f"cd {quoted}/rigforge\nsudo env RIGFORGE_APPLIANCE=1 ./rigforge.sh uninstall --yes\n", timeout=120) + + +def _network_invalid(entry): + try: + ipaddress.ip_network(entry.strip(), strict=False) + except ValueError: + return True + return False def check_config(config): @@ -154,7 +225,9 @@ def check_config(config): or pools[0].get("user", "docs-replay") != "docs-replay" or pools[0].get("pass", "x") not in ("", "x")): raise ReplayError("prepared config needs one throwaway pool, donation zero and an API allowlist") - ipaddress.ip_network(data["api_allow_from"], strict=False) + if any(not part.strip() for part in data["api_allow_from"].split(",")) or any( + _network_invalid(part) for part in data["api_allow_from"].split(",")): + raise ReplayError("prepared config API allowlist entries must be valid networks") endpoint = urlsplit("//" + pools[0]["url"]) if (not endpoint.hostname or not endpoint.port or endpoint.username is not None or endpoint.password is not None or endpoint.path or endpoint.query or endpoint.fragment diff --git a/tests/test-docs-replay.py b/tests/test-docs-replay.py index a349a100..638f29f2 100644 --- a/tests/test-docs-replay.py +++ b/tests/test-docs-replay.py @@ -3,10 +3,13 @@ import json import os from pathlib import Path +import subprocess import unittest from unittest.mock import Mock, patch -from docs_replay import Guest, PlatformError, ReplayError, block, check_config, recipes, replay +import docs_replay +from docs_replay import (Guest, PlatformError, ReplayError, block, candidate, + check_config, recipes, replay) class Markers(unittest.TestCase): @@ -60,6 +63,30 @@ def test_endpoint_cannot_embed_credentials_or_a_path(self): with self.assertRaises(ReplayError): check_config(json.dumps(data)) + def test_allowlist_accepts_the_lane_comma_list_and_rejects_invalid_members(self): + data = self.config() + data["api_allow_from"] = f"{data['api_allow_from']}, ::1/128" + check_config(json.dumps(data)) + for value in ("127.0.0.1/32, not-a-network", "127.0.0.1/32,", " "): + data = self.config() + data["api_allow_from"] = value + with self.subTest(value=value), self.assertRaises(ReplayError): + check_config(json.dumps(data)) + + +class Candidate(unittest.TestCase): + def test_driver_checkout_head_is_the_candidate(self): + completed = Mock(return_value=Mock(returncode=0, stdout="ab" * 20 + "\n")) + with patch.object(docs_replay.subprocess, "run", completed): + self.assertEqual(candidate(Path("/fixture")), "ab" * 20) + + def test_missing_or_malformed_head_is_refused(self): + for result in (Mock(returncode=128, stdout=""), Mock(returncode=0, stdout="main\n")): + with self.subTest(returncode=result.returncode), \ + patch.object(docs_replay.subprocess, "run", Mock(return_value=result)), \ + self.assertRaises(ReplayError): + candidate(Path("/fixture")) + class Agent(unittest.TestCase): def setUp(self): @@ -112,52 +139,85 @@ def test_running_guest_without_new_boot_is_not_autostart_failure(self): class Sequence(unittest.TestCase): + CANDIDATE = "cd" * 20 + def setUp(self): self.root = Path(__file__).resolve().parent.parent self.guest = Mock() self.guest.virsh.side_effect = ["Persistent: no\n", "running\n", ""] - self.guest.run.side_effect = ["/var/tmp/rigforge-docs.TEST\n"] + [""] * 9 - - def test_documents_drive_commands_across_both_reboots(self): + self.guest.run.side_effect = (["/var/tmp/rigforge-docs.TEST\n"] + [""] * 19 + + ["a" * 64 + "\n", "backups/rigforge-backup-20261117-010203.tar.gz\n"] + + [""] * 9) + self.config = json.dumps({ + "pools": [{"url": f"fixture-{os.getpid()}:12345", "user": "docs-replay", "pass": "x"}], + "DONATION": 0, "api_allow_from": "127.0.0.1/32, ::1/128"}).encode() + patcher = patch.object(docs_replay, "candidate", return_value=self.CANDIDATE) + patcher.start() + self.addCleanup(patcher.stop) + + def test_full_battery_drives_both_reboots_in_order(self): with patch("builtins.print"): - replay(self.root, self.guest, b"{}") + replay(self.root, self.guest, self.config) commands = recipes(self.root) scripts = [call.args[0] for call in self.guest.run.call_args_list] + self.assertEqual(len(scripts), 31) self.assertTrue(scripts[1].endswith(commands["clone"])) self.assertIn("config.json", scripts[2]) - self.assertIn(" baseline ", scripts[3]) - self.assertTrue(scripts[4].endswith(commands["dry-run"])) - self.assertIn(" dry-run-check ", scripts[5]) - self.assertTrue(scripts[6].endswith(commands["setup"])) - self.assertIn(" installed ", scripts[7]) - self.assertIn("uninstall --yes", scripts[8]) - self.assertIn(" removed ", scripts[9]) + for index, marker in ((3, " baseline "), (4, commands["dry-run"]), (5, " dry-run-check "), + (6, commands["setup"]), (7, " installed "), + (8, " allowlist-refuse "), (9, "169.254.241.3"), + (10, " allowlist-accept "), (12, '.control = "enabled"'), + (13, " control-apply "), (14, " control-revert "), + (15, "git tag v99.99.99"), (16, "E2E_UPGRADE_LEG=noop"), + (17, "E2E_UPGRADE_LEG=refused"), + (18, f"git fetch --quiet origin {self.CANDIDATE}"), + (19, f"E2E_EXPECTED_HEAD={self.CANDIDATE}"), (19, "check.sh upgraded"), + (20, "sha256sum config.json"), (21, "backup --yes"), + (23, "restore --yes backups/rigforge-backup-20261117-010203.tar.gz"), + (24, "E2E_RESTORED_CONFIG_SHA256=" + "a" * 64), + (25, "uninstall --yes"), (26, " removed "), + (28, "RIGFORGE_APPLIANCE=1 LC_ALL=C ./rigforge.sh"), (29, " appliance ")): + with self.subTest(marker=marker): + self.assertIn(marker, scripts[index]) self.assertEqual([call.args[0] for call in self.guest.reboot.call_args_list], [commands["reboot"], commands["reboot"]]) + def test_bad_digest_or_archive_path_stops_before_restore(self): + for digest, archive, stop in ( + ("not-a-digest", "backups/rigforge-backup-20261117-010203.tar.gz", 21), + ("a" * 64, "backups/untrusted.tar.gz", 22)): + with self.subTest(archive=archive): + self.guest.reset_mock() + self.guest.virsh.side_effect = ["Persistent: no\n", "running\n", ""] + self.guest.run.side_effect = (["/var/tmp/rigforge-docs.TEST\n"] + [""] * 19 + + [digest + "\n", archive + "\n"]) + with patch("builtins.print"), self.assertRaisesRegex(ReplayError, "digest|archive"): + replay(self.root, self.guest, self.config) + self.assertEqual(self.guest.run.call_count, stop) + def test_persistent_domain_is_refused_before_mutation(self): self.guest.virsh.side_effect = None self.guest.virsh.return_value = "Persistent: yes\n" with self.assertRaisesRegex(ReplayError, "transient"): - replay(self.root, self.guest, b"{}") + replay(self.root, self.guest, self.config) self.guest.run.assert_not_called() def test_stopped_domain_is_refused_before_mutation(self): self.guest.virsh.side_effect = ["Persistent: no\n", "shut off\n"] with self.assertRaisesRegex(PlatformError, "not running"): - replay(self.root, self.guest, b"{}") + replay(self.root, self.guest, self.config) self.guest.run.assert_not_called() def test_emulated_domain_is_refused_before_mutation(self): self.guest.virsh.side_effect = ["Persistent: no\n", "running\n", ""] with self.assertRaisesRegex(PlatformError, "KVM"): - replay(self.root, self.guest, b"{}") + replay(self.root, self.guest, self.config) self.guest.run.assert_not_called() def test_failed_dry_run_check_prevents_setup(self): self.guest.run.side_effect = ["/var/tmp/rigforge-docs.TEST\n"] + [""] * 4 + [ReplayError("changed")] with self.assertRaisesRegex(ReplayError, "changed"): - replay(self.root, self.guest, b"{}") + replay(self.root, self.guest, self.config) self.guest.reboot.assert_not_called() self.assertEqual(self.guest.run.call_count, 6) diff --git a/tests/test-e2e-docs-guest.sh b/tests/test-e2e-docs-guest.sh index 4869889b..21e9b3f0 100755 --- a/tests/test-e2e-docs-guest.sh +++ b/tests/test-e2e-docs-guest.sh @@ -45,6 +45,9 @@ printf 'modules fixture\n' >"$T586/modules" rm "$T586/nft-present" jq -n --arg url "$POOL_HOST:$POOL_PORT" '{HOME_DIR:"DYNAMIC_HOME",pools:[{url:$url}]}' >"$T586/clone/config.json" +cat >"$T586/nft-chain.json" <"$T586/clone/data/worker/xmrig/build/config.json" printf '%s\n' '#!/usr/bin/env bash' 'case "$1" in -s) echo Linux ;; -m) echo x86_64 ;; esac' >"$T586/bin/uname" @@ -54,8 +57,10 @@ printf '%s\n' '#!/usr/bin/env bash' \ 'is-system-running) exit 0 ;;' \ 'list-unit-files|list-units) [ "${FAKE_SYSTEMCTL_FAIL:-0}" = 1 ] && exit 2; [ "${FAKE_UNITS:-}" = present ] && echo "xmrig.service enabled"; exit 0 ;;' \ 'is-enabled|is-active) [ "${FAKE_INSTALLED:-0}" = 1 ] ;;' \ + 'show) printf "%s\n" "${FAKE_FRAGMENT:-/etc/systemd/system/xmrig.service}" ;;' \ 'esac' >"$T586/bin/systemctl" printf '%s\n' '#!/usr/bin/env bash' '[ "${FAKE_PROCESSES:-}" = present ] && echo "123 xmrig"; exit 0' >"$T586/bin/pgrep" +printf '%s\n' '#!/usr/bin/env bash' 'case "$*" in *rev-parse*) printf "%s\n" "${FAKE_HEAD:-$(printf a%.0s 1 40)}" ;; *) exit 0 ;; esac' >"$T586/bin/git" printf '%s\n' '#!/usr/bin/env bash' \ '[ "${FAKE_SS_FAIL:-0}" = 1 ] && exit 2' \ 'case "$1" in' \ @@ -65,13 +70,29 @@ printf '%s\n' '#!/usr/bin/env bash' \ 'exit 0' >"$T586/bin/ss" printf '%s\n' '#!/usr/bin/env bash' \ '[ "${FAKE_NFT_MODE:-}" = fail ] && exit 2' \ + 'if [ "$1" = -j ] && [ "$3" = chain ]; then dropped=0; [ -f "$FAKE_DROP_FILE" ] && dropped=$(cat "$FAKE_DROP_FILE"); sed "s/@PORT@/$FAKE_API_PORT/;s/@DROPPED@/$dropped/" "$FAKE_NFT_CHAIN_TEMPLATE"; exit 0; fi' \ 'if [ -f "$FAKE_NFT_FILE" ]; then printf '\''{"nftables":[{"table":{"family":"inet","name":"rigforge"}}]}\n'\''; else printf '\''{"nftables":[]}\n'\''; fi' >"$T586/bin/nft" printf '%s\n' '#!/usr/bin/env bash' 'printf "%s STREAM fixture\n" "$FAKE_RESOLVED_ADDRESS"' >"$T586/bin/getent" -printf '%s\n' '#!/usr/bin/env bash' 'printf "1: lo inet %s/8 scope host lo\n" "$FAKE_LOOPBACK_ADDRESS"' >"$T586/bin/ip" printf '%s\n' '#!/usr/bin/env bash' \ + 'case "$1" in' \ + '-o) printf "1: lo inet %s/8 scope host lo\n" "$FAKE_LOOPBACK_ADDRESS"; exit 0 ;;' \ + 'netns) [ "$2" = exec ] && shift 3 && exec "$@"; exit 0 ;;' \ + 'link) [ "$2" = show ] && exit 1; exit 0 ;;' \ + '-n) exit 0 ;;' \ + 'esac' \ + 'exit 0' >"$T586/bin/ip" +printf '%s\n' '#!/usr/bin/env bash' 'if [ "${FAKE_MOUNT:-ok}" = ok ]; then echo "hugetlbfs on /dev/hugepages type hugetlbfs (rw)"; else echo "proc on /proc type proc"; fi' >"$T586/bin/mount" +printf '%s\n' '#!/usr/bin/env bash' \ +printf '%s\n' '#!/usr/bin/env bash' \ + 'for a in "$@"; do if [ "$a" = --config ]; then cfg=$(cat); case "$cfg" in' \ + '*/status*) printf "{\"status\":\"%s\"}" "${FAKE_CONTROL_STATUS:-applied}"; exit 0 ;;' \ + '*/apply*|*/upgrade*) printf "{\"status\":\"accepted\",\"change_id\":\"0123456789abcdef\"}"; exit 0 ;;' \ + 'esac; exit 7; fi; done' \ 'case "$*" in' \ + '*--interface*169.254.241.2*) if [ "${FAKE_REFUSE_MODE:-drop}" = pass ]; then printf 200; exit 0; fi; if [ "${FAKE_REFUSE_MODE:-drop}" = drop ]; then n=0; [ -f "$FAKE_DROP_FILE" ] && n=$(cat "$FAKE_DROP_FILE"); n=$((n + 1)); printf "%s" "$n" >"$FAKE_DROP_FILE"; fi; exit 7 ;;' \ + '*--interface*169.254.241.3*) printf "%s" "${FAKE_ACCEPT_CODE:-200}"; exit 0 ;;' \ '*-X?PUT*) [ "${FAKE_CURL_MODE:-}" = transport ] && exit 7; [ "${FAKE_CURL_MODE:-}" = write200 ] && printf 200 || printf 403 ;;' \ - '*) n=0; [ -f "$FAKE_CURL_COUNT" ] && n=$(cat "$FAKE_CURL_COUNT"); n=$((n + 1)); printf "%s" "$n" >"$FAKE_CURL_COUNT"; printf "{\"donate_level\":0,\"hashrate\":{\"total\":[1]},\"connection\":{\"accepted\":%s,\"rejected\":0}}\n" "$n" ;;' \ + '*) n=0; [ -f "$FAKE_CURL_COUNT" ] && n=$(cat "$FAKE_CURL_COUNT"); n=$((n + 1)); printf "%s" "$n" >"$FAKE_CURL_COUNT"; printf "{\"donate_level\":%s,\"hashrate\":{\"total\":[1]},\"connection\":{\"accepted\":%s,\"rejected\":0}}\n" "${FAKE_DONATE_LEVEL:-0}" "$n" ;;' \ 'esac' >"$T586/bin/curl" printf '%s\n' '#!/usr/bin/env bash' ':' >"$T586/bin/sleep" chmod +x "$T586/bin"/* @@ -85,7 +106,8 @@ guest586() { E2E_MODULES_FILE="$T586/modules" E2E_MSR_LOAD_FILE="$T586/msr-load" \ E2E_SHARE_TIMEOUT=1 E2E_SHARE_INTERVAL=1 E2E_ACTIVE_TIMEOUT=1 FAKE_NFT_FILE="$T586/nft-present" \ FAKE_POOL_ADDRESS="$POOL_ADDRESS" FAKE_RESOLVED_ADDRESS="$POOL_ADDRESS" FAKE_POOL_PORT="$POOL_PORT" FAKE_API_PORT="$API_PORT" \ - FAKE_LOOPBACK_ADDRESS="$LOOPBACK_ADDRESS" FAKE_CURL_COUNT="$T586/curl-count" "$@" \ + FAKE_LOOPBACK_ADDRESS="$LOOPBACK_ADDRESS" FAKE_CURL_COUNT="$T586/curl-count" \ + FAKE_DROP_FILE="$T586/drop-count" FAKE_NFT_CHAIN_TEMPLATE="$T586/nft-chain.json" E2E_CONTROL_STATE_DIR="$T586/ctrlstate" "$@" \ bash "$ROOT/tests/e2e-docs-guest.sh" "${CASE_PHASE:?}" "$T586/clone" "$T586/state" } @@ -145,6 +167,80 @@ for failure in "FAKE_NFT_MODE=fail:nft" "FAKE_SS_FAIL=1:socket" "FAKE_SYSTEMCTL_ assert_contains "$label inventory error is explicit" "$probe_err" "inventory failed" done +printf '1.18.1\n' >"$T586/clone/VERSION" +mkdir -p "$T586/ctrlstate" "$T586/ctrlstate-empty" "$T586/clone/backups" +touch "$T586/ctrlstate/last" "$T586/clone/backups/rigforge-backup-20261117-000000.tar.gz" + +: >"$T586/drop-count" +CASE_PHASE=allowlist-refuse guest586 +assert_rc "guest verifier refuses the non-loopback source and sees the drop counter rise" "$?" 0 +not_refused="$(CASE_PHASE=allowlist-refuse guest586 FAKE_REFUSE_MODE=pass 2>&1)" +assert_rc "guest verifier fails when the second source is accepted" "$?" 1 +assert_contains "accepted-source negative control is explicit" "$not_refused" "second source was not refused" +: >"$T586/drop-count" +norise="$(CASE_PHASE=allowlist-refuse guest586 FAKE_REFUSE_MODE=norise 2>&1)" +assert_rc "guest verifier fails when the drop counter is stalled" "$?" 1 +assert_contains "stalled counter negative control is explicit" "$norise" "drop counter did not rise" +: >"$T586/drop-count" +CASE_PHASE=allowlist-refuse guest586 +bad_accept="$(CASE_PHASE=allowlist-accept guest586 FAKE_ACCEPT_CODE=403 2>&1)" +assert_rc "guest verifier fails a refused allowed-source probe" "$?" 1 +assert_contains "refused allowed-source negative control is explicit" "$bad_accept" "did not receive HTTP 200" +CASE_PHASE=allowlist-accept guest586 +assert_rc "guest verifier accepts the allowed second source and keeps loopback" "$?" 0 + +tok_err="$(CASE_PHASE=control-apply guest586 FAKE_INSTALLED=1 2>&1)" +assert_rc "control apply refuses to run without the token" "$?" 1 +assert_contains "missing token is explicit" "$tok_err" "control token is missing" +jq '."donate-level" = 1 | ."donate-over-proxy" = 1' "$GENERATED_FIXTURE" >"$T586/gen.tmp" && mv "$T586/gen.tmp" "$GENERATED_FIXTURE" +ctl_rej="$(CASE_PHASE=control-apply guest586 FAKE_INSTALLED=1 FAKE_DONATE_LEVEL=1 E2E_CONTROL_TOKEN=fixturetoken FAKE_CONTROL_STATUS=rejected 2>&1)" +assert_rc "control apply fails when the rig rejects the change" "$?" 1 +assert_contains "rejected control status is explicit" "$ctl_rej" "ended 'rejected'" +CASE_PHASE=control-apply guest586 FAKE_INSTALLED=1 FAKE_DONATE_LEVEL=1 E2E_CONTROL_TOKEN=fixturetoken +assert_rc "guest verifier proves one applied control change" "$?" 0 +jq '."donate-level" = 0 | ."donate-over-proxy" = 0' "$GENERATED_FIXTURE" >"$T586/gen.tmp" && mv "$T586/gen.tmp" "$GENERATED_FIXTURE" +CASE_PHASE=control-revert guest586 FAKE_INSTALLED=1 E2E_CONTROL_TOKEN=fixturetoken +assert_rc "guest verifier proves the rolled-back control change" "$?" 0 + +CASE_PHASE=upgrade-leg guest586 FAKE_INSTALLED=1 E2E_CONTROL_TOKEN=t E2E_UPGRADE_LEG=noop FAKE_CONTROL_STATUS=failed +assert_rc "noop leg fails on a failed status" "$?" 1 +CASE_PHASE=upgrade-leg guest586 FAKE_INSTALLED=1 E2E_CONTROL_TOKEN=t E2E_UPGRADE_LEG=noop FAKE_CONTROL_STATUS=noop +assert_rc "remote-upgrade noop leg reaches noop with the checkout intact" "$?" 0 +CASE_PHASE=upgrade-leg guest586 FAKE_INSTALLED=1 E2E_CONTROL_TOKEN=t E2E_UPGRADE_LEG=refused FAKE_CONTROL_STATUS=rolled_back +assert_rc "refused upgrade leg rolls back and leaves the throttle stamp" "$?" 0 +no_stamp="$(CASE_PHASE=upgrade-leg guest586 FAKE_INSTALLED=1 E2E_CONTROL_TOKEN=t E2E_UPGRADE_LEG=refused FAKE_CONTROL_STATUS=rolled_back E2E_CONTROL_STATE_DIR="$T586/ctrlstate-empty" 2>&1)" +assert_rc "refused leg fails without a throttle stamp" "$?" 1 +assert_contains "missing throttle stamp is explicit" "$no_stamp" "no throttle stamp" + +: >"$T586/curl-count" +: >"$T586/nft-present" +bad_head="$(CASE_PHASE=upgraded guest586 FAKE_INSTALLED=1 FAKE_PEER=present E2E_EXPECTED_HEAD="$(printf 'b%.0s' 1 40)" 2>&1)" +assert_rc "upgraded verifier fails when the checkout is not the candidate" "$?" 1 +assert_contains "candidate mismatch is explicit" "$bad_head" "not at the candidate commit" +CASE_PHASE=upgraded guest586 FAKE_INSTALLED=1 FAKE_PEER=present E2E_EXPECTED_HEAD="$(printf 'a%.0s' 1 40)" +assert_rc "upgraded verifier proves the candidate commit keeps shares landing at donation zero" "$?" 0 + +digest="$( { sha256sum "$T586/clone/config.json" || shasum -a 256 "$T586/clone/config.json"; } 2>/dev/null | awk '{print $1}')" +CASE_PHASE=restored guest586 E2E_RESTORED_CONFIG_SHA256="$digest" +assert_rc "restored verifier proves the backup round-trip digest" "$?" 0 +stale="$(CASE_PHASE=restored guest586 E2E_RESTORED_CONFIG_SHA256="$(printf '0%.0s' 1 64)" 2>&1)" +assert_rc "restored verifier fails a digest mismatch" "$?" 1 +assert_contains "digest mismatch is explicit" "$stale" "differs from the backup" +mv "$T586/clone/backups/rigforge-backup-20261117-000000.tar.gz" "$T586/archive.hold" +missing="$(CASE_PHASE=restored guest586 E2E_RESTORED_CONFIG_SHA256="$digest" 2>&1)" +assert_rc "restored verifier fails without the archive" "$?" 1 +assert_contains "missing archive is explicit" "$missing" "backup archive is missing" +mv "$T586/archive.hold" "$T586/clone/backups/rigforge-backup-20261117-000000.tar.gz" + +frag_err="$(CASE_PHASE=appliance guest586 FAKE_INSTALLED=1 2>&1)" +assert_rc "appliance verifier fails on a persistent unit fragment" "$?" 1 +assert_contains "persistent fragment is explicit" "$frag_err" "not a runtime unit" +mount_err="$(CASE_PHASE=appliance guest586 FAKE_INSTALLED=1 FAKE_FRAGMENT=/run/systemd/system/xmrig.service FAKE_MOUNT=none 2>&1)" +assert_rc "appliance verifier fails without the runtime hugetlbfs mount" "$?" 1 +assert_contains "missing hugetlbfs is explicit" "$mount_err" "hugetlbfs is not mounted" +CASE_PHASE=appliance guest586 FAKE_INSTALLED=1 FAKE_FRAGMENT=/run/systemd/system/xmrig.service +assert_rc "appliance verifier proves runtime-only units with the baseline files intact" "$?" 0 + if [ "$STANDALONE_586" = 1 ]; then printf 'docs guest tests: %s passed, %s failed\n' "$PASS" "$FAIL" [ "$FAIL" = 0 ] From de1febf68428ffdb504898c3765f6d2722402a27 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:09:04 -0600 Subject: [PATCH 3/5] Fix guest battery fixtures: valid nftables JSON, numeric drop counters, real 40-char heads (#663) Co-Authored-By: Claude Code --- docs/dev/file-budget.tsv | 1 + tests/test-e2e-docs-guest.sh | 17 ++++++++--------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/docs/dev/file-budget.tsv b/docs/dev/file-budget.tsv index daedbc6b..b442a972 100644 --- a/docs/dev/file-budget.tsv +++ b/docs/dev/file-budget.tsv @@ -2,6 +2,7 @@ # target/ceiling rationale and CONTRIBUTING.md for the gate. # pathceiling-in-lines. Ceilings only ever go down; a file at or below 400 lines drops its entry. rigforge.sh 6207 +tests/e2e-docs-guest.sh 565 tests/e2e-pithead.sh 563 tests/e2e-real.sh 1388 tests/run.sh 9556 diff --git a/tests/test-e2e-docs-guest.sh b/tests/test-e2e-docs-guest.sh index 21e9b3f0..4ebb9b53 100755 --- a/tests/test-e2e-docs-guest.sh +++ b/tests/test-e2e-docs-guest.sh @@ -46,7 +46,7 @@ rm "$T586/nft-present" jq -n --arg url "$POOL_HOST:$POOL_PORT" '{HOME_DIR:"DYNAMIC_HOME",pools:[{url:$url}]}' >"$T586/clone/config.json" cat >"$T586/nft-chain.json" <"$T586/clone/data/worker/xmrig/build/config.json" @@ -60,7 +60,7 @@ printf '%s\n' '#!/usr/bin/env bash' \ 'show) printf "%s\n" "${FAKE_FRAGMENT:-/etc/systemd/system/xmrig.service}" ;;' \ 'esac' >"$T586/bin/systemctl" printf '%s\n' '#!/usr/bin/env bash' '[ "${FAKE_PROCESSES:-}" = present ] && echo "123 xmrig"; exit 0' >"$T586/bin/pgrep" -printf '%s\n' '#!/usr/bin/env bash' 'case "$*" in *rev-parse*) printf "%s\n" "${FAKE_HEAD:-$(printf a%.0s 1 40)}" ;; *) exit 0 ;; esac' >"$T586/bin/git" +printf '%s\n' '#!/usr/bin/env bash' 'case "$*" in *rev-parse*) printf "%s\n" "${FAKE_HEAD:-$(printf a%.0s {1..40})}" ;; *) exit 0 ;; esac' >"$T586/bin/git" printf '%s\n' '#!/usr/bin/env bash' \ '[ "${FAKE_SS_FAIL:-0}" = 1 ] && exit 2' \ 'case "$1" in' \ @@ -70,7 +70,7 @@ printf '%s\n' '#!/usr/bin/env bash' \ 'exit 0' >"$T586/bin/ss" printf '%s\n' '#!/usr/bin/env bash' \ '[ "${FAKE_NFT_MODE:-}" = fail ] && exit 2' \ - 'if [ "$1" = -j ] && [ "$3" = chain ]; then dropped=0; [ -f "$FAKE_DROP_FILE" ] && dropped=$(cat "$FAKE_DROP_FILE"); sed "s/@PORT@/$FAKE_API_PORT/;s/@DROPPED@/$dropped/" "$FAKE_NFT_CHAIN_TEMPLATE"; exit 0; fi' \ + 'if [ "$1" = -j ] && [ "$3" = chain ]; then dropped=0; [ -s "$FAKE_DROP_FILE" ] && dropped=$(cat "$FAKE_DROP_FILE"); sed "s/@PORT@/$FAKE_API_PORT/;s/@DROPPED@/$dropped/" "$FAKE_NFT_CHAIN_TEMPLATE"; exit 0; fi' \ 'if [ -f "$FAKE_NFT_FILE" ]; then printf '\''{"nftables":[{"table":{"family":"inet","name":"rigforge"}}]}\n'\''; else printf '\''{"nftables":[]}\n'\''; fi' >"$T586/bin/nft" printf '%s\n' '#!/usr/bin/env bash' 'printf "%s STREAM fixture\n" "$FAKE_RESOLVED_ADDRESS"' >"$T586/bin/getent" printf '%s\n' '#!/usr/bin/env bash' \ @@ -82,14 +82,13 @@ printf '%s\n' '#!/usr/bin/env bash' \ 'esac' \ 'exit 0' >"$T586/bin/ip" printf '%s\n' '#!/usr/bin/env bash' 'if [ "${FAKE_MOUNT:-ok}" = ok ]; then echo "hugetlbfs on /dev/hugepages type hugetlbfs (rw)"; else echo "proc on /proc type proc"; fi' >"$T586/bin/mount" -printf '%s\n' '#!/usr/bin/env bash' \ printf '%s\n' '#!/usr/bin/env bash' \ 'for a in "$@"; do if [ "$a" = --config ]; then cfg=$(cat); case "$cfg" in' \ '*/status*) printf "{\"status\":\"%s\"}" "${FAKE_CONTROL_STATUS:-applied}"; exit 0 ;;' \ '*/apply*|*/upgrade*) printf "{\"status\":\"accepted\",\"change_id\":\"0123456789abcdef\"}"; exit 0 ;;' \ 'esac; exit 7; fi; done' \ 'case "$*" in' \ - '*--interface*169.254.241.2*) if [ "${FAKE_REFUSE_MODE:-drop}" = pass ]; then printf 200; exit 0; fi; if [ "${FAKE_REFUSE_MODE:-drop}" = drop ]; then n=0; [ -f "$FAKE_DROP_FILE" ] && n=$(cat "$FAKE_DROP_FILE"); n=$((n + 1)); printf "%s" "$n" >"$FAKE_DROP_FILE"; fi; exit 7 ;;' \ + '*--interface*169.254.241.2*) if [ "${FAKE_REFUSE_MODE:-drop}" = pass ]; then printf 200; exit 0; fi; if [ "${FAKE_REFUSE_MODE:-drop}" = drop ]; then n=0; [ -s "$FAKE_DROP_FILE" ] && n=$(cat "$FAKE_DROP_FILE"); n=$((n + 1)); printf "%s" "$n" >"$FAKE_DROP_FILE"; fi; exit 7 ;;' \ '*--interface*169.254.241.3*) printf "%s" "${FAKE_ACCEPT_CODE:-200}"; exit 0 ;;' \ '*-X?PUT*) [ "${FAKE_CURL_MODE:-}" = transport ] && exit 7; [ "${FAKE_CURL_MODE:-}" = write200 ] && printf 200 || printf 403 ;;' \ '*) n=0; [ -f "$FAKE_CURL_COUNT" ] && n=$(cat "$FAKE_CURL_COUNT"); n=$((n + 1)); printf "%s" "$n" >"$FAKE_CURL_COUNT"; printf "{\"donate_level\":%s,\"hashrate\":{\"total\":[1]},\"connection\":{\"accepted\":%s,\"rejected\":0}}\n" "${FAKE_DONATE_LEVEL:-0}" "$n" ;;' \ @@ -214,16 +213,16 @@ assert_contains "missing throttle stamp is explicit" "$no_stamp" "no throttle st : >"$T586/curl-count" : >"$T586/nft-present" -bad_head="$(CASE_PHASE=upgraded guest586 FAKE_INSTALLED=1 FAKE_PEER=present E2E_EXPECTED_HEAD="$(printf 'b%.0s' 1 40)" 2>&1)" +bad_head="$(CASE_PHASE=upgraded guest586 FAKE_INSTALLED=1 FAKE_PEER=present E2E_EXPECTED_HEAD="$(printf 'b%.0s' {1..40})" 2>&1)" assert_rc "upgraded verifier fails when the checkout is not the candidate" "$?" 1 assert_contains "candidate mismatch is explicit" "$bad_head" "not at the candidate commit" -CASE_PHASE=upgraded guest586 FAKE_INSTALLED=1 FAKE_PEER=present E2E_EXPECTED_HEAD="$(printf 'a%.0s' 1 40)" +CASE_PHASE=upgraded guest586 FAKE_INSTALLED=1 FAKE_PEER=present E2E_EXPECTED_HEAD="$(printf 'a%.0s' {1..40})" assert_rc "upgraded verifier proves the candidate commit keeps shares landing at donation zero" "$?" 0 -digest="$( { sha256sum "$T586/clone/config.json" || shasum -a 256 "$T586/clone/config.json"; } 2>/dev/null | awk '{print $1}')" +digest="$({ sha256sum "$T586/clone/config.json" || shasum -a 256 "$T586/clone/config.json"; } 2>/dev/null | awk '{print $1}')" CASE_PHASE=restored guest586 E2E_RESTORED_CONFIG_SHA256="$digest" assert_rc "restored verifier proves the backup round-trip digest" "$?" 0 -stale="$(CASE_PHASE=restored guest586 E2E_RESTORED_CONFIG_SHA256="$(printf '0%.0s' 1 64)" 2>&1)" +stale="$(CASE_PHASE=restored guest586 E2E_RESTORED_CONFIG_SHA256="$(printf '0%.0s' {1..64})" 2>&1)" assert_rc "restored verifier fails a digest mismatch" "$?" 1 assert_contains "digest mismatch is explicit" "$stale" "differs from the backup" mv "$T586/clone/backups/rigforge-backup-20261117-000000.tar.gz" "$T586/archive.hold" From bb7cdf2e9f4d3021a811d4a939b50e84f47da146 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 22:13:24 -0600 Subject: [PATCH 4/5] Document the guest battery lane and what stays on real hardware (#663) Co-Authored-By: Claude Code --- RELEASING.md | 9 +++++++++ tests/README.md | 49 +++++++++++++++++++++++++++++++++++-------------- 2 files changed, 44 insertions(+), 14 deletions(-) diff --git a/RELEASING.md b/RELEASING.md index 2eb776a9..7a57ea1e 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -43,6 +43,15 @@ promoted to `main` and tagged. The steps below build the release commit on `deve sudo bash tests/e2e-real.sh teardown # uninstall + assert a clean revert ``` + The steps that need a fresh host or a reboot no longer rest on this gate alone: the + bench's `rigforge`/`tier4-kvm` job runs `make e2e-docs-replay` on a fresh Ubuntu 24.04 + guest (tests/README.md › Documentation replay) — documented install, reboot-persistent + autostart, the API allowlist from a second source, control apply/revert, the + remote-upgrade chain onto the candidate, backup/restore, the uninstall revert and + appliance mode — and its green job is the gate evidence for those steps. What stays on + real hardware is what no guest can prove: real hashrate, tuning, MSR read-back, RAPL + and thermal-sensor checks — the `verify`, `watchdog` and `perf` phases above. + When a live Pithead stack is reachable, also run the worker↔stack contract gate (stack on its latest release tag — record `pithead version` in the run log). It asserts the mining round-trip, the `:8080` API contract, stratum auth (pass `E2E_STRATUM_PASS` if the stack uses one), dashboard diff --git a/tests/README.md b/tests/README.md index bf8d3b3a..647393df 100644 --- a/tests/README.md +++ b/tests/README.md @@ -51,6 +51,7 @@ CI median/p90, failures and occupied hours; missing evidence leaves rollout acce | **Unit + black-box suite** | [`run.sh`](run.sh) + [`test-contract-credentials.sh`](test-contract-credentials.sh) | Any host (macOS/Linux), no Docker; credential regression needs Python 3. **In CI.** | Config parsing, the XMRig-config generation matrix (every CPU/OS profile, simulated via PATH stubs), GRUB/HugePages math, the command surface, tune search, doctor: everything that doesn't need a real `/etc` or real hardware. The bulk of coverage. | `make test` (lint + suite) or `make test-suite` | | **Linux container e2e** | [`e2e/linux.sh`](e2e/linux.sh) → [`e2e/in-container.sh`](e2e/in-container.sh) | Disposable Ubuntu container, **needs Docker**. **In CI.** | The genuine Linux deploy path against a real (throwaway) `/etc` with real GNU tools (`sed -i`, `tee`, `envsubst`) + idempotency on re-run. Only the heavy/privileged bits (compile, package install, `systemctl`/`mount`) are stubbed. A second pass re-runs the container with `RIGFORGE_APPLIANCE=1` (#348) and proves the appliance contracts on that real `/etc`: units land in `/run/systemd/system`, no package installs, no fstab/limits.conf/logrotate writes, every enable carries `--runtime`. A third script, [`e2e/isolation.sh`](e2e/isolation.sh) (#668), puts the rig on a Docker `--internal` network whose only reachable peer is a SOCKS5 proxy fronting a stand-in GitHub (a TLS git smart-HTTP server plus the releases API). With `tor_socks5` set it runs `upgrade --check`, `setup`, a local `upgrade` with an XMRig pin change and the `control-upgrade` oneshot in its own empty environment, and proves from the proxy's log that every connection named a hostname. It also proves the block is real (a direct connection and a keyless `upgrade --check` fail), that an unreachable proxy fails closed without reaching the upstream, and that the live build survives the failed upgrade. | `make test-e2e` | | **Native macOS e2e** | [`e2e/macos.sh`](e2e/macos.sh) | A real Mac, **manual, local only. Not in CI** (macOS is deprecated, #493). | The macOS deploy path with genuine BSD tools the Linux CI can only stub: BSD `sed`, the macOS config profile, `mac_*` process control (real `nohup` + PID file), the launchd login agent, `backup`/`restore`. | `make test-e2e-macos` | +| **Docs-replay guest battery** | [`docs_replay.py`](docs_replay.py) + [`e2e-docs-guest.sh`](e2e-docs-guest.sh) | Transient Ubuntu 24.04 KVM guest on the bench's `rigforge`/`tier4-kvm` lane, **In CI via bench-ci**; by hand with `virsh`. | The install-to-uninstall battery on a fresh host: the documented install verbatim with a dry run that changes nothing, reboot-persistent autostart, accepted shares at donation zero on a throwaway endpoint, allowlist enforcement from a second source (refused, then accepted), one applied and one reverted control change, the remote-upgrade chain on real git onto the exact candidate commit, backup/restore, the uninstall revert across a reboot, and appliance mode with runtime-only units. Real hashrate, tuning, MSR read-back, RAPL and thermal checks stay with `e2e-real.sh`. | `make e2e-docs-replay` | | **Coverage gate** | [`coverage.sh`](coverage.sh) | kcov in **Docker**. **In CI.** | Line coverage of `rigforge.sh` and its shell helpers by running `run.sh` under kcov; enforces the committed floor ([`coverage-floor.txt`](coverage-floor.txt)) plus a patch-coverage gate (diff-cover) on changed lines. | `make coverage` | | **Release smoke (quick)** | [`smoke.sh`](smoke.sh) | Real Linux rig, **manual**. Not in CI. | The compiled binary actually starts and hashes (`xmrig --bench`, fully offline). Fast pre-tag confidence that the worker we ship runs. | `make smoke` | | **Release e2e (full)** | [`e2e-real.sh`](e2e-real.sh) | Real Linux rig, **manual, root**. Not in CI. | The real thing end to end: build + tune + kernel tuning + service + a real hash, the writable control path (#236) against real systemd (`control` phase), the remote-upgrade chain with real git as the root oneshot (`upgrade` phase, #322), then a clean uninstall. **The release gate.** | `make e2e-real` (see [`RELEASING.md`](../RELEASING.md)) | @@ -156,13 +157,17 @@ snapshots remain on disk when cleanup cannot prove the original config bytes and ### Documentation replay on a disposable VM -`make e2e-docs-replay` is the VM job entry point for the documented installation and -uninstall lifecycle. Run it on a Linux KVM controller with Python 3 and `virsh` access to -the local system libvirt instance. The job requires these environment variables: +`make e2e-docs-replay` is the VM job entry point for the install-to-uninstall +battery: the documented install, reboot-persistent autostart, allowlist enforcement +from a second source, one applied and one reverted control change, the remote-upgrade +chain onto the exact candidate commit, backup/restore, the uninstall revert and +appliance mode. It runs as the `rigforge`/`tier4-kvm` bench-ci job, and it can also be +driven by hand on a Linux KVM controller with Python 3 and `virsh` access to the +local system libvirt instance. The job requires these environment variables: | Variable | Required value | |---|---| -| `E2E_DOCS_DISPOSABLE` | `1`, acknowledging that setup, uninstall and two reboots will mutate the guest. | +| `E2E_DOCS_DISPOSABLE` | `1`, acknowledging that setup, uninstall, the appliance re-setup and two reboots will mutate the guest. | | `E2E_DOCS_VM_UUID` | UUID of a running, transient, disposable Ubuntu cloud VM with AVX2 exposed. Persistent domains are refused. | | `E2E_DOCS_CONFIG` | Path to the prepared configuration for this run, kept outside the checkout. | @@ -178,25 +183,41 @@ do not supply a wallet, production endpoint or credential. Leave `ACCESS_TOKEN` and control disabled and use the default worker location. Only `pools`, `DONATION`, `api_allow_from`, `HOME_DIR` and optional `threads` are accepted; pool objects accept only `url`, `user` and `pass`. The guest must be able -to download the documented release and its build dependencies. +to download the documented release and its build dependencies, and the candidate +commit must already be pushed, because the forward-upgrade leg fetches it from the +documented clone's origin. The driver extracts the marked Bash blocks from the README and walkthrough, checks their quick-start commands agree, and executes them unchanged through the guest agent. It inserts the prepared config before the documented dry run and -setup. This deliberately tests the release pinned by the documentation; it does -not silently replace that release with the candidate branch. Marker and command +setup. The battery installs the release pinned by the documentation first — the +documented install itself is never swapped for the candidate — then moves the +guest's checkout to the exact candidate commit with `git fetch`, `git checkout` +and `rigforge.sh upgrade`, and runs the remaining legs there. Marker and command agreement lint runs in `tests/run.sh` without Python. The host-driver regression and guest-check negative controls run under `make test-suite`. The job snapshots the system changes before dry run, checks autostart after a new boot ID, donation zero, the configured pool as the only miner peer, increasing -accepted shares with no rejects, and a refused base-API write. After uninstall and -a second new boot ID it checks units, processes, listeners, pool sockets, the nft -table, 2 MiB HugePages and GRUB restoration. A stopped or unreachable guest after -reboot is a platform failure (exit 2), never an autostart failure. Other failed -assertions exit 1. The controller emits only fixed progress messages; raw guest -output stays out of public evidence. Always discard the fixture after success, -failure or timeout; the driver never deletes a caller-owned VM. +accepted shares with no rejects, and a refused base-API write. From a second source +in a temporary netns the API must be refused while the nft drop counter rises, and +only after widening `api_allow_from` and applying may that source be accepted with +HTTP 200 while loopback keeps working; the allowlist is then restored. The control +path applies one change and reverts another, with the generated config and the +running miner following both. The remote-upgrade chain runs a noop leg and a +forged-tag leg that must roll back leaving the checkout, VERSION and throttle stamp +intact, and the forward leg upgrades to the candidate commit and re-proves mining. +A backup, a deliberate config edit and a restore must return the pre-backup config +digest. After uninstall and a second new boot ID it checks units, processes, +listeners, pool sockets, the nft table, 2 MiB HugePages and GRUB restoration. A +fresh `RIGFORGE_APPLIANCE=1` setup on the same stock guest must prove appliance +mode: runtime-only units only, GRUB, fstab, limits, modules and the kernel command +line byte-identical to the fresh baseline, hugetlbfs mounted at runtime and mining +at donation zero. A stopped or unreachable guest after reboot is a platform failure +(exit 2), never an autostart failure. Other failed assertions exit 1. The +controller emits only fixed progress messages; raw guest output stays out of public +evidence. Always discard the fixture after success, failure or timeout; the driver +never deletes a caller-owned VM. The existing worker-to-stack `network` phase also makes a bounded request from a temporary network namespace, bracketed by successful requests from the allowed From 986093d879ef6e1f87c3fb1c31b691a01f088942 Mon Sep 17 00:00:00 2001 From: "pithead-developer[bot]" <4933481+pithead-developer[bot]@users.noreply.github.com> Date: Tue, 17 Nov 2026 23:05:24 -0600 Subject: [PATCH 5/5] Replace the single-source allowlist instead of comma-widening; prove the base-API write refusal with the control token set (#663) Co-Authored-By: Claude Code --- docs/dev/file-budget.tsv | 2 +- tests/README.md | 6 ++++-- tests/docs_replay.py | 19 ++++++------------- tests/e2e-docs-guest.sh | 12 +++++++++--- tests/test-docs-replay.py | 16 ++++++++++------ tests/test-e2e-docs-guest.sh | 17 +++++++++++++---- 6 files changed, 43 insertions(+), 29 deletions(-) diff --git a/docs/dev/file-budget.tsv b/docs/dev/file-budget.tsv index b442a972..6c39aba0 100644 --- a/docs/dev/file-budget.tsv +++ b/docs/dev/file-budget.tsv @@ -2,7 +2,7 @@ # target/ceiling rationale and CONTRIBUTING.md for the gate. # pathceiling-in-lines. Ceilings only ever go down; a file at or below 400 lines drops its entry. rigforge.sh 6207 -tests/e2e-docs-guest.sh 565 +tests/e2e-docs-guest.sh 571 tests/e2e-pithead.sh 563 tests/e2e-real.sh 1388 tests/run.sh 9556 diff --git a/tests/README.md b/tests/README.md index 647393df..45cf33e9 100644 --- a/tests/README.md +++ b/tests/README.md @@ -201,8 +201,10 @@ The job snapshots the system changes before dry run, checks autostart after a ne boot ID, donation zero, the configured pool as the only miner peer, increasing accepted shares with no rejects, and a refused base-API write. From a second source in a temporary netns the API must be refused while the nft drop counter rises, and -only after widening `api_allow_from` and applying may that source be accepted with -HTTP 200 while loopback keeps working; the allowlist is then restored. The control +after `api_allow_from` is replaced with that source (the product grammar is one +address or CIDR) and applied, only it and loopback may reach the API — the source +gets HTTP 200 while loopback keeps working through the always-present `iifname lo` +rule; the allowlist is then restored. The control path applies one change and reverts another, with the generated config and the running miner following both. The remote-upgrade chain runs a noop leg and a forged-tag leg that must roll back leaving the checkout, VERSION and throttle stamp diff --git a/tests/docs_replay.py b/tests/docs_replay.py index 5a1feb60..6b2615ea 100644 --- a/tests/docs_replay.py +++ b/tests/docs_replay.py @@ -150,7 +150,7 @@ def replay(root, guest, config): print("PASS: reboot autostart, donation, pool, shares and read-only API", flush=True) guest.run(f"E2E_ALLOWLIST_ALLOWED_SOURCE={ALLOWED_SECOND_SOURCE} {check} allowlist-refuse {args}\n", timeout=300) guest.run("cd " + clone + "\njq --arg source " + shlex.quote(ALLOWED_SECOND_SOURCE) + - " '.api_allow_from += \", \" + $source' config.json >config.tmp && mv config.tmp config.json\n" + " '.api_allow_from = $source' config.json >config.tmp && mv config.tmp config.json\n" "sudo ./rigforge.sh apply\n", timeout=300) guest.run(f"E2E_ALLOWLIST_ALLOWED_SOURCE={ALLOWED_SECOND_SOURCE} {check} allowlist-accept {args}\n", timeout=180) guest.run("cd " + clone + "\njq --arg original " + shlex.quote(allow_from) + @@ -175,7 +175,7 @@ def replay(root, guest, config): guest.run(f"cd {quoted}/rigforge\ngit fetch --quiet --tags origin\n" f"git fetch --quiet origin {commit}\ngit checkout --quiet --force FETCH_HEAD\n" "sudo ./rigforge.sh upgrade\n", timeout=2400) - guest.run(f"E2E_EXPECTED_HEAD={commit} {check} upgraded {args}\n", timeout=900) + guest.run(f"E2E_CONTROL_TOKEN={token} E2E_EXPECTED_HEAD={commit} {check} upgraded {args}\n", timeout=900) print("PASS: remote upgrade from the previous release to the candidate kept shares landing", flush=True) digest = guest.run(f"cd {quoted}/rigforge\nsha256sum config.json | awk '{{print $1}}'\n").strip() if not re.fullmatch(r"[0-9a-f]{64}", digest): @@ -200,14 +200,6 @@ def replay(root, guest, config): guest.run(f"cd {quoted}/rigforge\nsudo env RIGFORGE_APPLIANCE=1 ./rigforge.sh uninstall --yes\n", timeout=120) -def _network_invalid(entry): - try: - ipaddress.ip_network(entry.strip(), strict=False) - except ValueError: - return True - return False - - def check_config(config): data = json.loads(config) allowed = {"pools", "DONATION", "api_allow_from", "HOME_DIR", "threads"} @@ -225,9 +217,10 @@ def check_config(config): or pools[0].get("user", "docs-replay") != "docs-replay" or pools[0].get("pass", "x") not in ("", "x")): raise ReplayError("prepared config needs one throwaway pool, donation zero and an API allowlist") - if any(not part.strip() for part in data["api_allow_from"].split(",")) or any( - _network_invalid(part) for part in data["api_allow_from"].split(",")): - raise ReplayError("prepared config API allowlist entries must be valid networks") + try: + ipaddress.ip_network(data["api_allow_from"], strict=False) + except ValueError: + raise ReplayError("prepared config api_allow_from must be one valid address or network") from None endpoint = urlsplit("//" + pools[0]["url"]) if (not endpoint.hostname or not endpoint.port or endpoint.username is not None or endpoint.password is not None or endpoint.path or endpoint.query or endpoint.fragment diff --git a/tests/e2e-docs-guest.sh b/tests/e2e-docs-guest.sh index 13e61bb8..847ba8bc 100755 --- a/tests/e2e-docs-guest.sh +++ b/tests/e2e-docs-guest.sh @@ -47,6 +47,7 @@ ALLOW_TARGET="${E2E_ALLOWLIST_TARGET:-169.254.241.1}" ALLOW_REFUSED_SOURCE="${E2E_ALLOWLIST_REFUSED_SOURCE:-169.254.241.2}" ALLOW_ALLOWED_SOURCE="${E2E_ALLOWLIST_ALLOWED_SOURCE:-169.254.241.3}" ALLOW_NET="${E2E_ALLOWLIST_NET:-169.254.241.0/29}" +SYSTEMD_SYSTEM_DIR="${E2E_SYSTEMD_SYSTEM_DIR:-/etc/systemd/system}" read_file() { [ -f "$1" ] && cat "$1" || printf '\n' @@ -301,8 +302,12 @@ _assert_accepted_shares() { _assert_read_only_api() { local code - code="$(curl -sS --noproxy '*' -o /dev/null -w '%{http_code}' --max-time 5 -H 'Content-Type: application/json' -X PUT --data '{}' "$API_URL/1/config")" || fail "base API write probe transport failed" - [ "$code" = 403 ] || fail "base API write probe did not return HTTP 403" + if [ -n "$CONTROL_TOKEN" ]; then + code="$(curl -sS --noproxy '*' -o /dev/null -w '%{http_code}' --max-time 5 -H 'Content-Type: application/json' -H "Authorization: Bearer $CONTROL_TOKEN" -X PUT --data '{}' "$API_URL/1/config")" || fail "base API write probe transport failed" + else + code="$(curl -sS --noproxy '*' -o /dev/null -w '%{http_code}' --max-time 5 -H 'Content-Type: application/json' -X PUT --data '{}' "$API_URL/1/config")" || fail "base API write probe transport failed" + fi + [ "$code" = 403 ] || fail "base API write probe did not return HTTP 403 (got $code)" } phase_installed() { @@ -415,6 +420,7 @@ _drop_counter() { nft -j list chain inet rigforge api 2>/dev/null | jq -r --argjson port "$1" ' [.nftables[].rule | select(.family == "inet" and .table == "rigforge" and .chain == "api") + | select(any(.expr[]?; has("match") and .match?.right == $port)) | select(any(.expr[]?; has("drop"))) | [.expr[]? | .counter?.packets // empty] | select(length == 1) | .[0]] @@ -497,7 +503,7 @@ phase_appliance() { /run/systemd/system/*) ;; *) fail "xmrig is not a runtime unit" ;; esac - persistent="$(find /etc/systemd/system -maxdepth 1 \( -name 'xmrig-*' -o -name 'rigforge-*' \) -print -quit 2>/dev/null || true)" + persistent="$(find "$SYSTEMD_SYSTEM_DIR" -maxdepth 1 \( -name 'xmrig-*' -o -name 'rigforge-*' \) -print -quit 2>/dev/null || true)" [ -z "$persistent" ] || fail "appliance mode wrote persistent units" cmp -s "$BASELINE/fstab" <(read_file "$FSTAB_FILE") || fail "appliance mode changed fstab" cmp -s "$BASELINE/limits" <(read_file "$LIMITS_FILE") || fail "appliance mode changed limits" diff --git a/tests/test-docs-replay.py b/tests/test-docs-replay.py index 638f29f2..3a9cab65 100644 --- a/tests/test-docs-replay.py +++ b/tests/test-docs-replay.py @@ -63,11 +63,13 @@ def test_endpoint_cannot_embed_credentials_or_a_path(self): with self.assertRaises(ReplayError): check_config(json.dumps(data)) - def test_allowlist_accepts_the_lane_comma_list_and_rejects_invalid_members(self): - data = self.config() - data["api_allow_from"] = f"{data['api_allow_from']}, ::1/128" - check_config(json.dumps(data)) - for value in ("127.0.0.1/32, not-a-network", "127.0.0.1/32,", " "): + def test_allowlist_matches_the_products_single_address_or_network_grammar(self): + for value in ("::1/128", "192.168.7.0/24"): + data = self.config() + data["api_allow_from"] = value + with self.subTest(value=value): + check_config(json.dumps(data)) + for value in ("127.0.0.1/32, ::1/128", "127.0.0.1/33", "not-a-network", " "): data = self.config() data["api_allow_from"] = value with self.subTest(value=value), self.assertRaises(ReplayError): @@ -150,7 +152,7 @@ def setUp(self): [""] * 9) self.config = json.dumps({ "pools": [{"url": f"fixture-{os.getpid()}:12345", "user": "docs-replay", "pass": "x"}], - "DONATION": 0, "api_allow_from": "127.0.0.1/32, ::1/128"}).encode() + "DONATION": 0, "api_allow_from": "127.0.0.1/32"}).encode() patcher = patch.object(docs_replay, "candidate", return_value=self.CANDIDATE) patcher.start() self.addCleanup(patcher.stop) @@ -166,12 +168,14 @@ def test_full_battery_drives_both_reboots_in_order(self): for index, marker in ((3, " baseline "), (4, commands["dry-run"]), (5, " dry-run-check "), (6, commands["setup"]), (7, " installed "), (8, " allowlist-refuse "), (9, "169.254.241.3"), + (9, "'.api_allow_from = $source'"), (10, " allowlist-accept "), (12, '.control = "enabled"'), (13, " control-apply "), (14, " control-revert "), (15, "git tag v99.99.99"), (16, "E2E_UPGRADE_LEG=noop"), (17, "E2E_UPGRADE_LEG=refused"), (18, f"git fetch --quiet origin {self.CANDIDATE}"), (19, f"E2E_EXPECTED_HEAD={self.CANDIDATE}"), (19, "check.sh upgraded"), + (19, "E2E_CONTROL_TOKEN="), (20, "sha256sum config.json"), (21, "backup --yes"), (23, "restore --yes backups/rigforge-backup-20261117-010203.tar.gz"), (24, "E2E_RESTORED_CONFIG_SHA256=" + "a" * 64), diff --git a/tests/test-e2e-docs-guest.sh b/tests/test-e2e-docs-guest.sh index 4ebb9b53..c4cb37d7 100755 --- a/tests/test-e2e-docs-guest.sh +++ b/tests/test-e2e-docs-guest.sh @@ -90,7 +90,7 @@ printf '%s\n' '#!/usr/bin/env bash' \ 'case "$*" in' \ '*--interface*169.254.241.2*) if [ "${FAKE_REFUSE_MODE:-drop}" = pass ]; then printf 200; exit 0; fi; if [ "${FAKE_REFUSE_MODE:-drop}" = drop ]; then n=0; [ -s "$FAKE_DROP_FILE" ] && n=$(cat "$FAKE_DROP_FILE"); n=$((n + 1)); printf "%s" "$n" >"$FAKE_DROP_FILE"; fi; exit 7 ;;' \ '*--interface*169.254.241.3*) printf "%s" "${FAKE_ACCEPT_CODE:-200}"; exit 0 ;;' \ - '*-X?PUT*) [ "${FAKE_CURL_MODE:-}" = transport ] && exit 7; [ "${FAKE_CURL_MODE:-}" = write200 ] && printf 200 || printf 403 ;;' \ + '*-X?PUT*) [ "${FAKE_CURL_MODE:-}" = transport ] && exit 7; [ "${FAKE_CURL_MODE:-}" = write200 ] && { printf 200; exit 0; }; case "$*" in *Bearer*) printf 403 ;; *) [ "${FAKE_TOKEN_SET:-0}" = 1 ] && printf 401 || printf 403 ;; esac ;;' \ '*) n=0; [ -f "$FAKE_CURL_COUNT" ] && n=$(cat "$FAKE_CURL_COUNT"); n=$((n + 1)); printf "%s" "$n" >"$FAKE_CURL_COUNT"; printf "{\"donate_level\":%s,\"hashrate\":{\"total\":[1]},\"connection\":{\"accepted\":%s,\"rejected\":0}}\n" "${FAKE_DONATE_LEVEL:-0}" "$n" ;;' \ 'esac' >"$T586/bin/curl" printf '%s\n' '#!/usr/bin/env bash' ':' >"$T586/bin/sleep" @@ -106,7 +106,8 @@ guest586() { E2E_SHARE_TIMEOUT=1 E2E_SHARE_INTERVAL=1 E2E_ACTIVE_TIMEOUT=1 FAKE_NFT_FILE="$T586/nft-present" \ FAKE_POOL_ADDRESS="$POOL_ADDRESS" FAKE_RESOLVED_ADDRESS="$POOL_ADDRESS" FAKE_POOL_PORT="$POOL_PORT" FAKE_API_PORT="$API_PORT" \ FAKE_LOOPBACK_ADDRESS="$LOOPBACK_ADDRESS" FAKE_CURL_COUNT="$T586/curl-count" \ - FAKE_DROP_FILE="$T586/drop-count" FAKE_NFT_CHAIN_TEMPLATE="$T586/nft-chain.json" E2E_CONTROL_STATE_DIR="$T586/ctrlstate" "$@" \ + FAKE_DROP_FILE="$T586/drop-count" FAKE_NFT_CHAIN_TEMPLATE="$T586/nft-chain.json" E2E_CONTROL_STATE_DIR="$T586/ctrlstate" \ + E2E_SYSTEMD_SYSTEM_DIR="$T586/units" "$@" \ bash "$ROOT/tests/e2e-docs-guest.sh" "${CASE_PHASE:?}" "$T586/clone" "$T586/state" } @@ -167,8 +168,8 @@ for failure in "FAKE_NFT_MODE=fail:nft" "FAKE_SS_FAIL=1:socket" "FAKE_SYSTEMCTL_ done printf '1.18.1\n' >"$T586/clone/VERSION" -mkdir -p "$T586/ctrlstate" "$T586/ctrlstate-empty" "$T586/clone/backups" -touch "$T586/ctrlstate/last" "$T586/clone/backups/rigforge-backup-20261117-000000.tar.gz" +mkdir -p "$T586/ctrlstate" "$T586/ctrlstate-empty" "$T586/clone/backups" "$T586/units" "$T586/units-persistent" +touch "$T586/ctrlstate/last" "$T586/clone/backups/rigforge-backup-20261117-000000.tar.gz" "$T586/units-persistent/xmrig-evil.service" : >"$T586/drop-count" CASE_PHASE=allowlist-refuse guest586 @@ -218,6 +219,11 @@ assert_rc "upgraded verifier fails when the checkout is not the candidate" "$?" assert_contains "candidate mismatch is explicit" "$bad_head" "not at the candidate commit" CASE_PHASE=upgraded guest586 FAKE_INSTALLED=1 FAKE_PEER=present E2E_EXPECTED_HEAD="$(printf 'a%.0s' {1..40})" assert_rc "upgraded verifier proves the candidate commit keeps shares landing at donation zero" "$?" 0 +CASE_PHASE=upgraded guest586 FAKE_INSTALLED=1 FAKE_PEER=present FAKE_TOKEN_SET=1 E2E_CONTROL_TOKEN=fixturetoken E2E_EXPECTED_HEAD="$(printf 'a%.0s' {1..40})" +assert_rc "upgraded verifier proves the base-API write stays refused with the control token" "$?" 0 +token401="$(CASE_PHASE=upgraded guest586 FAKE_INSTALLED=1 FAKE_PEER=present FAKE_TOKEN_SET=1 E2E_EXPECTED_HEAD="$(printf 'a%.0s' {1..40})" 2>&1)" +assert_rc "upgraded verifier fails when the bearer-less write probe is required" "$?" 1 +assert_contains "tokenized 401 is explicit" "$token401" "did not return HTTP 403 (got 401)" digest="$({ sha256sum "$T586/clone/config.json" || shasum -a 256 "$T586/clone/config.json"; } 2>/dev/null | awk '{print $1}')" CASE_PHASE=restored guest586 E2E_RESTORED_CONFIG_SHA256="$digest" @@ -237,6 +243,9 @@ assert_contains "persistent fragment is explicit" "$frag_err" "not a runtime uni mount_err="$(CASE_PHASE=appliance guest586 FAKE_INSTALLED=1 FAKE_FRAGMENT=/run/systemd/system/xmrig.service FAKE_MOUNT=none 2>&1)" assert_rc "appliance verifier fails without the runtime hugetlbfs mount" "$?" 1 assert_contains "missing hugetlbfs is explicit" "$mount_err" "hugetlbfs is not mounted" +planted="$(CASE_PHASE=appliance guest586 FAKE_INSTALLED=1 FAKE_FRAGMENT=/run/systemd/system/xmrig.service E2E_SYSTEMD_SYSTEM_DIR="$T586/units-persistent" 2>&1)" +assert_rc "appliance verifier fails when a persistent unit exists" "$?" 1 +assert_contains "planted persistent unit is explicit" "$planted" "wrote persistent units" CASE_PHASE=appliance guest586 FAKE_INSTALLED=1 FAKE_FRAGMENT=/run/systemd/system/xmrig.service assert_rc "appliance verifier proves runtime-only units with the baseline files intact" "$?" 0