Debian Codegraph @

tests/lib/tools/test_skills.py

raw
1 """Tests for skill-archive extraction (`anthropic.lib.tools._skills`).
2
3 Skill bundles are packaged wrapped in a single directory named after the skill
4 (e.g. `pdf/SKILL.md`). The extractor must strip that wrapper so files land at
5 `<dest>/SKILL.md`, not the doubled `<dest>/pdf/SKILL.md`. It must also still
6 refuse zip-slip / tar-slip members.
7 """
8
9 from __future__ import annotations
10
11 import io
12 import os
13 import stat
14 import tarfile
15 import zipfile
16 from types import SimpleNamespace
17 from typing import Any, AsyncIterator, cast
18 from pathlib import Path
19 from contextlib import asynccontextmanager
20 from collections.abc import Callable
21
22 ArchiveMaker = Callable[[Path, dict[str, bytes]], None]
23 # Maps an entry name to `(data, unix_mode)` so a test can pin the mode the
24 # archive records for that member.
25 ArchiveModeMaker = Callable[[Path, "dict[str, tuple[bytes, int]]"], None]
26
27 import pytest
28
29 from anthropic.lib.tools._skills import (
30 _strip_top,
31 _archive_top_dir,
32 _extract_skill_archive,
33 download_session_skills,
34 )
35
36
37 def _make_zip(path: Path, entries: dict[str, bytes]) -> None:
38 with zipfile.ZipFile(path, "w") as zf:
39 for name, data in entries.items():
40 zf.writestr(name, data)
41
42
43 def _make_targz(path: Path, entries: dict[str, bytes]) -> None:
44 with tarfile.open(path, "w:gz") as tf:
45 for name, data in entries.items():
46 info = tarfile.TarInfo(name)
47 info.size = len(data)
48 tf.addfile(info, io.BytesIO(data))
49
50
51 def _make_zip_modes(path: Path, entries: dict[str, tuple[bytes, int]]) -> None:
52 with zipfile.ZipFile(path, "w") as zf:
53 for name, (data, mode) in entries.items():
54 info = zipfile.ZipInfo(name)
55 # The Unix mode lives in the high 16 bits of `external_attr`.
56 info.external_attr = mode << 16
57 zf.writestr(info, data)
58
59
60 def _make_targz_modes(path: Path, entries: dict[str, tuple[bytes, int]]) -> None:
61 with tarfile.open(path, "w:gz") as tf:
62 for name, (data, mode) in entries.items():
63 info = tarfile.TarInfo(name)
64 info.size = len(data)
65 info.mode = mode
66 tf.addfile(info, io.BytesIO(data))
67
68
69 def _tar_file(
70 name: str, data: bytes, *, mode: int = 0o644, type: bytes = tarfile.REGTYPE
71 ) -> tuple[tarfile.TarInfo, bytes]:
72 info = tarfile.TarInfo(name)
73 info.size = len(data)
74 info.mode = mode
75 info.type = type
76 return info, data
77
78
79 def _tar_special(name: str, type: bytes, linkname: str = "") -> tuple[tarfile.TarInfo, bytes]:
80 info = tarfile.TarInfo(name)
81 info.type = type
82 info.linkname = linkname
83 if type in (tarfile.CHRTYPE, tarfile.BLKTYPE):
84 info.devmajor, info.devminor = 1, 3
85 return info, b""
86
87
88 def _make_tar(path: Path, members: list[tuple[tarfile.TarInfo, bytes]]) -> None:
89 with tarfile.open(path, "w:gz") as tf:
90 for info, data in members:
91 tf.addfile(info, io.BytesIO(data))
92
93
94 def _zip_entry(name: str, *, mode: int, create_system: int = 3) -> zipfile.ZipInfo:
95 info = zipfile.ZipInfo(name)
96 info.create_system = create_system
97 info.external_attr = mode << 16
98 return info
99
100
101 def _make_zip_infos(path: Path, entries: list[tuple[zipfile.ZipInfo, bytes]]) -> None:
102 with zipfile.ZipFile(path, "w") as zf:
103 for info, data in entries:
104 zf.writestr(info, data)
105
106
107 def _assert_only_files_and_dirs(root: Path) -> None:
108 for dirpath, dirnames, filenames in os.walk(root):
109 for name in (*dirnames, *filenames):
110 kind = stat.S_IFMT(os.lstat(Path(dirpath) / name).st_mode)
111 assert kind in (stat.S_IFREG, stat.S_IFDIR), f"{Path(dirpath) / name} is neither file nor directory"
112
113
114 def test_archive_top_dir_detection() -> None:
115 assert _archive_top_dir(["pdf/SKILL.md", "pdf/scripts/x.py"]) == "pdf"
116 assert _archive_top_dir(["pdf/SKILL.md"]) == "pdf"
117 # No common single root -> no strip.
118 assert _archive_top_dir(["SKILL.md", "scripts/x.py"]) == ""
119 assert _archive_top_dir(["a/x", "b/y"]) == ""
120 # Only the bare top dir, nothing nested -> nothing to unwrap.
121 assert _archive_top_dir(["pdf/"]) == ""
122 assert _archive_top_dir([]) == ""
123
124
125 def test_strip_top() -> None:
126 assert _strip_top("pdf/SKILL.md", "pdf") == "SKILL.md"
127 assert _strip_top("pdf/scripts/x.py", "pdf") == "scripts/x.py"
128 assert _strip_top("pdf", "pdf") == "" # bare top-dir entry
129 assert _strip_top("SKILL.md", "") == "SKILL.md" # no wrapper -> unchanged
130 assert _strip_top("other/x", "pdf") == "other/x" # not under the wrapper
131
132
133 @pytest.mark.parametrize("make", [_make_zip, _make_targz])
134 def test_extract_strips_skill_wrapper_dir(make: ArchiveMaker, tmp_path: Path) -> None:
135 archive = tmp_path / "skill.archive"
136 make(
137 archive,
138 {
139 "pdf/SKILL.md": b"# PDF",
140 "pdf/scripts/run.py": b"print(1)",
141 },
142 )
143 dest = tmp_path / "skills" / "pdf"
144 _extract_skill_archive(archive, dest)
145
146 # Stripped: files land directly under dest, not dest/pdf/.
147 assert (dest / "SKILL.md").read_bytes() == b"# PDF"
148 assert (dest / "scripts" / "run.py").read_bytes() == b"print(1)"
149 assert not (dest / "pdf").exists(), "wrapper dir was not stripped (doubling)"
150
151
152 @pytest.mark.parametrize("make", [_make_zip, _make_targz])
153 def test_extract_flat_archive_unchanged(make: ArchiveMaker, tmp_path: Path) -> None:
154 archive = tmp_path / "skill.archive"
155 make(archive, {"SKILL.md": b"# flat", "scripts/run.py": b"x"})
156 dest = tmp_path / "skills" / "flat"
157 _extract_skill_archive(archive, dest)
158 assert (dest / "SKILL.md").read_bytes() == b"# flat"
159 assert (dest / "scripts" / "run.py").read_bytes() == b"x"
160
161
162 def test_extract_refuses_zip_slip(tmp_path: Path) -> None:
163 archive = tmp_path / "evil.zip"
164 _make_zip(archive, {"../escape.txt": b"pwned"})
165 dest = tmp_path / "skills" / "x"
166 with pytest.raises(ValueError):
167 _extract_skill_archive(archive, dest)
168 assert not (tmp_path / "skills" / "escape.txt").exists()
169 assert not (tmp_path / "escape.txt").exists()
170
171
172 def _mode(p: Path) -> int:
173 return stat.S_IMODE(os.stat(p).st_mode)
174
175
176 def test_zip_preserves_executable_bit(tmp_path: Path) -> None:
177 archive = tmp_path / "skill.zip"
178 _make_zip_modes(
179 archive,
180 {
181 "scripts/run.sh": (b"#!/bin/sh\necho hi\n", 0o755),
182 "SKILL.md": (b"# doc", 0o644),
183 },
184 )
185 dest = tmp_path / "skills" / "x"
186 _extract_skill_archive(archive, dest)
187
188 exe = _mode(dest / "scripts" / "run.sh")
189 doc = _mode(dest / "SKILL.md")
190 assert exe & 0o111, "executable bit was dropped on zip extraction"
191 assert exe == 0o755
192 assert doc & 0o111 == 0
193 assert doc == 0o644
194
195
196 def test_zip_without_unix_attrs_is_not_executable(tmp_path: Path) -> None:
197 # `writestr` with a plain name records no Unix mode (external_attr == 0);
198 # the member must extract non-executable rather than inherit a random mode.
199 archive = tmp_path / "skill.zip"
200 _make_zip(archive, {"SKILL.md": b"# doc", "scripts/run.sh": b"echo hi"})
201 dest = tmp_path / "skills" / "x"
202 _extract_skill_archive(archive, dest)
203
204 assert _mode(dest / "SKILL.md") == 0o644
205 assert _mode(dest / "scripts" / "run.sh") == 0o644
206
207
208 def test_tar_preserves_executable_bit(tmp_path: Path) -> None:
209 archive = tmp_path / "skill.tar.gz"
210 _make_targz_modes(
211 archive,
212 {
213 "scripts/run.sh": (b"#!/bin/sh\necho hi\n", 0o755),
214 "SKILL.md": (b"# doc", 0o644),
215 },
216 )
217 dest = tmp_path / "skills" / "x"
218 _extract_skill_archive(archive, dest)
219
220 exe = _mode(dest / "scripts" / "run.sh")
221 doc = _mode(dest / "SKILL.md")
222 assert exe & 0o111, "executable bit was dropped on tar extraction"
223 assert exe == 0o755
224 assert doc & 0o111 == 0
225 assert doc == 0o644
226
227
228 @pytest.mark.parametrize("make", [_make_zip_modes, _make_targz_modes])
229 def test_extract_drops_setuid_setgid_sticky(make: ArchiveModeMaker, tmp_path: Path) -> None:
230 # setuid (0o4000) + setgid (0o2000) + sticky (0o1000) on an executable
231 # member must never survive extraction; the mode collapses to plain 0o755.
232 archive = tmp_path / "skill.archive"
233 make(
234 archive,
235 {
236 "scripts/run.sh": (b"#!/bin/sh\n", 0o7755),
237 "SKILL.md": (b"# doc", 0o4644),
238 },
239 )
240 dest = tmp_path / "skills" / "x"
241 _extract_skill_archive(archive, dest)
242
243 exe = _mode(dest / "scripts" / "run.sh")
244 doc = _mode(dest / "SKILL.md")
245 assert exe & 0o7000 == 0, "setuid/setgid/sticky leaked onto executable member"
246 assert exe == 0o755
247 # A non-executable member with setuid set must also drop the bit.
248 assert doc & 0o7000 == 0
249 assert doc == 0o644
250
251
252 def test_tar_special_members_are_skipped(tmp_path: Path) -> None:
253 archive = tmp_path / "skill.tar.gz"
254 _make_tar(
255 archive,
256 [
257 _tar_file("pdf/SKILL.md", b"# PDF"),
258 _tar_file("pdf/scripts/run.sh", b"#!/bin/sh\n", mode=0o755),
259 _tar_file("pdf/old", b"v7", type=tarfile.AREGTYPE),
260 _tar_special("pdf/abs", tarfile.SYMTYPE, "/etc/passwd"),
261 _tar_special("pdf/rel", tarfile.SYMTYPE, "SKILL.md"),
262 _tar_special("pdf/hl", tarfile.LNKTYPE, "pdf/SKILL.md"),
263 _tar_special("pdf/fifo", tarfile.FIFOTYPE),
264 _tar_special("pdf/dev", tarfile.CHRTYPE),
265 ],
266 )
267 dest = tmp_path / "skills" / "pdf"
268 _extract_skill_archive(archive, dest)
269
270 assert (dest / "SKILL.md").read_bytes() == b"# PDF"
271 assert (dest / "old").read_bytes() == b"v7"
272 assert _mode(dest / "scripts" / "run.sh") == 0o755
273 for name in ("abs", "rel", "hl", "fifo", "dev", "pdf"):
274 assert not os.path.lexists(dest / name), name
275 _assert_only_files_and_dirs(dest)
276 assert sorted(os.listdir(tmp_path)) == ["skill.tar.gz", "skills"]
277 assert os.listdir(tmp_path / "skills") == ["pdf"]
278
279
280 def test_zip_unix_special_entries_are_skipped_not_written_as_files(tmp_path: Path) -> None:
281 archive = tmp_path / "skill.zip"
282 _make_zip_infos(
283 archive,
284 [
285 (_zip_entry("pdf/SKILL.md", mode=0o644), b"# PDF"),
286 (_zip_entry("pdf/lnk", mode=stat.S_IFLNK | 0o777), b"/etc/passwd"),
287 (_zip_entry("pdf/fifo", mode=stat.S_IFIFO | 0o644), b""),
288 ],
289 )
290 dest = tmp_path / "skills" / "pdf"
291 _extract_skill_archive(archive, dest)
292
293 assert (dest / "SKILL.md").read_bytes() == b"# PDF"
294 assert not os.path.lexists(dest / "lnk")
295 assert not os.path.lexists(dest / "fifo")
296 _assert_only_files_and_dirs(dest)
297
298
299 def test_zip_non_unix_host_type_bits_are_plain_data(tmp_path: Path) -> None:
300 """Only a Unix creator host makes `external_attr` a mode; the same bits
301 from a FAT/NTFS archiver describe an ordinary file."""
302 archive = tmp_path / "skill.zip"
303 _make_zip_infos(
304 archive,
305 [
306 (_zip_entry("pdf/SKILL.md", mode=0o644, create_system=0), b"# PDF"),
307 (_zip_entry("pdf/lnk", mode=stat.S_IFLNK | 0o777, create_system=0), b"/etc/passwd"),
308 ],
309 )
310 dest = tmp_path / "skills" / "pdf"
311 _extract_skill_archive(archive, dest)
312
313 assert stat.S_ISREG(os.lstat(dest / "lnk").st_mode)
314 assert (dest / "lnk").read_bytes() == b"/etc/passwd"
315
316
317 def test_tar_top_level_special_does_not_defeat_wrapper_stripping(tmp_path: Path) -> None:
318 archive = tmp_path / "skill.tar.gz"
319 _make_tar(archive, [_tar_special("link", tarfile.SYMTYPE, "/tmp"), _tar_file("pdf/SKILL.md", b"# PDF")])
320 dest = tmp_path / "skills" / "pdf"
321 _extract_skill_archive(archive, dest)
322
323 assert (dest / "SKILL.md").read_bytes() == b"# PDF"
324 assert not (dest / "pdf").exists()
325 assert not os.path.lexists(dest / "link")
326
327
328 def test_tar_pax_global_header_is_not_extracted(tmp_path: Path) -> None:
329 """`git archive` tarballs start with a PAX global header; it is metadata,
330 not a member, and must neither appear on disk nor stop wrapper stripping."""
331 archive = tmp_path / "skill.tar"
332 with tarfile.open(archive, "w", format=tarfile.PAX_FORMAT, pax_headers={"comment": "0123abcd"}) as tf:
333 info, data = _tar_file("pdf/SKILL.md", b"# PDF")
334 tf.addfile(info, io.BytesIO(data))
335 dest = tmp_path / "skills" / "pdf"
336 _extract_skill_archive(archive, dest)
337
338 assert sorted(os.listdir(dest)) == ["SKILL.md"]
339
340
341 def test_zip_entries_without_type_bits_are_regular_files(tmp_path: Path) -> None:
342 archive = tmp_path / "skill.zip"
343 with zipfile.ZipFile(archive, "w") as zf:
344 zf.writestr(_zip_entry("pdf/scripts/run.sh", mode=0o755), b"#!/bin/sh\n")
345 zf.writestr("pdf/SKILL.md", b"# PDF")
346 dest = tmp_path / "skills" / "pdf"
347 _extract_skill_archive(archive, dest)
348
349 assert (dest / "SKILL.md").read_bytes() == b"# PDF"
350 assert _mode(dest / "scripts" / "run.sh") == 0o755
351
352
353 def test_zip_unix_directory_bits_without_trailing_slash_make_a_directory(tmp_path: Path) -> None:
354 archive = tmp_path / "skill.zip"
355 _make_zip_infos(
356 archive,
357 [
358 (_zip_entry("pdf/SKILL.md", mode=0o644), b"# PDF"),
359 (_zip_entry("pdf/sub", mode=stat.S_IFDIR | 0o755), b""),
360 ],
361 )
362 dest = tmp_path / "skills" / "pdf"
363 _extract_skill_archive(archive, dest)
364
365 assert (dest / "sub").is_dir()
366
367
368 def test_tar_path_screen_applies_to_skipped_members(tmp_path: Path) -> None:
369 """A member that would be skipped for its type is still subject to the
370 path-traversal screen, so the archive is refused as a whole."""
371 archive = tmp_path / "sub" / "skill.tar.gz"
372 archive.parent.mkdir()
373 _make_tar(archive, [_tar_special("../x", tarfile.SYMTYPE, "/etc/passwd"), _tar_file("pdf/SKILL.md", b"# PDF")])
374 dest = tmp_path / "sub" / "skills" / "pdf"
375 with pytest.raises(ValueError):
376 _extract_skill_archive(archive, dest)
377 assert not (dest / "SKILL.md").exists()
378 assert not os.path.lexists(dest.parent / "x")
379 assert not os.path.lexists(tmp_path / "sub" / "x")
380 assert not os.path.lexists(tmp_path / "x")
381
382
383 class _FakeVersions:
384 """Records the version each endpoint was addressed by; `download` streams a real archive."""
385
386 def __init__(self, archive: Path) -> None:
387 self.retrieves: list[str] = []
388 self.downloads: list[str] = []
389 self.with_streaming_response = SimpleNamespace(download=self._download)
390 self._archive = archive
391
392 async def retrieve(self, version: str, *, skill_id: str) -> Any:
393 self.retrieves.append(f"{skill_id}@{version}")
394 return SimpleNamespace(id="skillver_123", name="pdf")
395
396 @asynccontextmanager
397 async def _download(self, version: str, *, skill_id: str) -> AsyncIterator[Any]:
398 self.downloads.append(f"{skill_id}@{version}")
399 archive = self._archive
400
401 async def stream_to_file(dest: str) -> None:
402 Path(dest).write_bytes(archive.read_bytes())
403
404 yield SimpleNamespace(stream_to_file=stream_to_file)
405
406
407 async def test_download_retrieves_by_configured_version_and_downloads_by_returned_id(tmp_path: Path) -> None:
408 archive = tmp_path / "skill.tar.gz"
409 _make_targz(archive, {"pdf/SKILL.md": b"# PDF"})
410 versions = _FakeVersions(archive)
411 client = cast(Any, SimpleNamespace(beta=SimpleNamespace(skills=SimpleNamespace(versions=versions))))
412 session = cast(
413 Any, SimpleNamespace(agent=SimpleNamespace(skills=[SimpleNamespace(skill_id="skill_01", version="latest")]))
414 )
415 work = tmp_path / "work"
416 work.mkdir()
417 created = await download_session_skills(client, workdir=work, session=session)
418 assert versions.retrieves == ["skill_01@latest"]
419 assert versions.downloads == ["skill_01@skillver_123"]
420 assert created == [(work / "skills" / "pdf").resolve()]
421 assert (work / "skills" / "pdf" / "SKILL.md").read_text() == "# PDF"