#!/usr/bin/env python3 # -*- coding: utf-8 -*- """check-db-credentials.py — every variable that feeds a database password must TRAVEL with the backup (R-1106). WHAT WENT WRONG. A database engine reads POSTGRES_PASSWORD / MARIADB_ROOT_PASSWORD / … only when it initialises an EMPTY data directory. A restore puts a data directory back, and only the password it was created with opens it. Measured 2026-10-16 on demo-hp: Rallly and Grimmory removed, reinstalled (new generated passwords), restored from the off-site copy — the data came back and neither app could open it. Controller v0.324.0 restores the BACKUP's database password (operator decision 1A, `07` §7.4) and refuses a restore whose backup does not carry it. The backup carries a value only when its deploy field is `type: secret` (D5: `type: password` fields are admin logins and never leave the box). So a database password fed by a `type: password` field, or by a variable with no deploy field at all, could never be restored — this gate refuses it at push time. THE FACT, and the labels that are not it: * The fact is a DATABASE service's (image: postgres / postgis / pgvector / timescaledb / mariadb / mysql — the controller's own predicate, appbackup.dbTypeForImage) environment entry whose KEY is a credential (`(POSTGRES|PG|MARIADB|MYSQL)_*PASSWORD`, the controller's appbackup.dbCredentialKeyRe) and whose VALUE references a variable (${X}, ${X:-d}, $X). Each such X must be a `.felhom.yml` deploy field with `type: secret`. * NOT the fact: the same reference in the APP service (it reads the password, it does not create the data directory); a redis/valkey `*_PASSWORD` (not a database the backup dumps); a literal password (nothing to carry); a mention in a COMMENT; files under `steps/` (a superseded step's own definition). Mirrors controller `internal/appbackup.DBCredentialVars` (TestR1106_DBCredentialVarsAndVolumes). stdlib only, a line reader (catalog CI has no PyYAML). USAGE python3 scripts/check-db-credentials.py # every template directory python3 scripts/check-db-credentials.py rallly romm # only these python3 scripts/check-db-credentials.py --root= # judge another checkout (the decoy suite) Exit: 0 every DB password travels · 1 convicted · 2 inconclusive. Decoys: scripts/test_gate_decoys.py `db_cred_cases` (COVERS "db-credentials"). """ import io import os import re import sys ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DB_IMAGE = ("postgres", "postgis", "pgvector", "timescaledb", "mariadb", "mysql") CRED_KEY = re.compile(r"^(POSTGRES|PG|MARIADB|MYSQL)_[A-Z_]*PASSWORD$") REF = re.compile(r"\$\{([A-Za-z_][A-Za-z0-9_]*)(?:[:]?[-?+][^}]*)?\}|\$([A-Za-z_][A-Za-z0-9_]*)") def _strip_comment(line): out, q = [], None for i, ch in enumerate(line): if q: if ch == q: q = None elif ch in ("'", '"'): q = ch elif ch == "#" and (i == 0 or line[i - 1] in " \t"): break out.append(ch) return "".join(out).rstrip() def _unq(v): v = v.strip() if len(v) >= 2 and v[0] == v[-1] and v[0] in "'\"": return v[1:-1] return v def compose_db_refs(text): """{db_service: [(KEY, var), ...]} for every credential key of a database service that references a variable.""" services = {} # name -> {"image": str, "env": [(k, v)]} svc, svc_indent, in_env, env_indent = None, None, False, None top = None for raw in text.split("\n"): line = _strip_comment(raw) if not line.strip(): continue indent = len(line) - len(line.lstrip(" ")) s = line.strip() if indent == 0: top = s.split(":", 1)[0] svc, in_env = None, False continue if top != "services": continue if svc is None or indent <= svc_indent: m = re.match(r"^([A-Za-z0-9_.\-]+):\s*$", s) if m: svc, svc_indent, in_env = m.group(1), indent, False services[svc] = {"image": "", "env": []} continue if in_env and indent <= env_indent: in_env = False if in_env: if s.startswith("- "): item = _unq(s[2:]) if "=" in item: k, v = item.split("=", 1) services[svc]["env"].append((k.strip(), v)) else: m = re.match(r"^([A-Za-z0-9_]+):\s*(.*)$", s) if m: services[svc]["env"].append((m.group(1), _unq(m.group(2)))) continue m = re.match(r"^(image|environment):\s*(.*)$", s) if m and indent > svc_indent: if m.group(1) == "image": services[svc]["image"] = _unq(m.group(2)) else: in_env, env_indent = True, indent out = {} for name, sv in services.items(): if not any(k in sv["image"].lower() for k in DB_IMAGE): continue refs = [] for k, v in sv["env"]: if not CRED_KEY.match(k): continue for a, b in REF.findall(v): refs.append((k, a or b)) out[name] = refs return out def deploy_field_types(text): """{env_var: type} from `.felhom.yml` top-level `deploy_fields:` list items.""" fields, in_df, cur = {}, False, None for raw in text.split("\n"): line = _strip_comment(raw) if not line.strip(): continue indent = len(line) - len(line.lstrip(" ")) s = line.strip() if indent == 0: if cur and cur.get("env_var"): fields[cur["env_var"]] = cur.get("type", "") cur = None in_df = s.startswith("deploy_fields:") continue if not in_df: continue if s.startswith("- "): if cur and cur.get("env_var"): fields[cur["env_var"]] = cur.get("type", "") cur = {} s = s[2:].strip() m = re.match(r"^(env_var|type):\s*(.*)$", s) if m and cur is not None: cur[m.group(1)] = _unq(m.group(2)) if cur and cur.get("env_var"): fields[cur["env_var"]] = cur.get("type", "") return fields def check_app(tdir, app): d = os.path.join(tdir, app) try: compose = io.open(os.path.join(d, "docker-compose.yml"), encoding="utf-8").read() meta = io.open(os.path.join(d, ".felhom.yml"), encoding="utf-8").read() except (IOError, OSError) as e: return 2, "%s: unreadable template (%s)" % (app, e), [] refs = compose_db_refs(compose) types = deploy_field_types(meta) bad, listed = [], [] for svc in sorted(refs): for key, var in refs[svc]: listed.append("%s:%s<-%s" % (svc, key, var)) t = types.get(var) if t is None: bad.append("%s %s=${%s}: no deploy field %s — a restore cannot carry it" % (svc, key, var, var)) elif t != "secret": bad.append("%s %s=${%s}: field %s is type %r, not 'secret' — it never travels in the backup (D5)" % (svc, key, var, var, t)) if bad: return 1, "%s: %s" % (app, "; ".join(bad)), listed return 0, app, listed def main(argv): root, apps, verbose = ROOT, [], False for a in argv: if a.startswith("--root="): root = a.split("=", 1)[1] elif a == "--all": continue elif a == "-v": verbose = True elif a.startswith("-"): print("unknown option: %s" % a) return 2 else: apps.append(a) tdir = os.path.join(root, "templates") if not os.path.isdir(tdir): print("db-credentials: no templates/ under %s" % root) return 2 every = sorted(n for n in os.listdir(tdir) if os.path.isdir(os.path.join(tdir, n))) unknown = [a for a in apps if a not in every] if unknown: print("db-credentials: no such template: %s" % ", ".join(unknown)) return 2 convicted, undecided, total = [], [], 0 for app in (apps or every): v, msg, listed = check_app(tdir, app) total += len(listed) if verbose and listed: print(" %s: %s" % (app, ", ".join(listed))) if v == 1: convicted.append(msg) elif v == 2: undecided.append(msg) for m in convicted: print("REFUSED: " + m) for m in undecided: print("INCONCLUSIVE: " + m) n = len(apps or every) if convicted: print("db-credentials: %d of %d template(s) refused — make the variable a `type: secret` deploy field (R-1106)" % (len(convicted), n)) return 1 if undecided: print("db-credentials: INCONCLUSIVE on %d of %d template(s) — never a pass" % (len(undecided), n)) return 2 print("db-credentials gate OK: %d template(s), %d database password reference(s), each a `type: secret` field" % (n, total)) return 0 if __name__ == "__main__": sys.exit(main(sys.argv[1:]))