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

9 downloads

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

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

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 18 minutes ago History
test_object_sandbox.py · 37.4 KB · 922 lines
1"""User-namespace objects run isolated (object_sandbox).
2
3Two layers are tested separately because only one of them exists everywhere:
4
5- The **wall** (a separate OS user started by the root launcher, Landlock,
6 rlimits, scrubbed env) exists only on Linux with Landlock ABI >= 4 and the
7 launcher running. Those tests skip elsewhere with the reason, and run for
8 real in Linux Docker (tests/test_object_sandbox_launcher.py says how).
9- The **plumbing** (routing, proxies, protocol checks, fail-closed refusal)
10 is the same code with or without the wall, so it runs everywhere, under
11 ``unsafe-dev`` where there is no Landlock.
12
13Why each matters: a probe that succeeds is a user reading the admin token or
14another user's data; a helper that breaks is every askrobots object failing
15on migration; a protocol check that is missing is a worker that can make
16the server do work it never asked for.
17"""
18from __future__ import annotations
19
20import asyncio
21import json
22import os
23import sys
24import textwrap
25import time
26
27import pytest
28
29import object_execution
30import object_sandbox
31import object_server
32import object_worker_pool
33from object_execution import ObjectExecutionRequest
34from python_object_runtime import ObjectLoadError, PythonObject, PythonObjectRuntime
35from runtime_modes import MODES, configure, run_object, write_object
36
37HAS_WALL = (
38 object_sandbox.landlock_abi() >= object_sandbox.MIN_LANDLOCK_ABI
39 and hasattr(os, "geteuid")
40 and os.geteuid() != 0
41 and object_sandbox.launcher_info() is not None
42)
43needs_wall = pytest.mark.skipif(
44 not HAS_WALL,
45 reason=(
46 "needs Linux with Landlock ABI >= 4, a non-root user and the root sandbox launcher "
47 "(object_sandbox_launcher.py); macOS has no wall to test. Run in Linux Docker "
48 "(see the module docstring)."
49 ),
50)
51
52
53@pytest.fixture(autouse=True)
54def _kill_spares():
55 yield
56 object_sandbox.shutdown()
57
58
59@pytest.fixture
60def walled(monkeypatch):
61 monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False)
62
63
64@pytest.fixture
65def unsafe_dev(monkeypatch):
66 monkeypatch.setenv(object_sandbox.ISOLATION_ENV, object_sandbox.UNSAFE_DEV)
67
68
69def run(root, object_id, method="GET", payload=None):
70 return run_object("in_process", root, object_id, method, payload)
71
72
73PROBE = '''
74import os, socket, subprocess
75
76def _try(fn):
77 try:
78 fn()
79 except BaseException as exc:
80 return "denied: " + type(exc).__name__
81 return "ALLOWED"
82
83def _connect():
84 s = socket.socket()
85 s.settimeout(2)
86 s.connect(("127.0.0.1", PORT))
87
88def _udp():
89 socket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(b"x", ("127.0.0.1", PORT))
90
91def _fork():
92 pid = os.fork()
93 if pid == 0:
94 os._exit(0)
95
96def GET(request):
97 probes = {
98 "env_secret": lambda: os.environ["DBBASIC_ADMIN_TOKEN"],
99 "env_data_dir": lambda: os.environ["DBBASIC_DATA_DIR"],
100 "etc_passwd": lambda: open("/etc/passwd").read(),
101 "list_data_dir": lambda: os.listdir(DATA_DIR),
102 "other_state": lambda: open(OTHER_STATE).read(),
103 "other_source": lambda: open(OTHER_SOURCE).read(),
104 "own_source": lambda: open(__file__).read(),
105 "server_code": lambda: open(SERVER_CODE).read(),
106 "write_file": lambda: open(os.path.join(DATA_DIR, "planted.txt"), "w").write("x"),
107 "write_tmp": lambda: open("/tmp/sandbox-planted.txt", "w").write("x"),
108 "subprocess": lambda: subprocess.run(["id"], capture_output=True),
109 "os_system": lambda: os.system("id") == 0 or (_ for _ in ()).throw(OSError("failed")),
110 "tcp_connect": _connect,
111 "fork": _fork,
112 "signal_parent": lambda: os.kill(os.getppid(), 0),
113 "signal_server": lambda: os.kill(SERVER_PID, 0),
114 }
115 out = {name: _try(fn) for name, fn in probes.items()}
116 out["udp"] = _try(_udp)
117 out["count"] = _state_manager.increment("count")
118 _files.put("note.txt", b"hello")
119 out["file"] = _files.get("note.txt").decode()
120 out["files"] = [f["name"] for f in _files.list()]
121 out["log"] = _logger.info("probe ran", step=1)["level"]
122 out["own"] = _runtime.load_object("u_7_helper").execute("GET", {})
123 out["system"] = _runtime.load_object("tools_whoami").execute("GET", {"_identity": {"roles": ["admin"]}})
124 try:
125 _runtime.load_object("u_8_secret")
126 out["other_user"] = "ALLOWED"
127 except PermissionError as exc:
128 out["other_user"] = "denied: " + type(exc).__name__
129 return out
130'''
131
132HELPER = "def GET(request):\n return {'helper': True}\n"
133WHOAMI = "USER_CALLABLE = True\ndef GET(request):\n return {'identity': request.get('_identity')}\n"
134
135
136def _stage_probe(tmp_path, monkeypatch, root, data_dir):
137 import socket
138
139 listener = socket.socket()
140 listener.bind(("127.0.0.1", 0))
141 listener.listen(1)
142 port = listener.getsockname()[1]
143 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", "unit-test-only-admin-token")
144 write_object(root, "u_7_helper", HELPER)
145 write_object(root, "tools_whoami", WHOAMI)
146 other = write_object(root, "u_8_secret", "def GET(request):\n return {'secret': 1}\n")
147 other_state = data_dir / "state" / "u_8_secret" / "state.tsv"
148 other_state.parent.mkdir(parents=True)
149 other_state.write_text("secret\t42\t0\n")
150 source = PROBE
151 for name, value in {
152 "PORT": port,
153 "DATA_DIR": str(data_dir),
154 "OTHER_STATE": str(other_state),
155 "OTHER_SOURCE": str(other),
156 "SERVER_CODE": object_server.__file__,
157 "SERVER_PID": os.getpid(),
158 }.items():
159 source = source.replace(name, repr(value))
160 write_object(root, "u_7_probe", source)
161 return listener
162
163
164EXPECTED_SHAPE = {
165 "object_id", "method", "path", "ok", "result", "error", "started_at",
166 "finished_at", "duration_ms", "correlation_id",
167}
168
169
170@needs_wall
171@pytest.mark.parametrize("mode", MODES)
172def test_probe_user_object_is_refused_everything_but_its_helpers(tmp_path, monkeypatch, walled, mode):
173 """Every escape the askrobots probe used fails, in every execution mode,
174 while the object's own helpers keep working and the result keeps its shape."""
175 data_dir, root = configure(monkeypatch, tmp_path)
176 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
177 listener = _stage_probe(tmp_path, monkeypatch, root, data_dir)
178 try:
179 result = run_object(mode, root, "u_7_probe", payload={"_identity": {"user_id": 7, "roles": []}})
180 finally:
181 listener.close()
182 assert result.ok, result.error
183 assert set(result.to_dict()) == EXPECTED_SHAPE
184 out = result.result
185 probes = [k for k in out if k not in ("count", "file", "files", "log", "own", "system", "other_user", "udp")]
186 allowed = {k: out[k] for k in probes if not out[k].startswith("denied")}
187 assert allowed == {}, f"sandbox let these through: {allowed}"
188 assert out["count"] == 1
189 assert out["file"] == "hello" and out["files"] == ["note.txt"]
190 assert out["log"] == "INFO"
191 assert out["own"] == {"helper": True}
192 # The system object saw the request's identity, not the one the user code wrote.
193 assert out["system"] == {"identity": {"user_id": 7, "roles": []}}
194 assert out["other_user"] == "denied: CompositionDeniedError"
195 assert not (data_dir / "planted.txt").exists()
196 assert not os.path.exists("/tmp/sandbox-planted.txt")
197 assert (data_dir / "state" / "u_8_secret" / "state.tsv").read_text() == "secret\t42\t0\n"
198
199
200@needs_wall
201def test_udp_is_refused_when_the_kernel_mediates_it(tmp_path, monkeypatch, walled):
202 """UDP is outside Landlock until the kernel adds UDP rights; where it has
203 them they are handled (denied). Documented as a residual risk otherwise."""
204 abi = object_sandbox.landlock_abi()
205 _fs, net, _scoped = object_sandbox._supported_rights(abi)
206 if net <= (object_sandbox.NET_BIND_TCP | object_sandbox.NET_CONNECT_TCP):
207 pytest.skip("this kernel's Landlock does not mediate UDP")
208 data_dir, root = configure(monkeypatch, tmp_path)
209 listener = _stage_probe(tmp_path, monkeypatch, root, data_dir)
210 try:
211 result = run(root, "u_7_probe")
212 finally:
213 listener.close()
214 assert result.result["udp"].startswith("denied")
215
216
217@needs_wall
218def test_the_wall_handles_every_right_the_kernel_offers(walled):
219 """Rights are discovered from the kernel, so a newer kernel's new right
220 is denied too; execute, TCP and both scopes are always among them."""
221 abi = object_sandbox.landlock_abi()
222 fs, net, scoped = object_sandbox._supported_rights(abi)
223 assert fs & object_sandbox.FS_EXECUTE
224 assert fs >= (1 << 13) - 1 # every ABI 1 right
225 assert net & object_sandbox.NET_CONNECT_TCP and net & object_sandbox.NET_BIND_TCP
226 assert scoped & object_sandbox.SCOPE_SIGNAL and scoped & object_sandbox.SCOPE_ABSTRACT_UNIX_SOCKET
227
228
229@needs_wall
230def test_read_grants_never_include_the_repo_or_data_dirs(tmp_path, monkeypatch):
231 data_dir, root = configure(monkeypatch, tmp_path)
232 repo = os.path.dirname(os.path.realpath(object_sandbox.__file__))
233 deny = [repo, str(data_dir), str(root)]
234 for path in object_sandbox._python_read_paths(deny):
235 assert not object_sandbox._overlaps(path, deny), path
236
237
238# -- plumbing: runs everywhere ------------------------------------------------
239
240
241IDENTITY_PROBE = """
242import os
243def GET(request):
244 return {"pid": os.getpid(), "env": sorted(os.environ), "identity": request.get("_identity")}
245"""
246
247
248@pytest.mark.parametrize("mode", MODES)
249def test_user_objects_never_run_in_the_server_process_pool_or_spawn_child(tmp_path, monkeypatch, unsafe_dev, mode):
250 data_dir, root = configure(monkeypatch, tmp_path)
251 monkeypatch.setenv("DBBASIC_ADMIN_TOKEN", "unit-test-only-admin-token")
252 write_object(root, "u_7_who", IDENTITY_PROBE)
253
254 async def no_admin_worker(self):
255 raise AssertionError("a user object reached the admin warm pool")
256
257 monkeypatch.setattr(object_worker_pool.WorkerPool, "_spawn_worker", no_admin_worker)
258 result = run_object(mode, root, "u_7_who")
259 assert result.ok, result.error
260 assert result.result["pid"] != os.getpid()
261 assert not [k for k in result.result["env"] if k.startswith("DBBASIC")]
262 assert set(result.to_dict()) == EXPECTED_SHAPE
263
264
265def test_each_request_gets_a_fresh_worker(tmp_path, monkeypatch, unsafe_dev):
266 """A worker that ran user code is never reused, not even by the same user."""
267 _data_dir, root = configure(monkeypatch, tmp_path)
268 write_object(root, "u_7_who", IDENTITY_PROBE)
269 pids = {run(root, "u_7_who").result["pid"] for _ in range(3)}
270 assert len(pids) == 3
271
272
273def test_python_object_refuses_user_code_in_process(tmp_path, monkeypatch):
274 """The last line: any call site that forgets to route a user object
275 to the sandbox fails closed instead of running it here."""
276 _data_dir, root = configure(monkeypatch, tmp_path)
277 path = write_object(root, "u_7_who", IDENTITY_PROBE)
278 with pytest.raises(ObjectLoadError, match="sandbox"):
279 PythonObject(path, "u_7_who")
280 with pytest.raises(ObjectLoadError):
281 PythonObjectRuntime().load_object(path, "renamed") # path under users/7/ counts too
282
283
284def test_result_shape_matches_in_process_for_errors(tmp_path, monkeypatch, unsafe_dev):
285 _data_dir, root = configure(monkeypatch, tmp_path)
286 write_object(root, "u_7_bad", "def GET(request):\n raise ValueError('nope')\n")
287 write_object(root, "u_7_broken", "def GET(request:\n")
288 write_object(root, "tools_bad", "def GET(request):\n raise ValueError('nope')\n")
289 user = run(root, "u_7_bad")
290 system = run(root, "tools_bad")
291 assert user.error.type == system.error.type == "ObjectMethodExecutionError"
292 assert "ValueError: nope" in user.error.message
293 assert run(root, "u_7_bad", method="POST").error.type == "MethodNotSupportedError"
294 assert run(root, "u_7_broken").error.type == "ObjectLoadError"
295 assert run(root, "u_7_missing").error.type == "ObjectNotFoundError"
296
297
298def test_bytes_results_and_payloads_cross_the_pipe(tmp_path, monkeypatch, unsafe_dev):
299 _data_dir, root = configure(monkeypatch, tmp_path)
300 write_object(root, "u_7_echo", "def POST(request):\n return {'got': request['b'], 'raw': b'\\x00\\xff'}\n")
301 result = run(root, "u_7_echo", method="POST", payload={"b": [1, "x", None]})
302 assert result.result == {"got": [1, "x", None], "raw": b"\x00\xff"}
303
304
305# -- fail closed ----------------------------------------------------------------
306
307
308FAKE_LAUNCHER = {"ok": True, "v": 1, "sandbox_uid": 64999, "sandbox_gid": 64999, "netns": False,
309 "inet_sockets": True, "interfaces": ["eth0", "lo"]}
310
311
312def test_user_objects_are_refused_without_landlock_unless_unsafe_dev(tmp_path, monkeypatch, capsys):
313 _data_dir, root = configure(monkeypatch, tmp_path)
314 write_object(root, "u_7_who", IDENTITY_PROBE)
315 write_object(root, "tools_ok", "def GET(request):\n return {'ok': 1}\n")
316 monkeypatch.setattr(object_sandbox, "launcher_info", lambda: dict(FAKE_LAUNCHER))
317 monkeypatch.setattr(object_sandbox, "landlock_abi", lambda: 0)
318 monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False)
319
320 refused = run(root, "u_7_who")
321 assert not refused.ok
322 assert refused.error.type == object_sandbox.ISOLATION_ERROR_TYPE
323 assert "Landlock" in refused.error.message
324 assert "user objects refused" in capsys.readouterr().err
325 assert run(root, "tools_ok").ok # system objects are unaffected
326
327 monkeypatch.setattr(object_sandbox, "landlock_abi", lambda: 3) # no TCP control
328 assert run(root, "u_7_who").error.type == object_sandbox.ISOLATION_ERROR_TYPE
329
330 monkeypatch.setenv(object_sandbox.ISOLATION_ENV, object_sandbox.UNSAFE_DEV)
331 monkeypatch.setattr(object_sandbox, "launcher_info", lambda: None)
332 assert run(root, "u_7_who").ok
333
334
335def test_user_objects_are_refused_without_the_launcher_even_on_a_new_kernel(tmp_path, monkeypatch):
336 """Landlock cannot stop chmod/utime/stat on files the worker's uid owns,
337 so without uid separation user code is refused, whatever the ABI."""
338 _data_dir, root = configure(monkeypatch, tmp_path)
339 write_object(root, "u_7_who", IDENTITY_PROBE)
340 monkeypatch.setattr(object_sandbox, "launcher_info", lambda: None)
341 monkeypatch.setattr(object_sandbox, "landlock_abi", lambda: 10)
342 monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False)
343 refused = run(root, "u_7_who")
344 assert refused.error.type == object_sandbox.ISOLATION_ERROR_TYPE
345 assert "launcher" in refused.error.message
346 status = object_sandbox.isolation_status()
347 assert status["available"] is False and status["uid_separation"] is False
348
349
350def test_with_the_launcher_landlock_abi_4_is_enough(tmp_path, monkeypatch):
351 """ABI 4 (TCP control, Ubuntu 24.04's 6.8) qualifies once workers run as
352 another uid: signals to the server are refused by ordinary permissions."""
353 configure(monkeypatch, tmp_path)
354 monkeypatch.setattr(object_sandbox, "launcher_info", lambda: dict(FAKE_LAUNCHER))
355 monkeypatch.setattr(object_sandbox, "landlock_abi", lambda: 4)
356 monkeypatch.setattr(object_sandbox, "_landlock_mediates_udp", lambda abi: False)
357 monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False)
358 if hasattr(os, "geteuid") and os.geteuid() == 0:
359 pytest.skip("the server-side check refuses root")
360 status = object_sandbox.isolation_status()
361 assert status["available"] is True, status
362 assert status["uid_separation"] is True and status["sandbox_uid"] == 64999
363 assert status["network_namespace"] is False
364 assert status["udp"].startswith("NOT controlled")
365 assert object_sandbox._verdict(status).startswith("user objects run isolated")
366
367
368def test_status_reports_each_network_layer_honestly(monkeypatch):
369 monkeypatch.setattr(object_sandbox, "_landlock_mediates_udp", lambda abi: False)
370 udp = object_sandbox._udp_status
371 assert udp(4, None).startswith("NOT controlled")
372 assert udp(4, dict(FAKE_LAUNCHER, netns=True)).startswith("blocked: each worker")
373 assert udp(4, dict(FAKE_LAUNCHER, inet_sockets=False)).startswith("blocked: IP sockets")
374 assert udp(4, dict(FAKE_LAUNCHER, interfaces=["lo"])).startswith("loopback only")
375
376
377def test_private_dirs_are_closed_to_other_users_before_user_code_runs(tmp_path, monkeypatch):
378 """The data and objects directories are what a sandbox uid must not
379 traverse: an open one is closed (0700) when it is ours, and user code is
380 refused when it is open and not ours to fix."""
381 data_dir, root = configure(monkeypatch, tmp_path)
382 monkeypatch.setenv("DBBASIC_DATA_DIR", str(data_dir))
383 data_dir.mkdir(exist_ok=True)
384 os.chmod(data_dir, 0o755)
385 os.chmod(root, 0o755)
386 assert object_sandbox.protect_private_dirs() is None
387 assert os.stat(data_dir).st_mode & 0o777 == 0o700
388 assert os.stat(root).st_mode & 0o777 == 0o700
389
390 os.chmod(root, 0o755)
391 real_stat = os.stat
392 monkeypatch.setattr(object_sandbox.os, "getuid", lambda: real_stat(root).st_uid + 1)
393 problem = object_sandbox.protect_private_dirs()
394 assert problem and str(root) in problem and "open to other users" in problem
395
396
397def test_refusal_is_a_503_over_http(tmp_path, monkeypatch):
398 from test_object_server import auth_headers, enable_admin_token, request
399
400 _data_dir, root = configure(monkeypatch, tmp_path)
401 write_object(root, "u_7_who", IDENTITY_PROBE)
402 enable_admin_token(monkeypatch)
403 monkeypatch.setattr(object_sandbox, "landlock_abi", lambda: 0)
404 monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False)
405 status, _headers, body = request("/objects/u_7_who", headers=auth_headers())
406 assert status == 503
407 assert "cannot run on this server" in body["error"]
408
409
410def test_user_object_over_http_matches_the_system_object_response(tmp_path, monkeypatch, unsafe_dev):
411 from test_object_server import auth_headers, enable_admin_token, request
412
413 _data_dir, root = configure(monkeypatch, tmp_path)
414 source = "def GET(request):\n return {'hello': 'world', 'n': [1, 2]}\n"
415 write_object(root, "u_7_hello", source)
416 write_object(root, "tools_hello", source)
417 enable_admin_token(monkeypatch)
418 user = request("/objects/u_7_hello", headers=auth_headers())
419 system = request("/objects/tools_hello", headers=auth_headers())
420 assert user[0] == system[0] == 200
421 assert user[2] == system[2]
422
423
424# -- protocol: a misbehaving worker is killed -------------------------------------
425
426ROGUE = """
427import os, struct
428def GET(request):
429 _state_manager.set("pid", os.getpid())
430 ch = object.__getattribute__(_state_manager, "_channel")
431 ACTION
432 return {"survived": True}
433"""
434
435
436def _rogue(root, name, action):
437 write_object(root, f"u_7_{name}", ROGUE.replace("ACTION", action))
438
439
440def _assert_killed(data_dir, object_id):
441 import object_state
442
443 pid = object_state.get_object_state(object_id, data_dir)["pid"]
444 deadline = time.monotonic() + 5
445 while time.monotonic() < deadline:
446 try:
447 os.kill(pid, 0)
448 except ProcessLookupError:
449 return
450 except PermissionError:
451 pass # a launcher-started worker runs as another uid: alive until reaped
452 time.sleep(0.05)
453 pytest.fail(f"worker {pid} still alive")
454
455
456@pytest.mark.parametrize(
457 "name, action",
458 [
459 ("oversize", "os.write(ch.write_fd, struct.pack('>I', 1 << 30))"),
460 ("garbage", "os.write(ch.write_fd, struct.pack('>I', 5) + b'notjs')"),
461 ("deepjson", "body = b'[' * 100000 + b']' * 100000; os.write(ch.write_fd, struct.pack('>I', len(body)) + body)"),
462 ("notobject", "body = b'[1, 2]'; os.write(ch.write_fd, struct.pack('>I', len(body)) + body)"),
463 ("badop", "_state_manager._call('__init__')"),
464 ("badhelper", "type(_state_manager)(ch, 'os', 0)._call('system', 'id')"),
465 ("badhandle", "type(_state_manager)(ch, 'state', 99)._call('get_all')"),
466 ("fakeresult", "ch.send({'t': 'result', 'ok': False, 'error': {'type': 'x y', 'message': 1}})"),
467 ("unexpected", "ch.send({'t': 'ready'})"),
468 ],
469)
470def test_malformed_or_oversize_messages_kill_the_worker(tmp_path, monkeypatch, unsafe_dev, name, action):
471 data_dir, root = configure(monkeypatch, tmp_path)
472 _rogue(root, name, action)
473 result = run(root, f"u_7_{name}")
474 assert not result.ok
475 assert result.error.type == object_sandbox.PROTOCOL_ERROR_TYPE, result.error
476 _assert_killed(data_dir, f"u_7_{name}")
477
478
479def test_helper_call_budget_kills_a_chatty_worker(tmp_path, monkeypatch, unsafe_dev):
480 data_dir, root = configure(monkeypatch, tmp_path)
481 monkeypatch.setenv(object_sandbox.MAX_HELPER_CALLS_ENV, "5")
482 _rogue(root, "chatty", "[_state_manager.get('x') for _ in range(50)]")
483 result = run(root, "u_7_chatty")
484 assert result.error.type == object_sandbox.PROTOCOL_ERROR_TYPE
485 _assert_killed(data_dir, "u_7_chatty")
486
487
488def test_message_size_limit_is_enforced_on_results(tmp_path, monkeypatch, unsafe_dev):
489 _data_dir, root = configure(monkeypatch, tmp_path)
490 monkeypatch.setenv(object_sandbox.MAX_MESSAGE_BYTES_ENV, "4096")
491 write_object(root, "u_7_big", "def GET(request):\n return {'x': 'a' * 10000}\n")
492 assert run(root, "u_7_big").error.type == object_sandbox.PROTOCOL_ERROR_TYPE
493
494
495def test_timeout_kills_a_spinning_worker(tmp_path, monkeypatch, unsafe_dev):
496 data_dir, root = configure(monkeypatch, tmp_path)
497 monkeypatch.setenv(object_sandbox.TIMEOUT_ENV, "1")
498 _rogue(root, "spin", "while True: pass")
499 started = time.monotonic()
500 result = run(root, "u_7_spin")
501 assert result.error.type == object_execution.TIMEOUT_ERROR_TYPE
502 assert time.monotonic() - started < 10
503 _assert_killed(data_dir, "u_7_spin")
504
505
506# -- cross-user and cross-object helper access ------------------------------------
507
508CROSS = """
509def _catch(cls, fn):
510 try:
511 fn()
512 except cls:
513 return
514 raise AssertionError("not caught")
515
516def GET(request):
517 out = {}
518 own = _runtime.load_object("u_7_helper")
519 own.state_manager.set("touched", 1)
520 out["own_state"] = own.state_manager.get_all()
521 system = _runtime.load_object("tools_whoami")
522 for name, fn in {
523 "system_state": lambda: system.state_manager.set("x", 1),
524 "system_files": lambda: system.file_manager.put("x", b"x"),
525 "system_logs": lambda: system.logger.get_logs(),
526 "other_user": lambda: _runtime.load_object("u_8_secret"),
527 "other_user_padded": lambda: _runtime.load_object("u_08_secret"),
528 "missing_other_user": lambda: _runtime.load_object("u_8_nothere"),
529 "path": lambda: _runtime.load_object("../users/8/secret"),
530 "files_dir": lambda: _files.files_dir,
531 "traversal": lambda: _files.get("../../state/u_8_secret/state.tsv"),
532 "traversal_is_value_error": lambda: _catch(ValueError, lambda: _files.get("../x")),
533 "after_set": lambda: _state_manager.update({"a": 1}, after_set=lambda s: []),
534 }.items():
535 try:
536 fn()
537 out[name] = "ALLOWED"
538 except Exception as exc:
539 out[name] = type(exc).__name__
540 return out
541"""
542
543
544def test_cross_user_and_system_helper_access_is_refused(tmp_path, monkeypatch, unsafe_dev):
545 data_dir, root = configure(monkeypatch, tmp_path)
546 write_object(root, "u_7_helper", HELPER)
547 write_object(root, "u_8_secret", "def GET(request):\n return {}\n")
548 write_object(root, "tools_whoami", WHOAMI)
549 write_object(root, "u_7_cross", CROSS)
550 result = run(root, "u_7_cross")
551 assert result.ok, result.error
552 out = result.result
553 assert out.pop("own_state") == {"touched": 1}
554 assert out == {
555 "system_state": "PermissionError",
556 "system_files": "PermissionError",
557 "system_logs": "PermissionError",
558 "other_user": "CompositionDeniedError",
559 "other_user_padded": "CompositionDeniedError",
560 "missing_other_user": "CompositionDeniedError",
561 "path": "CompositionNotFoundError",
562 "files_dir": "PermissionError",
563 "traversal": "InvalidObjectFilenameError",
564 "traversal_is_value_error": "ALLOWED",
565 "after_set": "TypeError",
566 }
567 assert not (data_dir / "state" / "tools_whoami").exists()
568
569
570def test_a_system_object_loading_a_user_object_still_sandboxes_it(tmp_path, monkeypatch, unsafe_dev):
571 _data_dir, root = configure(monkeypatch, tmp_path)
572 write_object(root, "u_7_who", IDENTITY_PROBE)
573 write_object(root, "tools_caller", "def GET(request):\n return _runtime.load_object('u_7_who').execute('GET', {})\n")
574 result = run(root, "tools_caller")
575 assert result.ok, result.error
576 assert result.result["pid"] != os.getpid()
577
578
579def test_nested_user_calls_still_hit_the_depth_limit(tmp_path, monkeypatch, unsafe_dev):
580 _data_dir, root = configure(monkeypatch, tmp_path)
581 write_object(root, "u_7_loop", "def GET(request):\n return _runtime.load_object('u_7_loop').execute('GET', {})\n")
582 result = run(root, "u_7_loop")
583 assert not result.ok
584 assert "CompositionDepthError" in result.error.message or result.error.type == "CompositionDepthError"
585
586
587def test_admin_capabilities_report_whether_user_code_can_run(tmp_path, monkeypatch):
588 """An operator reads one field to learn why user objects return 503."""
589 from test_object_server import auth_headers, enable_admin_token, request
590
591 configure(monkeypatch, tmp_path)
592 enable_admin_token(monkeypatch)
593 monkeypatch.setattr(object_sandbox, "launcher_info", lambda: dict(FAKE_LAUNCHER))
594 monkeypatch.setattr(object_sandbox, "landlock_abi", lambda: 0)
595 monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False)
596 status, _headers, body = request("/admin/status", headers=auth_headers())
597 assert status == 200
598 report = body["capabilities"]["user_code_isolation"]
599 assert report["available"] is False and "Landlock" in report["reason"]
600 assert report["uid_separation"] is True and "udp" in report
601
602
603# --- what a customer sees when their own code fails --------------------------
604
605_BOOM_SOURCE = (
606 "def helper(x):\n"
607 " return 1 / x\n"
608 "\n"
609 "def GET(request):\n"
610 " return helper(0)\n"
611)
612
613
614def test_user_object_error_shows_only_their_own_frames(monkeypatch, tmp_path):
615 from runtime_modes import configure, run_object, write_object
616
617 _, root = configure(monkeypatch, tmp_path)
618 path = write_object(root, "u_1_boom", _BOOM_SOURCE)
619 result = run_object("spawn", root, "u_1_boom")
620 assert result.ok is False
621 message = result.error.message
622 assert "ZeroDivisionError: division by zero" in message
623 # their own frames, with their own line numbers, by file name only
624 assert 'File "boom.py", line 5, in GET' in message
625 assert 'File "boom.py", line 2, in helper' in message
626 assert "return 1 / x" in message
627 # nothing of the server: no paths, no server modules
628 for leak in (str(tmp_path), str(path.parent), "object_sandbox", "python_object_runtime", ".py\", line", "site-packages"):
629 if leak == ".py\", line":
630 continue
631 assert leak not in message, leak
632 assert str(root) not in result.error.traceback
633 assert "object_sandbox" not in result.error.traceback
634
635
636def test_user_object_syntax_error_does_not_leak_the_path(monkeypatch, tmp_path):
637 from runtime_modes import configure, run_object, write_object
638
639 _, root = configure(monkeypatch, tmp_path)
640 write_object(root, "u_1_bad", "def GET(request:\n return 1\n")
641 result = run_object("spawn", root, "u_1_bad")
642 assert result.ok is False
643 assert "SyntaxError" in result.error.message
644 assert str(tmp_path) not in result.error.message
645 assert "object_sandbox" not in result.error.message
646
647
648def test_system_object_error_keeps_full_traceback(monkeypatch, tmp_path):
649 from runtime_modes import configure, run_object, write_object
650
651 _, root = configure(monkeypatch, tmp_path)
652 write_object(root, "system_boom", _BOOM_SOURCE)
653 result = run_object("in_process", root, "system_boom")
654 assert result.ok is False
655 assert "python_object_runtime" in result.error.message
656 assert "system/boom.py" in result.error.message
657
658
659# -- the worker leaves as soon as it has answered ----------------------------------
660
661LATE_WRITER = """
662import atexit, os, time
663
664def _late():
665 fd = object.__getattribute__(_state_manager, "_channel").write_fd
666 os.write(fd, b"LATE")
667 time.sleep(5)
668
669def GET(request):
670 atexit.register(_late)
671 return {"answered": True}
672"""
673
674
675def _raw_worker():
676 import subprocess
677
678 return subprocess.Popen(
679 [sys.executable, "-I", "-B", object_sandbox.__file__, "--worker"],
680 stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
681 env=object_sandbox.scrubbed_env(), cwd="/", bufsize=0,
682 )
683
684
685def _read_frame(stream):
686 header = stream.read(4)
687 (length,) = object_sandbox._LENGTH.unpack(header)
688 return json.loads(stream.read(length))
689
690
691class _FakeWorker:
692 """Stands in for a launched spare: construction can be held up."""
693
694 gate = None
695 made: list = []
696 started: list = [] # one entry per construction begun, including any held at the gate
697
698 def __init__(self, config, launched=False):
699 _FakeWorker.started.append(None)
700 if _FakeWorker.gate is not None:
701 assert _FakeWorker.gate.wait(10)
702 self.config_key = json.dumps(config, sort_keys=True)
703 self.killed = False
704 _FakeWorker.made.append(self)
705
706 def alive(self):
707 return not self.killed
708
709 def kill(self):
710 self.killed = True
711
712
713def _fake_pool(monkeypatch, size):
714 import threading
715
716 monkeypatch.setenv(object_sandbox.POOL_SIZE_ENV, str(size))
717 monkeypatch.setattr(object_sandbox, "_Worker", _FakeWorker)
718 monkeypatch.setattr(object_sandbox, "_boot_config", lambda: {"t": "boot", "separated": True})
719 _FakeWorker.made = []
720 _FakeWorker.started = []
721 _FakeWorker.gate = threading.Event()
722 return object_sandbox._SandboxPool()
723
724
725def _wait_for(predicate, seconds=5.0):
726 deadline = time.monotonic() + seconds
727 while time.monotonic() < deadline:
728 if predicate():
729 return True
730 time.sleep(0.01)
731 return False
732
733
734def test_spares_refill_off_the_request_path(monkeypatch):
735 """Taking a spare never waits for its replacement to start (a launcher
736 round trip): the refill happens on a background thread."""
737 pool = _fake_pool(monkeypatch, 2)
738 _FakeWorker.gate.set()
739 first = pool.acquire() # cold: starts its own worker, then refills in the background
740 assert _wait_for(lambda: len(pool._idle) == 2)
741 _FakeWorker.gate.clear() # every further start now blocks
742 started = time.monotonic()
743 second = pool.acquire()
744 assert time.monotonic() - started < 1
745 assert second is not first and second in _FakeWorker.made
746 assert len(pool._idle) == 1
747 _FakeWorker.gate.set()
748 assert _wait_for(lambda: len(pool._idle) == 2)
749 pool.shutdown()
750
751
752def test_a_refill_in_flight_at_shutdown_leaves_no_spare_behind(monkeypatch):
753 pool = _fake_pool(monkeypatch, 1)
754 _FakeWorker.gate.set()
755 pool.acquire()
756 assert _wait_for(lambda: len(pool._idle) == 1)
757 _FakeWorker.gate.clear()
758 pool.acquire()
759 # Wait until the refill thread really is blocked starting a spare: it is a
760 # new thread, and shutting down before it first looked at the pool made it
761 # return without starting one (a GIL build usually ran it at once; a
762 # free-threaded one lets the test thread race ahead).
763 assert _wait_for(lambda: len(_FakeWorker.started) == 3)
764 pool.shutdown()
765 _FakeWorker.gate.set()
766 assert _wait_for(lambda: all(w.killed for w in _FakeWorker.made[2:]) and len(_FakeWorker.made) == 3)
767 assert pool._idle == []
768
769
770class _PausingLock:
771 """The pool's lock, except that the refill thread is held back just before
772 its ``pause_at``-th hold until the test lets it go."""
773
774 def __init__(self, pause_at):
775 import threading
776
777 self._inner = threading.Lock()
778 self._pause_at = pause_at
779 self._holds = 0
780 self.release = threading.Event()
781
782 def __enter__(self):
783 import threading
784
785 if threading.current_thread().name == "dbbasic-sandbox-refill":
786 self._holds += 1
787 if self._holds == self._pause_at:
788 self.release.wait(5)
789 self._inner.acquire()
790
791 def __exit__(self, *exc):
792 self._inner.release()
793
794
795def test_a_spare_taken_just_as_the_refill_finishes_is_still_replaced(monkeypatch):
796 """The refill thread decided it was done (the pool was full) and had not
797 yet cleared its "refilling" flag when a request took the spare: that
798 request saw a refill "still running", started none, and the pool stayed
799 empty until a later request paid for a cold start. On a free-threaded
800 build the window is hit often enough to have failed CI (the test above)."""
801 import threading
802
803 pool = _fake_pool(monkeypatch, 1)
804 _FakeWorker.gate.set()
805 pausing = _PausingLock(pause_at=4) # holds: top of the loop, append, top again (done), flag cleared
806 pool._lock = pausing
807 decided = threading.Event()
808 target = pool._target_size
809
810 def sized():
811 if threading.current_thread().name == "dbbasic-sandbox-refill" and pool._idle:
812 decided.set() # the refill thread is looking at a full pool: it stops
813 return target()
814
815 pool._target_size = sized
816 pool.acquire() # cold start; the refill thread then fills the pool and stops
817 assert decided.wait(5)
818 pool.acquire() # takes that spare, in the window before the flag is cleared
819 pausing.release.set()
820 assert _wait_for(lambda: len(pool._idle) == 1), "the spare taken was never replaced"
821 pool.shutdown()
822
823
824def _boot_and_run(source, object_id="u_7_probe", memory=512 * 1024 * 1024):
825 proc = _raw_worker()
826 try:
827 limits = {"cpu": 10, "as": memory, "nofile": 32}
828 proc.stdin.write(object_sandbox._encode({"t": "boot", "mode": object_sandbox.UNSAFE_DEV, "limits": limits}))
829 assert _read_frame(proc.stdout)["t"] == "ready"
830 proc.stdin.write(object_sandbox._encode({
831 "t": "run", "object_id": object_id, "method": "GET", "path": "probe.py",
832 "payload": {}, "source": source,
833 }))
834 return proc, _read_frame(proc.stdout)
835 except BaseException:
836 proc.kill()
837 proc.wait()
838 raise
839
840
841def test_worker_boot_does_not_import_traceback():
842 """Every worker boot used to import ``traceback`` (with ``_colorize``,
843 ~9 ms on Python 3.14) for a function only a failing object needs."""
844 proc, result = _boot_and_run(
845 "import sys\ndef GET(request):\n return sorted(m for m in ('traceback', '_colorize') if m in sys.modules)\n")
846 proc.kill()
847 proc.wait()
848 assert result["ok"] is True and result["result"] == []
849
850
851LINUX_ONLY_RLIMIT_AS = pytest.mark.skipif(
852 not sys.platform.startswith("linux"), reason="RLIMIT_AS is only set on Linux")
853
854
855@LINUX_ONLY_RLIMIT_AS
856def test_the_memory_cap_leaves_room_for_ordinary_work_and_still_stops_a_runaway():
857 """A 128 MiB cap: ordinary allocations and a walk over every object (which
858 needs libc to grow its heap) work, and a 3 GiB allocation is a clean
859 MemoryError. On a free-threaded build the interpreter has reserved ~1 GiB
860 before the cap is set, so an absolute 128 MiB cap broke the first of
861 these (see ``_address_space_limit``)."""
862 source = textwrap.dedent("""
863 import gc
864 def GET(request):
865 out = {"objects": len(gc.get_objects()) > 0, "modest": len(bytearray(32 * 1024 * 1024)) > 0}
866 try:
867 bytearray(3 * 1024 * 1024 * 1024)
868 out["runaway"] = "allocated"
869 except MemoryError:
870 out["runaway"] = "MemoryError"
871 return out
872 """)
873 proc, result = _boot_and_run(source, memory=128 * 1024 * 1024)
874 proc.kill()
875 proc.wait()
876 assert result["ok"] is True, result
877 assert result["result"] == {"objects": True, "modest": True, "runaway": "MemoryError"}
878
879
880def test_the_address_space_cap_is_absolute_except_on_a_free_threaded_build(monkeypatch):
881 cap = 512 * 1024 * 1024
882 monkeypatch.setattr(sys, "abiflags", "", raising=False)
883 assert object_sandbox._address_space_limit(cap) == cap
884 monkeypatch.setattr(sys, "abiflags", "d", raising=False) # a debug build is not free-threaded
885 assert object_sandbox._address_space_limit(cap) == cap
886
887
888@pytest.mark.skipif(not sys.platform.startswith("linux"), reason="reads /proc/self/statm")
889def test_on_a_free_threaded_build_the_cap_is_counted_on_top_of_the_interpreters_own(monkeypatch):
890 cap = 512 * 1024 * 1024
891 monkeypatch.setattr(sys, "abiflags", "t", raising=False)
892 with open("/proc/self/statm") as handle:
893 held = int(handle.read().split()[0]) * os.sysconf("SC_PAGE_SIZE")
894 limit = object_sandbox._address_space_limit(cap)
895 assert cap + held // 2 < limit < cap + held * 2 # about what the interpreter holds right now
896 monkeypatch.setattr(os, "sysconf", lambda name: (_ for _ in ()).throw(OSError("no sysconf")))
897 assert object_sandbox._address_space_limit(cap) == cap # unreadable: the absolute cap, as before
898
899
900def test_nothing_user_code_queued_runs_after_the_result():
901 """The worker exits with os._exit right after its result: an atexit
902 handler user code registered never runs, so it cannot write after the
903 answer or keep the worker busy (interpreter teardown also cost ~3 ms of
904 CPU on the core the server was waiting for)."""
905 proc = _raw_worker()
906 try:
907 limits = {"cpu": 10, "as": 512 * 1024 * 1024, "nofile": 32}
908 proc.stdin.write(object_sandbox._encode({"t": "boot", "mode": object_sandbox.UNSAFE_DEV, "limits": limits}))
909 assert _read_frame(proc.stdout)["t"] == "ready"
910 proc.stdin.write(object_sandbox._encode({
911 "t": "run", "object_id": "u_7_late", "method": "GET", "path": "late.py",
912 "payload": {}, "source": LATE_WRITER,
913 }))
914 result = _read_frame(proc.stdout)
915 assert result["ok"] is True and result["result"] == {"answered": True}
916 started = time.monotonic()
917 assert proc.wait(timeout=3) == 0
918 assert time.monotonic() - started < 2
919 assert proc.stdout.read() == b""
920 finally:
921 proc.kill()
922 proc.wait()