From 151e300abe18d760cf29d724b10cfaf62154ee9f Mon Sep 17 00:00:00 2001 From: hamdog0203 <360416966+hamdog0203@users.noreply.github.com> Date: Tue, 24 Nov 2026 11:09:17 +0100 Subject: [PATCH 1/2] progress_dashboard: handle null comment authors, require --run-tests for --tests, and catch I/O and history errors (DASH-HARDEN-CLI) --- tests/test_progress_dashboard.py | 82 ++++++++++++++++++++++++++++++++ tools/progress_dashboard.py | 36 +++++++++++--- 2 files changed, 112 insertions(+), 6 deletions(-) diff --git a/tests/test_progress_dashboard.py b/tests/test_progress_dashboard.py index ad22e81499..db44303a13 100644 --- a/tests/test_progress_dashboard.py +++ b/tests/test_progress_dashboard.py @@ -656,5 +656,87 @@ def test_out_as_existing_file_is_refused(self): self.assertIn("is not a directory", err.getvalue()) +class Hardening(unittest.TestCase): + @staticmethod + def _minimal_snap(): + return { + "schema": pd.SCHEMA, "generated_at": "2026-11-24T10:00:00Z", "git": {}, + "panels": [], "counts": {}, "components": [], "metrics": [], + "sources": [], "notes": [], "github": {}, "content_hash": "0" * 64, + } + + def test_github_login_skips_null_author_and_null_body(self): + def fake_gh(args, timeout=60): + if args[:2] == ["issue", "list"] and "Coordinating" in args[args.index("--search") + 1]: + return [{"number": 14, "title": "Coordinating who works on what", "updatedAt": "2026-11-24T00:00:00Z"}] + if args[:2] == ["issue", "view"] and args[2] == "14": + fields = args[args.index("--json") + 1] + if fields == "body": + return {"body": "### Up for grabs\n| X-1 |\n"} + if fields == "comments": + return {"comments": [ + {"author": None, "body": "claiming: X", "createdAt": "2026-11-24T01:00:00Z"}, + {"author": {"login": "alice"}, "body": None, "createdAt": "2026-11-24T01:01:00Z"}, + {"author": {"login": "alice"}, "body": "claiming: Y", "createdAt": "2026-11-24T01:02:00Z"}, + ]} + return [] + + col = pd.Collector() + with mock.patch.object(pd, "gh_json", fake_gh), mock.patch.object(pd.shutil, "which", lambda _: "/usr/bin/gh"): + summary = pd.collect_github(col, "o/r", "alice") + self.assertEqual(summary["mine"]["claims"], + [{"at": "2026-11-24T01:02:00Z", "issue": 14, "text": "claiming: Y"}]) + + def test_tests_flag_requires_run_tests(self): + with tempfile.TemporaryDirectory() as tmp: + err = io.StringIO() + with contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as stop: + pd.main(["--out", os.path.join(tmp, "out"), "--tests", "foo"]) + self.assertEqual(stop.exception.code, 2) + self.assertIn("--tests requires --run-tests", err.getvalue()) + + def test_ci_test_files_oserror_exits_2_cleanly(self): + with tempfile.TemporaryDirectory() as tmp: + err = io.StringIO() + with mock.patch.object(pd, "ci_test_files", side_effect=PermissionError(13, "denied", "tests/blocked")), \ + contextlib.redirect_stderr(err): + rc = pd.main(["--out", os.path.join(tmp, "out"), "--run-tests"]) + self.assertEqual(rc, 2) + self.assertIn("denied", err.getvalue()) + + def test_corrupt_non_list_and_bom_history_json(self): + snap = self._minimal_snap() + with tempfile.TemporaryDirectory() as tmp: + out = os.path.join(tmp, "out") + os.makedirs(out) + hist = Path(out, "history.json") + for bad in (b"{bad", b"{}"): + hist.write_bytes(bad) + err = io.StringIO() + with mock.patch.object(pd, "build", return_value=snap), contextlib.redirect_stderr(err): + rc = pd.main(["--out", out]) + self.assertEqual(rc, 2) + self.assertIn("error:", err.getvalue()) + + valid = [{"generated_at": "2026-11-24T09:00:00Z", "head": "abc", "content_hash": "0" * 16, "metrics": {}}] + hist.write_bytes(b"\xef\xbb\xbf" + json.dumps(valid).encode("utf-8")) + out_s, err = io.StringIO(), io.StringIO() + with mock.patch.object(pd, "build", return_value=snap), \ + contextlib.redirect_stdout(out_s), contextlib.redirect_stderr(err): + rc = pd.main(["--out", out]) + self.assertEqual(rc, 0, err.getvalue()) + + def test_write_outputs_oserror_exits_2_cleanly(self): + snap = self._minimal_snap() + with tempfile.TemporaryDirectory() as tmp: + err = io.StringIO() + with mock.patch.object(pd, "build", return_value=snap), \ + mock.patch.object(pd, "write_outputs", side_effect=PermissionError(13, "read-only", "progress.html")), \ + contextlib.redirect_stderr(err): + rc = pd.main(["--out", os.path.join(tmp, "out")]) + self.assertEqual(rc, 2) + self.assertIn("read-only", err.getvalue()) + + if __name__ == "__main__": unittest.main() diff --git a/tools/progress_dashboard.py b/tools/progress_dashboard.py index 9e9d0eb28b..8c4c224478 100644 --- a/tools/progress_dashboard.py +++ b/tools/progress_dashboard.py @@ -951,9 +951,11 @@ def collect_github(col, repo, login, d3d_issue=None): claims = [] for n in [num] + ([int(prev.group(1))] if prev else []): comments = gh_json(["issue", "view", str(n), "-R", repo, "--json", "comments"]) or {} - claims += [{"at": c.get("createdAt"), "issue": n, "text": plain(c["body"].splitlines()[0])[:160]} - for c in comments.get("comments", []) - if c.get("author", {}).get("login") == login and "claiming" in c["body"].lower()] + for c in comments.get("comments", []): + body_text = c.get("body") or "" + if (c.get("author") or {}).get("login") == login and "claiming" in body_text.lower(): + first_line = (body_text.splitlines() or [""])[0] + claims.append({"at": c.get("createdAt"), "issue": n, "text": plain(first_line)[:160]}) prs = gh_json(["pr", "list", "-R", repo, "--author", login, "--state", "all", "--limit", "50", "--json", "number,title,state,isDraft,updatedAt"]) or [] summary["mine"] = {"login": login, "claims": claims, @@ -1018,10 +1020,22 @@ def render_page(snap, history): return template.replace("/*__PROGRESS_LOGO__*/", logo_src()).replace("/*__PROGRESS_DATA__*/null", payload) +def _load_history(hist_path): + if not os.path.isfile(hist_path): + return [] + try: + history = json.loads(read_utf8(hist_path).lstrip("\ufeff")) + except ValueError as exc: + raise ValueError(f"{hist_path}: invalid JSON: {exc}") from None + if not isinstance(history, list) or any(not isinstance(item, dict) or "content_hash" not in item for item in history): + raise ValueError(f"{hist_path}: expected a JSON list of snapshot summaries") + return history + + def write_outputs(snap, out_dir): os.makedirs(os.path.join(out_dir, "snapshots"), exist_ok=True) hist_path = os.path.join(out_dir, "history.json") - history = json.loads(read_utf8(hist_path)) if os.path.isfile(hist_path) else [] + history = _load_history(hist_path) new = not history or history[-1]["content_hash"] != snap["content_hash"][:16] if new: stamp = snap["generated_at"].replace("-", "").replace(":", "") @@ -1058,6 +1072,8 @@ def main(argv=None): ap.error("--d3d-issue requires --github") if args.d3d_issue is not None and args.d3d_issue < 1: ap.error("--d3d-issue must be a positive integer") + if args.tests is not None and not args.run_tests: + ap.error("--tests requires --run-tests") if args.jobs < 1: ap.error("--jobs must be a positive integer") if args.test_timeout < 1: @@ -1075,7 +1091,12 @@ def main(argv=None): print(f"--work {args.work} is not a folder", file=sys.stderr) return 2 if args.run_tests: - args.test_files = [f for f in ci_test_files() if not args.tests or re.search(args.tests, f)] + try: + all_tests = ci_test_files() + except OSError as exc: + print(f"error: {exc.filename or ''}: {exc.strerror or exc}", file=sys.stderr) + return 2 + args.test_files = [f for f in all_tests if not args.tests or re.search(args.tests, f)] if args.tests and not args.test_files: ap.error("--tests did not match any test files") if os.path.exists(out_dir) and not os.path.isdir(out_dir): @@ -1088,10 +1109,13 @@ def main(argv=None): return 2 try: snap = build(args, out_dir) + new = write_outputs(snap, out_dir) except OSError as exc: print(f"error: {exc.filename or ''}: {exc.strerror or exc}", file=sys.stderr) return 2 - new = write_outputs(snap, out_dir) + except ValueError as exc: + print(f"error: {exc}", file=sys.stderr) + return 2 n = len(snap["components"]) print(f"{n} units, {len(snap['metrics'])} metrics -> {os.path.join(out_dir, 'progress.html')}" + ("" if new else " (no change since the last snapshot)")) From 3c2ad30d523ed06a6ed2debe30e035d08c984618 Mon Sep 17 00:00:00 2001 From: hamdog0203 <360416966+hamdog0203@users.noreply.github.com> Date: Tue, 24 Nov 2026 16:20:01 +0100 Subject: [PATCH 2/2] progress_dashboard: require string content_hash and dict metrics in history.json --- tests/test_progress_dashboard.py | 11 ++++++++++- tools/progress_dashboard.py | 7 ++++++- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/tests/test_progress_dashboard.py b/tests/test_progress_dashboard.py index db44303a13..81e61ee0de 100644 --- a/tests/test_progress_dashboard.py +++ b/tests/test_progress_dashboard.py @@ -710,13 +710,22 @@ def test_corrupt_non_list_and_bom_history_json(self): out = os.path.join(tmp, "out") os.makedirs(out) hist = Path(out, "history.json") - for bad in (b"{bad", b"{}"): + for bad in ( + b"{bad", + b"{}", + b'[{"content_hash":"old"}]', + b'[{"content_hash":"old","metrics":null}]', + b'[{"content_hash":"old","metrics":[]}]', + b'[{"content_hash":null,"metrics":{}}]', + ): hist.write_bytes(bad) err = io.StringIO() with mock.patch.object(pd, "build", return_value=snap), contextlib.redirect_stderr(err): rc = pd.main(["--out", out]) self.assertEqual(rc, 2) self.assertIn("error:", err.getvalue()) + self.assertEqual(hist.read_bytes(), bad) + self.assertFalse(Path(out, "progress.html").exists()) valid = [{"generated_at": "2026-11-24T09:00:00Z", "head": "abc", "content_hash": "0" * 16, "metrics": {}}] hist.write_bytes(b"\xef\xbb\xbf" + json.dumps(valid).encode("utf-8")) diff --git a/tools/progress_dashboard.py b/tools/progress_dashboard.py index 8c4c224478..562bb0654c 100644 --- a/tools/progress_dashboard.py +++ b/tools/progress_dashboard.py @@ -1027,7 +1027,12 @@ def _load_history(hist_path): history = json.loads(read_utf8(hist_path).lstrip("\ufeff")) except ValueError as exc: raise ValueError(f"{hist_path}: invalid JSON: {exc}") from None - if not isinstance(history, list) or any(not isinstance(item, dict) or "content_hash" not in item for item in history): + if not isinstance(history, list) or any( + not isinstance(item, dict) + or not isinstance(item.get("content_hash"), str) + or not isinstance(item.get("metrics"), dict) + for item in history + ): raise ValueError(f"{hist_path}: expected a JSON list of snapshot summaries") return history