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.
test_object_sandbox_fork_server.py · 27.1 KB · 633 lines
| 1 | """Warm parents: one fork server per user, one fresh child per call. |
| 2 | |
| 3 | A sandboxed call used to cost a whole worker boot (interpreter start, |
| 4 | imports, rlimits, Landlock: ~45 ms of CPU, ~7-13 ms of latency with spares |
| 5 | pre-started). A fork server is a booted worker that forks a child per call, |
| 6 | so the boot is paid once per user. What must not change is what a call can |
| 7 | see or leave behind: |
| 8 | |
| 9 | - **Nothing carries from one call to the next**, not even for the same user: |
| 10 | module globals, builtins, monkeypatched stdlib modules, the environment, |
| 11 | the random generator, processes. Each child is forked from a parent that |
| 12 | never ran user code and never held a request's data (the per-call pipes |
| 13 | are passed to it as fds; source, payload and results never cross it). |
| 14 | - **Nothing is ever shared between users**: one fork server per user, |
| 15 | never reused for another. |
| 16 | - **Fail closed**: when a fork server cannot be started or misbehaves, the |
| 17 | call takes a single-use spare, as before -- never a less isolated path. |
| 18 | |
| 19 | Plumbing tests run everywhere under ``unsafe-dev`` (the fork server works |
| 20 | without the wall); the wall tests need Linux with Landlock and the launcher |
| 21 | (run them in Linux Docker, see tests/test_object_sandbox_launcher.py). |
| 22 | """ |
| 23 | from __future__ import annotations |
| 24 | |
| 25 | import os |
| 26 | import signal |
| 27 | import sys |
| 28 | import threading |
| 29 | import time |
| 30 | |
| 31 | import pytest |
| 32 | |
| 33 | import object_sandbox |
| 34 | from runtime_modes import configure, run_object, write_object |
| 35 | from sandbox_signals import signal_worker |
| 36 | from test_object_sandbox import HAS_WALL, needs_wall |
| 37 | |
| 38 | |
| 39 | @pytest.fixture(autouse=True) |
| 40 | def _clean(): |
| 41 | object_sandbox.shutdown() |
| 42 | yield |
| 43 | object_sandbox.shutdown() |
| 44 | |
| 45 | |
| 46 | @pytest.fixture(params=["unsafe-dev", "walled"]) |
| 47 | def mode(request, monkeypatch): |
| 48 | if request.param == "walled": |
| 49 | if not HAS_WALL: |
| 50 | pytest.skip("needs Linux with Landlock ABI >= 4, a non-root user and the root sandbox launcher") |
| 51 | monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False) |
| 52 | else: |
| 53 | monkeypatch.setenv(object_sandbox.ISOLATION_ENV, object_sandbox.UNSAFE_DEV) |
| 54 | return request.param |
| 55 | |
| 56 | |
| 57 | def run(root, object_id, method="GET", payload=None): |
| 58 | return run_object("in_process", root, object_id, method, payload) |
| 59 | |
| 60 | |
| 61 | def _server_pid(owner): |
| 62 | server = object_sandbox._FORK_SERVERS._servers.get(owner) |
| 63 | return server.worker.pid if server is not None else None |
| 64 | |
| 65 | |
| 66 | def _warm(root, object_id, owner, seconds=15.0): |
| 67 | """Call until this user's fork server is up; return its pid.""" |
| 68 | deadline = time.monotonic() + seconds |
| 69 | while time.monotonic() < deadline: |
| 70 | result = run(root, object_id) |
| 71 | assert result.ok, result.error |
| 72 | if _server_pid(owner) is not None: |
| 73 | return _server_pid(owner) |
| 74 | time.sleep(0.05) |
| 75 | pytest.fail(f"no fork server for user {owner}") |
| 76 | |
| 77 | |
| 78 | def _gone(pid, seconds=5.0): |
| 79 | """True once ``pid`` no longer exists (as a live process or zombie).""" |
| 80 | deadline = time.monotonic() + seconds |
| 81 | while time.monotonic() < deadline: |
| 82 | if sys.platform.startswith("linux"): |
| 83 | if not os.path.exists(f"/proc/{pid}"): |
| 84 | return True |
| 85 | else: |
| 86 | try: |
| 87 | os.kill(pid, 0) |
| 88 | except ProcessLookupError: |
| 89 | return True |
| 90 | except PermissionError: |
| 91 | pass |
| 92 | time.sleep(0.02) |
| 93 | return False |
| 94 | |
| 95 | |
| 96 | WHO = """ |
| 97 | import os |
| 98 | import signal |
| 99 | def GET(request): |
| 100 | return {"pid": os.getpid(), "ppid": os.getppid(), "uid": os.getuid()} |
| 101 | """ |
| 102 | |
| 103 | |
| 104 | def test_calls_fork_from_the_users_own_warm_parent(tmp_path, monkeypatch, mode): |
| 105 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 106 | write_object(root, "u_7_who", WHO) |
| 107 | parent = _warm(root, "u_7_who", "7") |
| 108 | seen = [run(root, "u_7_who").result for _ in range(5)] |
| 109 | assert {r["ppid"] for r in seen} == {parent} # the fast path, every time |
| 110 | assert len({r["pid"] for r in seen}) == 5 # a fresh child per call |
| 111 | if mode == "walled": |
| 112 | assert {r["uid"] for r in seen} == {object_sandbox.launcher_info()["sandbox_uid"]} |
| 113 | |
| 114 | |
| 115 | LEAKY = """ |
| 116 | import builtins, json, os, random, string, sys |
| 117 | |
| 118 | STATE = [] |
| 119 | |
| 120 | def GET(request): |
| 121 | seen = { |
| 122 | "module_global": list(STATE), |
| 123 | "builtins": getattr(builtins, "LEAKED", None), |
| 124 | "json_patched": getattr(json, "LEAKED", None), |
| 125 | "stdlib_replaced": string.capwords.__name__ != "capwords", |
| 126 | "environ": os.environ.get("LEAKED"), |
| 127 | "planted_module": "planted_by_an_earlier_call" in sys.modules, |
| 128 | "random": random.random(), |
| 129 | } |
| 130 | # Not "MARK" + "ER-": the compiler folds that into one constant in this |
| 131 | # function's co_consts, a tuple the scan below finds in every call on |
| 132 | # Python 3.10-3.13 (gc stops tracking it only from 3.14). And this source |
| 133 | # text is itself in the child's memory, so the whole word must not be |
| 134 | # spelled out in a comment either. |
| 135 | marker = "".join(["MARK", "ER-"]) |
| 136 | seen["payload_in_memory"] = _scan(marker) |
| 137 | STATE.append("call") |
| 138 | builtins.LEAKED = "from an earlier call" |
| 139 | json.LEAKED = "from an earlier call" |
| 140 | string.capwords = lambda *a, **k: "hijacked" |
| 141 | os.environ["LEAKED"] = "from an earlier call" |
| 142 | sys.modules["planted_by_an_earlier_call"] = type(sys)("planted_by_an_earlier_call") |
| 143 | return seen |
| 144 | |
| 145 | def _scan(marker): |
| 146 | import gc |
| 147 | hits = 0 |
| 148 | for obj in gc.get_objects(): |
| 149 | try: |
| 150 | if isinstance(obj, dict): |
| 151 | values = list(obj.values()) |
| 152 | elif isinstance(obj, (list, tuple)): |
| 153 | values = list(obj) |
| 154 | else: |
| 155 | continue |
| 156 | except Exception: |
| 157 | continue |
| 158 | for value in values: |
| 159 | if isinstance(value, (str, bytes)) and marker in (value if isinstance(value, str) else value.decode("latin-1")): |
| 160 | hits += 1 |
| 161 | return hits |
| 162 | """ |
| 163 | |
| 164 | |
| 165 | def test_no_state_carries_from_one_call_to_the_next_of_the_same_user(tmp_path, monkeypatch, mode): |
| 166 | """Call 1 plants everything it can in its process; call 2 of the same |
| 167 | user's same object finds none of it, and its random generator is not a |
| 168 | replay. Call 1's payload (another visitor's data, say) is not in call |
| 169 | 2's memory either: the fork server never held it.""" |
| 170 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 171 | write_object(root, "u_7_leaky", LEAKY) |
| 172 | _warm(root, "u_7_leaky", "7") |
| 173 | # A list, not a bare string: gc does not track a dict holding only strings |
| 174 | # (before 3.14), so the scan could not see `{"secret": "MARKER-..."}` at all. |
| 175 | first = run(root, "u_7_leaky", "GET", {"secret": ["MARKER-visitor-one"]}) |
| 176 | second = run(root, "u_7_leaky", "GET", {"other": "nothing"}) |
| 177 | assert first.ok and second.ok, (first.error, second.error) |
| 178 | for result in (first, second): |
| 179 | seen = result.result |
| 180 | assert seen["module_global"] == [] and seen["builtins"] is None and seen["json_patched"] is None |
| 181 | assert seen["stdlib_replaced"] is False and seen["environ"] is None and seen["planted_module"] is False |
| 182 | assert first.result["payload_in_memory"] >= 1, "the scan cannot see a payload, so it proves nothing" |
| 183 | assert second.result["payload_in_memory"] == 0 |
| 184 | assert first.result["random"] != second.result["random"] |
| 185 | |
| 186 | |
| 187 | def test_different_users_never_share_a_warm_parent(tmp_path, monkeypatch, mode): |
| 188 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 189 | write_object(root, "u_7_who", WHO) |
| 190 | write_object(root, "u_8_who", WHO) |
| 191 | seven = _warm(root, "u_7_who", "7") |
| 192 | eight = _warm(root, "u_8_who", "8") |
| 193 | assert seven != eight |
| 194 | assert run(root, "u_7_who").result["ppid"] == seven |
| 195 | assert run(root, "u_8_who").result["ppid"] == eight |
| 196 | servers = object_sandbox._FORK_SERVERS._servers |
| 197 | assert servers["7"].owner == "7" and servers["8"].owner == "8" |
| 198 | config = object_sandbox._boot_config() |
| 199 | assert object_sandbox._FORK_SERVERS.get("9", config) is None # a third user gets its own, later |
| 200 | |
| 201 | |
| 202 | def test_the_owner_is_taken_from_the_id_and_must_agree_with_the_file(tmp_path): |
| 203 | from pathlib import Path |
| 204 | |
| 205 | owner = object_sandbox._fork_server_owner |
| 206 | assert owner("u_7_x", Path("/data/objects/users/7/x.py")) == "7" |
| 207 | assert owner("u_7_x", None) == "7" |
| 208 | assert owner("u_7_x", Path("/data/objects/users/8/x.py")) is None # disagreement: spare path |
| 209 | assert owner("tools_x", Path("/data/objects/users/7/x.py")) is None |
| 210 | assert owner("tools_x", None) is None |
| 211 | |
| 212 | |
| 213 | PID_THEN = """ |
| 214 | import os |
| 215 | import signal |
| 216 | def GET(request): |
| 217 | _state_manager.set("pid", os.getpid()) |
| 218 | ACTION |
| 219 | return {"pid": os.getpid()} |
| 220 | """ |
| 221 | |
| 222 | |
| 223 | def _stage(root, name, action): |
| 224 | write_object(root, f"u_7_{name}", PID_THEN.replace("ACTION", action)) |
| 225 | |
| 226 | |
| 227 | def test_a_child_is_killed_and_reaped_when_its_call_ends(tmp_path, monkeypatch, mode): |
| 228 | data_dir, root = configure(monkeypatch, tmp_path) |
| 229 | _stage(root, "plain", "pass") |
| 230 | _warm(root, "u_7_plain", "7") |
| 231 | result = run(root, "u_7_plain") |
| 232 | assert result.ok |
| 233 | assert _gone(result.result["pid"]) |
| 234 | |
| 235 | |
| 236 | def test_a_child_that_answers_and_keeps_running_is_still_killed(tmp_path, monkeypatch, mode): |
| 237 | """A forged result followed by more work: the server takes the first |
| 238 | result, and the child is killed regardless of what it does next.""" |
| 239 | import object_state |
| 240 | |
| 241 | data_dir, root = configure(monkeypatch, tmp_path) |
| 242 | forge = ( |
| 243 | "import time\n" |
| 244 | " ch = object.__getattribute__(_state_manager, '_channel')\n" |
| 245 | " ch.send({'t': 'result', 'ok': True, 'result': {'forged': True}})\n" |
| 246 | " time.sleep(30)" |
| 247 | ) |
| 248 | _stage(root, "forger", forge) |
| 249 | write_object(root, "u_7_who", WHO) |
| 250 | parent = _warm(root, "u_7_who", "7") |
| 251 | started = time.monotonic() |
| 252 | result = run(root, "u_7_forger") |
| 253 | assert time.monotonic() - started < 10 |
| 254 | assert result.ok and result.result == {"forged": True} |
| 255 | pid = object_state.get_object_state("u_7_forger", data_dir)["pid"] |
| 256 | assert _gone(pid) |
| 257 | assert run(root, "u_7_who").result["ppid"] == parent # the fork server is unharmed |
| 258 | |
| 259 | |
| 260 | def test_a_timeout_kills_the_child_and_keeps_the_warm_parent(tmp_path, monkeypatch, mode): |
| 261 | import object_execution |
| 262 | import object_state |
| 263 | |
| 264 | data_dir, root = configure(monkeypatch, tmp_path) |
| 265 | monkeypatch.setenv(object_sandbox.TIMEOUT_ENV, "1") |
| 266 | _stage(root, "spin", "while True: pass") |
| 267 | write_object(root, "u_7_who", WHO) |
| 268 | parent = _warm(root, "u_7_who", "7") |
| 269 | result = run(root, "u_7_spin") |
| 270 | assert result.error.type == object_execution.TIMEOUT_ERROR_TYPE |
| 271 | assert _gone(object_state.get_object_state("u_7_spin", data_dir)["pid"]) |
| 272 | after = run(root, "u_7_who") |
| 273 | assert after.ok and after.result["ppid"] == parent |
| 274 | |
| 275 | |
| 276 | def test_a_protocol_violation_kills_the_child_not_the_warm_parent(tmp_path, monkeypatch, mode): |
| 277 | import object_state |
| 278 | |
| 279 | data_dir, root = configure(monkeypatch, tmp_path) |
| 280 | _stage(root, "garbage", "os.write(object.__getattribute__(_state_manager, '_channel').write_fd, b'\\xff' * 64)") |
| 281 | write_object(root, "u_7_who", WHO) |
| 282 | parent = _warm(root, "u_7_who", "7") |
| 283 | result = run(root, "u_7_garbage") |
| 284 | assert result.error.type == object_sandbox.PROTOCOL_ERROR_TYPE |
| 285 | assert _gone(object_state.get_object_state("u_7_garbage", data_dir)["pid"]) |
| 286 | assert run(root, "u_7_who").result["ppid"] == parent |
| 287 | |
| 288 | |
| 289 | def _children_of(pid): |
| 290 | import subprocess |
| 291 | |
| 292 | if sys.platform.startswith("linux"): |
| 293 | found = set() |
| 294 | for task in os.listdir(f"/proc/{pid}/task"): |
| 295 | with open(f"/proc/{pid}/task/{task}/children") as handle: |
| 296 | found.update(int(x) for x in handle.read().split()) |
| 297 | return found |
| 298 | done = subprocess.run(["pgrep", "-P", str(pid)], capture_output=True, text=True) |
| 299 | return {int(x) for x in done.stdout.split()} |
| 300 | |
| 301 | |
| 302 | def test_the_child_forked_ahead_is_replaced_when_it_dies(tmp_path, monkeypatch): |
| 303 | """The fork server keeps one child forked ahead of the next call. If it |
| 304 | is gone when the call comes, the call gets a freshly forked one.""" |
| 305 | monkeypatch.setenv(object_sandbox.ISOLATION_ENV, object_sandbox.UNSAFE_DEV) |
| 306 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 307 | write_object(root, "u_7_who", WHO) |
| 308 | parent = _warm(root, "u_7_who", "7") |
| 309 | deadline = time.monotonic() + 5 |
| 310 | while not _children_of(parent) and time.monotonic() < deadline: |
| 311 | time.sleep(0.02) |
| 312 | [standby] = _children_of(parent) |
| 313 | signal_worker(standby) |
| 314 | result = run(root, "u_7_who") |
| 315 | assert result.ok and result.result["ppid"] == parent and result.result["pid"] != standby |
| 316 | assert run(root, "u_7_who").ok |
| 317 | |
| 318 | |
| 319 | def test_a_call_handed_to_a_dying_child_runs_on_a_fresh_one(tmp_path, monkeypatch): |
| 320 | """SIGKILL is not instant: a child forked ahead can be killed and still |
| 321 | take a call's pipes into its socket buffer before it is gone. It never |
| 322 | read the request, so the call runs on a fresh child instead of failing. |
| 323 | The death is pinned to that exact point: the child is stopped, handed |
| 324 | the call, then killed before it can take it.""" |
| 325 | monkeypatch.setenv(object_sandbox.ISOLATION_ENV, object_sandbox.UNSAFE_DEV) |
| 326 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 327 | write_object(root, "u_7_who", WHO) |
| 328 | parent = _warm(root, "u_7_who", "7") |
| 329 | server = object_sandbox._FORK_SERVERS._servers["7"] |
| 330 | for _ in range(3): |
| 331 | deadline = time.monotonic() + 5 |
| 332 | while not _children_of(parent) and time.monotonic() < deadline: |
| 333 | time.sleep(0.02) |
| 334 | [standby] = _children_of(parent) |
| 335 | signal_worker(standby, signal.SIGSTOP) |
| 336 | results = [] |
| 337 | caller = threading.Thread(target=lambda: results.append(run(root, "u_7_who"))) |
| 338 | caller.start() |
| 339 | deadline = time.monotonic() + 5 |
| 340 | while server.active < 1 and time.monotonic() < deadline: # handed over: "forked" came back |
| 341 | time.sleep(0.005) |
| 342 | assert server.active == 1 |
| 343 | signal_worker(standby) |
| 344 | caller.join(10) |
| 345 | [result] = results |
| 346 | assert result.ok, result.error |
| 347 | assert result.result["ppid"] == parent and result.result["pid"] != standby |
| 348 | assert object_sandbox._FORK_SERVERS._servers["7"] is server # no fallback to a spare |
| 349 | |
| 350 | |
| 351 | def test_a_child_that_took_its_call_and_died_is_never_run_again(tmp_path, monkeypatch, mode): |
| 352 | """Only a child certain never to have read its request is replaced. One |
| 353 | that ran the call and then died is the caller's error: never a second |
| 354 | run of the same call.""" |
| 355 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 356 | write_object(root, "u_7_who", WHO) |
| 357 | _warm(root, "u_7_who", "7") |
| 358 | write_object(root, "u_7_die", "import os\ndef GET(request):\n print('ran', flush=True)\n" |
| 359 | " os.kill(os.getpid(), 9)\n") |
| 360 | calls = [] |
| 361 | real_fork = object_sandbox._ForkServer.fork |
| 362 | |
| 363 | def counting_fork(self, first=b""): |
| 364 | calls.append(first) |
| 365 | return real_fork(self, first) |
| 366 | |
| 367 | monkeypatch.setattr(object_sandbox._ForkServer, "fork", counting_fork) |
| 368 | result = run(root, "u_7_die") |
| 369 | assert not result.ok and result.error.type == "ObjectWorkerError" |
| 370 | assert len(calls) == 1 |
| 371 | |
| 372 | |
| 373 | def test_a_failing_call_finds_traceback_already_imported(tmp_path, monkeypatch, mode): |
| 374 | """The customer-safe traceback of a failing call needs ``traceback`` |
| 375 | (~9 ms to import on Python 3.14): the fork server imports it once.""" |
| 376 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 377 | write_object(root, "u_7_who", WHO) |
| 378 | _warm(root, "u_7_who", "7") |
| 379 | write_object(root, "u_7_tb", "import sys\ndef GET(r):\n raise ValueError('traceback' in sys.modules)\n") |
| 380 | result = run(root, "u_7_tb") |
| 381 | assert result.error.type == "ObjectMethodExecutionError" |
| 382 | assert "ValueError: True" in result.error.message and 'File "tb.py", line 3' in result.error.message |
| 383 | |
| 384 | |
| 385 | def test_a_large_request_still_reaches_the_child(tmp_path, monkeypatch, mode): |
| 386 | """Small run requests are written into the child's pipe before the fork |
| 387 | server answers; one larger than that head start goes the ordinary way.""" |
| 388 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 389 | write_object(root, "u_7_who", WHO) |
| 390 | parent = _warm(root, "u_7_who", "7") |
| 391 | big = "# " + "x" * (object_sandbox._PREWRITE_MAX * 3) + "\n" + WHO |
| 392 | write_object(root, "u_7_big", big) |
| 393 | for payload in ({}, {"blob": "y" * (object_sandbox._PREWRITE_MAX * 2)}): |
| 394 | result = run(root, "u_7_big", "GET", payload) |
| 395 | assert result.ok, result.error |
| 396 | assert result.result["ppid"] == parent |
| 397 | |
| 398 | |
| 399 | def test_a_failed_warm_parent_falls_back_to_a_single_use_spare(tmp_path, monkeypatch, mode): |
| 400 | """Fail closed: a fork server that stops answering is retired, the call |
| 401 | runs on today's single-use path, and that user stays there for a while.""" |
| 402 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 403 | write_object(root, "u_7_who", WHO) |
| 404 | parent = _warm(root, "u_7_who", "7") |
| 405 | object_sandbox._FORK_SERVERS._servers["7"].worker.kill() # the fork server dies |
| 406 | result = run(root, "u_7_who") |
| 407 | assert result.ok and result.result["ppid"] != parent |
| 408 | assert "7" not in object_sandbox._FORK_SERVERS._servers |
| 409 | assert object_sandbox._FORK_SERVERS._cooldown["7"] > time.monotonic() |
| 410 | time.sleep(0.3) |
| 411 | assert run(root, "u_7_who").ok |
| 412 | assert "7" not in object_sandbox._FORK_SERVERS._servers # still cooling down: no new one yet |
| 413 | |
| 414 | |
| 415 | NEW_LAUNCHER = {"ok": True, "v": 1, "sandbox_uid": 64999, "sandbox_gid": 64999, "netns": False, |
| 416 | "inet_sockets": True, "interfaces": ["lo"], "channels": ["pipes", "socket"]} |
| 417 | |
| 418 | |
| 419 | @pytest.mark.parametrize("setting, abi, mode, on, says", [ |
| 420 | # auto (the default): only where Landlock scopes signals |
| 421 | ("", 4, "landlock", False, "off: Landlock ABI 4 cannot scope signals; set DBBASIC_USER_CODE_WARM_PARENTS=on"), |
| 422 | ("auto", 5, "landlock", False, "or use a kernel with ABI >= 6"), |
| 423 | ("auto", 6, "landlock", True, "on: Landlock ABI 6 scopes signals"), |
| 424 | ("", 10, "landlock", True, "on: Landlock ABI 10 scopes signals"), |
| 425 | ("", 0, object_sandbox.UNSAFE_DEV, True, "on (unsafe-dev, no wall)"), |
| 426 | # explicit opt-in below ABI 6 says what it costs |
| 427 | ("on", 4, "landlock", True, "on by opt-in (DBBASIC_USER_CODE_WARM_PARENTS=on) although Landlock ABI 4"), |
| 428 | ("ON", 4, "landlock", True, "another user's code can kill or stop a warm parent"), |
| 429 | # off always wins; an unknown value means auto |
| 430 | ("off", 10, "landlock", False, "off (DBBASIC_USER_CODE_WARM_PARENTS=off)"), |
| 431 | ("off", 0, object_sandbox.UNSAFE_DEV, False, "off (DBBASIC_USER_CODE_WARM_PARENTS=off)"), |
| 432 | ("yes please", 4, "landlock", False, "off: Landlock ABI 4"), |
| 433 | ]) |
| 434 | def test_warm_parents_need_signal_scoping_unless_opted_in(setting, abi, mode, on, says): |
| 435 | """Below Landlock ABI 6 a child could signal another user's long-lived |
| 436 | warm parent (same sandbox uid): off by default there (stock Ubuntu 24.04, |
| 437 | kernel 6.8, is ABI 4).""" |
| 438 | decided, why = object_sandbox.warm_parent_decision(setting, 8, mode, abi, dict(NEW_LAUNCHER)) |
| 439 | assert decided is on |
| 440 | assert says in why |
| 441 | |
| 442 | |
| 443 | def test_warm_users_zero_and_an_old_launcher_still_mean_off(): |
| 444 | decide = object_sandbox.warm_parent_decision |
| 445 | assert decide("on", 0, "landlock", 10, dict(NEW_LAUNCHER)) == ( |
| 446 | False, "off (DBBASIC_USER_CODE_WARM_USERS=0): every call takes a single-use spare") |
| 447 | old = {k: v for k, v in NEW_LAUNCHER.items() if k != "channels"} |
| 448 | on, why = decide("on", 8, "landlock", 10, old) |
| 449 | assert on is False and "too old" in why |
| 450 | |
| 451 | |
| 452 | def test_status_and_banner_say_why_warm_parents_are_off_on_abi_4(monkeypatch): |
| 453 | monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False) |
| 454 | monkeypatch.delenv(object_sandbox.WARM_PARENTS_ENV, raising=False) |
| 455 | monkeypatch.setattr(object_sandbox, "launcher_info", lambda: dict(NEW_LAUNCHER)) |
| 456 | monkeypatch.setattr(object_sandbox, "landlock_abi", lambda: 4) |
| 457 | monkeypatch.setattr(object_sandbox, "protect_private_dirs", lambda: None) |
| 458 | monkeypatch.setattr(object_sandbox.os, "geteuid", lambda: 1000) |
| 459 | status = object_sandbox.isolation_status() |
| 460 | assert status["warm_parents"]["enabled"] is False |
| 461 | assert "Landlock ABI 4 cannot scope signals" in status["warm_parents"]["status"] |
| 462 | assert "warm parents off: Landlock ABI 4" in object_sandbox._verdict(status) |
| 463 | config = dict(object_sandbox._boot_config(), separated=True) |
| 464 | assert object_sandbox._FORK_SERVERS.supported(config) is False |
| 465 | assert object_sandbox._FORK_SERVERS.get("7", config) is None |
| 466 | assert object_sandbox._FORK_SERVERS._starting == set() |
| 467 | monkeypatch.setenv(object_sandbox.WARM_PARENTS_ENV, "on") |
| 468 | assert object_sandbox._FORK_SERVERS.supported(config) is True |
| 469 | assert "opt-in" in object_sandbox.isolation_status()["warm_parents"]["status"] |
| 470 | |
| 471 | |
| 472 | def test_no_warm_parents_when_turned_off_or_the_launcher_is_too_old(tmp_path, monkeypatch, mode): |
| 473 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 474 | config = object_sandbox._boot_config() |
| 475 | monkeypatch.setenv(object_sandbox.WARM_USERS_ENV, "0") |
| 476 | assert object_sandbox._FORK_SERVERS.get("7", config) is None |
| 477 | assert object_sandbox._FORK_SERVERS._starting == set() |
| 478 | assert object_sandbox.isolation_status()["warm_parents"]["status"].startswith("off") |
| 479 | monkeypatch.delenv(object_sandbox.WARM_USERS_ENV) |
| 480 | assert object_sandbox.isolation_status()["warm_parents"]["max_users"] == object_sandbox.DEFAULT_WARM_USERS |
| 481 | old = {"ok": True, "v": 1, "sandbox_uid": 64999, "sandbox_gid": 64999, "netns": False, |
| 482 | "inet_sockets": True, "interfaces": ["lo"]} # no "channels": an older launcher |
| 483 | monkeypatch.setattr(object_sandbox, "launcher_info", lambda: dict(old)) |
| 484 | assert object_sandbox._FORK_SERVERS.supported(dict(config, separated=True)) is False |
| 485 | assert object_sandbox._FORK_SERVERS.get("7", dict(config, separated=True)) is None |
| 486 | assert "too old" in object_sandbox.isolation_status()["warm_parents"]["status"] |
| 487 | |
| 488 | |
| 489 | def test_least_recently_used_warm_parent_is_retired_past_the_cap(tmp_path, monkeypatch, mode): |
| 490 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 491 | monkeypatch.setenv(object_sandbox.WARM_USERS_ENV, "2") |
| 492 | for uid in (7, 8, 9): |
| 493 | write_object(root, f"u_{uid}_who", WHO) |
| 494 | _warm(root, "u_7_who", "7") |
| 495 | _warm(root, "u_8_who", "8") |
| 496 | run(root, "u_7_who") # 8 is now the least recently used |
| 497 | _warm(root, "u_9_who", "9") |
| 498 | assert set(object_sandbox._FORK_SERVERS._servers) == {"7", "9"} |
| 499 | |
| 500 | |
| 501 | def test_concurrent_calls_of_one_user_each_get_their_own_child(tmp_path, monkeypatch, mode): |
| 502 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 503 | write_object(root, "u_7_slow", "import os, time\ndef GET(r):\n time.sleep(0.3)\n return {'pid': os.getpid(), 'ppid': os.getppid()}\n") |
| 504 | write_object(root, "u_7_who", WHO) |
| 505 | parent = _warm(root, "u_7_who", "7") |
| 506 | results = [] |
| 507 | threads = [threading.Thread(target=lambda: results.append(run(root, "u_7_slow"))) for _ in range(3)] |
| 508 | for thread in threads: |
| 509 | thread.start() |
| 510 | for thread in threads: |
| 511 | thread.join() |
| 512 | assert all(r.ok for r in results) |
| 513 | assert {r.result["ppid"] for r in results} == {parent} |
| 514 | assert len({r.result["pid"] for r in results}) == 3 |
| 515 | |
| 516 | |
| 517 | # -- the wall, inside a forked child ----------------------------------------------- |
| 518 | |
| 519 | ESCAPES = """ |
| 520 | import ctypes, os, signal, socket |
| 521 | |
| 522 | def _try(fn): |
| 523 | try: |
| 524 | fn() |
| 525 | except BaseException as exc: |
| 526 | return "denied: " + type(exc).__name__ |
| 527 | return "ALLOWED" |
| 528 | |
| 529 | def _fork(): |
| 530 | pid = os.fork() |
| 531 | if pid == 0: |
| 532 | os._exit(0) |
| 533 | |
| 534 | def _ptrace_parent(): |
| 535 | libc = ctypes.CDLL(None, use_errno=True) |
| 536 | if libc.ptrace(16, os.getppid(), None, None) != 0: # PTRACE_ATTACH |
| 537 | raise OSError(ctypes.get_errno(), "ptrace") |
| 538 | |
| 539 | def _grow(): |
| 540 | blob = bytearray(1024 * 1024 * 1024) |
| 541 | return len(blob) |
| 542 | |
| 543 | def GET(request): |
| 544 | return { |
| 545 | "fork": _try(_fork), |
| 546 | "thread": _try(lambda: __import__("threading").Thread(target=lambda: None).start()), |
| 547 | "setsid": _try(os.setsid), |
| 548 | "signal_parent": _try(lambda: os.kill(os.getppid(), 0)), |
| 549 | "ptrace_parent": _try(_ptrace_parent), |
| 550 | "parent_memory": _try(lambda: open(f"/proc/{os.getppid()}/mem", "rb").read(1)), |
| 551 | "write_tmp": _try(lambda: open("/tmp/planted-by-a-child", "w").write("x")), |
| 552 | "tcp": _try(lambda: socket.create_connection(("127.0.0.1", 9), timeout=1)), |
| 553 | "memory": _try(_grow), |
| 554 | "exec": _try(lambda: os.execv("/bin/true", ["true"])), |
| 555 | } |
| 556 | """ |
| 557 | |
| 558 | |
| 559 | @needs_wall |
| 560 | def test_a_forked_child_is_walled_like_a_single_use_worker(tmp_path, monkeypatch): |
| 561 | """Inside the fast path's child: no processes or threads (RLIMIT_NPROC=0 |
| 562 | is set in the child), no way out of the fork server's session, no |
| 563 | ptrace of or (ABI >= 6) signals to the fork server (a nested Landlock |
| 564 | domain), no files, no TCP, a clean MemoryError at the memory limit.""" |
| 565 | monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False) |
| 566 | _data_dir, root = configure(monkeypatch, tmp_path) |
| 567 | write_object(root, "u_7_escape", ESCAPES) |
| 568 | write_object(root, "u_7_who", WHO) |
| 569 | parent = _warm(root, "u_7_who", "7") |
| 570 | result = run(root, "u_7_escape") |
| 571 | assert result.ok, result.error |
| 572 | out = result.result |
| 573 | allowed = {k: v for k, v in out.items() if v == "ALLOWED" and k != "signal_parent"} |
| 574 | assert allowed == {}, f"a forked child could still: {allowed}" |
| 575 | assert out["memory"] == "denied: MemoryError" |
| 576 | if object_sandbox.landlock_abi() >= 6: |
| 577 | assert out["signal_parent"] == "denied: PermissionError" |
| 578 | assert not os.path.exists("/tmp/planted-by-a-child") |
| 579 | assert run(root, "u_7_who").result["ppid"] == parent |
| 580 | |
| 581 | |
| 582 | ORPHAN = """ |
| 583 | import ctypes, os, time |
| 584 | def GET(request): |
| 585 | ctypes.CDLL(None).prctl(1, 0, 0, 0, 0) # clear PR_SET_PDEATHSIG |
| 586 | _state_manager.set("pid", os.getpid()) |
| 587 | time.sleep(30) |
| 588 | return {} |
| 589 | """ |
| 590 | |
| 591 | |
| 592 | @needs_wall |
| 593 | def test_a_child_outliving_its_warm_parent_is_swept_by_the_launcher(tmp_path, monkeypatch): |
| 594 | """A child that cleared its parent-death signal, when its fork server is |
| 595 | killed mid-call: the launcher kills everything in the fork server's |
| 596 | session, so the child does not survive as an orphan.""" |
| 597 | import object_state |
| 598 | |
| 599 | monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False) |
| 600 | data_dir, root = configure(monkeypatch, tmp_path) |
| 601 | write_object(root, "u_7_orphan", ORPHAN) |
| 602 | write_object(root, "u_7_who", WHO) |
| 603 | _warm(root, "u_7_who", "7") |
| 604 | results = [] |
| 605 | thread = threading.Thread(target=lambda: results.append(run(root, "u_7_orphan"))) |
| 606 | thread.start() |
| 607 | deadline = time.monotonic() + 10 |
| 608 | pid = None |
| 609 | while time.monotonic() < deadline and pid is None: |
| 610 | pid = (object_state.get_object_state("u_7_orphan", data_dir) or {}).get("pid") |
| 611 | time.sleep(0.02) |
| 612 | assert pid is not None |
| 613 | object_sandbox._FORK_SERVERS._servers["7"].close() # the connection closes: the launcher sweeps |
| 614 | assert _gone(pid) |
| 615 | thread.join(10) |
| 616 | assert results and not results[0].ok |
| 617 | |
| 618 | |
| 619 | @pytest.mark.skipif(not sys.platform.startswith("linux"), reason="the fork server only calls libc on Linux") |
| 620 | def test_a_fork_server_loads_libc_before_any_rlimit_tightens(monkeypatch): |
| 621 | """The fork server calls prctl through libc (ctypes). A free-threaded |
| 622 | interpreter has already reserved more address space than the 512 MiB |
| 623 | RLIMIT_AS (about 1 GiB at start-up), so ``import ctypes`` after the limit |
| 624 | is set raises MemoryError: the fork server died before its first fork, |
| 625 | no warm parent ever came up, and every call quietly took a single-use |
| 626 | spare. Without the wall (``unsafe-dev``) the boot must load libc first, |
| 627 | as the walled boot does.""" |
| 628 | order = [] |
| 629 | monkeypatch.setattr(object_sandbox, "_syscall", lambda: order.append("libc")) |
| 630 | monkeypatch.setattr(object_sandbox, "_set_rlimits", lambda *args, **kwargs: order.append("rlimits")) |
| 631 | config = dict(object_sandbox._boot_config(), mode=object_sandbox.UNSAFE_DEV, fork_server=True) |
| 632 | object_sandbox._worker_boot(None, config) |
| 633 | assert order == ["libc", "rlimits"] |