The privileges gate: the early warning for the box's catalog allow-list (R-971, D2 = A)
gates / gates (push) Successful in 7s

check-privileges.py (stdlib, --fast) judges every template and ladder step against the same classes the
controller v0.328.0 refuses; scripts/privilege-allowlist.json is a byte-identical copy of the controller's list.
Decoys + a reader-equals-PyYAML check in test_gate_decoys.py.

Claude-Session: https://claude.ai/code/session_0159rPz1ZhFKsS53msqPYxtS
This commit is contained in:
admin committed 2026-10-17 16:34:37 +02:00
1 parent 1af6ea7508
commit d5a443dbd1
5 files changed
+619

No files matched your search

+18
View File
@@ -1,3 +1,21 @@
## 2026-10-17 — the privileges gate: the early warning for the box's catalog allow-list (R-971, operator decision D2 = A)
- New gate `privileges` (`scripts/check-privileges.py`, `--fast`: the hook and CI). Since controller v0.328.0 the BOX
refuses, before it writes any app compose, every container right not on its compiled allow-list (privileged,
cap_add, devices, host namespaces, security_opt other than no-new-privileges, sysctls, volumes_from, build/include/
extends, env_file or config files outside the stack dir, aliasing named volumes, binds outside `${HDD_PATH}` /
`${USERDATA_PATH}` / `${IMPORT_PATH}`, the Docker socket, mount propagation, a `${VAR}` in a privileged key). This gate
judges every `templates/<app>/docker-compose.yml` AND every `steps/*.yml` the same way, so a bad template fails here
instead of being refused on every box. The box is the authority.
- `scripts/privilege-allowlist.json` is a byte-identical copy of the controller's `internal/privpolicy/allowlist.json`
(one entry today: homepage's read-only Docker socket); the gate checks the copy against the sibling clone when it is
there, and the controller's `TestAllowList_CatalogCopyIsIdentical` does the same from its side.
- Standard library only (CI has no PyYAML): a small compose reader; the decoy suite checks it equals PyYAML on all 123
catalog files. Decoys in `test_gate_decoys.py` (`privileges`): 6 genuine/decoy passes, 11 facts refused, rc 3 on no
templates; red-proved (with the allow-list check disabled, the 10 refusal cases fail).
- Survey: all 123 files, nothing in any class except homepage's socket (felhom.eu
`audits/agent-allowlist-rotation-2026-10-17/P2/survey.md`).
## 2026-10-17 — the 23 memory requests set to measured use (R-1125, operator decision D10 = A)
- `mem_request` of 23 apps = their typical use from the 2026-10-13 sizing run (`catalog-check.json`), rounded up (below
+7
View File
@@ -34,6 +34,8 @@ Gates, in order (all must pass; **non-zero exit on any failure**):
14. guide-version static, instant, ADVISORY — a user guide's checked_version is not the image tag the app
runs: a WARN naming both versions, and exit 0 always (it never fails a push)
16. redis-persistence static, instant, whole repo — no template's Redis/Valkey service runs append-only (R-1096)
17. privileges static, instant, whole repo — no template or ladder step asks for a container right the box's
allow-list does not give (R-971); the box (controller >= 0.328.0) refuses on its own
15. gate-decoys the decoy suite (test_gate_decoys.py) — each gate above still convicts its decoys
(R-1115). ~3 minutes, needs PyYAML: the full run only, never --fast
4. engine-major static, needs GIT HISTORY — no database engine pin crosses a MAJOR version
@@ -155,6 +157,11 @@ GATES = [
# R-1096 (2026-10-17): no catalog Redis runs append-only — a damaged AOF keeps Redis (and its app) down until a
# person repairs it; snapshots are written by temp-file-and-rename. Static, stdlib only: the hook and CI.
("redis-persistence", "check-redis-persistence.py", False, True, False),
# R-971 (2026-10-17, operator decision D2 = A): no template or ladder step asks for a container right the BOX's
# allow-list does not give (privileged, cap_add, devices, host namespaces, the Docker socket, binds outside the
# data roots, ...). The box (controller >= 0.328.0) is the authority and refuses on its own; this is the early
# warning, so a bad template fails here instead of on every box. Static, stdlib only: the hook and CI.
("privileges", "check-privileges.py", False, True, False),
# R-1115 (2026-10-17): the gates' OWN decoy suite — every gate above is red-proved against its decoys here. It
# was not in this table, so a case that stopped convicting (a template edit removed its premise) failed for a
# night with nobody looking. Static (a local clone, a stub docker), but ~3 minutes and it needs PyYAML, so NOT
+508
View File
@@ -0,0 +1,508 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""check-privileges.py — no template asks for container rights the box's allow-list does not give (R-971).
python3 scripts/check-privileges.py # every templates/<app>/docker-compose.yml and steps/*.yml
python3 scripts/check-privileges.py --root DIR # another checkout (the decoy harness)
WHY (R-971, operator decision D2 = A, 2026-10-17). A push to this repo's `main` reaches every installed app within
about 15 minutes. Since controller v0.328.0 the BOX refuses, before it writes any app compose, every setting in the
classes below unless that app's service has exactly that setting on the allow-list compiled into the controller
(felhom-controller `internal/privpolicy`). THE BOX IS THE AUTHORITY; this gate is the early warning, so a bad template
fails here before it is pushed instead of being refused on every box and alarming the operator.
THE CLASSES (the same setting strings as the controller's — a mismatch makes this gate and the box disagree):
privileged, cap_add, device, device_cgroup_rule, network_mode, pid, ipc, uts, userns_mode, cgroup, security_opt
(except no-new-privileges), sysctl, volumes_from, build, extends_file, env_file outside the stack dir, bind (a host
path outside ${HDD_PATH} / ${USERDATA_PATH} / ${IMPORT_PATH}, the Docker socket anywhere, mount propagation), volume
(driver / driver_opts / external / name), config_file / secret_file outside the stack dir, include, and
`interpolated <key>` for a ${VAR} inside any of the privileged keys.
THE LIST: scripts/privilege-allowlist.json, a BYTE-IDENTICAL copy of the controller's
internal/privpolicy/allowlist.json (pinned there by TestAllowList_CatalogCopyIsIdentical, and here by this gate when the
sibling clone is present). Why a copy and not a fetch: a fetch needs the network in CI and a pinned commit to be
reproducible; two identical files and one equality check is the boring version, and either side's test catches drift.
STANDARD LIBRARY ONLY (the CI runner has no PyYAML): a small reader for the subset compose files use here (block maps
and lists, flow lists and maps, quoted and plain scalars, block scalars, comments). The decoy suite checks it against
PyYAML on every catalog file where PyYAML exists.
Exit 0 clean · 1 a template asks for a right not on the list · 3 nothing to judge.
"""
import io
import json
import os
import re
import sys
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
ALLOWLIST = os.path.join("scripts", "privilege-allowlist.json")
CONTROLLER_COPY = os.path.join("..", "felhom-controller", "controller", "internal", "privpolicy", "allowlist.json")
PLACEHOLDER_ENV = {
"HDD_PATH": "/mnt/felhom-drives/check/felhom-data",
"USERDATA_PATH": "/mnt/felhom-drives/check/felhom-data/userdata",
"IMPORT_PATH": "/mnt/felhom-drives/check/felhom-data/userdata/import",
"DOMAIN": "example.invalid",
"SUBDOMAIN": "check",
}
ROOT_VARS = ("HDD_PATH", "USERDATA_PATH", "IMPORT_PATH")
SCALAR_KEYS = ("network_mode", "pid", "ipc", "uts", "userns_mode", "cgroup")
PRIVILEGED_KEYS = ("privileged", "cap_add", "devices", "device_cgroup_rules", "network_mode", "pid", "ipc", "uts",
"userns_mode", "cgroup", "security_opt", "sysctls", "volumes_from")
# ---------- a small YAML reader for compose files ----------
class YamlError(Exception):
pass
def _strip_comment(line):
out, q = [], None
for i, c in enumerate(line):
if q:
out.append(c)
if c == q:
q = None
continue
if c in "'\"" and (i == 0 or line[i - 1] in " \t[{,:-"):
q = c
elif c == "#" and (i == 0 or line[i - 1] in " \t"):
break
out.append(c)
return "".join(out).rstrip()
def _split_flow(s):
items, depth, cur, q = [], 0, [], None
for c in s:
if q:
cur.append(c)
if c == q:
q = None
continue
if c in "'\"":
q = c
elif c in "[{":
depth += 1
elif c in "]}":
depth -= 1
elif c == "," and depth == 0:
items.append("".join(cur).strip())
cur = []
continue
cur.append(c)
if "".join(cur).strip():
items.append("".join(cur).strip())
return items
def _key_split(s):
"""'key: value' -> (key, value) | None — a colon followed by a space or the end, outside quotes."""
q = None
for i, c in enumerate(s):
if q:
if c == q:
q = None
continue
if c in "'\"":
q = c
elif c == ":" and (i + 1 == len(s) or s[i + 1] == " "):
return _scalar(s[:i].strip()), s[i + 1:].strip()
elif c in "[{" and i == 0:
return None
return None
def _scalar(s):
s = s.strip()
if s.startswith("[") and s.endswith("]"):
return [_scalar(x) for x in _split_flow(s[1:-1])]
if s.startswith("{") and s.endswith("}"):
m = {}
for it in _split_flow(s[1:-1]):
kv = _key_split(it)
if kv:
m[kv[0]] = _scalar(kv[1]) if kv[1] != "" else None
return m
if len(s) >= 2 and s[0] == s[-1] and s[0] in "'\"":
body = s[1:-1]
return body.replace("''", "'") if s[0] == "'" else body.replace('\\"', '"').replace("\\\\", "\\")
if s in ("true", "True", "TRUE"):
return True
if s in ("false", "False", "FALSE"):
return False
if s in ("", "~", "null", "Null", "NULL"):
return None
if re.fullmatch(r"-?[0-9]+", s):
return int(s)
return s
def load(text):
raw = text.split("\n")
lines = [] # (indent, content, rawline)
i = 0
while i < len(raw):
r = raw[i]
if not r.strip() or r.lstrip().startswith("#"):
i += 1
continue
c = _strip_comment(r)
if not c.strip():
i += 1
continue
lines.append((len(c) - len(c.lstrip(" ")), c.strip(), i))
i += 1
pos = [0]
def block_scalar(start_line, parent_indent):
# the lines after `key: |` that are indented deeper than the parent
out = []
j = start_line + 1
while j < len(raw):
r = raw[j]
if r.strip() and (len(r) - len(r.lstrip(" "))) <= parent_indent:
break
out.append(r.strip())
j += 1
# skip the consumed lines in `lines`
while pos[0] < len(lines) and lines[pos[0]][2] < j:
pos[0] += 1
return " ".join(x for x in out if x)
def parse(indent):
if pos[0] >= len(lines):
return None
ind, content, _ = lines[pos[0]]
if content.startswith("- ") or content == "-":
return parse_seq(ind)
return parse_map(ind)
def value_after(ind, rest, lineno):
if rest in ("|", "|-", "|+", ">", ">-", ">+"):
return block_scalar(lineno, ind)
if rest == "":
if pos[0] < len(lines) and (lines[pos[0]][0] > ind or
(lines[pos[0]][0] == ind and lines[pos[0]][1].startswith("- "))):
return parse(lines[pos[0]][0])
return None
return _scalar(rest)
def parse_map(ind):
m = {}
while pos[0] < len(lines):
li, content, lineno = lines[pos[0]]
if li < ind:
break
if li > ind:
raise YamlError("unexpected indent at line %d" % (lineno + 1))
if content.startswith("- "):
break
kv = _key_split(content)
if not kv:
raise YamlError("not a key at line %d" % (lineno + 1))
pos[0] += 1
m[kv[0]] = value_after(ind, kv[1], lineno)
return m
def parse_seq(ind):
seq = []
while pos[0] < len(lines):
li, content, lineno = lines[pos[0]]
if li < ind or not (content.startswith("- ") or content == "-"):
break
if li > ind:
raise YamlError("unexpected indent at line %d" % (lineno + 1))
item = content[2:].strip() if content != "-" else ""
pos[0] += 1
kv = _key_split(item) if item and item[0] not in "[{\"'" else None
if kv:
# a mapping item: `- key: value` and its siblings, indented by the dash's width
sub_ind = ind + 2
first = {kv[0]: value_after(sub_ind, kv[1], lineno)}
while pos[0] < len(lines) and lines[pos[0]][0] == sub_ind and not lines[pos[0]][1].startswith("- "):
c2 = lines[pos[0]][1]
kv2 = _key_split(c2)
if not kv2:
raise YamlError("not a key at line %d" % (lines[pos[0]][2] + 1))
ln2 = lines[pos[0]][2]
pos[0] += 1
first[kv2[0]] = value_after(sub_ind, kv2[1], ln2)
seq.append(first)
elif item in ("|", "|-", "|+", ">", ">-", ">+"):
seq.append(block_scalar(lineno, ind))
elif item == "":
seq.append(parse(lines[pos[0]][0]) if pos[0] < len(lines) and lines[pos[0]][0] > ind else None)
else:
seq.append(_scalar(item))
return seq
doc = parse(0)
if pos[0] != len(lines):
raise YamlError("trailing content at line %d" % (lines[pos[0]][2] + 1))
return doc if isinstance(doc, dict) else {}
# ---------- the check (the controller's privpolicy, line for line) ----------
INTERP = re.compile(r"\$\$|\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?[-?+])([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)")
def render(v, env):
if v is None:
return ""
if isinstance(v, bool):
return "true" if v else "false"
if not isinstance(v, str):
return str(v)
def sub(m):
if m.group(0) == "$$":
return "$"
name, op, arg = m.group(1) or m.group(4), m.group(2), m.group(3) or ""
val, is_set = env.get(name, ""), name in env
if op == ":-" and val == "":
return arg
if op == "-" and not is_set:
return arg
if op == ":+":
return arg if val != "" else ""
if op == "+":
return arg if is_set else ""
return val
return INTERP.sub(sub, v)
def has_interp(v):
if isinstance(v, str):
return "$" in v.replace("$$", "")
if isinstance(v, dict):
return any(has_interp(k) or has_interp(x) for k, x in v.items())
if isinstance(v, list):
return any(has_interp(x) for x in v)
return False
def as_list(v):
if v is None:
return []
return v if isinstance(v, list) else [v]
def canon(v, env):
if isinstance(v, (dict, list)):
def tree(x):
if isinstance(x, dict):
return {k: tree(y) for k, y in x.items()}
if isinstance(x, list):
return [tree(y) for y in x]
return render(x, env) if isinstance(x, str) else x
return json.dumps(tree(v), sort_keys=True, separators=(",", ":"))
return render(v, env)
def shown(v, env):
return str(v) if has_interp(v) else render(v, env)
def truthy(s):
return s.strip().lower() in ("true", "yes", "on", "1")
def within(p, root):
return p == root or p.startswith(root + "/")
def has_dotdot(p):
return ".." in p.split("/")
def inside_stack(p):
return p != "" and not p.startswith("/") and not p.startswith("~") and not has_dotdot(p)
def root_led(raw):
if "$" not in raw.replace("$$", ""):
return True
for r in ROOT_VARS:
for form in ("${%s}" % r, "$" + r):
if raw.startswith(form):
rest = raw[len(form):]
if (rest == "" or rest.startswith("/")) and "$" not in rest.replace("$$", ""):
return True
return False
def valid_roots(env):
out = []
for r in ROOT_VARS:
v = env.get(r, "")
if v and v.startswith("/") and os.path.normpath(v) == v and v != "/" and not has_dotdot(v) and v.startswith("/mnt/"):
out.append(v)
return out
def violations(doc, env):
out = []
roots = valid_roots(env)
def add(svc, setting):
out.append((svc, setting))
if "include" in doc:
add("", "include")
for n, d in sorted((doc.get("volumes") or {}).items()):
d = d if isinstance(d, dict) else {}
for k in ("driver", "driver_opts", "external", "name"):
if k in d and not (k == "driver" and render(d[k], env) == "local"):
add("", "volume %s %s %s" % (n, k, canon(d[k], env)))
for top in ("configs", "secrets"):
for n, d in sorted((doc.get(top) or {}).items()):
d = d if isinstance(d, dict) else {}
if "file" in d and not inside_stack(render(d["file"], env)):
add("", "%s_file %s %s" % (top[:-1], n, shown(d["file"], env)))
for name, sd in sorted((doc.get("services") or {}).items()):
sd = dict(sd or {})
for k in PRIVILEGED_KEYS:
if k in sd and has_interp(sd[k]):
add(name, "interpolated " + k)
del sd[k]
if "privileged" in sd and truthy(render(sd["privileged"], env)):
add(name, "privileged true")
for v in as_list(sd.get("cap_add")):
c = render(v, env).upper()
add(name, "cap_add " + (c[4:] if c.startswith("CAP_") else c))
for v in as_list(sd.get("devices")):
add(name, "device " + canon(v, env))
for v in as_list(sd.get("device_cgroup_rules")):
add(name, "device_cgroup_rule " + render(v, env))
for k in SCALAR_KEYS:
if k in sd:
add(name, "%s %s" % (k, render(sd[k], env)))
for v in as_list(sd.get("security_opt")):
s = render(v, env)
if s.replace("=", ":").replace(" ", "") in ("no-new-privileges", "no-new-privileges:true"):
continue
add(name, "security_opt " + s)
sy = sd.get("sysctls")
if isinstance(sy, dict):
for k in sorted(sy):
add(name, "sysctl %s=%s" % (k, render(sy[k], env)))
elif isinstance(sy, list):
for v in sy:
add(name, "sysctl " + render(v, env))
for v in as_list(sd.get("volumes_from")):
add(name, "volumes_from " + render(v, env))
if "build" in sd:
add(name, "build")
ex = sd.get("extends")
if isinstance(ex, dict) and "file" in ex:
add(name, "extends_file " + shown(ex["file"], env))
for v in as_list(sd.get("env_file")):
raw = v.get("path") if isinstance(v, dict) else v
if not inside_stack(render(raw, env)):
add(name, "env_file " + shown(raw, env))
for v in as_list(sd.get("volumes")):
vol = volume(v, env, roots)
if vol:
add(name, vol)
return sorted(out)
def volume(v, env, roots):
prop = ""
if isinstance(v, str):
parts = v.split(":")
if len(parts) < 2:
return None
raw_src = parts[0]
src, dst, mode = render(parts[0], env), render(parts[1], env), "rw"
if len(parts) > 2:
for o in parts[2].split(","):
if o == "ro":
mode = "ro"
elif o in ("shared", "rshared", "slave", "rslave"):
prop = o
if not src.startswith(("/", ".", "~", "$")) and not raw_src.startswith(("/", ".", "~", "$")):
return None
elif isinstance(v, dict):
typ = render(v.get("type"), env)
raw_src = str(v.get("source"))
src, dst, mode = render(v.get("source"), env), render(v.get("target"), env), "rw"
if truthy(render(v.get("read_only"), env)):
mode = "ro"
b = v.get("bind")
if isinstance(b, dict) and render(b.get("propagation"), env) in ("shared", "rshared", "slave", "rslave"):
prop = render(b.get("propagation"), env)
if typ in ("volume", "tmpfs", "image"):
return None
if typ != "bind":
return "volume type " + typ
else:
return None
show = src if root_led(raw_src) else raw_src
setting = "bind %s -> %s %s" % (show, dst, mode)
if prop:
setting += " " + prop
socket = src.endswith(".sock") or "docker.sock" in src
under = src.startswith("/") and not has_dotdot(src) and any(within(os.path.normpath(src), r) for r in roots)
if not root_led(raw_src) or prop or socket or not under:
return setting
return None
def judge_files(root):
tdir = os.path.join(root, "templates")
files = []
for d, _, fs in os.walk(tdir):
for f in sorted(fs):
p = os.path.join(d, f)
if f == "docker-compose.yml" or (os.path.basename(d) == "steps" and f.endswith(".yml")):
files.append(p)
return tdir, sorted(files)
def main(argv):
root = ROOT
for a in argv:
if a.startswith("--root="):
root = a.split("=", 1)[1]
with io.open(os.path.join(root, ALLOWLIST), encoding="utf-8") as f:
raw_list = f.read()
allowed = {(e["app"], e["service"], e["setting"]) for e in json.loads(raw_list)["entries"]}
sibling = os.path.join(root, CONTROLLER_COPY)
if os.path.exists(sibling):
with io.open(sibling, encoding="utf-8") as f:
if f.read() != raw_list:
print("FAIL: %s differs from the controller's %s — change both in the same session" % (ALLOWLIST, CONTROLLER_COPY))
return 1
print("allow-list copy: byte-identical to the controller's")
else:
print("allow-list copy: no sibling felhom-controller clone — equality checked by the controller's own test")
tdir, files = judge_files(root)
if not files:
print("check-privileges: nothing to judge under %s" % tdir)
return 3
bad = []
for p in files:
rel = os.path.relpath(p, tdir)
app = rel.split(os.sep)[0]
try:
with io.open(p, encoding="utf-8") as f:
doc = load(f.read())
except (YamlError, UnicodeDecodeError) as e:
bad.append("%s: cannot be read (%s) — the box refuses a definition it cannot check" % (rel, e))
continue
for svc, setting in violations(doc, PLACEHOLDER_ENV):
if (app, svc, setting) not in allowed:
bad.append("%s: %s%s — not on the allow-list (scripts/privilege-allowlist.json)" % (rel, (svc + ": ") if svc else "", setting))
for b in bad:
print("REFUSED " + b)
if bad:
print("check-privileges: %d setting(s) the box would refuse, in %d files judged" % (len(bad), len(files)))
return 1
print("check-privileges: %d files judged, every class-setting on the allow-list" % len(files))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
+13
View File
@@ -0,0 +1,13 @@
{
"version": 1,
"note": "R-971 (operator decision D2 = A, 2026-10-17). The box's catalog allow-list, compiled into the controller. Each entry allows ONE exact setting for ONE service of ONE app; a changed setting is a different one and is refused. The catalog's scripts/privilege-allowlist.json is a byte-identical copy for its CI gate. Survey: felhom.eu documentation/audits/agent-allowlist-rotation-2026-10-17/P2/survey.md",
"entries": [
{
"app": "homepage",
"service": "homepage",
"setting": "bind /var/run/docker.sock -> /var/run/docker.sock ro",
"why": "the Docker widget and the docker service discovery list the household's containers and their state",
"doc": "https://gethomepage.dev/configs/docker/"
}
]
}
+73
View File
@@ -69,6 +69,7 @@ COVERS = {
"login-kind": "login_kind written only in a COMMENT, only inside the English i18n: block, or under ANOTHER mapping (resources:) - none is the field, each passes; vs the facts: an unknown value (`magic`), a wrong case (`EMAIL`), the key twice, and no templates/ at all (rc 3, never a pass); the three known values pass (controller 0.320.0)",
"copy-i18n": "Hungarian edited in a COMMENT/README/display_name (label, not copy) vs a real frozen string changed; an English block that is not English, is not matched to a Hungarian twin, or rewrites a credential (R-560). A retrieval promise REGISTERED in ALLOWLIST_EN passes only for its own app+path+sentence with a real reason; an entry for another app, a rewritten sentence, a stale entry or a two-word reason convicts (R-594). Also the DEGRADED mode CI actually runs — PyYAML shadowed out, freeze only (R-595). THE USER GUIDE (2026-10-15): a download-source name only in a COMMENT or in docs_url passes; vs the facts - guide strings not frozen, checked_version in the English block, an empty steps list, an FAQ entry with no answer, an unquoted version, an English guide with no Hungarian one, more English sections than Hungarian, a different step count, and a source name in either language",
"redis-persistence": "`--appendonly yes` only in a COMMENT, or only in a steps/ file (a tested step definition, not judged on purpose) - each passes; vs the facts: AOF in string form, in a flow list, in a block list, on a valkey image - each refused naming the app; image default (no command) and `--appendonly no` pass; no templates/ is rc 3 (R-1096)",
"privileges": "a dangerous key only in a COMMENT, `privileged: false`, `no-new-privileges:true`, a ${HDD_PATH} bind, the docker socket only in a comment, homepage's own allow-listed read-only socket - each passes; vs the facts: privileged true, cap_add, a host-root bind, a ${OTHER} bind, homepage's socket READ-WRITE, the same socket in ANOTHER app, network_mode host, a driver_opts bind volume, a ${VAR} in a privileged key, the same in a steps/ file, an allow-list copy that differs from the controller's - each refused naming the setting; no templates/ is rc 3; and the stdlib reader equals PyYAML on every catalog file (R-971)",
"gate-decoys": "this suite, run as a gate of the full run (R-1115): every case above is a decoy of its own gate, and ONE case that stops convicting turns the whole run red - measured 2026-10-17, when the credential-token case had lost its premise (gokapi's login line removed by 326f846) the suite printed FAIL and exited 1; the copy-i18n credential cases now edit an EXISTING line, so a removed premise stops the suite (`edit` raises) instead of passing",
}
@@ -823,6 +824,77 @@ def redis_persistence_cases():
shutil.rmtree(ws, ignore_errors=True)
def privileges_cases():
"""check-privileges.py reads templates/*/docker-compose.yml AND steps/*.yml under --root (R-971)."""
global ran
ws = tempfile.mkdtemp(prefix="catalog-privileges-")
allow = io.open(os.path.join(ROOT, "scripts", "privilege-allowlist.json"), encoding="utf-8").read()
try:
def compose(extra="", vol=""):
return ("services:\n app:\n image: example/app:1.0\n%s volumes:\n - app_data:/data\n%s"
"volumes:\n app_data:\n" % (extra, vol))
homepage = ("services:\n homepage:\n image: ghcr.io/gethomepage/homepage:v1.13.2\n volumes:\n"
" - homepage_config:/app/config\n - /var/run/docker.sock:/var/run/docker.sock:ro\nvolumes:\n homepage_config:\n")
def run(name, files, expect_rc, must=(), no_templates=False, list_body=None, controller_copy=None):
global ran
cat = os.path.join(ws, "cat")
shutil.rmtree(cat, ignore_errors=True)
os.makedirs(os.path.join(cat, "scripts"))
io.open(os.path.join(cat, "scripts", "privilege-allowlist.json"), "w", encoding="utf-8").write(list_body or allow)
if controller_copy is not None:
cc = os.path.join(ws, "felhom-controller", "controller", "internal", "privpolicy")
os.makedirs(cc, exist_ok=True)
io.open(os.path.join(cc, "allowlist.json"), "w", encoding="utf-8").write(controller_copy)
if not no_templates:
for rel, body in files.items():
p = os.path.join(cat, "templates", rel)
os.makedirs(os.path.dirname(p), exist_ok=True)
io.open(p, "w", encoding="utf-8").write(body)
r = sh([sys.executable, os.path.join(ROOT, "scripts", "check-privileges.py"), "--root=" + cat], ROOT)
shutil.rmtree(os.path.join(ws, "felhom-controller"), ignore_errors=True)
out = r.stdout + r.stderr; ran += 1
ok = r.returncode == expect_rc and all(m in out for m in must)
print(" %s %-70s rc=%d (expected %d)" % ("ok" if ok else "XX", name, r.returncode, expect_rc))
if not ok:
fails.append("%s: rc=%d expected %d; missing %s\n%s" % (name, r.returncode, expect_rc, [m for m in must if m not in out], out[-400:]))
print("\n-- privileges: genuine and decoys (each passes)")
run("GENUINE: a named volume and a ${HDD_PATH} bind", {"a/docker-compose.yml": compose(vol=" - ${HDD_PATH}/appdata/a:/config\n")}, 0, ("every class-setting",))
run("DECOY: privileged: true only in a COMMENT", {"a/docker-compose.yml": compose(" # privileged: true\n")}, 0)
run("DECOY: privileged: false", {"a/docker-compose.yml": compose(" privileged: false\n")}, 0)
run("DECOY: no-new-privileges (a hardening)", {"a/docker-compose.yml": compose(" security_opt:\n - no-new-privileges:true\n")}, 0)
run("DECOY: the docker socket only in a COMMENT", {"a/docker-compose.yml": compose(vol=" # - /var/run/docker.sock:/var/run/docker.sock\n")}, 0)
run("GENUINE: homepage's allow-listed read-only socket", {"homepage/docker-compose.yml": homepage}, 0)
print("-- privileges: the facts (each MUST be refused)")
run("FACT: privileged true", {"a/docker-compose.yml": compose(" privileged: true\n")}, 1, ("app: privileged true",))
run("FACT: cap_add", {"a/docker-compose.yml": compose(" cap_add: [SYS_ADMIN]\n")}, 1, ("cap_add SYS_ADMIN",))
run("FACT: the host root bound", {"a/docker-compose.yml": compose(vol=" - /:/host\n")}, 1, ("bind / -> /host rw",))
run("FACT: a bind through another variable", {"a/docker-compose.yml": compose(vol=" - ${OTHER}/x:/x\n")}, 1, ("bind ${OTHER}/x",))
run("FACT: homepage's socket READ-WRITE", {"homepage/docker-compose.yml": homepage.replace("docker.sock:ro", "docker.sock")}, 1, ("docker.sock rw",))
run("FACT: the allowed socket in ANOTHER app", {"glance/docker-compose.yml": homepage}, 1, ("glance/docker-compose.yml",))
run("FACT: network_mode host", {"a/docker-compose.yml": compose(" network_mode: host\n")}, 1, ("network_mode host",))
run("FACT: a driver_opts bind volume", {"a/docker-compose.yml": compose().replace("volumes:\n app_data:\n", "volumes:\n app_data:\n driver_opts:\n type: none\n o: bind\n device: /\n")}, 1, ("volume app_data driver_opts",))
run("FACT: a ${VAR} in a privileged key", {"a/docker-compose.yml": compose(" privileged: ${PRIV}\n")}, 1, ("interpolated privileged",))
run("FACT: privileged in a steps/ file", {"a/docker-compose.yml": compose(), "a/steps/0123456789abcdef.yml": compose(" privileged: true\n")}, 1, ("a/steps/0123456789abcdef.yml",))
run("FACT: the list copy differs from the controller's", {"a/docker-compose.yml": compose()}, 1, ("differs",), controller_copy=allow.replace("homepage", "glance"))
run("FACT: no templates/ at all (nothing to judge)", {}, 3, ("nothing to judge",), no_templates=True)
# The stdlib reader against PyYAML on every catalog file (this suite needs PyYAML anyway).
import importlib.util
import yaml
spec = importlib.util.spec_from_file_location("check_privileges", os.path.join(ROOT, "scripts", "check-privileges.py"))
m = importlib.util.module_from_spec(spec)
spec.loader.exec_module(m)
_, files = m.judge_files(ROOT)
bad = [p for p in files if m.violations(yaml.safe_load(io.open(p, encoding="utf-8")), m.PLACEHOLDER_ENV)
!= m.violations(m.load(io.open(p, encoding="utf-8").read()), m.PLACEHOLDER_ENV)]
ran += 1
ok = len(files) >= 100 and not bad
print(" %s %-70s files=%d differ=%d" % ("ok" if ok else "XX", "READER: the stdlib reader equals PyYAML on the catalog", len(files), len(bad)))
if not ok:
fails.append("privileges reader differs from PyYAML on %s (files=%d)" % (bad[:5], len(files)))
finally:
shutil.rmtree(ws, ignore_errors=True)
def unclean_boot_cases():
"""check-unclean-boot-images.py reads FILES: templates/*/.felhom.yml + docker-compose.yml (+ steps/), via --root (R-1007)."""
global ran
@@ -1968,6 +2040,7 @@ i18n:
login_kind_cases()
image_volumes_cases()
redis_persistence_cases()
privileges_cases()
if fails:
print()