diff --git a/.github/workflows/attested-release.yml b/.github/workflows/attested-release.yml index 420077f..5b88d74 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: @@ -28,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 @@ -41,7 +49,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' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b7c55c7..ea4effb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -14,21 +14,21 @@ 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 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 tests/test-first-upgrade-rollback.py python3 tests/test-manager.py python3 tests/test-limiter.py - 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 diff --git a/.github/workflows/image-security.yml b/.github/workflows/image-security.yml new file mode 100644 index 0000000..d3711a5 --- /dev/null +++ b/.github/workflows/image-security.yml @@ -0,0 +1,182 @@ +name: Sub deployable image CVE gate +on: + pull_request: + paths: + - 'install.sh' + - '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' + push: + branches: [main] + workflow_dispatch: + workflow_call: +permissions: + contents: read +jobs: + image-cve-gate: + 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 + 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=("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") + 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 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") + PY + - name: Build both signed-installer runtime containers + shell: bash + run: | + set -Eeuo pipefail + 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/${{ 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: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: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: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 + 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: | + 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: | + 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 }} + shell: bash + run: | + set -Eeuo pipefail + python3 - <<'PY' + import hashlib,io,os,pathlib,tarfile,urllib.request + 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() + 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 < entry.size <= 256*1024*1024: + raise SystemExit("Unexpected Trivy executable") + extracted=tar.extractfile(entry) + if extracted is None: raise SystemExit("Trivy binary missing") + target=pathlib.Path(os.environ["RUNNER_TEMP"])/"trivy" + data_bytes=extracted.read(256*1024*1024+1) + if len(data_bytes)>256*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 + shell: bash + run: | + set -Eeuo pipefail + "$RUNNER_TEMP/trivy" image --scanners vuln --format json \ + --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:rev-0000000000000000000000000000000000000000 + - name: Preserve evidence including any unresolved advisories + if: always() + uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 + with: + name: sub-runtime-image-security-${{ matrix.arch }} + path: | + ${{ runner.temp }}/caddy-vulnerabilities.json + ${{ runner.temp }}/limiter-vulnerabilities.json + ${{ 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 + shell: bash + run: | + set -Eeuo pipefail + python3 - <<'PY' + import collections,json,os,pathlib + folder=pathlib.Path(os.environ["RUNNER_TEMP"]) + count=0 + for file in ("caddy-vulnerabilities.json","limiter-vulnerabilities.json"): + report=json.loads((folder/file).read_text()) + vulnerabilities=[v for target in report.get("Results",[]) for v in target.get("Vulnerabilities",[])] + totals=collections.Counter(v.get("Severity","UNKNOWN") for v in vulnerabilities) + print(f"{file}: {dict(totals)}") + high=[v for v in vulnerabilities if v.get("Severity") in ("HIGH","CRITICAL")] + count+=len(high) + for v in high: + print("UNRESOLVED",file,v.get("VulnerabilityID"),v.get("PkgName"), + "installed="+str(v.get("InstalledVersion")), + "fixed="+str(v.get("FixedVersion") or "UNAVAILABLE")) + if count: + raise SystemExit(f"{count} High/Critical issues remain in Sub runtime images") + print("Verified: no High/Critical advisories in scanned exact-runtime-image digests") + PY diff --git a/VERSION b/VERSION index 17b2ccd..6f2743d 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.4.3 +0.4.4 diff --git a/install.sh b/install.sh index 9b882d9..0108a7a 100644 --- a/install.sh +++ b/install.sh @@ -114,11 +114,51 @@ $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_caddy_dockerfile() { + # Caddy's official binary retains x/net 0.60.0 in this exact image. + # 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@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 \ + --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 +} +# 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: python:3.12-alpine + image: @LIMITER_IMAGE@ + build: + context: . + dockerfile: Dockerfile.limiter + pull_policy: never restart: unless-stopped user: "65534:65534" command: ["python3", "-I", "/opt/limiter.py"] @@ -134,7 +174,11 @@ services: - /tmp # No published ports: Caddy is the only client, via a shared Unix socket. xmesh-sub: - image: caddy:2 + image: @CADDY_IMAGE@ + build: + context: . + dockerfile: Dockerfile.caddy + pull_policy: never container_name: xmesh-sub restart: unless-stopped depends_on: @@ -360,6 +404,8 @@ 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# 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 @@ -412,11 +458,51 @@ 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 +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 +# 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" "$SERVICE_UNIT" + elif [[ -f "$temp/previous/.absent-xmesh-sub-manager.service" ]]; then + 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 + 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" -chmod 600 "$temp/Caddyfile" "$temp/compose.yaml" "$temp/limiter.py" + render_limiter_dockerfile >"$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 @@ -507,15 +593,73 @@ if semver(new)/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" +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" +# 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 "$SERVICE_UNIT" ]]; then + cp -p "$SERVICE_UNIT" "$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" +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 -docker compose up -d --remove-orphans +# 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 # key is sent to Nexus; there is no reusable bearer credential to steal. @@ -610,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 @@ -620,6 +764,6 @@ fi install -m 644 "$temp/revision/VERSION" "$ROOT/VERSION" info "Started. Check HTTPS health: https://$DOMAIN/healthz" info "Status: cd $ROOT && sudo docker compose ps" -info "Upgrade: cd $ROOT && sudo docker compose pull && sudo docker compose up -d" +info "Upgrade: use the signed panel update workflow; local limiter images are rebuilt by the attested installer" info "Do not move existing users until a canary feed is verified." if [[ -n "$ENROLL_TOKEN" ]]; then info "Management agent enrolled. Check its status in Nexus Subscription Studio."; fi diff --git a/manager.py b/manager.py index 093d0bd..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") - 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"): + """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", "--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) diff --git a/tests/test-first-upgrade-rollback.py b/tests/test-first-upgrade-rollback.py new file mode 100644 index 0000000..b1d34eb --- /dev/null +++ b/tests/test-first-upgrade-rollback.py @@ -0,0 +1,221 @@ +#!/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 time +import uuid + +HERE = Path(__file__).resolve().parent.parent +INSTALL = (HERE / "install.sh").read_text() +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") + + +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, *, 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" + + gateway + + f" xmesh-sub-limiter:\n" + f" image: {limiter}\n" + 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 "") + ) + + +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] + 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 / "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) + 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 + assert_legacy_https(root) + + 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/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" + "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 / "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: 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"), + "down", "--volumes", "--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() diff --git a/tests/test-image-rollback.py b/tests/test-image-rollback.py new file mode 100644 index 0000000..c8071f0 --- /dev/null +++ b/tests/test-image-rollback.py @@ -0,0 +1,107 @@ +#!/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 +import os +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: + 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) + + +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", os.environ.get("XMESH_SUB_CADDY_IMAGE", "xmesh-sub-caddy:2.11.9-josev4r1"), original_caddy) + created.append(original_caddy) + 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) + 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', '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', '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 + + 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() diff --git a/tests/test-install.sh b/tests/test-install.sh index f10f2ac..b5ce3bd 100644 --- a/tests/test-install.sh +++ b/tests/test-install.sh @@ -17,6 +17,39 @@ 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" +# 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" +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@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" +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 + 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. 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: diff --git a/tests/test-manager.py b/tests/test-manager.py index 8c1a951..9af92a6 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), \ diff --git a/tests/test-runtime-edge.sh b/tests/test-runtime-edge.sh new file mode 100644 index 0000000..41c3afc --- /dev/null +++ b/tests/test-runtime-edge.sh @@ -0,0 +1,112 @@ +#!/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 +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. +chmod 0755 "$temp" +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 + rm -rf "$temp" +} +trap cleanup EXIT + +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" \ + "$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" + +# 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 "$socket_volume:/run/xmesh-sub" \ + -v "$temp/policy:/etc/xmesh-sub/policy:ro" \ + -v "$PWD/limiter.py:/opt/limiter.py:ro" \ + "$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 +done +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 + 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/policy" "$temp/policy/config.json" >&2 || true + exit 1 +fi + +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 "$socket_volume:/run/xmesh-sub:ro" \ + "$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; } +base="http://$address" +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 +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; } +# 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' diff --git a/tests/test-workflow-security.py b/tests/test-workflow-security.py index 91e90b7..06811ff 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)