diff --git a/.config/trivyignore b/.config/trivyignore index f570b76bc1..83445dd9cf 100644 --- a/.config/trivyignore +++ b/.config/trivyignore @@ -4,10 +4,12 @@ # distro CVEs are reported but don't block. The entries below are the currently-accepted *fixable* # findings, each with a rationale and how it clears. Revisit whenever Dependabot bumps a base image. -# Base-image build tooling living in the python:3.11-slim *system* site-packages — NOT in the app's -# /app/.venv and never invoked at runtime (the entrypoint runs the venv's python). Cleared by a base bump. -CVE-2026-23949 -CVE-2026-24049 +# Mute policy: a mute carries `exp:YYYY-MM-DD` about 30 days out and a one-sentence reason. +# Trivy stops muting an expired entry; trivyignore-expiry.sh reports entries expiring within 7 days. + +# Vendored setuptools copies in the python:3.11-slim base (never run by the app); a base-image bump clears them. +CVE-2026-23949 exp:2026-12-20 +CVE-2026-24049 exp:2026-12-20 # Appliance rootfs Go binaries. THIS BLOCK IS DELIBERATELY EMPTY — it stays so nobody re-adds a # line to it without reading why the last one went. It once held three findings on the grounds that diff --git a/.github/actions/install-trivy/action.yml b/.github/actions/install-trivy/action.yml index 71e9750bfc..7527a5ae6d 100644 --- a/.github/actions/install-trivy/action.yml +++ b/.github/actions/install-trivy/action.yml @@ -24,7 +24,7 @@ runs: steps: - id: attempt1 continue-on-error: true - uses: aquasecurity/setup-trivy@81e514348e19b6112ce2a7e3ecbafe19c1e1f567 # v0.3.1 + uses: aquasecurity/setup-trivy@81e514348e19b6112ce2a7e3ecbafe19c1e1f567 # zizmor: ignore[unpinned-tools] v0.3.1 with: version: ${{ inputs.version }} cache: true @@ -34,7 +34,7 @@ runs: - id: attempt2 if: steps.attempt1.outcome == 'failure' continue-on-error: true - uses: aquasecurity/setup-trivy@81e514348e19b6112ce2a7e3ecbafe19c1e1f567 # v0.3.1 + uses: aquasecurity/setup-trivy@81e514348e19b6112ce2a7e3ecbafe19c1e1f567 # zizmor: ignore[unpinned-tools] v0.3.1 with: version: ${{ inputs.version }} cache: true @@ -42,7 +42,7 @@ runs: run: sleep 30 shell: bash - if: steps.attempt1.outcome == 'failure' && steps.attempt2.outcome == 'failure' - uses: aquasecurity/setup-trivy@81e514348e19b6112ce2a7e3ecbafe19c1e1f567 # v0.3.1 + uses: aquasecurity/setup-trivy@81e514348e19b6112ce2a7e3ecbafe19c1e1f567 # zizmor: ignore[unpinned-tools] v0.3.1 with: version: ${{ inputs.version }} cache: true diff --git a/.github/actions/retry-trivy-scan/action.yml b/.github/actions/retry-trivy-scan/action.yml index 84826c5d4b..69719289a2 100644 --- a/.github/actions/retry-trivy-scan/action.yml +++ b/.github/actions/retry-trivy-scan/action.yml @@ -12,8 +12,8 @@ description: > The retry also covers a vulnerability-DB registry refusal (#3296): mirror.gcr.io answered 403 to both attempts of one run because they ran within the same second. So the retry waits first, and - lists ghcr.io ahead of the mirror (TRIVY_DB_REPOSITORY, tried in order), so a refusing mirror - no longer fails an unrelated PR. The first attempt keeps trivy's default order. + lists ghcr.io ahead of the ECR mirror (TRIVY_DB_REPOSITORY, tried in order), so a refusing registry + no longer fails an unrelated PR. The first attempt gets the same list from install-trivy. inputs: image-ref: required: true @@ -27,7 +27,7 @@ runs: run: sleep 30 - uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 env: - TRIVY_DB_REPOSITORY: ghcr.io/aquasecurity/trivy-db:2,mirror.gcr.io/aquasec/trivy-db:2 + TRIVY_DB_REPOSITORY: ghcr.io/aquasecurity/trivy-db:2,public.ecr.aws/aquasecurity/trivy-db:2 with: skip-setup-trivy: true image-ref: ${{ inputs.image-ref }} diff --git a/.github/dependabot.yml b/.github/dependabot.yml index e8b0c8ad7f..c92c63f7fd 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,6 +1,3 @@ -# Dependabot (Wave 7 tooling, #282): automated dependency + CVE update PRs across every -# supply-chain surface. Grouped + weekly to keep PR volume sane. -# # Dependabot reads this file from the DEFAULT branch (`develop`) only and resolves every `directory:` # there; one entry per surface covers everything (CONTRIBUTING.md § One integration branch, #1163, #1425). version: 2 @@ -14,6 +11,9 @@ updates: groups: actions: patterns: ["*"] + actions-security: + applies-to: security-updates + patterns: ["*"] # Dashboard Python deps — bumps the hashed uv.lock + pyproject floors (#283). - package-ecosystem: "uv" @@ -23,6 +23,9 @@ updates: groups: python: patterns: ["*"] + python-security: + applies-to: security-updates + patterns: ["*"] ignore: # protobuf/grpcio are pinned to what the vendored Tari gRPC stubs assert at import time # (see dashboard/pyproject.toml); a major bump needs the stubs regenerated first. @@ -48,6 +51,9 @@ updates: groups: docker: patterns: ["*"] + docker-security: + applies-to: security-updates + patterns: ["*"] ignore: # Major/minor base bumps (e.g. python 3.11->3.14, ubuntu 24.04->26.04) are deliberate # migrations, not security updates — keep Dependabot to digest + patch within the pinned tag. @@ -65,6 +71,9 @@ updates: groups: docker-appliance: patterns: ["*"] + docker-appliance-security: + applies-to: security-updates + patterns: ["*"] ignore: # Same policy as the docker entry above, and it binds the golang builder tag: a 1.26 -> 1.27 # move is a deliberate rebake, not a security update. It does NOT constrain @@ -96,6 +105,9 @@ updates: groups: compose: patterns: ["*"] + compose-security: + applies-to: security-updates + patterns: ["*"] ignore: # Same policy as the docker entry: digest + patch within the pinned tag. A Tari or Caddy # major/minor is a deliberate migration (compose flags, config compatibility), not a CVE fix. @@ -137,11 +149,31 @@ updates: groups: test-harness: patterns: ["*"] + test-harness-security: + applies-to: security-updates + patterns: ["*"] - package-ecosystem: "npm" directory: "/dashboard/tests/browser" schedule: interval: "weekly" + groups: + browser-tests: + patterns: ["*"] + browser-tests-security: + applies-to: security-updates + patterns: ["*"] + + - package-ecosystem: "cargo" + directory: "/tests/integration/mergemine/fixture" + schedule: + interval: "weekly" + groups: + mergemine-fixture: + patterns: ["*"] + mergemine-fixture-security: + applies-to: security-updates + patterns: ["*"] - package-ecosystem: "pre-commit" directory: "/" diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index ef2643b5a7..7d602e36d2 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,28 +4,19 @@ on: push: branches: [main, develop] pull_request: - # Two Monday sweeps hang off this schedule (every other job gates itself off the event): - # build-images (#833) rebuilds this branch and scans the rebuild, the only sweep that can go red - # before a release; sweep-shipped (#1313) scans the published ghcr images by resolved digest - # and reports into a tracking issue rather than reddening, since a fixable CVE in a shipped - # image asks for a patch release, a person's decision. - # THIS cron block is the one that fires (`schedule:` reads the DEFAULT branch, `develop`). Prove - # a cadence change fired with `gh run list --json event`: a schedule that never runs looks - # exactly like one that ran and found nothing (#1162). schedule: - cron: "0 5 * * 1" # Mondays 05:00 UTC -# Least privilege (#282): every job here only reads the repo — none push commits, comment, or -# publish packages. Narrowing the default GITHUB_TOKEN limits the blast radius of a compromised step. permissions: contents: read -# Cancel superseded runs of the same PR; never cancel push runs on main/develop (they set the -# diff-cover baseline and are required checks on the protected branch). #415. concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} +env: + TRIVY_DB_REPOSITORY: ghcr.io/aquasecurity/trivy-db:2,public.ecr.aws/aquasecurity/trivy-db:2 + jobs: dashboard: name: Dashboard tests (pytest + coverage) @@ -146,173 +137,6 @@ jobs: image-ref: pithead-${{ matrix.service }}:ci trivyignores: .config/trivyignore - sweep-shipped: - # The half of the Monday sweep that reports on what users are running (#1313). `build-images` - # above scans a rebuild of this branch; this scans the bytes on the registry. - # - # Every leg resolves the published TAG to a DIGEST and scans the digest: a tag is a moving - # pointer, so only the digest names the bytes a user pulled. It is printed in the report. - # - # fail-fast: false; the report job (always()) names an unscanned image UNCHECKED, not clean. - name: Shipped-image CVE sweep (${{ matrix.service }}) - if: github.event_name == 'schedule' - runs-on: ubuntu-latest - timeout-minutes: 20 - strategy: - fail-fast: false - matrix: - service: [monero, p2pool, tor, xmrig-proxy, dashboard, os-rootfs] - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Resolve the shipped tag to a digest, and take main's own Trivy ignore file - id: shipped - env: - SERVICE: ${{ matrix.service }} - run: | - set -Eeuo pipefail - # The scheduled run checks out develop. `main` is a different ref and a shallow clone - # does not carry it, so fetch it rather than assume it is here — since #1076 `main` is a - # fast-forward pointer to the released tag, and it is the only ref that knows what - # shipped. - git fetch --no-tags --depth=1 origin main - ver="$(git show origin/main:VERSION)" - [ -n "$ver" ] || { echo "::error::main carries no VERSION — cannot tell what shipped"; exit 1; } - tag="v$ver" - # main's OWN .trivyignore, never develop's; tries the moved path, falls back to the - # pre-move root path until main carries #1901's move (PR #2201), then drop the fallback. - git show origin/main:.config/trivyignore >main.trivyignore 2>/dev/null || git show origin/main:.trivyignore >main.trivyignore - repo="p2pool-starter-stack/pithead-$SERVICE" - # The packages are public, so an anonymous pull token is enough — no registry secret - # enters this workflow. - token="$(curl -fsS "https://ghcr.io/token?scope=repository:$repo:pull" | jq -er .token)" - digest="$(curl -fsSI \ - -H "Authorization: Bearer $token" \ - -H "Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.docker.distribution.manifest.v2+json" \ - "https://ghcr.io/v2/$repo/manifests/$tag" | - tr -d '\r' | awk 'tolower($1) == "docker-content-digest:" { print $2 }')" - # An unresolved digest must never fall through to a tag scan: the report would then say - # "shipped image" about bytes nobody can identify. Fail the leg instead and let it read - # UNCHECKED. - printf '%s' "$digest" | grep -Eq '^sha256:[0-9a-f]{64}$' || - { echo "::error::could not resolve ghcr.io/$repo:$tag to a digest — got [$digest]"; exit 1; } - echo "ref=ghcr.io/$repo@$digest" >>"$GITHUB_OUTPUT" - # The tag every leg swept, so the report can refuse to mix two releases if a cut lands - # mid-run. - printf '%s\n' "$tag" >"sweep-$SERVICE.tag" - - uses: ./.github/actions/install-trivy # the only step that installs trivy here (#2214) - with: - version: v0.73.0 # THE live pin, read by `make lint-trivy-parity` — see build-images (#1290) - - name: Scan the published image by digest (Trivy) - # Same scope as the gate above, and the same engine — but only because #1290's pin is on - # both jobs' install-trivy steps, each read by `make lint-trivy-parity`. Comparing this - # sweep's verdict against the rebuild's is the whole reason both exist, and those two - # literals are what decide which engine each job installs and therefore scans with. - # - # trivy pulls the digest from the registry itself — nothing is built here. - uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 - with: - skip-setup-trivy: true # scans with the binary the step above installed (#1290, #2214) - image-ref: ${{ steps.shipped.outputs.ref }} - scanners: vuln - severity: HIGH,CRITICAL - ignore-unfixed: true - # Report-only, deliberately. A fixable CVE in an image that is already published cannot - # be fixed by failing this run; it asks for a patch release. The run goes red only when - # the sweep itself could not do its job, which the report job decides. - exit-code: "0" - trivyignores: main.trivyignore - cache: "false" - format: json - output: sweep-${{ matrix.service }}.json - - name: Upload this image's scan output - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 - with: - name: shipped-sweep-${{ matrix.service }} - path: | - sweep-${{ matrix.service }}.json - sweep-${{ matrix.service }}.tag - # An empty upload would reach the report job as a scan that found nothing, which is the - # one thing this must never say off a leg that did not scan. - if-no-files-found: error - - sweep-shipped-report: - # One tracking issue, edited in place — the pin-watch.yml / trivyignore-watch.yml posture. An - # issue persists, is assignable, and lets a person write "held until the next cut, here's why" - # in a comment. A red square in the Actions tab cannot hold that, and this finding's whole - # value is the conversation about whether to cut a patch release. - name: Shipped-image CVE sweep — tracking issue - # always() so a failed scan leg still reports: an image with no scan output is UNCHECKED, and - # saying so is the entire point. Skipping the report on a partial sweep would leave the last - # good report standing as if it were current. - if: always() && github.event_name == 'schedule' - needs: sweep-shipped - runs-on: ubuntu-latest - timeout-minutes: 10 - # Least privilege (#282): issues.write is this job's one output — it never pushes or publishes. - permissions: - contents: read - issues: write - steps: - - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - - name: Collect every leg's scan output - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 - with: - pattern: shipped-sweep-* - merge-multiple: true - path: shipped-sweep - - name: Render the report - id: report - run: | - set -uo pipefail - # NOT `set -e`: an incomplete sweep is a result to publish, not a reason to publish - # nothing. The script names the images it could not check and exits 1; the rc is - # carried to the last step so the run still fails loudly. - bash scripts/watch/shipped-image-sweep-report.sh shipped-sweep >report.md - rc=$? - # An empty report is itself a failure to report — never publish silence. - [ -s report.md ] || { echo "The shipped-image sweep produced no report at all — see the run log." >report.md; rc=1; } - echo "rc=$rc" >>"$GITHUB_OUTPUT" - - name: Publish it to the tracking issue - env: - GH_TOKEN: ${{ github.token }} - RC: ${{ steps.report.outputs.rc }} - run: | - set -Eeuo pipefail - # The title is the upsert key and it lives in the script, so there is exactly one - # spelling of it anywhere. A second spelling here would file a second issue on the very - # next run and then keep both stale. - TITLE="$(bash scripts/watch/shipped-image-sweep-report.sh --title)" - body=$(cat report.md) - # Exact title match over the open list, NOT `--search`: the search index lags issue - # creation by minutes, so a search-based dedup files a second issue on the next run. - n=$(bash scripts/watch/find-open-issue.sh "$TITLE") - # A run that could not do its job must not DELETE the "last fully successful" date — - # that date is the only thing separating "failed once this morning" from "has been dead - # for six weeks". Stamp it on success, carry it forward on failure (pin-watch pattern). - if [ "$RC" = "0" ]; then - body="$body"$'\n\n'"_Last fully successful sweep: $(date -u +%F)_" - elif [ -n "$n" ]; then - prev=$(gh issue view "$n" --json body --jq .body | grep -a "^_Last fully successful sweep:" || true) - if [ -n "$prev" ]; then - body="$body"$'\n\n'"$prev (this run could not complete)" - fi - fi - if [ -n "$n" ]; then - gh issue edit "$n" --body "$body" - echo "updated #$n" - else - gh issue create --title "$TITLE" --label infra --body "$body" - fi - - name: Fail the run if the sweep could not cover every shipped image - if: steps.report.outputs.rc != '0' - run: | - echo "::error::the shipped-image sweep did not cover every published image — those images are UNCHECKED, not clean" - exit 1 - hadolint: name: Dockerfile lint (hadolint) if: github.event_name != 'schedule' # scheduled runs are the CVE sweep — build-images only (#833) @@ -395,7 +219,7 @@ jobs: checksum: 745765a3b6e360ad76743599ae5c42e9278c7edf8bbff9fc76d05bf2623a04dd enable-cache: false - name: Audit workflows (injection, token scope, self-hosted-runner risks) - run: uvx zizmor@1.25.2 --offline .github/workflows/ + run: uvx zizmor@1.25.2 --offline .github/workflows/ .github/actions/ compose: name: Compose config + security hardening diff --git a/.github/workflows/os-rootfs.yml b/.github/workflows/os-rootfs.yml index 53875fc383..7721172bbb 100644 --- a/.github/workflows/os-rootfs.yml +++ b/.github/workflows/os-rootfs.yml @@ -16,14 +16,6 @@ name: OS rootfs scan # CONTRIBUTING.md § One integration branch. on: pull_request: - # Every PR targets `develop`, which carries os/, so the paths filter alone decides which PRs - # build and scan: a change under os/ or to `.config/trivyignore` (a new mute must be scanned for real — - # #1156 added four that were never applied to the appliance). Until 2026-09-06 PRs into the - # os/-less default branch were excluded here; that exclusion would now skip every PR. - paths: - - "os/**" - - ".github/workflows/os-rootfs.yml" - - ".config/trivyignore" schedule: - cron: "0 6 * * 1" # Mondays 06:00 UTC, after ci.yml's 05:00 image sweep workflow_dispatch: @@ -36,6 +28,9 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} +env: + TRIVY_DB_REPOSITORY: ghcr.io/aquasecurity/trivy-db:2,public.ecr.aws/aquasecurity/trivy-db:2 + jobs: rootfs-image: name: Build + scan the appliance rootfs @@ -46,7 +41,21 @@ jobs: with: # The triggering ref, checkout's default: a PR run scans the PR; the weekly sweep and a # manual dispatch run on `develop`, which carries `os/` (#1162). + fetch-depth: 2 persist-credentials: false + - name: Decide whether this PR touches the rootfs inputs + id: scope + env: + EVENT: ${{ github.event_name }} + run: | + if [ "$EVENT" != "pull_request" ]; then + echo "build=true" >>"$GITHUB_OUTPUT" + elif git diff --name-only HEAD^1 HEAD | grep -Eq '^(os/|docker-compose\.yml$|VERSION$|lib/pithead/|scripts/build-pithead\.sh$|data/egress-map\.tsv$|pithead-completion\.bash$|config\.(reference|core-keys|minimal)\.json$|cosign\.pub$|build/(monero/bitmonero\.conf\.template|tari/|tari-wallet/)|\.github/workflows/os-rootfs\.yml$|\.github/actions/(install-trivy|retry-trivy-scan)/|\.config/trivyignore$)'; then + echo "build=true" >>"$GITHUB_OUTPUT" + else + echo "build=false" >>"$GITHUB_OUTPUT" + echo "No rootfs input changed in this PR; the rootfs build and scan were skipped." >>"$GITHUB_STEP_SUMMARY" + fi - name: Check the appliance tree exists # Only a PR may legitimately miss the tree: a branch cut before the appliance tree existed # can reach this workflow through the .config/trivyignore path filter. Every other trigger runs on @@ -54,6 +63,7 @@ jobs: # asked — and a quiet skip would report a green weekly sweep of nothing, which is the exact # failure #1162 was filed for. Fail instead. id: tree + if: steps.scope.outputs.build == 'true' env: EVENT: ${{ github.event_name }} run: | @@ -116,3 +126,7 @@ jobs: with: image-ref: pithead-os-rootfs:ci trivyignores: .config/trivyignore + - name: Name the cure for a failed scan + if: failure() && steps.tree.outputs.present == 'true' + run: | + echo "A fixable HIGH/CRITICAL CVE is in the appliance rootfs. Cure: rebake the apt layer by bumping APT_INDEX_STAMP in os/rootfs/Dockerfile, or bump the pinned digest or version that carries it." >>"$GITHUB_STEP_SUMMARY" diff --git a/.github/workflows/pin-watch.yml b/.github/workflows/pin-watch.yml index bc09cab2a5..6ca2a413f6 100644 --- a/.github/workflows/pin-watch.yml +++ b/.github/workflows/pin-watch.yml @@ -57,6 +57,10 @@ jobs: rc=$? # An empty report is itself a failure to report — never publish silence. [ -s report.md ] || { echo "The pin watcher produced no report at all — see the run log." >report.md; rc=1; } + RESOLVE_PINS_MISMATCH_OK=1 bash scripts/release/resolve-pins.sh >digests.txt 2>&1 + rc_digest=$? + { printf '\n## Third-party image digest pins\n\n```text\n'; cat digests.txt; printf '```\n'; } >>report.md + [ "$rc_digest" = 0 ] || rc=1 echo "rc=$rc" >>"$GITHUB_OUTPUT" - name: Publish it to this lane's tracking issue env: @@ -96,9 +100,3 @@ jobs: run: | echo "::error::one or more upstream lookups could not run — those pins are UNCHECKED, not current" exit 1 - # Digest-level check (#1137): does this lane's own docker-compose.yml pins still match what - # each tag resolves to right now. Separate from the report above on purpose — a version can - # be current while its digest has drifted, and that half-done-bump case is this step's job, - # not the report's. A mismatch or failed lookup fails this step, which fails the run. - - name: Check third-party image pins against their registries - run: bash scripts/release/resolve-pins.sh diff --git a/.github/workflows/scheduled-run-watch.yml b/.github/workflows/scheduled-run-watch.yml index f4bb6e938d..56dcf053a1 100644 --- a/.github/workflows/scheduled-run-watch.yml +++ b/.github/workflows/scheduled-run-watch.yml @@ -37,9 +37,7 @@ name: Scheduled-run watch # #1146). on: schedule: - # Mondays 08:00 UTC, after the other declared Monday slots. GitHub may start any of them hours - # late, so the cadence report allows 12 hours before LATE and a full period before MISSED. - - cron: "0 8 * * 1" + - cron: "0 8 * * *" workflow_dispatch: # Least privilege (#282). `actions: read` lets the job read this repo's scheduled-run histories @@ -50,6 +48,10 @@ permissions: contents: read issues: write +concurrency: + group: scheduled-run-watch + cancel-in-progress: false + jobs: scheduled-run-watch: name: Report declared schedule cadence and the Monday CVE sweep @@ -135,6 +137,13 @@ jobs: else gh issue create --title "$TITLE" --label infra --body "$body" fi + - name: Report red scheduled runs in a security issue + env: + GH_TOKEN: ${{ github.token }} + run: | + set -Eeuo pipefail + bash scripts/watch/security-issue.sh render-red watch/cadence.json >red.md + bash scripts/watch/security-issue.sh upsert "$(bash scripts/watch/security-issue.sh title-red)" red.md - name: Fail the run if the watch could not do its job if: steps.report.outputs.rc != '0' run: | diff --git a/.github/workflows/security-sweep.yml b/.github/workflows/security-sweep.yml new file mode 100644 index 0000000000..24371455e8 --- /dev/null +++ b/.github/workflows/security-sweep.yml @@ -0,0 +1,243 @@ +name: Security sweep + +on: + schedule: + - cron: "30 5 * * *" + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: security-sweep + cancel-in-progress: false + +jobs: + refs: + name: List the refs to sweep + runs-on: ubuntu-latest + timeout-minutes: 5 + outputs: + refs: ${{ steps.list.outputs.refs }} + steps: + - name: List develop, main and every develop-v* branch + id: list + run: | + set -Eeuo pipefail + heads="$(git ls-remote --heads "https://github.com/${GITHUB_REPOSITORY}.git" 'develop-v*')" + extra="$(printf '%s\n' "$heads" | sed 's|.*refs/heads/||' | grep -E '^develop-v[0-9A-Za-z._-]+$' | sort || true)" + refs="$(printf 'develop\nmain\n%s\n' "$extra" | grep -v '^$' | jq -R . | jq -sc .)" + echo "refs=$refs" >>"$GITHUB_OUTPUT" + echo "$refs" + + scan-ref: + name: Scan ${{ matrix.ref }} + needs: refs + runs-on: ubuntu-latest + timeout-minutes: 15 + strategy: + fail-fast: false + matrix: + ref: ${{ fromJSON(needs.refs.outputs.refs) }} + env: + OSV_SCANNER_VERSION: v2.7.1 + OSV_SCANNER_SHA256: fb7dab19a8bd9bbe5c3189f09d4b7ee1820c9553a23bac202648a56efd2f6ee8 + UV_PYTHON_DOWNLOADS: never + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + ref: ${{ matrix.ref }} + path: src + persist-credentials: false + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.11" + - uses: astral-sh/setup-uv@1db35dd8eee11c5894872e0b383ae6c406cf738d # v10.4.0 + with: + version: "0.12.13" + checksum: 745765a3b6e360ad76743599ae5c42e9278c7edf8bbff9fc76d05bf2623a04dd + enable-cache: false + - name: Install osv-scanner (sha256-verified release binary) + run: | + set -Eeuo pipefail + curl -fsSL -o "$RUNNER_TEMP/osv-scanner" \ + "https://github.com/google/osv-scanner/releases/download/${OSV_SCANNER_VERSION}/osv-scanner_linux_amd64" + echo "${OSV_SCANNER_SHA256} $RUNNER_TEMP/osv-scanner" | sha256sum -c - + chmod +x "$RUNNER_TEMP/osv-scanner" + - name: Scan the lockfiles at this ref (osv-scanner) + env: + REF: ${{ matrix.ref }} + run: | + set -Eeuo pipefail + mkdir -p out + printf '%s\n' "$REF" >out/ref.txt + cd src + args=() + while IFS= read -r f; do args+=(-L "$f"); done < <(git ls-files 'uv.lock' '*/uv.lock' 'package-lock.json' '*/package-lock.json' 'Cargo.lock' '*/Cargo.lock') + [ "${#args[@]}" -gt 0 ] || { echo "::error::no lockfile found at $REF — nothing was scanned"; exit 1; } + rc=0 + "$RUNNER_TEMP/osv-scanner" scan source "${args[@]}" --format json --output-file ../out/osv.json || rc=$? + [ "$rc" = 0 ] || [ "$rc" = 1 ] || { echo "::error::osv-scanner failed with exit code $rc"; exit 1; } + [ -s ../out/osv.json ] || { echo "::error::osv-scanner wrote no report"; exit 1; } + - name: Audit the workflows at this ref (zizmor, online) + env: + GH_TOKEN: ${{ github.token }} + run: | + set -Eeuo pipefail + cd src + uvx zizmor@1.25.2 --format json --no-exit-codes .github/workflows/ >../out/zizmor.json + jq -e 'type == "array"' ../out/zizmor.json >/dev/null + - name: Upload this ref's scan output + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: sweep-ref-${{ strategy.job-index }} + path: out/ + if-no-files-found: error + + report-ref: + name: Update the per-ref security issues + needs: [refs, scan-ref] + if: always() && needs.refs.result == 'success' + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: sweep-ref-* + path: sweep + - name: Upsert one issue per swept ref + env: + GH_TOKEN: ${{ github.token }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + set -Eeuo pipefail + for d in sweep/sweep-ref-*; do + [ -d "$d" ] || continue + ref="$(cat "$d/ref.txt")" + bash scripts/watch/security-issue.sh render-ref "$d" >"$d/body.md" + bash scripts/watch/security-issue.sh upsert "$(bash scripts/watch/security-issue.sh title-ref "$ref")" "$d/body.md" + done + + sweep-shipped: + name: Shipped-image CVE sweep (${{ matrix.service }}) + runs-on: ubuntu-latest + timeout-minutes: 20 + strategy: + fail-fast: false + matrix: + service: [monero, p2pool, tor, xmrig-proxy, dashboard, os-rootfs] + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Resolve the shipped tag to a digest, and take main's own Trivy ignore file + id: shipped + env: + SERVICE: ${{ matrix.service }} + run: | + set -Eeuo pipefail + git fetch --no-tags --depth=1 origin main + ver="$(git show origin/main:VERSION)" + [ -n "$ver" ] || { echo "::error::main carries no VERSION — cannot tell what shipped"; exit 1; } + tag="v$ver" + git show origin/main:.config/trivyignore >main.trivyignore 2>/dev/null || git show origin/main:.trivyignore >main.trivyignore + repo="p2pool-starter-stack/pithead-$SERVICE" + token="$(curl -fsS "https://ghcr.io/token?scope=repository:$repo:pull" | jq -er .token)" + digest="$(curl -fsSI \ + -H "Authorization: Bearer $token" \ + -H "Accept: application/vnd.oci.image.index.v1+json, application/vnd.docker.distribution.manifest.list.v2+json, application/vnd.docker.distribution.manifest.v2+json" \ + "https://ghcr.io/v2/$repo/manifests/$tag" | + tr -d '\r' | awk 'tolower($1) == "docker-content-digest:" { print $2 }')" + printf '%s' "$digest" | grep -Eq '^sha256:[0-9a-f]{64}$' || + { echo "::error::could not resolve ghcr.io/$repo:$tag to a digest — got [$digest]"; exit 1; } + echo "ref=ghcr.io/$repo@$digest" >>"$GITHUB_OUTPUT" + printf '%s\n' "$tag" >"sweep-$SERVICE.tag" + - uses: ./.github/actions/install-trivy + with: + version: v0.73.0 + - name: Scan the published image by digest (Trivy) + uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0 + with: + skip-setup-trivy: true + image-ref: ${{ steps.shipped.outputs.ref }} + scanners: vuln + severity: HIGH,CRITICAL + ignore-unfixed: true + exit-code: "0" + trivyignores: main.trivyignore + cache: "false" + format: json + output: sweep-${{ matrix.service }}.json + - name: Upload this image's scan output + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: shipped-sweep-${{ matrix.service }} + path: | + sweep-${{ matrix.service }}.json + sweep-${{ matrix.service }}.tag + if-no-files-found: error + + sweep-shipped-report: + name: Shipped-image CVE sweep — tracking issue + if: always() + needs: sweep-shipped + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + issues: write + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - name: Collect every leg's scan output + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + pattern: shipped-sweep-* + merge-multiple: true + path: shipped-sweep + - name: Render the report + id: report + run: | + set -uo pipefail + bash scripts/watch/shipped-image-sweep-report.sh shipped-sweep >report.md + rc=$? + [ -s report.md ] || { echo "The shipped-image sweep produced no report at all — see the run log." >report.md; rc=1; } + echo "rc=$rc" >>"$GITHUB_OUTPUT" + - name: Publish it to the tracking issue + env: + GH_TOKEN: ${{ github.token }} + RC: ${{ steps.report.outputs.rc }} + run: | + set -Eeuo pipefail + TITLE="$(bash scripts/watch/shipped-image-sweep-report.sh --title)" + body=$(cat report.md) + for t in "$TITLE" "Shipped-image CVE sweep (weekly report)"; do n=$(bash scripts/watch/find-open-issue.sh "$t"); [ -z "$n" ] || break; done + if [ "$RC" = "0" ]; then + body="$body"$'\n\n'"_Last fully successful sweep: $(date -u +%F)_" + elif [ -n "$n" ]; then + prev=$(gh issue view "$n" --json body --jq .body | grep -a "^_Last fully successful sweep:" || true) + if [ -n "$prev" ]; then + body="$body"$'\n\n'"$prev (this run could not complete)" + fi + fi + if [ -n "$n" ]; then + gh issue edit "$n" --title "$TITLE" --add-label security --body "$body" + echo "updated #$n" + else + gh issue create --title "$TITLE" --label security --body "$body" + fi + - name: Fail the run if the sweep could not cover every shipped image + if: steps.report.outputs.rc != '0' + run: | + echo "::error::the shipped-image sweep did not cover every published image — those images are UNCHECKED, not clean" + exit 1 diff --git a/.github/workflows/supply-chain.yml b/.github/workflows/supply-chain.yml new file mode 100644 index 0000000000..072a4149ad --- /dev/null +++ b/.github/workflows/supply-chain.yml @@ -0,0 +1,56 @@ +name: Supply chain + +on: + pull_request: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + dependency-review: + name: Dependency review + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - uses: actions/dependency-review-action@bbc44d14a204704ccc493733616cd1e93a0321ec # v5.0.1 + with: + fail-on-severity: high + fail-on-scopes: runtime, unknown + license-check: false + comment-summary-in-pr: never + + compose-image-scan: + name: Compose image scan + runs-on: ubuntu-latest + timeout-minutes: 20 + env: + TRIVY_DB_REPOSITORY: ghcr.io/aquasecurity/trivy-db:2,mirror.gcr.io/aquasec/trivy-db:2 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + fetch-depth: 2 + persist-credentials: false + - name: Detect a changed compose file + id: scope + run: | + if git diff --quiet HEAD^1 HEAD -- docker-compose.yml; then + echo "changed=false" >>"$GITHUB_OUTPUT" + echo "docker-compose.yml is unchanged; no image to scan." >>"$GITHUB_STEP_SUMMARY" + else + echo "changed=true" >>"$GITHUB_OUTPUT" + git show HEAD^1:docker-compose.yml >"$RUNNER_TEMP/base-compose.yml" + fi + - uses: ./.github/actions/install-trivy + if: steps.scope.outputs.changed == 'true' + with: + version: v0.73.0 + - name: Scan the changed third-party digests (Trivy) + if: steps.scope.outputs.changed == 'true' + run: bash scripts/ci/compose-image-scan.sh "$RUNNER_TEMP/base-compose.yml" docker-compose.yml .config/trivyignore diff --git a/.github/workflows/test-images.yml b/.github/workflows/test-images.yml index 2a08d2df15..d2289c0ed8 100644 --- a/.github/workflows/test-images.yml +++ b/.github/workflows/test-images.yml @@ -41,6 +41,9 @@ concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} +env: + TRIVY_DB_REPOSITORY: ghcr.io/aquasecurity/trivy-db:2,public.ecr.aws/aquasecurity/trivy-db:2 + jobs: test-images: name: Test image (${{ matrix.service }}) diff --git a/.github/workflows/trivyignore-watch.yml b/.github/workflows/trivyignore-watch.yml index c64fc92ab8..0027855af0 100644 --- a/.github/workflows/trivyignore-watch.yml +++ b/.github/workflows/trivyignore-watch.yml @@ -52,6 +52,7 @@ jobs: rc=$? # An empty report is itself a failure to report — never publish silence. [ -s report.md ] || { echo "The mute watch produced no report at all — see the run log." >report.md; rc=1; } + bash scripts/watch/trivyignore-expiry.sh >>report.md || rc=1 echo "rc=$rc" >>"$GITHUB_OUTPUT" - name: Publish it to the tracking issue env: diff --git a/.gitignore b/.gitignore index 0dc6b4030f..f87cd7b45a 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ config.json.bak-control /.pithead.bundle.* /data/* !/data/egress-map.tsv +/build/.tari-render.* /build/monero/bitmonero.conf /build/tari/config.toml Caddyfile diff --git a/Makefile b/Makefile index f6c48d6c35..3c31ba5eb0 100644 --- a/Makefile +++ b/Makefile @@ -71,6 +71,8 @@ test-tools: ## Build-tool contracts and CI workflow guards (no live services) python3 tests/stack/standalone/test_monero_download.py python3 tests/stack/standalone/test_appliance_release_docs.py bash scripts/watch/tor-bump.sh --self-test + bash scripts/ci/compose-image-scan.sh --self-test + bash scripts/watch/security-issue.sh --self-test bash scripts/watch/pin-bump.sh --self-test bash tests/watch/test-find-open-issue.sh sed -n '/^ shell-block:$$/,/^ shell-fragment:$$/p' .github/workflows/shell.yml | grep -Eq '^ timeout-minutes: 12( |$$)' @@ -207,6 +209,7 @@ lint-pithead-build: ## Test the generated CLI build and its ordering/refusal gua lint-trivy-parity: ## Fail if a gate workflow's install-trivy version: (the one line that decides the engine) drifts from the version scripts/watch/trivyignore-watch.sh scans with (#1290), or if the cached-installer shape that makes it the only pin breaks (#2214) bash scripts/watch/trivyignore-watch.sh --self-test bash scripts/watch/trivyignore-watch.sh --check-parity + bash scripts/watch/trivyignore-expiry.sh --self-test bash scripts/lint/lint-trivy-installer-cache.sh --self-test bash scripts/lint/lint-trivy-installer-cache.sh diff --git a/README.md b/README.md index 3b52fdfac6..7ca2b34818 100644 --- a/README.md +++ b/README.md @@ -101,14 +101,13 @@ This is the DIY path. For the appliance, download `pithead-os-vX.Y.Z.img.xz` fro [the appliance guide](docs/appliance.md) instead — no Linux to set up, no command line to learn. ```bash -# Grab the latest release — pulls the published, tested images (no local build) -curl -fsSL https://github.com/p2pool-starter-stack/pithead/releases/latest/download/pithead.tar.gz | tar xz -cd pithead -./pithead setup +# Fetch the latest release, check its sha256 and signature, unpack it and start setup +curl -fsSL https://raw.githubusercontent.com/p2pool-starter-stack/pithead/main/install.sh | bash ``` > Leave `config.json` absent for the setup wizard; have a Monero payout address ready, and a -> Tari payout address only if you enable merge-mining. For manual configuration, copy +> Tari payout address only if you enable merge-mining. For manual configuration, check and unpack the +> bundle by hand ([Get the code](docs/getting-started.md#2-get-the-code)), then copy > `config.minimal.json` or `config.reference.json` and edit it before setup; those files inherit > reference defaults rather than the wizard's new-install choices. To build from source (a `dev` > build), e.g. to contribute, see [Install from source](docs/getting-started.md#alternative-build-from-source). diff --git a/build/monero/entrypoint.sh b/build/monero/entrypoint.sh index 7260ad0091..695b432467 100644 --- a/build/monero/entrypoint.sh +++ b/build/monero/entrypoint.sh @@ -63,11 +63,12 @@ mkdir -p "$(dirname "$CONFIG_PATH")" echo "Initializing Monero configuration from template..." -# Inject environment variables into the configuration template -# We explicitly list variables to avoid accidental substitution of system environment variables -envsubst '${MONERO_NODE_USERNAME}${MONERO_NODE_PASSWORD}${MONERO_ONION_ADDRESS}${MONERO_PRUNE}${MONERO_PREP_THREADS}${MONERO_OUT_PEERS}${NETWORK_PREFIX}' <"$TEMPLATE_PATH" >"$CONFIG_PATH" +mask=$(umask) +umask 077 +rendered=$(mktemp "$CONFIG_PATH.XXXXXX") +trap 'rm -f "$rendered"' EXIT +envsubst '${MONERO_NODE_USERNAME}${MONERO_NODE_PASSWORD}${MONERO_ONION_ADDRESS}${MONERO_PRUNE}${MONERO_PREP_THREADS}${MONERO_OUT_PEERS}${NETWORK_PREFIX}' <"$TEMPLATE_PATH" >"$rendered" -# Apply the optional clearnet initial-sync transform (#183) and warn loudly while it's active. if clearnet_sync_active; then echo "==========================================================================" echo "WARNING: MONERO CLEARNET INITIAL SYNC IS ACTIVE (#183)" @@ -76,11 +77,12 @@ if clearnet_sync_active; then echo " broadcast STAYS on Tor, and wallets are never exposed. The dashboard" echo " switches monerod back to Tor automatically once the chain is synced (#234)." echo "==========================================================================" - apply_clearnet_initial_sync "$CONFIG_PATH" + apply_clearnet_initial_sync "$rendered" elif [ "${MONERO_CLEARNET_SYNC:-false}" = "true" ]; then echo "Monero clearnet initial sync already completed (#234) — starting Tor-only." fi +mv -fT -- "$rendered" "$CONFIG_PATH" +umask "$mask" echo "Starting Monero Daemon (monerod)..." -# Execute the daemon process, replacing the current shell to ensure correct signal handling (SIGTERM) exec monerod --config-file="$CONFIG_PATH" --non-interactive diff --git a/build/tor/Dockerfile b/build/tor/Dockerfile index 1901d30064..0b7f4f6fc5 100644 --- a/build/tor/Dockerfile +++ b/build/tor/Dockerfile @@ -1,10 +1,11 @@ -# Pinned to a named minor version by digest (#135, #373). The digest is authoritative; the tag -# names the Alpine minor line (3.24) so Dependabot's patch-update policy has a real version to track. FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf -ARG TOR_VERSION=0.4.9.17-r0 -RUN apk add --no-cache --upgrade libcrypto3 libssl3 musl musl-utils "tor=${TOR_VERSION}" netcat-openbsd \ - && tor --version | grep -F "Tor version ${TOR_VERSION%-r*}." +ARG TOR_VERSION=0.4.9.18-r0 +RUN addgroup -S -g 101 tor \ + && adduser -S -D -H -h /var/lib/tor -s /sbin/nologin -u 100 -G tor -g tor tor \ + && apk add --no-cache --upgrade busybox busybox-binsh ssl_client libcrypto3 libssl3 musl musl-utils "tor=${TOR_VERSION}" netcat-openbsd \ + && tor --version | grep -F "Tor version ${TOR_VERSION%-r*}." \ + && [ "$(id -u tor):$(id -g tor)" = 100:101 ] COPY torrc.template /etc/tor/torrc.template COPY entrypoint.sh /usr/local/bin/tor-entrypoint.sh diff --git a/build/xmrig-proxy/entrypoint.sh b/build/xmrig-proxy/entrypoint.sh index eaa8beff39..22368c4a5e 100755 --- a/build/xmrig-proxy/entrypoint.sh +++ b/build/xmrig-proxy/entrypoint.sh @@ -17,6 +17,11 @@ fi TLS_MOUNT="${PROXY_TLS_MOUNT:-/tls}" if [ "${PROXY_STRATUM_TLS:-false}" = "true" ] && [ -f "$TLS_MOUNT/cert.pem" ] && [ -f "$TLS_MOUNT/key.pem" ]; then set -- "$@" "--tls-cert=$TLS_MOUNT/cert.pem" "--tls-cert-key=$TLS_MOUNT/key.pem" +elif [ "${PROXY_STRATUM_TLS:-false}" = "true" ]; then + missing="" + [ -f "$TLS_MOUNT/cert.pem" ] || missing="$TLS_MOUNT/cert.pem" + [ -f "$TLS_MOUNT/key.pem" ] || missing="${missing:+$missing and }$TLS_MOUNT/key.pem" + echo "xmrig-proxy: stratum TLS is on but the key pair is incomplete (missing: $missing); starting without TLS (cleartext only). Run './pithead apply' to create the key pair again and restart xmrig-proxy, then pin the new fingerprint on each rig." >&2 || true fi exec xmrig-proxy "$@" diff --git a/dashboard/mining_dashboard/client/rig_reply.py b/dashboard/mining_dashboard/client/rig_reply.py index 361b0438bc..1f68e683e0 100644 --- a/dashboard/mining_dashboard/client/rig_reply.py +++ b/dashboard/mining_dashboard/client/rig_reply.py @@ -1,8 +1,11 @@ +import json + from mining_dashboard.helper.utils import finite_number, plausible_rate, safe_text _TEXT_MAX = 1024 _NUMBER_MAX = 2**63 - 1 _DEPTH_MAX = 16 +_CONFIG_MAX = 65536 def _flag(value): @@ -22,6 +25,11 @@ def clip(value): return clip +def _config(value): + value = _bounded(value) + return value if isinstance(value, dict) and len(json.dumps(value)) <= _CONFIG_MAX else None + + _SHAPE = { "uptime": finite_number, "kind": _text(64), @@ -47,7 +55,7 @@ def clip(value): "max_temp_c": finite_number, }, "control": {"change_id": _text(64), "status": _text(64), "reason": _clipped(500)}, - "config": {}, + "config": _config, "config_meta": {}, }, } @@ -72,7 +80,11 @@ def _bounded(value, depth=0): if depth > _DEPTH_MAX: return None if isinstance(value, dict): - return {key[:_TEXT_MAX]: _bounded(item, depth + 1) for key, item in value.items()} + return { + key[:_TEXT_MAX]: _bounded(item, depth + 1) + for key, item in value.items() + if key.isprintable() + } if isinstance(value, list): return [_bounded(item, depth + 1) for item in value] if isinstance(value, str): diff --git a/dashboard/mining_dashboard/client/xvb_client.py b/dashboard/mining_dashboard/client/xvb_client.py index 9b522842c1..13303ef4b6 100644 --- a/dashboard/mining_dashboard/client/xvb_client.py +++ b/dashboard/mining_dashboard/client/xvb_client.py @@ -140,7 +140,7 @@ def parse_round_stats(text): players = int(fields[7]) except ValueError: continue - if players <= 0: + if not 0 < players <= 10**9: continue first_ts = ts if first_ts is None else max(first_ts, ts) last_ts = ts if last_ts is None else min(last_ts, ts) diff --git a/dashboard/mining_dashboard/service/data_helpers.py b/dashboard/mining_dashboard/service/data_helpers.py index 4bac731c9f..1f8a0a7ae7 100644 --- a/dashboard/mining_dashboard/service/data_helpers.py +++ b/dashboard/mining_dashboard/service/data_helpers.py @@ -15,6 +15,7 @@ from datetime import UTC, datetime from mining_dashboard.client.xmrig_client import parse_rigforge +from mining_dashboard.client.xvb_client import _WINNERS_MAX_FUTURE_S from mining_dashboard.config import config from mining_dashboard.helper.utils import effective_hashrate, get_tier_info from mining_dashboard.service import mining_verdict as mv @@ -77,7 +78,7 @@ def _xvb_winners_gate_sec(avg_1h, avg_24h, tiers, last_win_ts, now): _, threshold = get_tier_info(min(avg_1h, avg_24h), tiers) if threshold > 0 and avg_1h <= threshold * (1 + _XVB_WINNERS_MARGIN): return _XVB_WINNERS_SYNC_FAST_SEC - if last_win_ts > 0 and now - last_win_ts < _XVB_WIN_FRESH_S: + if last_win_ts > 0 and -_WINNERS_MAX_FUTURE_S <= now - last_win_ts < _XVB_WIN_FRESH_S: return _XVB_WINNERS_SYNC_FAST_SEC return _XVB_WINNERS_SYNC_SEC diff --git a/dashboard/mining_dashboard/service/data_xvb_sync.py b/dashboard/mining_dashboard/service/data_xvb_sync.py index 4227b6d7e5..4d2bcab82a 100644 --- a/dashboard/mining_dashboard/service/data_xvb_sync.py +++ b/dashboard/mining_dashboard/service/data_xvb_sync.py @@ -3,6 +3,7 @@ import time from mining_dashboard.client.xvb_client import ( + _WINNERS_MAX_FUTURE_S, REG_INVALID, REG_NOT_ELIGIBLE, REG_OK, @@ -117,7 +118,14 @@ async def _sync_xvb_winners(self): xvb.get("avg_1h", 0) or 0, xvb.get("avg_24h", 0) or 0, self.state_manager.get_tiers(), - max((w.get("ts", 0) or 0 for w in recent_wins), default=0.0), + max( + ( + ts + for w in recent_wins + if (ts := w.get("ts", 0) or 0) <= now + _WINNERS_MAX_FUTURE_S + ), + default=0.0, + ), now, ) if now - self._last_xvb_winners_sync < gate: diff --git a/dashboard/mining_dashboard/web/auth.py b/dashboard/mining_dashboard/web/auth.py index 0e9efab9d0..c50b90542b 100644 --- a/dashboard/mining_dashboard/web/auth.py +++ b/dashboard/mining_dashboard/web/auth.py @@ -24,6 +24,7 @@ MAX_CONCURRENT_VERIFY = 4 MAX_LOGIN_BYTES = 4096 MAX_FIELD_CHARS = 256 +CHALLENGE = {"WWW-Authenticate": 'Basic realm="restricted"', "Cache-Control": "no-store"} class Attempts: @@ -55,14 +56,26 @@ def trusted_proxy(request) -> bool: return False +def limiter_key(address): + try: + ip = ipaddress.ip_address(address) + except (ValueError, TypeError): + return address or "unknown" + if ip.version == 6 and ip.ipv4_mapped is not None: + return str(ip.ipv4_mapped) + if ip.version == 6: + return str(ipaddress.ip_network(f"{ip}/64", strict=False)) + return str(ip) + + def client_key(request): forwarded = request.headers.get("X-Forwarded-For", "").split(",")[0].strip() if trusted_proxy(request) and forwarded: try: - return str(ipaddress.ip_address(forwarded)) + return limiter_key(str(ipaddress.ip_address(forwarded))) except ValueError: pass - return request.remote or "unknown" + return limiter_key(request.remote) def secure(request): @@ -108,6 +121,54 @@ async def _verify(request, username, password): raise aiohttp.ClientError("unexpected verifier status") +async def _verify_counted(request, key, credentials) -> bool: + attempts = request.app["auth"]["attempts"] + wait = attempts.retry_after(key) + if wait or request.app["auth"]["busy"] >= MAX_CONCURRENT_VERIFY: + raise web.HTTPTooManyRequests( + text="Too many sign-in attempts. Try again shortly.", + headers={"Retry-After": str(wait or FAILURE_WINDOW)}, + ) + ok = False + if credentials is not None: + request.app["auth"]["busy"] += 1 + try: + ok = await _verify(request, *credentials) + except (aiohttp.ClientError, TimeoutError): + logger.warning("Sign-in verifier unreachable") + raise web.HTTPServiceUnavailable(text="Sign-in is temporarily unavailable.") from None + finally: + request.app["auth"]["busy"] -= 1 + if not ok: + attempts.failed(key) + return ok + + +def _basic_credentials(request) -> tuple[str, str] | None: + scheme, _, value = request.headers.get("Authorization", "").partition(" ") + if scheme.lower() != "basic": + return None + try: + raw = base64.b64decode(value.strip(), validate=True).decode() + except (ValueError, UnicodeDecodeError): + return None + username, sep, password = raw.partition(":") + if not sep or len(username) > MAX_FIELD_CHARS or len(password) > MAX_FIELD_CHARS: + return None + return username, password + + +async def basic(request) -> web.Response: + key = client_key(request) + credentials = _basic_credentials(request) + if not await _verify_counted(request, key, credentials): + logger.warning("Failed dashboard basic-auth sign-in from %s", key) + raise web.HTTPUnauthorized(text="Authentication required.", headers=CHALLENGE) + return web.Response( + status=204, headers={"X-Auth-User": credentials[0], "Cache-Control": "no-store"} + ) + + async def login(request): epoch = request.headers.get(EPOCH_HEADER, "") if not epoch: @@ -126,23 +187,8 @@ async def login(request): if len(username) > MAX_FIELD_CHARS or len(password) > MAX_FIELD_CHARS or ":" in username: return web.json_response({"error": "Invalid username or password."}, status=401) - attempts, key = request.app["auth"]["attempts"], client_key(request) - wait = attempts.retry_after(key) - if wait or request.app["auth"]["busy"] >= MAX_CONCURRENT_VERIFY: - raise web.HTTPTooManyRequests( - text="Too many sign-in attempts. Try again shortly.", - headers={"Retry-After": str(wait or FAILURE_WINDOW)}, - ) - request.app["auth"]["busy"] += 1 - try: - ok = await _verify(request, username, password) - except (aiohttp.ClientError, TimeoutError): - logger.warning("Sign-in verifier unreachable") - raise web.HTTPServiceUnavailable(text="Sign-in is temporarily unavailable.") from None - finally: - request.app["auth"]["busy"] -= 1 - if not ok: - attempts.failed(key) + key = client_key(request) + if not await _verify_counted(request, key, (username, password)): logger.warning("Failed dashboard sign-in from %s", key) return web.json_response({"error": "Invalid username or password."}, status=401) @@ -217,5 +263,6 @@ def setup(app): web.post("/api/auth/login", login), web.post("/api/auth/logout", logout), web.get("/api/auth/check", check), + web.get("/api/auth/basic", basic), ] ) diff --git a/dashboard/mining_dashboard/web/server.py b/dashboard/mining_dashboard/web/server.py index 18d1f34e68..462c072a29 100644 --- a/dashboard/mining_dashboard/web/server.py +++ b/dashboard/mining_dashboard/web/server.py @@ -344,6 +344,8 @@ async def handle_worker_apply(request): err = control_service.validate_worker_changes(changes) if err: raise web.HTTPBadRequest(text=err) + if "pools" in changes and body.get("confirm") != "APPLY": + raise web.HTTPBadRequest(text="A pools change needs the typed APPLY confirmation.") changes = strip_sentinel_credentials(changes) actor = request.headers.get("X-Auth-User", "") state_mgr = request.app["state_manager"] diff --git a/dashboard/mining_dashboard/web/static/workers/workerpools.mjs b/dashboard/mining_dashboard/web/static/workers/workerpools.mjs new file mode 100644 index 0000000000..5a961f66a0 --- /dev/null +++ b/dashboard/mining_dashboard/web/static/workers/workerpools.mjs @@ -0,0 +1,22 @@ +import { html } from "../app/preact.mjs"; + +export const POOLS_HELD = { + status: "error", + error: "This changes the rig's pools. Type APPLY to confirm.", +}; + +export const POOLS_HOLD = { result: POOLS_HELD, poolsConfirm: "" }; + +export const poolsHeld = (changes, { result, poolsConfirm }) => + "pools" in changes && !(result === POOLS_HELD && poolsConfirm === "APPLY"); + +export const applyRequest = (worker, changes) => + "pools" in changes ? { worker, changes, confirm: "APPLY" } : { worker, changes }; + +export function PoolsConfirm({ view }) { + const { poolsConfirm, result } = view.state; + if (result !== POOLS_HELD) return null; + return html``; +} diff --git a/dashboard/mining_dashboard/web/static/workers/workerview.mjs b/dashboard/mining_dashboard/web/static/workers/workerview.mjs index 22f7060952..54f51b8787 100644 --- a/dashboard/mining_dashboard/web/static/workers/workerview.mjs +++ b/dashboard/mining_dashboard/web/static/workers/workerview.mjs @@ -28,6 +28,7 @@ import { parseJsonChanges, rigforgeReportsTarget, } from "./workerlogic.mjs"; +import { applyRequest, POOLS_HOLD, PoolsConfirm, poolsHeld } from "./workerpools.mjs"; import { CONTROL_HEADERS, pollWorkerResult, @@ -105,9 +106,7 @@ export class WorkerInspect extends Component { jsonError: null, busy: false, result: null, - // Per-worker hashrate chart (#1013): its own range preference (persisted, like the editor - // mode above) and its own loading flag — a range switch refetches ONLY the chart data - // (loadChart), never the full load(), so it can't wipe an in-progress config edit. + poolsConfirm: "", chartRange: loadPref("dashboardWorkerChartRange", ["24h", "1w", "all"], "24h"), chartLoading: false, waitVersion: null, @@ -244,17 +243,18 @@ export class WorkerInspect extends Component { this.setState({ result: { status: "error", error: "No changes to apply." } }); return; } + if (poolsHeld(changes, this.state)) return this.setState(POOLS_HOLD); this.setState({ busy: true, result: { status: "running" } }); try { const res = await fetch("/api/control/worker-apply", { method: "POST", headers: CONTROL_HEADERS, - body: JSON.stringify({ worker: this.props.name, changes }), + body: JSON.stringify(applyRequest(this.props.name, changes)), }); let out = await res.json(); if (out.status === "pending") out = await pollWorkerResult(out.id); this.setState({ busy: false, result: out }); - this.load(); // refresh telemetry + history with the new row + this.load(); } catch (e) { this.setState({ busy: false, result: { status: "error", error: String(e) } }); } @@ -334,6 +334,7 @@ export class WorkerInspect extends Component { }
Unsaved — Apply before closing, or the change is lost.
` : null} <${StatusLine} result=${result} />` diff --git a/dashboard/mining_dashboard/wizard/server.py b/dashboard/mining_dashboard/wizard/server.py index e63209146d..0d6765ac31 100644 --- a/dashboard/mining_dashboard/wizard/server.py +++ b/dashboard/mining_dashboard/wizard/server.py @@ -36,6 +36,7 @@ from aiohttp import web from mining_dashboard.config import documents +from mining_dashboard.web.auth import limiter_key from mining_dashboard.wizard.defaults import ( disk_inventory, explicit_wizard_config, @@ -193,9 +194,13 @@ def _disks() -> list[dict]: return disk_inventory(_spool_read("disks.tsv") or "") +def _mac(tok: str) -> str: + return hmac.new(tok.encode(), COOKIE.encode(), "sha256").hexdigest() + + def _authed(request: web.Request) -> bool: tok = os.environ.get("WIZARD_TOKEN", "") - return bool(tok) and hmac.compare_digest(request.cookies.get(COOKIE, ""), tok) + return bool(tok) and hmac.compare_digest(request.cookies.get(COOKIE, ""), _mac(tok)) async def index(request: web.Request) -> web.Response: @@ -219,7 +224,7 @@ async def auth(request: web.Request) -> web.Response: for peer, (_, until) in list(failures.items()): if until <= now: del failures[peer] - peer = request.remote + peer = limiter_key(request.remote) count, until = failures.get(peer, (0, now + AUTH_COOLDOWN_SECONDS)) if count >= MAX_FAILURES: return _auth_throttled(until - now) @@ -229,11 +234,7 @@ async def auth(request: web.Request) -> web.Response: failures.pop(peer, None) resp = web.HTTPFound("/") resp.set_cookie( - COOKIE, - tok, - httponly=True, - secure=request.app["secure_cookie"], - samesite="Strict", + COOKIE, _mac(tok), httponly=True, secure=request.app["secure_cookie"], samesite="Strict" ) raise resp if peer not in failures and len(failures) >= MAX_AUTH_CLIENTS: @@ -648,10 +649,6 @@ def main() -> None: bind = os.environ.get("WIZARD_BIND", "0.0.0.0:8000") cert = os.environ.get("WIZARD_TLS_CERT", "") key = os.environ.get("WIZARD_TLS_KEY", "") - # TLS because this page carries real secrets — node passwords, a Telegram bot token, a - # view key if one is pasted into the config. A self-signed certificate warns the browser, - # which is the honest tradeoff: the alternative is those secrets in clear on the LAN. The - # console prints the fingerprint so the warning can actually be checked. if cert and key and os.path.exists(cert) and os.path.exists(key): tls_bind = os.environ.get("WIZARD_BIND_TLS", "0.0.0.0:8443") asyncio.run(_run_both(bind, tls_bind, cert, key)) diff --git a/dashboard/tests/client/test_rig_reply.py b/dashboard/tests/client/test_rig_reply.py index d3ba730394..a0a105b649 100644 --- a/dashboard/tests/client/test_rig_reply.py +++ b/dashboard/tests/client/test_rig_reply.py @@ -170,6 +170,31 @@ def test_a_large_unlisted_counter_is_kept(): } +def test_keys_that_are_not_printable_text_are_dropped_with_their_value(): + reply = _reply( + '{"extra": {"a\\u202eb": 1, "ok": 2}, "rigforge": {"config": {"x\\ny": "v",' + ' "pools": [{"u\\u202erl": "h:1", "url": "h:2"}], "DONATION": 1}}}' + ) + assert reply["extra"] == {"ok": 2} + assert reply["rigforge"]["config"] == {"pools": [{"url": "h:2"}], "DONATION": 1} + + +def test_a_config_block_over_the_size_limit_is_dropped_and_the_rest_kept(): + config = {f"k{i}": "v" * 1000 for i in range(70)} + reply = _reply(json.dumps({"uptime": 5, "rigforge": {"version": "1.2.3", "config": config}})) + assert reply["uptime"] == 5 and reply["rigforge"] == {"version": "1.2.3"} + assert parse_rigforge(reply)["config"] is None + assert _reply('{"rigforge": {"config": "x"}}')["rigforge"] == {} + + +def test_a_config_block_under_the_size_limit_is_kept(): + config = {f"k{i}": "v" * 1000 for i in range(60)} + config["DONATION"] = 1 + reply = _reply(json.dumps({"rigforge": {"config": config}})) + assert reply["rigforge"]["config"] == config + assert parse_rigforge(reply)["config"] == {"DONATION": 1} + + class _Response: def __init__(self, status, payload): self.status, self._raw, self.content = status, json.dumps(payload).encode(), self diff --git a/dashboard/tests/client/test_xvb_untrusted.py b/dashboard/tests/client/test_xvb_untrusted.py index 6c3832ff35..93e837326c 100644 --- a/dashboard/tests/client/test_xvb_untrusted.py +++ b/dashboard/tests/client/test_xvb_untrusted.py @@ -2,7 +2,7 @@ import pytest -from mining_dashboard.client.xvb_client import XvbClient, parse_winners +from mining_dashboard.client.xvb_client import XvbClient, parse_round_stats, parse_winners WALLET = "48M2j8GjINNERPARTd8KgGBwa" ROW = "48M2j8Gj...d8KgGBwa\t{when}\t{rate}\t{height}\t\t{block}\t1/1\t1\tdonor\n" @@ -87,3 +87,22 @@ def test_winners_rows_dated_in_the_future_are_dropped(): when="2026-07-18 20:41:38", rate="1kH/s", height=2, block="past" ) assert [win["block_id"] for win in parse_winners(text, WALLET)] == ["past"] + + +@pytest.mark.parametrize("players", ["9" * 400, "9" * 4000, str(10**9 + 1), "0"]) +def test_round_stats_rows_with_a_players_count_out_of_range_are_skipped(players): + when = "2026-07-18 20:41:38" + text = ROW.format(when=when, rate="1kH/s", height=1, block="a").replace( + "\t1\tdonor", "\t27\tdonor" + ) + text += ROW.format(when=when, rate="1kH/s", height=2, block="b").replace( + "\t1\tdonor", f"\t{players}\tdonor" + ) + assert parse_round_stats(text)["types"] == {"donor": {"rounds": 1, "players_avg": 27.0}} + + +def test_round_stats_keep_a_players_count_at_the_limit(): + text = ROW.format(when="2026-07-18 20:41:38", rate="1kH/s", height=1, block="a").replace( + "\t1\tdonor", f"\t{10**9}\tdonor" + ) + assert parse_round_stats(text)["types"] == {"donor": {"rounds": 1, "players_avg": 1e9}} diff --git a/dashboard/tests/frontend/workers/workerpoolcredentials.test.mjs b/dashboard/tests/frontend/workers/workerpoolcredentials.test.mjs index 339adfdf76..aaed496ac4 100644 --- a/dashboard/tests/frontend/workers/workerpoolcredentials.test.mjs +++ b/dashboard/tests/frontend/workers/workerpoolcredentials.test.mjs @@ -14,6 +14,7 @@ import assert from "node:assert/strict"; import { test } from "node:test"; +import { POOLS_HELD } from "../../../mining_dashboard/web/static/workers/workerpools.mjs"; import { WorkerInspect } from "../../../mining_dashboard/web/static/workers/workerview.mjs"; const SENTINEL = { __secret__: true }; @@ -96,6 +97,7 @@ test("table mode: editing the pools row without a real password strips the senti { url: "pool.example:3333", user: "wallet.rig1", pass: SENTINEL, keepalive: true }, ]), }; + Object.assign(inst.state, { result: POOLS_HELD, poolsConfirm: "APPLY" }); let posted = null; const realFetch = globalThis.fetch; globalThis.fetch = async (url, opts) => { diff --git a/dashboard/tests/frontend/workers/workerview-pools.test.mjs b/dashboard/tests/frontend/workers/workerview-pools.test.mjs new file mode 100644 index 0000000000..b879c4c7d6 --- /dev/null +++ b/dashboard/tests/frontend/workers/workerview-pools.test.mjs @@ -0,0 +1,79 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { renderToString } from "../helpers/render.mjs"; +import { DETAIL, readyInstance } from "./workerview-helpers.mjs"; + +const CONFIRM_PROMPT = /TypeAPPLY<\/code> to change this rig's pools/;
+
+function captureApplies() {
+ const posted = [];
+ const realFetch = globalThis.fetch;
+ globalThis.fetch = async (_url, opts) => {
+ posted.push(JSON.parse(opts.body));
+ return { json: async () => ({ status: "applied" }) };
+ };
+ return { posted, restore: () => (globalThis.fetch = realFetch) };
+}
+
+test("a pools change is held until APPLY is typed, then sent with the confirmation", async () => {
+ const inst = readyInstance({ ...DETAIL, writable_keys: [...DETAIL.writable_keys, "pools"] });
+ inst.state.mode = "json";
+ inst.onJsonInput(JSON.stringify({ pools: [{ url: "pool.example:3333" }] }));
+ assert.doesNotMatch(renderToString(inst.render()), CONFIRM_PROMPT);
+ const { posted, restore } = captureApplies();
+ try {
+ await inst.apply();
+ assert.equal(posted.length, 0);
+ assert.match(renderToString(inst.render()), CONFIRM_PROMPT);
+ inst.state.poolsConfirm = "apply";
+ await inst.apply();
+ assert.equal(posted.length, 0);
+ assert.match(renderToString(inst.render()), CONFIRM_PROMPT);
+ inst.state.poolsConfirm = "APPLY";
+ await inst.apply();
+ } finally {
+ restore();
+ }
+ assert.equal(posted.length, 1);
+ assert.equal(posted[0].confirm, "APPLY");
+ assert.deepEqual(posted[0].changes, { pools: [{ url: "pool.example:3333" }] });
+ assert.doesNotMatch(renderToString(inst.render()), CONFIRM_PROMPT);
+});
+
+test("a typed APPLY does not carry past a failed send: the next pools change is held again", async () => {
+ const inst = readyInstance({ ...DETAIL, writable_keys: [...DETAIL.writable_keys, "pools"] });
+ inst.state.mode = "json";
+ inst.onJsonInput(JSON.stringify({ pools: [{ url: "pool.example:3333" }] }));
+ const realFetch = globalThis.fetch;
+ let sends = 0;
+ globalThis.fetch = async () => {
+ sends += 1;
+ throw new Error("network down");
+ };
+ try {
+ await inst.apply();
+ inst.state.poolsConfirm = "APPLY";
+ await inst.apply();
+ assert.equal(sends, 1);
+ assert.match(inst.state.result.error, /network down/);
+ await inst.apply();
+ } finally {
+ globalThis.fetch = realFetch;
+ }
+ assert.equal(sends, 1);
+ assert.equal(inst.state.poolsConfirm, "");
+ assert.match(renderToString(inst.render()), CONFIRM_PROMPT);
+});
+
+test("a change without pools sends no confirmation field", async () => {
+ const inst = readyInstance();
+ inst.state.tableEdits = { DONATION: "6" };
+ const { posted, restore } = captureApplies();
+ try {
+ await inst.apply();
+ } finally {
+ restore();
+ }
+ assert.equal(posted.length, 1);
+ assert.ok(!("confirm" in posted[0]));
+});
diff --git a/dashboard/tests/service/test_xvb_winners_gate_window.py b/dashboard/tests/service/test_xvb_winners_gate_window.py
new file mode 100644
index 0000000000..9b1f1f1959
--- /dev/null
+++ b/dashboard/tests/service/test_xvb_winners_gate_window.py
@@ -0,0 +1,54 @@
+import time
+from unittest.mock import MagicMock
+
+from mining_dashboard.service.data_helpers import (
+ _XVB_WINNERS_SYNC_FAST_SEC,
+ _XVB_WINNERS_SYNC_SEC,
+ _xvb_winners_gate_sec,
+)
+from mining_dashboard.service.data_service import DataService
+
+TIERS = {"donor": 1_000, "donor_whale": 100_000}
+NOW = 1_000_000.0
+
+
+def _gate(last_win_ts):
+ return _xvb_winners_gate_sec(250_000, 250_000, TIERS, last_win_ts, NOW)
+
+
+def test_a_win_dated_more_than_an_hour_ahead_keeps_the_baseline():
+ assert _gate(NOW + 3601) == _XVB_WINNERS_SYNC_SEC
+ assert _gate(NOW + 86_400 * 365) == _XVB_WINNERS_SYNC_SEC
+
+
+def test_a_win_up_to_an_hour_ahead_or_in_the_fresh_window_is_fast():
+ assert _gate(NOW + 3600) == _XVB_WINNERS_SYNC_FAST_SEC
+ assert _gate(NOW) == _XVB_WINNERS_SYNC_FAST_SEC
+ assert _gate(NOW - 5399) == _XVB_WINNERS_SYNC_FAST_SEC
+ assert _gate(NOW - 5400) == _XVB_WINNERS_SYNC_SEC
+
+
+async def _fetches_after(wins, wait):
+ sm = MagicMock()
+ sm.load_snapshot.return_value = None
+ sm.get_xvb_stats.return_value = {"avg_1h": 250_000, "avg_24h": 250_000}
+ sm.get_tiers.return_value = TIERS
+ sm.get_raffle_wins.return_value = wins
+ sm.add_raffle_wins.return_value = []
+ svc = DataService(sm, MagicMock(), MagicMock())
+ svc.xvb_client.get_recent_wins.return_value = {"wins": [], "round_stats": {}}
+ await svc._sync_xvb_winners()
+ svc._last_xvb_winners_sync -= wait
+ await svc._sync_xvb_winners()
+ return svc.xvb_client.get_recent_wins.call_count
+
+
+async def test_a_far_future_row_does_not_hide_a_fresh_win():
+ now = time.time()
+ wins = [{"ts": now - 600}, {"ts": now + 86_400 * 365}]
+ assert await _fetches_after(wins, _XVB_WINNERS_SYNC_FAST_SEC + 1) == 2
+
+
+async def test_a_far_future_row_alone_keeps_the_baseline():
+ wins = [{"ts": time.time() + 86_400 * 365}]
+ assert await _fetches_after(wins, _XVB_WINNERS_SYNC_FAST_SEC + 1) == 1
diff --git a/dashboard/tests/web/test_auth.py b/dashboard/tests/web/test_auth.py
index 400c53f5b0..58e9f4f334 100644
--- a/dashboard/tests/web/test_auth.py
+++ b/dashboard/tests/web/test_auth.py
@@ -120,6 +120,18 @@ async def test_rate_limit_is_per_client(self, stack):
other = await login(stack, headers={**EPOCH, "X-Forwarded-For": "10.0.0.2"})
assert other.status == 200
+ async def test_rate_limit_counts_one_ipv6_network_as_one_client(self, stack):
+ for n in range(auth.FAILURE_LIMIT):
+ await login(
+ stack,
+ password="nope",
+ headers={**EPOCH, "X-Forwarded-For": f"2001:db8:1:2::{n + 1}"},
+ )
+ same_net = await login(stack, headers={**EPOCH, "X-Forwarded-For": "2001:db8:1:2:abcd::9"})
+ assert same_net.status == 429
+ other_net = await login(stack, headers={**EPOCH, "X-Forwarded-For": "2001:db8:1:3::1"})
+ assert other_net.status == 200
+
async def test_concurrent_verifications_beyond_the_cap_are_refused(self, stack):
release = asyncio.Event()
started = []
@@ -159,6 +171,60 @@ async def test_login_page_is_served(self, stack):
assert 'id="login-remember"' in await resp.text()
+def basic_header(user=GOOD[0], password=GOOD[1]):
+ raw = base64.b64encode(f"{user}:{password}".encode()).decode()
+ return {"Authorization": "Basic " + raw}
+
+
+class TestBasic:
+ async def test_good_credentials_pass_with_the_actor(self, stack):
+ resp = await stack.get("/api/auth/basic", headers=basic_header())
+ assert resp.status == 204
+ assert resp.headers["X-Auth-User"] == "admin"
+
+ async def test_wrong_password_is_challenged(self, stack):
+ resp = await stack.get("/api/auth/basic", headers=basic_header(password="nope"))
+ assert resp.status == 401
+ assert resp.headers["WWW-Authenticate"] == 'Basic realm="restricted"'
+ assert "X-Auth-User" not in resp.headers
+
+ async def test_repeated_failures_lock_out_even_good_credentials(self, stack, verifier_calls):
+ for _ in range(auth.FAILURE_LIMIT):
+ bad = await stack.get("/api/auth/basic", headers=basic_header(password="nope"))
+ assert bad.status == 401
+ before = len(verifier_calls)
+ locked = await stack.get("/api/auth/basic", headers=basic_header())
+ assert locked.status == 429
+ assert int(locked.headers["Retry-After"]) >= 1
+ assert len(verifier_calls) == before
+
+ async def test_malformed_credentials_count_without_reaching_the_verifier(
+ self, stack, verifier_calls
+ ):
+ for value in ("Basic !!!", "Basic " + base64.b64encode(b"no-colon").decode()):
+ resp = await stack.get("/api/auth/basic", headers={"Authorization": value})
+ assert resp.status == 401
+ assert verifier_calls == []
+ assert len(stack.server.app["auth"]["attempts"]._failures["127.0.0.1"]) == 2
+
+ async def test_basic_and_form_failures_share_one_budget(self, stack):
+ for _ in range(auth.FAILURE_LIMIT - 1):
+ await stack.get("/api/auth/basic", headers=basic_header(password="nope"))
+ assert (await login(stack, password="nope")).status == 401
+ assert (await login(stack)).status == 429
+
+ async def test_the_limit_is_per_client(self, stack):
+ for _ in range(auth.FAILURE_LIMIT):
+ await stack.get(
+ "/api/auth/basic",
+ headers={**basic_header(password="nope"), "X-Forwarded-For": "10.0.2.1"},
+ )
+ other = await stack.get(
+ "/api/auth/basic", headers={**basic_header(), "X-Forwarded-For": "10.0.2.2"}
+ )
+ assert other.status == 204
+
+
class TestCheck:
async def signed_in(self, stack, **kw):
await login(stack, **kw)
@@ -308,3 +374,20 @@ def test_tracked_clients_are_bounded_and_evict_the_oldest(self):
assert len(attempts._failures) == auth.MAX_TRACKED_CLIENTS
assert "c0" not in attempts._failures
assert "new" in attempts._failures
+
+
+@pytest.mark.parametrize(
+ ("address", "key"),
+ [
+ ("192.0.2.7", "192.0.2.7"),
+ ("2001:db8:1:2:3:4:5:6", "2001:db8:1:2::/64"),
+ ("2001:db8:1:2::", "2001:db8:1:2::/64"),
+ ("::ffff:192.0.2.7", "192.0.2.7"),
+ ("::1", "::/64"),
+ ("not-an-address", "not-an-address"),
+ (None, "unknown"),
+ ("", "unknown"),
+ ],
+)
+def test_limiter_key_groups_ipv6_by_64_and_keeps_ipv4_whole(address, key):
+ assert auth.limiter_key(address) == key
diff --git a/dashboard/tests/web/test_server_worker_apply_edge_cases.py b/dashboard/tests/web/test_server_worker_apply_edge_cases.py
index a1349b78b7..dc22d7c3e6 100644
--- a/dashboard/tests/web/test_server_worker_apply_edge_cases.py
+++ b/dashboard/tests/web/test_server_worker_apply_edge_cases.py
@@ -30,3 +30,14 @@ async def test_apply_pending_when_runner_silent(
assert resp.status == 202
assert (await resp.json())["status"] == "pending"
assert worker_client.sm.get_worker_config_history("rig1") == [] # no terminal outcome yet
+
+
+@pytest.mark.parametrize("confirm", [None, "", "apply", "yes"])
+async def test_pools_change_without_typed_apply_is_refused(worker_client, control_spool, confirm):
+ body = {"worker": "rig1", "changes": {"pools": [{"url": "pool.example:3333"}]}}
+ if confirm is not None:
+ body["confirm"] = confirm
+ resp = await worker_client.post("/api/control/worker-apply", json=body, headers=CONTROL_HEADERS)
+ assert resp.status == 400
+ assert "typed APPLY" in await resp.text()
+ assert not list((control_spool / "requests").glob("*.json"))
diff --git a/dashboard/tests/web/test_server_worker_inspect.py b/dashboard/tests/web/test_server_worker_inspect.py
index e31d594e0f..ec1550151a 100644
--- a/dashboard/tests/web/test_server_worker_inspect.py
+++ b/dashboard/tests/web/test_server_worker_inspect.py
@@ -52,7 +52,7 @@ async def test_worker_apply_spools_tokenless_intent_and_records_history(
scrubbed = {"DONATION": 3, "pools": [{"url": "rig:3333"}]}
resp = await worker_client.post(
"/api/control/worker-apply",
- json={"worker": "rig1", "changes": sent},
+ json={"worker": "rig1", "changes": sent, "confirm": "APPLY"},
headers=CONTROL_HEADERS,
)
assert resp.status == 200
diff --git a/dashboard/tests/web/test_wizard_auth.py b/dashboard/tests/web/test_wizard_auth.py
index beeb288d8f..caf67d4776 100644
--- a/dashboard/tests/web/test_wizard_auth.py
+++ b/dashboard/tests/web/test_wizard_auth.py
@@ -1,4 +1,6 @@
# ruff: noqa: F403, F405
+import hmac
+
from tests.web._wizard_support import * # noqa: F403
@@ -110,6 +112,26 @@ async def test_authenticated_operator_sharing_blocked_peer_keeps_session(auth_cl
assert (await offender.get("/api/wizard-state")).status == 401
+async def test_lockout_counts_one_ipv6_network_as_one_client(auth_clients):
+ operator, _, exits = auth_clients
+ for attempt in range(wizard.MAX_FAILURES):
+ r = await operator.post(
+ "/auth",
+ data={"token": "pit-WRONGX"},
+ headers={"X-Test-Peer": f"2001:db8:5:6::{attempt + 1}"},
+ )
+ assert r.status == (403 if attempt < wizard.MAX_FAILURES - 1 else 429)
+ same_net = await operator.post(
+ "/auth", data={"token": "pit-WRONGX"}, headers={"X-Test-Peer": "2001:db8:5:6:ffff::1"}
+ )
+ assert same_net.status == 429
+ other_net = await operator.post(
+ "/auth", data={"token": "pit-WRONGX"}, headers={"X-Test-Peer": "2001:db8:5:7::1"}
+ )
+ assert other_net.status == 403
+ assert exits == []
+
+
async def test_failure_tracking_is_bounded_without_resetting_existing_peer(
auth_clients, monkeypatch
):
@@ -126,3 +148,45 @@ async def test_failure_tracking_is_bounded_without_resetting_existing_peer(
for _ in range(wizard.MAX_FAILURES - 2):
assert (await _auth(operator, "pit-WRONGX")).status == 403
assert (await _auth(operator, "pit-WRONGX")).status == 429
+
+
+def _derived(code):
+ return hmac.new(code.encode(), b"wizard_session", "sha256").hexdigest()
+
+
+async def _state_with(client, value):
+ return (await client.get("/api/wizard-state", cookies={wizard.COOKIE: value})).status
+
+
+async def test_session_cookie_holds_a_value_derived_from_the_code(client):
+ r = await _auth(client, "x7km2q")
+ value = r.cookies[wizard.COOKIE].value
+ assert value == _derived("pit-X7KM2Q")
+ assert "X7KM2Q" not in value.upper()
+ assert "HttpOnly" in r.headers["Set-Cookie"]
+ assert (await client.get("/api/wizard-state")).status == 200
+
+
+async def test_raw_code_cookie_is_not_a_session(client):
+ assert await _state_with(client, "pit-X7KM2Q") == 401
+ assert await _state_with(client, "X7KM2Q") == 401
+
+
+async def test_session_cookie_is_bound_to_the_current_code(client, monkeypatch):
+ assert await _state_with(client, _derived("pit-X7KM2Q")) == 200
+ assert await _state_with(client, _derived("pit-OTHER2")) == 401
+ monkeypatch.setenv("WIZARD_TOKEN", "pit-OTHER2")
+ assert await _state_with(client, _derived("pit-X7KM2Q")) == 401
+ assert await _state_with(client, _derived("pit-OTHER2")) == 200
+ monkeypatch.setenv("WIZARD_TOKEN", "")
+ assert await _state_with(client, _derived("")) == 401
+
+
+async def test_session_cookie_stays_valid_across_a_restart_with_the_same_code(client):
+ value = (await _auth(client)).cookies[wizard.COOKIE].value
+ async with TestClient(TestServer(wizard.make_app())) as restarted:
+ assert await _state_with(restarted, value) == 200
+
+
+async def test_session_value_is_not_accepted_as_the_code(client):
+ assert (await _auth(client, _derived("pit-X7KM2Q"))).status == 403
diff --git a/docker-compose.yml b/docker-compose.yml
index 441b81b052..e9958e520b 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -285,15 +285,9 @@ services:
- /tmp:size=64m,mode=1777
volumes:
- ${TARI_DATA_DIR}:/var/tari/node
- - ./build/tari:/var/tari/config
- # pithead's "LAN-only source rule is live" marker (#2749), as for monerod.
+ - ./build/tari:/var/tari/config:ro
- ./data/lan-guard:/lan-guard:ro
- # Read-only view of the shared clearnet-state dir (#234): the wrapper entrypoint reads the
- # dashboard-written "sync complete" marker to decide clearnet-vs-Tor at startup.
- ${CLEARNET_STATE_DIR:-./data/clearnet-state}:/clearnet-state:ro
- # Pithead wrapper (#183/#234): renders the runtime config (clearnet-vs-Tor, marker-gated) from
- # pithead's canonical Tor config, then runs and supervises minotari_node, rewinding a database
- # left on the dead 5.3.1 branch past the 350,000 fork first (#2618).
entrypoint:
- /var/tari/config/entrypoint.sh
command:
@@ -1027,21 +1021,10 @@ services:
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy_data:/data
- # JSON access log (#349): Caddy rolls it natively (4 MiB × 3 files, see generate_caddyfile);
- # the dashboard mounts the same dir read-only to show recent accesses and failed logins.
- ${CADDY_LOG_DIR:-./data/caddy-logs}:/var/log/caddy
- # The appliance's own certificate — the same one its setup page served, so the browser
- # that trusted it there is not asked again by the dashboard. Empty on DIY, where Caddy
- # keeps managing its internal CA (`tls internal`) and this mount is simply unused.
- ${PITHEAD_TLS_DIR:-./data/tls}:/pithead-tls:ro
healthcheck:
- # Config-loaded liveness (#904): probe Caddy's admin API on its default localhost:2019 bind
- # (the host loopback under network_mode: host; the generated Caddyfile never disables it).
- # /config/ answers 200 only from a running Caddy with its config loaded — more than
- # process-up, but deliberately not a vhost probe: the LAN vhost's scheme, port and auth all
- # vary with config, and busybox wget can't speak the internal-CA TLS. wget ships in the
- # alpine-based image (curl does not).
- test: ["CMD", "wget", "-q", "--spider", "-T", "5", "http://127.0.0.1:2019/config/"]
+ test: ["CMD", "wget", "-q", "--spider", "-T", "5", "http://127.0.0.1:2019/"]
interval: 30s
timeout: 5s
retries: 3
diff --git a/docs/appliance.md b/docs/appliance.md
index 086ccd4c89..834a2a3ded 100644
--- a/docs/appliance.md
+++ b/docs/appliance.md
@@ -711,6 +711,11 @@ failure in the `pithead-data-reset` service journal. An unavailable read-only pr
does not authorize further repairs or erasure. A reformat also requires its mount
directory to be allocated before formatting starts.
+If a factory reset you asked for cannot finish reformatting the data area, the reset
+stays requested: the `pithead-data-reset` service journal records the failure, the
+reset runs again at the next boot, and
+`cd /data/pithead && ./pithead doctor` warns until it has run.
+
## Recovering from a backup
Fresh flash, restore, done — if the machine is gone (dead disk, stolen, dropped), a backup
@@ -823,7 +828,7 @@ appliance; a manually deployed debug image carries its own SSH key for developme
**"Wrong token."** A generated token changes each time the setup service restarts; a valid
preseed token is reused. Read the current token from the console or your preseed file.
Five wrong attempts from the same network peer start a 60-second
-cooldown. Wait for the time shown on the page, then retry the same token; the wizard stays open
+cooldown. An IPv6 peer is counted by its /64 network, so devices sharing one /64 share the five. Wait for the time shown on the page, then retry the same token; the wizard stays open
and other authenticated operators keep their sessions.
**The address was rejected.** For Monero you most likely pasted a subaddress (starts with
diff --git a/docs/configuration.md b/docs/configuration.md
index 0c4ecb6fc6..f852ca48c9 100644
--- a/docs/configuration.md
+++ b/docs/configuration.md
@@ -290,7 +290,7 @@ the desired value is not presented as proof of what the still-running services u
| `dashboard.data_dir` | `auto` | Where the dashboard's database lives. `auto` = `./data/dashboard`, unless the four other `*.data_dir` all point under one parent directory — then the dashboard joins them at `/dashboard`. `upgrade`/`apply` moves the live database automatically only from the old in-install default. A confirmed change to an explicit path copies and verifies the database, including the payout-wallet alarm baseline, and leaves the old copy in place; a non-empty target refuses the change rather than guessing (see [Data directories](#data-directories)). |
| `dashboard.check_for_updates` | `true` _(on)_ | The dashboard periodically asks GitHub whether a newer Pithead release exists and, if so, shows a header badge linking to it (e.g. "New release v1.4.0 available"). Notify-only: it never updates anything; you upgrade with `./pithead upgrade` on your own terms. On by default because the check is routed over Tor (the same bridge SOCKS as the XvB fetch, `socks5h` so the DNS lookup goes through Tor too), so GitHub sees a Tor exit, not your IP. It's cached (hourly) and fails silently offline. The same flag also covers the per-worker [RigForge new-release badge](workers.md#rigforge-new-release-badge) — one more hourly, Tor-routed fetch of the latest RigForge release, compared against every rig's reported version. Set to `false` to opt out of both. See [Privacy › Runtime egress](privacy.md#runtime-egress). |
| `network.subnet` | `172.28.0.0/24` | The private Docker bridge the stack's containers run on. Change it only if install fails with `Pool overlaps with other one on this address space`, i.e. your host already uses `172.28.0.0/24` for another Docker network or interface. Must be a free `X.Y.Z.0/24` block (e.g. `"172.30.0.0/24"`); the services keep their fixed host octets (`.25`–`.31`) within it, so the structured addressing the dashboard and the worker SSRF guard rely on is preserved. |
-| `network.tor_egress_firewall` | `true` _(on)_ | Privacy-relevant, default on. Enforces "behind Tor" fail-closed: at `up`/`apply`, `pithead` installs host firewall rules (Docker's `DOCKER-USER` chain) that drop any direct clearnet dial from the mining containers (monerod/p2pool/tari/xmrig-proxy). Only Tor and containers explicitly selected for clearnet can reach the public internet directly; every other mining container remains blocked. On a DIY host `pithead-egress.service` restores the rules at boot, before Docker starts the containers. Needs root (like the GRUB/HugePages steps); removed at `down`. Set `false` (which also removes the boot unit) to skip it and rely on per-app Tor config only (e.g. a host where you manage egress yourself, or where `iptables` isn't available). An opted-in Monero or Tari initial sync gets an exception for that node only; the host removes and verifies it before the node restarts on Tor, then attests the live daemon and rules. P2Pool also gets a scoped exception while `p2pool.clearnet` is true; xmrig-proxy gets one only while XvB is enabled and `xvb.tor` is false. Each is removed at apply when its choice is turned off. Every other container keeps its restriction. See [Privacy › Optional clearnet initial sync](privacy.md#optional-clearnet-initial-sync-off-by-default). Full detail: [Privacy › Enforced fail-closed](privacy.md#enforced-fail-closed-not-just-configured-270). |
+| `network.tor_egress_firewall` | `true` _(on)_ | Privacy-relevant, default on. Enforces "behind Tor" fail-closed: at `up`/`apply`, `pithead` installs host firewall rules (Docker's `DOCKER-USER` chain) that drop any direct clearnet dial from the mining containers (monerod/p2pool/tari/xmrig-proxy). Only Tor and containers explicitly selected for clearnet can reach the public internet directly; every other mining container remains blocked. On a DIY host `pithead-egress.service` restores the rules at boot, before Docker starts the containers. Needs root (like the GRUB/HugePages steps); removed at `down`. If the rules cannot be installed, `up` and `apply` stop before starting any container. Set `false` (which also removes the boot unit) to skip it and rely on per-app Tor config only (e.g. a host where you manage egress yourself, or where `iptables` isn't available). An opted-in Monero or Tari initial sync gets an exception for that node only; the host removes and verifies it before the node restarts on Tor, then attests the live daemon and rules. P2Pool also gets a scoped exception while `p2pool.clearnet` is true; xmrig-proxy gets one only while XvB is enabled and `xvb.tor` is false. Each is removed at apply when its choice is turned off. Every other container keeps its restriction. See [Privacy › Optional clearnet initial sync](privacy.md#optional-clearnet-initial-sync-off-by-default). Full detail: [Privacy › Enforced fail-closed](privacy.md#enforced-fail-closed-not-just-configured-270). |
---
@@ -482,7 +482,7 @@ How it works and what to keep in mind:
[`p2pool.stratum_password`](#configuration-reference) and `p2pool.stratum_bind`.
- Exposing to the public internet is still discouraged. A password plus HTTPS is the right baseline,
but for reaching the dashboard from outside the LAN, publish it as a Tor onion service (below)
- rather than forwarding a port. Basic-auth has no rate-limiting or lockout on its own.
+ rather than forwarding a port.
On DIY installs, accepting Caddy's current leaf certificate in the browser can warn again after
an internal renewal (leaves last 12 hours by default). Trust this installation's root CA once
@@ -515,7 +515,8 @@ the page is served over HTTPS.
the disk is writable again.
- **Wrong passwords:** five failures from one address in a minute lock sign-in from that address
for the rest of the minute. Each attempt appears in the access log shown in the Security panel.
- Basic-auth requests are not rate-limited. On the onion address every visitor reaches the
+ Basic-auth requests count toward the same limit, so a script with a wrong password is locked
+ out for the rest of the minute too. On the onion address every visitor reaches the
dashboard from the Tor container, so they share one failure count.
- **Scripts and API clients** keep sending the username and password as HTTP basic auth, for
example `curl -u admin:PASSWORD`. A basic-auth request for a page that asks for HTML
diff --git a/docs/dashboard.md b/docs/dashboard.md
index f560998410..387155430e 100644
--- a/docs/dashboard.md
+++ b/docs/dashboard.md
@@ -511,8 +511,9 @@ instead of a blank axis.
The editor covers the keys RigForge lets the control path change: `pools`, `DONATION`, `autotune`,
`watchdog`, `watchdog_interval_min`, and `max_temp_c`. Nothing else (identity, filesystem paths, API
-ports, the control token) is editable from here. Two modes edit the same set of keys and submit the
-same `{worker, changes}` request:
+ports, the control token) is editable from here. A change that includes `pools` asks you to type
+`APPLY` before it is sent, and the dashboard refuses a `pools` change that arrives without that
+confirmation. Two modes edit the same set of keys and submit the same `{worker, changes}` request:
- **Table** (the default) — one row per writable key, prefilled from the last config the dashboard
applied. Only the rows you touch go into the change.
diff --git a/docs/dev/appliance-wizard.md b/docs/dev/appliance-wizard.md
index ec0e515673..58e6b7b289 100644
--- a/docs/dev/appliance-wizard.md
+++ b/docs/dev/appliance-wizard.md
@@ -35,6 +35,10 @@ peer's failures and creates its session. Existing authenticated cookies retain a
including for operators sharing the blocked peer. The failure map holds at most 1,024 peers and
evicts the entry it began tracking first when full, even if that peer is still in cooldown. Guessing is bounded per peer (five tries a minute), not globally, and the token does not rotate, so several peers multiply the rate; the six-character token holds about 29.7 bits. A network failure is reported separately from throttling.
+The session cookie holds the hex HMAC-SHA256 of the cookie name keyed with the token, never the
+token itself. It stays valid for as long as the token does, also across a restart of the page, and
+the token form does not accept it in place of the token.
+
## The stage machine
`wizard_stage()` in `wizard/server.py` derives the step from **spool files only**, and the client
diff --git a/docs/dev/file-budget.tsv b/docs/dev/file-budget.tsv
index acecffcf31..a915586d84 100644
--- a/docs/dev/file-budget.tsv
+++ b/docs/dev/file-budget.tsv
@@ -1,7 +1,6 @@
# Generated by scripts/lint/lint-file-budget.sh --generate. See this script header for the
# target/ceiling rationale and CONTRIBUTING.md for the gate.
# pathceiling-in-lines. Ceilings only ever go down; a file at or below 400 lines drops its entry.
-.github/workflows/ci.yml 440
dashboard/mining_dashboard/client/xmrig_client.py 446
dashboard/mining_dashboard/config/config.py 689
dashboard/mining_dashboard/service/control_service.py 414
@@ -23,7 +22,7 @@ dashboard/mining_dashboard/web/static/system/osupdate.mjs 404
dashboard/mining_dashboard/web/views/infra_views.py 401
dashboard/mining_dashboard/web/views/views.py 403
dashboard/mining_dashboard/web/views/xvb_views.py 682
-dashboard/mining_dashboard/wizard/server.py 664
+dashboard/mining_dashboard/wizard/server.py 661
dashboard/tests/client/test_xmrig_client.py 489
dashboard/tests/client/test_xvb_client.py 402
dashboard/tests/collector/test_containers.py 410
@@ -46,8 +45,8 @@ dashboard/tests/web/test_worker_detail_meta.py 425
dashboard/tests/web/views/test_infra_views.py 580
dashboard/tests/web/views/test_views.py 750
docs/tools/recovery-config-builder.html 424
-lib/pithead/12-firstboot-wizard.sh 476
-lib/pithead/14-local-miner.sh 414
+lib/pithead/12-firstboot-wizard.sh 438
+lib/pithead/14-local-miner.sh 410
lib/pithead/21-doctor-stack-checks.sh 413
lib/pithead/28-parse-and-validate-config.sh 464
lib/pithead/33-render-env.sh 481
@@ -91,11 +90,11 @@ tests/stack/control/test-control-add-only-ssrf.sh 447
tests/stack/control/test-control-support-bundle.sh 440
tests/stack/control/test-control-upgrade.sh 795
tests/stack/dashboard/test-dashboard-onion.sh 422
-tests/stack/dashboard/test-dashboard.sh 591
-tests/stack/doctor/test-doctor.sh 470
+tests/stack/dashboard/test-dashboard.sh 566
+tests/stack/doctor/test-doctor.sh 463
+tests/stack/standalone/test_compose.sh 455
tests/stack/firewall/tor-egress-enforcement.sh 444
tests/stack/run.sh 402
-tests/stack/standalone/test_compose.sh 462
tests/stack/test-backup.sh 476
tests/stack/test-cli.sh 410
tests/stack/test-config.sh 705
diff --git a/docs/dev/integration-testing.md b/docs/dev/integration-testing.md
index 2a84b5d8e0..a1e8e4ec8a 100644
--- a/docs/dev/integration-testing.md
+++ b/docs/dev/integration-testing.md
@@ -333,7 +333,7 @@ phases and exits through the normal restore trap; it never asks the harness to g
Where a run stops because of the bench rather than the branch, the harness says so on one stdout
line of its own, `e2e-env: `, at most once per run. bench-ci's `tier4-e2e` reads that line to
conclude the job `error: environment` instead of `failure`
-([bench-ci#613](https://github.com/p2pool-starter-stack/bench-ci/issues/613)). The line may be
+(bench-ci#613). The line may be
indented but carries nothing else: no `[ITEST]`, `!` or colour codes. Any other shape or key excuses
nothing. The heartbeat tail of the detached harness drops the line, so the full-log replay is its
only copy. The five keys:
diff --git a/docs/dev/releasing.md b/docs/dev/releasing.md
index 4744e54d5d..d4849be79f 100644
--- a/docs/dev/releasing.md
+++ b/docs/dev/releasing.md
@@ -109,8 +109,8 @@ that has stopped looks different from one with nothing to say.
CI runs a weekly CVE sweep on Mondays at 05:00 UTC from `develop`. It answers two questions with
two jobs: `build-images` rebuilds the stack images from the branch and scans them, while
`os-rootfs.yml` does the same for the appliance rootfs, so a fixable CVE is caught before a cut;
-`sweep-shipped` scans all six images already published, each tag resolved to a digest, so a CVE in
-the bytes users are running is caught after one.
+`sweep-shipped` in `security-sweep.yml` scans all six images already published, each tag resolved to a
+digest, every day, so a CVE in the bytes users are running is caught after one.
A digest-pinned base can lag a published security fix until upstream rebuilds the image. The Alpine
image builds name the base's openssl and musl packages in their apk upgrade list, and the Debian
@@ -134,13 +134,26 @@ A scheduled run has no pull request, so nothing draws a person to its result. On
rebuild scan went red and nobody was told for seven days
([#1377](https://github.com/p2pool-starter-stack/pithead/issues/1377)).
[`scheduled-run-watch.yml`](../../.github/workflows/scheduled-run-watch.yml) is that run's reader.
-It runs every Monday at 08:00 UTC, enumerates every workflow with a declared `schedule:`, and reads
+It runs every day at 08:00 UTC, enumerates every workflow with a declared `schedule:`, and reads
each workflow's server-filtered scheduled-run history. The report marks a run LATE after 12 hours
and MISSED after one full declared period. LATE is informational and MISSED is a reported finding;
neither makes the watcher fail. A schedule with no history gets one full period from the commit that
declared its cron before it can be MISSED. Every MISSED row names its nominal slot and links the runs
that bound the gap; when the gap starts at the declaration boundary, it names that boundary and the
-first observed run. The issue also keeps the sweep result and its six most recent runs.
+first observed run. The issue also keeps the sweep result and its six most recent runs. A second issue, "Security: a
+scheduled scan or watch run is red", carries the `security` label and lists every other workflow whose
+newest completed scheduled run is not green, so a broken scan cannot hide CVEs; it closes itself when
+every run is green again.
+
+## The daily security sweep
+
+[`security-sweep.yml`](../../.github/workflows/security-sweep.yml) runs every day at 05:30 UTC and
+never fails a pull request. For `develop`, `main` and every `develop-v*` branch it checks the ref out
+and runs osv-scanner over its lockfiles (fixable HIGH and CRITICAL advisories only) and online zizmor
+over its workflows, then keeps one `security`-labelled issue per ref up to date: edited in place, one
+comment when the finding set changes, closed when the ref is clean. A run goes red only when a scan
+could not run. Vulnerabilities in the monerod, p2pool and xmrig-proxy binaries are not detected by any
+scanner here; `pin-watch.yml` only reports newer upstream releases.
Six rows rather than one because a single red says little and a streak says the gate has stopped
being an instrument — the weekly link check was red for nine consecutive Mondays before anyone noticed
([#1419](https://github.com/p2pool-starter-stack/pithead/issues/1419)).
diff --git a/docs/dev/testing-strategy.md b/docs/dev/testing-strategy.md
index 3f64a42a2d..76296d8201 100644
--- a/docs/dev/testing-strategy.md
+++ b/docs/dev/testing-strategy.md
@@ -478,7 +478,7 @@ than inventing an appliance-side vocabulary next to it.
| Dashboard through Caddy, basic_auth | ✓ (`/metrics` leg still missing, #2058) | ✓ |
| Tor-only egress enforced (steady-state observation) | ✓ | one row, red on first execution (#2059) |
| Egress-firewall opt-out actually opens clearnet | ✓ (matrix scenario) | ✗ by-design (a scratch guest has no clearnet exposure surface to observe safely) |
-| XvB over Tor, XvB routing | ✓ | ✗ — the `stack` phase drove `--xvb-routing-smoke` once (job 510): the baseline rows and the P2Pool route passed, then the Tor-isolation probe failed and reported only its own static guess, because the probe discards every byte of its output. Not run from the phase until that is readable: #2444 |
+| XvB over Tor, XvB routing | ✓ | ✗ — the `stack` phase drove `--xvb-routing-smoke` once (job 510): the baseline rows and the P2Pool route passed, then the Tor-isolation probe failed and reported only its own static guess, because the probe discards every byte of its output. Not run from the phase until that is readable: #2444. The phase's short XvB leg (`tests/os/appliance-xvb-short-leg.sh`) separately proves the config switch and the Tor-routed XvB proxy route. |
| Shares / hashes flowing end to end | ✓ | ✓ workers online and stratum hashes advancing on the `stack` phase's remote-node guest (#2062); ✓ an ACCEPTED share, from both the coordinator's own built-in miner and a second, rig-role guest pointed at it, on the `rig` phase's own share leg (#2063 — the two-guest proof this table used to carry as a `✗`). Still `missing` on a local-node guest, which never clears the sync gate |
| Config hot-apply matrix (mode, prune, pool, secure, tari, subnet, stratum TLS, payout confirm) | ✓ 15 scenarios | partial — the `stack` phase (#2062) applies the remote-safe subset live (`pithead apply -y` per scenario, pool main→mini, re-apply no-op, secrets preserved). Prune, full-DB and local-node scenarios stay `by-design`: a scratch guest holds no chain |
| Secret preservation across re-apply | ✓ | partial (hostname approval leaves config byte-identical) |
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 0058b93f55..791a284dcd 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -10,9 +10,7 @@ dashboard, no Linux to set up.
> **TL;DR**
>
> ```bash
-> curl -fsSL https://github.com/p2pool-starter-stack/pithead/releases/latest/download/pithead.tar.gz | tar xz
-> cd pithead
-> ./pithead setup
+> curl -fsSL https://raw.githubusercontent.com/p2pool-starter-stack/pithead/main/install.sh | bash
> ```
>
> Have a Monero payout address ready; Tari merge-mining is an optional beta, off unless you say yes, and has its own payout address.
@@ -28,7 +26,7 @@ dashboard, no Linux to set up.
| CPU | A processor with AVX2 support for RandomX performance. |
| RAM | 16 GB minimum with HugePages enabled (~6 GB is reserved for RandomX); 32 GB for a full node or long uptimes. |
| Disk | A Monero node synced from genesis with pruning enabled consumed 285.8 GB in September 2026. Buy at least a 600 GB SSD with both Monero and Tari local, in either prune mode, or 370 GB with Tari remote. Both chains keep growing, so a 2–4 TB drive is the set-and-forget choice. Running either node on another machine drops its share — see [Running a node elsewhere](hardware.md#running-a-node-elsewhere). |
-| Software | Docker Engine, Docker Compose V2, `jq`, `openssl`, and `python3`. |
+| Software | Docker Engine 28 or newer (`doctor` warns on an older one), Docker Compose V2, `jq`, `openssl`, and `python3`. |
> 📐 Sizing guidance for the stack host — minimum vs. recommended specs, plus ways to run leaner —
> is in **[Hardware Requirements](hardware.md)**. Miner specs live in
@@ -54,19 +52,31 @@ On an unsupported OS, or if dependency detection misfires on an unusual setup, r
## 2. Get the code
-Download the latest release. This pulls the published, tested images (no local build), so the
-dashboard shows the real version and the update-checker works:
+Install the latest release with the installer. It checks the bundle against the release's sha256
+and signature (with a pinned cosign it downloads when none is installed), unpacks it into
+`./pithead-`, and starts the setup wizard there. Releases pull the published, tested
+images (no local build), so the dashboard shows the real version and the update-checker works:
```bash
-curl -fsSL https://github.com/p2pool-starter-stack/pithead/releases/latest/download/pithead.tar.gz | tar xz
-cd pithead
+curl -fsSL https://raw.githubusercontent.com/p2pool-starter-stack/pithead/main/install.sh | bash
```
-Leave `config.json` absent to use the setup wizard. Have a Monero payout address ready, and a
-Tari payout address if you enable merge-mining (Tari wallets are sometimes labeled Minotari).
-For a manual configuration, copy `config.minimal.json` or `config.reference.json` to `config.json`
-and edit it before setup; these files inherit the reference defaults rather than the wizard's
-new-install choices.
+Have a Monero payout address ready, and a Tari payout address if you enable merge-mining (Tari
+wallets are sometimes labeled Minotari).
+
+For a manual configuration, check the bundle and unpack it yourself, then copy
+`config.minimal.json` or `config.reference.json` to `config.json` and edit it before setup; these
+files inherit the reference defaults rather than the wizard's new-install choices. This needs
+cosign v2.6.3 on the host, and nothing is unpacked unless the signature checks out:
+
+```bash
+base=https://github.com/p2pool-starter-stack/pithead/releases/latest/download
+curl -fsSLO --proto =https --proto-redir =https "$base/pithead.tar.gz"
+curl -fsSLO --proto =https --proto-redir =https "$base/pithead.tar.gz.sig"
+curl -fsSL --proto =https --proto-redir =https -o cosign.pub https://raw.githubusercontent.com/p2pool-starter-stack/pithead/main/cosign.pub
+cosign verify-blob --key cosign.pub --signature pithead.tar.gz.sig --insecure-ignore-tlog=true pithead.tar.gz &&
+ tar xzf pithead.tar.gz && cd pithead
+```
### Alternative: build from source
@@ -93,6 +103,8 @@ numbered sources, so `make` builds the executable before the first `./pithead` c
./pithead setup
```
+The installer starts this for you. Run it yourself after a manual download, or to re-run setup later.
+
Setup walks through five stages. It's interactive on the first run and safe to re-run later.
1. **Dependency check.** Verifies Docker, Docker Compose, `jq`, `openssl`, and `python3` are present. On
diff --git a/docs/operations.md b/docs/operations.md
index c9dfe81fd6..aa612d7e85 100644
--- a/docs/operations.md
+++ b/docs/operations.md
@@ -28,7 +28,7 @@ separately, [below](#appliance-only-commands).
| `./pithead egress-status` | Check the Tor-only egress firewall the way `doctor` does and write the verdict to `data/control/results/egress-status.json` for the dashboard. Read-only. Fired every two minutes by `pithead-egress.timer`; `up`, `apply` and `upgrade` install the timer, and `network.tor_egress_firewall: false` or `uninstall` removes it. |
| `./pithead lan-guard-check` | Check the live LAN-only source rule. If it is missing, remove the node start marker and stop the nodes that publish LAN ports; if a stop cannot be verified, try restoring the rule on all three fixed node ports and keep reporting failure until the stop is verified. Fired every two minutes by `pithead-lan.timer`; `up`, `apply` and `upgrade` install the timer while a LAN port is configured or still published by a node. Run `./pithead up` after fixing the firewall to restore access. |
| `./pithead render` | Regenerate every derived file (`.env`, the Caddyfile, service configs, host units) from `config.json` without touching containers. The appliance runs this every boot; run it by hand after replacing the program under an existing config. |
-| `./pithead support-bundle` | Collect one `chmod 600` `support-bundle-.zip` in the current directory for a bug report, the same zip the dashboard's **Support bundle** card downloads on a Docker host. The window is `--since TIME` and `--until TIME` (RFC 3339, for example `2026-11-15T10:00:00Z`; the end second is included whole; the end defaults to now, the start to 72 hours before it), or `--hours N` (default 72, clamped to 168); a start after the end, an unparsable time or an end in the future is refused and nothing is written. The zip holds `containers/.log` for every container of the stack, stopped ones included, read in full with the engine's `logs --since --until` for the window (no 200-line limit); `logs/.log` from the host journal for `pithead-egress.service`, `pithead-egress.timer`, `pithead-lan-guard.service`, `pithead-lan-hold.service` and `pithead-lan.timer`; host facts, `doctor` in prose and JSON, a masked config, a redacted `.env`, the container list and `manifest.json`. Launch-line credentials, wallet addresses and the service onion are scrubbed from every container and journal file, as is any Monero address or onion written anywhere else in the text. The manifest has the same fields and size policy as `recovery-bundle` below; a container engine that is stopped, or a system journal this user cannot read (including a user outside the `adm` and `systemd-journal` groups who sees only their own journal), does not fail the bundle: it is listed under `failures` with the reason and no unit file is written, and a unit that is not installed shows as `missing`. Docker's log driver keeps only what its rotation retains, so a window older than that is shorter than asked without a flag. On an appliance the verb collects the journal bundle `recovery-bundle` writes. Read-only, and nothing leaves the box — review it, then share it. |
+| `./pithead support-bundle` | Collect one `chmod 600` `support-bundle-.zip` in the current directory for a bug report, the same zip the dashboard's **Support bundle** card downloads on a Docker host. The window is `--since TIME` and `--until TIME` (RFC 3339, for example `2026-11-15T10:00:00Z`; the end second is included whole; the end defaults to now, the start to 72 hours before it), or `--hours N` (default 72, clamped to 168); a start after the end, an unparsable time or an end in the future is refused and nothing is written. The zip holds `containers/.log` for every container of the stack, stopped ones included, read in full with the engine's `logs --since --until` for the window (no 200-line limit); `logs/.log` from the host journal for `pithead-egress.service`, `pithead-egress.timer`, `pithead-lan-guard.service`, `pithead-lan-hold.service` and `pithead-lan.timer`; host facts, `doctor` in prose and JSON, a masked config, a redacted `.env`, the container list and `manifest.json`. Launch-line credentials, wallet addresses and the service onion are scrubbed from every container and journal file, as is any Monero address or onion written anywhere else in the text, the value on the appliance's generated dashboard login line and the setup wizard's one-time token. The manifest has the same fields and size policy as `recovery-bundle` below; a container engine that is stopped, or a system journal this user cannot read (including a user outside the `adm` and `systemd-journal` groups who sees only their own journal), does not fail the bundle: it is listed under `failures` with the reason and no unit file is written, and a unit that is not installed shows as `missing`. Docker's log driver keeps only what its rotation retains, so a window older than that is shorter than asked without a flag. On an appliance the verb collects the journal bundle `recovery-bundle` writes. Read-only, and nothing leaves the box — review it, then share it. |
| `./pithead recovery-bundle` | The appliance's journal-only twin of `support-bundle` ([#4038](https://github.com/p2pool-starter-stack/pithead/issues/4038)): no dashboard and no network egress — it reads the system journal, the host state and the local service endpoints over the window you ask for, passes every line through the same redactor, writes one `chmod 600` `support-bundle-.zip` under `/data/pithead/support-bundles/` and prints its path. The window is `--since TIME` and `--until TIME` (RFC 3339, for example `2026-11-15T10:00:00Z`; the end second is included whole; the end defaults to now, the start to 72 hours before it), or the older `--hours N` (default 72, clamped to 168). A start after the end, an unparsable time or an end in the future is refused and nothing is written. The zip holds `journal/all.log` (the whole system journal for the window), `journal/kernel.log` (`journalctl -k`), `journal/boots.txt` (`journalctl --list-boots`), one `logs/.log` per Pithead service and timer and per quadlet-generated unit installed on the box (the list is read from the installed unit files when the bundle is collected), the host facts and `manifest.json`, plus the state snapshots listed under **Snapshots** below. The manifest lists every file with its window, size, state (`ok`, `empty` for a unit with no lines in the window, `missing` for a unit that is not installed and has no lines, `journal_short` when the file has lines but the journal starts after the requested start; the window block carries the same fact for the whole bundle) and truncation, every step that failed or timed out with its reason, the requested and the effective window, the oldest retained journal entry, the journald disk usage and settings, the Pithead version and the collection time. A start older than the oldest retained entry is clamped to it. **Snapshots** below. The manifest lists every file with its window, size, state (`ok`, `empty` for a unit with no lines in the window, `missing` for a unit that is not installed and has no lines, `journal_short` when the file has lines but the journal starts after the requested start; the window block carries the same fact for the whole bundle) and truncation, every step that failed or timed out with its reason, the requested and the effective window, the oldest retained journal entry, the journald disk usage and settings, the Pithead version and the collection time. A start older than the oldest retained entry is clamped to it. **Snapshots** below. The manifest lists every file with its window, size, state (`ok`, `empty` for a unit with no lines in the window, `missing` for a unit that is not installed and has no lines, `journal_short` when the file has lines but the journal starts after the requested start; the window block carries the same fact for the whole bundle) and truncation, every step that failed or timed out with its reason, the requested and the effective window, the oldest retained journal entry, the journald disk usage and settings, the Pithead version and the collection time. A start older than the oldest retained entry is clamped to it. **Snapshots** (#4128): `doctor.json` (`doctor --json`); `status/monerod.json`, `status/tari.json` and `status/p2pool.json`, each with height, peer count and a sync flag, or `reachable: false` and the reason when the service cannot answer (monerod answers `get_info` with the `.env` login, Tari answers its base node gRPC `GetTipInfo` and `GetNetworkStatus`, and P2Pool is read from its data-api files, so its sync flag is derived: every readable file under ten minutes old and a known sidechain height; a node that is remote is skipped and the manifest says so); `tor/control.txt` (bootstrap phase, entry guards and circuit state from the control port, authenticated with the cookie, which is read in memory and never written, with onion-service and SOCKS isolation fields dropped) and `tor/state-guards.txt` (only the `TorVersion`, `LastWritten` and `Guard` lines of the Tor state file, so no key can pass); `network/` (`networkctl status`, `ip addr`, `ip route`, `resolvectl status` and the `nft` ruleset with every IPv4 and IPv6 address redacted); `time/` (`timedatectl status` and the time-sync units); `containers/ps-a.txt` (state, exit code and image of every container) and `containers/images.txt` (image digests); `rauc.txt`, `rauc-detailed.txt` and `boot-slot.txt` (the kernel command line, which names the booted slot); `coredumps.txt` (`coredumpctl list`, metadata only, or "not installed"); `caddy/access.log` (the window's lines from the current and rotated generations, with every header but a short safe list (user agent, content type and length, accept, host, forwarded-for) replaced, every URL query replaced and every long path segment masked); `support-dir/` (every file under `/data/pithead/support/`, redacted); `state-markers.txt` (a bounded listing of `/data/pithead`, with the contents of marker files of 256 bytes or less whose names and contents do not look like a secret, URL or token); and `dashboard-history.jsonl` (every row in the window of the history, event, share, block, raffle, XvB, network, disk, worker, ping-failure and control-audit tables, with no row cap; payout rows are left out; a missing database or table is a manifest entry). **Time limits:** every capture runs under `timeout` (the host facts and unit-list reads under 15 seconds), 20 seconds for a snapshot (`PITHEAD_SUPPORT_SNAP_TIMEOUT`), 90 for doctor, 300 for a journal step, and the whole collection under 1500 seconds (`PITHEAD_SUPPORT_TOTAL_TIMEOUT`); a step that times out, fails, is skipped because the total ran out or is not installed is listed in `manifest.json` `failures` with its name, status, reason and elapsed seconds, the manifest states the limits in `limits`, and the bundle is still produced. **Size policy:** each capped file keeps the oldest quarter and the newest three quarters of a 16 MiB budget with a marker line inside the file saying how many lines and bytes were dropped; the files together are held to 64 MiB uncompressed by shrinking the largest first, and the manifest records every cut. Nothing is refused for size. Journald keeps up to 400 MiB (`SystemMaxUse`), enough for the 168 hours the dashboard offers at the log volume of about 2 MiB per hour the issue reports for a loaded test box (the 200 MiB cap held about 102 hours there; not re-measured when the cap was raised); a window older than the retained journal is flagged in the manifest rather than failing. It is the console recipe for a box that failed boot gating, where the machine stays up for diagnosis and the console advisory names this command (`/opt/pithead/pithead recovery-bundle`) beside the journal. Run it on tty1 or the serial console as root; the path it prints is the archive to copy off. Refuses where no journal exists: there, use `support-bundle`. Review the archive, then attach it to a bug report as the card's steps describe; a box whose dashboard answers collects the same artifact from the browser instead — the **Export logs** card in [Dashboard › Backup view](dashboard.md#backup-view), which works with or without the dashboard control channel. |
| `./pithead config-reset` | **DESTRUCTIVE**. Clear the configuration and reopen the setup wizard, keeping every data directory — chains, wallets, Tor onion keys and dashboard history all stay, so reconfiguring costs no resync. Type-to-confirm unless `-y` / `--yes`. If Compose shutdown fails, print its error and warn that containers may still be running, then continue the wipe (exit 0 on completion). The Tor-only egress rules come off only when the container engine shows no stack container still active; otherwise they stay, with a warning, until `./pithead down` stops the stack. |
| `./pithead uninstall` | **DESTRUCTIVE**. The clean exit: removes everything pithead put on this host, including the egress firewall rules with their `pithead-egress.service` boot unit and `pithead-egress.timer` check, the LAN-only source rule and its `pithead-lan.timer` check, and deletes NO data, on any flag. One exception: while the container engine shows a stack container still active, or cannot be asked, the egress firewall rules stay for the current boot, with a warning; run `./pithead down` before rebooting, because their boot unit is already gone. Prints the three-column inventory below, resolved for this box, and the exact command to delete the rest. Refuses in a `pithead-vX.Y.Z` directory that `current` does not point at, because every version directory drives the same live stack: run it in the live directory, and delete an old version directory by hand. Type-to-confirm unless `-y` / `--yes`. |
@@ -296,8 +296,9 @@ enables this by default; a custom/rootless install (or `setup --skip-deps`) may
`sudo systemctl enable --now docker`.
The Tor-egress firewall lives in the kernel, so a reboot clears it while the containers restart.
-`up`, `apply` and `upgrade` install `pithead-egress.service`, which Docker's own start pulls in and
-waits for: it puts the rules back into `DOCKER-USER` before any container starts. `doctor` warns
+`up`, `apply` and `upgrade` install `pithead-egress.service`, which Docker's own start requires and
+waits for: it puts the rules back into `DOCKER-USER` before any container starts. If it fails,
+Docker does not start, and stopping or restarting the unit by hand stops or restarts Docker too. `doctor` warns
when the rules are live but the unit is not enabled, and FAILs when the rules are missing. The
dashboard learns the same state from `pithead-egress.timer`, which runs `pithead egress-status`
every two minutes, and alerts when the rules go missing while the stack runs. See
@@ -507,12 +508,19 @@ whole sequence from the browser — see
[Dashboard › Upgrading from the dashboard](dashboard.md#upgrading-from-the-dashboard). The steps
below are what that button performs, and the only path for source checkouts.
-**Release bundle (the default):** from the install directory, re-download the latest bundle over it,
-then upgrade. `upgrade` **pulls** the new published images:
+**Release bundle (the default):** from the install directory, download the latest bundle and its
+signature, check them against the `cosign.pub` already in the install directory, unpack over it,
+then upgrade. A bundle that does not verify is never unpacked. `upgrade` **pulls** the new
+published images:
```bash
-curl -fsSL https://github.com/p2pool-starter-stack/pithead/releases/latest/download/pithead.tar.gz | tar xz --strip-components=1
-./pithead upgrade
+d=$(mktemp -d)
+base=https://github.com/p2pool-starter-stack/pithead/releases/latest/download
+curl -fsSL --proto =https --proto-redir =https -o "$d/pithead.tar.gz" "$base/pithead.tar.gz"
+curl -fsSL --proto =https --proto-redir =https -o "$d/pithead.tar.gz.sig" "$base/pithead.tar.gz.sig"
+cosign verify-blob --key cosign.pub --signature "$d/pithead.tar.gz.sig" --insecure-ignore-tlog=true "$d/pithead.tar.gz" &&
+ tar xzf "$d/pithead.tar.gz" --strip-components=1 &&
+ ./pithead upgrade
```
**Source checkout:** pull the latest code, then upgrade. `upgrade` **rebuilds** the first-party
@@ -566,14 +574,20 @@ Run `./pithead version` to see what is currently installed before and after an u
A cloned repo builds `:dev` images locally and shows a `dev · branch @ commit` version badge. To run
the published images instead (clean version badge, working update-checker, no local build), convert the
-install in place. `config.json`, `.env`, the Tor onion keys, and data directories are preserved:
+install in place. `config.json`, `.env`, the Tor onion keys, and data directories are preserved. The
+bundle is checked against the checkout's own `cosign.pub` (needs cosign v2.6.3): stop if
+`cosign verify-blob` reports a failure, before anything is unpacked:
```bash
./pithead backup -y # safety snapshot: config.json, .env, onion keys, dashboard db (chains excluded)
-# overlay the published release files — leaves config.json, .env, .git, and your data dirs untouched:
-curl -fsSL https://github.com/p2pool-starter-stack/pithead/releases/latest/download/pithead.tar.gz | tar xz --strip-components=1
-rm -f build/*/Dockerfile dashboard/Dockerfile # remove the image Dockerfiles → pithead switches from build to pull
-./pithead upgrade # re-render config, pull :vX.Y.Z, recreate
+d=$(mktemp -d)
+base=https://github.com/p2pool-starter-stack/pithead/releases/latest/download
+curl -fsSL --proto =https --proto-redir =https -o "$d/pithead.tar.gz" "$base/pithead.tar.gz"
+curl -fsSL --proto =https --proto-redir =https -o "$d/pithead.tar.gz.sig" "$base/pithead.tar.gz.sig"
+cosign verify-blob --key cosign.pub --signature "$d/pithead.tar.gz.sig" --insecure-ignore-tlog=true "$d/pithead.tar.gz" &&
+ tar xzf "$d/pithead.tar.gz" --strip-components=1 && # overlay the release files; config.json, .env, .git and data dirs stay
+ rm -f build/*/Dockerfile dashboard/Dockerfile && # remove the image Dockerfiles → pithead switches from build to pull
+ ./pithead upgrade # re-render config, pull :vX.Y.Z, recreate
```
`pithead` chooses build-vs-pull by whether `dashboard/Dockerfile` is present (the one Dockerfile
diff --git a/docs/privacy.md b/docs/privacy.md
index d6b0d18e77..c71d8febf9 100644
--- a/docs/privacy.md
+++ b/docs/privacy.md
@@ -49,7 +49,7 @@ by channel:
`FORWARD → DOCKER-USER` jump when it creates the network, so the chain is traversed on egress.
A reboot empties the chain, and the containers restart on their own when Docker starts, so
`pithead` also installs `pithead-egress.service`: a oneshot unit ordered before
- `docker.service` and pulled in by it, carrying the same rules. It inserts the `DROP` first,
+ `docker.service` and required by it, carrying the same rules. Docker does not start when it fails. It inserts the `DROP` first,
so a start that fails halfway blocks more than intended rather than less. Its P2Pool and XvB
accepts check separate current-choice markers at boot. Disabling a choice removes its boot
marker before refreshing the live rules; a shared guard still blocks startup until the host
@@ -132,7 +132,8 @@ Until the host attests a selected first sync's Tor transition, a failed live fir
prevents Compose startup. A selected
P2Pool, XvB or donation exception also refuses startup on refresh failure; after a choice is disabled, its
marker keeps that refusal through firewall opt-out until an enabled refresh proves the stale rule
-gone. Ordinary startup retains the firewall warning. Before Docker creates its first network,
+gone. Ordinary startup also refuses when the rules cannot be installed; `network.tor_egress_firewall: false`
+starts without them. Before Docker creates its first network,
the absent `FORWARD` jump is allowed only when Docker confirms the mining network is absent and no
mining container runs; Docker then adds the jump.
The check does CIDR-containment math, not a literal string match: a foreign `ACCEPT` or
diff --git a/install.sh b/install.sh
index d634ccd41e..f26cc37daf 100755
--- a/install.sh
+++ b/install.sh
@@ -10,6 +10,8 @@
set -euo pipefail
REPO="p2pool-starter-stack/pithead"
+COSIGN_PIN_URL="https://github.com/sigstore/cosign/releases/download/v2.6.3/cosign-linux-amd64"
+COSIGN_PIN_SHA256="7c78a7f2efc00088bd788a758db6e0928e79f3e0eb83eb5d3c499ed98da4c4f4"
fail() {
echo "[install] ERROR: $*" >&2
exit 1
@@ -37,10 +39,9 @@ for dep in curl tar sha256sum; do
command -v "$dep" >/dev/null 2>&1 || fail "'$dep' is required to install. apt install $dep, then re-run."
done
-# --- Resolve the release tag. No jq yet (setup installs it) — grep the API response.
TAG="${PITHEAD_VERSION:-}"
if [ -z "$TAG" ]; then
- TAG=$(curl -fsSL "https://api.github.com/repos/$REPO/releases/latest" |
+ TAG=$(curl -fsSL --proto =https --proto-redir =https "https://api.github.com/repos/$REPO/releases/latest" |
grep -m1 '"tag_name"' | sed -E 's/.*"tag_name": *"([^"]+)".*/\1/')
[ -n "$TAG" ] || fail "Could not resolve the latest release tag from the GitHub API."
fi
@@ -48,15 +49,11 @@ DIR="${PITHEAD_DIR:-$PWD/pithead-$TAG}"
[ -e "$DIR" ] && fail "$DIR already exists — pick another PITHEAD_DIR or remove it."
note "Installing Pithead $TAG into $DIR"
-# --- Fetch bundle + manifest; verify the bundle against the manifest's sha256 line when the
-# release carries one (releases newer than v1.14.0 do; for older ones HTTPS is the trust anchor,
-# same as cloning the repo). Image digests are pinned inside the bundle's compose file, and
-# `pithead up`/`upgrade` verify cosign signatures when cosign.pub + cosign are present.
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
-curl -fsSL -o "$TMP/pithead.tar.gz" "https://github.com/$REPO/releases/download/$TAG/pithead.tar.gz" ||
+curl -fsSL --proto =https --proto-redir =https -o "$TMP/pithead.tar.gz" "https://github.com/$REPO/releases/download/$TAG/pithead.tar.gz" ||
fail "Bundle download failed for $TAG."
-if curl -fsSL -o "$TMP/ingredients.md" "https://github.com/$REPO/releases/download/$TAG/ingredients-$TAG.md" 2>/dev/null; then
+if curl -fsSL --proto =https --proto-redir =https -o "$TMP/ingredients.md" "https://github.com/$REPO/releases/download/$TAG/ingredients-$TAG.md" 2>/dev/null; then
WANT=$(grep -m1 -oE 'bundle sha256: `[a-f0-9]{64}`' "$TMP/ingredients.md" | grep -oE '[a-f0-9]{64}' || true)
if [ -n "$WANT" ]; then
GOT=$(sha256sum "$TMP/pithead.tar.gz" | cut -d' ' -f1)
@@ -69,22 +66,32 @@ else
note "No release manifest found — trusting the HTTPS download."
fi
-# --- Cross-channel signature check: the pinned public key comes from the repo over a different
-# endpoint than the release download, so both must agree. Releases before the first signed cut
-# carry no .sig — noted and skipped; a present-but-bad signature is always fatal.
-if command -v cosign >/dev/null 2>&1; then
- if curl -fsSL -o "$TMP/pithead.tar.gz.sig" "https://github.com/$REPO/releases/download/$TAG/pithead.tar.gz.sig" 2>/dev/null; then
- curl -fsSL -o "$TMP/cosign.pub" "https://raw.githubusercontent.com/$REPO/main/cosign.pub" ||
- fail "The release carries a signature but the pinned key could not be fetched from the repo."
- cosign verify-blob --key "$TMP/cosign.pub" --signature "$TMP/pithead.tar.gz.sig" \
- --insecure-ignore-tlog=true "$TMP/pithead.tar.gz" >/dev/null 2>&1 ||
- fail "Bundle signature verification FAILED — the download does not match the release key. Refusing to install."
- note "Bundle signature verified (cosign, repo-pinned key)."
- else
- note "No bundle signature on this release (pre-signing era) — sha256/HTTPS are the trust anchors."
+signed_release() {
+ [[ $1 =~ ^v([0-9]{1,6})\.([0-9]{1,6})\.([0-9]{1,6})$ ]] || return 0
+ ((10#${BASH_REMATCH[1]} * 1000000000000 + 10#${BASH_REMATCH[2]} * 1000000 + 10#${BASH_REMATCH[3]} >= 1000018000001))
+}
+if curl -fsSL --proto =https --proto-redir =https -o "$TMP/pithead.tar.gz.sig" "https://github.com/$REPO/releases/download/$TAG/pithead.tar.gz.sig" 2>/dev/null; then
+ curl -fsSL --proto =https --proto-redir =https -o "$TMP/cosign.pub" "https://raw.githubusercontent.com/$REPO/main/cosign.pub" ||
+ fail "The release carries a signature but the pinned key could not be fetched from the repo."
+ COSIGN=$(command -v cosign || true)
+ if [ -z "$COSIGN" ]; then
+ note "cosign not installed — fetching the pinned cosign v2.6.3 into a temporary folder to check the signature."
+ curl -fsSL --proto =https --proto-redir =https -o "$TMP/cosign" "$COSIGN_PIN_URL" ||
+ fail "Could not download the pinned cosign to check the bundle signature. Install cosign, or run the installer again."
+ [ "$(sha256sum "$TMP/cosign" | cut -d' ' -f1)" = "$COSIGN_PIN_SHA256" ] ||
+ fail "The downloaded cosign does not match its pinned sha256. Refusing to install."
+ chmod 700 "$TMP/cosign"
+ COSIGN="$TMP/cosign"
+ "$COSIGN" version >/dev/null 2>&1 ||
+ fail "The downloaded cosign could not run (is the temporary folder mounted noexec?). Install cosign, or set TMPDIR to a folder that allows running programs."
fi
+ "$COSIGN" verify-blob --key "$TMP/cosign.pub" --signature "$TMP/pithead.tar.gz.sig" \
+ --insecure-ignore-tlog=true "$TMP/pithead.tar.gz" >/dev/null 2>&1 ||
+ fail "Bundle signature verification FAILED — the download does not match the release key. Refusing to install."
+ note "Bundle signature verified (cosign, repo-pinned key)."
else
- note "cosign not installed — skipping signature verification (sha256/HTTPS are the trust anchors)."
+ signed_release "$TAG" && fail "Release $TAG should carry a signature, but the signature could not be downloaded. Refusing to install. If this was a network error, run the installer again."
+ note "No bundle signature on this release (pre-signing era) — sha256/HTTPS are the trust anchors."
fi
mkdir -p "$DIR"
diff --git a/lib/pithead/01-lifecycle.sh b/lib/pithead/01-lifecycle.sh
index 1dead75704..111e3ed81b 100644
--- a/lib/pithead/01-lifecycle.sh
+++ b/lib/pithead/01-lifecycle.sh
@@ -96,8 +96,10 @@ compose_up() {
rmdir "$choice_marker" || return 1
fi
fi
+ elif [ "$(normalize_bool "$firewall_enabled")" = true ]; then
+ warn "Not starting containers: the Tor-only egress rules could not be installed. Fix the host firewall, or set network.tor_egress_firewall: false to start without them."
+ return 1
elif clearnet_sync_active || [ -n "$selected_ips" ] || [ -e "$choice_marker" ] || [ -L "$choice_marker" ]; then
- # Required egress protection failed; leave any stopped LAN nodes down.
return 1
fi
local rc=0
diff --git a/lib/pithead/02a-tor-egress-boot.sh b/lib/pithead/02a-tor-egress-boot.sh
index 09a42b4ac3..4b8c15ddbc 100644
--- a/lib/pithead/02a-tor-egress-boot.sh
+++ b/lib/pithead/02a-tor-egress-boot.sh
@@ -35,19 +35,17 @@ After=ufw.service firewalld.service netfilter-persistent.service nftables.servic
[Service]
Type=oneshot
RemainAfterExit=yes
-ExecStart=-$ipt -N DOCKER-USER
+ExecStart=-$ipt -N DOCKER-USER -w 5
EOF
for rule in "${rules[@]}"; do
- printf 'ExecStart=-%s -D DOCKER-USER -m comment --comment %s %s\n' "$ipt" "$TOR_EGRESS_TAG" "$rule"
+ printf 'ExecStart=-%s -D DOCKER-USER -m comment --comment %s %s -w 5\n' "$ipt" "$TOR_EGRESS_TAG" "$rule"
done
for ip in "$@"; do
- printf 'ExecStart=-%s -D DOCKER-USER -m comment --comment %s -s %s -j ACCEPT\n' "$ipt" "$TOR_EGRESS_TAG" "$ip"
+ printf 'ExecStart=-%s -D DOCKER-USER -m comment --comment %s -s %s -j ACCEPT -w 5\n' "$ipt" "$TOR_EGRESS_TAG" "$ip"
done
for ((i = ${#rules[@]} - 1; i >= 0; i--)); do
- printf 'ExecStart=%s -I DOCKER-USER 1 -m comment --comment %s %s\n' "$ipt" "$TOR_EGRESS_TAG" "${rules[$i]}"
+ printf 'ExecStart=%s -I DOCKER-USER 1 -m comment --comment %s %s -w 5\n' "$ipt" "$TOR_EGRESS_TAG" "${rules[$i]}"
done
- # Check markers at boot: an old unit must not reopen a completed sync or a disabled choice
- # when its rewrite failed after the live firewall removed that exception.
for ip in "$@"; do
case "$ip" in
*.26) chain=monero ;;
@@ -66,9 +64,9 @@ EOF
printf -v qtag '%q' "$TOR_EGRESS_TAG"
printf -v qip '%q' "$ip"
if [ -n "${chain:-}" ]; then
- cmd="if test ! -e $qmarker && test ! -L $qmarker; then $qipt -I DOCKER-USER 1 -m comment --comment $qtag -s $qip -j ACCEPT; fi"
+ cmd="if test ! -e $qmarker && test ! -L $qmarker; then $qipt -I DOCKER-USER 1 -m comment --comment $qtag -s $qip -j ACCEPT -w 5; fi"
else
- cmd="if { test -d $qmarker && test ! -L $qmarker; } || { test -d $qmarker2 && test ! -L $qmarker2; }; then $qipt -I DOCKER-USER 1 -m comment --comment $qtag -s $qip -j ACCEPT; fi"
+ cmd="if { test -d $qmarker && test ! -L $qmarker; } || { test -d $qmarker2 && test ! -L $qmarker2; }; then $qipt -I DOCKER-USER 1 -m comment --comment $qtag -s $qip -j ACCEPT -w 5; fi"
fi
printf "ExecStart=/bin/bash -c '%s'\n" "$cmd"
chain=
@@ -88,7 +86,7 @@ EOF
cat < [sync-ip ...]
+SYSTEM_BIN_DIRS=(/usr/sbin /usr/bin /sbin /bin)
+system_binary() {
+ local d
+ for d in "${SYSTEM_BIN_DIRS[@]}"; do
+ if [ -f "$d/$1" ] && [ -x "$d/$1" ]; then
+ printf '%s' "$d/$1"
+ return 0
+ fi
+ done
+ return 1
+}
+
+provision_tor_egress_boot_unit() {
tor_egress_boot_unit_applies || return 0
local ipt unit_dir want
- ipt=$(command -v iptables) || return 0
+ if ! ipt=$(system_binary iptables); then
+ warn "egress-boot:no-system-iptables — there is no iptables in ${SYSTEM_BIN_DIRS[*]}, so $TOR_EGRESS_BOOT_UNIT is not installed: after a host reboot the containers come back WITHOUT the Tor-only rules until './pithead up' runs."
+ return 0
+ fi
unit_dir=$(control_unit_dir)
want=$(render_tor_egress_boot_unit "$ipt" "$@")
if [ "$(cat "$unit_dir/$TOR_EGRESS_BOOT_UNIT" 2>/dev/null)" = "$want" ] &&
@@ -115,7 +125,7 @@ provision_tor_egress_boot_unit() { # [sync-ip ...]
return 0
fi
if printf '%s\n' "$want" | sudo tee "$unit_dir/$TOR_EGRESS_BOOT_UNIT" >/dev/null &&
- sudo systemctl daemon-reload && sudo systemctl enable "$TOR_EGRESS_BOOT_UNIT" >/dev/null 2>&1; then
+ sudo systemctl daemon-reload && sudo systemctl reenable "$TOR_EGRESS_BOOT_UNIT" >/dev/null 2>&1; then
log "Tor-egress firewall will be restored at boot, before Docker starts the containers ($TOR_EGRESS_BOOT_UNIT)."
else
warn "egress-boot:unit-install-failed — could not install $TOR_EGRESS_BOOT_UNIT. The firewall is live now, but a host reboot will bring the containers back WITHOUT it until './pithead up' runs."
diff --git a/lib/pithead/02b-lan-guard-units.sh b/lib/pithead/02b-lan-guard-units.sh
index b936250e6e..28b8b3d3e2 100644
--- a/lib/pithead/02b-lan-guard-units.sh
+++ b/lib/pithead/02b-lan-guard-units.sh
@@ -166,11 +166,10 @@ install_lan_guard_unit() { #
sudo systemctl daemon-reload && sudo systemctl enable "$2" >/dev/null 2>&1
}
-# Install both units for ... and hand compose restart "no"; 1 when either fails. Not --now.
-provision_lan_guard_boot_unit() { # ...
+provision_lan_guard_boot_unit() {
tor_egress_boot_unit_applies || return 0
local ipt docker unit_dir p c containers=()
- ipt=$(command -v iptables) || return 1
+ ipt=$(system_binary iptables) || return 1
docker=$(command -v docker) || return 1
unit_dir=$(control_unit_dir)
for p in "$@"; do
diff --git a/lib/pithead/02b-tor-egress-apply.sh b/lib/pithead/02b-tor-egress-apply.sh
index 2095cea2e8..319c582c5a 100644
--- a/lib/pithead/02b-tor-egress-apply.sh
+++ b/lib/pithead/02b-tor-egress-apply.sh
@@ -239,18 +239,19 @@ egress_sync_run_pending() {
mkdir -p "$cdir/results"
[ -d "$cdir/requests" ] && [ ! -L "$cdir/requests" ] || return 1
for file in "$cdir"/requests/*.json; do
- [ -e "$file" ] || continue
+ [ -e "$file" ] || [ -L "$file" ] || continue
name=${file##*/}
id=${name%.json}
[[ "$id" =~ ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$ ]] || {
- rm -f "$file"
+ claimed="$cdir/.claim.egress.$$"
+ rm -rf -- "$claimed" && mv -T -- "$file" "$claimed" && rm -rf -- "$claimed" || true
continue
}
claimed="$cdir/.claim.egress.$id"
- mv -- "$file" "$claimed" || continue
+ rm -rf -- "$claimed" && mv -T -- "$file" "$claimed" || continue
file="$claimed"
[ -f "$file" ] && [ ! -L "$file" ] && [ "$(wc -c <"$file")" -le 1024 ] || {
- rm -f "$file"
+ rm -rf -- "$file"
continue
}
chain=$(jq -r --arg id "$id" 'if .id == $id and .action == "egress-sync" and
diff --git a/lib/pithead/02e-tor-recovery.sh b/lib/pithead/02e-tor-recovery.sh
index 357bc86187..d908723f5a 100644
--- a/lib/pithead/02e-tor-recovery.sh
+++ b/lib/pithead/02e-tor-recovery.sh
@@ -24,15 +24,21 @@ tor_recovery_info() {
printf '%s' "$body" | jq -c --argjson out "$out" '.outgoing_connections_count = $out'
}
-tor_recovery_state_saturated() { #
- local state="$1"
- sudo test -f "$state" && sudo test ! -L "$state" || return 1
- sudo grep -qx 'CircuitBuildAbandonedCount 1000' "$state" || return 1
- sudo grep -qx 'TotalBuildTimes 1000' "$state" || return 1
- ! sudo grep -q '^CircuitBuildTimeBin ' "$state" || return 1
+tor_recovery_state_saturated() {
+ local verdict
+ verdict=$(
+ sudo python3 -I - "$1" 2>/dev/null <<'PY'
+import os, re, stat, sys
+fd = os.open(sys.argv[1], os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
+data = os.read(fd, 1048576) if stat.S_ISREG(os.fstat(fd).st_mode) else b""
+if re.search(rb"(?m)^CircuitBuildAbandonedCount 1000$", data) and re.search(rb"(?m)^TotalBuildTimes 1000$", data):
+ print("" if re.search(rb"(?m)^CircuitBuildTimeBin ", data) else "saturated")
+PY
+ ) || return 1
+ [ "$verdict" = saturated ]
}
-control_tor_history() ( #
+control_tor_history() (
local cdir="$1" id="$2" actor="$3" dir saturated=false record="$1/results/tor-heal-outage.json" old='{}' next now status est='' pend='' built='@'
PITHEAD_LOCK_TIMEOUT=0 mutation_lock_acquire tor-history || return 1
[ "${_PITHEAD_LOCK_OWNED:-0}" = 1 ] || return 1
diff --git a/lib/pithead/06-doctor.sh b/lib/pithead/06-doctor.sh
index 6406940337..8e55481a65 100644
--- a/lib/pithead/06-doctor.sh
+++ b/lib/pithead/06-doctor.sh
@@ -46,6 +46,12 @@ doctor() {
dr_info "Skipped — docker is not installed."
elif docker info >/dev/null 2>&1; then
dr_ok "Docker daemon is reachable."
+ local engine_version engine_major
+ engine_version=$(docker version --format '{{.Server.Version}}' 2>/dev/null)
+ engine_major=${engine_version%%[!0-9]*}
+ if [ -n "$engine_major" ] && [ "$engine_major" -lt 28 ]; then
+ dr_warn "Docker Engine $engine_version is older than 28, the oldest release Pithead supports — upgrade Docker."
+ fi
else
dr_fail_surface "Docker daemon is not reachable — start it (e.g. 'sudo systemctl start docker') and ensure your user is in the 'docker' group." "The container engine is not reachable, so the mining stack cannot run. This machine starts it at boot, so this system copy is faulty."
fi
@@ -146,6 +152,7 @@ doctor() {
echo "Network:"
check_stratum_exposure doctor
check_stratum_listening
+ check_stratum_tls_keypair
check_tor_running
check_egress_firewall_installed
check_host_egress_audit
@@ -337,6 +344,7 @@ doctor() {
fi
check_data_wipe_note
+ check_reset_requested
check_coreutils
diff --git a/lib/pithead/07-support-bundle.sh b/lib/pithead/07-support-bundle.sh
index 745df299b3..f4312ac2ab 100644
--- a/lib/pithead/07-support-bundle.sh
+++ b/lib/pithead/07-support-bundle.sh
@@ -145,6 +145,8 @@ bundle_redact_log() {
-e 's/(--wallet[ =])[^-[:space:]][^[:space:]]*/\1[redacted-address]/g' \
-e 's/(--merge-mine[ =][^[:space:]]+[[:space:]]+)[^-[:space:]][^[:space:]]*/\1[redacted-address]/g' \
-e 's/[a-z2-7]{56}\.onion/[redacted].onion/g' \
+ -e 's/(][[:space:]]{2,}password: )[^[:space:]]+/\1[redacted]/g' \
+ -e 's/(One-time token: )[^[:space:]]+/\1[redacted]/g' \
-e "$xmr_shape" \
-e "$xmr_shape"
}
diff --git a/lib/pithead/07a-support-bundle-collect.sh b/lib/pithead/07a-support-bundle-collect.sh
index 59efca2e05..35def61e91 100644
--- a/lib/pithead/07a-support-bundle-collect.sh
+++ b/lib/pithead/07a-support-bundle-collect.sh
@@ -145,7 +145,7 @@ bundle_support_collect() {
bundle_support_cap_py >"$tmp/cap.py"
bundle_support_pack_py >"$tmp/pack.py"
: >"$tmp/steps.tsv"
- bundle_support_snap_py >"$tmp/snap.py"
+ { bundle_support_read_py && bundle_support_snap_py; } >"$tmp/snap.py"
_BUNDLE_DEADLINE=$((SECONDS + ${PITHEAD_SUPPORT_TOTAL_TIMEOUT:-1500}))
since_epoch=$(date -u -d "$since" +%s 2>/dev/null) || since_epoch=0
until_epoch=$(date -u -d "$until" +%s 2>/dev/null) || until_epoch=0
diff --git a/lib/pithead/07c-support-bundle-snapshots.sh b/lib/pithead/07c-support-bundle-snapshots.sh
index 8a0e4d2753..d0b80b5d85 100644
--- a/lib/pithead/07c-support-bundle-snapshots.sh
+++ b/lib/pithead/07c-support-bundle-snapshots.sh
@@ -151,8 +151,8 @@ def tor(datadir, addr):
try:
if not (ipaddress.ip_address(host).is_private or ipaddress.ip_address(host).is_loopback):
raise ValueError("control address is not private")
- with open(os.path.join(datadir, "control_auth_cookie"), "rb") as fh:
- cookie = fh.read().hex()
+ with regular(os.path.join(datadir, "control_auth_cookie"), "rb", size=32) as fh:
+ cookie = fh.read(32).hex()
sock = socket.create_connection((host, int(port)), timeout=5)
sock.settimeout(5)
fh = sock.makefile("rwb")
@@ -267,7 +267,7 @@ def markers(root):
print("%s %d %s %s" % (kind, st.st_size, iso(st.st_mtime), os.path.relpath(path, root)))
if kind == "f" and st.st_size <= 256 and not skip.search(name):
try:
- with open(path, errors="replace") as fh:
+ with regular(path, errors="replace") as fh:
body = fh.read(256).strip()
except OSError:
continue
@@ -280,7 +280,7 @@ if __name__ == "__main__":
if mode in ("caddy", "history"):
{"caddy": caddy, "history": history}[mode](args[0], float(args[1]), float(args[2]))
else:
- {"tari": tari, "monerod": monerod, "p2pool": p2pool, "tor": tor, "markers": markers}[mode](*args)
+ {"tari": tari, "monerod": monerod, "p2pool": p2pool, "tor": tor, "markers": markers, "guards": guards}[mode](*args)
PY
}
@@ -350,7 +350,7 @@ bundle_support_snapshots() {
fi
bundle_support_snap "$tmp" status/p2pool.json python3 -I "$py" p2pool "$p2dir/stats"
bundle_support_snap "$tmp" tor/control.txt python3 -I "$py" tor "$tordir" "$tor_addr"
- bundle_support_snap "$tmp" tor/state-guards.txt awk '/^(TorVersion|LastWritten|Guard) / { gsub(/bridge_addr=[^ ]+/, "bridge_addr=[redacted]"); print }' "$tordir/state"
+ bundle_support_snap "$tmp" tor/state-guards.txt python3 -I "$py" guards "$tordir/state"
bundle_support_snap "$tmp" network/networkctl.txt networkctl status --no-pager
bundle_support_snap "$tmp" network/ip-addr.txt ip addr
diff --git a/lib/pithead/07d-support-bundle-reads.sh b/lib/pithead/07d-support-bundle-reads.sh
new file mode 100644
index 0000000000..d2b23d34c5
--- /dev/null
+++ b/lib/pithead/07d-support-bundle-reads.sh
@@ -0,0 +1,25 @@
+bundle_support_read_py() {
+ cat <<'PY'
+import os, re, stat, sys
+
+
+def regular(path, *args, size=None, **kw):
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
+ st = os.fstat(fd)
+ if stat.S_ISREG(st.st_mode) and size in (None, st.st_size):
+ return os.fdopen(fd, *args, **kw)
+ os.close(fd)
+ raise OSError("not a regular file of the expected size")
+
+
+def guards(path):
+ try:
+ fh = regular(path, "rb")
+ except OSError as exc:
+ sys.exit("the Tor state file is not readable: %s" % type(exc).__name__)
+ with fh:
+ for line in fh.read(1048576).split(b"\n"):
+ if re.match(rb"(TorVersion|LastWritten|Guard) ", line):
+ sys.stdout.buffer.write(re.sub(rb"bridge_addr=[^ ]+", b"bridge_addr=[redacted]", line) + b"\n")
+PY
+}
diff --git a/lib/pithead/08-uninstall-firstboot.sh b/lib/pithead/08-uninstall-firstboot.sh
index c060494a5a..358dbccccf 100644
--- a/lib/pithead/08-uninstall-firstboot.sh
+++ b/lib/pithead/08-uninstall-firstboot.sh
@@ -349,9 +349,9 @@ firstboot_consume_rig() ( #
keep_tok=$(jq -r '.access_token // ""' "$PWD/rig.json" 2>/dev/null)
if ! (
umask 077
- jq --arg w "${worker:-$(hostname)}" --arg t "$keep_tok" '{pool: .pool, worker: $w}
+ JQ_T="$keep_tok" jq --arg w "${worker:-$(hostname)}" '{pool: .pool, worker: $w}
+ (if (.stratum_password // "") == "" then {} else {stratum_password: .stratum_password} end)
- + (if $t == "" then {} else {access_token: $t} end)' \
+ + (if env.JQ_T == "" then {} else {access_token: env.JQ_T} end)' \
"$req" >"${snap%/*}/rig.json" 2>/dev/null && mv -fT "${snap%/*}/rig.json" "$PWD/rig.json"
); then
rm -f "$spool/rig-request.json" "$PWD/rig.json"
diff --git a/lib/pithead/12-firstboot-wizard.sh b/lib/pithead/12-firstboot-wizard.sh
index 832f0da9bf..b536b98000 100644
--- a/lib/pithead/12-firstboot-wizard.sh
+++ b/lib/pithead/12-firstboot-wizard.sh
@@ -176,11 +176,9 @@ firstboot_wizard() {
local rig_worker rig_pool rig_token
rig_worker=$(jq -r '.worker // ""' "$PWD/rig.json" 2>/dev/null)
rig_pool=$(jq -r '.pool // ""' "$PWD/rig.json" 2>/dev/null)
- rig_token=$(rig_access_token) || rig_token="" # empty here = the render leg refuses below
- # The rig's card: worker, pool, the control token (#1836 — minted once, shown ONCE, no login) and
- # this box's address; an unresolvable pool host (#1867) adds control:"off" and why instead.
- jq -n --arg w "$rig_worker" --arg s "stratum+tcp://$rig_pool" --arg t "$rig_token" --arg a "$(hostname -I 2>/dev/null | awk '{print $1}')" --arg allow "$(rig_coordinator_ip)" \
- --arg reason "the pool host does not resolve to an IPv4 address to pin it to" '{role: "rig", worker: $w, stratum: $s, token: $t, address: $a} + (if $allow == "" then {control: "off", reason: $reason} else {} end)' | write_handoff_card "$card_spool"
+ rig_token=$(rig_access_token) || rig_token=""
+ JQ_T="$rig_token" jq -n --arg w "$rig_worker" --arg s "stratum+tcp://$rig_pool" --arg a "$(hostname -I 2>/dev/null | awk '{print $1}')" --arg allow "$(rig_coordinator_ip)" \
+ --arg reason "the pool host does not resolve to an IPv4 address to pin it to" '{role: "rig", worker: $w, stratum: $s, token: env.JQ_T, address: $a} + (if $allow == "" then {control: "off", reason: $reason} else {} end)' | write_handoff_card "$card_spool"
local hwait=0
while ! wizard_spool_has "$spool" handoff-ack && [ "$hwait" -lt 600 ]; do
sleep 2
@@ -298,14 +296,9 @@ firstboot_wizard() {
dash_user=$(jq -r '.dashboard.auth.username // "admin"' "$candidate")
dash_pass=$(jq -r '.dashboard.auth.password // ""' "$candidate")
_console "" "Point your miners at this machine:" " $stratum_addr"
- # Publish over the setup TLS session and hold provisioning until they confirm
- # they saved it (or 10 minutes pass — an unattended pre-seeded run must not
- # hang forever), because the page goes DARK during provisioning and the
- # credentials must not vanish with it.
- jq -n --arg u "$dash_user" --arg p "$dash_pass" \
+ JQ_P="$dash_pass" JQ_MINER="$miner_connection" jq -n --arg u "$dash_user" \
--arg d "https://$(hostname).local" --arg s "$stratum_addr" \
- --argjson miner "$miner_connection" \
- '{username:$u,password:$p,dashboard:$d,stratum:$s} + $miner' | write_handoff_card "$card_spool"
+ '{username:$u,password:env.JQ_P,dashboard:$d,stratum:$s} + (env.JQ_MINER | fromjson)' | write_handoff_card "$card_spool"
local hwait=0
while ! wizard_spool_has "$spool" handoff-ack && [ "$hwait" -lt 600 ]; do
sleep 2
diff --git a/lib/pithead/14-local-miner.sh b/lib/pithead/14-local-miner.sh
index 2e7f222635..3a3b974c29 100644
--- a/lib/pithead/14-local-miner.sh
+++ b/lib/pithead/14-local-miner.sh
@@ -209,9 +209,9 @@ render_local_miner_config() {
port=$(stratum_port_effective)
secret=$(env_get PROXY_STRATUM_PASSWORD 2>/dev/null || true)
ceiling=$(local_miner_pool_ceiling_mb "$dir")
- (tmp=$(mktemp "$dir/config.json.XXXXXX") && jq -n --arg url "127.0.0.1:$port" --arg pass "$secret" --argjson reserve "$(($(hugepages_decision_pages) * 2))" \
+ (tmp=$(mktemp "$dir/config.json.XXXXXX") && JQ_PASS="$secret" jq -n --arg url "127.0.0.1:$port" --argjson reserve "$(($(hugepages_decision_pages) * 2))" \
--argjson ceiling "$ceiling" \
- '{pools: [({url: $url} + (if $pass != "" then {pass: $pass} else {} end))], hugepages_reserve_extra_mb: $reserve}
+ 'env.JQ_PASS as $pass | {pools: [({url: $url} + (if $pass != "" then {pass: $pass} else {} end))], hugepages_reserve_extra_mb: $reserve}
+ (if $ceiling > 0 then {hugepages_pool_ceiling_mb: $ceiling} else {} end)' \
>"$tmp" && mv -f "$tmp" "$dir/config.json")
log "Local miner config rendered to $dir/config.json (pool 127.0.0.1:$port)."
@@ -295,7 +295,7 @@ rig_access_token() {
tok=$(od -An -N16 -tx1 /dev/urandom 2>/dev/null | tr -d ' \n')
[[ "$tok" =~ ^[0-9a-f]{32}$ ]] || return 1
tmp=$(mktemp "$PWD/.rig.json.XXXXXXXXXX") || return 1
- if ! { (umask 077 && jq --arg t "$tok" '. + {access_token: $t}' "$PWD/rig.json" >"$tmp" 2>/dev/null) &&
+ if ! { (umask 077 && JQ_T="$tok" jq '. + {access_token: env.JQ_T}' "$PWD/rig.json" >"$tmp" 2>/dev/null) &&
chmod 600 "$tmp" && mv -f "$tmp" "$PWD/rig.json"; }; then
rm -f "$tmp"
return 1
@@ -318,16 +318,8 @@ rig_coordinator_ip() {
getent ahostsv4 "$host" 2>/dev/null | awk '$1 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ { print $1; exit }'
}
-# RigForge's config for a rig, derived from rig.json exactly the way the Both role's is derived
-# from config.json — rebuilt every boot, never repaired (bar the keys Worker Inspect writes, #3204).
-# The pool the operator gave, the worker name that labels this rig there (RigForge's pools[].user,
-# the hostname when empty), the stratum password when one was set, and (#1836) the rig's own token
-# on every API, the read-only sister feed the coordinator probes, and the writable control path
-# pinned to the coordinator's address, which is how the Workers view adopts the rig. Without the
-# token XMRig's API stood open on the LAN. control_upgrade stays off (a rig updates through its A/B
-# bundle); no hugepages_reserve_extra_mb (no stack here to leave headroom for).
render_rig_miner_config() {
- local dir tok allow keep
+ local dir tok allow keep tmp
dir=$(rigforge_dir)
if [ ! -d "$dir" ]; then
warn "This machine is a rig, but there is no RigForge tree at $dir — this image does not carry the miner."
@@ -340,11 +332,15 @@ render_rig_miner_config() {
allow=$(rig_coordinator_ip)
[ -n "$allow" ] || warn "The rig's control API stays off: the pool host does not resolve to an IPv4 address to pin it to. The read-only feed still serves, token required."
keep=$(jq -sc 'if length == 1 and (.[0] | type == "object") then .[0] | with_entries(select(.key | IN("DONATION", "autotune", "watchdog", "watchdog_interval_min", "max_temp_c"))) else {} end' "$dir/config.json" 2>/dev/null) || keep='{}'
- jq --argjson keep "$keep" --arg tok "$tok" --arg allow "$allow" '$keep + {pools: [({url: .pool, user: (.worker // "")}
+ tmp=$(mktemp "$dir/config.json.XXXXXX") || return 1
+ JQ_TOK="$tok" jq --argjson keep "$keep" --arg allow "$allow" '$keep + {pools: [({url: .pool, user: (.worker // "")}
+ (if (.stratum_password // "") == "" then {} else {pass: .stratum_password} end))],
- ACCESS_TOKEN: $tok, api: "enabled"}
+ ACCESS_TOKEN: env.JQ_TOK, api: "enabled"}
+ (if $allow == "" then {} else {control: "enabled", api_allow_from: $allow} end)' \
- "$PWD/rig.json" >"$dir/config.json" 2>/dev/null || return 1
+ "$PWD/rig.json" >"$tmp" 2>/dev/null && mv -fT -- "$tmp" "$dir/config.json" || {
+ rm -f "$tmp"
+ return 1
+ }
chmod 600 "$dir/config.json" 2>/dev/null || true
}
diff --git a/lib/pithead/16-reset.sh b/lib/pithead/16-reset.sh
index dbf1975b30..0b9f64eb5e 100644
--- a/lib/pithead/16-reset.sh
+++ b/lib/pithead/16-reset.sh
@@ -108,6 +108,18 @@ remove_tari_wallet_volumes() {
done
}
+reset_compose_down() {
+ local attempt tries="${PITHEAD_RESET_DOWN_TRIES:-3}"
+ docker compose stop -t "${PITHEAD_RESET_CADDY_STOP_S:-30}" caddy >/dev/null 2>&1 || true
+ for ((attempt = 1; attempt <= tries; attempt++)); do
+ docker compose down --remove-orphans && return 0
+ [ "$attempt" -lt "$tries" ] || break
+ warn "Stack shutdown failed (attempt $attempt of $tries) — a container's root filesystem can stay mounted for a moment after it exits. Retrying."
+ sleep "${PITHEAD_RESET_DOWN_RETRY_S:-10}"
+ done
+ return 1
+}
+
# config-reset: back to unprovisioned, chains kept. Removing config.json is most of the mechanism
# — pithead-firstboot's ConditionPathExists is `!config.json` AND `!machine-role`, and pithead-boot's
# is the same two paths OR'd instead — but machine-role (lib/pithead/08-uninstall-firstboot.sh)
@@ -147,7 +159,7 @@ config_reset() {
reset_slot_record_good || error "Could not preserve the boot slot before reset — configuration was not cleared."
restore_save_reset_paths
detect_os 2>/dev/null || true
- if docker compose down --remove-orphans; then
+ if reset_compose_down; then
remove_deactivated_profile_containers
else
warn "Stack shutdown failed — continuing with the config wipe. Containers may still be running; fix the Compose error shown above."
diff --git a/lib/pithead/20-doctor-install-checks.sh b/lib/pithead/20-doctor-install-checks.sh
index 61d4e88223..07d35b8193 100644
--- a/lib/pithead/20-doctor-install-checks.sh
+++ b/lib/pithead/20-doctor-install-checks.sh
@@ -294,3 +294,26 @@ check_appliance_cert() {
dr_fail_surface "The dashboard certificate has EXPIRED ($enddate) — browsers will refuse it. Run './pithead apply' to re-mint." "The dashboard certificate has EXPIRED ($enddate) — browsers will refuse it. This machine only re-mints it when the set of names it answers to changes, so it will not renew on its own; replacing it needs console access."
fi
}
+
+check_reset_requested() {
+ is_appliance || return 0
+ [ -e "$PRESEED_DIR/pithead-reset" ] || return 0
+ echo ""
+ echo "Factory reset:"
+ dr_warn "A factory reset is still requested: the next boot erases /data. If the machine already rebooted for it, the reset did not complete; the pithead-data-reset service journal may say why."
+}
+
+check_stratum_tls_keypair() {
+ [ "$(normalize_bool "$(env_get PROXY_STRATUM_TLS)")" = true ] || return 0
+ local dir f missing=""
+ dir=$(env_get PROXY_TLS_DIR)
+ [ -n "$dir" ] || dir="$PWD/data/proxy-tls"
+ for f in cert.pem key.pem; do
+ [ -f "$dir/$f" ] || missing="${missing:+$missing and }$f"
+ done
+ if [ -z "$missing" ]; then
+ dr_ok "Stratum TLS key pair is present."
+ else
+ dr_fail_surface "Stratum TLS is on but the key pair is incomplete (missing: $missing in $dir) — xmrig-proxy starts without TLS and rigs that pin the certificate can't connect. Fix: run './pithead apply' to create the key pair again and restart xmrig-proxy, then pin the new fingerprint on each rig." "Stratum TLS is on but the key pair is incomplete (missing: $missing) — the proxy starts without TLS and rigs that pin the certificate can't connect. Open Configuration and complete the confirmation step to create the key pair again, then pin the new fingerprint on each rig."
+ fi
+}
diff --git a/lib/pithead/23-setup-and-credentials.sh b/lib/pithead/23-setup-and-credentials.sh
index c2ad981f42..246bdbb01c 100644
--- a/lib/pithead/23-setup-and-credentials.sh
+++ b/lib/pithead/23-setup-and-credentials.sh
@@ -118,12 +118,9 @@ generate_node_password() {
printf '%s' "${raw:0:32}"
}
-# --- Tor v3 onion client authorization (#343) ---
-# Base32-encode a hex string (RFC 4648, no padding, uppercase) — the encoding Tor wants for its
-# x25519 client-auth keys. Implemented in awk so it needs no `base32` binary (absent on macOS),
-# which keeps it portable and unit-testable everywhere. Input: an even-length hex string.
b32encode_hex() {
- awk -v hex="$1" 'BEGIN {
+ B32_HEX="$1" awk 'BEGIN {
+ hex = ENVIRON["B32_HEX"]
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
bits = ""
n = length(hex)
@@ -176,21 +173,13 @@ cred_needs_generating() {
[ -z "$value" ] || [ "$value" == "$placeholder" ]
}
-# Persist the (possibly just-generated) local node RPC credentials back into config.json so they
-# stay stable across re-runs / `apply` and the user can see what was set for them. Atomic (write a
-# sibling temp file, then mv) and keeps config.json owner-only. Best-effort: a save failure warns
-# rather than aborting, since the in-memory creds still make this run work.
persist_node_credentials() {
local user="$1" pass="$2" tmp="${CONFIG_FILE}.tmp"
- # A dry run must only read (#556) — the caller already generated the creds in memory for the
- # render/diff; skip the write-back to config.json (or a staged control-channel copy).
[ "$PITHEAD_DRY_RUN" -eq 1 ] && return 0
- # Subshell umask (#368): the temp file carries the credentials, so it too must be owner-only
- # from creation — mv preserves its mode onto config.json.
if (
umask 077
- jq --arg u "$user" --arg p "$pass" \
- '.monero.node_username = $u | .monero.node_password = $p' \
+ JQ_NP="$pass" jq --arg u "$user" \
+ '.monero.node_username = $u | .monero.node_password = env.JQ_NP' \
"$CONFIG_FILE" >"$tmp" 2>/dev/null
); then
mv "$tmp" "$CONFIG_FILE"
diff --git a/lib/pithead/24-config-wizard.sh b/lib/pithead/24-config-wizard.sh
index 73e0911885..715256b29a 100644
--- a/lib/pithead/24-config-wizard.sh
+++ b/lib/pithead/24-config-wizard.sh
@@ -293,20 +293,17 @@ wizard_ask_stratum_password() {
fi
}
-# Assembles config.json from the globals wizard_ask_core/wizard_ask_shape set, and writes it.
wizard_write_config() {
local cfg
- cfg=$(jq -n \
+ cfg=$(JQ_MP="$IN_MONERO_PASS" JQ_SP="${WIZ_STRATUM_PASSWORD:-}" jq -n \
--arg mode "$MONERO_MODE_WIZ" \
--arg mwallet "$IN_MONERO_WALLET" \
--arg mu "$IN_MONERO_USER" \
- --arg mp "$IN_MONERO_PASS" \
--arg tmode "$TARI_MODE_WIZ" \
--arg pool "$POOL_TIER" \
- --arg stratum_password "${WIZ_STRATUM_PASSWORD:-}" \
- '{monero: {mode: $mode, wallet_address: $mwallet, node_username: $mu, node_password: $mp},
+ '{monero: {mode: $mode, wallet_address: $mwallet, node_username: $mu, node_password: env.JQ_MP},
tari: {mode: $tmode},
- p2pool: {pool: $pool, stratum_password: $stratum_password},
+ p2pool: {pool: $pool, stratum_password: env.JQ_SP},
xvb: {enabled: false},
dashboard: {secure: true}}')
@@ -334,7 +331,7 @@ wizard_write_config() {
fi
if [ -n "$IN_DASH_PASS" ]; then
- cfg=$(jq --arg u "$IN_DASH_USER" --arg p "$IN_DASH_PASS" '.dashboard.auth = {username: $u, password: $p}' <<<"$cfg")
+ cfg=$(JQ_DP="$IN_DASH_PASS" jq --arg u "$IN_DASH_USER" '.dashboard.auth = {username: $u, password: env.JQ_DP}' <<<"$cfg")
fi
cfg=$(jq --argjson fast "$CLEARNET_SYNC" \
@@ -348,7 +345,7 @@ wizard_write_config() {
fi
if [ -n "$TELEGRAM_BOT_TOKEN" ]; then
- cfg=$(jq --arg t "$TELEGRAM_BOT_TOKEN" --arg c "$TELEGRAM_CHAT_ID" '.telegram = {enabled: true, bot_token: $t, chat_id: $c}' <<<"$cfg")
+ cfg=$(JQ_TT="$TELEGRAM_BOT_TOKEN" jq --arg c "$TELEGRAM_CHAT_ID" '.telegram = {enabled: true, bot_token: env.JQ_TT, chat_id: $c}' <<<"$cfg")
fi
if [ "${LOCAL_MINER:-false}" = true ]; then
diff --git a/lib/pithead/26-appliance-tls-provisioning.sh b/lib/pithead/26-appliance-tls-provisioning.sh
index 664993a6be..35d4785e04 100644
--- a/lib/pithead/26-appliance-tls-provisioning.sh
+++ b/lib/pithead/26-appliance-tls-provisioning.sh
@@ -8,9 +8,9 @@ ensure_onion_password() {
[ "$(config_bool '.dashboard.onion.enabled' false)" == "true" ] || return 0
[ -z "$(jq -r '.dashboard.auth.password // ""' "$CONFIG_FILE")" ] || return 0
local gen tmp
- gen=$(generate_node_password) || return 1 # 32 alnum chars: clears the >=16 floor, no quotes, no weak pattern
+ gen=$(generate_node_password) || return 1
tmp=$(mktemp) || error "Could not create a temp file to save the generated dashboard password."
- jq --arg p "$gen" '.dashboard.auth.password = $p' "$CONFIG_FILE" >"$tmp" && mv "$tmp" "$CONFIG_FILE" ||
+ JQ_P="$gen" jq 'env.JQ_P as $p | .dashboard.auth.password = $p' "$CONFIG_FILE" >"$tmp" && mv "$tmp" "$CONFIG_FILE" ||
error "Could not save the generated dashboard password to $CONFIG_FILE."
log "Dashboard onion is on but no password was set — generated one and saved it to config.json (login: admin; see dashboard.auth.password)."
}
@@ -344,10 +344,10 @@ ensure_appliance_dashboard_password() { # [spool-dir] [config, default $CONFIG_F
return 0
fi
local gen tmp user
- gen=$(generate_node_password) || return 1 # 32 alnum: clears the >=16 floor, no quotes, no weak pattern
+ gen=$(generate_node_password) || return 1
user=$(jq -r '.dashboard.auth.username // "admin"' "$config")
tmp=$(mktemp) || return 1
- if jq --arg p "$gen" '.dashboard.auth.password = $p' "$config" >"$tmp" && mv "$tmp" "$config"; then
+ if JQ_P="$gen" jq '.dashboard.auth.password = env.JQ_P' "$config" >"$tmp" && mv "$tmp" "$config"; then
_console "" "Dashboard login for this machine:" " user: $user" " password: $gen" \
"Write this down — it is also in config.json on the machine."
return 0
diff --git a/lib/pithead/31-directories-and-dashboard-state.sh b/lib/pithead/31-directories-and-dashboard-state.sh
index 52b699e0d8..7f796a5aaa 100644
--- a/lib/pithead/31-directories-and-dashboard-state.sh
+++ b/lib/pithead/31-directories-and-dashboard-state.sh
@@ -104,6 +104,14 @@ ensure_stratum_tls_cert() {
chmod 600 "$PROXY_TLS_DIR/key.pem" 2>/dev/null || sudo chmod 600 "$PROXY_TLS_DIR/key.pem"
chmod 644 "$PROXY_TLS_DIR/cert.pem" 2>/dev/null || sudo chmod 644 "$PROXY_TLS_DIR/cert.pem"
announce_stratum_tls
+ restart_proxy_for_new_stratum_cert
+}
+
+restart_proxy_for_new_stratum_cert() {
+ [ "$(docker inspect xmrig-proxy --format '{{.State.Running}}' 2>/dev/null || true)" = true ] || return 0
+ log "xmrig-proxy is running without the new key pair; restarting it so it serves TLS..."
+ docker compose restart xmrig-proxy ||
+ warn "xmrig-proxy could not be restarted; run './pithead restart' so it picks up the new key pair."
}
# Surface the stratum TLS state + the fingerprint rigs must pin (#261) — the companion to
diff --git a/lib/pithead/31a-miner-connection.sh b/lib/pithead/31a-miner-connection.sh
index 9c8fffc68d..54a24fa0ea 100644
--- a/lib/pithead/31a-miner-connection.sh
+++ b/lib/pithead/31a-miner-connection.sh
@@ -51,9 +51,9 @@ wizard_prepare_miner_connection() ( # [spool] -> connect
fi
fingerprint=$(stratum_tls_fingerprint) || return 1
[ "$STRATUM_TLS" != true ] || [[ "$fingerprint" =~ ^[0-9a-f]{64}$ ]] || return 1
- jq -n --arg password "$STRATUM_PASSWORD" --argjson tls "$STRATUM_TLS" \
+ JQ_SP="$STRATUM_PASSWORD" jq -n --argjson tls "$STRATUM_TLS" \
--arg fingerprint "$fingerprint" --arg tls_dir "$final_dir" --arg target "$target" --arg wipe "$wipe" \
- '{stratum_password:$password,stratum_tls:$tls,stratum_fingerprint:$fingerprint,tls_dir:$tls_dir,target:$target,wipe:$wipe}' >"$carry/state.json" || return 1
+ '{stratum_password:env.JQ_SP,stratum_tls:$tls,stratum_fingerprint:$fingerprint,tls_dir:$tls_dir,target:$target,wipe:$wipe}' >"$carry/state.json" || return 1
if [ "$installer" = 0 ] && [ "$mode" = auto ]; then
tmp=$(mktemp "${ENV_FILE}.XXXXXX") || return 1
if [ -f "$ENV_FILE" ]; then
diff --git a/lib/pithead/34-inject-service-configs.sh b/lib/pithead/34-inject-service-configs.sh
index adbccbac36..7b913929c1 100644
--- a/lib/pithead/34-inject-service-configs.sh
+++ b/lib/pithead/34-inject-service-configs.sh
@@ -1,22 +1,19 @@
inject_service_configs() {
log "Injecting service configurations..."
- cp build/tari/config.toml.template build/tari/config.toml
- local tari_onion_short="${TARI_ONION%%.*}"
- safe_sed "s//$tari_onion_short/g" build/tari/config.toml
- # Rebase the Tor SOCKS IP onto the configured subnet prefix (#180): a no-op at the
- # default 172.28.0, rewrites the .25 Tor IP when network.subnet has been moved.
- safe_sed "s/172\.28\.0/$NETWORK_PREFIX/g" build/tari/config.toml
+ local tari_onion_short="${TARI_ONION%%.*}" tari_tmp
+ if tari_tmp=$(mktemp -d build/.tari-render.XXXXXX); then
+ cp -P -- build/tari/config.toml.template "$tari_tmp/config.toml" && [ ! -L "$tari_tmp/config.toml" ] &&
+ chmod 644 "$tari_tmp/config.toml" &&
+ safe_sed "s//$tari_onion_short/g" "$tari_tmp/config.toml" &&
+ safe_sed "s/172\.28\.0/$NETWORK_PREFIX/g" "$tari_tmp/config.toml" &&
+ mv -fT -- "$tari_tmp/config.toml" build/tari/config.toml ||
+ warn "Could not render build/tari/config.toml from its template; the file was left as it was."
+ rm -f "$tari_tmp/config.toml"
+ rmdir "$tari_tmp" 2>/dev/null || true
+ else
+ warn "Could not create a render folder in build/; build/tari/config.toml was left as it was."
+ fi
- # config.toml is always rendered for Tor (onion, socks5 transport through Tor) — the CANONICAL
- # config. The optional clearnet initial sync (#183) is applied per-start inside the container by
- # build/tari/entrypoint.sh (which copies this file and transforms the copy), gated on the
- # TARI_CLEARNET_SYNC flag AND the dashboard's auto-transition marker (#234) — so once synced the
- # node returns to Tor on its own and `apply` never re-renders clearnet over it. Same idea for
- # monerod, whose entrypoint envsubsts + transforms in-container. Here we only re-arm:
-
- # Re-arm clearnet auto-sync (#234): clear a chain's "sync complete" marker whenever its flag is
- # OFF, so re-enabling later starts a fresh clearnet sync. While a flag is ON, leave the marker
- # and its host-owned attestation in place. A firewall toggle must not re-arm a completed sync.
local _csdir _cdir
_csdir=$(clearnet_state_dir)
_cdir=$(env_get CONTROL_DIR 2>/dev/null)
diff --git a/lib/pithead/35-caddyfile-and-auth-helpers.sh b/lib/pithead/35-caddyfile-and-auth-helpers.sh
index e6060403d0..5cbdf03acf 100644
--- a/lib/pithead/35-caddyfile-and-auth-helpers.sh
+++ b/lib/pithead/35-caddyfile-and-auth-helpers.sh
@@ -55,7 +55,12 @@ generate_caddyfile() {
if [ -n "${DASHBOARD_AUTH_HASH_B64:-}" ]; then
local hash
hash=$(printf '%s' "$DASHBOARD_AUTH_HASH_B64" | openssl base64 -d -A)
- auth=$(printf ' basic_auth {\n %s %s\n }' "$DASHBOARD_AUTH_USER" "$hash")
+ auth=$(printf '%s\n' \
+ ' forward_auth 127.0.0.1:8000 {' \
+ ' uri /api/auth/basic' \
+ ' header_up X-Forwarded-For {http.request.remote.host}' \
+ ' copy_headers X-Auth-User' \
+ ' }')
epoch=$(printf 'pithead-session-epoch-v1:%s:%s' "$DASHBOARD_AUTH_USER" "$DASHBOARD_AUTH_HASH_B64" | sha256_hex)
gate=$(printf '%s\n' \
' request_header -X-Auth-User' \
@@ -79,7 +84,6 @@ generate_caddyfile() {
' vars pithead_basic 1' \
' redir @pithead_page /login 303' \
"$auth" \
- ' request_header X-Auth-User {http.auth.user.id}' \
' }' \
' @pithead_session not vars pithead_basic 1' \
' forward_auth @pithead_session 127.0.0.1:8000 {' \
@@ -107,40 +111,14 @@ generate_caddyfile() {
}
}
}'
- # Caddy LAN listen port (#740). An empty HOST_PORT — or a value that equals the scheme's own
- # default (443 for HTTPS, 80 for HTTP) — keeps the standard port and renders today's Caddyfile
- # verbatim. A custom port is appended to the site address so an existing reverse proxy on the
- # host can keep 80/443 (co-hosting, #181). In HTTPS mode a custom port also disables Caddy's
- # automatic :80 -> HTTPS redirect (a global option emitted once at the top of the file) so port
- # 80 is left free for that proxy; the fronting proxy owns any http->https bounce instead.
- local dport="${HOST_PORT:-}" port_suffix="" global_block="" own_plain_port=0
+ local dport="${HOST_PORT:-}" port_suffix="" global_block=$'{\n admin off\n}\n\n' own_plain_port=0
if [ "$DASHBOARD_SECURE" == "true" ]; then
[ "$dport" == "443" ] && dport=""
+ global_block=$'{\n admin off\n auto_https disable_redirects\n}\n\n'
if [ -n "$dport" ]; then
port_suffix=":$dport"
- global_block='{
- auto_https disable_redirects
-}
-
-'
else
- # Caddy's own HTTP->HTTPS redirect is a CATCH-ALL, and its target is the Host header the
- # request carried: :80 answered `Host: evil.example` with `308 -> https://evil.example`
- # (#1123, measured against the running bench appliance, not read off the config). Same
- # open redirector #1118 closed in the setup wizard, except this one is the state the
- # machine spends its life in, and it lands the operator on the dashboard login — the
- # screen where they type the dashboard password.
- #
- # So take :80 over rather than leaving it to auto_https. The site is built below, once
- # $site_hosts and the bind list exist: this is the port decision, that is the address
- # decision, and the bind list is what keeps the new block from reopening the addresses
- # #1021 closed.
own_plain_port=1
- global_block='{
- auto_https disable_redirects
-}
-
-'
fi
else
[ "$dport" == "80" ] && dport=""
@@ -345,6 +323,7 @@ $proxy_user_hdr
}
EOF
[ -z "$verify_site" ] || printf '\n%s' "$verify_site" >>"$target"
+ printf '\nhttp://:2019 {\n bind 127.0.0.1\n respond / 204\n respond /config/ 204\n respond 404\n}\n' >>"$target"
if [ "${DASHBOARD_ONION_ENABLED:-false}" == "true" ]; then
if [ -z "$auth" ]; then
diff --git a/lib/pithead/36-quadlet-units.sh b/lib/pithead/36-quadlet-units.sh
index de32c4868a..0ae2d8aeef 100644
--- a/lib/pithead/36-quadlet-units.sh
+++ b/lib/pithead/36-quadlet-units.sh
@@ -143,7 +143,7 @@ Environment=WAIT_FOR_TOR=1 $(_qenvq TARI_CLEARNET_SYNC)
Entrypoint=/var/tari/config/entrypoint.sh
Exec=--disable-splash-screen --non-interactive
Volume=$(_qenv TARI_DATA_DIR):/var/tari/node
-Volume=$(_qenv QUADLET_HOST_CONFIG_DIR)/build/tari:/var/tari/config
+Volume=$(_qenv QUADLET_HOST_CONFIG_DIR)/build/tari:/var/tari/config:ro
Volume=$(_qenv CLEARNET_STATE_DIR):/clearnet-state:ro
Tmpfs=/tmp:size=64m,mode=1777
PublishPort=$(_qenv TARI_GRPC_BIND):18142:18142
@@ -358,7 +358,7 @@ Description=pithead control socket proxy
ContainerName=docker-control
Image=$(_qcompose_image docker-control)
Network=proxy.network
-Environment=CONTAINERS=1 POST=1 ALLOW_START=1 ALLOW_STOP=1
+Environment=POST=1 ALLOW_START=1 ALLOW_STOP=1
Volume=$proxy_sock:/var/run/docker.sock:ro
Tmpfs=/run
Tmpfs=/tmp
diff --git a/lib/pithead/42-control-approval-helpers.sh b/lib/pithead/42-control-approval-helpers.sh
index 00653aa453..0dcee1b4f5 100644
--- a/lib/pithead/42-control-approval-helpers.sh
+++ b/lib/pithead/42-control-approval-helpers.sh
@@ -167,16 +167,18 @@ control_validate_data_dir_overlaps() { #
protected_paths=("$monero_current" "$tari_current" "$p2pool_current" "$tor_current" "$current_dashboard"
"$control_dir" "$clearnet_dir" "$caddy_dir" "$proxy_tls_dir" "$data_root/proxy-tls" "$pithead_tls_dir" "$(os_update_staging_dir)"
"$PWD/${LAN_GUARD_MARKER%/*}" "$PWD/data/firstboot")
- for path in "${protected_paths[@]}"; do
- lex=$(realpath -ms -- "$path" 2>/dev/null) || lex=""
- real=$(realpath -m -- "$path" 2>/dev/null) || real=""
+ for ((j = 0; j < ${#protected_paths[@]}; j++)); do
+ lex=$(realpath -ms -- "${protected_paths[j]}" 2>/dev/null) || lex=""
+ real=$(realpath -m -- "${protected_paths[j]}" 2>/dev/null) || real=""
+ [ -n "$lex" ] && [ -n "$real" ] || {
+ printf 'the protected host folder %s cannot be resolved safely. %s' "${protected_names[j]}" "$(_control_host_remedy)"
+ return 1
+ }
protected_lexes+=("$lex")
protected_reals+=("$real")
done
for ((i = 0; i < ${#paths[@]}; i++)); do
for ((j = 0; j < ${#protected_paths[@]}; j++)); do
- [ -n "${protected_lexes[j]}" ] && [ -n "${protected_reals[j]}" ] || continue
- # Keeping any service at its own current mount is intentional; every cross-over is not.
if [ "$i" -eq "$j" ] && [ "$j" -lt 5 ] &&
[ "${lexes[i]}" = "${protected_lexes[j]}" ] &&
[ "${reals[i]}" = "${protected_reals[j]}" ]; then
diff --git a/lib/pithead/45-control-backup.sh b/lib/pithead/45-control-backup.sh
index 173732b841..6def087188 100644
--- a/lib/pithead/45-control-backup.sh
+++ b/lib/pithead/45-control-backup.sh
@@ -123,8 +123,8 @@ control_backup() { #
mv "$archive" "$dest"
chown "0:$APP_GID" "$dest" 2>/dev/null || true
chmod 640 "$dest" 2>/dev/null || true
- (umask 077 && control_write_result "$results" "$id" "$(jq -n --arg p "$pass" --arg f "$fname" '
- {status:"applied", passphrase:$p, archive:$f,
+ (umask 077 && control_write_result "$results" "$id" "$(JQ_P="$pass" jq -n --arg f "$fname" '
+ {status:"applied", passphrase:env.JQ_P, archive:$f,
contents:["config.json","the stack .env (secrets)","Caddyfile, if present",
"the Tor onion-service key directory, if present","the dashboard database"],
note:"This passphrase is shown once and cannot be recovered — save it now.",
@@ -180,11 +180,9 @@ control_onion_client_key() { #
return 0
fi
IFS=$'\t' read -r onion privkey <<<"$cred"
- # Same perms as the backup kit, for the same reason: root-owned, readable only by the
- # dashboard's own uid/gid, because this file holds a secret while its window is open.
- (umask 077 && control_write_result "$results" "$id" "$(jq -n --arg o "$onion" --arg k "$privkey" '
- {status:"applied", onion_url:("http://" + $o), client_key:$k,
- torrc_line:(($o | sub("\\.onion$"; "")) + ":descriptor:x25519:" + $k),
+ (umask 077 && control_write_result "$results" "$id" "$(JQ_K="$privkey" jq -n --arg o "$onion" '
+ {status:"applied", onion_url:("http://" + $o), client_key:env.JQ_K,
+ torrc_line:(($o | sub("\\.onion$"; "")) + ":descriptor:x25519:" + env.JQ_K),
note:"This is a PRIVATE key and is shown once. Paste it into Tor Browser when it asks for the onion key, or put the torrc line in your ClientOnionAuthDir.",
ts:(now|floor)}')")
chown "0:$APP_GID" "$results/$id.json" 2>/dev/null || true
diff --git a/os/installer/pithead-install b/os/installer/pithead-install
index f2284406b1..e328eb5604 100755
--- a/os/installer/pithead-install
+++ b/os/installer/pithead-install
@@ -143,29 +143,36 @@ wipe_data_partition() { # $1 disk, $2 mode (data|all)
echo "==> wiping user data, preserving the synced chains"
mnt=$(mktemp -d)
mount "$part" "$mnt"
- # A failed step below must not leave the partition mounted-busy for the operator's retry —
- # the script's own EXIT trap is installed later in main(), so this window needs its own.
- # shellcheck disable=SC2064 # expand NOW: $mnt is a local, out of scope when the trap fires
+ # shellcheck disable=SC2064
trap "umount '$mnt' 2>/dev/null || true; rmdir '$mnt' 2>/dev/null || true" EXIT
+ wipe_user_tree "$mnt"
+ umount "$mnt"
+ rmdir "$mnt"
+ trap - EXIT
+}
+
+wipe_user_tree() {
+ local mnt=$1 keep d
keep="$mnt/.wipe-keep.$$"
mkdir -p "$keep"
- # Same-filesystem renames: preserving a 250 GB chain must not copy it.
for d in monero tari; do
[ -d "$mnt/pithead/data/$d" ] && mv "$mnt/pithead/data/$d" "$keep/$d"
done
rm -rf "$mnt/pithead"
- # Host identity (#894): the SSH host key lives OUTSIDE pithead/ (generated by a systemd unit,
- # not by pithead itself), so the rm -rf above never reaches it — delete it explicitly. The
- # machine-id (/data/pithead/machine-id) is already gone with the rest of pithead/ above.
rm -rf "$mnt/ssh"
mkdir -p "$mnt/pithead/data"
for d in monero tari; do
[ -d "$keep/$d" ] && mv "$keep/$d" "$mnt/pithead/data/$d"
done
rmdir "$keep" 2>/dev/null || true
- umount "$mnt"
- rmdir "$mnt"
- trap - EXIT
+ (
+ cd -P -- "$mnt" && base=$(pwd -P) && cd -P -- containers/storage/volumes 2>/dev/null || exit 0
+ [ "$(pwd -P)" = "$base/containers/storage/volumes" ] || exit 0
+ for v in *; do
+ [ ! -L "$v" ] && [ -d "$v/_data" ] || continue
+ find "./$v/_data" -mindepth 1 -delete
+ done
+ )
}
main() {
diff --git a/os/overlay/pithead-boot-stack-health b/os/overlay/pithead-boot-stack-health
index 5168fe2c18..ee46a9a022 100644
--- a/os/overlay/pithead-boot-stack-health
+++ b/os/overlay/pithead-boot-stack-health
@@ -93,10 +93,11 @@ schema_hold_arm() {
dir=$(gate_env_val DASHBOARD_DATA_DIR)
[ -n "$dir" ] || return 0
if booted_slot_committed; then
- rm -f "$dir/$SCHEMA_HOLD_NAME" && sync
+ rm -rf -- "${dir:?}/$SCHEMA_HOLD_NAME" && sync
return 0
fi
- mkdir -p "$dir" && tmp=$(mktemp "$dir/$SCHEMA_HOLD_NAME.XXXXXX") && mv -fT -- "$tmp" "$dir/$SCHEMA_HOLD_NAME" && sync &&
+ mkdir -p "$dir" && tmp=$(mktemp "$dir/$SCHEMA_HOLD_NAME.XXXXXX") && rm -rf -- "${dir:?}/$SCHEMA_HOLD_NAME" &&
+ mv -fT -- "$tmp" "$dir/$SCHEMA_HOLD_NAME" && sync &&
echo "pithead-boot: dashboard schema hold armed — the booted slot is uncommitted, so the dashboard keeps its previous-release database schema until the gate commits"
}
@@ -104,8 +105,8 @@ schema_hold_release() {
local dir
dir=$(gate_env_val DASHBOARD_DATA_DIR)
[ -n "$dir" ] || return 0
- [ -e "$dir/$SCHEMA_HOLD_NAME" ] || return 0
- rm -f "$dir/$SCHEMA_HOLD_NAME" && sync
+ [ -e "$dir/$SCHEMA_HOLD_NAME" ] || [ -L "$dir/$SCHEMA_HOLD_NAME" ] || return 0
+ rm -rf -- "${dir:?}/$SCHEMA_HOLD_NAME" && sync
echo "pithead-boot: dashboard schema hold released — restarting the dashboard to run its deferred database migrations"
${PITHEAD_DASHBOARD_RESTART_CMD:-docker compose restart dashboard} >/dev/null 2>&1 ||
echo "pithead-boot: FAULT — the committed slot could not restart the dashboard to run its deferred database migrations; run 'docker compose restart dashboard' from /data/pithead" >&2
diff --git a/os/overlay/pithead-data-reset b/os/overlay/pithead-data-reset
index 52d4ddd9be..7d782667c3 100644
--- a/os/overlay/pithead-data-reset
+++ b/os/overlay/pithead-data-reset
@@ -220,10 +220,11 @@ main() {
log "factory-reset requested — wiping $data_part"
if reformat_data "$data_part"; then
record_wipe "${marker:+$esp_mnt}" "factory-reset requested"
+ [ -z "$marker" ] || rm -f "$marker" 2>/dev/null || true
else
- [ "$?" -ne 2 ] || rc=2
+ rc=$?
+ log "factory reset did not complete — it stays requested and runs again at the next boot"
fi
- [ "$rc" -eq 2 ] || [ -z "$marker" ] || rm -f "$marker" 2>/dev/null || true
;;
reformat-wedged)
log "$data_part could not be mounted after every repair — reinitializing it so the box can recover"
diff --git a/os/overlay/pithead-media-config b/os/overlay/pithead-media-config
index e55cc9488f..b79bc41aa2 100644
--- a/os/overlay/pithead-media-config
+++ b/os/overlay/pithead-media-config
@@ -161,8 +161,8 @@ media_config_diff() { # — requires SECRET_PATHS_JSON (se
jq -n -r --slurpfile o "$old" --slurpfile n "$new" --argjson secret "$SECRET_PATHS_JSON" '
def is_secret($p):
($secret | any(. == $p))
- or ($p[0:2] == ["workers","list"] and $p[-1] == "token")
- or ($p[0:2] == ["dashboard","workers"] and $p[-1] == "token")
+ or ($p[0:2] == ["workers","list"] and ($p[-1] == "token" or $p[-1] == "api_token"))
+ or ($p[0:2] == ["dashboard","workers"] and ($p[-1] == "token" or $p[-1] == "api_token"))
or ($p[0:2] == ["notifications","webhooks"]);
def show($v): if $v == null then "(unset)" else ($v | tostring) end;
($o[0]) as $O | ($n[0]) as $N |
diff --git a/os/quadlet/docker-control.container b/os/quadlet/docker-control.container
index ac925b1365..d2e5ee2c2b 100644
--- a/os/quadlet/docker-control.container
+++ b/os/quadlet/docker-control.container
@@ -4,7 +4,7 @@ Description=pithead control socket proxy
ContainerName=docker-control
Image=docker.io/tecnativa/docker-socket-proxy:v0.5.0@sha256:1f5038b54f06c3e18422902cf00ba21803d1c97805aae032e5e6673d532d3459
Network=proxy.network
-Environment=CONTAINERS=1 POST=1 ALLOW_START=1 ALLOW_STOP=1
+Environment=POST=1 ALLOW_START=1 ALLOW_STOP=1
Volume=/run/podman/podman.sock:/var/run/docker.sock:ro
Tmpfs=/run
Tmpfs=/tmp
diff --git a/os/quadlet/local/docker-control.container b/os/quadlet/local/docker-control.container
index ac925b1365..d2e5ee2c2b 100644
--- a/os/quadlet/local/docker-control.container
+++ b/os/quadlet/local/docker-control.container
@@ -4,7 +4,7 @@ Description=pithead control socket proxy
ContainerName=docker-control
Image=docker.io/tecnativa/docker-socket-proxy:v0.5.0@sha256:1f5038b54f06c3e18422902cf00ba21803d1c97805aae032e5e6673d532d3459
Network=proxy.network
-Environment=CONTAINERS=1 POST=1 ALLOW_START=1 ALLOW_STOP=1
+Environment=POST=1 ALLOW_START=1 ALLOW_STOP=1
Volume=/run/podman/podman.sock:/var/run/docker.sock:ro
Tmpfs=/run
Tmpfs=/tmp
diff --git a/os/quadlet/local/tari.container b/os/quadlet/local/tari.container
index d4e74d0d13..64990a08da 100644
--- a/os/quadlet/local/tari.container
+++ b/os/quadlet/local/tari.container
@@ -13,7 +13,7 @@ Environment=WAIT_FOR_TOR=1 "TARI_CLEARNET_SYNC=false"
Entrypoint=/var/tari/config/entrypoint.sh
Exec=--disable-splash-screen --non-interactive
Volume=/opt/pithead/data/tari:/var/tari/node
-Volume=/home/pithead/build/tari:/var/tari/config
+Volume=/home/pithead/build/tari:/var/tari/config:ro
Volume=/opt/pithead/data/clearnet-state:/clearnet-state:ro
Tmpfs=/tmp:size=64m,mode=1777
PublishPort=127.0.0.1:18142:18142
diff --git a/os/quadlet/payout/docker-control.container b/os/quadlet/payout/docker-control.container
index ac925b1365..d2e5ee2c2b 100644
--- a/os/quadlet/payout/docker-control.container
+++ b/os/quadlet/payout/docker-control.container
@@ -4,7 +4,7 @@ Description=pithead control socket proxy
ContainerName=docker-control
Image=docker.io/tecnativa/docker-socket-proxy:v0.5.0@sha256:1f5038b54f06c3e18422902cf00ba21803d1c97805aae032e5e6673d532d3459
Network=proxy.network
-Environment=CONTAINERS=1 POST=1 ALLOW_START=1 ALLOW_STOP=1
+Environment=POST=1 ALLOW_START=1 ALLOW_STOP=1
Volume=/run/podman/podman.sock:/var/run/docker.sock:ro
Tmpfs=/run
Tmpfs=/tmp
diff --git a/os/quadlet/payout/tari.container b/os/quadlet/payout/tari.container
index d4e74d0d13..64990a08da 100644
--- a/os/quadlet/payout/tari.container
+++ b/os/quadlet/payout/tari.container
@@ -13,7 +13,7 @@ Environment=WAIT_FOR_TOR=1 "TARI_CLEARNET_SYNC=false"
Entrypoint=/var/tari/config/entrypoint.sh
Exec=--disable-splash-screen --non-interactive
Volume=/opt/pithead/data/tari:/var/tari/node
-Volume=/home/pithead/build/tari:/var/tari/config
+Volume=/home/pithead/build/tari:/var/tari/config:ro
Volume=/opt/pithead/data/clearnet-state:/clearnet-state:ro
Tmpfs=/tmp:size=64m,mode=1777
PublishPort=127.0.0.1:18142:18142
diff --git a/os/rootfs/Dockerfile b/os/rootfs/Dockerfile
index 101028f301..fdae560354 100644
--- a/os/rootfs/Dockerfile
+++ b/os/rootfs/Dockerfile
@@ -66,11 +66,13 @@ ARG PITHEAD_UPDATER=""
RUN set -e; \
updater_packages=""; \
if [ "$PITHEAD_UPDATER" = "rauc" ]; then updater_packages="rauc rauc-service"; fi; \
+ sed -i 's/^Components: main$/Components: main non-free-firmware/' /etc/apt/sources.list.d/debian.sources; \
+ [ "$(grep -c '^Components: main non-free-firmware$' /etc/apt/sources.list.d/debian.sources)" = 2 ]; \
apt-get update; \
apt-get install -y --no-install-recommends \
apt \
systemd systemd-sysv systemd-timesyncd systemd-resolved dbus udev \
- linux-image-amd64 initramfs-tools zstd \
+ linux-image-amd64 initramfs-tools zstd intel-microcode amd64-microcode \
grub-efi-amd64 shim-signed \
podman podman-docker netavark aardvark-dns catatonit uidmap \
jq openssl curl ca-certificates iproute2 gzip libpcre2-8-0 libsqlite3-0 perl-base zlib1g \
@@ -337,3 +339,10 @@ RUN if [ -n "$PITHEAD_TEST_SSH_PUBKEY" ]; then \
&& if [ -n "$PITHEAD_TEST_MARKER" ]; then \
printf '%s\n' "$PITHEAD_TEST_MARKER" > /etc/pithead-test-marker; \
fi
+RUN printf 'IUCODE_TOOL_INITRAMFS=yes\nIUCODE_TOOL_SCANCPUS=no\n' >>/etc/default/intel-microcode \
+ && printf 'AMD64UCODE_INITRAMFS=yes\n' >>/etc/default/amd64-microcode \
+ && update-initramfs -u -k all \
+ && for initrd in /boot/initrd.img-*; do \
+ lsinitramfs -l "$initrd" | awk '$NF == "kernel/x86/microcode/GenuineIntel.bin" && $5 >= 4194304 { i = 1 } \
+ $NF == "kernel/x86/microcode/AuthenticAMD.bin" && $5 > 0 { a = 1 } END { exit !(i && a) }' || exit 1; \
+ done
diff --git a/scripts/ci/compose-image-scan.sh b/scripts/ci/compose-image-scan.sh
new file mode 100755
index 0000000000..78e2cf6010
--- /dev/null
+++ b/scripts/ci/compose-image-scan.sh
@@ -0,0 +1,138 @@
+#!/usr/bin/env bash
+set -Eeuo pipefail
+
+TRIVY="${TRIVY:-trivy}"
+
+digest_images() {
+ grep -Eo 'image:[[:space:]]*[^[:space:]]+@sha256:[0-9a-f]{64}' "$1" | sed -E 's/^image:[[:space:]]*//' | sort -u
+}
+
+image_name() {
+ local n="${1%%@*}"
+ printf '%s' "${n%:*}"
+}
+
+scan_ids() {
+ local ref="$1" ignore="$2" out
+ out="$(mktemp)"
+ for _ in 1 2; do
+ if "$TRIVY" image --quiet --scanners vuln --severity HIGH,CRITICAL --ignore-unfixed \
+ --ignorefile "$ignore" --format json --output "$out" "$ref"; then
+ if ! jq -r '[.Results[]?.Vulnerabilities[]?.VulnerabilityID] | unique[]' "$out"; then
+ rm -f "$out"
+ echo "::error::could not read the scan of $ref" >&2
+ return 1
+ fi
+ rm -f "$out"
+ return 0
+ fi
+ sleep "${SCAN_RETRY_SLEEP:-30}"
+ done
+ rm -f "$out"
+ echo "::error::could not scan $ref" >&2
+ return 1
+}
+
+previous_ref() {
+ local base="$1" name="$2" ref
+ while read -r ref; do
+ if [ "$(image_name "$ref")" = "$name" ]; then
+ printf '%s' "$ref"
+ return 0
+ fi
+ done < <(digest_images "$base")
+}
+
+run() {
+ local base="$1" head="$2" ignore="$3" rc=0 new old name ids_old ids_new added
+ while read -r new; do
+ name="$(image_name "$new")"
+ old="$(previous_ref "$base" "$name")"
+ [ "$old" = "$new" ] && continue
+ ids_new="$(scan_ids "$new" "$ignore")" || {
+ rc=1
+ continue
+ }
+ ids_old=""
+ if [ -n "$old" ]; then
+ ids_old="$(scan_ids "$old" "$ignore")" || {
+ rc=1
+ continue
+ }
+ fi
+ added="$(comm -23 <(printf '%s\n' "$ids_new" | sed '/^$/d' | sort) <(printf '%s\n' "$ids_old" | sed '/^$/d' | sort))"
+ if [ -n "$added" ]; then
+ echo "FAIL $name: new fixable HIGH/CRITICAL in the changed digest: $(echo "$added" | tr '\n' ' ')"
+ rc=1
+ else
+ echo "ok $name: no new fixable HIGH/CRITICAL"
+ fi
+ done < <(digest_images "$head")
+ return "$rc"
+}
+
+self_test() {
+ local d fail=0 rc a b
+ d="$(mktemp -d)"
+ trap 'rm -rf "$d"' RETURN
+ a="sha256:$(printf 'a%.0s' {1..64})"
+ b="sha256:$(printf 'b%.0s' {1..64})"
+ printf ' image: r.io/x/app:1@%s\n image: r.io/x/same:1@%s\n' "$a" "$a" >"$d/base.yml"
+ printf ' image: r.io/x/app:2@%s\n image: r.io/x/same:1@%s\n' "$b" "$a" >"$d/head.yml"
+ : >"$d/ignore"
+ cat >"$d/trivy" <<'FAKE'
+#!/usr/bin/env bash
+ref="${*: -1}"
+out=""
+while [ $# -gt 0 ]; do
+ [ "$1" = --output ] && out="$2"
+ shift
+done
+case "$ref" in
+*"@sha256:aaaa"*) ids="$FAKE_OLD" ;;
+*"@sha256:bbbb"*) ids="$FAKE_NEW" ;;
+*)
+ echo "unexpected scan of $ref" >&2
+ exit 2
+ ;;
+esac
+if [ -n "${FAKE_TRUNC:-}" ]; then
+ printf '{"Results": [{"Vulnerab' >"$out"
+ exit 0
+fi
+jq -n --arg ids "$ids" '{Results: [{Vulnerabilities: ($ids | split(" ") | map(select(. != "") | {VulnerabilityID: .}))}]}' >"$out"
+FAKE
+ chmod +x "$d/trivy"
+ export TRIVY="$d/trivy" SCAN_RETRY_SLEEP=0
+ FAKE_OLD="CVE-1" FAKE_NEW="CVE-1" run "$d/base.yml" "$d/head.yml" "$d/ignore" >/dev/null && rc=0 || rc=$?
+ [ "$rc" = 0 ] || {
+ echo "FAIL: id present in old digest must not fail"
+ fail=1
+ }
+ FAKE_OLD="CVE-1" FAKE_NEW="CVE-1 CVE-2" run "$d/base.yml" "$d/head.yml" "$d/ignore" >/dev/null && rc=0 || rc=$?
+ [ "$rc" = 1 ] || {
+ echo "FAIL: new id must fail"
+ fail=1
+ }
+ FAKE_TRUNC=1 FAKE_OLD="" FAKE_NEW="" run "$d/base.yml" "$d/head.yml" "$d/ignore" >"$d/trunc.out" 2>/dev/null && rc=0 || rc=$?
+ { [ "$rc" = 1 ] && ! grep -q '^ok ' "$d/trunc.out"; } || {
+ echo "FAIL: an unreadable scan must fail, not report ok"
+ fail=1
+ }
+ FAKE_OLD="CVE-1" FAKE_NEW="" run "$d/base.yml" "$d/base.yml" "$d/ignore" >/dev/null && rc=0 || rc=$?
+ [ "$rc" = 0 ] || {
+ echo "FAIL: unchanged compose must pass without scanning"
+ fail=1
+ }
+ [ "$fail" = 0 ] && echo "compose-image-scan self-test ok"
+ return "$fail"
+}
+
+case "${1:-}" in
+--self-test) self_test ;;
+"")
+ echo "usage: $0 | --self-test" >&2
+ exit 2
+ ;;
+*) run "$@" ;;
+esac
diff --git a/scripts/lint/lint-trivy-installer-cache.sh b/scripts/lint/lint-trivy-installer-cache.sh
index ed9a7d8d77..bb6e31f304 100755
--- a/scripts/lint/lint-trivy-installer-cache.sh
+++ b/scripts/lint/lint-trivy-installer-cache.sh
@@ -21,7 +21,7 @@
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
-GATE_WORKFLOWS="$ROOT/.github/workflows/ci.yml $ROOT/.github/workflows/os-rootfs.yml $ROOT/.github/workflows/test-images.yml"
+GATE_WORKFLOWS="$ROOT/.github/workflows/ci.yml $ROOT/.github/workflows/os-rootfs.yml $ROOT/.github/workflows/test-images.yml $ROOT/.github/workflows/security-sweep.yml"
INSTALL_ACTION="$ROOT/.github/actions/install-trivy/action.yml"
RETRY_ACTION="$ROOT/.github/actions/retry-trivy-scan/action.yml"
diff --git a/scripts/lint/verify-healthcheck-scripts.sh b/scripts/lint/verify-healthcheck-scripts.sh
index 7066202657..688d1649d4 100755
--- a/scripts/lint/verify-healthcheck-scripts.sh
+++ b/scripts/lint/verify-healthcheck-scripts.sh
@@ -291,7 +291,7 @@ services:
caddy:
image: caddy:2.11.4
healthcheck:
- test: ["CMD", "wget", "-q", "--spider", "-T", "5", "http://127.0.0.1:2019/config/"]
+ test: ["CMD", "wget", "-q", "--spider", "-T", "5", "http://127.0.0.1:2019/"]
foo-blocklist:
build: ./build/foo-blocklist
diff --git a/scripts/release/resolve-pins.sh b/scripts/release/resolve-pins.sh
index c8f7da15fb..276f04b799 100755
--- a/scripts/release/resolve-pins.sh
+++ b/scripts/release/resolve-pins.sh
@@ -86,10 +86,19 @@ run_check() { #
printf 'NO PINS FOUND: %s yielded no tag@sha256 image references. The extraction no longer matches the file, so nothing was checked — this is a broken gate, not a clean one.\n' "$compose_file"
return 1
fi
+ local reported=0
+ if [ "${RESOLVE_PINS_MISMATCH_OK:-0}" = 1 ]; then
+ reported=$mismatched
+ mismatched=0
+ fi
if [ "$((failed + mismatched))" -gt 0 ]; then
printf '\n%s\n' "$failed lookup(s) unchecked, $mismatched pin(s) mismatched. Fix before cutting."
return 1
fi
+ if [ "$reported" -gt 0 ]; then
+ printf '\n%s\n' "$reported pin(s) mismatched (reported, not failed). Fix before cutting."
+ return 0
+ fi
printf '\nEvery third-party image pin matches what its registry resolves that tag to.\n'
return 0
}
@@ -133,10 +142,17 @@ EOF
st "a moved tag with the old digest left behind is caught" "$rc" "1"
st "the mismatch is named, not swallowed" "$(printf '%s' "$out" | grep -c MISMATCH)" "1"
+ if out="$(RESOLVE_PINS_MISMATCH_OK=1 run_check "$fx2" 2>&1)"; then rc=0; else rc=$?; fi
+ st "report mode prints a mismatch and still exits 0" "$rc" "0"
+ st "report mode still names the mismatch" "$(printf '%s' "$out" | grep -c MISMATCH)" "1"
+ st "report mode never says every pin matches" "$(printf '%s' "$out" | grep -c 'Every third-party image pin matches')" "0"
+
docker() { return 1; }
if out="$(run_check "$fx2" 2>&1)"; then rc=0; else rc=$?; fi
st "a resolver that cannot run fails, never current" "$rc" "1"
st "a failed lookup is never printed as current" "$(printf '%s' "$out" | grep -c '^current:')" "0"
+ if out="$(RESOLVE_PINS_MISMATCH_OK=1 run_check "$fx2" 2>&1)"; then rc=0; else rc=$?; fi
+ st "report mode never forgives a failed lookup" "$rc" "1"
docker() { printf 'not-a-digest\n'; }
if out="$(run_check "$fx2" 2>&1)"; then rc=0; else rc=$?; fi
diff --git a/scripts/watch/scheduled-run-watch.sh b/scripts/watch/scheduled-run-watch.sh
index 1ac0976b20..bb130fb7f4 100755
--- a/scripts/watch/scheduled-run-watch.sh
+++ b/scripts/watch/scheduled-run-watch.sh
@@ -111,7 +111,7 @@ render_report() {
printf 'The Monday run of `ci.yml` is also the CVE sweep — `build-images` scans a rebuild of this\n'
printf 'branch (#833) and `sweep-shipped` scans the published digests (#1313). A scheduled run\n'
printf 'has no pull request, so nothing draws anyone to its red tick. This issue is its reader\n'
- printf '(#1377); it is rewritten in place every week.\n\n'
+ printf '(#1377); it is rewritten in place every day.\n\n'
render_cadence "$dir" || rc=$?
diff --git a/scripts/watch/security-issue.sh b/scripts/watch/security-issue.sh
new file mode 100755
index 0000000000..0875341529
--- /dev/null
+++ b/scripts/watch/security-issue.sh
@@ -0,0 +1,232 @@
+#!/usr/bin/env bash
+
+set -Eeuo pipefail
+
+RED_TITLE="Security: a scheduled scan or watch run is red"
+
+usage() {
+ cat >&2 <<'EOF'
+Renders scan output into security-labelled tracking issues and upserts them (security-sweep.yml,
+scheduled-run-watch.yml). One open issue per title, edited in place, a comment only when the
+finding set changes, closed when the finding set is empty. It does no scanning.
+
+ security-issue.sh render-ref osv.json + zizmor.json + ref.txt of one swept ref -> body (empty when clean)
+ security-issue.sh render-red latest red scheduled runs from scheduled-run-watch's cadence.json
+ security-issue.sh title-ref the issue title for a swept ref
+ security-issue.sh upsert create/edit/close; an empty means clean
+ security-issue.sh --self-test
+EOF
+ exit 2
+}
+
+title_ref() { printf 'Security sweep: vulnerable dependencies or workflows on %s\n' "$1"; }
+
+osv_rows() {
+ jq -r '
+ [.results[]?.packages[]? | . as $p | .vulnerabilities[]? |
+ (([.affected[]?.ranges[]?.events[]?.fixed] | map(select(. != null)) | unique | join(", "))) as $fixed |
+ {id, cve: ((.aliases // []) | map(select(startswith("CVE-"))) | .[0] // "-"),
+ pkg: $p.package.name, ver: $p.package.version, sev: (.database_specific.severity // "UNKNOWN"), fixed: $fixed}
+ | select((.sev == "HIGH" or .sev == "CRITICAL") and .fixed != "")]
+ | unique_by(.id + .pkg + .ver) | sort_by(.pkg, .id)[]
+ | [.id, .cve, .pkg, .ver, .sev, .fixed] | @tsv' "$1"
+}
+
+zizmor_rows() {
+ jq -r '[.[] | {ident, sev: .determinations.severity, desc,
+ file: (.locations[0].symbolic.key.Local.given_path // "?"),
+ line: ((.locations[0].concrete.location.start_point.row // 0) + 1)}]
+ | unique_by(.ident + .file + (.line | tostring)) | sort_by(.file, .line)[]
+ | [.ident, .sev, "\(.file):\(.line)", .desc] | @tsv' "$1"
+}
+
+hash_of() { sort | cksum | cut -d' ' -f1; }
+
+render_ref() {
+ local dir="$1" ref osv zz table="" n=0 hash run
+ ref="$(cat "$dir/ref.txt")"
+ run="${RUN_URL:-}"
+ osv=""
+ zz=""
+ if [ -s "$dir/osv.json" ]; then
+ osv="$(osv_rows "$dir/osv.json")" || return 1
+ fi
+ if [ -s "$dir/zizmor.json" ]; then
+ zz="$(zizmor_rows "$dir/zizmor.json")" || return 1
+ fi
+ [ -n "$osv$zz" ] || return 0
+ hash="$(printf '%s\n%s\n' "$osv" "$zz" | grep -v '^$' | cut -f1-4 | hash_of)"
+ if [ -n "$osv" ]; then
+ n=$((n + $(printf '%s\n' "$osv" | wc -l)))
+ table="${table}Fixable HIGH or CRITICAL advisories in lockfile dependencies:"$'\n\n'
+ table="${table}| Advisory | CVE | Package | Version | Severity | Fixed in |"$'\n'"|---|---|---|---|---|---|"$'\n'
+ table="${table}$(printf '%s\n' "$osv" | awk -F'\t' '{ printf "| %s | %s | `%s` | %s | %s | %s |\n", $1, $2, $3, $4, $5, $6 }')"$'\n\n'
+ fi
+ if [ -n "$zz" ]; then
+ n=$((n + $(printf '%s\n' "$zz" | wc -l)))
+ table="${table}Workflow audit findings (online zizmor):"$'\n\n'
+ table="${table}| Audit | Severity | Location | Finding |"$'\n'"|---|---|---|---|"$'\n'
+ table="${table}$(printf '%s\n' "$zz" | awk -F'\t' '{ printf "| %s | %s | `%s` | %s |\n", $1, $2, $3, $4 }')"$'\n\n'
+ fi
+ printf '\n' "$hash"
+ printf "## What's the problem\n\nThe daily security sweep found %s finding(s) on \`%s\`.\n\n%s" "$n" "$ref" "$table"
+ printf '## What it impacts\n\nWhatever ships from %s: a vulnerable dependency or an exploitable workflow.\n\n' "\`$ref\`"
+ printf '## How I found it\n\nosv-scanner over the lockfiles and online zizmor over the workflows at this ref in the daily sweep%s.\n\n' "${run:+ ($run)}"
+ printf '## How important is it\n\nSecurity fixes go first: a fixable HIGH or CRITICAL is a patch-release trigger. Advisories with no fix are not listed.\n\n'
+ printf '## Acceptance criteria\n\nThe next daily sweep reports nothing for this ref; this issue then closes itself.\n\n'
+ printf '## Possible solutions\n\nBump the listed packages to the fixed version, or pin and fix the flagged workflow step.\n'
+}
+
+render_red() {
+ local rows hash
+ rows="$(jq -r '.workflows[]? | select(.path != ".github/workflows/scheduled-run-watch.yml") |
+ if .runs == null then [.path, "unknown", "-", "history could not be read"]
+ else ([.runs[] | select(.status == "completed")] | sort_by(.createdAt) | reverse | .[0]) as $r |
+ if $r == null then empty
+ elif ($r.conclusion == "success" or $r.conclusion == "cancelled" or $r.conclusion == "skipped") then empty
+ else [.path, $r.conclusion, $r.createdAt, $r.url] end end | @tsv' "$1")"
+ [ -n "$rows" ] || return 0
+ hash="$(printf '%s\n' "$rows" | cut -f1-2 | hash_of)"
+ printf '\n' "$hash"
+ printf "## What's the problem\n\nThe newest completed scheduled run of these workflows is not green, so the scan it performs may not be covering the stack:\n\n"
+ printf '| Workflow | Result | Started | Run |\n|---|---|---|---|\n'
+ printf '%s\n' "$rows" | awk -F'\t' '{ printf "| `%s` | %s | %s | %s |\n", $1, $2, $3, $4 }'
+ printf '\n## What it impacts\n\nNew CVEs or stale pins can go unreported while a sweep is red. Vulnerabilities in the monerod, p2pool and xmrig-proxy binaries are not detected by any scanner here.\n\n'
+ printf '## How I found it\n\nThe daily scheduled-run watch compared each workflow'"'"'s newest completed scheduled run with its conclusion.\n\n'
+ printf '## How important is it\n\nA broken sweep hides CVEs, so fix it ahead of feature work.\n\n'
+ printf '## Acceptance criteria\n\nEvery listed workflow'"'"'s newest scheduled run is green; this issue then closes itself.\n\n'
+ printf '## Possible solutions\n\nOpen the linked run, fix the cause, and run the workflow once with workflow_dispatch.\n'
+}
+
+upsert() {
+ local title="$1" file="$2" n old new
+ n="$(bash "$(dirname "${BASH_SOURCE[0]}")/find-open-issue.sh" "$title")"
+ if [ ! -s "$file" ]; then
+ if [ -n "$n" ]; then
+ gh issue close "$n" --comment "The sweep found nothing on $(date -u +%F); closing."
+ echo "closed #$n"
+ else
+ echo "clean, no open issue"
+ fi
+ return 0
+ fi
+ if [ -n "$n" ]; then
+ old="$(gh issue view "$n" --json body --jq .body | grep -a -m1 '^\nbody\n' >"$t/body"
+ GH_LIST='[]' upsert T "$t/body" >/dev/null
+ st "no open issue and findings creates one with the security label" "$(grep -c 'issue create --title T --label security' "$t/log")" "1"
+ : >"$t/log"
+ GH_LIST='[{"number":7,"title":"T"}]' GH_OLD_BODY='' upsert T "$t/body" >/dev/null
+ st "unchanged findings edit in place" "$(grep -c 'issue edit 7' "$t/log")" "1"
+ st "unchanged findings add no comment" "$(grep -c 'issue comment' "$t/log")" "0"
+ : >"$t/log"
+ GH_LIST='[{"number":7,"title":"T"}]' GH_OLD_BODY='' upsert T "$t/body" >/dev/null
+ st "changed findings add one comment" "$(grep -c 'issue comment 7' "$t/log")" "1"
+ : >"$t/log"
+ GH_LIST='[{"number":7,"title":"T"}]' upsert T "$t/empty" >/dev/null
+ st "clean closes the open issue" "$(grep -c 'issue close 7' "$t/log")" "1"
+ : >"$t/log"
+ GH_LIST='[]' upsert T "$t/empty" >/dev/null
+ st "clean with no issue does nothing else" "$(grep -c 'issue' "$t/log")" "1"
+ [ "$st_fail" = 0 ] && echo "security-issue self-test OK"
+ exit "$st_fail"
+fi
+
+case "${1:-}" in
+render-ref)
+ [ $# -eq 2 ] || usage
+ render_ref "$2"
+ ;;
+render-red)
+ [ $# -eq 2 ] || usage
+ render_red "$2"
+ ;;
+title-ref)
+ [ $# -eq 2 ] || usage
+ title_ref "$2"
+ ;;
+title-red) printf '%s\n' "$RED_TITLE" ;;
+upsert)
+ [ $# -eq 3 ] || usage
+ upsert "$2" "$3"
+ ;;
+*) usage ;;
+esac
diff --git a/scripts/watch/shipped-image-sweep-report.sh b/scripts/watch/shipped-image-sweep-report.sh
index 29fd6fc894..88a9868d8e 100755
--- a/scripts/watch/shipped-image-sweep-report.sh
+++ b/scripts/watch/shipped-image-sweep-report.sh
@@ -13,12 +13,6 @@
# means "consider cutting a patch release", a decision a person makes — not a build to fail. The
# run goes red only when the sweep itself could not do its job.
#
-# WHAT THIS SCRIPT IS. It does no scanning and touches no network. ci.yml's `sweep-shipped` matrix
-# resolves each published tag to a digest, scans that digest with trivy, and uploads two files per
-# image; this script reads that directory and renders the tracking-issue body. Keeping the render
-# out of the workflow is what makes it testable — `--self-test` drives every failure mode below
-# through fixtures with no docker, no network, and no GitHub.
-#
# INCOMPLETE IS NEVER CLEAN. Every refusal below exits 1 and says UNCHECKED in the report rather
# than printing a reassuring zero. This is the defect class the whole currency lane exists for: a
# watcher with nothing to say and a watcher that has quietly died look identical from the Actions
@@ -26,7 +20,6 @@
#
# - the artifact directory is missing, or holds no scan output at all
# - an expected image produced no report (its matrix leg failed)
-# - an unexpected image appeared (ci.yml's matrix and SWEPT_IMAGES below have drifted)
# - a report cannot be parsed
# - a report names an artifact that is NOT a digest reference, so the run cannot honestly claim
# it scanned published bytes rather than a moving tag
@@ -43,17 +36,8 @@
set -Eeuo pipefail
-# THE TITLE IS A CONSTANT AND MUST NEVER BE EDITED. The workflow upserts the tracking issue by
-# EXACT title match over the open issue list. Change this string and the next run silently files a
-# SECOND issue instead of updating the first, then keeps both — the old one frozen at whatever it
-# last said, which reads as a sweep that found nothing new. Renaming the issue by hand in the web
-# UI breaks it the same way.
-SWEEP_ISSUE_TITLE="Shipped-image CVE sweep (weekly report)"
-
-# The images this report expects to find, which must match ci.yml's `sweep-shipped` matrix. The
-# two lists are checked against each other at run time rather than trusted: a service added to the
-# matrix and not here arrives as an unexpected file, one added here and not to the matrix arrives
-# as a missing leg, and BOTH exit 1. A silently shrinking sweep is the failure this guards.
+SWEEP_ISSUE_TITLE="Shipped-image CVE sweep (daily report)"
+
SWEPT_IMAGES="monero p2pool tor xmrig-proxy dashboard os-rootfs"
# Only fixable HIGH/CRITICAL are counted, the same scope ci.yml's gate uses (`ignore-unfixed`), and
@@ -108,9 +92,6 @@ render_report() {
return 1
fi
- # An unexpected report means ci.yml's matrix grew and SWEPT_IMAGES did not. Catch it before
- # rendering, because the summary table below is keyed on SWEPT_IMAGES and would simply not
- # show the new image — a sweep that silently omits an image is exactly what #1313 is about.
for file in "$dir"/sweep-*.json; do
[ -e "$file" ] || continue
svc="$(basename "$file" .json)"
@@ -120,7 +101,7 @@ render_report() {
[ "$s" = "$svc" ] && expected=1 && break
done
if [ "$expected" -eq 0 ]; then
- problems="${problems}- \`$svc\` was swept but is not in this report's image list — ci.yml's \`sweep-shipped\` matrix and \`SWEPT_IMAGES\` in \`scripts/watch/shipped-image-sweep-report.sh\` have drifted apart.
+ problems="${problems}- \`$svc\` was swept but is not in this report's image list — security-sweep.yml's \`sweep-shipped\` matrix and \`SWEPT_IMAGES\` in \`scripts/watch/shipped-image-sweep-report.sh\` have drifted apart.
"
rc=1
fi
diff --git a/scripts/watch/trivyignore-expiry.sh b/scripts/watch/trivyignore-expiry.sh
new file mode 100755
index 0000000000..4cc6eee05f
--- /dev/null
+++ b/scripts/watch/trivyignore-expiry.sh
@@ -0,0 +1,58 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+WARN_DAYS=7
+
+plus_days() {
+ date -u -d "$1 +$2 days" +%F 2>/dev/null || date -u -j -v"+$2d" -f %F "$1" +%F
+}
+
+report() {
+ local file="$1" today="$2" soon id exp rest rows="" expired=0 expiring=0 undated=0
+ soon="$(plus_days "$today" "$WARN_DAYS")"
+ while read -r id rest; do
+ case "$id" in '' | '#'*) continue ;; esac
+ exp="$(printf '%s\n' "$rest" | tr ' ' '\n' | sed -n 's/^exp:\([0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}\)$/\1/p' | head -n1)"
+ if [ -z "$exp" ]; then
+ rows="${rows}| \`$id\` | none | **NO exp: DATE** |"$'\n'
+ undated=$((undated + 1))
+ elif [[ "$exp" < "$today" ]]; then
+ rows="${rows}| \`$id\` | $exp | **EXPIRED** |"$'\n'
+ expired=$((expired + 1))
+ elif [[ "$exp" < "$soon" || "$exp" == "$soon" ]]; then
+ rows="${rows}| \`$id\` | $exp | expires within $WARN_DAYS days |"$'\n'
+ expiring=$((expiring + 1))
+ fi
+ done <"$file"
+ if [ -n "$rows" ]; then
+ printf '\n### Mute expiry\n\n| finding ID | exp | verdict |\n|---|---|---|\n%s' "$rows"
+ else
+ printf '\n### Mute expiry\n\nNo mute is expired, undated or expiring within %s days.\n' "$WARN_DAYS"
+ fi
+ printf '\n\n' "$expired" "$expiring" "$undated"
+}
+
+if [ "${1:-}" = "--self-test" ]; then
+ fx="$(mktemp)"
+ trap 'rm -f "$fx"' EXIT
+ printf '# c\nCVE-OLD exp:2026-01-01\nCVE-SOON exp:2026-11-25\nCVE-FAR exp:2027-01-01\nCVE-NONE\n' >"$fx"
+ out="$(report "$fx" 2026-11-20)"
+ fail=0
+ chk() { printf '%s' "$out" | grep -qF -- "$1" || {
+ echo "self-test FAIL: $1"
+ fail=1
+ }; }
+ chk "CVE-OLD\` | 2026-01-01 | **EXPIRED**"
+ chk "CVE-SOON\` | 2026-11-25 | expires within 7 days"
+ chk "CVE-NONE\` | none | **NO exp: DATE**"
+ chk 'expired=1 expiring=1 undated=1'
+ if printf '%s' "$out" | grep -qF CVE-FAR; then
+ echo "self-test FAIL: far-dated mute reported"
+ fail=1
+ fi
+ [ "$fail" = 0 ] && echo "trivyignore-expiry self-test OK"
+ exit "$fail"
+fi
+
+report "${1:-$ROOT/.config/trivyignore}" "$(date -u +%F)"
diff --git a/scripts/watch/trivyignore-watch.sh b/scripts/watch/trivyignore-watch.sh
index 8ca1dcd0fe..27e9904565 100755
--- a/scripts/watch/trivyignore-watch.sh
+++ b/scripts/watch/trivyignore-watch.sh
@@ -49,7 +49,7 @@ IGNOREFILE="$ROOT/.config/trivyignore"
# The CVE-gate workflows whose install-trivy steps must stay pinned to TRIVY_VERSION (#1290).
# Overridable so --self-test can point this at fixture files instead.
-GATE_WORKFLOWS="$ROOT/.github/workflows/ci.yml $ROOT/.github/workflows/os-rootfs.yml $ROOT/.github/workflows/test-images.yml"
+GATE_WORKFLOWS="$ROOT/.github/workflows/ci.yml $ROOT/.github/workflows/os-rootfs.yml $ROOT/.github/workflows/test-images.yml $ROOT/.github/workflows/supply-chain.yml $ROOT/.github/workflows/security-sweep.yml"
# The parity contract's pinned scanning engine (#1290); do not use `:latest`.
TRIVY_VERSION="0.73.0"
@@ -92,7 +92,7 @@ build_image() {
# -> finding IDs; a clean Trivy target can omit Vulnerabilities (shipped-image-sweep-report.sh).
scan_image() {
local tag="$1" json
- json=$(docker run --rm -v /var/run/docker.sock:/var/run/docker.sock "$TRIVY_IMAGE" \
+ json=$(docker run --rm -e TRIVY_DB_REPOSITORY="ghcr.io/aquasecurity/trivy-db:2,public.ecr.aws/aquasecurity/trivy-db:2" -v /var/run/docker.sock:/var/run/docker.sock "$TRIVY_IMAGE" \
image --scanners vuln --severity "$SEVERITY" --ignore-unfixed --format json "$tag" \
2>/dev/null) || return 1
printf '%s' "$json" | jq -sr '
@@ -307,7 +307,7 @@ if [ "${1:-}" = "--self-test" ]; then
fi
}
- st "shipped sweep keeps released-main root fallback" "$(grep -Fc 'git show origin/main:.config/trivyignore >main.trivyignore 2>/dev/null || git show origin/main:.trivyignore >main.trivyignore' "$ROOT/.github/workflows/ci.yml")" "1"
+ st "shipped sweep keeps released-main root fallback" "$(grep -Fc 'git show origin/main:.config/trivyignore >main.trivyignore 2>/dev/null || git show origin/main:.trivyignore >main.trivyignore' "$ROOT/.github/workflows/security-sweep.yml")" "1"
st "weekly workflow keeps tracker #1382 exact title" "$(grep -Fc 'TITLE: "Obsolete .trivyignore mutes (weekly report)"' "$ROOT/.github/workflows/trivyignore-watch.yml")" "1"
st "rootfs tag is fetched and inputs staged before docker build" \
"$(awk '/^[[:space:]]*git -C "\$ROOT" fetch -q --depth=1 origin/{fetch=NR} /^[[:space:]]*bash "\$ROOT\/os\/build-image.sh" --stage-only/{stage=NR} /^[[:space:]]*docker build -f "\$ROOT\/os\/rootfs\/Dockerfile"/{build=NR} END {print (fetch > 0 && stage > fetch && build > stage)}' "$ROOT/scripts/watch/trivyignore-watch.sh")" "1"
diff --git a/tests/integration/lib/restore-proof.sh b/tests/integration/lib/restore-proof.sh
index 9e8390a766..d37e925813 100644
--- a/tests/integration/lib/restore-proof.sh
+++ b/tests/integration/lib/restore-proof.sh
@@ -110,9 +110,9 @@ restore_egress_boot_unit() {
return 1
;;
esac
- on_bench "sudo systemctl disable --now pithead-egress.service >/dev/null 2>&1; sudo rm -f /etc/systemd/system/pithead-egress.service; sudo systemctl daemon-reload" >/dev/null 2>&1 || true
+ on_bench "sudo systemctl disable pithead-egress.service >/dev/null 2>&1; sudo systemctl --job-mode=ignore-dependencies stop pithead-egress.service >/dev/null 2>&1; sudo rm -f /etc/systemd/system/pithead-egress.service; sudo systemctl daemon-reload" >/dev/null 2>&1 || true
if [ "$(egress_boot_unit_state)" = absent ] &&
- on_bench "! systemctl show -p Wants --value docker.service | grep -q pithead-egress" >/dev/null 2>&1; then
+ on_bench "! systemctl show -p Wants -p Requires --value docker.service | grep -q pithead-egress" >/dev/null 2>&1; then
ok "restore proof: pithead-egress.service removed — no trace of this run's boot unit on the bench (#2460)"
return 0
fi
diff --git a/tests/integration/lib/run-egress-status.sh b/tests/integration/lib/run-egress-status.sh
index e6f7bb7a5d..9ab6d9fea7 100644
--- a/tests/integration/lib/run-egress-status.sh
+++ b/tests/integration/lib/run-egress-status.sh
@@ -55,14 +55,14 @@ fault_firewall_boot_restore() {
assert_eq "up installed and enabled the boot unit (#2460)" \
"$(rx 'systemctl is-enabled pithead-egress.service 2>/dev/null')" "enabled"
assert_contains "docker.service pulls the boot unit in (#2460)" \
- "$(rx 'systemctl show -p Wants --value docker.service')" "pithead-egress.service"
+ "$(rx 'systemctl show -p Requires --value docker.service')" "pithead-egress.service"
assert_contains "docker.service starts only after it (#2460)" \
"$(rx 'systemctl show -p After --value docker.service')" "pithead-egress.service"
rx 'bash -c "source ./pithead && remove_tor_egress_firewall" >/dev/null 2>&1' || true
assert_eq "the rules are gone, as after a reboot" \
"$(rx 'sudo iptables-save 2>/dev/null | grep -c pithead-tor-egress')" "0"
local rc=0
- rx 'sudo systemctl restart pithead-egress.service' >/dev/null 2>&1 || rc=$?
+ rx 'sudo systemctl --job-mode=ignore-dependencies restart pithead-egress.service' >/dev/null 2>&1 || rc=$?
assert_rc "the boot unit starts cleanly on the real kernel (#2460)" "$rc" "0"
rc=0
rx 'bash -c "source ./pithead && tor_egress_enforced"' >/dev/null 2>&1 || rc=$?
diff --git a/tests/integration/lib/run-lan-guard.sh b/tests/integration/lib/run-lan-guard.sh
index c68829f8ba..0bdf76fd02 100644
--- a/tests/integration/lib/run-lan-guard.sh
+++ b/tests/integration/lib/run-lan-guard.sh
@@ -280,7 +280,7 @@ assert_lan_guard_boot_restore() { # ...
assert_contains "Docker waits for Tor egress too (#2901)" \
"$(rx 'systemctl show -p After --value docker.service')" "pithead-egress.service"
rc=0
- rx 'sudo systemctl restart pithead-egress.service' >/dev/null 2>&1 || rc=$?
+ rx 'sudo systemctl --job-mode=ignore-dependencies restart pithead-egress.service' >/dev/null 2>&1 || rc=$?
assert_rc "the Tor-egress boot unit starts after the LAN guard (#2901)" "$rc" "0"
rc=0
rx 'bash -c "source ./pithead && tor_egress_enforced"' >/dev/null 2>&1 || rc=$?
diff --git a/tests/integration/lib/run-rig-control.sh b/tests/integration/lib/run-rig-control.sh
index bb5f974de5..ae8e479bf5 100644
--- a/tests/integration/lib/run-rig-control.sh
+++ b/tests/integration/lib/run-rig-control.sh
@@ -2,7 +2,7 @@
: "${INTEGRATION_RUN_SUITE:?source via the suite runner}"
_worker_apply() { # -> echoes the dashboard result JSON
local body
- body="$(printf '%s' "$2" | jq -ce --arg w "$1" 'if type == "object" then {worker:$w,changes:.} else error("changes") end')" || return 1
+ body="$(printf '%s' "$2" | jq -ce --arg w "$1" 'if type == "object" then {worker:$w,changes:.} + (if has("pools") then {confirm:"APPLY"} else {} end) else error("changes") end')" || return 1
printf '%s' "$body" | rx "curl -fsS --max-time 60 -X POST -H 'Content-Type: application/json' -H 'X-Pithead-Control: 1' --data-binary @- http://127.0.0.1:8000/api/control/worker-apply" --stdin 2>/dev/null
}
diff --git a/tests/integration/lib/xvb-off-dwell.sh b/tests/integration/lib/xvb-off-dwell.sh
index 0a98b75dc6..5e9b0456df 100644
--- a/tests/integration/lib/xvb-off-dwell.sh
+++ b/tests/integration/lib/xvb-off-dwell.sh
@@ -22,7 +22,8 @@ assert_xvb_off_no_dwell_churn() {
return 0
fi
identity="$(rx "timeout 15 docker inspect --format '{{.Id}} {{.State.StartedAt}}' dashboard" 2>/dev/null)" || identity=""
- started="$(rx "date -d $(quote_arg "${identity#* }") +%s" 2>/dev/null)" || started=""
+ started="${identity#* }"
+ started="$(rx "date -d $(quote_arg "${started% [A-Z]*}") +%s" 2>/dev/null)" || started=""
now="$(rx 'date +%s' 2>/dev/null)" || now=""
if [ -z "$identity" ] || ! [[ "$started $now" =~ ^[0-9]{1,12}\ [0-9]{1,12}$ ]] || [ "$now" -lt "$started" ]; then
it_fail "$row" "could not establish dashboard uptime"
diff --git a/tests/integration/mini-stack/boot-health-proxy.py b/tests/integration/mini-stack/boot-health-proxy.py
index 910d0046d3..a5d9d29755 100644
--- a/tests/integration/mini-stack/boot-health-proxy.py
+++ b/tests/integration/mini-stack/boot-health-proxy.py
@@ -104,13 +104,13 @@ def summary(failures, warning):
require(request(PROBE, headers={"X-Pithead-Boot-Probe": CAPABILITY})[0] == 401)
data = summary(0, False)
require(any(e["uri"] == PROBE and e["status"] == 401 for e in data["entries"]), data)
- for _ in range(4):
+ require(request(PROBE, BAD_AUTH, headers={"X-Pithead-Boot-Probe": CAPABILITY})[0] == 401)
+ for _ in range(3):
require(request("/", BAD_AUTH)[0] == 401)
summary(4, False)
- require(request("/", BAD_AUTH)[0] == 401)
+ require(request("/")[0] == 401)
summary(5, True)
- # Even local wrong credentials on the exact health path are ordinary failures.
- require(request(PROBE, BAD_AUTH, headers={"X-Pithead-Boot-Probe": CAPABILITY})[0] == 401)
+ require(request("/")[0] == 401)
summary(6, True)
elif mode in {"external", "proxy"}:
forged = {
@@ -122,7 +122,7 @@ def summary(failures, warning):
"User-Agent": "curl",
}
# Wait for the front proxy without creating a login failure.
- for _ in range(50):
+ for _ in range(300):
try:
if request("/", GOOD_AUTH)[0] == 200:
break
diff --git a/tests/integration/mini-stack/test-boot-health-proxy.sh b/tests/integration/mini-stack/test-boot-health-proxy.sh
index 7526f5aa8d..2eed0eca7a 100644
--- a/tests/integration/mini-stack/test-boot-health-proxy.sh
+++ b/tests/integration/mini-stack/test-boot-health-proxy.sh
@@ -40,12 +40,37 @@ docker run -d --name "$name-dashboard" --network "container:$name-caddy" \
run_driver() {
docker run --rm -i --network "$1" -e DASHBOARD_AUTH_HASH_B64 --entrypoint python pithead-dashboard:itest - "$2" "$3" <"$ROOT/tests/integration/mini-stack/boot-health-proxy.py"
}
+restart_dashboard() {
+ docker restart "$name-dashboard" >/dev/null
+ for _ in $(seq 60); do
+ docker exec "$name-dashboard" python -c "
+import urllib.error, urllib.request
+try:
+ urllib.request.urlopen('http://127.0.0.1:8000/api/auth/check', timeout=2)
+except urllib.error.HTTPError:
+ pass
+" 2>/dev/null && return 0
+ sleep 1
+ done
+ error "dashboard did not come back after restart"
+}
+restart_caddy() {
+ docker restart "$name-caddy" >/dev/null
+ for _ in $(seq 60); do
+ docker exec "$name-caddy" wget -q --spider -T 2 http://127.0.0.1:2019/ 2>/dev/null && {
+ restart_dashboard
+ return 0
+ }
+ sleep 1
+ done
+ error "caddy did not come back after restart"
+}
run_driver "container:$name-caddy" local 127.0.0.1
run_driver "$name" external "$name-caddy"
-# A real fronting proxy turns an external socket into a loopback connection to Caddy.
docker run -d --name "$name-front" --network "container:$name-caddy" \
-v "$ROOT/tests/integration/mini-stack/boot-health-front-proxy.py:/fixture.py:ro" \
--entrypoint python pithead-dashboard:itest /fixture.py >/dev/null
+restart_dashboard
run_driver "$name" proxy "$name-caddy"
run_driver "container:$name-caddy" final 127.0.0.1
docker exec -i -e DASHBOARD_AUTH_HASH_B64 "$name-dashboard" python - <<'PYLOG'
@@ -62,16 +87,17 @@ from pathlib import Path
if 'fixture-password' in Path('/access-log/access.log').read_text():
raise AssertionError('password leaked into access log')
"
+restart_dashboard
login_out=$(run_driver "container:$name-caddy" login 127.0.0.1)
old_cookie=$(printf '%s\n' "$login_out" | sed -n 's/^COOKIE=//p')
[ -n "$old_cookie" ]
DASHBOARD_AUTH_HASH_B64=$(printf '%s\n' rotated-password | docker run --rm -i "$image" caddy hash-password | openssl base64 -A)
generate_caddyfile "$scratch/Caddyfile"
-docker exec "$name-caddy" caddy reload --config /etc/caddy/Caddyfile >/dev/null
+restart_caddy
docker run --rm -i --network "container:$name-caddy" -e OLD_COOKIE="$old_cookie" -e DASHBOARD_AUTH_HASH_B64 --entrypoint python \
pithead-dashboard:itest - rotated 127.0.0.1 <"$ROOT/tests/integration/mini-stack/boot-health-proxy.py"
DASHBOARD_AUTH_HASH_B64=""
generate_caddyfile "$scratch/Caddyfile"
-docker exec "$name-caddy" caddy reload --config /etc/caddy/Caddyfile >/dev/null
+restart_caddy
run_driver "container:$name-caddy" unlocked 127.0.0.1
echo ' ✓ rendered Caddy boot marker survives auth and cannot suppress network login failures'
diff --git a/tests/integration/selftest/selftest-bundle-redact-log.sh b/tests/integration/selftest/selftest-bundle-redact-log.sh
index 317c67765f..76042a6288 100755
--- a/tests/integration/selftest/selftest-bundle-redact-log.sh
+++ b/tests/integration/selftest/selftest-bundle-redact-log.sh
@@ -338,5 +338,28 @@ body_kept "a 95-character token with a non-address prefix survives" \
body_kept "a sha256 digest survives" \
"image sha256:$SHA256_HEX pulled" "$SHA256_HEX"
+echo "== unit: the generated dashboard login and the one-time setup token are masked =="
+GEN_LOGIN="Synth3ticGeneratedLogin00000000A"
+JPFX="Nov 24 10:00:00 fixture pithead-firstboot[812]:"
+assert_eq "the generated login line in the journal keeps its prefix and masks the value" \
+ "$(printf '%s [pithead] password: %s\n' "$JPFX" "$GEN_LOGIN" | brl)" \
+ "$JPFX [pithead] password: [redacted]"
+assert_eq "the generated login line without a journal prefix masks the value" \
+ "$(printf '[pithead] password: %s\n' "$GEN_LOGIN" | brl)" \
+ "[pithead] password: [redacted]"
+assert_eq "the one-time token line in the journal keeps its prefix and masks the value" \
+ "$(printf '%s [pithead] One-time token: pit-ABC123\n' "$JPFX" | brl)" \
+ "$JPFX [pithead] One-time token: [redacted]"
+assert_eq "a stratum password status line is unchanged" \
+ "$(printf 'Stratum password: none set\n' | brl)" "Stratum password: none set"
+assert_eq "a stratum password status line after the log prefix is unchanged" \
+ "$(printf '[pithead] Stratum password: none set\n' | brl)" "[pithead] Stratum password: none set"
+assert_eq "a line that only names a password is unchanged" \
+ "$(printf '[pithead] password: see dashboard.auth.password in config.json\n' | brl)" \
+ "[pithead] password: see dashboard.auth.password in config.json"
+assert_eq "the rpc-login credential keeps its existing masking" \
+ "$(printf -- '--rpc-login %s:%s --zmq-port 18083\n' "$RPC_USER" "$RPC_PASS" | brl)" \
+ "--rpc-login [redacted] --zmq-port 18083"
+
echo "selftest-bundle-redact-log: $IT_PASS passed, $IT_FAIL failed"
[ "$IT_FAIL" -eq 0 ] || exit 1
diff --git a/tests/integration/selftest/selftest-e2e-restore-proof.sh b/tests/integration/selftest/selftest-e2e-restore-proof.sh
index ae395e2082..f3e74271c0 100755
--- a/tests/integration/selftest/selftest-e2e-restore-proof.sh
+++ b/tests/integration/selftest/selftest-e2e-restore-proof.sh
@@ -333,7 +333,7 @@ egress_restore() { # [sticky]
step() { printf 'step:%s\n' "$1" >&2; }
on_bench() {
case "$1" in
- *"disable --now"*)
+ *"disable pithead-egress.service"*)
removals=$((removals + 1))
[ "$STICKY" = 1 ] || UNIT=absent
;;
diff --git a/tests/integration/selftest/selftest-xvb-off-dwell.sh b/tests/integration/selftest/selftest-xvb-off-dwell.sh
index fa0b7ed7f4..ec213e9668 100644
--- a/tests/integration/selftest/selftest-xvb-off-dwell.sh
+++ b/tests/integration/selftest/selftest-xvb-off-dwell.sh
@@ -44,14 +44,19 @@ fixture() {
esac
;;
*'docker inspect'*)
- if [ "$arm" = restart ] && [ "$(cat "$td/clock")" -gt 10000060 ]; then
+ if [ "$arm" = podman-time ]; then
+ echo 'cid 2026-11-28 07:00:31.123456789 +0000 UTC'
+ elif [ "$arm" = restart ] && [ "$(cat "$td/clock")" -gt 10000060 ]; then
echo 'replacement started'
else
echo 'container started'
if [ "$arm" = failed-final-inspect ] && [ "$(cat "$td/clock")" -gt 10000060 ]; then return 1; fi
fi
;;
- 'date -d '*) echo 10000000 ;;
+ 'date -d '*)
+ [ "$arm" != podman-time ] || [[ "$1" != *' UTC'* ]] || return 1
+ echo 10000000
+ ;;
'date +%s')
if [ "$arm" = bad-clock ]; then echo nonsense; else cat "$td/clock"; fi
;;
@@ -117,6 +122,7 @@ fixture() {
echo "PASS: $arm -> $want"
}
fixture quiet PASS
+fixture podman-time PASS
fixture boundary PASS
fixture churn FAIL
fixture early-only FAIL
diff --git a/tests/integration/tor-client/Dockerfile b/tests/integration/tor-client/Dockerfile
index 339aedce29..10acda38a6 100644
--- a/tests/integration/tor-client/Dockerfile
+++ b/tests/integration/tor-client/Dockerfile
@@ -1,6 +1,6 @@
FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
-RUN apk add --no-cache --upgrade libcrypto3 libssl3 musl musl-utils tor curl ca-certificates
+RUN apk add --no-cache --upgrade busybox busybox-binsh ssl_client libcrypto3 libssl3 musl musl-utils tor curl ca-certificates
COPY probe.sh /usr/local/bin/probe.sh
RUN chmod 0755 /usr/local/bin/probe.sh
diff --git a/tests/netwatch/Dockerfile b/tests/netwatch/Dockerfile
index d24afa1c6c..e2a5e1281a 100644
--- a/tests/netwatch/Dockerfile
+++ b/tests/netwatch/Dockerfile
@@ -1,5 +1,5 @@
FROM alpine:3.24@sha256:f59abe656b692d901e184be3445e084786602108599d2a51d229c0f5a48c71bf
-RUN apk add --no-cache --upgrade libcrypto3 libssl3 musl musl-utils zlib conntrack-tools tcpdump
+RUN apk add --no-cache --upgrade busybox busybox-binsh ssl_client libcrypto3 libssl3 musl musl-utils zlib conntrack-tools tcpdump
ENTRYPOINT ["/usr/sbin/conntrack"]
diff --git a/tests/os/README.md b/tests/os/README.md
index e30d59a185..764e413eee 100644
--- a/tests/os/README.md
+++ b/tests/os/README.md
@@ -535,6 +535,16 @@ the host's `/etc`.
scope here for want of inputs this guest cannot give them: the `monero.mode=local` scenario
(#2443, needs a seeded chain) and `--xvb-routing-smoke` (#2444, its probe discards its own
diagnostics, so the red is unreadable).
+ The guest runs with `xvb.enabled` false. One short leg (`appliance-xvb-short-leg.sh`,
+ `selftest-xvb-short-leg.sh`) runs right after provisioning and before the DIY gate. It first reads
+ the dashboard's mode as `P2POOL (XvB Disabled)`. It then checks that the guest reaches the XvB
+ endpoint through Tor, and records a counted `missing` skip with the reason when it cannot. Next it
+ sets `xvb.enabled` through the host-side config edit and `./pithead apply -y`, waits for the
+ dashboard to show XvB active with a zero fetch-failure count, and routes the live proxy to XvB with the
+ controller's own actuator. The proxy's one enabled pool must be the XvB pool over Tor under the
+ stack wallet's donor id. It restores the P2Pool route and the snapshotted config, and requires the
+ dashboard to read XvB off again. Each wait is bounded (180 s state, 150 s proxy API and route), so
+ the leg adds a few minutes.
`--keep` leaves the VM and disks for inspection; `--phase boot|update|install|provision|rig|rigmedia|media|fault|reset|image-upgrade|crossupdate|realupgrade|realupgrade-main|realupgrade-negctl|stack|all`
scopes the run. A failed assertion is recorded and the run carries on, so one bench boot collects
diff --git a/tests/os/appliance-xvb-short-leg.sh b/tests/os/appliance-xvb-short-leg.sh
new file mode 100644
index 0000000000..4d48571367
--- /dev/null
+++ b/tests/os/appliance-xvb-short-leg.sh
@@ -0,0 +1,164 @@
+# shellcheck shell=bash
+# shellcheck disable=SC2154
+
+_XVB_SHORT_OFF='P2POOL (XvB Disabled)'
+_XVB_SHORT_ROUTED=0
+
+_xvb_short_state() {
+ _ssh 'curl -fsS --max-time 10 http://127.0.0.1:8000/api/state' 2>/dev/null |
+ jq -r '[(.hashrate.mode_name // ""), (.hashrate.xvb_fail_count // 0)] | @tsv' 2>/dev/null
+}
+
+_xvb_short_state_is() {
+ local mode="${2%%$'\t'*}" fails="${2##*$'\t'}"
+ case "$1:$mode" in
+ off:"$_XVB_SHORT_OFF") return 0 ;;
+ off:* | on:*Disabled* | on:) return 1 ;;
+ on:*) [ "$fails" = 0 ] ;;
+ esac
+}
+
+_xvb_short_wait() {
+ local state="" deadline
+ deadline=$(($(date +%s) + ${XVB_SHORT_STATE_TIMEOUT:-180}))
+ while [ "$(date +%s)" -lt "$deadline" ]; do
+ state="$(_xvb_short_state)"
+ _xvb_short_state_is "$1" "$state" && return 0
+ sleep 3
+ done
+ printf '%s' "${state:-unreadable}" | tr '\t' ' '
+ return 1
+}
+
+_xvb_short_route_payload() {
+ printf '%s\n' "import asyncio, json" \
+ "from mining_dashboard.client.xmrig_proxy_client import XMRigProxyClient" \
+ "from mining_dashboard.config.config import PROXY_API_PORT, PROXY_AUTH_TOKEN, PROXY_HOST, XVB_DONOR_ID, XVB_POOL_URL" \
+ "from mining_dashboard.service.storage_service import StateManager" \
+ "from mining_dashboard.service.xvb.algo_service import AlgoService" \
+ "async def main():" \
+ " client = XMRigProxyClient(PROXY_HOST, PROXY_API_PORT, PROXY_AUTH_TOKEN)" \
+ " await AlgoService(StateManager(), client, None).switch_miners('XVB')" \
+ " pools = client.get_config().get('pools', [])" \
+ " print(json.dumps({'xvb_url': XVB_POOL_URL, 'donor': XVB_DONOR_ID, 'pools': [{'url': p.get('url'), 'user': p.get('user'), 'enabled': p.get('enabled'), 'tor': bool(p.get('socks5'))} for p in pools]}))" \
+ "asyncio.run(main())" |
+ base64 | tr -d '\n'
+}
+
+_xvb_short_route_ok() {
+ printf '%s' "$1" | jq -e --arg w "$2" '
+ .donor as $d | .xvb_url as $u |
+ ($d | length) >= 8 and ($w | startswith($d)) and
+ ([.pools[] | select(.enabled)] | length == 1 and .[0].url == $u and .[0].user == $d and .[0].tor == true)' \
+ >/dev/null 2>&1
+}
+
+_xvb_short_route_shape() {
+ printf '%s' "$1" | jq -r --arg w "$2" '
+ [.pools[]? | select(.enabled)] as $on | (.donor // "") as $d |
+ "enabled pools: \($on | length), first is the XvB pool: \(($on[0].url // "") == .xvb_url), user is the donor id: \(($on[0].user // "") == $d), donor id prefixes the wallet: \(($d | length) >= 8 and ($w | startswith($d))), over Tor: \($on[0].tor // false)"' 2>/dev/null || printf 'route unreadable'
+}
+
+_xvb_short_route_wait() {
+ local route="" deadline
+ deadline=$(($(date +%s) + ${XVB_SHORT_ROUTE_TIMEOUT:-60}))
+ while :; do
+ route="$(_xvb_guest_python "$(_xvb_short_route_payload)")"
+ _xvb_short_route_ok "$route" "$HARNESS_WALLET" && return 0
+ [ "$(date +%s)" -lt "$deadline" ] || break
+ sleep 3
+ done
+ _xvb_short_route_shape "$route" "$HARNESS_WALLET"
+ return 1
+}
+
+_xvb_short_no_route() {
+ local status
+ if ! status="$(_xvb_wait_for_tor)"; then
+ printf 'guest Tor never bootstrapped (last health: %s), so XvB is unreachable' "$status"
+ return 0
+ fi
+ ! _xvb_real_tor_fetch_retry || return 1
+ printf 'XvB endpoint unreachable through the guest Tor SOCKS'
+}
+
+_xvb_short_set_on() {
+ SSH_TIMEOUT=480 _ssh 'set -eu
+cd /data/pithead
+jq -c ".xvb.enabled = true" config.json >config.json.xvb-short
+mv config.json.xvb-short config.json
+./pithead apply -y' >/dev/null 2>&1
+}
+
+_xvb_short_prove() {
+ local state route
+ if ! _xvb_short_set_on; then
+ bad "XvB leg: xvb.enabled=true through ./pithead apply -y was refused"
+ return 1
+ fi
+ if ! state="$(_xvb_short_wait on)"; then
+ bad "XvB leg: dashboard never showed XvB active with no fetch error within ${XVB_SHORT_STATE_TIMEOUT:-180}s (last: $state)"
+ return 1
+ fi
+ ok "XvB leg: dashboard state shows XvB active with no fetch error"
+ if ! _xvb_wait_for_proxy_api; then
+ bad "XvB leg: xmrig-proxy API never answered within ${XVB_PROXY_READY_TIMEOUT:-150}s $(_xvb_proxy_diag)"
+ return 1
+ fi
+ _XVB_SHORT_ROUTED=1
+ if ! _xvb_actuate XVB true >/dev/null; then
+ bad "XvB leg: the controller could not route the live proxy to XvB within ${XVB_ACTUATE_TIMEOUT:-150}s (guest: $(_xvb_guest_stderr))"
+ return 1
+ fi
+ if ! route="$(_xvb_short_route_wait)"; then
+ bad "XvB leg: the live proxy route is not the XvB pool over Tor under the stack wallet's donor id within ${XVB_SHORT_ROUTE_TIMEOUT:-60}s ($route; guest: $(_xvb_guest_stderr))"
+ return 1
+ fi
+ ok "XvB leg: the live proxy routes to the XvB pool over Tor under the stack wallet's donor id"
+ state="$(_xvb_short_state)"
+ if ! _xvb_short_state_is on "$state"; then
+ bad "XvB leg: dashboard reported an XvB error after routing (state: $(printf '%s' "$state" | tr '\t' ' '))"
+ return 1
+ fi
+}
+
+_xvb_short_restore() {
+ local rc=0 state
+ if [ "$_XVB_SHORT_ROUTED" = 1 ] && ! _xvb_actuate P2POOL false >/dev/null; then
+ bad "XvB leg: the proxy was left on XvB, the P2Pool restore did not confirm (guest: $(_xvb_guest_stderr))"
+ rc=1
+ fi
+ if ! approval_restore_pending; then
+ bad "XvB leg: restoring the original config failed, XvB may be left on"
+ return 1
+ fi
+ if state="$(_xvb_short_wait off)"; then
+ ok "XvB leg: XvB is off again"
+ else
+ bad "XvB leg: dashboard never read XvB off after the restore (last: $state)"
+ rc=1
+ fi
+ return "$rc"
+}
+
+phase_stack_xvb_short() {
+ local state reason rc=0
+ info "stack leg — short XvB-on proof; XvB is off for the rest of the battery"
+ if ! state="$(_xvb_short_wait off)"; then
+ bad "XvB leg: XvB is not off by default on the stack guest (dashboard: $state)"
+ return 1
+ fi
+ ok "XvB leg: XvB is off by default on the stack guest"
+ if reason="$(_xvb_short_no_route)"; then
+ it_skip_leg "short XvB-on proof" "$reason" missing
+ return 0
+ fi
+ if ! approval_capture_restore_snapshot; then
+ bad "XvB leg: could not snapshot the guest's config.json"
+ return 1
+ fi
+ _XVB_SHORT_ROUTED=0
+ _xvb_short_prove || rc=1
+ _xvb_short_restore || rc=1
+ return "$rc"
+}
diff --git a/tests/os/boot-probe-evidence.py b/tests/os/boot-probe-evidence.py
index 0b27e60731..dea4fa9e2d 100644
--- a/tests/os/boot-probe-evidence.py
+++ b/tests/os/boot-probe-evidence.py
@@ -4,7 +4,6 @@
import json
import sys
import time
-import urllib.request
from pathlib import Path
@@ -85,24 +84,6 @@ def log_storage(path):
return result
-def caddy_configuration():
- """Read host-network admin config without emitting any credentials or topology."""
- result = {"available": False, "boot_matcher": False, "log_destination": False}
- try:
- opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
- with opener.open("http://127.0.0.1:2019/config/", timeout=3) as response:
- config = json.loads(response.read(1048576))
- serialized = json.dumps(config)
- result.update(
- available=True,
- boot_matcher="X-Pithead-Boot-Probe" in serialized and "pithead_probe" in serialized,
- log_destination="/var/log/caddy/access.log" in serialized,
- )
- except (OSError, ValueError):
- pass
- return result
-
-
def report(rows, summary, boot_started, now, expected_failures):
"""Bounded diagnostics: counts and context flags, never request/header/user values."""
rows = rows or []
@@ -235,7 +216,6 @@ def selftest():
patch.object(sys, "argv", [__file__, "0"]),
patch("time.time", return_value=1100),
patch("time.sleep"),
- patch("urllib.request.build_opener", side_effect=OSError("fixture unavailable")),
patch.object(Path, "read_text", return_value="200"),
redirect_stdout(captured),
):
@@ -250,20 +230,6 @@ def selftest():
raise AssertionError("live evidence entry point lost its assertion reason")
if json.loads(output.splitlines()[-1])["marked_wrong_uri"] != 1 or fixture_value in output:
raise AssertionError("live evidence entry point lost or leaked its diagnostic")
- with patch("urllib.request.build_opener") as factory:
- factory.return_value.open.return_value = io.BytesIO(
- json.dumps(
- {
- "matcher": "X-Pithead-Boot-Probe",
- "field": "pithead_probe",
- "filename": "/var/log/caddy/access.log",
- "credential": fixture_value,
- }
- ).encode()
- )
- configuration = caddy_configuration()
- if not all(configuration.values()) or fixture_value in json.dumps(configuration):
- raise AssertionError("configuration diagnostic lost flags or leaked a credential")
import os
from tempfile import TemporaryDirectory
@@ -326,7 +292,6 @@ def selftest():
{
**report(rows, summary, boot_started, now, expected),
"storage": log_storage(audit_service.config.ACCESS_LOG_PATH),
- "caddy": caddy_configuration(),
},
sort_keys=True,
)
@@ -340,7 +305,6 @@ def selftest():
{
**report(rows, summary, boot_started, now, expected),
"storage": log_storage(audit_service.config.ACCESS_LOG_PATH),
- "caddy": caddy_configuration(),
},
sort_keys=True,
),
diff --git a/tests/os/phases/install-reinstall.sh b/tests/os/phases/install-reinstall.sh
index 45230624bb..6d88c71224 100644
--- a/tests/os/phases/install-reinstall.sh
+++ b/tests/os/phases/install-reinstall.sh
@@ -16,6 +16,13 @@ _phase_install_reinstall() {
bad "could not plant the reinstall sentinels and 1.x-shaped config"
return 1
}
+ _ssh "n=0; for d in /data/containers/storage/volumes/*/_data; do
+ [ -d \"\$d\" ] && [ ! -L \"\$d\" ] || continue
+ echo volume-data > \"\$d/.reinstall-volume-sentinel\" && n=\$((n + 1))
+ done; [ \"\$n\" -gt 0 ]" || {
+ bad "no named volume folder under /data/containers/storage/volumes to plant the reinstall sentinel in"
+ return 1
+ }
_ssh "systemctl poweroff" 2>/dev/null || true
sleep 8
vm_destroy_or_refuse || return
@@ -100,6 +107,10 @@ _phase_install_reinstall() {
s=OK
test -s \"\$T/pithead/data/monero/chain-sentinel\" || s=NO-MONERO-CHAIN
test -s \"\$T/pithead/data/tari/chain-sentinel\" || s=\$s,NO-TARI-CHAIN
+ ls -d \"\$T\"/containers/storage/volumes/*/_data >/dev/null 2>&1 || s=\$s,NO-VOLUME-FOLDER
+ for f in \"\$T\"/containers/storage/volumes/*/_data/.reinstall-volume-sentinel; do
+ test -e \"\$f\" && s=\$s,VOLUME-DATA-SURVIVED
+ done
test -e \"\$T/pithead/reinstall-sentinel\" && s=\$s,USER-DATA-SURVIVED
umount \"\$T\" 2>&1 || s=\$s,UMOUNT-FAILED
echo \"verdict=\$s\"" 2>&1)
diff --git a/tests/os/phases/stack.sh b/tests/os/phases/stack.sh
index e5e531e3e6..d8cf8eef21 100644
--- a/tests/os/phases/stack.sh
+++ b/tests/os/phases/stack.sh
@@ -38,13 +38,9 @@ stack_browser_config() {
# because the DIY bench's own persistent config happens to carry it disabled; that is a gap
# in the assertion's expected list, filed separately, not a config choice for this phase to
# suppress by diverging from the wizard's default.
- # xvb.enabled stays true even though no invocation here drives XvB routing today: it is the
- # baseline the #2444 row will need the moment that probe is readable enough to run from this
- # phase, and holding it keeps this guest byte-identical to the one job 633 passed against, so
- # that job stays a valid comparison for the next run rather than a differently-configured one.
cfg=$(printf '%s' "$1" | jq -c --arg m "$HARNESS_WALLET" --arg t "$HARNESS_TARI" \
'.monero.wallet_address = $m | .tari.wallet_address = $t | .p2pool.pool = "mini" |
- .xvb.enabled = true') || return 1
+ .xvb.enabled = false') || return 1
if [ -n "$th" ]; then
remote_node_proposal "$cfg" "$2" "$3" "$4" "$5" "$6" "$th" "$grpc"
else
@@ -276,6 +272,7 @@ phase_stack() {
}
_provision_remote_node_coordinator "$img" "$mh" "$rpc" "$zmq" "$mu" "$mp" "$th" "$grpc" || return 1
_stack_container_restart_leg || return 1
+ phase_stack_xvb_short || true
local miner_rc=0
miner_backup_trial || miner_rc=$?
diff --git a/tests/os/run.sh b/tests/os/run.sh
index f97ee58cd5..f39343e7c0 100755
--- a/tests/os/run.sh
+++ b/tests/os/run.sh
@@ -116,6 +116,8 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]:-$0}")" && pwd)"
. "$SCRIPT_DIR/appliance-egress-leg.sh"
# shellcheck source=tests/os/appliance-xvb-routing-leg.sh
. "$SCRIPT_DIR/appliance-xvb-routing-leg.sh"
+# shellcheck source=tests/os/appliance-xvb-short-leg.sh
+. "$SCRIPT_DIR/appliance-xvb-short-leg.sh"
# shellcheck source=tests/os/appliance-address-watch-leg.sh
. "$SCRIPT_DIR/appliance-address-watch-leg.sh"
# shellcheck source=tests/os/appliance-dashboard-exposure-leg.sh
diff --git a/tests/os/selftest-data-reset-probe.sh b/tests/os/selftest-data-reset-probe.sh
index 28abe0883f..d346f66513 100644
--- a/tests/os/selftest-data-reset-probe.sh
+++ b/tests/os/selftest-data-reset-probe.sh
@@ -13,6 +13,7 @@ TRACE="$work/trace"
MKTEMP_FAIL=""
MARKER_PRESENT=""
MOUNT_RESULT=1
+MKFS_RESULT=0
cases=0
fail() {
@@ -30,6 +31,7 @@ reset_fixture() {
MKTEMP_FAIL=""
MARKER_PRESENT=""
MOUNT_RESULT=1
+ MKFS_RESULT=0
}
mktemp() {
@@ -90,7 +92,7 @@ mke2fs() {
function mkfs.ext4 {
printf 'mkfs.ext4\n' >>"$TRACE"
- return 0
+ return "$MKFS_RESULT"
}
for failed_probe in 1 2 3 4 5; do
@@ -214,4 +216,28 @@ esp_mnt=$(awk '$1 == "mktemp" { print $2; exit }' "$TRACE")
[ -f "$esp_mnt/$MARKER_NAME" ] || fail 'refused reset consumed the reset marker'
cases=$((cases + 1))
+reset_fixture
+MARKER_PRESENT=1
+MKFS_RESULT=1
+main >"$work/main-output" 2>"$work/main-error"
+rc=$?
+[ "$rc" -ne 0 ] || fail 'main returned 0 when the requested reformat failed'
+[ "$(count 'mkfs.ext4')" -eq 1 ] || fail 'requested reset did not attempt the reformat exactly once'
+esp_mnt=$(awk '$1 == "mktemp" { print $2; exit }' "$TRACE")
+[ -f "$esp_mnt/$MARKER_NAME" ] || fail 'failed requested reformat consumed the reset marker'
+[ ! -e "$esp_mnt/$WIPE_LOG_NAME" ] || fail 'failed requested reformat recorded a wipe'
+grep -q 'stays requested and runs again at the next boot' "$work/main-error" ||
+ fail 'failed requested reformat did not say the reset stays requested'
+cases=$((cases + 1))
+
+reset_fixture
+MARKER_PRESENT=1
+main >"$work/main-output" 2>"$work/main-error"
+rc=$?
+[ "$rc" -eq 0 ] || fail "requested reset returned $rc after a successful reformat"
+esp_mnt=$(awk '$1 == "mktemp" { print $2; exit }' "$TRACE")
+[ ! -e "$esp_mnt/$MARKER_NAME" ] || fail 'successful requested reset kept the reset marker'
+grep -q 'factory-reset requested' "$esp_mnt/$WIPE_LOG_NAME" || fail 'successful requested reset recorded no wipe'
+cases=$((cases + 1))
+
printf 'selftest-data-reset-probe: %s cases passed\n' "$cases"
diff --git a/tests/os/selftest-install-wipe-tree.sh b/tests/os/selftest-install-wipe-tree.sh
new file mode 100644
index 0000000000..c86f1b0cdb
--- /dev/null
+++ b/tests/os/selftest-install-wipe-tree.sh
@@ -0,0 +1,112 @@
+#!/usr/bin/env bash
+set -euo pipefail
+here="$(cd "$(dirname "$0")" && pwd)"
+work=$(mktemp -d)
+trap 'rm -rf "$work"' EXIT
+# shellcheck source=/dev/null
+source <(sed '$d' "$here/../../os/installer/pithead-install")
+
+fail() {
+ echo "Install wipe=data tree: FAIL: $*" >&2
+ exit 1
+}
+shape() { ls -ldn "$1" | awk '{print $1, $3, $4}'; }
+blk=$(find /dev -maxdepth 1 -type b 2>/dev/null | sed -n 1p)
+fixture=''
+lsblk() { printf '%s data\n' "$blk"; }
+mktemp() { if [ "$*" = -d ] && [ -n "$fixture" ]; then printf '%s\n' "$fixture"; else command mktemp "$@"; fi; }
+mount() { :; }
+umount() { :; }
+rmdir() { [ "$1" = "$fixture" ] || command rmdir "$@"; }
+run_wipe() {
+ if [ -z "$blk" ]; then
+ wipe_user_tree "$1"
+ return
+ fi
+ fixture=$1
+ wipe_data_partition fixture-disk data >/dev/null
+ fixture=''
+ trap 'rm -rf "$work"' EXIT
+}
+
+t="$work/t"
+vol="$t/containers/storage/volumes"
+mkdir -p "$t/pithead/data/monero" "$t/pithead/data/tari" "$t/ssh" "$work/outside/linked" \
+ "$work/outside/entry/_data" "$vol/wallet_data/_data/sub" "$vol/caddy_data/_data" \
+ "$vol/-x y/_data" "$vol/empty" "$t/containers/storage/overlay/layer"
+echo chain >"$t/pithead/data/monero/c"
+echo chain >"$t/pithead/data/tari/c"
+echo cfg >"$t/pithead/config.json"
+echo key >"$t/ssh/host_key"
+echo keep >"$work/outside/target"
+echo keep >"$work/outside/linked/f"
+echo keep >"$work/outside/entry/_data/f"
+echo w >"$vol/wallet_data/_data/wallet.db"
+echo w >"$vol/wallet_data/_data/.hidden"
+echo w >"$vol/wallet_data/_data/sub/x"
+ln -s "$work/outside/target" "$vol/wallet_data/_data/link"
+echo c >"$vol/caddy_data/_data/cert"
+echo d >"$vol/-x y/_data/f"
+echo other >"$vol/wallet_data/other"
+echo stray >"$vol/stray"
+mkdir -p "$vol/linked"
+ln -s "$work/outside/linked" "$vol/linked/_data"
+ln -s "$work/outside/entry" "$vol/entrylink"
+echo layer >"$t/containers/storage/overlay/layer/f"
+chmod 700 "$vol/wallet_data/_data"
+chmod 750 "$vol/caddy_data/_data"
+before_w=$(shape "$vol/wallet_data/_data")
+before_c=$(shape "$vol/caddy_data/_data")
+
+run_wipe "$t"
+
+[ "$(cat "$t/pithead/data/monero/c")" = chain ] || fail "monero chain"
+[ "$(cat "$t/pithead/data/tari/c")" = chain ] || fail "tari chain"
+[ ! -e "$t/pithead/config.json" ] || fail "pithead/ user data kept"
+[ ! -e "$t/ssh" ] || fail "ssh/ kept"
+for d in wallet_data caddy_data "-x y"; do
+ [ -d "$vol/$d/_data" ] && [ -z "$(ls -A "$vol/$d/_data")" ] || fail "volume $d not emptied"
+done
+[ "$(shape "$vol/wallet_data/_data")" = "$before_w" ] || fail "wallet_data/_data mode or owner"
+[ "$(shape "$vol/caddy_data/_data")" = "$before_c" ] || fail "caddy_data/_data mode or owner"
+[ "$(cat "$vol/wallet_data/other")" = other ] || fail "volume record file"
+[ "$(cat "$vol/stray")" = stray ] || fail "stray volumes entry"
+[ "$(cat "$t/containers/storage/overlay/layer/f")" = layer ] || fail "image layer"
+[ "$(cat "$work/outside/target")" = keep ] || fail "link target inside a volume"
+[ "$(cat "$work/outside/linked/f")" = keep ] || fail "_data link target"
+[ -L "$vol/linked/_data" ] || fail "_data link removed"
+[ "$(cat "$work/outside/entry/_data/f")" = keep ] || fail "volumes entry link target"
+[ ! -e "$t/.wipe-keep.$$" ] || fail "keep folder left behind"
+
+t2="$work/t2"
+mkdir -p "$t2/pithead/data/monero" "$t2/containers" "$work/elsewhere/volumes/v/_data"
+echo chain >"$t2/pithead/data/monero/c"
+echo keep >"$work/elsewhere/volumes/v/_data/f"
+ln -s "$work/elsewhere" "$t2/containers/storage"
+run_wipe "$t2"
+[ "$(cat "$work/elsewhere/volumes/v/_data/f")" = keep ] || fail "store reached through a link"
+[ "$(cat "$t2/pithead/data/monero/c")" = chain ] || fail "monero chain without volumes"
+
+t3="$work/t3"
+mkdir -p "$t3/pithead/data/tari" "$t3/ssh"
+echo chain >"$t3/pithead/data/tari/c"
+run_wipe "$t3"
+[ "$(cat "$t3/pithead/data/tari/c")" = chain ] && [ ! -e "$t3/ssh" ] || fail "tree without a store"
+
+t4="$work/t4"
+mkdir -p "$t4/pithead/data/monero" "$t4/containers/storage/volumes/v/_data"
+echo chain >"$t4/pithead/data/monero/c"
+echo w >"$t4/containers/storage/volumes/v/_data/f"
+find() { return 1; }
+set +e
+(
+ set -e
+ run_wipe "$t4"
+) 2>/dev/null
+rc=$?
+set -e
+unset -f find
+[ "$rc" != 0 ] || fail "a volume that cannot be emptied is reported as wiped"
+[ "$(cat "$t4/pithead/data/monero/c")" = chain ] || fail "monero chain after a failed volume wipe"
+! compgen -G "$t4/.wipe-keep.*" >/dev/null || fail "keep folder left behind after a failed volume wipe"
+echo 'Install wipe=data tree: PASS'
diff --git a/tests/os/selftest-schema-hold.sh b/tests/os/selftest-schema-hold.sh
index 41fbc34aa7..ae5966bcf1 100644
--- a/tests/os/selftest-schema-hold.sh
+++ b/tests/os/selftest-schema-hold.sh
@@ -150,6 +150,33 @@ done
[ -z "$(ls -A "$T/target-dir")" ] || fail "arming must not write into a linked folder"
[ ! -e "$T/missing" ] || fail "arming must not create a dangling link's target"
+printf 'keep-me\n' >"$T/target-dir/inside"
+plant() {
+ rm -f "$marker"
+ case "$1" in
+ empty) mkdir "$marker" ;;
+ full) mkdir -p "$marker/deep/er" && printf 'x\n' >"$marker/deep/er/file" && ln -s "$T/target-dir" "$marker/deep/out" ;;
+ dirlink) ln -s "$T/target-dir" "$marker" ;;
+ filelink) ln -s "$T/target-file" "$marker" ;;
+ dangling) ln -s "$T/missing" "$marker" ;;
+ esac
+}
+for planted in empty full dirlink filelink dangling; do
+ RAUC_STATUS_FILE="$T/good.json"
+ plant "$planted"
+ schema_hold_arm >/dev/null 2>&1
+ [ ! -e "$marker" ] && [ ! -L "$marker" ] || fail "a committed boot must remove what sits at the marker ($planted)"
+ plant "$planted"
+ schema_hold_release >/dev/null 2>&1 || fail "release must not fail the boot ($planted)"
+ [ ! -e "$marker" ] && [ ! -L "$marker" ] || fail "release must remove what sits at the marker ($planted)"
+ RAUC_STATUS_FILE="$T/bad.json"
+ plant "$planted"
+ schema_hold_arm >/dev/null 2>&1 || fail "arming over a folder or link at the marker must still arm ($planted)"
+ [ -f "$marker" ] && [ ! -L "$marker" ] || fail "arming must leave a real marker in its place ($planted)"
+done
+[ "$(cat "$T/target-dir/inside")" = keep-me ] || fail "removing the marker must keep the files of a linked folder"
+[ "$(cat "$T/target-file")" = keep-me ] && [ "$(mode_of "$T/target-file")" = 640 ] || fail "removing the marker must keep a linked file"
+
mktemp() {
local made
made=$(command mktemp "$@") || return
diff --git a/tests/os/selftest-xvb-short-leg.sh b/tests/os/selftest-xvb-short-leg.sh
new file mode 100755
index 0000000000..0de05fbffb
--- /dev/null
+++ b/tests/os/selftest-xvb-short-leg.sh
@@ -0,0 +1,96 @@
+#!/usr/bin/env bash
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+# shellcheck disable=SC2034
+OS_RUN_SUITE=1 SCRIPT_DIR="$HERE" HARNESS_WALLET=fixturewalletaddress0123456789
+# shellcheck source=tests/os/appliance-xvb-routing-leg.sh
+source "$HERE/appliance-xvb-routing-leg.sh"
+# shellcheck source=tests/os/appliance-xvb-short-leg.sh
+source "$HERE/appliance-xvb-short-leg.sh"
+# shellcheck source=tests/os/xvb-selftest-clock.sh
+source "$HERE/xvb-selftest-clock.sh"
+
+work=$(mktemp -d)
+trap 'rm -rf "$work"' EXIT
+_xvb_selftest_clock "$work/clock"
+XVB_SHORT_STATE_TIMEOUT=4 XVB_PROXY_READY_TIMEOUT=4 XVB_ACTUATE_TIMEOUT=4 XVB_SHORT_ROUTE_TIMEOUT=6
+
+ok() { printf x >>"$work/pass"; }
+bad() { printf x >>"$work/fail"; }
+info() { :; }
+it_skip_leg() { printf x >>"$work/skips"; }
+_xvb_proxy_diag() { :; }
+_xvb_guest_stderr() { :; }
+approval_capture_restore_snapshot() { return 0; }
+approval_restore_pending() {
+ printf x >>"$work/restores"
+ printf off >"$work/xvb"
+ return "${RESTORE_RC:-0}"
+}
+_xvb_wait_for_tor() { [ "${TOR:-up}" = up ] || { printf starting && return 1; }; }
+_xvb_real_tor_fetch_retry() { [ "${FETCH:-up}" = up ]; }
+_xvb_wait_for_proxy_api() { return 0; }
+_xvb_short_set_on() {
+ printf x >>"$work/applies"
+ [ "${APPLY_RC:-0}" = 0 ] || return 1
+ printf on >"$work/xvb"
+}
+_xvb_actuate() { [ "$1" != XVB ] || [ "${ACTUATE:-up}" = up ]; }
+_xvb_guest_python() {
+ local n
+ n=$(cat "$work/reads" 2>/dev/null) || n=0
+ n=$((${n:-0} + 1))
+ printf '%s' "$n" >"$work/reads"
+ if [ "$n" -le "${LATE:-0}" ]; then printf '%s' "${EARLY_ROUTE:-}"; else printf '%s' "$ROUTE"; fi
+}
+_xvb_short_state() {
+ if [ "$(cat "$work/xvb")" = on ]; then
+ printf 'XVB\t%s\n' "${FAILS:-0}"
+ else
+ printf '%s\t0\n' "${BASE:-$_XVB_SHORT_OFF}"
+ fi
+}
+
+good_route='{"xvb_url":"x.example:4247","donor":"fixturew","pools":[{"url":"x.example:4247","user":"fixturew","enabled":true,"tor":true},{"url":"p2pool:3333","user":"fixturewalletaddress0123456789","enabled":false,"tor":false}]}'
+
+case_run() {
+ local label="$1" wp="$2" wf="$3" ws="$4" wa="$5" wr="$6" rc=0 got
+ shift 6
+ : >"$work/pass" && : >"$work/fail" && : >"$work/skips" && : >"$work/applies" && : >"$work/restores" && printf off >"$work/xvb"
+ (
+ for kv in "$@"; do export "${kv?}"; done
+ phase_stack_xvb_short
+ ) || rc=$?
+ got="$(wc -c <"$work/pass" | tr -d ' ')/$(wc -c <"$work/fail" | tr -d ' ')/$(wc -c <"$work/skips" | tr -d ' ')/$(wc -c <"$work/applies" | tr -d ' ')/$(wc -c <"$work/restores" | tr -d ' ')"
+ [ "$got" = "$wp/$wf/$ws/$wa/$wr" ] || {
+ printf 'selftest-xvb-short-leg: FAIL %s: got pass/fail/skips/applies/restores %s want %s/%s/%s/%s/%s (rc %s)\n' \
+ "$label" "$got" "$wp" "$wf" "$ws" "$wa" "$wr" "$rc" >&2
+ exit 1
+ }
+}
+
+ROUTE="$good_route"
+case_run "a clean on and off leg passes four rows" 4 0 0 1 1
+: >"$work/reads"
+case_run "a route that settles a few seconds late passes" 4 0 0 1 1 LATE=1 'EARLY_ROUTE={"xvb_url":"x.example:4247","donor":"fixturew","pools":[{"url":"p2pool:3333","user":"fixturew","enabled":true,"tor":false}]}'
+: >"$work/reads"
+case_run "a guest with no Tor skips, never turns XvB on" 1 0 1 0 0 TOR=down
+case_run "an unreachable XvB endpoint skips, never turns XvB on" 1 0 1 0 0 FETCH=down
+case_run "XvB on by default is red before anything is changed" 0 1 0 0 0 "BASE=XVB"
+case_run "a refused apply is red and still restores" 2 1 0 1 1 APPLY_RC=1
+case_run "an XvB fetch error reads as not active, red, restored" 2 1 0 1 1 FAILS=2
+case_run "a controller that cannot route to XvB is red and restored" 3 1 0 1 1 ACTUATE=down
+case_run "a failed restore is red" 3 1 0 1 1 RESTORE_RC=1
+
+for broken in \
+ '{"xvb_url":"x.example:4247","donor":"fixturew","pools":[{"url":"x.example:4247","user":"fixturew","enabled":true,"tor":false}]}' \
+ '{"xvb_url":"x.example:4247","donor":"fixturew","pools":[{"url":"p2pool:3333","user":"fixturew","enabled":true,"tor":true}]}' \
+ '{"xvb_url":"x.example:4247","donor":"otherwal","pools":[{"url":"x.example:4247","user":"otherwal","enabled":true,"tor":true}]}' \
+ '{"xvb_url":"x.example:4247","donor":"short","pools":[{"url":"x.example:4247","user":"short","enabled":true,"tor":true}]}' \
+ '{"xvb_url":"x.example:4247","donor":"fixturew","pools":[{"url":"x.example:4247","user":"fixturew","enabled":true,"tor":true},{"url":"p2pool:3333","user":"fixturew","enabled":true,"tor":false}]}' \
+ ''; do
+ ROUTE="$broken"
+ case_run "a wrong live route is red and restored: ${broken:-empty}" 3 1 0 1 1
+done
+
+echo 'selftest-xvb-short-leg: PASS'
diff --git a/tests/os/verify-image.sh b/tests/os/verify-image.sh
index 5aeab656ca..6894f7d4af 100755
--- a/tests/os/verify-image.sh
+++ b/tests/os/verify-image.sh
@@ -135,6 +135,8 @@ chk "serial getty condition shipped as a drop-in" 'test -s "$ROOT/etc/systemd/sy
chk "pithead-media-config script present and executable" 'test -x "$ROOT/usr/local/sbin/pithead-media-config"'
chk "pithead-boot calls the media-config channel before render" \
'grep -q "pithead-media-config" "$ROOT/usr/local/sbin/pithead-boot"'
+chk "early CPU microcode for Intel and AMD in the initrd" \
+ 'LC_ALL=C grep -aq kernel/x86/microcode/GenuineIntel.bin "$ROOT/initrd.img" && LC_ALL=C grep -aq kernel/x86/microcode/AuthenticAMD.bin "$ROOT/initrd.img"'
chk "podman-restart retired (it killed the stack it started)" '[ ! -e "$ROOT/etc/systemd/system/multi-user.target.wants/podman-restart.service" ] && [ ! -e "$ROOT/etc/systemd/system/podman-restart.service.d" ]'
chk "kernel + initrd in the slot" '[ -s "$ROOT/vmlinuz" ] || [ -L "$ROOT/vmlinuz" ]'
diff --git a/tests/stack/appliance/test-appliance-media.sh b/tests/stack/appliance/test-appliance-media.sh
index 777d187809..c762f45ef3 100644
--- a/tests/stack/appliance/test-appliance-media.sh
+++ b/tests/stack/appliance/test-appliance-media.sh
@@ -186,12 +186,16 @@ EOF
diffout=$(
export PITHEAD_MEDIA_BIN="$MC/pithead"
source "$ROOT/os/overlay/pithead-media-config"
- SECRET_PATHS_JSON=$(_secret_paths_json) # the real fetch, against the sandboxed pithead copy
- media_config_diff "$MC/good.json" "$MC/changed.json"
+ SECRET_PATHS_JSON=$(_secret_paths_json)
+ media_config_diff <(jq '.workers.list=[{name:"rig1",api_token:"api-token-old-value"}] | .dashboard.workers=[{name:"rig2",api_token:"api-token-old-second"}]' "$MC/good.json") \
+ <(jq '.workers.list=[{name:"rig1",api_token:"api-token-new-value"}] | .dashboard.workers=[{name:"rig2",api_token:"api-token-new-second"}]' "$MC/changed.json")
)
assert_contains "the payout wallet change shows old -> new in full (that IS the point)" "$diffout" "$VALID_PRIMARY -> 44MnN1f3Eto8DZYUWuE5XZNUtE3vcRzt2j6PzqWpPau34e6Cf4fAxt6X2MBmrm6F9YMEiMNjN6W4Shn4pLcfNAja621jwyg"
assert_contains "a changed secret (dashboard password) names the path" "$diffout" "dashboard.auth.password"
assert_not_contains "a changed secret never shows the new value" "$diffout" "a-new-dashboard-password"
+assert_contains "a changed worker API token is listed as changed with its value hidden" "$diffout" "workers.list.0.api_token: changed (value hidden)"
+assert_contains "a changed worker API token under dashboard.workers is listed the same way" "$diffout" "dashboard.workers.0.api_token: changed (value hidden)"
+assert_eq "no worker API token value is printed, old or new" "$(printf '%s' "$diffout" | grep -c 'api-token-' || true)" "0"
rc=$(
export PITHEAD_MEDIA_BIN="$MC/pithead"
@@ -211,8 +215,6 @@ rc=$(
)
assert_eq "a real change -> media_config_identical false" "$rc" "1"
-# Masking fails CLOSED: with no secret-path list there is no diff and no "identical" verdict —
-# an earlier draft fell back to an empty list, which printed raw secret values to the console.
rc=$(
export PITHEAD_MEDIA_BIN="$MC/does-not-exist"
source "$ROOT/os/overlay/pithead-media-config"
@@ -354,8 +356,6 @@ fi
assert_contains "the cancelled change is announced on the console" "$(cat "$MC/abort.out")" \
"Media configuration channel: cancelled — no changes applied."
-# main() must FAIL CLOSED end to end when the secret-path list can't be read: with a broken host
-# program, no diff (which could leak raw secret values) is ever shown and no config is applied.
STICK6="$MC/stick-nosecrets"
mkdir -p "$STICK6"
cp "$MC/changed.json" "$STICK6/pithead-config.json"
diff --git a/tests/stack/appliance/test-appliance-reset-lock.sh b/tests/stack/appliance/test-appliance-reset-lock.sh
index 80b639dc13..4aacd7ad6f 100644
--- a/tests/stack/appliance/test-appliance-reset-lock.sh
+++ b/tests/stack/appliance/test-appliance-reset-lock.sh
@@ -60,6 +60,7 @@ RSLREBOOTED="$RSL/.rebooted"
rsl_seed() { # a provisioned box with clean logs: re-armed before EVERY run, contended or not
printf '{}\n' >"$RSL/config.json"
cat >"$RSL/.env" <"$V/config.json"
+printf '{ "network":{"tor_egress_firewall":false}, "monero": {"mode":"local","wallet_address":"%s","node_username":"u","node_password":"p"}, "tari":{"wallet_address":"'"$VALID_TARI"'"}, "p2pool":{"pool":"main"}, "dashboard":{"secure":true,"host":"box.lan"} }\n' "$WALLET" >"$V/config.json"
kept_dir="$V/"'kept $literal'
jq --arg dir "$kept_dir" '.monero.data_dir = $dir' "$V/config.json" >"$V/config.json.tmp" && mv "$V/config.json.tmp" "$V/config.json"
out="$(cd "$V" && PATH="$V/bin:$PATH" ./pithead apply -y 2>&1)"
diff --git a/tests/stack/control/control-backup-ownership.sh b/tests/stack/control/control-backup-ownership.sh
index 869576880f..f041ab04df 100644
--- a/tests/stack/control/control-backup-ownership.sh
+++ b/tests/stack/control/control-backup-ownership.sh
@@ -83,6 +83,7 @@ EOS
printf '#!/usr/bin/env bash\nexec "$@"\n' >"$XB/bin/sudo"
chmod +x "$XB/bin/docker" "$XB/bin/sudo"
cat >"$XB/.env" <<'EOS'
+TOR_EGRESS_FIREWALL=false
MONERO_ONION_ADDRESS=mona.onion
TARI_ONION_ADDRESS=taria.onion
P2POOL_ONION_ADDRESS=p2pa.onion
diff --git a/tests/stack/control/test-support-bundle-snapshots.sh b/tests/stack/control/test-support-bundle-snapshots.sh
index 39e8691e8a..107b85c246 100644
--- a/tests/stack/control/test-support-bundle-snapshots.sh
+++ b/tests/stack/control/test-support-bundle-snapshots.sh
@@ -350,3 +350,51 @@ assert_eq "the manifest records the steps the limit skipped" \
assert_eq "the skip names the limit" \
"$(sb_man "$SN/x5" '[.failures[] | select(.status == "skipped") | .reason | contains("total time limit")] | all')" "true"
assert_eq "the manifest states the total limit it applied" "$(sb_man "$SN/x5" '.limits.total_seconds')" "1"
+
+echo "== support bundle snapshots: the cookie, the Tor state and marker bodies are read only as regular files =="
+SR="$SN/reads"
+mkdir -p "$SR/e2e" "$SR/link" "$SR/dangling" "$SR/fifo" "$SR/folder/control_auth_cookie" "$SR/short" \
+ "$SR/m" "$SR/m2" "$SR/g-link" "$SR/g-fifo" "$SR/g-folder/state" "$SR/g-none"
+ln -s "$SN/tor/control_auth_cookie" "$SR/e2e/control_auth_cookie"
+ln -s "$SN/tor/state" "$SR/e2e/state"
+sed "s#^TOR_DATA_DIR=.*#TOR_DATA_DIR=$SR/e2e#" "$sn_env" >"$SN/env5"
+sn_tor fine
+sn_run c412c412-0000-4000-8000-000000000006 fine "PITHEAD_ENV_FILE=$SN/env5" "PITHEAD_SUPPORT_TOR_CONTROL=127.0.0.1:$(cat "$SN/port")"
+kill "$SN_TOR_PID" 2>/dev/null || true
+sb_unzip "$SB/results/c412c412-0000-4000-8000-000000000006.zip" "$SN/x6"
+assert_not_contains "a linked cookie is not sent to the control port" "$(cat "$SN/x6/bundle/tor/control.txt")" "PROGRESS=100"
+assert_not_contains "a linked Tor state file is not read" "$(cat "$SN/x6/bundle/tor/state-guards.txt")" "guardone"
+run_sourced "$SANDBOX" bundle_support_read_py >"$SR/snap.py" 2>/dev/null
+run_sourced "$SANDBOX" bundle_support_snap_py >>"$SR/snap.py"
+python3 -I -c 'import socket, sys
+s = socket.create_server(("127.0.0.1", 0)); open(sys.argv[1], "w").write(str(s.getsockname()[1]))
+while True: c = s.accept()[0]; open(sys.argv[2], "a").write(c.makefile("rb").readline().decode()); c.close()' "$SR/port" "$SR/conn.log" &
+timeout 10 bash -c 'until [ -s "$1" ]; do sleep 0.1; done' _ "$SR/port"
+printf '%-32s' 'LINKED COOKIE' >"$SR/m/plain"
+ln -s "$SR/m/plain" "$SR/link/control_auth_cookie"
+ln -s "$SR/none" "$SR/dangling/control_auth_cookie"
+mkfifo "$SR/fifo/control_auth_cookie" "$SR/m/pipe" "$SR/g-fifo/state"
+printf '%031d' 0 >"$SR/short/control_auth_cookie"
+sr_out=$(for c in link dangling fifo folder short; do
+ printf ' %s:%s' "$c" "$(timeout 10 python3 -I "$SR/snap.py" tor "$SR/$c" "127.0.0.1:$(cat "$SR/port")" 2>/dev/null | jq -r .reachable)"
+done)
+assert_eq "a linked, dangling, FIFO, folder or short cookie gives the unavailable Tor snapshot" "$sr_out" " link:false dangling:false fifo:false folder:false short:false"
+assert_eq "no refused cookie opens a control connection" "$(cat "$SR/conn.log" 2>/dev/null)" ""
+timeout 10 python3 -I "$SR/snap.py" tor "$SN/tor" "127.0.0.1:$(cat "$SR/port")" >/dev/null 2>&1
+assert_contains "a regular 32-byte cookie is sent as before" "$(cat "$SR/conn.log")" "AUTHENTICATE $SN_COOKIE_HEX"
+kill "$!" 2>/dev/null || true
+ln -s "$SR/m/plain" "$SR/m2/linked"
+timeout 10 python3 -I "$SR/snap.py" markers "$SR/m" >"$SR/m.out"
+assert_eq "a FIFO in the marker tree does not hold the listing" "$?:$(tail -n 1 "$SR/m.out")" "0: content: LINKED COOKIE"
+assert_not_contains "a marker swapped for a link after its listing is not read" \
+ "$(timeout 10 python3 -I -c 'import os, runpy, sys; os.lstat = os.stat; sys.argv = sys.argv[1:]; runpy.run_path(sys.argv[0], run_name="__main__")' "$SR/snap.py" markers "$SR/m2")" "LINKED COOKIE"
+printf 'TorVersion Tor 0.4.8.12\nGuard in=bridges rsa_id=CC bridge_addr=192.0.2.9:443 nickname=b\nKey SEEDED\n' >"$SR/g-state"
+assert_eq "the guard lines of a regular state file are the same bytes as before" "$(python3 -I "$SR/snap.py" guards "$SR/g-state" | od -c)" \
+ "$(awk '/^(TorVersion|LastWritten|Guard) / { gsub(/bridge_addr=[^ ]+/, "bridge_addr=[redacted]"); print }' "$SR/g-state" | od -c)"
+ln -s "$SR/g-state" "$SR/g-link/state"
+exec 3<>"$SR/g-fifo/state" && printf 'Guard fed\n' >&3
+sr_out=$(for c in link fifo folder none; do
+ printf ' %s:%s' "$c" "$(timeout 10 python3 -I "$SR/snap.py" guards "$SR/g-$c/state" 2>/dev/null | wc -c | tr -d ' ')"
+done)
+exec 3>&-
+assert_eq "a linked, FIFO, folder or missing state file gives no guard lines" "$sr_out" " link:0 fifo:0 folder:0 none:0"
diff --git a/tests/stack/dashboard/caddy-admin-off.sh b/tests/stack/dashboard/caddy-admin-off.sh
new file mode 100644
index 0000000000..e9af8f5d8a
--- /dev/null
+++ b/tests/stack/dashboard/caddy-admin-off.sh
@@ -0,0 +1,74 @@
+# shellcheck shell=bash
+: "${STACK_SUITE:?is unset: this file is a tests/stack/run.sh fragment, not a script — run tests/stack/run.sh}"
+caddy_admin_hb64="$(printf '%s' '$2y$14$UNITTESTbcrypthashvalue000000000000000000000000000000' | openssl base64 -A)"
+caddy_admin_health=$'http://:2019 {\n bind 127.0.0.1\n respond / 204\n respond /config/ 204\n respond 404\n}'
+caddy_admin_old="$ROOT/tests/stack/fixtures/caddy/v2.0.4-https-login.Caddyfile"
+caddy_admin_render() {
+ (
+ # shellcheck disable=SC1090
+ cd "$SANDBOX" && source "$STACK" 2>/dev/null
+ set +e
+ HOST_IP=box.lan DASHBOARD_AUTH_USER=admin DASHBOARD_SECURE="$1" HOST_PORT="$2" DASHBOARD_AUTH_HASH_B64="$3" \
+ generate_caddyfile >/dev/null 2>&1
+ cat Caddyfile
+ )
+}
+caddy_admin_missing() {
+ local line missing=""
+ while IFS= read -r line; do
+ case $'\n'"$2"$'\n' in *$'\n'"$line"$'\n'*) ;; *) missing="${missing}[$line]" ;; esac
+ done <<<"$1"
+ printf '%s' "${missing:-none}"
+}
+
+echo "== unit: generate_caddyfile turns Caddy's admin endpoint off =="
+caddy_http="$(caddy_admin_render false "" "")"
+caddy_https="$(caddy_admin_render true "" "$caddy_admin_hb64")"
+caddy_custom="$(caddy_admin_render true 8443 "")"
+assert_eq "plain HTTP: the file opens with a global block that turns the admin endpoint off" \
+ "$(printf '%s\n' "$caddy_http" | sed -n '1,3p')" $'{\n admin off\n}'
+assert_eq "HTTPS on 443: the global block turns the admin endpoint and Caddy's own redirect off" \
+ "$(printf '%s\n' "$caddy_https" | sed -n '1,4p')" $'{\n admin off\n auto_https disable_redirects\n}'
+assert_eq "HTTPS on a custom port: the global block turns the admin endpoint and Caddy's own redirect off" \
+ "$(printf '%s\n' "$caddy_custom" | sed -n '1,4p')" $'{\n admin off\n auto_https disable_redirects\n}'
+assert_eq "every render has exactly one admin line" \
+ "$(printf '%s\n' "$caddy_http" "$caddy_https" "$caddy_custom" | grep -c '^ admin off$')" "3"
+assert_contains "HTTPS on 443 still answers :80 itself" "$caddy_https" $'\nhttp:// {\n'
+assert_not_contains "HTTPS on a custom port leaves :80 alone" "$caddy_custom" $'\nhttp:// {\n'
+assert_contains "plain HTTP: the loopback health site answers / and /config/ and nothing else" "$caddy_http" "$caddy_admin_health"
+assert_contains "HTTPS on 443: the loopback health site answers / and /config/ and nothing else" "$caddy_https" "$caddy_admin_health"
+assert_contains "HTTPS on a custom port: the loopback health site answers / and /config/ and nothing else" "$caddy_custom" "$caddy_admin_health"
+assert_contains "the health site answers the 2.0.4 compose probe path with 204" "$caddy_https" $' respond /config/ 204\n respond 404'
+
+echo "== static: nothing in the stack talks to Caddy's admin endpoint =="
+caddy_admin_users="$(cd "$ROOT" && grep -rnE 'caddy (reload|stop)([^a-z]|$)|localhost:2019|127\.0\.0\.1:2019/[A-Za-z]|CADDY_ADMIN' \
+ lib os build dashboard/mining_dashboard scripts tests/integration tests/os .github docker-compose.yml pithead install.sh 2>/dev/null)"
+assert_eq "no caddy reload, caddy stop or admin-endpoint address outside the unit tests" "$caddy_admin_users" ""
+
+echo "== black-box: an upgrade renders the new Caddyfile before compose up starts Caddy =="
+caddy_admin_dir="$SANDBOX/caddy-admin-upgrade"
+mkdir -p "$caddy_admin_dir"
+cp "$caddy_admin_old" "$caddy_admin_dir/Caddyfile"
+caddy_at_up="$(
+ cd "$caddy_admin_dir" || exit
+ # shellcheck disable=SC1090
+ source "$STACK" 2>/dev/null
+ set +e
+ for f in is_appliance is_source_checkout; do eval "$f() { return 1; }"; done
+ for f in mutation_lock_acquire mutation_lock_release log require_env ensure_onion_password parse_and_validate_config \
+ load_preserved_state ensure_directories resolve_dashboard_host render_env tari_upgrade_space_precheck \
+ provision_node_onions inject_service_configs provision_ssh_access provision_console_login migrate_compose_project \
+ apply_tor_egress_firewall migrate_dashboard_data verify_release_images update_current_symlink \
+ provision_control_runner provision_egress_check_units provision_lan_guard_check_units; do eval "$f() { :; }"; done
+ compose_up_checked() { cp Caddyfile Caddyfile.at-up; }
+ PITHEAD_ENV_STAGE="$PWD/.env.stage" ENV_FILE="$PWD/.env" HOST_IP=box.lan DASHBOARD_AUTH_USER=admin \
+ DASHBOARD_SECURE=true DASHBOARD_AUTH_HASH_B64="$caddy_admin_hb64" stack_upgrade >/dev/null 2>&1
+ cat Caddyfile.at-up 2>/dev/null
+)"
+assert_eq "upgrade from 2.0.4: Caddy starts with the admin endpoint off" \
+ "$(printf '%s\n' "$caddy_at_up" | sed -n '1,4p')" $'{\n admin off\n auto_https disable_redirects\n}'
+assert_contains "upgrade from 2.0.4: Caddy starts with the loopback health site" "$caddy_at_up" "$caddy_admin_health"
+assert_eq "upgrade from 2.0.4: every site the old Caddyfile served is still served" \
+ "$(caddy_admin_missing "$(grep -E '^[^ {}].* \{$' "$caddy_admin_old")" "$caddy_at_up")" "none"
+assert_eq "upgrade from 2.0.4: every upstream the old Caddyfile proxied to is still proxied to" \
+ "$(caddy_admin_missing "$(grep -E '^ +reverse_proxy ' "$caddy_admin_old")" "$caddy_at_up")" "none"
diff --git a/tests/stack/dashboard/test-dashboard-bridge-bind.sh b/tests/stack/dashboard/test-dashboard-bridge-bind.sh
index 2d747eb4e9..860c03a736 100644
--- a/tests/stack/dashboard/test-dashboard-bridge-bind.sh
+++ b/tests/stack/dashboard/test-dashboard-bridge-bind.sh
@@ -32,7 +32,7 @@ caddy_bridge="$(
generate_caddyfile >/dev/null 2>&1
cat Caddyfile
)"
-bridge_bind="$(printf '%s' "$caddy_bridge" | grep '^ bind ' | sort -u)"
+bridge_bind="$(printf '%s' "$caddy_bridge" | grep '^ bind ' | grep -vx ' bind 127.0.0.1' | sort -u)"
assert_eq "the bind keeps the LAN, ULA and loopback and drops engine bridges but keeps LAN bridges (br0, br-lan)" \
"$bridge_bind" " bind 192.168.1.10 fd00::1 192.168.50.2 192.168.60.2 127.0.0.1 ::1"
site_line="$(printf '%s' "$caddy_bridge" | grep -m1 '^https://pithead.local')"
diff --git a/tests/stack/dashboard/test-dashboard-login.sh b/tests/stack/dashboard/test-dashboard-login.sh
index efa6fac7e1..5b2997d292 100644
--- a/tests/stack/dashboard/test-dashboard-login.sh
+++ b/tests/stack/dashboard/test-dashboard-login.sh
@@ -22,7 +22,9 @@ assert_contains "login: session check goes through forward_auth" "$caddy_on" "fo
assert_contains "login: forward_auth targets the dashboard check endpoint" "$caddy_on" "uri /api/auth/check"
assert_contains "login: forward_auth copies the actor from the session" "$caddy_on" "copy_headers X-Auth-User X-Pithead-Session-Refresh"
assert_contains "login: basic auth still gates scripts and API clients" "$caddy_on" "route @pithead_basic {"
-assert_contains "login: the basic-auth actor reaches the dashboard" "$caddy_on" " request_header X-Auth-User {http.auth.user.id}"
+assert_contains "login: basic credentials are checked by the dashboard, which counts failures" "$caddy_on" " uri /api/auth/basic"
+assert_contains "login: the basic-auth actor comes back from that check" "$caddy_on" " copy_headers X-Auth-User"
+assert_not_contains "login: the gate itself checks no basic credentials" "${caddy_on%%http://127.0.0.1:8001*}" "basic_auth"
assert_contains "login: client-supplied actor header is stripped first" "$caddy_on" "request_header -X-Auth-User"
assert_contains "login: the sign-in endpoints skip the gate" "$caddy_on" "@pithead_public path /login /api/auth/login /api/auth/logout"
public_line=$(printf '%s\n' "$caddy_on" | grep -F "@pithead_public path")
@@ -53,3 +55,5 @@ assert_not_contains "no login: no verifier site" "$caddy_off" "127.0.0.1:8001"
assert_not_contains "no login: no epoch" "$caddy_off" "X-Pithead-Auth-Epoch"
assert_contains "no login: the sign-in paths are 404, as before" "$caddy_off" "respond @pithead_auth_paths 404"
assert_contains "no login: the actor placeholder still renders empty" "$caddy_off" "header_up X-Auth-User {http.auth.user.id}"
+# shellcheck source=tests/stack/dashboard/caddy-admin-off.sh
+source "$ROOT/tests/stack/dashboard/caddy-admin-off.sh" || return $?
diff --git a/tests/stack/dashboard/test-dashboard-onion.sh b/tests/stack/dashboard/test-dashboard-onion.sh
index dba86239ab..9e210b7c90 100644
--- a/tests/stack/dashboard/test-dashboard-onion.sh
+++ b/tests/stack/dashboard/test-dashboard-onion.sh
@@ -36,7 +36,7 @@ caddy_onion="$(
cat Caddyfile
)"
assert_contains "onion vhost bound to the bridge gateway" "$caddy_onion" "http://172.28.0.1 {"
-assert_contains "onion vhost carries basic_auth" "$caddy_onion" "basic_auth"
+assert_contains "onion vhost carries the counted basic check" "${caddy_onion#*172.28.0.1}" "uri /api/auth/basic"
assert_contains "onion vhost carries the session gate" "${caddy_onion#*172.28.0.1}" "forward_auth @pithead_session 127.0.0.1:8000"
assert_contains "onion vhost serves the sign-in endpoints" "${caddy_onion#*172.28.0.1}" "@pithead_public path /login"
onion_site="${caddy_onion#*172.28.0.1}"
@@ -81,7 +81,7 @@ case "$https_site" in
*"tls internal"*) ok "onion HTTPS vhost uses a self-signed cert (tls internal)" ;;
*) bad "onion HTTPS vhost uses tls internal" "no 'tls internal' on the https onion site" ;;
esac
-assert_contains "onion HTTPS vhost carries the same basic_auth (#343)" "$https_site" "basic_auth"
+assert_contains "onion HTTPS vhost carries the same counted basic check (#343)" "$https_site" "uri /api/auth/basic"
# Not yet provisioned (placeholder address) -> HTTP onion vhost only, no HTTPS one (a later apply adds it).
# shellcheck disable=SC1090 # STACK path is dynamic by design
caddy_onion_ph="$(
diff --git a/tests/stack/dashboard/test-dashboard.sh b/tests/stack/dashboard/test-dashboard.sh
index 57b90851d8..19211b2cfc 100644
--- a/tests/stack/dashboard/test-dashboard.sh
+++ b/tests/stack/dashboard/test-dashboard.sh
@@ -138,8 +138,7 @@ assert_contains "the LAN address is still published" "$caddy_default" "192.168.1
assert_contains "the ULA is still published — private scope, not routable" "$caddy_default" "fd00::1"
assert_contains "a bind line closes the wildcard listener" "$caddy_default" " bind "
assert_contains "bind keeps loopback for the host-networked dashboard" "$caddy_default" "127.0.0.1 ::1"
-# The bind line is the boundary — it specifically must not carry the global address.
-bindline=$(printf '%s' "$caddy_default" | grep '^ bind ')
+bindline=$(printf '%s' "$caddy_default" | grep '^ bind ' | grep -vx ' bind 127.0.0.1')
case "$bindline" in
*2001:db8:*) bad "the bind line excludes the global v6" "global address present in: $bindline" ;;
*) ok "the bind line excludes the global v6" ;;
@@ -156,16 +155,10 @@ esac
# shellcheck disable=SC1090 # STACK path is dynamic by design
caddy_optin="$(_caddy_appliance true)"
assert_contains "the opt-in publishes the global v6 again" "$caddy_optin" "2001:db8::1"
-case "$caddy_optin" in
-*" bind "*) bad "the opt-in leaves the listener open" "a bind line was still emitted" ;;
-*) ok "the opt-in leaves the listener open" ;;
+case "$(printf '%s\n' "$caddy_optin" | grep '^ bind ' | grep -vx ' bind 127.0.0.1')" in
+"") ok "the opt-in leaves the listener open" ;;
+*) bad "the opt-in leaves the listener open" "a bind line was still emitted" ;;
esac
-# An operator who PINS dashboard.host is the most deliberately-configured box there is, and the
-# first cut of this fix left exactly those boxes wide open: the bind was derived from the
-# auto-expanded site list, so pinning the host produced a single-host site list and NO bind — the
-# wildcard listener, and the whole exposure, back again. The bind is built from the BOX's
-# addresses now, never from the site list, because they answer different questions: which Host
-# values Caddy matches, versus which sockets it opens.
# shellcheck disable=SC1090 # STACK path is dynamic by design
caddy_pinned="$(
# shellcheck disable=SC1090
@@ -233,7 +226,7 @@ caddy_onion="$(
cat Caddyfile
)"
assert_eq "insecure+onion: both vhosts bind, never one wildcard and one specific" \
- "$(printf '%s' "$caddy_onion" | grep -c '^ bind ')" "3"
+ "$(printf '%s' "$caddy_onion" | grep -c '^ bind ')" "4"
_site_count() { printf '%s' "$1" | grep -cE '^[^[:space:]{].*\{[[:space:]]*$'; }
_bind_count() { printf '%s' "$1" | grep -c '^ bind '; }
@@ -253,8 +246,8 @@ caddy_onion_https="$(
generate_caddyfile >/dev/null 2>&1
cat Caddyfile
)"
-assert_eq "secure+onion+provisioned: the HTTPS onion vhost renders (7 site blocks)" \
- "$(_site_count "$caddy_onion_https")" "7"
+assert_eq "secure+onion+provisioned: the HTTPS onion vhost renders (8 site blocks)" \
+ "$(_site_count "$caddy_onion_https")" "8"
assert_eq "secure+onion+provisioned: every site block binds — no unbound wildcard on :443" \
"$(_bind_count "$caddy_onion_https")" "$(_site_count "$caddy_onion_https")"
@@ -282,8 +275,8 @@ caddy_onion_https_diy="$(
generate_caddyfile >/dev/null 2>&1
cat Caddyfile
)"
-assert_eq "DIY secure+onion+provisioned: only the loopback verifier binds" \
- "$(_bind_count "$caddy_onion_https_diy")" "1"
+assert_eq "DIY secure+onion+provisioned: only the loopback verifier and health site bind" \
+ "$(_bind_count "$caddy_onion_https_diy")" "2"
_dupe_sites() {
printf '%s' "$1" | grep -E '^[^[:space:]{].*\{[[:space:]]*$' |
@@ -326,8 +319,8 @@ caddy_onion_off="$(
generate_caddyfile >/dev/null 2>&1
cat Caddyfile
)"
-assert_eq "DIY insecure+onion: neither vhost binds — only the loopback verifier does" \
- "$(printf '%s' "$caddy_onion_off" | grep -c '^ bind ')" "1"
+assert_eq "DIY insecure+onion: neither vhost binds — only the loopback verifier and health site do" \
+ "$(printf '%s' "$caddy_onion_off" | grep -c '^ bind ')" "2"
unset -f _caddy_appliance
unset -f _site_count _bind_count
unset -f _dupe_sites
diff --git a/tests/stack/doctor/test-doctor-appliance.sh b/tests/stack/doctor/test-doctor-appliance.sh
index 1d17144056..d1d0a642b8 100644
--- a/tests/stack/doctor/test-doctor-appliance.sh
+++ b/tests/stack/doctor/test-doctor-appliance.sh
@@ -82,16 +82,9 @@ assert_contains "bundle .env redacts token keys" "$(cat "$DJ/sb-extract/bundle/e
assert_eq "no raw secret value anywhere in the bundle" "$(grep -rc "ORIGINALTOKEN" "$DJ/sb-extract" | grep -vc ":0")" "0"
echo "== unit: check_data_wipe_note — doctor surfaces the wipe note, a support conversation gets the fact (#1121) =="
-# Same shape as the pre-seeding block: PITHEAD_PRESEED_DIR stands in for the ESP. Appliance-only
-# (the note only ever exists on that channel), so PITHEAD_APPLIANCE has to be forced on here —
-# tests run off the appliance.
mk_tmpdir CDW
mkdir -p "$CDW/esp"
export PITHEAD_PRESEED_DIR="$CDW/esp"
-# Stands in for /run (tmpfs): data_wipe_note()'s one-shot cache has to live in a file, never a
-# shell variable, because every caller reads it through `$(...)` command substitution, which
-# forks a subshell (#1208 job 557/560 — a variable-based cache never worked, since a subshell's
-# writes to it vanish when the subshell exits).
export PITHEAD_DATA_WIPE_NOTE_CACHE="$CDW/wipe-note-cache.json"
out=$(PITHEAD_APPLIANCE=0 run_sourced "$SANDBOX" check_data_wipe_note 2>&1)
@@ -122,7 +115,6 @@ assert_eq "the .pending marker itself stays consumed (never re-armed by a re-run
assert_contains "the underlying wipe log is untouched — only the marker was consumed" \
"$(cat "$CDW/esp/pithead-data-wiped")" "2026-08-21T09:00:00Z"
-# A LATER boot (cache cleared, marker already consumed on disk) is what finally ends it.
rm -f "$PITHEAD_DATA_WIPE_NOTE_CACHE"
out=$(PITHEAD_APPLIANCE=1 run_sourced "$SANDBOX" check_data_wipe_note 2>&1)
assert_eq "a later boot -> silent, never a stale re-WARN (#1208)" "$out" ""
@@ -137,6 +129,14 @@ rm -f "$PITHEAD_DATA_WIPE_NOTE_CACHE"
out=$(PITHEAD_APPLIANCE=1 run_sourced "$SANDBOX" check_data_wipe_note 2>&1)
assert_eq "a factory-reset info line is one-shot too (later boot -> silent)" "$out" ""
+out=$(PITHEAD_APPLIANCE=1 run_sourced "$SANDBOX" check_reset_requested 2>&1)
+assert_eq "no factory reset requested -> doctor says nothing" "$out" ""
+: >"$CDW/esp/pithead-reset"
+out=$(PITHEAD_APPLIANCE=1 run_sourced "$SANDBOX" check_reset_requested 2>&1)
+assert_contains "a factory reset still requested -> WARN" "$out" "WARN"
+assert_contains "the WARN says the next boot erases /data" "$out" "the next boot erases /data"
+out=$(PITHEAD_APPLIANCE=0 run_sourced "$SANDBOX" check_reset_requested 2>&1)
+assert_eq "off the appliance -> silent even with a factory reset requested" "$out" ""
unset PITHEAD_PRESEED_DIR PITHEAD_DATA_WIPE_NOTE_CACHE
rm -rf "$CDW"
unset CDW out
diff --git a/tests/stack/doctor/test-doctor-exposure.sh b/tests/stack/doctor/test-doctor-exposure.sh
index 74ae227abc..2898e19007 100644
--- a/tests/stack/doctor/test-doctor-exposure.sh
+++ b/tests/stack/doctor/test-doctor-exposure.sh
@@ -140,3 +140,50 @@ chmod +x "$DRBIN/curl"
_xp_out=$(PITHEAD_APPLIANCE=0 RUNNING_CONTAINERS=tor PATH="$DRBIN:$PATH" run_sourced "$_xp_env" check_tor_clearnet_egress 2>&1)
assert_contains "Tor egress hint names control prerequisite" "$_xp_out" "dashboard.control.enabled:true"
assert_contains "Tor egress hint names login prerequisite" "$_xp_out" "dashboard login"
+
+echo "== unit: doctor checks the stratum TLS key pair on the host =="
+_xp_tlsd="$_xp_env/proxy-tls"
+mkdir -p "$_xp_tlsd"
+_xp_tls_row() {
+ printf 'PROXY_STRATUM_TLS=%s\nPROXY_TLS_DIR=%s\n' "$1" "$_xp_tlsd" >"$_xp_env/.env"
+ PITHEAD_APPLIANCE="${2:-0}" run_sourced "$_xp_env" check_stratum_tls_keypair 2>&1
+}
+assert_eq "stratum TLS off with no key pair: doctor row is silent" "$(_xp_tls_row false)" ""
+_xp_out=$(_xp_tls_row true)
+assert_contains "stratum TLS on with no key pair: FAIL" "$_xp_out" "✗ FAIL"
+assert_contains "stratum TLS on with no key pair: names both files" "$_xp_out" "missing: cert.pem and key.pem"
+assert_contains "stratum TLS on with no key pair: names apply" "$_xp_out" "./pithead apply"
+_xp_out=$(_xp_tls_row true 1)
+assert_contains "stratum TLS on with no key pair, appliance: FAIL" "$_xp_out" "✗ FAIL"
+assert_contains "stratum TLS on with no key pair, appliance: names Configuration" "$_xp_out" "Open Configuration"
+assert_not_contains "stratum TLS on with no key pair, appliance: no console command" "$_xp_out" "./pithead apply"
+printf 'key' >"$_xp_tlsd/key.pem"
+_xp_out=$(_xp_tls_row true)
+assert_contains "stratum TLS on with only the key: names the cert" "$_xp_out" "missing: cert.pem"
+assert_not_contains "stratum TLS on with only the key: key is not named" "$_xp_out" "key.pem"
+assert_contains "stratum TLS on with only the key: FAIL" "$_xp_out" "✗ FAIL"
+printf 'cert' >"$_xp_tlsd/cert.pem"
+_xp_out=$(_xp_tls_row true)
+assert_contains "stratum TLS on with the key pair: OK" "$_xp_out" "✓ OK Stratum TLS key pair is present."
+assert_not_contains "stratum TLS on with the key pair: no FAIL" "$_xp_out" "FAIL"
+rm -f "$_xp_tlsd/key.pem"
+_xp_out=$(_xp_tls_row true)
+assert_contains "stratum TLS on with only the cert: names the key" "$_xp_out" "missing: key.pem"
+assert_not_contains "stratum TLS on with only the cert: cert is not named" "$_xp_out" "cert.pem"
+assert_contains "stratum TLS on with only the cert: FAIL" "$_xp_out" "✗ FAIL"
+assert_eq "stratum TLS off with only the cert: doctor row is silent" "$(_xp_tls_row false)" ""
+mkdir -p "$_xp_env/data/proxy-tls"
+printf 'cert' >"$_xp_env/data/proxy-tls/cert.pem"
+printf 'key' >"$_xp_env/data/proxy-tls/key.pem"
+printf 'PROXY_STRATUM_TLS=true\n' >"$_xp_env/.env"
+assert_contains "stratum TLS on with no folder setting: the default folder is checked" \
+ "$(PITHEAD_APPLIANCE=0 run_sourced "$_xp_env" check_stratum_tls_keypair 2>&1)" "✓ OK Stratum TLS key pair is present."
+_xp_doc="$SANDBOX/doctor-stratum-tls-bb"
+mkdir -p "$_xp_doc/bin"
+cp "$STACK" "$_xp_doc/pithead"
+printf '#!/usr/bin/env bash\ncase "$*" in info) exit 1 ;; *) exit 0 ;; esac\n' >"$_xp_doc/bin/docker"
+printf '#!/usr/bin/env bash\nexit 0\n' >"$_xp_doc/bin/sudo"
+chmod +x "$_xp_doc/bin/docker" "$_xp_doc/bin/sudo"
+printf 'PROXY_STRATUM_TLS=true\nPROXY_TLS_DIR=%s\n' "$_xp_tlsd" >"$_xp_doc/.env"
+_xp_out=$(cd "$_xp_doc" && PITHEAD_APPLIANCE=0 PATH="$_xp_doc/bin:$PATH" ./pithead doctor 2>&1)
+assert_contains "doctor runs the stratum TLS key pair row" "$_xp_out" "missing: key.pem"
diff --git a/tests/stack/doctor/test-doctor.sh b/tests/stack/doctor/test-doctor.sh
index 9d5ba10184..435b7f2d72 100644
--- a/tests/stack/doctor/test-doctor.sh
+++ b/tests/stack/doctor/test-doctor.sh
@@ -448,3 +448,16 @@ assert_contains "doctor runs to the summary" "$out" "Diagnostics summary"
assert_contains "doctor flags the unreachable daemon" "$out" "Docker daemon is not reachable"
assert_rc "doctor exits 1 on a critical FAIL" "$rc" "1"
assert_contains "doctor header carries the version (#386)" "$out" "Version: pithead v9.9.9"
+cat >"$DOC/bin/docker" <<'EOF'
+#!/usr/bin/env bash
+case "$*" in
+ "version --format {{.Server.Version}}") echo "$FAKE_ENGINE_VERSION" ;;
+ *) exit 0 ;;
+esac
+EOF
+out="$(cd "$DOC" && FAKE_ENGINE_VERSION=27.5.1 PATH="$DOC/bin:$PATH" ./pithead doctor 2>&1)"
+assert_contains "doctor warns on a Docker Engine older than 28" "$out" "Docker Engine 27.5.1 is older than 28"
+out="$(cd "$DOC" && FAKE_ENGINE_VERSION=28.0.4 PATH="$DOC/bin:$PATH" ./pithead doctor 2>&1)"
+assert_not_contains "doctor accepts Docker Engine 28" "$out" "is older than 28"
+out="$(cd "$DOC" && FAKE_ENGINE_VERSION='' PATH="$DOC/bin:$PATH" ./pithead doctor 2>&1)"
+assert_not_contains "an unreadable engine version is not called old" "$out" "is older than 28"
diff --git a/tests/stack/firewall/choice-startup.sh b/tests/stack/firewall/choice-startup.sh
index 878aed6630..bb5b58a15d 100644
--- a/tests/stack/firewall/choice-startup.sh
+++ b/tests/stack/firewall/choice-startup.sh
@@ -42,7 +42,10 @@ assert_eq "failed refresh removes only the disabled XvB boot marker" "$([ -d "$L
lg 'apply_lan_guard() { :; }; tor_egress_choice_active() { return 1; }; tor_egress_sync_ips() { :; }; apply_tor_egress_firewall() { :; }; compose_up -d' >/dev/null
: >"$LG_ORDER"
lg 'apply_lan_guard() { echo lan >>"$LG_ORDER"; }; tor_egress_sync_ips() { :; }; apply_tor_egress_firewall() { echo "egress:$1" >>"$LG_ORDER"; return 1; }; compose_up -d' >/dev/null
-assert_eq "ordinary startup keeps its warning-only firewall behavior" "$(cat "$LG_ORDER")" $'lan\negress:refresh\ncompose'
+assert_eq "ordinary startup refuses when the egress rules cannot be installed" "$(cat "$LG_ORDER")" $'lan\negress:refresh'
+: >"$LG_ORDER"
+lg 'apply_lan_guard() { echo lan >>"$LG_ORDER"; }; env_get() { [ "$1" != TOR_EGRESS_FIREWALL ] || echo false; }; tor_egress_sync_ips() { :; }; apply_tor_egress_firewall() { echo "egress:$1" >>"$LG_ORDER"; return 1; }; compose_up -d' >/dev/null
+assert_eq "firewall opt-out still starts when the refresh fails" "$(tail -n 2 "$LG_ORDER")" $'egress:refresh\ncompose'
lg_real 'env_get() { case "$1" in DONATION_ENABLED) echo true ;; DONATION_TOR_ENABLED) echo false ;; esac; }; tor_egress_sync_ips() { echo 172.28.0.29; }; apply_tor_egress_iptables() { :; }; apply_tor_egress_firewall refresh' >/dev/null
assert_eq "donation alone arms the choice marker" "$([ -d "$LGD/.pithead.lock.egress-choice-active" ] && echo yes)" yes
assert_eq "donation has its own boot-time choice marker" "$([ -d "$LGD/.pithead.lock.egress-choice-active/donation" ] && echo yes)" yes
diff --git a/tests/stack/firewall/egress-run-pending.sh b/tests/stack/firewall/egress-run-pending.sh
new file mode 100644
index 0000000000..a6501cefae
--- /dev/null
+++ b/tests/stack/firewall/egress-run-pending.sh
@@ -0,0 +1,57 @@
+# shellcheck shell=bash
+echo "== egress-run-pending claims every requests entry before it reads one =="
+ERP=$(mktemp -d "$SANDBOX/egress-run.XXXXXX")
+ERP_REQ="$ERP/data/control/requests"
+ERP_ID=00000000-0000-4000-8000-0000000000e1
+ERP_DIR_ID=00000000-0000-4000-8000-0000000000e2
+ERP_LINK_ID=00000000-0000-4000-8000-0000000000e3
+ERP_OLD_ID=00000000-0000-4000-8000-0000000000e4
+mkdir -p "$ERP_REQ" "$ERP/outside/dir" "$ERP_REQ/empty.json" "$ERP_REQ/full.json" "$ERP_REQ/$ERP_DIR_ID.json" "$ERP_REQ/line"$'\n'"break.json"
+printf 'keep\n' >"$ERP/outside/file.txt"
+printf 'keep\n' >"$ERP/outside/dir/inner.txt"
+chmod 640 "$ERP/outside/file.txt"
+chmod 750 "$ERP/outside/dir"
+printf 'x\n' >"$ERP_REQ/full.json/x"
+printf 'x\n' >"$ERP_REQ/$ERP_DIR_ID.json/x"
+printf 'x\n' >"$ERP_REQ/name.json"
+ln -s "$ERP/missing" "$ERP_REQ/dangling.json"
+ln -s "$ERP/outside/file.txt" "$ERP_REQ/to-file.json"
+ln -s "$ERP/outside/dir" "$ERP_REQ/to-dir.json"
+ln -s "$ERP/outside/dir" "$ERP_REQ/$ERP_LINK_ID.json"
+printf '{"id":"%s","action":"egress-sync","chain":"monero"}\n' "$ERP_ID" >"$ERP_REQ/$ERP_ID.json"
+mkdir -p "$ERP/data/control/.claim.egress.$ERP_OLD_ID" "$ERP/data/control/.claim.egress.$$"
+printf 'x\n' >"$ERP/data/control/.claim.egress.$ERP_OLD_ID/x"
+printf 'x\n' >"$ERP/data/control/.claim.egress.$$/x"
+printf '{"id":"%s","action":"egress-sync","chain":"monero"}\n' "$ERP_OLD_ID" >"$ERP_REQ/$ERP_OLD_ID.json"
+ERP_RC=$(
+ cd "$ERP" || exit
+ # shellcheck disable=SC1090
+ source "$STACK"
+ set +e
+ egress_sync_refresh() { [ "$1" = monero ]; }
+ egress_sync_run_pending
+ printf 'first=%s ' "$?"
+ egress_sync_run_pending
+ printf 'empty=%s ' "$?"
+ mv data/control/requests data/control/gone
+ egress_sync_run_pending
+ printf 'missing=%s' "$?"
+ mv data/control/gone data/control/requests
+)
+erp_gone() { if [ -e "$ERP_REQ/$2" ] || [ -L "$ERP_REQ/$2" ]; then bad "$1" "still present"; else ok "$1"; fi; }
+erp_gone "an empty folder with a non-UUID name is removed" empty.json
+erp_gone "a non-empty folder with a non-UUID name is removed" full.json
+erp_gone "a folder with a line break in its name is removed" "line"$'\n'"break.json"
+erp_gone "a dangling link is removed" dangling.json
+erp_gone "a link to a file is removed" to-file.json
+erp_gone "a link to a folder is removed" to-dir.json
+erp_gone "a regular file with a non-UUID name is removed" name.json
+erp_gone "a folder with a UUID name leaves the requests folder" "$ERP_DIR_ID.json"
+erp_gone "a link with a UUID name leaves the requests folder" "$ERP_LINK_ID.json"
+assert_eq "no claim is left in the control folder" "$(find "$ERP/data/control" -maxdepth 1 -name '.claim.*' | wc -l | tr -d ' ')" "0"
+assert_eq "the valid request beside them is applied" "$(jq -r .status "$ERP/data/control/results/$ERP_ID.json")" "applied"
+assert_eq "a request whose claim name held an older folder is applied" "$(jq -r .status "$ERP/data/control/results/$ERP_OLD_ID.json")" "applied"
+assert_eq "no result is written for the other entries" "$(find "$ERP/data/control/results" -type f | wc -l | tr -d ' ')" "2"
+assert_eq "a linked file keeps its content and mode" "$(cat "$ERP/outside/file.txt") $(stat -c %a "$ERP/outside/file.txt")" "keep 640"
+assert_eq "a linked folder keeps its file and mode" "$(cat "$ERP/outside/dir/inner.txt") $(stat -c %a "$ERP/outside/dir")" "keep 750"
+assert_eq "return codes stay the same for a run, an empty and a missing requests folder" "$ERP_RC" "first=0 empty=0 missing=1"
diff --git a/tests/stack/firewall/lan-guard-teardown.sh b/tests/stack/firewall/lan-guard-teardown.sh
index a18798dc54..21a2b25041 100644
--- a/tests/stack/firewall/lan-guard-teardown.sh
+++ b/tests/stack/firewall/lan-guard-teardown.sh
@@ -93,6 +93,7 @@ assert_eq "...before removing the rule or the config" "$(lg_rule_removed) $(test
unset LG_IPT_LOG
echo "== reset and uninstall remove the Tor-only egress rules only after a stop that worked =="
+export PITHEAD_RESET_DOWN_RETRY_S=0
cp "$LGD/.env" "$LGD/.env.egress"
lg_egress() {
cp "$LGD/.env.egress" "$LGD/.env"
@@ -101,7 +102,7 @@ lg_egress() {
}
lg_ev() { tr '\n' ' ' <"$LGD/egress-ev"; }
lg_out="$(lg_egress 1 'config_reset -y')"
-assert_eq "config-reset whose stop fails, with no stack container active, removes the egress rules" "$(lg_ev "$lg_out")" "ev:down ev:egress-off "
+assert_eq "config-reset whose stop fails, with no stack container active, removes the egress rules" "$(lg_ev "$lg_out")" "ev:down ev:down ev:down ev:egress-off "
assert_contains "...and still warns that the shutdown failed" "$lg_out" "Stack shutdown failed"
assert_contains "...and still clears the config" "$lg_out" "Configuration cleared"
assert_eq "...(.env gone)" "$(test -e "$LGD/.env" || echo absent)" "absent"
@@ -221,7 +222,7 @@ assert_eq "a restarting stack container counts as active" "$(lg_ev "$lg_out")" "
lg_out="$(LG_CENSUS="running c1" LG_CENSUS_LABEL="project=lan-guard --filter label=com.docker.compose.project.working_dir=$LGD" lg_egress 0 'config_reset -y')"
assert_eq "a running container of this folder's legacy project counts as active" "$(lg_ev "$lg_out")" "ev:down ev:rm "
lg_out="$(LG_CENSUS="running c1" lg_egress 1 'config_reset -y')"
-assert_eq "config-reset whose stop fails with a stack container running keeps the egress rules" "$(lg_ev "$lg_out")" "ev:down "
+assert_eq "config-reset whose stop fails with a stack container running keeps the egress rules" "$(lg_ev "$lg_out")" "ev:down ev:down ev:down "
assert_contains "...warns that the shutdown failed" "$lg_out" "Stack shutdown failed"
assert_contains "...and about the rules" "$lg_out" "Tor-only egress rules stay"
LG_LIVE=1 lg apply_lan_guard >/dev/null
diff --git a/tests/stack/firewall/lan-guard.sh b/tests/stack/firewall/lan-guard.sh
index 7503315235..fa29dc6c98 100644
--- a/tests/stack/firewall/lan-guard.sh
+++ b/tests/stack/firewall/lan-guard.sh
@@ -156,11 +156,11 @@ printf 'TARI_GRPC_BIND=0.0.0.0\nMONERO_RPC_BIND=127.0.0.1\nMONERO_ZMQ_BIND=127.0
printf 'boot-1\n' >"$LGD/boot_id"
lg() {
rm -f "$LG_STOPPED_FILE"
- (cd "$LGD" && PITHEAD_APPLIANCE="${LG_APPLIANCE:-0}" PITHEAD_UNIT_DIR="$LGD/units" PITHEAD_BOOT_ID_FILE="$LGD/boot_id" PATH="$LGD/bin:$PATH" bash -c "source '$STACK'; apply_tor_egress_firewall() { :; }; $1" 2>&1)
+ (cd "$LGD" && PITHEAD_APPLIANCE="${LG_APPLIANCE:-0}" PITHEAD_UNIT_DIR="$LGD/units" PITHEAD_BOOT_ID_FILE="$LGD/boot_id" PATH="$LGD/bin:$PATH" bash -c "source '$STACK'; SYSTEM_BIN_DIRS=(\"\${LG_SYSTEM_BIN:-$LGD/bin}\"); apply_tor_egress_firewall() { :; }; $1" 2>&1)
}
lg_real() {
rm -f "$LG_STOPPED_FILE"
- (cd "$LGD" && PITHEAD_APPLIANCE="${LG_APPLIANCE:-0}" PITHEAD_UNIT_DIR="$LGD/units" PITHEAD_BOOT_ID_FILE="$LGD/boot_id" PATH="$LGD/bin:$PATH" bash -c "source '$STACK'; $1" 2>&1)
+ (cd "$LGD" && PITHEAD_APPLIANCE="${LG_APPLIANCE:-0}" PITHEAD_UNIT_DIR="$LGD/units" PITHEAD_BOOT_ID_FILE="$LGD/boot_id" PATH="$LGD/bin:$PATH" bash -c "source '$STACK'; SYSTEM_BIN_DIRS=(\"\${LG_SYSTEM_BIN:-$LGD/bin}\"); $1" 2>&1)
}
LG_UNIT="$LGD/units/pithead-lan-guard.service"
LG_HOLD="$LGD/units/pithead-lan-hold.service"
@@ -300,6 +300,11 @@ assert_contains "...and enables it for the next boot" "$(cat "$LG_SYSTEMCTL")" "
assert_not_contains "...without starting it (apply's rule is already live)" "$(cat "$LG_SYSTEMCTL")" "start pithead-lan-guard"
rm -f "$LG_SYSTEMCTL"
LG_LIVE=1 LG_ENABLED=0 lg apply_lan_guard >/dev/null
+rm -f "$LG_UNIT"
+mkdir -p "$LGD/sys"
+lg_out=$(LG_LIVE=1 LG_SYSTEM_BIN="$LGD/sys" lg apply_lan_guard)
+assert_eq "with iptables only on PATH, no LAN-guard unit is written" "$(test -e "$LG_UNIT" && echo present)" ""
+assert_contains "...and the hold is named as not enabled" "$lg_out" "boot unit that restores it after a reboot could not be installed"
assert_not_contains "a re-apply with the same unit, already enabled, does not reload systemd" "$(cat "$LG_SYSTEMCTL" 2>/dev/null)" "daemon-reload"
rm -f "$LG_UNIT"
LG_LIVE=0 lg apply_lan_guard >/dev/null
diff --git a/tests/stack/fixtures/caddy/v2.0.4-https-login.Caddyfile b/tests/stack/fixtures/caddy/v2.0.4-https-login.Caddyfile
new file mode 100644
index 0000000000..3992c5e97f
--- /dev/null
+++ b/tests/stack/fixtures/caddy/v2.0.4-https-login.Caddyfile
@@ -0,0 +1,92 @@
+{
+ auto_https disable_redirects
+}
+
+http://box.lan {
+
+ redir https://{host}{uri} 308
+}
+
+http:// {
+
+ redir https://box.lan{uri} 308
+}
+
+https:// {
+
+ redir https://box.lan{uri} 308
+}
+
+https://box.lan {
+ tls internal
+
+ log {
+ output file /var/log/caddy/access.log {
+ roll_size 4MiB
+ roll_keep 2
+ mode 0644
+ }
+ format filter {
+ wrap json
+ fields {
+ request>headers>X-Pithead-Boot-Probe delete
+ }
+ }
+ }
+ @boot_health {
+ remote_ip 127.0.0.1 ::1
+ method GET
+ expression {http.request.uri} == "/.pithead-boot-health"
+ not header Authorization *
+ header X-Pithead-Boot-Probe "cf0a708db78d1f2d269d4f0508fc9ba6153c30e7505c2062b4df30d8135d4732"
+ }
+ route {
+ log_append @boot_health "$KR/.env"
+printf 'TOR_EGRESS_FIREWALL=false\nCOMPOSE_PROFILES=local_node,local_tari,payout_confirm,tari_payout_confirm\n' >"$KR/.env"
# RUNNING_STUB lists the containers `docker ps` reports running; the service list is the stack's.
cat >"$KRBIN/docker" <<'EOF'
#!/usr/bin/env bash
diff --git a/tests/stack/lifecycle/lock-core.sh b/tests/stack/lifecycle/lock-core.sh
index 785120d4b2..a33c324a6c 100644
--- a/tests/stack/lifecycle/lock-core.sh
+++ b/tests/stack/lifecycle/lock-core.sh
@@ -10,7 +10,7 @@ echo "== unit: the mutation lock serialises mutating windows (#1342) =="
LKDIR="$SANDBOX/lock"
mkdir -p "$LKDIR"
# These fixtures exercise configured Compose mutations; configless shutdown has its own suite.
-: >"$LKDIR/.env"
+printf 'TOR_EGRESS_FIREWALL=false\n' >"$LKDIR/.env"
LKBIN="$SANDBOX/lockbin"
make_stubs "$LKBIN"
LKFILE="$LKDIR/explicit.lock"
@@ -338,7 +338,7 @@ assert_contains "the mutation it could not serialise still runs" "$(cat "$LKLOG"
LKROOT="$SANDBOX/deploy"
mkdir -p "$LKROOT/pithead-v1.0.0" "$LKROOT/pithead-v2.0.0" "$LKROOT/plain-a" "$LKROOT/plain-b"
for lk_fixture in pithead-v1.0.0 pithead-v2.0.0 plain-a plain-b; do
- : >"$LKROOT/$lk_fixture/.env"
+ printf 'TOR_EGRESS_FIREWALL=false\n' >"$LKROOT/$lk_fixture/.env"
done
unset lk_fixture
# Hold a window in one dir; drive a mutating verb from its sibling. `env -u PITHEAD_LOCK_HELD`
diff --git a/tests/stack/lifecycle/lock-wiring.sh b/tests/stack/lifecycle/lock-wiring.sh
index 5a951a734f..c8eec966e0 100644
--- a/tests/stack/lifecycle/lock-wiring.sh
+++ b/tests/stack/lifecycle/lock-wiring.sh
@@ -35,6 +35,7 @@ chmod +x "$LKW/bin/sudo"
lock_wiring_fixture() { #
mkdir -p "$1/data/tor" "$1/data/dashboard"
cat >"$1/.env" <<'ENVEOF'
+TOR_EGRESS_FIREWALL=false
MONERO_ONION_ADDRESS=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.onion
TARI_ONION_ADDRESS=bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb.onion
P2POOL_ONION_ADDRESS=cccccccccccccccccccccccccccccccccccccccccccccccccccccccc.onion
@@ -43,7 +44,7 @@ HOST_IP=box.lan
DEPLOYMENT_COMPLETED=true
COMPOSE_PROFILES=local_node
ENVEOF
- printf '{ "monero": {"mode":"local","wallet_address":"%s","node_username":"u","node_password":"p"}, "tari":{"wallet_address":"%s"}, "p2pool":{"pool":"main"}, "dashboard":{"secure":true,"host":"box.lan"} }\n' "$WALLET" "$VALID_TARI" >"$1/config.json"
+ printf '{ "network":{"tor_egress_firewall":false}, "monero": {"mode":"local","wallet_address":"%s","node_username":"u","node_password":"p"}, "tari":{"wallet_address":"%s"}, "p2pool":{"pool":"main"}, "dashboard":{"secure":true,"host":"box.lan"} }\n' "$WALLET" "$VALID_TARI" >"$1/config.json"
printf 'CADDY-ORIG\n' >"$1/Caddyfile"
printf 'ONIONKEY-ORIG\n' >"$1/data/tor/hs_ed25519_secret_key"
printf 'DBDATA-ORIG\n' >"$1/data/dashboard/dashboard.db"
diff --git a/tests/stack/lifecycle/recovery.sh b/tests/stack/lifecycle/recovery.sh
index c790c9e337..243bad7ad5 100644
--- a/tests/stack/lifecycle/recovery.sh
+++ b/tests/stack/lifecycle/recovery.sh
@@ -248,7 +248,7 @@ HOST_IP=box.lan
DEPLOYMENT_COMPLETED=true
COMPOSE_PROFILES=local_node
EOF
-printf '{ "monero": {"mode":"local","wallet_address":"%s","node_username":"u","node_password":"p"}, "tari":{"wallet_address":"'"$VALID_TARI"'"}, "p2pool":{"pool":"mini"}, "dashboard":{"secure":false,"host":"box.lan"} }\n' "$WALLET" >"$A/config.json"
+printf '{ "network":{"tor_egress_firewall":false}, "monero": {"mode":"local","wallet_address":"%s","node_username":"u","node_password":"p"}, "tari":{"wallet_address":"'"$VALID_TARI"'"}, "p2pool":{"pool":"mini"}, "dashboard":{"secure":false,"host":"box.lan"} }\n' "$WALLET" >"$A/config.json"
# First apply: real config delta committed, but `compose up` FAILS -> marker left, rc 1, guidance.
out="$(cd "$A" && DOCKER_LOG="$A/docker.log" FAIL_UP=1 PATH="$A/bin:$PATH" ./pithead apply -y 2>&1)"
rc=$?
@@ -307,7 +307,7 @@ DEPLOYMENT_COMPLETED=true
COMPOSE_PROFILES=local_node
MONERO_OUT_PEERS=48
EOF
-printf '{ "monero": {"mode":"local","wallet_address":"%s","node_username":"u","node_password":"p","out_peers":49}, "tari":{"wallet_address":"'"$VALID_TARI"'"}, "p2pool":{"pool":"mini"}, "dashboard":{"secure":false,"host":"box.lan"} }\n' "$WALLET" >"$R2/config.json"
+printf '{ "network":{"tor_egress_firewall":false}, "monero": {"mode":"local","wallet_address":"%s","node_username":"u","node_password":"p","out_peers":49}, "tari":{"wallet_address":"'"$VALID_TARI"'"}, "p2pool":{"pool":"mini"}, "dashboard":{"secure":false,"host":"box.lan"} }\n' "$WALLET" >"$R2/config.json"
RACE_CNT="$R2/race-count"
out="$(cd "$R2" && RACE_CNT_FILE="$RACE_CNT" PATH="$R2/bin:$PATH" ./pithead apply -y 2>&1)"
rc=$?
@@ -393,7 +393,7 @@ apply_noop_steps() {
apply
) | grep -xE 'provision|compose' | tr '\n' ','
}
-: >"$SANDBOX/.env"
+printf 'TOR_EGRESS_FIREWALL=false\n' >"$SANDBOX/.env"
printf '{}\n' >"$SANDBOX/config.json"
assert_eq "a no-change apply still converges the control units, and recreates nothing" \
"$(apply_noop_steps)" "provision,"
diff --git a/tests/stack/lifecycle/recreate-names.sh b/tests/stack/lifecycle/recreate-names.sh
index 0eed8a4e28..e5ce9a03f5 100644
--- a/tests/stack/lifecycle/recreate-names.sh
+++ b/tests/stack/lifecycle/recreate-names.sh
@@ -9,7 +9,7 @@ echo "== unit: an apply never ends with a service under compose's recreate name
# surplus and starts the replacement without renaming it. The stub's container list is a file.
RN="$SANDBOX/recreate-names"
mkdir -p "$RN"
-printf 'COMPOSE_PROFILES=local_node\n' >"$RN/.env"
+printf 'TOR_EGRESS_FIREWALL=false\nCOMPOSE_PROFILES=local_node\n' >"$RN/.env"
printf 'monerod\np2pool\n' >"$RN/names"
rn_out=$(
cd "$RN" || exit
@@ -47,7 +47,7 @@ echo "== unit: compose_up_checked retries once when the engine's stop API times
# answered the stop with a 500 about the exit file. The container is stopped on the second pass.
ST="$SANDBOX/stop-timeout"
mkdir -p "$ST"
-printf 'COMPOSE_PROFILES=local_node\n' >"$ST/.env"
+printf 'TOR_EGRESS_FIREWALL=false\nCOMPOSE_PROFILES=local_node\n' >"$ST/.env"
st_out=$(
cd "$ST" || exit
# shellcheck disable=SC1090
diff --git a/tests/stack/lifecycle/tari-upgrade-space.sh b/tests/stack/lifecycle/tari-upgrade-space.sh
index f7c5e20034..c302e92358 100644
--- a/tests/stack/lifecycle/tari-upgrade-space.sh
+++ b/tests/stack/lifecycle/tari-upgrade-space.sh
@@ -108,7 +108,7 @@ case "\$*" in
esac
exec "$U2/stub/docker" "\$@"
EOF
-cp "$TUS/bin/df" "$U2/stub/sudo" "$U2/bin/"
+cp "$TUS/bin/df" "$U2/stub/sudo" "$U2/stub/iptables" "$U2/stub/iptables-restore" "$U2/bin/"
chmod +x "$U2/bin/docker"
cp "$ROOT/build/tari/config.toml.template" "$U2/build/tari/"
truncate -s 100G "$U2/data/tari/mainnet/data/base_node/db/data.mdb"
diff --git a/tests/stack/run.sh b/tests/stack/run.sh
index 8dc44074f1..d7986971b0 100755
--- a/tests/stack/run.sh
+++ b/tests/stack/run.sh
@@ -17,11 +17,9 @@ if ! _audit=$(stack_blocks_audit "$HERE/run.sh" "$ROOT/.github/workflows/shell.y
printf 'run.sh: the block layout is broken (#2631):\n%s\n' "$_audit" >&2
exit 2
fi
-# The full run's tally file, handed down by the loop below. Taken and unset at once, so a fragment
-# that starts run.sh itself cannot append to it.
_tally="${STACK_TALLY:-}"
unset STACK_TALLY
-stack_verdict() { #