interplane.Get Omega
Read in your language

interplane-forge

INTERPLANE Forge

Brought by drakestapleton

branch main Branches Tags History

interplane-forge / infra / test / ops-scratch.sh

371 lines · 26408 bytes Raw Blame History
1#!/usr/bin/env bash
2# infra/test/ops-scratch.sh: exercise infra/ops/* and the ops changes in infra/spark/ on the Spark,
3# writing only into a scratch dir. Each check has a negative control.
4# Live contact, all read-only: IPL_TEST_ROUNDS probe rounds of GETs to https://interplane.io and one
5# openssl read of its certificate; reads of ~/.radicle/storage/*/refs and readable /etc/nginx
6# (archived into the scratch spool, encrypted to a THROWAWAY age key made here); `systemctl show`
7# of the Forgejo units and ssh.service; the Forgejo setup files under /home/atlas (staged into
8# scratch). A throwaway non-root nginx listens on 127.0.0.1:$IPL_TEST_PORT and is stopped on exit.
9# Nothing live is written, enabled, started or stopped.
10# Usage: bash infra/test/ops-scratch.sh
11# Env: IPL_TEST_ROUNDS (3) IPL_TEST_SLEEP (20 s between rounds) IPL_TEST_PORT (14548)
12# KEEP=1 keeps the scratch dir (the Mac pull test reads its spool)
13# Host tools: bash, curl, openssl, age, GNU tar, nginx 1.24, inotify-tools, flock, systemd-analyze, patch.
14set -u
15PATH=$PATH:/usr/sbin # nginx is /usr/sbin/nginx; some agent shells leave sbin out
16R=$(cd "$(dirname "$0")/../.." && pwd)
17O=$R/infra/ops; SP=$R/infra/spark
18ROUNDS=${IPL_TEST_ROUNDS:-3}; NAP=${IPL_TEST_SLEEP:-20}; PORT=${IPL_TEST_PORT:-14548}
19S=$(mktemp -d /tmp/ipl-ops-test.XXXXXX)
20NGXPID=$S/ngx/nginx.pid
21# stopsup PIDFILE: stop a supervisor started by minrun (section 6). Its first line records its own
22# pid; under setsid that bash leads its own session and process group, so the pid is the group id
23# (the pid of `setsid bash ... &` is not: setsid forks when it already leads a group). TERM the
24# group, wait up to 5 s, KILL what is left.
25stopsup() {
26 local g; g=$(cat "$1" 2>/dev/null) || return 0
27 case $g in ''|*[!0-9]*) return 0;; esac
28 kill -TERM -- "-$g" 2>/dev/null
29 for _ in $(seq 1 25); do kill -0 -- "-$g" 2>/dev/null || break; sleep 0.2; done
30 kill -KILL -- "-$g" 2>/dev/null
31 rm -f -- "$1"
32}
33cleanup() {
34 local f
35 for f in "$S"/*.sup.pid; do [ -e "$f" ] && stopsup "$f"; done
36 [ -f "$NGXPID" ] && kill -QUIT "$(cat "$NGXPID")" 2>/dev/null
37 if [ "${KEEP:-0}" = 1 ]; then echo "scratch kept: $S"; else rm -rf -- "$S"; fi
38}
39trap cleanup EXIT
40# a signal ends the run through exit, so cleanup (supervisors first, then the directory) runs on
41# every exit path
42trap 'exit 129' HUP; trap 'exit 130' INT; trap 'exit 143' TERM
43pass=0; fail=0
44ok() { pass=$((pass + 1)); echo "PASS $*"; }
45bad() { fail=$((fail + 1)); echo "FAIL $*"; }
46chk() { local n=$1; shift; if "$@"; then ok "$n"; else bad "$n"; fi; }
47# rc NAME WANT CMD...: run CMD, output to $S/last.out, compare the exit code.
48rc() {
49 local n=$1 want=$2 got; shift 2
50 "$@" >"$S/last.out" 2>&1; got=$?
51 if [ "$got" = "$want" ]; then ok "$n (exit $got)"; else bad "$n (exit $got, want $want)"; show 30; fi
52}
53show() { sed 's/^/ | /' "$S/last.out" | head -n "${1:-20}"; }
54has() { grep -q -- "$1" "${2:-$S/last.out}"; }
55hasnt() { ! grep -q -- "$1" "${2:-$S/last.out}"; }
56echo "ops-scratch: repo $R head $(git -C "$R" rev-parse --short HEAD) scratch $S $(date -u +%FT%TZ)"
57
58echo "== 1. syntax"
59for f in "$O"/*.sh "$O"/mac/forge-backup-pull.sh "$SP"/edge-mirror.sh "$SP"/forgejo/forgejo-backup \
60 "$SP"/forgejo/forgejo-runtime-restore.sh "$R"/infra/test/ops-scratch.sh; do
61 case $(head -1 "$f") in *bash*) sh=bash;; *) sh=sh;; esac
62 rc "$sh -n ${f#"$R"/}" 0 "$sh" -n "$f"
63done
64printf 'if then fi\n' >"$S/broken.sh"
65rc "negative: bash -n on a broken file" 2 bash -n "$S/broken.sh"
66
67echo "== 2. probe"
68rc "probe --dry-run" 0 env IPL_UPTIME_STATE="$S/u-dry" "$O/ipl-uptime-probe.sh" --dry-run; show
69chk "probe --dry-run wrote nothing" test ! -e "$S/u-dry"
70rc "negative: probe refuses a non-https base" 2 env IPL_UPTIME_BASE=http://interplane.io IPL_UPTIME_STATE="$S/u-x" "$O/ipl-uptime-probe.sh"
71for i in $(seq 1 "$ROUNDS"); do
72 rc "probe live round $i" 0 env IPL_UPTIME_STATE="$S/u" "$O/ipl-uptime-probe.sh"; show
73 [ "$i" -lt "$ROUNDS" ] && sleep "$NAP"
74done
75n=$(wc -l <"$S/u/probes.tsv"); n200=$(awk -F'\t' '$3 ~ /^[23]/' "$S/u/probes.tsv" | wc -l)
76chk "probes.tsv has $n lines from $ROUNDS rounds, $n200 with 2xx/3xx" test "$n" = $((ROUNDS * 5))
77echo " cert.txt: $(cat "$S/u/cert.txt")"
78chk "cert expiry read with openssl" grep -qP '^\S+\t20\d\d-\d\d-\d\dT\d\d:\d\d:\d\dZ\t' "$S/u/cert.txt"
79rc "negative: probe against a closed port" 0 env IPL_UPTIME_BASE=https://127.0.0.1:1 IPL_UPTIME_PATHS=/ IPL_UPTIME_STATE="$S/u-neg" "$O/ipl-uptime-probe.sh"; show
80chk "negative: closed port recorded as status 000" grep -qP '\t/\t000\t' "$S/u-neg/probes.tsv"
81chk "negative: closed port gives no certificate" grep -q 'no certificate read' "$S/u-neg/cert.txt"
82
83echo "== 3. page"
84rc "render --dry-run" 0 env IPL_UPTIME_STATE="$S/u" "$O/ipl-uptime-render.sh" --dry-run
85cp "$S/last.out" "$S/page.html"
86chk "page says inside view, not an outside check" has 'Inside view from the Spark; not an outside check' "$S/page.html"
87chk "page shows the cert expiry" grep -q 'certificate served for interplane.io expires 20' "$S/page.html"
88chk "page has one row per path (5)" test "$(grep -c '^<tr><td>/' "$S/page.html")" = 5
89chk "page has no script, no style element, no style attribute" hasnt '<script\|<style\|style=' "$S/page.html"
90chk "page claims no percentage" hasnt '%' "$S/page.html"
91grep -E 'Measured window|<tr><td>/|expires' "$S/page.html" | sed 's/^/ | /'
92rc "render to a file" 0 env IPL_UPTIME_STATE="$S/u" IPL_UPTIME_OUT="$S/www/index.html" "$O/ipl-uptime-render.sh"
93chk "rendered file is 0644" test "$(stat -c %a "$S/www/index.html")" = 644
94rc "negative: output dir cannot be made" 1 env IPL_UPTIME_STATE="$S/u" IPL_UPTIME_OUT=/proc/ipl-none/index.html "$O/ipl-uptime-render.sh"
95rc "negative: 48 h later the 24 h window is empty" 0 env IPL_UPTIME_STATE="$S/u" IPL_UPTIME_NOW="$(date -u -d '+2 days' +%FT%TZ)" "$O/ipl-uptime-render.sh" --dry-run
96chk "negative: no rows, 'Nothing is claimed'" has 'Nothing is claimed for that period'
97rc "negative: 1 h later the page reports stale" 0 env IPL_UPTIME_STATE="$S/u" IPL_UPTIME_NOW="$(date -u -d '+1 hour' +%FT%TZ)" "$O/ipl-uptime-render.sh" --dry-run
98chk "negative: stale banner" has '<strong>Stale:</strong>'
99rc "negative: failed probes listed" 0 env IPL_UPTIME_STATE="$S/u-neg" "$O/ipl-uptime-render.sh" --dry-run
100chk "negative: failed table with status 000" has '<td>000</td>'
101
102# Section 4 tests the vhost of THIS tree (the file beside this script), so a green run speaks for the
103# head under test: the site root and static folders come from disk, every other path goes to forged.
104# The uptime locations live in the home-root lane (forge/home-root), which this tree may not carry:
105# they are tested only when IPL_TEST_VHOST_REF names a ref that has them (section 4b), else NOT_RUN.
106VREF=${IPL_TEST_VHOST_REF:-}
107echo "== 4. vhost of this tree (infra/spark/nginx/sites-interplane.io, throwaway nginx on 127.0.0.1:$PORT)"
108mkdir -p "$S/ngx/snippets" "$S/ngx/logs" "$S/ngx/tmp" "$S/ngx/tmp/cache" "$S/site"
109: >"$S/ngx/snippets/forge-headers.conf"; : >"$S/ngx/snippets/forge-proxy.conf"; : >"$S/ngx/snippets/forge-archive.conf"
110mkdir -p "$S/site/protocol"; echo '<!doctype html><title>protocol home</title>' >"$S/site/protocol/index.html"
111echo '<!doctype html><title>static root page</title>' >"$S/site/index.html"
112openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes -days 1 -subj /CN=interplane.io \
113 -keyout "$S/ngx/key.pem" -out "$S/ngx/cert.pem" >/dev/null 2>&1
114vhost() { # $1 = vhost source file -> $S/ngx/site.conf
115 sed -e "s#/etc/nginx/certs/interplane.io/fullchain.pem#$S/ngx/cert.pem#" \
116 -e "s#/etc/nginx/certs/interplane.io/key.pem#$S/ngx/key.pem#" \
117 -e "s#/etc/nginx/snippets/#$S/ngx/snippets/#" \
118 -e "s#root /var/www/interplane.io;#root $S/site;#" \
119 -e "s#alias /var/www/interplane-uptime/;#alias $S/www/;#" \
120 -e "s#listen 127.0.0.1:4444 ssl http2;#listen 127.0.0.1:$PORT ssl http2;#" \
121 -e "/listen 127.0.0.1:4448/d" "$1" >"$S/ngx/site.conf"
122 ! grep -v '^[[:space:]]*#' "$S/ngx/site.conf" | grep -q '/etc/nginx\|/var/www\|:4444\|:4448'
123}
124cat >"$S/ngx/nginx.conf" <<EOF
125worker_processes 1;
126pid $NGXPID;
127error_log $S/ngx/logs/error.log;
128events { worker_connections 64; }
129http {
130 include /etc/nginx/mime.types;
131 access_log off;
132 client_body_temp_path $S/ngx/tmp/cb; proxy_temp_path $S/ngx/tmp/px; fastcgi_temp_path $S/ngx/tmp/fc;
133 uwsgi_temp_path $S/ngx/tmp/uw; scgi_temp_path $S/ngx/tmp/sc;
134 proxy_cache_path $S/ngx/tmp/cache levels=1:2 keys_zone=forge_pages:1m inactive=10m use_temp_path=off;
135 map \$http_cookie \$forge_nocache { "" 0; default 1; }
136 map \$http_accept \$forge_json { default 0; "~text/html" 0; "~application/json" 1; }
137 upstream forged { server 127.0.0.1:9; } # nothing listens: forge paths answer 502 here
138 include $S/ngx/site.conf;
139}
140EOF
141ngx() { nginx -p "$S/ngx" -c "$S/ngx/nginx.conf" -e "$S/ngx/logs/error.log" "$@"; }
142get() { curl -sk -o "$S/body" -D "$S/hdr" -w '%{http_code}' --resolve "interplane.io:$PORT:127.0.0.1" "https://interplane.io:$PORT$1"; }
143ngx_cycle() { # $1 = label, $2 = vhost file; leaves nginx running
144 [ -f "$NGXPID" ] && { ngx -s quit; sleep 1; }
145 chk "$1: vhost rewritten to scratch paths only" vhost "$2"
146 rc "$1: nginx -t" 0 ngx -t
147 rc "$1: nginx start" 0 ngx; sleep 1
148}
149if ss -ltn | grep -q "127.0.0.1:$PORT "; then
150 bad "port $PORT busy; set IPL_TEST_PORT"
151else
152 ngx_cycle "this tree's vhost" "$SP/nginx/sites-interplane.io"
153 c=$(get /); chk "GET / = 200 from disk, not forged (got $c)" test "$c" = 200
154 chk " body is the static root page" has 'static root page' "$S/body"
155 chk " server CSP applies (script-src 'none'; style-src 'self')" grep -qi "^content-security-policy:.*script-src 'none'; style-src 'self'" "$S/hdr"
156 chk " HSTS applies" grep -qi '^strict-transport-security: max-age=31536000' "$S/hdr"
157 c=$(get /protocol/); chk "a static folder is served from disk (/protocol/, got $c)" test "$c" = 200
158 c=$(get /explore); chk "a path with no file on disk goes to forged (502 here, got $c)" test "$c" = 502
159 c=$(get /galaxy/); chk "/galaxy/ goes to forged (502 here, got $c)" test "$c" = 502
160 if grep -q 'location \^~ /status/uptime/' "$SP/nginx/sites-interplane.io"; then
161 c=$(get /status/uptime/); chk "this tree has the uptime location: GET /status/uptime/ = 200 (got $c)" test "$c" = 200
162 else
163 c=$(get /status/uptime/); chk "this tree has no uptime location: /status/uptime/ goes to forged (502, got $c)" test "$c" = 502
164 fi
165 # negative control: the same vhost with the disk lookup taken out must not serve the root page
166 sed -e 's#try_files \$uri \$uri/ @forged;#try_files /no-such-file @forged;#' "$SP/nginx/sites-interplane.io" >"$S/vhost-mut"
167 chk "negative: the mutant vhost differs" sh -c "! cmp -s '$SP/nginx/sites-interplane.io' '$S/vhost-mut'"
168 ngx_cycle "negative (disk lookup removed)" "$S/vhost-mut"
169 c=$(get /); chk "negative: without the disk lookup / goes to forged (502, got $c)" test "$c" = 502
170 ngx -s quit; sleep 1; rm -f "$NGXPID"
171fi
172
173echo "== 4b. uptime locations of another ref (IPL_TEST_VHOST_REF, for example forge/home-root)"
174if [ -z "$VREF" ]; then
175 echo " NOT_RUN: IPL_TEST_VHOST_REF is not set; /status/uptime/ has no public path on this tree (infra/RUNBOOK.md section 6)"
176elif ss -ltn | grep -q "127.0.0.1:$PORT "; then
177 bad "port $PORT busy; set IPL_TEST_PORT"
178elif ! git -C "$R" show "$VREF:infra/spark/nginx/sites-interplane.io" >"$S/vhost-new" 2>/dev/null; then
179 echo " NOT_RUN: no ref $VREF here"
180else
181 rm -f "$S/site/index.html"
182 cp "$SP/nginx/sites-interplane.io" "$S/vhost-base"
183 if grep -q 'location \^~ /status/uptime/' "$S/vhost-base"; then git -C "$R" show edge/spark-front-door:infra/spark/nginx/sites-interplane.io >"$S/vhost-base" 2>/dev/null; fi
184 ngx_cycle "negative (base vhost, no uptime location)" "$S/vhost-base"
185 c=$(get /status/uptime/); chk "negative: base vhost sends /status/uptime/ to forged (502, got $c)" test "$c" = 502
186 ngx_cycle "$VREF vhost" "$S/vhost-new"
187 c=$(get /status/uptime/); chk "GET /status/uptime/ = 200 (got $c)" test "$c" = 200
188 chk " body is the probe page" has 'not an outside check' "$S/body"
189 chk " server CSP applies (script-src 'none'; style-src 'self')" grep -qi "^content-security-policy:.*script-src 'none'; style-src 'self'" "$S/hdr"
190 chk " HSTS applies" grep -qi '^strict-transport-security: max-age=31536000' "$S/hdr"
191 c=$(get /status/uptime); chk "GET /status/uptime = 301 (got $c)" test "$c" = 301
192 chk " Location: /status/uptime/" grep -qi '^location: /status/uptime/' "$S/hdr"
193 c=$(get /status/uptime/none.html); chk "negative: missing file under the alias = 404, not forged (got $c)" test "$c" = 404
194 c=$(get /status/other); chk "negative: /status/other still goes to forged (502, got $c)" test "$c" = 502
195 c=$(get /status/); chk "/status/ still takes the 301 to /protocol/status/ (got $c)" test "$c" = 301
196 chk " Location: /protocol/status/" grep -qi '^location: /protocol/status/' "$S/hdr"
197 c=$(get /protocol/); chk "static /protocol/ still served (got $c)" test "$c" = 200
198 ngx -s quit; sleep 1; rm -f "$NGXPID"
199fi
200
201echo "== 5. forge-backup (throwaway keys)"
202age-keygen -o "$S/k1.txt" 2>/dev/null; age-keygen -o "$S/k2.txt" 2>/dev/null
203K1=$(age-keygen -y "$S/k1.txt")
204mkdir -p "$S/forge-data/tmp" "$S/forge-data/logs" "$S/forge-data/archives/r" "$S/forge-data/collab/r" "$S/forge-data/search"
205echo 'event 1' >"$S/forge-data/social.log"; echo DECOY-SECRET >"$S/forge-data/social.key"; echo 1 >"$S/forge-data/x.pid"
206for d in tmp logs archives/r collab/r search; do echo cache >"$S/forge-data/$d/f"; done
207B() { env -u FORGE_BACKUP_RECIPIENT FORGE_BACKUP_SPOOL="$S/spool" FORGE_BACKUP_FORGE_DATA="$S/forge-data" "$@"; }
208rc "negative: --dry-run without recipient" 3 B "$O/forge-backup.sh" --dry-run; show 12
209rc "negative: run without recipient" 3 B "$O/forge-backup.sh" run; show 3
210chk "negative: no spool created" test ! -e "$S/spool"
211rc "negative: run with a malformed recipient" 3 B FORGE_BACKUP_RECIPIENT=age1notakey "$O/forge-backup.sh" run
212mkdir -p "$S/fakengx/keys"; echo x >"$S/fakengx/keys/k"
213rc "negative: a keys/ path in a source stops the dry-run" 4 B FORGE_BACKUP_RECIPIENT="$K1" FORGE_BACKUP_NGINX="$S/fakengx" "$O/forge-backup.sh" --dry-run
214rc "negative: a keys/ path in a source stops a run" 4 B FORGE_BACKUP_RECIPIENT="$K1" FORGE_BACKUP_NGINX="$S/fakengx" FORGE_BACKUP_SPOOL="$S/spool-keys" "$O/forge-backup.sh" run
215chk " no archive written" test -z "$(ls "$S/spool-keys"/*.age 2>/dev/null)"
216rc "--dry-run with throwaway recipient" 0 B FORGE_BACKUP_RECIPIENT="$K1" "$O/forge-backup.sh" --dry-run; show 12
217rc "run 1" 0 B FORGE_BACKUP_RECIPIENT="$K1" "$O/forge-backup.sh" run; show 3
218rc "run 2, nothing changed" 0 B FORGE_BACKUP_RECIPIENT="$K1" "$O/forge-backup.sh" run; show 3
219chk " says unchanged" has 'unchanged since the last archive'
220touch "$S/forge-data/social.log" "$S/forge-data/tmp/f"
221rc "run 3, only mtimes and an excluded file changed" 0 B FORGE_BACKUP_RECIPIENT="$K1" "$O/forge-backup.sh" run
222chk " still unchanged" has 'unchanged since the last archive'
223sleep 1; echo 'event 2' >>"$S/forge-data/social.log"
224rc "run 4, social.log changed" 0 B FORGE_BACKUP_RECIPIENT="$K1" "$O/forge-backup.sh" run; show 3
225mapfile -t AR < <(ls "$S/spool"/forge-backup-*.tar.gz.age)
226chk "spool has 2 archives, each with .sha256, plus latest.json" test "${#AR[@]}" = 2 -a -f "${AR[1]}.sha256" -a -f "$S/spool/latest.json"
227echo " latest.json: $(cat "$S/spool/latest.json")"; ls -l "$S/spool" | sed 's/^/ | /'
228chk "latest.json names the newest archive and its sha256" grep -q "\"file\": \"$(basename "${AR[1]}")\", \"sha256\": \"$(cut -d' ' -f1 "${AR[1]}.sha256")\"" "$S/spool/latest.json"
229chk "archives are 0600 age files" test "$(stat -c %a "${AR[1]}")" = 600 -a "$(head -c 21 "${AR[1]}")" = age-encryption.org/v1
230chk "ciphertext does not contain the social.log text" bash -c "! grep -q 'event 2' '${AR[1]}'"
231rc "restore with the right key (drill)" 0 "$O/forge-backup.sh" restore "${AR[1]}" "$S/k1.txt" "$S/r1"; show 12
232chk " social.log restored with both events" test "$(cat "$S/r1/forge-data/social.log" 2>&1)" = "$(printf 'event 1\nevent 2')"
233chk " no social.key, *.pid, tmp, logs, archives, collab, search" test "$(ls -A "$S/r1/forge-data" 2>&1)" = social.log
234chk " no keys/ and no objects/ anywhere" test -z "$(find "$S/r1" \( -name keys -o -name objects -o -name social.key \) -print)"
235live=$(find "$HOME"/.radicle/storage/*/refs -type f 2>/dev/null | wc -l); got=$(find "$S/r1/storage" -path '*/refs/*' -type f | wc -l)
236chk " Radicle ref files: $got restored, $live live now" test "$got" -gt 0 -a "$got" -le $((live + 50)) -a "$got" -ge $((live - 50))
237chk " nginx.conf restored" test -f "$S/r1/nginx/nginx.conf"
238rc "negative: restore with the wrong key" 1 "$O/forge-backup.sh" restore "${AR[1]}" "$S/k2.txt" "$S/r2"; show 3
239chk " says decryption FAILED" has 'decryption FAILED'
240rc "negative: restore into a non-empty dir" 1 "$O/forge-backup.sh" restore "${AR[1]}" "$S/k1.txt" "$S/r1"; show 2
241mkdir "$S/tamper"; cp "${AR[1]}" "${AR[1]}.sha256" "$S/tamper/"; printf 'x' >>"$S/tamper/$(basename "${AR[1]}")"
242rc "negative: restore of a modified archive" 1 "$O/forge-backup.sh" restore "$S/tamper/$(basename "${AR[1]}")" "$S/k1.txt" "$S/r3"; show 3
243
244echo "== 6. onchange-glob"
245# Every call here gets a private XDG_RUNTIME_DIR. The first one uses the patterns of the real unit
246# (aien-run-forge-backup.service), so with the real runtime dir it names the real unit's list file.
247SHARED=${XDG_RUNTIME_DIR:-/run/user/$(id -u)}/onchange-glob
248shared_state() { if [ -d "$SHARED" ]; then (cd "$SHARED" && stat -c '%n %s %Y' ./* 2>/dev/null; sha256sum ./* 2>/dev/null) | sort; else echo absent; fi; }
249before=$(shared_state)
250mkdir -p -m 700 "$S/xdg"
251rc "--dry-run on the forge-backup patterns" 0 env XDG_RUNTIME_DIR="$S/xdg" "$O/onchange-glob.sh" --dry-run 3600 86400 "$HOME/forge-data" /etc/nginx '/etc/nginx/*/' \
252 "$HOME/.radicle/storage" "$HOME/.radicle/storage/*/" "$HOME/.radicle/storage/*/refs/**/" -- "$O/forge-backup.sh" run; show 12
253chk "--dry-run wrote nothing (no state dir, no list)" test ! -e "$S/xdg/onchange-glob"
254rc "negative: no directory matches" 2 env XDG_RUNTIME_DIR="$S/xdg" "$O/onchange-glob.sh" --dry-run 1 2 "$S/none/*/" -- true
255mkdir -p "$S/g/a/refs/heads"
256XDG_RUNTIME_DIR=$S timeout 40 "$O/onchange-glob.sh" 1 3600 "$S/g" "$S/g/*/" "$S/g/*/refs/**/" -- \
257 sh -c "echo run >>'$S/g.runs'" 2>"$S/g.err" &
258gp=$!; sleep 2
259chk "a real run does write its list (in the private runtime dir)" bash -c "ls '$S/onchange-glob/'*.dirs >/dev/null 2>&1"
260touch "$S/g/a/refs/heads/main"; sleep 3
261chk "a ref write triggers a run, the watch stays up (runs=$(wc -l <"$S/g.runs"))" bash -c "kill -0 $gp && [ \$(wc -l <'$S/g.runs') -ge 2 ]"
262mkdir "$S/g/b"; for _ in $(seq 1 10); do kill -0 "$gp" 2>/dev/null || break; sleep 1; done
263if kill -0 "$gp" 2>/dev/null; then bad "a new repo dir ends the watch for a restart"; kill "$gp"; else ok "a new repo dir ends the watch for a restart"; fi
264wait "$gp" 2>/dev/null
265chk " logged 'watched directory set changed'" has 'watched directory set changed' "$S/g.err"
266# MIN_GAP across a restart: aien-onchange runs at start, so a restarted watch must still wait.
267# minrun TAG RUNTIME: a supervisor loop stands in for systemd (Restart=always, RestartSec=2); a new
268# dir after 1 s ends the first watch. RUNTIME=same keeps one XDG_RUNTIME_DIR (systemd's case);
269# RUNTIME=fresh gives every restart an empty one, i.e. the stamp is lost: the negative control.
270# Sets mg (smallest gap between run starts, s) and mn (runs).
271# The supervisor records its own pid in $S/TAG.sup.pid and loops only while $S/TAG exists; minrun
272# stops its whole process group with stopsup, and cleanup stops any supervisor still recorded
273# before it removes the scratch dir (finding T1 of verdict-32b98460: the loop outlived the run).
274# It is started with setsid -f, which always forks: the supervisor is never this shell's child $!
275# nor in its process group, with or without job control. That is the case of T1 (setsid forks
276# when it already leads a group, as a job of a `bash -m` shell on a terminal does); without -f a
277# shell with no job control kept the old kill working, so the T1 checks below could not fail.
278minrun() {
279 local t=$1 rt
280 mkdir -p "$S/$t/a" "$S/$t.rt"
281 if [ "$2" = same ]; then rt=$S/$t.rt; else rt='$(mktemp -d '"$S/$t.rt"'/XXXXXX)'; fi
282 cat >"$S/$t.sup" <<EOF
283echo \$\$ >"$S/$t.sup.pid"
284while [ -d "$S/$t" ]; do
285 XDG_RUNTIME_DIR=$rt "$O/onchange-glob.sh" 6 3600 "$S/$t" "$S/$t/*/" -- sh -c 'date +%s >>"$S/$t.runs"' 2>>"$S/$t.err"
286 sleep 2
287done
288EOF
289 setsid -f bash "$S/$t.sup"
290 for _ in $(seq 1 50); do [ -s "$S/$t.sup.pid" ] && break; sleep 0.1; done
291 sleep 1; mkdir "$S/$t/b"; sleep 17
292 stopsup "$S/$t.sup.pid"
293 mn=$(wc -l <"$S/$t.runs")
294 mg=$(awk 'NR > 1 { g = $1 - p; if (m == "" || g < m) m = g } { p = $1 } END { print m + 0 }' "$S/$t.runs")
295}
296# noproc PATTERN: no process has PATTERN in its command line (pgrep leaves itself out)
297noproc() { ! pgrep -f -- "$1" >/dev/null; }
298minrun m same
299chk "a restarted watch keeps MIN_GAP 6 s (runs $mn, smallest gap ${mg} s)" test "$mn" -ge 3 -a "$mg" -ge 6
300sleep 1
301chk " the supervisor, its watch and its runs are gone after minrun (T1)" noproc "$S/m.sup"
302chk " no watch of $S/m is left" noproc "onchange-glob.sh 6 3600 $S/m "
303minrun mneg fresh
304chk "negative: with the stamp lost at each restart a run follows the restart at once (runs $mn, smallest gap ${mg} s)" \
305 test "$mn" -ge 3 -a "$mg" -lt 6
306sleep 1
307chk " the supervisor, its watch and its runs are gone after minrun (T1)" noproc "$S/mneg.sup"
308chk " no watch of $S/mneg is left" noproc "onchange-glob.sh 6 3600 $S/mneg "
309
310chk "the shared runtime dir $SHARED is as it was before this section" test "$before" = "$(shared_state)"
311
312echo "== 7. edge-mirror lock (HUB is an invalid name: no rsync can reach anything)"
313flock "$S/em.lock" sleep 8 &
314sleep 1
315rc "negative: second runner waits while the lock is held" 124 timeout 3 env HUB=ipl-ops-nohost.invalid EDGE_MIRROR_LOCK="$S/em.lock" EDGE_MIRROR_LOG="$S/em.log" sh "$SP/edge-mirror.sh"
316chk " nothing logged while waiting" test ! -s "$S/em.log"
317wait
318rc "after the lock is free it runs (every pull fails on the invalid host)" 1 env HUB=ipl-ops-nohost.invalid EDGE_MIRROR_LOCK="$S/em.lock" EDGE_MIRROR_LOG="$S/em.log" sh "$SP/edge-mirror.sh"
319chk " log ends 'done rc=1' with 7 FAIL lines" bash -c "tail -1 '$S/em.log' | grep -q 'done rc=1' && [ \$(grep -c ' FAIL ' '$S/em.log') = 7 ]"
320
321echo "== 8. Forgejo scripts"
322# The refusal is tested against a systemctl stand-in whose units name an ExecStart binary that does
323# not exist. It read the live units before, so it passed only while the live Forgejo binaries were
324# missing (2026-11-08); with them restored (atlas-forgejo.service ok) it failed with exit 0.
325# forgejo-backup sets its own PATH (/usr/local/bin:/usr/bin:/bin), so the stand-in is reached through
326# a scratch copy whose one changed line puts $S/stub first on that PATH; nothing else differs (checked).
327mkdir -p "$S/stub"
328cat >"$S/stub/systemctl" <<'EOF'
329#!/bin/sh
330case " $* " in
331*" show "*) echo "{ path=/nonexistent/ipl-ops-test/forgejo ; argv[]=/nonexistent/ipl-ops-test/forgejo web ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }" ;;
332*" is-active "*) echo inactive; exit 3 ;;
333*) exit 1 ;;
334esac
335EOF
336chmod 755 "$S/stub/systemctl"
337sed "s|^PATH=/usr/local/bin:/usr/bin:/bin\$|PATH=$S/stub:/usr/local/bin:/usr/bin:/bin|" "$SP/forgejo/forgejo-backup" >"$S/fb.stub"
338chk " the scratch copy differs from forgejo-backup in its PATH line only" \
339 bash -c "[ \$(diff '$SP/forgejo/forgejo-backup' '$S/fb.stub' | grep -c '^>') = 1 ] && grep -q '^PATH=$S/stub:' '$S/fb.stub'"
340rc "negative: forgejo-backup --dry-run refuses, a unit binary is missing (systemctl stand-in)" 1 env FORGEJO_BACKUP_DEST="$S/fbdest" sh "$S/fb.stub" --dry-run; show 12
341chk " it names the missing binary and refuses before stopping anything" bash -c "grep -q 'MISSING /nonexistent/ipl-ops-test/forgejo' '$S/last.out' && grep -q 'refusing to stop Forgejo' '$S/last.out'"
342rc "forgejo-backup --dry-run with present binaries (ssh.service stands in)" 0 env FORGEJO_BACKUP_SYS_UNIT=ssh.service FORGEJO_BACKUP_STORAGE_UNIT=ssh.service "$SP/forgejo/forgejo-backup" --dry-run; show 12
343rc "negative: forgejo-backup usage error" 1 "$SP/forgejo/forgejo-backup" --bogus
344live_fb=$HOME/.local/bin/forgejo-backup
345if cmp -s "$live_fb" "$SP/forgejo/forgejo-backup"; then
346 ok "live forgejo-backup already equals the repo copy (installed)"
347 if [ -f "$live_fb.bak-20261111" ]; then
348 rc "patch applies to pre-migration backup (output to scratch)" 0 patch -s -o "$S/fb.patched" "$live_fb.bak-20261111" "$SP/forgejo/forgejo-backup.patch"
349 chk " result equals the repo copy" cmp -s "$S/fb.patched" "$SP/forgejo/forgejo-backup"
350 fi
351else
352 rc "patch applies to the live script (output to scratch)" 0 patch -s -o "$S/fb.patched" "$live_fb" "$SP/forgejo/forgejo-backup.patch"
353 chk " result equals the repo copy" cmp -s "$S/fb.patched" "$SP/forgejo/forgejo-backup"
354fi
355rc "negative: patch refuses an already patched file" 1 patch -s -f --dry-run -o "$S/fb.again" "$SP/forgejo/forgejo-backup" "$SP/forgejo/forgejo-backup.patch"
356rc "forgejo-runtime-restore --dry-run into scratch" 0 "$SP/forgejo/forgejo-runtime-restore.sh" --dry-run "$S/fr"; show 14
357rc "negative: runtime restore into a non-empty dir" 1 "$SP/forgejo/forgejo-runtime-restore.sh" --dry-run "$S/fr"
358rc "negative: runtime restore with missing sources" 1 env SRC=/nonexistent "$SP/forgejo/forgejo-runtime-restore.sh" --dry-run "$S/fr2"
359
360echo "== 9. unit files"
361mkdir -p "$S/units"
362for u in "$O"/*.service "$SP"/aien-run-forgejo-backup.service "$SP"/edge-mirror-onchange.service; do
363 sed "s#%h/work/forge/web#$R#g" "$u" >"$S/units/$(basename "$u")"
364 chk "$(basename "$u"): continuous, Restart=always, no timer" bash -c "grep -q '(continuous;' '$u' && grep -q '^Restart=always' '$u' && ! grep -qi 'OnCalendar\|OnUnitActiveSec' '$u'"
365done
366rc "systemd-analyze --user verify (paths pointed at this worktree)" 0 systemd-analyze --user verify "$S"/units/*.service; show 10
367sed 's#^ExecStart=.*#ExecStart=/nonexistent/ipl-ops-binary#' "$S/units/aien-run-ipl-uptime.service" >"$S/units-bad.service"
368rc "negative: verify flags a missing ExecStart binary" 1 systemd-analyze --user verify "$S/units-bad.service"
369
370echo "ops-scratch: $pass passed, $fail failed"
371[ "$fail" = 0 ]