#!/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//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 ` 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:]))