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_schedule_sandbox.py · 8.0 KB · 199 lines
| 1 | """``_schedule`` for user objects (``u_<uid>_*``), through the sandbox proxy. |
| 2 | |
| 3 | A user object may keep itself fresh like any other, but the schedule is a |
| 4 | standing order for the daemon to run code, so it is bounded: an object may |
| 5 | schedule only itself, no faster than once a minute, and one user's objects |
| 6 | hold at most a fixed number of schedules. Each limit missing is one user |
| 7 | filling the daemon's every poll. |
| 8 | |
| 9 | As in test_object_sandbox.py, the plumbing runs everywhere under |
| 10 | ``unsafe-dev`` and the same checks run behind the real wall on Linux with |
| 11 | Landlock ABI >= 6 (skipped elsewhere; run in Linux Docker). |
| 12 | """ |
| 13 | from __future__ import annotations |
| 14 | |
| 15 | import json |
| 16 | import os |
| 17 | import textwrap |
| 18 | |
| 19 | import pytest |
| 20 | |
| 21 | import object_daemon |
| 22 | import object_sandbox |
| 23 | import object_schedule |
| 24 | import object_state |
| 25 | from python_object_runtime import PythonObjectRuntime |
| 26 | from runtime_modes import configure, run_object, write_object |
| 27 | |
| 28 | HAS_WALL = ( |
| 29 | object_sandbox.landlock_abi() >= object_sandbox.MIN_LANDLOCK_ABI |
| 30 | and hasattr(os, "geteuid") |
| 31 | and os.geteuid() != 0 |
| 32 | and object_sandbox.launcher_info() is not None |
| 33 | ) |
| 34 | WALL_REASON = ("needs Linux with Landlock ABI >= 4, a non-root user and the root sandbox launcher; " |
| 35 | "run in Linux Docker (see test_object_sandbox.py)") |
| 36 | |
| 37 | ISOLATION = [ |
| 38 | pytest.param(object_sandbox.UNSAFE_DEV, id="unsafe-dev"), |
| 39 | pytest.param("", id="walled", marks=pytest.mark.skipif(not HAS_WALL, reason=WALL_REASON)), |
| 40 | ] |
| 41 | |
| 42 | USER_TICKER = textwrap.dedent(''' |
| 43 | def tick(): |
| 44 | _state_manager.increment("ticks") |
| 45 | return {"ticks": _state_manager.get("ticks")} |
| 46 | |
| 47 | def GET(request): |
| 48 | try: |
| 49 | return {"task": _schedule(request.get("every", 60), request.get("method", "tick"))} |
| 50 | except Exception as exc: |
| 51 | return {"refused": type(exc).__name__ + ": " + str(exc)} |
| 52 | |
| 53 | def DELETE(request): |
| 54 | return {"removed": _unschedule()} |
| 55 | ''') |
| 56 | |
| 57 | # Reaches past _schedule to the raw proxy and names handle 1 -- an object |
| 58 | # it loaded -- the way a hostile object would try to schedule someone else. |
| 59 | CROSS_OBJECT = textwrap.dedent(''' |
| 60 | def GET(request): |
| 61 | _runtime.load_object("u_1_ticker") |
| 62 | channel = object.__getattribute__(_state_manager, "_channel") |
| 63 | remote = type(_state_manager).__mro__[1] |
| 64 | try: |
| 65 | remote(channel, "schedule", 1)._call("schedule", 60, "tick") |
| 66 | except Exception as exc: |
| 67 | return {"refused": type(exc).__name__ + ": " + str(exc)} |
| 68 | return {"refused": None} |
| 69 | ''') |
| 70 | |
| 71 | |
| 72 | @pytest.fixture(autouse=True) |
| 73 | def _kill_spares(): |
| 74 | yield |
| 75 | object_sandbox.shutdown() |
| 76 | |
| 77 | |
| 78 | @pytest.fixture(params=ISOLATION) |
| 79 | def isolation(request, monkeypatch): |
| 80 | if request.param: |
| 81 | monkeypatch.setenv(object_sandbox.ISOLATION_ENV, request.param) |
| 82 | else: |
| 83 | monkeypatch.delenv(object_sandbox.ISOLATION_ENV, raising=False) |
| 84 | return request.param |
| 85 | |
| 86 | |
| 87 | def tasks(data_dir): |
| 88 | state = object_state.get_object_state("scheduler", data_dir) |
| 89 | return {key: json.loads(value) for key, value in state.items() if key.startswith("task_")} |
| 90 | |
| 91 | |
| 92 | def test_user_object_schedules_itself(isolation, tmp_path, monkeypatch): |
| 93 | data_dir, root = configure(monkeypatch, tmp_path) |
| 94 | write_object(root, "u_1_ticker", USER_TICKER) |
| 95 | |
| 96 | result = run_object("in_process", root, "u_1_ticker", "GET", {"every": 60}) |
| 97 | |
| 98 | assert result.ok, result.error |
| 99 | assert result.result["task"]["id"] == "obj.u_1_ticker.tick" |
| 100 | assert list(tasks(data_dir)) == ["task_obj.u_1_ticker.tick"] |
| 101 | assert run_object("in_process", root, "u_1_ticker", "DELETE").result == {"removed": 1} |
| 102 | assert tasks(data_dir) == {} |
| 103 | |
| 104 | |
| 105 | def test_user_object_cannot_schedule_another_object(isolation, tmp_path, monkeypatch): |
| 106 | data_dir, root = configure(monkeypatch, tmp_path) |
| 107 | write_object(root, "u_1_ticker", USER_TICKER) |
| 108 | write_object(root, "u_1_sneaky", CROSS_OBJECT) |
| 109 | |
| 110 | result = run_object("in_process", root, "u_1_sneaky", "GET") |
| 111 | |
| 112 | assert result.ok, result.error |
| 113 | assert result.result["refused"].startswith("ScheduleError: an object may only schedule its own") |
| 114 | assert tasks(data_dir) == {} |
| 115 | |
| 116 | |
| 117 | def test_user_object_minimum_interval_and_missing_method(isolation, tmp_path, monkeypatch): |
| 118 | data_dir, root = configure(monkeypatch, tmp_path) |
| 119 | write_object(root, "u_1_ticker", USER_TICKER) |
| 120 | |
| 121 | too_fast = run_object("in_process", root, "u_1_ticker", "GET", {"every": 5}).result |
| 122 | assert "at least 60 for a user object" in too_fast["refused"] |
| 123 | missing = run_object("in_process", root, "u_1_ticker", "GET", {"method": "nope"}).result |
| 124 | assert "no function 'nope'" in missing["refused"] |
| 125 | assert tasks(data_dir) == {} |
| 126 | |
| 127 | |
| 128 | def test_per_user_cap_on_scheduled_methods(isolation, tmp_path, monkeypatch): |
| 129 | data_dir, root = configure(monkeypatch, tmp_path) |
| 130 | monkeypatch.setenv(object_schedule.USER_MAX_TASKS_ENV, "2") |
| 131 | for name in ("a", "b", "c"): |
| 132 | write_object(root, f"u_1_{name}", USER_TICKER) |
| 133 | write_object(root, "u_2_a", USER_TICKER) |
| 134 | object_schedule.schedule("tools_weather", "tick", 30, base_dir=data_dir) # system: not counted |
| 135 | |
| 136 | assert "task" in run_object("in_process", root, "u_1_a", "GET").result |
| 137 | assert "task" in run_object("in_process", root, "u_1_b", "GET").result |
| 138 | assert "task" in run_object("in_process", root, "u_1_b", "GET", {"every": 120}).result # update, not new |
| 139 | refused = run_object("in_process", root, "u_1_c", "GET").result["refused"] |
| 140 | assert "user 1 already has 2 scheduled method(s); the limit is 2" in refused |
| 141 | assert "task" in run_object("in_process", root, "u_2_a", "GET").result # another user's own budget |
| 142 | assert sorted(tasks(data_dir)) == [ |
| 143 | "task_obj.tools_weather.tick", "task_obj.u_1_a.tick", "task_obj.u_1_b.tick", "task_obj.u_2_a.tick"] |
| 144 | |
| 145 | |
| 146 | def test_daemon_runs_a_user_objects_scheduled_method_in_the_sandbox(isolation, tmp_path, monkeypatch): |
| 147 | data_dir, root = configure(monkeypatch, tmp_path) |
| 148 | (root / "triggers").mkdir() |
| 149 | (root / "triggers" / "scheduler.py").write_text("def POST(request):\n return {}\n") |
| 150 | write_object(root, "u_1_ticker", USER_TICKER) |
| 151 | run_object("in_process", root, "u_1_ticker", "GET") |
| 152 | manager = object_state.ObjectStateManager("scheduler", base_dir=data_dir) |
| 153 | row = json.loads(manager.get("task_obj.u_1_ticker.tick")) |
| 154 | manager.set("task_obj.u_1_ticker.tick", json.dumps({**row, "next_run": 1})) |
| 155 | |
| 156 | object_daemon.process_scheduler(PythonObjectRuntime()) |
| 157 | |
| 158 | assert object_state.get_object_state("u_1_ticker", data_dir)["ticks"] == 1 |
| 159 | assert tasks(data_dir)["task_obj.u_1_ticker.tick"]["run_count"] == 1 |
| 160 | |
| 161 | |
| 162 | def test_every_refusal_is_a_schedule_error_and_a_value_error(isolation, tmp_path, monkeypatch): |
| 163 | data_dir, root = configure(monkeypatch, tmp_path) |
| 164 | write_object(root, "u_1_ticker", textwrap.dedent(''' |
| 165 | def tick(): |
| 166 | return 1 |
| 167 | |
| 168 | def GET(request): |
| 169 | kind = request.get("case") |
| 170 | calls = { |
| 171 | "interval": lambda: _schedule(1, "tick"), |
| 172 | "missing": lambda: _schedule(60, "nope"), |
| 173 | "verb": lambda: _schedule(60, "GET"), |
| 174 | "badname": lambda: _unschedule("../x"), |
| 175 | } |
| 176 | try: |
| 177 | calls[kind]() |
| 178 | except ValueError as exc: |
| 179 | return {"type": type(exc).__name__, "value_error": True} |
| 180 | return {"type": None} |
| 181 | ''')) |
| 182 | for case in ("interval", "missing", "verb", "badname"): |
| 183 | result = run_object("in_process", root, "u_1_ticker", "GET", {"case": case}) |
| 184 | assert result.ok, result.error |
| 185 | assert result.result == {"type": "ScheduleError", "value_error": True}, case |
| 186 | assert tasks(data_dir) == {} |
| 187 | |
| 188 | |
| 189 | @pytest.mark.parametrize( |
| 190 | "verb", ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"] |
| 191 | ) |
| 192 | def test_http_verb_names_cannot_be_scheduled(tmp_path, monkeypatch, verb): |
| 193 | data_dir, _ = configure(monkeypatch, tmp_path) |
| 194 | with pytest.raises(object_schedule.ScheduleError, match="HTTP method name"): |
| 195 | object_schedule.schedule("tools_weather", verb, 60, base_dir=data_dir) |
| 196 | with pytest.raises(object_schedule.ScheduleError): |
| 197 | object_schedule.unschedule("tools_weather", verb, base_dir=data_dir) |
| 198 | assert tasks(data_dir) == {} |
| 199 | assert object_schedule.ScheduleError.__mro__[1] is ValueError |