Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(serve): reject web UI archive members that escape the cache directory (#3975)

Raghav Chamadiya0923c297148b
diff --git a/packages/cli/src/repowise/cli/commands/serve_cmd.py b/packages/cli/src/repowise/cli/commands/serve_cmd.py
index 5abe23086..8876c509b 100644
--- a/packages/cli/src/repowise/cli/commands/serve_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/serve_cmd.py
@@ -5,13 +5,14 @@ from __future__ import annotations
import contextlib
import json
import os
+import posixpath
import shutil
import socket
import subprocess
import tarfile
import tempfile
from datetime import UTC, datetime
-from pathlib import Path
+from pathlib import Path, PurePosixPath, PureWindowsPath
import click
@@ -443,6 +444,57 @@ def _local_build_is_stale(web_dir: Path) -> bool:
return False
+def _safe_extract_tar(archive: Path, dest: Path) -> None:
+ """Extract a .tar.gz into ``dest``, refusing any member that would land outside it."""
+ root = dest.resolve()
+
+ def _inside(target: Path) -> bool:
+ return target == root or target.is_relative_to(root)
+
+ def _check_name(raw: str, member: str, what: str) -> str:
+ name = raw.replace("\\", "/")
+ # A colon covers drive-relative names (C:x) and NTFS alternate data streams.
+ if (
+ name.startswith("/")
+ or Path(name).is_absolute()
+ or PureWindowsPath(name).drive
+ or ":" in name
+ ):
+ raise ValueError(f"archive {what} is absolute or drive-qualified: {member}")
+ return name
+
+ with tarfile.open(archive, "r:gz") as tar:
+ members = tar.getmembers()
+ symlinks = {posixpath.normpath(m.name.replace("\\", "/")) for m in members if m.issym()}
+ for m in members:
+ name = _check_name(m.name, m.name, "member path")
+ target = (root / name).resolve()
+ if not _inside(target):
+ raise ValueError(f"archive member escapes the destination: {m.name}")
+ # Static resolution cannot follow links the archive itself creates, so no
+ # path may pass through one (blocks chains like a -> . then a/b -> ..).
+ parts = PurePosixPath(posixpath.normpath(name)).parts
+ if any("/".join(parts[:i]) in symlinks for i in range(1, len(parts))):
+ raise ValueError(f"archive member passes through a link: {m.name}")
+ if m.issym() or m.islnk():
+ link = _check_name(m.linkname, m.name, "link target")
+ # Symlinks resolve from the member's directory, hardlinks from the root.
+ base = target.parent if m.issym() else root
+ if not _inside((base / link).resolve()):
+ raise ValueError(f"archive link escapes the destination: {m.name}")
+ if m.islnk():
+ lparts = PurePosixPath(posixpath.normpath(link)).parts
+ if any("/".join(lparts[:i]) in symlinks for i in range(1, len(lparts) + 1)):
+ raise ValueError(f"archive link passes through a link: {m.name}")
+ elif not (m.isfile() or m.isdir()):
+ raise ValueError(f"archive member is not a file or directory: {m.name}")
+ # The stdlib data filter (3.11.4+) re-checks the same rules at write time.
+ if hasattr(tarfile, "data_filter"):
+ tar.extractall(root, members=members, filter="data")
+ else:
+ tar.extractall(root, members=members)
+
+
def _download_web(version: str) -> bool:
"""Download pre-built web frontend from GitHub releases."""
import httpx
@@ -474,8 +526,7 @@ def _download_web(version: str) -> bool:
else:
item.unlink()
- with tarfile.open(tmp_path, "r:gz") as tar:
- tar.extractall(_WEB_CACHE_DIR)
+ _safe_extract_tar(Path(tmp_path), _WEB_CACHE_DIR)
_MARKER_FILE.write_text(version)
console.print("[green]Web UI downloaded and cached.[/green]")
diff --git a/tests/unit/cli/test_serve_web_extract.py b/tests/unit/cli/test_serve_web_extract.py
new file mode 100644
index 000000000..f7e75584b
--- /dev/null
+++ b/tests/unit/cli/test_serve_web_extract.py
@@ -0,0 +1,182 @@
+"""The downloaded web UI archive must never write outside the cache directory."""
+
+from __future__ import annotations
+
+import io
+import tarfile
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands import serve_cmd
+
+
+def _make_tar(path: Path, members: list[tuple[str, str | None, bytes]]) -> Path:
+ """Write a .tar.gz of (name, symlink_target_or_None, data) entries."""
+ with tarfile.open(path, "w:gz") as tar:
+ for name, link, data in members:
+ info = tarfile.TarInfo(name)
+ if link is not None:
+ # "hard:" prefix marks a hardlink; otherwise a symlink.
+ if link.startswith("hard:"):
+ info.type, info.linkname = tarfile.LNKTYPE, link[5:]
+ else:
+ info.type, info.linkname = tarfile.SYMTYPE, link
+ tar.addfile(info)
+ else:
+ info.size = len(data)
+ tar.addfile(info, io.BytesIO(data))
+ return path
+
+
+def _dest(tmp_path: Path) -> Path:
+ dest = tmp_path / "cache" / "web"
+ dest.mkdir(parents=True)
+ return dest
+
+
+def test_legit_archive_extracts_as_before(tmp_path: Path) -> None:
+ archive = _make_tar(
+ tmp_path / "web.tar.gz",
+ [
+ ("server.js", None, b"console.log(1)"),
+ (".next/static/app.js", None, b"x"),
+ ("node_modules/.bin/next", "../next/dist/bin/next", b""),
+ ("node_modules/next/dist/bin/next", None, b"#!/usr/bin/env node"),
+ ],
+ )
+ dest = _dest(tmp_path)
+ serve_cmd._safe_extract_tar(archive, dest)
+ assert (dest / "server.js").read_bytes() == b"console.log(1)"
+ assert (dest / ".next" / "static" / "app.js").read_bytes() == b"x"
+ assert (dest / "node_modules" / "next" / "dist" / "bin" / "next").exists()
+
+
+ ("member", "link", "message"),
+ [
+ ("../evil.txt", None, "escapes the destination"),
+ ("sub/../../evil.txt", None, "escapes the destination"),
+ ("/evil.txt", None, "absolute or drive-qualified"),
+ ("link", "../../evil_dir", "link escapes"),
+ ("link", "/etc", "absolute or drive-qualified"),
+ ("C:evil.txt", None, "drive-qualified"),
+ ("a:stream", None, "drive-qualified"),
+ ("//server/share/evil.txt", None, "drive-qualified"),
+ ("link", "C:evil", "drive-qualified"),
+ ("hl", "hard:../evil.txt", "link escapes"),
+ ],
+)
+def test_escaping_member_is_rejected(
+ tmp_path: Path, member: str, link: str | None, message: str
+) -> None:
+ archive = _make_tar(
+ tmp_path / "web.tar.gz",
+ [("server.js", None, b"ok"), (member, link, b"pwned")],
+ )
+ dest = _dest(tmp_path)
+ with pytest.raises(ValueError, match=message):
+ serve_cmd._safe_extract_tar(archive, dest)
+ # Validation runs before any write: nothing lands anywhere.
+ assert list(dest.iterdir()) == []
+ assert not (tmp_path / "cache" / "evil.txt").exists()
+ assert not (tmp_path / "evil.txt").exists()
+
+
+def test_download_web_reports_failure_on_tampered_archive(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ archive = _make_tar(tmp_path / "web.tar.gz", [("../evil.txt", None, b"pwned")])
+ payload = archive.read_bytes()
+
+ class _Resp:
+ def __enter__(self) -> _Resp:
+ return self
+
+ def __exit__(self, *_: object) -> None:
+ return None
+
+ def raise_for_status(self) -> None:
+ return None
+
+ def iter_bytes(self, chunk_size: int) -> list[bytes]:
+ return [payload]
+
+ import httpx
+
+ monkeypatch.setattr(httpx, "stream", lambda *_a, **_k: _Resp())
+ dest = _dest(tmp_path)
+ monkeypatch.setattr(serve_cmd, "_WEB_CACHE_DIR", dest)
+ monkeypatch.setattr(serve_cmd, "_MARKER_FILE", dest / ".version")
+
+ assert serve_cmd._download_web("0.0.0") is False
+ assert not (dest / ".version").exists()
+ assert not (tmp_path / "cache" / "evil.txt").exists()
+
+
+def _assert_nothing_written(tmp_path: Path, dest: Path) -> None:
+ assert list(dest.iterdir()) == []
+ assert not (tmp_path / "cache" / "b").exists()
+ assert not (tmp_path / "cache" / "evil").exists()
+
+
+def test_symlink_chain_is_rejected(tmp_path: Path) -> None:
+ archive = _make_tar(tmp_path / "web.tar.gz", [("a", ".", b""), ("a/b", "..", b"")])
+ dest = _dest(tmp_path)
+ with pytest.raises(ValueError, match="passes through a link"):
+ serve_cmd._safe_extract_tar(archive, dest)
+ _assert_nothing_written(tmp_path, dest)
+
+
+def test_hardlink_through_symlink_is_rejected(tmp_path: Path) -> None:
+ archive = _make_tar(tmp_path / "web.tar.gz", [("a", ".", b""), ("h", "hard:a", b"")])
+ dest = _dest(tmp_path)
+ with pytest.raises(ValueError, match="passes through a link"):
+ serve_cmd._safe_extract_tar(archive, dest)
+ _assert_nothing_written(tmp_path, dest)
+
+
[email protected]("kind", [tarfile.FIFOTYPE, tarfile.CHRTYPE, tarfile.BLKTYPE])
+def test_special_file_member_is_rejected(tmp_path: Path, kind: bytes) -> None:
+ archive = tmp_path / "web.tar.gz"
+ with tarfile.open(archive, "w:gz") as tar:
+ info = tarfile.TarInfo("dev")
+ info.type = kind
+ tar.addfile(info)
+ dest = _dest(tmp_path)
+ with pytest.raises(ValueError, match="not a file or directory"):
+ serve_cmd._safe_extract_tar(archive, dest)
+ _assert_nothing_written(tmp_path, dest)
+
+
+ "members",
+ [
+ [("a", "..", b""), ("a/evil", None, b"pwned")],
+ [("../evil", None, b"pwned")],
+ [("a", ".", b""), ("a/b", "..", b"")],
+ ],
+)
+def test_fallback_without_data_filter_rejects(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, members: list[tuple[str, str | None, bytes]]
+) -> None:
+ monkeypatch.delattr(tarfile, "data_filter", raising=False)
+ archive = _make_tar(tmp_path / "web.tar.gz", members)
+ dest = _dest(tmp_path)
+ with pytest.raises(ValueError):
+ serve_cmd._safe_extract_tar(archive, dest)
+ _assert_nothing_written(tmp_path, dest)
+
+
+def test_fallback_without_data_filter_extracts_legit(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.delattr(tarfile, "data_filter", raising=False)
+ archive = _make_tar(
+ tmp_path / "web.tar.gz",
+ [("server.js", None, b"ok"), (".next/static/app.js", None, b"x")],
+ )
+ dest = _dest(tmp_path)
+ serve_cmd._safe_extract_tar(archive, dest)
+ assert (dest / "server.js").read_bytes() == b"ok"
+ assert (dest / ".next" / "static" / "app.js").read_bytes() == b"x"