From 4f5aa67e5be4fd84deb82f2827f713642a90f334 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:26:00 +0300 Subject: [PATCH 01/68] security(sub): move gateway and limiter to versioned current Alpine images --- install.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/install.sh b/install.sh index 9b882d9..7ab75bd 100644 --- a/install.sh +++ b/install.sh @@ -118,7 +118,7 @@ render_compose() { cat <<'YAML' services: xmesh-sub-limiter: - image: python:3.12-alpine + image: python:3.12.16-alpine3.24 restart: unless-stopped user: "65534:65534" command: ["python3", "-I", "/opt/limiter.py"] @@ -134,7 +134,7 @@ services: - /tmp # No published ports: Caddy is the only client, via a shared Unix socket. xmesh-sub: - image: caddy:2 + image: caddy:2.11.9-alpine container_name: xmesh-sub restart: unless-stopped depends_on: @@ -507,7 +507,7 @@ if semver(new) Date: Mon, 16 Nov 2026 15:26:18 +0300 Subject: [PATCH 02/68] test(sub): assert signed installer renders reviewed image tags --- tests/test-install.sh | 101 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/tests/test-install.sh b/tests/test-install.sh index f10f2ac..f9d6cd6 100644 --- a/tests/test-install.sh +++ b/tests/test-install.sh @@ -17,6 +17,107 @@ grep -Fq 'header_up -X-Forwarded-Uri' <<< "$out" grep -Fq 'header_up -Authorization' <<< "$out" grep -Fq 'header_up -Cookie' <<< "$out" grep -Fq 'xmesh-sub-limiter:' <<< "$out" +# The signed installer must use exactly the images tested by the image scanner, +# not unpinned major-version tags that could silently change after approval. +grep -Fq 'image: caddy:2.11.9-alpine' <<< "$out" +grep -Fq 'image: python:3.12.16-alpine3.24' <<< "$out" +if grep -Eq 'image: (caddy:2|python:3\\.12-alpine) +grep -Fq './run:/run/xmesh-sub:ro' <<< "$out" +# The signed installer embeds the exact, audited limiter source, no unsigned +# source fetch or module download is permitted on the Sub VPS. +tmp_limiter=$(mktemp) +trap 'rm -f "$tmp_limiter"' EXIT +sed -n '/^# limiter.py$/,$p' <<< "$out" | sed '1d' >"$tmp_limiter" +cmp -s limiter.py "$tmp_limiter" || { echo 'ERROR: signed installer limiter differs from source' >&2; exit 1; } +# The standard proxy must retain origin subscription metadata, including +# profile-web-page-url and support-url. The personal webpage points to the +# same allowlisted /s/{token} route with ?view=portal. +# Caddy reverse_proxy forwards query parameters and upstream response headers +# by default. Do not introduce response-header stripping or URI rewriting. +if grep -Eq 'header_down|uri strip_prefix|rewrite \*|header -profile-web-page-url|header -support-url' <<< "$out"; then + echo 'ERROR: gateway must not strip subscription profile metadata' >&2 + exit 1 +fi +grep -Fq 'Referrer-Policy "no-referrer"' <<< "$out" +grep -Fq 'Cache-Control "private, no-store"' <<< "$out" +grep -Fq 'header_up -Cookie' <<< "$out" +# A real HTML portal needs its exact CSS/JS files; all other paths remain 404. +grep -Fq 'path /subscription-studio.css /subscription-surface.css /subscription-public.css /qr-code.js /subscription-experience.js /subscription-traffic.js /subscription-portal.js' <<< "$out" +grep -Fq 'handle @portal_assets {' <<< "$out" +# Ensure only one explicit public static allowlist, not a blanket /js/* or /*. +if grep -Eq 'path /\*|path /js/\*|path /styles/\*' <<< "$out"; then + echo 'ERROR: portal static allowlist is too broad' >&2 + exit 1 +fi +grep -Fq 'read_only: true' <<< "$out" +grep -Fq 'Validation successful' <<< "$out" +# Nexus mounts its public readiness route under /api/v1. A bare /health/ready is 404. +# Literal source-code signatures (not intended for shell expansion). +# shellcheck disable=SC2016 +grep -Fq '"$PANEL/api/v1/health/ready"' install.sh +# shellcheck disable=SC2016 +if grep -Fq '"$PANEL/health/ready"' install.sh; then + echo 'ERROR: installer uses the old, unmounted Nexus readiness path' >&2 + exit 1 +fi +out=$(bash install.sh --panel https://panel.example.org --domain sub.example.org --path /example/vpn --email ops@example.org --dry-run) +grep -Fq 'path_regexp ^(/example/vpn|/sub|/portal)/[0-9a-f]{64}$' <<< "$out" +grep -Fq 'email ops@example.org' <<< "$out" +fail_expected --panel http://panel.example.org --domain sub.example.org --path /s +fail_expected --panel https://panel.example.org/login --domain sub.example.org --path /s +fail_expected --panel https://panel.example.org:443 --domain sub.example.org --path /s +fail_expected --panel https://127.0.0.1 --domain sub.example.org --path /s +fail_expected --panel https://panel.example.org --domain panel.example.org --path /s +fail_expected --panel https://panel.example.org --domain 'evil;curl bad' --path /s +fail_expected --panel https://panel.example.org --domain sub.example.org --path /api/admin +# Literal injection payload must not expand in the test shell. +# shellcheck disable=SC2016 +fail_expected --panel https://panel.example.org --domain sub.example.org --path '/s/$(whoami)' +fail_expected --panel https://panel.example.org --domain sub.example.org --path /s/../login +fail_expected --panel https://panel.example.org --domain sub.example.org --path /s/ +fail_expected --panel https://panel.example.org --domain sub.example.org --path /s --email 'ops@evil.com;rm' +token=$(printf 'a%.0s' {1..64}) +printf '%s\n' "$token" | bash install.sh --panel https://panel.example.org --domain sub.example.org --path /s --enroll-token-stdin --dry-run >/dev/null +if bash install.sh --panel https://panel.example.org --domain sub.example.org --path /s --enroll-token "$token" --dry-run >/dev/null 2>&1; then + echo 'ERROR: enrollment tokens must never be accepted in argv' >&2; exit 1 +fi +if printf '%s\n' invalid | bash install.sh --panel https://panel.example.org --domain sub.example.org --path /s --enroll-token-stdin --dry-run >/dev/null 2>&1; then + echo 'ERROR: malformed stdin enrollment token was accepted' >&2; exit 1 +fi +grep -Fq 'gh attestation verify' install.sh +# shellcheck disable=SC2016 # literal source-code assertion, not expansion +grep -Fq -- '--source-digest "$RELEASE_SHA"' install.sh +grep -Fq -- '--cert-identity' install.sh +grep -Fq 'release_verify.py' install.sh +grep -Fq 'Refusing release downgrade' install.sh +if grep -Fq 'release.json.sig' install.sh || grep -Fq 'signed_release(' manager.py; then + echo 'ERROR: legacy offline-manifest release authentication is still enabled' >&2 + exit 1 +fi +# No script may execute at root without an exact attested source commit. +grep -Fq 'Use the automatically attested installer command from Nexus' install.sh +grep -Fq 'ProtectKernelModules=true' install.sh +grep -Fq 'NoNewPrivileges=true' install.sh +grep -Fq 'xmesh-sub-manager.service' install.sh +grep -Fq 'manager.read_config(root / "manager.json")' install.sh +grep -Fq '/api/v1/sub-server/claim' install.sh +grep -Fq '"publicKey": public_key' install.sh +grep -Fq 'agent-key.pem' install.sh +if grep -Fq 'agentToken' install.sh || grep -Fq 'agentToken' manager.py; then + echo 'ERROR: legacy bearer authentication must be removed' >&2; exit 1 +fi +grep -Fq 'SKIP_MANAGER_RESTART' install.sh +# The embedded limiter must EXACTLY match the reviewed standalone source. +python3 - <<'PY' +from pathlib import Path +source=Path('install.sh').read_text().split(" cat <<'XMESH_LIMITER_SOURCE'\n",1)[1].split("\nXMESH_LIMITER_SOURCE",1)[0] +assert source.rstrip('\n')+'\n' == Path('limiter.py').read_text(), 'Limiter embedded in installer differs from tested source' +PY +echo 'Installer validation tests passed' + <<< "$out"; then + echo 'ERROR: floating legacy image found in rendered compose' >&2 + exit 1 +fi grep -Fq './run:/run/xmesh-sub:ro' <<< "$out" # The signed installer embeds the exact, audited limiter source, no unsigned # source fetch or module download is permitted on the Sub VPS. From 2b01c52595108746e0ddba1798e907a489c3f4df Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:26:33 +0300 Subject: [PATCH 03/68] ci(sub): validate Caddy with exact image declared in installer --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b7c55c7..cc21f91 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -28,7 +28,7 @@ jobs: - name: Validate rendered Caddy configuration run: | bash install.sh --panel https://panel.example.org --domain sub.example.org --path /s --dry-run | sed -n '/^# Caddyfile$/,/^# compose.yaml$/p' | sed '1d;$d' > Caddyfile - docker run --rm -v "$PWD/Caddyfile:/etc/caddy/Caddyfile:ro" caddy:2 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile + docker run --rm -v "$PWD/Caddyfile:/etc/caddy/Caddyfile:ro" caddy:2.11.9-alpine caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile - name: Verify keyless release security policy and negative cases run: | python3 -m py_compile release_verify.py From fe6d4d33df9814f606235b64891afa69517e40dc Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:26:36 +0300 Subject: [PATCH 04/68] ci(sub): validate Caddy with exact image declared in installer --- .github/workflows/attested-release.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/attested-release.yml b/.github/workflows/attested-release.yml index ae1bfc9..70474d6 100644 --- a/.github/workflows/attested-release.yml +++ b/.github/workflows/attested-release.yml @@ -41,7 +41,7 @@ jobs: run: | bash install.sh --panel https://panel.example.org --domain sub.example.org --path /s --dry-run | sed -n '/^# Caddyfile$/,/^# compose.yaml$/p' | sed '1d;$d' > Caddyfile - docker run --rm -v "$PWD/Caddyfile:/etc/caddy/Caddyfile:ro" caddy:2 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile + docker run --rm -v "$PWD/Caddyfile:/etc/caddy/Caddyfile:ro" caddy:2.11.9-alpine caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile - name: Enforce immutable release contract run: | python3 - <<'PY' From f4850c5099dded2aaffc031f7e6755aa02a9bb43 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:27:35 +0300 Subject: [PATCH 05/68] security(ci): scan both signed-installer runtime images, record digests and fail on High CVEs --- .github/workflows/image-security.yml | 113 +++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 .github/workflows/image-security.yml diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml new file mode 100644 index 0000000..59e4800 --- /dev/null +++ b/.github/workflows/image-security.yml @@ -0,0 +1,113 @@ +name: Sub deployable image CVE gate +on: + pull_request: + paths: + - 'install.sh' + - 'tests/test-install.sh' + - '.github/workflows/image-security.yml' + - '.github/workflows/ci.yml' + - '.github/workflows/attested-release.yml' + push: + branches: [main] + workflow_dispatch: +permissions: + contents: read +jobs: + image-cve-gate: + runs-on: ubuntu-24.04 + timeout-minutes: 40 + steps: + - name: Fetch exact source without persistent credentials + uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + with: + persist-credentials: false + - name: Verify images rendered by signed installer + shell: bash + run: | + set -Eeuo pipefail + bash install.sh --panel https://panel.example.org --domain sub.example.org --path /s --dry-run > "$RUNNER_TEMP/sub-dry-run" + sed -n '/^# compose.yaml$/,/^# limiter.py$/p' "$RUNNER_TEMP/sub-dry-run" | sed '1d;$d' > "$RUNNER_TEMP/compose.yaml" + python3 - <<'PY' + import os, pathlib, re + compose=pathlib.Path(os.environ["RUNNER_TEMP"],"compose.yaml").read_text() + refs=re.findall(r"^\s+image:\s+(\S+)\s*$",compose,re.M) + allowed=("python:3.12.16-alpine3.24","caddy:2.11.9-alpine") + if len(refs)!=2 or set(refs)!=set(allowed): + raise SystemExit(f"Unexpected installer runtime images: {refs}") + pathlib.Path(os.environ["RUNNER_TEMP"],"image-refs.txt").write_text("\n".join(refs)+"\n") + print("Verified both signed-installer image references") + PY + - name: Pull and record actual image content digests + shell: bash + run: | + set -Eeuo pipefail + : > "$RUNNER_TEMP/image-digests.txt" + while IFS= read -r ref; do + docker pull --platform linux/amd64 "$ref" + docker image inspect --format '{{index .RepoDigests 0}}' "$ref" | tee -a "$RUNNER_TEMP/image-digests.txt" + done < "$RUNNER_TEMP/image-refs.txt" + - name: Install pinned and checksum-verified Trivy v0.76.2 + shell: bash + run: | + set -Eeuo pipefail + python3 - <<'PY' + import hashlib,io,os,pathlib,tarfile,urllib.request + url="https://github.com/aquasecurity/trivy/releases/download/v0.76.2/trivy_0.76.2_Linux-64bit.tar.gz" + wanted="bc0fc726e017b8927a62b2d3531d7a84ee01769daf5c99ed866dced54089fdbf" + with urllib.request.urlopen(url,timeout=75) as request: + data=request.read(100*1024*1024+1) + if len(data)>100*1024*1024 or hashlib.sha256(data).hexdigest()!=wanted: + raise SystemExit("Trivy tarball failed pinned SHA-256/size validation") + with tarfile.open(fileobj=io.BytesIO(data),mode="r:gz") as tar: + entry=tar.getmember("trivy") + if not entry.isfile() or not 0 Date: Mon, 16 Nov 2026 15:30:18 +0300 Subject: [PATCH 06/68] test(sub): restore complete Bash image pin assertion --- tests/test-install.sh | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/test-install.sh b/tests/test-install.sh index f9d6cd6..fcbe9bd 100644 --- a/tests/test-install.sh +++ b/tests/test-install.sh @@ -21,7 +21,10 @@ grep -Fq 'xmesh-sub-limiter:' <<< "$out" # not unpinned major-version tags that could silently change after approval. grep -Fq 'image: caddy:2.11.9-alpine' <<< "$out" grep -Fq 'image: python:3.12.16-alpine3.24' <<< "$out" -if grep -Eq 'image: (caddy:2|python:3\\.12-alpine) +if grep -Eq '^ image: (caddy:2|python:3[.]12-alpine)$' <<< "$out"; then + echo 'ERROR: floating legacy runtime image found in rendered Compose' >&2 + exit 1 +fi grep -Fq './run:/run/xmesh-sub:ro' <<< "$out" # The signed installer embeds the exact, audited limiter source, no unsigned # source fetch or module download is permitted on the Sub VPS. From 1c6e4592e6de9796646b27fad46dd69e1c52a98f Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:30:33 +0300 Subject: [PATCH 07/68] ci(sub): expose checksum and size diagnostics but never execute unverified Trivy --- .github/workflows/image-security.yml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index 59e4800..89d30f3 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -56,8 +56,9 @@ jobs: wanted="bc0fc726e017b8927a62b2d3531d7a84ee01769daf5c99ed866dced54089fdbf" with urllib.request.urlopen(url,timeout=75) as request: data=request.read(100*1024*1024+1) - if len(data)>100*1024*1024 or hashlib.sha256(data).hexdigest()!=wanted: - raise SystemExit("Trivy tarball failed pinned SHA-256/size validation") + actual=hashlib.sha256(data).hexdigest() + if len(data)>100*1024*1024 or actual!=wanted: + raise SystemExit(f"Trivy archive mismatch: size={len(data)}, actual_sha256={actual}, expected_sha256={wanted}. Refusing to execute.") with tarfile.open(fileobj=io.BytesIO(data),mode="r:gz") as tar: entry=tar.getmember("trivy") if not entry.isfile() or not 0 Date: Mon, 16 Nov 2026 15:33:48 +0300 Subject: [PATCH 08/68] test(sub): restore clean installer test and exact runtime image assertions --- tests/test-install.sh | 100 +----------------------------------------- 1 file changed, 1 insertion(+), 99 deletions(-) diff --git a/tests/test-install.sh b/tests/test-install.sh index fcbe9bd..0263489 100644 --- a/tests/test-install.sh +++ b/tests/test-install.sh @@ -17,108 +17,10 @@ grep -Fq 'header_up -X-Forwarded-Uri' <<< "$out" grep -Fq 'header_up -Authorization' <<< "$out" grep -Fq 'header_up -Cookie' <<< "$out" grep -Fq 'xmesh-sub-limiter:' <<< "$out" -# The signed installer must use exactly the images tested by the image scanner, -# not unpinned major-version tags that could silently change after approval. grep -Fq 'image: caddy:2.11.9-alpine' <<< "$out" grep -Fq 'image: python:3.12.16-alpine3.24' <<< "$out" if grep -Eq '^ image: (caddy:2|python:3[.]12-alpine)$' <<< "$out"; then - echo 'ERROR: floating legacy runtime image found in rendered Compose' >&2 - exit 1 -fi -grep -Fq './run:/run/xmesh-sub:ro' <<< "$out" -# The signed installer embeds the exact, audited limiter source, no unsigned -# source fetch or module download is permitted on the Sub VPS. -tmp_limiter=$(mktemp) -trap 'rm -f "$tmp_limiter"' EXIT -sed -n '/^# limiter.py$/,$p' <<< "$out" | sed '1d' >"$tmp_limiter" -cmp -s limiter.py "$tmp_limiter" || { echo 'ERROR: signed installer limiter differs from source' >&2; exit 1; } -# The standard proxy must retain origin subscription metadata, including -# profile-web-page-url and support-url. The personal webpage points to the -# same allowlisted /s/{token} route with ?view=portal. -# Caddy reverse_proxy forwards query parameters and upstream response headers -# by default. Do not introduce response-header stripping or URI rewriting. -if grep -Eq 'header_down|uri strip_prefix|rewrite \*|header -profile-web-page-url|header -support-url' <<< "$out"; then - echo 'ERROR: gateway must not strip subscription profile metadata' >&2 - exit 1 -fi -grep -Fq 'Referrer-Policy "no-referrer"' <<< "$out" -grep -Fq 'Cache-Control "private, no-store"' <<< "$out" -grep -Fq 'header_up -Cookie' <<< "$out" -# A real HTML portal needs its exact CSS/JS files; all other paths remain 404. -grep -Fq 'path /subscription-studio.css /subscription-surface.css /subscription-public.css /qr-code.js /subscription-experience.js /subscription-traffic.js /subscription-portal.js' <<< "$out" -grep -Fq 'handle @portal_assets {' <<< "$out" -# Ensure only one explicit public static allowlist, not a blanket /js/* or /*. -if grep -Eq 'path /\*|path /js/\*|path /styles/\*' <<< "$out"; then - echo 'ERROR: portal static allowlist is too broad' >&2 - exit 1 -fi -grep -Fq 'read_only: true' <<< "$out" -grep -Fq 'Validation successful' <<< "$out" -# Nexus mounts its public readiness route under /api/v1. A bare /health/ready is 404. -# Literal source-code signatures (not intended for shell expansion). -# shellcheck disable=SC2016 -grep -Fq '"$PANEL/api/v1/health/ready"' install.sh -# shellcheck disable=SC2016 -if grep -Fq '"$PANEL/health/ready"' install.sh; then - echo 'ERROR: installer uses the old, unmounted Nexus readiness path' >&2 - exit 1 -fi -out=$(bash install.sh --panel https://panel.example.org --domain sub.example.org --path /example/vpn --email ops@example.org --dry-run) -grep -Fq 'path_regexp ^(/example/vpn|/sub|/portal)/[0-9a-f]{64}$' <<< "$out" -grep -Fq 'email ops@example.org' <<< "$out" -fail_expected --panel http://panel.example.org --domain sub.example.org --path /s -fail_expected --panel https://panel.example.org/login --domain sub.example.org --path /s -fail_expected --panel https://panel.example.org:443 --domain sub.example.org --path /s -fail_expected --panel https://127.0.0.1 --domain sub.example.org --path /s -fail_expected --panel https://panel.example.org --domain panel.example.org --path /s -fail_expected --panel https://panel.example.org --domain 'evil;curl bad' --path /s -fail_expected --panel https://panel.example.org --domain sub.example.org --path /api/admin -# Literal injection payload must not expand in the test shell. -# shellcheck disable=SC2016 -fail_expected --panel https://panel.example.org --domain sub.example.org --path '/s/$(whoami)' -fail_expected --panel https://panel.example.org --domain sub.example.org --path /s/../login -fail_expected --panel https://panel.example.org --domain sub.example.org --path /s/ -fail_expected --panel https://panel.example.org --domain sub.example.org --path /s --email 'ops@evil.com;rm' -token=$(printf 'a%.0s' {1..64}) -printf '%s\n' "$token" | bash install.sh --panel https://panel.example.org --domain sub.example.org --path /s --enroll-token-stdin --dry-run >/dev/null -if bash install.sh --panel https://panel.example.org --domain sub.example.org --path /s --enroll-token "$token" --dry-run >/dev/null 2>&1; then - echo 'ERROR: enrollment tokens must never be accepted in argv' >&2; exit 1 -fi -if printf '%s\n' invalid | bash install.sh --panel https://panel.example.org --domain sub.example.org --path /s --enroll-token-stdin --dry-run >/dev/null 2>&1; then - echo 'ERROR: malformed stdin enrollment token was accepted' >&2; exit 1 -fi -grep -Fq 'gh attestation verify' install.sh -# shellcheck disable=SC2016 # literal source-code assertion, not expansion -grep -Fq -- '--source-digest "$RELEASE_SHA"' install.sh -grep -Fq -- '--cert-identity' install.sh -grep -Fq 'release_verify.py' install.sh -grep -Fq 'Refusing release downgrade' install.sh -if grep -Fq 'release.json.sig' install.sh || grep -Fq 'signed_release(' manager.py; then - echo 'ERROR: legacy offline-manifest release authentication is still enabled' >&2 - exit 1 -fi -# No script may execute at root without an exact attested source commit. -grep -Fq 'Use the automatically attested installer command from Nexus' install.sh -grep -Fq 'ProtectKernelModules=true' install.sh -grep -Fq 'NoNewPrivileges=true' install.sh -grep -Fq 'xmesh-sub-manager.service' install.sh -grep -Fq 'manager.read_config(root / "manager.json")' install.sh -grep -Fq '/api/v1/sub-server/claim' install.sh -grep -Fq '"publicKey": public_key' install.sh -grep -Fq 'agent-key.pem' install.sh -if grep -Fq 'agentToken' install.sh || grep -Fq 'agentToken' manager.py; then - echo 'ERROR: legacy bearer authentication must be removed' >&2; exit 1 -fi -grep -Fq 'SKIP_MANAGER_RESTART' install.sh -# The embedded limiter must EXACTLY match the reviewed standalone source. -python3 - <<'PY' -from pathlib import Path -source=Path('install.sh').read_text().split(" cat <<'XMESH_LIMITER_SOURCE'\n",1)[1].split("\nXMESH_LIMITER_SOURCE",1)[0] -assert source.rstrip('\n')+'\n' == Path('limiter.py').read_text(), 'Limiter embedded in installer differs from tested source' -PY -echo 'Installer validation tests passed' - <<< "$out"; then - echo 'ERROR: floating legacy image found in rendered compose' >&2 + echo 'ERROR: floating legacy image in signed installer' >&2 exit 1 fi grep -Fq './run:/run/xmesh-sub:ro' <<< "$out" From 2a589238543c4f55ea3c4991af2a9c37739a7bf5 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:34:04 +0300 Subject: [PATCH 09/68] ci(sub): allow legitimate 256 MiB Trivy binary while enforcing bounded extraction --- .github/workflows/image-security.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index 89d30f3..6626873 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -61,12 +61,15 @@ jobs: raise SystemExit(f"Trivy archive mismatch: size={len(data)}, actual_sha256={actual}, expected_sha256={wanted}. Refusing to execute.") with tarfile.open(fileobj=io.BytesIO(data),mode="r:gz") as tar: entry=tar.getmember("trivy") - if not entry.isfile() or not 0256*1024*1024 or len(data_bytes)!=entry.size: + raise SystemExit("Unexpected Trivy executable extraction size") + target.write_bytes(data_bytes) target.chmod(0o700) PY - name: Scan both exact deployable runtime images From cd754ee86382c1c765a8a942d84450b34cd22b65 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:40:49 +0300 Subject: [PATCH 10/68] security(sub): prebuild patched Kerberos limiter container from signed Dockerfile --- install.sh | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/install.sh b/install.sh index 7ab75bd..56d8168 100644 --- a/install.sh +++ b/install.sh @@ -114,11 +114,24 @@ $DOMAIN { } CONF } +render_limiter_dockerfile() { + # Build once during the signed installation, not at service startup. A + # patched Kerberos library prevents the known krb5 1.22.2-r1 CVE inventory + # from lingering in the Python image even if upstream tags are stale. + cat <<'DOCKER' +FROM python:3.12.16-alpine3.24@sha256:c5ba3deef00c7758561a0f03c26f44f10589263d40e732b8748e0d1f38f6dd89 +RUN apk --no-cache upgrade krb5-libs +DOCKER +} render_compose() { cat <<'YAML' services: xmesh-sub-limiter: - image: python:3.12.16-alpine3.24 + image: xmesh-sub-limiter:3.12.16-krb5r1 + build: + context: . + dockerfile: Dockerfile.limiter + pull_policy: never restart: unless-stopped user: "65534:65534" command: ["python3", "-I", "/opt/limiter.py"] @@ -360,6 +373,7 @@ XMESH_LIMITER_SOURCE if ((DRY_RUN)); then info "Validation successful, no host changes made." info "Panel: $PANEL | Subscription: https://$DOMAIN$SUB_PATH/{token}" + printf '\n# Dockerfile.limiter\n'; render_limiter_dockerfile printf '\n# Caddyfile\n'; render_caddyfile printf '\n# compose.yaml\n'; render_compose printf '\n# limiter.py\n'; render_limiter @@ -416,7 +430,8 @@ trap 'rm -rf "$temp"' EXIT render_caddyfile >"$temp/Caddyfile" render_compose >"$temp/compose.yaml" render_limiter >"$temp/limiter.py" -chmod 600 "$temp/Caddyfile" "$temp/compose.yaml" "$temp/limiter.py" + render_limiter_dockerfile >"$temp/Dockerfile.limiter" +chmod 600 "$temp/Caddyfile" "$temp/compose.yaml" "$temp/limiter.py" "$temp/Dockerfile.limiter" if command -v python3 >/dev/null; then python3 -m py_compile "$temp/limiter.py" || die "Invalid edge limiter" fi @@ -507,15 +522,22 @@ if semver(new) Date: Mon, 16 Nov 2026 15:41:18 +0300 Subject: [PATCH 11/68] security(sub): back up and restore signed limiter Dockerfile with atomic update rollback --- manager.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/manager.py b/manager.py index 093d0bd..753f19c 100644 --- a/manager.py +++ b/manager.py @@ -85,7 +85,7 @@ def backup_installation(root: Path = ROOT) -> Path: backup = Path(tempfile.mkdtemp(prefix="pre-update-", dir=str(destination))) backup.chmod(0o700) files = ("Caddyfile", "compose.yaml", "manager.py", "manager.json", "agent-key.pem", "limiter.py", - "release_verify.py", "RELEASE_SHA", "VERSION") + "release_verify.py", "RELEASE_SHA", "VERSION", "Dockerfile.limiter") for name in files: old = root / name if old.is_file(): @@ -97,7 +97,7 @@ def backup_installation(root: Path = ROOT) -> Path: def restore_installation(backup: Path, root: Path = ROOT) -> None: for name in ("Caddyfile", "compose.yaml", "manager.py", "manager.json", "agent-key.pem", "limiter.py", - "release_verify.py", "RELEASE_SHA", "VERSION"): + "release_verify.py", "RELEASE_SHA", "VERSION", "Dockerfile.limiter"): saved = backup / name target = root / name if saved.is_file(): @@ -105,7 +105,7 @@ def restore_installation(backup: Path, root: Path = ROOT) -> None: elif (backup / (".absent-" + name)).is_file(): target.unlink(missing_ok=True) subprocess.run(["docker", "compose", "-f", str(root / "compose.yaml"), - "up", "-d", "--remove-orphans"], cwd=root, check=True, timeout=180) + "up", "-d", "--no-build", "--remove-orphans"], cwd=root, check=True, timeout=180) def signed_agent_headers(route: str, payload: bytes, key: Path = PRIVATE_KEY_FILE) -> dict: From adf1e0fc773e96e754589f9a0542b5e4a59ac585 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:41:41 +0300 Subject: [PATCH 12/68] test(sub): verify signed Dockerfile build, patched-base digest and offline-runtime policy --- tests/test-install.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/test-install.sh b/tests/test-install.sh index 0263489..76bd4c6 100644 --- a/tests/test-install.sh +++ b/tests/test-install.sh @@ -18,7 +18,11 @@ grep -Fq 'header_up -Authorization' <<< "$out" grep -Fq 'header_up -Cookie' <<< "$out" grep -Fq 'xmesh-sub-limiter:' <<< "$out" grep -Fq 'image: caddy:2.11.9-alpine' <<< "$out" -grep -Fq 'image: python:3.12.16-alpine3.24' <<< "$out" +grep -Fq 'dockerfile: Dockerfile.limiter' <<< "$out" +grep -Fq 'pull_policy: never' <<< "$out" +grep -Fq 'FROM python:3.12.16-alpine3.24@sha256:c5ba3deef00c7758561a0f03c26f44f10589263d40e732b8748e0d1f38f6dd89' <<< "$out" +grep -Fq 'RUN apk --no-cache upgrade krb5-libs' <<< "$out" +grep -Fq 'image: xmesh-sub-limiter:3.12.16-krb5r1' <<< "$out" if grep -Eq '^ image: (caddy:2|python:3[.]12-alpine)$' <<< "$out"; then echo 'ERROR: floating legacy image in signed installer' >&2 exit 1 From c84c9c07a28d9b03cbf937192a84c1c901261182 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:42:21 +0300 Subject: [PATCH 13/68] ci(sub): build and scan patched signed-install limiter image instead of vulnerable Python base --- .github/workflows/image-security.yml | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index 6626873..d4c27ee 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -31,21 +31,30 @@ jobs: import os, pathlib, re compose=pathlib.Path(os.environ["RUNNER_TEMP"],"compose.yaml").read_text() refs=re.findall(r"^\s+image:\s+(\S+)\s*$",compose,re.M) - allowed=("python:3.12.16-alpine3.24","caddy:2.11.9-alpine") + allowed=("xmesh-sub-limiter:3.12.16-krb5r1","caddy:2.11.9-alpine") if len(refs)!=2 or set(refs)!=set(allowed): raise SystemExit(f"Unexpected installer runtime images: {refs}") pathlib.Path(os.environ["RUNNER_TEMP"],"image-refs.txt").write_text("\n".join(refs)+"\n") + dockerfile=pathlib.Path(os.environ["RUNNER_TEMP"],"sub-dry-run").read_text().split("# Dockerfile.limiter\n",1)[1].split("\n# Caddyfile\n",1)[0] + if "FROM python:3.12.16-alpine3.24@sha256:c5ba3deef00c7758561a0f03c26f44f10589263d40e732b8748e0d1f38f6dd89" not in dockerfile or "apk --no-cache upgrade krb5-libs" not in dockerfile: + raise SystemExit("Signed installer did not render the pinned patched limiter Dockerfile") + pathlib.Path(os.environ["RUNNER_TEMP"],"Dockerfile.limiter").write_text(dockerfile) print("Verified both signed-installer image references") PY - - name: Pull and record actual image content digests + - name: Build exact signed-install limiter and inspect both image identities shell: bash run: | set -Eeuo pipefail - : > "$RUNNER_TEMP/image-digests.txt" - while IFS= read -r ref; do - docker pull --platform linux/amd64 "$ref" - docker image inspect --format '{{index .RepoDigests 0}}' "$ref" | tee -a "$RUNNER_TEMP/image-digests.txt" - done < "$RUNNER_TEMP/image-refs.txt" + docker pull --platform linux/amd64 caddy:2.11.9-alpine + docker pull --platform linux/amd64 python:3.12.16-alpine3.24 + mkdir -p "$RUNNER_TEMP/limiter-build" + cp "$RUNNER_TEMP/Dockerfile.limiter" "$RUNNER_TEMP/limiter-build/Dockerfile" + docker build --pull --platform linux/amd64 --tag xmesh-sub-limiter:3.12.16-krb5r1 "$RUNNER_TEMP/limiter-build" + { + docker image inspect --format '{{index .RepoDigests 0}}' caddy:2.11.9-alpine + docker image inspect --format '{{index .RepoDigests 0}}' python:3.12.16-alpine3.24 + docker image inspect --format '{{.Id}}' xmesh-sub-limiter:3.12.16-krb5r1 + } | tee "$RUNNER_TEMP/image-digests.txt" - name: Install pinned and checksum-verified Trivy v0.76.2 shell: bash run: | @@ -79,7 +88,7 @@ jobs: "$RUNNER_TEMP/trivy" image --scanners vuln --format json \ --output "$RUNNER_TEMP/caddy-vulnerabilities.json" --no-progress caddy:2.11.9-alpine "$RUNNER_TEMP/trivy" image --scanners vuln --format json \ - --output "$RUNNER_TEMP/limiter-vulnerabilities.json" --no-progress python:3.12.16-alpine3.24 + --output "$RUNNER_TEMP/limiter-vulnerabilities.json" --no-progress xmesh-sub-limiter:3.12.16-krb5r1 - name: Preserve evidence including any unresolved advisories if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 @@ -90,6 +99,7 @@ jobs: ${{ runner.temp }}/limiter-vulnerabilities.json ${{ runner.temp }}/image-digests.txt ${{ runner.temp }}/image-refs.txt + ${{ runner.temp }}/Dockerfile.limiter if-no-files-found: warn retention-days: 14 - name: Fail closed on unresolved High and Critical vulnerabilities From 294ab4d0c71639f3753619cb58758eaa54f9b401 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:44:46 +0300 Subject: [PATCH 14/68] security(sub): build Caddy with patched x/net 0.62.0 before deploying signed gateway --- install.sh | 28 +++++++++++++++++++++++++--- 1 file changed, 25 insertions(+), 3 deletions(-) diff --git a/install.sh b/install.sh index 56d8168..672a23e 100644 --- a/install.sh +++ b/install.sh @@ -123,6 +123,17 @@ FROM python:3.12.16-alpine3.24@sha256:c5ba3deef00c7758561a0f03c26f44f10589263d40 RUN apk --no-cache upgrade krb5-libs DOCKER } +render_caddy_dockerfile() { + # Caddy's official binary retains x/net 0.60.0 in this exact image. + # Rebuild with the patched HTML parser while retaining the stock modules, + # native Caddyfile syntax, ACME support and persistent /data volume. + cat <<'DOCKER' +FROM caddy:2.11.9-builder-alpine AS builder +RUN xcaddy build v2.11.9 --replace golang.org/x/net=golang.org/x/net@v0.62.0 +FROM caddy:2.11.9-alpine@sha256:003a97808e781aa9f7e75cc2f43d34d461099031faf5e20faefb9f61126836f0 +COPY --from=builder /usr/bin/caddy /usr/bin/caddy +DOCKER +} render_compose() { cat <<'YAML' services: @@ -147,7 +158,11 @@ services: - /tmp # No published ports: Caddy is the only client, via a shared Unix socket. xmesh-sub: - image: caddy:2.11.9-alpine + image: xmesh-sub-caddy:2.11.9-xnet062r1 + build: + context: . + dockerfile: Dockerfile.caddy + pull_policy: never container_name: xmesh-sub restart: unless-stopped depends_on: @@ -374,6 +389,7 @@ if ((DRY_RUN)); then info "Validation successful, no host changes made." info "Panel: $PANEL | Subscription: https://$DOMAIN$SUB_PATH/{token}" printf '\n# Dockerfile.limiter\n'; render_limiter_dockerfile + printf '\n# Dockerfile.caddy\n'; render_caddy_dockerfile printf '\n# Caddyfile\n'; render_caddyfile printf '\n# compose.yaml\n'; render_compose printf '\n# limiter.py\n'; render_limiter @@ -431,7 +447,8 @@ render_caddyfile >"$temp/Caddyfile" render_compose >"$temp/compose.yaml" render_limiter >"$temp/limiter.py" render_limiter_dockerfile >"$temp/Dockerfile.limiter" -chmod 600 "$temp/Caddyfile" "$temp/compose.yaml" "$temp/limiter.py" "$temp/Dockerfile.limiter" + render_caddy_dockerfile >"$temp/Dockerfile.caddy" +chmod 600 "$temp/Caddyfile" "$temp/compose.yaml" "$temp/limiter.py" "$temp/Dockerfile.limiter" "$temp/Dockerfile.caddy" if command -v python3 >/dev/null; then python3 -m py_compile "$temp/limiter.py" || die "Invalid edge limiter" fi @@ -528,12 +545,17 @@ mkdir -p "$temp/image-build" cp "$temp/Dockerfile.limiter" "$temp/image-build/Dockerfile" docker build --pull -t xmesh-sub-limiter:3.12.16-krb5r1 "$temp/image-build" || die "Could not build patched limiter image; existing deployment unchanged" -docker run --rm -v "$temp/Caddyfile:/etc/caddy/Caddyfile:ro" caddy:2.11.9-alpine caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile || +mkdir -p "$temp/caddy-build" +cp "$temp/Dockerfile.caddy" "$temp/caddy-build/Dockerfile" +docker build --pull -t xmesh-sub-caddy:2.11.9-xnet062r1 "$temp/caddy-build" || + die "Could not build patched Caddy binary; existing deployment unchanged" +docker run --rm -v "$temp/Caddyfile:/etc/caddy/Caddyfile:ro" xmesh-sub-caddy:2.11.9-xnet062r1 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile || die "Gateway configuration invalid, existing deployment unchanged" [[ ! -f "$ROOT/Caddyfile" ]] || cp -p "$ROOT/Caddyfile" "$ROOT/Caddyfile.previous" install -m 600 "$temp/Caddyfile" "$ROOT/Caddyfile" install -m 600 "$temp/compose.yaml" "$ROOT/compose.yaml" install -m 644 "$temp/Dockerfile.limiter" "$ROOT/Dockerfile.limiter" +install -m 644 "$temp/Dockerfile.caddy" "$ROOT/Dockerfile.caddy" install -m 644 "$temp/limiter.py" "$ROOT/limiter.py" cd "$ROOT" docker compose pull --ignore-buildable From f56d1aa0ad8b1a07bc6909fdb14061c0e20dbbb4 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:44:57 +0300 Subject: [PATCH 15/68] security(sub): include patched Caddy build recipe in rollback backup --- manager.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/manager.py b/manager.py index 753f19c..2595a2d 100644 --- a/manager.py +++ b/manager.py @@ -85,7 +85,7 @@ def backup_installation(root: Path = ROOT) -> Path: backup = Path(tempfile.mkdtemp(prefix="pre-update-", dir=str(destination))) backup.chmod(0o700) files = ("Caddyfile", "compose.yaml", "manager.py", "manager.json", "agent-key.pem", "limiter.py", - "release_verify.py", "RELEASE_SHA", "VERSION", "Dockerfile.limiter") + "release_verify.py", "RELEASE_SHA", "VERSION", "Dockerfile.limiter", "Dockerfile.caddy") for name in files: old = root / name if old.is_file(): @@ -97,7 +97,7 @@ def backup_installation(root: Path = ROOT) -> Path: def restore_installation(backup: Path, root: Path = ROOT) -> None: for name in ("Caddyfile", "compose.yaml", "manager.py", "manager.json", "agent-key.pem", "limiter.py", - "release_verify.py", "RELEASE_SHA", "VERSION", "Dockerfile.limiter"): + "release_verify.py", "RELEASE_SHA", "VERSION", "Dockerfile.limiter", "Dockerfile.caddy"): saved = backup / name target = root / name if saved.is_file(): From 7311b6251233138e94fc9bbc0f7033a8f35fe2e2 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:45:21 +0300 Subject: [PATCH 16/68] test(sub): assert both signed patched gateway build recipes and disabled runtime pulling --- tests/test-install.sh | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/tests/test-install.sh b/tests/test-install.sh index 76bd4c6..4957112 100644 --- a/tests/test-install.sh +++ b/tests/test-install.sh @@ -17,11 +17,15 @@ grep -Fq 'header_up -X-Forwarded-Uri' <<< "$out" grep -Fq 'header_up -Authorization' <<< "$out" grep -Fq 'header_up -Cookie' <<< "$out" grep -Fq 'xmesh-sub-limiter:' <<< "$out" -grep -Fq 'image: caddy:2.11.9-alpine' <<< "$out" +grep -Fq 'image: xmesh-sub-caddy:2.11.9-xnet062r1' <<< "$out" grep -Fq 'dockerfile: Dockerfile.limiter' <<< "$out" grep -Fq 'pull_policy: never' <<< "$out" grep -Fq 'FROM python:3.12.16-alpine3.24@sha256:c5ba3deef00c7758561a0f03c26f44f10589263d40e732b8748e0d1f38f6dd89' <<< "$out" grep -Fq 'RUN apk --no-cache upgrade krb5-libs' <<< "$out" +grep -Fq 'dockerfile: Dockerfile.caddy' <<< "$out" +grep -Fq 'FROM caddy:2.11.9-builder-alpine AS builder' <<< "$out" +grep -Fq 'RUN xcaddy build v2.11.9 --replace golang.org/x/net=golang.org/x/net@v0.62.0' <<< "$out" +grep -Fq 'FROM caddy:2.11.9-alpine@sha256:003a97808e781aa9f7e75cc2f43d34d461099031faf5e20faefb9f61126836f0' <<< "$out" grep -Fq 'image: xmesh-sub-limiter:3.12.16-krb5r1' <<< "$out" if grep -Eq '^ image: (caddy:2|python:3[.]12-alpine)$' <<< "$out"; then echo 'ERROR: floating legacy image in signed installer' >&2 From c917d07eaed22e63899317b9d93f8f90b9049368 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 15:45:58 +0300 Subject: [PATCH 17/68] ci(sub): build signed patched Caddy and limiter images before scanning actual deployables --- .github/workflows/image-security.yml | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index d4c27ee..b5ad2e1 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -31,30 +31,38 @@ jobs: import os, pathlib, re compose=pathlib.Path(os.environ["RUNNER_TEMP"],"compose.yaml").read_text() refs=re.findall(r"^\s+image:\s+(\S+)\s*$",compose,re.M) - allowed=("xmesh-sub-limiter:3.12.16-krb5r1","caddy:2.11.9-alpine") + allowed=("xmesh-sub-limiter:3.12.16-krb5r1","xmesh-sub-caddy:2.11.9-xnet062r1") if len(refs)!=2 or set(refs)!=set(allowed): raise SystemExit(f"Unexpected installer runtime images: {refs}") pathlib.Path(os.environ["RUNNER_TEMP"],"image-refs.txt").write_text("\n".join(refs)+"\n") - dockerfile=pathlib.Path(os.environ["RUNNER_TEMP"],"sub-dry-run").read_text().split("# Dockerfile.limiter\n",1)[1].split("\n# Caddyfile\n",1)[0] + dockerfile=pathlib.Path(os.environ["RUNNER_TEMP"],"sub-dry-run").read_text().split("# Dockerfile.limiter\n",1)[1].split("\n# Dockerfile.caddy\n",1)[0] if "FROM python:3.12.16-alpine3.24@sha256:c5ba3deef00c7758561a0f03c26f44f10589263d40e732b8748e0d1f38f6dd89" not in dockerfile or "apk --no-cache upgrade krb5-libs" not in dockerfile: raise SystemExit("Signed installer did not render the pinned patched limiter Dockerfile") pathlib.Path(os.environ["RUNNER_TEMP"],"Dockerfile.limiter").write_text(dockerfile) + caddyfile=pathlib.Path(os.environ["RUNNER_TEMP"],"sub-dry-run").read_text().split("# Dockerfile.caddy\n",1)[1].split("\n# Caddyfile\n",1)[0] + if "FROM caddy:2.11.9-builder-alpine" not in caddyfile or "xcaddy build v2.11.9 --replace golang.org/x/net=golang.org/x/net@v0.62.0" not in caddyfile: + raise SystemExit("Signed installer did not render patched Caddy builder") + pathlib.Path(os.environ["RUNNER_TEMP"],"Dockerfile.caddy").write_text(caddyfile) print("Verified both signed-installer image references") PY - - name: Build exact signed-install limiter and inspect both image identities + - name: Build both signed-installer runtime containers shell: bash run: | set -Eeuo pipefail docker pull --platform linux/amd64 caddy:2.11.9-alpine docker pull --platform linux/amd64 python:3.12.16-alpine3.24 - mkdir -p "$RUNNER_TEMP/limiter-build" + mkdir -p "$RUNNER_TEMP/limiter-build" "$RUNNER_TEMP/caddy-build" cp "$RUNNER_TEMP/Dockerfile.limiter" "$RUNNER_TEMP/limiter-build/Dockerfile" + cp "$RUNNER_TEMP/Dockerfile.caddy" "$RUNNER_TEMP/caddy-build/Dockerfile" docker build --pull --platform linux/amd64 --tag xmesh-sub-limiter:3.12.16-krb5r1 "$RUNNER_TEMP/limiter-build" + docker build --pull --platform linux/amd64 --tag xmesh-sub-caddy:2.11.9-xnet062r1 "$RUNNER_TEMP/caddy-build" { docker image inspect --format '{{index .RepoDigests 0}}' caddy:2.11.9-alpine docker image inspect --format '{{index .RepoDigests 0}}' python:3.12.16-alpine3.24 docker image inspect --format '{{.Id}}' xmesh-sub-limiter:3.12.16-krb5r1 + docker image inspect --format '{{.Id}}' xmesh-sub-caddy:2.11.9-xnet062r1 } | tee "$RUNNER_TEMP/image-digests.txt" + docker run --rm -v "$RUNNER_TEMP/sub-dry-run:/tmp/ignore:ro" xmesh-sub-caddy:2.11.9-xnet062r1 caddy version - name: Install pinned and checksum-verified Trivy v0.76.2 shell: bash run: | @@ -86,7 +94,7 @@ jobs: run: | set -Eeuo pipefail "$RUNNER_TEMP/trivy" image --scanners vuln --format json \ - --output "$RUNNER_TEMP/caddy-vulnerabilities.json" --no-progress caddy:2.11.9-alpine + --output "$RUNNER_TEMP/caddy-vulnerabilities.json" --no-progress xmesh-sub-caddy:2.11.9-xnet062r1 "$RUNNER_TEMP/trivy" image --scanners vuln --format json \ --output "$RUNNER_TEMP/limiter-vulnerabilities.json" --no-progress xmesh-sub-limiter:3.12.16-krb5r1 - name: Preserve evidence including any unresolved advisories @@ -100,6 +108,7 @@ jobs: ${{ runner.temp }}/image-digests.txt ${{ runner.temp }}/image-refs.txt ${{ runner.temp }}/Dockerfile.limiter + ${{ runner.temp }}/Dockerfile.caddy if-no-files-found: warn retention-days: 14 - name: Fail closed on unresolved High and Critical vulnerabilities From 43c4da0ab048f90f9f59dc494c12db5ba2caa688 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 16:33:40 +0300 Subject: [PATCH 18/68] security(sub): test patched JOSE v4 Smallstep graph in Caddy build --- tests/test-install.sh | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/tests/test-install.sh b/tests/test-install.sh index 4957112..fa4ea2a 100644 --- a/tests/test-install.sh +++ b/tests/test-install.sh @@ -17,14 +17,17 @@ grep -Fq 'header_up -X-Forwarded-Uri' <<< "$out" grep -Fq 'header_up -Authorization' <<< "$out" grep -Fq 'header_up -Cookie' <<< "$out" grep -Fq 'xmesh-sub-limiter:' <<< "$out" -grep -Fq 'image: xmesh-sub-caddy:2.11.9-xnet062r1' <<< "$out" +grep -Fq 'image: xmesh-sub-caddy:2.11.9-josev4r1' <<< "$out" grep -Fq 'dockerfile: Dockerfile.limiter' <<< "$out" grep -Fq 'pull_policy: never' <<< "$out" grep -Fq 'FROM python:3.12.16-alpine3.24@sha256:c5ba3deef00c7758561a0f03c26f44f10589263d40e732b8748e0d1f38f6dd89' <<< "$out" grep -Fq 'RUN apk --no-cache upgrade krb5-libs' <<< "$out" grep -Fq 'dockerfile: Dockerfile.caddy' <<< "$out" grep -Fq 'FROM caddy:2.11.9-builder-alpine AS builder' <<< "$out" -grep -Fq 'RUN xcaddy build v2.11.9 --replace golang.org/x/net=golang.org/x/net@v0.62.0' <<< "$out" +grep -Fq 'RUN xcaddy build v2.11.9' <<< "$out" +grep -Fq 'github.com/smallstep/certificates@v0.30.3-0.20261105213751-6d5a251fbe01' <<< "$out" +grep -Fq 'go.step.sm/crypto@v0.92.0' <<< "$out" +grep -Fq 'golang.org/x/net@v0.62.0' <<< "$out" grep -Fq 'FROM caddy:2.11.9-alpine@sha256:003a97808e781aa9f7e75cc2f43d34d461099031faf5e20faefb9f61126836f0' <<< "$out" grep -Fq 'image: xmesh-sub-limiter:3.12.16-krb5r1' <<< "$out" if grep -Eq '^ image: (caddy:2|python:3[.]12-alpine)$' <<< "$out"; then From 8ee67b973e1eb3ce1b0b87462e2126569535fdb4 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 16:33:43 +0300 Subject: [PATCH 19/68] security(sub): test patched JOSE v4 Smallstep graph in Caddy build --- .github/workflows/image-security.yml | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index b5ad2e1..b23b448 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -31,7 +31,7 @@ jobs: import os, pathlib, re compose=pathlib.Path(os.environ["RUNNER_TEMP"],"compose.yaml").read_text() refs=re.findall(r"^\s+image:\s+(\S+)\s*$",compose,re.M) - allowed=("xmesh-sub-limiter:3.12.16-krb5r1","xmesh-sub-caddy:2.11.9-xnet062r1") + allowed=("xmesh-sub-limiter:3.12.16-krb5r1","xmesh-sub-caddy:2.11.9-josev4r1") if len(refs)!=2 or set(refs)!=set(allowed): raise SystemExit(f"Unexpected installer runtime images: {refs}") pathlib.Path(os.environ["RUNNER_TEMP"],"image-refs.txt").write_text("\n".join(refs)+"\n") @@ -40,7 +40,7 @@ jobs: raise SystemExit("Signed installer did not render the pinned patched limiter Dockerfile") pathlib.Path(os.environ["RUNNER_TEMP"],"Dockerfile.limiter").write_text(dockerfile) caddyfile=pathlib.Path(os.environ["RUNNER_TEMP"],"sub-dry-run").read_text().split("# Dockerfile.caddy\n",1)[1].split("\n# Caddyfile\n",1)[0] - if "FROM caddy:2.11.9-builder-alpine" not in caddyfile or "xcaddy build v2.11.9 --replace golang.org/x/net=golang.org/x/net@v0.62.0" not in caddyfile: + if not all(item in caddyfile for item in ("FROM caddy:2.11.9-builder-alpine", "xcaddy build v2.11.9", "github.com/smallstep/certificates@v0.30.3-0.20261105213751-6d5a251fbe01", "go.step.sm/crypto@v0.92.0", "golang.org/x/net@v0.62.0")): raise SystemExit("Signed installer did not render patched Caddy builder") pathlib.Path(os.environ["RUNNER_TEMP"],"Dockerfile.caddy").write_text(caddyfile) print("Verified both signed-installer image references") @@ -55,14 +55,20 @@ jobs: cp "$RUNNER_TEMP/Dockerfile.limiter" "$RUNNER_TEMP/limiter-build/Dockerfile" cp "$RUNNER_TEMP/Dockerfile.caddy" "$RUNNER_TEMP/caddy-build/Dockerfile" docker build --pull --platform linux/amd64 --tag xmesh-sub-limiter:3.12.16-krb5r1 "$RUNNER_TEMP/limiter-build" - docker build --pull --platform linux/amd64 --tag xmesh-sub-caddy:2.11.9-xnet062r1 "$RUNNER_TEMP/caddy-build" + docker build --pull --platform linux/amd64 --tag xmesh-sub-caddy:2.11.9-josev4r1 "$RUNNER_TEMP/caddy-build" { docker image inspect --format '{{index .RepoDigests 0}}' caddy:2.11.9-alpine docker image inspect --format '{{index .RepoDigests 0}}' python:3.12.16-alpine3.24 docker image inspect --format '{{.Id}}' xmesh-sub-limiter:3.12.16-krb5r1 - docker image inspect --format '{{.Id}}' xmesh-sub-caddy:2.11.9-xnet062r1 + docker image inspect --format '{{.Id}}' xmesh-sub-caddy:2.11.9-josev4r1 } | tee "$RUNNER_TEMP/image-digests.txt" - docker run --rm -v "$RUNNER_TEMP/sub-dry-run:/tmp/ignore:ro" xmesh-sub-caddy:2.11.9-xnet062r1 caddy version + docker run --rm -v "$RUNNER_TEMP/sub-dry-run:/tmp/ignore:ro" xmesh-sub-caddy:2.11.9-josev4r1 caddy version + docker run --rm xmesh-sub-caddy:2.11.9-josev4r1 caddy build-info > "$RUNNER_TEMP/caddy-build-info.txt" + if grep -Fq 'github.com/go-jose/go-jose/v3' "$RUNNER_TEMP/caddy-build-info.txt"; then + echo 'Unexpected vulnerable JOSE-v3 dependency in final Caddy build' >&2 + exit 1 + fi + grep -Fq 'github.com/go-jose/go-jose/v4' "$RUNNER_TEMP/caddy-build-info.txt" || { echo 'Expected patched JOSE-v4 missing' >&2; exit 1; } - name: Install pinned and checksum-verified Trivy v0.76.2 shell: bash run: | @@ -94,7 +100,7 @@ jobs: run: | set -Eeuo pipefail "$RUNNER_TEMP/trivy" image --scanners vuln --format json \ - --output "$RUNNER_TEMP/caddy-vulnerabilities.json" --no-progress xmesh-sub-caddy:2.11.9-xnet062r1 + --output "$RUNNER_TEMP/caddy-vulnerabilities.json" --no-progress xmesh-sub-caddy:2.11.9-josev4r1 "$RUNNER_TEMP/trivy" image --scanners vuln --format json \ --output "$RUNNER_TEMP/limiter-vulnerabilities.json" --no-progress xmesh-sub-limiter:3.12.16-krb5r1 - name: Preserve evidence including any unresolved advisories From fce38ad1e027d011e8467ff4ef47c5a75a3ae467 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 16:33:46 +0300 Subject: [PATCH 20/68] security(sub): test patched JOSE v4 Smallstep graph in Caddy build --- install.sh | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/install.sh b/install.sh index 672a23e..ef880e9 100644 --- a/install.sh +++ b/install.sh @@ -125,11 +125,14 @@ DOCKER } render_caddy_dockerfile() { # Caddy's official binary retains x/net 0.60.0 in this exact image. - # Rebuild with the patched HTML parser while retaining the stock modules, - # native Caddyfile syntax, ACME support and persistent /data volume. + # Rebuild Caddy using the upstream Smallstep JOSE-v4 migration and patched + # x/net; retain stock Caddy modules, native Caddyfile syntax and ACME. cat <<'DOCKER' FROM caddy:2.11.9-builder-alpine AS builder -RUN xcaddy build v2.11.9 --replace golang.org/x/net=golang.org/x/net@v0.62.0 +RUN xcaddy build v2.11.9 \ + --replace github.com/smallstep/certificates=github.com/smallstep/certificates@v0.30.3-0.20261105213751-6d5a251fbe01 \ + --replace go.step.sm/crypto=go.step.sm/crypto@v0.92.0 \ + --replace golang.org/x/net=golang.org/x/net@v0.62.0 FROM caddy:2.11.9-alpine@sha256:003a97808e781aa9f7e75cc2f43d34d461099031faf5e20faefb9f61126836f0 COPY --from=builder /usr/bin/caddy /usr/bin/caddy DOCKER @@ -158,7 +161,7 @@ services: - /tmp # No published ports: Caddy is the only client, via a shared Unix socket. xmesh-sub: - image: xmesh-sub-caddy:2.11.9-xnet062r1 + image: xmesh-sub-caddy:2.11.9-josev4r1 build: context: . dockerfile: Dockerfile.caddy @@ -547,9 +550,9 @@ docker build --pull -t xmesh-sub-limiter:3.12.16-krb5r1 "$temp/image-build" || die "Could not build patched limiter image; existing deployment unchanged" mkdir -p "$temp/caddy-build" cp "$temp/Dockerfile.caddy" "$temp/caddy-build/Dockerfile" -docker build --pull -t xmesh-sub-caddy:2.11.9-xnet062r1 "$temp/caddy-build" || +docker build --pull -t xmesh-sub-caddy:2.11.9-josev4r1 "$temp/caddy-build" || die "Could not build patched Caddy binary; existing deployment unchanged" -docker run --rm -v "$temp/Caddyfile:/etc/caddy/Caddyfile:ro" xmesh-sub-caddy:2.11.9-xnet062r1 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile || +docker run --rm -v "$temp/Caddyfile:/etc/caddy/Caddyfile:ro" xmesh-sub-caddy:2.11.9-josev4r1 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile || die "Gateway configuration invalid, existing deployment unchanged" [[ ! -f "$ROOT/Caddyfile" ]] || cp -p "$ROOT/Caddyfile" "$ROOT/Caddyfile.previous" install -m 600 "$temp/Caddyfile" "$ROOT/Caddyfile" From 6f5822739c07bc10acede7ff1f1aa4769e507d68 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 16:37:29 +0300 Subject: [PATCH 21/68] security(sub): verify exact patched runtime images on amd64 and arm64 --- .github/workflows/image-security.yml | 23 ++++++++++++++++------- 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index b23b448..2fe195f 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -14,8 +14,17 @@ permissions: contents: read jobs: image-cve-gate: - runs-on: ubuntu-24.04 - timeout-minutes: 40 + name: image-cve-gate (${{ matrix.arch }}) + strategy: + fail-fast: false + matrix: + include: + - arch: amd64 + runner: ubuntu-24.04 + - arch: arm64 + runner: ubuntu-24.04-arm + runs-on: ${{ matrix.runner }} + timeout-minutes: 45 steps: - name: Fetch exact source without persistent credentials uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 @@ -49,13 +58,13 @@ jobs: shell: bash run: | set -Eeuo pipefail - docker pull --platform linux/amd64 caddy:2.11.9-alpine - docker pull --platform linux/amd64 python:3.12.16-alpine3.24 + docker pull --platform linux/${{ matrix.arch }} caddy:2.11.9-alpine + docker pull --platform linux/${{ matrix.arch }} python:3.12.16-alpine3.24 mkdir -p "$RUNNER_TEMP/limiter-build" "$RUNNER_TEMP/caddy-build" cp "$RUNNER_TEMP/Dockerfile.limiter" "$RUNNER_TEMP/limiter-build/Dockerfile" cp "$RUNNER_TEMP/Dockerfile.caddy" "$RUNNER_TEMP/caddy-build/Dockerfile" - docker build --pull --platform linux/amd64 --tag xmesh-sub-limiter:3.12.16-krb5r1 "$RUNNER_TEMP/limiter-build" - docker build --pull --platform linux/amd64 --tag xmesh-sub-caddy:2.11.9-josev4r1 "$RUNNER_TEMP/caddy-build" + docker build --pull --platform linux/${{ matrix.arch }} --tag xmesh-sub-limiter:3.12.16-krb5r1 "$RUNNER_TEMP/limiter-build" + docker build --pull --platform linux/${{ matrix.arch }} --tag xmesh-sub-caddy:2.11.9-josev4r1 "$RUNNER_TEMP/caddy-build" { docker image inspect --format '{{index .RepoDigests 0}}' caddy:2.11.9-alpine docker image inspect --format '{{index .RepoDigests 0}}' python:3.12.16-alpine3.24 @@ -107,7 +116,7 @@ jobs: if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: - name: sub-runtime-image-security + name: sub-runtime-image-security-${{ matrix.arch }} path: | ${{ runner.temp }}/caddy-vulnerabilities.json ${{ runner.temp }}/limiter-vulnerabilities.json From 2720f8d83355ee547e03071bd4751aa0fd815118 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 16:40:45 +0300 Subject: [PATCH 22/68] ci(sub): checksum-pin architecture-correct Trivy binaries for ARM64 and AMD64 --- .github/workflows/image-security.yml | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index 2fe195f..e91ed0f 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -79,13 +79,22 @@ jobs: fi grep -Fq 'github.com/go-jose/go-jose/v4' "$RUNNER_TEMP/caddy-build-info.txt" || { echo 'Expected patched JOSE-v4 missing' >&2; exit 1; } - name: Install pinned and checksum-verified Trivy v0.76.2 + env: + TRIVY_ARCH: ${{ matrix.arch }} shell: bash run: | set -Eeuo pipefail python3 - <<'PY' import hashlib,io,os,pathlib,tarfile,urllib.request - url="https://github.com/aquasecurity/trivy/releases/download/v0.76.2/trivy_0.76.2_Linux-64bit.tar.gz" - wanted="bc0fc726e017b8927a62b2d3531d7a84ee01769daf5c99ed866dced54089fdbf" + arch=os.environ.get("TRIVY_ARCH") + signed_release_assets={ + "amd64":("Linux-64bit","bc0fc726e017b8927a62b2d3531d7a84ee01769daf5c99ed866dced54089fdbf"), + "arm64":("Linux-ARM64","ab9d51f86e6a5fb936f605faff6b593ac51bc378fff4d3e8b9d58358b9c367c3"), + } + if arch not in signed_release_assets: + raise SystemExit("Unsupported Trivy architecture") + suffix,wanted=signed_release_assets[arch] + url=f"https://github.com/aquasecurity/trivy/releases/download/v0.76.2/trivy_0.76.2_{suffix}.tar.gz" with urllib.request.urlopen(url,timeout=75) as request: data=request.read(100*1024*1024+1) actual=hashlib.sha256(data).hexdigest() From 2f33ac49e5ed2784f5762ee84fd896f077d4299e Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 16:42:46 +0300 Subject: [PATCH 23/68] ci(sub): validate signed Caddy routing config on both architectures before scan --- .github/workflows/image-security.yml | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index e91ed0f..4e9c3c4 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -72,6 +72,9 @@ jobs: docker image inspect --format '{{.Id}}' xmesh-sub-caddy:2.11.9-josev4r1 } | tee "$RUNNER_TEMP/image-digests.txt" docker run --rm -v "$RUNNER_TEMP/sub-dry-run:/tmp/ignore:ro" xmesh-sub-caddy:2.11.9-josev4r1 caddy version + sed -n '/^# Caddyfile$/,/^# compose.yaml$/p' "$RUNNER_TEMP/sub-dry-run" | sed '1d;$d' > "$RUNNER_TEMP/Caddyfile" + test -s "$RUNNER_TEMP/Caddyfile" + docker run --rm -v "$RUNNER_TEMP/Caddyfile:/etc/caddy/Caddyfile:ro" xmesh-sub-caddy:2.11.9-josev4r1 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile docker run --rm xmesh-sub-caddy:2.11.9-josev4r1 caddy build-info > "$RUNNER_TEMP/caddy-build-info.txt" if grep -Fq 'github.com/go-jose/go-jose/v3' "$RUNNER_TEMP/caddy-build-info.txt"; then echo 'Unexpected vulnerable JOSE-v3 dependency in final Caddy build' >&2 From 7a2ed45b169f2d4ea952452d28d664c284874565 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 16:43:58 +0300 Subject: [PATCH 24/68] security(sub): pin proven multi-arch Caddy builder manifest digest --- install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/install.sh b/install.sh index ef880e9..29871b4 100644 --- a/install.sh +++ b/install.sh @@ -128,7 +128,7 @@ render_caddy_dockerfile() { # Rebuild Caddy using the upstream Smallstep JOSE-v4 migration and patched # x/net; retain stock Caddy modules, native Caddyfile syntax and ACME. cat <<'DOCKER' -FROM caddy:2.11.9-builder-alpine AS builder +FROM caddy:2.11.9-builder-alpine@sha256:646fee578e680989ca5c7fd1ce6f1de574d19fd71ef2221810cc0510a9f40c86 AS builder RUN xcaddy build v2.11.9 \ --replace github.com/smallstep/certificates=github.com/smallstep/certificates@v0.30.3-0.20261105213751-6d5a251fbe01 \ --replace go.step.sm/crypto=go.step.sm/crypto@v0.92.0 \ From 546c512007cd1aab8cf93c86648da8b701979e30 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 16:44:00 +0300 Subject: [PATCH 25/68] security(sub): pin proven multi-arch Caddy builder manifest digest --- tests/test-install.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test-install.sh b/tests/test-install.sh index fa4ea2a..d3eb100 100644 --- a/tests/test-install.sh +++ b/tests/test-install.sh @@ -23,7 +23,7 @@ grep -Fq 'pull_policy: never' <<< "$out" grep -Fq 'FROM python:3.12.16-alpine3.24@sha256:c5ba3deef00c7758561a0f03c26f44f10589263d40e732b8748e0d1f38f6dd89' <<< "$out" grep -Fq 'RUN apk --no-cache upgrade krb5-libs' <<< "$out" grep -Fq 'dockerfile: Dockerfile.caddy' <<< "$out" -grep -Fq 'FROM caddy:2.11.9-builder-alpine AS builder' <<< "$out" +grep -Fq 'FROM caddy:2.11.9-builder-alpine@sha256:646fee578e680989ca5c7fd1ce6f1de574d19fd71ef2221810cc0510a9f40c86 AS builder' <<< "$out" grep -Fq 'RUN xcaddy build v2.11.9' <<< "$out" grep -Fq 'github.com/smallstep/certificates@v0.30.3-0.20261105213751-6d5a251fbe01' <<< "$out" grep -Fq 'go.step.sm/crypto@v0.92.0' <<< "$out" From 323935c6c28d527c93cc76364083fa6f1b2edf2b Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 16:44:04 +0300 Subject: [PATCH 26/68] security(sub): pin proven multi-arch Caddy builder manifest digest --- .github/workflows/image-security.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index 4e9c3c4..18e78f8 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -49,7 +49,7 @@ jobs: raise SystemExit("Signed installer did not render the pinned patched limiter Dockerfile") pathlib.Path(os.environ["RUNNER_TEMP"],"Dockerfile.limiter").write_text(dockerfile) caddyfile=pathlib.Path(os.environ["RUNNER_TEMP"],"sub-dry-run").read_text().split("# Dockerfile.caddy\n",1)[1].split("\n# Caddyfile\n",1)[0] - if not all(item in caddyfile for item in ("FROM caddy:2.11.9-builder-alpine", "xcaddy build v2.11.9", "github.com/smallstep/certificates@v0.30.3-0.20261105213751-6d5a251fbe01", "go.step.sm/crypto@v0.92.0", "golang.org/x/net@v0.62.0")): + if not all(item in caddyfile for item in ("FROM caddy:2.11.9-builder-alpine@sha256:646fee578e680989ca5c7fd1ce6f1de574d19fd71ef2221810cc0510a9f40c86", "xcaddy build v2.11.9", "github.com/smallstep/certificates@v0.30.3-0.20261105213751-6d5a251fbe01", "go.step.sm/crypto@v0.92.0", "golang.org/x/net@v0.62.0")): raise SystemExit("Signed installer did not render patched Caddy builder") pathlib.Path(os.environ["RUNNER_TEMP"],"Dockerfile.caddy").write_text(caddyfile) print("Verified both signed-installer image references") From 4f06d185a2c1d2ae9394b4a57f27712f5c001480 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:13:54 +0300 Subject: [PATCH 27/68] security(release): make architecture image CVE gate reusable by trusted attester --- .github/workflows/image-security.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index 18e78f8..7e1cecf 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -10,6 +10,7 @@ on: push: branches: [main] workflow_dispatch: + workflow_call: permissions: contents: read jobs: From 3091f31b13e1ba16db5aabe95f0d4720bef772c0 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:14:05 +0300 Subject: [PATCH 28/68] security(release): block provenance publication until both architecture CVE gates pass --- .github/workflows/attested-release.yml | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/.github/workflows/attested-release.yml b/.github/workflows/attested-release.yml index 70474d6..deab08e 100644 --- a/.github/workflows/attested-release.yml +++ b/.github/workflows/attested-release.yml @@ -14,7 +14,15 @@ concurrency: cancel-in-progress: false jobs: + runtime-image-security: + # Reuse the exact two-architecture CVE gate on the trusted main revision. + # No signing or OIDC token is available to this job. + permissions: + contents: read + uses: ./.github/workflows/image-security.yml + publish: + needs: runtime-image-security if: github.repository == 'TriplexCorp/XMesh-Sub' && github.ref == 'refs/heads/main' runs-on: ubuntu-24.04 permissions: From d5f4d7b423b5bd5924a0f797dec1f50937f75942 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:14:28 +0300 Subject: [PATCH 29/68] test(sub): guard signer dependency on strict multiarch image CVE gate --- tests/test-workflow-security.py | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/tests/test-workflow-security.py b/tests/test-workflow-security.py index 91e90b7..a4582c1 100644 --- a/tests/test-workflow-security.py +++ b/tests/test-workflow-security.py @@ -9,7 +9,10 @@ def unpinned_actions(text): uses = re.findall(r"^\s*(?:-\s*)?uses:\s*([^\s#]+)", text, re.MULTILINE) - return [value for value in uses if not re.fullmatch( + # This one local reusable workflow is protected by the same reviewed + # commit as the publisher; arbitrary local includes are not allowed. + reviewed_local = {"./.github/workflows/image-security.yml"} + return [value for value in uses if value not in reviewed_local and not re.fullmatch( r"[A-Za-z0-9_.-]+/[A-Za-z0-9_./-]+@[0-9a-f]{40}", value )] @@ -24,6 +27,27 @@ def test_full_commit_with_comment_is_accepted(self): "- uses: actions/attest@" + "a" * 40 + " # reviewed v4\n" ), []) + def test_only_reviewed_local_reusable_gate_is_allowed(self): + self.assertEqual(unpinned_actions( + " uses: ./.github/workflows/image-security.yml\\n" + ), []) + self.assertTrue(unpinned_actions(" uses: ./.github/workflows/unsafe.yml\\n")) + + def test_attester_cannot_publish_before_two_architecture_security_gates(self): + publisher = (ROOT / ".github/workflows/attested-release.yml").read_text() + gate = (ROOT / ".github/workflows/image-security.yml").read_text() + self.assertIn("uses: ./.github/workflows/image-security.yml", publisher) + self.assertRegex(publisher, r"(?m)^ publish:\\n needs: runtime-image-security\\n") + self.assertRegex(gate, r"(?m)^ workflow_call:$") + self.assertIn("arch: amd64", gate) + self.assertIn("arch: arm64", gate) + self.assertIn("fail-fast: false", gate) + self.assertIn("Fail closed on unresolved High and Critical vulnerabilities", gate) + self.assertIn('raise SystemExit(f"{count} High/Critical issues remain in Sub runtime images")', gate) + self.assertNotIn("continue-on-error: true", gate) + self.assertNotIn("|| true", gate) + self.assertNotIn("secrets: inherit", publisher) + def test_all_checked_in_actions_are_pinned(self): workflows = list((ROOT / ".github/workflows").glob("*.yml")) self.assertTrue(workflows) From 2f768b056e3d7fb2d1435a742c2cfddfff1e19f1 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:14:52 +0300 Subject: [PATCH 30/68] test(sub): correct literal newline matching in release dependency regression tests --- tests/test-workflow-security.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test-workflow-security.py b/tests/test-workflow-security.py index a4582c1..06811ff 100644 --- a/tests/test-workflow-security.py +++ b/tests/test-workflow-security.py @@ -29,15 +29,15 @@ def test_full_commit_with_comment_is_accepted(self): def test_only_reviewed_local_reusable_gate_is_allowed(self): self.assertEqual(unpinned_actions( - " uses: ./.github/workflows/image-security.yml\\n" + " uses: ./.github/workflows/image-security.yml\n" ), []) - self.assertTrue(unpinned_actions(" uses: ./.github/workflows/unsafe.yml\\n")) + self.assertTrue(unpinned_actions(" uses: ./.github/workflows/unsafe.yml\n")) def test_attester_cannot_publish_before_two_architecture_security_gates(self): publisher = (ROOT / ".github/workflows/attested-release.yml").read_text() gate = (ROOT / ".github/workflows/image-security.yml").read_text() self.assertIn("uses: ./.github/workflows/image-security.yml", publisher) - self.assertRegex(publisher, r"(?m)^ publish:\\n needs: runtime-image-security\\n") + self.assertRegex(publisher, r"(?m)^ publish:\n needs: runtime-image-security\n") self.assertRegex(gate, r"(?m)^ workflow_call:$") self.assertIn("arch: amd64", gate) self.assertIn("arch: arm64", gate) From 52042adf0166c10a7bd06bb2fc9e2fe50cb618ab Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:18:44 +0300 Subject: [PATCH 31/68] test(sub): exercise real Caddy-to-Unix-limiter routing and spoofed-header denial in containers --- tests/test-runtime-edge.sh | 85 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 85 insertions(+) create mode 100644 tests/test-runtime-edge.sh diff --git a/tests/test-runtime-edge.sh b/tests/test-runtime-edge.sh new file mode 100644 index 0000000..62da09b --- /dev/null +++ b/tests/test-runtime-edge.sh @@ -0,0 +1,85 @@ +#!/usr/bin/env bash +# Disposable container integration test: generated Caddy routes + real Unix limiter. +# Runs only in CI, never on a production VPS. +set -Eeuo pipefail +cd "$(dirname "$0")/.." +[[ $# == 1 && -s "$1/Caddyfile" ]] || { echo 'Missing generated Caddyfile' >&2; exit 1; } +source_caddyfile=$1/Caddyfile +temp=$(mktemp -d) +limiter_name="xmesh-edge-limiter-$$" +caddy_name="xmesh-edge-caddy-$$" +cleanup() { + docker rm -f "$caddy_name" "$limiter_name" >/dev/null 2>&1 || true + rm -rf "$temp" +} +trap cleanup EXIT + +mkdir -p "$temp/run" "$temp/policy" +sudo chown 65534:65534 "$temp/run" +chmod 0770 "$temp/run" +printf '%s\n' '{"enabled":true,"mode":"protect","ipPerMinute":1}' > "$temp/policy/config.json" +chmod 0644 "$temp/policy/config.json" + +# Keep exact generated subscriber matcher, forward_auth and sanitization, +# replacing ONLY the TLS site address and first panel upstream for local CI. +python3 - "$source_caddyfile" "$temp/Caddyfile" <<'PY' +from pathlib import Path +import sys +raw=Path(sys.argv[1]).read_text() +upstream=''' reverse_proxy https://panel.example.org { + header_up Host panel.example.org + header_up -Authorization + header_up -Cookie + }''' +if raw.count(upstream)!=2 or raw.count('sub.example.org {')!=1: + raise SystemExit('Unexpected production Caddy routing; cannot safely stub upstream') +if 'forward_auth unix//run/xmesh-sub/rate.sock {' not in raw: + raise SystemExit('Production Caddyfile has lost the Unix-socket enforcement') +patched=raw.replace('sub.example.org {','http://:8080 {',1).replace( + upstream,' respond "allowed" 200',1) +if patched.count('forward_auth unix//run/xmesh-sub/rate.sock {')!=1: + raise SystemExit('CI must preserve exact forward_auth rule') +Path(sys.argv[2]).write_text(patched) +PY + +docker run -d --name "$limiter_name" --network none \ + --user 65534:65534 --read-only --tmpfs /tmp \ + --security-opt no-new-privileges --cap-drop ALL \ + -v "$temp/run:/run/xmesh-sub" \ + -v "$temp/policy:/etc/xmesh-sub/policy:ro" \ + -v "$PWD/limiter.py:/opt/limiter.py:ro" \ + xmesh-sub-limiter:3.12.16-krb5r1 python3 -I /opt/limiter.py >/dev/null +for i in $(seq 1 60); do + [[ -S "$temp/run/rate.sock" ]] && break + sleep 0.2 +done +[[ -S "$temp/run/rate.sock" ]] || { echo 'Limiter socket failed to appear' >&2; exit 1; } + +docker run -d --name "$caddy_name" --network bridge \ + --security-opt no-new-privileges \ + -p '127.0.0.1::8080' \ + -v "$temp/Caddyfile:/etc/caddy/Caddyfile:ro" \ + -v "$temp/run:/run/xmesh-sub:ro" \ + xmesh-sub-caddy:2.11.9-josev4r1 caddy run --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null + +address=$(docker port "$caddy_name" 8080/tcp | head -n 1) +[[ "$address" =~ ^127[.]0[.]0[.]1:[0-9]+$ ]] || { echo 'Unexpected local-only Caddy binding' >&2; exit 1; } +base="http://$address" +for i in $(seq 1 60); do + [[ $(curl -s -o /dev/null -w '%{http_code}' --max-time 2 "$base/healthz") == 200 ]] && break + sleep 0.2 +done +status() { + curl -sS -o /dev/null -w '%{http_code}' --max-time 6 "$@" +} +[[ $(status "$base/healthz") == 200 ]] || { echo 'Health endpoint not reachable' >&2; exit 1; } +[[ $(status "$base/api/admin") == 404 ]] || { echo 'Admin path leaked through subscription ingress' >&2; exit 1; } +[[ $(status "$base/s/not-a-token") == 404 ]] || { echo 'Invalid subscription route was accepted' >&2; exit 1; } +token=$(printf 'a%.0s' {1..64}) +route="$base/s/$token" +[[ $(status "$route") == 200 ]] || { echo 'First allowed subscription request failed' >&2; exit 1; } +[[ $(status -H 'X-Forwarded-For: 198.51.100.4' "$route") == 429 ]] || + { echo 'Client spoofed XFF to bypass direct-peer rate limit' >&2; exit 1; } +[[ $(status -H 'X-XMesh-Peer-IP: 198.51.100.55' "$route") == 429 ]] || + { echo 'Client spoofed internal peer-IP header to bypass rate limit' >&2; exit 1; } +echo 'Verified: Caddy routes, private Unix gate and spoof-resistant per-peer HTTP 429' From 86137427909f096aecab1b10de0239c4acc72314 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:18:57 +0300 Subject: [PATCH 32/68] ci(sub): require real container gateway rate-limit and spoofing tests on both architectures --- .github/workflows/image-security.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index 7e1cecf..1744ffe 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -4,6 +4,7 @@ on: paths: - 'install.sh' - 'tests/test-install.sh' + - 'tests/test-runtime-edge.sh' - '.github/workflows/image-security.yml' - '.github/workflows/ci.yml' - '.github/workflows/attested-release.yml' @@ -82,6 +83,9 @@ jobs: exit 1 fi grep -Fq 'github.com/go-jose/go-jose/v4' "$RUNNER_TEMP/caddy-build-info.txt" || { echo 'Expected patched JOSE-v4 missing' >&2; exit 1; } + - name: Exercise real Caddy and Unix limiter against spoofed client headers + shell: bash + run: bash tests/test-runtime-edge.sh "$RUNNER_TEMP" - name: Install pinned and checksum-verified Trivy v0.76.2 env: TRIVY_ARCH: ${{ matrix.arch }} From c2e194e91bdd890f11350e5017e28733d51cc4ea Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:19:14 +0300 Subject: [PATCH 33/68] test(sub): include live container regression shell in signed-release lint --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cc21f91..a9ff7aa 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,8 +14,8 @@ jobs: persist-credentials: false - name: Syntax and ShellCheck run: | - bash -n install.sh bootstrap.sh tests/test-install.sh tests/test-bootstrap.sh - shellcheck -s bash install.sh bootstrap.sh tests/test-install.sh tests/test-bootstrap.sh + bash -n install.sh bootstrap.sh tests/test-install.sh tests/test-bootstrap.sh tests/test-runtime-edge.sh + shellcheck -s bash install.sh bootstrap.sh tests/test-install.sh tests/test-bootstrap.sh tests/test-runtime-edge.sh - name: Installer argument tests run: | bash tests/test-install.sh From e3eada803c65edc760c6570d418d324d18632dc2 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:19:17 +0300 Subject: [PATCH 34/68] test(sub): include live container regression shell in signed-release lint --- .github/workflows/attested-release.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/attested-release.yml b/.github/workflows/attested-release.yml index deab08e..b176962 100644 --- a/.github/workflows/attested-release.yml +++ b/.github/workflows/attested-release.yml @@ -36,8 +36,8 @@ jobs: persist-credentials: false - name: Lint and integration tests run: | - bash -n install.sh bootstrap.sh tests/test-install.sh tests/test-bootstrap.sh - shellcheck -s bash install.sh bootstrap.sh tests/test-install.sh tests/test-bootstrap.sh + bash -n install.sh bootstrap.sh tests/test-install.sh tests/test-bootstrap.sh tests/test-runtime-edge.sh + shellcheck -s bash install.sh bootstrap.sh tests/test-install.sh tests/test-bootstrap.sh tests/test-runtime-edge.sh bash tests/test-install.sh bash tests/test-bootstrap.sh python3 -m py_compile manager.py release_verify.py limiter.py From 98a124f2b106574fdda78c9f9a7048061a947373 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:20:08 +0300 Subject: [PATCH 35/68] test(sub): satisfy strict ShellCheck for bounded readiness loops --- tests/test-runtime-edge.sh | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/test-runtime-edge.sh b/tests/test-runtime-edge.sh index 62da09b..0e88cc4 100644 --- a/tests/test-runtime-edge.sh +++ b/tests/test-runtime-edge.sh @@ -49,7 +49,7 @@ docker run -d --name "$limiter_name" --network none \ -v "$temp/policy:/etc/xmesh-sub/policy:ro" \ -v "$PWD/limiter.py:/opt/limiter.py:ro" \ xmesh-sub-limiter:3.12.16-krb5r1 python3 -I /opt/limiter.py >/dev/null -for i in $(seq 1 60); do +for ((attempt=0; attempt<60; attempt++)); do [[ -S "$temp/run/rate.sock" ]] && break sleep 0.2 done @@ -65,7 +65,7 @@ docker run -d --name "$caddy_name" --network bridge \ address=$(docker port "$caddy_name" 8080/tcp | head -n 1) [[ "$address" =~ ^127[.]0[.]0[.]1:[0-9]+$ ]] || { echo 'Unexpected local-only Caddy binding' >&2; exit 1; } base="http://$address" -for i in $(seq 1 60); do +for ((attempt=0; attempt<60; attempt++)); do [[ $(curl -s -o /dev/null -w '%{http_code}' --max-time 2 "$base/healthz") == 200 ]] && break sleep 0.2 done From 7062c261c7ec7bc338d6e7a331978da9ae481571 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:21:38 +0300 Subject: [PATCH 36/68] test(sub): set socket directory permissions before transferring ownership --- tests/test-runtime-edge.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test-runtime-edge.sh b/tests/test-runtime-edge.sh index 0e88cc4..5680c40 100644 --- a/tests/test-runtime-edge.sh +++ b/tests/test-runtime-edge.sh @@ -15,8 +15,8 @@ cleanup() { trap cleanup EXIT mkdir -p "$temp/run" "$temp/policy" -sudo chown 65534:65534 "$temp/run" chmod 0770 "$temp/run" +sudo chown 65534:65534 "$temp/run" printf '%s\n' '{"enabled":true,"mode":"protect","ipPerMinute":1}' > "$temp/policy/config.json" chmod 0644 "$temp/policy/config.json" From b6e2ab72a89532e09c0033eaf513188470bc88f3 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:49:11 +0300 Subject: [PATCH 37/68] test(sub): make non-secret fixtures traversable and surface limiter crash diagnostics --- tests/test-runtime-edge.sh | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/test-runtime-edge.sh b/tests/test-runtime-edge.sh index 5680c40..91bac9c 100644 --- a/tests/test-runtime-edge.sh +++ b/tests/test-runtime-edge.sh @@ -6,10 +6,15 @@ cd "$(dirname "$0")/.." [[ $# == 1 && -s "$1/Caddyfile" ]] || { echo 'Missing generated Caddyfile' >&2; exit 1; } source_caddyfile=$1/Caddyfile temp=$(mktemp -d) +# Disposable non-secret fixtures must be traversable by container uid 65534. +# The socket itself remains under a uid-65534 owned, mode-0770 subdirectory. +chmod 0755 "$temp" limiter_name="xmesh-edge-limiter-$$" caddy_name="xmesh-edge-caddy-$$" cleanup() { docker rm -f "$caddy_name" "$limiter_name" >/dev/null 2>&1 || true + # Regain ownership of the disposable socket directory before cleanup. + sudo chown -R "$(id -u):$(id -g)" "$temp" 2>/dev/null || true rm -rf "$temp" } trap cleanup EXIT @@ -53,7 +58,14 @@ for ((attempt=0; attempt<60; attempt++)); do [[ -S "$temp/run/rate.sock" ]] && break sleep 0.2 done -[[ -S "$temp/run/rate.sock" ]] || { echo 'Limiter socket failed to appear' >&2; exit 1; } +if [[ ! -S "$temp/run/rate.sock" ]]; then + echo 'Limiter socket failed to appear; diagnostic container status and logs:' >&2 + docker inspect --format '{{.State.Status}} {{.State.ExitCode}} {{.State.Error}}' "$limiter_name" >&2 || true + docker logs "$limiter_name" >&2 || true + echo 'Fixture permissions:' >&2 + stat -c '%a %u:%g %n' "$temp" "$temp/run" "$temp/policy" "$temp/policy/config.json" >&2 || true + exit 1 +fi docker run -d --name "$caddy_name" --network bridge \ --security-opt no-new-privileges \ From 72fdd24e192515b12b0653592b4791c37103ce8b Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:51:47 +0300 Subject: [PATCH 38/68] test(sub): inspect running limiter mount and Unix socket on CI failure --- tests/test-runtime-edge.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/test-runtime-edge.sh b/tests/test-runtime-edge.sh index 91bac9c..729ac8b 100644 --- a/tests/test-runtime-edge.sh +++ b/tests/test-runtime-edge.sh @@ -62,6 +62,9 @@ if [[ ! -S "$temp/run/rate.sock" ]]; then echo 'Limiter socket failed to appear; diagnostic container status and logs:' >&2 docker inspect --format '{{.State.Status}} {{.State.ExitCode}} {{.State.Error}}' "$limiter_name" >&2 || true docker logs "$limiter_name" >&2 || true + echo 'Inspect container process, bind mounts and socket:' >&2 + docker inspect --format '{{json .Mounts}} {{json .Config.Cmd}} {{json .Config.Entrypoint}}' "$limiter_name" >&2 || true + docker exec "$limiter_name" sh -c 'id; ls -ld /run/xmesh-sub /etc/xmesh-sub/policy; ls -al /run/xmesh-sub; ps aux' >&2 || true echo 'Fixture permissions:' >&2 stat -c '%a %u:%g %n' "$temp" "$temp/run" "$temp/policy" "$temp/policy/config.json" >&2 || true exit 1 From e2a5475fb2e828f287ef154320ae45dfb136e01b Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:54:40 +0300 Subject: [PATCH 39/68] test(sub): share limiter Unix socket through a Docker volume, not runner tmp mount --- tests/test-runtime-edge.sh | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/tests/test-runtime-edge.sh b/tests/test-runtime-edge.sh index 729ac8b..cbc6f8e 100644 --- a/tests/test-runtime-edge.sh +++ b/tests/test-runtime-edge.sh @@ -9,19 +9,24 @@ temp=$(mktemp -d) # Disposable non-secret fixtures must be traversable by container uid 65534. # The socket itself remains under a uid-65534 owned, mode-0770 subdirectory. chmod 0755 "$temp" -limiter_name="xmesh-edge-limiter-$$" -caddy_name="xmesh-edge-caddy-$$" +limiter_name="xmesh-edge-limiter-$" +caddy_name="xmesh-edge-caddy-$" +socket_volume="xmesh-edge-socket-$" cleanup() { docker rm -f "$caddy_name" "$limiter_name" >/dev/null 2>&1 || true - # Regain ownership of the disposable socket directory before cleanup. - sudo chown -R "$(id -u):$(id -g)" "$temp" 2>/dev/null || true + docker volume rm -f "$socket_volume" >/dev/null 2>&1 || true rm -rf "$temp" } trap cleanup EXIT -mkdir -p "$temp/run" "$temp/policy" -chmod 0770 "$temp/run" -sudo chown 65534:65534 "$temp/run" +mkdir -p "$temp/policy" +# A Docker-managed volume is genuinely shared by sibling containers even +# when the CI runner and the Docker daemon use separate mount namespaces. +docker volume create "$socket_volume" >/dev/null +docker run --rm --user 0 --entrypoint sh \ + -v "$socket_volume:/run/xmesh-sub" \ + xmesh-sub-caddy:2.11.9-josev4r1 \ + -c 'chown 65534:65534 /run/xmesh-sub && chmod 0770 /run/xmesh-sub' printf '%s\n' '{"enabled":true,"mode":"protect","ipPerMinute":1}' > "$temp/policy/config.json" chmod 0644 "$temp/policy/config.json" @@ -50,15 +55,15 @@ PY docker run -d --name "$limiter_name" --network none \ --user 65534:65534 --read-only --tmpfs /tmp \ --security-opt no-new-privileges --cap-drop ALL \ - -v "$temp/run:/run/xmesh-sub" \ + -v "$socket_volume:/run/xmesh-sub" \ -v "$temp/policy:/etc/xmesh-sub/policy:ro" \ -v "$PWD/limiter.py:/opt/limiter.py:ro" \ xmesh-sub-limiter:3.12.16-krb5r1 python3 -I /opt/limiter.py >/dev/null for ((attempt=0; attempt<60; attempt++)); do - [[ -S "$temp/run/rate.sock" ]] && break + docker exec "$limiter_name" test -S /run/xmesh-sub/rate.sock >/dev/null 2>&1 && break sleep 0.2 done -if [[ ! -S "$temp/run/rate.sock" ]]; then +if ! docker exec "$limiter_name" test -S /run/xmesh-sub/rate.sock >/dev/null 2>&1; then echo 'Limiter socket failed to appear; diagnostic container status and logs:' >&2 docker inspect --format '{{.State.Status}} {{.State.ExitCode}} {{.State.Error}}' "$limiter_name" >&2 || true docker logs "$limiter_name" >&2 || true @@ -66,7 +71,7 @@ if [[ ! -S "$temp/run/rate.sock" ]]; then docker inspect --format '{{json .Mounts}} {{json .Config.Cmd}} {{json .Config.Entrypoint}}' "$limiter_name" >&2 || true docker exec "$limiter_name" sh -c 'id; ls -ld /run/xmesh-sub /etc/xmesh-sub/policy; ls -al /run/xmesh-sub; ps aux' >&2 || true echo 'Fixture permissions:' >&2 - stat -c '%a %u:%g %n' "$temp" "$temp/run" "$temp/policy" "$temp/policy/config.json" >&2 || true + stat -c '%a %u:%g %n' "$temp" "$temp/policy" "$temp/policy/config.json" >&2 || true exit 1 fi @@ -74,7 +79,7 @@ docker run -d --name "$caddy_name" --network bridge \ --security-opt no-new-privileges \ -p '127.0.0.1::8080' \ -v "$temp/Caddyfile:/etc/caddy/Caddyfile:ro" \ - -v "$temp/run:/run/xmesh-sub:ro" \ + -v "$socket_volume:/run/xmesh-sub:ro" \ xmesh-sub-caddy:2.11.9-josev4r1 caddy run --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null address=$(docker port "$caddy_name" 8080/tcp | head -n 1) From 8b44804b88a107d37b1d237ecf51331ebb9750d3 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Mon, 16 Nov 2026 17:56:56 +0300 Subject: [PATCH 40/68] test(sub): restore unique valid Docker container and volume PID suffixes --- tests/test-runtime-edge.sh | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/test-runtime-edge.sh b/tests/test-runtime-edge.sh index cbc6f8e..ecb2972 100644 --- a/tests/test-runtime-edge.sh +++ b/tests/test-runtime-edge.sh @@ -9,9 +9,9 @@ temp=$(mktemp -d) # Disposable non-secret fixtures must be traversable by container uid 65534. # The socket itself remains under a uid-65534 owned, mode-0770 subdirectory. chmod 0755 "$temp" -limiter_name="xmesh-edge-limiter-$" -caddy_name="xmesh-edge-caddy-$" -socket_volume="xmesh-edge-socket-$" +limiter_name="xmesh-edge-limiter-$$" +caddy_name="xmesh-edge-caddy-$$" +socket_volume="xmesh-edge-socket-$$" cleanup() { docker rm -f "$caddy_name" "$limiter_name" >/dev/null 2>&1 || true docker volume rm -f "$socket_volume" >/dev/null 2>&1 || true From 226af5113e1fadfe383e8faad369f46b248c529f Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 04:17:30 +0300 Subject: [PATCH 41/68] security(sub): preserve exact old Docker image IDs and verify HTTPS before update success --- manager.py | 95 ++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 89 insertions(+), 6 deletions(-) diff --git a/manager.py b/manager.py index 2595a2d..a2e055d 100644 --- a/manager.py +++ b/manager.py @@ -79,25 +79,83 @@ def version_tuple(version: str) -> tuple[int, int, int]: return tuple(map(int, match.groups())) if match else (0, 0, 0) +BACKUP_FILES = ("Caddyfile", "compose.yaml", "manager.py", "manager.json", "agent-key.pem", + "limiter.py", "release_verify.py", "RELEASE_SHA", "VERSION", + "Dockerfile.limiter", "Dockerfile.caddy") +DOCKER_IMAGE_ID = re.compile(r"^sha256:[0-9a-f]{64}$") + + +def _docker_output(argv: list[str], root: Path) -> str: + result = subprocess.run(["docker", *argv], cwd=root, check=True, timeout=30, + capture_output=True, text=True) + return result.stdout.strip() + + def backup_installation(root: Path = ROOT) -> Path: + """Preserve files AND exact local image IDs before an installer overwrites tags.""" destination = root / "backups" destination.mkdir(mode=0o700, exist_ok=True) backup = Path(tempfile.mkdtemp(prefix="pre-update-", dir=str(destination))) backup.chmod(0o700) - files = ("Caddyfile", "compose.yaml", "manager.py", "manager.json", "agent-key.pem", "limiter.py", - "release_verify.py", "RELEASE_SHA", "VERSION", "Dockerfile.limiter", "Dockerfile.caddy") - for name in files: + for name in BACKUP_FILES: old = root / name if old.is_file(): shutil.copy2(old, backup / name) else: (backup / (".absent-" + name)).touch() + + # The installer uses fixed local image tags that Docker reassigns during + # docker build. Saving only compose.yaml cannot recover their old content. + # Ask the *old* compose config for the exact image names before upgrading. + compose = backup / "compose.yaml" + if not compose.is_file(): + raise RuntimeError("Cannot update gateway without existing Compose configuration") + output = _docker_output(["compose", "-f", str(compose), "config", "--images"], root) + refs = sorted(set(output.splitlines())) + if not 1 <= len(refs) <= 4 or any( + not ref or len(ref) > 255 or any(ch.isspace() for ch in ref) or "@" in ref + for ref in refs): + raise RuntimeError("Unrecognized original gateway image references") + snapshots = [] + for index, ref in enumerate(refs): + image_id = _docker_output(["image", "inspect", "--format", "{{.Id}}", ref], root) + if not DOCKER_IMAGE_ID.fullmatch(image_id): + raise RuntimeError("Could not identify original gateway image") + rescue_tag = f"xmesh-sub-rollback-{index}:{backup.name}" + subprocess.run(["docker", "image", "tag", image_id, rescue_tag], cwd=root, + check=True, timeout=30) + snapshots.append({"reference": ref, "image_id": image_id, "rescue_tag": rescue_tag}) + image_manifest = backup / "images.json" + image_manifest.write_text(json.dumps(snapshots, separators=(",", ":")), encoding="utf-8") + image_manifest.chmod(0o600) return backup def restore_installation(backup: Path, root: Path = ROOT) -> None: - for name in ("Caddyfile", "compose.yaml", "manager.py", "manager.json", "agent-key.pem", "limiter.py", - "release_verify.py", "RELEASE_SHA", "VERSION", "Dockerfile.limiter", "Dockerfile.caddy"): + """Restore old image IDs before force-recreating containers from old files.""" + image_manifest = backup / "images.json" + if not image_manifest.is_file(): + raise RuntimeError("Rollback image inventory missing; refusing partial restore") + snapshots = json.loads(image_manifest.read_text(encoding="utf-8")) + if not isinstance(snapshots, list) or not 1 <= len(snapshots) <= 4: + raise RuntimeError("Invalid rollback image inventory") + # Validate every retained image before mutating any deployed tag or file. + for entry in snapshots: + if (not isinstance(entry, dict) or set(entry) != {"reference", "image_id", "rescue_tag"} + or not isinstance(entry["reference"], str) + or not isinstance(entry["rescue_tag"], str) + or not isinstance(entry["image_id"], str) + or not DOCKER_IMAGE_ID.fullmatch(entry["image_id"]) + or not entry["rescue_tag"].startswith("xmesh-sub-rollback-") + or not entry["reference"] or any(ch.isspace() for ch in entry["reference"])): + raise RuntimeError("Invalid rollback image entry") + if _docker_output(["image", "inspect", "--format", "{{.Id}}", + entry["rescue_tag"]], root) != entry["image_id"]: + raise RuntimeError("Retained rollback image is missing or changed") + for entry in snapshots: + subprocess.run(["docker", "image", "tag", entry["rescue_tag"], + entry["reference"]], cwd=root, check=True, timeout=30) + for name in BACKUP_FILES: saved = backup / name target = root / name if saved.is_file(): @@ -105,7 +163,31 @@ def restore_installation(backup: Path, root: Path = ROOT) -> None: elif (backup / (".absent-" + name)).is_file(): target.unlink(missing_ok=True) subprocess.run(["docker", "compose", "-f", str(root / "compose.yaml"), - "up", "-d", "--no-build", "--remove-orphans"], cwd=root, check=True, timeout=180) + "up", "-d", "--no-build", "--force-recreate", "--remove-orphans"], + cwd=root, check=True, timeout=180) + + +def verify_updated_gateway(config: dict, root: Path = ROOT) -> None: + """Check the real public HTTPS endpoint before reporting update success.""" + running = _docker_output(["compose", "-f", str(root / "compose.yaml"), + "ps", "--services", "--status", "running"], root).splitlines() + if not {"xmesh-sub", "xmesh-sub-limiter"}.issubset(set(running)): + raise RuntimeError("Updated gateway containers are not running") + # A previous HTTPS certificate and DNS are expected on an existing gateway. + # Verify actual external routing and certificate trust, not just container state. + url = "https://" + config["domain"] + "/healthz" + error = None + for attempt in range(6): + try: + with verified_open(urllib.request.Request(url, method="GET"), timeout=12) as response: + if response.status == 200 and response.read(3) == b"ok": + return + error = RuntimeError("Subscription gateway health response is invalid") + except (OSError, ValueError, urllib.error.URLError) as exc: + error = exc + if attempt < 5: + time.sleep(5) + raise RuntimeError("Updated subscription gateway failed verified HTTPS health check") from error def signed_agent_headers(route: str, payload: bytes, key: Path = PRIVATE_KEY_FILE) -> dict: @@ -218,6 +300,7 @@ def perform_update(config: dict) -> None: "--domain", config["domain"], "--path", config["path"], "--release-sha", sha, "--skip-manager-restart", ], check=True, timeout=900, stdout=subprocess.DEVNULL) + verify_updated_gateway(config) except Exception as original: try: restore_installation(backup) From ab77f73a0502fd3cd08a9c6af6d8eb9de6ddc44e Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 04:18:11 +0300 Subject: [PATCH 42/68] test(sub): verify image-level rollback, fail-closed snapshots, and HTTPS health gate --- tests/test-manager.py | 110 +++++++++++++++++++++++++++++++++++++----- 1 file changed, 99 insertions(+), 11 deletions(-) diff --git a/tests/test-manager.py b/tests/test-manager.py index 8c1a951..10a63b7 100644 --- a/tests/test-manager.py +++ b/tests/test-manager.py @@ -202,24 +202,112 @@ def test_release_trust_is_bound_to_exact_main_commit(self): self.assertIn('.github/workflows/attested-release.yml', manager.release_verify.CERT_IDENTITY) - def test_backup_and_rollback_restore_original_configuration(self): + def test_backup_and_rollback_restore_original_configuration_and_images(self): with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) (root / "compose.yaml").write_text("services: original") (root / "manager.json").write_text("original server settings") (root / "agent-key.pem").write_text("original private key") - backup = manager.backup_installation(root) - (root / "compose.yaml").write_text("services: broken") - (root / "manager.json").unlink() - (root / "agent-key.pem").write_text("tampered") - (root / "VERSION").write_text("9.9.9") - with patch.object(manager.subprocess, "run") as run: + caddy_id = "sha256:" + "a" * 64 + limiter_id = "sha256:" + "b" * 64 + old_images = { + "xmesh-sub-caddy:2.11.9-josev4r1": caddy_id, + "xmesh-sub-limiter:3.12.16-krb5r1": limiter_id, + } + images = dict(old_images) + def docker_output(argv, _root): + if argv[0:4] == ["compose", "-f", str(root / "backups" / + "missing"), "config"]: + raise AssertionError("Unexpected Compose path") + if argv[0] == "compose" and argv[-2:] == ["config", "--images"]: + return "\n".join(old_images) + if argv[0:3] == ["image", "inspect", "--format"]: + return images[argv[-1]] + raise AssertionError(f"Unexpected Docker query: {argv}") + def docker_command(argv, **_kwargs): + if argv[:3] == ["docker", "image", "tag"]: + images[argv[4]] = images.get(argv[3], argv[3]) + return subprocess.CompletedProcess(argv, 0) + with patch.object(manager, "_docker_output", side_effect=docker_output), \ + patch.object(manager.subprocess, "run", side_effect=docker_command) as run: + backup = manager.backup_installation(root) + saved = json.loads((backup / "images.json").read_text()) + self.assertEqual(len(saved), 2) + self.assertEqual((backup / "images.json").stat().st_mode & 0o777, 0o600) + # Model the attested installer overwriting both mutable local tags. + for ref in images.keys() & old_images.keys(): + images[ref] = "sha256:" + "c" * 64 + (root / "compose.yaml").write_text("services: broken") + (root / "manager.json").unlink() + (root / "agent-key.pem").write_text("tampered") + (root / "VERSION").write_text("9.9.9") manager.restore_installation(backup, root) + for ref, old_id in old_images.items(): + self.assertEqual(images[ref], old_id) + self.assertEqual((root / "compose.yaml").read_text(), "services: original") + self.assertEqual((root / "manager.json").read_text(), "original server settings") + self.assertEqual((root / "agent-key.pem").read_text(), "original private key") + self.assertFalse((root / "VERSION").exists()) + self.assertIn("--force-recreate", run.call_args.args[0]) + self.assertIn("--no-build", run.call_args.args[0]) + + def test_rollback_rejects_missing_or_changed_images_before_mutating_files(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + (root / "compose.yaml").write_text("services: original") + backup = root / "backups" / "pre-update-safe" + backup.mkdir(parents=True) + (backup / "compose.yaml").write_text("services: original") + (backup / "images.json").write_text(json.dumps([{ + "reference": "xmesh-sub-caddy:2.11.9-josev4r1", + "image_id": "sha256:" + "a" * 64, + "rescue_tag": "xmesh-sub-rollback-0:pre-update-safe", + }])) + with patch.object(manager, "_docker_output", return_value="sha256:" + "b" * 64), \ + patch.object(manager.subprocess, "run") as docker: + with self.assertRaisesRegex(RuntimeError, "missing or changed"): + manager.restore_installation(backup, root) + docker.assert_not_called() self.assertEqual((root / "compose.yaml").read_text(), "services: original") - self.assertEqual((root / "manager.json").read_text(), "original server settings") - self.assertEqual((root / "agent-key.pem").read_text(), "original private key") - self.assertFalse((root / "VERSION").exists()) - self.assertEqual(run.call_args.args[0][0:2], ["docker", "compose"]) + (backup / "images.json").unlink() + with self.assertRaisesRegex(RuntimeError, "inventory missing"): + manager.restore_installation(backup, root) + + def test_update_health_failure_rolls_back_the_snapshotted_images(self): + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + version = folder / "VERSION" + version.write_text("0.5.0") + script = folder / "install.sh" + script.write_text("#!/usr/bin/env bash\n") + with patch.object(manager.release_verify, "latest_source_sha", return_value="a"*40), \ + patch.object(manager.release_verify, "stage_revision", + return_value={"VERSION": version, "install.sh": script}), \ + patch.object(manager, "current_version", return_value="0.4.1"), \ + patch.object(manager, "backup_installation", return_value=folder / "backup"), \ + patch.object(manager, "verify_updated_gateway", + side_effect=RuntimeError("health check failed")), \ + patch.object(manager, "restore_installation") as restore, \ + patch.object(manager.subprocess, "run") as run: + with self.assertRaisesRegex(RuntimeError, "health check failed"): + manager.perform_update(self.config) + restore.assert_called_once_with(folder / "backup") + self.assertEqual(run.call_count, 2) + self.assertIn("--skip-manager-restart", run.call_args.args[0]) + + def test_updated_gateway_requires_real_https_health_after_both_services_run(self): + with patch.object(manager, "_docker_output", + return_value="xmesh-sub-limiter\\nxmesh-sub"), \ + patch.object(manager, "verified_open") as request: + response = request.return_value.__enter__.return_value + response.status = 200 + response.read.return_value = b"ok" + manager.verify_updated_gateway(self.config, root=Path("/tmp/test-sub-only")) + self.assertEqual(request.call_args.args[0].full_url, + "https://" + self.config["domain"] + "/healthz") + with patch.object(manager, "_docker_output", return_value="xmesh-sub"): + with self.assertRaisesRegex(RuntimeError, "containers are not running"): + manager.verify_updated_gateway(self.config, root=Path("/tmp/test-sub-only")) def test_update_rejects_unattested_revision_before_execution(self): with patch.object(manager.release_verify,'latest_source_sha',return_value='a'*40), \ From ef1a42b0bf5fdcc8e6471faf35cab0117561114b Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 04:18:54 +0300 Subject: [PATCH 43/68] test(sub): correct mocked Compose service list newline in health gate test --- tests/test-manager.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test-manager.py b/tests/test-manager.py index 10a63b7..9af92a6 100644 --- a/tests/test-manager.py +++ b/tests/test-manager.py @@ -297,7 +297,7 @@ def test_update_health_failure_rolls_back_the_snapshotted_images(self): def test_updated_gateway_requires_real_https_health_after_both_services_run(self): with patch.object(manager, "_docker_output", - return_value="xmesh-sub-limiter\\nxmesh-sub"), \ + return_value="xmesh-sub-limiter\nxmesh-sub"), \ patch.object(manager, "verified_open") as request: response = request.return_value.__enter__.return_value response.status = 200 From bc9725c963094c89ec0b6373e19f6985ebc1e930 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 04:19:46 +0300 Subject: [PATCH 44/68] test(sub): prove actual image-ID and container recovery on disposable Docker Compose --- tests/test-image-rollback.py | 104 +++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 tests/test-image-rollback.py diff --git a/tests/test-image-rollback.py b/tests/test-image-rollback.py new file mode 100644 index 0000000..1782925 --- /dev/null +++ b/tests/test-image-rollback.py @@ -0,0 +1,104 @@ +#!/usr/bin/env python3 +"""CI-only Docker proof: keep/recover old image IDs after mutable tags change. + +Uses disposable Compose project, temporary tags and no public ports, credentials, +network services, or production data. Requires locally built candidate images. +""" +import importlib.util +import json +from pathlib import Path +import subprocess +import tempfile +import uuid + +ROOT = Path(__file__).resolve().parent.parent +spec = importlib.util.spec_from_file_location("xmesh_sub_manager", ROOT / "manager.py") +manager = importlib.util.module_from_spec(spec) +spec.loader.exec_module(manager) + + +def docker(*args): + return subprocess.run(["docker", *args], text=True, capture_output=True, + check=True, timeout=180).stdout.strip() + + +def container_image(compose: Path, service: str) -> str: + cid = docker("compose", "-f", str(compose), "ps", "-q", service) + if not cid: + raise RuntimeError(f"{service} did not start") + return docker("inspect", "--format", "{{.Image}}", cid) + + +def main(): + suffix = uuid.uuid4().hex[:16] + original_caddy = f"xmesh-sub-ci-caddy:{suffix}" + original_limiter = f"xmesh-sub-ci-limiter:{suffix}" + created = [] + backup = None + with tempfile.TemporaryDirectory(prefix="xmesh-sub-rollback-") as directory: + root = Path(directory) + compose = root / "compose.yaml" + try: + docker("image", "tag", "xmesh-sub-caddy:2.11.9-josev4r1", original_caddy) + created.append(original_caddy) + docker("image", "tag", "xmesh-sub-limiter:3.12.16-krb5r1", original_limiter) + created.append(original_limiter) + caddy_image = docker("image", "inspect", "--format", "{{.Id}}", original_caddy) + limiter_image = docker("image", "inspect", "--format", "{{.Id}}", original_limiter) + if caddy_image == limiter_image: + raise RuntimeError("Cannot test rollback with identical images") + compose.write_text( + f"services:\n" + f" xmesh-sub:\n" + f" image: {original_caddy}\n" + f" pull_policy: never\n" + f" entrypoint: ['sh', '-c']\n" + f" command: 'sleep 300'\n" + f" xmesh-sub-limiter:\n" + f" image: {original_limiter}\n" + f" pull_policy: never\n" + f" entrypoint: ['sh', '-c']\n" + f" command: 'sleep 300'\n", encoding="utf-8") + docker("compose", "-f", str(compose), "up", "-d", "--no-build") + assert container_image(compose, "xmesh-sub") == caddy_image + assert container_image(compose, "xmesh-sub-limiter") == limiter_image + + backup = manager.backup_installation(root) + manifest = json.loads((backup / "images.json").read_text()) + assert len(manifest) == 2, manifest + assert set(x["image_id"] for x in manifest) == {caddy_image, limiter_image} + + # Model what install.sh does on upgrade: replace both original + # mutable tags with new image bytes. The Docker daemon must retain + # the old *image IDs* through private rollback tags. + docker("image", "tag", limiter_image, original_caddy) + docker("image", "tag", caddy_image, original_limiter) + docker("compose", "-f", str(compose), "up", "-d", "--no-build", + "--force-recreate") + assert container_image(compose, "xmesh-sub") == limiter_image + assert container_image(compose, "xmesh-sub-limiter") == caddy_image + + manager.restore_installation(backup, root) + assert container_image(compose, "xmesh-sub") == caddy_image + assert container_image(compose, "xmesh-sub-limiter") == limiter_image + assert docker("image", "inspect", "--format", "{{.Id}}", + original_caddy) == caddy_image + assert docker("image", "inspect", "--format", "{{.Id}}", + original_limiter) == limiter_image + print("PASS: real Docker rollback restored original image IDs and recreated both services") + finally: + if compose.exists(): + subprocess.run(["docker", "compose", "-f", str(compose), + "down", "--remove-orphans"], capture_output=True, + timeout=120, check=False) + if backup is not None: + for image in json.loads((backup / "images.json").read_text()): + subprocess.run(["docker", "image", "rm", image["rescue_tag"]], + capture_output=True, timeout=30, check=False) + for ref in created: + subprocess.run(["docker", "image", "rm", ref], capture_output=True, + timeout=30, check=False) + + +if __name__ == "__main__": + main() From 7c2a96ed8aa24f11de2118e1814012db5c0bd48d Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 04:19:56 +0300 Subject: [PATCH 45/68] ci(sub): gate release on real Docker image and Compose rollback proof, both architectures --- .github/workflows/image-security.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index 1744ffe..cf6905a 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -5,6 +5,7 @@ on: - 'install.sh' - 'tests/test-install.sh' - 'tests/test-runtime-edge.sh' + - 'tests/test-image-rollback.py' - '.github/workflows/image-security.yml' - '.github/workflows/ci.yml' - '.github/workflows/attested-release.yml' @@ -86,6 +87,9 @@ jobs: - name: Exercise real Caddy and Unix limiter against spoofed client headers shell: bash run: bash tests/test-runtime-edge.sh "$RUNNER_TEMP" + - name: Recover exact old Docker image IDs after simulated broken upgrade + shell: bash + run: python3 tests/test-image-rollback.py - name: Install pinned and checksum-verified Trivy v0.76.2 env: TRIVY_ARCH: ${{ matrix.arch }} From 6e6bcffdacc33f2ce1b58f24dae1f48ac113f99b Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 04:20:04 +0300 Subject: [PATCH 46/68] ci(sub): syntax-check disposable Docker rollback regression before image matrix --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a9ff7aa..8f89083 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: bash tests/test-bootstrap.sh - name: Outbound signed agent and edge IP limiter tests run: | - python3 -m py_compile manager.py limiter.py + python3 -m py_compile manager.py limiter.py tests/test-image-rollback.py python3 tests/test-manager.py python3 tests/test-limiter.py - name: Validate rendered Caddy configuration From 53d1754058fc0213e8931c0dcbdc2b2a76e6d577 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 04:21:56 +0300 Subject: [PATCH 47/68] test(sub): use executable shell entrypoint and empty CMD in disposable Docker rollback harness --- tests/test-image-rollback.py | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/test-image-rollback.py b/tests/test-image-rollback.py index 1782925..3208bc7 100644 --- a/tests/test-image-rollback.py +++ b/tests/test-image-rollback.py @@ -25,7 +25,9 @@ def docker(*args): def container_image(compose: Path, service: str) -> str: cid = docker("compose", "-f", str(compose), "ps", "-q", service) if not cid: - raise RuntimeError(f"{service} did not start") + containers = docker("compose", "-f", str(compose), "ps", "-a") + logs = docker("compose", "-f", str(compose), "logs", "--tail", "25") + raise RuntimeError(f"{service} did not start; status={containers!r}; logs={logs!r}") return docker("inspect", "--format", "{{.Image}}", cid) @@ -52,13 +54,13 @@ def main(): f" xmesh-sub:\n" f" image: {original_caddy}\n" f" pull_policy: never\n" - f" entrypoint: ['sh', '-c']\n" - f" command: 'sleep 300'\n" + f" entrypoint: ['sh', '-c', 'sleep 300']\n" + f" command: []\n" f" xmesh-sub-limiter:\n" f" image: {original_limiter}\n" f" pull_policy: never\n" - f" entrypoint: ['sh', '-c']\n" - f" command: 'sleep 300'\n", encoding="utf-8") + f" entrypoint: ['sh', '-c', 'sleep 300']\n" + f" command: []\n", encoding="utf-8") docker("compose", "-f", str(compose), "up", "-d", "--no-build") assert container_image(compose, "xmesh-sub") == caddy_image assert container_image(compose, "xmesh-sub-limiter") == limiter_image From 92e2a681a9ab8bf5c6682f6d5013fb037ae0c677 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:19:39 +0300 Subject: [PATCH 48/68] security(sub): use per-attested-revision immutable Docker image tags to protect first upgrade --- install.sh | 38 ++++++++++++++++++++++++++++++-------- 1 file changed, 30 insertions(+), 8 deletions(-) diff --git a/install.sh b/install.sh index 29871b4..5c2de5c 100644 --- a/install.sh +++ b/install.sh @@ -137,11 +137,24 @@ FROM caddy:2.11.9-alpine@sha256:003a97808e781aa9f7e75cc2f43d34d461099031faf5e20f COPY --from=builder /usr/bin/caddy /usr/bin/caddy DOCKER } +# Every attested revision has immutable local image names. In particular, +# the FIRST upgrade from an old manager must never overwrite the Docker tags +# required to recover the previous running configuration. +image_release_tag() { + local sha=${RELEASE_SHA:-0000000000000000000000000000000000000000} + [[ "$sha" =~ ^[a-f0-9]{40}$ ]] || die "Invalid immutable image release revision" + printf 'rev-%s' "$sha" +} +sub_limiter_image() { printf 'xmesh-sub-limiter:%s' "$(image_release_tag)"; } +sub_caddy_image() { printf 'xmesh-sub-caddy:%s' "$(image_release_tag)"; } render_compose() { - cat <<'YAML' + local limiter_image caddy_image + limiter_image=$(sub_limiter_image) + caddy_image=$(sub_caddy_image) + cat <<'YAML' | sed -e "s|@LIMITER_IMAGE@|$limiter_image|g" -e "s|@CADDY_IMAGE@|$caddy_image|g" services: xmesh-sub-limiter: - image: xmesh-sub-limiter:3.12.16-krb5r1 + image: @LIMITER_IMAGE@ build: context: . dockerfile: Dockerfile.limiter @@ -161,7 +174,7 @@ services: - /tmp # No published ports: Caddy is the only client, via a shared Unix socket. xmesh-sub: - image: xmesh-sub-caddy:2.11.9-josev4r1 + image: @CADDY_IMAGE@ build: context: . dockerfile: Dockerfile.caddy @@ -546,13 +559,22 @@ PY # The build context contains no keys, account records or verified manager code. mkdir -p "$temp/image-build" cp "$temp/Dockerfile.limiter" "$temp/image-build/Dockerfile" -docker build --pull -t xmesh-sub-limiter:3.12.16-krb5r1 "$temp/image-build" || - die "Could not build patched limiter image; existing deployment unchanged" +limiter_image=$(sub_limiter_image) +caddy_image=$(sub_caddy_image) +# A signed source revision owns its image names. Never rebuild an already +# installed revision under the same tag: a repeat installation should not +# silently replace the original image ID with a newer Alpine package set. +if ! docker image inspect "$limiter_image" >/dev/null 2>&1; then + docker build --pull -t "$limiter_image" "$temp/image-build" || + die "Could not build patched limiter image; existing deployment unchanged" +fi mkdir -p "$temp/caddy-build" cp "$temp/Dockerfile.caddy" "$temp/caddy-build/Dockerfile" -docker build --pull -t xmesh-sub-caddy:2.11.9-josev4r1 "$temp/caddy-build" || - die "Could not build patched Caddy binary; existing deployment unchanged" -docker run --rm -v "$temp/Caddyfile:/etc/caddy/Caddyfile:ro" xmesh-sub-caddy:2.11.9-josev4r1 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile || +if ! docker image inspect "$caddy_image" >/dev/null 2>&1; then + docker build --pull -t "$caddy_image" "$temp/caddy-build" || + die "Could not build patched Caddy binary; existing deployment unchanged" +fi +docker run --rm -v "$temp/Caddyfile:/etc/caddy/Caddyfile:ro" "$caddy_image" caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile || die "Gateway configuration invalid, existing deployment unchanged" [[ ! -f "$ROOT/Caddyfile" ]] || cp -p "$ROOT/Caddyfile" "$ROOT/Caddyfile.previous" install -m 600 "$temp/Caddyfile" "$ROOT/Caddyfile" From 0ec2a7895154270d28f91d0eed6b225cee0cb063 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:19:59 +0300 Subject: [PATCH 49/68] test(sub): enforce distinct immutable image tags for each attested release --- tests/test-install.sh | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/tests/test-install.sh b/tests/test-install.sh index d3eb100..963afab 100644 --- a/tests/test-install.sh +++ b/tests/test-install.sh @@ -17,7 +17,19 @@ grep -Fq 'header_up -X-Forwarded-Uri' <<< "$out" grep -Fq 'header_up -Authorization' <<< "$out" grep -Fq 'header_up -Cookie' <<< "$out" grep -Fq 'xmesh-sub-limiter:' <<< "$out" -grep -Fq 'image: xmesh-sub-caddy:2.11.9-josev4r1' <<< "$out" +# Even first-install dry-run receives a deterministic test-only revision. +test_sha=0000000000000000000000000000000000000000 +grep -Fq "image: xmesh-sub-caddy:rev-$test_sha" <<< "$out" +grep -Fq "image: xmesh-sub-limiter:rev-$test_sha" <<< "$out" +# Distinct signed revisions must have distinct image names, and placeholders +# must never survive into a runnable Compose file. +another_sha=1111111111111111111111111111111111111111 +out_alt=$(bash install.sh --panel https://panel.example.org --domain sub.example.org --path /s --release-sha "$another_sha" --dry-run) +grep -Fq "image: xmesh-sub-caddy:rev-$another_sha" <<< "$out_alt" +grep -Fq "image: xmesh-sub-limiter:rev-$another_sha" <<< "$out_alt" +if grep -Fq "@CADDY_IMAGE@" <<< "$out_alt" || grep -Fq "@LIMITER_IMAGE@" <<< "$out_alt"; then + echo "ERROR: unresolved image names in installer output" >&2; exit 1 +fi grep -Fq 'dockerfile: Dockerfile.limiter' <<< "$out" grep -Fq 'pull_policy: never' <<< "$out" grep -Fq 'FROM python:3.12.16-alpine3.24@sha256:c5ba3deef00c7758561a0f03c26f44f10589263d40e732b8748e0d1f38f6dd89' <<< "$out" @@ -29,7 +41,9 @@ grep -Fq 'github.com/smallstep/certificates@v0.30.3-0.20261105213751-6d5a251fbe0 grep -Fq 'go.step.sm/crypto@v0.92.0' <<< "$out" grep -Fq 'golang.org/x/net@v0.62.0' <<< "$out" grep -Fq 'FROM caddy:2.11.9-alpine@sha256:003a97808e781aa9f7e75cc2f43d34d461099031faf5e20faefb9f61126836f0' <<< "$out" -grep -Fq 'image: xmesh-sub-limiter:3.12.16-krb5r1' <<< "$out" +# The production installer must not overwrite old mutable local image tags. +grep -Fq 'docker image inspect "$limiter_image"' install.sh +grep -Fq 'docker image inspect "$caddy_image"' install.sh if grep -Eq '^ image: (caddy:2|python:3[.]12-alpine)$' <<< "$out"; then echo 'ERROR: floating legacy image in signed installer' >&2 exit 1 From f95ec3fbca5ba0012d9b810d84be5efd5e1ecb58 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:20:35 +0300 Subject: [PATCH 50/68] test(sub): scan and exercise exact per-revision Docker images from signed installer --- tests/test-runtime-edge.sh | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/test-runtime-edge.sh b/tests/test-runtime-edge.sh index ecb2972..d73bfcf 100644 --- a/tests/test-runtime-edge.sh +++ b/tests/test-runtime-edge.sh @@ -5,6 +5,8 @@ set -Eeuo pipefail cd "$(dirname "$0")/.." [[ $# == 1 && -s "$1/Caddyfile" ]] || { echo 'Missing generated Caddyfile' >&2; exit 1; } source_caddyfile=$1/Caddyfile +caddy_image=${XMESH_SUB_CADDY_IMAGE:-xmesh-sub-caddy:2.11.9-josev4r1} +limiter_image=${XMESH_SUB_LIMITER_IMAGE:-xmesh-sub-limiter:3.12.16-krb5r1} temp=$(mktemp -d) # Disposable non-secret fixtures must be traversable by container uid 65534. # The socket itself remains under a uid-65534 owned, mode-0770 subdirectory. @@ -25,7 +27,7 @@ mkdir -p "$temp/policy" docker volume create "$socket_volume" >/dev/null docker run --rm --user 0 --entrypoint sh \ -v "$socket_volume:/run/xmesh-sub" \ - xmesh-sub-caddy:2.11.9-josev4r1 \ + "$caddy_image" \ -c 'chown 65534:65534 /run/xmesh-sub && chmod 0770 /run/xmesh-sub' printf '%s\n' '{"enabled":true,"mode":"protect","ipPerMinute":1}' > "$temp/policy/config.json" chmod 0644 "$temp/policy/config.json" @@ -58,7 +60,7 @@ docker run -d --name "$limiter_name" --network none \ -v "$socket_volume:/run/xmesh-sub" \ -v "$temp/policy:/etc/xmesh-sub/policy:ro" \ -v "$PWD/limiter.py:/opt/limiter.py:ro" \ - xmesh-sub-limiter:3.12.16-krb5r1 python3 -I /opt/limiter.py >/dev/null + "$limiter_image" python3 -I /opt/limiter.py >/dev/null for ((attempt=0; attempt<60; attempt++)); do docker exec "$limiter_name" test -S /run/xmesh-sub/rate.sock >/dev/null 2>&1 && break sleep 0.2 @@ -80,7 +82,7 @@ docker run -d --name "$caddy_name" --network bridge \ -p '127.0.0.1::8080' \ -v "$temp/Caddyfile:/etc/caddy/Caddyfile:ro" \ -v "$socket_volume:/run/xmesh-sub:ro" \ - xmesh-sub-caddy:2.11.9-josev4r1 caddy run --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null + "$caddy_image" caddy run --config /etc/caddy/Caddyfile --adapter caddyfile >/dev/null address=$(docker port "$caddy_name" 8080/tcp | head -n 1) [[ "$address" =~ ^127[.]0[.]0[.]1:[0-9]+$ ]] || { echo 'Unexpected local-only Caddy binding' >&2; exit 1; } From 9654a18f20dc0e858a69a5227ecde192f8f0c8a2 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:20:38 +0300 Subject: [PATCH 51/68] test(sub): scan and exercise exact per-revision Docker images from signed installer --- tests/test-image-rollback.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/test-image-rollback.py b/tests/test-image-rollback.py index 3208bc7..c8071f0 100644 --- a/tests/test-image-rollback.py +++ b/tests/test-image-rollback.py @@ -6,6 +6,7 @@ """ import importlib.util import json +import os from pathlib import Path import subprocess import tempfile @@ -41,9 +42,9 @@ def main(): root = Path(directory) compose = root / "compose.yaml" try: - docker("image", "tag", "xmesh-sub-caddy:2.11.9-josev4r1", original_caddy) + docker("image", "tag", os.environ.get("XMESH_SUB_CADDY_IMAGE", "xmesh-sub-caddy:2.11.9-josev4r1"), original_caddy) created.append(original_caddy) - docker("image", "tag", "xmesh-sub-limiter:3.12.16-krb5r1", original_limiter) + docker("image", "tag", os.environ.get("XMESH_SUB_LIMITER_IMAGE", "xmesh-sub-limiter:3.12.16-krb5r1"), original_limiter) created.append(original_limiter) caddy_image = docker("image", "inspect", "--format", "{{.Id}}", original_caddy) limiter_image = docker("image", "inspect", "--format", "{{.Id}}", original_limiter) From 820d0b4cd21c3ab1e74c91cbadfa72f8505303cd Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:20:41 +0300 Subject: [PATCH 52/68] test(sub): scan and exercise exact per-revision Docker images from signed installer --- .github/workflows/image-security.yml | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index cf6905a..2d28f0d 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -43,7 +43,7 @@ jobs: import os, pathlib, re compose=pathlib.Path(os.environ["RUNNER_TEMP"],"compose.yaml").read_text() refs=re.findall(r"^\s+image:\s+(\S+)\s*$",compose,re.M) - allowed=("xmesh-sub-limiter:3.12.16-krb5r1","xmesh-sub-caddy:2.11.9-josev4r1") + allowed=("xmesh-sub-limiter:rev-0000000000000000000000000000000000000000","xmesh-sub-caddy:rev-0000000000000000000000000000000000000000") if len(refs)!=2 or set(refs)!=set(allowed): raise SystemExit(f"Unexpected installer runtime images: {refs}") pathlib.Path(os.environ["RUNNER_TEMP"],"image-refs.txt").write_text("\n".join(refs)+"\n") @@ -66,19 +66,19 @@ jobs: mkdir -p "$RUNNER_TEMP/limiter-build" "$RUNNER_TEMP/caddy-build" cp "$RUNNER_TEMP/Dockerfile.limiter" "$RUNNER_TEMP/limiter-build/Dockerfile" cp "$RUNNER_TEMP/Dockerfile.caddy" "$RUNNER_TEMP/caddy-build/Dockerfile" - docker build --pull --platform linux/${{ matrix.arch }} --tag xmesh-sub-limiter:3.12.16-krb5r1 "$RUNNER_TEMP/limiter-build" - docker build --pull --platform linux/${{ matrix.arch }} --tag xmesh-sub-caddy:2.11.9-josev4r1 "$RUNNER_TEMP/caddy-build" + docker build --pull --platform linux/${{ matrix.arch }} --tag xmesh-sub-limiter:rev-0000000000000000000000000000000000000000 "$RUNNER_TEMP/limiter-build" + docker build --pull --platform linux/${{ matrix.arch }} --tag xmesh-sub-caddy:rev-0000000000000000000000000000000000000000 "$RUNNER_TEMP/caddy-build" { docker image inspect --format '{{index .RepoDigests 0}}' caddy:2.11.9-alpine docker image inspect --format '{{index .RepoDigests 0}}' python:3.12.16-alpine3.24 - docker image inspect --format '{{.Id}}' xmesh-sub-limiter:3.12.16-krb5r1 - docker image inspect --format '{{.Id}}' xmesh-sub-caddy:2.11.9-josev4r1 + docker image inspect --format '{{.Id}}' xmesh-sub-limiter:rev-0000000000000000000000000000000000000000 + docker image inspect --format '{{.Id}}' xmesh-sub-caddy:rev-0000000000000000000000000000000000000000 } | tee "$RUNNER_TEMP/image-digests.txt" - docker run --rm -v "$RUNNER_TEMP/sub-dry-run:/tmp/ignore:ro" xmesh-sub-caddy:2.11.9-josev4r1 caddy version + docker run --rm -v "$RUNNER_TEMP/sub-dry-run:/tmp/ignore:ro" xmesh-sub-caddy:rev-0000000000000000000000000000000000000000 caddy version sed -n '/^# Caddyfile$/,/^# compose.yaml$/p' "$RUNNER_TEMP/sub-dry-run" | sed '1d;$d' > "$RUNNER_TEMP/Caddyfile" test -s "$RUNNER_TEMP/Caddyfile" - docker run --rm -v "$RUNNER_TEMP/Caddyfile:/etc/caddy/Caddyfile:ro" xmesh-sub-caddy:2.11.9-josev4r1 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile - docker run --rm xmesh-sub-caddy:2.11.9-josev4r1 caddy build-info > "$RUNNER_TEMP/caddy-build-info.txt" + docker run --rm -v "$RUNNER_TEMP/Caddyfile:/etc/caddy/Caddyfile:ro" xmesh-sub-caddy:rev-0000000000000000000000000000000000000000 caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile + docker run --rm xmesh-sub-caddy:rev-0000000000000000000000000000000000000000 caddy build-info > "$RUNNER_TEMP/caddy-build-info.txt" if grep -Fq 'github.com/go-jose/go-jose/v3' "$RUNNER_TEMP/caddy-build-info.txt"; then echo 'Unexpected vulnerable JOSE-v3 dependency in final Caddy build' >&2 exit 1 @@ -86,10 +86,14 @@ jobs: grep -Fq 'github.com/go-jose/go-jose/v4' "$RUNNER_TEMP/caddy-build-info.txt" || { echo 'Expected patched JOSE-v4 missing' >&2; exit 1; } - name: Exercise real Caddy and Unix limiter against spoofed client headers shell: bash - run: bash tests/test-runtime-edge.sh "$RUNNER_TEMP" + run: | + XMESH_SUB_CADDY_IMAGE=xmesh-sub-caddy:rev-0000000000000000000000000000000000000000 XMESH_SUB_LIMITER_IMAGE=xmesh-sub-limiter:rev-0000000000000000000000000000000000000000 \ + bash tests/test-runtime-edge.sh "$RUNNER_TEMP" - name: Recover exact old Docker image IDs after simulated broken upgrade shell: bash - run: python3 tests/test-image-rollback.py + run: | + XMESH_SUB_CADDY_IMAGE=xmesh-sub-caddy:rev-0000000000000000000000000000000000000000 XMESH_SUB_LIMITER_IMAGE=xmesh-sub-limiter:rev-0000000000000000000000000000000000000000 \ + python3 tests/test-image-rollback.py - name: Install pinned and checksum-verified Trivy v0.76.2 env: TRIVY_ARCH: ${{ matrix.arch }} @@ -130,9 +134,9 @@ jobs: run: | set -Eeuo pipefail "$RUNNER_TEMP/trivy" image --scanners vuln --format json \ - --output "$RUNNER_TEMP/caddy-vulnerabilities.json" --no-progress xmesh-sub-caddy:2.11.9-josev4r1 + --output "$RUNNER_TEMP/caddy-vulnerabilities.json" --no-progress xmesh-sub-caddy:rev-0000000000000000000000000000000000000000 "$RUNNER_TEMP/trivy" image --scanners vuln --format json \ - --output "$RUNNER_TEMP/limiter-vulnerabilities.json" --no-progress xmesh-sub-limiter:3.12.16-krb5r1 + --output "$RUNNER_TEMP/limiter-vulnerabilities.json" --no-progress xmesh-sub-limiter:rev-0000000000000000000000000000000000000000 - name: Preserve evidence including any unresolved advisories if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 From 6c2949fd804fa24fad54f418ec370e1c82ab9215 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:21:29 +0300 Subject: [PATCH 53/68] test(sub): satisfy shellcheck for literal immutable-image installer guards --- tests/test-install.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tests/test-install.sh b/tests/test-install.sh index 963afab..b5ce3bd 100644 --- a/tests/test-install.sh +++ b/tests/test-install.sh @@ -42,7 +42,9 @@ grep -Fq 'go.step.sm/crypto@v0.92.0' <<< "$out" grep -Fq 'golang.org/x/net@v0.62.0' <<< "$out" grep -Fq 'FROM caddy:2.11.9-alpine@sha256:003a97808e781aa9f7e75cc2f43d34d461099031faf5e20faefb9f61126836f0' <<< "$out" # The production installer must not overwrite old mutable local image tags. +# shellcheck disable=SC2016 # Literal installer source assertion, not interpolation. grep -Fq 'docker image inspect "$limiter_image"' install.sh +# shellcheck disable=SC2016 grep -Fq 'docker image inspect "$caddy_image"' install.sh if grep -Eq '^ image: (caddy:2|python:3[.]12-alpine)$' <<< "$out"; then echo 'ERROR: floating legacy image in signed installer' >&2 From 242c95e4821a1586f8367f24f9456df2be95f442 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:22:11 +0300 Subject: [PATCH 54/68] security(sub): automatic first-upgrade rollback for old managers using preserved image tags --- install.sh | 78 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 76 insertions(+), 2 deletions(-) diff --git a/install.sh b/install.sh index 5c2de5c..15aa7bc 100644 --- a/install.sh +++ b/install.sh @@ -458,7 +458,44 @@ if [[ ! -e "$ROOT/edge-policy/config.json" ]]; then chmod 644 "$ROOT/edge-policy/config.json" fi temp=$(mktemp -d "$ROOT/.install.XXXXXXXX") -trap 'rm -rf "$temp"' EXIT +existing_install=0 +install_mutated=0 +# The first updater may be a PRE-remediation manager, which does not know how +# to save images/configuration. The signed INSTALLER must protect that upgrade. +# Rollback data contains private keys: the entire staging directory is 0700. +installer_exit() { + local status=$1 name + trap - EXIT + if ((status != 0 && existing_install == 1 && install_mutated == 1)); then + printf 'XMesh Sub: update failed; restoring previous gateway deployment\n' >&2 + set +e + for name in Caddyfile compose.yaml Dockerfile.limiter Dockerfile.caddy limiter.py manager.py release_verify.py RELEASE_SHA VERSION agent-key.pem manager.json; do + if [[ -f "$temp/previous/$name" ]]; then + cp -p -- "$temp/previous/$name" "$ROOT/$name" || + printf 'XMesh Sub: rollback ERROR restoring %s\n' "$name" >&2 + elif [[ -f "$temp/previous/.absent-$name" ]]; then + rm -f -- "$ROOT/$name" || + printf 'XMesh Sub: rollback ERROR removing %s\n' "$name" >&2 + fi + done + if [[ -f "$temp/previous/xmesh-sub-manager.service" ]]; then + cp -p -- "$temp/previous/xmesh-sub-manager.service" /etc/systemd/system/xmesh-sub-manager.service + elif [[ -f "$temp/previous/.absent-xmesh-sub-manager.service" ]]; then + rm -f /etc/systemd/system/xmesh-sub-manager.service + fi + systemctl daemon-reload + if ! (cd "$ROOT" && docker compose up -d --no-build --force-recreate --remove-orphans); then + printf 'XMesh Sub: CRITICAL: automatic gateway rollback failed; inspect the original Compose deployment\n' >&2 + fi + if ((SKIP_MANAGER_RESTART == 0)) && [[ -f /etc/systemd/system/xmesh-sub-manager.service ]]; then + systemctl restart xmesh-sub-manager.service || + printf 'XMesh Sub: rollback WARN: manager service could not restart\n' >&2 + fi + fi + rm -rf -- "$temp" + exit "$status" +} +trap 'installer_exit "$?"' EXIT render_caddyfile >"$temp/Caddyfile" render_compose >"$temp/compose.yaml" render_limiter >"$temp/limiter.py" @@ -576,6 +613,42 @@ if ! docker image inspect "$caddy_image" >/dev/null 2>&1; then fi docker run --rm -v "$temp/Caddyfile:/etc/caddy/Caddyfile:ro" "$caddy_image" caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile || die "Gateway configuration invalid, existing deployment unchanged" +# Capture ALL existing configuration before touching live files. In +# particular, the old manager cannot be relied upon to perform this backup. +# Old images are preserved by revision-specific tags; verify they still exist. +if [[ -f "$ROOT/compose.yaml" ]]; then + previous_images=$(docker compose -f "$ROOT/compose.yaml" config --images) || + die "Could not inspect old Compose image references; leaving deployment unchanged" + [[ -n "$previous_images" ]] || + die "Old Compose has no restorable image references" + image_count=0 + while IFS= read -r old_ref; do + [[ -n "$old_ref" && "$old_ref" != *[[:space:]]* ]] || + die "Invalid old image reference; leaving deployment unchanged" + docker image inspect "$old_ref" >/dev/null 2>&1 || + die "Old gateway image is missing; refusing unsafe first upgrade" + ((image_count+=1)) + ((image_count<=6)) || die "Unexpected original gateway image inventory" + done <<< "$previous_images" + mkdir -m 700 "$temp/previous" + for name in Caddyfile compose.yaml Dockerfile.limiter Dockerfile.caddy limiter.py manager.py release_verify.py RELEASE_SHA VERSION agent-key.pem manager.json; do + if [[ -f "$ROOT/$name" ]]; then + cp -p -- "$ROOT/$name" "$temp/previous/$name" || + die "Unable to snapshot old gateway file" + else + : > "$temp/previous/.absent-$name" + fi + done + if [[ -f /etc/systemd/system/xmesh-sub-manager.service ]]; then + cp -p /etc/systemd/system/xmesh-sub-manager.service "$temp/previous/xmesh-sub-manager.service" + else + : > "$temp/previous/.absent-xmesh-sub-manager.service" + fi + existing_install=1 +fi +# From this point onward, failure restores both the old files and the old +# Docker containers. This also covers upgrades launched by OLD managers. +install_mutated=1 [[ ! -f "$ROOT/Caddyfile" ]] || cp -p "$ROOT/Caddyfile" "$ROOT/Caddyfile.previous" install -m 600 "$temp/Caddyfile" "$ROOT/Caddyfile" install -m 600 "$temp/compose.yaml" "$ROOT/compose.yaml" @@ -583,7 +656,8 @@ install -m 644 "$temp/Dockerfile.limiter" "$ROOT/Dockerfile.limiter" install -m 644 "$temp/Dockerfile.caddy" "$ROOT/Dockerfile.caddy" install -m 644 "$temp/limiter.py" "$ROOT/limiter.py" cd "$ROOT" -docker compose pull --ignore-buildable +# Both images were built locally from the verified installer. Do not pull +# arbitrary remote tags before activating this attested revision. docker compose up -d --no-build --remove-orphans if [[ -n "$ENROLL_TOKEN" ]]; then # Fresh Ed25519 identity is generated on the Sub VPS. Only the public From c4df2b69f432e3ea34cea968eca5155046414c9e Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:22:39 +0300 Subject: [PATCH 55/68] testability(sub): keep manager unit path fixed but isolate it in rollback harness --- install.sh | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/install.sh b/install.sh index 15aa7bc..d28b033 100644 --- a/install.sh +++ b/install.sh @@ -458,6 +458,7 @@ if [[ ! -e "$ROOT/edge-policy/config.json" ]]; then chmod 644 "$ROOT/edge-policy/config.json" fi temp=$(mktemp -d "$ROOT/.install.XXXXXXXX") +SERVICE_UNIT=/etc/systemd/system/xmesh-sub-manager.service existing_install=0 install_mutated=0 # The first updater may be a PRE-remediation manager, which does not know how @@ -479,15 +480,15 @@ installer_exit() { fi done if [[ -f "$temp/previous/xmesh-sub-manager.service" ]]; then - cp -p -- "$temp/previous/xmesh-sub-manager.service" /etc/systemd/system/xmesh-sub-manager.service + cp -p -- "$temp/previous/xmesh-sub-manager.service" $SERVICE_UNIT elif [[ -f "$temp/previous/.absent-xmesh-sub-manager.service" ]]; then - rm -f /etc/systemd/system/xmesh-sub-manager.service + rm -f $SERVICE_UNIT fi systemctl daemon-reload if ! (cd "$ROOT" && docker compose up -d --no-build --force-recreate --remove-orphans); then printf 'XMesh Sub: CRITICAL: automatic gateway rollback failed; inspect the original Compose deployment\n' >&2 fi - if ((SKIP_MANAGER_RESTART == 0)) && [[ -f /etc/systemd/system/xmesh-sub-manager.service ]]; then + if ((SKIP_MANAGER_RESTART == 0)) && [[ -f $SERVICE_UNIT ]]; then systemctl restart xmesh-sub-manager.service || printf 'XMesh Sub: rollback WARN: manager service could not restart\n' >&2 fi @@ -639,8 +640,8 @@ if [[ -f "$ROOT/compose.yaml" ]]; then : > "$temp/previous/.absent-$name" fi done - if [[ -f /etc/systemd/system/xmesh-sub-manager.service ]]; then - cp -p /etc/systemd/system/xmesh-sub-manager.service "$temp/previous/xmesh-sub-manager.service" + if [[ -f $SERVICE_UNIT ]]; then + cp -p $SERVICE_UNIT "$temp/previous/xmesh-sub-manager.service" else : > "$temp/previous/.absent-xmesh-sub-manager.service" fi @@ -753,7 +754,7 @@ SystemCallArchitectures=native [Install] WantedBy=multi-user.target UNIT - install -m 644 "$temp/xmesh-sub-manager.service" /etc/systemd/system/xmesh-sub-manager.service + install -m 644 "$temp/xmesh-sub-manager.service" $SERVICE_UNIT systemctl daemon-reload systemctl enable xmesh-sub-manager.service >/dev/null if ((SKIP_MANAGER_RESTART == 0)); then From d292c82db75551f23029fe9659c8f548c8be2a14 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:23:18 +0300 Subject: [PATCH 56/68] fix(sub): safely quote fixed manager service path in installer rollback --- install.sh | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/install.sh b/install.sh index d28b033..0108a7a 100644 --- a/install.sh +++ b/install.sh @@ -480,15 +480,15 @@ installer_exit() { fi done if [[ -f "$temp/previous/xmesh-sub-manager.service" ]]; then - cp -p -- "$temp/previous/xmesh-sub-manager.service" $SERVICE_UNIT + cp -p -- "$temp/previous/xmesh-sub-manager.service" "$SERVICE_UNIT" elif [[ -f "$temp/previous/.absent-xmesh-sub-manager.service" ]]; then - rm -f $SERVICE_UNIT + rm -f "$SERVICE_UNIT" fi systemctl daemon-reload if ! (cd "$ROOT" && docker compose up -d --no-build --force-recreate --remove-orphans); then printf 'XMesh Sub: CRITICAL: automatic gateway rollback failed; inspect the original Compose deployment\n' >&2 fi - if ((SKIP_MANAGER_RESTART == 0)) && [[ -f $SERVICE_UNIT ]]; then + if ((SKIP_MANAGER_RESTART == 0)) && [[ -f "$SERVICE_UNIT" ]]; then systemctl restart xmesh-sub-manager.service || printf 'XMesh Sub: rollback WARN: manager service could not restart\n' >&2 fi @@ -640,8 +640,8 @@ if [[ -f "$ROOT/compose.yaml" ]]; then : > "$temp/previous/.absent-$name" fi done - if [[ -f $SERVICE_UNIT ]]; then - cp -p $SERVICE_UNIT "$temp/previous/xmesh-sub-manager.service" + if [[ -f "$SERVICE_UNIT" ]]; then + cp -p "$SERVICE_UNIT" "$temp/previous/xmesh-sub-manager.service" else : > "$temp/previous/.absent-xmesh-sub-manager.service" fi @@ -754,7 +754,7 @@ SystemCallArchitectures=native [Install] WantedBy=multi-user.target UNIT - install -m 644 "$temp/xmesh-sub-manager.service" $SERVICE_UNIT + install -m 644 "$temp/xmesh-sub-manager.service" "$SERVICE_UNIT" systemctl daemon-reload systemctl enable xmesh-sub-manager.service >/dev/null if ((SKIP_MANAGER_RESTART == 0)); then From 46ce9737af6af6d8d1f6dad13603470024ede9ee Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:24:02 +0300 Subject: [PATCH 57/68] test(sub): prove legacy-manager first update rolls back real old Docker images and secrets --- tests/test-first-upgrade-rollback.py | 154 +++++++++++++++++++++++++++ 1 file changed, 154 insertions(+) create mode 100644 tests/test-first-upgrade-rollback.py diff --git a/tests/test-first-upgrade-rollback.py b/tests/test-first-upgrade-rollback.py new file mode 100644 index 0000000..b8d6abb --- /dev/null +++ b/tests/test-first-upgrade-rollback.py @@ -0,0 +1,154 @@ +#!/usr/bin/env python3 +"""Real Docker proof of an old-manager FIRST upgrade and installer rollback. + +The old manager cannot save image IDs. Exercise the literal backup and EXIT +rollback functions extracted from the signed install.sh, with a disposable +Compose project and private dummy files. Production /opt and systemd untouched. +""" +import os +from pathlib import Path +import re +import shlex +import subprocess +import tempfile +import uuid + +HERE = Path(__file__).resolve().parent.parent +INSTALL = (HERE / "install.sh").read_text() +SNAP_START = "# Capture ALL existing configuration before touching live files." +SNAP_END = "# From this point onward, failure restores both the old files" +OLD_CADDY = os.environ.get("XMESH_SUB_CADDY_IMAGE", "xmesh-sub-caddy:2.11.9-josev4r1") +OLD_LIMITER = os.environ.get("XMESH_SUB_LIMITER_IMAGE", "xmesh-sub-limiter:3.12.16-krb5r1") + + +def docker(*args, cwd=None): + return subprocess.run(["docker", *args], check=True, capture_output=True, + text=True, timeout=90, cwd=cwd).stdout.strip() + + +def image_for(root, service): + cid = docker("compose", "-f", str(root / "compose.yaml"), "ps", "-q", service) + if not cid: + raise AssertionError(f"Missing running service: {service}") + return docker("inspect", "--format", "{{.Image}}", cid) + + +def compose_image(caddy, limiter): + # Two running process containers, but no real public listening ports. + return ( + f"services:\n" + f" xmesh-sub:\n" + f" image: {caddy}\n" + f" pull_policy: never\n" + f" entrypoint: ['sh', '-c', 'sleep 300']\n" + f" command: []\n" + f" xmesh-sub-limiter:\n" + f" image: {limiter}\n" + f" pull_policy: never\n" + f" entrypoint: ['sh', '-c', 'sleep 300']\n" + f" command: []\n" + ) + + +def main(): + assert INSTALL.count(SNAP_START) == INSTALL.count(SNAP_END) == 1 + before = INSTALL.split(SNAP_START, 1)[1].split(SNAP_END, 1)[0] + rollback = re.search(r"(?ms)^installer_exit\(\) \{.*?^\}$", INSTALL) + assert rollback, "Signed installer EXIT rollback function missing" + assert 'docker compose up -d --no-build --force-recreate --remove-orphans' in rollback.group() + assert "sub_caddy_image()" in INSTALL and "sub_limiter_image()" in INSTALL + assert 'if ! docker image inspect "$caddy_image"' in INSTALL + + suffix = uuid.uuid4().hex[:12] + old_caddy = f"xmesh-sub-old-caddy:{suffix}" + old_limiter = f"xmesh-sub-old-limiter:{suffix}" + new_caddy = f"xmesh-sub-caddy:rev-{'a' * 40}" + new_limiter = f"xmesh-sub-limiter:rev-{'a' * 40}" + created = [old_caddy, old_limiter, new_caddy, new_limiter] + with tempfile.TemporaryDirectory(prefix="xmesh-sub-first-upgrade-") as directory: + root = Path(directory) + temp = root / "staging" + temp.mkdir(mode=0o700) + service = root / "manager-unit.service" + bin_dir = root / "mock-bin" + bin_dir.mkdir() + script = bin_dir / "systemctl" + script.write_text("#!/bin/sh\nexit 0\n") + script.chmod(0o700) + try: + # Old image refs and IDs exist before the first signed new install. + docker("image", "tag", OLD_CADDY, old_caddy) + docker("image", "tag", OLD_LIMITER, old_limiter) + expected = { + "xmesh-sub": docker("image", "inspect", "--format", "{{.Id}}", old_caddy), + "xmesh-sub-limiter": docker("image", "inspect", "--format", "{{.Id}}", old_limiter), + } + assert len(set(expected.values())) == 2 + + # New revision tags deliberately point to the *opposite* binaries. + # An old manager that overwrites old tags cannot safely recover. + docker("image", "tag", OLD_LIMITER, new_caddy) + docker("image", "tag", OLD_CADDY, new_limiter) + (root / "compose.yaml").write_text(compose_image(old_caddy, old_limiter)) + (root / "VERSION").write_text("0.1.0\n") + (root / "manager.json").write_text('{"dummy":"secret"}\n') + (root / "manager.json").chmod(0o600) + service.write_text("original systemd unit\n") + docker("compose", "-f", str(root / "compose.yaml"), "up", "-d", "--no-build") + for name, old_id in expected.items(): + assert image_for(root, name) == old_id + + mutated_compose = root / "new-compose.fixture" + mutated_compose.write_text(compose_image(new_caddy, new_limiter)) + test = ( + "set -Eeuo pipefail\n" + f"ROOT={shlex.quote(str(root))}\n" + f"temp={shlex.quote(str(temp))}\n" + f"SERVICE_UNIT={shlex.quote(str(service))}\n" + "SKIP_MANAGER_RESTART=1\n" + "existing_install=0\n" + "install_mutated=0\n" + + rollback.group() + "\n" + + SNAP_START + "\n" + before + "\n" + "test \"$existing_install\" = 1\n" + "install_mutated=1\n" + "trap 'installer_exit \"$?\"' EXIT\n" + "printf 'BROKEN\\n' > \"$ROOT/VERSION\"\n" + "printf 'BROKEN\\n' > \"$ROOT/manager.json\"\n" + "printf 'BROKEN\\n' > \"$SERVICE_UNIT\"\n" + f"cp {shlex.quote(str(mutated_compose))} \"$ROOT/compose.yaml\"\n" + "docker compose -f \"$ROOT/compose.yaml\" up -d --no-build --force-recreate\n" + "exit 51\n" + ) + env = dict(os.environ, PATH=str(bin_dir) + ":" + os.environ["PATH"]) + result = subprocess.run(["bash", "-c", test], cwd=root, env=env, + capture_output=True, text=True, timeout=120) + if result.returncode != 51: + raise AssertionError("Installer rollback did not preserve injected error " + + str(result.returncode) + "\n" + result.stderr[-5000:]) + assert "restoring previous gateway deployment" in result.stderr + assert (root / "VERSION").read_text() == "0.1.0\n" + assert (root / "manager.json").read_text() == '{"dummy":"secret"}\n' + assert (root / "manager.json").stat().st_mode & 0o777 == 0o600 + assert service.read_text() == "original systemd unit\n" + assert (root / "compose.yaml").read_text() == compose_image(old_caddy, old_limiter) + for name, old_id in expected.items(): + assert image_for(root, name) == old_id, (name, old_id) + assert not temp.exists(), "Private rollback staging directory not cleaned" + # Installing another SHA must never change the identity of a + # previous revision's Docker tag. + assert docker("image", "inspect", "--format", "{{.Id}}", old_caddy) == expected["xmesh-sub"] + assert docker("image", "inspect", "--format", "{{.Id}}", old_limiter) == expected["xmesh-sub-limiter"] + print("PASS: real old-manager first-upgrade rollback restores files, " + "manager settings and both original running Docker images") + finally: + if (root / "compose.yaml").exists(): + subprocess.run(["docker", "compose", "-f", str(root / "compose.yaml"), + "down", "--remove-orphans"], capture_output=True, timeout=60) + for tag in created: + subprocess.run(["docker", "image", "rm", tag], + capture_output=True, timeout=20) + + +if __name__ == "__main__": + main() From 25481ac670d32bcc6fc0ba1306e3ab0ba1422899 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:24:19 +0300 Subject: [PATCH 58/68] ci(sub): require legacy first-upgrade real Docker rollback proof before signed release --- .github/workflows/image-security.yml | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml index 2d28f0d..d3711a5 100644 --- a/.github/workflows/image-security.yml +++ b/.github/workflows/image-security.yml @@ -6,6 +6,7 @@ on: - 'tests/test-install.sh' - 'tests/test-runtime-edge.sh' - 'tests/test-image-rollback.py' + - 'tests/test-first-upgrade-rollback.py' - '.github/workflows/image-security.yml' - '.github/workflows/ci.yml' - '.github/workflows/attested-release.yml' @@ -94,6 +95,11 @@ jobs: run: | XMESH_SUB_CADDY_IMAGE=xmesh-sub-caddy:rev-0000000000000000000000000000000000000000 XMESH_SUB_LIMITER_IMAGE=xmesh-sub-limiter:rev-0000000000000000000000000000000000000000 \ python3 tests/test-image-rollback.py + - name: Prove first-ever upgrade rollback with legacy manager and real containers + shell: bash + run: | + XMESH_SUB_CADDY_IMAGE=xmesh-sub-caddy:rev-0000000000000000000000000000000000000000 XMESH_SUB_LIMITER_IMAGE=xmesh-sub-limiter:rev-0000000000000000000000000000000000000000 \ + python3 tests/test-first-upgrade-rollback.py - name: Install pinned and checksum-verified Trivy v0.76.2 env: TRIVY_ARCH: ${{ matrix.arch }} From 490d46d9ecbb6d6838b6b11db4cb16c67b018b38 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:24:23 +0300 Subject: [PATCH 59/68] ci(sub): require legacy first-upgrade real Docker rollback proof before signed release --- .github/workflows/ci.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8f89083..ea4effb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: bash tests/test-bootstrap.sh - name: Outbound signed agent and edge IP limiter tests run: | - python3 -m py_compile manager.py limiter.py tests/test-image-rollback.py + python3 -m py_compile manager.py limiter.py tests/test-image-rollback.py tests/test-first-upgrade-rollback.py python3 tests/test-manager.py python3 tests/test-limiter.py - name: Validate rendered Caddy configuration From 6afb8141c704444583f5114a115389344208fa7b Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:27:33 +0300 Subject: [PATCH 60/68] test(sub): extract complete installer backup shell block without splitting comment line --- tests/test-first-upgrade-rollback.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test-first-upgrade-rollback.py b/tests/test-first-upgrade-rollback.py index b8d6abb..5c1901e 100644 --- a/tests/test-first-upgrade-rollback.py +++ b/tests/test-first-upgrade-rollback.py @@ -15,7 +15,7 @@ HERE = Path(__file__).resolve().parent.parent INSTALL = (HERE / "install.sh").read_text() -SNAP_START = "# Capture ALL existing configuration before touching live files." +SNAP_START = "# Old images are preserved by revision-specific tags; verify they still exist.\n" SNAP_END = "# From this point onward, failure restores both the old files" OLD_CADDY = os.environ.get("XMESH_SUB_CADDY_IMAGE", "xmesh-sub-caddy:2.11.9-josev4r1") OLD_LIMITER = os.environ.get("XMESH_SUB_LIMITER_IMAGE", "xmesh-sub-limiter:3.12.16-krb5r1") From ad1285a5a7f2ba748c55f27f023b59b51b2da442 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:42:38 +0300 Subject: [PATCH 61/68] test(sub): assert legacy subscriber HTTPS survives first-upgrade rollback --- tests/test-first-upgrade-rollback.py | 82 +++++++++++++++++++++++++--- 1 file changed, 74 insertions(+), 8 deletions(-) diff --git a/tests/test-first-upgrade-rollback.py b/tests/test-first-upgrade-rollback.py index 5c1901e..2957f9c 100644 --- a/tests/test-first-upgrade-rollback.py +++ b/tests/test-first-upgrade-rollback.py @@ -11,6 +11,7 @@ import shlex import subprocess import tempfile +import time import uuid HERE = Path(__file__).resolve().parent.parent @@ -33,15 +34,28 @@ def image_for(root, service): return docker("inspect", "--format", "{{.Image}}", cid) -def compose_image(caddy, limiter): - # Two running process containers, but no real public listening ports. +def compose_image(caddy, limiter, *, https_gateway=False): + # Only loopback's random host port is exposed to CI. The legacy gateway + # serves real TLS using Caddy's *local* CA, never public ACME/DNS. + gateway = ( + " entrypoint: ['caddy', 'run', '--config', '/etc/caddy/Caddyfile', '--adapter', 'caddyfile']\n" + " command: []\n" + " ports:\n" + " - '127.0.0.1::8443'\n" + " volumes:\n" + " - ./Caddyfile:/etc/caddy/Caddyfile:ro\n" + " - ./caddy-data:/data\n" + " - ./caddy-config:/config\n" + ) if https_gateway else ( + " entrypoint: ['sh', '-c', 'sleep 300']\n" + " command: []\n" + ) return ( f"services:\n" f" xmesh-sub:\n" f" image: {caddy}\n" f" pull_policy: never\n" - f" entrypoint: ['sh', '-c', 'sleep 300']\n" - f" command: []\n" + + gateway + f" xmesh-sub-limiter:\n" f" image: {limiter}\n" f" pull_policy: never\n" @@ -50,6 +64,51 @@ def compose_image(caddy, limiter): ) +LEGACY_CADDYFILE = """https://localhost:8443 { + tls internal + handle /healthz { + respond "ok" 200 + } + handle /s/* { + respond "legacy-subscriber" 200 + } + handle /portal/* { + respond "legacy-portal" 200 + } + handle { + respond "Not Found" 404 + } +} +""" + + +def assert_legacy_https(root): + """Check real TLS on loopback before and after forced recreation/rollback.""" + cid = docker("compose", "-f", str(root / "compose.yaml"), "ps", "-q", "xmesh-sub") + binding = docker("port", cid, "8443/tcp").splitlines() + if len(binding) != 1 or not re.fullmatch(r"127\.0\.0\.1:[0-9]+", binding[0]): + raise AssertionError(f"TLS gateway escaped loopback: {binding!r}") + host_port = binding[0].split(":")[-1] + for suffix, expected in (("/healthz", "ok"), ("/s/" + "a" * 64, "legacy-subscriber"), + ("/portal/" + "b" * 64, "legacy-portal")): + command = [ + "curl", "--noproxy", "*", "--insecure", "--fail", "--silent", + "--show-error", "--max-time", "2", "--connect-to", + f"localhost:8443:127.0.0.1:{host_port}", + "https://localhost:8443" + suffix, + ] + for attempt in range(60): + result = subprocess.run(command, capture_output=True, text=True, timeout=4) + if result.returncode == 0 and result.stdout.strip() == expected: + break + time.sleep(0.25) + else: + raise AssertionError( + f"Legacy HTTPS {suffix} was not restored: rc={result.returncode}, " + f"body={result.stdout!r}, stderr={result.stderr[-1000:]!r}" + ) + + def main(): assert INSTALL.count(SNAP_START) == INSTALL.count(SNAP_END) == 1 before = INSTALL.split(SNAP_START, 1)[1].split(SNAP_END, 1)[0] @@ -89,7 +148,9 @@ def main(): # An old manager that overwrites old tags cannot safely recover. docker("image", "tag", OLD_LIMITER, new_caddy) docker("image", "tag", OLD_CADDY, new_limiter) - (root / "compose.yaml").write_text(compose_image(old_caddy, old_limiter)) + (root / "Caddyfile").write_text(LEGACY_CADDYFILE) + (root / "compose.yaml").write_text( + compose_image(old_caddy, old_limiter, https_gateway=True)) (root / "VERSION").write_text("0.1.0\n") (root / "manager.json").write_text('{"dummy":"secret"}\n') (root / "manager.json").chmod(0o600) @@ -97,6 +158,7 @@ def main(): docker("compose", "-f", str(root / "compose.yaml"), "up", "-d", "--no-build") for name, old_id in expected.items(): assert image_for(root, name) == old_id + assert_legacy_https(root) mutated_compose = root / "new-compose.fixture" mutated_compose.write_text(compose_image(new_caddy, new_limiter)) @@ -114,6 +176,7 @@ def main(): "install_mutated=1\n" "trap 'installer_exit \"$?\"' EXIT\n" "printf 'BROKEN\\n' > \"$ROOT/VERSION\"\n" + "printf 'BROKEN\\n' > \"$ROOT/Caddyfile\"\n" "printf 'BROKEN\\n' > \"$ROOT/manager.json\"\n" "printf 'BROKEN\\n' > \"$SERVICE_UNIT\"\n" f"cp {shlex.quote(str(mutated_compose))} \"$ROOT/compose.yaml\"\n" @@ -131,16 +194,19 @@ def main(): assert (root / "manager.json").read_text() == '{"dummy":"secret"}\n' assert (root / "manager.json").stat().st_mode & 0o777 == 0o600 assert service.read_text() == "original systemd unit\n" - assert (root / "compose.yaml").read_text() == compose_image(old_caddy, old_limiter) + assert (root / "Caddyfile").read_text() == LEGACY_CADDYFILE + assert (root / "compose.yaml").read_text() == compose_image( + old_caddy, old_limiter, https_gateway=True) for name, old_id in expected.items(): assert image_for(root, name) == old_id, (name, old_id) + assert_legacy_https(root) assert not temp.exists(), "Private rollback staging directory not cleaned" # Installing another SHA must never change the identity of a # previous revision's Docker tag. assert docker("image", "inspect", "--format", "{{.Id}}", old_caddy) == expected["xmesh-sub"] assert docker("image", "inspect", "--format", "{{.Id}}", old_limiter) == expected["xmesh-sub-limiter"] - print("PASS: real old-manager first-upgrade rollback restores files, " - "manager settings and both original running Docker images") + print("PASS: legacy first-upgrade rollback restores real HTTPS subscriber " + "and portal endpoints, private files and both old Docker image IDs") finally: if (root / "compose.yaml").exists(): subprocess.run(["docker", "compose", "-f", str(root / "compose.yaml"), From 21d8d07565c882fb211fc4a3c125371be94107f5 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 06:46:26 +0300 Subject: [PATCH 62/68] test(sub): use disposable Docker volumes for HTTPS rollback fixture --- tests/test-first-upgrade-rollback.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/test-first-upgrade-rollback.py b/tests/test-first-upgrade-rollback.py index 2957f9c..b1d34eb 100644 --- a/tests/test-first-upgrade-rollback.py +++ b/tests/test-first-upgrade-rollback.py @@ -44,8 +44,8 @@ def compose_image(caddy, limiter, *, https_gateway=False): " - '127.0.0.1::8443'\n" " volumes:\n" " - ./Caddyfile:/etc/caddy/Caddyfile:ro\n" - " - ./caddy-data:/data\n" - " - ./caddy-config:/config\n" + " - caddy-data:/data\n" + " - caddy-config:/config\n" ) if https_gateway else ( " entrypoint: ['sh', '-c', 'sleep 300']\n" " command: []\n" @@ -61,6 +61,7 @@ def compose_image(caddy, limiter, *, https_gateway=False): f" pull_policy: never\n" f" entrypoint: ['sh', '-c', 'sleep 300']\n" f" command: []\n" + + ("volumes:\n caddy-data:\n caddy-config:\n" if https_gateway else "") ) @@ -210,7 +211,7 @@ def main(): finally: if (root / "compose.yaml").exists(): subprocess.run(["docker", "compose", "-f", str(root / "compose.yaml"), - "down", "--remove-orphans"], capture_output=True, timeout=60) + "down", "--volumes", "--remove-orphans"], capture_output=True, timeout=60) for tag in created: subprocess.run(["docker", "image", "rm", tag], capture_output=True, timeout=20) From 0cc804f29e122946d9736de625f842ce05cfe427 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 07:14:41 +0300 Subject: [PATCH 63/68] ci(sub): preserve main token-scoped OIDC verification under multi-arch release gate --- .github/workflows/attested-release.yml | 20 ++++++++++++++------ 1 file changed, 14 insertions(+), 6 deletions(-) diff --git a/.github/workflows/attested-release.yml b/.github/workflows/attested-release.yml index b176962..5b88d74 100644 --- a/.github/workflows/attested-release.yml +++ b/.github/workflows/attested-release.yml @@ -83,11 +83,17 @@ jobs: --deny-self-hosted-runners done - - name: Prove anonymous clean-VPS verification works (no token/login) - # This tests the PUBLIC API + Sigstore bundle fallback used on a VPS. - # The workflow token is deliberately not exposed to this subprocess. + - name: Verify signed release in isolated CLI without anonymous API IP exhaustion + # GitHub-hosted runners share the unauthenticated REST rate limit by + # egress IP (60/hour). Only GET /attestations/sha256:... receives this + # short-lived Actions token; downloaded artifacts and bundles remain + # UNTRUSTED until the same offline signature, certificate identity, + # main ref and exact SHA checks all pass. + # This is NOT an anonymous-network clean-VPS acceptance test. That + # separate deployment gate remains required before a production rollout. env: - GH_CONFIG_DIR: ${{ runner.temp }}/isolated-anonymous-gh + GH_CONFIG_DIR: ${{ runner.temp }}/isolated-release-gh + XMESH_ATTESTATION_INDEX_TOKEN: ${{ github.token }} run: | unset GH_TOKEN GITHUB_TOKEN python3 - <<'PY' @@ -95,7 +101,9 @@ jobs: from pathlib import Path import release_verify with tempfile.TemporaryDirectory() as temp: - files=release_verify.stage_revision(os.environ['GITHUB_SHA'],Path(temp)) + files=release_verify.stage_revision( + os.environ['GITHUB_SHA'], Path(temp), + attestations_read_token=os.environ['XMESH_ATTESTATION_INDEX_TOKEN']) assert set(files)==set(release_verify.FILES) - print('Clean VPS verified all four public release files with no Github login') + print('Verified exact signed release: isolated CLI, offline OIDC proof, scoped API reads') PY From d9b6bcbc448949e971c4249fbb3f8ae082223374 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 07:14:48 +0300 Subject: [PATCH 64/68] fix(sub): carry forward main OIDC API quota protection in release_verify.py --- release_verify.py | 41 +++++++++++++++++++++++++++++------------ 1 file changed, 29 insertions(+), 12 deletions(-) diff --git a/release_verify.py b/release_verify.py index bed92f8..baaf8ef 100644 --- a/release_verify.py +++ b/release_verify.py @@ -8,6 +8,7 @@ import hashlib import json +import os import tempfile from urllib.parse import urlparse from pathlib import Path @@ -32,17 +33,29 @@ def redirect_request(self, req, fp, code, msg, headers, newurl): return None -def fetch_bytes(url: str, limit: int) -> bytes: +def fetch_bytes(url: str, limit: int, *, attestations_read_token: str | None = None) -> bytes: if not url.startswith(("https://api.github.com/", "https://raw.githubusercontent.com/")): raise ValueError("Untrusted source host") opener = urllib.request.build_opener( urllib.request.HTTPSHandler(context=ssl.create_default_context()), NoRedirect(), ) - with opener.open(urllib.request.Request(url, headers={ - "User-Agent": "XMesh-Sub-Release-Verifier/1", - "Accept": "application/vnd.github+json", - }), timeout=25) as reply: + headers = { + "User-Agent": "XMesh-Sub-Release-Verifier/1", + "Accept": "application/vnd.github+json", + } + # GitHub Actions shares its unauthenticated 60/hour IP quota with other + # runners. Its short-lived token can fetch the *public attestation index* + # without granting the attestation any trust. This is never used for raw + # source downloads and never passed to the offline signature verifier. + index_prefix = f"https://api.github.com/repos/{REPO}/attestations/sha256:" + if attestations_read_token is not None: + if not url.startswith(index_prefix) or not attestations_read_token.isascii() or not ( + 1 <= len(attestations_read_token) <= 1024 + ) or any(not (ch.isalnum() or ch in "-_.") for ch in attestations_read_token): + raise ValueError("Invalid attestation index read credential or endpoint") + headers["Authorization"] = "Bearer " + attestations_read_token + with opener.open(urllib.request.Request(url, headers=headers), timeout=25) as reply: data = reply.read(limit + 1) if len(data) > limit: raise ValueError("Oversized release response") @@ -68,7 +81,7 @@ def latest_source_sha() -> str: return sha -def public_bundles(file: Path) -> list[dict]: +def public_bundles(file: Path, *, attestations_read_token: str | None = None) -> list[dict]: """Fetch public Sigstore bundles without a GitHub login or access token. The API response and bundle URLs are untrusted. The actual signature, @@ -76,7 +89,8 @@ def public_bundles(file: Path) -> list[dict]: """ digest = hashlib.sha256(file.read_bytes()).hexdigest() index = json.loads(fetch_bytes( - f"https://api.github.com/repos/{REPO}/attestations/sha256:{digest}", 256 * 1024)) + f"https://api.github.com/repos/{REPO}/attestations/sha256:{digest}", 256 * 1024, + attestations_read_token=attestations_read_token)) entries = index.get("attestations") if isinstance(index, dict) else None if not isinstance(entries, list) or not 1 <= len(entries) <= 30: raise ValueError("No public attestation bundles") @@ -112,11 +126,11 @@ def public_bundles(file: Path) -> list[dict]: return bundles -def verify_file(file: Path, sha: str) -> None: +def verify_file(file: Path, sha: str, *, attestations_read_token: str | None = None) -> None: if not SHA_RE.fullmatch(sha) or not file.is_file() or file.is_symlink(): raise ValueError("Invalid release artifact") ensure_gh() - bundles = public_bundles(file) + bundles = public_bundles(file, attestations_read_token=attestations_read_token) with tempfile.TemporaryDirectory(prefix="xmesh-attestation-") as tmp: path = Path(tmp) / "bundles.jsonl" path.write_text("".join(json.dumps(x, separators=(",", ":")) + "\n" for x in bundles)) @@ -130,9 +144,12 @@ def verify_file(file: Path, sha: str) -> None: "--source-digest", sha, "--deny-self-hosted-runners", ], check=True, timeout=90, stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL) + stderr=subprocess.DEVNULL, + # Even the optional CI GET token must not reach the gh process. + env={key: value for key, value in os.environ.items() + if key not in ("GH_TOKEN", "GITHUB_TOKEN", "XMESH_ATTESTATION_INDEX_TOKEN")}) -def stage_revision(sha: str, directory: Path) -> dict[str, Path]: +def stage_revision(sha: str, directory: Path, *, attestations_read_token: str | None = None) -> dict[str, Path]: if not SHA_RE.fullmatch(sha) or not directory.is_dir() or directory.is_symlink(): raise ValueError("Invalid release staging") result = {} @@ -145,7 +162,7 @@ def stage_revision(sha: str, directory: Path) -> dict[str, Path]: if file.exists() or file.is_symlink(): raise ValueError("Refusing existing release staging target") file.write_bytes(data) - verify_file(file, sha) + verify_file(file, sha, attestations_read_token=attestations_read_token) result[name] = file version = result["VERSION"].read_text("ascii").strip() if not re.fullmatch(r"\d+\.\d+\.\d+", version): From 7a836afa52ea1f1dde8c6691fb6a8cedd9e616a7 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 07:14:50 +0300 Subject: [PATCH 65/68] fix(sub): carry forward main OIDC API quota protection in tests/test-release-verify.py --- tests/test-release-verify.py | 61 ++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/tests/test-release-verify.py b/tests/test-release-verify.py index 6d56e9c..711b79b 100644 --- a/tests/test-release-verify.py +++ b/tests/test-release-verify.py @@ -51,6 +51,67 @@ def test_untrusted_public_bundle_url_is_rejected(self): with self.assertRaises(ValueError): release.public_bundles(file) + def test_ci_token_is_restricted_to_attestation_index_get(self): + index = ("https://api.github.com/repos/" + release.REPO + + "/attestations/sha256:" + "a" * 64) + with patch.object(release.urllib.request, "build_opener") as make_opener: + reply = make_opener.return_value.open.return_value.__enter__.return_value + reply.read.return_value = b'{"attestations":[]}' + self.assertEqual( + release.fetch_bytes(index, 1024, + attestations_read_token="ghs_test-safe_123"), + b'{"attestations":[]}') + req = make_opener.return_value.open.call_args.args[0] + self.assertEqual(req.full_url, index) + self.assertEqual(req.get_header("Authorization"), + "Bearer ghs_test-safe_123") + make_opener.return_value.open.reset_mock() + release.fetch_bytes(index, 1024) + unauthenticated = make_opener.return_value.open.call_args.args[0] + self.assertIsNone(unauthenticated.get_header("Authorization")) + for url in ( + "https://raw.githubusercontent.com/" + release.REPO + "/main/VERSION", + "https://api.github.com/repos/" + release.REPO + "/commits/main", + "http://api.github.com/repos/" + release.REPO + "/attestations/sha256:" + "a" * 64, + ): + with self.assertRaises(ValueError): + release.fetch_bytes(url, 1024, + attestations_read_token="ghs_test-safe_123") + self.assertEqual(make_opener.return_value.open.call_count, 1) + for invalid in ("token with spaces", "bad\r\nInjected: true", ""): + with self.assertRaises(ValueError): + release.fetch_bytes(index, 1024, + attestations_read_token=invalid) + + def test_optional_api_token_never_reaches_offline_verifier(self): + sha = "f" * 40 + with tempfile.TemporaryDirectory() as d: + file = Path(d) / "install.sh" + file.write_text("release") + with patch.object(release, "ensure_gh"), patch.object( + release, "public_bundles", + return_value=[{"verificationMaterial": {}, "dsseEnvelope": {}}] + ) as bundles, patch.object(release.subprocess, "run") as runner, patch.dict( + release.os.environ, + {"XMESH_ATTESTATION_INDEX_TOKEN": "ghs_test-safe_123", + "GH_TOKEN": "fake-gh", "GITHUB_TOKEN": "fake-github"}, + ): + release.verify_file( + file, sha, attestations_read_token="ghs_test-safe_123") + bundles.assert_called_once_with( + file, attestations_read_token="ghs_test-safe_123") + args = runner.call_args.args[0] + self.assertIn("--bundle", args) + self.assertEqual(args[args.index("--source-digest") + 1], sha) + self.assertEqual(args[args.index("--cert-identity") + 1], + release.CERT_IDENTITY) + self.assertEqual(args[args.index("--source-ref") + 1], + release.SOURCE_REF) + self.assertNotIn("XMESH_ATTESTATION_INDEX_TOKEN", + runner.call_args.kwargs["env"]) + self.assertNotIn("GH_TOKEN", runner.call_args.kwargs["env"]) + self.assertNotIn("GITHUB_TOKEN", runner.call_args.kwargs["env"]) + def test_reject_vulnerable_cli(self): for raw in ('gh version 2.45.0 (Ubuntu)\n','gh version 2.101.9\n','nonsense\n'): with patch.object(release.subprocess,'run') as call: From 5f817f4263c2938d6514f308a86419918d93d63a Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 07:16:19 +0300 Subject: [PATCH 66/68] test(sub): reject IPv6-valued spoofed headers at public Caddy edge --- tests/test-runtime-edge.sh | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/tests/test-runtime-edge.sh b/tests/test-runtime-edge.sh index d73bfcf..41c3afc 100644 --- a/tests/test-runtime-edge.sh +++ b/tests/test-runtime-edge.sh @@ -104,4 +104,9 @@ route="$base/s/$token" { echo 'Client spoofed XFF to bypass direct-peer rate limit' >&2; exit 1; } [[ $(status -H 'X-XMesh-Peer-IP: 198.51.100.55' "$route") == 429 ]] || { echo 'Client spoofed internal peer-IP header to bypass rate limit' >&2; exit 1; } -echo 'Verified: Caddy routes, private Unix gate and spoof-resistant per-peer HTTP 429' +# An IPv6-valued forged header must not reset a direct IPv4 peer's bucket. +[[ $(status -H 'X-Forwarded-For: 2001:db8:beef::100' "$route") == 429 ]] || + { echo 'Client spoofed IPv6 XFF to bypass direct-peer rate limit' >&2; exit 1; } +[[ $(status -H 'X-XMesh-Peer-IP: 2001:db8:beef::200' "$route") == 429 ]] || + { echo 'Client spoofed IPv6 internal peer header to bypass rate limit' >&2; exit 1; } +echo 'Verified: Caddy routes, private Unix gate and IPv4/IPv6 spoof-resistant per-peer HTTP 429' From 797d17188cc07e787b8033850c9f0d407262da6d Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 07:16:28 +0300 Subject: [PATCH 67/68] test(sub): verify IPv6 /64 and mapped IPv4 quota isolation --- tests/test-limiter.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/tests/test-limiter.py b/tests/test-limiter.py index 774574d..593a0ba 100644 --- a/tests/test-limiter.py +++ b/tests/test-limiter.py @@ -37,6 +37,20 @@ def test_token_bucket_refill_and_bound(self): with self.assertRaises(OverflowError): limit.allow("192.0.2.3",2,now=130) + def test_ipv6_and_mapped_ipv4_buckets_are_scoped_correctly(self): + limiter = edge.BucketLimiter(max_ips=4) + self.assertTrue(limiter.allow("2001:db8:a:b::1", 1, now=100)) + # Native IPv6 shares tokens across /64, even when an attacker rotates + # the host bits. Adjacent /64 retains an independent bucket. + self.assertFalse(limiter.allow("2001:db8:a:b:ffff::99", 1, now=100)) + self.assertTrue(limiter.allow("2001:db8:a:c::1", 1, now=100)) + # IPv4-mapped IPv6 must not grant a second per-IP quota. + self.assertTrue(limiter.allow("192.0.2.5", 1, now=100)) + self.assertFalse(limiter.allow("::ffff:192.0.2.5", 1, now=100)) + self.assertTrue(limiter.allow("::ffff:192.0.2.6", 1, now=100)) + with self.assertRaises(OverflowError): + limiter.allow("2001:db8:a:d::1", 1, now=100) + def test_worker_exhaustion_closes_connection_instead_of_spawning_threads(self): import socketserver with tempfile.TemporaryDirectory() as directory: From e55657269551825001a0f4c9f27d8cafaf3b3f06 Mon Sep 17 00:00:00 2001 From: Xmesh Creator Date: Tue, 17 Nov 2026 07:18:05 +0300 Subject: [PATCH 68/68] release(sub): bump signed gateway version to 0.4.4 for patched image and rollback rollout --- VERSION | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/VERSION b/VERSION index 17b2ccd..6f2743d 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.4.3 +0.4.4