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_sandbox.py · 121.7 KB · 2985 lines
| 1 | """User-namespace objects (``u_<uid>_*``) run here, behind an OS wall. |
| 2 | |
| 3 | Why this exists |
| 4 | --------------- |
| 5 | The askrobots object server screened user code with an AST allow-list that |
| 6 | still let ``os``, ``pathlib``, ``urllib`` and ``open()`` through; an offline |
| 7 | probe object read environment secrets, the server's code and another user's |
| 8 | object, wrote files and made HTTP calls. In this server, before this module, |
| 9 | an object could read ``DBBASIC_ADMIN_TOKEN`` from ``os.environ``, list and |
| 10 | write the data directory, run programs and open sockets -- acceptable only |
| 11 | because just admins could write source. A scanner is not a wall; the OS is. |
| 12 | So user code never runs in the server process, the admin warm pool or the |
| 13 | spawn path. It runs here: |
| 14 | |
| 15 | 1. **A fresh, single-use worker process** (``python -I -B object_sandbox.py |
| 16 | --worker``) started with a scrubbed environment (PATH, LANG, LC_*, TZ and |
| 17 | nothing else: no ``DBBASIC_*``, no tokens). |
| 18 | 2. **Before any user code is read**, the worker sets rlimits (CPU seconds, |
| 19 | address space, ``RLIMIT_FSIZE=0``, a small ``RLIMIT_NOFILE``, |
| 20 | ``RLIMIT_CORE=0``, ``RLIMIT_NPROC=0``) and then a Landlock domain that |
| 21 | handles every filesystem, network and scope right the running kernel |
| 22 | accepts, granting only read access to the Python installation's |
| 23 | ``sys.path`` directories (never the repo, data or objects directories). |
| 24 | Execute is denied everywhere; TCP bind/connect are denied for every port; |
| 25 | abstract UNIX sockets and signals cannot leave the domain. |
| 26 | 3. The parent reads the object's source and sends it over the pipe, so the |
| 27 | sandbox never needs the objects directory. ``_state_manager``, |
| 28 | ``_logger``, ``_files`` and ``_runtime`` in the worker are proxies: every |
| 29 | call is a message the parent validates, size-limits and performs with the |
| 30 | ordinary helpers bound to THAT object id. A worker that sends anything the |
| 31 | parent does not expect is killed, not argued with. |
| 32 | 4. The worker serves exactly one request and is then killed (its whole |
| 33 | process group). Spares are pre-started and already sandboxed, so the boot |
| 34 | cost is off the request path; a worker that ever held user code is never |
| 35 | reused, for anyone. |
| 36 | 5. **Warm parents.** A user who called recently has a fork server: a worker |
| 37 | booted exactly as above (sandbox uid, rlimits, Landlock) that never runs |
| 38 | user code and never sees a request's data. Each call of that user is a |
| 39 | child it forks, handed two fresh pipes as fds, which then behaves as the |
| 40 | single-use worker of point 4 (RLIMIT_NPROC=0 and RLIMIT_CPU set, a nested |
| 41 | Landlock domain, its own process group) and is SIGKILLed and reaped after |
| 42 | the call. A fork server belongs to one user and is never used for |
| 43 | another; when one cannot be started or misbehaves, calls take a spare. |
| 44 | By default only where Landlock scopes signals (ABI >= 6): below that, |
| 45 | another user's code could signal a long-lived warm parent |
| 46 | (``warm_parent_decision``; DBBASIC_USER_CODE_WARM_PARENTS=on opts in). |
| 47 | |
| 48 | Why these choices |
| 49 | ----------------- |
| 50 | - ``RLIMIT_NPROC = 0``: the brief worried it is unreliable because it counts |
| 51 | the uid's processes. It counts them, which is exactly why 0 works: the |
| 52 | kernel refuses fork/clone while ``processes(uid) >= limit``, and a running |
| 53 | worker always has at least one. The exception is a privileged process |
| 54 | (root or ``CAP_SYS_RESOURCE``), so the worker refuses to boot as root. |
| 55 | Landlock's execute denial covers ``exec`` independently; the two together |
| 56 | stop ``fork``, ``subprocess`` and ``os.system``. Threads count too, so |
| 57 | user code cannot start threads. |
| 58 | - **A different uid, from a root launcher** (object_sandbox_launcher.py). |
| 59 | Landlock has no right for metadata changes, so a worker running as the |
| 60 | server's uid could ``chmod``/``utime`` every file the server owns and |
| 61 | ``stat`` its way around other customers' objects. A worker started by the |
| 62 | launcher runs as a dedicated sandbox user that owns nothing, the data and |
| 63 | objects directories are mode 0700 (``protect_private_dirs``), and the |
| 64 | server cannot be signalled by a uid that is not its own. |
| 65 | - **Landlock ABI >= 4 with the launcher.** ABI 4 adds TCP control. Until |
| 66 | ABI 6 a Landlocked process may still ``kill()`` any process of its own uid; |
| 67 | with uid separation that uid is the sandbox user, not the server. A worker |
| 68 | that finds itself running as the server's uid on an ABI < 6 kernel refuses |
| 69 | to boot. |
| 70 | - **Every right the kernel accepts is handled**, found by asking the kernel |
| 71 | bit by bit rather than from a table, so a newer kernel's new right (for |
| 72 | example control over UNIX-socket resolution) is denied without a code |
| 73 | change. Only READ_FILE/READ_DIR are ever granted. |
| 74 | - **One process per request**, forked from a per-user warm parent rather than |
| 75 | reused: reusing a process would keep module globals alive between callers |
| 76 | of the same object. A boot costs ~45 ms of CPU, so under load spares could |
| 77 | not keep up (a call waited for one); a fork costs well under a |
| 78 | millisecond. The parent holds nothing of any call: the per-call pipes go |
| 79 | to it as fds and the data travels only on them, so a child's memory holds |
| 80 | no earlier caller's payload (docs/runtime-contract.md "Warm parents"). |
| 81 | - **stdlib modules with C dependencies are imported before the wall** (see |
| 82 | ``_PRELOAD_MODULES``): after Landlock the shared libraries they link (for |
| 83 | example libcrypto) are unreadable, so ``import hashlib`` would fail later. |
| 84 | |
| 85 | What the wall does NOT cover (documented, not hidden): UDP and other socket |
| 86 | families Landlock does not mediate on the running kernel when the worker has |
| 87 | no network namespace of its own, signals between concurrently running |
| 88 | workers on kernels without Landlock signal scoping (ABI < 6: they share the |
| 89 | sandbox uid), CPU and cache side channels, kernel bugs, and anything a |
| 90 | *system* object does when user code calls it (that object runs on the |
| 91 | normal path with the caller's identity). |
| 92 | |
| 93 | Fail closed: without a reachable launcher, without Landlock ABI >= 4 |
| 94 | (macOS, older kernels, a container whose seccomp profile hides the |
| 95 | syscalls), or when the server runs as root, user objects are refused with |
| 96 | ``UserCodeIsolationUnavailableError`` (HTTP 503) unless |
| 97 | ``DBBASIC_USER_CODE_ISOLATION=unsafe-dev`` is set -- development only: the |
| 98 | same worker and proxies, without the kernel wall (and through the launcher |
| 99 | when one is running). |
| 100 | |
| 101 | This file is also the worker program. Its top level imports only the |
| 102 | standard library, so the worker never loads server code; parent-side code |
| 103 | imports server modules lazily. |
| 104 | """ |
| 105 | from __future__ import annotations |
| 106 | |
| 107 | import base64 |
| 108 | import json |
| 109 | import os |
| 110 | import re |
| 111 | import struct |
| 112 | import sys |
| 113 | import time |
| 114 | from datetime import datetime, timezone |
| 115 | |
| 116 | # ``typing`` and ``traceback`` are not imported at the top: this file is also |
| 117 | # the worker program, and on Python 3.14 ``traceback`` alone (it pulls in |
| 118 | # ``_colorize``) cost ~9 ms of every worker boot, measured with -X importtime. |
| 119 | TYPE_CHECKING = False |
| 120 | if TYPE_CHECKING: |
| 121 | from typing import Any |
| 122 | |
| 123 | # --------------------------------------------------------------------------- |
| 124 | # Configuration (parent side reads env; the worker gets values over the pipe) |
| 125 | # --------------------------------------------------------------------------- |
| 126 | |
| 127 | ISOLATION_ENV = "DBBASIC_USER_CODE_ISOLATION" |
| 128 | UNSAFE_DEV = "unsafe-dev" |
| 129 | POOL_SIZE_ENV = "DBBASIC_USER_CODE_POOL_SIZE" |
| 130 | TIMEOUT_ENV = "DBBASIC_USER_CODE_TIMEOUT_SECONDS" |
| 131 | CPU_SECONDS_ENV = "DBBASIC_USER_CODE_CPU_SECONDS" |
| 132 | MEMORY_MB_ENV = "DBBASIC_USER_CODE_MEMORY_MB" |
| 133 | MAX_FILES_ENV = "DBBASIC_USER_CODE_MAX_OPEN_FILES" |
| 134 | MAX_MESSAGE_BYTES_ENV = "DBBASIC_USER_CODE_MAX_MESSAGE_BYTES" |
| 135 | MAX_HELPER_CALLS_ENV = "DBBASIC_USER_CODE_MAX_HELPER_CALLS" |
| 136 | |
| 137 | DEFAULT_POOL_SIZE = 2 |
| 138 | DEFAULT_TIMEOUT_SECONDS = 30.0 |
| 139 | DEFAULT_CPU_SECONDS = 10 |
| 140 | DEFAULT_MEMORY_MB = 512 |
| 141 | DEFAULT_MAX_OPEN_FILES = 32 |
| 142 | DEFAULT_MAX_MESSAGE_BYTES = 8 * 1024 * 1024 |
| 143 | DEFAULT_MAX_HELPER_CALLS = 10_000 |
| 144 | BOOT_TIMEOUT_SECONDS = 10.0 |
| 145 | |
| 146 | # Warm parents (fork servers): one per user who called recently, each a |
| 147 | # booted sandbox worker that forks one fresh child per call. 0 turns the |
| 148 | # fast path off (every call takes a single-use spare, as before). |
| 149 | WARM_PARENTS_ENV = "DBBASIC_USER_CODE_WARM_PARENTS" # auto (default) | on | off |
| 150 | WARM_USERS_ENV = "DBBASIC_USER_CODE_WARM_USERS" |
| 151 | WARM_IDLE_ENV = "DBBASIC_USER_CODE_WARM_IDLE_SECONDS" |
| 152 | DEFAULT_WARM_USERS = 8 |
| 153 | # Warm parents live for many calls. Below this ABI Landlock cannot scope |
| 154 | # signals, so one user's code could signal (kill, stop) another user's warm |
| 155 | # parent, which shares the sandbox uid: "auto" turns them off there. |
| 156 | WARM_PARENTS_MIN_LANDLOCK_ABI = 6 |
| 157 | DEFAULT_WARM_IDLE_SECONDS = 600.0 |
| 158 | FORK_SERVER_MAX_CALLS = 1000 # then it is replaced (a fresh hash seed and memory layout) |
| 159 | FORK_SERVER_CONTROL_SECONDS = 2.0 # a fork or reap answer later than this retires it |
| 160 | FORK_SERVER_COOLDOWN_SECONDS = 60.0 # after a failure, that user takes the spare path for this long |
| 161 | |
| 162 | # With the launcher (uid separation): TCP control is the floor. A worker |
| 163 | # that runs as the server's own uid additionally needs signal scoping (6). |
| 164 | MIN_LANDLOCK_ABI = 4 |
| 165 | SAME_UID_MIN_LANDLOCK_ABI = 6 |
| 166 | |
| 167 | LAUNCHER_SOCKET_ENV = "DBBASIC_SANDBOX_LAUNCHER_SOCKET" |
| 168 | DEFAULT_LAUNCHER_SOCKET = "/run/dbbasic-sandbox/launcher.sock" |
| 169 | _LAUNCHER_PROTOCOL = 1 |
| 170 | _LAUNCHER_CACHE_SECONDS = 5.0 |
| 171 | |
| 172 | ISOLATION_ERROR_TYPE = "UserCodeIsolationUnavailableError" |
| 173 | PROTOCOL_ERROR_TYPE = "ObjectSandboxProtocolError" |
| 174 | _TIMEOUT_ERROR_TYPE = "ObjectExecutionTimeoutError" # == object_execution.TIMEOUT_ERROR_TYPE |
| 175 | _WORKER_ERROR_TYPE = "ObjectWorkerError" # == object_execution.WORKER_ERROR_TYPE |
| 176 | |
| 177 | # Environment keys a worker may inherit. Everything else -- DBBASIC_*, |
| 178 | # tokens, cloud credentials -- never reaches the process. |
| 179 | _ENV_ALLOW = ("PATH", "LANG", "TZ", "PYTHONHASHSEED", "PYTHONDONTWRITEBYTECODE") |
| 180 | _ENV_ALLOW_PREFIX = ("LC_",) |
| 181 | |
| 182 | # Imported in the worker before the wall goes up. Only modules whose C |
| 183 | # extension links a system library outside the Python tree need this (after |
| 184 | # the wall, libbz2/liblzma/libcrypto/libuuid are unreadable), plus the few |
| 185 | # nearly every object uses. Everything else in the stdlib imports normally |
| 186 | # later. Measured: the full "common stdlib" list cost ~40ms per worker boot; |
| 187 | # this one costs a fraction of that. |
| 188 | _PRELOAD_MODULES = ( |
| 189 | "json", "datetime", "re", "math", "random", "decimal", |
| 190 | "hashlib", "hmac", "zlib", "bz2", "lzma", "uuid", |
| 191 | ) |
| 192 | |
| 193 | _LENGTH = struct.Struct(">I") |
| 194 | _BYTES_TAG = "__dbbasic_bytes__" |
| 195 | |
| 196 | # A scheduled method (object_schedule, ``_schedule``) is named by its |
| 197 | # function name, not an HTTP verb. Public names only: a scheduled run can |
| 198 | # never reach a ``_helper`` or an injected ``_state_manager``. Defined here |
| 199 | # because the sandbox worker imports nothing but the standard library. |
| 200 | SCHEDULED_METHOD_RE = re.compile(r"[A-Za-z][A-Za-z0-9_]{0,59}") |
| 201 | |
| 202 | |
| 203 | def call_scheduled(func, payload): |
| 204 | """Call a scheduled method the way the askrobots runtime did -- with no |
| 205 | arguments -- unless its signature needs one, then with the payload.""" |
| 206 | import inspect |
| 207 | |
| 208 | try: |
| 209 | inspect.signature(func).bind() |
| 210 | except TypeError: |
| 211 | return func(payload) |
| 212 | except ValueError: # no introspectable signature |
| 213 | return func() |
| 214 | return func() |
| 215 | |
| 216 | |
| 217 | # --------------------------------------------------------------------------- |
| 218 | # Wire format (both sides): 4-byte big-endian length + UTF-8 JSON. Bytes |
| 219 | # values travel as {"__dbbasic_bytes__": "<base64>"}. |
| 220 | # --------------------------------------------------------------------------- |
| 221 | |
| 222 | |
| 223 | def _to_wire(value: Any) -> Any: |
| 224 | if isinstance(value, (bytes, bytearray)): |
| 225 | return {_BYTES_TAG: base64.b64encode(bytes(value)).decode("ascii")} |
| 226 | if isinstance(value, dict): |
| 227 | out = {} |
| 228 | for key, item in value.items(): |
| 229 | if not isinstance(key, str): |
| 230 | if isinstance(key, (int, float, bool)) or key is None: |
| 231 | key = json.dumps(key) |
| 232 | else: |
| 233 | raise TypeError(f"keys must be str, not {type(key).__name__}") |
| 234 | out[key] = _to_wire(item) |
| 235 | return out |
| 236 | if isinstance(value, (list, tuple)): |
| 237 | return [_to_wire(item) for item in value] |
| 238 | if value is None or isinstance(value, (str, int, float, bool)): |
| 239 | return value |
| 240 | raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable") |
| 241 | |
| 242 | |
| 243 | def _from_wire(value: Any) -> Any: |
| 244 | if isinstance(value, dict): |
| 245 | if len(value) == 1 and _BYTES_TAG in value: |
| 246 | raw = value[_BYTES_TAG] |
| 247 | if not isinstance(raw, str): |
| 248 | raise ValueError("bad bytes value") |
| 249 | return base64.b64decode(raw.encode("ascii"), validate=True) |
| 250 | return {key: _from_wire(item) for key, item in value.items()} |
| 251 | if isinstance(value, list): |
| 252 | return [_from_wire(item) for item in value] |
| 253 | return value |
| 254 | |
| 255 | |
| 256 | def _encode(message: dict[str, Any]) -> bytes: |
| 257 | body = json.dumps(_to_wire(message), separators=(",", ":")).encode("utf-8") |
| 258 | return _LENGTH.pack(len(body)) + body |
| 259 | |
| 260 | |
| 261 | def _utc_timestamp() -> str: |
| 262 | return datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z") |
| 263 | |
| 264 | |
| 265 | # --------------------------------------------------------------------------- |
| 266 | # Landlock (Linux), through ctypes. Syscall numbers 444/445/446 are the same |
| 267 | # on every architecture that has them (x86_64, aarch64, ...). |
| 268 | # --------------------------------------------------------------------------- |
| 269 | |
| 270 | _SYS_CREATE_RULESET = 444 |
| 271 | _SYS_ADD_RULE = 445 |
| 272 | _SYS_RESTRICT_SELF = 446 |
| 273 | _CREATE_RULESET_VERSION = 1 |
| 274 | _RULE_PATH_BENEATH = 1 |
| 275 | _PR_SET_NO_NEW_PRIVS = 38 |
| 276 | |
| 277 | FS_EXECUTE = 1 << 0 |
| 278 | FS_READ_FILE = 1 << 2 |
| 279 | FS_READ_DIR = 1 << 3 |
| 280 | NET_BIND_TCP = 1 << 0 |
| 281 | NET_CONNECT_TCP = 1 << 1 |
| 282 | SCOPE_ABSTRACT_UNIX_SOCKET = 1 << 0 |
| 283 | SCOPE_SIGNAL = 1 << 1 |
| 284 | |
| 285 | _libc = None |
| 286 | |
| 287 | |
| 288 | def _syscall(): |
| 289 | global _libc |
| 290 | if _libc is None: |
| 291 | import ctypes |
| 292 | |
| 293 | _libc = ctypes.CDLL(None, use_errno=True) |
| 294 | _libc.syscall.restype = ctypes.c_long |
| 295 | return _libc |
| 296 | |
| 297 | |
| 298 | def landlock_abi() -> int: |
| 299 | """The running kernel's Landlock ABI version, 0 when there is none. |
| 300 | |
| 301 | Tests monkeypatch this to simulate a kernel without Landlock.""" |
| 302 | if not sys.platform.startswith("linux"): |
| 303 | return 0 |
| 304 | try: |
| 305 | import ctypes |
| 306 | |
| 307 | libc = _syscall() |
| 308 | abi = libc.syscall(_SYS_CREATE_RULESET, None, ctypes.c_size_t(0), ctypes.c_uint32(_CREATE_RULESET_VERSION)) |
| 309 | except Exception: |
| 310 | return 0 |
| 311 | return int(abi) if abi > 0 else 0 |
| 312 | |
| 313 | |
| 314 | def _ruleset_attr(abi: int): |
| 315 | import ctypes |
| 316 | |
| 317 | class RulesetAttr(ctypes.Structure): |
| 318 | _fields_ = [ |
| 319 | ("handled_access_fs", ctypes.c_uint64), |
| 320 | ("handled_access_net", ctypes.c_uint64), |
| 321 | ("scoped", ctypes.c_uint64), |
| 322 | ] |
| 323 | |
| 324 | size = 8 if abi < 4 else 16 if abi < 6 else 24 |
| 325 | return RulesetAttr, size |
| 326 | |
| 327 | |
| 328 | def _try_ruleset(attr_cls, size: int, fs: int, net: int, scoped: int) -> int: |
| 329 | import ctypes |
| 330 | |
| 331 | attr = attr_cls(fs, net, scoped) |
| 332 | fd = _syscall().syscall(_SYS_CREATE_RULESET, ctypes.byref(attr), ctypes.c_size_t(size), ctypes.c_uint32(0)) |
| 333 | return int(fd) |
| 334 | |
| 335 | |
| 336 | def _supported_rights(abi: int) -> tuple[int, int, int]: |
| 337 | """Every fs/net/scope right this kernel accepts, asked one bit at a time. |
| 338 | |
| 339 | Discovered rather than tabulated so a kernel newer than this code still |
| 340 | has its new rights handled (= denied, since we grant only reads).""" |
| 341 | attr_cls, size = _ruleset_attr(abi) |
| 342 | found = [0, 0, 0] |
| 343 | fields = [0] if abi < 4 else [0, 1] if abi < 6 else [0, 1, 2] |
| 344 | for field in fields: |
| 345 | for bit in range(64): |
| 346 | values = [0, 0, 0] |
| 347 | values[field] = 1 << bit |
| 348 | fd = _try_ruleset(attr_cls, size, *values) |
| 349 | if fd >= 0: |
| 350 | os.close(fd) |
| 351 | found[field] |= 1 << bit |
| 352 | return found[0], found[1], found[2] |
| 353 | |
| 354 | |
| 355 | def _build_ruleset(read_paths: list[str], abi: int) -> tuple[int, dict[str, int]]: |
| 356 | """A Landlock ruleset fd that handles every right this kernel accepts and |
| 357 | grants only reads beneath ``read_paths``. The caller restricts with it |
| 358 | (``_restrict_self``) and closes it.""" |
| 359 | import ctypes |
| 360 | |
| 361 | libc = _syscall() |
| 362 | fs, net, scoped = _supported_rights(abi) |
| 363 | if not fs & FS_EXECUTE or not net & NET_CONNECT_TCP or not net & NET_BIND_TCP: |
| 364 | raise OSError("Landlock does not report execute and TCP control") |
| 365 | if abi >= 6 and (not scoped & SCOPE_SIGNAL or not scoped & SCOPE_ABSTRACT_UNIX_SOCKET): |
| 366 | raise OSError("Landlock does not report signal and abstract-socket scoping") |
| 367 | attr_cls, size = _ruleset_attr(abi) |
| 368 | ruleset_fd = _try_ruleset(attr_cls, size, fs, net, scoped) |
| 369 | if ruleset_fd < 0: |
| 370 | raise OSError(ctypes.get_errno(), "landlock_create_ruleset failed") |
| 371 | |
| 372 | class PathBeneath(ctypes.Structure): |
| 373 | _pack_ = 1 |
| 374 | _fields_ = [("allowed_access", ctypes.c_uint64), ("parent_fd", ctypes.c_int32)] |
| 375 | |
| 376 | try: |
| 377 | for path in read_paths: |
| 378 | try: |
| 379 | fd = os.open(path, os.O_PATH | os.O_CLOEXEC) |
| 380 | except OSError: |
| 381 | continue |
| 382 | try: |
| 383 | allowed = FS_READ_FILE | (FS_READ_DIR if os.path.isdir(path) else 0) |
| 384 | rule = PathBeneath(allowed & fs, fd) |
| 385 | if libc.syscall(_SYS_ADD_RULE, ruleset_fd, _RULE_PATH_BENEATH, ctypes.byref(rule), ctypes.c_uint32(0)) != 0: |
| 386 | raise OSError(ctypes.get_errno(), f"landlock_add_rule failed for {path}") |
| 387 | finally: |
| 388 | os.close(fd) |
| 389 | except BaseException: |
| 390 | os.close(ruleset_fd) |
| 391 | raise |
| 392 | return ruleset_fd, {"abi": abi, "fs": fs, "net": net, "scoped": scoped} |
| 393 | |
| 394 | |
| 395 | def _restrict_self(ruleset_fd: int) -> None: |
| 396 | import ctypes |
| 397 | |
| 398 | libc = _syscall() |
| 399 | if libc.prctl(_PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) != 0: |
| 400 | raise OSError(ctypes.get_errno(), "prctl(PR_SET_NO_NEW_PRIVS) failed") |
| 401 | if libc.syscall(_SYS_RESTRICT_SELF, ruleset_fd, ctypes.c_uint32(0)) != 0: |
| 402 | raise OSError(ctypes.get_errno(), "landlock_restrict_self failed") |
| 403 | |
| 404 | |
| 405 | def _apply_landlock(read_paths: list[str], abi: int) -> dict[str, int]: |
| 406 | ruleset_fd, info = _build_ruleset(read_paths, abi) |
| 407 | try: |
| 408 | _restrict_self(ruleset_fd) |
| 409 | finally: |
| 410 | os.close(ruleset_fd) |
| 411 | return info |
| 412 | |
| 413 | |
| 414 | def _overlaps(path: str, others: list[str]) -> bool: |
| 415 | for other in others: |
| 416 | if path == other or path.startswith(other.rstrip("/") + "/") or other.startswith(path.rstrip("/") + "/"): |
| 417 | return True |
| 418 | return False |
| 419 | |
| 420 | |
| 421 | def _python_read_paths(deny: list[str]) -> list[str]: |
| 422 | """The interpreter's own sys.path directories (stdlib, lib-dynload, |
| 423 | site-packages), minus anything overlapping the server's repo, data or |
| 424 | objects directories. An editable install puts the repo itself on |
| 425 | sys.path; the overlap rule drops it.""" |
| 426 | paths = [] |
| 427 | candidates = [p for p in sys.path if p and os.path.isabs(p)] |
| 428 | candidates.append("/usr/share/zoneinfo") # zoneinfo without tzdata |
| 429 | for candidate in candidates: |
| 430 | real = os.path.realpath(candidate) |
| 431 | if not os.path.exists(real) or _overlaps(real, deny) or real in paths: |
| 432 | continue |
| 433 | paths.append(real) |
| 434 | return paths |
| 435 | |
| 436 | |
| 437 | # --------------------------------------------------------------------------- |
| 438 | # Worker side |
| 439 | # --------------------------------------------------------------------------- |
| 440 | |
| 441 | |
| 442 | class _WorkerChannel: |
| 443 | def __init__(self, read_fd: int, write_fd: int): |
| 444 | self.read_fd = read_fd |
| 445 | self.write_fd = write_fd |
| 446 | |
| 447 | def send(self, message: dict[str, Any]) -> None: |
| 448 | data = _encode(message) |
| 449 | view = memoryview(data) |
| 450 | while view: |
| 451 | written = os.write(self.write_fd, view) |
| 452 | view = view[written:] |
| 453 | |
| 454 | def _read_exact(self, size: int) -> bytes: |
| 455 | chunks = [] |
| 456 | while size: |
| 457 | chunk = os.read(self.read_fd, min(size, 1 << 20)) |
| 458 | if not chunk: |
| 459 | raise EOFError("parent closed the pipe") |
| 460 | chunks.append(chunk) |
| 461 | size -= len(chunk) |
| 462 | return b"".join(chunks) |
| 463 | |
| 464 | def recv(self) -> dict[str, Any]: |
| 465 | (length,) = _LENGTH.unpack(self._read_exact(4)) |
| 466 | return _from_wire(json.loads(self._read_exact(length).decode("utf-8"))) |
| 467 | |
| 468 | |
| 469 | # Mirrors of the server-side exception classes, so ``except |
| 470 | # PermissionError`` and the error-type names in results match in-process |
| 471 | # execution exactly. |
| 472 | class ObjectLoadError(Exception): |
| 473 | pass |
| 474 | |
| 475 | |
| 476 | class MethodNotSupportedError(Exception): |
| 477 | pass |
| 478 | |
| 479 | |
| 480 | class ObjectMethodExecutionError(Exception): |
| 481 | pass |
| 482 | |
| 483 | |
| 484 | class CompositionError(RuntimeError): |
| 485 | pass |
| 486 | |
| 487 | |
| 488 | class CompositionDeniedError(CompositionError, PermissionError): |
| 489 | pass |
| 490 | |
| 491 | |
| 492 | class CompositionNotFoundError(CompositionError, LookupError): |
| 493 | pass |
| 494 | |
| 495 | |
| 496 | class CompositionDepthError(CompositionError): |
| 497 | pass |
| 498 | |
| 499 | |
| 500 | class ScheduleError(ValueError): |
| 501 | """A _schedule/_unschedule call the scheduler refuses (a ValueError, so |
| 502 | ``except ValueError`` in ported objects still catches it).""" |
| 503 | |
| 504 | |
| 505 | # Names an object answers HTTP with. Scheduling one would make the daemon |
| 506 | # call the request handler with no request: refused, whatever the case. |
| 507 | HTTP_VERB_NAMES = frozenset({"GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"}) |
| 508 | |
| 509 | |
| 510 | _MIRRORED = { |
| 511 | cls.__name__: cls |
| 512 | for cls in (ScheduleError, CompositionError, CompositionDeniedError, CompositionNotFoundError, CompositionDepthError) |
| 513 | } |
| 514 | _BUILTIN_ERRORS = { |
| 515 | "ValueError", "TypeError", "KeyError", "LookupError", "IndexError", |
| 516 | "FileNotFoundError", "FileExistsError", "IsADirectoryError", "PermissionError", |
| 517 | "RuntimeError", "OSError", "NotImplementedError", "AttributeError", |
| 518 | } |
| 519 | |
| 520 | |
| 521 | def _remote_exception(error: Any) -> BaseException: |
| 522 | if not isinstance(error, dict): |
| 523 | return RuntimeError("helper call failed") |
| 524 | name = str(error.get("type") or "RuntimeError") |
| 525 | message = str(error.get("message") or "") |
| 526 | if name in _MIRRORED: |
| 527 | return _MIRRORED[name](message) |
| 528 | if name in _BUILTIN_ERRORS: |
| 529 | return getattr(__import__("builtins"), name)(message) |
| 530 | # A server-side class (InvalidObjectFilenameError, ...) keeps its name and |
| 531 | # its nearest builtin base, so ``except ValueError`` still catches it. |
| 532 | base = getattr(__import__("builtins"), str(error.get("base") or ""), None) |
| 533 | if not (isinstance(base, type) and issubclass(base, Exception)): |
| 534 | base = RuntimeError |
| 535 | return type(name, (base,), {})(message) |
| 536 | |
| 537 | |
| 538 | class _Remote: |
| 539 | """Base for helper proxies: one call = one round trip to the parent.""" |
| 540 | |
| 541 | def __init__(self, channel: _WorkerChannel, helper: str, handle: int): |
| 542 | object.__setattr__(self, "_channel", channel) |
| 543 | object.__setattr__(self, "_helper", helper) |
| 544 | object.__setattr__(self, "_handle", handle) |
| 545 | |
| 546 | def _call(self, op: str, *args: Any, **kwargs: Any) -> Any: |
| 547 | channel = object.__getattribute__(self, "_channel") |
| 548 | channel.send({ |
| 549 | "t": "call", |
| 550 | "helper": object.__getattribute__(self, "_helper"), |
| 551 | "h": object.__getattribute__(self, "_handle"), |
| 552 | "op": op, |
| 553 | "args": list(args), |
| 554 | "kwargs": kwargs, |
| 555 | }) |
| 556 | reply = channel.recv() |
| 557 | if reply.get("t") != "reply": |
| 558 | raise RuntimeError("unexpected reply from the object server") |
| 559 | if reply.get("ok"): |
| 560 | return reply.get("value") |
| 561 | raise _remote_exception(reply.get("error")) |
| 562 | |
| 563 | |
| 564 | class StateManagerProxy(_Remote): |
| 565 | def get(self, key, default=None): |
| 566 | return self._call("get", key, default) |
| 567 | |
| 568 | def set(self, key, value): |
| 569 | return self._call("set", key, value) |
| 570 | |
| 571 | def increment(self, key, delta=1): |
| 572 | return self._call("increment", key, delta) |
| 573 | |
| 574 | def delete(self, key): |
| 575 | return self._call("delete", key) |
| 576 | |
| 577 | def delete_many(self, keys): |
| 578 | return self._call("delete_many", list(keys)) |
| 579 | |
| 580 | def update(self, set_items, *, after_set=None): |
| 581 | if after_set is not None: |
| 582 | raise TypeError("update(after_set=...) is not available to user objects") |
| 583 | return self._call("update", dict(set_items)) |
| 584 | |
| 585 | def get_all(self): |
| 586 | return self._call("get_all") |
| 587 | |
| 588 | def reload(self): |
| 589 | return self._call("reload") |
| 590 | |
| 591 | |
| 592 | class LoggerProxy(_Remote): |
| 593 | def log(self, level, message, **fields): |
| 594 | return self._call("log", level, message, **fields) |
| 595 | |
| 596 | def debug(self, message, **fields): |
| 597 | return self._call("debug", message, **fields) |
| 598 | |
| 599 | def info(self, message, **fields): |
| 600 | return self._call("info", message, **fields) |
| 601 | |
| 602 | def warning(self, message, **fields): |
| 603 | return self._call("warning", message, **fields) |
| 604 | |
| 605 | def error(self, message, **fields): |
| 606 | return self._call("error", message, **fields) |
| 607 | |
| 608 | def critical(self, message, **fields): |
| 609 | return self._call("critical", message, **fields) |
| 610 | |
| 611 | def get_logs(self, *, level=None, limit=None, offset=0, **filters): |
| 612 | return self._call("get_logs", level=level, limit=limit, offset=offset, **filters) |
| 613 | |
| 614 | |
| 615 | class FileStoreProxy(_Remote): |
| 616 | def put(self, filename, content): |
| 617 | if not isinstance(content, (bytes, bytearray)): |
| 618 | raise TypeError("_files.put content must be bytes") |
| 619 | return self._call("put", filename, bytes(content)) |
| 620 | |
| 621 | def get(self, filename): |
| 622 | return self._call("get", filename) |
| 623 | |
| 624 | def delete(self, filename): |
| 625 | return self._call("delete", filename) |
| 626 | |
| 627 | def list(self): |
| 628 | return self._call("list") |
| 629 | |
| 630 | def exists(self, filename): |
| 631 | return self._call("exists", filename) |
| 632 | |
| 633 | @property |
| 634 | def files_dir(self): |
| 635 | raise PermissionError("_files.files_dir is not available to user objects; use put/get/list") |
| 636 | |
| 637 | |
| 638 | class LoadedObjectProxy(_Remote): |
| 639 | """What ``_runtime.load_object`` returns inside the sandbox.""" |
| 640 | |
| 641 | def __init__(self, channel, handle: int, object_id: str): |
| 642 | super().__init__(channel, "object", handle) |
| 643 | object.__setattr__(self, "object_id", object_id) |
| 644 | object.__setattr__(self, "state_manager", StateManagerProxy(channel, "state", handle)) |
| 645 | object.__setattr__(self, "logger", LoggerProxy(channel, "log", handle)) |
| 646 | object.__setattr__(self, "file_manager", FileStoreProxy(channel, "files", handle)) |
| 647 | |
| 648 | def execute(self, method, payload): |
| 649 | return self._call("execute", method, payload) |
| 650 | |
| 651 | |
| 652 | class ComposerProxy(_Remote): |
| 653 | def load_object(self, object_id, *_ignored, **_ignored_kw): |
| 654 | info = self._call("load_object", object_id) |
| 655 | return LoadedObjectProxy(object.__getattribute__(self, "_channel"), int(info["h"]), info["object_id"]) |
| 656 | |
| 657 | |
| 658 | class ScheduleProxy(_Remote): |
| 659 | def schedule(self, interval_seconds, method_name): |
| 660 | return self._call("schedule", interval_seconds, method_name) |
| 661 | |
| 662 | def unschedule(self, method_name=None): |
| 663 | return self._call("unschedule", method_name) |
| 664 | |
| 665 | |
| 666 | def _schedule_helpers(channel, module): |
| 667 | """``_schedule``/``_unschedule`` for the object in this worker. They take |
| 668 | no object id: the parent binds every call to the object it is running.""" |
| 669 | proxy = ScheduleProxy(channel, "schedule", 0) |
| 670 | |
| 671 | def _schedule(interval_seconds, method_name): |
| 672 | if isinstance(method_name, str) and not callable(getattr(module, method_name, None)): |
| 673 | raise ScheduleError(f"this object has no function {method_name!r} to schedule") |
| 674 | return proxy.schedule(interval_seconds, method_name) |
| 675 | |
| 676 | def _unschedule(method_name=None): |
| 677 | return proxy.unschedule(method_name) |
| 678 | |
| 679 | return _schedule, _unschedule |
| 680 | |
| 681 | |
| 682 | def _set_rlimits(limits: dict[str, int], strict: bool, fork_server: bool = False) -> None: |
| 683 | """The worker's rlimits. A fork server (it never runs user code) keeps |
| 684 | RLIMIT_NPROC and RLIMIT_CPU: it must fork, and it lives for many calls. |
| 685 | Each of its children sets both before reading anything |
| 686 | (``_set_call_rlimits``); the rest are inherited.""" |
| 687 | import resource |
| 688 | import signal |
| 689 | |
| 690 | signal.signal(signal.SIGXFSZ, signal.SIG_IGN) # EFBIG instead of death |
| 691 | wanted = [ |
| 692 | ("RLIMIT_CORE", 0, 0), |
| 693 | ("RLIMIT_FSIZE", 0, 0), |
| 694 | ("RLIMIT_NOFILE", limits["nofile"], limits["nofile"]), |
| 695 | ] |
| 696 | if not fork_server: |
| 697 | wanted += [("RLIMIT_CPU", limits["cpu"], limits["cpu"] + 1), ("RLIMIT_NPROC", 0, 0)] |
| 698 | if sys.platform.startswith("linux"): |
| 699 | address_space = _address_space_limit(limits["as"]) |
| 700 | wanted.append(("RLIMIT_AS", address_space, address_space)) |
| 701 | _setrlimits(wanted, strict) |
| 702 | |
| 703 | |
| 704 | def _address_space_limit(configured: int) -> int: |
| 705 | """The ``RLIMIT_AS`` for a memory cap of ``configured`` bytes. |
| 706 | |
| 707 | A free-threaded build's allocator reserves about 1 GiB of address space |
| 708 | before any of this runs (lazily committed, so it is not memory in use). A |
| 709 | 512 MiB cap set afterwards is already exceeded: every new mapping fails |
| 710 | at once (a libc malloc that must grow, an extension module's dlopen, a |
| 711 | thread stack), so user code hits MemoryError in ``gc.get_objects()``, |
| 712 | while what the interpreter already reserved is not capped at all. There |
| 713 | the cap is counted on top of the address space the interpreter already |
| 714 | holds. Other builds hold about 25 MiB and keep the absolute cap.""" |
| 715 | if "t" not in getattr(sys, "abiflags", ""): |
| 716 | return configured |
| 717 | try: |
| 718 | with open("/proc/self/statm") as handle: |
| 719 | held = int(handle.read().split()[0]) * os.sysconf("SC_PAGE_SIZE") |
| 720 | except (OSError, ValueError, IndexError): |
| 721 | return configured |
| 722 | return held + configured |
| 723 | |
| 724 | |
| 725 | def _set_call_rlimits(limits: dict[str, int], strict: bool) -> None: |
| 726 | _setrlimits([("RLIMIT_CPU", limits["cpu"], limits["cpu"] + 1), ("RLIMIT_NPROC", 0, 0)], strict) |
| 727 | |
| 728 | |
| 729 | def _setrlimits(wanted: list, strict: bool) -> None: |
| 730 | import resource |
| 731 | |
| 732 | for name, soft, hard in wanted: |
| 733 | try: |
| 734 | resource.setrlimit(getattr(resource, name), (soft, hard)) |
| 735 | except (ValueError, OSError, AttributeError): |
| 736 | if strict: |
| 737 | raise |
| 738 | |
| 739 | |
| 740 | def _worker_boot(channel: _WorkerChannel, config: dict[str, Any]) -> dict[str, Any]: |
| 741 | landlock = config.get("mode") != UNSAFE_DEV |
| 742 | fork_server = config.get("fork_server") is True |
| 743 | for name in _PRELOAD_MODULES: |
| 744 | try: |
| 745 | __import__(name) |
| 746 | except Exception: |
| 747 | pass |
| 748 | if landlock: |
| 749 | if os.geteuid() == 0: |
| 750 | raise OSError("refusing to sandbox user code as root: RLIMIT_NPROC does not bind root") |
| 751 | abi = landlock_abi() |
| 752 | if abi < int(config.get("min_abi", MIN_LANDLOCK_ABI)): |
| 753 | raise OSError(f"Landlock ABI {abi} is below the required {config.get('min_abi')}") |
| 754 | # Belt and braces for the launcher: a worker that is (somehow) the |
| 755 | # server's own uid could signal it without Landlock signal scoping. |
| 756 | if os.getuid() == config.get("server_uid") and config.get("separated"): |
| 757 | raise OSError("the launcher was meant to start this worker as another user") |
| 758 | if os.getuid() == config.get("server_uid") and abi < SAME_UID_MIN_LANDLOCK_ABI: |
| 759 | raise OSError(f"running as the server's uid needs Landlock ABI >= {SAME_UID_MIN_LANDLOCK_ABI}, " |
| 760 | f"this kernel has {abi}") |
| 761 | _syscall() # load libc before NOFILE/AS tighten and before the wall |
| 762 | read_paths = _python_read_paths([str(p) for p in config.get("deny", [])]) |
| 763 | _set_rlimits(config["limits"], strict=True, fork_server=fork_server) |
| 764 | if fork_server: |
| 765 | # The same wall again, kept for the children: each one restricts |
| 766 | # itself with it, so it lives in a domain nested inside this |
| 767 | # one and Landlock refuses it ptrace (and, on ABI >= 6, signals) |
| 768 | # against this process. |
| 769 | global _CHILD_RULESET |
| 770 | _CHILD_RULESET, _info = _build_ruleset(read_paths, abi) |
| 771 | info = _apply_landlock(read_paths, abi) |
| 772 | info["read_paths"] = read_paths |
| 773 | return info |
| 774 | if fork_server and sys.platform.startswith("linux"): |
| 775 | # A fork server and its children call prctl through libc (ctypes), |
| 776 | # as the walled path above does. Load it now: ctypes imported after |
| 777 | # RLIMIT_AS is set raises MemoryError on a free-threaded build, whose |
| 778 | # allocator has already reserved more address space than the limit |
| 779 | # (about 1 GiB against the 512 MiB default), so every new mapping -- |
| 780 | # an extension module's dlopen included -- is refused. The fork |
| 781 | # server then died before its first fork and every call quietly took |
| 782 | # a single-use spare. |
| 783 | _syscall() |
| 784 | _set_rlimits(config["limits"], strict=False, fork_server=fork_server) |
| 785 | return {"abi": 0} |
| 786 | |
| 787 | |
| 788 | def _scrub(text: str, path: str) -> str: |
| 789 | """Hide the absolute path of the user's own file in free text.""" |
| 790 | import os |
| 791 | |
| 792 | if path and path != os.path.basename(path): |
| 793 | text = text.replace(path, os.path.basename(path)) |
| 794 | return text |
| 795 | |
| 796 | |
| 797 | def user_traceback(exc: BaseException, path: str, source: str | None = None) -> str: |
| 798 | """The part of a failure a customer may see: only frames from their own |
| 799 | source file, named by file name (not the server's data directory) with |
| 800 | their own line numbers. Server frames and paths (/opt/..., /data/...) |
| 801 | are left out; the exception line itself is added by the caller.""" |
| 802 | import os |
| 803 | import traceback |
| 804 | |
| 805 | name = os.path.basename(path) |
| 806 | source_lines = source.splitlines() if isinstance(source, str) else [] |
| 807 | lines: list[str] = [] |
| 808 | for frame in traceback.extract_tb(exc.__traceback__): |
| 809 | if frame.filename != path: |
| 810 | continue |
| 811 | lines.append(f' File "{name}", line {frame.lineno}, in {frame.name}') |
| 812 | # The worker cannot read the file back (the wall); the source it was |
| 813 | # handed is the same text. |
| 814 | text = frame.line |
| 815 | if not text and frame.lineno and 0 < frame.lineno <= len(source_lines): |
| 816 | text = source_lines[frame.lineno - 1] |
| 817 | if text: |
| 818 | lines.append(f" {text.strip()}") |
| 819 | if isinstance(exc, SyntaxError) and exc.lineno: |
| 820 | lines.append(f' File "{name}", line {exc.lineno}') |
| 821 | if not lines: |
| 822 | return "" |
| 823 | return "Traceback (most recent call last):\n" + "\n".join(lines) + "\n" |
| 824 | |
| 825 | |
| 826 | def _worker_execute(channel: _WorkerChannel, request: dict[str, Any]) -> dict[str, Any]: |
| 827 | import types |
| 828 | |
| 829 | object_id = str(request.get("object_id") or "") |
| 830 | named = request.get("named") is True |
| 831 | method_name = str(request.get("method") or "GET") |
| 832 | if not named: |
| 833 | method_name = method_name.upper() |
| 834 | path = str(request.get("path") or object_id) |
| 835 | payload = request.get("payload") or {} |
| 836 | source = request.get("source") |
| 837 | try: |
| 838 | module = types.ModuleType("_dbbasic_object_" + "".join(c if c.isalnum() or c == "_" else "_" for c in object_id)) |
| 839 | module.__file__ = path |
| 840 | module.__package__ = "" |
| 841 | try: |
| 842 | exec(compile(source, path, "exec"), module.__dict__) |
| 843 | except Exception as exc: |
| 844 | raise ObjectLoadError( |
| 845 | f"Failed to load object {object_id}: " |
| 846 | f"{type(exc).__name__}: {_scrub(str(exc), path)}\n{user_traceback(exc, path, source)}" |
| 847 | ) from exc |
| 848 | # Helpers are injected after the module body runs, as PythonObject does. |
| 849 | module._state_manager = StateManagerProxy(channel, "state", 0) |
| 850 | module._logger = LoggerProxy(channel, "log", 0) |
| 851 | module._files = FileStoreProxy(channel, "files", 0) |
| 852 | module._runtime = ComposerProxy(channel, "runtime", 0) |
| 853 | module._schedule, module._unschedule = _schedule_helpers(channel, module) |
| 854 | if named and not SCHEDULED_METHOD_RE.fullmatch(method_name): |
| 855 | raise MethodNotSupportedError(f"{method_name!r} is not a schedulable method name") |
| 856 | func = getattr(module, method_name, None) |
| 857 | if not callable(func): |
| 858 | available = [n for n in ("GET", "POST", "PUT", "DELETE") if callable(getattr(module, n, None))] |
| 859 | raise MethodNotSupportedError( |
| 860 | f"Method {method_name} not supported by object {object_id}. Available methods: {available}" |
| 861 | ) |
| 862 | try: |
| 863 | output = call_scheduled(func, payload) if named else func(payload) |
| 864 | except CompositionDepthError: |
| 865 | raise |
| 866 | except Exception as exc: |
| 867 | raise ObjectMethodExecutionError( |
| 868 | f"{method_name} failed for object {object_id}: " |
| 869 | f"{type(exc).__name__}: {_scrub(str(exc), path)}\n{user_traceback(exc, path, source)}" |
| 870 | ) from exc |
| 871 | except BaseException as exc: |
| 872 | return { |
| 873 | "t": "result", |
| 874 | "ok": False, |
| 875 | "error": { |
| 876 | "type": type(exc).__name__, |
| 877 | "message": str(exc), |
| 878 | "traceback": "", # the message carries the customer-safe frames |
| 879 | }, |
| 880 | } |
| 881 | try: |
| 882 | _encode({"result": output}) |
| 883 | except (TypeError, ValueError) as exc: |
| 884 | return { |
| 885 | "t": "result", |
| 886 | "ok": False, |
| 887 | "error": {"type": _WORKER_ERROR_TYPE, "message": f"Object result can't be returned: {exc}", "traceback": ""}, |
| 888 | } |
| 889 | return {"t": "result", "ok": True, "result": output} |
| 890 | |
| 891 | |
| 892 | def _serve_one(channel: _WorkerChannel) -> int: |
| 893 | """Read ONE run request, execute it, send the result.""" |
| 894 | try: |
| 895 | request = channel.recv() |
| 896 | except BaseException: |
| 897 | return 0 |
| 898 | if request.get("t") != "run": |
| 899 | return 2 |
| 900 | try: |
| 901 | response = _worker_execute(channel, request) |
| 902 | except BaseException as exc: # a broken proxy round trip, EOF, ... |
| 903 | response = {"t": "result", "ok": False, "error": {"type": type(exc).__name__, "message": str(exc), "traceback": ""}} |
| 904 | try: |
| 905 | channel.send(response) |
| 906 | except BaseException: |
| 907 | return 4 |
| 908 | return 0 |
| 909 | |
| 910 | |
| 911 | def _worker_main() -> int: |
| 912 | # The protocol gets private fds; 0/1/2 point at /dev/null so print() and |
| 913 | # input() in user code cannot corrupt the stream or spam server logs. |
| 914 | proto_in = os.dup(0) |
| 915 | proto_out = os.dup(1) |
| 916 | devnull = os.open(os.devnull, os.O_RDWR) |
| 917 | for fd in (0, 1, 2): |
| 918 | os.dup2(devnull, fd) |
| 919 | os.close(devnull) |
| 920 | channel = _WorkerChannel(proto_in, proto_out) |
| 921 | try: |
| 922 | config = channel.recv() |
| 923 | if config.get("t") != "boot": |
| 924 | return 2 |
| 925 | info = _worker_boot(channel, config) |
| 926 | except BaseException as exc: |
| 927 | try: |
| 928 | channel.send({"t": "boot_error", "message": f"{type(exc).__name__}: {exc}"}) |
| 929 | except BaseException: |
| 930 | pass |
| 931 | return 3 |
| 932 | channel.send({"t": "ready", **{k: v for k, v in info.items() if k != "read_paths"}}) |
| 933 | if config.get("fork_server") is True: |
| 934 | return _fork_server_main(channel, config) |
| 935 | return _serve_one(channel) |
| 936 | |
| 937 | |
| 938 | # -- fork server (one per user; see "Warm parents" in docs/runtime-contract.md) |
| 939 | # |
| 940 | # A fork server is a booted worker -- sandbox uid, rlimits, Landlock -- that |
| 941 | # never runs user code and never sees a request's data. Per call the server |
| 942 | # sends it ONE control message, {"t": "fork", "id": N}, with two fresh pipe |
| 943 | # fds attached (SCM_RIGHTS); it forks a child that takes those pipes as its |
| 944 | # own channel and speaks the ordinary single-use protocol with the server |
| 945 | # directly. Source, payload, helper calls and results travel only on the |
| 946 | # child's pipes, so nothing of one call is ever in the fork server's memory |
| 947 | # to be copied into the next child. After the result the server sends |
| 948 | # {"t": "reap", "id": N}: the fork server SIGKILLs and reaps that child. |
| 949 | # |
| 950 | # A child acknowledges its pipes with one byte on a private ack pipe before |
| 951 | # it reads anything from them, and closes that pipe before any user code |
| 952 | # runs. Only the child ever holds the pipe's write end. The fork server |
| 953 | # reads it only at reap, after the child is dead, and reports "received": |
| 954 | # end of file with no byte is the one answer that means "never took the |
| 955 | # call" (a pipe, unlike a socket, has no reset to tell apart from it). Such |
| 956 | # a child never read its request, so the server may run the call again on a |
| 957 | # fresh child: that covers a forked-ahead child that died while it waited |
| 958 | # (SIGKILL is not instant, so a dying child can still take the pipes into |
| 959 | # its socket buffer). Nothing that acknowledged, or might have, is ever run |
| 960 | # again. |
| 961 | |
| 962 | _CHILD_RULESET = -1 |
| 963 | _PR_SET_PDEATHSIG = 1 |
| 964 | _PR_SET_DUMPABLE = 4 |
| 965 | _MAX_CONTROL_BYTES = 4096 |
| 966 | |
| 967 | |
| 968 | def _is_pipe_end(fd: int, writable: bool) -> bool: |
| 969 | import fcntl |
| 970 | import stat |
| 971 | |
| 972 | try: |
| 973 | if not stat.S_ISFIFO(os.fstat(fd).st_mode): |
| 974 | return False |
| 975 | mode = fcntl.fcntl(fd, fcntl.F_GETFL) & os.O_ACCMODE |
| 976 | except OSError: |
| 977 | return False |
| 978 | return mode == (os.O_WRONLY if writable else os.O_RDONLY) |
| 979 | |
| 980 | |
| 981 | def _recv_control(sock) -> tuple[dict[str, Any], list[int]]: |
| 982 | """One framed control message and the fds attached to it (at most two). |
| 983 | Raises EOFError when the server is gone, ValueError when it is malformed.""" |
| 984 | import array |
| 985 | import socket |
| 986 | |
| 987 | data = bytearray() |
| 988 | fds: list[int] = [] |
| 989 | try: |
| 990 | while True: |
| 991 | need = 4 if len(data) < 4 else 4 + _LENGTH.unpack(bytes(data[:4]))[0] |
| 992 | if len(data) >= 4 and need - 4 > _MAX_CONTROL_BYTES: |
| 993 | raise ValueError("oversize control message") |
| 994 | if len(data) == need and len(data) > 4: |
| 995 | return json.loads(bytes(data[4:]).decode("utf-8")), fds |
| 996 | msg, ancdata, flags, _addr = sock.recvmsg(need - len(data), socket.CMSG_SPACE(3 * 4)) |
| 997 | for level, kind, cdata in ancdata: |
| 998 | if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS: |
| 999 | got = array.array("i") |
| 1000 | got.frombytes(cdata[: len(cdata) - (len(cdata) % got.itemsize)]) |
| 1001 | fds.extend(got) |
| 1002 | if flags & getattr(socket, "MSG_CTRUNC", 0) or len(fds) > 2: |
| 1003 | raise ValueError("too many fds") |
| 1004 | if not msg: |
| 1005 | raise EOFError("server closed the control channel") |
| 1006 | data.extend(msg) |
| 1007 | except BaseException: |
| 1008 | for fd in fds: |
| 1009 | try: |
| 1010 | os.close(fd) |
| 1011 | except OSError: |
| 1012 | pass |
| 1013 | raise |
| 1014 | |
| 1015 | |
| 1016 | def _fork_server_main(channel: _WorkerChannel, config: dict[str, Any]) -> int: |
| 1017 | import gc |
| 1018 | import signal |
| 1019 | import socket |
| 1020 | |
| 1021 | import traceback # noqa: F401 -- once here, not in every failing call (~9 ms on 3.14) |
| 1022 | |
| 1023 | strict = config.get("mode") != UNSAFE_DEV |
| 1024 | if sys.platform.startswith("linux"): |
| 1025 | # Not dumpable: no process of the sandbox uid may ptrace it or read |
| 1026 | # its memory through /proc (Landlock forbids /proc anyway). |
| 1027 | if _syscall().prctl(_PR_SET_DUMPABLE, 0, 0, 0, 0) != 0 and strict: |
| 1028 | return 3 |
| 1029 | sock = socket.socket(fileno=os.dup(channel.read_fd)) |
| 1030 | me = os.getpid() |
| 1031 | running: dict[int, int] = {} # call id -> child pid, not yet reaped |
| 1032 | finished: dict[int, int] = {} # call id -> wait status of a child that exited by itself |
| 1033 | acks: dict[int, int] = {} # call id -> read end of its child's ack pipe, until reap |
| 1034 | # One child is forked ahead of time, between calls, and has done all of |
| 1035 | # its setup (fds, group, rlimits, nested Landlock); it waits on a private |
| 1036 | # socket for the two pipes of the next call, so a call does not wait for |
| 1037 | # a fork. |
| 1038 | standby: list = [] # [pid, our end of its handoff socket, its ack pipe's read end], or empty |
| 1039 | |
| 1040 | def fork_child() -> tuple[int, Any, int]: |
| 1041 | ours, theirs = socket.socketpair() |
| 1042 | ack_r, ack_w = os.pipe() |
| 1043 | gc.freeze() # keep this process's objects shared with every child (copy-on-write) |
| 1044 | try: |
| 1045 | pid = os.fork() |
| 1046 | except OSError: |
| 1047 | ours.close() |
| 1048 | theirs.close() |
| 1049 | os.close(ack_r) |
| 1050 | os.close(ack_w) |
| 1051 | return -1, None, -1 |
| 1052 | if pid == 0: |
| 1053 | _fork_child_main(theirs.fileno(), ack_w, config, me, strict) # never returns |
| 1054 | theirs.close() |
| 1055 | os.close(ack_w) # the child holds the only write end |
| 1056 | os.set_blocking(ack_r, False) |
| 1057 | return pid, ours, ack_r |
| 1058 | |
| 1059 | def kill_pid(pid: int) -> int | None: |
| 1060 | # Only ever called for a child not yet reaped, so the pid is still |
| 1061 | # that child's. It leads its own group; it cannot fork, but the |
| 1062 | # group goes too. |
| 1063 | for kill in (os.killpg, os.kill): |
| 1064 | try: |
| 1065 | kill(pid, signal.SIGKILL) |
| 1066 | except OSError: |
| 1067 | pass |
| 1068 | try: |
| 1069 | return os.waitpid(pid, 0)[1] |
| 1070 | except ChildProcessError: |
| 1071 | return None |
| 1072 | |
| 1073 | def drop_standby() -> None: |
| 1074 | if standby: |
| 1075 | pid, ours, ack_r = standby |
| 1076 | del standby[:] |
| 1077 | ours.close() |
| 1078 | os.close(ack_r) |
| 1079 | kill_pid(pid) |
| 1080 | |
| 1081 | def reap_exited() -> None: |
| 1082 | while True: |
| 1083 | try: |
| 1084 | pid, status = os.waitpid(-1, os.WNOHANG) |
| 1085 | except ChildProcessError: |
| 1086 | return |
| 1087 | if pid == 0: |
| 1088 | return |
| 1089 | if standby and standby[0] == pid: |
| 1090 | standby[1].close() |
| 1091 | os.close(standby[2]) |
| 1092 | del standby[:] |
| 1093 | for call_id, child in list(running.items()): |
| 1094 | if child == pid: |
| 1095 | finished[call_id] = status |
| 1096 | del running[call_id] |
| 1097 | |
| 1098 | def kill_and_reap(call_id) -> tuple[int | None, bool]: |
| 1099 | """Kill and reap a call's child: (wait status, did it acknowledge |
| 1100 | its pipes). Read only once the child is dead, so the answer is |
| 1101 | final; anything unclear counts as acknowledged.""" |
| 1102 | if call_id in finished: |
| 1103 | status = finished.pop(call_id) |
| 1104 | else: |
| 1105 | pid = running.pop(call_id, None) |
| 1106 | status = kill_pid(pid) if pid is not None else None |
| 1107 | ack_r = acks.pop(call_id, None) |
| 1108 | received = True |
| 1109 | if ack_r is not None: |
| 1110 | try: |
| 1111 | # b"" is end of file: the child (the only writer) is gone |
| 1112 | # and never wrote. A byte, a writer still open |
| 1113 | # (BlockingIOError) or any error all count as received. |
| 1114 | received = os.read(ack_r, 1) != b"" |
| 1115 | except OSError: |
| 1116 | pass |
| 1117 | finally: |
| 1118 | os.close(ack_r) |
| 1119 | return status, received |
| 1120 | |
| 1121 | def hand_over(fds: list[int]) -> tuple[int, int]: |
| 1122 | """Give a call's pipes to the standby child (or a fresh one): |
| 1123 | (pid, read end of its ack pipe), or (-1, -1).""" |
| 1124 | import array |
| 1125 | |
| 1126 | for _attempt in range(2): |
| 1127 | if standby: |
| 1128 | pid, ours, ack_r = standby |
| 1129 | del standby[:] |
| 1130 | else: |
| 1131 | pid, ours, ack_r = fork_child() |
| 1132 | if pid < 0: |
| 1133 | return -1, -1 |
| 1134 | try: |
| 1135 | ours.sendmsg([b"\0"], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))]) |
| 1136 | return pid, ack_r |
| 1137 | except OSError: |
| 1138 | os.close(ack_r) |
| 1139 | kill_pid(pid) # it died waiting: never hand a call to anything else |
| 1140 | finally: |
| 1141 | ours.close() |
| 1142 | return -1, -1 |
| 1143 | |
| 1144 | def refill() -> None: |
| 1145 | if not standby: |
| 1146 | pid, ours, ack_r = fork_child() |
| 1147 | if pid > 0: |
| 1148 | standby[:] = [pid, ours, ack_r] |
| 1149 | |
| 1150 | try: |
| 1151 | refill() |
| 1152 | while True: |
| 1153 | try: |
| 1154 | message, fds = _recv_control(sock) |
| 1155 | except (EOFError, OSError, ValueError): |
| 1156 | return 0 |
| 1157 | kind = message.get("t") if isinstance(message, dict) else None |
| 1158 | call_id = message.get("id") if isinstance(message, dict) else None |
| 1159 | valid_id = isinstance(call_id, int) and not isinstance(call_id, bool) |
| 1160 | if kind == "fork": |
| 1161 | pid = -1 |
| 1162 | if (valid_id and call_id not in running and call_id not in finished and len(fds) == 2 |
| 1163 | and _is_pipe_end(fds[0], writable=False) and _is_pipe_end(fds[1], writable=True)): |
| 1164 | reap_exited() |
| 1165 | pid, ack_r = hand_over(fds) |
| 1166 | if pid > 0: |
| 1167 | running[call_id] = pid |
| 1168 | acks[call_id] = ack_r |
| 1169 | for fd in fds: |
| 1170 | os.close(fd) |
| 1171 | channel.send({"t": "forked", "id": call_id, "ok": pid > 0}) |
| 1172 | elif kind == "reap" and valid_id: |
| 1173 | for fd in fds: |
| 1174 | os.close(fd) |
| 1175 | status, received = kill_and_reap(call_id) |
| 1176 | reap_exited() |
| 1177 | channel.send({"t": "reaped", "id": call_id, "status": status, "received": received}) |
| 1178 | refill() # between calls, so no call waits for this fork |
| 1179 | else: # "exit", or anything this side does not expect |
| 1180 | for fd in fds: |
| 1181 | os.close(fd) |
| 1182 | return 0 |
| 1183 | finally: |
| 1184 | drop_standby() |
| 1185 | for call_id in set(running) | set(acks): |
| 1186 | kill_and_reap(call_id) |
| 1187 | |
| 1188 | |
| 1189 | def _receive_call_pipes(handoff: int, ack: int) -> list[int]: |
| 1190 | """The two pipe fds of this child's call, sent by its fork server, and |
| 1191 | acknowledged on ``ack`` before anything is read from them: a child that |
| 1192 | dies before this byte never took the call (see the fork server). Both |
| 1193 | the handoff socket and the ack pipe are closed here, before any user |
| 1194 | code runs.""" |
| 1195 | import array |
| 1196 | import socket |
| 1197 | |
| 1198 | try: |
| 1199 | with socket.socket(fileno=handoff) as sock: |
| 1200 | _msg, ancdata, flags, _addr = sock.recvmsg(1, socket.CMSG_SPACE(3 * 4)) |
| 1201 | fds: list[int] = [] |
| 1202 | for level, kind, cdata in ancdata: |
| 1203 | if level == socket.SOL_SOCKET and kind == socket.SCM_RIGHTS: |
| 1204 | got = array.array("i") |
| 1205 | got.frombytes(cdata[: len(cdata) - (len(cdata) % got.itemsize)]) |
| 1206 | fds.extend(got) |
| 1207 | if (len(fds) != 2 or flags & getattr(socket, "MSG_CTRUNC", 0) |
| 1208 | or not _is_pipe_end(fds[0], writable=False) or not _is_pipe_end(fds[1], writable=True)): |
| 1209 | raise OSError("no call pipes from the fork server") |
| 1210 | if os.write(ack, b"\1") != 1: |
| 1211 | raise OSError("could not acknowledge the call pipes") |
| 1212 | finally: |
| 1213 | os.close(ack) |
| 1214 | return fds |
| 1215 | |
| 1216 | |
| 1217 | def _fork_child_main(handoff: int, ack: int, config: dict[str, Any], parent: int, strict: bool) -> None: |
| 1218 | """In the forked child: become a fresh single-use worker for ONE call, |
| 1219 | then exit. All of the setup runs before the call's pipes even exist.""" |
| 1220 | import signal |
| 1221 | |
| 1222 | code = 1 |
| 1223 | try: |
| 1224 | # Nothing of the fork server's but the handoff socket, the write end |
| 1225 | # of its own ack pipe (both closed once the call's pipes are in) and |
| 1226 | # the ruleset, closed below: its control channel above all. |
| 1227 | keep = {0, 1, 2, handoff, ack, _CHILD_RULESET} |
| 1228 | for fd in range(3, max(int(config["limits"]["nofile"]), max(keep)) + 1): |
| 1229 | if fd not in keep: |
| 1230 | try: |
| 1231 | os.close(fd) |
| 1232 | except OSError: |
| 1233 | pass |
| 1234 | # A group of its own: as a group leader it can never setsid() out of |
| 1235 | # the fork server's session, which the launcher sweeps on exit. |
| 1236 | os.setpgid(0, 0) |
| 1237 | if sys.platform.startswith("linux"): |
| 1238 | if _syscall().prctl(_PR_SET_PDEATHSIG, signal.SIGKILL, 0, 0, 0) != 0 and strict: |
| 1239 | raise OSError("PR_SET_PDEATHSIG failed") |
| 1240 | if os.getppid() != parent: |
| 1241 | raise OSError("the fork server died before this child started") |
| 1242 | _set_call_rlimits(config["limits"], strict) |
| 1243 | if _CHILD_RULESET >= 0: |
| 1244 | _restrict_self(_CHILD_RULESET) |
| 1245 | os.close(_CHILD_RULESET) |
| 1246 | elif strict: |
| 1247 | raise OSError("no nested Landlock ruleset for this child") |
| 1248 | read_fd, write_fd = _receive_call_pipes(handoff, ack) |
| 1249 | code = _serve_one(_WorkerChannel(read_fd, write_fd)) |
| 1250 | except BaseException: |
| 1251 | pass |
| 1252 | finally: |
| 1253 | os._exit(code) |
| 1254 | |
| 1255 | |
| 1256 | # --------------------------------------------------------------------------- |
| 1257 | # Parent side |
| 1258 | # --------------------------------------------------------------------------- |
| 1259 | |
| 1260 | |
| 1261 | class SandboxProtocolError(Exception): |
| 1262 | """The worker sent something the parent does not accept.""" |
| 1263 | |
| 1264 | |
| 1265 | class _SandboxTimeout(Exception): |
| 1266 | pass |
| 1267 | |
| 1268 | |
| 1269 | class _WorkerGone(Exception): |
| 1270 | pass |
| 1271 | |
| 1272 | |
| 1273 | def _env_number(name: str, default: float, *, minimum: float = 0) -> float: |
| 1274 | raw = os.environ.get(name, "").strip() |
| 1275 | try: |
| 1276 | value = float(raw) if raw else default |
| 1277 | except ValueError: |
| 1278 | return default |
| 1279 | return value if value >= minimum else default |
| 1280 | |
| 1281 | |
| 1282 | def isolation_mode() -> str: |
| 1283 | """``landlock`` (default, fail closed) or ``unsafe-dev``.""" |
| 1284 | return UNSAFE_DEV if os.environ.get(ISOLATION_ENV, "").strip().lower() == UNSAFE_DEV else "landlock" |
| 1285 | |
| 1286 | |
| 1287 | def launcher_socket() -> str: |
| 1288 | return os.environ.get(LAUNCHER_SOCKET_ENV, "").strip() or DEFAULT_LAUNCHER_SOCKET |
| 1289 | |
| 1290 | |
| 1291 | def _recv_exact(conn, size: int) -> bytes: |
| 1292 | chunks = [] |
| 1293 | while size: |
| 1294 | chunk = conn.recv(size) |
| 1295 | if not chunk: |
| 1296 | raise OSError("sandbox launcher closed the connection") |
| 1297 | chunks.append(chunk) |
| 1298 | size -= len(chunk) |
| 1299 | return b"".join(chunks) |
| 1300 | |
| 1301 | |
| 1302 | def _launcher_call(message: dict[str, Any], fds: tuple[int, ...] = (), timeout: float = BOOT_TIMEOUT_SECONDS): |
| 1303 | """One request to the launcher: (open connection, reply dict). Raises |
| 1304 | OSError for anything that is not a well-formed reply.""" |
| 1305 | import array |
| 1306 | import socket |
| 1307 | |
| 1308 | conn = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) |
| 1309 | try: |
| 1310 | conn.settimeout(timeout) |
| 1311 | conn.connect(launcher_socket()) |
| 1312 | body = json.dumps(message, separators=(",", ":")).encode("utf-8") |
| 1313 | data = _LENGTH.pack(len(body)) + body |
| 1314 | if fds: |
| 1315 | conn.sendmsg([data], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))]) |
| 1316 | else: |
| 1317 | conn.sendall(data) |
| 1318 | (length,) = _LENGTH.unpack(_recv_exact(conn, 4)) |
| 1319 | if length > 65536: |
| 1320 | raise OSError("oversize reply from the sandbox launcher") |
| 1321 | try: |
| 1322 | reply = json.loads(_recv_exact(conn, length).decode("utf-8")) |
| 1323 | except (ValueError, UnicodeDecodeError) as exc: |
| 1324 | raise OSError("malformed reply from the sandbox launcher") from exc |
| 1325 | if not isinstance(reply, dict): |
| 1326 | raise OSError("malformed reply from the sandbox launcher") |
| 1327 | except BaseException: |
| 1328 | conn.close() |
| 1329 | raise |
| 1330 | return conn, reply |
| 1331 | |
| 1332 | |
| 1333 | _LAUNCHER_CACHE: dict[str, tuple[float, dict[str, Any]]] = {} |
| 1334 | |
| 1335 | |
| 1336 | def launcher_info() -> dict[str, Any] | None: |
| 1337 | """The launcher's status, or None when no launcher answers -- or when |
| 1338 | the one that answers would run workers as this process's own uid (that |
| 1339 | is no separation at all). Positive answers are cached for 5 seconds; |
| 1340 | tests monkeypatch this to simulate either.""" |
| 1341 | if not hasattr(os, "getuid"): |
| 1342 | return None |
| 1343 | path = launcher_socket() |
| 1344 | cached = _LAUNCHER_CACHE.get(path) |
| 1345 | if cached is not None and time.monotonic() - cached[0] < _LAUNCHER_CACHE_SECONDS: |
| 1346 | return cached[1] |
| 1347 | try: |
| 1348 | conn, reply = _launcher_call({"v": _LAUNCHER_PROTOCOL, "op": "status"}, timeout=2.0) |
| 1349 | conn.close() |
| 1350 | except OSError: |
| 1351 | return None |
| 1352 | uid = reply.get("sandbox_uid") |
| 1353 | if reply.get("ok") is not True or not isinstance(uid, int) or uid in (0, os.getuid()): |
| 1354 | return None |
| 1355 | _LAUNCHER_CACHE[path] = (time.monotonic(), reply) |
| 1356 | return reply |
| 1357 | |
| 1358 | |
| 1359 | def _private_paths() -> list[str]: |
| 1360 | """What the sandbox user must not traverse, stat or touch: the data |
| 1361 | directory, every object root, a separate backups directory and the |
| 1362 | admin token file. The code directory is deliberately not here: the |
| 1363 | worker must read object_sandbox.py, and the code is public anyway.""" |
| 1364 | import object_namespace |
| 1365 | from object_versions import DEFAULT_DATA_DIR |
| 1366 | |
| 1367 | paths = [os.environ.get("DBBASIC_DATA_DIR", DEFAULT_DATA_DIR)] |
| 1368 | paths.extend(str(root) for root in object_namespace.get_object_roots()) |
| 1369 | for key in ("DBBASIC_BACKUPS_DIR", "DBBASIC_ADMIN_TOKEN_FILE"): |
| 1370 | if os.environ.get(key): |
| 1371 | paths.append(os.environ[key]) |
| 1372 | return paths |
| 1373 | |
| 1374 | |
| 1375 | _PROTECTED_LOGGED: set[str] = set() |
| 1376 | |
| 1377 | |
| 1378 | def protect_private_dirs() -> str | None: |
| 1379 | """Close the server's private paths to other users (mode 0700/0600) |
| 1380 | where they are open and ours; None when all are closed, otherwise why |
| 1381 | one cannot be. Checked before every user-object run, so a directory |
| 1382 | created later (umask 022) is closed before any worker could reach it.""" |
| 1383 | import stat as stat_module |
| 1384 | |
| 1385 | for path in _private_paths(): |
| 1386 | try: |
| 1387 | info = os.stat(path) |
| 1388 | except OSError: |
| 1389 | continue # not there yet: nothing to reach |
| 1390 | if not info.st_mode & 0o007: |
| 1391 | continue |
| 1392 | mode = 0o700 if stat_module.S_ISDIR(info.st_mode) else 0o600 |
| 1393 | if info.st_uid == os.getuid(): |
| 1394 | try: |
| 1395 | os.chmod(path, mode) |
| 1396 | except OSError: |
| 1397 | pass |
| 1398 | else: |
| 1399 | if path not in _PROTECTED_LOGGED: |
| 1400 | _PROTECTED_LOGGED.add(path) |
| 1401 | print(f"[dbbasic] closed {path} to other users (mode {mode:o}) so sandboxed user code " |
| 1402 | "cannot reach it", file=sys.stderr, flush=True) |
| 1403 | continue |
| 1404 | return (f"{path} is open to other users (mode {stat_module.S_IMODE(info.st_mode):o}) and this " |
| 1405 | f"server cannot close it; make it owned by the server user with mode {mode:o}") |
| 1406 | return None |
| 1407 | |
| 1408 | |
| 1409 | _UDP_BY_ABI: dict[int, bool] = {} |
| 1410 | |
| 1411 | |
| 1412 | def _landlock_mediates_udp(abi: int) -> bool: |
| 1413 | if abi < 4 or not sys.platform.startswith("linux"): |
| 1414 | return False |
| 1415 | if abi not in _UDP_BY_ABI: |
| 1416 | try: |
| 1417 | _fs, net, _scoped = _supported_rights(abi) |
| 1418 | except Exception: |
| 1419 | net = 0 |
| 1420 | _UDP_BY_ABI[abi] = bool(net & ~(NET_BIND_TCP | NET_CONNECT_TCP)) |
| 1421 | return _UDP_BY_ABI[abi] |
| 1422 | |
| 1423 | |
| 1424 | def _udp_status(abi: int, launcher: dict[str, Any] | None) -> str: |
| 1425 | if launcher and launcher.get("netns"): |
| 1426 | return "blocked: each worker has its own empty network namespace" |
| 1427 | if launcher and launcher.get("inet_sockets") is False: |
| 1428 | return "blocked: IP sockets are not available to the launcher or its workers" |
| 1429 | if launcher and launcher.get("interfaces") == ["lo"]: |
| 1430 | return "loopback only: the launcher runs in a private network namespace" |
| 1431 | if _landlock_mediates_udp(abi): |
| 1432 | return "blocked: Landlock handles UDP on this kernel" |
| 1433 | return "NOT controlled: user code can send UDP datagrams (no network namespace; see runtime-contract.md)" |
| 1434 | |
| 1435 | |
| 1436 | def isolation_status() -> dict[str, Any]: |
| 1437 | """Whether user objects can run here, how they are isolated, and why |
| 1438 | not. Cheap: one syscall, a cached launcher status, a few stats.""" |
| 1439 | mode = isolation_mode() |
| 1440 | abi = landlock_abi() |
| 1441 | launcher = launcher_info() |
| 1442 | status = { |
| 1443 | "mode": mode, |
| 1444 | "available": False, |
| 1445 | "landlock_abi": abi, |
| 1446 | "uid_separation": launcher is not None, |
| 1447 | "sandbox_uid": launcher.get("sandbox_uid") if launcher else None, |
| 1448 | "network_namespace": bool(launcher and launcher.get("netns")), |
| 1449 | "udp": _udp_status(abi, launcher), |
| 1450 | "warm_parents": _warm_parent_status(launcher, abi), |
| 1451 | "launcher_socket": launcher_socket(), |
| 1452 | "reason": "", |
| 1453 | } |
| 1454 | if mode == UNSAFE_DEV: |
| 1455 | if launcher is not None: |
| 1456 | protect_private_dirs() |
| 1457 | status.update(available=True, reason=( |
| 1458 | f"{ISOLATION_ENV}={UNSAFE_DEV}: user code runs WITHOUT the kernel wall (development only)")) |
| 1459 | elif launcher is None: |
| 1460 | status["reason"] = ( |
| 1461 | f"no sandbox launcher answers at {launcher_socket()}; user objects run only as a separate OS user " |
| 1462 | "started by object_sandbox_launcher.py (docs/runtime-contract.md \"User Object Isolation\")") |
| 1463 | elif abi < MIN_LANDLOCK_ABI: |
| 1464 | found = "no Landlock" if abi == 0 else f"Landlock ABI {abi}" |
| 1465 | status["reason"] = (f"user objects need Landlock ABI >= {MIN_LANDLOCK_ABI} (Linux >= 6.7); " |
| 1466 | f"this host has {found}") |
| 1467 | elif hasattr(os, "geteuid") and os.geteuid() == 0: |
| 1468 | status["reason"] = "user objects are not run while the server runs as root" |
| 1469 | else: |
| 1470 | problem = protect_private_dirs() |
| 1471 | if problem: |
| 1472 | status["reason"] = problem |
| 1473 | else: |
| 1474 | status["available"] = True |
| 1475 | return status |
| 1476 | |
| 1477 | |
| 1478 | def is_user_code(object_id: str, path: Any = None) -> bool: |
| 1479 | """True for anything that looks like a user-namespace object. Fail closed: |
| 1480 | any ``u_<digits>_`` prefix, or a source under ``users/<uid>/``.""" |
| 1481 | import object_runtime_helpers |
| 1482 | |
| 1483 | if isinstance(object_id, str) and object_runtime_helpers._user_namespace(object_id) is not None: |
| 1484 | return True |
| 1485 | if path is not None: |
| 1486 | from pathlib import Path |
| 1487 | |
| 1488 | return object_runtime_helpers._path_namespace(Path(path)) is not None |
| 1489 | return False |
| 1490 | |
| 1491 | |
| 1492 | def scrubbed_env() -> dict[str, str]: |
| 1493 | env = {} |
| 1494 | for key, value in os.environ.items(): |
| 1495 | if key in _ENV_ALLOW or key.startswith(_ENV_ALLOW_PREFIX): |
| 1496 | env[key] = value |
| 1497 | env.setdefault("PATH", "/usr/bin:/bin") |
| 1498 | return env |
| 1499 | |
| 1500 | |
| 1501 | def _deny_paths() -> list[str]: |
| 1502 | from pathlib import Path |
| 1503 | |
| 1504 | import object_namespace |
| 1505 | from object_versions import DEFAULT_DATA_DIR |
| 1506 | |
| 1507 | paths = {os.path.dirname(os.path.realpath(__file__)), os.path.realpath(os.getcwd())} |
| 1508 | paths.add(os.path.realpath(os.environ.get("DBBASIC_DATA_DIR", DEFAULT_DATA_DIR))) |
| 1509 | for root in object_namespace.get_object_roots(): |
| 1510 | paths.add(os.path.realpath(str(Path(root)))) |
| 1511 | for key in ("DBBASIC_PACKAGES_DIR", "DBBASIC_ADMIN_TOKEN_FILE"): |
| 1512 | if os.environ.get(key): |
| 1513 | paths.add(os.path.realpath(os.environ[key])) |
| 1514 | return sorted(p for p in paths if p and p != "/") |
| 1515 | |
| 1516 | |
| 1517 | def _boot_config() -> dict[str, Any]: |
| 1518 | memory_mb = int(_env_number(MEMORY_MB_ENV, DEFAULT_MEMORY_MB, minimum=64)) |
| 1519 | return { |
| 1520 | "t": "boot", |
| 1521 | "mode": isolation_mode(), |
| 1522 | "min_abi": MIN_LANDLOCK_ABI, |
| 1523 | "server_uid": os.getuid() if hasattr(os, "getuid") else -1, |
| 1524 | "separated": launcher_info() is not None, |
| 1525 | "deny": _deny_paths(), |
| 1526 | "limits": { |
| 1527 | "cpu": int(_env_number(CPU_SECONDS_ENV, DEFAULT_CPU_SECONDS, minimum=1)), |
| 1528 | "as": memory_mb * 1024 * 1024, |
| 1529 | "nofile": int(_env_number(MAX_FILES_ENV, DEFAULT_MAX_OPEN_FILES, minimum=8)), |
| 1530 | }, |
| 1531 | } |
| 1532 | |
| 1533 | |
| 1534 | # -- why a worker died ------------------------------------------------------ |
| 1535 | # |
| 1536 | # A warm worker (a fork server) or a spare that dies is replaced or bypassed |
| 1537 | # without any caller noticing: the call takes the slower single-use path and |
| 1538 | # still succeeds. That is the point of failing closed, and it is also how a |
| 1539 | # fork server that died at every start went unnoticed for days. So each death |
| 1540 | # is said once, at warning level, with what is known about the cause; a crash |
| 1541 | # loop then gets one line a minute with a count. The lines carry no object |
| 1542 | # id, source, payload or user: only the kind of worker, its pid, how it |
| 1543 | # ended, and the memory limit it had. |
| 1544 | |
| 1545 | WORKER_LOG_INTERVAL_SECONDS = 60.0 |
| 1546 | _EARLY_EXIT_SECONDS = 1.0 # an exit this soon after start is a start that failed |
| 1547 | _EARLY_SIGNAL_SECONDS = 5.0 # SIGKILL or SIGSEGV this soon after start |
| 1548 | _STDERR_TAIL_BYTES = 2048 |
| 1549 | _MAX_LOG_CAUSES = 256 |
| 1550 | |
| 1551 | |
| 1552 | class _RateLimitedLog: |
| 1553 | """Say a line the first time its cause is seen; after that at most one |
| 1554 | line per cause per ``interval`` seconds, which carries the number left |
| 1555 | out since the last one.""" |
| 1556 | |
| 1557 | def __init__(self, emit=None, interval: float = WORKER_LOG_INTERVAL_SECONDS, clock=time.monotonic): |
| 1558 | import threading |
| 1559 | |
| 1560 | self._emit = emit or _emit_warning |
| 1561 | self._interval = interval |
| 1562 | self._clock = clock |
| 1563 | self._lock = threading.Lock() |
| 1564 | self._seen: dict[str, list] = {} # cause -> [when last said, left out since] |
| 1565 | |
| 1566 | def warn(self, cause: str, line: str) -> bool: |
| 1567 | """True if the line was said now, False if it was only counted.""" |
| 1568 | now = self._clock() |
| 1569 | with self._lock: |
| 1570 | entry = self._seen.get(cause) |
| 1571 | if entry is None and len(self._seen) >= _MAX_LOG_CAUSES: |
| 1572 | cause = "other" |
| 1573 | entry = self._seen.get(cause) |
| 1574 | if entry is None: |
| 1575 | self._seen[cause] = [now, 0] |
| 1576 | elif now - entry[0] < self._interval: |
| 1577 | entry[1] += 1 |
| 1578 | return False |
| 1579 | else: |
| 1580 | if entry[1]: |
| 1581 | line = f"{line} ({entry[1]} more like this in the last {int(now - entry[0])} s, not logged)" |
| 1582 | entry[0], entry[1] = now, 0 |
| 1583 | self._emit(line) |
| 1584 | return True |
| 1585 | |
| 1586 | def reset(self) -> None: |
| 1587 | with self._lock: |
| 1588 | self._seen.clear() |
| 1589 | |
| 1590 | |
| 1591 | def _emit_warning(line: str) -> None: |
| 1592 | import logging # not at module level: this file is also the worker's script |
| 1593 | |
| 1594 | logging.getLogger("dbbasic.object_sandbox").warning("%s", line) |
| 1595 | |
| 1596 | |
| 1597 | _WORKER_LOG = _RateLimitedLog() |
| 1598 | |
| 1599 | |
| 1600 | def _parse_launcher_exit(body: bytes) -> int | None: |
| 1601 | """The status in the launcher's ``{"exited": true, "status": N}`` |
| 1602 | message (N as subprocess reports it), or None for anything else.""" |
| 1603 | try: |
| 1604 | message = json.loads(body.decode("utf-8")) |
| 1605 | except (ValueError, UnicodeDecodeError, RecursionError): |
| 1606 | return None |
| 1607 | if not isinstance(message, dict) or message.get("exited") is not True: |
| 1608 | return None |
| 1609 | status = message.get("status") |
| 1610 | if not isinstance(status, int) or isinstance(status, bool) or not -128 <= status <= 255: |
| 1611 | return None |
| 1612 | return status |
| 1613 | |
| 1614 | |
| 1615 | def _describe_status(status: int | None) -> str: |
| 1616 | """``status`` as subprocess reports it: negative for a signal.""" |
| 1617 | if status is None: |
| 1618 | return "exit status unknown" |
| 1619 | if status < 0: |
| 1620 | import signal |
| 1621 | |
| 1622 | try: |
| 1623 | return f"killed by {signal.Signals(-status).name}" |
| 1624 | except ValueError: |
| 1625 | return f"killed by signal {-status}" |
| 1626 | return f"exit status {status}" |
| 1627 | |
| 1628 | |
| 1629 | def _death_hint(status: int | None, age: float | None, ready: bool, text: str = "") -> str: |
| 1630 | """A sentence for the log when a death looks like the memory limit, else |
| 1631 | "". ``text`` (the worker's boot error and the end of its stderr) is only |
| 1632 | searched, never logged.""" |
| 1633 | import signal |
| 1634 | |
| 1635 | why = "" |
| 1636 | if "MemoryError" in text: |
| 1637 | why = "it reported MemoryError" |
| 1638 | elif (status is not None and -status in (signal.SIGKILL, signal.SIGSEGV) |
| 1639 | and age is not None and age <= _EARLY_SIGNAL_SECONDS): |
| 1640 | why = f"{_describe_status(status)} {age:.1f} s after it started" |
| 1641 | elif not ready and age is not None and age <= _EARLY_EXIT_SECONDS and status not in (None, 0): |
| 1642 | why = f"it exited {age:.1f} s after it started" |
| 1643 | if not why: |
| 1644 | return "" |
| 1645 | return (f"; this looks like the memory limit ({why}): a free-threaded Python reserves about 1 GiB " |
| 1646 | f"of address space before the limit applies, so check {MEMORY_MB_ENV}") |
| 1647 | |
| 1648 | |
| 1649 | def _log_worker_death(kind: str, worker: Any, event: str, *, status: int | None = None, |
| 1650 | detail: str = "", cause: str = "", config: dict[str, Any] | None = None) -> None: |
| 1651 | """One warning for a worker that exited or did not start. ``detail`` is |
| 1652 | text this server or the worker's boot wrote (never user code: a fork |
| 1653 | server runs none, and a worker that has not started has run none). |
| 1654 | ``cause`` groups lines for the rate limit when ``detail`` varies.""" |
| 1655 | pid = getattr(worker, "pid", None) |
| 1656 | limit = getattr(worker, "memory_limit", None) |
| 1657 | if limit is None and config is not None: |
| 1658 | limit = (config.get("limits") or {}).get("as") |
| 1659 | started = getattr(worker, "started", None) |
| 1660 | age = time.monotonic() - started if started is not None else None |
| 1661 | ready = bool(getattr(worker, "ready", False)) and event != "failed to start" |
| 1662 | tail = worker.stderr_tail() if hasattr(worker, "stderr_tail") else "" |
| 1663 | hint = _death_hint(status, age, ready, f"{detail}\n{tail}") |
| 1664 | line = f"user-code {kind}" + (f" (pid {pid})" if pid is not None else "") + f" {event}: {_describe_status(status)}" |
| 1665 | if age is not None: |
| 1666 | line += f" after {age:.1f} s" |
| 1667 | line += f", memory limit {limit // (1024 * 1024)} MiB" if isinstance(limit, int) else ", memory limit unknown" |
| 1668 | if detail: |
| 1669 | line += f" ({' '.join(detail.split())[:200]})" |
| 1670 | _WORKER_LOG.warn(f"{kind}|{event}|{_describe_status(status)}|{cause}|{bool(hint)}", line + hint) |
| 1671 | |
| 1672 | |
| 1673 | def _log_fallback(reason: str) -> None: |
| 1674 | _WORKER_LOG.warn(f"fallback|{reason}", |
| 1675 | f"user-code warm worker unavailable ({reason}): calls take the slower single-use path " |
| 1676 | f"for {FORK_SERVER_COOLDOWN_SECONDS:g} s, then a new one is started") |
| 1677 | |
| 1678 | |
| 1679 | class _Worker: |
| 1680 | """One worker process: started by the launcher as the sandbox user when |
| 1681 | one answers, otherwise (``unsafe-dev`` only: isolation_status refuses |
| 1682 | the walled mode without a launcher) as a child of this process.""" |
| 1683 | |
| 1684 | def __init__(self, config: dict[str, Any], launched: bool = False, channel: str = "pipes"): |
| 1685 | self.config_key = json.dumps(config, sort_keys=True) |
| 1686 | self.process = None |
| 1687 | self.conn = None |
| 1688 | self.sock = None |
| 1689 | self.launched = launched |
| 1690 | self.channel = channel |
| 1691 | self.pid = None |
| 1692 | self.ready = False |
| 1693 | self._stderr = None |
| 1694 | self._launcher_status = None |
| 1695 | self._launcher_buffer = bytearray() |
| 1696 | self.memory_limit = (config.get("limits") or {}).get("as") |
| 1697 | self.started = time.monotonic() |
| 1698 | if launched: |
| 1699 | self._start_launched() |
| 1700 | else: |
| 1701 | self._start_local() |
| 1702 | os.set_blocking(self.write_fd, False) |
| 1703 | self._buffer = bytearray() |
| 1704 | self.ready = False |
| 1705 | self.info: dict[str, Any] = {} |
| 1706 | # A boot message fits in the pipe buffer, so this never blocks. |
| 1707 | self.send(config, time.monotonic() + BOOT_TIMEOUT_SECONDS) |
| 1708 | |
| 1709 | def _adopt_socket(self, sock) -> None: |
| 1710 | """Our end of a socket channel: distinct fds to read, write and |
| 1711 | sendmsg on, each closed exactly once by kill().""" |
| 1712 | import socket |
| 1713 | |
| 1714 | fd = sock.detach() |
| 1715 | self.write_fd = fd |
| 1716 | self.read_fd = os.dup(fd) |
| 1717 | self.sock = socket.socket(fileno=os.dup(fd)) |
| 1718 | |
| 1719 | def _start_local(self) -> None: |
| 1720 | import subprocess |
| 1721 | import tempfile |
| 1722 | |
| 1723 | # The worker points its own fd 2 at /dev/null before it reads |
| 1724 | # anything, so this file only ever holds what the interpreter itself |
| 1725 | # said while starting (it is how a worker that cannot start says |
| 1726 | # why). It is searched for a memory error, never logged. |
| 1727 | try: |
| 1728 | self._stderr = tempfile.TemporaryFile() |
| 1729 | except OSError: |
| 1730 | self._stderr = None |
| 1731 | stderr = self._stderr if self._stderr is not None else subprocess.DEVNULL |
| 1732 | if self.channel == "socket": |
| 1733 | import socket |
| 1734 | |
| 1735 | ours, theirs = socket.socketpair() |
| 1736 | try: |
| 1737 | self.process = subprocess.Popen( |
| 1738 | [sys.executable, "-I", "-B", os.path.abspath(__file__), "--worker"], |
| 1739 | stdin=theirs.fileno(), stdout=theirs.fileno(), stderr=stderr, |
| 1740 | env=scrubbed_env(), cwd="/", close_fds=True, start_new_session=True, |
| 1741 | ) |
| 1742 | except BaseException: |
| 1743 | ours.close() |
| 1744 | raise |
| 1745 | finally: |
| 1746 | theirs.close() |
| 1747 | self.pid = self.process.pid |
| 1748 | self._adopt_socket(ours) |
| 1749 | return |
| 1750 | self.process = subprocess.Popen( |
| 1751 | [sys.executable, "-I", "-B", os.path.abspath(__file__), "--worker"], |
| 1752 | stdin=subprocess.PIPE, |
| 1753 | stdout=subprocess.PIPE, |
| 1754 | stderr=stderr, |
| 1755 | env=scrubbed_env(), |
| 1756 | cwd="/", |
| 1757 | close_fds=True, |
| 1758 | start_new_session=True, |
| 1759 | bufsize=0, |
| 1760 | ) |
| 1761 | self.pid = self.process.pid |
| 1762 | self.read_fd = self.process.stdout.fileno() |
| 1763 | self.write_fd = self.process.stdin.fileno() |
| 1764 | |
| 1765 | def _start_launched(self) -> None: |
| 1766 | """Hand the launcher the worker's ends of two pipes (SCM_RIGHTS); |
| 1767 | keep ours. The connection stays open for the worker's lifetime: |
| 1768 | closing it is how this process asks the launcher to kill it.""" |
| 1769 | if self.channel == "socket": |
| 1770 | import socket |
| 1771 | |
| 1772 | ours, theirs = socket.socketpair() |
| 1773 | try: |
| 1774 | conn, reply = _launcher_call( |
| 1775 | {"v": _LAUNCHER_PROTOCOL, "op": "spawn", "env": scrubbed_env(), "channel": "socket"}, |
| 1776 | fds=(theirs.fileno(),), |
| 1777 | ) |
| 1778 | except BaseException: |
| 1779 | ours.close() |
| 1780 | raise |
| 1781 | finally: |
| 1782 | theirs.close() |
| 1783 | pid = reply.get("pid") |
| 1784 | if reply.get("ok") is not True or not isinstance(pid, int) or isinstance(pid, bool): |
| 1785 | conn.close() |
| 1786 | ours.close() |
| 1787 | raise OSError(f"sandbox launcher refused: {str(reply.get('error') or 'malformed reply')[:200]}") |
| 1788 | conn.settimeout(None) |
| 1789 | self.conn = conn |
| 1790 | self.pid = pid |
| 1791 | self._adopt_socket(ours) |
| 1792 | return |
| 1793 | to_worker_r, to_worker_w = os.pipe() |
| 1794 | from_worker_r, from_worker_w = os.pipe() |
| 1795 | try: |
| 1796 | conn, reply = _launcher_call( |
| 1797 | {"v": _LAUNCHER_PROTOCOL, "op": "spawn", "env": scrubbed_env()}, |
| 1798 | fds=(to_worker_r, from_worker_w), |
| 1799 | ) |
| 1800 | except BaseException: |
| 1801 | for fd in (to_worker_w, from_worker_r): |
| 1802 | os.close(fd) |
| 1803 | raise |
| 1804 | finally: |
| 1805 | os.close(to_worker_r) |
| 1806 | os.close(from_worker_w) |
| 1807 | pid = reply.get("pid") |
| 1808 | if reply.get("ok") is not True or not isinstance(pid, int) or isinstance(pid, bool): |
| 1809 | conn.close() |
| 1810 | os.close(to_worker_w) |
| 1811 | os.close(from_worker_r) |
| 1812 | raise OSError(f"sandbox launcher refused: {str(reply.get('error') or 'malformed reply')[:200]}") |
| 1813 | conn.settimeout(None) |
| 1814 | self.conn = conn |
| 1815 | self.pid = pid |
| 1816 | self.read_fd = from_worker_r |
| 1817 | self.write_fd = to_worker_w |
| 1818 | |
| 1819 | def alive(self) -> bool: |
| 1820 | if self.process is not None: |
| 1821 | return self.process.poll() is None |
| 1822 | import select |
| 1823 | |
| 1824 | if self.conn is None or self._launcher_status is not None or self._launcher_buffer: |
| 1825 | return False # gone, or the launcher has said (and we have read) that it ended |
| 1826 | readable, _w, _x = select.select([self.conn], [], [], 0) |
| 1827 | return not readable # the launcher only ever closes on its side when it is gone |
| 1828 | |
| 1829 | def send(self, message: dict[str, Any], deadline: float) -> None: |
| 1830 | self.send_frame(_encode(message), deadline) |
| 1831 | |
| 1832 | def send_frame(self, frame: bytes, deadline: float) -> None: |
| 1833 | import select |
| 1834 | |
| 1835 | view = memoryview(frame) |
| 1836 | while view: |
| 1837 | remaining = deadline - time.monotonic() |
| 1838 | if remaining <= 0: |
| 1839 | raise _SandboxTimeout() |
| 1840 | _r, writable, _x = select.select([], [self.write_fd], [], remaining) |
| 1841 | if not writable: |
| 1842 | continue |
| 1843 | try: |
| 1844 | written = os.write(self.write_fd, view) |
| 1845 | except BlockingIOError: |
| 1846 | continue |
| 1847 | except (BrokenPipeError, OSError) as exc: |
| 1848 | raise _WorkerGone() from exc |
| 1849 | view = view[written:] |
| 1850 | |
| 1851 | def _fill(self, size: int, deadline: float) -> None: |
| 1852 | import select |
| 1853 | |
| 1854 | while len(self._buffer) < size: |
| 1855 | remaining = deadline - time.monotonic() |
| 1856 | if remaining <= 0: |
| 1857 | raise _SandboxTimeout() |
| 1858 | readable, _w, _x = select.select([self.read_fd], [], [], remaining) |
| 1859 | if not readable: |
| 1860 | continue |
| 1861 | chunk = os.read(self.read_fd, max(65536, size - len(self._buffer))) |
| 1862 | if not chunk: |
| 1863 | raise _WorkerGone() |
| 1864 | self._buffer.extend(chunk) |
| 1865 | |
| 1866 | def recv(self, deadline: float, max_bytes: int) -> dict[str, Any]: |
| 1867 | self._fill(4, deadline) |
| 1868 | (length,) = _LENGTH.unpack(bytes(self._buffer[:4])) |
| 1869 | if length > max_bytes: |
| 1870 | raise SandboxProtocolError(f"worker message of {length} bytes exceeds the {max_bytes}-byte limit") |
| 1871 | self._fill(4 + length, deadline) |
| 1872 | body = bytes(self._buffer[4:4 + length]) |
| 1873 | del self._buffer[:4 + length] |
| 1874 | try: |
| 1875 | message = _from_wire(json.loads(body.decode("utf-8"))) |
| 1876 | except (ValueError, UnicodeDecodeError, RecursionError) as exc: |
| 1877 | raise SandboxProtocolError(f"worker sent malformed JSON: {type(exc).__name__}") from exc |
| 1878 | if not isinstance(message, dict) or not isinstance(message.get("t"), str): |
| 1879 | raise SandboxProtocolError("worker message is not an object with a type") |
| 1880 | return message |
| 1881 | |
| 1882 | def wait_ready(self, deadline: float) -> None: |
| 1883 | if self.ready: |
| 1884 | return |
| 1885 | message = self.recv(deadline, 65536) |
| 1886 | if message.get("t") == "boot_error": |
| 1887 | raise _BootRefused(str(message.get("message") or "worker refused to boot")) |
| 1888 | if message.get("t") != "ready": |
| 1889 | raise SandboxProtocolError("worker did not report ready") |
| 1890 | self.ready = True |
| 1891 | self.info = {k: v for k, v in message.items() if k != "t"} |
| 1892 | |
| 1893 | def stderr_tail(self) -> str: |
| 1894 | """The end of what the interpreter wrote to stderr while starting |
| 1895 | (local workers only; the launcher keeps its workers' stderr).""" |
| 1896 | handle = self._stderr |
| 1897 | if handle is None: |
| 1898 | return "" |
| 1899 | try: |
| 1900 | size = handle.seek(0, os.SEEK_END) |
| 1901 | handle.seek(max(0, size - _STDERR_TAIL_BYTES)) |
| 1902 | return handle.read(_STDERR_TAIL_BYTES).decode("utf-8", "replace") |
| 1903 | except (OSError, ValueError): |
| 1904 | return "" |
| 1905 | |
| 1906 | def status_now(self, wait: float = 0.0) -> int | None: |
| 1907 | """Its exit status if it has already ended (waiting at most |
| 1908 | ``wait`` seconds), without killing it. The launcher reaps a |
| 1909 | launched worker and says how it ended on the worker's connection; |
| 1910 | None when it has not (an older launcher never does).""" |
| 1911 | if self.process is None: |
| 1912 | return self._launcher_exit_status(wait) |
| 1913 | try: |
| 1914 | return self.process.wait(timeout=wait) if wait > 0 else self.process.poll() |
| 1915 | except Exception: |
| 1916 | return None |
| 1917 | |
| 1918 | def _launcher_exit_status(self, wait: float) -> int | None: |
| 1919 | import select |
| 1920 | import socket |
| 1921 | |
| 1922 | if self.conn is None or self._launcher_status is not None: |
| 1923 | return self._launcher_status |
| 1924 | buffer = self._launcher_buffer |
| 1925 | deadline = time.monotonic() + max(wait, 0.0) |
| 1926 | try: |
| 1927 | while True: |
| 1928 | if len(buffer) >= 4: |
| 1929 | (length,) = _LENGTH.unpack(bytes(buffer[:4])) |
| 1930 | if length > 4096: |
| 1931 | return None |
| 1932 | if len(buffer) >= 4 + length: |
| 1933 | self._launcher_status = _parse_launcher_exit(bytes(buffer[4:4 + length])) |
| 1934 | return self._launcher_status |
| 1935 | readable, _w, _x = select.select([self.conn], [], [], max(0.0, deadline - time.monotonic())) |
| 1936 | if not readable: |
| 1937 | return None |
| 1938 | chunk = self.conn.recv(4096, getattr(socket, "MSG_DONTWAIT", 0)) |
| 1939 | if not chunk: |
| 1940 | return None # the launcher is gone |
| 1941 | buffer.extend(chunk) |
| 1942 | except (OSError, ValueError): |
| 1943 | return None |
| 1944 | |
| 1945 | def kill(self) -> None: |
| 1946 | import signal |
| 1947 | |
| 1948 | if self._stderr is not None: |
| 1949 | try: |
| 1950 | self._stderr.close() |
| 1951 | except OSError: |
| 1952 | pass |
| 1953 | self._stderr = None |
| 1954 | if self.process is None: |
| 1955 | # The launcher kills and reaps the worker when its connection closes. |
| 1956 | if self.conn is not None: |
| 1957 | self.conn.close() |
| 1958 | self.conn = None |
| 1959 | self._close_channel() |
| 1960 | return |
| 1961 | try: |
| 1962 | os.killpg(self.process.pid, signal.SIGKILL) |
| 1963 | except (ProcessLookupError, PermissionError, OSError): |
| 1964 | try: |
| 1965 | self.process.kill() |
| 1966 | except OSError: |
| 1967 | pass |
| 1968 | if self.channel == "socket": |
| 1969 | self._close_channel() |
| 1970 | for stream in (self.process.stdin, self.process.stdout): |
| 1971 | try: |
| 1972 | if stream is not None: |
| 1973 | stream.close() |
| 1974 | except OSError: |
| 1975 | pass |
| 1976 | try: |
| 1977 | self.process.wait(timeout=5) |
| 1978 | except Exception: |
| 1979 | pass |
| 1980 | |
| 1981 | def _close_channel(self) -> None: |
| 1982 | for fd in (self.write_fd, self.read_fd): |
| 1983 | try: |
| 1984 | if fd >= 0: |
| 1985 | os.close(fd) |
| 1986 | except OSError: |
| 1987 | pass |
| 1988 | self.write_fd = self.read_fd = -1 |
| 1989 | if self.sock is not None: |
| 1990 | self.sock.close() |
| 1991 | self.sock = None |
| 1992 | |
| 1993 | def exit_code(self) -> int | None: |
| 1994 | if self.process is None: |
| 1995 | return None # the launcher reaps it; this process may not even signal it |
| 1996 | try: |
| 1997 | return self.process.wait(timeout=0.5) |
| 1998 | except Exception: |
| 1999 | return None |
| 2000 | |
| 2001 | |
| 2002 | class _BootRefused(Exception): |
| 2003 | pass |
| 2004 | |
| 2005 | |
| 2006 | class _SandboxPool: |
| 2007 | """Pre-started, already-sandboxed spares. Each serves ONE request. |
| 2008 | |
| 2009 | Spares are refilled by a background thread, never on the request path: |
| 2010 | starting one is a launcher round trip (~2-3 ms measured) that the caller |
| 2011 | used to wait for before its own request could run.""" |
| 2012 | |
| 2013 | def __init__(self) -> None: |
| 2014 | import threading |
| 2015 | |
| 2016 | self._lock = threading.Lock() |
| 2017 | self._idle: list[_Worker] = [] |
| 2018 | self._registered = False |
| 2019 | self._refilling = False |
| 2020 | self._generation = 0 # bumped by shutdown(): a refill in flight discards what it started |
| 2021 | |
| 2022 | def _target_size(self) -> int: |
| 2023 | return int(_env_number(POOL_SIZE_ENV, DEFAULT_POOL_SIZE, minimum=0)) |
| 2024 | |
| 2025 | def acquire(self, config: dict[str, Any] | None = None) -> _Worker: |
| 2026 | config = config or _boot_config() |
| 2027 | key = json.dumps(config, sort_keys=True) |
| 2028 | worker = None |
| 2029 | stale: list[_Worker] = [] |
| 2030 | with self._lock: |
| 2031 | if not self._registered: |
| 2032 | import atexit |
| 2033 | |
| 2034 | atexit.register(self.shutdown) |
| 2035 | self._registered = True |
| 2036 | while self._idle: |
| 2037 | candidate = self._idle.pop(0) |
| 2038 | if candidate.config_key == key and candidate.alive(): |
| 2039 | worker = candidate |
| 2040 | break |
| 2041 | stale.append(candidate) |
| 2042 | for old in stale: |
| 2043 | if old.config_key == key: # not replaced for a new configuration: it died waiting |
| 2044 | _log_worker_death("spare worker", old, "exited", status=old.status_now(0.1)) |
| 2045 | old.kill() |
| 2046 | if worker is None: |
| 2047 | worker = _Worker(config, launched=config["separated"]) |
| 2048 | self._refill_in_background(config) |
| 2049 | return worker |
| 2050 | |
| 2051 | def _refill_in_background(self, config: dict[str, Any]) -> None: |
| 2052 | import threading |
| 2053 | |
| 2054 | with self._lock: |
| 2055 | if self._refilling or len(self._idle) >= self._target_size(): |
| 2056 | return |
| 2057 | self._refilling = True |
| 2058 | generation = self._generation |
| 2059 | threading.Thread(target=self._replenish, args=(config, generation), |
| 2060 | name="dbbasic-sandbox-refill", daemon=True).start() |
| 2061 | |
| 2062 | def _replenish(self, config: dict[str, Any], generation: int) -> None: |
| 2063 | stopped = False |
| 2064 | try: |
| 2065 | while True: |
| 2066 | with self._lock: |
| 2067 | if generation != self._generation or len(self._idle) >= self._target_size(): |
| 2068 | # Deciding to stop and clearing the flag are one hold |
| 2069 | # of the lock: a request that takes the spare this |
| 2070 | # moment must either see the refill still running (it |
| 2071 | # re-checks the count) or see it finished (and start |
| 2072 | # one), never "running" for a thread that has already |
| 2073 | # decided it is done, which left the pool short. |
| 2074 | if generation == self._generation: |
| 2075 | self._refilling = False |
| 2076 | stopped = True |
| 2077 | return |
| 2078 | try: |
| 2079 | spare = _Worker(config, launched=config["separated"]) |
| 2080 | except OSError as exc: |
| 2081 | _log_worker_death("spare worker", None, "failed to start", config=config, |
| 2082 | detail=f"{type(exc).__name__}: {exc}", cause=type(exc).__name__) |
| 2083 | return # the next request starts its own worker and tries again |
| 2084 | with self._lock: |
| 2085 | if generation == self._generation: |
| 2086 | self._idle.append(spare) |
| 2087 | continue |
| 2088 | spare.kill() |
| 2089 | return |
| 2090 | finally: |
| 2091 | if not stopped: |
| 2092 | with self._lock: |
| 2093 | if generation == self._generation: |
| 2094 | self._refilling = False |
| 2095 | |
| 2096 | def shutdown(self) -> None: |
| 2097 | with self._lock: |
| 2098 | idle, self._idle = self._idle, [] |
| 2099 | self._generation += 1 |
| 2100 | self._refilling = False |
| 2101 | for worker in idle: |
| 2102 | worker.kill() |
| 2103 | |
| 2104 | |
| 2105 | _POOL = _SandboxPool() |
| 2106 | |
| 2107 | |
| 2108 | class _ForkServerFailed(Exception): |
| 2109 | """The fast path is unusable for this call; take a spare instead.""" |
| 2110 | |
| 2111 | |
| 2112 | _PREWRITE_MAX = 16 * 1024 # well inside any pipe buffer (64 KiB on Linux, 16 KiB minimum on macOS) |
| 2113 | |
| 2114 | |
| 2115 | class _ForkedChild(_Worker): |
| 2116 | """One call's child of a fork server: the same pipe protocol as a |
| 2117 | single-use worker, already booted. Killing it means asking its fork |
| 2118 | server to SIGKILL and reap it (this process cannot signal the sandbox |
| 2119 | uid).""" |
| 2120 | |
| 2121 | def __init__(self, server: "_ForkServer", call_id: int, read_fd: int, write_fd: int): |
| 2122 | self.server = server |
| 2123 | self.call_id = call_id |
| 2124 | self.config_key = server.config_key |
| 2125 | self.process = None |
| 2126 | self.conn = None |
| 2127 | self.sock = None |
| 2128 | self.launched = True |
| 2129 | self.channel = "pipes" |
| 2130 | self.pid = None |
| 2131 | self._stderr = None |
| 2132 | self._launcher_status = None |
| 2133 | self._launcher_buffer = bytearray() |
| 2134 | self.memory_limit = server.worker.memory_limit |
| 2135 | self.started = time.monotonic() |
| 2136 | self.read_fd = read_fd |
| 2137 | self.write_fd = write_fd |
| 2138 | os.set_blocking(write_fd, False) |
| 2139 | self._buffer = bytearray() |
| 2140 | self.ready = True |
| 2141 | self.run_sent = False |
| 2142 | self.info = {"fork_server": True} |
| 2143 | self._status = None |
| 2144 | self._done = False |
| 2145 | self.received = True # until its fork server says otherwise, at reap |
| 2146 | |
| 2147 | def alive(self) -> bool: |
| 2148 | return not self._done |
| 2149 | |
| 2150 | def never_took_the_call(self) -> bool: |
| 2151 | """Killed, and its fork server is certain it died before it even |
| 2152 | acknowledged its pipes: it read nothing, so nothing of the call ran.""" |
| 2153 | return self._done and not self.received |
| 2154 | |
| 2155 | def kill(self) -> None: |
| 2156 | if self._done: |
| 2157 | return |
| 2158 | self._done = True |
| 2159 | self._close_channel() # EOF first, so a child blocked on its pipe stops at once |
| 2160 | self._status, self.received = self.server.reap(self.call_id) |
| 2161 | |
| 2162 | def exit_code(self) -> int | None: |
| 2163 | if self._status is None: |
| 2164 | return None |
| 2165 | if os.WIFEXITED(self._status): |
| 2166 | return os.WEXITSTATUS(self._status) |
| 2167 | if os.WIFSIGNALED(self._status): |
| 2168 | return -os.WTERMSIG(self._status) |
| 2169 | return None |
| 2170 | |
| 2171 | |
| 2172 | class _ForkServer: |
| 2173 | """The server side of one user's warm parent: a sandbox worker booted |
| 2174 | with ``fork_server`` on a socket channel. It is only ever used for the |
| 2175 | user it was started for.""" |
| 2176 | |
| 2177 | def __init__(self, owner: str, config: dict[str, Any]): |
| 2178 | import threading |
| 2179 | |
| 2180 | self.owner = owner |
| 2181 | self.config_key = json.dumps(config, sort_keys=True) |
| 2182 | self.worker = _Worker(dict(config, fork_server=True), launched=config["separated"], channel="socket") |
| 2183 | self.lock = threading.Lock() |
| 2184 | self.next_id = 0 |
| 2185 | self.calls = 0 |
| 2186 | self.active = 0 |
| 2187 | self.dead = False |
| 2188 | self.retiring = False |
| 2189 | self.closed = False |
| 2190 | self.death_logged = False |
| 2191 | self.last_used = time.monotonic() |
| 2192 | |
| 2193 | def log_death(self, event: str, detail: str = "", cause: str = "") -> None: |
| 2194 | """Say once why this fork server is no longer used, before it is |
| 2195 | killed (afterwards its status would only say that we killed it).""" |
| 2196 | with self.lock: |
| 2197 | if self.death_logged: |
| 2198 | return |
| 2199 | self.death_logged = True |
| 2200 | _log_worker_death("fork server", self.worker, event, status=self.worker.status_now(0.2), |
| 2201 | detail=detail, cause=cause) |
| 2202 | _log_fallback(f"fork server {event}") |
| 2203 | |
| 2204 | def wait_ready(self, deadline: float) -> None: |
| 2205 | self.worker.wait_ready(deadline) |
| 2206 | if self.worker.info.get("abi", 0) == 0 and isolation_mode() != UNSAFE_DEV: |
| 2207 | raise SandboxProtocolError("fork server booted without the wall") |
| 2208 | |
| 2209 | def _control(self, message: dict[str, Any], fds: tuple[int, ...] = ()) -> dict[str, Any]: |
| 2210 | """One control round trip; the caller holds self.lock. Any failure |
| 2211 | marks this fork server dead (it is then retired, never retried).""" |
| 2212 | import array |
| 2213 | import socket |
| 2214 | |
| 2215 | deadline = time.monotonic() + FORK_SERVER_CONTROL_SECONDS |
| 2216 | try: |
| 2217 | if self.worker.sock is None: |
| 2218 | raise _WorkerGone() |
| 2219 | if fds: |
| 2220 | data = _encode(message) |
| 2221 | sent = self.worker.sock.sendmsg( |
| 2222 | [data], [(socket.SOL_SOCKET, socket.SCM_RIGHTS, array.array("i", fds))]) |
| 2223 | if sent != len(data): |
| 2224 | raise _WorkerGone() |
| 2225 | else: |
| 2226 | self.worker.send(message, deadline) |
| 2227 | reply = self.worker.recv(deadline, 65536) |
| 2228 | except (OSError, _WorkerGone, _SandboxTimeout, SandboxProtocolError) as exc: |
| 2229 | self.dead = True |
| 2230 | self.failure = type(exc).__name__ |
| 2231 | raise _ForkServerFailed(f"{type(exc).__name__}: {exc}") from exc |
| 2232 | if reply.get("id") != message.get("id"): |
| 2233 | self.dead = True |
| 2234 | raise _ForkServerFailed("fork server answered out of turn") |
| 2235 | return reply |
| 2236 | |
| 2237 | def fork(self, first: bytes = b"") -> _ForkedChild: |
| 2238 | """A child for one call. ``first`` (the encoded run request, when it |
| 2239 | fits in a pipe buffer) is written to the child's pipe before the |
| 2240 | fork server's answer is read, so the child is already working while |
| 2241 | that answer travels. If the answer is a refusal no child ever got |
| 2242 | the pipe, so nothing ran and the caller may use a spare instead.""" |
| 2243 | to_child_r, to_child_w = os.pipe() |
| 2244 | from_child_r, from_child_w = os.pipe() |
| 2245 | written = False |
| 2246 | if first and len(first) <= _PREWRITE_MAX: |
| 2247 | os.write(to_child_w, first) # fits the pipe buffer: never blocks |
| 2248 | written = True |
| 2249 | try: |
| 2250 | with self.lock: |
| 2251 | if self.dead or self.closed: |
| 2252 | raise _ForkServerFailed("fork server is gone") |
| 2253 | self.next_id += 1 |
| 2254 | call_id = self.next_id |
| 2255 | reply = self._control({"t": "fork", "id": call_id}, (to_child_r, from_child_w)) |
| 2256 | if reply.get("t") != "forked" or reply.get("ok") is not True: |
| 2257 | self.dead = True |
| 2258 | raise _ForkServerFailed("fork server could not fork") |
| 2259 | self.calls += 1 |
| 2260 | self.active += 1 |
| 2261 | self.last_used = time.monotonic() |
| 2262 | except BaseException: |
| 2263 | os.close(to_child_w) |
| 2264 | os.close(from_child_r) |
| 2265 | raise |
| 2266 | finally: |
| 2267 | os.close(to_child_r) |
| 2268 | os.close(from_child_w) |
| 2269 | child = _ForkedChild(self, call_id, from_child_r, to_child_w) |
| 2270 | child.run_sent = written |
| 2271 | return child |
| 2272 | |
| 2273 | def reap(self, call_id: int) -> tuple[int | None, bool]: |
| 2274 | """(wait status, did the child acknowledge its pipes). Anything but |
| 2275 | an explicit ``received: false`` counts as acknowledged.""" |
| 2276 | status = None |
| 2277 | received = True |
| 2278 | with self.lock: |
| 2279 | self.active -= 1 |
| 2280 | if not self.dead and not self.closed: |
| 2281 | try: |
| 2282 | reply = self._control({"t": "reap", "id": call_id}) |
| 2283 | if reply.get("t") != "reaped": |
| 2284 | self.dead = True |
| 2285 | else: |
| 2286 | if isinstance(reply.get("status"), int): |
| 2287 | status = reply["status"] |
| 2288 | received = reply.get("received") is not False |
| 2289 | except _ForkServerFailed: |
| 2290 | pass |
| 2291 | close_now = self.dead or (self.retiring and self.active <= 0) |
| 2292 | died = self.dead and not self.closed |
| 2293 | if died: |
| 2294 | self.log_death("stopped answering", cause=getattr(self, "failure", "")) |
| 2295 | if close_now: |
| 2296 | self.close() |
| 2297 | return status, received |
| 2298 | |
| 2299 | def retire(self) -> None: |
| 2300 | """Stop using it; close it once its running calls are reaped.""" |
| 2301 | with self.lock: |
| 2302 | self.retiring = True |
| 2303 | close_now = self.active <= 0 or self.dead |
| 2304 | if close_now: |
| 2305 | self.close() |
| 2306 | |
| 2307 | def close(self) -> None: |
| 2308 | """Kill it and anything it still runs (the launcher kills the whole |
| 2309 | session when the connection closes).""" |
| 2310 | with self.lock: |
| 2311 | if self.closed: |
| 2312 | return |
| 2313 | self.closed = True |
| 2314 | self.worker.kill() |
| 2315 | |
| 2316 | |
| 2317 | class _ForkServers: |
| 2318 | """At most one fork server per user, never shared between users: a |
| 2319 | user's calls fork from a parent that only that user's calls ever used. |
| 2320 | Started in the background on a user's first call (that call takes a |
| 2321 | spare), retired when idle, after FORK_SERVER_MAX_CALLS calls, when the |
| 2322 | configuration changes, or on any failure (that user then takes the |
| 2323 | spare path for FORK_SERVER_COOLDOWN_SECONDS). The least recently used |
| 2324 | one is retired when more users than DBBASIC_USER_CODE_WARM_USERS have |
| 2325 | one.""" |
| 2326 | |
| 2327 | def __init__(self) -> None: |
| 2328 | import threading |
| 2329 | |
| 2330 | self._lock = threading.Lock() |
| 2331 | self._servers: dict[str, _ForkServer] = {} |
| 2332 | self._starting: set[str] = set() |
| 2333 | self._cooldown: dict[str, float] = {} |
| 2334 | self._generation = 0 |
| 2335 | self._registered = False |
| 2336 | |
| 2337 | def capacity(self) -> int: |
| 2338 | return int(_env_number(WARM_USERS_ENV, DEFAULT_WARM_USERS, minimum=0)) |
| 2339 | |
| 2340 | def _idle_seconds(self) -> float: |
| 2341 | return _env_number(WARM_IDLE_ENV, DEFAULT_WARM_IDLE_SECONDS, minimum=1) |
| 2342 | |
| 2343 | def supported(self, config: dict[str, Any]) -> bool: |
| 2344 | """Whether warm parents may be used now (``warm_parent_decision``).""" |
| 2345 | if not hasattr(os, "fork"): |
| 2346 | return False |
| 2347 | if not config.get("separated") and isolation_mode() != UNSAFE_DEV: |
| 2348 | return False # no launcher: dev machines only, like the spares |
| 2349 | on, _why = warm_parent_decision( |
| 2350 | os.environ.get(WARM_PARENTS_ENV, ""), self.capacity(), isolation_mode(), landlock_abi(), |
| 2351 | launcher_info() if config.get("separated") else None) |
| 2352 | return on |
| 2353 | |
| 2354 | def running(self) -> int: |
| 2355 | with self._lock: |
| 2356 | return len(self._servers) |
| 2357 | |
| 2358 | def get(self, owner: str | None, config: dict[str, Any]) -> _ForkServer | None: |
| 2359 | """This user's ready fork server, or None (and, when there is none |
| 2360 | yet, start one in the background for the user's next call).""" |
| 2361 | if owner is None or self.capacity() <= 0 or not self.supported(config): |
| 2362 | return None |
| 2363 | key = json.dumps(config, sort_keys=True) |
| 2364 | now = time.monotonic() |
| 2365 | idle = self._idle_seconds() |
| 2366 | retire: list[_ForkServer] = [] |
| 2367 | found = None |
| 2368 | with self._lock: |
| 2369 | if not self._registered: |
| 2370 | import atexit |
| 2371 | |
| 2372 | atexit.register(self.shutdown) |
| 2373 | self._registered = True |
| 2374 | for name, server in list(self._servers.items()): |
| 2375 | if (server.dead or server.config_key != key or server.calls >= FORK_SERVER_MAX_CALLS |
| 2376 | or now - server.last_used > idle): |
| 2377 | retire.append(self._servers.pop(name)) |
| 2378 | found = self._servers.get(owner) |
| 2379 | start = (found is None and owner not in self._starting |
| 2380 | and self._cooldown.get(owner, 0.0) <= now) |
| 2381 | if start: |
| 2382 | self._starting.add(owner) |
| 2383 | generation = self._generation |
| 2384 | for server in retire: |
| 2385 | server.retire() |
| 2386 | if start: |
| 2387 | import threading |
| 2388 | |
| 2389 | threading.Thread(target=self._start, args=(owner, config, generation), |
| 2390 | name="dbbasic-sandbox-fork-server", daemon=True).start() |
| 2391 | return found |
| 2392 | |
| 2393 | def _start(self, owner: str, config: dict[str, Any], generation: int) -> None: |
| 2394 | server = None |
| 2395 | try: |
| 2396 | server = _ForkServer(owner, config) |
| 2397 | server.wait_ready(time.monotonic() + BOOT_TIMEOUT_SECONDS) |
| 2398 | except (OSError, _BootRefused, _WorkerGone, _SandboxTimeout, SandboxProtocolError) as exc: |
| 2399 | detail = f"boot refused: {exc}" if isinstance(exc, _BootRefused) else f"{type(exc).__name__}: {exc}" |
| 2400 | if server is not None: |
| 2401 | server.log_death("failed to start", detail=detail, cause=type(exc).__name__) |
| 2402 | server.close() |
| 2403 | else: |
| 2404 | _log_worker_death("fork server", None, "failed to start", config=config, |
| 2405 | detail=detail, cause=type(exc).__name__) |
| 2406 | _log_fallback("fork server failed to start") |
| 2407 | with self._lock: |
| 2408 | self._starting.discard(owner) |
| 2409 | self._cooldown[owner] = time.monotonic() + FORK_SERVER_COOLDOWN_SECONDS |
| 2410 | return |
| 2411 | evict: list[_ForkServer] = [] |
| 2412 | with self._lock: |
| 2413 | self._starting.discard(owner) |
| 2414 | if generation != self._generation: |
| 2415 | evict.append(server) |
| 2416 | else: |
| 2417 | old = self._servers.pop(owner, None) |
| 2418 | if old is not None: |
| 2419 | evict.append(old) |
| 2420 | self._servers[owner] = server |
| 2421 | while len(self._servers) > max(self.capacity(), 1): |
| 2422 | victim = min((s for o, s in self._servers.items() if o != owner), |
| 2423 | key=lambda s: s.last_used, default=None) |
| 2424 | if victim is None: |
| 2425 | break |
| 2426 | evict.append(self._servers.pop(victim.owner)) |
| 2427 | for old in evict: |
| 2428 | old.retire() |
| 2429 | |
| 2430 | def failed(self, owner: str, server: _ForkServer) -> None: |
| 2431 | server.log_death("stopped answering", cause=getattr(server, "failure", "")) |
| 2432 | with self._lock: |
| 2433 | if self._servers.get(owner) is server: |
| 2434 | del self._servers[owner] |
| 2435 | self._cooldown[owner] = time.monotonic() + FORK_SERVER_COOLDOWN_SECONDS |
| 2436 | server.retire() |
| 2437 | |
| 2438 | def shutdown(self) -> None: |
| 2439 | with self._lock: |
| 2440 | servers, self._servers = list(self._servers.values()), {} |
| 2441 | self._generation += 1 |
| 2442 | self._starting.clear() |
| 2443 | self._cooldown.clear() |
| 2444 | for server in servers: |
| 2445 | server.close() |
| 2446 | |
| 2447 | |
| 2448 | _FORK_SERVERS = _ForkServers() |
| 2449 | |
| 2450 | |
| 2451 | def _fork_server_owner(object_id: str, path: Any) -> str | None: |
| 2452 | """The user a call belongs to, for choosing its fork server; None (the |
| 2453 | spare path) unless the object id and its file agree on one user.""" |
| 2454 | import object_runtime_helpers |
| 2455 | |
| 2456 | by_id = object_runtime_helpers._user_namespace(object_id) if isinstance(object_id, str) else None |
| 2457 | by_path = object_runtime_helpers._path_namespace(path) if path is not None else None |
| 2458 | if by_id is None or (by_path is not None and by_path != by_id): |
| 2459 | return None |
| 2460 | return by_id |
| 2461 | |
| 2462 | |
| 2463 | def shutdown() -> None: |
| 2464 | """Kill every pre-started spare and fork server (tests, server shutdown).""" |
| 2465 | _POOL.shutdown() |
| 2466 | _FORK_SERVERS.shutdown() |
| 2467 | |
| 2468 | |
| 2469 | _REFUSAL_LOGGED: set[str] = set() |
| 2470 | |
| 2471 | |
| 2472 | def _log_refusal(reason: str) -> None: |
| 2473 | if reason in _REFUSAL_LOGGED: |
| 2474 | return |
| 2475 | _REFUSAL_LOGGED.add(reason) |
| 2476 | print(f"[dbbasic] user objects refused: {reason}. Set {ISOLATION_ENV}={UNSAFE_DEV} " |
| 2477 | "only on a development machine.", file=sys.stderr, flush=True) |
| 2478 | |
| 2479 | |
| 2480 | # -- helper dispatch -------------------------------------------------------- |
| 2481 | |
| 2482 | _STATE_OPS = frozenset({"get", "set", "increment", "delete", "delete_many", "update", "get_all", "reload"}) |
| 2483 | _LOG_OPS = frozenset({"log", "debug", "info", "warning", "error", "critical", "get_logs"}) |
| 2484 | _FILE_OPS = frozenset({"put", "get", "delete", "list", "exists"}) |
| 2485 | _SCHEDULE_OPS = frozenset({"schedule", "unschedule"}) |
| 2486 | _MAX_ERROR_TEXT = 64 * 1024 |
| 2487 | |
| 2488 | |
| 2489 | def _builtin_base(exc: BaseException) -> str: |
| 2490 | import builtins |
| 2491 | |
| 2492 | for cls in type(exc).__mro__: |
| 2493 | if getattr(builtins, cls.__name__, None) is cls: |
| 2494 | return cls.__name__ |
| 2495 | return "RuntimeError" |
| 2496 | |
| 2497 | |
| 2498 | class _Target: |
| 2499 | def __init__(self, object_id: str, path: Any, user: bool, base_dir: Any): |
| 2500 | self.object_id = object_id |
| 2501 | self.path = path |
| 2502 | self.user = user |
| 2503 | self.base_dir = base_dir |
| 2504 | self._state = None |
| 2505 | self._logger = None |
| 2506 | self._files = None |
| 2507 | |
| 2508 | def helper(self, name: str): |
| 2509 | import object_logs |
| 2510 | import object_runtime_helpers |
| 2511 | import object_state |
| 2512 | |
| 2513 | if name == "state": |
| 2514 | if self._state is None: |
| 2515 | self._state = object_state.ObjectStateManager(self.object_id, base_dir=self.base_dir) |
| 2516 | return self._state |
| 2517 | if name == "log": |
| 2518 | if self._logger is None: |
| 2519 | self._logger = object_logs.ObjectLogger(self.object_id, base_dir=self.base_dir) |
| 2520 | return self._logger |
| 2521 | if self._files is None: |
| 2522 | self._files = object_runtime_helpers.ObjectFileStore(self.object_id, base_dir=self.base_dir) |
| 2523 | return self._files |
| 2524 | |
| 2525 | |
| 2526 | class _Session: |
| 2527 | """Everything the parent knows about one sandboxed execution.""" |
| 2528 | |
| 2529 | def __init__(self, object_id: str, path: Any, base_dir: Any, identity: Any, deadline: float, max_bytes: int): |
| 2530 | self.base_dir = base_dir |
| 2531 | self.identity = identity |
| 2532 | self.deadline = deadline |
| 2533 | self.max_bytes = max_bytes |
| 2534 | self.calls = 0 |
| 2535 | self.max_calls = int(_env_number(MAX_HELPER_CALLS_ENV, DEFAULT_MAX_HELPER_CALLS, minimum=1)) |
| 2536 | self.targets = [_Target(object_id, path, True, base_dir)] |
| 2537 | |
| 2538 | def _payload(self, payload: Any) -> dict[str, Any]: |
| 2539 | """User code never chooses the identity a callee sees: it is the |
| 2540 | identity of the request that started the chain (or none).""" |
| 2541 | if not isinstance(payload, dict): |
| 2542 | raise TypeError("execute payload must be a dict") |
| 2543 | clean = dict(payload) |
| 2544 | clean.pop("_identity", None) |
| 2545 | if self.identity is not None: |
| 2546 | clean["_identity"] = self.identity |
| 2547 | return clean |
| 2548 | |
| 2549 | def handle(self, message: dict[str, Any]) -> dict[str, Any]: |
| 2550 | """Validate one helper call (protocol errors raise) and perform it |
| 2551 | (helper errors come back as a reply the worker re-raises).""" |
| 2552 | self.calls += 1 |
| 2553 | if self.calls > self.max_calls: |
| 2554 | raise SandboxProtocolError(f"more than {self.max_calls} helper calls in one execution") |
| 2555 | helper = message.get("helper") |
| 2556 | op = message.get("op") |
| 2557 | handle = message.get("h") |
| 2558 | args = message.get("args") |
| 2559 | kwargs = message.get("kwargs") |
| 2560 | if not isinstance(op, str) or not isinstance(args, list) or not isinstance(kwargs, dict): |
| 2561 | raise SandboxProtocolError("malformed helper call") |
| 2562 | if not isinstance(handle, int) or isinstance(handle, bool) or not 0 <= handle < len(self.targets): |
| 2563 | raise SandboxProtocolError("helper call names an unknown object handle") |
| 2564 | if not all(isinstance(k, str) for k in kwargs): |
| 2565 | raise SandboxProtocolError("malformed helper call") |
| 2566 | allowed = {"state": _STATE_OPS, "log": _LOG_OPS, "files": _FILE_OPS, |
| 2567 | "schedule": _SCHEDULE_OPS, |
| 2568 | "runtime": frozenset({"load_object"}), "object": frozenset({"execute"})}.get(helper) |
| 2569 | if allowed is None or op not in allowed: |
| 2570 | raise SandboxProtocolError(f"unknown helper call {helper!r}.{op!r}") |
| 2571 | target = self.targets[handle] |
| 2572 | try: |
| 2573 | value = self._perform(target, helper, op, args, kwargs) |
| 2574 | _encode({"value": value}) # replies must cross the wire |
| 2575 | except SandboxProtocolError: |
| 2576 | raise |
| 2577 | except Exception as exc: |
| 2578 | return {"t": "reply", "ok": False, |
| 2579 | "error": {"type": type(exc).__name__, "base": _builtin_base(exc), |
| 2580 | "message": str(exc)[:_MAX_ERROR_TEXT]}} |
| 2581 | return {"t": "reply", "ok": True, "value": value} |
| 2582 | |
| 2583 | def _perform(self, target: _Target, helper: str, op: str, args: list, kwargs: dict) -> Any: |
| 2584 | if helper == "runtime": |
| 2585 | if len(args) != 1 or kwargs: |
| 2586 | raise TypeError("load_object takes one object id") |
| 2587 | return self._load(target, args[0]) |
| 2588 | if helper == "object": |
| 2589 | if target is self.targets[0] or len(args) != 2 or kwargs: |
| 2590 | raise SandboxProtocolError("malformed execute call") |
| 2591 | return self._execute(target, args[0], args[1]) |
| 2592 | if helper == "schedule": |
| 2593 | return self._schedule(target, op, args, kwargs) |
| 2594 | if not target.user: |
| 2595 | raise PermissionError( |
| 2596 | f"{target.object_id} is not in your namespace: a user object may only " |
| 2597 | "execute() a system object, not use its state, logs or files" |
| 2598 | ) |
| 2599 | if helper == "state" and op == "update" and kwargs: |
| 2600 | raise TypeError("update(after_set=...) is not available to user objects") |
| 2601 | if helper == "state" and op in ("get_all", "reload") and (args or kwargs): |
| 2602 | raise TypeError(f"{op}() takes no arguments") |
| 2603 | return getattr(target.helper(helper), op)(*args, **kwargs) |
| 2604 | |
| 2605 | def _schedule(self, target: _Target, op: str, args: list, kwargs: dict) -> Any: |
| 2606 | """A user object may schedule only ITSELF: the object this session |
| 2607 | is running, never one it loaded (object_schedule holds the limits).""" |
| 2608 | import object_schedule |
| 2609 | |
| 2610 | if target is not self.targets[0]: |
| 2611 | raise ScheduleError("an object may only schedule its own methods") |
| 2612 | if kwargs: |
| 2613 | raise ScheduleError(f"{op}() takes positional arguments only") |
| 2614 | if op == "schedule": |
| 2615 | if len(args) != 2: |
| 2616 | raise ScheduleError("_schedule(interval_seconds, method_name) takes two arguments") |
| 2617 | row = object_schedule.schedule(target.object_id, args[1], args[0], base_dir=self.base_dir) |
| 2618 | return {key: row.get(key) for key in ("id", "method", "interval_seconds", "next_run", "status")} |
| 2619 | if len(args) > 1: |
| 2620 | raise ScheduleError("_unschedule(method_name=None) takes at most one argument") |
| 2621 | return object_schedule.unschedule(target.object_id, args[0] if args else None, base_dir=self.base_dir) |
| 2622 | |
| 2623 | def _load(self, caller: _Target, object_id: Any) -> dict[str, Any]: |
| 2624 | import object_runtime_helpers |
| 2625 | |
| 2626 | composer = object_runtime_helpers.ObjectComposer(caller.object_id, base_dir=self.base_dir) |
| 2627 | path = composer.resolve(object_id) |
| 2628 | user = is_user_code(object_id, path) |
| 2629 | self.targets.append(_Target(object_id, path, user, self.base_dir)) |
| 2630 | return {"h": len(self.targets) - 1, "object_id": object_id} |
| 2631 | |
| 2632 | def _execute(self, target: _Target, method: Any, payload: Any) -> Any: |
| 2633 | import object_runtime_helpers |
| 2634 | |
| 2635 | if not isinstance(method, str): |
| 2636 | raise TypeError("execute method must be a string") |
| 2637 | payload = self._payload(payload) |
| 2638 | if target.user: |
| 2639 | remaining = self.deadline - time.monotonic() |
| 2640 | if remaining <= 0: |
| 2641 | raise _SandboxTimeout() |
| 2642 | with object_runtime_helpers.execution_frame(target.object_id): |
| 2643 | result = run_user_object( |
| 2644 | target.object_id, target.path, method, payload, |
| 2645 | base_dir=self.base_dir, timeout_seconds=remaining, |
| 2646 | correlation_id=None, identity=self.identity, |
| 2647 | ) |
| 2648 | return _unwrap(result) |
| 2649 | from python_object_runtime import PythonObject |
| 2650 | |
| 2651 | # A system object called from user code runs on the normal path, in |
| 2652 | # this process, with the identity of the request (never one the user |
| 2653 | # code wrote into the payload). |
| 2654 | return PythonObject(path=target.path, object_id=target.object_id, base_dir=self.base_dir).execute(method, payload) |
| 2655 | |
| 2656 | |
| 2657 | def _unwrap(result) -> Any: |
| 2658 | """A nested call's value, or its failure re-raised under the callee's |
| 2659 | own error type name (as in-process composition would surface it).""" |
| 2660 | if result.ok: |
| 2661 | return result.result |
| 2662 | error = result.error |
| 2663 | name = error.type if error is not None and error.type.isidentifier() else "ObjectMethodExecutionError" |
| 2664 | raise type(name, (RuntimeError,), {})(error.message if error is not None else "object failed") |
| 2665 | |
| 2666 | |
| 2667 | def _result(object_id, method, path, ok, value, error, started_at, started_perf, correlation_id): |
| 2668 | import object_execution |
| 2669 | |
| 2670 | return object_execution.ObjectExecutionResult( |
| 2671 | object_id=object_id, |
| 2672 | method=method, |
| 2673 | path=path, |
| 2674 | ok=ok, |
| 2675 | result=value, |
| 2676 | error=error, |
| 2677 | started_at=started_at, |
| 2678 | finished_at=_utc_timestamp(), |
| 2679 | duration_ms=round((time.perf_counter() - started_perf) * 1000, 3), |
| 2680 | correlation_id=correlation_id, |
| 2681 | ) |
| 2682 | |
| 2683 | |
| 2684 | def _error(error_type: str, message: str, traceback_text: str = ""): |
| 2685 | import object_execution |
| 2686 | |
| 2687 | return object_execution.ObjectExecutionError(type=error_type, message=message, traceback=traceback_text) |
| 2688 | |
| 2689 | |
| 2690 | def default_timeout_seconds() -> float: |
| 2691 | return _env_number(TIMEOUT_ENV, DEFAULT_TIMEOUT_SECONDS, minimum=0.001) |
| 2692 | |
| 2693 | |
| 2694 | def run_user_object( |
| 2695 | object_id: str, |
| 2696 | path: Any, |
| 2697 | method: str, |
| 2698 | payload: dict[str, Any], |
| 2699 | *, |
| 2700 | base_dir: Any, |
| 2701 | timeout_seconds: float | None = None, |
| 2702 | correlation_id: str | None = None, |
| 2703 | identity: Any = None, |
| 2704 | named_method: bool = False, |
| 2705 | ): |
| 2706 | """Run one user object method in a fresh sandboxed worker. |
| 2707 | |
| 2708 | Returns an ``ObjectExecutionResult`` shaped exactly as in-process |
| 2709 | execution would; refusals, timeouts and protocol violations are results |
| 2710 | too, never exceptions.""" |
| 2711 | from pathlib import Path |
| 2712 | |
| 2713 | started_perf = time.perf_counter() |
| 2714 | started_at = _utc_timestamp() |
| 2715 | method = (method or "GET").strip() |
| 2716 | if not named_method: |
| 2717 | method = method.upper() or "GET" |
| 2718 | path = Path(path) if path is not None else None |
| 2719 | |
| 2720 | def fail(error_type: str, message: str, tb: str = ""): |
| 2721 | return _result(object_id, method, path, False, None, _error(error_type, message, tb), |
| 2722 | started_at, started_perf, correlation_id) |
| 2723 | |
| 2724 | status = isolation_status() |
| 2725 | if not status["available"]: |
| 2726 | _log_refusal(status["reason"]) |
| 2727 | return fail(ISOLATION_ERROR_TYPE, f"User objects cannot run on this server: {status['reason']}.") |
| 2728 | if path is None or not path.is_file(): |
| 2729 | return fail("ObjectNotFoundError", f"Object not found: {object_id}") |
| 2730 | try: |
| 2731 | source = path.read_text() |
| 2732 | except (OSError, UnicodeDecodeError) as exc: |
| 2733 | return fail("ObjectLoadError", f"Failed to load object {object_id} from {path}: {type(exc).__name__}: {exc}") |
| 2734 | |
| 2735 | timeout = timeout_seconds if timeout_seconds and timeout_seconds > 0 else default_timeout_seconds() |
| 2736 | max_bytes = int(_env_number(MAX_MESSAGE_BYTES_ENV, DEFAULT_MAX_MESSAGE_BYTES, minimum=1024)) |
| 2737 | deadline = time.monotonic() + timeout |
| 2738 | session = _Session(object_id, path, base_dir, identity, deadline, max_bytes) |
| 2739 | |
| 2740 | run = { |
| 2741 | "t": "run", |
| 2742 | "object_id": object_id, |
| 2743 | "method": method, |
| 2744 | "named": bool(named_method), |
| 2745 | "path": str(path), |
| 2746 | "payload": payload, |
| 2747 | "source": source, |
| 2748 | } |
| 2749 | try: |
| 2750 | run_frame = _encode(run) |
| 2751 | except (TypeError, ValueError, RecursionError) as exc: # payload that cannot cross the wire |
| 2752 | return fail(_WORKER_ERROR_TYPE, f"Request can't be sent to an object worker: {exc}") |
| 2753 | config = _boot_config() |
| 2754 | owner = _fork_server_owner(object_id, path) |
| 2755 | for attempt in range(2): |
| 2756 | worker = None |
| 2757 | server = _FORK_SERVERS.get(owner, config) |
| 2758 | if server is not None: |
| 2759 | try: |
| 2760 | worker = server.fork(run_frame) |
| 2761 | except _ForkServerFailed: |
| 2762 | _FORK_SERVERS.failed(owner, server) # fail closed: today's single-use spare below |
| 2763 | worker = None |
| 2764 | if worker is None: |
| 2765 | try: |
| 2766 | worker = _POOL.acquire(config) |
| 2767 | except OSError as exc: |
| 2768 | _log_worker_death("single-use worker", None, "failed to start", config=config, |
| 2769 | detail=f"{type(exc).__name__}: {exc}", cause=type(exc).__name__) |
| 2770 | return fail(_WORKER_ERROR_TYPE, f"Failed to start a user-code worker: {type(exc).__name__}: {exc}") |
| 2771 | heard = False # any message from this worker at all |
| 2772 | gone = None |
| 2773 | try: |
| 2774 | try: |
| 2775 | worker.wait_ready(min(deadline, time.monotonic() + BOOT_TIMEOUT_SECONDS)) |
| 2776 | except _BootRefused as exc: |
| 2777 | _log_refusal(str(exc)) |
| 2778 | return fail(ISOLATION_ERROR_TYPE, f"User objects cannot run on this server: {exc}.") |
| 2779 | if not getattr(worker, "run_sent", False): |
| 2780 | worker.send_frame(run_frame, deadline) |
| 2781 | while True: |
| 2782 | message = worker.recv(deadline, max_bytes) |
| 2783 | heard = True |
| 2784 | kind = message.get("t") |
| 2785 | if kind == "call": |
| 2786 | worker.send(session.handle(message), deadline) |
| 2787 | continue |
| 2788 | if kind != "result": |
| 2789 | raise SandboxProtocolError(f"unexpected worker message {kind!r}") |
| 2790 | return _result_message(message, object_id, method, path, started_at, started_perf, correlation_id) |
| 2791 | except _SandboxTimeout: |
| 2792 | return fail(_TIMEOUT_ERROR_TYPE, f"{method} timed out for object {object_id} after {timeout:g} seconds") |
| 2793 | except SandboxProtocolError as exc: |
| 2794 | print(f"[dbbasic] killed user-code worker for {object_id}: {exc}", file=sys.stderr, flush=True) |
| 2795 | return fail(PROTOCOL_ERROR_TYPE, f"Object worker for {object_id} broke the protocol and was stopped: {exc}") |
| 2796 | except (_WorkerGone, _BootRefused): |
| 2797 | code = worker.exit_code() |
| 2798 | gone = fail(_WORKER_ERROR_TYPE, f"Object worker exited without a result (exit code {code})") |
| 2799 | _log_worker_death("forked child" if isinstance(worker, _ForkedChild) else "single-use worker", |
| 2800 | worker, "exited without a result", |
| 2801 | status=code if code is not None else worker.status_now(0.1)) |
| 2802 | if attempt > 0 or heard or not isinstance(worker, _ForkedChild): |
| 2803 | return gone |
| 2804 | except (TypeError, ValueError, RecursionError) as exc: # payload that cannot cross the wire |
| 2805 | return fail(_WORKER_ERROR_TYPE, f"Request can't be sent to an object worker: {exc}") |
| 2806 | finally: |
| 2807 | worker.kill() |
| 2808 | # A forked child that died before it took its pipes (a forked-ahead |
| 2809 | # child killed while it waited) never read the request: nothing of |
| 2810 | # this call ran, so it runs once more on a fresh child. Anything |
| 2811 | # less certain is the caller's error, never a second run. |
| 2812 | if not worker.never_took_the_call(): |
| 2813 | return gone |
| 2814 | return gone |
| 2815 | |
| 2816 | |
| 2817 | def _result_message(message, object_id, method, path, started_at, started_perf, correlation_id): |
| 2818 | ok = message.get("ok") |
| 2819 | if ok is True: |
| 2820 | return _result(object_id, method, path, True, message.get("result"), None, |
| 2821 | started_at, started_perf, correlation_id) |
| 2822 | error = message.get("error") |
| 2823 | if ok is not False or not isinstance(error, dict): |
| 2824 | raise SandboxProtocolError("malformed result") |
| 2825 | fields = [] |
| 2826 | for key in ("type", "message", "traceback"): |
| 2827 | value = error.get(key, "") |
| 2828 | if not isinstance(value, str): |
| 2829 | raise SandboxProtocolError("malformed result error") |
| 2830 | fields.append(value[:_MAX_ERROR_TEXT]) |
| 2831 | if not fields[0].isidentifier(): |
| 2832 | raise SandboxProtocolError("malformed result error type") |
| 2833 | return _result(object_id, method, path, False, None, _error(*fields), |
| 2834 | started_at, started_perf, correlation_id) |
| 2835 | |
| 2836 | |
| 2837 | def execute_request(request, path, *, base_dir, timeout_seconds: float | None = None): |
| 2838 | """``run_user_object`` for an ``ObjectExecutionRequest``.""" |
| 2839 | payload = request.normalized_payload() |
| 2840 | return run_user_object( |
| 2841 | request.object_id, path, request.normalized_method(), payload, |
| 2842 | base_dir=base_dir, timeout_seconds=timeout_seconds, |
| 2843 | correlation_id=request.correlation_id, identity=payload.get("_identity"), |
| 2844 | named_method=bool(getattr(request, "named_method", False)), |
| 2845 | ) |
| 2846 | |
| 2847 | |
| 2848 | class SandboxedObject: |
| 2849 | """What ``_runtime.load_object`` returns to a *system* object asking for |
| 2850 | a user object: the managers are the real ones (the caller is trusted |
| 2851 | server code); ``execute`` crosses into the sandbox.""" |
| 2852 | |
| 2853 | def __init__(self, path, object_id: str, base_dir): |
| 2854 | import object_logs |
| 2855 | import object_runtime_helpers |
| 2856 | import object_state |
| 2857 | from pathlib import Path |
| 2858 | |
| 2859 | self.path = Path(path) |
| 2860 | self.object_id = object_id |
| 2861 | self.base_dir = base_dir |
| 2862 | self.state_manager = object_state.ObjectStateManager(object_id, base_dir=base_dir) |
| 2863 | self.logger = object_logs.ObjectLogger(object_id, base_dir=base_dir) |
| 2864 | self.file_manager = object_runtime_helpers.ObjectFileStore(object_id, base_dir=base_dir) |
| 2865 | |
| 2866 | def execute(self, method: str, payload: dict[str, Any]) -> Any: |
| 2867 | import object_runtime_helpers |
| 2868 | |
| 2869 | with object_runtime_helpers.execution_frame(self.object_id): |
| 2870 | result = run_user_object(self.object_id, self.path, method, dict(payload or {}), |
| 2871 | base_dir=self.base_dir, |
| 2872 | identity=(payload or {}).get("_identity")) |
| 2873 | return _unwrap(result) |
| 2874 | |
| 2875 | |
| 2876 | def warm_parent_decision(setting: str, capacity: int, mode: str, abi: int, |
| 2877 | launcher: dict[str, Any] | None) -> tuple[bool, str]: |
| 2878 | """Are warm parents (per-user fork servers) on, and why. Pure, so the |
| 2879 | gate is tested for every kernel without that kernel. |
| 2880 | |
| 2881 | ``setting`` is DBBASIC_USER_CODE_WARM_PARENTS: ``auto`` (the default) |
| 2882 | turns them on only where Landlock scopes signals (ABI >= 6), because a |
| 2883 | warm parent lives for many calls and below that ABI another user's code |
| 2884 | running as the same sandbox uid could kill or stop it. ``on`` opts in |
| 2885 | anyway; ``off`` never uses them.""" |
| 2886 | setting = (setting or "auto").strip().lower() |
| 2887 | if setting not in ("auto", "on", "off"): |
| 2888 | setting = "auto" |
| 2889 | spares = "every call takes a single-use spare" |
| 2890 | if setting == "off": |
| 2891 | return False, f"off ({WARM_PARENTS_ENV}=off): {spares}" |
| 2892 | if capacity <= 0: |
| 2893 | return False, f"off ({WARM_USERS_ENV}=0): {spares}" |
| 2894 | if launcher is not None and "socket" not in (launcher.get("channels") or []): |
| 2895 | return False, ("off: the sandbox launcher is too old to hand a fork server its channel; " |
| 2896 | f"{spares}") |
| 2897 | users = f"one fork server per recent user, up to {capacity} users" |
| 2898 | if mode == UNSAFE_DEV: |
| 2899 | return True, f"on ({UNSAFE_DEV}, no wall): {users}" |
| 2900 | if abi >= WARM_PARENTS_MIN_LANDLOCK_ABI: |
| 2901 | return True, f"on: Landlock ABI {abi} scopes signals; {users}" |
| 2902 | if setting == "on": |
| 2903 | return True, (f"on by opt-in ({WARM_PARENTS_ENV}=on) although Landlock ABI {abi} cannot scope " |
| 2904 | f"signals: another user's code can kill or stop a warm parent; {users}") |
| 2905 | return False, (f"off: Landlock ABI {abi} cannot scope signals; set {WARM_PARENTS_ENV}=on to opt in, " |
| 2906 | f"or use a kernel with ABI >= {WARM_PARENTS_MIN_LANDLOCK_ABI}; {spares}") |
| 2907 | |
| 2908 | |
| 2909 | def _warm_parent_status(launcher: dict[str, Any] | None, abi: int | None = None) -> dict[str, Any]: |
| 2910 | capacity = _FORK_SERVERS.capacity() |
| 2911 | on, why = warm_parent_decision(os.environ.get(WARM_PARENTS_ENV, ""), capacity, isolation_mode(), |
| 2912 | landlock_abi() if abi is None else abi, launcher) |
| 2913 | return {"enabled": on, "max_users": capacity, "running": _FORK_SERVERS.running(), "status": why} |
| 2914 | |
| 2915 | |
| 2916 | def _verdict(status: dict[str, Any]) -> str: |
| 2917 | if not status["available"]: |
| 2918 | return "user objects REFUSED: " + status["reason"] |
| 2919 | if status["mode"] == UNSAFE_DEV: |
| 2920 | return "user objects run WITHOUT the kernel wall (development only)" |
| 2921 | return (f"user objects run isolated: separate uid {status['sandbox_uid']}, Landlock ABI " |
| 2922 | f"{status['landlock_abi']}, network namespace {'yes' if status['network_namespace'] else 'no'}; " |
| 2923 | f"UDP {status['udp']}; warm parents {status['warm_parents']['status']}") |
| 2924 | |
| 2925 | |
| 2926 | def _not_the_service_user(status: dict[str, Any], uid: int, groups: set[int], socket_info: Any) -> bool: |
| 2927 | """True when ``--status`` found no launcher only because of who ran it. |
| 2928 | The launcher answers the server's uid alone and its socket is |
| 2929 | root:<server group> 0660 in a 0750 directory, so root (or any other |
| 2930 | user) sees "no launcher" on a host where the server itself is served. |
| 2931 | ``socket_info`` is the socket's stat result, PermissionError when this |
| 2932 | user may not even look, or None when there is no socket.""" |
| 2933 | import stat as stat_module |
| 2934 | |
| 2935 | if status["available"] or status["mode"] == UNSAFE_DEV or status["uid_separation"]: |
| 2936 | return False |
| 2937 | if isinstance(socket_info, PermissionError): |
| 2938 | return True |
| 2939 | if socket_info is None or not stat_module.S_ISSOCK(socket_info.st_mode): |
| 2940 | return False |
| 2941 | return uid == 0 and socket_info.st_gid != 0 or uid != 0 and socket_info.st_gid not in groups |
| 2942 | |
| 2943 | |
| 2944 | def _status_for_operator() -> dict[str, Any]: |
| 2945 | """isolation_status() plus the verdict line ``--status`` prints. Run by |
| 2946 | someone other than the service user, a missing launcher answer says |
| 2947 | nothing about the server, so the verdict says to run it as that user |
| 2948 | instead of REFUSED. ``available`` (the exit status) is unchanged.""" |
| 2949 | status = isolation_status() |
| 2950 | status["verdict"] = _verdict(status) |
| 2951 | if not status["available"] and hasattr(os, "getuid"): |
| 2952 | try: |
| 2953 | socket_info: Any = os.stat(status["launcher_socket"]) |
| 2954 | except PermissionError as exc: |
| 2955 | socket_info = exc |
| 2956 | except OSError: |
| 2957 | socket_info = None |
| 2958 | if _not_the_service_user(status, os.getuid(), {os.getgid(), *os.getgroups()}, socket_info): |
| 2959 | status["verdict"] = ( |
| 2960 | "cannot tell as this user: run this as the service user (docker compose exec -u dbbasic ..., " |
| 2961 | "or sudo -u dbbasic ...). The sandbox launcher answers only the server's own user, and this " |
| 2962 | f"is uid {os.getuid()}, so the result above says nothing about whether user objects run") |
| 2963 | return status |
| 2964 | |
| 2965 | |
| 2966 | if __name__ == "__main__": |
| 2967 | if "--worker" in sys.argv[1:]: |
| 2968 | # Leave without interpreter teardown once the answer is sent: nothing |
| 2969 | # user code queued (atexit handlers, finalizers) runs after its |
| 2970 | # result, and the worker does not spend ~3 ms finalizing on the core |
| 2971 | # the server is waiting to be scheduled on (measured: that teardown |
| 2972 | # was most of a warm call's latency). |
| 2973 | code = 1 |
| 2974 | try: |
| 2975 | code = _worker_main() |
| 2976 | finally: |
| 2977 | os._exit(code) |
| 2978 | if "--status" in sys.argv[1:]: |
| 2979 | # Operator check: can this host run user objects? Exit 0 = yes. |
| 2980 | sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) |
| 2981 | status = _status_for_operator() |
| 2982 | print(json.dumps(status, indent=2)) |
| 2983 | raise SystemExit(0 if status["available"] else 1) |
| 2984 | print("usage: python object_sandbox.py --worker | --status", file=sys.stderr) |
| 2985 | raise SystemExit(2) |