spill_safety.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. """Symlink-safe creation helpers for spill/cache files under ``~/.hermes``, where a plain
  2. ``open(path, "w")`` would follow a pre-planted symlink onto ``~/.bashrc`` etc. New files use
  3. ``O_CREAT | O_EXCL`` (fails on ANY existing path, even a dangling link); overwrites ``lstat`` +
  4. ``unlink`` first (removes the link, never its target) then create exclusively, so the pair
  5. can't be raced. ``private=True`` (default) = ``0o700`` dirs / ``0o600`` files for spills that
  6. may hold pre-redaction secrets; ``private=False`` keeps umask perms for cache dirs bind-mounted
  7. into remote backends (``credential_files._CACHE_DIRS``). Disk failures raise ``OSError``."""
  8. from __future__ import annotations
  9. import os
  10. import stat
  11. from pathlib import Path
  12. from typing import IO
  13. from hermes_dir_acl import make_user_dir
  14. __all__ = ["ensure_spill_dir", "open_exclusive", "write_text_exclusive"]
  15. # O_NOFOLLOW is POSIX-only; on Windows O_EXCL alone already refuses every pre-existing path.
  16. _O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
  17. def ensure_spill_dir(path: Path, *, private: bool = True) -> Path:
  18. """Create ``path`` (and parents) as a directory, refusing symlinks. ``private=True``
  19. creates the leaf ``0o700`` and tightens an existing leaf. Raises ``OSError`` if the leaf
  20. is not a real directory."""
  21. path = Path(path)
  22. make_user_dir(path, mode=0o700 if private else 0o777, parents=True, exist_ok=True)
  23. st = os.lstat(path)
  24. if not stat.S_ISDIR(st.st_mode):
  25. raise OSError(f"spill dir is not a directory (symlink?): {path}")
  26. if private and stat.S_IMODE(st.st_mode) != 0o700:
  27. os.chmod(path, 0o700)
  28. return path
  29. def open_exclusive(path: Path, *, private: bool = True, overwrite: bool = False,
  30. encoding: str = "utf-8", errors: str = "strict") -> IO[str]:
  31. """Open ``path`` for writing via exclusive create; never follows a link. ``overwrite=True``
  32. first unlinks an existing path (``lstat``-checked, so only the link itself is removed and
  33. directories are refused), then creates exclusively — the overwrite path cannot be
  34. redirected through a symlink either."""
  35. path = Path(path)
  36. if overwrite:
  37. try:
  38. st = os.lstat(path)
  39. except FileNotFoundError:
  40. pass
  41. else:
  42. if stat.S_ISDIR(st.st_mode):
  43. raise OSError(f"refusing to overwrite a directory: {path}")
  44. os.unlink(path)
  45. mode = 0o600 if private else 0o666 # non-private honors umask
  46. fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_NOFOLLOW, mode)
  47. try:
  48. return os.fdopen(fd, "w", encoding=encoding, errors=errors)
  49. except Exception:
  50. os.close(fd)
  51. raise
  52. def write_text_exclusive(path: Path, text: str, *, private: bool = True, overwrite: bool = False,
  53. encoding: str = "utf-8", errors: str = "strict") -> None:
  54. """``Path.write_text`` equivalent that refuses to follow symlinks."""
  55. with open_exclusive(path, private=private, overwrite=overwrite, encoding=encoding,
  56. errors=errors) as fh:
  57. fh.write(text)