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_admin_routes_broken_state.py · 11.4 KB · 319 lines
| 1 | """An admin-token GET never answers 500 because the box's own files are broken. |
| 2 | |
| 3 | The Scroll operator console opens /admin/status and /permissions/policy to |
| 4 | find and repair a bad policy. Both used to crash with an unhandled |
| 5 | ValueError. This sweep calls every admin-gated GET route with the admin token |
| 6 | in each broken state (and once with a healthy box, to prove the route list is |
| 7 | real) and holds: no 500. A route answers its normal 200, or a deliberate, |
| 8 | documented error (400 for a schema the broken state cannot be checked |
| 9 | against, 503 with error_detail for collection search/membership when the |
| 10 | policy cannot be read). Non-admin behaviour stays what it was. |
| 11 | """ |
| 12 | from __future__ import annotations |
| 13 | |
| 14 | import json |
| 15 | import os |
| 16 | |
| 17 | import pytest |
| 18 | |
| 19 | import object_identity |
| 20 | import object_permission_store |
| 21 | import object_server |
| 22 | from test_object_server import raw_request, request, write_records, write_source |
| 23 | |
| 24 | TOKEN = "e" * 32 |
| 25 | ADMIN = [("authorization", f"Token {TOKEN}")] |
| 26 | |
| 27 | POLICY = { |
| 28 | "access_mode": "role_based", |
| 29 | "rules": [ |
| 30 | { |
| 31 | "effect": "allow", |
| 32 | "principal": "registered", |
| 33 | "actions": ["read"], |
| 34 | "collection": "contacts", |
| 35 | "reason": "contacts", |
| 36 | } |
| 37 | ], |
| 38 | } |
| 39 | |
| 40 | # (path, query_string): every admin-gated GET route family. |
| 41 | ROUTES = [ |
| 42 | ("/health", "metrics=true"), |
| 43 | ("/health", ""), |
| 44 | ("/admin/status", ""), |
| 45 | ("/admin/storage", ""), |
| 46 | ("/admin/changes", ""), |
| 47 | ("/admin/ops", ""), |
| 48 | ("/admin/backups", ""), |
| 49 | ("/admin/backups/scheduled", ""), |
| 50 | ("/admin/files", ""), |
| 51 | ("/admin/files/runner", ""), |
| 52 | ("/admin/reconciles", ""), |
| 53 | ("/admin/objects", ""), |
| 54 | ("/admin/objects/runner", ""), |
| 55 | ("/admin/collections", ""), |
| 56 | ("/admin/collections/contacts", ""), |
| 57 | ("/admin/collections/contacts/records", ""), |
| 58 | ("/admin/collections/contacts/records/1", ""), |
| 59 | ("/admin/collections/contacts/changes", ""), |
| 60 | ("/admin/collections/contacts/records/1/changes", ""), |
| 61 | ("/admin/schemas", ""), |
| 62 | ("/admin/schemas/contacts", ""), |
| 63 | ("/admin/identity/accounts", ""), |
| 64 | ("/admin/identity/users", ""), |
| 65 | ("/admin/identity/sessions", ""), |
| 66 | ("/daemon/status", ""), |
| 67 | ("/daemon/scheduler/tasks", ""), |
| 68 | ("/daemon/queue/messages", ""), |
| 69 | ("/identity", ""), |
| 70 | ("/identity/accounts", ""), |
| 71 | ("/identity/users", ""), |
| 72 | ("/identity/users/alice", ""), |
| 73 | ("/identity/users/alice/api-keys", ""), |
| 74 | ("/identity/sessions", ""), |
| 75 | ("/permissions/policy", ""), |
| 76 | ("/permissions/status", ""), |
| 77 | ("/permissions/audit", ""), |
| 78 | ("/permissions/unshipped", ""), |
| 79 | ("/events", ""), |
| 80 | ("/events/deliveries", ""), |
| 81 | ("/events/subscriptions", ""), |
| 82 | ("/packages", ""), |
| 83 | ("/packages/app-counter", ""), |
| 84 | ("/packages/app-counter/changes", ""), |
| 85 | ("/objects", ""), |
| 86 | ("/objects/runner", ""), |
| 87 | ("/objects/runner", "source=true&format=json"), |
| 88 | ("/objects/runner", "state=true"), |
| 89 | ("/objects/runner", "versions=true"), |
| 90 | ("/objects/runner", "logs=true&format=json"), |
| 91 | ("/objects/runner", "metadata=true"), |
| 92 | ("/objects/runner", "files=true"), |
| 93 | ("/objects/runner", "changes=true"), |
| 94 | ("/objects/runner", "source_changes=true"), |
| 95 | ("/collections", ""), |
| 96 | ("/collections/contacts", ""), |
| 97 | ("/collections/contacts/records", ""), |
| 98 | ("/collections/contacts/records/1", ""), |
| 99 | ("/collections/contacts/changes", ""), |
| 100 | ("/schemas", ""), |
| 101 | ("/schemas/contacts", ""), |
| 102 | ("/api/search", "q=Ada"), |
| 103 | ("/api/schema/contacts", ""), |
| 104 | ("/api/flags", ""), |
| 105 | ("/prefs", ""), |
| 106 | ] |
| 107 | |
| 108 | |
| 109 | def _policy_file(data_dir): |
| 110 | return data_dir / "permissions" / "policy.json" |
| 111 | |
| 112 | |
| 113 | def _drop_policy_cache(): |
| 114 | object_permission_store._POLICY_CACHE.clear() |
| 115 | |
| 116 | |
| 117 | def _break_invalid_json(data_dir): |
| 118 | _policy_file(data_dir).write_text("{ broken") |
| 119 | |
| 120 | |
| 121 | def _break_access_mode(data_dir): |
| 122 | _policy_file(data_dir).write_text(json.dumps({"access_mode": "nonsense", "rules": []})) |
| 123 | |
| 124 | |
| 125 | def _break_policy_directory(data_dir): |
| 126 | path = _policy_file(data_dir) |
| 127 | path.unlink() |
| 128 | path.mkdir() |
| 129 | |
| 130 | |
| 131 | def _break_policy_chmod(data_dir): |
| 132 | if os.geteuid() == 0: |
| 133 | pytest.skip("chmod 000 does not stop root") |
| 134 | _policy_file(data_dir).chmod(0) |
| 135 | |
| 136 | |
| 137 | def _directory_in_place(name): |
| 138 | def _break(data_dir): |
| 139 | path = data_dir / "identity" / name |
| 140 | if path.exists(): |
| 141 | path.unlink() |
| 142 | path.mkdir(parents=True, exist_ok=True) |
| 143 | |
| 144 | return _break |
| 145 | |
| 146 | |
| 147 | STATES = { |
| 148 | "healthy": None, |
| 149 | "policy_invalid_json": _break_invalid_json, |
| 150 | "policy_bad_access_mode": _break_access_mode, |
| 151 | "policy_is_directory": _break_policy_directory, |
| 152 | "policy_chmod_000": _break_policy_chmod, |
| 153 | "users_unreadable": _directory_in_place("users.tsv"), |
| 154 | "sessions_unreadable": _directory_in_place("sessions.tsv"), |
| 155 | "api_keys_unreadable": _directory_in_place("api_keys.tsv"), |
| 156 | } |
| 157 | |
| 158 | |
| 159 | @pytest.fixture |
| 160 | def box(tmp_path, monkeypatch): |
| 161 | data_dir = tmp_path / "data" |
| 162 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir)) |
| 163 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects")) |
| 164 | for name in ( |
| 165 | object_server.PERMISSION_AUDIT_ENV, |
| 166 | object_server.PERMISSION_TRUST_HEADERS_ENV, |
| 167 | object_server.SESSION_LOGIN_ENV, |
| 168 | object_server.SESSION_LOGIN_TOKEN_ENV, |
| 169 | object_server.PASSWORD_LOGIN_ENV, |
| 170 | object_server.REQUIRE_KNOWN_IDENTITY_USERS_ENV, |
| 171 | "DBBASIC_IDENTITY_VERIFY_URL", |
| 172 | ): |
| 173 | monkeypatch.delenv(name, raising=False) |
| 174 | monkeypatch.setenv(object_server.ADMIN_TOKEN_ENV, TOKEN) |
| 175 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 176 | object_permission_store.replace_policy(POLICY, base_dir=data_dir) |
| 177 | schema = data_dir / "schemas" / "contacts.json" |
| 178 | schema.parent.mkdir(parents=True, exist_ok=True) |
| 179 | schema.write_text( |
| 180 | json.dumps({"fields": [{"name": "id"}, {"name": "name"}], "search": {"fields": ["name"]}}) |
| 181 | ) |
| 182 | write_records(data_dir, "contacts", "id\tname\n1\tAda\n") |
| 183 | write_source( |
| 184 | tmp_path / "objects" / "runner.py", |
| 185 | "def GET(request):\n return {'ran': True}\n", |
| 186 | ) |
| 187 | object_identity.create_user({"user_id": "alice", "email": "alice@example.org"}, base_dir=data_dir) |
| 188 | created = object_identity.create_session({"user_id": "alice"}, base_dir=data_dir) |
| 189 | _drop_policy_cache() |
| 190 | return data_dir, created["token"] |
| 191 | |
| 192 | |
| 193 | def _sweep(headers): |
| 194 | results = {} |
| 195 | for path, query in ROUTES: |
| 196 | try: |
| 197 | status, _, body = raw_request(path, query_string=query, headers=headers) |
| 198 | except Exception as exc: # an unhandled error is a 500 under any ASGI server |
| 199 | status, body = 500, f"{type(exc).__name__}: {exc}".encode() |
| 200 | results[(path, query)] = (status, body) |
| 201 | return results |
| 202 | |
| 203 | |
| 204 | def _is_503_with_detail(status, body): |
| 205 | if status != 503: |
| 206 | return False |
| 207 | try: |
| 208 | return bool(json.loads(body).get("error_detail")) |
| 209 | except ValueError: |
| 210 | return False |
| 211 | |
| 212 | |
| 213 | @pytest.mark.parametrize("state", list(STATES)) |
| 214 | def test_admin_token_gets_no_500_from_any_admin_route(box, state): |
| 215 | data_dir, _ = box |
| 216 | breaker = STATES[state] |
| 217 | if breaker is not None: |
| 218 | breaker(data_dir) |
| 219 | _drop_policy_cache() |
| 220 | results = _sweep(ADMIN) |
| 221 | table = os.environ.get("SWEEP_TABLE") |
| 222 | if table: |
| 223 | with open(table, "a") as handle: |
| 224 | for (path, query), (status, _) in results.items(): |
| 225 | handle.write(f"{state}\t{path}?{query}\t{status}\n") |
| 226 | crashed = { |
| 227 | f"{key[0]}?{key[1]}": (status, body[:90].decode("utf-8", "replace")) |
| 228 | for key, (status, body) in results.items() |
| 229 | if status >= 500 and not _is_503_with_detail(status, body) |
| 230 | } |
| 231 | assert not crashed, crashed |
| 232 | if state == "healthy": |
| 233 | not_ok = {key: status for key, (status, _) in results.items() if status != 200} |
| 234 | assert not not_ok, not_ok |
| 235 | else: |
| 236 | for key, (status, body) in results.items(): |
| 237 | assert status in (200, 400, 404, 503), (key, status, body[:200]) |
| 238 | |
| 239 | |
| 240 | def test_admin_status_reports_a_broken_policy_instead_of_crashing(box): |
| 241 | data_dir, _ = box |
| 242 | _break_invalid_json(data_dir) |
| 243 | _drop_policy_cache() |
| 244 | status, _, payload = request("/admin/status", headers=ADMIN) |
| 245 | assert status == 200, payload |
| 246 | assert payload["permissions"]["mode"] == "enforced" |
| 247 | assert any("Permission policy file is invalid" in a for a in payload["alerts"]), payload["alerts"] |
| 248 | assert payload["permissions"]["policy"]["valid"] is False |
| 249 | assert payload["inventory"]["objects"] >= 1 |
| 250 | |
| 251 | |
| 252 | def test_policy_get_returns_a_repairable_body_for_admin_only(box): |
| 253 | data_dir, alice = box |
| 254 | _break_invalid_json(data_dir) |
| 255 | _drop_policy_cache() |
| 256 | status, _, payload = request("/permissions/policy", headers=ADMIN) |
| 257 | assert status == 200, payload |
| 258 | assert payload["status"] == "ok" |
| 259 | assert payload["policy"] is None |
| 260 | assert "invalid JSON" in payload["error"] |
| 261 | assert payload["raw"] == "{ broken" |
| 262 | assert payload["raw_truncated"] is False |
| 263 | # the repair works, and GET then returns the policy with no error |
| 264 | status, _, repaired = request( |
| 265 | "/permissions/policy", method="PUT", body=json.dumps(POLICY).encode(), headers=ADMIN |
| 266 | ) |
| 267 | assert status == 200, repaired |
| 268 | status, _, payload = request("/permissions/policy", headers=ADMIN) |
| 269 | assert payload["policy"]["access_mode"] == "role_based" |
| 270 | assert "error" not in payload and "raw" not in payload |
| 271 | # non-admin: never the file's text or the error |
| 272 | _break_invalid_json(data_dir) |
| 273 | _drop_policy_cache() |
| 274 | status, _, payload = request("/permissions/policy", headers=[("authorization", f"Bearer {alice}")]) |
| 275 | assert status in (401, 403, 503) |
| 276 | assert "{ broken" not in json.dumps(payload) |
| 277 | assert "raw" not in payload and "error_detail" not in payload |
| 278 | status, _, payload = request( |
| 279 | "/collections/contacts/records", headers=[("authorization", f"Bearer {alice}")] |
| 280 | ) |
| 281 | assert status == 503 and "error_detail" not in payload |
| 282 | assert payload["code"] == "permission_policy_unavailable" |
| 283 | status, _, payload = request("/permissions/policy") |
| 284 | assert status in (401, 403, 503) and "raw" not in payload |
| 285 | |
| 286 | |
| 287 | def test_policy_raw_is_bounded_and_omitted_when_unreadable(box): |
| 288 | data_dir, _ = box |
| 289 | _policy_file(data_dir).write_text("{" + "x" * (70 * 1024)) |
| 290 | _drop_policy_cache() |
| 291 | status, _, payload = request("/permissions/policy", headers=ADMIN) |
| 292 | assert status == 200 and payload["policy"] is None |
| 293 | assert payload["raw_truncated"] is True and len(payload["raw"]) == 64 * 1024 |
| 294 | _break_policy_directory(data_dir) |
| 295 | _drop_policy_cache() |
| 296 | status, _, payload = request("/permissions/policy", headers=ADMIN) |
| 297 | assert status == 200 and payload["policy"] is None and payload["error"] |
| 298 | assert "raw" not in payload |
| 299 | |
| 300 | |
| 301 | @pytest.mark.parametrize("state", [name for name in STATES if name != "healthy"]) |
| 302 | def test_non_admin_never_sees_detail_or_a_500_in_a_broken_state(box, state): |
| 303 | data_dir, alice = box |
| 304 | STATES[state](data_dir) |
| 305 | _drop_policy_cache() |
| 306 | for headers in ([], [("authorization", f"Bearer {alice}")]): |
| 307 | for key, (status, body) in _sweep(headers).items(): |
| 308 | assert status in (200, 401, 403, 404, 503), (state, key, status, body[:120]) |
| 309 | text = body.decode("utf-8", "replace") |
| 310 | assert "error_detail" not in text and '"raw"' not in text, (state, key, text[:200]) |
| 311 | assert str(data_dir) not in text, (state, key) |
| 312 | |
| 313 | |
| 314 | def test_identity_file_unreadable_is_a_503_with_detail_for_the_admin(box): |
| 315 | data_dir, _ = box |
| 316 | _directory_in_place("users.tsv")(data_dir) |
| 317 | status, _, payload = request("/identity/users", headers=ADMIN) |
| 318 | assert status == 503 and payload["code"] == "identity_store_unavailable" |
| 319 | assert "could not be read" in payload["error_detail"] |