Compare commits
17
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4ced47941d | ||
|
|
6df8d4b332 | ||
|
|
ff535fae1f | ||
|
|
b6911fb63f | ||
|
|
24f4a5ebac | ||
|
|
5ec7d9b6d3 | ||
|
|
06e5ad0ce7 | ||
|
|
2774399add | ||
|
|
f0a737832c | ||
|
|
4cb4ad39f8 | ||
|
|
8ab6fdcef0 | ||
|
|
56404f4777 | ||
|
|
3ce1dc8662 | ||
|
|
3eee8e6023 | ||
|
|
c91187aa85 | ||
|
|
193d39e109 | ||
|
|
aebb68fe9d |
No files matched your search
@@ -133,6 +133,29 @@ jobs:
|
|||||||
PKG_CACHE=${{ steps.pkgcache.outputs.url }}
|
PKG_CACHE=${{ steps.pkgcache.outputs.url }}
|
||||||
outputs: type=image,"name=repo.anhonesthost.net/cloud-hosting-platform/haproxy-manager-base,ghcr.io/shadowdao/haproxy-manager-base",push-by-digest=true,name-canonical=true,push=true
|
outputs: type=image,"name=repo.anhonesthost.net/cloud-hosting-platform/haproxy-manager-base,ghcr.io/shadowdao/haproxy-manager-base",push-by-digest=true,name-canonical=true,push=true
|
||||||
|
|
||||||
|
# Per-platform ELF check BEFORE anything is tagged (2026-11-19: an "arm64"
|
||||||
|
# entry held x86-64 binaries). amd64 mismatch fails the job and publishes
|
||||||
|
# nothing. An arm64 mismatch (or a failed check) keeps arm64 OUT of the
|
||||||
|
# tags (amd64-only publish, as for a failed arm64 build) and the job is
|
||||||
|
# failed afterwards so it is not mistaken for a good multi-arch publish.
|
||||||
|
- name: Verify amd64 image binaries are amd64
|
||||||
|
env:
|
||||||
|
DIGEST: ${{ steps.amd64.outputs.digest }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
python3 -I scripts/verify-image-arch.py "repo.anhonesthost.net/cloud-hosting-platform/haproxy-manager-base@${DIGEST}" amd64
|
||||||
|
|
||||||
|
- name: Verify arm64 image binaries are arm64
|
||||||
|
id: arm64check
|
||||||
|
if: steps.arm64.outcome == 'success'
|
||||||
|
continue-on-error: true
|
||||||
|
timeout-minutes: 10
|
||||||
|
env:
|
||||||
|
DIGEST: ${{ steps.arm64.outputs.digest }}
|
||||||
|
run: |
|
||||||
|
set -euo pipefail
|
||||||
|
python3 -I scripts/verify-image-arch.py "repo.anhonesthost.net/cloud-hosting-platform/haproxy-manager-base@${DIGEST}" arm64
|
||||||
|
|
||||||
# imagetools needs a NEW buildx. Same pinned, sha256-verified binary as
|
# imagetools needs a NEW buildx. Same pinned, sha256-verified binary as
|
||||||
# mirror-base-image.yaml (kept identical on purpose). The assemble step
|
# mirror-base-image.yaml (kept identical on purpose). The assemble step
|
||||||
# previously ran on whatever buildx the (possibly ephemeral) runner had
|
# previously ran on whatever buildx the (possibly ephemeral) runner had
|
||||||
@@ -163,7 +186,8 @@ jobs:
|
|||||||
BUILDKIT_PROGRESS: plain
|
BUILDKIT_PROGRESS: plain
|
||||||
AMD64_DIGEST: ${{ steps.amd64.outputs.digest }}
|
AMD64_DIGEST: ${{ steps.amd64.outputs.digest }}
|
||||||
ARM64_DIGEST: ${{ steps.arm64.outputs.digest }}
|
ARM64_DIGEST: ${{ steps.arm64.outputs.digest }}
|
||||||
ARM64_OUTCOME: ${{ steps.arm64.outcome }}
|
# success only if the build AND the ELF check succeeded (a skipped check = not verified = not attached)
|
||||||
|
ARM64_OUTCOME: ${{ steps.arm64check.outcome == 'success' && steps.arm64.outcome || 'unverified' }}
|
||||||
VERSION: ${{ steps.ver.outputs.version }}
|
VERSION: ${{ steps.ver.outputs.version }}
|
||||||
TAGS: ${{ steps.tags.outputs.tags }}
|
TAGS: ${{ steps.tags.outputs.tags }}
|
||||||
run: |
|
run: |
|
||||||
@@ -199,26 +223,21 @@ jobs:
|
|||||||
PLATFORMS: ${{ steps.assemble.outputs.platforms }}
|
PLATFORMS: ${{ steps.assemble.outputs.platforms }}
|
||||||
run: |
|
run: |
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
repos="repo.anhonesthost.net/cloud-hosting-platform/haproxy-manager-base ghcr.io/shadowdao/haproxy-manager-base"
|
# Version-independent digest logic lives in the script (tested by
|
||||||
want=$(printf '%s' "$PLATFORMS" | tr ',' '\n' | sort | tr '\n' ' ')
|
# scripts/test-verify-published-tags.py); buildx 0.28 ignores --format.
|
||||||
ref_digest=""; ref_name=""; fail=0
|
export IMAGETOOLS="${BUILDX} imagetools"
|
||||||
for r in $repos; do
|
tag_args=()
|
||||||
for t in $TAGS; do
|
for t in $TAGS; do tag_args+=(--tag "$t"); done
|
||||||
ref="${r}:${t}"
|
scripts/verify-published-tags.sh \
|
||||||
if ! d=$(timeout 90 $BUILDX imagetools inspect "$ref" --format '{{.Manifest.Digest}}' 2>&1); then
|
--platforms "$PLATFORMS" \
|
||||||
echo "::error::MISSING or unreadable: ${ref}: ${d}"; fail=1; continue
|
--repo repo.anhonesthost.net/cloud-hosting-platform/haproxy-manager-base \
|
||||||
fi
|
--repo ghcr.io/shadowdao/haproxy-manager-base \
|
||||||
[[ "$d" =~ ^sha256:[0-9a-f]{64}$ ]] || { echo "::error::bad digest for ${ref}: ${d}"; fail=1; continue; }
|
"${tag_args[@]}"
|
||||||
got=$(timeout 90 $BUILDX imagetools inspect "$ref" --format '{{range .Manifest.Manifests}}{{if ne .Platform.OS "unknown"}}{{.Platform.OS}}/{{.Platform.Architecture}}{{"\n"}}{{end}}{{end}}' | sort | tr '\n' ' ')
|
|
||||||
if [ "$got" != "$want" ]; then
|
# Tags are already published (amd64-only) if arm64 failed verification; fail
|
||||||
echo "::error::platform mismatch for ${ref}: have [${got}] want [${want}]"; fail=1
|
# the job so that is visible instead of reading as a green multi-arch publish.
|
||||||
fi
|
- name: Fail if arm64 was built but its binaries are not arm64
|
||||||
echo "ok ${ref} ${d} [${got}]"
|
if: always() && steps.arm64.outcome == 'success' && steps.arm64check.outcome != 'success'
|
||||||
if [ -z "$ref_digest" ]; then ref_digest="$d"; ref_name="$ref"
|
run: |
|
||||||
elif [ "$d" != "$ref_digest" ]; then
|
echo "::error::arm64 image was built but failed the ELF architecture check; tags were published amd64-only (or not at all)"
|
||||||
echo "::error::digest mismatch: ${ref}=${d} vs ${ref_name}=${ref_digest}"; fail=1
|
exit 1
|
||||||
fi
|
|
||||||
done
|
|
||||||
done
|
|
||||||
[ "$fail" = 0 ] || { echo "::error::tag verification FAILED"; exit 1; }
|
|
||||||
echo "verified: ${TAGS} in both registries, digest ${ref_digest}, platforms ${PLATFORMS}"
|
|
||||||
@@ -14,6 +14,10 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
- **WAF body inspection**: `python3 scripts/test-waf-body-inspection.py` - offline (runs in the image build); pins `option http-buffer-request`, the `X-WHP-WAF-Body` complete/partial stamp (strip -> stamp -> SPOE -> strip), `tune.bufsize` against the 100 ms SPOE fail-open budget and the 65535-byte SPOP frame cap, and Coraza's body limits in `coraza-spoa/config.yaml`. Run it after touching the Coraza block, `tune.bufsize`, or the SPOE engine.
|
- **WAF body inspection**: `python3 scripts/test-waf-body-inspection.py` - offline (runs in the image build); pins `option http-buffer-request`, the `X-WHP-WAF-Body` complete/partial stamp (strip -> stamp -> SPOE -> strip), `tune.bufsize` against the 100 ms SPOE fail-open budget and the 65535-byte SPOP frame cap, and Coraza's body limits in `coraza-spoa/config.yaml`. Run it after touching the Coraza block, `tune.bufsize`, or the SPOE engine.
|
||||||
- **Superseded-cert retirement**: covered by the same file (`TestRetirementRules`, `TestSanOverlapRetirement`). A new bundle retires any OTHER pem/lineage sharing ANY name (CN or SAN) with it - the pem moved to `cert-retired/`, the lineage's live+archive+renewal moved TOGETHER to `/etc/letsencrypt/retired/<stamp>/` (leaving archive/ behind makes certbot refuse the name forever), never deleted; the bundle's own `--cert-name` lineage is `live/<primary>` exactly and is never retired - unless that cert is still the only valid one for a name this edge serves (`retirement_blockers()`). `GET /api/capabilities` advertises this to WHP, which must not use whole-site re-bundling without it. Expired pems already in the crt dir are moved to `cert-retired/` by `cert_retire_expired_pems` (never the last pem, never `default_self_signed_cert.pem`). Expired lineages are never published (`cert_is_expired` in `cert-publish-lib.sh`, `leaf_is_expired()` in Python). Fixtures: `scripts/test-fixtures/san-certs/`.
|
- **Superseded-cert retirement**: covered by the same file (`TestRetirementRules`, `TestSanOverlapRetirement`). A new bundle retires any OTHER pem/lineage sharing ANY name (CN or SAN) with it - the pem moved to `cert-retired/`, the lineage's live+archive+renewal moved TOGETHER to `/etc/letsencrypt/retired/<stamp>/` (leaving archive/ behind makes certbot refuse the name forever), never deleted; the bundle's own `--cert-name` lineage is `live/<primary>` exactly and is never retired - unless that cert is still the only valid one for a name this edge serves (`retirement_blockers()`). `GET /api/capabilities` advertises this to WHP, which must not use whole-site re-bundling without it. Expired pems already in the crt dir are moved to `cert-retired/` by `cert_retire_expired_pems` (never the last pem, never `default_self_signed_cert.pem`). Expired lineages are never published (`cert_is_expired` in `cert-publish-lib.sh`, `leaf_is_expired()` in Python). Fixtures: `scripts/test-fixtures/san-certs/`.
|
||||||
- **Multi-arch index assembly (coraza-spoa)**: `python3 scripts/test-assemble-multiarch-index.py` - offline (NOT run in the image build; it also reads `.gitea/workflows/build-push-coraza.yaml`); `scripts/assemble-multiarch-index.sh` turns the by-digest amd64 + arm64 pushes into the tag(s): arm64 is attached only if THIS run's arm64 step outcome is `success` (failure => amd64-only tag, never a stale arm64), a bad amd64 digest publishes nothing. `scripts/e2e-coraza-multiarch.sh` rehearses the whole thing against throwaway local registries (see coraza-spoa/README.md "Multi-arch").
|
- **Multi-arch index assembly (coraza-spoa)**: `python3 scripts/test-assemble-multiarch-index.py` - offline (NOT run in the image build; it also reads `.gitea/workflows/build-push-coraza.yaml`); `scripts/assemble-multiarch-index.sh` turns the by-digest amd64 + arm64 pushes into the tag(s): arm64 is attached only if THIS run's arm64 step outcome is `success` (failure => amd64-only tag, never a stale arm64), a bad amd64 digest publishes nothing. `scripts/e2e-coraza-multiarch.sh` rehearses the whole thing against throwaway local registries (see coraza-spoa/README.md "Multi-arch").
|
||||||
|
- **Publish verify gate**: `python3 scripts/test-verify-published-tags.py` - offline (needs `jq`; NOT run in the image build); `scripts/verify-published-tags.sh` is the last build-push.yaml step: every tag in every registry must resolve, carry the assembled platforms, and share ONE index digest. The digest is the sha256 of `imagetools inspect --raw` cross-checked against the text `Digest:` line / bare `--format` output (buildx 0.28 ignores `--format` and prints full text; CI run 5381).
|
||||||
|
- **Supervisor fast relaunch**: `python3 scripts/test-haproxy-supervisor-relaunch.py` - runs in the image build; needs a real `haproxy` (skips without one). Starts a real master, runs the real `haproxy-supervisor.sh`, SIGABRTs the worker and asserts a new master is serving < 3 s after the old one exits, started from bash (python stub never ran), marker present during and gone after, no second master, invalid config -> python fallback. `scripts/test-haproxy-supervisor.py` (stubs, ~60 s) covers the fast/fallback/idempotency logic. Run both after touching `haproxy-supervisor.sh`.
|
||||||
|
- **Per-host thread count knob**: `python3 scripts/test-nbthread-knob.py` - runs in the image build; `HAPROXY_NBTHREAD` (container env, 1-64; invalid/unset = ignored) renders `nbthread N` in `global` ONLY when set, so every other host's config is byte-identical. Real `haproxy -c` of `nbthread 1` is the `nbthread-1` scenario in `scripts/validate-rendered-config.py`. WHP side: `/etc/whp/edge-nbthread` -> `lib-edge-container.sh` -> `docker run -e` at recreate.
|
||||||
|
- **Health-check timing**: `python3 scripts/test-health-check-timing.py` - runs in the image build; one `default-server inter 30s fastinter 10s downinter 30s rise 2 fall 3` in `defaults` + `spread-checks 50` in `global` (hap_header.tpl), never per server line; the Coraza SPOA server keeps `inter 2s`. Pins that a dead backend is still detected in <= 2 min and that `fastinter` (which sizes the post-reload start-up stagger window) stays >= 5s. Real `haproxy -c` coverage: the `check-timing`/`spread-checks` assertions in `scripts/validate-rendered-config.py`.
|
||||||
- **Default splash**: `python3 scripts/test-default-splash.py` - offline (runs in the image build); unrouted hosts (server hostname, bare IP, unknown names) are answered by `http-request return ... file /haproxy/errors/default-splash.html` BEFORE the Coraza SPOE call, never for a routed host (`routed_hosts.list`/`routed_wildcards.list`, written by `generate_config()` from the routing rows and in the rollback set), never for ACME/blocked/suspended. Run it after touching the splash block, the routing ACL templates, or the domain loops in `generate_config()`. See README "Default Splash".
|
- **Default splash**: `python3 scripts/test-default-splash.py` - offline (runs in the image build); unrouted hosts (server hostname, bare IP, unknown names) are answered by `http-request return ... file /haproxy/errors/default-splash.html` BEFORE the Coraza SPOE call, never for a routed host (`routed_hosts.list`/`routed_wildcards.list`, written by `generate_config()` from the routing rows and in the rollback set), never for ACME/blocked/suspended. Run it after touching the splash block, the routing ACL templates, or the domain loops in `generate_config()`. See README "Default Splash".
|
||||||
- **gunicorn access logging**: `python3 scripts/test-gunicorn-access-logging.py` - real gunicorn; :8080 has no access log, :8000 access goes to `/var/log/haproxy/api-access.log` (rotated by `scripts/gunicorn-access-rotate.py`), nothing per-request on stdout (journald rate-limit/Graylog flood), gunicorn errors stay on stderr. See docs/logging.md. Run after touching start-up.sh's gunicorn lines.
|
- **gunicorn access logging**: `python3 scripts/test-gunicorn-access-logging.py` - real gunicorn; :8080 has no access log, :8000 access goes to `/var/log/haproxy/api-access.log` (rotated by `scripts/gunicorn-access-rotate.py`), nothing per-request on stdout (journald rate-limit/Graylog flood), gunicorn errors stay on stderr. See docs/logging.md. Run after touching start-up.sh's gunicorn lines.
|
||||||
- **Access log receiver**: `python3 scripts/test-access-log-receiver.py` - offline (runs in the image build); one datagram = one line (PRI stripped, control chars neutralised), size cap + gzip generations, write errors drop without raising, real UNIX-socket path. Run it after touching `haproxy-log-receiver.py` or the `log` line in `hap_header.tpl`.
|
- **Access log receiver**: `python3 scripts/test-access-log-receiver.py` - offline (runs in the image build); one datagram = one line (PRI stripped, control chars neutralised), size cap + gzip generations, write errors drop without raising, real UNIX-socket path. Run it after touching `haproxy-log-receiver.py` or the `log` line in `hap_header.tpl`.
|
||||||
@@ -180,4 +184,4 @@ re-reads it on reload, so a failed runtime command must degrade to
|
|||||||
- gunicorn uses `haproxy_gunicorn_worker.TimeoutThreadWorker` (gthread + client socket timeout + first-byte deadline + total header deadline + wedge watchdog). Stock gthread leaves client sockets blocking with NO timeout; `--timeout` only watches the main thread's heartbeat
|
- gunicorn uses `haproxy_gunicorn_worker.TimeoutThreadWorker` (gthread + client socket timeout + first-byte deadline + total header deadline + wedge watchdog). Stock gthread leaves client sockets blocking with NO timeout; `--timeout` only watches the main thread's heartbeat
|
||||||
- Supports deployment on servers with git directory at `/root/whp` and web file sync via rsync to `/docker/whp/web/`
|
- Supports deployment on servers with git directory at `/root/whp` and web file sync via rsync to `/docker/whp/web/`
|
||||||
- HAProxy is the 3.2 LTS series from haproxy.debian.net (`trixie-backports-3.2`, native OpenSSL 3.5 QUIC); exact build in `/haproxy/HAPROXY_VERSION`. Debian trixie's 3.0.11 had the DNS-resolver watchdog abort (haproxy #3101)
|
- HAProxy is the 3.2 LTS series from haproxy.debian.net (`trixie-backports-3.2`, native OpenSSL 3.5 QUIC); exact build in `/haproxy/HAPROXY_VERSION`. Debian trixie's 3.0.11 had the DNS-resolver watchdog abort (haproxy #3101)
|
||||||
- HAProxy runs as `haproxy -W -db` (foreground master, started by `haproxy_manager.spawn_haproxy_master()`), NOT daemonised: `daemon` re-points the master's stderr at /dev/null and loses ALERTs and the ha_panic/watchdog thread dump. Its stderr is appended to `/var/log/haproxy/haproxy-stderr.log` (haproxy-logs volume) and `scripts/haproxy-stderr-relay.py` re-emits it on the container stderr (`haproxy-stderr: ` prefix). The in-container supervisor probes with `pidof` every `HAPROXY_SUPERVISOR_INTERVAL` (default 2 s) and only runs python when HAProxy is gone; Crash evidence (dump blocks opened only by the anchored `Thread N is about to kill` header, `[ALERT] (PID) :`, `Current worker (N) exited with code N`; ANCHORED patterns, so keywords echoed from URLs/Host/server names never match) bypasses the bucket within a budget (1000 lines / 10 min, 60 s cooldown after a bound closes a block) and goes to STDERR (journald PRIORITY 3); routine reload noise is collapsed into one `[relay] reload/start ok: N routine lines collapsed` line per reload and everything benign goes to STDOUT (PRIORITY 6; docker's journald driver does not parse `<N>` prefixes), with a per-minute `[relay] suppressed N lines` summary. `python3 scripts/test-haproxy-stderr-relay.py` (offline) covers the relay
|
- HAProxy runs as `haproxy -W -db` (foreground master, started by `haproxy_manager.spawn_haproxy_master()`), NOT daemonised: `daemon` re-points the master's stderr at /dev/null and loses ALERTs and the ha_panic/watchdog thread dump. Its stderr is appended to `/var/log/haproxy/haproxy-stderr.log` (haproxy-logs volume) and `scripts/haproxy-stderr-relay.py` re-emits it on the container stderr (`haproxy-stderr: ` prefix). The in-container supervisor probes with `pidof` every `HAPROXY_SUPERVISOR_INTERVAL` (default 1 s) and, when HAProxy is gone, relaunches it DIRECTLY FROM BASH against the on-disk config (`haproxy -c` then the same `haproxy -W -db -S ...` command, detached to PID 1; ~0.8 s measured on an idle host, was 16 s through python on a starved one) and falls back to `ensure_haproxy.py` only if the config is missing/invalid or the launch fails; while recovering it keeps the marker `/tmp/haproxy-restarting` (`<epoch> <pid>`, `HAPROXY_SUPERVISOR_MARKER`) so the host watchdog does not `docker restart` on top of it; Crash evidence (dump blocks opened only by the anchored `Thread N is about to kill` header, `[ALERT] (PID) :`, `Current worker (N) exited with code N`; ANCHORED patterns, so keywords echoed from URLs/Host/server names never match) bypasses the bucket within a budget (1000 lines / 10 min, 60 s cooldown after a bound closes a block) and goes to STDERR (journald PRIORITY 3); routine reload noise is collapsed into one `[relay] reload/start ok: N routine lines collapsed` line per reload and everything benign goes to STDOUT (PRIORITY 6; docker's journald driver does not parse `<N>` prefixes), with a per-minute `[relay] suppressed N lines` summary. `python3 scripts/test-haproxy-stderr-relay.py` (offline) covers the relay
|
||||||
+15
@@ -10,6 +10,17 @@
|
|||||||
# Future improvement: a scheduled Gitea Action that does the above automatically.
|
# Future improvement: a scheduled Gitea Action that does the above automatically.
|
||||||
FROM repo.anhonesthost.net/cloud-hosting-platform/python:3.12-slim
|
FROM repo.anhonesthost.net/cloud-hosting-platform/python:3.12-slim
|
||||||
|
|
||||||
|
# Base-architecture guard. If the mirrored base tag is a single-platform
|
||||||
|
# (flattened amd64) manifest instead of a multi-arch index, buildx silently uses
|
||||||
|
# that amd64 base for a linux/arm64 build, every RUN below executes natively as
|
||||||
|
# x86-64, and the result is x86-64 binaries labelled arm64 (2026-11-19:
|
||||||
|
# haproxy-manager-base:latest). TARGETARCH is set by buildx (empty on the legacy
|
||||||
|
# builder, where the check is skipped). On a correct build this is a no-op.
|
||||||
|
ARG TARGETARCH
|
||||||
|
RUN if [ -n "${TARGETARCH}" ] && [ "$(dpkg --print-architecture)" != "${TARGETARCH}" ]; then \
|
||||||
|
echo "FATAL: base image is $(dpkg --print-architecture) but this build targets ${TARGETARCH}; the in-house python:3.12-slim mirror is not a multi-arch index (re-run mirror-base-image.yaml)" >&2; exit 1; \
|
||||||
|
fi
|
||||||
|
|
||||||
# image.source is what ghcr.io uses to link the package to a GitHub repo
|
# image.source is what ghcr.io uses to link the package to a GitHub repo
|
||||||
# sidebar; pointing at the public GitHub mirror enables that linking. The
|
# sidebar; pointing at the public GitHub mirror enables that linking. The
|
||||||
# canonical source-of-truth git remote is still Gitea, but Gitea's registry
|
# canonical source-of-truth git remote is still Gitea, but Gitea's registry
|
||||||
@@ -147,12 +158,16 @@ RUN pip install -r requirements.txt
|
|||||||
# The unit suites run here too. They had never run anywhere automated either,
|
# The unit suites run here too. They had never run anywhere automated either,
|
||||||
# and they cost a few seconds.
|
# and they cost a few seconds.
|
||||||
RUN python3 /haproxy/scripts/test-wpadmin-gate.py \
|
RUN python3 /haproxy/scripts/test-wpadmin-gate.py \
|
||||||
|
&& python3 /haproxy/scripts/test-wpadmin-gate-behaviour.py \
|
||||||
&& python3 /haproxy/scripts/test-trusted-proxy-gate.py \
|
&& python3 /haproxy/scripts/test-trusted-proxy-gate.py \
|
||||||
&& python3 /haproxy/scripts/test-xmlrpc-rate-limit.py \
|
&& python3 /haproxy/scripts/test-xmlrpc-rate-limit.py \
|
||||||
&& python3 /haproxy/scripts/test-default-splash.py \
|
&& python3 /haproxy/scripts/test-default-splash.py \
|
||||||
|
&& python3 /haproxy/scripts/test-nbthread-knob.py \
|
||||||
|
&& python3 /haproxy/scripts/test-health-check-timing.py \
|
||||||
&& python3 /haproxy/scripts/test-access-log-receiver.py \
|
&& python3 /haproxy/scripts/test-access-log-receiver.py \
|
||||||
&& python3 /haproxy/scripts/test-haproxy-stderr-relay.py \
|
&& python3 /haproxy/scripts/test-haproxy-stderr-relay.py \
|
||||||
&& python3 /haproxy/scripts/test-haproxy-supervisor.py \
|
&& python3 /haproxy/scripts/test-haproxy-supervisor.py \
|
||||||
|
&& python3 /haproxy/scripts/test-haproxy-supervisor-relaunch.py \
|
||||||
&& python3 /haproxy/scripts/test-config-rollback.py \
|
&& python3 /haproxy/scripts/test-config-rollback.py \
|
||||||
&& python3 /haproxy/scripts/test-cert-write-safety.py \
|
&& python3 /haproxy/scripts/test-cert-write-safety.py \
|
||||||
&& python3 /haproxy/scripts/test-cert-scripts.py \
|
&& python3 /haproxy/scripts/test-cert-scripts.py \
|
||||||
|
|||||||
@@ -3153,6 +3153,21 @@ def get_or_create_cluster_secret():
|
|||||||
logger.error("Failed to get/create cluster-secret: %s", e)
|
logger.error("Failed to get/create cluster-secret: %s", e)
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
def parse_nbthread(raw):
|
||||||
|
"""HAPROXY_NBTHREAD -> int 1..64, or None (= do not render `nbthread`).
|
||||||
|
|
||||||
|
Fail-safe: anything that is not a plain positive integer in range is
|
||||||
|
IGNORED with a warning, never rendered, so a typo in a host file cannot
|
||||||
|
produce an invalid haproxy.cfg (which would be a total edge outage)."""
|
||||||
|
raw = (raw or '').strip()
|
||||||
|
if not raw:
|
||||||
|
return None
|
||||||
|
if not (raw.isascii() and raw.isdigit()) or not 1 <= int(raw) <= 64:
|
||||||
|
logger.warning(f"Ignoring HAPROXY_NBTHREAD={raw!r}: expected an integer 1-64")
|
||||||
|
return None
|
||||||
|
return int(raw)
|
||||||
|
|
||||||
def generate_config():
|
def generate_config():
|
||||||
try:
|
try:
|
||||||
conn = sqlite3.connect(DB_FILE)
|
conn = sqlite3.connect(DB_FILE)
|
||||||
@@ -3246,10 +3261,15 @@ def generate_config():
|
|||||||
splash_raw = os.environ.get('HAPROXY_DEFAULT_SPLASH', '').strip().lower()
|
splash_raw = os.environ.get('HAPROXY_DEFAULT_SPLASH', '').strip().lower()
|
||||||
default_splash = splash_raw not in ('0', 'false', 'no', 'off')
|
default_splash = splash_raw not in ('0', 'false', 'no', 'off')
|
||||||
|
|
||||||
|
# Optional per-host thread count (global `nbthread`). Unset/invalid =
|
||||||
|
# not rendered = HAProxy's automatic choice, byte-identical config.
|
||||||
|
nbthread = parse_nbthread(os.environ.get('HAPROXY_NBTHREAD'))
|
||||||
|
|
||||||
# Add Haproxy Default Headers
|
# Add Haproxy Default Headers
|
||||||
default_headers = template_env.get_template('hap_header.tpl').render(
|
default_headers = template_env.get_template('hap_header.tpl').render(
|
||||||
cluster_secret = get_or_create_cluster_secret(),
|
cluster_secret = get_or_create_cluster_secret(),
|
||||||
syslog_target = syslog_target,
|
syslog_target = syslog_target,
|
||||||
|
nbthread = nbthread,
|
||||||
coraza_spoe_backend = coraza_spoe_backend,
|
coraza_spoe_backend = coraza_spoe_backend,
|
||||||
)
|
)
|
||||||
config_parts.append(default_headers)
|
config_parts.append(default_headers)
|
||||||
|
|||||||
@@ -10,9 +10,26 @@
|
|||||||
#
|
#
|
||||||
# The liveness probe is `pidof` (a few ms), NOT python: ensure_haproxy.py imports
|
# The liveness probe is `pidof` (a few ms), NOT python: ensure_haproxy.py imports
|
||||||
# the 4000-line manager (Flask, Jinja, ...) which costs ~0.5 s of CPU per run and
|
# the 4000-line manager (Flask, Jinja, ...) which costs ~0.5 s of CPU per run and
|
||||||
# was affordable at 15 s but not at 2 s. python only runs when haproxy is gone.
|
# was affordable at 15 s but not at 2 s. 2026-11 evidence: every watchdog abort
|
||||||
# 2026-11 evidence: every watchdog abort took the whole edge down for 15-52 s,
|
# took the whole edge down for 15-52 s, most of it detection latency + start.
|
||||||
# most of it detection latency + start; the default is now 2 s (was 15).
|
#
|
||||||
|
# FAST PATH (2026-11-26, whp02 abort: python took 16 s just to LOG "process not
|
||||||
|
# found" on an I/O-starved host). When haproxy is gone the loop relaunches it
|
||||||
|
# DIRECTLY FROM BASH against the config on disk (the one the dead master loaded
|
||||||
|
# successfully minutes ago): `haproxy -c -f cfg` first, then the same command,
|
||||||
|
# flags, user and detach trick as haproxy_manager.spawn_haproxy_master()
|
||||||
|
# (`haproxy -W -db -S /tmp/haproxy-cli,level,admin -f cfg`, stderr appended to the
|
||||||
|
# stderr log, re-parented to PID 1 so gunicorn reaps it). Only if that fails
|
||||||
|
# (config missing/invalid, haproxy exits or never logs "Loading success.") does
|
||||||
|
# it fall back to `python ensure_haproxy.py` (regenerates + validates + starts).
|
||||||
|
# Never starts a second master: pidof is re-checked after validation, right
|
||||||
|
# before the launch. Every step is logged with a UTC millisecond timestamp.
|
||||||
|
#
|
||||||
|
# While a recovery is in progress the loop keeps HAPROXY_SUPERVISOR_MARKER
|
||||||
|
# (default /tmp/haproxy-restarting) containing "<epoch-seconds> <supervisor pid>"
|
||||||
|
# so the host watchdog (WHP panel/internal/watchdog/haproxy.go) can see the
|
||||||
|
# in-place restart is underway and not `docker restart` on top of it. It is
|
||||||
|
# removed when the recovery finishes (success or failure).
|
||||||
#
|
#
|
||||||
# Two backoffs:
|
# Two backoffs:
|
||||||
# * a restart attempt that FAILS (config HAProxy rejects): the loop doubles its
|
# * a restart attempt that FAILS (config HAProxy rejects): the loop doubles its
|
||||||
@@ -36,10 +53,15 @@ _posint() { # _posint VALUE DEFAULT
|
|||||||
esac
|
esac
|
||||||
}
|
}
|
||||||
|
|
||||||
INTERVAL="$(_posint "${HAPROXY_SUPERVISOR_INTERVAL:-}" 2)"
|
INTERVAL="$(_posint "${HAPROXY_SUPERVISOR_INTERVAL:-}" 1)"
|
||||||
MAX_BACKOFF="$(_posint "${HAPROXY_SUPERVISOR_MAX_BACKOFF:-}" 30)"
|
MAX_BACKOFF="$(_posint "${HAPROXY_SUPERVISOR_MAX_BACKOFF:-}" 30)"
|
||||||
QUICK_DEATH="$(_posint "${HAPROXY_SUPERVISOR_QUICK_DEATH:-}" 10)"
|
QUICK_DEATH="$(_posint "${HAPROXY_SUPERVISOR_QUICK_DEATH:-}" 10)"
|
||||||
STABLE="$(_posint "${HAPROXY_SUPERVISOR_STABLE:-}" 60)"
|
STABLE="$(_posint "${HAPROXY_SUPERVISOR_STABLE:-}" 60)"
|
||||||
|
START_WAIT="$(_posint "${HAPROXY_START_WAIT:-}" 10)"
|
||||||
|
CFG="${HAPROXY_SUPERVISOR_CFG:-/etc/haproxy/haproxy.cfg}"
|
||||||
|
BIN="${HAPROXY_SUPERVISOR_BIN:-haproxy}"
|
||||||
|
MASTER_SOCK="${HAPROXY_SUPERVISOR_SOCKET:-/tmp/haproxy-cli}"
|
||||||
|
MARKER="${HAPROXY_SUPERVISOR_MARKER:-/tmp/haproxy-restarting}"
|
||||||
STEPS=""
|
STEPS=""
|
||||||
for s in ${HAPROXY_SUPERVISOR_BACKOFF_STEPS:-2 5 10 30}; do
|
for s in ${HAPROXY_SUPERVISOR_BACKOFF_STEPS:-2 5 10 30}; do
|
||||||
v="$(_posint "$s" 0)"
|
v="$(_posint "$s" 0)"
|
||||||
@@ -58,6 +80,115 @@ _step() {
|
|||||||
echo "${v}"
|
echo "${v}"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
# --- logging / timing helpers -------------------------------------------------
|
||||||
|
_now_ms() {
|
||||||
|
if [ -n "${EPOCHREALTIME:-}" ]; then
|
||||||
|
local t="${EPOCHREALTIME/./}" # microseconds
|
||||||
|
echo $(( t / 1000 ))
|
||||||
|
else
|
||||||
|
echo $(( $(date +%s) * 1000 ))
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
_log() { # _log LEVEL MESSAGE... (stderr = container stderr, like the old echo)
|
||||||
|
local lvl="$1"; shift
|
||||||
|
printf '%s [haproxy-supervisor] %s: %s\n' "$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)" "${lvl}" "$*" >&2
|
||||||
|
}
|
||||||
|
|
||||||
|
_stderr_log() { # same fallback as haproxy_manager._stderr_log_path()
|
||||||
|
local p="${HAPROXY_STDERR_LOG:-/var/log/haproxy/haproxy-stderr.log}"
|
||||||
|
if mkdir -p "$(dirname "${p}")" 2>/dev/null && (umask 027; : >>"${p}") 2>/dev/null; then
|
||||||
|
echo "${p}"
|
||||||
|
else
|
||||||
|
echo /tmp/haproxy-stderr.log
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
_marker_set() { printf '%s %s\n' "$(date +%s)" "$$" >"${MARKER}" 2>/dev/null || true; }
|
||||||
|
_marker_clear() { rm -f "${MARKER}" 2>/dev/null || true; }
|
||||||
|
trap _marker_clear EXIT
|
||||||
|
# A marker left by a supervisor that was SIGKILLed mid-recovery (`docker restart`
|
||||||
|
# kills everything after PID 1 exits; no EXIT trap runs) survives in /tmp, which
|
||||||
|
# a restart does not reset. This process never started that recovery: drop it.
|
||||||
|
_marker_clear
|
||||||
|
|
||||||
|
# Direct bash relaunch. Return 0 = haproxy is up (started here or already
|
||||||
|
# running), 1 = caller must fall back to ensure_haproxy.py.
|
||||||
|
fast_relaunch() {
|
||||||
|
local t0="$1" t cfg_ms log_path offset text i
|
||||||
|
if [ ! -r "${CFG}" ]; then
|
||||||
|
_log WARN "fast path skipped: config ${CFG} missing/unreadable"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
if ! command -v "${BIN}" >/dev/null 2>&1; then
|
||||||
|
_log WARN "fast path skipped: ${BIN} not found on PATH"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
if ! timeout 20 "${BIN}" -c -q -f "${CFG}" >/dev/null 2>&1; then
|
||||||
|
_log WARN "fast path skipped: '${BIN} -c -f ${CFG}' rejected the on-disk config"
|
||||||
|
return 1
|
||||||
|
fi
|
||||||
|
t="$(_now_ms)"; cfg_ms=$(( t - t0 ))
|
||||||
|
_log INFO "on-disk config valid (+${cfg_ms} ms)"
|
||||||
|
# Idempotency: never a second master. Re-check right before launching (the
|
||||||
|
# validation above took time; the API's start_haproxy may have won).
|
||||||
|
if pidof -q haproxy; then
|
||||||
|
_log INFO "haproxy is already running; nothing to start"
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
log_path="$(_stderr_log)"
|
||||||
|
offset="$(stat -c %s "${log_path}" 2>/dev/null || echo 0)"
|
||||||
|
# Same detach as spawn_haproxy_master(): the double fork re-parents haproxy to
|
||||||
|
# PID 1 (gunicorn reaps it; a zombie child of this loop would keep pidof true).
|
||||||
|
( chmod 0640 "${log_path}" 2>/dev/null
|
||||||
|
"${BIN}" -W -db -S "${MASTER_SOCK},level,admin" -f "${CFG}" \
|
||||||
|
</dev/null >>"${log_path}" 2>&1 & )
|
||||||
|
t="$(_now_ms)"
|
||||||
|
_log INFO "launched '${BIN} -W -db -S ${MASTER_SOCK},level,admin -f ${CFG}' (+$(( t - t0 )) ms)"
|
||||||
|
# Wait for "Loading success." (deadline HAPROXY_START_WAIT; alive + no [ALERT] at
|
||||||
|
# the deadline also counts), exactly like spawn_haproxy_master().
|
||||||
|
for i in $(seq 1 $(( START_WAIT * 10 ))); do
|
||||||
|
text="$(tail -c +$(( offset + 1 )) "${log_path}" 2>/dev/null || true)"
|
||||||
|
case "${text}" in
|
||||||
|
*"Loading success."*)
|
||||||
|
t="$(_now_ms)"
|
||||||
|
_log INFO "haproxy up in place: config loaded (+$(( t - t0 )) ms since detection)"
|
||||||
|
return 0 ;;
|
||||||
|
esac
|
||||||
|
# exited (or never came up) after the 1 s grace: stop waiting
|
||||||
|
if [ "${i}" -gt 10 ] && ! pidof -q haproxy; then break; fi
|
||||||
|
sleep 0.1
|
||||||
|
done
|
||||||
|
if pidof -q haproxy; then
|
||||||
|
case "${text}" in *"[ALERT]"*) ;; *)
|
||||||
|
_log INFO "haproxy up in place: alive, slow to log (+$(( $(_now_ms) - t0 )) ms since detection)"
|
||||||
|
return 0 ;;
|
||||||
|
esac
|
||||||
|
fi
|
||||||
|
_log ERROR "direct relaunch failed: $(printf '%s' "${text}" | tail -n 3 | tr '\n' '|')"
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# Recover a missing haproxy: fast path, then the python fallback.
|
||||||
|
recover() {
|
||||||
|
local t0
|
||||||
|
t0="$(_now_ms)"
|
||||||
|
_marker_set
|
||||||
|
_log WARN "haproxy process not found — attempting in-place restart (direct relaunch first)"
|
||||||
|
if fast_relaunch "${t0}"; then
|
||||||
|
_marker_clear
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
_log WARN "falling back to ensure_haproxy.py (+$(( $(_now_ms) - t0 )) ms)"
|
||||||
|
if python /haproxy/scripts/ensure_haproxy.py 2>&1; then
|
||||||
|
_log INFO "ensure_haproxy.py succeeded (+$(( $(_now_ms) - t0 )) ms since detection)"
|
||||||
|
_marker_clear
|
||||||
|
return 0
|
||||||
|
fi
|
||||||
|
_log ERROR "ensure_haproxy.py failed (+$(( $(_now_ms) - t0 )) ms)"
|
||||||
|
_marker_clear
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
|
||||||
delay="${INTERVAL}"
|
delay="${INTERVAL}"
|
||||||
last_start=-1 # SECONDS at our last successful (re)start; -1 = none yet
|
last_start=-1 # SECONDS at our last successful (re)start; -1 = none yet
|
||||||
quick=0 # consecutive deaths within QUICK_DEATH of a start
|
quick=0 # consecutive deaths within QUICK_DEATH of a start
|
||||||
@@ -75,14 +206,14 @@ while true; do
|
|||||||
if [ "${up}" -lt "${QUICK_DEATH}" ]; then
|
if [ "${up}" -lt "${QUICK_DEATH}" ]; then
|
||||||
quick=$((quick + 1))
|
quick=$((quick + 1))
|
||||||
wait_s="$(_step "${quick}")"
|
wait_s="$(_step "${quick}")"
|
||||||
echo "haproxy-supervisor: haproxy died ${up}s after start (quick death #${quick}); waiting ${wait_s}s before restart" >&2
|
_log WARN "haproxy died ${up}s after start (quick death #${quick}); waiting ${wait_s}s before restart"
|
||||||
sleep "${wait_s}"
|
sleep "${wait_s}"
|
||||||
pidof -q haproxy && continue
|
pidof -q haproxy && continue
|
||||||
elif [ "${up}" -ge "${STABLE}" ]; then
|
elif [ "${up}" -ge "${STABLE}" ]; then
|
||||||
quick=0
|
quick=0
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
if python /haproxy/scripts/ensure_haproxy.py 2>&1; then
|
if recover; then
|
||||||
delay="${INTERVAL}"
|
delay="${INTERVAL}"
|
||||||
last_start="${SECONDS}"
|
last_start="${SECONDS}"
|
||||||
else
|
else
|
||||||
|
|||||||
@@ -54,6 +54,7 @@ destructive there; see _cleanup_tmp().
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
|
import platform
|
||||||
import re
|
import re
|
||||||
import shutil
|
import shutil
|
||||||
import stat
|
import stat
|
||||||
@@ -63,6 +64,12 @@ import textwrap
|
|||||||
import time
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
|
# Subprocess ceiling. The arm64 image gate runs under QEMU (~30x slower: this
|
||||||
|
# file took 8 s natively and 229 s emulated, and the 200-iteration bash loop in
|
||||||
|
# test_validation_of_a_live_pem_being_republished_is_not_spurious then exceeded
|
||||||
|
# a flat 120 s, failing the arm64 leg of every build). Native x86 keeps 120 s.
|
||||||
|
SUBPROCESS_TIMEOUT = 120 if platform.machine() in ('x86_64', 'AMD64') else 900
|
||||||
|
|
||||||
MODULE_DIR = os.path.abspath(
|
MODULE_DIR = os.path.abspath(
|
||||||
os.environ.get('HAPROXY_MANAGER_DIR',
|
os.environ.get('HAPROXY_MANAGER_DIR',
|
||||||
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
|
||||||
@@ -379,7 +386,7 @@ class CertScriptFixture(unittest.TestCase):
|
|||||||
path = os.path.join(SCRIPTS_DIR, name)
|
path = os.path.join(SCRIPTS_DIR, name)
|
||||||
self.assertTrue(os.path.exists(path), f'{path} does not exist')
|
self.assertTrue(os.path.exists(path), f'{path} does not exist')
|
||||||
return subprocess.run(['bash', path], env=self.env(**env_overrides),
|
return subprocess.run(['bash', path], env=self.env(**env_overrides),
|
||||||
capture_output=True, text=True, timeout=120)
|
capture_output=True, text=True, timeout=SUBPROCESS_TIMEOUT)
|
||||||
|
|
||||||
def bundle_is_valid(self, path):
|
def bundle_is_valid(self, path):
|
||||||
"""Ask the shipped library whether HAProxy could use this bundle."""
|
"""Ask the shipped library whether HAProxy could use this bundle."""
|
||||||
@@ -964,7 +971,7 @@ class TestCertPublishLibrary(CertScriptFixture):
|
|||||||
['bash', '-c',
|
['bash', '-c',
|
||||||
'. "$1"; for i in $(seq 1 200); do cert_bundle_valid "$2" || exit 1; done',
|
'. "$1"; for i in $(seq 1 200); do cert_bundle_valid "$2" || exit 1; done',
|
||||||
'_', LIB, self.live_pem],
|
'_', LIB, self.live_pem],
|
||||||
env=self.env(), capture_output=True, text=True, timeout=120)
|
env=self.env(), capture_output=True, text=True, timeout=SUBPROCESS_TIMEOUT)
|
||||||
_stop()
|
_stop()
|
||||||
|
|
||||||
output = result.stdout + result.stderr
|
output = result.stdout + result.stderr
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Real-haproxy test for the supervisor's FAST relaunch path.
|
||||||
|
|
||||||
|
Starts a real `haproxy -W -db` master with a minimal config, runs the REAL
|
||||||
|
scripts/haproxy-supervisor.sh next to it (python is stubbed on PATH so any
|
||||||
|
fallback to ensure_haproxy.py is detected), then kills the worker with SIGABRT
|
||||||
|
(exactly the 2026-11-19/25/26 failure: the master logs exit-on-failure and
|
||||||
|
exits 134). Asserts:
|
||||||
|
|
||||||
|
* the master really exits (the premise of the bug),
|
||||||
|
* a NEW master is serving within 3 s of that exit (it was 16 s on whp02),
|
||||||
|
* it was started directly from bash (the python stub never ran),
|
||||||
|
* the recovery marker existed during the restart and is gone afterwards,
|
||||||
|
* the supervisor log lines carry timestamps for each step,
|
||||||
|
* a second master is never started while one is running,
|
||||||
|
* an invalid on-disk config falls back to ensure_haproxy.py (python stub).
|
||||||
|
|
||||||
|
Needs a real `haproxy`, `pidof`, `bash`, `timeout` (no procps: children are read from /proc). Skips (exit 0, loudly)
|
||||||
|
when haproxy is not installed, so it is meaningful in the image build (where
|
||||||
|
validate-rendered-config.py also needs the binary) and on a dev box with haproxy.
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import signal
|
||||||
|
import socket
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
SUPERVISOR = os.path.join(HERE, 'haproxy-supervisor.sh')
|
||||||
|
HAPROXY = shutil.which('haproxy')
|
||||||
|
|
||||||
|
PYTHON_STUB = """#!/bin/sh
|
||||||
|
date +%s.%N >> "$STATE/python-ran"
|
||||||
|
exit 1
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _free_port():
|
||||||
|
s = socket.socket()
|
||||||
|
s.bind(('127.0.0.1', 0))
|
||||||
|
port = s.getsockname()[1]
|
||||||
|
s.close()
|
||||||
|
return port
|
||||||
|
|
||||||
|
|
||||||
|
def _all_pids():
|
||||||
|
r = subprocess.run(['pidof', 'haproxy'], stdout=subprocess.PIPE, text=True)
|
||||||
|
return sorted(int(x) for x in r.stdout.split())
|
||||||
|
|
||||||
|
|
||||||
|
def _master_pids():
|
||||||
|
"""haproxy processes whose parent is not itself haproxy (workers share the name)."""
|
||||||
|
pids = _all_pids()
|
||||||
|
out = []
|
||||||
|
for pid in pids:
|
||||||
|
try:
|
||||||
|
with open('/proc/%d/stat' % pid) as fh:
|
||||||
|
ppid = int(fh.read().rsplit(')', 1)[1].split()[1])
|
||||||
|
except (OSError, ValueError, IndexError):
|
||||||
|
continue
|
||||||
|
if ppid not in pids:
|
||||||
|
out.append(pid)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _worker_of(master):
|
||||||
|
"""Children of `master` from /proc (the image has no procps/pgrep)."""
|
||||||
|
out = []
|
||||||
|
for name in os.listdir('/proc'):
|
||||||
|
if not name.isdigit():
|
||||||
|
continue
|
||||||
|
try:
|
||||||
|
with open('/proc/%s/stat' % name) as fh:
|
||||||
|
ppid = int(fh.read().rsplit(')', 1)[1].split()[1])
|
||||||
|
except (OSError, ValueError, IndexError):
|
||||||
|
continue
|
||||||
|
if ppid == master:
|
||||||
|
out.append(int(name))
|
||||||
|
return sorted(out)
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(HAPROXY, 'haproxy binary not installed')
|
||||||
|
class RelaunchTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
if _all_pids():
|
||||||
|
self.skipTest('another haproxy is already running on this host')
|
||||||
|
self.d = tempfile.mkdtemp(prefix='hap-relaunch-')
|
||||||
|
self.state = os.path.join(self.d, 'state')
|
||||||
|
os.mkdir(self.state)
|
||||||
|
self.port = _free_port()
|
||||||
|
self.cfg = os.path.join(self.d, 'haproxy.cfg')
|
||||||
|
self.write_cfg(valid=True)
|
||||||
|
self.log = os.path.join(self.d, 'stderr.log')
|
||||||
|
self.marker = os.path.join(self.d, 'restarting')
|
||||||
|
self.sock = os.path.join(self.d, 'cli')
|
||||||
|
py = os.path.join(self.d, 'python')
|
||||||
|
with open(py, 'w') as fh:
|
||||||
|
fh.write(PYTHON_STUB)
|
||||||
|
os.chmod(py, os.stat(py).st_mode | stat.S_IXUSR)
|
||||||
|
self.env = dict(os.environ, PATH=self.d + ':' + os.environ['PATH'], STATE=self.state,
|
||||||
|
HAPROXY_SUPERVISOR_CFG=self.cfg, HAPROXY_SUPERVISOR_MARKER=self.marker,
|
||||||
|
HAPROXY_SUPERVISOR_SOCKET=self.sock, HAPROXY_STDERR_LOG=self.log)
|
||||||
|
self.sup = None
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
if self.sup:
|
||||||
|
self.sup.terminate()
|
||||||
|
try:
|
||||||
|
self.sup.wait(5)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
self.sup.kill()
|
||||||
|
self.sup.wait()
|
||||||
|
for pid in _all_pids():
|
||||||
|
try:
|
||||||
|
os.kill(pid, signal.SIGKILL)
|
||||||
|
except OSError:
|
||||||
|
pass
|
||||||
|
if getattr(self, 'suplog', None):
|
||||||
|
self.suplog.close()
|
||||||
|
end = time.monotonic() + 5
|
||||||
|
while _all_pids() and time.monotonic() < end: # let the kernel finish reaping before the next test
|
||||||
|
time.sleep(0.05)
|
||||||
|
shutil.rmtree(self.d, ignore_errors=True)
|
||||||
|
|
||||||
|
def write_cfg(self, valid):
|
||||||
|
body = ('global\n maxconn 100\n\n'
|
||||||
|
'defaults\n mode http\n timeout connect 1s\n timeout client 5s\n timeout server 5s\n\n'
|
||||||
|
'frontend fe\n bind 127.0.0.1:%d\n http-request return status 200 content-type text/plain string ok\n'
|
||||||
|
% self.port)
|
||||||
|
if not valid:
|
||||||
|
body += '\nthis-is-not-a-haproxy-keyword 1\n'
|
||||||
|
with open(self.cfg, 'w') as fh:
|
||||||
|
fh.write(body)
|
||||||
|
|
||||||
|
def start_master(self):
|
||||||
|
with open(self.log, 'ab') as lf:
|
||||||
|
subprocess.Popen([HAPROXY, '-W', '-db', '-S', self.sock + ',level,admin', '-f', self.cfg],
|
||||||
|
stdin=subprocess.DEVNULL, stdout=lf, stderr=lf, start_new_session=True)
|
||||||
|
self.wait_for(lambda: self.serving(), 10, 'initial master serving')
|
||||||
|
return _master_pids()[0]
|
||||||
|
|
||||||
|
def serving(self):
|
||||||
|
try:
|
||||||
|
with socket.create_connection(('127.0.0.1', self.port), timeout=0.5) as c:
|
||||||
|
c.sendall(b'GET / HTTP/1.0\r\n\r\n')
|
||||||
|
return b'200' in c.recv(64)
|
||||||
|
except OSError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def wait_for(self, fn, timeout, what):
|
||||||
|
end = time.monotonic() + timeout
|
||||||
|
while time.monotonic() < end:
|
||||||
|
if fn():
|
||||||
|
return time.monotonic()
|
||||||
|
time.sleep(0.02)
|
||||||
|
self.fail('timed out waiting for ' + what)
|
||||||
|
|
||||||
|
def start_supervisor(self, **extra):
|
||||||
|
env = dict(self.env, **extra)
|
||||||
|
self.suplog = open(os.path.join(self.d, 'supervisor.out'), 'w')
|
||||||
|
self.sup = subprocess.Popen(['bash', SUPERVISOR], env=env, stdout=self.suplog, stderr=subprocess.STDOUT,
|
||||||
|
stdin=subprocess.DEVNULL)
|
||||||
|
|
||||||
|
def sup_output(self):
|
||||||
|
self.suplog.flush()
|
||||||
|
with open(os.path.join(self.d, 'supervisor.out')) as fh:
|
||||||
|
return fh.read()
|
||||||
|
|
||||||
|
def test_worker_abort_is_relaunched_directly_in_under_3_seconds(self):
|
||||||
|
master = self.start_master()
|
||||||
|
self.start_supervisor()
|
||||||
|
workers = _worker_of(master)
|
||||||
|
self.assertTrue(workers, 'no worker under the master')
|
||||||
|
os.kill(workers[0], signal.SIGABRT)
|
||||||
|
# premise: the master exits on a worker abort (exit-on-failure)
|
||||||
|
died = self.wait_for(lambda: master not in _master_pids(), 5, 'master to exit after the worker abort')
|
||||||
|
up = self.wait_for(lambda: self.serving() and master not in _master_pids(), 10, 'relaunched edge serving')
|
||||||
|
gap = up - died
|
||||||
|
self.wait_for(lambda: 'haproxy up in place' in self.sup_output(), 3, 'supervisor "up in place" line')
|
||||||
|
out = self.sup_output()
|
||||||
|
print('measured relaunch time (master exit -> serving): %.2f s' % gap)
|
||||||
|
self.assertLess(gap, 3.0, out)
|
||||||
|
new = _master_pids()
|
||||||
|
self.assertEqual(len(new), 1, 'exactly one master, got %r' % new)
|
||||||
|
self.assertNotEqual(new[0], master)
|
||||||
|
self.assertFalse(os.path.exists(os.path.join(self.state, 'python-ran')), 'fast path fell back to python\n' + out)
|
||||||
|
for step in ('haproxy process not found', 'on-disk config valid', 'launched', 'haproxy up in place'):
|
||||||
|
self.assertIn(step, out)
|
||||||
|
self.assertRegex(out, r'\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{3}Z \[haproxy-supervisor\]')
|
||||||
|
self.wait_for(lambda: not os.path.exists(self.marker), 3, 'marker cleared')
|
||||||
|
|
||||||
|
def test_marker_exists_while_restarting(self):
|
||||||
|
master = self.start_master()
|
||||||
|
self.start_supervisor()
|
||||||
|
os.kill(_worker_of(master)[0], signal.SIGABRT)
|
||||||
|
seen = []
|
||||||
|
end = time.monotonic() + 8
|
||||||
|
while time.monotonic() < end:
|
||||||
|
if os.path.exists(self.marker):
|
||||||
|
with open(self.marker) as fh:
|
||||||
|
seen.append(fh.read().split())
|
||||||
|
if seen and not os.path.exists(self.marker):
|
||||||
|
break
|
||||||
|
time.sleep(0.005)
|
||||||
|
# the recovery is ~100s of ms: a 5 ms poll sees the marker unless it was missed entirely
|
||||||
|
self.assertTrue(seen, 'marker never observed\n' + self.sup_output())
|
||||||
|
self.assertEqual(len(seen[0]), 2)
|
||||||
|
self.assertLess(abs(int(seen[0][0]) - time.time()), 30)
|
||||||
|
|
||||||
|
def test_running_master_is_never_duplicated(self):
|
||||||
|
master = self.start_master()
|
||||||
|
self.start_supervisor()
|
||||||
|
time.sleep(3.5)
|
||||||
|
self.assertEqual(_master_pids(), [master])
|
||||||
|
self.assertNotIn('haproxy process not found', self.sup_output())
|
||||||
|
|
||||||
|
def test_invalid_config_falls_back_to_ensure_haproxy(self):
|
||||||
|
master = self.start_master()
|
||||||
|
self.start_supervisor()
|
||||||
|
self.write_cfg(valid=False)
|
||||||
|
os.kill(_worker_of(master)[0], signal.SIGABRT)
|
||||||
|
self.wait_for(lambda: os.path.exists(os.path.join(self.state, 'python-ran')), 8, 'python fallback')
|
||||||
|
self.assertIn('rejected the on-disk config', self.sup_output())
|
||||||
|
self.assertEqual(_master_pids(), [])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
if not HAPROXY:
|
||||||
|
print('SKIP: haproxy not installed; the real-haproxy relaunch test did not run')
|
||||||
|
unittest.main()
|
||||||
@@ -25,7 +25,7 @@ exit ${ENSURE_RC:-0}
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
class SupervisorTests(unittest.TestCase):
|
class SupervisorBase:
|
||||||
def setUp(self):
|
def setUp(self):
|
||||||
self.d = tempfile.mkdtemp(prefix='hap-sup-')
|
self.d = tempfile.mkdtemp(prefix='hap-sup-')
|
||||||
self.state = os.path.join(self.d, 'state')
|
self.state = os.path.join(self.d, 'state')
|
||||||
@@ -39,6 +39,10 @@ class SupervisorTests(unittest.TestCase):
|
|||||||
def run_sup(self, seconds, **env):
|
def run_sup(self, seconds, **env):
|
||||||
e = dict(os.environ, PATH=self.d + ':' + os.environ['PATH'], STATE=self.state)
|
e = dict(os.environ, PATH=self.d + ':' + os.environ['PATH'], STATE=self.state)
|
||||||
e.setdefault('LIFE', '0')
|
e.setdefault('LIFE', '0')
|
||||||
|
# keep the fast path OFF unless a test opts in (no config -> python fallback)
|
||||||
|
e.setdefault('HAPROXY_SUPERVISOR_CFG', os.path.join(self.d, 'no-such.cfg'))
|
||||||
|
e.setdefault('HAPROXY_SUPERVISOR_MARKER', os.path.join(self.state, 'marker'))
|
||||||
|
e.setdefault('HAPROXY_STDERR_LOG', os.path.join(self.d, 'stderr.log'))
|
||||||
e.update(env)
|
e.update(env)
|
||||||
try:
|
try:
|
||||||
subprocess.run(['bash', SCRIPT], env=e, timeout=seconds, stdout=subprocess.PIPE,
|
subprocess.run(['bash', SCRIPT], env=e, timeout=seconds, stdout=subprocess.PIPE,
|
||||||
@@ -54,6 +58,8 @@ class SupervisorTests(unittest.TestCase):
|
|||||||
except OSError:
|
except OSError:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
class SupervisorTests(SupervisorBase, unittest.TestCase):
|
||||||
def test_non_integer_interval_does_not_kill_the_supervisor(self):
|
def test_non_integer_interval_does_not_kill_the_supervisor(self):
|
||||||
self.assertEqual(self.run_sup(8, HAPROXY_SUPERVISOR_INTERVAL='0.5', ENSURE_RC='1'), 'running')
|
self.assertEqual(self.run_sup(8, HAPROXY_SUPERVISOR_INTERVAL='0.5', ENSURE_RC='1'), 'running')
|
||||||
self.assertGreaterEqual(len(self.starts()), 2) # fell back to the default interval and kept trying
|
self.assertGreaterEqual(len(self.starts()), 2) # fell back to the default interval and kept trying
|
||||||
@@ -93,5 +99,78 @@ class SupervisorTests(unittest.TestCase):
|
|||||||
self.assertEqual(self.starts(), [])
|
self.assertEqual(self.starts(), [])
|
||||||
|
|
||||||
|
|
||||||
|
# stand-in `haproxy`: -c validates (rc from $CHECK_RC); a launch stamps the start,
|
||||||
|
# logs the line the supervisor waits for, and records whether the marker existed
|
||||||
|
HAPROXY = """#!/bin/sh
|
||||||
|
if [ "$1" = "-c" ]; then exit ${CHECK_RC:-0}; fi
|
||||||
|
[ -f "$MARKER" ] && echo yes >> "$STATE/marker-seen"
|
||||||
|
date +%s.%N > "$STATE/started"
|
||||||
|
date +%s.%N >> "$STATE/direct"
|
||||||
|
echo "[NOTICE] Loading success." >&2
|
||||||
|
exit ${LAUNCH_RC:-0}
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class FastPathTests(SupervisorBase, unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
p = os.path.join(self.d, 'haproxy')
|
||||||
|
with open(p, 'w') as fh:
|
||||||
|
fh.write(HAPROXY)
|
||||||
|
os.chmod(p, os.stat(p).st_mode | stat.S_IXUSR)
|
||||||
|
self.cfg = os.path.join(self.d, 'haproxy.cfg')
|
||||||
|
with open(self.cfg, 'w') as fh:
|
||||||
|
fh.write('# stub\n')
|
||||||
|
|
||||||
|
def fast_env(self, **kw):
|
||||||
|
e = dict(HAPROXY_SUPERVISOR_CFG=self.cfg, MARKER=os.path.join(self.state, 'marker'),
|
||||||
|
HAPROXY_SUPERVISOR_INTERVAL='1', LIFE='1000')
|
||||||
|
e.update(kw)
|
||||||
|
return e
|
||||||
|
|
||||||
|
def direct(self):
|
||||||
|
try:
|
||||||
|
with open(os.path.join(self.state, 'direct')) as fh:
|
||||||
|
return fh.read().split()
|
||||||
|
except OSError:
|
||||||
|
return []
|
||||||
|
|
||||||
|
def test_dead_haproxy_is_relaunched_directly_without_python(self):
|
||||||
|
self.run_sup(4, **self.fast_env(LIFE='0')) # LIFE=0: haproxy is always "gone" at the first poll
|
||||||
|
self.assertGreaterEqual(len(self.direct()), 1)
|
||||||
|
self.assertEqual(self.starts(), []) # ensure_haproxy.py / python never ran
|
||||||
|
with open(os.path.join(self.state, 'marker-seen')) as fh:
|
||||||
|
self.assertEqual(fh.read().split(), ['yes'] * len(self.direct()))
|
||||||
|
self.assertFalse(os.path.exists(os.path.join(self.state, 'marker'))) # cleared after the recovery
|
||||||
|
|
||||||
|
def test_invalid_config_falls_back_to_python(self):
|
||||||
|
self.run_sup(4, **self.fast_env(LIFE='0', CHECK_RC='1'))
|
||||||
|
self.assertEqual(self.direct(), [])
|
||||||
|
self.assertGreaterEqual(len(self.starts()), 1)
|
||||||
|
self.assertFalse(os.path.exists(os.path.join(self.state, 'marker')))
|
||||||
|
|
||||||
|
def test_failed_direct_launch_falls_back_to_python(self):
|
||||||
|
# haproxy binary not on PATH: the direct path cannot start it
|
||||||
|
self.run_sup(4, **self.fast_env(LIFE='0', HAPROXY_SUPERVISOR_BIN='no-such-haproxy-bin'))
|
||||||
|
self.assertEqual(self.direct(), [])
|
||||||
|
self.assertGreaterEqual(len(self.starts()), 1)
|
||||||
|
|
||||||
|
def test_missing_config_falls_back_to_python(self):
|
||||||
|
self.run_sup(4, **self.fast_env(LIFE='0', HAPROXY_SUPERVISOR_CFG=os.path.join(self.d, 'gone.cfg')))
|
||||||
|
self.assertEqual(self.direct(), [])
|
||||||
|
self.assertGreaterEqual(len(self.starts()), 1)
|
||||||
|
|
||||||
|
def test_running_haproxy_never_gets_a_second_master(self):
|
||||||
|
with open(os.path.join(self.state, 'started'), 'w') as fh:
|
||||||
|
fh.write(str(time.time()))
|
||||||
|
self.assertEqual(self.run_sup(3, **self.fast_env()), 'running')
|
||||||
|
self.assertEqual(self.direct(), [])
|
||||||
|
self.assertEqual(self.starts(), [])
|
||||||
|
|
||||||
|
def test_poll_interval_defaults_to_one_second(self):
|
||||||
|
self.run_sup(3, **{k: v for k, v in self.fast_env(LIFE='0').items() if k != 'HAPROXY_SUPERVISOR_INTERVAL'})
|
||||||
|
self.assertGreaterEqual(len(self.direct()), 1) # first relaunch inside the 3 s budget (2 s poll + start would not fit twice)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
unittest.main()
|
unittest.main()
|
||||||
Executable
+110
@@ -0,0 +1,110 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Backend health-check timing: one `default-server` line, jittered, pinned.
|
||||||
|
|
||||||
|
WHP appends `check ssl verify none` to every backend server, and each check is
|
||||||
|
a full TLS handshake. On a host with ~426 checked servers the HAProxy default
|
||||||
|
(inter 2s) is ~200+ handshakes/s of health-check churn, which together with
|
||||||
|
memory pressure preceded the 2026-11-25 watchdog aborts. So the interval is
|
||||||
|
30s, set ONCE in `defaults` (never per server line), and the checks are
|
||||||
|
desynchronised with the global `spread-checks`.
|
||||||
|
|
||||||
|
What this pins (the real `haproxy -c` of the same config is the
|
||||||
|
`check-timing` assertions in scripts/validate-rendered-config.py):
|
||||||
|
* exactly one default-server line, in `defaults`, with the agreed timing;
|
||||||
|
* `spread-checks 50` in `global` (documented max, 0..50);
|
||||||
|
* the agreed timing detects a dead backend in <= ~75 s worst case (inside the 1-2
|
||||||
|
minutes Josh accepted) -- computed from the numbers, so changing one of
|
||||||
|
them without re-justifying the other fails here;
|
||||||
|
* no template puts inter/fastinter/downinter on a customer server line
|
||||||
|
(that would bypass the one knob), and the Coraza SPOA server keeps its
|
||||||
|
own fast timing.
|
||||||
|
|
||||||
|
python3 scripts/test-health-check-timing.py
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
MODULE_DIR = os.path.abspath(
|
||||||
|
os.environ.get('HAPROXY_MANAGER_DIR',
|
||||||
|
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')))
|
||||||
|
sys.path.insert(0, MODULE_DIR)
|
||||||
|
import haproxy_manager as hm # noqa: E402
|
||||||
|
|
||||||
|
WANT = 'default-server inter 30s fastinter 10s downinter 30s rise 2 fall 3'
|
||||||
|
|
||||||
|
|
||||||
|
def header(**kw):
|
||||||
|
return hm.template_env.get_template('hap_header.tpl').render(
|
||||||
|
cluster_secret='s', syslog_target='/log.sock',
|
||||||
|
coraza_spoe_backend=kw.pop('coraza_spoe_backend', None), **kw)
|
||||||
|
|
||||||
|
|
||||||
|
def code(text):
|
||||||
|
return '\n'.join(l for l in text.splitlines() if not l.lstrip().startswith('#'))
|
||||||
|
|
||||||
|
|
||||||
|
def section(out, name):
|
||||||
|
m = re.search(r'^%s\b.*?(?=^\S|\Z)' % name, code(out), re.M | re.S)
|
||||||
|
assert m, name
|
||||||
|
return m.group(0)
|
||||||
|
|
||||||
|
|
||||||
|
class Timing(unittest.TestCase):
|
||||||
|
def test_one_default_server_in_defaults(self):
|
||||||
|
for kw in ({}, {'coraza_spoe_backend': '127.0.0.1:9000'}, {'nbthread': 1}):
|
||||||
|
out = header(**kw)
|
||||||
|
lines = re.findall(r'^\s*default-server\s.*$', code(out), re.M)
|
||||||
|
self.assertEqual(len(lines), 1, kw)
|
||||||
|
self.assertEqual(' '.join(lines[0].split()), WANT)
|
||||||
|
self.assertIn('default-server', section(out, 'defaults'))
|
||||||
|
self.assertNotIn('default-server', section(out, 'global'))
|
||||||
|
|
||||||
|
def test_spread_checks_in_global_at_documented_max(self):
|
||||||
|
out = header()
|
||||||
|
self.assertEqual(re.findall(r'^\s*spread-checks\s+(\d+)\s*$', section(out, 'global'), re.M),
|
||||||
|
['50'])
|
||||||
|
self.assertEqual(code(out).count('spread-checks'), 1)
|
||||||
|
|
||||||
|
def test_dead_backend_detected_within_two_minutes(self):
|
||||||
|
m = re.search(r'inter (\d+)s fastinter (\d+)s downinter (\d+)s rise (\d+) fall (\d+)', WANT)
|
||||||
|
inter, fast, down, rise, fall = map(int, m.groups())
|
||||||
|
jitter = 1.5 # spread-checks 50: each wait is up to +50%
|
||||||
|
# first failing check <= inter*1.5 after death, then fall-1 more at fastinter
|
||||||
|
mark_down = inter * jitter + (fall - 1) * fast * jitter
|
||||||
|
mark_up = down * jitter + (rise - 1) * fast * jitter
|
||||||
|
self.assertLessEqual(mark_down, 120)
|
||||||
|
self.assertLessEqual(mark_up, 120)
|
||||||
|
# start-up stagger window is the smallest interval in use (fastinter):
|
||||||
|
# 2s would recreate a whole-edge burst on every reload
|
||||||
|
self.assertGreaterEqual(fast, 5)
|
||||||
|
|
||||||
|
def test_no_per_server_timing_in_customer_templates(self):
|
||||||
|
tdir = os.path.join(MODULE_DIR, 'templates')
|
||||||
|
for name in sorted(os.listdir(tdir)):
|
||||||
|
if not name.endswith('.tpl') or name == 'hap_coraza_spoa_backend.tpl':
|
||||||
|
continue
|
||||||
|
with open(os.path.join(tdir, name)) as fh:
|
||||||
|
body = code(fh.read())
|
||||||
|
for line in body.splitlines():
|
||||||
|
if line.strip().startswith('server '):
|
||||||
|
self.assertNotRegex(line, r'\b(inter|fastinter|downinter)\b', name)
|
||||||
|
|
||||||
|
def test_coraza_spoa_keeps_fast_checks(self):
|
||||||
|
src = hm.template_env.get_template('hap_coraza_spoa_backend.tpl').render(agent_target='127.0.0.1:9000')
|
||||||
|
line = [l for l in code(src).splitlines() if l.strip().startswith('server coraza-spoa')]
|
||||||
|
self.assertEqual(len(line), 1)
|
||||||
|
for token in ('check', 'inter 2s', 'fastinter 2s', 'downinter 2s'):
|
||||||
|
self.assertIn(token, line[0])
|
||||||
|
|
||||||
|
def test_server_line_rendering_unchanged(self):
|
||||||
|
# the per-server options still come straight from WHP, untouched
|
||||||
|
out = hm.template_env.get_template('hap_backend.tpl').render(
|
||||||
|
name='x', servers=[{'server_name': 's', 'server_address': 'a',
|
||||||
|
'server_port': 443, 'server_options': 'check ssl verify none'}])
|
||||||
|
self.assertIn('server s a:443 check ssl verify none resolvers docker_dns init-addr last,libc,none', out)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main(verbosity=2)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""HAPROXY_NBTHREAD knob: parsing, rendering, and the unset-path invariant.
|
||||||
|
|
||||||
|
The invariant that matters: a host that does not set HAPROXY_NBTHREAD gets a
|
||||||
|
`global` section BYTE-IDENTICAL to what the image rendered before the knob
|
||||||
|
existed (HAProxy keeps choosing its own thread count). The real `haproxy -c`
|
||||||
|
of the `nbthread 1` shape is in scripts/validate-rendered-config.py.
|
||||||
|
|
||||||
|
python3 scripts/test-nbthread-knob.py
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
MODULE_DIR = os.path.abspath(
|
||||||
|
os.environ.get('HAPROXY_MANAGER_DIR',
|
||||||
|
os.path.join(os.path.dirname(os.path.abspath(__file__)), '..')))
|
||||||
|
sys.path.insert(0, MODULE_DIR)
|
||||||
|
import haproxy_manager as hm # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def render(**kw):
|
||||||
|
return hm.template_env.get_template('hap_header.tpl').render(
|
||||||
|
cluster_secret='s', syslog_target='/log.sock',
|
||||||
|
coraza_spoe_backend=kw.pop('coraza_spoe_backend', None), **kw)
|
||||||
|
|
||||||
|
|
||||||
|
class ParseNbthread(unittest.TestCase):
|
||||||
|
def test_unset_and_blank(self):
|
||||||
|
for raw in (None, '', ' '):
|
||||||
|
self.assertIsNone(hm.parse_nbthread(raw))
|
||||||
|
|
||||||
|
def test_valid(self):
|
||||||
|
self.assertEqual(hm.parse_nbthread('1'), 1)
|
||||||
|
self.assertEqual(hm.parse_nbthread(' 4\n'), 4)
|
||||||
|
self.assertEqual(hm.parse_nbthread('64'), 64)
|
||||||
|
|
||||||
|
def test_invalid_is_ignored_never_rendered(self):
|
||||||
|
for raw in ('0', '65', '-1', 'abc', '1.5', '1 2', '1;x', '١', '0x4', '+2'):
|
||||||
|
self.assertIsNone(hm.parse_nbthread(raw), raw)
|
||||||
|
|
||||||
|
|
||||||
|
class Render(unittest.TestCase):
|
||||||
|
def test_unset_has_no_nbthread_at_all(self):
|
||||||
|
for kw in ({}, {'nbthread': None}, {'nbthread': 0}, {'coraza_spoe_backend': 'x:1'}):
|
||||||
|
self.assertNotIn('nbthread', render(**kw).replace('{{', ''), kw)
|
||||||
|
|
||||||
|
def test_unset_is_byte_identical_to_template_without_the_block(self):
|
||||||
|
src_path = os.path.join(MODULE_DIR, 'templates', 'hap_header.tpl')
|
||||||
|
with open(src_path) as fh:
|
||||||
|
src = fh.read()
|
||||||
|
stripped, n = re.subn(r'\{%- if nbthread %\}.*?\{%- endif %\}\n', '', src, flags=re.S)
|
||||||
|
self.assertEqual(n, 1, 'expected exactly one nbthread block in hap_header.tpl')
|
||||||
|
legacy = hm.template_env.from_string(stripped)
|
||||||
|
for coraza in (None, 'x:1'):
|
||||||
|
want = legacy.render(cluster_secret='s', syslog_target='/log.sock',
|
||||||
|
coraza_spoe_backend=coraza)
|
||||||
|
self.assertEqual(render(coraza_spoe_backend=coraza), want)
|
||||||
|
self.assertEqual(render(coraza_spoe_backend=coraza, nbthread=None), want)
|
||||||
|
|
||||||
|
def test_set_renders_one_directive_in_global_only(self):
|
||||||
|
out = render(nbthread=1)
|
||||||
|
self.assertEqual(len(re.findall(r'^\s*nbthread 1$', out, re.M)), 1)
|
||||||
|
glob = out.split('\nresolvers ', 1)[0]
|
||||||
|
self.assertIn('\n nbthread 1\n', glob)
|
||||||
|
self.assertLess(out.index('nbthread 1'), out.index('tune.ssl.default-dh-param'))
|
||||||
|
# nothing else changed: removing the directive restores the unset render
|
||||||
|
self.assertEqual(out.replace('\n nbthread 1', '', 1).count('nbthread 1'), 0)
|
||||||
|
|
||||||
|
def test_no_cpu_map_or_thread_groups_rendered(self):
|
||||||
|
for kw in ({}, {'nbthread': 1}):
|
||||||
|
out = '\n'.join(l for l in render(**kw).splitlines()
|
||||||
|
if not l.lstrip().startswith('#'))
|
||||||
|
for bad in ('cpu-map', 'thread-groups', 'nbtgroups'):
|
||||||
|
self.assertNotIn(bad, out)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main(verbosity=2)
|
||||||
Executable
+43
@@ -0,0 +1,43 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Tests scripts/verify-image-arch.py against a stub `docker` (no daemon needed)."""
|
||||||
|
import os, stat, subprocess, sys, tempfile, textwrap
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
SCRIPT = os.path.join(HERE, "verify-image-arch.py")
|
||||||
|
fails = 0
|
||||||
|
|
||||||
|
def elf(machine):
|
||||||
|
return b"\x7fELF\x02\x01\x01" + b"\0" * 11 + machine.to_bytes(2, "little") + b"\0" * 40
|
||||||
|
|
||||||
|
def run(cfg_arch, file_arch, expect_rc, label, psutil_so=True):
|
||||||
|
global fails
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
stub = os.path.join(td, "docker")
|
||||||
|
with open(stub, "w") as f:
|
||||||
|
f.write(textwrap.dedent(f"""\
|
||||||
|
#!/usr/bin/env python3
|
||||||
|
import sys, os
|
||||||
|
a = sys.argv[1:]
|
||||||
|
E = {elf(file_arch)!r}
|
||||||
|
if a[0] == "image": print("{cfg_arch}")
|
||||||
|
elif a[0] == "create": print("cid1")
|
||||||
|
elif a[0] == "cp":
|
||||||
|
src, dst = a[-2], a[-1]
|
||||||
|
if src.endswith("/psutil"):
|
||||||
|
os.makedirs(dst)
|
||||||
|
if {psutil_so!r}: open(os.path.join(dst, "_psutil_linux.cpython-312.so"), "wb").write(E)
|
||||||
|
else: open(dst, "wb").write(E)
|
||||||
|
"""))
|
||||||
|
os.chmod(stub, os.stat(stub).st_mode | stat.S_IXUSR)
|
||||||
|
r = subprocess.run([sys.executable, "-I", SCRIPT, "ref@sha256:x", "arm64"],
|
||||||
|
env={"DOCKER": stub, "PATH": os.environ["PATH"]}, capture_output=True, text=True)
|
||||||
|
ok = r.returncode == expect_rc
|
||||||
|
print(("ok " if ok else "FAIL"), label, "rc=", r.returncode)
|
||||||
|
if not ok:
|
||||||
|
fails += 1; print(r.stdout, r.stderr)
|
||||||
|
|
||||||
|
run("arm64", 183, 0, "genuine arm64 passes")
|
||||||
|
run("arm64", 62, 1, "arm64-labelled x86-64 binaries (the 2026-11-19 bug) fail")
|
||||||
|
run("amd64", 183, 1, "wrong config architecture fails")
|
||||||
|
run("arm64", 183, 1, "missing compiled extension fails closed", psutil_so=False)
|
||||||
|
sys.exit(1 if fails else 0)
|
||||||
Executable
+193
@@ -0,0 +1,193 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Offline tests for scripts/verify-published-tags.sh (final publish gate).
|
||||||
|
|
||||||
|
CI run 5381 failed because buildx v0.28.0 ignores `--format '{{.Manifest.Digest}}'`
|
||||||
|
and prints the whole inspect text, while buildx 0.38 prints a bare digest. A stub
|
||||||
|
`imagetools` emulates BOTH output styles (plus `--raw`), so no registry or Docker
|
||||||
|
is needed. Held invariants:
|
||||||
|
- the 0.28-style (full text) and 0.38-style (bare digest) outputs both verify
|
||||||
|
- a reported digest that disagrees with the sha256 of the raw manifest fails
|
||||||
|
- a missing tag, a platform mismatch, or different digests across registries /
|
||||||
|
tags fail the job
|
||||||
|
- build-push.yaml's verify step uses the script, and release/* + rc-* tags
|
||||||
|
resolve to ONLY <version>-rc and <sha> (never latest)
|
||||||
|
|
||||||
|
Running: python3 scripts/test-verify-published-tags.py (needs jq)
|
||||||
|
"""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import stat
|
||||||
|
import subprocess
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
ROOT = os.path.dirname(HERE)
|
||||||
|
SCRIPT = os.path.join(HERE, 'verify-published-tags.sh')
|
||||||
|
WORKFLOW = os.path.join(ROOT, '.gitea', 'workflows', 'build-push.yaml')
|
||||||
|
|
||||||
|
STUB = r'''#!/usr/bin/env python3
|
||||||
|
import hashlib, json, os, sys
|
||||||
|
a = sys.argv[1:]
|
||||||
|
mode = os.environ['STUB_MODE'] # v028 | v038
|
||||||
|
table = json.load(open(os.environ['STUB_TABLE'])) # ref -> {"raw": str, "lie": optional digest}
|
||||||
|
assert a[0] == 'inspect'
|
||||||
|
ref = [x for x in a[1:] if not x.startswith('-') and not x.startswith('{{')][0]
|
||||||
|
ent = table.get(ref)
|
||||||
|
if ent is None:
|
||||||
|
sys.stderr.write('ERROR: %s: not found\n' % ref); sys.exit(1)
|
||||||
|
raw = ent['raw'].encode() + (b'\n' if ent.get('nl') else b'')
|
||||||
|
digest = ent.get('lie') or 'sha256:' + hashlib.sha256(ent['raw'].encode()).hexdigest()
|
||||||
|
if '--raw' in a:
|
||||||
|
sys.stdout.buffer.write(raw); sys.exit(0)
|
||||||
|
if '--format' in a:
|
||||||
|
if mode == 'v038':
|
||||||
|
print(digest)
|
||||||
|
else: # 0.28: --format ignored, whole text printed
|
||||||
|
print('Name: ' + ref); print('MediaType: application/vnd.oci.image.index.v1+json')
|
||||||
|
print('Digest: ' + digest)
|
||||||
|
sys.exit(0)
|
||||||
|
print('Name: ' + ref)
|
||||||
|
print('MediaType: application/vnd.oci.image.index.v1+json')
|
||||||
|
print('Digest: ' + digest)
|
||||||
|
print(' ')
|
||||||
|
print('Manifests: ')
|
||||||
|
for m in json.loads(ent['raw'])['manifests']:
|
||||||
|
print(' Name: %s@%s' % (ref, m['digest']))
|
||||||
|
print(' Digest: sha256:' + 'f' * 64) # indented: must never be mistaken for the index digest
|
||||||
|
print(' Platform: %s/%s' % (m['platform']['os'], m['platform']['architecture']))
|
||||||
|
'''
|
||||||
|
|
||||||
|
|
||||||
|
def index(archs, salt=''):
|
||||||
|
ms = [{'mediaType': 'application/vnd.oci.image.manifest.v1+json',
|
||||||
|
'digest': 'sha256:' + hashlib.sha256((x + salt).encode()).hexdigest(), 'size': 1,
|
||||||
|
'platform': {'architecture': x, 'os': 'linux'}} for x in archs]
|
||||||
|
ms.append({'mediaType': 'application/vnd.oci.image.manifest.v1+json',
|
||||||
|
'digest': 'sha256:' + '7' * 64, 'size': 1,
|
||||||
|
'platform': {'architecture': 'unknown', 'os': 'unknown'},
|
||||||
|
'annotations': {'vnd.docker.reference.type': 'attestation-manifest'}})
|
||||||
|
return json.dumps({'schemaVersion': 2, 'mediaType': 'application/vnd.oci.image.index.v1+json',
|
||||||
|
'manifests': ms}, separators=(',', ':'))
|
||||||
|
|
||||||
|
|
||||||
|
REPOS = ['reg.one/a/img', 'reg.two/b/img']
|
||||||
|
TAGS = ['1.2-rc', 'abc123']
|
||||||
|
|
||||||
|
|
||||||
|
class VerifyTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.stub = os.path.join(self.tmp.name, 'stub')
|
||||||
|
open(self.stub, 'w').write(STUB)
|
||||||
|
os.chmod(self.stub, os.stat(self.stub).st_mode | stat.S_IEXEC)
|
||||||
|
self.table = os.path.join(self.tmp.name, 'table.json')
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def table_for(self, raw, **over):
|
||||||
|
t = {'%s:%s' % (r, g): {'raw': raw} for r in REPOS for g in TAGS}
|
||||||
|
for k, v in over.items():
|
||||||
|
ref = k.replace('__', ':').replace('_', '/', 0)
|
||||||
|
t[ref] = v
|
||||||
|
return t
|
||||||
|
|
||||||
|
def run_script(self, table, mode, platforms='linux/amd64,linux/arm64', tags=TAGS):
|
||||||
|
json.dump(table, open(self.table, 'w'))
|
||||||
|
args = [SCRIPT, '--platforms', platforms]
|
||||||
|
for r in REPOS:
|
||||||
|
args += ['--repo', r]
|
||||||
|
for t in tags:
|
||||||
|
args += ['--tag', t]
|
||||||
|
env = dict(os.environ, IMAGETOOLS=self.stub, STUB_MODE=mode, STUB_TABLE=self.table)
|
||||||
|
return subprocess.run(args, env=env, capture_output=True, text=True, timeout=60)
|
||||||
|
|
||||||
|
def test_buildx_028_full_text_output_verifies(self):
|
||||||
|
r = self.run_script(self.table_for(index(['amd64', 'arm64'])), 'v028')
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
self.assertIn('verified:', r.stdout)
|
||||||
|
self.assertNotIn('bad digest', r.stdout)
|
||||||
|
|
||||||
|
def test_buildx_038_bare_digest_output_verifies(self):
|
||||||
|
r = self.run_script(self.table_for(index(['amd64', 'arm64'])), 'v038')
|
||||||
|
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
|
||||||
|
|
||||||
|
def test_trailing_newline_on_raw_output_tolerated(self):
|
||||||
|
raw = index(['amd64', 'arm64'])
|
||||||
|
t = {'%s:%s' % (r, g): {'raw': raw, 'nl': True} for r in REPOS for g in TAGS}
|
||||||
|
self.assertEqual(self.run_script(t, 'v028').returncode, 0)
|
||||||
|
|
||||||
|
def test_amd64_only_publish_matches_platforms(self):
|
||||||
|
raw = index(['amd64'])
|
||||||
|
self.assertEqual(self.run_script(self.table_for(raw), 'v028', 'linux/amd64').returncode, 0)
|
||||||
|
r = self.run_script(self.table_for(raw), 'v028', 'linux/amd64,linux/arm64')
|
||||||
|
self.assertEqual(r.returncode, 1)
|
||||||
|
self.assertIn('platform mismatch', r.stdout)
|
||||||
|
|
||||||
|
def test_missing_tag_fails(self):
|
||||||
|
t = self.table_for(index(['amd64', 'arm64']))
|
||||||
|
del t['reg.two/b/img:abc123']
|
||||||
|
r = self.run_script(t, 'v038')
|
||||||
|
self.assertEqual(r.returncode, 1)
|
||||||
|
self.assertIn('MISSING', r.stdout)
|
||||||
|
|
||||||
|
def test_different_digest_across_registries_fails(self):
|
||||||
|
t = self.table_for(index(['amd64', 'arm64']))
|
||||||
|
t['reg.two/b/img:1.2-rc'] = {'raw': index(['amd64', 'arm64'], salt='other')}
|
||||||
|
for mode in ('v028', 'v038'):
|
||||||
|
r = self.run_script(t, mode)
|
||||||
|
self.assertEqual(r.returncode, 1, mode)
|
||||||
|
self.assertIn('digest mismatch', r.stdout)
|
||||||
|
|
||||||
|
def test_reported_digest_disagreeing_with_raw_manifest_fails(self):
|
||||||
|
t = self.table_for(index(['amd64', 'arm64']))
|
||||||
|
t['reg.one/a/img:1.2-rc']['lie'] = 'sha256:' + '0' * 64
|
||||||
|
for mode in ('v028', 'v038'):
|
||||||
|
r = self.run_script(t, mode)
|
||||||
|
self.assertEqual(r.returncode, 1, mode)
|
||||||
|
self.assertIn('cross-check FAILED', r.stdout)
|
||||||
|
|
||||||
|
def test_garbage_manifest_fails(self):
|
||||||
|
t = self.table_for('not json')
|
||||||
|
self.assertEqual(self.run_script(t, 'v038').returncode, 1)
|
||||||
|
|
||||||
|
|
||||||
|
class WorkflowTest(unittest.TestCase):
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
import yaml
|
||||||
|
cls.src = open(WORKFLOW).read()
|
||||||
|
cls.doc = yaml.safe_load(cls.src)
|
||||||
|
cls.steps = cls.doc['jobs']['Build-and-Push']['steps']
|
||||||
|
|
||||||
|
def step(self, name):
|
||||||
|
return [s for s in self.steps if s.get('name') == name][0]
|
||||||
|
|
||||||
|
def test_verify_step_uses_script_not_format_digest(self):
|
||||||
|
run = self.step('Verify published tags in every registry')['run']
|
||||||
|
self.assertIn('scripts/verify-published-tags.sh', run)
|
||||||
|
self.assertNotIn('{{.Manifest.Digest}}', run)
|
||||||
|
|
||||||
|
def test_run_blocks_are_valid_bash(self):
|
||||||
|
for s in self.steps:
|
||||||
|
if 'run' in s:
|
||||||
|
p = subprocess.run(['bash', '-n'], input=s['run'], text=True, capture_output=True)
|
||||||
|
self.assertEqual(p.returncode, 0, '%s: %s' % (s.get('name'), p.stderr))
|
||||||
|
|
||||||
|
def test_release_and_rc_never_publish_latest(self):
|
||||||
|
run = self.step('Resolve tags')['run']
|
||||||
|
m = re.search(r'refs/heads/release/\*\|refs/tags/rc-\*\)\s*\n\s*tags="([^"]*)"', run)
|
||||||
|
self.assertIsNotNone(m)
|
||||||
|
self.assertEqual(m.group(1), '${VERSION}-rc ${SHA}')
|
||||||
|
main = re.search(r'refs/heads/main\)\s*\n\s*tags="([^"]*)"', run)
|
||||||
|
self.assertIsNotNone(main)
|
||||||
|
self.assertEqual(main.group(1), 'latest ${VERSION} ${SHA}')
|
||||||
|
# latest appears in no other tag assignment
|
||||||
|
self.assertEqual(len(re.findall(r'tags="[^"]*latest', run)), 1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""BEHAVIOURAL test of the wp-admin edge gate against the REAL haproxy binary.
|
||||||
|
|
||||||
|
test-wpadmin-gate.py asserts on the TEXT of the rendered config. This file runs
|
||||||
|
the actual gate rules (extracted from the rendered hap_listener.tpl, not
|
||||||
|
re-typed) in a real haproxy and sends real requests, so the install-screen
|
||||||
|
exemption and its path-normalisation edge cases are measured, not inferred.
|
||||||
|
|
||||||
|
Only the exclusion ACLs that depend on the client address (is_local,
|
||||||
|
is_trusted_ip, is_whitelisted) are stubbed to never match: the test client is
|
||||||
|
127.0.0.1, which the real is_local would exempt wholesale. Everything else
|
||||||
|
(normalize-uri chain, wp_admin_* ACLs, deny rules, set-var, redirect) is the
|
||||||
|
production text.
|
||||||
|
|
||||||
|
A request that PASSES the gate gets 200 "ok" from a stub `http-request return`;
|
||||||
|
a gated one gets the edge 302 (Location: .../wp-login.php?redirect_to=...) or
|
||||||
|
the 403 deny.
|
||||||
|
|
||||||
|
Skips (exit 0, loud message) when no `haproxy` binary is on PATH. The Dockerfile
|
||||||
|
build has one, so the image build always runs it.
|
||||||
|
|
||||||
|
python3 scripts/test-wpadmin-gate-behaviour.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import socket
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
sys.path.insert(0, HERE)
|
||||||
|
os.environ.setdefault('HAPROXY_MANAGER_DIR', os.path.abspath(os.path.join(HERE, '..')))
|
||||||
|
|
||||||
|
import importlib.util # noqa: E402
|
||||||
|
|
||||||
|
_spec = importlib.util.spec_from_file_location(
|
||||||
|
'wpadmin_gate_tests', os.path.join(HERE, 'test-wpadmin-gate.py'))
|
||||||
|
gate = importlib.util.module_from_spec(_spec)
|
||||||
|
_spec.loader.exec_module(gate)
|
||||||
|
|
||||||
|
HAPROXY = shutil.which('haproxy')
|
||||||
|
|
||||||
|
# Code lines (comment-stripped) that make up the gate, in template order.
|
||||||
|
_KEEP = re.compile(
|
||||||
|
r'^(?:'
|
||||||
|
r'http-request normalize-uri '
|
||||||
|
r'|acl (?:has_wp_logged_in|wp_gate_exempt|wp_admin_\w+|path_has_encoded_sep) '
|
||||||
|
r'|http-request deny deny_status 403 if wp_admin'
|
||||||
|
r'|http-request set-var\(txn\.wp_login_url\) '
|
||||||
|
r'|http-request redirect code 302 location %\[var\(txn\.wp_login_url\)\]'
|
||||||
|
r')')
|
||||||
|
|
||||||
|
# (description, raw request path, extra header, expected status, location-prefix)
|
||||||
|
PASS, REDIR, DENY = 200, 302, 403
|
||||||
|
LOGIN = '/wp-login.php?redirect_to='
|
||||||
|
|
||||||
|
CASES = [
|
||||||
|
# --- the install/setup screens: exempt ------------------------------
|
||||||
|
('setup-config.php', '/wp-admin/setup-config.php', None, PASS, None),
|
||||||
|
('setup-config.php language step', '/wp-admin/setup-config.php?step=-1', None, PASS, None),
|
||||||
|
('install.php', '/wp-admin/install.php', None, PASS, None),
|
||||||
|
('install.php step 2', '/wp-admin/install.php?step=2', None, PASS, None),
|
||||||
|
('subdirectory install', '/blog/wp-admin/install.php', None, PASS, None),
|
||||||
|
('subdirectory setup-config', '/blog/wp-admin/setup-config.php', None, PASS, None),
|
||||||
|
# spellings that NORMALISE to the exempt path are the same request to the backend
|
||||||
|
('dotdot normalises to the exempt page', '/wp-admin/css/../setup-config.php', None, PASS, None),
|
||||||
|
('encoded dot normalises to the exempt page', '/wp-admin/setup-config%2Ephp', None, PASS, None),
|
||||||
|
('double slash merges to the exempt page', '//wp-admin/install.php', None, PASS, None),
|
||||||
|
# --- everything near them stays gated -------------------------------
|
||||||
|
('dashboard', '/wp-admin/', None, REDIR, LOGIN + '%2Fwp-admin%2F'),
|
||||||
|
('index.php', '/wp-admin/index.php', None, REDIR, LOGIN),
|
||||||
|
('upgrade.php is NOT exempt', '/wp-admin/upgrade.php', None, REDIR, LOGIN),
|
||||||
|
('plugins.php', '/wp-admin/plugins.php', None, REDIR, LOGIN),
|
||||||
|
('setup-config.php.php', '/wp-admin/setup-config.php.php', None, REDIR, LOGIN),
|
||||||
|
('setup-config.phpx', '/wp-admin/setup-config.phpx', None, REDIR, LOGIN),
|
||||||
|
('install.php.bak', '/wp-admin/install.php.bak', None, REDIR, LOGIN),
|
||||||
|
('case variant Setup-Config.php', '/wp-admin/Setup-Config.php', None, REDIR, LOGIN),
|
||||||
|
('case variant Install.php', '/wp-admin/Install.php', None, REDIR, LOGIN),
|
||||||
|
('upper-case dir WP-ADMIN', '/WP-ADMIN/install.php', None, REDIR, LOGIN),
|
||||||
|
('path info after the script', '/wp-admin/install.php/x', None, REDIR, LOGIN),
|
||||||
|
('trailing slash', '/wp-admin/install.php/', None, REDIR, LOGIN),
|
||||||
|
('inserted directory', '/wp-admin/evil/install.php', None, REDIR, LOGIN),
|
||||||
|
('inserted directory (setup-config)', '/wp-admin/x/setup-config.php', None, REDIR, LOGIN),
|
||||||
|
('dotdot climbs off the exempt page', '/wp-admin/install.php/../plugins.php', None, REDIR, LOGIN),
|
||||||
|
('asset dir dotdot to plugins.php', '/wp-admin/css/../plugins.php', None, REDIR, LOGIN),
|
||||||
|
('encoded slash separator', '/wp-admin%2Fsetup-config.php', None, DENY, None),
|
||||||
|
('encoded slash before wp-admin', '/blog%2Fwp-admin/install.php', None, DENY, None),
|
||||||
|
('backslash prefix (open redirect guard)', '/%5Cevil.example/wp-admin/plugins.php', None, DENY, None),
|
||||||
|
# --- identity still passes ------------------------------------------
|
||||||
|
('logged-in cookie on plugins.php', '/wp-admin/plugins.php',
|
||||||
|
'Cookie: wordpress_logged_in_abc=1', PASS, None),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _free_port():
|
||||||
|
s = socket.socket()
|
||||||
|
s.bind(('127.0.0.1', 0))
|
||||||
|
port = s.getsockname()[1]
|
||||||
|
s.close()
|
||||||
|
return port
|
||||||
|
|
||||||
|
|
||||||
|
def _raw_get(port, path, header=None):
|
||||||
|
req = 'GET %s HTTP/1.1\r\nHost: site.example.com\r\nConnection: close\r\n' % path
|
||||||
|
if header:
|
||||||
|
req += header + '\r\n'
|
||||||
|
req += '\r\n'
|
||||||
|
with socket.create_connection(('127.0.0.1', port), timeout=5) as s:
|
||||||
|
s.sendall(req.encode('latin-1'))
|
||||||
|
buf = b''
|
||||||
|
while True:
|
||||||
|
chunk = s.recv(4096)
|
||||||
|
if not chunk:
|
||||||
|
break
|
||||||
|
buf += chunk
|
||||||
|
head = buf.split(b'\r\n\r\n', 1)[0].decode('latin-1')
|
||||||
|
lines = head.split('\r\n')
|
||||||
|
status = int(lines[0].split()[1])
|
||||||
|
loc = None
|
||||||
|
for ln in lines[1:]:
|
||||||
|
if ln.lower().startswith('location:'):
|
||||||
|
loc = ln.split(':', 1)[1].strip()
|
||||||
|
return status, loc
|
||||||
|
|
||||||
|
|
||||||
|
@unittest.skipUnless(HAPROXY, 'SKIP: no haproxy binary on PATH (the image build has one)')
|
||||||
|
class WpAdminGateBehaviour(unittest.TestCase):
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def setUpClass(cls):
|
||||||
|
cfg = gate.render_listener()
|
||||||
|
lines = []
|
||||||
|
for raw in cfg.split('\n'):
|
||||||
|
stripped = raw.strip()
|
||||||
|
if not stripped or stripped.startswith('#'):
|
||||||
|
continue
|
||||||
|
code = stripped.split(' #', 1)[0].rstrip()
|
||||||
|
if _KEEP.match(code):
|
||||||
|
lines.append(code)
|
||||||
|
joined = '\n'.join(lines)
|
||||||
|
# Guard against a silently empty extraction: every moving part must be there.
|
||||||
|
for needle in ('normalize-uri path-strip-dotdot full', 'acl wp_admin_install',
|
||||||
|
'acl wp_admin_allowed', 'acl wp_admin_asset', 'acl wp_gate_exempt',
|
||||||
|
'acl has_wp_logged_in', 'acl path_has_encoded_sep',
|
||||||
|
'set-var(txn.wp_login_url)', 'http-request redirect code 302'):
|
||||||
|
assert needle in joined, 'extraction lost %r' % needle
|
||||||
|
|
||||||
|
cls.tmp = tempfile.mkdtemp(prefix='wpgate-behaviour-')
|
||||||
|
exempt = os.path.join(cls.tmp, 'exempt.list')
|
||||||
|
open(exempt, 'w').close()
|
||||||
|
joined = joined.replace('/etc/haproxy/wpadmin_gate_exempt.list', exempt)
|
||||||
|
cls.port = _free_port()
|
||||||
|
conf = '\n'.join([
|
||||||
|
'global',
|
||||||
|
' expose-experimental-directives',
|
||||||
|
' maxconn 100',
|
||||||
|
'defaults',
|
||||||
|
' mode http',
|
||||||
|
' timeout connect 2s',
|
||||||
|
' timeout client 5s',
|
||||||
|
' timeout server 5s',
|
||||||
|
'frontend gate',
|
||||||
|
' bind 127.0.0.1:%d' % cls.port,
|
||||||
|
# client-address exclusions stubbed: the real is_local would match 127.0.0.1
|
||||||
|
' acl is_local src 203.0.113.1',
|
||||||
|
' acl is_trusted_ip src 203.0.113.2',
|
||||||
|
' acl is_whitelisted src 203.0.113.3',
|
||||||
|
' ' + joined.replace('\n', '\n '),
|
||||||
|
' http-request return status 200 content-type text/plain string ok',
|
||||||
|
'',
|
||||||
|
])
|
||||||
|
cls.conf_path = os.path.join(cls.tmp, 'gate.cfg')
|
||||||
|
with open(cls.conf_path, 'w') as f:
|
||||||
|
f.write(conf)
|
||||||
|
chk = subprocess.run([HAPROXY, '-c', '-f', cls.conf_path],
|
||||||
|
capture_output=True, text=True)
|
||||||
|
assert chk.returncode == 0, 'haproxy -c rejected the gate:\n' + chk.stdout + chk.stderr
|
||||||
|
cls.proc = subprocess.Popen([HAPROXY, '-db', '-f', cls.conf_path],
|
||||||
|
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||||
|
for _ in range(50):
|
||||||
|
try:
|
||||||
|
socket.create_connection(('127.0.0.1', cls.port), timeout=0.2).close()
|
||||||
|
break
|
||||||
|
except OSError:
|
||||||
|
time.sleep(0.1)
|
||||||
|
else:
|
||||||
|
raise AssertionError('haproxy did not start listening')
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def tearDownClass(cls):
|
||||||
|
proc = getattr(cls, 'proc', None)
|
||||||
|
if proc:
|
||||||
|
proc.terminate()
|
||||||
|
try:
|
||||||
|
proc.wait(timeout=5)
|
||||||
|
except subprocess.TimeoutExpired:
|
||||||
|
proc.kill()
|
||||||
|
shutil.rmtree(getattr(cls, 'tmp', ''), ignore_errors=True)
|
||||||
|
|
||||||
|
def test_cases(self):
|
||||||
|
for desc, path, header, want, loc_prefix in CASES:
|
||||||
|
with self.subTest(desc=desc, path=path):
|
||||||
|
status, loc = _raw_get(self.port, path, header)
|
||||||
|
self.assertEqual(status, want, '%s: %s -> %s %s' % (desc, path, status, loc))
|
||||||
|
if loc_prefix is not None:
|
||||||
|
self.assertIsNotNone(loc, 'no Location header for ' + path)
|
||||||
|
self.assertTrue(loc.endswith(loc_prefix) or loc_prefix in loc,
|
||||||
|
'%s: Location %r' % (path, loc))
|
||||||
|
# redirect must stay same-origin (open-redirect guard)
|
||||||
|
self.assertTrue(loc.startswith('/') and not loc.startswith('//'), loc)
|
||||||
|
|
||||||
|
def test_nul_byte_after_exempt_name_is_not_exempt(self):
|
||||||
|
"""%00 is not an unreserved escape, so it is not decoded and the path no
|
||||||
|
longer ends in the exempt name. Anything but a pass-through is fine
|
||||||
|
(gated 302, or haproxy refusing the request)."""
|
||||||
|
status, _ = _raw_get(self.port, '/wp-admin/setup-config.php%00')
|
||||||
|
self.assertNotEqual(status, PASS)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main(verbosity=2)
|
||||||
@@ -59,7 +59,7 @@ import haproxy_manager # noqa: E402
|
|||||||
|
|
||||||
ALLOWLIST = ('/admin-ajax.php', '/admin-post.php',
|
ALLOWLIST = ('/admin-ajax.php', '/admin-post.php',
|
||||||
'/load-styles.php', '/load-scripts.php')
|
'/load-styles.php', '/load-scripts.php')
|
||||||
EXCLUSIONS = ('!wp_admin_allowed', '!wp_admin_asset', '!has_wp_logged_in',
|
EXCLUSIONS = ('!wp_admin_allowed', '!wp_admin_install', '!wp_admin_asset', '!has_wp_logged_in',
|
||||||
'!wp_gate_exempt', '!is_local', '!is_trusted_ip', '!is_whitelisted')
|
'!wp_gate_exempt', '!is_local', '!is_trusted_ip', '!is_whitelisted')
|
||||||
|
|
||||||
# The normalizer set, in the order it MUST render. Decoding has to precede the
|
# The normalizer set, in the order it MUST render. Decoding has to precede the
|
||||||
@@ -220,10 +220,23 @@ class WpAdminGate(unittest.TestCase):
|
|||||||
line = require_rule(self.cfg, 'acl wp_admin_asset', 'wp_admin_asset ACL')
|
line = require_rule(self.cfg, 'acl wp_admin_asset', 'wp_admin_asset ACL')
|
||||||
self.assertRegex(line, r'path_reg.*\(css\|js\|images\)')
|
self.assertRegex(line, r'path_reg.*\(css\|js\|images\)')
|
||||||
|
|
||||||
def test_install_php_is_NOT_allowlisted(self):
|
def test_install_php_is_not_in_the_ajax_allowlist(self):
|
||||||
"""install.php is deliberately gated -- a takeover vector on abandoned installs."""
|
"""install.php / setup-config.php live in their OWN ACL (wp_admin_install),
|
||||||
|
not in wp_admin_allowed, so the admin-ajax/asset allowlist stays minimal."""
|
||||||
line = require_rule(self.cfg, 'acl wp_admin_allowed', 'wp_admin_allowed ACL')
|
line = require_rule(self.cfg, 'acl wp_admin_allowed', 'wp_admin_allowed ACL')
|
||||||
self.assertNotIn('install.php', line)
|
self.assertNotIn('install.php', line)
|
||||||
|
self.assertNotIn('setup-config.php', line)
|
||||||
|
|
||||||
|
def test_install_screens_exempt_exactly_two_anchored_paths(self):
|
||||||
|
"""A fresh WordPress redirects every request to /wp-admin/setup-config.php
|
||||||
|
and a manual installer has no cookie. Exactly these two pages are exempt,
|
||||||
|
each anchored to /wp-admin/<file> (path_end, no regex, no wildcard).
|
||||||
|
upgrade.php is deliberately NOT exempt (logged-in only)."""
|
||||||
|
line = require_rule(self.cfg, 'acl wp_admin_install', 'wp_admin_install ACL')
|
||||||
|
self.assertEqual(line.split(None, 3)[2], 'path_end')
|
||||||
|
entries = line.split()[3:]
|
||||||
|
self.assertEqual(sorted(entries),
|
||||||
|
['/wp-admin/install.php', '/wp-admin/setup-config.php'])
|
||||||
|
|
||||||
def test_redirect_rule_has_all_exclusions(self):
|
def test_redirect_rule_has_all_exclusions(self):
|
||||||
rule = require_rule_by_predicate(
|
rule = require_rule_by_predicate(
|
||||||
|
|||||||
@@ -146,6 +146,17 @@ SCENARIOS = (
|
|||||||
'HAPROXY_CORAZA_SPOE_BACKEND': '127.0.0.1:9000',
|
'HAPROXY_CORAZA_SPOE_BACKEND': '127.0.0.1:9000',
|
||||||
'HAPROXY_DEFAULT_SPLASH': 'off',
|
'HAPROXY_DEFAULT_SPLASH': 'off',
|
||||||
}),
|
}),
|
||||||
|
# Per-host thread count knob: `nbthread 1` must parse next to everything
|
||||||
|
# else rendered (limited-quic, QUIC bind, SPOE, stats-file). A bad value
|
||||||
|
# must be IGNORED (not rendered), never reach haproxy.
|
||||||
|
('nbthread-1', {
|
||||||
|
'HAPROXY_SUSPENSION_ENABLED': 'true',
|
||||||
|
'HAPROXY_CORAZA_SPOE_BACKEND': '127.0.0.1:9000',
|
||||||
|
'HAPROXY_NBTHREAD': '1',
|
||||||
|
}),
|
||||||
|
('nbthread-bad', {
|
||||||
|
'HAPROXY_NBTHREAD': 'abc',
|
||||||
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -308,7 +319,7 @@ def render(scenario_name, env_overrides, workdir):
|
|||||||
|
|
||||||
saved_env = {}
|
saved_env = {}
|
||||||
for key in ('HAPROXY_SUSPENSION_ENABLED', 'HAPROXY_CORAZA_SPOE_BACKEND',
|
for key in ('HAPROXY_SUSPENSION_ENABLED', 'HAPROXY_CORAZA_SPOE_BACKEND',
|
||||||
'HAPROXY_DEFAULT_SPLASH'):
|
'HAPROXY_DEFAULT_SPLASH', 'HAPROXY_NBTHREAD'):
|
||||||
saved_env[key] = os.environ.pop(key, None)
|
saved_env[key] = os.environ.pop(key, None)
|
||||||
os.environ.update(env_overrides)
|
os.environ.update(env_overrides)
|
||||||
|
|
||||||
@@ -342,6 +353,12 @@ def assert_scenario_branches(scenario_name, config_path, env_overrides):
|
|||||||
'HAPROXY_CORAZA_SPOE_BACKEND' in env_overrides),
|
'HAPROXY_CORAZA_SPOE_BACKEND' in env_overrides),
|
||||||
'splash': ('file /haproxy/errors/default-splash.html',
|
'splash': ('file /haproxy/errors/default-splash.html',
|
||||||
env_overrides.get('HAPROXY_DEFAULT_SPLASH') != 'off'),
|
env_overrides.get('HAPROXY_DEFAULT_SPLASH') != 'off'),
|
||||||
|
'nbthread': ('\n nbthread 1\n',
|
||||||
|
env_overrides.get('HAPROXY_NBTHREAD') == '1'),
|
||||||
|
# Health-check timing is unconditional: every scenario carries it.
|
||||||
|
'check-timing': ('\n default-server inter 30s fastinter 10s '
|
||||||
|
'downinter 30s rise 2 fall 3\n', True),
|
||||||
|
'spread-checks': ('\n spread-checks 50\n', True),
|
||||||
}
|
}
|
||||||
for label, (needle, should_be_present) in expected.items():
|
for label, (needle, should_be_present) in expected.items():
|
||||||
present = needle in text
|
present = needle in text
|
||||||
|
|||||||
Executable
+93
@@ -0,0 +1,93 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Verify that a per-platform image really contains binaries for that platform.
|
||||||
|
|
||||||
|
CI only (not copied into images' runtime use). Usage:
|
||||||
|
|
||||||
|
verify-image-arch.py <image-ref> <amd64|arm64>
|
||||||
|
|
||||||
|
Pulls <image-ref> (normally <repo>@sha256:<digest> of ONE platform, pushed by
|
||||||
|
digest and not yet tagged) with --platform linux/<arch>, never runs it, and
|
||||||
|
checks:
|
||||||
|
* the image config's architecture equals <arch>;
|
||||||
|
* the ELF e_machine of haproxy, bash, the python interpreter and every
|
||||||
|
compiled extension of the python stack (psutil *.so) equals <arch>.
|
||||||
|
|
||||||
|
Why: 2026-11-19, haproxy-manager-base:latest carried an "arm64" entry whose
|
||||||
|
binaries were all x86-64 (the in-house python:3.12-slim base was a flattened
|
||||||
|
amd64-only manifest, so the arm64 build silently ran on an amd64 base).
|
||||||
|
Manifest/config metadata said arm64; only the ELF headers told the truth.
|
||||||
|
|
||||||
|
Exit 0 = every checked file matches; non-zero = mismatch or could not check
|
||||||
|
(fail closed). Env DOCKER overrides the docker command (tests use a stub).
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import shlex
|
||||||
|
import struct
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
|
||||||
|
EM = {"amd64": 62, "arm64": 183} # EM_X86_64, EM_AARCH64
|
||||||
|
EM_NAME = {62: "x86-64", 183: "aarch64", 40: "arm", 3: "i386"}
|
||||||
|
FILES = ["/usr/sbin/haproxy", "/bin/bash", "/usr/local/bin/python3.12"]
|
||||||
|
EXT_DIR = "/usr/local/lib/python3.12/site-packages/psutil" # compiled (_psutil_linux*.so)
|
||||||
|
|
||||||
|
|
||||||
|
def elf_machine(path):
|
||||||
|
"""e_machine of an ELF file, or None if it is not a little-endian ELF."""
|
||||||
|
with open(path, "rb") as f:
|
||||||
|
h = f.read(20)
|
||||||
|
if len(h) < 20 or h[:4] != b"\x7fELF":
|
||||||
|
return None
|
||||||
|
endian = "<" if h[5] == 1 else ">"
|
||||||
|
return struct.unpack(endian + "H", h[18:20])[0]
|
||||||
|
|
||||||
|
|
||||||
|
def docker(*args, check=True):
|
||||||
|
cmd = shlex.split(os.environ.get("DOCKER", "docker")) + list(args)
|
||||||
|
return subprocess.run(cmd, check=check, capture_output=True, text=True)
|
||||||
|
|
||||||
|
|
||||||
|
def main(argv):
|
||||||
|
if len(argv) != 3 or argv[2] not in EM:
|
||||||
|
print("usage: verify-image-arch.py <image-ref> <amd64|arm64>", file=sys.stderr)
|
||||||
|
return 2
|
||||||
|
ref, arch = argv[1], argv[2]
|
||||||
|
want = EM[arch]
|
||||||
|
bad = []
|
||||||
|
docker("pull", "--quiet", "--platform", f"linux/{arch}", ref)
|
||||||
|
cfg = docker("image", "inspect", ref, "--format", "{{.Architecture}}").stdout.strip()
|
||||||
|
print(f"{ref}: image config architecture={cfg} (expected {arch})")
|
||||||
|
if cfg != arch:
|
||||||
|
bad.append(f"config architecture {cfg!r}")
|
||||||
|
cid = docker("create", "--platform", f"linux/{arch}", ref).stdout.strip()
|
||||||
|
try:
|
||||||
|
with tempfile.TemporaryDirectory() as td:
|
||||||
|
for f in FILES:
|
||||||
|
dst = os.path.join(td, os.path.basename(f))
|
||||||
|
docker("cp", "-L", f"{cid}:{f}", dst)
|
||||||
|
m = elf_machine(dst)
|
||||||
|
print(f" {f}: {EM_NAME.get(m, m)}")
|
||||||
|
if m != want:
|
||||||
|
bad.append(f"{f} is {EM_NAME.get(m, m)}")
|
||||||
|
extdir = os.path.join(td, "psutil")
|
||||||
|
docker("cp", f"{cid}:{EXT_DIR}", extdir)
|
||||||
|
sos = sorted(os.path.join(extdir, n) for n in os.listdir(extdir) if n.endswith(".so"))
|
||||||
|
if not sos:
|
||||||
|
bad.append(f"no compiled extension found in {EXT_DIR}")
|
||||||
|
for so in sos:
|
||||||
|
m = elf_machine(so)
|
||||||
|
print(f" psutil/{os.path.basename(so)}: {EM_NAME.get(m, m)}")
|
||||||
|
if m != want:
|
||||||
|
bad.append(f"psutil/{os.path.basename(so)} is {EM_NAME.get(m, m)}")
|
||||||
|
finally:
|
||||||
|
docker("rm", cid, check=False)
|
||||||
|
if bad:
|
||||||
|
print(f"::error::{ref} is labelled linux/{arch} but: " + "; ".join(bad), file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
print(f"OK: {ref} is genuinely {arch}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
sys.exit(main(sys.argv))
|
||||||
Executable
+97
@@ -0,0 +1,97 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Final publish gate: every <repo>:<tag> must resolve, carry exactly the
|
||||||
|
# platforms the assemble step reported, and have ONE index digest across all
|
||||||
|
# tags and all registries. Any miss or mismatch exits 1.
|
||||||
|
#
|
||||||
|
# verify-published-tags.sh --platforms linux/amd64,linux/arm64 \
|
||||||
|
# --repo <registry/path> [--repo ...] --tag <tag> [--tag ...]
|
||||||
|
#
|
||||||
|
# The index digest is computed in a buildx-VERSION-INDEPENDENT way. CI run 5381
|
||||||
|
# showed buildx v0.28.0 ignores `--format '{{.Manifest.Digest}}'` and prints the
|
||||||
|
# whole inspect text, while 0.38 prints a bare digest. So the digest comes from:
|
||||||
|
# 1. sha256 of the raw manifest bytes (`inspect --raw`) - always, authoritative
|
||||||
|
# (a content digest IS the sha256 of the manifest bytes);
|
||||||
|
# 2. the strictly anchored `Digest:` line of the default text output, if present;
|
||||||
|
# 3. the `--format '{{.Manifest.Digest}}'` output, ONLY if it is a bare digest
|
||||||
|
# (0.28's full-text output is ignored here, not an error).
|
||||||
|
# Every source that is available must agree, else the ref fails.
|
||||||
|
# Platforms are read from the raw JSON (also version independent).
|
||||||
|
#
|
||||||
|
# Env: IMAGETOOLS overrides the command (default "docker buildx imagetools");
|
||||||
|
# the CI step sets it to "$BUILDX imagetools"; the test suite uses a stub.
|
||||||
|
set -uo pipefail
|
||||||
|
|
||||||
|
IMAGETOOLS=${IMAGETOOLS:-docker buildx imagetools}
|
||||||
|
platforms=""; repos=(); tags=()
|
||||||
|
while [ $# -gt 0 ]; do
|
||||||
|
case "$1" in
|
||||||
|
--platforms) platforms=${2-}; shift 2 ;;
|
||||||
|
--repo) repos+=("${2-}"); shift 2 ;;
|
||||||
|
--tag) tags+=("${2-}"); shift 2 ;;
|
||||||
|
*) echo "verify-published-tags: unknown argument: $1" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
[ -n "$platforms" ] && [ ${#repos[@]} -gt 0 ] && [ ${#tags[@]} -gt 0 ] \
|
||||||
|
|| { echo "::error::verify-published-tags: --platforms, --repo and --tag are required"; exit 2; }
|
||||||
|
command -v jq >/dev/null || { echo "::error::verify-published-tags: jq is required"; exit 2; }
|
||||||
|
|
||||||
|
want=$(printf '%s' "$platforms" | tr ',' '\n' | sort | tr '\n' ' ')
|
||||||
|
work=$(mktemp -d); trap 'rm -rf "$work"' EXIT
|
||||||
|
digest_re='^sha256:[0-9a-f]{64}$'
|
||||||
|
ref_digest=""; ref_name=""; fail=0
|
||||||
|
|
||||||
|
for r in "${repos[@]}"; do
|
||||||
|
for t in "${tags[@]}"; do
|
||||||
|
ref="${r}:${t}"
|
||||||
|
raw="$work/raw"
|
||||||
|
if ! timeout 90 $IMAGETOOLS inspect --raw "$ref" >"$raw" 2>"$work/err" || [ ! -s "$raw" ]; then
|
||||||
|
echo "::error::MISSING or unreadable: ${ref}: $(head -c 300 "$work/err")"; fail=1; continue
|
||||||
|
fi
|
||||||
|
# Raw bytes as served, and with trailing newlines stripped (some buildx
|
||||||
|
# versions append one when printing); the content digest is one of the two.
|
||||||
|
h1="sha256:$(sha256sum <"$raw" | cut -d' ' -f1)"
|
||||||
|
h2="sha256:$(printf '%s' "$(cat "$raw")" | sha256sum | cut -d' ' -f1)"
|
||||||
|
|
||||||
|
# Source 2: strictly anchored top-level "Digest:" line of the text output.
|
||||||
|
textd=""
|
||||||
|
if timeout 90 $IMAGETOOLS inspect "$ref" >"$work/text" 2>/dev/null; then
|
||||||
|
mapfile -t lines < <(grep -E '^Digest:[[:space:]]+sha256:[0-9a-f]{64}[[:space:]]*$' "$work/text" | sed -E 's/^Digest:[[:space:]]+//; s/[[:space:]]+$//')
|
||||||
|
[ ${#lines[@]} -eq 1 ] && textd=${lines[0]}
|
||||||
|
fi
|
||||||
|
# Source 3: bare --format output, only when it really is a bare digest.
|
||||||
|
fmtd=""
|
||||||
|
if out=$(timeout 90 $IMAGETOOLS inspect "$ref" --format '{{.Manifest.Digest}}' 2>/dev/null); then
|
||||||
|
out=$(printf '%s' "$out" | tr -d '[:space:]')
|
||||||
|
[[ "$out" =~ $digest_re ]] && fmtd=$out
|
||||||
|
fi
|
||||||
|
|
||||||
|
d=""
|
||||||
|
for cand in "$textd" "$fmtd"; do
|
||||||
|
[ -n "$cand" ] || continue
|
||||||
|
if [ "$cand" != "$h1" ] && [ "$cand" != "$h2" ]; then
|
||||||
|
echo "::error::digest cross-check FAILED for ${ref}: reported ${cand}, raw manifest hashes to ${h1}"; fail=1; d="!"; break
|
||||||
|
fi
|
||||||
|
d=$cand
|
||||||
|
done
|
||||||
|
[ "$d" = "!" ] && continue
|
||||||
|
[ -n "$d" ] || d=$h2
|
||||||
|
[[ "$d" =~ $digest_re ]] || { echo "::error::bad digest for ${ref}: ${d}"; fail=1; continue; }
|
||||||
|
if [ -z "$textd$fmtd" ]; then
|
||||||
|
echo "::warning::no reported digest for ${ref}; using sha256 of the raw manifest"
|
||||||
|
fi
|
||||||
|
|
||||||
|
if ! got=$(jq -r '.manifests[]? | select(.platform.os != "unknown") | "\(.platform.os)/\(.platform.architecture)"' "$raw" 2>/dev/null | sort | tr '\n' ' '); then
|
||||||
|
echo "::error::unparseable manifest for ${ref}"; fail=1; continue
|
||||||
|
fi
|
||||||
|
if [ "$got" != "$want" ]; then
|
||||||
|
echo "::error::platform mismatch for ${ref}: have [${got}] want [${want}]"; fail=1
|
||||||
|
fi
|
||||||
|
echo "ok ${ref} ${d} [${got}]"
|
||||||
|
if [ -z "$ref_digest" ]; then ref_digest="$d"; ref_name="$ref"
|
||||||
|
elif [ "$d" != "$ref_digest" ]; then
|
||||||
|
echo "::error::digest mismatch: ${ref}=${d} vs ${ref_name}=${ref_digest}"; fail=1
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
done
|
||||||
|
[ "$fail" = 0 ] || { echo "::error::tag verification FAILED"; exit 1; }
|
||||||
|
echo "verified: ${tags[*]} in ${#repos[@]} registries, digest ${ref_digest}, platforms ${platforms}"
|
||||||
@@ -13,4 +13,4 @@ backend coraza-spoa-backend
|
|||||||
option spop-check
|
option spop-check
|
||||||
timeout connect 5s
|
timeout connect 5s
|
||||||
timeout server 30s
|
timeout server 30s
|
||||||
server coraza-spoa {{ agent_target }} check
|
server coraza-spoa {{ agent_target }} check inter 2s fastinter 2s downinter 2s rise 2 fall 3
|
||||||
@@ -40,6 +40,30 @@ global
|
|||||||
user haproxy
|
user haproxy
|
||||||
group haproxy
|
group haproxy
|
||||||
daemon
|
daemon
|
||||||
|
{%- if nbthread %}
|
||||||
|
|
||||||
|
# PER-HOST THREAD COUNT. Only emitted when HAPROXY_NBTHREAD is set on the
|
||||||
|
# container (WHP: /etc/whp/edge-nbthread -> lib-edge-container.sh -> docker run -e),
|
||||||
|
# so a host that does not set it renders byte-identically to before and
|
||||||
|
# HAProxy keeps choosing automatically (all CPUs in its affinity mask).
|
||||||
|
# Why a host would set 1: 2026-11-19 sdbees, thread 1 spun on a server
|
||||||
|
# lock held by a TLS health-check thread stalled in a page fault under
|
||||||
|
# memory pressure -> watchdog abort (whole edge down). With one thread
|
||||||
|
# there is no other lock holder, so the failure class cannot occur.
|
||||||
|
# Do NOT combine with cpu-map/thread-groups here: neither is rendered.
|
||||||
|
nbthread {{ nbthread }}
|
||||||
|
{%- endif %}
|
||||||
|
|
||||||
|
# Health-check jitter. Every `check` interval (default-server below) is
|
||||||
|
# randomised by +/- 50% so the hundreds of checks on a big edge drift
|
||||||
|
# apart instead of re-forming one burst per interval. The start-up offsets
|
||||||
|
# alone do NOT do this: HAProxy spreads the FIRST check of every server
|
||||||
|
# over the smallest interval in use, and a server that has not yet
|
||||||
|
# reached full health (every server after a start or reload) counts as
|
||||||
|
# `fastinter`, so the whole fleet starts inside a few seconds and would
|
||||||
|
# stay in lockstep with a fixed 30s period. 50 is the documented
|
||||||
|
# maximum (configuration.txt "spread-checks": 0..50 percent, default 0).
|
||||||
|
spread-checks 50
|
||||||
|
|
||||||
# SSL and Performance
|
# SSL and Performance
|
||||||
tune.ssl.default-dh-param 2048
|
tune.ssl.default-dh-param 2048
|
||||||
@@ -170,6 +194,29 @@ defaults
|
|||||||
timeout server 10m
|
timeout server 10m
|
||||||
timeout http-keep-alive 30s
|
timeout http-keep-alive 30s
|
||||||
timeout check 10s
|
timeout check 10s
|
||||||
|
|
||||||
|
# Backend health checks, set ONCE here for every `server ... check` line
|
||||||
|
# (WHP appends `check ssl verify none` per server; each check is a full
|
||||||
|
# TLS handshake, so on whp01 -- ~426 checked servers -- the old 2s default
|
||||||
|
# was ~200+ handshakes/s of pure health-check churn).
|
||||||
|
# inter 30s steady state: one check per server per ~30s (jittered
|
||||||
|
# 15-45s by `spread-checks` in global).
|
||||||
|
# fastinter 10s used while a server is transitioning (going down/up)
|
||||||
|
# AND for a server not yet at full health, i.e. every
|
||||||
|
# server after a start/reload. It also sizes the
|
||||||
|
# start-up stagger window (HAProxy spreads first checks
|
||||||
|
# over the smallest interval in use), so it is 10s, not
|
||||||
|
# 2s: 2s would put all first checks of a reload into a
|
||||||
|
# ~2s burst, the very churn this removes.
|
||||||
|
# downinter 30s a server already fully DOWN is re-tested at the same
|
||||||
|
# low rate.
|
||||||
|
# rise 2 fall 3 the HAProxy defaults, stated so they are pinned.
|
||||||
|
# A dead backend is marked DOWN in at most ~75s (first failing check
|
||||||
|
# <= 45s after it dies, then two more at fastinter, each <= 15s with the
|
||||||
|
# +50% jitter; ~50s typical); a recovered one is back UP in about the
|
||||||
|
# same (downinter <= 45s, then one more at fastinter). Servers without `check` are unaffected.
|
||||||
|
# The Coraza SPOA server sets its own fast timing (hap_coraza_spoa_backend.tpl).
|
||||||
|
default-server inter 30s fastinter 10s downinter 30s rise 2 fall 3
|
||||||
timeout tarpit 10s # Tarpit delay for low-level scanners (before silent-drop)
|
timeout tarpit 10s # Tarpit delay for low-level scanners (before silent-drop)
|
||||||
maxconn 3000
|
maxconn 3000
|
||||||
|
|
||||||
|
|||||||
@@ -431,11 +431,36 @@ frontend web
|
|||||||
# suffix matching (/blog/wp-admin/admin-ajax.php ends with
|
# suffix matching (/blog/wp-admin/admin-ajax.php ends with
|
||||||
# /wp-admin/admin-ajax.php) while rejecting an inserted directory.
|
# /wp-admin/admin-ajax.php) while rejecting an inserted directory.
|
||||||
#
|
#
|
||||||
# install.php is DELIBERATELY NOT allowlisted. It is legitimately
|
# The WordPress install/setup screens ARE exempt (wp_admin_install below):
|
||||||
# reachable without a cookie during a fresh install, but it is also a
|
# exactly /wp-admin/setup-config.php and /wp-admin/install.php. A fresh
|
||||||
# standing scanner target and a real takeover vector on a site that was
|
# WordPress with no wp-config.php redirects EVERY request to
|
||||||
# half-installed and then abandoned. Anyone genuinely installing uses the
|
# /wp-admin/setup-config.php, and a person doing a manual install has no
|
||||||
# per-site exempt-list opt-out below instead.
|
# cookie by definition -- gating those two pages bounced the installer to
|
||||||
|
# wp-login.php?redirect_to=/wp-admin/setup-config.php (a login form that
|
||||||
|
# can never succeed on a site with no database) and, worse, that URL then
|
||||||
|
# tripped CRS 930120 ("config.php" in ARGS:redirect_to) so the visitor saw
|
||||||
|
# the WAF block page instead of WordPress's own setup screen. WordPress
|
||||||
|
# itself refuses both once the site is installed (setup-config.php exits
|
||||||
|
# "wp-config.php already exists"; install.php shows "Already Installed"
|
||||||
|
# when the options table has siteurl), so the exemption exposes nothing on
|
||||||
|
# a finished site. RESIDUAL RISK (known tradeoff of exempting these two pages,
|
||||||
|
# requested 2026-11-19): (1) WordPress files present but NO wp-config.php
|
||||||
|
# (half upload, deleted by mistake, mid-restore/transfer): any visitor can
|
||||||
|
# run setup-config.php with their own database and then install.php, i.e.
|
||||||
|
# take the site over (admin -> plugin upload -> code execution). Scanners
|
||||||
|
# probe for exactly this. (2) A half-installed site (wp-config.php present,
|
||||||
|
# no tables, or a $table_prefix pointing at no tables) lets any visitor
|
||||||
|
# finish install.php?step=2 and choose the admin account. The old gate
|
||||||
|
# blocked cookieless scanners from both on edge-fronted sites (not a real
|
||||||
|
# defence: has_wp_logged_in only checks the cookie NAME, so a targeted
|
||||||
|
# attacker could always send one); WordPress itself never did.
|
||||||
|
# Matching is exact (path_end on the normalised path,
|
||||||
|
# case-sensitive): /wp-admin/setup-config.php.php, /wp-admin/Install.php,
|
||||||
|
# /wp-admin/install.php/x, /wp-admin/evil/install.php are all still gated.
|
||||||
|
# upgrade.php is NOT exempt: WordPress only sends logged-in users there
|
||||||
|
# (admin_init), and a logged-in user carries the cookie, so it needs no
|
||||||
|
# exemption. The install screens' CSS/JS come from the css|js|images dirs
|
||||||
|
# and load-styles.php / load-scripts.php, already allowed above.
|
||||||
#
|
#
|
||||||
# Honors the same whitelist as every other rule in this frontend
|
# Honors the same whitelist as every other rule in this frontend
|
||||||
# (RFC1918 / trusted_ips.list / trusted_ips.map), and a per-site opt-out
|
# (RFC1918 / trusted_ips.list / trusted_ips.map), and a per-site opt-out
|
||||||
@@ -515,6 +540,7 @@ frontend web
|
|||||||
# the intended "reject a literal backslash" semantics.
|
# the intended "reject a literal backslash" semantics.
|
||||||
acl wp_admin_safe_path path_reg ^/[^/\\\\]
|
acl wp_admin_safe_path path_reg ^/[^/\\\\]
|
||||||
acl wp_admin_allowed path_end /wp-admin/admin-ajax.php /wp-admin/admin-post.php /wp-admin/load-styles.php /wp-admin/load-scripts.php
|
acl wp_admin_allowed path_end /wp-admin/admin-ajax.php /wp-admin/admin-post.php /wp-admin/load-styles.php /wp-admin/load-scripts.php
|
||||||
|
acl wp_admin_install path_end /wp-admin/setup-config.php /wp-admin/install.php
|
||||||
# The (?!.*\.php) lookahead is DEFENCE IN DEPTH, not the primary fix. This
|
# The (?!.*\.php) lookahead is DEFENCE IN DEPTH, not the primary fix. This
|
||||||
# ACL grants an un-gated bypass to everything under wp-admin/css|js|images,
|
# ACL grants an un-gated bypass to everything under wp-admin/css|js|images,
|
||||||
# and it used to anchor its prefix but not its suffix, so
|
# and it used to anchor its prefix but not its suffix, so
|
||||||
@@ -589,7 +615,7 @@ frontend web
|
|||||||
http-request deny deny_status 403 if wp_admin_word path_has_encoded_sep !has_wp_logged_in !wp_gate_exempt !is_local !is_trusted_ip !is_whitelisted
|
http-request deny deny_status 403 if wp_admin_word path_has_encoded_sep !has_wp_logged_in !wp_gate_exempt !is_local !is_trusted_ip !is_whitelisted
|
||||||
http-request deny deny_status 403 if wp_admin_path !wp_admin_safe_path !has_wp_logged_in !wp_gate_exempt !is_local !is_trusted_ip !is_whitelisted
|
http-request deny deny_status 403 if wp_admin_path !wp_admin_safe_path !has_wp_logged_in !wp_gate_exempt !is_local !is_trusted_ip !is_whitelisted
|
||||||
http-request set-var(txn.wp_login_url) path,regsub(/wp-admin/.*,/wp-login.php,i) if wp_admin_path
|
http-request set-var(txn.wp_login_url) path,regsub(/wp-admin/.*,/wp-login.php,i) if wp_admin_path
|
||||||
http-request redirect code 302 location %[var(txn.wp_login_url)]?redirect_to=%[path,url_enc] if wp_admin_path wp_admin_safe_path !wp_admin_allowed !wp_admin_asset !has_wp_logged_in !wp_gate_exempt !is_local !is_trusted_ip !is_whitelisted
|
http-request redirect code 302 location %[var(txn.wp_login_url)]?redirect_to=%[path,url_enc] if wp_admin_path wp_admin_safe_path !wp_admin_allowed !wp_admin_install !wp_admin_asset !has_wp_logged_in !wp_gate_exempt !is_local !is_trusted_ip !is_whitelisted
|
||||||
|
|
||||||
# IP blocking using map file (manual blocks only)
|
# IP blocking using map file (manual blocks only)
|
||||||
# Map file format: /etc/haproxy/blocked_ips.map contains "<ip_or_cidr> 1" per line
|
# Map file format: /etc/haproxy/blocked_ips.map contains "<ip_or_cidr> 1" per line
|
||||||
|
|||||||
Reference in new issue
Block a user