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_fresh_box_enforcement.py · 14.6 KB · 312 lines
| 1 | """A fresh box with enforcement requested starts fail-closed, never open, never bricked. |
| 2 | |
| 3 | Commit 7994543 made a requested-but-blocked enforcement refuse to start, |
| 4 | because the alternative was worse: requests ran unenforced (audit/shadow |
| 5 | mode) while the operator believed customers were fenced. But two fresh-box |
| 6 | states were "blocked" only because the readiness gate was written for a |
| 7 | running site, and both are states every new box passes through: |
| 8 | |
| 9 | - the one-click install (scripts/one-click-install.sh): the starting apps' package |
| 10 | rules, password login on, enforcement on, an admin token, and no users yet; the |
| 11 | first admin arrives through /setup. "No non-admin identity path" counted |
| 12 | users, so the box never came up. |
| 13 | - an empty data directory (no policy file) that the operator bootstraps |
| 14 | with the admin token, as Scroll's sandbox does: the default policy grants |
| 15 | nothing, so "no allow grants" blocked it as well. |
| 16 | |
| 17 | Neither blocker describes a box that would run open if enforced: an empty |
| 18 | policy enforced means non-admins are denied, which is the safe outcome; a |
| 19 | sign-in path with no users yet means the first user is still to come. So |
| 20 | both now start with enforcement EFFECTIVE, the admin token (and /setup) as |
| 21 | the way in. |
| 22 | |
| 23 | Since then requested enforcement is always effective (readiness is |
| 24 | diagnostics only, test_enforcement_fail_closed), so the one refusal left is |
| 25 | no admin token. A box with no sign-in mechanism configured at all starts |
| 26 | too, enforced, with a WARNING naming the fresh-box order: only the admin |
| 27 | token and public grants get in, which is safe. |
| 28 | """ |
| 29 | from __future__ import annotations |
| 30 | |
| 31 | import asyncio |
| 32 | import json |
| 33 | import re |
| 34 | import urllib.parse |
| 35 | |
| 36 | import pytest |
| 37 | |
| 38 | import object_identity_sources |
| 39 | import object_permission_store |
| 40 | import object_server |
| 41 | import object_setup |
| 42 | from test_object_server import raw_request, request, write_records, write_source |
| 43 | |
| 44 | TOKEN = "f" * 32 |
| 45 | PASSWORD = "correct horse battery" |
| 46 | ADMIN = [("authorization", f"Token {TOKEN}")] |
| 47 | |
| 48 | |
| 49 | def run_lifespan(): |
| 50 | sent = [] |
| 51 | inbox = [{"type": "lifespan.startup"}, {"type": "lifespan.shutdown"}] |
| 52 | |
| 53 | async def receive(): |
| 54 | return inbox.pop(0) |
| 55 | |
| 56 | async def send(message): |
| 57 | sent.append(message) |
| 58 | |
| 59 | asyncio.run(object_server._handle_lifespan(receive, send)) |
| 60 | return sent[0] |
| 61 | |
| 62 | |
| 63 | def _clean_env(monkeypatch, tmp_path): |
| 64 | data_dir = tmp_path / "data" |
| 65 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir)) |
| 66 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects")) |
| 67 | for name in ( |
| 68 | object_server.ADMIN_TOKEN_ENV, |
| 69 | object_server.PERMISSION_ENFORCEMENT_ENV, |
| 70 | object_server.PERMISSION_AUDIT_ENV, |
| 71 | object_server.ALLOW_BLOCKED_ENFORCEMENT_START_ENV, |
| 72 | object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, |
| 73 | object_server.PERMISSION_TRUST_HEADERS_ENV, |
| 74 | object_server.SESSION_LOGIN_ENV, |
| 75 | object_server.PASSWORD_LOGIN_ENV, |
| 76 | object_identity_sources.IDENTITY_VERIFY_URL_ENV, |
| 77 | ): |
| 78 | monkeypatch.delenv(name, raising=False) |
| 79 | monkeypatch.setattr(object_server, "PASSWORD_LOGIN_FAILURE_DELAY_SECONDS", 0) |
| 80 | return data_dir |
| 81 | |
| 82 | |
| 83 | def _one_click_env(monkeypatch): |
| 84 | """The environment scripts/one-click-install.sh writes (set_env lines), plus install.sh's admin token.""" |
| 85 | monkeypatch.setenv(object_server.ADMIN_TOKEN_ENV, TOKEN) |
| 86 | monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true") |
| 87 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 88 | monkeypatch.setenv(object_server.COOKIE_SECURE_ENV, "true") |
| 89 | monkeypatch.setenv(object_server.RATE_LIMIT_TRUST_PROXY_HEADERS_ENV, "true") |
| 90 | |
| 91 | |
| 92 | def _post_form(path, form, headers=()): |
| 93 | return raw_request(path, method="POST", body=urllib.parse.urlencode(form).encode(), |
| 94 | headers=[("content-type", "application/x-www-form-urlencoded"), *headers]) |
| 95 | |
| 96 | |
| 97 | def _session_cookie(set_cookie: bytes) -> tuple[str, str]: |
| 98 | pair = set_cookie.decode().split(";", 1)[0] |
| 99 | assert pair.startswith(object_server.SESSION_COOKIE_NAME + "=") |
| 100 | return ("cookie", pair) |
| 101 | |
| 102 | |
| 103 | @pytest.fixture |
| 104 | def one_click_box(tmp_path, monkeypatch): |
| 105 | """The one-click installer's exact state after its last step, before anyone opens /setup.""" |
| 106 | data_dir = _clean_env(monkeypatch, tmp_path) |
| 107 | # what the installer does, in its order: setup code hash in, policy saved (a stand-in for the apps' rules), env written |
| 108 | code = object_setup.new_code() |
| 109 | path = object_setup.code_path(data_dir) |
| 110 | path.parent.mkdir(parents=True, exist_ok=True) |
| 111 | path.write_text(object_setup.code_hash(code) + "\n", encoding="ascii") |
| 112 | object_permission_store.replace_policy(object_permission_store.starter_policy_payload(), |
| 113 | base_dir=data_dir) |
| 114 | _one_click_env(monkeypatch) |
| 115 | write_records(data_dir, "contacts", "id\tname\n1\tAlice\n") |
| 116 | write_source(tmp_path / "objects" / "site" / "home.py", "def GET(request):\n return {'ok': True}\n") |
| 117 | write_source(tmp_path / "objects" / "secret" / "runner.py", "def GET(request):\n return {'ran': True}\n") |
| 118 | return data_dir, code |
| 119 | |
| 120 | |
| 121 | # ---- Case A: the one-click install ------------------------------------------------ |
| 122 | |
| 123 | |
| 124 | def test_one_click_box_starts_with_enforcement_effective_before_anyone_signs_up(one_click_box): |
| 125 | assert run_lifespan()["type"] == "lifespan.startup.complete" |
| 126 | assert object_server._permission_enforcement_enabled() is True |
| 127 | assert object_server._permission_enforcement_blocked() is False |
| 128 | assert object_server._permission_enforcement_problems() == [] |
| 129 | |
| 130 | |
| 131 | def test_waiting_one_click_box_answers_anonymous_only_on_health_and_setup(one_click_box): |
| 132 | for path in ("/objects/site_home", "/objects/secret_runner", "/collections/contacts/records", |
| 133 | "/collections/dbbasic_probe/records", "/identity/users", "/login"): |
| 134 | status, _, body = raw_request(path) |
| 135 | assert status == 503, path |
| 136 | assert json.loads(body)["setup"] == "/setup" |
| 137 | status, _, body = raw_request("/health") |
| 138 | assert status == 200 and json.loads(body)["setup"] == "waiting" |
| 139 | status, _, body = raw_request("/setup", headers=[("accept", "text/html")]) |
| 140 | assert status == 200 and b'name="code"' in body |
| 141 | |
| 142 | |
| 143 | def test_waiting_one_click_box_still_answers_the_admin_token(one_click_box): |
| 144 | status, _, _ = raw_request("/identity/users", headers=ADMIN) |
| 145 | assert status == 200 |
| 146 | status, _, payload = request("/collections/contacts/records", headers=ADMIN) |
| 147 | assert status == 200 and payload["records"] == [{"id": "1", "name": "Alice"}] |
| 148 | |
| 149 | |
| 150 | def test_after_setup_the_owner_signs_in_and_enforcement_holds_for_everyone_else(one_click_box): |
| 151 | data_dir, code = one_click_box |
| 152 | assert run_lifespan()["type"] == "lifespan.startup.complete" |
| 153 | |
| 154 | status, headers, _ = _post_form("/setup", {"code": code, "email": "owner@example.org", |
| 155 | "password": PASSWORD}) |
| 156 | assert status == 303 and not object_setup.waiting(data_dir) |
| 157 | status, headers, _ = _post_form("/login", {"email": "owner@example.org", "password": PASSWORD}) |
| 158 | assert status == 303 |
| 159 | owner = [_session_cookie(headers[b"set-cookie"])] |
| 160 | |
| 161 | # the owner (admin role) and the admin token reach what the policy grants nobody else |
| 162 | for who in (owner, ADMIN): |
| 163 | status, _, payload = request("/collections/contacts/records", headers=who) |
| 164 | assert status == 200 and payload["records"] == [{"id": "1", "name": "Alice"}] |
| 165 | status, _, payload = request("/objects/secret_runner", headers=who) |
| 166 | assert status == 200 and payload == {"ran": True} |
| 167 | |
| 168 | # anonymous: exactly the starter grants, and enforced (403), not shadow (200) |
| 169 | status, _, payload = request("/objects/site_home") |
| 170 | assert status == 200 and payload == {"ok": True} |
| 171 | status, _, payload = request("/collections/contacts/records") |
| 172 | assert status == 403, payload |
| 173 | status, _, payload = request("/objects/secret_runner") |
| 174 | assert status == 403, payload |
| 175 | assert object_server._permission_enforcement_enabled() is True |
| 176 | |
| 177 | |
| 178 | def test_restarting_after_setup_still_starts(one_click_box): |
| 179 | data_dir, code = one_click_box |
| 180 | object_setup.complete(code, "owner@example.org", PASSWORD, base_dir=data_dir) |
| 181 | assert run_lifespan()["type"] == "lifespan.startup.complete" |
| 182 | assert object_server._permission_enforcement_enabled() is True |
| 183 | |
| 184 | |
| 185 | # ---- Case B: an empty data directory bootstrapped with the admin token ------------------- |
| 186 | |
| 187 | |
| 188 | @pytest.fixture |
| 189 | def empty_box(tmp_path, monkeypatch): |
| 190 | """No policy file at all; enforcement, password login and an admin token (Scroll's sandbox).""" |
| 191 | data_dir = _clean_env(monkeypatch, tmp_path) |
| 192 | monkeypatch.setenv(object_server.ADMIN_TOKEN_ENV, TOKEN) |
| 193 | monkeypatch.setenv(object_server.PASSWORD_LOGIN_ENV, "true") |
| 194 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 195 | write_records(data_dir, "contacts", "id\tname\n1\tAlice\n") |
| 196 | write_source(tmp_path / "objects" / "site" / "home.py", "def GET(request):\n return {'ok': True}\n") |
| 197 | assert not object_permission_store.policy_path(data_dir).exists() |
| 198 | return data_dir |
| 199 | |
| 200 | |
| 201 | def test_empty_box_starts_fail_closed(empty_box): |
| 202 | assert run_lifespan()["type"] == "lifespan.startup.complete" |
| 203 | assert object_server._permission_enforcement_enabled() is True |
| 204 | assert object_server._permission_enforcement_blocked() is False |
| 205 | |
| 206 | |
| 207 | def test_empty_box_denies_anonymous_everything_and_the_admin_token_everything_allowed(empty_box): |
| 208 | for path in ("/objects/site_home", "/collections/contacts/records"): |
| 209 | status, _, payload = request(path) |
| 210 | assert status == 403, (path, payload) |
| 211 | status, _, payload = request("/objects/site_home", headers=ADMIN) |
| 212 | assert status == 200 and payload == {"ok": True} |
| 213 | status, _, payload = request("/collections/contacts/records", headers=ADMIN) |
| 214 | assert status == 200 and payload["records"] == [{"id": "1", "name": "Alice"}] |
| 215 | |
| 216 | |
| 217 | def test_empty_box_bootstraps_over_the_api_with_the_admin_token(empty_box): |
| 218 | """The sandbox's order: start, make a superuser, then give the box a policy over the API.""" |
| 219 | body = json.dumps({"user_id": "boss", "email": "boss@example.org", "roles": ["superuser"]}).encode() |
| 220 | status, _, payload = request("/identity/users", method="POST", body=body, headers=ADMIN) |
| 221 | assert status in (200, 201), payload |
| 222 | policy = json.dumps(object_permission_store.starter_policy_payload()).encode() |
| 223 | status, _, payload = request("/permissions/policy", method="PUT", body=policy, headers=ADMIN) |
| 224 | assert status == 200, payload |
| 225 | status, _, payload = request("/objects/site_home") |
| 226 | assert status == 200 and payload == {"ok": True} |
| 227 | status, _, _ = request("/collections/contacts/records") |
| 228 | assert status == 403 |
| 229 | |
| 230 | |
| 231 | def test_empty_policy_is_reported_as_deny_all_not_as_a_blocker(empty_box): |
| 232 | status, _, payload = request("/permissions/status", headers=ADMIN) |
| 233 | assert status == 200 |
| 234 | assert payload["readiness"] == {"can_enable_enforcement": True, "blockers": []} |
| 235 | assert payload["permissions"]["enforcement_enabled"] is True |
| 236 | assert any("no allow grants" in w and "denied" in w for w in payload["warnings"]) |
| 237 | |
| 238 | |
| 239 | # ---- what still refuses ----------------------------------------------------------------- |
| 240 | |
| 241 | |
| 242 | def test_identity_source_only_box_still_starts(tmp_path, monkeypatch): |
| 243 | data_dir = _clean_env(monkeypatch, tmp_path) |
| 244 | monkeypatch.setenv(object_server.ADMIN_TOKEN_ENV, TOKEN) |
| 245 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 246 | monkeypatch.setenv(object_identity_sources.IDENTITY_VERIFY_URL_ENV, "https://auth.example.com/verify/") |
| 247 | monkeypatch.setenv(object_identity_sources.IDENTITY_VERIFY_SECRET_ENV, "test-shared-secret-0123") |
| 248 | monkeypatch.setenv(object_identity_sources.IDENTITY_AUDIENCE_ENV, "box-test.example") |
| 249 | object_permission_store.replace_policy( |
| 250 | {"access_mode": "registered", |
| 251 | "rules": [{"effect": "allow", "principal": "registered", "actions": ["read"], |
| 252 | "collection": "contacts"}]}, |
| 253 | base_dir=data_dir, |
| 254 | ) |
| 255 | assert run_lifespan()["type"] == "lifespan.startup.complete" |
| 256 | assert object_server._permission_enforcement_enabled() is True |
| 257 | |
| 258 | |
| 259 | def test_one_click_box_without_an_admin_token_still_refuses(one_click_box, monkeypatch): |
| 260 | monkeypatch.delenv(object_server.ADMIN_TOKEN_ENV) |
| 261 | sent = run_lifespan() |
| 262 | assert sent["type"] == "lifespan.startup.failed" |
| 263 | assert object_server.ADMIN_TOKEN_ENV in sent["message"] and "Set it and start again" in sent["message"] |
| 264 | |
| 265 | |
| 266 | def test_empty_box_with_no_sign_in_mechanism_starts_enforced_and_names_the_bootstrap_order( |
| 267 | empty_box, monkeypatch, capsys |
| 268 | ): |
| 269 | """No password login, trusted headers, session login or identity source: probably a |
| 270 | misconfiguration, but enforced it is safe (the admin token and public grants only). It used |
| 271 | to refuse to start; now it starts with a WARNING that says how a fresh box is meant to be |
| 272 | started, and the admin token can still make users, mint sessions and save a policy.""" |
| 273 | monkeypatch.delenv(object_server.PASSWORD_LOGIN_ENV) |
| 274 | sent = run_lifespan() |
| 275 | assert sent["type"] == "lifespan.startup.complete" |
| 276 | err = capsys.readouterr().err |
| 277 | assert "WARNING" in err and "Permission enforcement is ON" in err |
| 278 | assert "No non-admin sign-in path" in err |
| 279 | assert object_server.PASSWORD_LOGIN_ENV in err |
| 280 | assert "starter_policy_payload" in err and "before the first start" in err |
| 281 | status, _, payload = request("/collections/contacts/records") |
| 282 | assert status == 403, payload |
| 283 | status, _, payload = request("/collections/contacts/records", headers=ADMIN) |
| 284 | assert status == 200 and payload["records"] == [{"id": "1", "name": "Alice"}] |
| 285 | status, _, payload = request("/health") |
| 286 | assert status == 200 |
| 287 | |
| 288 | |
| 289 | # ---- the one-click script saves no starter policy; its policy is the starting apps' rules ----------- |
| 290 | |
| 291 | |
| 292 | def test_one_click_script_no_longer_saves_a_starter_policy(): |
| 293 | from pathlib import Path |
| 294 | script = (Path(__file__).resolve().parents[1] / "scripts" / "one-click-install.sh").read_text() |
| 295 | assert "starter_policy_payload" not in script |
| 296 | assert "replace_policy" not in script |
| 297 | |
| 298 | |
| 299 | def test_one_click_starting_apps_alone_leave_a_non_empty_all_package_policy(tmp_path): |
| 300 | from pathlib import Path |
| 301 | import object_packages |
| 302 | root = Path(__file__).resolve().parents[1] |
| 303 | script = (root / "scripts" / "one-click-install.sh").read_text() |
| 304 | apps = re.findall(r'"(app-[a-z-]+)"', re.search(r'for app in \(([^)]*)\):', script).group(1)) |
| 305 | for app in apps: |
| 306 | object_packages.install_package(app, root=root / "packages", base_dir=tmp_path, |
| 307 | object_roots=[tmp_path / "objects"], allow_replace=True) |
| 308 | policy = object_permission_store.load_policy(base_dir=tmp_path) \ |
| 309 | if hasattr(object_permission_store, "load_policy") else None |
| 310 | data = json.loads((tmp_path / "permissions" / "policy.json").read_text()) |
| 311 | rules = (data.get("policy") or data)["rules"] |
| 312 | assert rules and all(rule.get("package") for rule in rules) |