Debian Codegraph @

tests/lib/tools/test_file_store.py

raw
1 """Tests for `FileStore` — the confined-folder filesystem layer.
2
3 The verbs (`put` / `get` / `ls` / `find_symlinks` / `hashtree` /
4 `hash_file` / `move` / `remove`) plus the open and `async with`
5 lifecycle. These tests exercise the filesystem directly; consumers (memory
6 sync, the skills downloader, the builtin memory tool) get their own suites.
7 """
8
9 from __future__ import annotations
10
11 import io
12 import os
13 import stat
14 import shutil
15 import hashlib
16 import zipfile
17 from pathlib import Path
18
19 import pytest
20 import pytest_asyncio
21
22 from anthropic.lib.tools._file_store import Root, FileStore, FileStoreError, LocalFileStore
23
24 pytestmark = pytest.mark.skipif(os.name != "posix", reason="FileStore refuses non-POSIX platforms")
25
26
27 def _sha(content: str | bytes) -> str:
28 return hashlib.sha256(content.encode("utf-8") if isinstance(content, str) else content).hexdigest()
29
30
31 async def _created_store(root: Path, *, utf8_only: bool = False) -> FileStore:
32 fs = await FileStore.open(root, utf8_only=utf8_only)
33 await fs.create_root()
34 return fs
35
36
37 @pytest_asyncio.fixture()
38 async def store(tmp_path: Path) -> FileStore:
39 return await _created_store(tmp_path / "store")
40
41
42 def test_localfilestore_is_an_alias_for_the_combined_class() -> None:
43 assert LocalFileStore is FileStore
44
45
46 @pytest.mark.asyncio()
47 async def test_filestore_put_writes_text_and_creates_owner_only_parents(store: FileStore) -> None:
48 """`put` creates nested parents 0o700 and stores text as UTF-8 (file 0o600)."""
49 await store.put("projects/foo/notes.md", "héllo")
50
51 dest = store.root().path / "projects" / "foo" / "notes.md"
52 assert dest.read_text(encoding="utf-8") == "héllo"
53 assert stat.S_IMODE(dest.parent.stat().st_mode) == 0o700
54 assert stat.S_IMODE(dest.stat().st_mode) == 0o600
55
56
57 @pytest.mark.asyncio()
58 async def test_filestore_put_executable_sets_owner_exec(store: FileStore) -> None:
59 await store.put("run.sh", b"#!/bin/sh\necho hi\n", is_executable=True)
60 assert stat.S_IMODE((store.root().path / "run.sh").stat().st_mode) == 0o700
61
62
63 @pytest.mark.asyncio()
64 async def test_filestore_put_is_atomic_and_leaves_no_temp_on_success(store: FileStore) -> None:
65 await store.put("a.md", "first")
66 await store.put("a.md", "second") # overwrite
67 assert (store.root().path / "a.md").read_text() == "second"
68 assert sorted(p.name for p in store.root().path.iterdir()) == ["a.md"]
69
70
71 @pytest.mark.asyncio()
72 async def test_filestore_creates_every_parent_owner_only_under_permissive_umask(tmp_path: Path) -> None:
73 """Every directory the store creates — including intermediate parents, which
74 `mkdir(parents=True, mode=...)` would leave at the umask default — is 0o700."""
75 old_umask = os.umask(0)
76 try:
77 root = tmp_path / "nested" / "store"
78 fs = await _created_store(root)
79 await fs.put("projects/foo/notes.md", "hi")
80 for directory in (tmp_path / "nested", root, root / "projects", root / "projects" / "foo"):
81 assert stat.S_IMODE(directory.stat().st_mode) == 0o700, directory
82 finally:
83 os.umask(old_umask)
84
85
86 @pytest.mark.asyncio()
87 @pytest.mark.parametrize("bad", ["../secret.md", "a/../../secret.md"])
88 async def test_filestore_every_verb_refuses_an_escaping_path(tmp_path: Path, store: FileStore, bad: str) -> None:
89 """`..` (and absolute) paths raise FileStoreError on every verb; nothing
90 is read or written outside the root."""
91 (tmp_path / "secret.md").write_text("top secret")
92 await store.put("ok.md", "ok")
93
94 with pytest.raises(FileStoreError):
95 await store.put(bad, "nope")
96 with pytest.raises(FileStoreError):
97 await store.get(bad)
98 with pytest.raises(FileStoreError):
99 await store.ls(bad)
100 with pytest.raises(FileStoreError):
101 await store.hashtree(bad)
102 with pytest.raises(FileStoreError):
103 await store.hash_file(bad)
104 with pytest.raises(FileStoreError):
105 await store.find_symlinks(bad)
106 with pytest.raises(FileStoreError):
107 await store.move("ok.md", bad)
108 with pytest.raises(FileStoreError):
109 await store.move(bad, "landed.md")
110 with pytest.raises(FileStoreError):
111 await store.remove(bad)
112
113 assert (tmp_path / "secret.md").read_text() == "top secret"
114
115
116 @pytest.mark.asyncio()
117 async def test_filestore_get_does_not_follow_a_symlink_leaf(store: FileStore) -> None:
118 """A symlink at the target is refused on read and replaced — not written
119 through — on put."""
120 await store.put("real.md", "original")
121 os.symlink(store.root().path / "real.md", store.root().path / "link.md")
122
123 with pytest.raises(FileStoreError):
124 await store.get("link.md")
125 await store.put("link.md", "new")
126 assert (store.root().path / "real.md").read_text() == "original"
127 assert not (store.root().path / "link.md").is_symlink()
128 assert (store.root().path / "link.md").read_text() == "new"
129
130
131 @pytest.mark.asyncio()
132 async def test_filestore_get_refuses_a_non_regular_file(store: FileStore) -> None:
133 """A present-but-non-regular leaf (fifo, symlink, ...) raises FileStoreError
134 instead of hanging or being read."""
135 os.mkfifo(store.root().path / "pipe.md")
136 os.symlink(store.root().path / "pipe.md", store.root().path / "link.md")
137
138 with pytest.raises(FileStoreError, match="not a regular file"):
139 await store.get("pipe.md")
140 with pytest.raises(FileStoreError, match="is a symlink"):
141 await store.get("link.md")
142
143 # The open itself must refuse the fifo (O_NONBLOCK + fstat) — it must not
144 # block the read forever.
145 from anthropic.lib.tools import _file_store as mod
146
147 with pytest.raises(FileStoreError, match="not a regular file"):
148 mod._open_regular_file("pipe.md", store.root().path / "pipe.md")
149
150
151 @pytest.mark.asyncio()
152 async def test_filestore_get_returns_none_when_absent(store: FileStore) -> None:
153 assert await store.get("absent.md") is None
154 await store.put("present.md", "here")
155 assert await store.get("present.md") == b"here"
156
157
158 @pytest.mark.asyncio()
159 async def test_filestore_ls_lists_recursively_and_never_descends_symlinks(tmp_path: Path, store: FileStore) -> None:
160 await store.put("a.md", "alpha")
161 await store.put("sub/b.md", "bravo")
162 outside = tmp_path / "outside"
163 outside.mkdir()
164 (outside / "s.md").write_text("secret")
165 os.symlink(outside, store.root().path / "lnkdir")
166 os.symlink(outside / "s.md", store.root().path / "lnk.md")
167
168 assert await store.ls() == {"a.md", "sub/b.md"}
169 assert await store.ls("sub") == {"sub/b.md"}
170 assert await store.ls("absent") == set()
171 assert await store.ls("a.md/under") == set()
172 with pytest.raises(FileStoreError, match="not a directory"):
173 await store.ls("a.md")
174
175
176 @pytest.mark.asyncio()
177 async def test_filestore_find_symlinks_reports_every_symlink(tmp_path: Path, store: FileStore) -> None:
178 """Listings skip symlinks silently; `find_symlinks` is how a caller sees them."""
179 await store.put("a.md", "alpha")
180 await store.put("sub/b.md", "bravo")
181 assert await store.find_symlinks() == set()
182
183 outside = tmp_path / "outside"
184 outside.mkdir()
185 (outside / "s.md").write_text("secret")
186 os.symlink(outside, store.root().path / "lnkdir")
187 os.symlink(outside / "s.md", store.root().path / "sub" / "lnk.md")
188 os.symlink(store.root().path / "gone.md", store.root().path / "dangling.md")
189
190 assert await store.find_symlinks() == {"lnkdir", "sub/lnk.md", "dangling.md"}
191 assert await store.find_symlinks("sub") == {"sub/lnk.md"}
192 assert await store.find_symlinks("absent") == set()
193
194
195 @pytest.mark.asyncio()
196 async def test_filestore_hashtree_hashes_regular_files_and_skips_symlinks(tmp_path: Path, store: FileStore) -> None:
197 await store.put("a.md", "alpha")
198 await store.put("sub/b.md", "bravo")
199 outside = tmp_path / "secret.txt"
200 outside.write_text("secret")
201 os.symlink(outside, store.root().path / "link.md")
202
203 assert await store.hashtree() == {"a.md": _sha("alpha"), "sub/b.md": _sha("bravo")}
204 assert await store.hashtree("sub/") == {"sub/b.md": _sha("bravo")}
205
206
207 @pytest.mark.skipif(os.geteuid() == 0, reason="permission checks do not bind root")
208 @pytest.mark.asyncio()
209 async def test_filestore_listings_raise_on_an_unreadable_subdirectory(store: FileStore) -> None:
210 """An unreadable subdirectory fails the listing rather than dropping out of it."""
211 await store.put("a.md", "alpha")
212 await store.put("locked/b.md", "bravo")
213 locked = store.root().path / "locked"
214 locked.chmod(0o000)
215 try:
216 with pytest.raises(PermissionError):
217 await store.hashtree()
218 with pytest.raises(PermissionError):
219 await store.ls()
220 with pytest.raises(PermissionError):
221 await store.find_symlinks()
222 finally:
223 locked.chmod(0o700)
224 assert await store.hashtree() == {"a.md": _sha("alpha"), "locked/b.md": _sha("bravo")}
225
226
227 @pytest.mark.asyncio()
228 async def test_filestore_hashtree_refuses_a_symlinked_prefix(tmp_path: Path, store: FileStore) -> None:
229 """A prefix that is a symlink (here to a directory outside the root) is
230 refused, not silently listed as empty."""
231 outside = tmp_path / "outside"
232 outside.mkdir()
233 (outside / "secret.md").write_text("secret")
234 os.symlink(outside, store.root().path / "sub")
235
236 with pytest.raises(FileStoreError):
237 await store.hashtree("sub")
238
239
240 @pytest.mark.asyncio()
241 async def test_filestore_hash_file_hashes_one_file_and_shares_the_cache(
242 store: FileStore, monkeypatch: pytest.MonkeyPatch
243 ) -> None:
244 from anthropic.lib.tools import _file_store as mod
245
246 monkeypatch.setattr(mod, "_TIMESTAMP_TRUST_MARGIN_NS", -(10**15))
247 hashed: list[str] = []
248 real_hash = mod._hash_file
249
250 def counting_hash(path: Path) -> str:
251 hashed.append(path.name)
252 return real_hash(path)
253
254 monkeypatch.setattr(mod, "_hash_file", counting_hash)
255
256 await store.put("a.md", "alpha")
257 assert await store.hash_file("a.md") == _sha("alpha")
258 assert await store.hash_file("absent.md") is None
259 # hashtree reuses the entry hash_file just cached.
260 assert await store.hashtree() == {"a.md": _sha("alpha")}
261 assert hashed == ["a.md"]
262
263 os.symlink(store.root().path / "a.md", store.root().path / "lnk.md")
264 with pytest.raises(FileStoreError, match="is a symlink"):
265 await store.hash_file("lnk.md")
266
267
268 @pytest.mark.asyncio()
269 async def test_filestore_move_renames_within_root_and_refuses_existing_dest(store: FileStore) -> None:
270 await store.put("a.md", "alpha")
271 await store.move("a.md", "nested/b.md")
272 assert await store.get("nested/b.md") == b"alpha"
273 assert await store.get("a.md") is None
274
275 await store.put("c.md", "charlie")
276 with pytest.raises(FileStoreError, match="exists"):
277 await store.move("nested/b.md", "c.md")
278
279
280 @pytest.mark.asyncio()
281 async def test_filestore_root_path_is_banned_from_the_interface(store: FileStore) -> None:
282 """A rel_path resolving to the root: put/get refuse, move/remove do nothing."""
283 await store.put("x.md", "x")
284
285 await store.remove("/") # no-op
286 assert await store.get("x.md") == b"x"
287 await store.move("/", "elsewhere") # no-op
288 await store.move("x.md", "/") # no-op
289 assert await store.ls() == {"x.md"}
290
291 with pytest.raises(FileStoreError):
292 await store.put("/", "data")
293 with pytest.raises(FileStoreError, match="not a regular file"):
294 await store.get("/")
295
296
297 @pytest.mark.asyncio()
298 async def test_filestore_remove_deletes_file_and_subtree(store: FileStore) -> None:
299 await store.put("a.md", "a")
300 await store.put("sub/b.md", "b")
301
302 await store.remove("a.md")
303 assert not (store.root().path / "a.md").exists()
304 await store.remove("sub")
305 assert not (store.root().path / "sub").exists()
306 await store.remove("absent.md") # no-op
307
308
309 @pytest.mark.asyncio()
310 async def test_filestore_remove_unlinks_a_dangling_symlink(store: FileStore) -> None:
311 os.symlink(store.root().path / "gone.md", store.root().path / "dangling.md")
312
313 await store.remove("dangling.md")
314 assert not (store.root().path / "dangling.md").is_symlink()
315
316
317 @pytest.mark.skipif(os.geteuid() == 0, reason="permission checks do not bind root")
318 @pytest.mark.asyncio()
319 async def test_filestore_open_raises_on_an_unreadable_mount_path(tmp_path: Path) -> None:
320 """A mount path the process cannot stat raises at open — it is never read
321 as absent, which would mark a real directory ours to remove on dispose."""
322 locked = tmp_path / "locked"
323 (locked / "store").mkdir(parents=True)
324 locked.chmod(0o000)
325 try:
326 with pytest.raises(PermissionError):
327 await FileStore.open(locked / "store")
328 finally:
329 locked.chmod(0o700)
330
331
332 @pytest.mark.asyncio()
333 async def test_filestore_async_with_removes_root_only_if_created(tmp_path: Path) -> None:
334 async with await _created_store(tmp_path / "fresh") as fs:
335 await fs.put("x.md", "x")
336 assert fs.root() == Root(path=(tmp_path / "fresh").resolve(), removed_on_dispose=True)
337 assert not (tmp_path / "fresh").exists()
338
339 (tmp_path / "old").mkdir()
340 async with await FileStore.open(tmp_path / "old") as fs:
341 await fs.put("y.md", "y")
342 assert not fs.root().removed_on_dispose
343 assert (tmp_path / "old" / "y.md").read_text() == "y"
344
345
346 @pytest.mark.asyncio()
347 async def test_filestore_dispose_removes_the_root_it_created_and_keeps_preexisting(tmp_path: Path) -> None:
348 fresh = await _created_store(tmp_path / "fresh")
349 await fresh.put("x.md", "x")
350 await fresh.dispose()
351 assert not (tmp_path / "fresh").exists()
352
353 (tmp_path / "old").mkdir()
354 old = await FileStore.open(tmp_path / "old")
355 await old.put("y.md", "y")
356 await old.dispose()
357 assert (tmp_path / "old" / "y.md").read_text() == "y"
358
359
360 @pytest.mark.asyncio()
361 async def test_filestore_put_writes_archive_bytes_verbatim(store: FileStore) -> None:
362 """Archive-shaped bytes land as a single byte-identical file — extraction
363 is never inferred from the content."""
364 bio = io.BytesIO()
365 with zipfile.ZipFile(bio, "w") as zf:
366 zf.writestr(zipfile.ZipInfo("pdf/SKILL.md"), b"# pdf")
367 blob = bio.getvalue()
368
369 await store.put("bundle.zip", blob)
370 assert await store.get("bundle.zip") == blob
371 assert await store.hashtree() == {"bundle.zip": _sha(blob)}
372
373
374 @pytest.mark.asyncio()
375 @pytest.mark.parametrize("bad", ["bundles/v1/", "dir/.", ".", "/", ""])
376 async def test_filestore_put_refuses_a_directory_rel(store: FileStore, bad: str) -> None:
377 with pytest.raises(FileStoreError):
378 await store.put(bad, b"data")
379 assert await store.hashtree() == {}
380
381
382 @pytest.mark.asyncio()
383 async def test_filestore_utf8_restriction_refuses_binary_content(tmp_path: Path) -> None:
384 """A store opened with `utf8_only=True` refuses binary content on both
385 verbs that touch it: a put of invalid bytes writes nothing, and a get of a
386 file that bypassed the store (written directly to disk) is refused rather
387 than returned — so callers that decode get's result can never throw."""
388 store = await _created_store(tmp_path / "store", utf8_only=True)
389 binary = b"\xff\xfe\x00 not utf-8"
390
391 with pytest.raises(FileStoreError, match="not valid utf-8"):
392 await store.put("blob.bin", binary)
393 assert not (tmp_path / "store" / "blob.bin").exists()
394
395 # str puts and conforming bytes are unaffected.
396 await store.put("note.md", "hello")
397 await store.put("bytes.md", "hello".encode())
398 assert await store.get("note.md") == b"hello"
399
400 # A file smuggled in behind the store's back is refused at get.
401 (tmp_path / "store" / "smuggled.bin").write_bytes(binary)
402 with pytest.raises(FileStoreError, match="not valid utf-8"):
403 await store.get("smuggled.bin")
404
405 # An unrestricted store keeps returning raw bytes.
406 loose = await _created_store(tmp_path / "store2")
407 await loose.put("blob.bin", binary)
408 assert await loose.get("blob.bin") == binary
409
410
411 def test_filestore_is_path_legal() -> None:
412 assert FileStore.is_path_legal("/mnt/memory/notes")
413 assert not FileStore.is_path_legal("mnt/relative")
414 assert not FileStore.is_path_legal("/mnt/../../etc/cron.d")
415 assert not FileStore.is_path_legal("")
416
417
418 @pytest.mark.asyncio()
419 async def test_filestore_hashtree_rehashes_only_what_changed(store: FileStore, monkeypatch: pytest.MonkeyPatch) -> None:
420 """A file whose stat identity (mtime, ctime, size) is unchanged since the
421 last walk is served from the cache; a changed file is re-read. The trust
422 margin is disabled here so fresh files cache immediately; a writer that
423 restores mtime and size (`rsync -t` style) is still re-hashed, because
424 userspace cannot restore ctime."""
425 from anthropic.lib.tools import _file_store as mod
426
427 monkeypatch.setattr(mod, "_TIMESTAMP_TRUST_MARGIN_NS", -(10**15))
428 hashed: list[str] = []
429 real_hash = mod._hash_file
430
431 def counting_hash(path: Path) -> str:
432 hashed.append(path.name)
433 return real_hash(path)
434
435 monkeypatch.setattr(mod, "_hash_file", counting_hash)
436
437 await store.put("a.md", "alpha")
438 await store.put("b.md", "bravo")
439 assert await store.hashtree() == {"a.md": _sha("alpha"), "b.md": _sha("bravo")}
440 assert sorted(hashed) == ["a.md", "b.md"]
441
442 hashed.clear()
443 assert await store.hashtree() == {"a.md": _sha("alpha"), "b.md": _sha("bravo")}
444 assert hashed == []
445
446 # An mtime-and-size-preserving rewrite: same length, mtime restored. The
447 # sleep guarantees the rewrite's ctime lands on a later coarse-clock tick
448 # than the original's — ctime is the one stamp the rewrite cannot restore.
449 import time as time_mod
450
451 time_mod.sleep(0.05)
452 b = store.root().path / "b.md"
453 st = b.stat()
454 b.write_text("BRAVO")
455 os.utime(b, ns=(st.st_atime_ns, st.st_mtime_ns))
456 assert (await store.hashtree())["b.md"] == _sha("BRAVO")
457 assert hashed == ["b.md"]
458
459
460 @pytest.mark.asyncio()
461 async def test_filestore_hashtree_distrusts_fresh_stamps(store: FileStore, monkeypatch: pytest.MonkeyPatch) -> None:
462 """Filesystems stamp times with coarse clocks, so a same-tick rewrite can
463 reuse the exact stat identity of the version just hashed. A file whose
464 stamps are within the trust margin of the walk is never cached — pinned
465 by freezing the walk clock at the file's own stamp time."""
466 from anthropic.lib.tools import _file_store as mod
467
468 hashed: list[str] = []
469 real_hash = mod._hash_file
470
471 def counting_hash(path: Path) -> str:
472 hashed.append(path.name)
473 return real_hash(path)
474
475 monkeypatch.setattr(mod, "_hash_file", counting_hash)
476
477 await store.put("racy.md", "AAAAAA")
478 stamp = (store.root().path / "racy.md").stat().st_ctime_ns
479 monkeypatch.setattr(mod, "_now_ns", lambda: stamp)
480
481 assert (await store.hashtree())["racy.md"] == _sha("AAAAAA")
482 assert (await store.hashtree())["racy.md"] == _sha("AAAAAA")
483 # Both walks hashed: nothing this fresh is ever cached.
484 assert hashed == ["racy.md", "racy.md"]
485
486 # What the margin defends: a same-tick rewrite that preserves the whole
487 # stat identity must be seen by the next walk.
488 (store.root().path / "racy.md").write_text("BBBBBB")
489 assert (await store.hashtree())["racy.md"] == _sha("BBBBBB")
490
491 # The margin's width is part of the contract: stamps 1.5s old are still
492 # distrusted (coarse filesystems stamp in whole seconds); 10s-old stamps
493 # are safely past it.
494 hashed.clear()
495 now = (store.root().path / "racy.md").stat().st_ctime_ns
496 monkeypatch.setattr(mod, "_now_ns", lambda: now + 1_500_000_000)
497 await store.hashtree()
498 await store.hashtree()
499 assert hashed == ["racy.md", "racy.md"]
500 monkeypatch.setattr(mod, "_now_ns", lambda: now + 10_000_000_000)
501 await store.hashtree()
502 await store.hashtree()
503 assert hashed == ["racy.md"] * 3
504
505
506 @pytest.mark.asyncio()
507 async def test_filestore_create_root_makes_the_folder_owner_only(tmp_path: Path) -> None:
508 store = await FileStore.open(tmp_path / "store")
509 await store.create_root()
510 assert stat.S_IMODE((tmp_path / "store").stat().st_mode) == 0o700
511 await store.create_root() # already existing is fine
512 assert store.root().removed_on_dispose
513
514
515 @pytest.mark.asyncio()
516 async def test_filestore_put_never_creates_a_missing_root(tmp_path: Path) -> None:
517 """Only create_root() makes the folder: a put into a store that was never
518 created, or whose folder was removed, raises and re-creates nothing — not
519 the root and nothing above it."""
520 root = tmp_path / "mnt" / "store"
521 fs = await FileStore.open(root)
522
523 with pytest.raises(FileNotFoundError):
524 await fs.put("a.md", "a")
525 with pytest.raises(FileNotFoundError):
526 await fs.put("sub/a.md", "a")
527 assert not (tmp_path / "mnt").exists()
528
529 await fs.create_root()
530 await fs.put("a.md", "a")
531 shutil.rmtree(root)
532 with pytest.raises(FileNotFoundError):
533 await fs.put("b.md", "b")
534 with pytest.raises(FileNotFoundError):
535 await fs.put("sub/b.md", "b")
536 assert not root.exists()
537
538 shutil.rmtree(tmp_path / "mnt")
539 with pytest.raises(FileNotFoundError):
540 await fs.put("z.md", "z")
541 assert not (tmp_path / "mnt").exists()
542
543 await fs.create_root()
544 await fs.put("z.md", "z")
545 assert await fs.get("z.md") == b"z"
546
547
548 @pytest.mark.asyncio()
549 async def test_filestore_move_never_creates_a_missing_root(store: FileStore) -> None:
550 await store.put("a.md", "a")
551 shutil.rmtree(store.root().path)
552
553 with pytest.raises(FileNotFoundError):
554 await store.move("a.md", "sub/b.md")
555 assert not store.root().path.exists()