Gate db-credentials: every database password variable is a type: secret field, so the backup carries it (R-1106)
gates / gates (push) Successful in 6s
gates / gates (push) Successful in 6s
This commit is contained in:
1 parent
79df20a75b
commit
af75dc0fb5
5 files changed
+303
-12
No files matched your search
@@ -129,6 +129,9 @@ GATES = [
|
||||
# templates were under it — the deploy screen and the box's overcommit warning read less than the app may take.
|
||||
# Static, stdlib only (no PyYAML on CI), so --fast: the hook and CI.
|
||||
("mem-limit-sum", "check-mem-limit-sum.py", True, True, False),
|
||||
# R-1106 (2026-10-16 night): a database service's password variable must be a `type: secret` deploy field, so the
|
||||
# backup carries it and a restore can put the password back with the data (controller v0.324.0). Static, stdlib.
|
||||
("db-credentials", "check-db-credentials.py", True, True, False),
|
||||
# R-127 leg (a) (2026-10-05): every data-encrypting key carries `data_key: true` (by its NAME, or by a registry
|
||||
# entry with its reason) and every flag is accounted for — the restore's fail-closed gate reads only that flag.
|
||||
("data-key", "check-data-key.py", True, True, False),
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
#!/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=<dir> # 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:]))
|
||||
@@ -60,6 +60,7 @@ COVERS = {
|
||||
"probe-measured": "the measurement written in the TAGLINE or another comment block, not directly above setup_done_probe:; a date with no before/after; before/after with no date; 'read upstream' instead of 'measured' - vs a genuine measured comment (R-715)",
|
||||
"family-gate": "family_gate written only in a COMMENT (not gated, no min_controller owed); min_controller only in a comment; a golden DIRECTORY named 0.287.0 with no bake log (the mkdir shape, R-410); a sibling with no golden (stated NOT CHECKED, never a pass of rule 3) - vs the facts: an unanchorable exception (regex, '/', '..'), an exception list with no gate, min_controller below 0.287.0, the newest baked golden below 0.287.0; and a genuine family app passes (decisions 63/64, finding F1)",
|
||||
"onboarding": "a NEW template with no record; a record missing an id, or carrying it only inside an HTML comment; a `done` whose path does not exist, is an EMPTY directory (the mkdir shape, R-410) or names an absent sibling-repo file; an `n/a` with an empty or two-word reason; an `open` row; `opened:` backdated before the checklist; the template a new app copies lacking a new id - vs a complete record, an id added after `opened:`, and an exempt app's record with open rows (NEW-APP-CHECKLIST.md)",
|
||||
"db-credentials": "the password variable only in a COMMENT; the same reference in the APP service; a redis `REDIS_PASSWORD`; a literal DB password - vs the facts: a DB password fed by a variable with no deploy field, by a `type: password` field, in list form and in map form (R-1106)",
|
||||
"mem-limit-sum": "the right figure only in a COMMENT (the compose header's 'mem_limit: 640M', the .felhom.yml arithmetic) while the field is wrong; a `memory:` under reservations: (not a limit) making the sum come out right; a `mem_limit:` outside resources:; a steps/ file with the old figure (not judged) - vs the facts: a field under the sum, a service with no limit, an unreadable size (R-758)",
|
||||
"data-key": "a data_key: true only in a COMMENT or inside the i18n: block (not the field); an 'Encryption key' LABEL on a signing secret (copy, not the fact - must pass unflagged) - vs the facts: an *_ENCRYPTION_KEY field unflagged, a REGISTERED field unflagged, an unexplained flag, a stale registry entry, a non-boolean flag (R-127)",
|
||||
"unclean-boot-images": "the new image only in a compose COMMENT, on ANOTHER service (machine-learning), or under a COMMENTED-OUT block; a template with no block - each passes; vs the facts: the repair's service bumped with the list unchanged, the same in a steps/ file (the ladder), a block naming a service the compose does not run, a block with an empty images: list; and the genuine bump with the list updated (flow and block list) passes (R-1007, decision 236)",
|
||||
@@ -1104,6 +1105,61 @@ def mem_sum_cases():
|
||||
shutil.rmtree(ws, ignore_errors=True)
|
||||
|
||||
|
||||
def db_cred_cases():
|
||||
"""check-db-credentials.py reads templates/*/docker-compose.yml + .felhom.yml via --root (R-1106)."""
|
||||
global ran
|
||||
import tempfile
|
||||
ws = tempfile.mkdtemp(prefix="catalog-dbcred-")
|
||||
try:
|
||||
COMPOSE = (
|
||||
"# header: POSTGRES_PASSWORD=${NOT_A_FIELD} is a comment\n"
|
||||
"services:\n"
|
||||
" demo:\n image: demo/demo:1.0\n environment:\n"
|
||||
" - DATABASE_URL=postgres://demo:${DB_PASSWORD}@demo-db/demo\n - POSTGRES_PASSWORD=${APP_ONLY}\n"
|
||||
" demo-db:\n image: postgres:16-alpine\n environment:\n"
|
||||
" - POSTGRES_USER=demo\n - POSTGRES_PASSWORD=${DB_PASSWORD} # ${ALSO_COMMENT}\n"
|
||||
" demo-cache:\n image: redis:7-alpine\n environment:\n - REDIS_PASSWORD=${CACHE_PW}\n"
|
||||
" demo-maria:\n image: mariadb:11.4\n environment:\n"
|
||||
" MARIADB_ROOT_PASSWORD: \"${DB_ROOT_PASSWORD:-x}\"\n MARIADB_PASSWORD: literal\n")
|
||||
META = ('display_name: "Demo"\ndeploy_fields:\n'
|
||||
' - env_var: DB_PASSWORD\n label: DB\n type: secret\n'
|
||||
' - env_var: DB_ROOT_PASSWORD\n label: Root\n type: secret\n'
|
||||
' - env_var: ADMIN_PASSWORD\n label: Admin\n type: password\n')
|
||||
|
||||
def run(name, compose, meta, expect_rc, must=()):
|
||||
global ran
|
||||
cat = os.path.join(ws, "cat")
|
||||
shutil.rmtree(cat, ignore_errors=True)
|
||||
d = os.path.join(cat, "templates", "demo")
|
||||
os.makedirs(d)
|
||||
io.open(os.path.join(d, "docker-compose.yml"), "w", encoding="utf-8").write(compose)
|
||||
io.open(os.path.join(d, ".felhom.yml"), "w", encoding="utf-8").write(meta)
|
||||
r = sh([sys.executable, os.path.join(ROOT, "scripts", "check-db-credentials.py"), "--root=" + cat], ROOT)
|
||||
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-- db-credentials: genuine and decoys")
|
||||
run("GENUINE + DECOYS: comment, app-service ref, redis, literal - all not judged", COMPOSE, META, 0,
|
||||
("db-credentials gate OK", "2 database password reference(s)"))
|
||||
print("-- db-credentials: the facts (each MUST be refused)")
|
||||
run("FACT: list form, the variable has no deploy field",
|
||||
COMPOSE.replace("POSTGRES_PASSWORD=${DB_PASSWORD} #", "POSTGRES_PASSWORD=${PG_SECRET} #"), META, 1,
|
||||
("no deploy field PG_SECRET",))
|
||||
run("FACT: list form, fed by a `type: password` field",
|
||||
COMPOSE.replace("POSTGRES_PASSWORD=${DB_PASSWORD} #", "POSTGRES_PASSWORD=${ADMIN_PASSWORD} #"), META, 1,
|
||||
("type 'password'",))
|
||||
run("FACT: map form, the variable has no deploy field",
|
||||
COMPOSE, META.replace(" - env_var: DB_ROOT_PASSWORD\n label: Root\n type: secret\n", ""), 1,
|
||||
("no deploy field DB_ROOT_PASSWORD",))
|
||||
finally:
|
||||
shutil.rmtree(ws, ignore_errors=True)
|
||||
|
||||
|
||||
def data_key_cases():
|
||||
"""check-data-key.py reads templates/*/.felhom.yml via --root (R-127 leg a)."""
|
||||
global ran
|
||||
@@ -1857,6 +1913,7 @@ i18n:
|
||||
onboarding_cases()
|
||||
family_gate_cases()
|
||||
mem_sum_cases()
|
||||
db_cred_cases()
|
||||
data_key_cases()
|
||||
unclean_boot_cases()
|
||||
login_kind_cases()
|
||||
|
||||
Reference in new issue
Block a user