Files
Kamino/tests/scripts/test_check_tarball.py
T
Defame1297 35e780cf79
Build / build (pull_request) Successful in 18s
Lint / lint (pull_request) Successful in 1m21s
Molecule / molecule (pull_request) Successful in 1s
ci(check_tarball): refuse AGENTS.md at any depth
An AGENTS.md under roles/ holds contributor rules; shipped in the
Collection, a consumer's agent reading an installed role would load
them. galaxy.yml build_ignore lists the current ones, and the archive
check now refuses any AGENTS.md, compared case-insensitively, as the
allow list behind that deny list. A root AGENTS.md was already refused
by ALLOWED_TOP.

Refs: #244

Assisted-by: Claude Code
2026-11-23 19:16:17 +00:00

444 lines
16 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 io
import pathlib
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import unittest
import yaml
REPO = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(REPO / "scripts"))
import check_tarball
class TarballTest(unittest.TestCase):
def test_clean(self):
self.assertEqual(
check_tarball.problems(
[
"README.md",
"roles/",
"roles/a/tasks/main.yml",
"LICENSES/MIT.txt",
"tests/sanity/x.txt",
]
),
[],
)
def test_stray_top_level(self):
for name in (
".venv/lib/a.py",
"CLAUDE.md",
".claude/settings.json",
"importer_result.json",
"extensions/m.yml",
):
self.assertEqual(len(check_tarball.problems([name])), 1, name)
def test_forbidden_inside_allowed(self):
self.assertEqual(
len(check_tarball.problems(["roles/a/molecule/default/molecule.yml"])), 1
)
self.assertEqual(len(check_tarball.problems(["roles/a/files/k.pem"])), 1)
self.assertEqual(len(check_tarball.problems(["tests/scripts/t.py"])), 1)
def test_widened_forbidden_names(self):
for name in (
"roles/a/files/my_vault.yml",
"roles/a/Vault-Pass.txt",
"roles/a/vaultfile",
"roles/a/id_rsa",
"roles/a/files/id_rsa.pub",
"roles/a/id_ed25519",
"roles/a/.envrc",
"roles/a/.env",
"roles/a/.env.local",
"roles/a/prod.env.bak",
"roles/a/.ssh/config",
"roles/a/files/.ssh",
):
found = check_tarball.problems([name])
self.assertEqual(len(found), 1, name)
self.assertIn("forbidden pattern", found[0], name)
def test_agents_md_is_refused_at_any_depth(self):
for name in (
"roles/AGENTS.md",
"roles/x/AGENTS.md",
"roles/x/templates/Agents.md",
):
found = check_tarball.problems([name])
self.assertEqual(len(found), 1, name)
self.assertIn("forbidden pattern", found[0], name)
self.assertEqual(
check_tarball.problems(
["roles/x/README.md", "roles/x/files/agents_notes.md"]
),
[],
)
def test_ambiguous_names_are_rejected(self):
cases = {
"roles/a/x ": "ends in a space or a dot",
"roles/a/x.": "ends in a space or a dot",
"roles/a/dir /x": "ends in a space or a dot",
"roles/a/CON": "reserved Windows device name",
"roles/a/nul.txt": "reserved Windows device name",
"roles/a/Com1.yml": "reserved Windows device name",
"roles/a/LPT9": "reserved Windows device name",
"roles/a/aux.tar.gz": "reserved Windows device name",
"roles/a/f::$DATA": "NTFS stream",
"roles/a/GIT~1/config": "8.3 alias",
"roles/a/git~12": "8.3 alias",
"roles/a/\uff0egit/config": "'.git' path component",
"roles/a/x\u00a0y": "control or invisible",
"roles/a/x\u3000y": "control or invisible",
"roles/a/x\ud800y": "control or invisible",
"roles/a/x\ue000y": "control or invisible",
"roles/a/x\u0378y": "control or invisible",
"roles/a/" + "n" * 256: "longer than 255 bytes",
"roles/a/" + "\u00e9" * 128: "longer than 255 bytes",
}
for name, text in cases.items():
found = check_tarball.problems([name])
self.assertEqual(len(found), 1, name)
self.assertIn(text, found[0], name)
def test_ordinary_names_still_pass(self):
ok = [
"roles/a/my file.yml",
"roles/a/console.yml",
"roles/a/n" * 1 + "x",
"roles/a/" + "n" * 255,
"roles/a/tasks/auxiliary.yml",
"roles/a/.hidden",
"roles/a/caf\u00e9.yml",
"roles/a/git.yml",
]
for name in ok:
self.assertEqual(check_tarball.problems([name]), [], name)
def test_normalize_strips_one_slash_each_side_only(self):
self.assertEqual(check_tarball.normalize("./a/b"), "a/b")
self.assertEqual(check_tarball.normalize("a/b/"), "a/b")
self.assertEqual(check_tarball.normalize("a//"), "a/")
self.assertEqual(
check_tarball.problems(["a//b"])[0].count("empty path component"), 1
)
self.assertEqual(len(check_tarball.problems(["roles//a"])), 1)
self.assertEqual(len(check_tarball.problems(["roles/a//"])), 1)
self.assertEqual(check_tarball.problems(["./roles/a/x.yml", "roles/b/"]), [])
SCRIPT = pathlib.Path(__file__).resolve().parents[2] / "scripts" / "check_tarball.py"
class CraftedTarballTest(unittest.TestCase):
"""Build tarballs by hand and run the script on them, as the Build workflow does."""
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.path = pathlib.Path(self.tmp.name) / "c.tar.gz"
def build(self, *entries):
"""entries: (name, type, linkname); type is a tarfile type constant."""
with tarfile.open(self.path, "w:gz") as tar:
for name, typ, link in entries:
info = tarfile.TarInfo(name)
info.type = typ
info.linkname = link
data = b"x\n" if typ == tarfile.REGTYPE else None
info.size = len(data) if data else 0
tar.addfile(info, io.BytesIO(data) if data else None)
def check(self):
proc = subprocess.run(
[sys.executable, "-I", str(SCRIPT), str(self.path)],
capture_output=True,
text=True,
check=False,
)
return proc.returncode, proc.stderr
def required(self, skip=()):
return [
(name, tarfile.REGTYPE, "")
for name in sorted(check_tarball.REQUIRED)
if name not in skip
]
def test_legitimate_tarball_passes(self):
self.build(
*self.required(),
("roles", tarfile.DIRTYPE, ""),
("roles/a/tasks/main.yml", tarfile.REGTYPE, ""),
("LICENSES/MIT.txt", tarfile.REGTYPE, ""),
("meta", tarfile.DIRTYPE, ""),
)
code, err = self.check()
self.assertEqual(code, 0, err)
def test_required_file_present_only_as_dot_slash_name(self):
self.build(
*self.required(skip=("COPYING",)), ("./COPYING", tarfile.REGTYPE, "")
)
code, err = self.check()
self.assertEqual(code, 0, err)
def test_double_slash_and_dot_slash_paths(self):
self.assert_rejected(("a//b", tarfile.REGTYPE, ""), "empty path component")
self.assert_rejected(
("roles//a/x", tarfile.REGTYPE, ""), "empty path component"
)
self.build(
*self.required(),
("./roles/a/x.yml", tarfile.REGTYPE, ""),
("./roles/", tarfile.DIRTYPE, ""),
)
code, err = self.check()
self.assertEqual(code, 0, err)
def test_case_insensitive_duplicates_are_rejected(self):
self.assert_rejected(
("readme.md", tarfile.REGTYPE, ""), "appears more than once"
)
self.build(
*self.required(),
("roles/a/X.yml", tarfile.REGTYPE, ""),
("roles/a/x.YML", tarfile.REGTYPE, ""),
)
code, err = self.check()
self.assertEqual(code, 1, err)
self.assertIn("ignoring case", err)
self.build(
*self.required(),
("roles/a/X.yml", tarfile.REGTYPE, ""),
("roles/a/y.yml", tarfile.REGTYPE, ""),
)
self.assertEqual(self.check()[0], 0)
def test_file_and_directory_with_the_same_path_are_rejected(self):
self.assert_rejected(
("COPYING/x", tarfile.REGTYPE, ""),
"COPYING: is both a file and a directory",
)
self.assert_rejected(
("copying/x", tarfile.REGTYPE, ""), "is both a file and a directory"
)
self.build(
*self.required(),
("roles/a", tarfile.REGTYPE, ""),
("roles/a/x", tarfile.REGTYPE, ""),
)
code, err = self.check()
self.assertEqual(code, 1, err)
self.assertIn("roles/a: is both a file and a directory", err)
def test_widened_and_ambiguous_names_through_the_script(self):
self.assert_rejected(
("roles/a/secrets.vault.yml", tarfile.REGTYPE, ""), "forbidden pattern"
)
self.assert_rejected(
("roles/a/CON.txt", tarfile.REGTYPE, ""), "reserved Windows device name"
)
self.assert_rejected(
("roles/a/x.", tarfile.REGTYPE, ""), "ends in a space or a dot"
)
def test_real_build_passes(self):
"""Build the Collection with ansible-galaxy from a copy of this checkout and check it."""
galaxy = shutil.which("ansible-galaxy")
if not galaxy:
self.skipTest(
"ansible-galaxy is not on PATH; the Build workflow covers the real archive"
)
src = pathlib.Path(self.tmp.name) / "src"
shutil.copytree(
REPO,
src,
ignore=shutil.ignore_patterns(
".git", ".venv", "__pycache__", "output", "*.tar.gz"
),
)
out = pathlib.Path(self.tmp.name) / "dist"
build = subprocess.run(
[
galaxy,
"collection",
"build",
"--force",
"--output-path",
str(out),
str(src),
],
capture_output=True,
text=True,
check=False,
)
self.assertEqual(build.returncode, 0, build.stderr)
tarballs = list(out.glob("mortis-kamino-*.tar.gz"))
self.assertEqual(len(tarballs), 1, tarballs)
with tarfile.open(tarballs[0]) as tar:
names = {
check_tarball.normalize(m.name) for m in tar.getmembers() if m.isreg()
}
self.assertTrue(check_tarball.REQUIRED <= names, check_tarball.REQUIRED - names)
proc = subprocess.run(
[sys.executable, "-I", str(SCRIPT), str(tarballs[0])],
capture_output=True,
text=True,
check=False,
)
self.assertEqual(proc.returncode, 0, proc.stderr)
def assert_rejected(self, entry, text):
self.build(*self.required(), entry)
code, err = self.check()
self.assertEqual(code, 1, err)
self.assertIn(text, err)
def test_symlink_is_rejected(self):
self.assert_rejected(
("roles/a/link", tarfile.SYMTYPE, "/etc/passwd"), "symlink"
)
def test_hardlink_is_rejected(self):
self.assert_rejected(("roles/a/hard", tarfile.LNKTYPE, "README.md"), "hardlink")
def test_device_and_fifo_are_rejected(self):
self.assert_rejected(("roles/a/dev", tarfile.CHRTYPE, ""), "device")
self.assert_rejected(("roles/a/fifo", tarfile.FIFOTYPE, ""), "fifo")
def test_parent_component_is_rejected(self):
self.assert_rejected(("roles/../.venv/x", tarfile.REGTYPE, ""), "'..'")
def test_absolute_path_is_rejected(self):
self.assert_rejected(("/etc/cron.d/x", tarfile.REGTYPE, ""), "absolute")
def test_empty_component_is_rejected(self):
self.assert_rejected(
("roles//a/x", tarfile.REGTYPE, ""), "empty path component"
)
def test_git_component_is_rejected(self):
self.assert_rejected(("roles/a/.git", tarfile.DIRTYPE, ""), "'.git'")
self.assert_rejected(("plugins/.git/config", tarfile.REGTYPE, ""), "'.git'")
def test_case_variants_are_rejected(self):
self.assert_rejected(("roles/a/.GIT/config", tarfile.REGTYPE, ""), "'.git'")
self.assert_rejected(("roles/a/.Git", tarfile.DIRTYPE, ""), "'.git'")
self.assert_rejected(
("roles/a/Molecule/default/m.yml", tarfile.REGTYPE, ""), "forbidden pattern"
)
self.assert_rejected(
("roles/a/files/K.PEM", tarfile.REGTYPE, ""), "forbidden pattern"
)
self.assert_rejected(
("tests/Scripts/t.py", tarfile.REGTYPE, ""), "forbidden pattern"
)
def test_backslash_is_rejected(self):
self.assert_rejected(("roles\\a\\x.yml", tarfile.REGTYPE, ""), "backslash")
def test_control_and_zero_width_characters_are_rejected(self):
for name in (
"roles/a/x\u200b.yml",
"roles/a/x\n.yml",
"roles/a/\u202ex.yml",
"roles/a/x\ty",
):
self.assert_rejected((name, tarfile.REGTYPE, ""), "control or invisible")
def test_duplicate_member_is_rejected(self):
self.assert_rejected(
("README.md", tarfile.REGTYPE, ""), "appears more than once"
)
self.assert_rejected(
("./README.md", tarfile.REGTYPE, ""), "appears more than once"
)
def test_empty_archive_is_rejected(self):
self.build()
code, err = self.check()
self.assertEqual(code, 1, err)
self.assertIn("empty", err)
def test_missing_required_file_is_rejected(self):
for name in sorted(check_tarball.REQUIRED):
self.build(*self.required(skip=(name,)))
code, err = self.check()
self.assertEqual(code, 1, name)
self.assertIn(f"{name}: required file is missing", err)
def test_required_file_as_directory_does_not_count(self):
self.build(*self.required(skip=("COPYING",)), ("COPYING", tarfile.DIRTYPE, ""))
code, err = self.check()
self.assertEqual(code, 1, err)
self.assertIn("COPYING: required file is missing", err)
def test_unreadable_archive_is_one_line(self):
self.path.write_bytes(b"not a tarball at all")
self.assert_one_line_failure(self.path, "cannot read")
self.assert_one_line_failure(
pathlib.Path(self.tmp.name) / "missing.tar.gz", "cannot read"
)
self.build(*self.required())
self.path.write_bytes(self.path.read_bytes()[:40]) # truncated
self.assert_one_line_failure(self.path, "cannot read")
def assert_one_line_failure(self, path, text):
proc = subprocess.run(
[sys.executable, "-I", str(SCRIPT), str(path)],
capture_output=True,
text=True,
check=False,
)
self.assertEqual(proc.returncode, 1, proc.stderr)
self.assertNotIn("Traceback", proc.stderr)
self.assertIn(text, proc.stderr)
self.assertEqual(len(proc.stderr.strip().splitlines()), 1, proc.stderr)
def test_existing_rules_still_apply(self):
self.assert_rejected((".venv/bin/x", tarfile.REGTYPE, ""), "top-level entry")
self.assert_rejected(
("roles/a/molecule/default/m.yml", tarfile.REGTYPE, ""), "forbidden pattern"
)
class BuildWorkflowTest(unittest.TestCase):
"""The symlink guard of build.yml prunes directories that the build itself skips."""
# ansible-galaxy excludes these without being told (ansible.galaxy.collection, the default ignore list).
DEFAULT_EXCLUDED = frozenset({".git"})
def test_pruned_directories_are_not_built(self):
workflow = (REPO / ".gitea" / "workflows" / "build.yml").read_text()
pruned = set(re.findall(r"-path \./(\S+) -prune", workflow))
self.assertTrue(
pruned,
"no -prune target found in build.yml; update this test with the step",
)
ignored = (
set(yaml.safe_load((REPO / "galaxy.yml").read_text())["build_ignore"])
| self.DEFAULT_EXCLUDED
)
self.assertEqual(
sorted(pruned - ignored),
[],
"build.yml prunes a directory that the build does not skip",
)
if __name__ == "__main__":
unittest.main()