fix(build): harden the Collection archive check and refuse source symlinks
Build / build (pull_request) Successful in 9s
Lint / lint (pull_request) Successful in 6s
Molecule / molecule (pull_request) Successful in 30s

check_tarball.py now compares path components case-insensitively (.GIT,
Molecule), rejects backslashes and control or zero-width characters,
duplicate members, an empty archive and a missing REQUIRED file, and
reports an unreadable archive as one line. Drop the shebang and the
executable bit and pass check= to subprocess.run so ansible-test sanity
passes.

ansible-galaxy dereferences symlinks, which the archive check cannot see,
so the Build workflow fails when the source tree holds a symlink.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MmzvM9skAvYcph2c9EiPcm
This commit is contained in:
Defame1297andClaude Sonnet 5.5 committed 2026-10-25 19:20:48 +00:00
1 parent 580df0b892
commit b5751e14d6
4 files changed
+143 -23

No files matched your search

+12
View File
@@ -83,6 +83,18 @@ jobs:
fi fi
echo "Tag $TAG is annotated and matches galaxy.yml version $version" echo "Tag $TAG is annotated and matches galaxy.yml version $version"
# ansible-galaxy dereferences symlinks when it builds, so a symlink in the source tree
# reaches the archive as a regular file with the target's content, where
# scripts/check_tarball.py cannot see it. Refuse them in the tree instead.
- name: Refuse symlinks in the source tree
run: |
links="$(find . -path ./.git -prune -o -path ./.venv -prune -o -type l -print)"
if [ -n "$links" ]; then
echo "::error::symlinks in the source tree would be dereferenced into the Collection archive:"
echo "$links"
exit 1
fi
- name: Build the Collection - name: Build the Collection
run: | run: |
export PATH="/opt/venv/bin:$PATH" export PATH="/opt/venv/bin:$PATH"
@@ -4,4 +4,8 @@ minor_changes:
the roles' molecule scenarios, CLAUDE.md or other repository tooling; the Build workflow the roles' molecule scenarios, CLAUDE.md or other repository tooling; the Build workflow
now fails when the archive holds anything outside an allow list, a member that is not a now fails when the archive holds anything outside an allow list, a member that is not a
regular file or directory (symlinks, hardlinks, devices), or a path that is absolute or regular file or directory (symlinks, hardlinks, devices), or a path that is absolute or
holds an empty, '..' or '.git' component. holds an empty, '..' or '.git' component (compared case-insensitively), a backslash or a
control or zero-width character; it also fails on duplicate members, an empty archive or one
that lacks MANIFEST.json, FILES.json, COPYING, README.md, meta/runtime.yml or
changelogs/changelog.yaml, and on symlinks in the source tree (which ansible-galaxy would
dereference).
Executable → Regular
+59 -17
View File
@@ -1,25 +1,42 @@
#!/usr/bin/env python3
# SPDX-FileCopyrightText: Defame1297 and contributors # SPDX-FileCopyrightText: Defame1297 and contributors
# SPDX-License-Identifier: GPL-3.0-or-later # SPDX-License-Identifier: GPL-3.0-or-later
"""Assert that a built Collection tarball holds only files meant for consumers. """Assert that a built Collection tarball holds only files meant for consumers.
scripts/check_tarball.py dist/mortis-kamino-X.Y.Z.tar.gz python3 scripts/check_tarball.py dist/mortis-kamino-X.Y.Z.tar.gz
galaxy.yml `build_ignore` is a deny list: a new file at the repository root (a tool's galaxy.yml `build_ignore` is a deny list: a new file at the repository root (a tool's
cache, an editor's directory, an agent's settings) ships silently. This check is the cache, an editor's directory, an agent's settings) ships silently. This check is the
allow list. A top-level entry that is not in ALLOWED_TOP, or a path under an entry that allow list. It fails the build for:
matches FORBIDDEN, fails the build, and so does a member that is not a regular file or
directory, or whose path is absolute or holds an empty, '.', '..' or '.git' component. When the Collection gains a plugin type or a * a top-level entry that is not in ALLOWED_TOP, or a path under an entry that matches
directory consumers should get, add it to ALLOWED_TOP in the same change. FORBIDDEN (both compared case-insensitively, so `.GIT` and `Molecule` do not slip by);
* a member that is not a regular file or directory;
* a path that is absolute or holds an empty, '.', '..' or '.git' component, a backslash,
or a control or zero-width character;
* two members with the same name;
* an empty archive, or one that lacks a file of REQUIRED;
* an archive that cannot be read (one line, exit 1).
ansible-galaxy dereferences symlinks while building, so a symlink in the source tree
reaches the archive as a regular file and is invisible here; the Build workflow checks
the source tree for symlinks separately.
When the Collection gains a plugin type or a directory consumers should get, add it to
ALLOWED_TOP in the same change.
""" """
import fnmatch import fnmatch
import sys import sys
import tarfile import tarfile
import unicodedata
ALLOWED_TOP = { ALLOWED_TOP = {
"COPYING", "FILES.json", "LICENSES", "MANIFEST.json", "NOTICE", "README.md", "COPYING", "FILES.json", "LICENSES", "MANIFEST.json", "NOTICE", "README.md",
"REUSE.toml", "changelogs", "docs", "meta", "plugins", "roles", "tests", "REUSE.toml", "changelogs", "docs", "meta", "plugins", "roles", "tests",
} }
# Every Collection archive built by ansible-galaxy holds these.
REQUIRED = {
"MANIFEST.json", "FILES.json", "COPYING", "README.md", "meta/runtime.yml", "changelogs/changelog.yaml",
}
# Checked on every member, whatever its top-level directory. # Checked on every member, whatever its top-level directory.
FORBIDDEN = [ FORBIDDEN = [
"*/molecule/*", "*/molecule", "tests/scripts*", "*.pyc", "*__pycache__*", "*.tar.gz", "*/molecule/*", "*/molecule", "tests/scripts*", "*.pyc", "*__pycache__*", "*.tar.gz",
@@ -27,25 +44,33 @@ FORBIDDEN = [
] ]
def normalize(name):
"""The member name without a leading './' and trailing '/'."""
path = name.rstrip("/")
return path[2:] if path.startswith("./") else path
def path_problems(name): def path_problems(name):
"""Problems of one member path, as a list of messages (empty when the path is fine).""" """Problems of one member path, as a list of messages (empty when the path is fine)."""
if name.startswith("/"): if name.startswith("/"):
return [f"{name}: absolute path"] return [f"{name!r}: absolute path"]
path = name.rstrip("/") if "\\" in name:
if path.startswith("./"): return [f"{name!r}: backslash in the path"]
path = path[2:] odd = [c for c in name if unicodedata.category(c) in ("Cc", "Cf", "Zl", "Zp")]
if not path: if odd:
return [] return [f"{name!r}: control or invisible character in the path"]
path = normalize(name)
parts = path.split("/") parts = path.split("/")
if "" in parts: if "" in parts:
return [f"{path}: empty path component ('//')"] return [f"{path}: empty path component ('//')"]
if "." in parts or ".." in parts: if "." in parts or ".." in parts:
return [f"{path}: '.' or '..' path component"] return [f"{path}: '.' or '..' path component"]
if ".git" in parts: folded = [part.casefold() for part in parts]
if ".git" in folded:
return [f"{path}: '.git' path component"] return [f"{path}: '.git' path component"]
if parts[0] not in ALLOWED_TOP: if parts[0] not in ALLOWED_TOP:
return [f"{path}: top-level entry '{parts[0]}' is not allowed in the Collection archive"] return [f"{path}: top-level entry '{parts[0]}' is not allowed in the Collection archive"]
if any(fnmatch.fnmatch(path, pat) for pat in FORBIDDEN): if any(fnmatch.fnmatchcase("/".join(folded), pat) for pat in FORBIDDEN):
return [f"{path}: matches a forbidden pattern"] return [f"{path}: matches a forbidden pattern"]
return [] return []
@@ -74,13 +99,30 @@ def member_problems(members):
return found return found
def archive_problems(members):
"""All problems of an archive: members, duplicates, emptiness and the REQUIRED files."""
if not members:
return ["the archive is empty"]
found = member_problems(members)
names = [normalize(m.name) for m in members]
for name in sorted({n for n in names if names.count(n) > 1}):
found.append(f"{name}: appears more than once in the archive")
present = {normalize(m.name) for m in members if m.isreg()}
found += [f"{name}: required file is missing" for name in sorted(REQUIRED - present)]
return found
def main(argv): def main(argv):
if len(argv) != 2: if len(argv) != 2:
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
return 2 return 2
with tarfile.open(argv[1]) as tar: try:
members = tar.getmembers() with tarfile.open(argv[1]) as tar:
bad = member_problems(members) members = tar.getmembers()
except (tarfile.TarError, OSError, EOFError) as exc:
sys.stderr.write(f"cannot read {argv[1]}: {' '.join(str(exc).split())}\n")
return 1
bad = archive_problems(members)
if bad: if bad:
sys.stderr.write("Unexpected files in the Collection archive:\n " + "\n ".join(bad) + "\n") sys.stderr.write("Unexpected files in the Collection archive:\n " + "\n ".join(bad) + "\n")
return 1 return 1
+67 -5
View File
@@ -51,16 +51,25 @@ class CraftedTarballTest(unittest.TestCase):
tar.addfile(info, io.BytesIO(data) if data else None) tar.addfile(info, io.BytesIO(data) if data else None)
def check(self): def check(self):
proc = subprocess.run([sys.executable, "-I", str(SCRIPT), str(self.path)], capture_output=True, text=True) proc = subprocess.run([sys.executable, "-I", str(SCRIPT), str(self.path)], capture_output=True, text=True,
check=False)
return proc.returncode, proc.stderr 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): def test_legitimate_tarball_passes(self):
self.build(("roles", tarfile.DIRTYPE, ""), ("roles/a/tasks/main.yml", tarfile.REGTYPE, ""), self.build(*self.required(), ("roles", tarfile.DIRTYPE, ""), ("roles/a/tasks/main.yml", tarfile.REGTYPE, ""),
("README.md", tarfile.REGTYPE, ""), ("LICENSES/MIT.txt", tarfile.REGTYPE, "")) ("LICENSES/MIT.txt", tarfile.REGTYPE, ""), ("meta", tarfile.DIRTYPE, ""))
self.assertEqual(self.check()[0], 0) code, err = self.check()
self.assertEqual(code, 0, err)
def test_required_set_matches_a_real_build(self):
self.assertEqual(check_tarball.REQUIRED, {
"MANIFEST.json", "FILES.json", "COPYING", "README.md", "meta/runtime.yml", "changelogs/changelog.yaml"})
def assert_rejected(self, entry, text): def assert_rejected(self, entry, text):
self.build(("README.md", tarfile.REGTYPE, ""), entry) self.build(*self.required(), entry)
code, err = self.check() code, err = self.check()
self.assertEqual(code, 1, err) self.assertEqual(code, 1, err)
self.assertIn(text, err) self.assertIn(text, err)
@@ -88,6 +97,59 @@ class CraftedTarballTest(unittest.TestCase):
self.assert_rejected(("roles/a/.git", tarfile.DIRTYPE, ""), "'.git'") self.assert_rejected(("roles/a/.git", tarfile.DIRTYPE, ""), "'.git'")
self.assert_rejected(("plugins/.git/config", tarfile.REGTYPE, ""), "'.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): def test_existing_rules_still_apply(self):
self.assert_rejected((".venv/bin/x", tarfile.REGTYPE, ""), "top-level entry") self.assert_rejected((".venv/bin/x", tarfile.REGTYPE, ""), "top-level entry")
self.assert_rejected(("roles/a/molecule/default/m.yml", tarfile.REGTYPE, ""), "forbidden pattern") self.assert_rejected(("roles/a/molecule/default/m.yml", tarfile.REGTYPE, ""), "forbidden pattern")