Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

update: Control bundles may carry relative links inside themselves (packer and unpacker); tests

Niko12215778a9ef17f8
diff --git a/packaging/feed_tool.py b/packaging/feed_tool.py
index 5e4f0f77f..f279130ed 100644
--- a/packaging/feed_tool.py
+++ b/packaging/feed_tool.py
@@ -115,15 +115,27 @@ def _write_archive(files: list[tuple[str, Path]], archive: Path, fmt: str, entry
info.uid = info.gid = 0
info.uname = info.gname = ""
info.mtime = 0
+ if info.issym(): # a Control bundle's Python has relative symlinks; engines have none
+ tar.addfile(info)
+ continue
info.mode = _mode(path, rel, entrypoint)
with path.open("rb") as stream:
tar.addfile(info, stream)
-def _tree(folder: Path) -> list[tuple[str, Path]]:
+def _tree(folder: Path, *, links: bool = False) -> list[tuple[str, Path]]:
+ """Regular files under `folder`; with `links` also the symbolic links, which must be relative and stay inside it."""
found = []
+ root = folder.resolve()
for path in sorted(folder.rglob("*")):
- if path.is_file() and not path.is_symlink():
+ if path.is_symlink():
+ if not links:
+ continue
+ target = os.readlink(path)
+ if os.path.isabs(target) or not (path.parent / target).resolve().is_relative_to(root):
+ raise SystemExit(f"{path} is a symbolic link that leaves the package ({target}); a package may only link inside itself")
+ found.append((path.relative_to(folder).as_posix(), path))
+ elif path.is_file():
found.append((path.relative_to(folder).as_posix(), path))
return found
@@ -149,8 +161,8 @@ def pack_engine(folder: Path, out: Path, fmt: str = "tar.gz", *, url_prefix: str
def pack_control(folder: Path, out: Path, *, version: str, platform: str, fmt: str = "tar.gz",
entry_file: str = "strata.py", url_prefix: str = "control/") -> dict:
folder = Path(folder)
- files = _tree(folder)
- installed = sum(p.stat().st_size for _, p in files)
+ files = _tree(folder, links=True)
+ installed = sum(p.stat().st_size for _, p in files if not p.is_symlink())
name = f"strata-control-{version}-{platform}.{fmt}"
archive = Path(out) / name
_write_archive(files, archive, fmt, entry_file)
diff --git a/strata_control/updater.py b/strata_control/updater.py
index f0ac6959f..2e6cd9321 100644
--- a/strata_control/updater.py
+++ b/strata_control/updater.py
@@ -296,9 +296,52 @@ def _archive_size(archive: Path, fmt: str) -> int:
return sum(m.size for m in tar.getmembers() if m.isfile())
-def extract(archive: Path, destination: Path, fmt: str, installed_bytes: int) -> None:
+def _extract_with_links(archive: Path, destination: Path, fmt: str) -> None:
+ """Like `components.safe_extract`, but a relative symbolic link that stays inside `destination` is allowed. A Control bundle's
+ Python needs them (libpython, terminfo). Every name is checked before anything is written; hard links, devices, absolute
+ links and links that leave the folder are refused."""
+ mode = {"tar.gz": "r:gz", "tar.xz": "r:xz"}.get(fmt)
+ if mode is None:
+ raise components.ComponentError(f"links are only unpacked from tar archives, not {fmt}")
+ root = destination.resolve()
+ with tarfile.open(archive, mode) as tar:
+ members = tar.getmembers()
+ for m in members:
+ components._check_member_within(destination, m.name)
+ if m.isdir() or m.isfile():
+ continue
+ if not m.issym():
+ raise components.UnsafeArchive(f"the archive contains a member that is not a file or a symbolic link ({m.name!r})")
+ link = m.linkname.replace("\\", "/")
+ if not link or link.startswith("/") or re.match(r"^[A-Za-z]:", link):
+ raise components.UnsafeArchive(f"the archive has an absolute symbolic link ({m.name!r})")
+ resolved = (destination / m.name).parent.joinpath(link).resolve()
+ if resolved != root and root not in resolved.parents:
+ raise components.UnsafeArchive(f"the symbolic link {m.name!r} leaves the package")
+ destination.mkdir(parents=True, exist_ok=True)
+ links = []
+ for m in members:
+ target = components._check_member_within(destination, m.name)
+ if m.isdir():
+ target.mkdir(parents=True, exist_ok=True)
+ elif m.isfile():
+ target.parent.mkdir(parents=True, exist_ok=True)
+ source = tar.extractfile(m)
+ with target.open("wb") as out:
+ shutil.copyfileobj(source, out)
+ if m.mode & 0o111:
+ target.chmod(0o755)
+ else:
+ links.append((target, m.linkname))
+ for target, linkname in links:
+ target.parent.mkdir(parents=True, exist_ok=True)
+ os.symlink(linkname, target)
+
+
+def extract(archive: Path, destination: Path, fmt: str, installed_bytes: int, *, allow_links: bool = False) -> None:
"""Unpack into a fresh folder. The archive's own total size must not exceed what the signed feed declared, so a package
- cannot grow into a disk-filling bomb; names and links are checked by `components.safe_extract` before anything is written."""
+ cannot grow into a disk-filling bomb; names and links are checked by `components.safe_extract` before anything is written
+ (an engine package may not contain links; a Control bundle may contain relative links that stay inside it)."""
try:
total = _archive_size(archive, fmt)
except (tarfile.TarError, zipfile.BadZipFile, OSError, EOFError) as exc:
@@ -308,7 +351,10 @@ def extract(archive: Path, destination: Path, fmt: str, installed_bytes: int) ->
if destination.exists():
shutil.rmtree(destination, ignore_errors=True)
try:
- components.safe_extract(archive, destination, fmt=fmt)
+ if allow_links:
+ _extract_with_links(archive, destination, fmt)
+ else:
+ components.safe_extract(archive, destination, fmt=fmt)
except components.ComponentError as exc:
shutil.rmtree(destination, ignore_errors=True)
raise UpdateError(f"the archive was refused: {exc}", 5) from None
@@ -830,7 +876,7 @@ def update_control(ctx: Context, feed: feedmod.Feed, state: State) -> dict:
stage = updates_dir(root) / "staging" / ("control-" + uuid.uuid4().hex[:8])
try:
ctx.say("verify", f"Unpacking Control {pkg.version}", component="control")
- extract(archive, stage, pkg.format, pkg.installed_bytes)
+ extract(archive, stage, pkg.format, pkg.installed_bytes, allow_links=pkg.format != "zip")
entry = stage / pkg.entry
if not entry.is_file():
raise UpdateError(f"the Control package has no {pkg.entry}", 5)
diff --git a/tests/terminal/test_updater.py b/tests/terminal/test_updater.py
index 80c62df02..9457b3c42 100644
--- a/tests/terminal/test_updater.py
+++ b/tests/terminal/test_updater.py
@@ -509,6 +509,49 @@ class OtherComponents(UpdaterCase):
self.assertIsNone(updater.active_control(self.components))
self.assertFalse((self.components / "control" / "0.1.46").exists())
+ @unittest.skipIf(WINDOWS, "symbolic links need no privilege only on POSIX")
+ def test_a_control_bundle_may_link_inside_itself_and_nowhere_else(self):
+ bundle = self.root / "control-links"
+ (bundle / "python" / "lib").mkdir(parents=True)
+ (bundle / "strata.py").write_text("print('strata 0.1.46 (stub)')\n")
+ (bundle / "python" / "lib" / "libpython3.12.so").write_bytes(b"lib")
+ os.symlink("libpython3.12.so", bundle / "python" / "lib" / "libpython3.so")
+ from feed_tool import build_feed, pack_control
+ (self.release / "control").mkdir()
+ entry = pack_control(bundle, self.release / "control", version="0.1.46", platform=PLATFORM)
+ build_feed(self.release, key=self.key, sequence=1, control_dir=self.release / "control")
+ out = updater.run_update(self.ctx(), engine=False, control=True)
+ self.assertEqual(out["results"][0]["status"], "updated", out)
+ link = self.components / "control" / "0.1.46" / "python" / "lib" / "libpython3.so"
+ self.assertTrue(link.is_symlink() and os.readlink(link) == "libpython3.12.so")
+ self.assertEqual(link.read_bytes(), b"lib")
+
+ @unittest.skipIf(WINDOWS, "symbolic links need no privilege only on POSIX")
+ def test_a_control_archive_with_a_link_out_of_the_package_is_refused(self):
+ import tarfile
+ from feed_tool import build_feed
+ (self.release / "control").mkdir()
+ archive = self.release / "control" / "evil.tar.gz"
+ good = self.root / "strata.py"
+ good.write_text("print('strata 0.1.46')\n")
+ for target in ("/etc/passwd", "../../outside", "a/../../../outside"):
+ with self.subTest(target=target):
+ with tarfile.open(archive, "w:gz") as tar:
+ tar.add(good, arcname="strata.py")
+ info = tarfile.TarInfo("python/evil")
+ info.type, info.linkname = tarfile.SYMTYPE, target
+ tar.addfile(info)
+ data = archive.read_bytes()
+ (self.release / "control" / "evil.entry.json").write_text(json.dumps({
+ "version": "0.1.46", "platform": PLATFORM, "format": "tar.gz", "url": "control/evil.tar.gz", "size": len(data),
+ "sha256": hashlib.sha256(data).hexdigest(), "installed_bytes": 100, "entry": "strata.py"}))
+ build_feed(self.release, key=self.key, sequence=self.sequence + 1, control_dir=self.release / "control")
+ self.sequence += 1
+ out = updater.run_update(self.ctx(), engine=False, control=True)
+ self.assertEqual(out["exit_code"], 5, out)
+ self.assertRegex(out["results"][0]["error"], "symbolic link")
+ self.assertIsNone(updater.active_control(self.components))
+
class Cli(UpdaterCase):
"""`strata update`, `strata components update|rollback` against a feed in a folder, with the test key file the way the