| #!/usr/bin/env python3 | |
| # | |
| # Copyright 2026 The Fuchsia Authors | |
| # | |
| # Licensed under a BSD-style license <LICENSE-BSD>, Apache License, Version 2.0 | |
| # <LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, or the MIT | |
| # license <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option. | |
| # This file may not be copied, modified, or distributed except according to | |
| # those terms. | |
| """Unit tests for `anneal/ci/pr_preflight.py`.""" | |
| from __future__ import annotations | |
| import io | |
| import json | |
| import os | |
| from pathlib import Path | |
| import subprocess | |
| import sys | |
| import tempfile | |
| import time | |
| import unittest | |
| from unittest import mock | |
| CI_DIR = Path(__file__).resolve().parent | |
| if str(CI_DIR) not in sys.path: | |
| sys.path.insert(0, str(CI_DIR)) | |
| import pr_preflight | |
| def _git(repo: Path, *args: str, env: dict[str, str] | None = None) -> str: | |
| merged_env = { | |
| k: v for k, v in os.environ.items() if not k.startswith("GIT_") | |
| } | |
| merged_env["GIT_CONFIG_NOSYSTEM"] = "1" | |
| merged_env["GIT_CONFIG_GLOBAL"] = os.devnull | |
| if env: | |
| merged_env.update(env) | |
| proc = subprocess.run( | |
| ["git", "-c", "core.hooksPath=/dev/null", "-C", str(repo), *args], | |
| env=merged_env, | |
| check=True, | |
| capture_output=True, | |
| text=True, | |
| ) | |
| return proc.stdout.strip() | |
| class TestPrPreflight(unittest.TestCase): | |
| def setUp(self) -> None: | |
| # Isolate tests from ambient ANNEAL_PREFLIGHT_* env vars. | |
| self._env_patch = mock.patch.dict( | |
| os.environ, | |
| { | |
| "ANNEAL_PREFLIGHT_EXTRA_LEAK_REGEX": "", | |
| "ANNEAL_PREFLIGHT_EXTRA_LEAK_FILE": "", | |
| "ANNEAL_PREFLIGHT_GH_CACHE": "", | |
| }, | |
| clear=False, | |
| ) | |
| self._env_patch.start() | |
| self.addCleanup(self._env_patch.stop) | |
| def _init_repo(self, root: Path) -> Path: | |
| repo = root / "repo" | |
| repo.mkdir() | |
| _git(repo, "init", "-q", "-b", "main") | |
| _git(repo, "config", "user.name", "Test Engineer") | |
| _git(repo, "config", "user.email", "engineer@google.com") | |
| (repo / "docs").mkdir(parents=True) | |
| (repo / ".gemini").mkdir(parents=True) | |
| header = ( | |
| "<!-- Copyright 2026 The Fuchsia Authors\n\n" | |
| "Licensed under a BSD-style license <LICENSE-BSD>, Apache License, " | |
| "Version 2.0\n" | |
| "<LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0>, " | |
| "or the MIT\n" | |
| "license <LICENSE-MIT or https://opensource.org/licenses/MIT>, " | |
| "at your option.\n" | |
| "This file may not be copied, modified, or distributed except " | |
| "according to\n" | |
| "those terms. -->\n\n" | |
| ) | |
| crr = ( | |
| "<!-- code-review-rules:begin -->\n" | |
| "Rule 1.\n" | |
| "<!-- code-review-rules:end -->\n" | |
| ) | |
| (repo / "AGENTS.md").write_text( | |
| "# Agents\n\n" + crr, encoding="utf-8" | |
| ) | |
| (repo / ".gemini" / "styleguide.md").write_text( | |
| "# Style\n\n" + crr, encoding="utf-8" | |
| ) | |
| (repo / "THIRD_PARTY_NOTICES.md").write_text( | |
| header + "# Third-Party Notices\n", encoding="utf-8" | |
| ) | |
| (repo / "docs" / "note.md").write_text( | |
| header + "# Note\n\nInitial clean paragraph.\n", | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", ".") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Add initial note\n\nAdd the initial note fixture.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| return repo | |
| def test_clean_commit_stale_cache_pure_rebase_and_whitespace_diff( | |
| self, | |
| ) -> None: | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| repo = self._init_repo(tmp) | |
| missing_cache = tmp / "no_gh_cache.json" | |
| _git(repo, "checkout", "-b", "feat/clean") | |
| doc_path = repo / "docs" / "note.md" | |
| extra_lines = "\n".join( | |
| f"Paragraph line {i} stays cleanly wrapped." for i in range(20) | |
| ) | |
| doc_path.write_text( | |
| doc_path.read_text(encoding="utf-8") + "\n" + extra_lines + "\n", | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "docs/note.md") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Extend note with wrapped lines\n\n" | |
| "Explain why the extra note lines are helpful.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| prior_sha = _git(repo, "rev-parse", "HEAD") | |
| # Stale cache (>900s) MUST fall back to `gh_fetch_fn`. | |
| stale_cache = tmp / "stale_gh_cache.json" | |
| stale_cache.write_text( | |
| json.dumps({ | |
| "fetched_at_epoch": time.time() - 3600.0, | |
| "prs": [], | |
| }), | |
| encoding="utf-8", | |
| ) | |
| live_rows = [ | |
| { | |
| "number": 4284, | |
| "author": {"login": "bob"}, | |
| "headRefName": "other-branch", | |
| "isDraft": False, | |
| "files": {"nodes": [{"path": "docs/note.md"}]}, | |
| } | |
| ] | |
| rc, rep = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| gh_cache_path=stale_cache, | |
| gh_fetch_fn=lambda _slug: live_rows, | |
| ) | |
| self.assertEqual(rc, 0, rep) | |
| self.assertEqual(len(rep["overlaps"]), 1) | |
| self.assertEqual(rep["overlaps"][0]["pr"], 4284) | |
| self.assertFalse(rep["is_pure_verbatim_rebase"]) | |
| # Same-base commit-message amend is NOT a pure rebase. | |
| _git( | |
| repo, | |
| "commit", | |
| "--amend", | |
| "-m", | |
| "[docs] Extend note with wrapped lines\n\n" | |
| "Updated commit message on same base.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| rc_amend, rep_amend = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| prior_head_ref=prior_sha, | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc_amend, 0) | |
| self.assertFalse(rep_amend["is_pure_verbatim_rebase"]) | |
| # Advance `main` with an unrelated file and rebase `feat/clean`: | |
| # base moved, raw tree deltas and commit messages match -> True. | |
| amended_sha = _git(repo, "rev-parse", "HEAD") | |
| _git(repo, "checkout", "main") | |
| (repo / "README_OTHER.txt").write_text( | |
| "main move\n", encoding="utf-8" | |
| ) | |
| _git(repo, "add", "README_OTHER.txt") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Move main forward\n\nAdvance main.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| _git(repo, "checkout", "feat/clean") | |
| _git(repo, "rebase", "main") | |
| rc_reb, rep_reb = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| prior_head_ref=amended_sha, | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc_reb, 0, rep_reb) | |
| self.assertTrue(rep_reb["is_pure_verbatim_rebase"]) | |
| # Rebase that ALSO alters leading indentation MUST NOT be treated | |
| # as a pure rebase (proves exact blob OID comparison). | |
| doc_path.write_text( | |
| doc_path.read_text(encoding="utf-8").replace( | |
| "Paragraph line 0", " Paragraph line 0", 1 | |
| ), | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "docs/note.md") | |
| _git(repo, "commit", "--amend", "--no-edit") | |
| rc_ws, rep_ws = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| prior_head_ref=amended_sha, | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc_ws, 0, rep_ws) | |
| self.assertFalse(rep_ws["is_pure_verbatim_rebase"]) | |
| def test_benign_go_paths_and_dotted_internal_identifiers_pass(self) -> None: | |
| """Separate clean commit verifies benign Go paths and `.Internal.`.""" | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| repo = self._init_repo(tmp) | |
| missing_cache = tmp / "no_gh_cache.json" | |
| _git(repo, "checkout", "-b", "feat/benign") | |
| doc_path = repo / "docs" / "note.md" | |
| doc_path.write_text( | |
| doc_path.read_text(encoding="utf-8") | |
| + "\nBenign paths: `src/go/parser.rs`, `foo/go/bar`,\n" | |
| + "`go/main.go`, `pkg.go/foo`, `my-go/bar`.\n" | |
| + "Lean and Rust names: `Std.Internal.UV`, `Lean.Internal`,\n" | |
| + "`self.internal.push(x)`.\n", | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "docs/note.md") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Mention benign paths and internal identifiers\n\n" | |
| "Verify Go source paths and dotted Internal names pass.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| rc, rep = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc, 0, rep) | |
| self.assertEqual(rep["findings"], []) | |
| def test_blocks_leaks_cr_unicode_separators_intermediate_and_extra_file( | |
| self, | |
| ) -> None: | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| repo = self._init_repo(tmp) | |
| missing_cache = tmp / "no_gh_cache.json" | |
| _git(repo, "checkout", "-b", "feat/leak") | |
| _git(repo, "config", "user.email", "personal@example.com") | |
| # Poison local git config + .gitattributes to verify isolation: | |
| # color.ui=always, diff.external, and -diff binary attributes must | |
| # NOT hide added lines from the leak scanner. | |
| _git(repo, "config", "color.ui", "always") | |
| _git(repo, "config", "diff.external", "true") | |
| (repo / ".gitattributes").write_text( | |
| "*.md -diff\n", encoding="utf-8" | |
| ) | |
| doc_path = repo / "docs" / "note.md" | |
| orig_note = doc_path.read_text(encoding="utf-8") | |
| doc_path.write_bytes( | |
| orig_note.encode("utf-8") | |
| + b"\nline with bare\rCR and \xe2\x80\xa8unicode-sep\n" | |
| + b"++ b/fake_header " | |
| + b"https://" + b"b/" + b"12345678\n" | |
| + b"++i; // http://" + b"go/" + b"abc/def\n" | |
| + b"http://" + b"cl/" + b"123456789 and " | |
| + b"conversation" + b"://abc\n" | |
| + b"alpha-secret and beta-42 and CUSTOM_TAB_SECRET\n" | |
| ) | |
| _git(repo, "add", ".gitattributes", "docs/note.md") | |
| msg_file = tmp / "msg_with_rs.txt" | |
| msg_file.write_bytes( | |
| b"[docs] Intermediate commit\n\n" | |
| b"Before\x1eAfter " + b"yaqs/" + b"998877\n\n" | |
| b"Agent-authored-by: AI agent acting on alice's behalf\n" | |
| ) | |
| _git(repo, "commit", "-F", str(msg_file)) | |
| # Commit 2 deletes ALL leaked lines from `note.md`; intermediate | |
| # commit 1 MUST still be caught before `git push` publishes it! | |
| doc_path.write_text( | |
| orig_note + "\nClean final line.\n", encoding="utf-8" | |
| ) | |
| _git(repo, "add", "docs/note.md") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Clean up note\n\nRemove temporary lines.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| # Test bare regexes starting with `[` character class (must NOT be | |
| # misparsed as JSON), bare regexes with `:` (`(?:`, alternation), | |
| # AND tab-delimited `label\tregex` entries in a non-.json text file. | |
| extra_file = tmp / "extra_leaks.txt" | |
| extra_file.write_text( | |
| "[Aa]lpha-secret|beta:gamma\n" | |
| "(?:beta|delta)-\\d+\n" | |
| "custom_tab\tCUSTOM_TAB_SECRET\n", | |
| encoding="utf-8", | |
| ) | |
| with mock.patch.dict( | |
| os.environ, {"ANNEAL_PREFLIGHT_EXTRA_LEAK_FILE": str(extra_file)} | |
| ): | |
| rc, rep = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc, 1) | |
| checks = {f["check"] for f in rep["findings"]} | |
| self.assertIn("cla-email", checks) | |
| self.assertIn("public-leak:shortlink", checks) | |
| self.assertIn("public-leak:go_shortlink", checks) | |
| self.assertIn("public-leak:conversation_uri", checks) | |
| self.assertIn("public-leak:file_extra_1", checks) | |
| self.assertIn("public-leak:file_extra_2", checks) | |
| self.assertIn("public-leak:custom_tab", checks) | |
| paths = {f.get("path") for f in rep["findings"] if f.get("path")} | |
| self.assertIn("docs/note.md", paths) | |
| self.assertNotIn("fake_header https://" + "b/" + "12345678", paths) | |
| self.assertTrue( | |
| any( | |
| f.get("check") == "public-leak:shortlink" | |
| and f.get("commit") | |
| and not f.get("path") | |
| for f in rep["findings"] | |
| ), | |
| rep["findings"], | |
| ) | |
| # JSON format for ANNEAL_PREFLIGHT_EXTRA_LEAK_FILE also works, and | |
| # invalid regexes fail closed as a structured `leak-config` finding. | |
| json_extra = tmp / "extra.json" | |
| json_extra.write_text( | |
| json.dumps({"json_colon": r"(?:alpha|omega)-secret"}), | |
| encoding="utf-8", | |
| ) | |
| with mock.patch.dict( | |
| os.environ, | |
| {"ANNEAL_PREFLIGHT_EXTRA_LEAK_FILE": str(json_extra)}, | |
| ): | |
| rc_j, rep_j = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| require_google_cla_email=False, | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc_j, 1) | |
| self.assertIn( | |
| "public-leak:json_colon", | |
| {f["check"] for f in rep_j["findings"]}, | |
| ) | |
| self.assertNotIn( | |
| "cla-email", {f["check"] for f in rep_j["findings"]} | |
| ) | |
| with mock.patch.dict( | |
| os.environ, {"ANNEAL_PREFLIGHT_EXTRA_LEAK_REGEX": "(unclosed"} | |
| ): | |
| rc_bad, rep_bad = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc_bad, 1) | |
| self.assertIn( | |
| "leak-config", {f["check"] for f in rep_bad["findings"]} | |
| ) | |
| def test_multicommit_pr_title_leading_dash_and_stdin_body_scan( | |
| self, | |
| ) -> None: | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| repo = self._init_repo(tmp) | |
| missing_cache = tmp / "no_gh_cache.json" | |
| _git(repo, "checkout", "-b", "feat/multi") | |
| doc_path = repo / "docs" / "note.md" | |
| for idx in (1, 2): | |
| doc_path.write_text( | |
| doc_path.read_text(encoding="utf-8") | |
| + f"\nClean paragraph {idx}.\n", | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "docs/note.md") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| f"[docs] Clean commit {idx}\n\n" | |
| f"Add clean paragraph {idx}.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| leaked_body = ( | |
| "Clean intro.\nSee http://" + "go/" + "internal-design\n" | |
| ) | |
| with mock.patch.object(sys, "stdin", io.StringIO(leaked_body)): | |
| rc, rep = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| pr_title="-dash-prefixed title " + "b/" + "1234567", | |
| pr_body_file="-", | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc, 1, rep) | |
| found = {(f["check"], f.get("path")) for f in rep["findings"]} | |
| self.assertIn(("public-leak:shortlink", "<pr-title>"), found) | |
| self.assertIn(("public-leak:go_shortlink", "<pr-body>"), found) | |
| def test_hygiene_corrupt_json_fails_closed(self) -> None: | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| repo = self._init_repo(tmp) | |
| missing_cache = tmp / "no_gh_cache.json" | |
| _git(repo, "checkout", "-b", "feat/bad-json") | |
| doc_path = repo / "docs" / "note.md" | |
| doc_path.write_text( | |
| doc_path.read_text(encoding="utf-8") + "\nTiny edit.\n", | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "docs/note.md") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Tiny edit\n\nExercise corrupt hygiene JSON.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| fake_hygiene = tmp / "bad_hygiene.py" | |
| fake_hygiene.write_text( | |
| "print('not valid json')\n", encoding="utf-8" | |
| ) | |
| stage = pr_preflight.run_hygiene_stage( | |
| repo, "main", "HEAD", hygiene_script=fake_hygiene | |
| ) | |
| self.assertFalse(stage["ok"]) | |
| self.assertIsNone(stage["human_review_surface"]) | |
| self.assertTrue( | |
| any(f.get("check") == "hygiene-json" for f in stage["findings"]) | |
| ) | |
| # Non-list `findings` and missing `human_review_surface` also fail | |
| # closed in `run_hygiene_stage`. | |
| bad_list_script = tmp / "bad_list_hygiene.py" | |
| bad_list_script.write_text( | |
| 'import json; print(json.dumps({"ok": True, "findings": "x", ' | |
| '"warnings": [], "human_review_surface": []}))\n', | |
| encoding="utf-8", | |
| ) | |
| bad_list_stage = pr_preflight.run_hygiene_stage( | |
| repo, "main", "HEAD", hygiene_script=bad_list_script | |
| ) | |
| self.assertFalse(bad_list_stage["ok"]) | |
| self.assertTrue( | |
| any( | |
| f.get("check") == "hygiene-json" | |
| for f in bad_list_stage["findings"] | |
| ) | |
| ) | |
| no_hrs_script = tmp / "no_hrs_hygiene.py" | |
| no_hrs_script.write_text( | |
| 'import json; print(json.dumps({"ok": True, "findings": [], ' | |
| '"warnings": []}))\n', | |
| encoding="utf-8", | |
| ) | |
| no_hrs_stage = pr_preflight.run_hygiene_stage( | |
| repo, "main", "HEAD", hygiene_script=no_hrs_script | |
| ) | |
| self.assertFalse(no_hrs_stage["ok"]) | |
| self.assertIsNone(no_hrs_stage["human_review_surface"]) | |
| with mock.patch.object( | |
| pr_preflight, "run_hygiene_stage", return_value=stage | |
| ): | |
| rc, rep = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc, 1) | |
| self.assertIsNone(rep["human_review_surface"]) | |
| def test_merge_commit_and_added_text_file_non_text_flag(self) -> None: | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| repo = self._init_repo(tmp) | |
| missing_cache = tmp / "no_gh_cache.json" | |
| # Add both a plain text file and an empty 0-byte text file: | |
| # `has_non_text_diff` MUST remain False for both! | |
| _git(repo, "checkout", "-b", "feat/merge-clean") | |
| new_doc = repo / "docs" / "extra.md" | |
| new_doc.write_text( | |
| "<!-- Copyright 2026 The Fuchsia Authors\n\n" | |
| "Licensed under a BSD-style license <LICENSE-BSD>, Apache " | |
| "License, Version 2.0\n" | |
| "<LICENSE-APACHE or " | |
| "https://www.apache.org/licenses/LICENSE-2.0>, or the MIT\n" | |
| "license <LICENSE-MIT or " | |
| "https://opensource.org/licenses/MIT>, at your option.\n" | |
| "This file may not be copied, modified, or distributed except " | |
| "according to\n" | |
| "those terms. -->\n\n" | |
| "# Extra\n\nClean text addition.\n", | |
| encoding="utf-8", | |
| ) | |
| (repo / "docs" / ".gitkeep").write_bytes(b"") | |
| _git(repo, "add", "docs/extra.md", "docs/.gitkeep") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Add extra note and empty file\n\n" | |
| "Add clean text file and 0-byte marker.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| rc_add, rep_add = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc_add, 0, rep_add) | |
| self.assertFalse(rep_add["has_non_text_diff"]) | |
| # Positive `has_non_text_diff` checks: binary file, symlink, and | |
| # executable mode flip (`100644 -> 100755`) MUST all return True. | |
| _git(repo, "checkout", "-b", "feat/binary-diff", "main") | |
| (repo / "blob.bin").write_bytes(b"\x00\x01\x02binary") | |
| _git(repo, "add", "blob.bin") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[ci] Add binary blob\n\nTest binary detection.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| _, _, _, bin_non_text = pr_preflight.resolve_changed_files_and_loc( | |
| repo, "main", "HEAD" | |
| ) | |
| self.assertTrue(bin_non_text) | |
| _git(repo, "checkout", "-b", "feat/symlink-diff", "main") | |
| os.symlink("docs/note.md", repo / "note_link") | |
| _git(repo, "add", "note_link") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[ci] Add symlink\n\nTest symlink detection.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| _, _, _, sym_non_text = pr_preflight.resolve_changed_files_and_loc( | |
| repo, "main", "HEAD" | |
| ) | |
| self.assertTrue(sym_non_text) | |
| _git(repo, "checkout", "-b", "feat/mode-flip", "main") | |
| os.chmod(repo / "docs" / "note.md", 0o755) | |
| _git(repo, "add", "docs/note.md") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[ci] Flip mode\n\nTest mode-change detection.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| _, _, _, mode_non_text = pr_preflight.resolve_changed_files_and_loc( | |
| repo, "main", "HEAD" | |
| ) | |
| self.assertTrue(mode_non_text) | |
| # Merge commits in the PR range MUST fail closed (`merge-commit`). | |
| _git(repo, "checkout", "main") | |
| (repo / "UPSTREAM_ONLY.txt").write_text( | |
| "Upstream change.\n", | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "UPSTREAM_ONLY.txt") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Upstream commit\n\nUpstream change.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| _git(repo, "checkout", "feat/merge-clean") | |
| _git( | |
| repo, | |
| "merge", | |
| "--no-ff", | |
| "main", | |
| "-m", | |
| "Merge main into feat/merge-clean\n\nSync branch.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| merge_findings = pr_preflight.scan_public_leaks_and_cla( | |
| repo, | |
| _git(repo, "merge-base", "main", "HEAD"), | |
| "HEAD", | |
| ) | |
| self.assertTrue( | |
| any(f["check"] == "merge-commit" for f in merge_findings), | |
| merge_findings, | |
| ) | |
| # Moved hunk in identical context MUST return | |
| # `is_pure_verbatim_rebase=False` because blob OIDs differ. | |
| _git(repo, "checkout", "main") | |
| repeated_body = ( | |
| "fn guarded() {\n" | |
| " let a = 1;\n" | |
| " let b = 2;\n" | |
| " check(x);\n" | |
| " use(a, b);\n" | |
| "}\n\n" | |
| "fn unguarded() {\n" | |
| " let a = 1;\n" | |
| " let b = 2;\n" | |
| " check(x);\n" | |
| " use(a, b);\n" | |
| "}\n" | |
| ) | |
| (repo / "sample.rs").write_text(repeated_body, encoding="utf-8") | |
| _git(repo, "add", "sample.rs") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[ci] Add sample.rs\n\nSeed identical blocks.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| _git(repo, "checkout", "-b", "feat/hunk-prior", "main") | |
| (repo / "sample.rs").write_text( | |
| repeated_body.replace( | |
| "fn guarded() {\n let a = 1;\n let b = 2;\n" | |
| " check(x);\n", | |
| "fn guarded() {\n let a = 1;\n let b = 2;\n" | |
| " check(x);\n return;\n", | |
| 1, | |
| ), | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "sample.rs") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[ci] Add return guard\n\nInsert early return.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| prior_hunk = _git(repo, "rev-parse", "HEAD") | |
| # Advance main on an unrelated file. | |
| _git(repo, "checkout", "main") | |
| (repo / "UNRELATED_HUNK.txt").write_text("ok\n", encoding="utf-8") | |
| _git(repo, "add", "UNRELATED_HUNK.txt") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Unrelated base\n\nAdvance main.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| # Apply the same textual hunk to `unguarded()` instead -> False! | |
| _git(repo, "checkout", "-b", "feat/hunk-moved", "main") | |
| (repo / "sample.rs").write_text( | |
| repeated_body.replace( | |
| "fn unguarded() {\n let a = 1;\n let b = 2;\n" | |
| " check(x);\n", | |
| "fn unguarded() {\n let a = 1;\n let b = 2;\n" | |
| " check(x);\n return;\n", | |
| 1, | |
| ), | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "sample.rs") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[ci] Add return guard\n\nInsert early return.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| self.assertFalse( | |
| pr_preflight._is_pure_tree_rebase( | |
| repo, "main", "HEAD", prior_hunk | |
| ) | |
| ) | |
| # Multi-commit genuine forward rebase onto disjoint base -> True! | |
| _git(repo, "checkout", "-b", "feat/multi-rebase", "main") | |
| note_p = repo / "docs" / "note.md" | |
| note_p.write_text( | |
| note_p.read_text(encoding="utf-8") + "\nCommit one.\n", | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "docs/note.md") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Multi step 1\n\nFirst commit.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| note_p.write_text( | |
| note_p.read_text(encoding="utf-8") + "Commit two.\n", | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "docs/note.md") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Multi step 2\n\nSecond commit.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| prior_multi = _git(repo, "rev-parse", "HEAD") | |
| # Empty `--pr-title` on a multi-commit range MUST fail closed too! | |
| rc_mc_empty, rep_mc_empty = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| pr_title="", | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc_mc_empty, 1, rep_mc_empty) | |
| self.assertTrue( | |
| any( | |
| f.get("check") == "pr-title" | |
| for f in rep_mc_empty["findings"] | |
| ), | |
| rep_mc_empty["findings"], | |
| ) | |
| rc_mc_ws, rep_mc_ws = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| pr_title=" ", | |
| gh_cache_path=missing_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc_mc_ws, 1, rep_mc_ws) | |
| # Advance main on an unrelated file and rebase the 2-commit branch. | |
| _git(repo, "checkout", "main") | |
| (repo / "UNRELATED_MULTI.txt").write_text("ok\n", encoding="utf-8") | |
| _git(repo, "add", "UNRELATED_MULTI.txt") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Unrelated multi base\n\nAdvance main.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| _git(repo, "checkout", "feat/multi-rebase") | |
| _git(repo, "rebase", "main") | |
| self.assertTrue( | |
| pr_preflight._is_pure_tree_rebase( | |
| repo, "main", "HEAD", prior_multi | |
| ) | |
| ) | |
| # Reversing head and prior_head tests backward rebase -> False. | |
| self.assertFalse( | |
| pr_preflight._is_pure_tree_rebase( | |
| repo, "main", prior_multi, "HEAD" | |
| ) | |
| ) | |
| # Base edit on a PR-touched file MUST return False. | |
| prior_touch = _git(repo, "rev-parse", "HEAD") | |
| _git(repo, "checkout", "main") | |
| note_p.write_text( | |
| note_p.read_text(encoding="utf-8").replace( | |
| "# Note", "# Note (updated on main)", 1 | |
| ), | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "docs/note.md") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Update heading on main\n\nEdit same file.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| _git(repo, "checkout", "feat/multi-rebase") | |
| _git(repo, "rebase", "main") | |
| self.assertFalse( | |
| pr_preflight._is_pure_tree_rebase( | |
| repo, "main", "HEAD", prior_touch | |
| ) | |
| ) | |
| def test_preflight_passes_on_its_own_source_file_diff(self) -> None: | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| repo = self._init_repo(tmp) | |
| _git(repo, "checkout", "-b", "feat/self-scan") | |
| dst = repo / "ci" / "pr_preflight.py" | |
| dst.parent.mkdir(parents=True, exist_ok=True) | |
| dst.write_text( | |
| Path(pr_preflight.__file__).read_text(encoding="utf-8"), | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "ci/pr_preflight.py") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[ci] Add pre-push pull request preflight runner\n\n" | |
| "Verify pr_preflight.py passes its own leak and hygiene scan.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| with mock.patch.object( | |
| pr_preflight.shutil, "which", return_value=None | |
| ): | |
| rc, rep = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="HEAD", | |
| gh_cache_path=tmp / "missing_cache.json", | |
| ) | |
| self.assertEqual(rc, 0, rep) | |
| self.assertEqual(rep["findings"], []) | |
| self.assertTrue( | |
| any(w.get("check") == "overlap-radar" for w in rep["warnings"]), | |
| rep["warnings"], | |
| ) | |
| def test_fail_closed_git_errors_env_cache_isolation_and_cli_main( | |
| self, | |
| ) -> None: | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| repo = self._init_repo(tmp) | |
| # Fail closed when git rev-list/diff fail on invalid ref. | |
| bad_findings = pr_preflight.scan_public_leaks_and_cla( | |
| repo, "HEAD", "nonexistent-ref-xyz" | |
| ) | |
| bad_checks = {f["check"] for f in bad_findings} | |
| self.assertIn("git-log", bad_checks) | |
| self.assertIn("git-diff", bad_checks) | |
| # Fresh ANNEAL_PREFLIGHT_GH_CACHE is used for DEFAULT_REPO_SLUG, | |
| # but MUST be ignored for a different repo_slug! | |
| fresh_cache = tmp / "fresh_gh_cache.json" | |
| cached_pr = { | |
| "number": 9001, | |
| "author": {"login": "carol"}, | |
| "headRefName": "cached-branch", | |
| "isDraft": False, | |
| "files": {"nodes": [{"path": "docs/note.md"}]}, | |
| } | |
| fresh_cache.write_text( | |
| json.dumps({ | |
| "fetched_at_epoch": time.time(), | |
| "prs": [cached_pr], | |
| }), | |
| encoding="utf-8", | |
| ) | |
| with mock.patch.dict( | |
| os.environ, {"ANNEAL_PREFLIGHT_GH_CACHE": str(fresh_cache)} | |
| ): | |
| default_rows = pr_preflight.load_open_prs_for_overlap( | |
| repo_slug=pr_preflight.DEFAULT_REPO_SLUG, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(len(default_rows), 1) | |
| self.assertEqual(default_rows[0]["number"], 9001) | |
| called: list[str] = [] | |
| other_rows = pr_preflight.load_open_prs_for_overlap( | |
| repo_slug="other-org/other-repo", | |
| gh_fetch_fn=lambda slug: (called.append(slug) or []), | |
| ) | |
| self.assertEqual(other_rows, []) | |
| self.assertEqual(called, ["other-org/other-repo"]) | |
| # Exercise `main()` CLI JSON output wiring from a subdirectory. | |
| _git(repo, "checkout", "-b", "feat/cli") | |
| doc_path = repo / "docs" / "note.md" | |
| doc_path.write_text( | |
| doc_path.read_text(encoding="utf-8") + "\nCLI test line.\n", | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "docs/note.md") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Exercise CLI main\n\nTest CLI JSON output.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| buf = io.StringIO() | |
| with mock.patch.object( | |
| pr_preflight.shutil, "which", return_value=None | |
| ), mock.patch.object(sys, "stdout", buf): | |
| rc_cli = pr_preflight.main([ | |
| "--repo", | |
| str(repo / "docs"), | |
| "--base", | |
| "main", | |
| "--head", | |
| "HEAD", | |
| "--gh-cache-path", | |
| str(fresh_cache), | |
| "--json", | |
| ]) | |
| self.assertEqual(rc_cli, 0, buf.getvalue()) | |
| parsed = json.loads(buf.getvalue()) | |
| self.assertTrue(parsed["ok"]) | |
| self.assertEqual(len(parsed["overlaps"]), 1) | |
| self.assertEqual(parsed["overlaps"][0]["pr"], 9001) | |
| # Corrupt non-UTF-8 cache file falls back cleanly instead of | |
| # raising `UnicodeDecodeError`. | |
| bad_utf8_cache = tmp / "bad_utf8_cache.json" | |
| bad_utf8_cache.write_bytes(b"\xff\xfe\x00invalid") | |
| fb_rows = pr_preflight.load_open_prs_for_overlap( | |
| gh_cache_path=bad_utf8_cache, | |
| gh_fetch_fn=lambda _slug: [{"number": 77}], | |
| ) | |
| self.assertEqual(fb_rows, [{"number": 77}]) | |
| # Passing a branch name to `--head` still excludes the author's own | |
| # open PR from overlaps. | |
| self_cache = tmp / "self_branch_cache.json" | |
| self_cache.write_text( | |
| json.dumps({ | |
| "fetched_at_epoch": time.time(), | |
| "prs": [{ | |
| "number": 9002, | |
| "author": {"login": "alice"}, | |
| "headRefName": "feat/cli", | |
| "isDraft": False, | |
| "files": {"nodes": [{"path": "docs/note.md"}]}, | |
| }], | |
| }), | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "checkout", "main") | |
| rc_br, rep_br = pr_preflight.run_preflight( | |
| repo_dir=repo, | |
| base_ref="main", | |
| head_ref="feat/cli", | |
| gh_cache_path=self_cache, | |
| gh_fetch_fn=lambda _slug: [], | |
| ) | |
| self.assertEqual(rc_br, 0, rep_br) | |
| self.assertEqual(rep_br["overlaps"], []) | |
| _git(repo, "checkout", "feat/cli") | |
| # Empty --pr-title or --pr-body-file MUST fail closed, never skip. | |
| buf_empty = io.StringIO() | |
| with mock.patch.object( | |
| pr_preflight.shutil, "which", return_value=None | |
| ), mock.patch.object(sys, "stdout", buf_empty): | |
| rc_empty_title = pr_preflight.main([ | |
| "--repo", | |
| str(repo), | |
| "--base", | |
| "main", | |
| "--head", | |
| "HEAD", | |
| "--pr-title", | |
| "", | |
| "--gh-cache-path", | |
| str(fresh_cache), | |
| "--json", | |
| ]) | |
| self.assertEqual(rc_empty_title, 1, buf_empty.getvalue()) | |
| with self.assertRaises(ValueError): | |
| pr_preflight.main([ | |
| "--repo", | |
| str(repo), | |
| "--base", | |
| "main", | |
| "--head", | |
| "HEAD", | |
| "--pr-body-file", | |
| "", | |
| ]) | |
| def test_malformed_hunk_fails_closed_and_pins_repo_diff_config( | |
| self, | |
| ) -> None: | |
| # `_iter_added_diff_lines` MUST fail closed on unexpected in-hunk | |
| # lines, malformed hunk headers, and truncated hunks. | |
| bad_in_hunk = ( | |
| "diff --git a/f.txt b/f.txt\n" | |
| "+++ b/f.txt\n" | |
| "@@ -2,4 +2,4 @@\n" | |
| "-l2\n" | |
| "+CHANGED2\n" | |
| "\n" | |
| " l4\n" | |
| "-l5\n" | |
| "+LEAK\n" | |
| ) | |
| with self.assertRaises(ValueError): | |
| pr_preflight._iter_added_diff_lines(bad_in_hunk) | |
| with self.assertRaises(ValueError): | |
| pr_preflight._iter_added_diff_lines( | |
| "diff --git a/f.txt b/f.txt\n+++ b/f.txt\n@@ bogus @@\n" | |
| ) | |
| with self.assertRaises(ValueError): | |
| pr_preflight._iter_added_diff_lines( | |
| "diff --git a/f.txt b/f.txt\n+++ b/f.txt\n" | |
| "@@ -1,1 +1,2 @@\n-old\n+new1\n" | |
| ) | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| repo = self._init_repo(tmp) | |
| # Hostile repo-local git config (`diff.interHunkContext=3`, | |
| # `diff.suppressBlankEmpty=true`, `i18n.logOutputEncoding=UTF-16`) | |
| # MUST NOT hide leaks in intermediate commits or commit messages. | |
| _git(repo, "checkout", "main") | |
| target = repo / "fused.txt" | |
| target.write_text("l1\nl2\n\nl4\nl5\n", encoding="utf-8") | |
| _git(repo, "add", "fused.txt") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Seed fused.txt\n\nAdd baseline lines.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| _git(repo, "checkout", "-b", "feat/hostile-config") | |
| target.write_text( | |
| "l1\nCHANGED2\n\nl4\nLEAKLINE see " + "b/" + "12345678\n", | |
| encoding="utf-8", | |
| ) | |
| _git(repo, "add", "fused.txt") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Intermediate change\n\nRefs " | |
| + "cl/" | |
| + "98765432\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| # Revert the file in commit 2 so the leak exists only in commit 1. | |
| target.write_text("l1\nl2\n\nl4\nl5\n", encoding="utf-8") | |
| _git(repo, "add", "fused.txt") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Revert fused.txt\n\nRestore baseline.\n\n" | |
| "Agent-authored-by: AI agent acting on alice's behalf", | |
| ) | |
| _git(repo, "config", "diff.interHunkContext", "3") | |
| _git(repo, "config", "diff.suppressBlankEmpty", "true") | |
| _git(repo, "config", "i18n.logOutputEncoding", "UTF-16") | |
| findings = pr_preflight.scan_public_leaks_and_cla( | |
| repo, _git(repo, "merge-base", "main", "HEAD"), "HEAD" | |
| ) | |
| msgs = [f["message"] for f in findings] | |
| self.assertTrue( | |
| any( | |
| f["check"] == "public-leak:shortlink" | |
| and f.get("path") == "fused.txt" | |
| for f in findings | |
| ), | |
| findings, | |
| ) | |
| self.assertTrue( | |
| any( | |
| f["check"] == "public-leak:shortlink" | |
| and "message matches" in m | |
| for f, m in zip(findings, msgs) | |
| ), | |
| findings, | |
| ) | |
| # A malformed diff returned by git MUST yield a `git-diff` finding. | |
| with mock.patch.object( | |
| pr_preflight, | |
| "_iter_added_diff_lines", | |
| side_effect=ValueError("synthetic malformed hunk"), | |
| ): | |
| bad_diff_findings = pr_preflight.scan_public_leaks_and_cla( | |
| repo, _git(repo, "merge-base", "main", "HEAD"), "HEAD" | |
| ) | |
| self.assertTrue( | |
| any(f["check"] == "git-diff" for f in bad_diff_findings), | |
| bad_diff_findings, | |
| ) | |
| def test_hostile_submodule_and_diff_config_isolation(self) -> None: | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| sub = tmp / "submod_origin" | |
| sub.mkdir() | |
| _git(sub, "init", "-q", "-b", "main") | |
| _git(sub, "config", "user.name", "Sub") | |
| _git(sub, "config", "user.email", "sub@google.com") | |
| (sub / "lib.txt").write_text("v1\n", encoding="utf-8") | |
| _git(sub, "add", "lib.txt") | |
| _git( | |
| sub, | |
| "commit", | |
| "-m", | |
| "[test] sub v1\n\nAgent-authored-by: test", | |
| ) | |
| sub_v1 = _git(sub, "rev-parse", "HEAD") | |
| (sub / "lib.txt").write_text("v2\n", encoding="utf-8") | |
| _git(sub, "add", "lib.txt") | |
| _git( | |
| sub, | |
| "commit", | |
| "-m", | |
| "[test] sub v2\n\nAgent-authored-by: test", | |
| ) | |
| sub_v2 = _git(sub, "rev-parse", "HEAD") | |
| repo = self._init_repo(tmp) | |
| _git(repo, "checkout", "main") | |
| _git( | |
| repo, | |
| "-c", | |
| "protocol.file.allow=always", | |
| "submodule", | |
| "add", | |
| str(sub), | |
| "mysub", | |
| ) | |
| _git(repo / "mysub", "checkout", "-q", sub_v1) | |
| (repo / ".mailmap").write_text( | |
| "<good@google.com> <ext@example.com>\n", encoding="utf-8" | |
| ) | |
| _git(repo, "add", "mysub", ".gitmodules", ".mailmap") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[test] seed submodule\n\nAgent-authored-by: test", | |
| ) | |
| _git(repo, "checkout", "-b", "feat/submodule-hostile") | |
| _git(repo / "mysub", "checkout", "-q", sub_v2) | |
| _git(repo, "add", "mysub") | |
| (repo / ".gitmodules").write_text( | |
| '[submodule "mysub"]\n\tpath = mysub\n\turl = ' | |
| + str(sub) | |
| + "\n\tignore = all\n", | |
| encoding="utf-8", | |
| ) | |
| (repo / "note.txt").write_text( | |
| "ref " + "b/" + "12345678\n", encoding="utf-8" | |
| ) | |
| _git(repo, "add", ".gitmodules", "note.txt") | |
| _git( | |
| repo, | |
| "-c", | |
| "user.email=ext@example.com", | |
| "commit", | |
| "-m", | |
| "[test] bump sub and add note\n\nAgent-authored-by: test", | |
| ) | |
| # Poison repo-local git config with submodule-hiding and | |
| # diff-breaking knobs. | |
| _git(repo, "config", "diff.ignoreSubmodules", "all") | |
| _git(repo, "config", "submodule.mysub.ignore", "all") | |
| _git(repo, "config", "diff.submodule", "diff") | |
| _git(repo, "config", "submodule.recurse", "true") | |
| _git(repo, "config", "diff.orderFile", "/nonexistent/orderfile") | |
| _git(repo, "config", "diff.external", "/bin/false") | |
| _git(repo, "config", "diff.colorMoved", "zebra") | |
| _git(repo, "config", "diff.wsErrorHighlight", "all") | |
| _git(repo, "config", "log.mailmap", "true") | |
| _mb, paths, _loc, non_text = ( | |
| pr_preflight.resolve_changed_files_and_loc(repo, "main", "HEAD") | |
| ) | |
| self.assertIn("mysub", paths, paths) | |
| self.assertIn("note.txt", paths, paths) | |
| self.assertTrue(non_text) | |
| findings = pr_preflight.scan_public_leaks_and_cla( | |
| repo, _git(repo, "merge-base", "main", "HEAD"), "HEAD" | |
| ) | |
| self.assertFalse( | |
| any(f["check"] == "git-diff" for f in findings), findings | |
| ) | |
| self.assertTrue( | |
| any( | |
| f["check"] == "public-leak:shortlink" | |
| and f.get("path") == "note.txt" | |
| for f in findings | |
| ), | |
| findings, | |
| ) | |
| self.assertTrue( | |
| any(f["check"] == "cla-email" for f in findings), findings | |
| ) | |
| # Rebase gitlink swap regression: `.gitmodules` `ignore = all` | |
| # MUST NOT cause `git diff-tree` inside `_is_pure_tree_rebase` to | |
| # ignore swapped submodule OIDs. | |
| rb_repo = tmp / "rb_repo" | |
| rb_repo.mkdir() | |
| _git(rb_repo, "init", "-q", "-b", "main") | |
| _git(rb_repo, "config", "user.name", "Rb") | |
| _git(rb_repo, "config", "user.email", "rb@google.com") | |
| (rb_repo / "base.txt").write_text("base\n", encoding="utf-8") | |
| _git(rb_repo, "add", "base.txt") | |
| _git(rb_repo, "commit", "-m", "[test] base\n\nAgent-authored-by: test") | |
| gm_text = ( | |
| '[submodule "mysub"]\n\tpath = mysub\n\turl = ' | |
| + str(sub) | |
| + "\n\tignore = all\n" | |
| ) | |
| _git(rb_repo, "checkout", "-b", "feat/prior") | |
| (rb_repo / ".gitmodules").write_text(gm_text, encoding="utf-8") | |
| _git( | |
| rb_repo, | |
| "update-index", | |
| "--add", | |
| "--cacheinfo", | |
| f"160000,{sub_v1},mysub", | |
| ) | |
| _git(rb_repo, "add", ".gitmodules") | |
| _git(rb_repo, "commit", "-m", "[test] add sub\n\nAgent-authored-by: test") | |
| prior_sha = _git(rb_repo, "rev-parse", "HEAD") | |
| _git(rb_repo, "checkout", "main") | |
| (rb_repo / "other.txt").write_text("other\n", encoding="utf-8") | |
| _git(rb_repo, "add", "other.txt") | |
| _git( | |
| rb_repo, | |
| "commit", | |
| "-m", | |
| "[test] advance main\n\nAgent-authored-by: test", | |
| ) | |
| _git(rb_repo, "checkout", "-b", "feat/rebased-same") | |
| (rb_repo / ".gitmodules").write_text(gm_text, encoding="utf-8") | |
| _git( | |
| rb_repo, | |
| "update-index", | |
| "--add", | |
| "--cacheinfo", | |
| f"160000,{sub_v1},mysub", | |
| ) | |
| _git(rb_repo, "add", ".gitmodules") | |
| _git(rb_repo, "commit", "-m", "[test] add sub\n\nAgent-authored-by: test") | |
| self.assertTrue( | |
| pr_preflight._is_pure_tree_rebase( | |
| rb_repo, "main", "HEAD", prior_sha | |
| ) | |
| ) | |
| _git(rb_repo, "checkout", "main") | |
| _git(rb_repo, "checkout", "-b", "feat/rebased-swap") | |
| (rb_repo / ".gitmodules").write_text(gm_text, encoding="utf-8") | |
| _git( | |
| rb_repo, | |
| "update-index", | |
| "--add", | |
| "--cacheinfo", | |
| f"160000,{sub_v2},mysub", | |
| ) | |
| _git(rb_repo, "add", ".gitmodules") | |
| _git(rb_repo, "commit", "-m", "[test] add sub\n\nAgent-authored-by: test") | |
| self.assertFalse( | |
| pr_preflight._is_pure_tree_rebase( | |
| rb_repo, "main", "HEAD", prior_sha | |
| ) | |
| ) | |
| def test_replace_refs_cannot_spoof_scans_or_rebase_check(self) -> None: | |
| with tempfile.TemporaryDirectory() as td: | |
| tmp = Path(td) | |
| repo = self._init_repo(tmp) | |
| # Seed an unrelated clean commit so a `git replace` ref can point | |
| # the leaky commit to a clean commit with zero leaks. | |
| _git(repo, "checkout", "main") | |
| _git(repo, "checkout", "-b", "clean-decoy") | |
| (repo / "clean.txt").write_text("harmless\n", encoding="utf-8") | |
| _git(repo, "add", "clean.txt") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Clean decoy\n\nAgent-authored-by: test", | |
| ) | |
| clean_decoy_sha = _git(repo, "rev-parse", "HEAD") | |
| _git(repo, "checkout", "main") | |
| _git(repo, "checkout", "-b", "feat/leaky-replaced") | |
| (repo / "leak.txt").write_text( | |
| "see " + "b/" + "12345678\n", encoding="utf-8" | |
| ) | |
| _git(repo, "add", "leak.txt") | |
| _git( | |
| repo, | |
| "commit", | |
| "-m", | |
| "[docs] Add note\n\nRefs " + "cl/" + "12345678\n\n" | |
| "Agent-authored-by: test", | |
| ) | |
| leaky_sha = _git(repo, "rev-parse", "HEAD") | |
| # Verify `git replace` actually hides the leak under plain `git` | |
| # (proving the fixture exercises replace-ref resolution). | |
| _git(repo, "replace", leaky_sha, clean_decoy_sha) | |
| plain_diff = _git(repo, "diff", f"main..{leaky_sha}") | |
| self.assertNotIn("leak.txt", plain_diff) | |
| _mb, paths, _loc, _nt = pr_preflight.resolve_changed_files_and_loc( | |
| repo, "main", "feat/leaky-replaced" | |
| ) | |
| self.assertEqual(paths, ["leak.txt"]) | |
| findings = pr_preflight.scan_public_leaks_and_cla( | |
| repo, | |
| _git(repo, "merge-base", "main", "feat/leaky-replaced"), | |
| "feat/leaky-replaced", | |
| ) | |
| self.assertTrue( | |
| any( | |
| f["check"] == "public-leak:shortlink" | |
| and f.get("path") == "leak.txt" | |
| for f in findings | |
| ), | |
| findings, | |
| ) | |
| self.assertTrue( | |
| any( | |
| f["check"] == "public-leak:shortlink" | |
| and "message matches" in f.get("message", "") | |
| for f in findings | |
| ), | |
| findings, | |
| ) | |
| # A `git replace` ref on a rebased branch MUST NOT trick | |
| # `_is_pure_tree_rebase` into accepting a tampered commit or | |
| # rejecting a genuine verbatim rebase. | |
| rb = tmp / "rb_replace" | |
| rb.mkdir() | |
| _git(rb, "init", "-q", "-b", "main") | |
| _git(rb, "config", "user.name", "Rb") | |
| _git(rb, "config", "user.email", "rb@google.com") | |
| (rb / "doc.txt").write_text("v1\n", encoding="utf-8") | |
| _git(rb, "add", "doc.txt") | |
| _git(rb, "commit", "-m", "[docs] v1\n\nAgent-authored-by: test") | |
| _git(rb, "checkout", "-b", "feat/prior") | |
| (rb / "doc.txt").write_text("v2\n", encoding="utf-8") | |
| _git(rb, "add", "doc.txt") | |
| _git(rb, "commit", "-m", "[docs] v2\n\nAgent-authored-by: test") | |
| prior_sha = _git(rb, "rev-parse", "HEAD") | |
| _git(rb, "checkout", "main") | |
| (rb / "base_only.txt").write_text("advance\n", encoding="utf-8") | |
| _git(rb, "add", "base_only.txt") | |
| _git( | |
| rb, | |
| "commit", | |
| "-m", | |
| "[docs] advance main\n\nAgent-authored-by: test", | |
| ) | |
| _git(rb, "checkout", "-b", "feat/rebased-clean") | |
| (rb / "doc.txt").write_text("v2\n", encoding="utf-8") | |
| _git(rb, "add", "doc.txt") | |
| _git(rb, "commit", "-m", "[docs] v2\n\nAgent-authored-by: test") | |
| clean_rb_sha = _git(rb, "rev-parse", "HEAD") | |
| _git(rb, "checkout", "main") | |
| _git(rb, "checkout", "-b", "feat/rebased-tampered") | |
| (rb / "doc.txt").write_text("tampered\n", encoding="utf-8") | |
| _git(rb, "add", "doc.txt") | |
| _git(rb, "commit", "-m", "[docs] v2\n\nAgent-authored-by: test") | |
| tampered_rb_sha = _git(rb, "rev-parse", "HEAD") | |
| _git(rb, "replace", tampered_rb_sha, clean_rb_sha) | |
| self.assertFalse( | |
| pr_preflight._is_pure_tree_rebase( | |
| rb, "main", "feat/rebased-tampered", prior_sha | |
| ) | |
| ) | |
| _git(rb, "replace", "-d", tampered_rb_sha) | |
| _git(rb, "replace", clean_rb_sha, tampered_rb_sha) | |
| self.assertTrue( | |
| pr_preflight._is_pure_tree_rebase( | |
| rb, "main", "feat/rebased-clean", prior_sha | |
| ) | |
| ) | |
| if __name__ == "__main__": | |
| unittest.main() |