offgit 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
offgit/paths.py ADDED
@@ -0,0 +1,367 @@
1
+ """Registry path validation and race-resistant local file operations.
2
+
3
+ All local reads/writes go through a directory file descriptor opened on the
4
+ project root and walk each component with ``O_NOFOLLOW | O_DIRECTORY`` so a
5
+ symlink planted in an ancestor (or at the target) is refused instead of
6
+ followed. Writes use a temp file in the destination directory, ``fsync``,
7
+ ``os.replace`` relative to the parent dirfd, then ``fsync`` of the directory.
8
+
9
+ Residual risk (documented in docs/security.md): a malicious local process
10
+ running as the same user can still race between our final re-hash and the
11
+ rename; offgit narrows that window but cannot close it without a filesystem
12
+ transaction.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import contextlib
18
+ import errno
19
+ import os
20
+ import secrets
21
+ import stat
22
+ import unicodedata
23
+ from collections.abc import Iterable, Iterator
24
+ from dataclasses import dataclass
25
+
26
+ from offgit.errors import LocalChangedError, PathError, UnsafeLocalFile
27
+ from offgit.hashing import sha256_hex
28
+
29
+ MAX_PATH_BYTES = 1024
30
+ MAX_COMPONENT_BYTES = 255
31
+ TEMP_MARKER = ".offgit-tmp-"
32
+
33
+ _O_NOFOLLOW = getattr(os, "O_NOFOLLOW", 0)
34
+ _O_DIRECTORY = getattr(os, "O_DIRECTORY", 0)
35
+ _O_CLOEXEC = getattr(os, "O_CLOEXEC", 0)
36
+ _O_NONBLOCK = getattr(os, "O_NONBLOCK", 0)
37
+
38
+
39
+ def validate_rel_path(path: str) -> str:
40
+ """Validate a registry path. Returns it unchanged or raises PathError."""
41
+ if not isinstance(path, str) or path == "":
42
+ raise PathError("Path is empty")
43
+ if len(path.encode("utf-8", "surrogatepass")) > MAX_PATH_BYTES:
44
+ raise PathError(f"Path is too long: {path!r}")
45
+ try:
46
+ path.encode("utf-8")
47
+ except UnicodeEncodeError as exc:
48
+ raise PathError(f"Path is not valid UTF-8: {path!r}") from exc
49
+ for ch in path:
50
+ if ord(ch) < 0x20 or ord(ch) == 0x7F or 0x80 <= ord(ch) <= 0x9F:
51
+ raise PathError(f"Path contains control characters: {path!r}")
52
+ if "\\" in path:
53
+ raise PathError(f"Path contains a backslash: {path!r}", hint="Use '/' separators")
54
+ if any(ch in path for ch in "*?[]"):
55
+ raise PathError(
56
+ f"Path contains glob metacharacters (* ? [ ]): {path!r}",
57
+ hint="offgit registers exact paths only; Git's ignore checks treat these characters "
58
+ "inconsistently, so they are not supported",
59
+ )
60
+ if path.startswith("/"):
61
+ raise PathError(f"Absolute paths are not allowed: {path!r}")
62
+ if path.endswith("/"):
63
+ raise PathError(f"Path must name a file, not end with '/': {path!r}")
64
+ if unicodedata.normalize("NFC", path) != path:
65
+ raise PathError(
66
+ f"Path is not Unicode NFC-normalized: {path!r}",
67
+ hint="Rename the file to its NFC form (macOS may store NFD names); see docs/security.md",
68
+ )
69
+ for comp in path.split("/"):
70
+ if comp == "":
71
+ raise PathError(f"Path has an empty component: {path!r}")
72
+ if comp in (".", ".."):
73
+ raise PathError(f"Path has a '.' or '..' component: {path!r}")
74
+ if comp.casefold() == ".git":
75
+ raise PathError(f"Paths inside .git are not allowed: {path!r}")
76
+ if len(comp.encode("utf-8")) > MAX_COMPONENT_BYTES:
77
+ raise PathError(f"Path component is too long: {path!r}")
78
+ if TEMP_MARKER in comp:
79
+ raise PathError(f"Path uses offgit's reserved temp-file marker: {path!r}")
80
+ return path
81
+
82
+
83
+ def normalize_user_path(arg: str) -> str:
84
+ """Turn a CLI argument into a registry path (only strips a leading './')."""
85
+ p = arg
86
+ while p.startswith("./"):
87
+ p = p[2:]
88
+ return validate_rel_path(p)
89
+
90
+
91
+ def collision_key(path: str) -> str:
92
+ return unicodedata.normalize("NFC", path).casefold()
93
+
94
+
95
+ def check_collisions(paths: Iterable[str]) -> None:
96
+ """Reject case/NFC-fold collisions and file-vs-directory prefix collisions."""
97
+ seen: dict[str, str] = {}
98
+ keys: list[tuple[str, str]] = []
99
+ for p in paths:
100
+ k = collision_key(p)
101
+ if k in seen and seen[k] != p:
102
+ raise PathError(f"Paths collide on case-insensitive filesystems: {seen[k]!r} and {p!r}")
103
+ if k in seen:
104
+ raise PathError(f"Path listed twice: {p!r}")
105
+ seen[k] = p
106
+ keys.append((k, p))
107
+ folded = {k for k, _ in keys}
108
+ for k, p in keys:
109
+ parts = k.split("/")
110
+ for i in range(1, len(parts)):
111
+ prefix = "/".join(parts[:i])
112
+ if prefix in folded:
113
+ raise PathError(f"Path {p!r} would be inside registered file {prefix!r}")
114
+
115
+
116
+ # ---------------------------------------------------------------------------
117
+ # dirfd based operations
118
+
119
+
120
+ @dataclass(frozen=True)
121
+ class LocalFile:
122
+ """Result of inspecting one registered path on disk."""
123
+
124
+ path: str
125
+ exists: bool
126
+ data: bytes | None = None
127
+ sha256: str | None = None
128
+ mode: int | None = None
129
+ nlink: int = 1
130
+
131
+ @property
132
+ def size(self) -> int | None:
133
+ return None if self.data is None else len(self.data)
134
+
135
+
136
+ class Root:
137
+ """An open handle on the project root directory."""
138
+
139
+ def __init__(self, root: str) -> None:
140
+ self.path = root
141
+ try:
142
+ self.fd = os.open(root, os.O_RDONLY | _O_DIRECTORY | _O_CLOEXEC)
143
+ except OSError as exc:
144
+ raise PathError(f"Cannot open project root {root!r}: {exc.strerror}") from exc
145
+
146
+ def close(self) -> None:
147
+ if self.fd >= 0:
148
+ os.close(self.fd)
149
+ self.fd = -1
150
+
151
+ def __enter__(self) -> Root:
152
+ return self
153
+
154
+ def __exit__(self, *exc: object) -> None:
155
+ self.close()
156
+
157
+ # -- directory walking -------------------------------------------------
158
+
159
+ @contextlib.contextmanager
160
+ def parent_dir(self, rel: str, *, create: bool = False) -> Iterator[int]:
161
+ """Yield an fd for the parent directory of ``rel`` (never following symlinks)."""
162
+ validate_rel_path(rel)
163
+ comps = rel.split("/")[:-1]
164
+ fds: list[int] = []
165
+ cur = self.fd
166
+ try:
167
+ for comp in comps:
168
+ try:
169
+ st = os.stat(comp, dir_fd=cur, follow_symlinks=False)
170
+ except FileNotFoundError:
171
+ if not create:
172
+ raise
173
+ os.mkdir(comp, 0o777, dir_fd=cur) # umask applies
174
+ st = os.stat(comp, dir_fd=cur, follow_symlinks=False)
175
+ if stat.S_ISLNK(st.st_mode):
176
+ raise UnsafeLocalFile(f"{rel}: ancestor {comp!r} is a symlink", code="symlink")
177
+ if not stat.S_ISDIR(st.st_mode):
178
+ raise UnsafeLocalFile(
179
+ f"{rel}: ancestor {comp!r} is not a directory", code="not_a_directory"
180
+ )
181
+ try:
182
+ nfd = os.open(
183
+ comp, os.O_RDONLY | _O_DIRECTORY | _O_NOFOLLOW | _O_CLOEXEC, dir_fd=cur
184
+ )
185
+ except OSError as exc:
186
+ if exc.errno in (errno.ELOOP, errno.ENOTDIR):
187
+ raise UnsafeLocalFile(
188
+ f"{rel}: ancestor {comp!r} changed or is a symlink", code="symlink"
189
+ ) from exc
190
+ raise
191
+ fds.append(nfd)
192
+ nst = os.fstat(nfd)
193
+ if (nst.st_dev, nst.st_ino) != (st.st_dev, st.st_ino):
194
+ raise UnsafeLocalFile(f"{rel}: ancestor {comp!r} was replaced", code="race")
195
+ cur = nfd
196
+ if _exists(".git", cur):
197
+ raise UnsafeLocalFile(
198
+ f"{rel}: crosses a nested Git repository boundary at {comp!r}",
199
+ code="nested_repository",
200
+ )
201
+ yield cur
202
+ finally:
203
+ for fd in reversed(fds):
204
+ os.close(fd)
205
+
206
+ # -- reading -----------------------------------------------------------
207
+
208
+ def inspect(self, rel: str, *, max_bytes: int, read: bool = True) -> LocalFile:
209
+ """Return a LocalFile for ``rel``. Missing files (or parents) are ``exists=False``."""
210
+ name = rel.rsplit("/", maxsplit=1)[-1]
211
+ try:
212
+ with self.parent_dir(rel) as pfd:
213
+ return _read_regular(rel, name, pfd, max_bytes=max_bytes, read=read)
214
+ except FileNotFoundError:
215
+ return LocalFile(path=rel, exists=False)
216
+
217
+ # -- writing -----------------------------------------------------------
218
+
219
+ def atomic_write(
220
+ self,
221
+ rel: str,
222
+ data: bytes,
223
+ *,
224
+ expected_sha256: str | None,
225
+ max_bytes: int,
226
+ temp_name: str | None = None,
227
+ ) -> str:
228
+ """Atomically replace ``rel`` with ``data``.
229
+
230
+ ``expected_sha256`` is the hash the current on-disk file must still have
231
+ (``None`` means it must not exist). Returns the temp name used.
232
+ """
233
+ name = rel.rsplit("/", maxsplit=1)[-1]
234
+ temp_name = temp_name or make_temp_name(name)
235
+ with self.parent_dir(rel, create=True) as pfd:
236
+ current = _read_regular(rel, name, pfd, max_bytes=max_bytes, read=True)
237
+ _check_expected(rel, current, expected_sha256)
238
+ mode = 0o600
239
+ if current.exists and current.mode is not None:
240
+ # keep ordinary permission bits, drop setuid/setgid/sticky
241
+ mode = stat.S_IMODE(current.mode) & 0o777
242
+ flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | _O_NOFOLLOW | _O_CLOEXEC
243
+ tfd = os.open(temp_name, flags, 0o600, dir_fd=pfd)
244
+ try:
245
+ try:
246
+ view = memoryview(data)
247
+ while view:
248
+ n = os.write(tfd, view)
249
+ view = view[n:]
250
+ os.fchmod(tfd, mode)
251
+ os.fsync(tfd)
252
+ finally:
253
+ os.close(tfd)
254
+ # Final revalidation immediately before the rename (narrows TOCTOU).
255
+ again = _read_regular(rel, name, pfd, max_bytes=max_bytes, read=True)
256
+ _check_expected(rel, again, expected_sha256)
257
+ os.replace(temp_name, name, src_dir_fd=pfd, dst_dir_fd=pfd)
258
+ except BaseException:
259
+ with contextlib.suppress(OSError):
260
+ os.unlink(temp_name, dir_fd=pfd)
261
+ raise
262
+ os.fsync(pfd)
263
+ return temp_name
264
+
265
+ def remove_temp(self, rel: str, temp_name: str) -> bool:
266
+ """Remove a leftover offgit temp file recorded in a journal. Returns True if removed."""
267
+ if TEMP_MARKER not in temp_name or "/" in temp_name:
268
+ return False
269
+ try:
270
+ with self.parent_dir(rel) as pfd:
271
+ st = os.stat(temp_name, dir_fd=pfd, follow_symlinks=False)
272
+ if not stat.S_ISREG(st.st_mode):
273
+ return False
274
+ os.unlink(temp_name, dir_fd=pfd)
275
+ return True
276
+ except (FileNotFoundError, UnsafeLocalFile):
277
+ return False
278
+
279
+
280
+ def make_temp_name(name: str) -> str:
281
+ base = name[:120]
282
+ return f".{base}{TEMP_MARKER}{secrets.token_hex(6)}"
283
+
284
+
285
+ def _exists(name: str, dir_fd: int) -> bool:
286
+ try:
287
+ os.stat(name, dir_fd=dir_fd, follow_symlinks=False)
288
+ except FileNotFoundError:
289
+ return False
290
+ return True
291
+
292
+
293
+ def _check_expected(rel: str, current: LocalFile, expected: str | None) -> None:
294
+ if expected is None:
295
+ if current.exists:
296
+ raise LocalChangedError(f"{rel}: file appeared while offgit was writing; not replaced")
297
+ elif not current.exists:
298
+ raise LocalChangedError(f"{rel}: file disappeared while offgit was writing; not replaced")
299
+ elif current.sha256 != expected:
300
+ raise LocalChangedError(f"{rel}: file changed while offgit was writing; not replaced")
301
+
302
+
303
+ def _read_regular(rel: str, name: str, pfd: int, *, max_bytes: int, read: bool) -> LocalFile:
304
+ for _attempt in range(3):
305
+ try:
306
+ st = os.stat(name, dir_fd=pfd, follow_symlinks=False)
307
+ except FileNotFoundError:
308
+ return LocalFile(path=rel, exists=False)
309
+ if stat.S_ISLNK(st.st_mode):
310
+ raise UnsafeLocalFile(f"{rel}: is a symlink", code="symlink")
311
+ if stat.S_ISDIR(st.st_mode):
312
+ raise UnsafeLocalFile(f"{rel}: is a directory", code="not_a_file")
313
+ if not stat.S_ISREG(st.st_mode):
314
+ raise UnsafeLocalFile(f"{rel}: is not a regular file", code="special_file")
315
+ if st.st_size > max_bytes:
316
+ raise UnsafeLocalFile(
317
+ f"{rel}: {st.st_size} bytes exceeds the per-file limit of {max_bytes} bytes",
318
+ code="file_too_large",
319
+ )
320
+ if not read:
321
+ return LocalFile(path=rel, exists=True, mode=st.st_mode, nlink=st.st_nlink)
322
+ try:
323
+ fd = os.open(name, os.O_RDONLY | _O_NOFOLLOW | _O_NONBLOCK | _O_CLOEXEC, dir_fd=pfd)
324
+ except FileNotFoundError:
325
+ continue
326
+ except OSError as exc:
327
+ if exc.errno == errno.ELOOP:
328
+ raise UnsafeLocalFile(f"{rel}: is a symlink", code="symlink") from exc
329
+ raise
330
+ try:
331
+ before = os.fstat(fd)
332
+ if (before.st_dev, before.st_ino) != (st.st_dev, st.st_ino) or not stat.S_ISREG(
333
+ before.st_mode
334
+ ):
335
+ continue
336
+ chunks: list[bytes] = []
337
+ total = 0
338
+ while True:
339
+ chunk = os.read(fd, 1 << 20)
340
+ if not chunk:
341
+ break
342
+ total += len(chunk)
343
+ if total > max_bytes:
344
+ raise UnsafeLocalFile(
345
+ f"{rel}: exceeds the per-file limit of {max_bytes} bytes",
346
+ code="file_too_large",
347
+ )
348
+ chunks.append(chunk)
349
+ after = os.fstat(fd)
350
+ finally:
351
+ os.close(fd)
352
+ if (
353
+ after.st_size != total
354
+ or after.st_mtime_ns != before.st_mtime_ns
355
+ or after.st_ctime_ns != before.st_ctime_ns
356
+ ):
357
+ continue # modified while reading; retry
358
+ data = b"".join(chunks)
359
+ return LocalFile(
360
+ path=rel,
361
+ exists=True,
362
+ data=data,
363
+ sha256=sha256_hex(data),
364
+ mode=before.st_mode,
365
+ nlink=before.st_nlink,
366
+ )
367
+ raise LocalChangedError(f"{rel}: kept changing while being read; try again")