fix(build): reject links, special files and unsafe paths in the Collection archive
Build / build (pull_request) Failing after 8s
Lint / lint (pull_request) Successful in 5s
Molecule / molecule (pull_request) Successful in 35s

check_tarball.py now iterates the tar members instead of their names. Only regular
files and directories are allowed, so a symlink or hardlink cannot smuggle a
file in under an allowed directory. Absolute paths and paths with an empty, '.',
'..' or '.git' component are rejected, so roles/../.venv/x no longer passes the
top-level allow list. Tests build crafted tarballs and run the script on them.

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 18:54:11 +00:00
1 parent e3acab9ca2
commit 580df0b892
3 files changed
+118 -15

No files matched your search

@@ -2,4 +2,6 @@ minor_changes:
- >- - >-
The Collection archive no longer contains extensions/ (the image-smoke molecule scenario), The Collection archive no longer contains extensions/ (the image-smoke molecule scenario),
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. 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
holds an empty, '..' or '.git' component.
+46 -14
View File
@@ -8,7 +8,8 @@
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. A top-level entry that is not in ALLOWED_TOP, or a path under an entry that
matches FORBIDDEN, fails the build. When the Collection gains a plugin type or a 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
directory consumers should get, add it to ALLOWED_TOP in the same change. directory consumers should get, add it to ALLOWED_TOP in the same change.
""" """
import fnmatch import fnmatch
@@ -26,19 +27,50 @@ FORBIDDEN = [
] ]
def path_problems(name):
"""Problems of one member path, as a list of messages (empty when the path is fine)."""
if name.startswith("/"):
return [f"{name}: absolute path"]
path = name.rstrip("/")
if path.startswith("./"):
path = path[2:]
if not path:
return []
parts = path.split("/")
if "" in parts:
return [f"{path}: empty path component ('//')"]
if "." in parts or ".." in parts:
return [f"{path}: '.' or '..' path component"]
if ".git" in parts:
return [f"{path}: '.git' path component"]
if parts[0] not in ALLOWED_TOP:
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):
return [f"{path}: matches a forbidden pattern"]
return []
def problems(names): def problems(names):
found = [] found = []
for name in sorted(names): for name in sorted(names):
path = name.rstrip("/") found += path_problems(name)
if path.startswith("./"): return found
path = path[2:]
if not path:
continue def member_problems(members):
top = path.split("/", 1)[0] """Check tarfile members: only regular files and directories, and only fine paths.
if top not in ALLOWED_TOP:
found.append(f"{path}: top-level entry '{top}' is not allowed in the Collection archive") Links, devices and fifos are rejected whatever their name: a symlink such as
elif any(fnmatch.fnmatch(path, pat) for pat in FORBIDDEN): roles/a/link -> /etc/passwd would ship the target's content on the consumer's side
found.append(f"{path}: matches a forbidden pattern") (or make an extractor write outside its directory).
"""
found = []
for member in sorted(members, key=lambda m: m.name):
if not (member.isreg() or member.isdir()):
kind = ("symlink" if member.issym() else "hardlink" if member.islnk()
else "device" if member.isdev() else "fifo" if member.isfifo() else "special file")
found.append(f"{member.name}: {kind} is not allowed in the Collection archive")
found += path_problems(member.name)
return found return found
@@ -47,12 +79,12 @@ def main(argv):
sys.stderr.write(__doc__) sys.stderr.write(__doc__)
return 2 return 2
with tarfile.open(argv[1]) as tar: with tarfile.open(argv[1]) as tar:
names = tar.getnames() members = tar.getmembers()
bad = problems(names) bad = member_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
print(f"{argv[1]}: {len(names)} entries, all allowed") print(f"{argv[1]}: {len(members)} entries, all allowed")
return 0 return 0
+69
View File
@@ -1,8 +1,12 @@
# 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
"""Run with: python3 -m unittest discover -s tests/scripts""" """Run with: python3 -m unittest discover -s tests/scripts"""
import io
import pathlib import pathlib
import subprocess
import sys import sys
import tarfile
import tempfile
import unittest import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "scripts")) sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[2] / "scripts"))
@@ -24,5 +28,70 @@ class TarballTest(unittest.TestCase):
self.assertEqual(len(check_tarball.problems(["tests/scripts/t.py"])), 1) self.assertEqual(len(check_tarball.problems(["tests/scripts/t.py"])), 1)
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)
return proc.returncode, proc.stderr
def test_legitimate_tarball_passes(self):
self.build(("roles", tarfile.DIRTYPE, ""), ("roles/a/tasks/main.yml", tarfile.REGTYPE, ""),
("README.md", tarfile.REGTYPE, ""), ("LICENSES/MIT.txt", tarfile.REGTYPE, ""))
self.assertEqual(self.check()[0], 0)
def assert_rejected(self, entry, text):
self.build(("README.md", tarfile.REGTYPE, ""), 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_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")
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()