Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

9 downloads

dbbasic-object-server/object_files.py
Install on DigitalOcean Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_files.py · 11.1 KB · 335 lines
1"""Object-owned file helpers.
2
3The working prototype stores object-owned files under:
4
5 data/files/{object_id}/
6
7The HTTP surface gates writes separately from reads. These helpers keep path
8handling local and conservative so higher layers can apply auth, quotas, and
9permission policy.
10"""
11
12from __future__ import annotations
13
14import os
15import stat
16import tempfile
17from dataclasses import asdict, dataclass
18from pathlib import Path
19from typing import Any
20
21import object_user_quotas
22from object_namespace import validate_object_id
23from object_versions import DEFAULT_DATA_DIR, InvalidObjectIdError
24
25
26class InvalidObjectFilenameError(ValueError):
27 """Raised when an object file name is unsafe."""
28
29
30class ObjectFileNotFoundError(FileNotFoundError):
31 """Raised when an object-owned file is missing."""
32
33
34class ObjectFileExistsError(FileExistsError):
35 """Raised when an object-owned file already exists."""
36
37
38class ObjectFileTooLargeError(ValueError):
39 """Raised when an object-owned file exceeds the configured size limit."""
40
41
42@dataclass(frozen=True)
43class ObjectFileMetadata:
44 name: str
45 size: int
46 modified: float
47
48 def to_dict(self) -> dict[str, Any]:
49 return asdict(self)
50
51
52def object_files_dir(object_id: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
53 """Return the object-owned files directory for a validated object id."""
54 if not validate_object_id(object_id):
55 raise InvalidObjectIdError(f"Invalid object ID: {object_id}")
56
57 return Path(base_dir) / "files" / object_id
58
59
60def list_object_files(
61 object_id: str,
62 base_dir: Path | str = DEFAULT_DATA_DIR,
63) -> list[dict[str, Any]]:
64 """List object-owned files as metadata dictionaries.
65
66 A file is listed when it is a file, its name is one _safe_file_path
67 accepts, and its real path is inside the object's files directory.
68 Asking that per file (`_listed_metadata_checked`) costs three
69 realpath() calls, each an lstat() of every directory from / down: about
70 40 system calls a file, 2.9 s for 11,000 files, on every GET of
71 /collections, /admin/status and /admin/files.
72
73 Most files need none of it. A regular file that is not a symlink,
74 reached from the files directory through directories that are not
75 symlinks either, has its real path inside that directory by
76 construction, and the one lstat() that establishes "regular file, not a
77 symlink" is also its size and mtime. Anything else -- a symlink, a
78 directory that is one, a name the prefix does not explain, an lstat()
79 that fails -- is asked the full question exactly as before. Nothing is
80 cached: every call reads the disk.
81 """
82 files_dir = object_files_dir(object_id, base_dir)
83 if not files_dir.exists():
84 return []
85 if not files_dir.is_dir():
86 raise OSError(f"Object files path is not a directory: {files_dir}")
87
88 prefix = str(files_dir) + os.sep
89 plain_dirs: dict[str, bool] = {str(files_dir): True}
90 files = []
91 for path in sorted(files_dir.rglob("*")):
92 metadata = _listed_metadata_plain(path, prefix, plain_dirs)
93 if metadata is _NOT_PLAIN:
94 metadata = _listed_metadata_checked(files_dir, path)
95 if metadata is not None:
96 files.append(metadata.to_dict())
97
98 return files
99
100
101_NOT_PLAIN: Any = object()
102
103
104def _listed_metadata_plain(
105 path: Path,
106 prefix: str,
107 plain_dirs: dict[str, bool],
108) -> ObjectFileMetadata | None:
109 """The answer for the plain case, None for "not listed", or _NOT_PLAIN
110 when only _listed_metadata_checked can say."""
111 text = str(path)
112 if not text.startswith(prefix):
113 return _NOT_PLAIN
114 try:
115 found = os.lstat(text)
116 except OSError:
117 return _NOT_PLAIN
118 if stat.S_ISDIR(found.st_mode):
119 return None # is_file() is False for a directory
120 if not stat.S_ISREG(found.st_mode):
121 return _NOT_PLAIN
122 if not _is_plain_dir(os.path.dirname(text), plain_dirs):
123 return _NOT_PLAIN
124 name = text[len(prefix):]
125 if os.sep != "/":
126 name = name.replace(os.sep, "/")
127 if not name or "\x00" in name or name.startswith("/") or ".." in name:
128 return None # the names _safe_file_path refuses
129 return ObjectFileMetadata(name=name, size=found.st_size, modified=found.st_mtime)
130
131
132def _is_plain_dir(directory: str, plain_dirs: dict[str, bool]) -> bool:
133 """True when `directory` and every directory between it and the files
134 directory (already in `plain_dirs`) is a real directory, not a symlink."""
135 known = plain_dirs.get(directory)
136 if known is not None:
137 return known
138 parent = os.path.dirname(directory)
139 if parent == directory:
140 return False
141 plain = False
142 if _is_plain_dir(parent, plain_dirs):
143 try:
144 plain = stat.S_ISDIR(os.lstat(directory).st_mode)
145 except OSError:
146 plain = False
147 plain_dirs[directory] = plain
148 return plain
149
150
151def _listed_metadata_checked(files_dir: Path, path: Path) -> ObjectFileMetadata | None:
152 """The full question, as list_object_files asked it of every file."""
153 if not path.is_file():
154 return None
155 relative_name = path.relative_to(files_dir).as_posix()
156 try:
157 safe_path = _safe_file_path(files_dir, relative_name)
158 except InvalidObjectFilenameError:
159 return None
160 if path.resolve() != safe_path:
161 return None
162 return _metadata(files_dir, path)
163
164
165def list_all_object_files(
166 base_dir: Path | str = DEFAULT_DATA_DIR,
167 *,
168 object_id: str | None = None,
169) -> list[dict[str, Any]]:
170 """List object-owned files across the local file store."""
171 if object_id is not None:
172 return [
173 {"object_id": object_id, **metadata}
174 for metadata in list_object_files(object_id, base_dir=base_dir)
175 ]
176
177 files_root = Path(base_dir) / "files"
178 if not files_root.exists():
179 return []
180 if not files_root.is_dir():
181 raise OSError(f"Object files root is not a directory: {files_root}")
182
183 files = []
184 for object_dir in sorted(files_root.iterdir()):
185 if not object_dir.is_dir() or not validate_object_id(object_dir.name):
186 continue
187 files.extend(
188 {"object_id": object_dir.name, **metadata}
189 for metadata in list_object_files(object_dir.name, base_dir=base_dir)
190 )
191
192 files.sort(key=lambda item: (-float(item["modified"]), item["object_id"], item["name"]))
193 return files
194
195
196def read_object_file(
197 object_id: str,
198 filename: str,
199 base_dir: Path | str = DEFAULT_DATA_DIR,
200) -> tuple[bytes, dict[str, Any]]:
201 """Read one object-owned file and return bytes plus metadata."""
202 files_dir = object_files_dir(object_id, base_dir)
203 path = _safe_file_path(files_dir, filename)
204 if not path.exists() or not path.is_file():
205 raise ObjectFileNotFoundError(f"File not found: {filename}")
206
207 return path.read_bytes(), _metadata(files_dir, path).to_dict()
208
209
210def write_object_file(
211 object_id: str,
212 filename: str,
213 content: bytes,
214 base_dir: Path | str = DEFAULT_DATA_DIR,
215 *,
216 overwrite: bool = False,
217 max_bytes: int | None = None,
218) -> dict[str, Any]:
219 """Write one object-owned file and return metadata."""
220 if max_bytes is not None and len(content) > max_bytes:
221 raise ObjectFileTooLargeError(
222 f"Object file exceeds max size: {len(content)} bytes > {max_bytes} bytes"
223 )
224
225 files_dir = object_files_dir(object_id, base_dir)
226 path = _safe_write_file_path(files_dir, filename)
227 if path.exists():
228 if path.is_symlink() or not path.is_file():
229 raise InvalidObjectFilenameError(f"Invalid filename: {filename!r}")
230 if not overwrite:
231 raise ObjectFileExistsError(f"File already exists: {filename}")
232
233 try:
234 object_user_quotas.check_files_write(
235 object_id,
236 base_dir,
237 new_size=len(content),
238 replaced_size=path.stat().st_size if path.is_file() else 0,
239 )
240 except object_user_quotas.UserQuotaExceededError as exc:
241 raise ObjectFileTooLargeError(str(exc)) from exc
242
243 path.parent.mkdir(parents=True, exist_ok=True)
244 temp_path: Path | None = None
245 try:
246 with tempfile.NamedTemporaryFile(
247 "wb",
248 delete=False,
249 dir=path.parent,
250 prefix=f".{path.name}.",
251 suffix=".tmp",
252 ) as temp_file:
253 temp_file.write(content)
254 temp_path = Path(temp_file.name)
255 temp_path.replace(path)
256 finally:
257 if temp_path is not None and temp_path.exists():
258 temp_path.unlink()
259
260 return _metadata(files_dir, path).to_dict()
261
262
263def delete_object_file(
264 object_id: str,
265 filename: str,
266 base_dir: Path | str = DEFAULT_DATA_DIR,
267) -> dict[str, Any]:
268 """Delete one object-owned file and return its previous metadata."""
269 files_dir = object_files_dir(object_id, base_dir)
270 path = _safe_write_file_path(files_dir, filename)
271 if not path.exists() or not path.is_file() or path.is_symlink():
272 raise ObjectFileNotFoundError(f"File not found: {filename}")
273
274 metadata = _metadata(files_dir, path).to_dict()
275 path.unlink()
276 _prune_empty_dirs(path.parent, files_dir)
277 return metadata
278
279
280def _safe_file_path(files_dir: Path, filename: str) -> Path:
281 if not filename or "\x00" in filename or filename.startswith("/") or ".." in filename:
282 raise InvalidObjectFilenameError(f"Invalid filename: {filename!r}")
283
284 root = files_dir.resolve()
285 resolved = (files_dir / filename).resolve()
286 try:
287 resolved.relative_to(root)
288 except ValueError as exc:
289 raise InvalidObjectFilenameError(f"Path traversal blocked: {filename!r}") from exc
290
291 return resolved
292
293
294def _safe_write_file_path(files_dir: Path, filename: str) -> Path:
295 if not filename or "\x00" in filename or filename.startswith("/") or ".." in filename:
296 raise InvalidObjectFilenameError(f"Invalid filename: {filename!r}")
297
298 relative = Path(filename)
299 if relative.is_absolute() or any(part in {"", ".", ".."} for part in relative.parts):
300 raise InvalidObjectFilenameError(f"Invalid filename: {filename!r}")
301
302 root = files_dir.resolve()
303 candidate = files_dir / relative
304 current = files_dir
305 for part in relative.parts[:-1]:
306 current = current / part
307 if current.exists() and current.is_symlink():
308 raise InvalidObjectFilenameError(f"Invalid filename: {filename!r}")
309
310 if candidate.exists() and candidate.is_symlink():
311 raise InvalidObjectFilenameError(f"Invalid filename: {filename!r}")
312
313 try:
314 candidate.parent.resolve().relative_to(root)
315 except ValueError as exc:
316 raise InvalidObjectFilenameError(f"Path traversal blocked: {filename!r}") from exc
317
318 return candidate
319
320
321def _prune_empty_dirs(start: Path, stop: Path) -> None:
322 stop = stop.resolve()
323 current = start
324 while current != stop:
325 try:
326 current.rmdir()
327 except OSError:
328 return
329 current = current.parent
330
331
332def _metadata(files_dir: Path, path: Path) -> ObjectFileMetadata:
333 stat = path.stat()
334 name = path.relative_to(files_dir).as_posix()
335 return ObjectFileMetadata(name=name, size=stat.st_size, modified=stat.st_mtime)