From c7981ba94ce9f0afe065cd40de571e8ab8a544fe Mon Sep 17 00:00:00 2001 From: Hanif Koh Date: Fri, 27 Nov 2026 12:59:52 +0800 Subject: [PATCH] Harden the Sliced G-code Comparison Against Broken Artifacts and Comments A corrupt or encrypted zip member, or a bad file name, is now an artifact error, so a broken artifact gets the "made no comparison" note instead of stopping the comment, and the report step writes a report whatever fails. The fence also drops format, C1 and line separator characters. The comment is posted before the old one is deleted, comments without a user are skipped, a body GitHub returns with other line ends counts as unchanged, and a download redirect must be https. The commenter's concurrency group is on the job, so the skipped wakes of other labels cannot take the place of a pending real one. New tests cover the bounded read of a member, a run on another branch, other bot comments, comments past the first page, the newest run of a commit, and the token never reaching the storage host. --- .github/workflows/check_gcode_comment.yml | 12 +- .github/workflows/pr-label-bot.yml | 2 +- scripts/ci_check_gcode.py | 61 ++++++-- scripts/tests/test_ci_check_gcode.py | 183 +++++++++++++++++++++- 4 files changed, 230 insertions(+), 28 deletions(-) diff --git a/.github/workflows/check_gcode_comment.yml b/.github/workflows/check_gcode_comment.yml index 96c0a49bd9..5933a3a294 100644 --- a/.github/workflows/check_gcode_comment.yml +++ b/.github/workflows/check_gcode_comment.yml @@ -23,11 +23,6 @@ permissions: # Needed to delete outdated bot comments through the issues/comments endpoint. issues: write -# One handler at a time per source branch, so two wakes cannot race delete-and-post. -concurrency: - group: ${{ github.workflow }}-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }} - cancel-in-progress: false - jobs: post_comment: name: Post the comparison comment @@ -35,6 +30,11 @@ jobs: timeout-minutes: 10 # A label workflow run for any other label is skipped and has nothing to wake. if: ${{ github.event.workflow_run.event == 'pull_request' && github.event.workflow_run.conclusion != 'skipped' }} + # One handler at a time per source branch, so two wakes cannot race post-and-delete. On the + # job, not the workflow, so the skipped wakes of other labels never take a pending place. + concurrency: + group: ${{ github.workflow }}-${{ github.event.workflow_run.head_repository.full_name }}-${{ github.event.workflow_run.head_branch }} + cancel-in-progress: false steps: - name: Checkout the scripts from the default branch uses: actions/checkout@v7 @@ -46,7 +46,7 @@ jobs: persist-credentials: false - name: Update the comment - # A failure would leave a red check on the pull request, which blocks pr-merge-bot. + # The comparison is not a check; a failure is reported in the log and the next wake retries. continue-on-error: true env: GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/pr-label-bot.yml b/.github/workflows/pr-label-bot.yml index a81f09128a..9f6d34812f 100644 --- a/.github/workflows/pr-label-bot.yml +++ b/.github/workflows/pr-label-bot.yml @@ -383,7 +383,7 @@ jobs: // A label added with the workflow token starts no workflow, so without the app // token the comment waits for a build to finish. const when = process.env.STARTS_WORKFLOWS === 'true' - ? 'is posted when the build of the latest commit finishes, or shortly if it already has' + ? 'is posted when the build of the latest commit finishes, or shortly if it already has (with a note saying why if there is none); a maintainer may first have to approve the run' : 'is posted when the running build finishes, or after the next push that builds; a PR that changes no built file gets none'; try { await github.rest.issues.createComment({ diff --git a/scripts/ci_check_gcode.py b/scripts/ci_check_gcode.py index 5061bb0d12..6fc25ae357 100644 --- a/scripts/ci_check_gcode.py +++ b/scripts/ci_check_gcode.py @@ -22,10 +22,12 @@ import os import platform import sys import tempfile +import unicodedata import urllib.error import urllib.parse import urllib.request import zipfile +import zlib from dataclasses import dataclass, field sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) @@ -39,7 +41,7 @@ WORKFLOW = "build_all.yml" COMMITS_BACK = 30 # A deflated artifact is refused when it is larger than this many times the member limit. ZIP_FACTOR = 4 -# fingerprints.tsv is about 60 KB for 1,336 slices. +# fingerprints.tsv is about 144 KB for 1,336 slices. FINGERPRINTS_LIMIT = 4 * 1024 * 1024 SMALL_LIMIT = 4096 # How many slice names are listed under each vendor. @@ -50,6 +52,9 @@ BASELINE_LINE = "Baseline: " # A comment holds at most 65,536 characters; the report inside it is cut well before. FENCE_LIMIT = 50000 FENCE = "````" +# Bidi controls, and format characters that only hide text. The joiners (U+200C, U+200D) are kept. +HIDDEN_CHARACTERS = (set("\u061c\u200b\u200e\u200f\u202a\u202b\u202c\u202d\u202e\u2060\u2066\u2067\u2068\u2069\ufeff") + | {chr(c) for c in range(0x206A, 0x2070)} | {chr(c) for c in range(0xE0000, 0xE0080)}) LABEL = "check-gcode" MARKER = "" HEADING = "## Sliced G-code comparison" @@ -103,9 +108,12 @@ class Api: except urllib.error.HTTPError as error: if error.code not in (301, 302, 303, 307, 308): raise - location = error.headers["Location"] + location = error.headers["Location"] or "" error.close() - response = urllib.request.urlopen(location, timeout=60) + if not location.startswith("https://"): + raise ArtifactError("the download redirect is not to an https address") + # No further redirect is followed: storage answers directly. + response = opener.open(location, timeout=60) with response: data = response.read(limit + 1) if len(data) > limit: @@ -160,7 +168,9 @@ def read_artifact(api, repo, art, names, limit): if len(content) > limit: raise ArtifactError("an artifact file is larger than its limit") found[name] = content - except (zipfile.BadZipFile, zipfile.LargeZipFile, NotImplementedError, EOFError, OSError) as error: + # zlib.error: a corrupt stream; RuntimeError: an encrypted member; ValueError: a bad file name. + except (zipfile.BadZipFile, zipfile.LargeZipFile, NotImplementedError, EOFError, OSError, + zlib.error, RuntimeError, ValueError) as error: raise ArtifactError("the artifact is not a readable zip") from error return found @@ -222,7 +232,10 @@ def build_report(baseline, base_rows, head_rows, base_made_with, head_made_with, def fence(data): """Text from an artifact as a Markdown code block nothing in it can close or turn into markup.""" text = data.decode("utf-8", "replace") - text = "".join(c for c in text if c in "\n\t" or (c >= " " and c != "\x7f")) + # Control characters, line separators, bidi controls and invisible characters would change how + # the text reads. Other format characters, such as the joiners in emoji and some scripts, are kept. + text = "".join(c for c in text if c in "\n\t" + or not (unicodedata.category(c) in ("Cc", "Cs", "Zl", "Zp") or c in HIDDEN_CHARACTERS)) while FENCE in text: text = text.replace(FENCE, "```") if len(text.encode()) > FENCE_LIMIT: @@ -270,7 +283,7 @@ def _stable(body): """The part of a comment that a new commit or a new baseline with the same result leaves alone: all but the last line, without the baseline paragraph inside the fence.""" kept, skipping = [], False - for line in body.splitlines()[:-1]: + for line in body.rstrip().splitlines()[:-1]: if line.startswith(BASELINE_LINE): skipping = True elif line == FENCE: @@ -284,7 +297,8 @@ def _bot_comments(api, repo, number): found, page = [], 1 while True: batch = api.get(f"repos/{repo}/issues/{number}/comments", per_page=100, page=page) - found += [c for c in batch if c["user"]["login"] == BOT_LOGIN and c["body"].startswith(MARKER)] + found += [c for c in batch if (c["user"] or {}).get("login") == BOT_LOGIN + and (c["body"] or "").startswith(MARKER)] if len(batch) < 100: return found page += 1 @@ -293,14 +307,19 @@ def _bot_comments(api, repo, number): def post_comment(api, repo, number, body): """Keeps an identical comment, edits one whose result is the same, else replaces them all.""" old = _bot_comments(api, repo, number) - if len(old) == 1 and old[0]["body"] == body: - return - if len(old) == 1 and _stable(old[0]["body"]) == _stable(body): - api.send("PATCH", f"repos/{repo}/issues/comments/{old[0]['id']}", {"body": body}) - return - for c in old: + # The newest one is compared, so one left behind by a failed delete cannot make every wake post. + newest, extra = (old[-1], old[:-1]) if old else (None, []) + # GitHub may hand the body back with other line ends. + if newest and newest["body"].replace("\r", "").rstrip() == body.rstrip(): + pass + elif newest and _stable(newest["body"]) == _stable(body): + api.send("PATCH", f"repos/{repo}/issues/comments/{newest['id']}", {"body": body}) + else: + # Posted first, so a failed post leaves the old comment rather than none. + api.send("POST", f"repos/{repo}/issues/{number}/comments", {"body": body}) + extra = old + for c in extra: api.send("DELETE", f"repos/{repo}/issues/comments/{c['id']}") - api.send("POST", f"repos/{repo}/issues/{number}/comments", {"body": body}) def comment_body(sha, report=None, note=None): @@ -328,7 +347,17 @@ def find_report(api, repo, pr): art = find_artifact(api, repo, run["id"]) if not art: continue - files = read_artifact(api, repo, art, ["pr_number.txt", "report.txt"], REPORT_LIMIT) + try: + files = read_artifact(api, repo, art, ["pr_number.txt", "report.txt"], REPORT_LIMIT) + except ArtifactError: + # A broken artifact: an older run may still have a good one. + continue + except urllib.error.HTTPError as error: + # Any other failure posts nothing, so a passing outage cannot replace the comment. + if error.code not in (404, 410): + raise + # The artifact expired after it was listed. + continue if files.get("pr_number.txt", b"").strip() == str(pr["number"]).encode() and "report.txt" in files: return files["report.txt"], None return None, NO_COMPARISON @@ -389,7 +418,7 @@ def main(argv=None): return 0 try: text = report_main(args, api) - except (ArtifactError, urllib.error.URLError, OSError, ValueError, KeyError, TypeError) as error: + except Exception as error: # noqa: BLE001 - the step must still write a report # The type only: the message of an error from the baseline's files can hold their text. print(f"The comparison could not be made ({type(error).__name__}).") text = f"The comparison could not be made ({type(error).__name__}).\n" diff --git a/scripts/tests/test_ci_check_gcode.py b/scripts/tests/test_ci_check_gcode.py index 76022ad0fb..2afd2bb462 100644 --- a/scripts/tests/test_ci_check_gcode.py +++ b/scripts/tests/test_ci_check_gcode.py @@ -78,6 +78,41 @@ class ReadArtifactTest(unittest.TestCase): with self.assertRaises(cc.ArtifactError): cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT) + def test_a_member_honestly_larger_than_the_limit_is_refused(self): + api, art = self.api_with(make_zip({"report.txt": "x" * (LIMIT + 1)})) + with self.assertRaises(cc.ArtifactError): + cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT) + + def test_a_member_is_never_decompressed_past_the_limit(self): + # A zip bomb must not be inflated whole before its size is checked. + sizes = [] + real_read = zipfile.ZipExtFile.read + + def read(member, n=-1): + sizes.append(n) + return real_read(member, n) + + api, art = self.api_with(make_zip({"report.txt": "x" * (LIMIT * 50)})) + with mock.patch.object(zipfile.ZipExtFile, "read", read), self.assertRaises(cc.ArtifactError): + cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT) + self.assertEqual(sizes, [LIMIT + 1]) + + def test_a_corrupt_or_encrypted_member_is_an_artifact_error(self): + data = bytearray(make_zip({"report.txt": "z" * 500})) + local = data.index(b"PK\x03\x04") + start = local + 30 + int.from_bytes(data[local + 26:local + 28], "little") + corrupt = bytearray(data) + corrupt[start:start + 4] = b"\xff\xff\xff\xff" + # Bit 0 of the general purpose flags, in both headers, marks a member as encrypted. + encrypted = bytearray(data) + central = encrypted.index(b"PK\x01\x02") + encrypted[local + 6] |= 1 + encrypted[central + 8] |= 1 + for bad in (bytes(corrupt), bytes(encrypted)): + api, art = self.api_with(bad) + with self.assertRaises(cc.ArtifactError): + cc.read_artifact(api, REPO, art, ["report.txt"], LIMIT) + def test_an_artifact_over_the_size_cap_is_refused_before_it_is_downloaded(self): api, art = self.api_with(b"", size=cc.ZIP_FACTOR * LIMIT + 1) with self.assertRaises(cc.ArtifactError): @@ -154,6 +189,11 @@ class FindBaselineTest(unittest.TestCase): {31: [artifact(310)], 20: [artifact(200)]}) self.assertEqual(cc.find_baseline(api, REPO, "main", "c3" * 20).run_id, 20) + def test_the_newest_run_of_a_commit_is_used(self): + api = self.api(self.COMMITS, [run(30, "c3" * 20), run(35, "c3" * 20, event="schedule")], + {30: [artifact(300)], 35: [artifact(350)]}) + self.assertEqual(cc.find_baseline(api, REPO, "main", "c3" * 20).run_id, 35) + def test_a_nightly_run_is_a_baseline(self): api = self.api(self.COMMITS, [run(40, "c3" * 20, event="schedule")], {40: [artifact(400)]}) self.assertEqual(cc.find_baseline(api, REPO, "main", "c3" * 20).run_id, 40) @@ -191,8 +231,16 @@ class FenceTest(unittest.TestCase): self.assertFalse(any("````" in line for line in body)) def test_control_characters_are_dropped_and_bad_utf8_replaced(self): - fenced = cc.fence(b"a\x00b\x1b[31mc\td\xff\n") - self.assertIn("ab[31mc\td\ufffd", fenced) + fenced = cc.fence(b"a\x00b\x1b[31mc\td\xff\x7fe\r\n") + self.assertIn("ab[31mc\td\ufffde\n", fenced) + + def test_bidi_controls_c1_and_line_separators_are_dropped_but_joiners_kept(self): + fenced = cc.fence("a\u202eb\u0085c\u2066d\u2028e \U0001f469\u200d\U0001f52c\n".encode()) + self.assertIn("abcde \U0001f469\u200d\U0001f52c\n", fenced) + + def test_invisible_characters_are_dropped_but_joiners_kept(self): + fenced = cc.fence("a\u200bb\u2060c\ufeffd\u206ae\U000e0041f\u200cg\n".encode()) + self.assertIn("abcdef\u200cg\n", fenced) def test_a_long_report_is_cut_on_a_line_boundary_inside_the_fence(self): fenced = cc.fence(("x" * 99 + "\n").encode() * 1000) @@ -298,7 +346,8 @@ def comment(comment_id, body): class CommentTest(unittest.TestCase): def run_comment(self, api, head_repo=HEAD_REPO): - cc.comment(api, REPO, head_repo, "fix") + with contextlib.redirect_stdout(io.StringIO()): + cc.comment(api, REPO, head_repo, "fix") return api.sent def posted(self, sent): @@ -319,8 +368,10 @@ class CommentTest(unittest.TestCase): self.assertEqual(self.run_comment(api), []) def test_a_pull_request_into_another_branch_is_told_why_there_is_no_report(self): - body = self.posted(self.run_comment(CommentFake([pull(base="feature/x")]))) + api = CommentFake([pull(base="feature/x")], [pr_run(1)], {1: report_artifact()}) + body = self.posted(self.run_comment(api)) self.assertIn("no `Build all` run", body) + self.assertNotIn("G-code changed", body) def test_a_commit_without_a_build_is_told_why(self): body = self.posted(self.run_comment(CommentFake([pull()]))) @@ -345,6 +396,15 @@ class CommentTest(unittest.TestCase): self.assertNotIn("forged", body) self.assertIn("no `Build all` run", body) + def test_a_run_from_another_branch_of_the_same_repository_is_not_used(self): + api = CommentFake([pull()], [pr_run(2, branch="other")], {2: report_artifact("forged\n")}) + self.assertNotIn("forged", self.posted(self.run_comment(api))) + + def test_a_broken_artifact_falls_through_to_the_note(self): + api = CommentFake([pull()], [pr_run(1)], {1: report_artifact()}) + api.blobs[f"repos/{REPO}/actions/artifacts/10/zip"] = b"not a zip" + self.assertIn("made no comparison", self.posted(self.run_comment(api))) + def test_an_artifact_naming_another_pull_request_is_not_used(self): api = CommentFake([pull()], [pr_run(1)], {1: report_artifact(number="6\n")}) self.assertIn("made no comparison", self.posted(self.run_comment(api))) @@ -381,8 +441,115 @@ class CommentTest(unittest.TestCase): api = CommentFake([pull()], [pr_run(1)], {1: report_artifact("after\n")}, [comment(9, old), {"id": 8, "user": {"login": "someone"}, "body": cc.MARKER}]) sent = self.run_comment(api) + # Posted before the old one goes, so a failed post leaves the old comment. self.assertEqual([(m, p) for m, p, _ in sent], - [("DELETE", f"repos/{REPO}/issues/comments/9"), ("POST", f"repos/{REPO}/issues/5/comments")]) + [("POST", f"repos/{REPO}/issues/5/comments"), ("DELETE", f"repos/{REPO}/issues/comments/9")]) + + def test_other_bot_comments_and_comments_without_a_user_are_left_alone(self): + old = self.body_for("before\n") + others = [comment(7, "@someone the build for `build-all` starts now."), {"id": 6, "user": None, "body": "x"}] + api = CommentFake([pull()], [pr_run(1)], {1: report_artifact("after\n")}, others + [comment(9, old)]) + deleted = [p for m, p, _ in self.run_comment(api) if m == "DELETE"] + self.assertEqual(deleted, [f"repos/{REPO}/issues/comments/9"]) + + def test_an_identical_comment_with_other_line_ends_is_kept(self): + old = self.body_for("same\n").replace("\n", "\r\n").rstrip() + api = CommentFake([pull()], [pr_run(1)], {1: report_artifact("same\n")}, [comment(9, old)]) + self.assertEqual(self.run_comment(api), []) + + def test_a_crlf_comment_with_the_same_result_is_edited_in_place(self): + old = self.body_for("same\nBaseline: compared with aaaa\n", sha="e" * 40).replace("\n", "\r\n") + api = CommentFake([pull()], [pr_run(1)], {1: report_artifact("same\nBaseline: compared with bbbb\n")}, + [comment(9, old)]) + self.assertEqual([m for m, _, _ in self.run_comment(api)], ["PATCH"]) + + def test_a_comment_left_by_a_failed_delete_is_cleaned_up_without_posting_again(self): + current = self.body_for("same\n") + api = CommentFake([pull()], [pr_run(1)], {1: report_artifact("same\n")}, + [comment(8, self.body_for("older\n")), comment(9, current)]) + self.assertEqual([(m, p) for m, p, _ in self.run_comment(api)], [("DELETE", f"repos/{REPO}/issues/comments/8")]) + + def failing_download(self, error): + api = CommentFake([pull()], [pr_run(2), pr_run(1)], {2: report_artifact("new\n"), 1: report_artifact("old\n")}) + real = api.get_bytes + + def get_bytes(path, limit): + if path.endswith("/20/zip"): + raise error + return real(path, limit) + + api.get_bytes = get_bytes + return api + + def test_an_artifact_that_is_gone_falls_through_to_an_older_run(self): + for code in (404, 410): + with self.subTest(code=code): + api = self.failing_download(urllib.error.HTTPError("x", code, "Gone", {}, None)) + self.assertIn("````\nold\n````", self.posted(self.run_comment(api))) + + def test_a_download_that_fails_for_another_reason_posts_nothing(self): + # A passing outage must not replace the comment with a note that the build made no comparison. + for error in (urllib.error.HTTPError("x", 503, "Unavailable", {}, None), urllib.error.URLError("dns"), + TimeoutError(), ConnectionResetError()): + with self.subTest(error=type(error).__name__): + api = self.failing_download(error) + with self.assertRaises(type(error)): + self.run_comment(api) + self.assertEqual(api.sent, []) + + def test_the_comment_is_found_past_the_first_page(self): + old = self.body_for("before\n") + api = CommentFake([pull()], [pr_run(1)], {1: report_artifact("after\n")}) + pages = {1: [comment(100 + i, "other") for i in range(100)], 2: [comment(9, old)]} + api.gets[f"repos/{REPO}/issues/5/comments"] = lambda params: pages.get(params["page"], []) + deleted = [p for m, p, _ in self.run_comment(api) if m == "DELETE"] + self.assertEqual(deleted, [f"repos/{REPO}/issues/comments/9"]) + + +class GetBytesTest(unittest.TestCase): + """Api.get_bytes with urllib faked: the storage host must never see the token.""" + + def fake(self, location="https://storage.example/blob", body=b"zipdata"): + seen = [] + + class Opener: + def open(self, request, timeout): + if isinstance(request, str): + seen.append(("storage", request)) + if body is None: + raise urllib.error.HTTPError(request, 302, "Found", {"Location": "http://x/"}, None) + return io.BytesIO(body) + seen.append(("api", request.get_header("Authorization"))) + raise urllib.error.HTTPError(request.full_url, 302, "Found", {"Location": location}, None) + + self.build_opener = mock.patch.object(cc.urllib.request, "build_opener", return_value=Opener()) + return seen, self.build_opener, \ + mock.patch.object(cc.urllib.request, "urlopen", side_effect=AssertionError("not via urlopen")) + + def test_the_redirect_is_followed_without_the_token(self): + seen, opener, urlopen = self.fake() + with opener, urlopen: + self.assertEqual(cc.Api("secret").get_bytes("repos/x/zip", 100), b"zipdata") + self.assertEqual(seen, [("api", "Bearer secret"), ("storage", "https://storage.example/blob")]) + + def test_a_download_larger_than_the_limit_is_refused(self): + _, opener, urlopen = self.fake(body=b"x" * 101) + with opener, urlopen, self.assertRaises(cc.ArtifactError): + cc.Api("secret").get_bytes("repos/x/zip", 100) + + def test_storage_redirecting_again_is_not_followed(self): + seen, opener, urlopen = self.fake(body=None) + with opener as build_opener, urlopen, self.assertRaises(urllib.error.HTTPError): + cc.Api("secret").get_bytes("repos/x/zip", 100) + # Both hops go through an opener that turns a redirect into an error. + build_opener.assert_called_once_with(cc._NoRedirect) + self.assertEqual(len([s for s in seen if s[0] == "storage"]), 1) + + def test_a_redirect_that_is_not_https_is_refused(self): + seen, opener, urlopen = self.fake(location="http://storage.example/blob") + with opener, urlopen, self.assertRaises(cc.ArtifactError): + cc.Api("secret").get_bytes("repos/x/zip", 100) + self.assertEqual([s for s in seen if s[0] == "storage"], []) class CommentCommandTest(unittest.TestCase): @@ -415,6 +582,12 @@ class ReportCommandTest(unittest.TestCase): self.assertNotIn("line from the artifact", text) self.assertIn("could not be made (ValueError)", report) + def test_any_error_still_writes_a_report(self): + with tempfile.TemporaryDirectory() as folder: + code, _, report, _ = self.run_report(folder, RuntimeError("x")) + self.assertEqual(code, 0) + self.assertIn("could not be made (RuntimeError)", report) + def test_the_summary_holds_the_report_inside_a_fence(self): with tempfile.TemporaryDirectory() as folder: _, _, report, summary = self.run_report(folder, text="G-code is the same\n")