| 1 |
"""`FileStore` — one confined folder; a relative path cannot escape it. |
| 2 |
|
| 3 |
Beta scope: symlinks are refused or skipped wherever the store meets them, but |
| 4 |
there is no hardening against a process racing the store's own syscalls; |
| 5 |
fsync durability, non-POSIX hosts, and read-size caps are out of scope. |
| 6 |
""" |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import os |
| 11 |
import stat |
| 12 |
import time |
| 13 |
import errno |
| 14 |
import shutil |
| 15 |
import hashlib |
| 16 |
from typing import IO, Union, NamedTuple |
| 17 |
from pathlib import Path, PurePosixPath |
| 18 |
from contextlib import suppress |
| 19 |
|
| 20 |
import anyio |
| 21 |
from anyio.to_thread import run_sync |
| 22 |
|
| 23 |
__all__ = ["FileStore", "LocalFileStore", "FileStoreError", "Root"] |
| 24 |
|
| 25 |
PutData = Union[str, bytes] |
| 26 |
|
| 27 |
_OWNER_ONLY_DIR_MODE = 0o700 |
| 28 |
_OWNER_ONLY_FILE_MODE = 0o600 |
| 29 |
_OWNER_ONLY_EXEC_MODE = 0o700 |
| 30 |
|
| 31 |
# 0 where the platform lacks them; `open` refuses such platforms. |
| 32 |
_O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0) |
| 33 |
_O_NONBLOCK = getattr(os, "O_NONBLOCK", 0) |
| 34 |
|
| 35 |
|
| 36 |
class FileStoreError(Exception): |
| 37 |
"""A refused operation — input the store will not act on. OS errors propagate as `OSError`.""" |
| 38 |
|
| 39 |
ESCAPES_ROOT = "escapes the store root" |
| 40 |
IS_A_SYMLINK = "is a symlink" |
| 41 |
NOT_A_FILE = "is not a regular file" |
| 42 |
NOT_A_DIRECTORY = "is not a directory" |
| 43 |
NOT_UTF8 = "is not valid utf-8" |
| 44 |
MOVE_DESTINATION_EXISTS = "already exists" |
| 45 |
|
| 46 |
def __init__(self, reason: str, rel_path: str) -> None: |
| 47 |
super().__init__(f"path {rel_path!r} {reason}") |
| 48 |
self.reason = reason |
| 49 |
self.rel_path = rel_path |
| 50 |
|
| 51 |
|
| 52 |
class Root(NamedTuple): |
| 53 |
"""The store's resolved root, and what `FileStore.dispose` will do to it.""" |
| 54 |
|
| 55 |
path: Path |
| 56 |
#: True when `open` found no root, so `dispose` removes it. A root that |
| 57 |
#: was already there is someone else's — a pre-seeded mount, a caller's |
| 58 |
#: workdir — and is kept. |
| 59 |
removed_on_dispose: bool |
| 60 |
|
| 61 |
|
| 62 |
class _Hashed(NamedTuple): |
| 63 |
mtime_ns: int |
| 64 |
#: userspace cannot set ctime, so writers that preserve mtimes |
| 65 |
#: (`rsync -t`, `cp -p`) still miss the cache. |
| 66 |
ctime_ns: int |
| 67 |
size: int |
| 68 |
sha: str |
| 69 |
|
| 70 |
|
| 71 |
class FileStore: |
| 72 |
"""One confined folder of regular files. |
| 73 |
|
| 74 |
Every `rel_path` is relative to the root (a leading `/` also means the |
| 75 |
root) and refused with `FileStoreError` when it escapes. The store |
| 76 |
holds regular files only: symlinks are refused on read and skipped by |
| 77 |
listings — `find_symlinks` reports them. A `rel_path` resolving to |
| 78 |
the root itself is banned by this interface: `put` and `get` refuse it, |
| 79 |
`move` and `remove` do nothing. A store opened with `utf8_only=True` |
| 80 |
refuses binary content the same way — on `put` of such bytes and on |
| 81 |
`get` of such a file. Only `create_root` makes the root: writes |
| 82 |
create directories below it, never the root itself, so a root removed |
| 83 |
while the store is open stays removed and the write raises |
| 84 |
`FileNotFoundError`. |
| 85 |
""" |
| 86 |
|
| 87 |
def __init__(self, root: Path, removed_on_dispose: bool, utf8_only: bool = False) -> None: |
| 88 |
self._root = root |
| 89 |
self._removed_on_dispose = removed_on_dispose |
| 90 |
self._utf8_only = utf8_only |
| 91 |
self._hashes: dict[str, _Hashed] = {} |
| 92 |
|
| 93 |
@staticmethod |
| 94 |
def is_path_legal(path: str) -> bool: |
| 95 |
"""True for a path usable verbatim as a store location: absolute, no `..`.""" |
| 96 |
p = PurePosixPath(path) |
| 97 |
return p.is_absolute() and ".." not in p.parts |
| 98 |
|
| 99 |
@classmethod |
| 100 |
async def open(cls, root: str | os.PathLike[str], *, utf8_only: bool = False) -> FileStore: |
| 101 |
"""Resolve `root`; creates nothing — only `create_root` makes the folder.""" |
| 102 |
if not _platform_supported(): |
| 103 |
raise RuntimeError("FileStore requires O_NOFOLLOW support on this platform") |
| 104 |
adir = anyio.Path(root) |
| 105 |
# lstat, not exists(): exists() follows symlinks and swallows permission |
| 106 |
# errors — either would mark a real directory ours to delete on dispose. |
| 107 |
try: |
| 108 |
await adir.lstat() |
| 109 |
except FileNotFoundError: |
| 110 |
removed_on_dispose = True |
| 111 |
else: |
| 112 |
removed_on_dispose = False |
| 113 |
return cls(root=Path(await adir.resolve()), removed_on_dispose=removed_on_dispose, utf8_only=utf8_only) |
| 114 |
|
| 115 |
async def create_root(self) -> None: |
| 116 |
"""Create the root directory and any missing ancestors; already existing is fine.""" |
| 117 |
await run_sync(_make_dir_and_ancestors, self._root) |
| 118 |
|
| 119 |
def root(self) -> Root: |
| 120 |
return Root(path=self._root, removed_on_dispose=self._removed_on_dispose) |
| 121 |
|
| 122 |
async def dispose(self) -> None: |
| 123 |
"""Remove the root iff `open` created it; pre-existing roots are kept.""" |
| 124 |
if not self._removed_on_dispose: |
| 125 |
return |
| 126 |
with suppress(FileNotFoundError): |
| 127 |
await run_sync(shutil.rmtree, self._root) |
| 128 |
|
| 129 |
async def __aenter__(self) -> FileStore: |
| 130 |
return self |
| 131 |
|
| 132 |
async def __aexit__(self, *exc: object) -> None: |
| 133 |
await self.dispose() |
| 134 |
|
| 135 |
async def put(self, rel_path: str, data: PutData, *, is_executable: bool = False) -> None: |
| 136 |
"""Write `str` (UTF-8) or `bytes` atomically to the file at `rel_path`. |
| 137 |
|
| 138 |
Missing directories below the root are created; a missing root is not — |
| 139 |
the write raises `FileNotFoundError`. |
| 140 |
""" |
| 141 |
# "dir/." names a directory just like a trailing "/". |
| 142 |
tail = rel_path.replace("\\", "/") |
| 143 |
if tail.endswith(("/", "/.")) or tail in ("", "."): |
| 144 |
raise FileStoreError(FileStoreError.NOT_A_FILE, rel_path) |
| 145 |
dest = self._resolve_under_root(rel_path) |
| 146 |
payload = data.encode("utf-8") if isinstance(data, str) else bytes(data) |
| 147 |
self._require_utf8(rel_path, payload) |
| 148 |
await run_sync(_make_dirs_below_root, self._root, dest.parent) |
| 149 |
await run_sync(_replace_via_temp, dest, payload, is_executable) |
| 150 |
|
| 151 |
async def get(self, rel_path: str) -> bytes | None: |
| 152 |
"""The file's bytes; `None` when absent.""" |
| 153 |
dest = self._resolve_under_root(rel_path) |
| 154 |
|
| 155 |
def read() -> bytes | None: |
| 156 |
try: |
| 157 |
f = _open_regular_file(rel_path, dest) |
| 158 |
except FileNotFoundError: |
| 159 |
return None |
| 160 |
with f: |
| 161 |
return f.read() |
| 162 |
|
| 163 |
data = await run_sync(read) |
| 164 |
if data is None: |
| 165 |
return None |
| 166 |
self._require_utf8(rel_path, data) |
| 167 |
return data |
| 168 |
|
| 169 |
async def ls(self, under: str = "/") -> set[str]: |
| 170 |
"""The relative path of every file under the directory `under`.""" |
| 171 |
base = self._resolve_under_root(under) |
| 172 |
|
| 173 |
def walk() -> set[str]: |
| 174 |
return {rel for rel, _ in _filenames_in_dir(self._root, under, base)} |
| 175 |
|
| 176 |
return await run_sync(walk) |
| 177 |
|
| 178 |
async def find_symlinks(self, under: str = "/") -> set[str]: |
| 179 |
"""Every symlink under `under` — listings skip them and reads refuse |
| 180 |
them, so a caller that must know they exist asks here.""" |
| 181 |
base = self._resolve_under_root(under) |
| 182 |
return await run_sync(_symlinks_in_dir, self._root, under, base) |
| 183 |
|
| 184 |
async def hashtree(self, under: str = "/") -> dict[str, str]: |
| 185 |
"""`{rel_path: sha256_hex}` of every file under the directory `under`. |
| 186 |
|
| 187 |
Unchanged files — same size, mtime, and ctime since the last call — |
| 188 |
reuse their recorded hash instead of being re-read. |
| 189 |
""" |
| 190 |
base = self._resolve_under_root(under) |
| 191 |
|
| 192 |
def hash_all() -> dict[str, str]: |
| 193 |
walk_start_ns = _now_ns() |
| 194 |
out: dict[str, str] = {} |
| 195 |
for rel, full in _filenames_in_dir(self._root, under, base): |
| 196 |
sha = self._hash_via_cache(rel, full, walk_start_ns) |
| 197 |
if sha is not None: |
| 198 |
out[rel] = sha |
| 199 |
return out |
| 200 |
|
| 201 |
return await run_sync(hash_all) |
| 202 |
|
| 203 |
async def hash_file(self, rel_path: str) -> str | None: |
| 204 |
"""One file's sha256; `None` when absent. Shares `hashtree`'s cache.""" |
| 205 |
dest = self._resolve_under_root(rel_path) |
| 206 |
|
| 207 |
def one() -> str | None: |
| 208 |
try: |
| 209 |
st = dest.lstat() |
| 210 |
except FileNotFoundError: |
| 211 |
return None |
| 212 |
if stat.S_ISLNK(st.st_mode): |
| 213 |
raise FileStoreError(FileStoreError.IS_A_SYMLINK, rel_path) |
| 214 |
if not stat.S_ISREG(st.st_mode): |
| 215 |
raise FileStoreError(FileStoreError.NOT_A_FILE, rel_path) |
| 216 |
return self._hash_via_cache(dest.relative_to(self._root).as_posix(), dest, _now_ns()) |
| 217 |
|
| 218 |
return await run_sync(one) |
| 219 |
|
| 220 |
async def move(self, src: str, dst: str) -> None: |
| 221 |
"""Rename `src` to `dst`; an existing `dst` is refused. The banned |
| 222 |
store root as either end does nothing.""" |
| 223 |
s = self._resolve_under_root(src) |
| 224 |
d = self._resolve_under_root(dst) |
| 225 |
if s == self._root or d == self._root: |
| 226 |
return |
| 227 |
if await anyio.Path(d).exists(): |
| 228 |
raise FileStoreError(FileStoreError.MOVE_DESTINATION_EXISTS, dst) |
| 229 |
await run_sync(_make_dirs_below_root, self._root, d.parent) |
| 230 |
await run_sync(os.rename, s, d) |
| 231 |
|
| 232 |
async def remove(self, rel_path: str) -> None: |
| 233 |
"""Delete a file or subtree; absent — and the banned store root — do nothing.""" |
| 234 |
dest = self._resolve_under_root(rel_path) |
| 235 |
if dest == self._root: |
| 236 |
return |
| 237 |
|
| 238 |
def delete() -> None: |
| 239 |
try: |
| 240 |
# lstat: a dangling symlink must still be unlinked. |
| 241 |
st = dest.lstat() |
| 242 |
except FileNotFoundError: |
| 243 |
return |
| 244 |
if stat.S_ISDIR(st.st_mode): |
| 245 |
shutil.rmtree(dest, ignore_errors=True) |
| 246 |
else: |
| 247 |
with suppress(FileNotFoundError): |
| 248 |
os.unlink(dest) |
| 249 |
|
| 250 |
await run_sync(delete) |
| 251 |
|
| 252 |
def _resolve_under_root(self, rel_path: str) -> Path: |
| 253 |
norm = PurePosixPath(rel_path.replace("\\", "/").lstrip("/")) |
| 254 |
if norm.is_absolute() or ".." in norm.parts: |
| 255 |
raise FileStoreError(FileStoreError.ESCAPES_ROOT, rel_path) |
| 256 |
return self._root.joinpath(*norm.parts) |
| 257 |
|
| 258 |
def _require_utf8(self, rel_path: str, data: bytes) -> None: |
| 259 |
if not self._utf8_only: |
| 260 |
return |
| 261 |
try: |
| 262 |
data.decode("utf-8") |
| 263 |
except UnicodeDecodeError: |
| 264 |
raise FileStoreError(FileStoreError.NOT_UTF8, rel_path) from None |
| 265 |
|
| 266 |
def _hash_via_cache(self, rel: str, full: Path, walk_start_ns: int) -> str | None: |
| 267 |
try: |
| 268 |
st = full.lstat() |
| 269 |
except FileNotFoundError: |
| 270 |
return None # vanished since the walk: not in this snapshot |
| 271 |
if not stat.S_ISREG(st.st_mode): |
| 272 |
return None |
| 273 |
cached = self._hashes.get(rel) |
| 274 |
if cached is not None and _unchanged_since_hashed(cached, st): |
| 275 |
sha = cached.sha |
| 276 |
else: |
| 277 |
try: |
| 278 |
sha = _hash_file(full) |
| 279 |
except (FileNotFoundError, FileStoreError): |
| 280 |
return None |
| 281 |
except OSError as e: |
| 282 |
if e.errno in (errno.ELOOP, errno.EMLINK): |
| 283 |
return None |
| 284 |
raise |
| 285 |
if _old_enough_to_cache(st, walk_start_ns): |
| 286 |
self._hashes[rel] = _Hashed(st.st_mtime_ns, st.st_ctime_ns, st.st_size, sha) |
| 287 |
return sha |
| 288 |
|
| 289 |
|
| 290 |
# The helpers below block; they are always called via run_sync. |
| 291 |
|
| 292 |
|
| 293 |
def _platform_supported() -> bool: |
| 294 |
return _O_NOFOLLOW != 0 |
| 295 |
|
| 296 |
|
| 297 |
def _make_dir_and_ancestors(path: Path) -> None: |
| 298 |
missing: list[Path] = [] |
| 299 |
current = path |
| 300 |
while not current.exists() and current != current.parent: |
| 301 |
missing.append(current) |
| 302 |
current = current.parent |
| 303 |
for directory in reversed(missing): |
| 304 |
with suppress(FileExistsError): |
| 305 |
os.mkdir(directory, _OWNER_ONLY_DIR_MODE) |
| 306 |
|
| 307 |
|
| 308 |
def _make_dirs_below_root(root: Path, directory: Path) -> None: |
| 309 |
# Never the root itself: only create_root() makes it, so a write racing an |
| 310 |
# rm -rf of the folder fails with ENOENT instead of re-creating it. |
| 311 |
current = root |
| 312 |
for part in directory.relative_to(root).parts: |
| 313 |
current = current / part |
| 314 |
with suppress(FileExistsError): |
| 315 |
os.mkdir(current, _OWNER_ONLY_DIR_MODE) |
| 316 |
|
| 317 |
|
| 318 |
def _replace_via_temp(dest: Path, data: bytes, is_executable: bool) -> None: |
| 319 |
mode = _OWNER_ONLY_EXEC_MODE if is_executable else _OWNER_ONLY_FILE_MODE |
| 320 |
tmp = dest.parent / f".fs-{os.urandom(8).hex()}.tmp" |
| 321 |
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_NOFOLLOW, mode) |
| 322 |
try: |
| 323 |
with os.fdopen(fd, "wb") as f: |
| 324 |
f.write(data) |
| 325 |
os.replace(tmp, dest) |
| 326 |
except BaseException: |
| 327 |
# Best-effort temp cleanup; never mask the original error. |
| 328 |
with suppress(OSError): |
| 329 |
os.unlink(tmp) |
| 330 |
raise |
| 331 |
|
| 332 |
|
| 333 |
def _open_regular_file(rel_path: str, dest: Path) -> IO[bytes]: |
| 334 |
# O_NONBLOCK: a FIFO fails the fstat check below instead of blocking the open. |
| 335 |
try: |
| 336 |
fd = os.open(dest, os.O_RDONLY | _O_NOFOLLOW | _O_NONBLOCK) |
| 337 |
except OSError as e: |
| 338 |
# FreeBSD reports EMLINK rather than ELOOP for O_NOFOLLOW. |
| 339 |
if e.errno in (errno.ELOOP, errno.EMLINK): |
| 340 |
raise FileStoreError(FileStoreError.IS_A_SYMLINK, rel_path) from None |
| 341 |
raise |
| 342 |
try: |
| 343 |
if not stat.S_ISREG(os.fstat(fd).st_mode): |
| 344 |
raise FileStoreError(FileStoreError.NOT_A_FILE, rel_path) |
| 345 |
except BaseException: |
| 346 |
os.close(fd) |
| 347 |
raise |
| 348 |
return os.fdopen(fd, "rb") |
| 349 |
|
| 350 |
|
| 351 |
def _hash_file(path: Path) -> str: |
| 352 |
digest = hashlib.sha256() |
| 353 |
with _open_regular_file(path.name, path) as f: |
| 354 |
for chunk in iter(lambda: f.read(1024 * 1024), b""): |
| 355 |
digest.update(chunk) |
| 356 |
return digest.hexdigest() |
| 357 |
|
| 358 |
|
| 359 |
def _raise_unless_vanished(error: OSError) -> None: |
| 360 |
# For os.walk, which otherwise skips an unreadable directory as if it were empty. |
| 361 |
if not isinstance(error, FileNotFoundError): |
| 362 |
raise error |
| 363 |
|
| 364 |
|
| 365 |
def _filenames_in_dir(root: Path, under: str, base: Path) -> list[tuple[str, Path]]: |
| 366 |
"""Every regular file under `base` as `(rel_path, path)`; an absent |
| 367 |
`base` is empty, a present non-directory is refused.""" |
| 368 |
try: |
| 369 |
st = base.lstat() |
| 370 |
except (FileNotFoundError, NotADirectoryError): |
| 371 |
return [] |
| 372 |
if not stat.S_ISDIR(st.st_mode): |
| 373 |
raise FileStoreError(FileStoreError.NOT_A_DIRECTORY, under) |
| 374 |
out: list[tuple[str, Path]] = [] |
| 375 |
# os.walk never descends symlinked directories (unlike rglob before 3.13). |
| 376 |
for dirpath, _dirnames, filenames in os.walk(base, onerror=_raise_unless_vanished): |
| 377 |
for name in filenames: |
| 378 |
full = Path(dirpath) / name |
| 379 |
try: |
| 380 |
fst = full.lstat() |
| 381 |
except FileNotFoundError: |
| 382 |
continue # a listing is a snapshot, not a lock |
| 383 |
if stat.S_ISREG(fst.st_mode): |
| 384 |
out.append((full.relative_to(root).as_posix(), full)) |
| 385 |
return out |
| 386 |
|
| 387 |
|
| 388 |
def _symlinks_in_dir(root: Path, under: str, base: Path) -> set[str]: |
| 389 |
try: |
| 390 |
st = base.lstat() |
| 391 |
except (FileNotFoundError, NotADirectoryError): |
| 392 |
return set() |
| 393 |
if stat.S_ISLNK(st.st_mode): |
| 394 |
return {base.relative_to(root).as_posix()} |
| 395 |
if not stat.S_ISDIR(st.st_mode): |
| 396 |
raise FileStoreError(FileStoreError.NOT_A_DIRECTORY, under) |
| 397 |
out: set[str] = set() |
| 398 |
for dirpath, dirnames, filenames in os.walk(base, onerror=_raise_unless_vanished): |
| 399 |
for name in (*dirnames, *filenames): |
| 400 |
full = Path(dirpath) / name |
| 401 |
try: |
| 402 |
fst = full.lstat() |
| 403 |
except FileNotFoundError: |
| 404 |
continue |
| 405 |
if stat.S_ISLNK(fst.st_mode): |
| 406 |
out.add(full.relative_to(root).as_posix()) |
| 407 |
return out |
| 408 |
|
| 409 |
|
| 410 |
def _unchanged_since_hashed(cached: _Hashed, st: os.stat_result) -> bool: |
| 411 |
return (st.st_mtime_ns, st.st_ctime_ns, st.st_size) == (cached.mtime_ns, cached.ctime_ns, cached.size) |
| 412 |
|
| 413 |
|
| 414 |
# Filesystems stamp times with coarse clocks, so a rewrite shortly after a |
| 415 |
# hashed write can reuse the exact stamps. Files younger than the margin are |
| 416 |
# simply re-hashed next walk. |
| 417 |
_TIMESTAMP_TRUST_MARGIN_NS = 2_000_000_000 |
| 418 |
|
| 419 |
# Tests freeze this clock. |
| 420 |
_now_ns = time.time_ns |
| 421 |
|
| 422 |
|
| 423 |
def _old_enough_to_cache(st: os.stat_result, walk_start_ns: int) -> bool: |
| 424 |
return max(st.st_mtime_ns, st.st_ctime_ns) < walk_start_ns - _TIMESTAMP_TRUST_MARGIN_NS |
| 425 |
|
| 426 |
|
| 427 |
LocalFileStore = FileStore |