D39 = B: the security-fix lane — a security_fix ladder step (box walk required, bench optional, CVE/GHSA notice), its gates + 8 decoys, the writer (--write-ladder --security), the box venue (box_walk.py --security, drill-mirror refresh); two stale tests fixed
gates / gates (push) Successful in 58s

09 §3 decision 255, R-1239. Proven on 9202 (drill catalog) — felhom.eu audits/security-lane-2026-10-23/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012qRErfCoiTkvDK9N5XHbzb
This commit is contained in:
adminandClaude Opus 5.5 committed 2026-10-23 13:08:51 +02:00
1 parent cde26abc02
commit 3898593594
12 files changed
+755 -36

No files matched your search

+271
View File
@@ -423,9 +423,35 @@ def _drill_bump(app, frm, to, service_hint=None):
r = sh(["git", "-C", DRILL, "push", "-q", "origin", "main"], timeout=120)
h = sh(["git", "-C", DRILL, "rev-parse", "--short=12", "HEAD"]).stdout.strip()
say(f" [5] drill commit {h}: {app} {frm} -> {to} (push rc={r.returncode})")
refresh_box_mirror()
return h
BOX_VOL = "/var/lib/docker/volumes/felhom-controller-data/_data" # the controller's data volume, guest path
BOX_CVOL = "/opt/docker/felhom-controller" # the same, inside the controller container
MIRROR_URL = f"file://{BOX_CVOL}/drill-catalog.git"
def refresh_box_mirror():
"""A box pointed at the drill through its LOCAL MIRROR (R-992: no catalog credential on the box — the mirror method of
felhom.eu audits/burndown-3-2026-10-17/tools/repoint.py) sees a drill commit only after the mirror is loaded again.
Without this a drill commit reaches Gitea and never the box, and a walk then presses Update on nothing. A box on any
other catalog URL is left alone (it fetches the drill itself)."""
conf = guest(f"grep -E '^\\s+repo_url:' {BOX_VOL}/controller.yaml")
if MIRROR_URL not in conf:
return False
import secrets as _s
b = f"/tmp/drill-walk-{os.getpid()}-{_s.token_hex(4)}.bundle"
sh(["git", "-C", DRILL, "bundle", "create", b, "main"])
sh(["scp", "-q", "-o", "StrictHostKeyChecking=accept-new"] + (["-J", _T["jump"]] if _T["jump"] else [])
+ [b, f"{_T['ssh']}:{b}"], timeout=120)
sh(ssh_args() + [f"pct push {GUEST} {b} {BOX_VOL}/{os.path.basename(b)} && rm -f {b}"], timeout=120)
out = guest(f"""docker exec felhom-controller sh -c 'git -C {BOX_CVOL}/drill-catalog.git fetch -q {BOX_CVOL}/{os.path.basename(b)} +main:main && rm -f {BOX_CVOL}/{os.path.basename(b)}; git -C {BOX_CVOL}/drill-catalog.git log -1 --format="%h" main'""")
os.remove(b)
say(f" [5] the box's drill mirror now at {out.strip()}")
return True
def sync_rescan(expect_app=None, expect_ref=None, tries=12, delay=5):
"""Sync, rescan, and — when told what to expect — WAIT FOR THE BADGE TO CATCH UP.
@@ -635,3 +661,248 @@ def restore(name, snapshot_id=None, wait_s=1200):
"http": head, "location": loc[:1], "seconds": round(time.time() - t0, 1),
"state_after": st.get("state"), "hold_after": st.get("hold_reason"),
"observables_after": observables(name)}
# ------------------------------------------------------------------ the security-fix walk (D39 = B)
SECURITY_WALK_VERSION = 1
SOAK_DEFAULT_S = 600
def soak(name, seconds, interval=10):
"""The box's memory soak (`09` §3 decision 255): every `interval` s for `seconds`, per container of the app, the
app's own memory (cgroup `anon`, decision 22 — the cgroup peak counts the file cache) against its limit, the
cgroup peak, the OOM-kill counter and the restart count. One guest call; the guest prints one JSON line a sample."""
script = f"""
set -u
ids=$(docker ps -a --filter label=com.docker.compose.project={name} --format '{{{{.ID}}}}')
end=$(( $(date +%s) + {int(seconds)} ))
while :; do
for id in $ids; do
full=$(docker inspect -f '{{{{.Id}}}}' $id); nm=$(docker inspect -f '{{{{.Name}}}}' $id | tr -d /)
rc=$(docker inspect -f '{{{{.RestartCount}}}}' $id); run=$(docker inspect -f '{{{{.State.Running}}}}' $id)
start=$(docker inspect -f '{{{{.State.StartedAt}}}}' $id); oomk=$(docker inspect -f '{{{{.State.OOMKilled}}}}' $id)
cg=""; for c in /sys/fs/cgroup/system.slice/docker-$full.scope /sys/fs/cgroup/docker/$full; do [ -d "$c" ] && cg=$c; done
anon=0; mx=max; pk=0; ok=0
if [ -n "$cg" ]; then
anon=$(awk '$1=="anon"{{print $2}}' $cg/memory.stat); mx=$(cat $cg/memory.max)
pk=$(cat $cg/memory.peak 2>/dev/null || echo 0); ok=$(awk '$1=="oom_kill"{{print $2}}' $cg/memory.events)
fi
printf '{{"t":%s,"c":"%s","anon":%s,"max":"%s","peak":%s,"oom_kill":%s,"restarts":%s,"running":"%s","started":"%s","oomkilled":"%s","cg":"%s"}}\\n' \\
"$(date +%s)" "$nm" "${{anon:-0}}" "$mx" "${{pk:-0}}" "${{ok:-0}}" "$rc" "$run" "$start" "$oomk" "$cg"
done
[ "$(date +%s)" -ge "$end" ] && break
sleep {int(interval)}
done
"""
out = guest(script, timeout=int(seconds) + 300)
samples = []
for line in out.splitlines():
try:
samples.append(json.loads(line))
except ValueError:
continue
per = {}
for s in samples:
c = per.setdefault(s["c"], {"samples": 0, "anon_peak": 0, "cg_peak": 0, "limit": None, "oom_kill": [],
"restarts": [], "running": [], "started": set(), "oomkilled": False, "cgroup": s["cg"]})
c["samples"] += 1
c["anon_peak"] = max(c["anon_peak"], int(s["anon"]))
c["cg_peak"] = max(c["cg_peak"], int(s["peak"]))
c["limit"] = int(s["max"]) if str(s["max"]).isdigit() else None
c["oom_kill"].append(int(s["oom_kill"]))
c["restarts"].append(int(s["restarts"]))
c["running"].append(s["running"] == "true")
c["started"].add(s["started"])
c["oomkilled"] = c["oomkilled"] or s["oomkilled"] == "true"
res = {"soak_s": int(seconds), "interval_s": interval, "samples": len(samples), "containers": {}}
kills = restarts = 0
peaks = []
for nm, c in per.items():
k = (max(c["oom_kill"]) - min(c["oom_kill"])) if c["oom_kill"] else 0
r = (max(c["restarts"]) - min(c["restarts"])) + (len(c["started"]) - 1)
kills += k + (1 if c["oomkilled"] else 0)
restarts += r
pct = round(100.0 * c["anon_peak"] / c["limit"], 1) if c["limit"] else None
cgp = round(100.0 * c["cg_peak"] / c["limit"], 1) if c["limit"] else None
if pct is not None:
peaks.append(pct)
res["containers"][nm] = {"samples": c["samples"], "anon_peak_bytes": c["anon_peak"], "limit_bytes": c["limit"],
"anon_peak_pct": pct, "cgroup_peak_pct": cgp, "oom_kill_delta": k,
"oom_killed_flag": c["oomkilled"], "restarts_delta": r,
"running_all_samples": all(c["running"]), "cgroup": c["cgroup"]}
res["oom_kills"], res["restarts"] = kills, restarts
res["peak_pct"] = max(peaks) if peaks else None
return res
def setup_gate_probe(sub):
"""How the setup gate (decision 46) answers this app right now, as the household's browser and as a script: status and
redirect target only (the cookie is never printed)."""
out = {}
for label, hdr in (("browser", ["-H", "Accept: text/html"]), ("script", [])):
r = sh(["curl", "-sk", "-D", "-", "-o", "/dev/null", "-H", f"Host: {sub}.{DOMAIN}"] + hdr + [f"{BASE}/identity"])
st = re.match(r"HTTP/\S+ (\d+)", r.stdout or "")
loc = _loc(r.stdout)
out[label] = {"status": st.group(1) if st else None, "redirect": re.sub(r"\?.*", "?…", loc) if loc else None}
return out
def security_walk(app, frm, to, evdir, soak_s=SOAK_DEFAULT_S, values=None):
"""`box_walk.py --security <app> --from <svc=ref,…> --to <svc=ref,…> --ev <dir> [--soak N] [--value K=V …]` — the BOX venue of a
security-fix step (`09` §3 decision 255, D39 = B), on scratch guest 9202 pointed at the DRILL catalog, through the
product's own endpoints only:
1. the drill's template for <app> must stand at FROM (the caller puts it there; this walk never guesses);
2. <app> is installed fresh; the four version observables must read FROM;
3. seed + read-back when a box fixture has the app, else `seed: "none"` — written, never hidden;
4. a DRILL-only commit moves the compose FROM -> TO; sync + rescan until the box's catalog_images carry TO;
5. the product's guarded Update, every phase with its time;
6. after: final phase `done`, no undo, no hold, the app running, the four observables equal TO, the seed read back;
7. the memory soak (default 600 s): a kill or a restart = failed;
8. <evdir>/box-verdict-<app>.json: `proven` only if all of that holds; `inconclusive` stays `inconclusive`.
The app is removed through the product at the end unless KEEP=1."""
import upgrade_fixtures_box as fixtures
import upgrade_fixtures_box28 as _f28
global LOG
LOG = []
FX = dict(_f28.FIXTURES28)
FX.update(fixtures.FIXTURES)
os.makedirs(evdir, exist_ok=True)
rec = {"app": app, "walk": "security", "box_walk_version": SECURITY_WALK_VERSION, "verdict": "inconclusive",
"venue": f"box {GUEST} (drill catalog), the guarded Update", "from": frm, "to": to}
def finish(verdict, why):
rec["verdict"], rec["why"] = verdict, why
rec["log"] = LOG
write_verdict(rec, evdir)
os.replace(os.path.join(evdir, "verdict.json"), os.path.join(evdir, f"box-verdict-{app}.json"))
say(f"RESULT {verdict} — {why}")
if not os.environ.get("KEEP") and stack(app).get("deployed"):
remove(app)
return 0 if verdict == "proven" else 1
login()
conf = guest("grep -A3 '^git:' /var/lib/docker/volumes/felhom-controller-data/_data/controller.yaml")
if "app-catalog-drill" not in conf and MIRROR_URL not in conf:
return finish("inconclusive", f"guest {GUEST} is not on the drill catalog (nor its local mirror) — nothing done")
sh(["git", "-C", DRILL, "pull", "-q", "--rebase", "origin", "main"], timeout=120)
drill_imgs = images_of(open(f"{DRILL}/templates/{app}/docker-compose.yml").read())
if drill_imgs != frm:
return finish("inconclusive", f"the drill's {app} is at {drill_imgs}, not at FROM {frm} — put it there first")
fx = FX.get(app)
sub = getattr(fx, "sub", app) if fx else app
if stack(app).get("deployed"):
say(f" [1] removing the existing {app} first (scratch box)")
remove(app)
sync_rescan()
if not deploy(app, sub, values):
return finish("inconclusive", "the install at FROM did not complete — nothing was tested")
wait_app(sub, "/identity" if app == "plex" else "/", tries=60)
rec["observables_before"] = observables(app)
if rec["observables_before"]["pinned_images"] != frm:
return finish("inconclusive", f"installed at {rec['observables_before']['pinned_images']}, not at FROM")
rec["setup_gate_before"] = setup_gate_probe(sub)
say(f" [2] setup gate as installed: {rec['setup_gate_before']}")
tok = None
if fx is None or fx.__class__.__name__ == "NoRoute":
rec["seed"] = "none"
rec["seed_why"] = getattr(fx, "tried", "no box fixture for this app")
say(f" [3] seed: none — {rec['seed_why']}")
else:
tok = fx.seed(w_self(), sub, say)
if tok is None or not fx.verify(w_self(), sub, tok, say):
return finish("inconclusive", "C1: the fixture could not seed and read back before the update")
rec["seed"] = "read_back"
froms = ",".join(frm[s] for s in sorted(frm) if frm[s] != to.get(s))
tos = ",".join(to[s] for s in sorted(frm) if frm[s] != to.get(s))
rec["drill_commit"] = drill_bump(app, froms, tos)
if not rec["drill_commit"]:
return finish("inconclusive", "the drill could not be moved FROM -> TO")
moved = [s for s in sorted(to) if frm.get(s) != to[s]]
rec["sync_waited_s"] = sync_rescan(app, to[moved[0]], tries=40, delay=10)
if rec["sync_waited_s"] is None:
return finish("inconclusive", f"the box never read TO {to[moved[0]]} from the drill catalog — nothing pressed")
rec["badge_before"] = badges(app)
rec["measured_at"] = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
rec["update"] = press_update(app, poll=1.0, cap_s=1800)
time.sleep(15)
st = stack(app)
rec["observables_after"] = obs = observables(app)
rec["badge_after"] = badges(app)
rec["state_after"], rec["hold_after"] = st.get("state"), st.get("hold_reason")
ii = (st.get("app_config") or {}).get("installed_images") or {}
rec["to_digests"] = {s: (ii.get(s) or {}).get("digest") if isinstance(ii.get(s), dict) else None for s in to}
u = rec["update"]
if not u.get("accepted"):
return finish("failed", f"the Update was refused: {u.get('http')} {str(u.get('refusal'))[:200]}")
if u.get("final_phase") != "done" or u.get("update_error") or rec["hold_after"]:
return finish("failed", f"the update ended {u.get('final_phase')!r} (error {u.get('update_error')!r}, hold {rec['hold_after']!r})")
live = sorted({l.split("image:", 1)[1].strip() for l in obs.get("live_compose_image_lines") or [] if "image:" in l})
four = {"pinned": obs.get("pinned_images"), "installed": obs.get("installed_images"), "catalog": obs.get("catalog_images"),
"live_compose": live}
rec["four_observables"] = four
running = {l.split()[1] for l in obs.get("docker_inspect") or [] if "running=true" in l}
bad = {k: v for k, v in four.items() if k != "live_compose" and v != to}
if bad or set(live) != set(to.values()) or not set(to.values()) <= running:
return finish("failed", f"the version observables are not TO: {bad or four['live_compose']}, running {sorted(running)}")
if rec["state_after"] != "running":
return finish("failed", f"the app is {rec['state_after']!r} after the update")
if tok is not None:
rec["seed_read_after"] = fx.verify(w_self(), sub, tok, say)
if not rec["seed_read_after"]:
return finish("failed", "the seed did not read back after the update")
if any(not d for d in rec["to_digests"].values()):
return finish("inconclusive", f"the box recorded no digest for a TO service: {rec['to_digests']}")
rec["setup_gate_after"] = setup_gate_probe(sub)
say(f" [7] memory soak {soak_s} s …")
rec["memory"] = m = soak(app, soak_s)
say(f" [7] soak: peak {m.get('peak_pct')}% of the limit (anon), kills {m.get('oom_kills')}, restarts {m.get('restarts')}")
if m.get("samples", 0) == 0 or m.get("peak_pct") is None:
return finish("inconclusive", "the soak read no sample — not a pass")
if m["oom_kills"] or m["restarts"] or not all(c["running_all_samples"] for c in m["containers"].values()):
return finish("failed", f"the soak saw {m['oom_kills']} OOM kill(s) and {m['restarts']} restart(s)")
return finish("proven", "the security-fix step ran on the box through the guarded Update; healthy, TO on all four "
"observables, no undo, no hold, a clean soak" + ("" if tok is None else ", seed read back"))
def images_of(compose_text):
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import ladder
return ladder.images_in(compose_text)
def w_self():
return sys.modules[__name__]
def _refs(spec):
"""`svc=ref,svc2=ref2` -> {svc: ref}."""
out = {}
for part in spec.split(","):
k, _, v = part.strip().partition("=")
if k and v:
out[k] = v
return out
def main(argv):
ap = argparse.ArgumentParser(prog="box_walk.py")
ap.add_argument("--security", metavar="APP", required=True,
help="the security-fix walk (09 decision 255) for this app")
ap.add_argument("--from", dest="frm", required=True, help="svc=ref,… the drill must stand at")
ap.add_argument("--to", required=True, help="svc=ref,… the step moves to")
ap.add_argument("--ev", required=True, help="evidence directory")
ap.add_argument("--soak", type=int, default=SOAK_DEFAULT_S)
ap.add_argument("--value", action="append", default=[], metavar="KEY=VAL",
help="a deploy field the wizard would get from the household (e.g. HDD_PATH=<the drive>)")
a = ap.parse_args(argv)
frm, to = _refs(a.frm), _refs(a.to)
if set(frm) != set(to):
print("box_walk: --from and --to must name the same services")
return 2
vals = dict(v.split("=", 1) for v in a.value if "=" in v)
return security_walk(a.security, frm, to, a.ev, a.soak, vals or None)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))