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_linux_sandbox_signal_helper.py · 2.3 KB · 58 lines
| 1 | """The Linux lane's root signal helper (tests/linux_sandbox/signal_helper.py) |
| 2 | refuses everything but SIGKILL or SIGSTOP to a process of the sandbox user. |
| 3 | |
| 4 | It runs as root in the test image, so what it refuses is pinned here. That it |
| 5 | does signal a sandbox-user process is shown by the tests that use it |
| 6 | (tests/sandbox_signals.py) when scripts/test_linux_sandbox.sh runs them. |
| 7 | """ |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import json |
| 11 | import os |
| 12 | import subprocess |
| 13 | import sys |
| 14 | from pathlib import Path |
| 15 | |
| 16 | import pytest |
| 17 | |
| 18 | sys.path.insert(0, str(Path(__file__).resolve().parent / "linux_sandbox")) |
| 19 | |
| 20 | import signal_helper # noqa: E402 |
| 21 | |
| 22 | NOBODY_ELSE = 2 ** 31 - 2 # a uid no process here has |
| 23 | |
| 24 | |
| 25 | @pytest.mark.parametrize("body, why", [ |
| 26 | (b"not json", "not JSON"), |
| 27 | (b"[1, 9]", "exactly pid and signal"), |
| 28 | (b'{"pid": 5}', "exactly pid and signal"), |
| 29 | (b'{"pid": 5, "signal": "SIGKILL", "group": true}', "exactly pid and signal"), |
| 30 | (b'{"pid": "5", "signal": "SIGKILL"}', "integer above 1"), |
| 31 | (b'{"pid": true, "signal": "SIGKILL"}', "integer above 1"), |
| 32 | (b'{"pid": 1, "signal": "SIGKILL"}', "integer above 1"), |
| 33 | (b'{"pid": -1, "signal": "SIGKILL"}', "integer above 1"), |
| 34 | (b'{"pid": 0, "signal": "SIGKILL"}', "integer above 1"), |
| 35 | (b'{"pid": 5, "signal": "SIGTERM"}', "SIGKILL or SIGSTOP"), |
| 36 | (b'{"pid": 5, "signal": 9}', "SIGKILL or SIGSTOP"), |
| 37 | ]) |
| 38 | def test_a_malformed_request_is_refused(body, why): |
| 39 | reply = signal_helper.handle(body, NOBODY_ELSE) |
| 40 | assert reply.startswith("refused: ") and why in reply |
| 41 | |
| 42 | |
| 43 | @pytest.mark.skipif(not sys.platform.startswith("linux") or not hasattr(os, "pidfd_open"), |
| 44 | reason="needs Linux /proc and pidfd_open") |
| 45 | def test_a_process_that_is_not_the_sandbox_users_is_left_alone(): |
| 46 | proc = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)"]) |
| 47 | try: |
| 48 | ask = json.dumps({"pid": proc.pid, "signal": "SIGKILL"}).encode() |
| 49 | assert signal_helper.handle(ask, NOBODY_ELSE) == "refused: the process is not the sandbox user's" |
| 50 | assert proc.poll() is None |
| 51 | # Sanity: the same request is honoured when the uid is the target's. |
| 52 | assert signal_helper.handle(ask, os.getuid()) == "ok" |
| 53 | assert proc.wait(5) == -9 |
| 54 | gone = signal_helper.handle(ask, os.getuid()) |
| 55 | assert gone.startswith("refused: no such process") |
| 56 | finally: |
| 57 | proc.kill() |
| 58 | proc.wait() |