diff --git a/infra/github-backup/bin/app_setup.py b/infra/github-backup/bin/app_setup.py index fc474111e5..ccce4d36d5 100644 --- a/infra/github-backup/bin/app_setup.py +++ b/infra/github-backup/bin/app_setup.py @@ -31,7 +31,14 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from ghb_common import load_config -CFG = load_config() +try: + CFG = load_config() +except (ValueError, OSError) as e: + # A wrong-shape config is a clean, field-naming diagnostic for + # every subcommand (#6849) — never a raw KeyError/TypeError + # traceback from the import-time indexing below. + print(f"app_setup: {e}", file=sys.stderr) + sys.exit(2) NAMES = CFG["app"]["bitwarden_secret_names"] @@ -49,22 +56,49 @@ def app_manifest(worker_url): } -def _bws_list(): - r = subprocess.run( - ["bws", "secret", "list"], capture_output=True, text=True, env=dict(os.environ) - ) +def _bws_json(argv, what): + """Run a bws read command and return its parsed JSON. + + The subprocess failure is reported as the bws failure it is + (return code + stderr excerpt), and unparseable output is a + named diagnostic — never a raw JSONDecodeError or a misleading + downstream shape accident (#6849). + """ + r = subprocess.run(argv, capture_output=True, text=True, env=dict(os.environ)) if r.returncode != 0: - raise RuntimeError(f"bws secret list failed: {r.stderr[:200]}") - return json.loads(r.stdout or "[]") + raise RuntimeError(f"{what} failed (exit {r.returncode}): {r.stderr[:200]}") + try: + return json.loads(r.stdout or "null") + except json.JSONDecodeError: + raise RuntimeError(f"{what} returned unparseable output: {r.stdout[:200]!r}") + + +def _bws_list(): + secrets = _bws_json(["bws", "secret", "list"], "bws secret list") + if not isinstance(secrets, list) or not all( + isinstance(s, dict) + and isinstance(s.get("id"), str) + and isinstance(s.get("key"), str) + for s in secrets + ): + raise RuntimeError( + "bws secret list returned an unexpected shape: " + "expected a list of objects with string 'id' and 'key'" + ) + return secrets def _project_id(): if os.environ.get("GHB_BWS_PROJECT_ID"): return os.environ["GHB_BWS_PROJECT_ID"] - r = subprocess.run( - ["bws", "project", "list"], capture_output=True, text=True, env=dict(os.environ) - ) - projects = json.loads(r.stdout or "[]") + projects = _bws_json(["bws", "project", "list"], "bws project list") + if not isinstance(projects, list) or not all( + isinstance(p, dict) and isinstance(p.get("id"), str) for p in projects + ): + raise RuntimeError( + "bws project list returned an unexpected shape: " + "expected a list of objects with string 'id'" + ) if not projects: raise RuntimeError("no Bitwarden projects visible to this token") return projects[0]["id"] @@ -95,13 +129,13 @@ def bws_get(name): sid = next((s["id"] for s in _bws_list() if s.get("key") == name), None) if not sid: raise KeyError(name) - r = subprocess.run( - ["bws", "secret", "get", sid], - capture_output=True, - text=True, - env=dict(os.environ), - ) - return json.loads(r.stdout)["value"] + got = _bws_json(["bws", "secret", "get", sid], f"bws secret get {name}") + if not isinstance(got, dict) or not isinstance(got.get("value"), str): + raise RuntimeError( + f"bws secret get {name} returned an unexpected shape: " + "expected an object with a string 'value'" + ) + return got["value"] def cmd_manifest(): @@ -124,6 +158,36 @@ def cmd_manifest(): ) +def validate_conversion(conv): + """The full conversion response, validated BEFORE anything is + stored (#6849): a response missing a late field must store + nothing, never a partial credential set. Returns the validated + (id, client_id, client_secret, pem, slug) tuple.""" + if not isinstance(conv, dict): + raise RuntimeError( + "conversion response is not an object — nothing stored" + ) + problems = [] + if not isinstance(conv.get("id"), int) or isinstance(conv.get("id"), bool): + problems.append("'id' must be an integer") + for field in ("client_id", "client_secret", "pem", "slug"): + if not isinstance(conv.get(field), str) or not conv.get(field): + problems.append(f"'{field}' must be a non-empty string") + if problems: + raise RuntimeError( + "conversion response failed validation (" + + "; ".join(problems) + + ") — nothing stored" + ) + return ( + conv["id"], + conv["client_id"], + conv["client_secret"], + conv["pem"], + conv["slug"], + ) + + def cmd_convert(code): import urllib.request @@ -135,12 +199,13 @@ def cmd_convert(code): req.add_header("Accept", "application/vnd.github+json") with urllib.request.urlopen(req, timeout=60) as r: conv = json.loads(r.read()) - bws_set(NAMES["app_id"], str(conv["id"])) - bws_set(NAMES["client_id"], conv["client_id"]) - bws_set(NAMES["client_secret"], conv["client_secret"]) - bws_set(NAMES["private_key"], conv["pem"]) + app_id, client_id, client_secret, pem, slug = validate_conversion(conv) + bws_set(NAMES["app_id"], str(app_id)) + bws_set(NAMES["client_id"], client_id) + bws_set(NAMES["client_secret"], client_secret) + bws_set(NAMES["private_key"], pem) print( - f"App created: id={conv['id']} slug={conv['slug']} — credentials stored " + f"App created: id={app_id} slug={slug} — credentials stored " f"in Bitwarden by name ({', '.join(NAMES.values())})." ) print("Next: app_setup.py webhook-secret, then install the App per RUNBOOK §App.") @@ -156,6 +221,26 @@ def cmd_webhook_secret(): ) +def validate_installations(installs): + """The installations payload, validated before any indexing + (#6849): a list of objects with an integer 'id' and an + 'account' object with a string 'login'.""" + if not isinstance(installs, list) or not all( + isinstance(i, dict) + and isinstance(i.get("id"), int) + and not isinstance(i.get("id"), bool) + and isinstance(i.get("account"), dict) + and isinstance(i["account"].get("login"), str) + for i in installs + ): + raise RuntimeError( + "installations response returned an unexpected shape: " + "expected a list of objects with integer 'id' and " + "'account.login' string" + ) + return installs + + def cmd_install_report(): # JWT minting needs a JOSE lib; use PyJWT if present, else cryptography. try: @@ -178,6 +263,7 @@ def cmd_install_report(): req.add_header("Accept", "application/vnd.github+json") with urllib.request.urlopen(req, timeout=60) as r: installs = json.loads(r.read()) + validate_installations(installs) for i in installs: acct = i["account"]["login"] print( diff --git a/infra/github-backup/bin/ghb_common.py b/infra/github-backup/bin/ghb_common.py index f3c32ee8f3..182f0a68d9 100644 --- a/infra/github-backup/bin/ghb_common.py +++ b/infra/github-backup/bin/ghb_common.py @@ -19,9 +19,92 @@ CONFIG_PATH = os.path.join(GB_DIR, "config.json") +# The config fields the github-backup tools read, by name (#6849): +# app_setup indexes app.name / app.events / app.bitwarden_secret_names +# (the five names below are the ones it stores under) and +# worker.webhook_path at import time, so those are the shapes +# validate_config guarantees for every consumer of load_config. +CONFIG_SECRET_NAME_KEYS = [ + "app_id", + "client_id", + "client_secret", + "private_key", + "webhook_secret", +] + + +def validate_config(cfg, source="config.json"): + """Split a loaded config.json into (clean config, named problems). + + Same contract as validate_plan/validate_state (#6637): every + problem names the field and the shape it found. Only the fields + the tools actually index are guaranteed (see above); other + sections pass through untouched. + """ + if not isinstance(cfg, dict): + return {}, [ + f"{source}: top level is {_shape(cfg)}, expected an object" + ] + problems = [] + app = cfg.get("app") + if not isinstance(app, dict): + problems.append( + f"{source}: 'app' is {_shape(app)}, expected an object" + ) + else: + name = app.get("name") + if not isinstance(name, str) or not name: + problems.append( + f"{source}: 'app.name' is {_shape(name)}, " + f"expected a non-empty string" + ) + events = app.get("events") + if not isinstance(events, list) or not all( + isinstance(e, str) for e in events + ): + problems.append( + f"{source}: 'app.events' is {_shape(events)}, " + f"expected a list of strings" + ) + names = app.get("bitwarden_secret_names") + if not isinstance(names, dict) or not all( + isinstance(k, str) and isinstance(v, str) and v + for k, v in names.items() + ): + problems.append( + f"{source}: 'app.bitwarden_secret_names' is " + f"{_shape(names)}, expected an object mapping " + f"strings to non-empty strings" + ) + else: + for key in CONFIG_SECRET_NAME_KEYS: + if key not in names: + problems.append( + f"{source}: 'app.bitwarden_secret_names' is " + f"missing {key!r}, required by app_setup" + ) + worker = cfg.get("worker") + if not isinstance(worker, dict): + problems.append( + f"{source}: 'worker' is {_shape(worker)}, expected an object" + ) + else: + path = worker.get("webhook_path") + if not isinstance(path, str) or not path: + problems.append( + f"{source}: 'worker.webhook_path' is {_shape(path)}, " + f"expected a non-empty string" + ) + return (cfg if not problems else {}), problems + + def load_config(): with open(CONFIG_PATH) as f: - return json.load(f) + cfg = json.load(f) + _, problems = validate_config(cfg) + if problems: + raise ValueError("; ".join(problems)) + return cfg def backup_root(cfg=None): diff --git a/infra/github-backup/tests/test_app_setup_shape.py b/infra/github-backup/tests/test_app_setup_shape.py new file mode 100644 index 0000000000..23adb08e73 --- /dev/null +++ b/infra/github-backup/tests/test_app_setup_shape.py @@ -0,0 +1,211 @@ +#!/usr/bin/env python3 +"""Regression tests for app_setup shape validation (#6849). + +Run: python3 infra/github-backup/tests/test_app_setup_shape.py +""" + +import contextlib +import io +import json +import os +import subprocess +import sys +import unittest +from types import SimpleNamespace +from unittest.mock import patch + +BIN = os.path.abspath( + os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "bin") +) +sys.path.insert(0, BIN) + +import ghb_common + + +def good_config(): + return { + "app": { + "name": "developing-today-backup", + "events": ["push", "repository"], + "bitwarden_secret_names": { + "app_id": "a", + "client_id": "b", + "client_secret": "c", + "private_key": "d", + "webhook_secret": "e", + }, + }, + "worker": {"webhook_path": "/github"}, + } + + +class ValidateConfigTests(unittest.TestCase): + def test_real_config_passes(self): + cfg = ghb_common.load_config() + clean, problems = ghb_common.validate_config(cfg) + self.assertEqual(problems, []) + self.assertEqual(clean, cfg) + + def test_good_config_passes(self): + clean, problems = ghb_common.validate_config(good_config()) + self.assertEqual(problems, []) + self.assertEqual(clean["app"]["name"], "developing-today-backup") + + def test_wrong_shapes_name_the_field(self): + cases = [] + cfg = good_config(); del cfg["app"]; cases.append((cfg, "'app'")) + cfg = good_config(); cfg["app"] = [1]; cases.append((cfg, "'app'")) + cfg = good_config(); cfg["app"]["bitwarden_secret_names"] = "names" + cases.append((cfg, "bitwarden_secret_names")) + cfg = good_config(); del cfg["app"]["bitwarden_secret_names"]["pem" if False else "private_key"] + cases.append((cfg, "private_key")) + cfg = good_config(); cfg["app"]["events"] = "push"; cases.append((cfg, "app.events")) + cfg = good_config(); cfg["worker"] = {}; cases.append((cfg, "webhook_path")) + cases.append(([1, 2], "top level")) + for cfg, needle in cases: + clean, problems = ghb_common.validate_config(cfg) + self.assertEqual(clean, {}, needle) + self.assertTrue(any(needle in p for p in problems), (needle, problems)) + + +class AppSetupImportTests(unittest.TestCase): + def test_import_with_real_config(self): + import app_setup + + self.assertEqual(app_setup.NAMES["app_id"], "github-app.backup-app-id") + manifest = app_setup.app_manifest("https://worker.example") + self.assertEqual(manifest["name"], "developing-today-backup") + self.assertTrue(manifest["hook_attributes"]["url"].endswith("/github")) + + def test_import_with_wrong_shape_config_exits_cleanly(self): + driver = ( + "import sys; sys.path.insert(0, %r)\n" + "import ghb_common\n" + "def bad(): raise ValueError(\"config.json: 'app' is a list, expected an object\")\n" + "ghb_common.load_config = bad\n" + "import app_setup\n" % BIN + ) + r = subprocess.run( + [sys.executable, "-c", driver], capture_output=True, text=True + ) + self.assertEqual(r.returncode, 2) + self.assertIn("'app'", r.stderr) + self.assertNotIn("Traceback", r.stderr) + + +def fake_run(result): + return patch.object( + __import__("app_setup").subprocess, "run", return_value=result + ) + + +class BwsReaderTests(unittest.TestCase): + def setUp(self): + import app_setup + + self.app_setup = app_setup + + def test_bws_list_error_object_is_named_shape_error(self): + with fake_run(SimpleNamespace(returncode=0, stdout='{"error": "x"}', stderr="")): + with self.assertRaises(RuntimeError) as cm: + self.app_setup._bws_list() + self.assertIn("unexpected shape", str(cm.exception)) + + def test_bws_list_non_object_items_are_named_shape_error(self): + with fake_run(SimpleNamespace(returncode=0, stdout="[1, 2]", stderr="")): + with self.assertRaises(RuntimeError) as cm: + self.app_setup._bws_list() + self.assertIn("unexpected shape", str(cm.exception)) + + def test_bws_list_failure_reports_bws_stderr(self): + with fake_run(SimpleNamespace(returncode=1, stdout="", stderr="token expired")): + with self.assertRaises(RuntimeError) as cm: + self.app_setup._bws_list() + self.assertIn("token expired", str(cm.exception)) + + def test_project_id_failure_reports_bws_not_no_projects(self): + with patch.dict(os.environ, {}, clear=False): + os.environ.pop("GHB_BWS_PROJECT_ID", None) + with fake_run(SimpleNamespace(returncode=1, stdout="", stderr="bws exploded")): + with self.assertRaises(RuntimeError) as cm: + self.app_setup._project_id() + self.assertIn("bws exploded", str(cm.exception)) + self.assertNotIn("no Bitwarden projects", str(cm.exception)) + + def test_project_id_empty_list_keeps_no_projects_message(self): + with patch.dict(os.environ, {}, clear=False): + os.environ.pop("GHB_BWS_PROJECT_ID", None) + with fake_run(SimpleNamespace(returncode=0, stdout="[]", stderr="")): + with self.assertRaises(RuntimeError) as cm: + self.app_setup._project_id() + self.assertIn("no Bitwarden projects", str(cm.exception)) + + def test_bws_get_failure_is_runtime_not_json_error(self): + seq = [ + SimpleNamespace(returncode=0, stdout='[{"id": "1", "key": "k"}]', stderr=""), + SimpleNamespace(returncode=1, stdout="", stderr="get failed hard"), + ] + with patch.object(self.app_setup.subprocess, "run", side_effect=seq): + with self.assertRaises(RuntimeError) as cm: + self.app_setup.bws_get("k") + self.assertIn("get failed hard", str(cm.exception)) + + +class ConversionTests(unittest.TestCase): + def setUp(self): + import app_setup + + self.app_setup = app_setup + + def run_convert(self, conv): + stored = [] + payload = json.dumps(conv).encode() + + class Resp: + def __enter__(self): + return SimpleNamespace(read=lambda: payload) + + def __exit__(self, *a): + return False + + import urllib.request + + with ( + patch.object(urllib.request, "urlopen", return_value=Resp()), + patch.object( + self.app_setup, "bws_set", side_effect=lambda n, v: stored.append((n, v)) + ), + contextlib.redirect_stdout(io.StringIO()), + ): + self.app_setup.cmd_convert("CODE") + return stored + + def test_partial_conversion_stores_nothing(self): + conv = {"id": 1, "client_id": "c", "client_secret": "s", "slug": "app"} + with self.assertRaises(RuntimeError) as cm: + self.run_convert(conv) + self.assertIn("pem", str(cm.exception)) + + def test_full_conversion_stores_all_four_in_order(self): + conv = { + "id": 42, + "client_id": "cid", + "client_secret": "sec", + "pem": "PEM", + "slug": "my-app", + } + stored = self.run_convert(conv) + self.assertEqual( + [v for _, v in stored], ["42", "cid", "sec", "PEM"] + ) + + def test_installations_shape_validated_before_indexing(self): + bad = [{"id": 1, "account": "not-an-object"}] + with self.assertRaises(RuntimeError): + self.app_setup.validate_installations(bad) + good = [{"id": 1, "account": {"login": "octo"}}] + self.assertEqual(self.app_setup.validate_installations(good), good) + + +if __name__ == "__main__": + unittest.main()