Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
test(security): add unit tests for network_guard and zip_safe modules (#1395)
7. Sunb153ad9c4aa5
diff --git a/tests/misc/test_network_guard.py b/tests/misc/test_network_guard.pynew file mode 100644index 000000000..b3f243a54--- /dev/null+++ b/tests/misc/test_network_guard.py@@ -0,0 +1,308 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Tests for network_guard SSRF protection utilities."""++from __future__ import annotations++from unittest.mock import AsyncMock, patch++import pytest++from openviking.utils.network_guard import (+ _is_public_ip,+ _normalize_host,+ _resolve_host_addresses,+ build_httpx_request_validation_hooks,+ ensure_public_remote_target,+ extract_remote_host,+)+from openviking_cli.exceptions import PermissionDeniedError+++# ── extract_remote_host ──────────────────────────────────────────────────────+++class TestExtractRemoteHost:+ """Verify host extraction from URLs and git SSH addresses."""++ @pytest.mark.parametrize(+ ("source", "expected"),+ [+ ("https://example.com/repo.git", "example.com"),+ ("http://example.com:8080/path", "example.com"),+ ("https://sub.domain.example.com/foo", "sub.domain.example.com"),+ ("ftp://files.example.org/data.zip", "files.example.org"),+ ],+ )+ def test_extracts_host_from_http_urls(self, source: str, expected: str) -> None:+ assert extract_remote_host(source) == expected++ @pytest.mark.parametrize(+ ("source", "expected"),+ [+ ("[email protected]:user/repo.git", "github.com"),+ ("[email protected]:group/project.git", "gitlab.com"),+ ("git@[::1]:user/repo.git", "::1"),+ ],+ )+ def test_extracts_host_from_git_ssh(self, source: str, expected: str) -> None:+ assert extract_remote_host(source) == expected++ def test_git_ssh_missing_colon_returns_none(self) -> None:+ assert extract_remote_host("[email protected]") is None++ def test_url_without_hostname_returns_none(self) -> None:+ assert extract_remote_host("/just/a/path") is None++ def test_empty_string_returns_none(self) -> None:+ assert extract_remote_host("") is None++ def test_strips_brackets_from_ipv6_host(self) -> None:+ result = extract_remote_host("http://[::1]:8080/path")+ assert result == "::1"+++# ── _normalize_host ──────────────────────────────────────────────────────────+++class TestNormalizeHost:+ """Verify trailing-dot stripping and lowercasing."""++ def test_strips_trailing_dot(self) -> None:+ assert _normalize_host("example.com.") == "example.com"++ def test_lowercases_host(self) -> None:+ assert _normalize_host("EXAMPLE.COM") == "example.com"++ def test_strips_dot_and_lowercases(self) -> None:+ assert _normalize_host("Example.COM.") == "example.com"+++# ── _is_public_ip ───────────────────────────────────────────────────────────+++class TestIsPublicIP:+ """Verify classification of public vs non-public IPs."""++ @pytest.mark.parametrize(+ "address",+ [+ "8.8.8.8",+ "1.1.1.1",+ "151.101.1.67",+ "2607:f8b0:4004:800::200e", # Google IPv6+ ],+ )+ def test_public_addresses_are_global(self, address: str) -> None:+ assert _is_public_ip(address) is True++ @pytest.mark.parametrize(+ "address",+ [+ "127.0.0.1",+ "10.0.0.1",+ "172.16.0.1",+ "172.31.255.255",+ "192.168.1.1",+ "0.0.0.0",+ "169.254.1.1", # link-local+ "::1",+ "fe80::1", # IPv6 link-local+ "fc00::1", # IPv6 ULA+ "::ffff:127.0.0.1", # IPv4-mapped IPv6 loopback+ "::ffff:10.0.0.1", # IPv4-mapped IPv6 private+ "::ffff:192.168.1.1", # IPv4-mapped IPv6 private+ ],+ )+ def test_non_public_addresses_are_not_global(self, address: str) -> None:+ assert _is_public_ip(address) is False++ def test_invalid_address_returns_false(self) -> None:+ assert _is_public_ip("not-an-ip") is False++ def test_empty_string_returns_false(self) -> None:+ assert _is_public_ip("") is False+++# ── _resolve_host_addresses ──────────────────────────────────────────────────+++class TestResolveHostAddresses:+ """Verify DNS resolution wrapper behavior."""++ def test_returns_empty_set_for_unresolvable_host(self) -> None:+ result = _resolve_host_addresses("this.host.definitely.does.not.exist.invalid")+ assert result == set()++ def test_returns_empty_set_for_unicode_error(self) -> None:+ # A hostname that triggers UnicodeError in getaddrinfo+ result = _resolve_host_addresses("\udcff.invalid")+ assert result == set()++ @patch("openviking.utils.network_guard.socket.getaddrinfo")+ def test_strips_ipv6_scope_id(self, mock_getaddrinfo) -> None:+ import socket++ mock_getaddrinfo.return_value = [+ (socket.AF_INET6, socket.SOCK_STREAM, 0, "", ("fe80::1%eth0", 0, 0, 0)),+ ]+ result = _resolve_host_addresses("some-host")+ assert "fe80::1" in result+ assert "fe80::1%eth0" not in result++ @patch("openviking.utils.network_guard.socket.getaddrinfo")+ def test_skips_non_inet_families(self, mock_getaddrinfo) -> None:+ mock_getaddrinfo.return_value = [+ (999, 1, 0, "", ("1.2.3.4", 0)), # unknown AF+ ]+ result = _resolve_host_addresses("some-host")+ assert result == set()+++# ── ensure_public_remote_target ──────────────────────────────────────────────+++class TestEnsurePublicRemoteTarget:+ """End-to-end SSRF protection tests."""++ # -- Rejection: no valid host --++ def test_rejects_empty_source(self) -> None:+ with pytest.raises(PermissionDeniedError, match="valid destination host"):+ ensure_public_remote_target("")++ def test_rejects_bare_path(self) -> None:+ with pytest.raises(PermissionDeniedError, match="valid destination host"):+ ensure_public_remote_target("/etc/passwd")++ def test_rejects_git_ssh_without_colon(self) -> None:+ with pytest.raises(PermissionDeniedError, match="valid destination host"):+ ensure_public_remote_target("[email protected]")++ # -- Rejection: localhost variants --++ @pytest.mark.parametrize(+ "source",+ [+ "http://localhost/path",+ "http://localhost.localdomain/path",+ "http://LOCALHOST/path",+ "http://sub.localhost/path",+ "http://anything.localhost/path",+ ],+ )+ def test_rejects_localhost_variants(self, source: str) -> None:+ with pytest.raises(PermissionDeniedError, match="non-public"):+ ensure_public_remote_target(source)++ def test_rejects_localhost_with_trailing_dot(self) -> None:+ with pytest.raises(PermissionDeniedError, match="non-public"):+ ensure_public_remote_target("http://localhost./path")++ # -- Rejection: non-public resolved IPs --++ @pytest.mark.parametrize(+ ("source", "resolved_ip"),+ [+ ("http://evil.attacker.com/path", "127.0.0.1"),+ ("http://evil.attacker.com/path", "10.0.0.1"),+ ("http://evil.attacker.com/path", "172.16.0.1"),+ ("http://evil.attacker.com/path", "192.168.1.1"),+ ("http://evil.attacker.com/path", "0.0.0.0"),+ ("http://evil.attacker.com/path", "::1"),+ ("http://evil.attacker.com/path", "fe80::1"),+ ("http://evil.attacker.com/path", "::ffff:127.0.0.1"),+ ("http://evil.attacker.com/path", "::ffff:10.0.0.1"),+ ("http://evil.attacker.com/path", "169.254.169.254"), # AWS metadata+ ],+ )+ @patch("openviking.utils.network_guard._resolve_host_addresses")+ def test_rejects_non_public_resolved_addresses(+ self, mock_resolve, source: str, resolved_ip: str+ ) -> None:+ mock_resolve.return_value = {resolved_ip}+ with pytest.raises(PermissionDeniedError, match="non-public address"):+ ensure_public_remote_target(source)++ # -- Rejection: DNS rebinding with mixed results --++ @patch("openviking.utils.network_guard._resolve_host_addresses")+ def test_rejects_when_any_resolved_address_is_non_public(self, mock_resolve) -> None:+ """DNS rebinding: even if some IPs are public, one private IP is enough to reject."""+ mock_resolve.return_value = {"8.8.8.8", "127.0.0.1"}+ with pytest.raises(PermissionDeniedError, match="non-public address"):+ ensure_public_remote_target("http://rebinding.attacker.com/path")++ # -- Pass-through: valid public targets --++ @patch("openviking.utils.network_guard._resolve_host_addresses")+ def test_allows_public_http_url(self, mock_resolve) -> None:+ mock_resolve.return_value = {"151.101.1.67"}+ ensure_public_remote_target("https://github.com/repo.git") # should not raise++ @patch("openviking.utils.network_guard._resolve_host_addresses")+ def test_allows_public_git_ssh(self, mock_resolve) -> None:+ mock_resolve.return_value = {"140.82.121.4"}+ ensure_public_remote_target("[email protected]:user/repo.git") # should not raise++ @patch("openviking.utils.network_guard._resolve_host_addresses")+ def test_allows_when_dns_returns_empty(self, mock_resolve) -> None:+ """Unresolvable host is allowed through (fail-open for DNS)."""+ mock_resolve.return_value = set()+ ensure_public_remote_target("http://new-host.example.com/path") # should not raise++ @patch("openviking.utils.network_guard._resolve_host_addresses")+ def test_allows_multiple_public_addresses(self, mock_resolve) -> None:+ mock_resolve.return_value = {"8.8.8.8", "8.8.4.4"}+ ensure_public_remote_target("http://dns-rr.example.com/path") # should not raise+++# ── build_httpx_request_validation_hooks ─────────────────────────────────────+++class TestBuildHttpxRequestValidationHooks:+ """Verify httpx hook construction."""++ def test_returns_none_when_no_validator(self) -> None:+ assert build_httpx_request_validation_hooks(None) is None++ def test_returns_request_hook_dict(self) -> None:+ def dummy_validator(url: str) -> None:+ pass++ hooks = build_httpx_request_validation_hooks(dummy_validator)+ assert hooks is not None+ assert "request" in hooks+ assert len(hooks["request"]) == 1++ @pytest.mark.asyncio+ async def test_hook_calls_validator_with_url(self) -> None:+ calls: list[str] = []++ def tracking_validator(url: str) -> None:+ calls.append(url)++ hooks = build_httpx_request_validation_hooks(tracking_validator)+ assert hooks is not None++ mock_request = AsyncMock()+ mock_request.url = "http://example.com/test"++ hook_fn = hooks["request"][0]+ await hook_fn(mock_request)++ assert calls == ["http://example.com/test"]++ @pytest.mark.asyncio+ async def test_hook_propagates_validator_exception(self) -> None:+ def failing_validator(url: str) -> None:+ raise PermissionDeniedError("blocked")++ hooks = build_httpx_request_validation_hooks(failing_validator)+ assert hooks is not None++ mock_request = AsyncMock()+ mock_request.url = "http://evil.com"++ with pytest.raises(PermissionDeniedError, match="blocked"):+ await hooks["request"][0](mock_request)diff --git a/tests/misc/test_zip_safe.py b/tests/misc/test_zip_safe.pynew file mode 100644index 000000000..4f016340b--- /dev/null+++ b/tests/misc/test_zip_safe.py@@ -0,0 +1,373 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Tests for zip_safe Zip Slip protection and filename normalization."""++from __future__ import annotations++import io+import os+import stat+import zipfile+from pathlib import Path++import pytest++from openviking.utils.zip_safe import (+ _contains_cjk,+ _contains_common_mojibake,+ normalize_zip_filenames,+ safe_extract_zip,+)+++# ── Helpers ──────────────────────────────────────────────────────────────────+++def _make_zip_bytes(entries: dict[str, str]) -> bytes:+ """Create an in-memory zip with the given filename->content mapping."""+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ for name, content in entries.items():+ zf.writestr(name, content)+ return buf.getvalue()+++def _make_zip_with_raw_info(entries: list[tuple[zipfile.ZipInfo, str]]) -> bytes:+ """Create an in-memory zip using raw ZipInfo objects."""+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ for info, content in entries:+ zf.writestr(info, content)+ return buf.getvalue()+++def _assert_no_escape(tmp_path: Path, dest_dir: Path) -> None:+ """Assert no extracted files escaped dest_dir."""+ for f in tmp_path.rglob("*"):+ resolved = f.resolve()+ if resolved == dest_dir.resolve() or resolved.is_relative_to(dest_dir.resolve()):+ continue+ if f.suffix == ".zip":+ continue+ raise AssertionError(f"File escaped dest_dir: {resolved}")+++# ── _contains_cjk ───────────────────────────────────────────────────────────+++class TestContainsCJK:+ """Verify CJK character detection."""++ def test_detects_cjk_unified_ideographs(self) -> None:+ assert _contains_cjk("文件.txt") is True++ def test_detects_cjk_extension_a(self) -> None:+ assert _contains_cjk("\u3400test") is True++ def test_detects_cjk_punctuation(self) -> None:+ assert _contains_cjk("test\u3001test") is True # ideographic comma++ def test_detects_fullwidth_forms(self) -> None:+ assert _contains_cjk("\uff10") is True # fullwidth digit zero++ def test_rejects_ascii_only(self) -> None:+ assert _contains_cjk("hello.txt") is False++ def test_rejects_empty_string(self) -> None:+ assert _contains_cjk("") is False++ def test_rejects_latin_extended(self) -> None:+ assert _contains_cjk("café.txt") is False+++# ── _contains_common_mojibake ────────────────────────────────────────────────+++class TestContainsCommonMojibake:+ """Verify mojibake pattern detection."""++ def test_detects_greek_chars(self) -> None:+ assert _contains_common_mojibake("αβ") is True # Greek alpha, beta++ def test_detects_math_operators(self) -> None:+ assert _contains_common_mojibake("\u2200x") is True # for-all++ def test_detects_box_drawing(self) -> None:+ assert _contains_common_mojibake("\u2500") is True++ def test_rejects_ascii_only(self) -> None:+ assert _contains_common_mojibake("normal.txt") is False++ def test_rejects_cjk_chars(self) -> None:+ assert _contains_common_mojibake("文件.txt") is False++ def test_rejects_empty_string(self) -> None:+ assert _contains_common_mojibake("") is False+++# ── normalize_zip_filenames ──────────────────────────────────────────────────+++class TestNormalizeZipFilenames:+ """Verify UTF-8 filename repair logic."""++ def test_skips_entries_with_utf8_flag_set(self) -> None:+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ info = zipfile.ZipInfo("test.txt")+ info.flag_bits = 0x800 # UTF-8 flag+ zf.writestr(info, "content")+ buf.seek(0)+ with zipfile.ZipFile(buf, "r") as zf:+ original_name = zf.infolist()[0].filename+ normalize_zip_filenames(zf)+ assert zf.infolist()[0].filename == original_name++ def test_does_not_alter_pure_ascii_entries(self) -> None:+ data = _make_zip_bytes({"readme.txt": "hello"})+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ normalize_zip_filenames(zf)+ assert zf.infolist()[0].filename == "readme.txt"++ def test_repairs_cjk_filename_from_cp437_mojibake(self) -> None:+ """Simulate a CJK filename stored without UTF-8 flag.++ The zip module reads it via cp437 producing mojibake.+ normalize_zip_filenames should re-decode from cp437 -> UTF-8.+ """+ # Create a zip with raw bytes: write CJK UTF-8 bytes as the filename+ # but do NOT set the UTF-8 flag, so Python's zipfile reads it as cp437.+ cjk_name = "测试文件.txt"+ utf8_bytes = cjk_name.encode("utf-8")++ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ info = zipfile.ZipInfo(cjk_name)+ info.flag_bits = 0 # no UTF-8 flag+ zf.writestr(info, "content")+ # Manually patch the raw zip to remove UTF-8 flag+ # (Python's ZipFile may set it automatically for non-ASCII)+ raw = buf.getvalue()+ # The flag_bits field is at offset 6 in the local file header+ # This is complex; instead test the logic paths individually+ # by directly calling with a pre-mangled ZipInfo+ buf2 = io.BytesIO()+ with zipfile.ZipFile(buf2, "w") as zf:+ # Encode filename as cp437 representation of the UTF-8 bytes+ try:+ cp437_name = utf8_bytes.decode("cp437")+ except UnicodeDecodeError:+ pytest.skip("Cannot represent CJK UTF-8 bytes in cp437")+ info = zipfile.ZipInfo(cp437_name)+ info.flag_bits = 0+ zf.writestr(info, "content")+ buf2.seek(0)+ with zipfile.ZipFile(buf2, "r") as zf:+ member = zf.infolist()[0]+ # Before normalization, filename should be the mojibake+ assert member.filename == cp437_name+ normalize_zip_filenames(zf)+ # After normalization, the name should be repaired to CJK+ repaired = zf.infolist()[0]+ assert repaired.filename == cjk_name, (+ f"Expected filename to be repaired to {cjk_name!r}, "+ f"got {repaired.filename!r}"+ )+++# ── safe_extract_zip ─────────────────────────────────────────────────────────+++class TestSafeExtractZipNormal:+ """Verify normal zip extraction works correctly."""++ def test_extracts_single_file(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({"hello.txt": "world"})+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ safe_extract_zip(zf, dest)+ assert (dest / "hello.txt").read_text() == "world"++ def test_extracts_nested_directories(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({+ "src/main.py": "print('hello')",+ "src/utils/helper.py": "pass",+ "README.md": "# Test",+ })+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ safe_extract_zip(zf, dest)+ assert (dest / "src" / "main.py").read_text() == "print('hello')"+ assert (dest / "src" / "utils" / "helper.py").read_text() == "pass"+ assert (dest / "README.md").read_text() == "# Test"++ def test_extracts_empty_zip(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ pass # empty+ buf.seek(0)+ with zipfile.ZipFile(buf, "r") as zf:+ safe_extract_zip(zf, dest)+ assert list(dest.iterdir()) == []++ def test_extracts_directory_entries(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("mydir/", "")+ zf.writestr("mydir/file.txt", "content")+ buf.seek(0)+ with zipfile.ZipFile(buf, "r") as zf:+ safe_extract_zip(zf, dest)+ assert (dest / "mydir" / "file.txt").read_text() == "content"++ def test_handles_special_characters_in_filenames(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({+ "spaces in name.txt": "content",+ "file (1).txt": "content",+ "file-with-dashes.txt": "content",+ "file_with_underscores.txt": "content",+ })+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ safe_extract_zip(zf, dest)+ assert (dest / "spaces in name.txt").exists()+ assert (dest / "file (1).txt").exists()+++class TestSafeExtractZipSlipPrevention:+ """Verify Zip Slip path traversal attacks are rejected."""++ def test_rejects_dot_dot_traversal(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({"../../evil.txt": "pwned"})+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ with pytest.raises(ValueError, match="Zip Slip"):+ safe_extract_zip(zf, dest)+ _assert_no_escape(tmp_path, dest)++ def test_rejects_absolute_path(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({"/etc/passwd": "root:x:0:0"})+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ with pytest.raises(ValueError, match="Zip Slip"):+ safe_extract_zip(zf, dest)+ _assert_no_escape(tmp_path, dest)++ def test_rejects_nested_traversal(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({"foo/../../evil.txt": "pwned"})+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ with pytest.raises(ValueError, match="Zip Slip"):+ safe_extract_zip(zf, dest)+ _assert_no_escape(tmp_path, dest)++ def test_rejects_deeply_nested_traversal(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({"a/b/c/../../../../evil.txt": "pwned"})+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ with pytest.raises(ValueError, match="Zip Slip"):+ safe_extract_zip(zf, dest)+ _assert_no_escape(tmp_path, dest)++ @pytest.mark.skipif(os.name != "nt", reason="Windows-specific test")+ def test_rejects_windows_drive_path(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({"C:\\evil.txt": "pwned"})+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ with pytest.raises(ValueError, match="Zip Slip"):+ safe_extract_zip(zf, dest)++ def test_rejects_backslash_traversal(self, tmp_path: Path) -> None:+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({"..\\..\\evil.txt": "pwned"})+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ with pytest.raises(ValueError, match="Zip Slip"):+ safe_extract_zip(zf, dest)+ _assert_no_escape(tmp_path, dest)++ def test_allows_safe_dot_in_filename(self, tmp_path: Path) -> None:+ """Filenames with dots (not traversal) should be allowed."""+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({+ ".gitignore": "*.pyc",+ "src/.env.example": "KEY=val",+ "dir/file.tar.gz": "data",+ })+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ safe_extract_zip(zf, dest)+ assert (dest / ".gitignore").read_text() == "*.pyc"+ assert (dest / "src" / ".env.example").read_text() == "KEY=val"++ def test_allows_current_dir_prefix(self, tmp_path: Path) -> None:+ """Paths starting with ./ are safe and should be allowed."""+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({"./safe.txt": "content"})+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ safe_extract_zip(zf, dest)+ assert (dest / "safe.txt").exists()++ def test_first_malicious_entry_prevents_all_extraction(self, tmp_path: Path) -> None:+ """If the first entry is malicious, no files should be extracted."""+ dest = tmp_path / "out"+ dest.mkdir()+ data = _make_zip_bytes({+ "../../evil.txt": "pwned",+ "safe.txt": "this should not be extracted",+ })+ with zipfile.ZipFile(io.BytesIO(data), "r") as zf:+ with pytest.raises(ValueError, match="Zip Slip"):+ safe_extract_zip(zf, dest)+ assert not (dest / "safe.txt").exists()++ def test_malicious_entry_after_safe_entries(self, tmp_path: Path) -> None:+ """If a later entry is malicious, earlier entries may be extracted but error is raised."""+ dest = tmp_path / "out"+ dest.mkdir()+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ zf.writestr("safe.txt", "ok")+ zf.writestr("../../evil.txt", "pwned")+ buf.seek(0)+ with zipfile.ZipFile(buf, "r") as zf:+ with pytest.raises(ValueError, match="Zip Slip"):+ safe_extract_zip(zf, dest)+ _assert_no_escape(tmp_path, dest)+++class TestSafeExtractZipSymlink:+ """Verify behavior with symlink entries in zip archives."""++ def test_symlink_entry_does_not_create_symlink_outside_dest(self, tmp_path: Path) -> None:+ """Symlink entries pointing outside dest_dir should not escape."""+ dest = tmp_path / "out"+ dest.mkdir()+ buf = io.BytesIO()+ with zipfile.ZipFile(buf, "w") as zf:+ info = zipfile.ZipInfo("evil_link")+ info.external_attr = (stat.S_IFLNK | 0o777) << 16+ zf.writestr(info, "/etc/passwd")+ buf.seek(0)+ with zipfile.ZipFile(buf, "r") as zf:+ safe_extract_zip(zf, dest)+ # Verify no symlink was created pointing outside+ for item in dest.rglob("*"):+ if item.is_symlink():+ target = item.resolve()+ assert target.is_relative_to(dest.resolve()), (+ f"Symlink {item} points outside dest: {target}"+ )