Files
felhom.eu/documentation/audits/new-app-securo-2026-11-15/tools/securo_box.py
T
adminandClaude Opus 5.5 c616727d84
gates / gates (push) Successful in 2m8s
Securo onboarding: the audit evidence and R-1399 (the website lists fewer apps than the catalog)
documentation/audits/new-app-securo-2026-11-15/: source and image reads, bench (negative control, the
0.17.0 -> 0.18.0 move, memory from birth, storage), 9202 on the drill catalog (the guarded Update, the
undo on a real failure, the setup gate against a stranger's poll, accounts, the visitor's address and
lock-out through the simulated tunnel, receipt upload, backup -> remove -> restore), card pictures and
the guide label check. R-1399 (P4, Apps & catalog): wger and Securo have no card on the apps page and
the count says 63. The catalog commit follows after the operator's yes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012qRErfCoiTkvDK9N5XHbzb
2026-11-15 15:08:22 +01:00

432 lines
25 KiB
Python

#!/usr/bin/env python3
"""securo_box.py <phase> — Securo's checklist measurements on scratch guest 9202 (drill catalog), through the product's
own endpoints and the app's own front door. Evidence under $EV/box/<phase>.txt. Secrets are never printed.
install — the from-birth memory sampler and a STRANGER's poll (no dashboard session, no gate cookie, through traefik,
once a second: GET / and POST /api/setup/create-admin) start BEFORE the deploy press; then the deploy, the
setup gate as a stranger and as the household, the household's first admin (the fixture's seed) and the
probe flip. [3.1 3.3 3.5 4.3 5.1(box) 9.2]
checks — sign-up refused (3.4), sign-in the way the browser does (3.9), the visitor's address and the lock-out
through the simulated tunnel (3.6, 3.10), family members and a password change (3.7), an attachment through
the front door (2.8), an unknown page (1.8), the server process (1.5), the negative control (4.4), sizes (2.7).
restore — needs a per-app backup (taken by the guarded Update's backing-up phase, R-648): remove keeping backups,
restore through the product, read back. [2.5]
remove — remove keeping data, list what is left; reinstall-free remove with data, list again. [2.6]
Usage: SC=<0600 dir with .ctlpw> TARGET=9202 EV=<audit dir> python3 securo_box.py <phase>
"""
import json, os, re, secrets, sys, time
from urllib.parse import urlencode
sys.path.insert(0, "/mnt/5_hdd/felhom.eu/git/app-catalog-felhom.eu/scripts")
import box_walk as w
import upgrade_fixtures_box28 as f28
APP, SUB = "securo", "finance"
EVR = os.environ["EV"]
phase = sys.argv[1]
os.makedirs(f"{EVR}/box", exist_ok=True)
log = open(f"{EVR}/box/{phase}.txt", "a", buffering=1)
TOK = os.path.join(w.SC, "securo-seed.json") # 0600, the seeded login: never committed, never printed
HOST = f"{SUB}.{w.DOMAIN}"
FX = f28.FIXTURES28[APP]
FRONT_IMG = "ghcr.io/securo-finance/securo-frontend:0.18.0" # has curl; used as the simulated cloudflared
def say(*a):
w.say(*a)
log.write(" ".join(map(str, a)) + "\n")
def stranger(path, method="GET", data=None, headers=()):
"""A stranger on the LAN through traefik: no dashboard session, no gate cookie."""
args = ["curl", "-sk", "--max-time", "15", "-H", f"Host: {HOST}", "-o", "-", "-w", "\n%{http_code}"]
for h in headers:
args += ["-H", h]
if method != "GET":
args += ["-X", method]
if data is not None:
args += ["--data-binary", "@-"]
r = w.sh(args + [f"{w.BASE}{path}"], inp=data)
body, _, code = (r.stdout or "").rpartition("\n")
return code.strip(), body
def tunnel(path, xff, data, label, ctype="application/x-www-form-urlencoded", visitor="198.51.100.66"):
"""The internet visitor, simulated as in audits/visitors-2026-10-01 and night-burndown-2026-10-06/r777: a container
at cloudflared's fixed 172.16.253.2 on felhom-tunnel posts to traefik (172.16.253.3) with what Cloudflare sends."""
script = f"""docker run --rm -i --network felhom-tunnel --ip 172.16.253.2 --entrypoint curl {FRONT_IMG} -sk --max-time 20 \\
--resolve '{HOST}:443:172.16.253.3' -o /dev/null -w '%{{http_code}}' \\
-H 'CF-Connecting-IP: {visitor}' -H 'X-Forwarded-For: {xff}' -H 'X-Forwarded-Proto: https' \\
-H 'Content-Type: {ctype}' -X POST --data-binary @/dev/stdin 'https://{HOST}{path}'"""
# the body goes in as base64, decoded with NO trailing newline (a heredoc added one: 2026-11-15 first run, every
# „right password" through the tunnel read 400)
import base64
b64 = base64.b64encode(data.encode()).decode()
return w.guest(f"printf '%s' '{b64}' | base64 -d | " + script).strip()
def redis_keys():
return sorted(l for l in w.guest("docker exec securo-redis redis-cli --scan --pattern 'rate_limit:*'").split() if l)
def login_form(u, pw, origin=True):
h = ["Content-Type: application/x-www-form-urlencoded"]
if origin:
h += [f"Origin: https://{HOST}", f"Referer: https://{HOST}/login"]
code, body = w.app_curl(SUB, "/api/auth/login", *sum((["-H", x] for x in h), []),
data=urlencode({"username": u, "password": pw}), method="POST")[1:]
tok = None
try:
tok = json.loads(body).get("access_token")
except Exception:
pass
return code, tok, body
def tokens():
return json.load(open(TOK))
def install():
w.login()
if w.stack(APP).get("deployed"):
sys.exit("securo is already installed on the box — remove it first")
# the from-birth sampler (felhom.eu audits/new-apps-2026-10-01/tools/sampler.sh) — swap is ON on 9202 (512 MB), the
# bench is the swap-0 venue
smp = open("/mnt/5_hdd/felhom.eu/git/felhom.eu/documentation/audits/new-apps-2026-10-01/tools/sampler.sh").read()
w.guest("cat > /root/sampler-securo.sh <<'EOF_S'\n" + smp + "\nEOF_S\n"
"rm -f /root/mem-securo.csv.stop; NAMES='securo securo-backend securo-worker securo-beat securo-db securo-redis' "
"OUT=/root/mem-securo.csv DUR=3600 nohup bash /root/sampler-securo.sh >/dev/null 2>&1 &")
# the stranger's poll, from the HOST of 9202's network (DooPlex is on the same LAN): GET / and the open setup call
poll = os.path.join(w.SC, "stranger-poll.sh")
open(poll, "w").write(f"""#!/bin/bash
end=$(( $(date +%s) + 900 ))
while [ $(date +%s) -lt $end ] && [ ! -f {w.SC}/stranger-poll.stop ]; do
g=$(curl -sk --max-time 5 -o /dev/null -w '%{{http_code}}' -H 'Host: {HOST}' {w.BASE}/)
s=$(curl -sk --max-time 5 -o /tmp/securo-poll-body.$$ -w '%{{http_code}}' -H 'Host: {HOST}' {w.BASE}/api/setup/status)
b=$(head -c 60 /tmp/securo-poll-body.$$ | tr -d '\\n')
c=$(curl -sk --max-time 5 -o /dev/null -w '%{{http_code}}' -H 'Host: {HOST}' -H 'Content-Type: application/json' \\
-X POST --data '{{"email":"stranger@drill.felhom.eu","password":"Stranger-1234567!","currency":"HUF"}}' {w.BASE}/api/setup/create-admin)
echo "$(date +%H:%M:%S) GET/ $g status $s [$b] create-admin $c"
sleep 1
done
rm -f /tmp/securo-poll-body.$$
""")
os.chmod(poll, 0o700)
import subprocess
pf = open(f"{EVR}/box/stranger-poll.txt", "w")
pp = subprocess.Popen(["bash", poll], stdout=pf, stderr=subprocess.STDOUT)
t0 = time.time()
say(f"install: sampler and the stranger's poll started; deploy press at {time.strftime('%H:%M:%S')}")
ok = w.deploy(APP, SUB)
say(f"install: deploy finished={ok} after {time.time() - t0:.0f} s")
# healthy: every container's own healthcheck, polled
for _ in range(120):
st = w.guest("docker ps -a --filter label=com.docker.compose.project=securo --format '{{.Names}} {{.Status}}'")
if st.count("(healthy)") >= 5 and "starting" not in st and "unhealthy" not in st:
break
time.sleep(5)
say(f"4.3 all healthy {time.time() - t0:.0f} s after the press:\n{st.strip()}")
say("4.3 restart counts:", w.guest("for c in securo securo-backend securo-worker securo-beat securo-db securo-redis; do "
"echo -n \"$c=$(docker inspect -f '{{.RestartCount}}' $c) \"; done"))
say("3.3 setup gate as installed (the controller's own probe):", w.setup_gate_probe(SUB))
for p in ("/", "/api/setup/status"):
code, body = stranger(p, headers=("Accept: text/html",))
say(f"3.3 a stranger before the setup: GET {p} -> {code} {body[:80]!r}")
code, body = stranger("/api/setup/create-admin", "POST", json.dumps({"email": "stranger@drill.felhom.eu",
"password": "Stranger-1234567!", "currency": "HUF"}), ("Content-Type: application/json",))
say(f"3.3 a stranger's create-admin before the setup -> {code} {body[:80]!r}")
# the household: through the gate (the fixture's app_curl carries the gate cookie), the first admin
t = FX.seed(w, SUB, say)
if not t:
say("install: the household's seed FAILED —", getattr(FX, "tried", ""))
return
ok = FX.verify(w, SUB, t, say)
say("C1 read-back before anything else:", ok)
fd = os.open(TOK, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
os.write(fd, json.dumps(t).encode())
os.close(fd)
for _ in range(24):
pr = w.setup_gate_probe(SUB)
if "true" in str(pr).lower() or "open" in str(pr).lower():
break
time.sleep(5)
say("3.3 the probe after the household's setup:", pr)
w.GATE.pop(SUB, None)
for p in ("/", "/api/setup/status"):
code, body = stranger(p)
say(f"3.3 a stranger after the setup: GET {p} -> {code} {body[:80]!r}")
code, body = stranger("/api/setup/create-admin", "POST", json.dumps({"email": "stranger@drill.felhom.eu",
"password": "Stranger-1234567!", "currency": "HUF"}), ("Content-Type: application/json",))
say(f"3.3 a stranger's create-admin after the setup -> {code} {body[:80]!r}")
open(f"{w.SC}/stranger-poll.stop", "w").close()
pp.wait(timeout=30)
os.remove(f"{w.SC}/stranger-poll.stop")
hits = [l for l in open(f"{EVR}/box/stranger-poll.txt") if "create-admin 200" in l or "has_users" in l]
say(f"3.5 the stranger's poll: {sum(1 for _ in open(f'{EVR}/box/stranger-poll.txt'))} rounds; rounds where the "
f"stranger reached the app's own answer: {len(hits)}" + (f" — FIRST {hits[0].strip()}" if hits else ""))
def checks():
w.login()
t = tokens()
w.GATE[SUB] = ""
# 3.4 sign-up
for p, body in (("/api/auth/register", {"email": "stranger@drill.felhom.eu", "password": "Stranger-1234567!"}),):
code, out = stranger(p, "POST", json.dumps(body), ("Content-Type: application/json",))
say(f"3.4 a stranger's sign-up POST {p} -> {code} {out[:100]!r}")
code, out = stranger("/register", headers=("Accept: text/html",))
say(f"3.4 the sign-up PAGE GET /register -> {code} (the SPA; the call behind it is refused above)")
# 3.9 the browser's sign-in: form body, https Origin + Referer, through traefik
c1, tok, _ = login_form(t["u"], t["pw"])
c2, tok2, b2 = login_form(t["u"], t["pw"] + "x")
say(f"3.9 browser sign-in through traefik with an https Origin: right password -> {c1} token={'yes' if tok else 'no'}; "
f"wrong -> {c2} {b2[:60]!r}")
code, out = w.app_curl(SUB, "/api/users/me", "-H", f"Authorization: Bearer {tok}")[1:]
say(f"3.9 the token reads the account: GET /api/users/me -> {code}, e-mail matches={t['u'] in out}")
code, out = w.app_curl(SUB, "/api/users/me")[1:]
say(f"3.9 the same without a token -> {code}")
time.sleep(61) # the login window (5 a minute per key) empties before the address checks
# 3.10 + 3.6 the visitor's address, through the simulated tunnel
w.guest("docker exec securo-redis redis-cli --scan --pattern 'rate_limit:*' | xargs -r docker exec -i securo-redis redis-cli del >/dev/null")
bad = urlencode({"username": t["u"], "password": "wrong-" + secrets.token_hex(4)})
good = urlencode({"username": t["u"], "password": t["pw"]})
say("3.10 one failed sign-in per shape, then the rate-limit keys the backend wrote (key = the address it believed):")
for label, xff, vis in (("tunnel visitor A", "198.51.100.66", "198.51.100.66"),
("tunnel visitor A, forged leftmost", "10.0.0.5, 198.51.100.66", "198.51.100.66"),
("tunnel visitor B", "198.51.100.77", "198.51.100.77")):
code = tunnel("/api/auth/login", xff, bad, label, visitor=vis)
say(f" {label}: XFF {xff!r} -> {code}; keys now {redis_keys()}")
c, _, _ = login_form(t["u"], "wrong-lan")
say(f" LAN visitor (DooPlex, no XFF) -> {c}; keys now {redis_keys()}")
w.guest("docker exec securo-redis redis-cli --scan --pattern 'rate_limit:*' | xargs -r docker exec -i securo-redis redis-cli del >/dev/null")
say("3.6 lock-out: 8 wrong passwords from tunnel visitor A, then the household's right password from A, from B, from the LAN:")
codes = [tunnel("/api/auth/login", "198.51.100.66", bad, "A") for _ in range(8)]
say(f" A's 8 wrong tries: {codes}")
say(f" A, right password -> {tunnel('/api/auth/login', '198.51.100.66', good, 'A-right')}")
say(f" B, right password -> {tunnel('/api/auth/login', '198.51.100.77', good, 'B-right', visitor='198.51.100.77')}")
say(f" LAN, right password -> {login_form(t['u'], t['pw'])[0]}")
say(f" A forging a new leftmost entry, right password -> "
f"{tunnel('/api/auth/login', '10.9.9.9, 198.51.100.66', good, 'A-forged')}")
time.sleep(61)
say(f" A, right password 61 s later -> {tunnel('/api/auth/login', '198.51.100.66', good, 'A-later')}")
# 3.7 family members and a password change
_, tok, _ = login_form(t["u"], t["pw"])
auth = ["-H", f"Authorization: Bearer {tok}", "-H", "Content-Type: application/json"]
fu, fpw = "csalad" + secrets.token_hex(3) + "@drill.felhom.eu", "Csalad-" + secrets.token_hex(8) + "!aA"
code, out = w.app_curl(SUB, "/api/admin/users", *auth, method="POST",
data=json.dumps({"email": fu, "password": fpw, "is_superuser": False}))[1:]
say(f"3.7 the admin creates a family member: POST /api/admin/users -> {code} {re.sub(r'[0-9a-f-]{36}', '<id>', out)[:120]!r}")
c, ftok, _ = login_form(fu, fpw)
say(f"3.7 the family member signs in -> {c} token={'yes' if ftok else 'no'}")
npw = "Uj-" + secrets.token_hex(8) + "!aA"
code, out = w.app_curl(SUB, "/api/users/me", "-H", f"Authorization: Bearer {ftok}", "-H", "Content-Type: application/json",
method="PATCH", data=json.dumps({"password": npw}))[1:]
say(f"3.7 the member changes the own password: PATCH /api/users/me -> {code}; old password now -> "
f"{login_form(fu, fpw)[0]}, new -> {login_form(fu, npw)[0]}")
code, out = w.app_curl(SUB, "/api/admin/users", "-H", f"Authorization: Bearer {login_form(fu, npw)[1]}",
"-H", "Content-Type: application/json", method="POST",
data=json.dumps({"email": "x" + fu, "password": fpw}))[1:]
say(f"3.7 the family member (not admin) cannot create users: POST /api/admin/users -> {code}")
# 2.8 an attachment through the front door
_, tok, _ = login_form(t["u"], t["pw"])
code, out = w.app_curl(SUB, "/api/transactions?q=" + t["desc"], "-H", f"Authorization: Bearer {tok}")[1:]
try:
items = json.loads(out)
items = items.get("items") or items.get("transactions") or items.get("data") or []
txid = items[0]["id"]
except Exception:
txid = None
say(f"2.8 could not read the seeded transaction's id: {code} {out[:120]!r}")
if txid:
png = os.path.join(w.SC, "receipt.png")
import base64
open(png, "wb").write(base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="))
r = w.sh(["curl", "-sk", "-H", f"Host: {HOST}", "-H", f"Authorization: Bearer {tok}", "-w", "\n%{http_code}",
"-F", f"file=@{png};type=image/png", f"{w.BASE}/api/transactions/{txid}/attachments"])
body, _, code = (r.stdout or "").rpartition("\n")
say(f"2.8 upload a receipt: POST /api/transactions/<id>/attachments -> {code.strip()} {body[:120]!r}")
try:
aid = json.loads(body)["id"]
except Exception:
aid = None
if aid:
for path in (f"/api/transactions/{txid}/attachments/{aid}", f"/api/attachments/{aid}",
f"/api/transactions/{txid}/attachments/{aid}/download"):
r = w.sh(["curl", "-sk", "-H", f"Host: {HOST}", "-H", f"Authorization: Bearer {tok}", "-o",
os.path.join(w.SC, "receipt-back.png"), "-w", "%{http_code}", f"{w.BASE}{path}"])
if (r.stdout or "").strip() == "200":
same = open(png, "rb").read() == open(os.path.join(w.SC, "receipt-back.png"), "rb").read()
noauth = stranger(path)[0]
say(f"2.8 read it back: GET {path} -> 200, bytes identical={same}; without a token -> {noauth}")
break
else:
say("2.8 no download route answered 200 (tried three shapes) — read the app's routes")
# 1.8, 1.5, 2.7
code, out = stranger("/api/no-such-thing-" + secrets.token_hex(3))
say(f"1.8 an unknown API path -> {code} {out[:100]!r} (a stack trace would show 'Traceback' or 'File \"')")
say("1.5 the server processes:", w.guest("for c in securo-backend securo-worker securo-beat; do echo \"$c: $(docker exec $c "
"sh -c 'tr \"\\0\" \" \" < /proc/1/cmdline')\"; done"))
say("2.7 sizes:", w.guest("docker exec securo-db psql -U securo -d securo -Atc \"select pg_size_pretty(pg_database_size('securo'))\"; "
"docker exec securo-backend du -sh /app/data/attachments"))
# 4.4 the negative control: the backend stopped, the controller's own state and the front door
w.guest("docker stop securo-backend >/dev/null")
seen = []
for s in range(0, 120, 5):
time.sleep(5)
st = w.stack(APP).get("state")
seen.append((s + 5, st))
if st not in ("running",):
break
say(f"4.4 securo-backend STOPPED: the controller's state over time {seen}; front door /api/health -> {stranger('/api/health')[0]}")
w.guest("docker start securo-backend >/dev/null")
for s in range(0, 180, 5):
time.sleep(5)
if w.stack(APP).get("state") == "running":
break
say(f"4.4 started again: state {w.stack(APP).get('state')} after ~{s + 5} s; seed reads back: {FX.verify(w, SUB, t, say)}")
def remove_phase():
w.login()
say("2.6 remove, keeping data (the product's own remove, remove_hdd_data=false):")
code, d = w.ctl("POST", f"/api/stacks/{APP}/remove", {"remove_hdd_data": False, "remove_backups": False})
say(" ->", code, str(d)[:120])
time.sleep(20)
say(" left:", w.guest("docker ps -a --filter name=securo --format '{{.Names}}'; docker volume ls --format '{{.Name}}' | grep -i securo; "
"ls /opt/docker/stacks/securo/ 2>&1"))
def checks2():
"""The second run of 3.6, 2.8 and 4.4's read-back (2026-11-15): the tunnel body fixed, and a 61 s pause before each
part — every LAN visitor shares ONE rate-limit key ("unknown"), so the first run's many LAN sign-ins hit 429."""
w.login()
t = tokens()
w.GATE[SUB] = ""
bad = urlencode({"username": t["u"], "password": "wrong-" + secrets.token_hex(4)})
good = urlencode({"username": t["u"], "password": t["pw"]})
time.sleep(61)
w.guest("docker exec securo-redis redis-cli --scan --pattern 'rate_limit:*' | xargs -r docker exec -i securo-redis redis-cli del >/dev/null")
say("3.6 control first: tunnel visitor B, right password ->", tunnel("/api/auth/login", "198.51.100.77", good, "B0", visitor="198.51.100.77"))
say("3.6 lock-out: 8 wrong passwords from tunnel visitor A, then the household's right password from A, from B, from the LAN:")
codes = [tunnel("/api/auth/login", "198.51.100.66", bad, "A") for _ in range(8)]
say(f" A's 8 wrong tries: {codes}")
say(f" A, right password -> {tunnel('/api/auth/login', '198.51.100.66', good, 'A-right')}")
say(f" B, right password -> {tunnel('/api/auth/login', '198.51.100.77', good, 'B-right', visitor='198.51.100.77')}")
say(f" LAN, right password -> {login_form(t['u'], t['pw'])[0]}")
say(f" A forging a new leftmost entry, right password -> "
f"{tunnel('/api/auth/login', '10.9.9.9, 198.51.100.66', good, 'A-forged')}")
say(f" the keys: {redis_keys()}")
time.sleep(61)
say(f" A, right password 61 s later -> {tunnel('/api/auth/login', '198.51.100.66', good, 'A-later')}")
time.sleep(61)
_, tok, _ = login_form(t["u"], t["pw"])
code, out = w.app_curl(SUB, "/api/transactions?q=" + t["desc"], "-H", f"Authorization: Bearer {tok}")[1:]
try:
d = json.loads(out)
items = d.get("items") or d.get("transactions") or d.get("data") or []
txid = items[0]["id"]
except Exception:
txid = None
say(f"2.8 could not read the seeded transaction's id: {code} {out[:200]!r}")
if txid:
import base64
png = os.path.join(w.SC, "receipt.png")
open(png, "wb").write(base64.b64decode(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="))
r = w.sh(["curl", "-sk", "-H", f"Host: {HOST}", "-H", f"Authorization: Bearer {tok}", "-w", "\n%{http_code}",
"-F", f"file=@{png};type=image/png", f"{w.BASE}/api/transactions/{txid}/attachments"])
body, _, code = (r.stdout or "").rpartition("\n")
say(f"2.8 upload a receipt through traefik: POST /api/transactions/<id>/attachments -> {code.strip()} "
f"{re.sub(r'[0-9a-f-]{36}', '<id>', body)[:200]!r}")
try:
aid = json.loads(body)["id"]
except Exception:
aid = None
if aid:
back = os.path.join(w.SC, "receipt-back.png")
for path in (f"/api/transactions/{txid}/attachments/{aid}", f"/api/transactions/{txid}/attachments/{aid}/download",
f"/api/attachments/{aid}"):
r = w.sh(["curl", "-sk", "-H", f"Host: {HOST}", "-H", f"Authorization: Bearer {tok}", "-o", back,
"-w", "%{http_code}", f"{w.BASE}{path}"])
say(f"2.8 GET {re.sub(r'[0-9a-f-]{36}', '<id>', path)} -> {(r.stdout or '').strip()}")
if (r.stdout or "").strip() == "200":
same = open(png, "rb").read() == open(back, "rb").read()
say(f"2.8 read it back: bytes identical={same}; the same GET without a token -> {stranger(path)[0]}")
break
time.sleep(61)
say(f"4.4 (after the restart of the first run) the seed reads back: {FX.verify(w, SUB, t, say)}")
def _drill(msg, a, b):
"""One drill commit moving every securo image tag a -> b (the frontend and the backend x3), loaded into the box."""
import subprocess
D = w.DRILL
g = lambda *x: subprocess.run(["git", "-C", D] + list(x), capture_output=True, text=True, timeout=120)
g("pull", "-q", "--rebase", "origin", "main")
f = f"{D}/templates/{APP}/docker-compose.yml"
c = open(f).read()
n = c.count(f":{a}\n")
open(f, "w").write(c.replace(f":{a}\n", f":{b}\n"))
g("add", f"templates/{APP}")
g("commit", "-q", "-m", msg)
r = g("push", "-q", "origin", "main")
say(f" drill: {n} image lines {a} -> {b} ({msg}; push rc={r.returncode}, head {g('rev-parse', '--short=12', 'HEAD').stdout.strip()})")
w.refresh_box_mirror()
def restore_phase():
"""2.5 + 2.6: a per-app backup exists only from the guarded Update's backing-up phase (R-648: no whole-box press
from a drill), so: install at 0.17.0, seed, update to 0.18.0 (the backup), remove KEEPING backups, restore through
the household's own button, read back; then 2.6's two removes."""
w.login()
if w.stack(APP).get("deployed"):
say("2.5 removing the checks install first (scratch box)")
w.remove(APP)
_drill("DRILL securo: back to 0.17.0 for the restore case (2.5), moved forward again in the same run", "0.18.0", "0.17.0")
w.sync_rescan()
if not w.deploy(APP, SUB):
say("2.5 the install at 0.17.0 did not complete")
return
w.wait_app(SUB, "/api/health", want=("200",), tries=60)
t = FX.seed(w, SUB, say)
if not t or not FX.verify(w, SUB, t, say):
say("2.5 C1 failed — stop")
return
fd = os.open(TOK, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
os.write(fd, json.dumps(t).encode())
os.close(fd)
_drill("DRILL securo: forward to 0.18.0 again (2.5)", "0.17.0", "0.18.0")
w.sync_rescan(APP, "ghcr.io/securo-finance/securo-backend:0.18.0", tries=40, delay=10)
u = w.press_update(APP, poll=1.0, cap_s=1800)
say(f"2.5 the guarded Update (its backing-up phase is the per-app backup): final phase {u.get('final_phase')!r}")
time.sleep(15)
say("2.5 read-back after the update:", FX.verify(w, SUB, t, say))
snaps = w.snapshots(APP)
say(f"2.5 restorable copies offered: {len(snaps)}: " + "; ".join(str({k: v for k, v in x.items() if k in ('id', 'short_id', 'time', 'created', 'tier', 'kind', 'source')}) for x in snaps[:4]))
code, d = w.ctl("POST", f"/api/stacks/{APP}/stop")
time.sleep(10)
code, d = w.ctl("POST", f"/api/stacks/{APP}/remove", {"remove_hdd_data": True, "remove_backups": False})
say(f"2.5 remove, KEEPING backups -> {code} {str(d)[:160]}")
time.sleep(10)
say("2.5 left after that remove:", w.guest("docker ps -a --filter name=securo --format '{{.Names}}'; docker volume ls --format '{{.Name}}' | grep -i securo; ls /opt/docker/stacks/securo/"))
r = w.restore(APP)
say(f"2.5 restore: {str({k: v for k, v in r.items() if k not in ('observables_after', 'snapshots')})[:400]}")
w.GATE.pop(SUB, None)
w.wait_app(SUB, "/api/health", want=("200",), tries=60)
say("2.5 after the restore — the seeded account and transaction, and the household's own password:", FX.verify(w, SUB, t, say))
say("2.5 the setup gate after the restore:", w.setup_gate_probe(SUB))
# 2.6
w.ctl("POST", f"/api/stacks/{APP}/stop")
time.sleep(10)
code, d = w.ctl("POST", f"/api/stacks/{APP}/remove", {"remove_hdd_data": False, "remove_backups": False})
say(f"2.6 remove, keep data -> {code} {str(d)[:200]}")
time.sleep(10)
say("2.6 left:", w.guest("docker ps -a --filter name=securo --format '{{.Names}}'; docker volume ls --format '{{.Name}}' | grep -i securo; ls /opt/docker/stacks/securo/"))
if __name__ == "__main__":
{"install": install, "checks": checks, "checks2": checks2, "restore": restore_phase, "remove": remove_phase}[phase]()