askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_runtime_helpers.py · 9.5 KB · 239 lines
| 1 | """Runtime helpers injected into every Python object: ``_files`` and ``_runtime``. |
| 2 | |
| 3 | Objects written for the previous object server call ``_files.put/get/list/ |
| 4 | delete`` and ``_runtime.load_object(object_id)``; both are provided here with |
| 5 | the same method names and return shapes, under this server's security rules |
| 6 | (see docs/object-authoring.md "Runtime Helpers"). ``PythonObject`` injects them, |
| 7 | so they behave identically in-process, in warm pool workers and in spawned |
| 8 | children. |
| 9 | """ |
| 10 | |
| 11 | from __future__ import annotations |
| 12 | |
| 13 | import os |
| 14 | import re |
| 15 | import threading |
| 16 | from contextlib import contextmanager |
| 17 | from pathlib import Path |
| 18 | from typing import Any, Iterator |
| 19 | |
| 20 | import object_files |
| 21 | import object_user_access |
| 22 | from object_namespace import parse_user_object_id, resolve_object_id, validate_object_id |
| 23 | from object_versions import DEFAULT_DATA_DIR |
| 24 | |
| 25 | MAX_OBJECT_FILE_BYTES_ENV = "DBBASIC_MAX_OBJECT_FILE_BYTES" |
| 26 | DEFAULT_MAX_OBJECT_FILE_BYTES = 1_048_576 |
| 27 | |
| 28 | # Nested object executions allowed on one call chain (the outermost request |
| 29 | # counts as 1). Self-calls and A -> B -> A loops stop with CompositionDepthError. |
| 30 | MAX_COMPOSITION_DEPTH = 8 |
| 31 | |
| 32 | _USERISH_RE = re.compile(r"^u_(\d+)_") |
| 33 | |
| 34 | |
| 35 | def max_object_file_bytes() -> int: |
| 36 | """Per-file size limit for ``_files.put`` (same knob as the HTTP file API).""" |
| 37 | raw = os.environ.get(MAX_OBJECT_FILE_BYTES_ENV, "").strip() |
| 38 | try: |
| 39 | value = int(raw) if raw else DEFAULT_MAX_OBJECT_FILE_BYTES |
| 40 | except ValueError: |
| 41 | return DEFAULT_MAX_OBJECT_FILE_BYTES |
| 42 | return value if value >= 0 else DEFAULT_MAX_OBJECT_FILE_BYTES |
| 43 | |
| 44 | |
| 45 | class ObjectFileStore: |
| 46 | """Per-object file storage bound to ONE object id (``_files``). |
| 47 | |
| 48 | Files live in ``<data dir>/files/<object_id>/`` and are the same files the |
| 49 | HTTP object-file API serves. All path safety is ``object_files``'. |
| 50 | """ |
| 51 | |
| 52 | def __init__(self, object_id: str, base_dir: Path | str = DEFAULT_DATA_DIR): |
| 53 | if not validate_object_id(object_id): |
| 54 | raise ValueError(f"Invalid object ID: {object_id!r}") |
| 55 | self.object_id = object_id |
| 56 | self.base_dir = Path(base_dir) |
| 57 | |
| 58 | @property |
| 59 | def files_dir(self) -> Path: |
| 60 | """The object's directory (created on first access).""" |
| 61 | path = object_files.object_files_dir(self.object_id, self.base_dir) |
| 62 | path.mkdir(parents=True, exist_ok=True) |
| 63 | return path |
| 64 | |
| 65 | def put(self, filename: str, content: bytes) -> None: |
| 66 | """Store (or replace) a file. Raises ValueError for a bad name or size.""" |
| 67 | if not isinstance(content, (bytes, bytearray)): |
| 68 | raise TypeError("_files.put content must be bytes") |
| 69 | try: |
| 70 | object_files.write_object_file( |
| 71 | self.object_id, |
| 72 | filename, |
| 73 | bytes(content), |
| 74 | self.base_dir, |
| 75 | overwrite=True, |
| 76 | max_bytes=max_object_file_bytes(), |
| 77 | ) |
| 78 | except (TypeError, AttributeError) as exc: |
| 79 | raise ValueError(f"Invalid filename: {filename!r}") from exc |
| 80 | |
| 81 | def get(self, filename: str) -> bytes: |
| 82 | """Return a file's bytes; FileNotFoundError when it does not exist.""" |
| 83 | try: |
| 84 | data, _meta = object_files.read_object_file(self.object_id, filename, self.base_dir) |
| 85 | except (TypeError, AttributeError) as exc: |
| 86 | raise ValueError(f"Invalid filename: {filename!r}") from exc |
| 87 | return data |
| 88 | |
| 89 | def delete(self, filename: str) -> None: |
| 90 | """Delete a file; deleting a missing file is not an error.""" |
| 91 | try: |
| 92 | object_files.delete_object_file(self.object_id, filename, self.base_dir) |
| 93 | except object_files.ObjectFileNotFoundError: |
| 94 | return |
| 95 | except (TypeError, AttributeError) as exc: |
| 96 | raise ValueError(f"Invalid filename: {filename!r}") from exc |
| 97 | |
| 98 | def list(self) -> list[dict[str, Any]]: |
| 99 | """Return ``[{"name", "size", "modified"}, ...]`` for this object's files.""" |
| 100 | return object_files.list_object_files(self.object_id, self.base_dir) |
| 101 | |
| 102 | def exists(self, filename: str) -> bool: |
| 103 | try: |
| 104 | self.get(filename) |
| 105 | except FileNotFoundError: |
| 106 | return False |
| 107 | return True |
| 108 | |
| 109 | |
| 110 | class CompositionError(RuntimeError): |
| 111 | """Base class for ``_runtime.load_object`` refusals.""" |
| 112 | |
| 113 | |
| 114 | class CompositionDeniedError(CompositionError, PermissionError): |
| 115 | """A user-namespace object tried to load another user's object.""" |
| 116 | |
| 117 | |
| 118 | class CompositionNotFoundError(CompositionError, LookupError): |
| 119 | """The requested object id does not resolve to an object.""" |
| 120 | |
| 121 | |
| 122 | class CompositionDepthError(CompositionError): |
| 123 | """Nested object executions exceeded MAX_COMPOSITION_DEPTH.""" |
| 124 | |
| 125 | |
| 126 | _depth = threading.local() |
| 127 | |
| 128 | |
| 129 | @contextmanager |
| 130 | def execution_frame(object_id: str) -> Iterator[None]: |
| 131 | """Count one object execution on this thread's call chain.""" |
| 132 | current = getattr(_depth, "value", 0) |
| 133 | if current >= MAX_COMPOSITION_DEPTH: |
| 134 | raise CompositionDepthError( |
| 135 | f"Object call depth limit ({MAX_COMPOSITION_DEPTH}) exceeded while " |
| 136 | f"executing {object_id}; check for an object calling itself." |
| 137 | ) |
| 138 | _depth.value = current + 1 |
| 139 | try: |
| 140 | yield |
| 141 | finally: |
| 142 | _depth.value = current |
| 143 | |
| 144 | |
| 145 | def _user_namespace(object_id: str) -> str | None: |
| 146 | """User id this id looks like it belongs to, or None. Deliberately loose: |
| 147 | anything starting ``u_<digits>_`` counts, even if the strict id regex |
| 148 | would not parse it, so an odd spelling can never dodge the rule.""" |
| 149 | parsed = parse_user_object_id(object_id) |
| 150 | if parsed: |
| 151 | return str(parsed[0]) |
| 152 | match = _USERISH_RE.match(object_id) |
| 153 | return match.group(1) if match else None |
| 154 | |
| 155 | |
| 156 | def _path_namespace(path: Path) -> str | None: |
| 157 | """User id when a resolved source lives under a ``users/<uid>/`` directory.""" |
| 158 | parts = path.parts |
| 159 | for index in range(len(parts) - 2): |
| 160 | if parts[index] == "users" and parts[index + 1].isdigit(): |
| 161 | return parts[index + 1] |
| 162 | return None |
| 163 | |
| 164 | |
| 165 | class ObjectComposer: |
| 166 | """``_runtime``: lets one object load another (composition). |
| 167 | |
| 168 | Rule (fail closed): a user-namespace object (``u_<uid>_...``) may load |
| 169 | objects in its own namespace or non-user (system/package) objects that |
| 170 | opt in with a module-level ``USER_CALLABLE = True`` (object_user_access), |
| 171 | never ``u_<other>_*`` and never an object that has not opted in. Non-user objects may load anything. Loading never skips |
| 172 | the callee's own checks: ``execute`` on the result counts toward the depth |
| 173 | limit, and a locked check may not run objects at all. |
| 174 | """ |
| 175 | |
| 176 | def __init__(self, caller_object_id: str, base_dir: Path | str = DEFAULT_DATA_DIR): |
| 177 | self.caller_object_id = caller_object_id |
| 178 | self.base_dir = Path(base_dir) |
| 179 | |
| 180 | def load_object(self, object_id: str, *_ignored: Any, **_ignored_kw: Any): |
| 181 | """Return a loaded object (``.execute(method, payload)``, ``.state_manager``, |
| 182 | ``.file_manager``, ``.logger``, ``.object_id``) for an object id. |
| 183 | |
| 184 | A user-namespace target is never loaded into this process: the caller |
| 185 | gets an ``object_sandbox.SandboxedObject`` whose ``execute`` runs the |
| 186 | code in an isolated worker (docs/runtime-contract.md "User Object |
| 187 | Isolation").""" |
| 188 | path = self.resolve(object_id) |
| 189 | |
| 190 | import object_sandbox |
| 191 | |
| 192 | if object_sandbox.is_user_code(object_id, path): |
| 193 | return object_sandbox.SandboxedObject(path=path, object_id=object_id, base_dir=self.base_dir) |
| 194 | |
| 195 | from python_object_runtime import PythonObject |
| 196 | |
| 197 | return PythonObject(path=path, object_id=object_id, base_dir=self.base_dir) |
| 198 | |
| 199 | def resolve(self, object_id: str) -> Path: |
| 200 | """Apply every load rule and return the target's source path. |
| 201 | |
| 202 | Shared by ``load_object`` and the sandbox's ``_runtime`` proxy, so the |
| 203 | namespace rule is enforced by one piece of code for both.""" |
| 204 | import object_records # lazy: sits below object_execution |
| 205 | |
| 206 | running = object_records.in_locked_check() |
| 207 | if running is not None: |
| 208 | raise object_records.LockedCheckWriteError( |
| 209 | f"Locked check {running!r} tried to load object {object_id!r}; a check only reads." |
| 210 | ) |
| 211 | if not isinstance(object_id, str) or not validate_object_id(object_id): |
| 212 | raise CompositionNotFoundError( |
| 213 | f"_runtime.load_object takes an object id, got {object_id!r}" |
| 214 | ) |
| 215 | |
| 216 | caller_ns = _user_namespace(self.caller_object_id) |
| 217 | target_ns = _user_namespace(object_id) |
| 218 | if caller_ns is not None and target_ns is not None and target_ns != caller_ns: |
| 219 | raise CompositionDeniedError( |
| 220 | f"Object {self.caller_object_id} may not load {object_id}: " |
| 221 | "it belongs to another user's namespace." |
| 222 | ) |
| 223 | |
| 224 | path = resolve_object_id(object_id) |
| 225 | if path is None or not path.exists(): |
| 226 | raise CompositionNotFoundError(f"Object not found: {object_id}") |
| 227 | resolved_ns = _path_namespace(path) |
| 228 | if caller_ns is not None and resolved_ns is not None and resolved_ns != caller_ns: |
| 229 | raise CompositionDeniedError( |
| 230 | f"Object {self.caller_object_id} may not load {object_id}: " |
| 231 | "it belongs to another user's namespace." |
| 232 | ) |
| 233 | if caller_ns is not None and resolved_ns is None and not object_user_access.is_user_callable(path): |
| 234 | raise CompositionDeniedError( |
| 235 | f"Object {self.caller_object_id} may not load {object_id}: it is a system " |
| 236 | f"object that does not allow user code to call it (its source must set " |
| 237 | f"{object_user_access.USER_CALLABLE} = True to opt in)." |
| 238 | ) |
| 239 | return path |