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_setup.py · 16.0 KB · 358 lines
| 1 | """First-owner setup of a one-click box (object_setup + /setup and the waiting gate in object_server). |
| 2 | |
| 3 | What these protect: a box on the public internet with no owner yet must not answer anything but its |
| 4 | health and its setup page; only the holder of the installer's code may become its admin; and that can |
| 5 | happen once, even when two people try at the same moment. |
| 6 | """ |
| 7 | |
| 8 | import json |
| 9 | import threading |
| 10 | import urllib.parse |
| 11 | |
| 12 | import pytest |
| 13 | |
| 14 | import object_credentials |
| 15 | import object_identity |
| 16 | import object_server |
| 17 | import object_setup |
| 18 | |
| 19 | from test_object_server import raw_request |
| 20 | |
| 21 | PASSWORD = "correct horse battery" |
| 22 | ADMIN_TOKEN = "setup-test-admin-token" |
| 23 | |
| 24 | |
| 25 | def _place_code(data_dir, code): |
| 26 | path = object_setup.code_path(data_dir) |
| 27 | path.parent.mkdir(parents=True, exist_ok=True) |
| 28 | path.write_text(object_setup.code_hash(code) + "\n", encoding="ascii") |
| 29 | return path |
| 30 | |
| 31 | |
| 32 | # ---- the module --------------------------------------------------------------- |
| 33 | |
| 34 | |
| 35 | def test_the_box_keeps_only_a_hash_of_the_code(tmp_path): |
| 36 | code = object_setup.new_code() |
| 37 | path = _place_code(tmp_path, code) |
| 38 | |
| 39 | stored = path.read_text() |
| 40 | assert code not in stored |
| 41 | assert stored.startswith("sha256:") and len(stored.strip()) == len("sha256:") + 64 |
| 42 | |
| 43 | |
| 44 | def test_typing_the_code_is_forgiving_but_a_wrong_length_is_nothing(): |
| 45 | code = "7K3MQ9ZT1W4XB8RN2PVE" |
| 46 | assert object_setup.normalize_code(object_setup.display(code).lower()) == code |
| 47 | assert object_setup.normalize_code(" 7k3mq 9zt1w-4xb8r n2pve ") == code |
| 48 | # base32 leaves out I, L and O; someone reading them off a screen means 1, 1 and 0 |
| 49 | assert object_setup.normalize_code("7K3MQ9ZTIW4XB8RN2PVE") == code |
| 50 | assert object_setup.normalize_code(code[:-1]) == "" |
| 51 | assert object_setup.normalize_code(code + "A") == "" |
| 52 | assert object_setup.normalize_code("U" * 20) == "" # U is not in the alphabet either |
| 53 | |
| 54 | |
| 55 | def test_the_right_code_makes_one_admin_with_the_chosen_password_and_closes_setup(tmp_path): |
| 56 | code = object_setup.new_code() |
| 57 | _place_code(tmp_path, code) |
| 58 | assert object_setup.waiting(tmp_path) |
| 59 | |
| 60 | user = object_setup.complete(object_setup.display(code), "Owner@Example.org", PASSWORD, "Owner", base_dir=tmp_path) |
| 61 | |
| 62 | assert user["roles"] == ["admin"] and user["email"] == "Owner@Example.org" |
| 63 | assert object_credentials.verify_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 64 | assert not object_setup.code_path(tmp_path).exists() |
| 65 | assert list(object_setup.code_path(tmp_path).parent.glob("setup_code*")) == [] |
| 66 | assert not object_setup.waiting(tmp_path) |
| 67 | # the code can't be used again, even by the same person |
| 68 | assert object_setup.complete(code, "other@example.org", PASSWORD, base_dir=tmp_path) is None |
| 69 | assert len(object_identity.list_users(base_dir=tmp_path)) == 1 |
| 70 | |
| 71 | |
| 72 | def test_a_wrong_code_makes_nothing_and_the_right_one_still_works(tmp_path): |
| 73 | code = object_setup.new_code() |
| 74 | _place_code(tmp_path, code) |
| 75 | |
| 76 | assert object_setup.complete(object_setup.new_code(), "a@example.org", PASSWORD, base_dir=tmp_path) is None |
| 77 | assert object_setup.complete("", "a@example.org", PASSWORD, base_dir=tmp_path) is None |
| 78 | assert object_identity.list_users(base_dir=tmp_path) == [] |
| 79 | assert object_setup.waiting(tmp_path) |
| 80 | assert object_setup.complete(code, "a@example.org", PASSWORD, base_dir=tmp_path) is not None |
| 81 | |
| 82 | |
| 83 | def test_a_bad_password_or_email_is_refused_before_the_code_is_used(tmp_path): |
| 84 | """The person fixes the form and tries again: a short password must not burn their only code.""" |
| 85 | code = object_setup.new_code() |
| 86 | _place_code(tmp_path, code) |
| 87 | |
| 88 | with pytest.raises(object_setup.SetupError): |
| 89 | object_setup.complete(code, "a@example.org", "short", base_dir=tmp_path) |
| 90 | with pytest.raises(object_setup.SetupError): |
| 91 | object_setup.complete(code, "not an email", PASSWORD, base_dir=tmp_path) |
| 92 | assert object_setup.waiting(tmp_path) |
| 93 | assert object_setup.complete(code, "a@example.org", PASSWORD, base_dir=tmp_path) is not None |
| 94 | |
| 95 | |
| 96 | def test_a_failure_while_making_the_admin_gives_the_code_back(tmp_path, monkeypatch): |
| 97 | code = object_setup.new_code() |
| 98 | _place_code(tmp_path, code) |
| 99 | |
| 100 | def broken(*args, **kwargs): |
| 101 | raise OSError("disk full") |
| 102 | monkeypatch.setattr(object_identity, "create_user", broken) |
| 103 | with pytest.raises(OSError): |
| 104 | object_setup.complete(code, "a@example.org", PASSWORD, base_dir=tmp_path) |
| 105 | monkeypatch.undo() |
| 106 | |
| 107 | assert object_setup.waiting(tmp_path) |
| 108 | assert object_credentials._read_credentials(object_credentials.credentials_path(tmp_path)) == [] |
| 109 | assert object_setup.complete(code, "a@example.org", PASSWORD, base_dir=tmp_path) is not None |
| 110 | |
| 111 | |
| 112 | def _sessions_cannot_be_ended(monkeypatch): |
| 113 | def broken(*args, **kwargs): |
| 114 | raise OSError("disk full") |
| 115 | monkeypatch.setattr(object_identity, "revoke_user_sessions", broken) |
| 116 | |
| 117 | |
| 118 | def test_sessions_that_cannot_be_ended_leave_no_password_behind_and_give_the_code_back(tmp_path, monkeypatch): |
| 119 | """set_password writes the credential and then fails to end sessions: before, the credential row stayed |
| 120 | with no user, ready for whoever is next given that id.""" |
| 121 | code = object_setup.new_code() |
| 122 | _place_code(tmp_path, code) |
| 123 | |
| 124 | _sessions_cannot_be_ended(monkeypatch) |
| 125 | with pytest.raises(object_credentials.SessionRevocationError): |
| 126 | object_setup.complete(code, "owner@example.org", PASSWORD, base_dir=tmp_path) |
| 127 | monkeypatch.undo() |
| 128 | |
| 129 | assert object_credentials._read_credentials(object_credentials.credentials_path(tmp_path)) == [] |
| 130 | assert object_identity.list_users(base_dir=tmp_path) == [] |
| 131 | assert object_setup.waiting(tmp_path) |
| 132 | user = object_setup.complete(code, "owner@example.org", PASSWORD, base_dir=tmp_path) |
| 133 | assert user is not None and object_credentials.verify_password(user["user_id"], PASSWORD, base_dir=tmp_path) |
| 134 | |
| 135 | |
| 136 | def test_two_setups_at_once_make_exactly_one_admin(tmp_path): |
| 137 | """The claim is the rename of the code file. Without it both requests pass the hash check and both |
| 138 | become admin of someone's server.""" |
| 139 | code = object_setup.new_code() |
| 140 | _place_code(tmp_path, code) |
| 141 | start = threading.Barrier(8) |
| 142 | results = [] |
| 143 | |
| 144 | def attempt(n): |
| 145 | start.wait() |
| 146 | results.append(object_setup.complete(code, f"p{n}@example.org", PASSWORD, base_dir=tmp_path)) |
| 147 | |
| 148 | threads = [threading.Thread(target=attempt, args=(n,)) for n in range(8)] |
| 149 | for thread in threads: |
| 150 | thread.start() |
| 151 | for thread in threads: |
| 152 | thread.join() |
| 153 | |
| 154 | assert len([r for r in results if r is not None]) == 1 |
| 155 | assert len(object_identity.list_users(base_dir=tmp_path)) == 1 |
| 156 | |
| 157 | |
| 158 | def test_an_admin_made_from_the_shell_ends_waiting_whatever_file_is_left(tmp_path): |
| 159 | """The way out when the code is lost: SSH in and run create-superuser.""" |
| 160 | code = object_setup.new_code() |
| 161 | _place_code(tmp_path, code) |
| 162 | object_identity.create_user({"user_id": "operator", "roles": ["admin"]}, base_dir=tmp_path) |
| 163 | |
| 164 | assert not object_setup.waiting(tmp_path) |
| 165 | assert object_setup.complete(code, "a@example.org", PASSWORD, base_dir=tmp_path) is None |
| 166 | assert [u["user_id"] for u in object_identity.list_users(base_dir=tmp_path)] == ["operator"] |
| 167 | |
| 168 | |
| 169 | def test_an_identity_store_that_cant_be_read_is_not_handed_out(tmp_path, monkeypatch): |
| 170 | code = object_setup.new_code() |
| 171 | _place_code(tmp_path, code) |
| 172 | |
| 173 | def unreadable(**kwargs): |
| 174 | raise ValueError("bad row") |
| 175 | monkeypatch.setattr(object_identity, "list_users", unreadable) |
| 176 | |
| 177 | assert not object_setup.waiting(tmp_path) |
| 178 | assert object_setup.complete(code, "a@example.org", PASSWORD, base_dir=tmp_path) is None |
| 179 | |
| 180 | |
| 181 | def test_a_server_without_a_code_file_is_never_waiting(tmp_path): |
| 182 | assert not object_setup.waiting(tmp_path) |
| 183 | |
| 184 | |
| 185 | # ---- the server ----------------------------------------------------------------- |
| 186 | |
| 187 | |
| 188 | @pytest.fixture |
| 189 | def waiting_box(tmp_path, monkeypatch): |
| 190 | data_dir = tmp_path / "data" |
| 191 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir)) |
| 192 | monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true") |
| 193 | monkeypatch.setenv(object_server.COOKIE_SECURE_ENV, "false") |
| 194 | monkeypatch.setenv(object_server.ADMIN_TOKEN_ENV, ADMIN_TOKEN) |
| 195 | monkeypatch.setattr(object_server, "PASSWORD_LOGIN_FAILURE_DELAY_SECONDS", 0) |
| 196 | code = object_setup.new_code() |
| 197 | _place_code(data_dir, code) |
| 198 | return data_dir, code |
| 199 | |
| 200 | |
| 201 | def _post(path, form, headers=()): |
| 202 | return raw_request(path, method="POST", body=urllib.parse.urlencode(form).encode(), |
| 203 | headers=[("content-type", "application/x-www-form-urlencoded"), *headers]) |
| 204 | |
| 205 | |
| 206 | def test_a_waiting_box_answers_only_health_and_setup(waiting_box): |
| 207 | for path in ("/objects", "/identity/users", "/login", "/signup", "/", "/dav/files/"): |
| 208 | status, _headers, body = raw_request(path) |
| 209 | assert status == 503, path |
| 210 | assert json.loads(body)["setup"] == "/setup" |
| 211 | |
| 212 | status, headers, _ = raw_request("/notes", headers=[("accept", "text/html")]) |
| 213 | assert status == 303 and headers[b"location"] == b"/setup" |
| 214 | |
| 215 | status, _, body = raw_request("/health") |
| 216 | assert status == 200 and json.loads(body)["setup"] == "waiting" |
| 217 | status, _, body = raw_request("/setup", headers=[("accept", "text/html")]) |
| 218 | assert status == 200 and b'name="code"' in body |
| 219 | |
| 220 | |
| 221 | def test_the_admin_token_still_reaches_a_waiting_box(waiting_box): |
| 222 | """Whoever holds it has root on the box already; locking them out would only stop repairs.""" |
| 223 | status, _, _ = raw_request("/identity/users", headers=[("authorization", f"Token {ADMIN_TOKEN}")]) |
| 224 | assert status == 200 |
| 225 | |
| 226 | |
| 227 | def test_the_setup_page_reads_the_code_from_the_part_of_the_address_never_sent(waiting_box): |
| 228 | _, _, body = raw_request("/setup", headers=[("accept", "text/html")]) |
| 229 | page = body.decode() |
| 230 | assert "location.hash" in page and "history.replaceState" in page |
| 231 | assert 'name="referrer" content="strict-origin"' in page |
| 232 | |
| 233 | |
| 234 | def test_setup_through_the_page_signs_the_owner_in_and_opens_the_box(waiting_box): |
| 235 | data_dir, code = waiting_box |
| 236 | status, headers, _ = _post("/setup", {"code": code, "email": "owner@example.org", "password": PASSWORD}) |
| 237 | |
| 238 | assert status == 303 |
| 239 | assert headers[b"set-cookie"].startswith(b"dbbasic_session=") |
| 240 | assert not object_setup.waiting(data_dir) |
| 241 | status, _, body = raw_request("/health") |
| 242 | assert "setup" not in json.loads(body) |
| 243 | status, _, _ = raw_request("/setup", headers=[("accept", "text/html")]) |
| 244 | assert status == 404 |
| 245 | # and the password they chose is the one that signs them in |
| 246 | status, headers, _ = _post("/login", {"email": "owner@example.org", "password": PASSWORD}) |
| 247 | assert status == 303 and headers[b"set-cookie"].startswith(b"dbbasic_session=") |
| 248 | |
| 249 | |
| 250 | def test_a_wrong_code_on_the_page_says_so_and_makes_nothing(waiting_box): |
| 251 | data_dir, _code = waiting_box |
| 252 | status, headers, body = _post("/setup", {"code": object_setup.new_code(), "email": "x@example.org", "password": PASSWORD}) |
| 253 | |
| 254 | assert status == 400 and b"isn't right" in body |
| 255 | assert b"set-cookie" not in headers |
| 256 | assert object_identity.list_users(base_dir=data_dir) == [] |
| 257 | |
| 258 | |
| 259 | @pytest.mark.parametrize("enforce", ["true", "false"], ids=["enforced", "unenforced"]) |
| 260 | def test_setup_whose_sessions_cannot_be_ended_says_so_and_can_be_tried_again(waiting_box, monkeypatch, enforce): |
| 261 | data_dir, code = waiting_box |
| 262 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, enforce) |
| 263 | with monkeypatch.context() as broken: |
| 264 | _sessions_cannot_be_ended(broken) |
| 265 | status, headers, body = _post("/setup", {"code": code, "email": "owner@example.org", "password": PASSWORD}) |
| 266 | |
| 267 | assert status == 500 and b"nothing was set up" in body |
| 268 | assert b"set-cookie" not in headers |
| 269 | assert object_credentials._read_credentials(object_credentials.credentials_path(data_dir)) == [] |
| 270 | assert object_setup.waiting(data_dir) |
| 271 | status, headers, _ = _post("/setup", {"code": code, "email": "owner@example.org", "password": PASSWORD}) |
| 272 | assert status == 303 and headers[b"set-cookie"].startswith(b"dbbasic_session=") |
| 273 | |
| 274 | |
| 275 | def test_setup_from_another_site_is_refused(waiting_box): |
| 276 | data_dir, code = waiting_box |
| 277 | status, _, _ = _post("/setup", {"code": code, "email": "x@example.org", "password": PASSWORD}, |
| 278 | headers=[("origin", "https://evil.example"), ("host", "box.example")]) |
| 279 | assert status == 400 |
| 280 | assert object_setup.waiting(data_dir) |
| 281 | |
| 282 | |
| 283 | def test_guessing_codes_is_limited(waiting_box): |
| 284 | data_dir, code = waiting_box |
| 285 | for _ in range(object_server.SETUP_ATTEMPTS_PER_HOUR_PER_IP): |
| 286 | _post("/setup", {"code": object_setup.new_code(), "email": "x@example.org", "password": PASSWORD}) |
| 287 | status, _, _ = _post("/setup", {"code": code, "email": "x@example.org", "password": PASSWORD}) |
| 288 | assert status == 429 |
| 289 | assert object_setup.waiting(data_dir) |
| 290 | |
| 291 | |
| 292 | def test_setup_refuses_when_password_login_is_off(waiting_box, monkeypatch): |
| 293 | """It would make an admin who could never sign in again.""" |
| 294 | data_dir, code = waiting_box |
| 295 | monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "false") |
| 296 | status, _, body = _post("/setup", {"code": code, "email": "x@example.org", "password": PASSWORD}) |
| 297 | assert status == 409 and object_server.PASSWORD_LOGIN_ENV.encode() in body |
| 298 | assert object_setup.waiting(data_dir) |
| 299 | |
| 300 | |
| 301 | def test_health_names_the_installed_release_and_commit(tmp_path, monkeypatch): |
| 302 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(tmp_path)) |
| 303 | (tmp_path / "installed.json").write_text(json.dumps( |
| 304 | {"release": "2026.11v1", "commit": "a" * 40, "extra": "<script>"})) |
| 305 | _, _, body = raw_request("/health") |
| 306 | assert json.loads(body) == {"status": "ok", "release": "2026.11v1", "commit": "a" * 40} |
| 307 | |
| 308 | (tmp_path / "installed.json").write_text(json.dumps({"release": "bad value!", "commit": "nope"})) |
| 309 | _, _, body = raw_request("/health") |
| 310 | assert json.loads(body) == {"status": "ok"} |
| 311 | |
| 312 | |
| 313 | def test_the_owner_gets_a_readable_id_from_their_email_unless_it_is_taken(tmp_path): |
| 314 | """Pages say "signed in as <id>"; a random id there was the first thing the first test box showed.""" |
| 315 | code = object_setup.new_code() |
| 316 | _place_code(tmp_path, code) |
| 317 | object_identity.create_user({"user_id": "owner", "roles": []}, base_dir=tmp_path) |
| 318 | |
| 319 | user = object_setup.complete(code, "Owner@example.org", PASSWORD, base_dir=tmp_path) |
| 320 | assert user["user_id"] != "owner" # taken: a random id, never someone else's |
| 321 | |
| 322 | other = tmp_path / "other" |
| 323 | _place_code(other, code) |
| 324 | assert object_setup.complete(code, "Ann.Lee+x@example.org", PASSWORD, base_dir=other)["user_id"] == "ann.leex" |
| 325 | |
| 326 | |
| 327 | def test_the_setup_page_also_reads_a_code_link_opened_on_the_same_page(waiting_box): |
| 328 | """Changing only the part after # loads nothing new, so the page must listen for it (seen on a test box).""" |
| 329 | _, _, body = raw_request("/setup", headers=[("accept", "text/html")]) |
| 330 | assert b'addEventListener("hashchange"' in body |
| 331 | |
| 332 | |
| 333 | def test_the_one_click_starting_apps_come_after_what_they_depend_on(): |
| 334 | """object_packages.install_package doesn't install dependencies, and 2026.11v1 installed notes without |
| 335 | app-views: its notes page said "Object not found: site_view_render".""" |
| 336 | import re |
| 337 | from pathlib import Path |
| 338 | root = Path(__file__).resolve().parents[1] |
| 339 | script = (root / "scripts" / "one-click-install.sh").read_text() |
| 340 | block = re.search(r'for app in \(([^)]*)\):', script).group(1) |
| 341 | apps = re.findall(r'"(app-[a-z-]+)"', block) |
| 342 | assert "app-notes" in apps and "app-views" in apps |
| 343 | for position, app in enumerate(apps): |
| 344 | manifest = json.loads((root / "packages" / app / "dbbasic-package.json").read_text()) |
| 345 | for needed in manifest.get("dependencies") or []: |
| 346 | assert needed in apps[:position], f"{app} needs {needed} installed before it" |
| 347 | |
| 348 | |
| 349 | def test_the_cloud_init_installs_one_release_and_clones_at_it(): |
| 350 | """A release whose cloud-init still names the one before installs the one before. And a clone of main runs |
| 351 | the script from files install.sh then checks out from under it.""" |
| 352 | import re |
| 353 | from pathlib import Path |
| 354 | text = (Path(__file__).resolve().parents[1] / "cloud-init.yaml").read_text() |
| 355 | clone = re.search(r"git clone --quiet --branch (\S+) https://\S+ /opt/dbbasic-object-server", text) |
| 356 | run = re.search(r"one-click-install\.sh (\S+)\s*$", text, re.M) |
| 357 | assert clone and run and clone.group(1) == run.group(1) |
| 358 | assert re.fullmatch(r"20\d{2}\.(0[1-9]|1[0-2])v[1-9]\d*", run.group(1)) |