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_enforcement_fail_closed.py · 41.0 KB · 962 lines
| 1 | """A requested enforcement stays enforced when the box drifts after it started. |
| 2 | |
| 3 | DBBASIC_ENABLE_PERMISSION_ENFORCEMENT=true used to be a request that a |
| 4 | readiness gate could quietly decline on every request: the gate re-read the |
| 5 | identity store and the policy each time, and whenever one of its checks |
| 6 | failed the request ran in shadow mode -- decided, logged, and served anyway. |
| 7 | A box that started healthy went open the moment its last session expired, |
| 8 | its last user was disabled, its users file became unreadable, its policy |
| 9 | file was corrupted or set to `password` mode. Collection reads returned |
| 10 | every row to anonymous callers and objects with no grant executed. |
| 11 | |
| 12 | These tests start a healthy enforced box, break one thing, and check that a |
| 13 | non-admin request still gets only what the policy grants. Each has a |
| 14 | lockout twin: the admin token still gets in, /health still answers, and the |
| 15 | owner can repair the state over HTTP where that is possible at all. |
| 16 | """ |
| 17 | from __future__ import annotations |
| 18 | |
| 19 | import asyncio |
| 20 | import json |
| 21 | import os |
| 22 | |
| 23 | import pytest |
| 24 | |
| 25 | import object_identity |
| 26 | import object_permission_audit |
| 27 | import object_permission_store |
| 28 | import object_permissions |
| 29 | import object_server |
| 30 | import object_user_files |
| 31 | from test_object_server import raw_request, request, write_records, write_source |
| 32 | |
| 33 | TOKEN = "e" * 32 |
| 34 | ADMIN = [("authorization", f"Token {TOKEN}")] |
| 35 | |
| 36 | POLICY = { |
| 37 | "access_mode": "role_based", |
| 38 | "rules": [ |
| 39 | { |
| 40 | "effect": "allow", |
| 41 | "principal": "registered", |
| 42 | "actions": ["read"], |
| 43 | "collection": "contacts", |
| 44 | "row_filter": {"owner_id": "$user_id"}, |
| 45 | "reason": "own contacts", |
| 46 | }, |
| 47 | { |
| 48 | "effect": "allow", |
| 49 | "principal": "registered", |
| 50 | "actions": ["read"], |
| 51 | "collection": "files", |
| 52 | "row_filter": {"owner_id": "$user_id"}, |
| 53 | "reason": "own files", |
| 54 | }, |
| 55 | ], |
| 56 | } |
| 57 | |
| 58 | |
| 59 | def run_lifespan(): |
| 60 | sent = [] |
| 61 | inbox = [{"type": "lifespan.startup"}, {"type": "lifespan.shutdown"}] |
| 62 | |
| 63 | async def receive(): |
| 64 | return inbox.pop(0) |
| 65 | |
| 66 | async def send(message): |
| 67 | sent.append(message) |
| 68 | |
| 69 | asyncio.run(object_server._handle_lifespan(receive, send)) |
| 70 | return sent[0] |
| 71 | |
| 72 | |
| 73 | class Box: |
| 74 | def __init__(self, data_dir, alice_token, alice_session_id, file_id): |
| 75 | self.data_dir = data_dir |
| 76 | self.alice_token = alice_token |
| 77 | self.alice_session_id = alice_session_id |
| 78 | self.file_id = file_id |
| 79 | |
| 80 | @property |
| 81 | def alice(self): |
| 82 | return [("authorization", f"Bearer {self.alice_token}")] |
| 83 | |
| 84 | |
| 85 | def _write_schema(data_dir, name, payload): |
| 86 | path = data_dir / "schemas" / f"{name}.json" |
| 87 | path.parent.mkdir(parents=True, exist_ok=True) |
| 88 | path.write_text(json.dumps(payload)) |
| 89 | |
| 90 | |
| 91 | @pytest.fixture |
| 92 | def box(tmp_path, monkeypatch): |
| 93 | """A healthy enforced box whose only non-admin sign-in path is one live session.""" |
| 94 | data_dir = tmp_path / "data" |
| 95 | monkeypatch.setenv(object_server.DATA_DIR_ENV, str(data_dir)) |
| 96 | monkeypatch.setenv("DBBASIC_OBJECTS_DIR", str(tmp_path / "objects")) |
| 97 | for name in ( |
| 98 | object_server.PERMISSION_AUDIT_ENV, |
| 99 | object_server.ALLOW_BLOCKED_ENFORCEMENT_START_ENV, |
| 100 | object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, |
| 101 | object_server.PERMISSION_TRUST_HEADERS_ENV, |
| 102 | object_server.SESSION_LOGIN_ENV, |
| 103 | object_server.SESSION_LOGIN_TOKEN_ENV, |
| 104 | object_server.PASSWORD_LOGIN_ENV, |
| 105 | object_server.REQUIRE_KNOWN_IDENTITY_USERS_ENV, |
| 106 | "DBBASIC_IDENTITY_VERIFY_URL", |
| 107 | ): |
| 108 | monkeypatch.delenv(name, raising=False) |
| 109 | monkeypatch.setenv(object_server.ADMIN_TOKEN_ENV, TOKEN) |
| 110 | monkeypatch.setenv(object_server.PERMISSION_ENFORCEMENT_ENV, "true") |
| 111 | monkeypatch.setenv(object_server.USER_FILES_ENABLED_ENV, "true") |
| 112 | |
| 113 | object_permission_store.replace_policy(POLICY, base_dir=data_dir) |
| 114 | _write_schema( |
| 115 | data_dir, |
| 116 | "contacts", |
| 117 | { |
| 118 | "fields": [{"name": "id"}, {"name": "name"}, {"name": "owner_id"}], |
| 119 | "search": {"fields": ["name"]}, |
| 120 | }, |
| 121 | ) |
| 122 | write_records( |
| 123 | data_dir, |
| 124 | "contacts", |
| 125 | "id\tname\towner_id\n1\tAlice note\talice\n2\tBob note\tbob\n", |
| 126 | ) |
| 127 | write_records( |
| 128 | data_dir, |
| 129 | "files", |
| 130 | "id\tfilename\tcontent_type\tsize\towner_id\nf1\tbob.txt\ttext/plain\t6\tbob\n", |
| 131 | ) |
| 132 | object_user_files.save_file("bob", "f1", b"bobbin", base_dir=data_dir) |
| 133 | write_source( |
| 134 | tmp_path / "objects" / "secret" / "runner.py", |
| 135 | "def GET(request):\n return {'ran': True}\n", |
| 136 | ) |
| 137 | |
| 138 | object_identity.create_user({"user_id": "alice", "email": "alice@example.org"}, base_dir=data_dir) |
| 139 | created = object_identity.create_session({"user_id": "alice"}, base_dir=data_dir) |
| 140 | |
| 141 | assert run_lifespan()["type"] == "lifespan.startup.complete" |
| 142 | b = Box(data_dir, created["token"], created["session"]["session_id"], "f1") |
| 143 | # baseline: healthy, enforced, fenced |
| 144 | assert object_server._permission_enforcement_enabled() is True |
| 145 | _assert_fenced(b) |
| 146 | status, _, payload = request("/collections/contacts/records", headers=b.alice) |
| 147 | assert status == 200 and [r["id"] for r in payload["records"]] == ["1"] |
| 148 | return b |
| 149 | |
| 150 | |
| 151 | SECRETS = (b"Alice note", b"Bob note", b"bobbin", b'"ran"') |
| 152 | REFUSED = (401, 403, 503) |
| 153 | |
| 154 | |
| 155 | def _no_secret(body): |
| 156 | assert not any(secret in body for secret in SECRETS), body |
| 157 | |
| 158 | |
| 159 | def _assert_fenced(b, *, check_audit=True): |
| 160 | """Anonymous gets nothing the policy does not grant, on every surface. |
| 161 | |
| 162 | Asserts on the data (no private row, file byte or object result in any |
| 163 | body) and on the exact refusal, and that a single-record answer does not |
| 164 | tell an existing id from a missing one. |
| 165 | """ |
| 166 | status, _, body = raw_request("/collections/contacts/records") |
| 167 | _no_secret(body) |
| 168 | assert status in REFUSED, (status, body) |
| 169 | existing = raw_request("/collections/contacts/records/2") |
| 170 | missing = raw_request("/collections/contacts/records/999") |
| 171 | _no_secret(existing[2]) |
| 172 | assert existing[0] in REFUSED, existing |
| 173 | assert (existing[0], existing[2]) == (missing[0], missing[2]) |
| 174 | status, _, body = raw_request("/objects/secret_runner") |
| 175 | _no_secret(body) |
| 176 | assert status in REFUSED, (status, body) |
| 177 | existing = raw_request(f"/api/files/{b.file_id}") |
| 178 | missing = raw_request("/api/files/nosuchfile") |
| 179 | _no_secret(existing[2]) |
| 180 | assert existing[0] in REFUSED, existing |
| 181 | assert (existing[0], existing[2]) == (missing[0], missing[2]) |
| 182 | status, _, body = raw_request("/api/search", query_string="q=note") |
| 183 | _no_secret(body) |
| 184 | assert status in REFUSED or json.loads(body).get("total_count") == 0, (status, body) |
| 185 | anonymous = object_permissions.PermissionSubject.anonymous() |
| 186 | assert object_server._ws_can_subscribe(anonymous, "contacts") is False |
| 187 | if check_audit: |
| 188 | entries = object_permission_audit.get_permission_audit(b.data_dir) |
| 189 | assert entries, "enforced requests are audited" |
| 190 | last = entries[-1] |
| 191 | assert last["enforced"] is True |
| 192 | assert "enforcement_blocked" not in last |
| 193 | |
| 194 | |
| 195 | def _assert_admin_gets_in(b): |
| 196 | status, _, payload = request("/health") |
| 197 | assert status == 200, payload |
| 198 | status, _, payload = request("/permissions/status", headers=ADMIN) |
| 199 | assert status == 200, payload |
| 200 | status, _, payload = request("/objects/secret_runner", headers=ADMIN) |
| 201 | assert status == 200 and payload == {"ran": True}, (status, payload) |
| 202 | |
| 203 | |
| 204 | |
| 205 | |
| 206 | def _expire_every_session(monkeypatch): |
| 207 | future = object_identity._now() + object_identity.timedelta(days=400) |
| 208 | monkeypatch.setattr(object_identity, "_now", lambda: future) |
| 209 | |
| 210 | |
| 211 | # ---- 1. the only session expires ----------------------------------------------------- |
| 212 | |
| 213 | |
| 214 | def test_drift_last_session_expires_stays_enforced(box, monkeypatch): |
| 215 | _expire_every_session(monkeypatch) |
| 216 | _assert_fenced(box) |
| 217 | |
| 218 | |
| 219 | def test_last_session_expired_admin_token_still_works_and_can_mint_a_session(box, monkeypatch): |
| 220 | _expire_every_session(monkeypatch) |
| 221 | _assert_admin_gets_in(box) |
| 222 | status, _, created = request( |
| 223 | "/identity/sessions", |
| 224 | method="POST", |
| 225 | body=json.dumps({"user_id": "alice", "ttl_seconds": 3600 * 24 * 800}).encode(), |
| 226 | headers=ADMIN, |
| 227 | ) |
| 228 | assert status == 201, created |
| 229 | status, _, payload = request( |
| 230 | "/collections/contacts/records", |
| 231 | headers=[("authorization", f"Bearer {created['token']}")], |
| 232 | ) |
| 233 | assert status == 200 and [r["id"] for r in payload["records"]] == ["1"] |
| 234 | |
| 235 | |
| 236 | # ---- 2. the only session is revoked -------------------------------------------------- |
| 237 | |
| 238 | |
| 239 | def test_drift_last_session_revoked_stays_enforced(box): |
| 240 | object_identity.revoke_session(box.alice_session_id, base_dir=box.data_dir) |
| 241 | _assert_fenced(box) |
| 242 | |
| 243 | |
| 244 | # ---- 3. session login is the only path and its last user is disabled ------------------ |
| 245 | |
| 246 | |
| 247 | @pytest.fixture |
| 248 | def session_login_box(box, monkeypatch): |
| 249 | monkeypatch.setenv(object_server.SESSION_LOGIN_ENV, "true") |
| 250 | monkeypatch.setenv(object_server.SESSION_LOGIN_TOKEN_ENV, "s" * 32) |
| 251 | object_identity.revoke_session(box.alice_session_id, base_dir=box.data_dir) |
| 252 | readiness = object_server.object_permission_status.enforcement_readiness( |
| 253 | base_dir=box.data_dir, permissions=object_server._permission_readiness_inputs() |
| 254 | ) |
| 255 | assert readiness["can_enable_enforcement"] is True # session login is the path |
| 256 | object_identity.set_user_status("alice", "disabled", base_dir=box.data_dir) |
| 257 | return box |
| 258 | |
| 259 | |
| 260 | def test_drift_last_user_disabled_with_session_login_stays_enforced(session_login_box): |
| 261 | _assert_fenced(session_login_box) |
| 262 | |
| 263 | |
| 264 | def test_last_user_disabled_admin_token_still_works_and_can_re_enable(session_login_box): |
| 265 | _assert_admin_gets_in(session_login_box) |
| 266 | object_identity.set_user_status("alice", "active", base_dir=session_login_box.data_dir) |
| 267 | readiness = object_server.object_permission_status.enforcement_readiness( |
| 268 | base_dir=session_login_box.data_dir, |
| 269 | permissions=object_server._permission_readiness_inputs(), |
| 270 | ) |
| 271 | assert readiness["can_enable_enforcement"] is True |
| 272 | |
| 273 | |
| 274 | # ---- 4. the identity store becomes unreadable -------------------------------------------- |
| 275 | |
| 276 | |
| 277 | def _break_users_file(data_dir): |
| 278 | path = object_identity.users_path(data_dir) |
| 279 | path.rename(path.with_name(path.name + ".saved")) |
| 280 | path.mkdir() |
| 281 | |
| 282 | |
| 283 | def _repair_users_file(data_dir): |
| 284 | """Put the file back as it was. (Re-creating alice with create_user is refused |
| 285 | while her session is still signed in: it would hand the session on.)""" |
| 286 | path = object_identity.users_path(data_dir) |
| 287 | path.rmdir() |
| 288 | path.with_name(path.name + ".saved").rename(path) |
| 289 | |
| 290 | |
| 291 | def test_drift_identity_store_unreadable_anonymous_gets_policy(box): |
| 292 | _break_users_file(box.data_dir) |
| 293 | _assert_fenced(box) |
| 294 | |
| 295 | |
| 296 | def test_drift_identity_store_unreadable_signed_in_user_gets_503(box): |
| 297 | _break_users_file(box.data_dir) |
| 298 | status, headers, payload = request("/collections/contacts/records", headers=box.alice) |
| 299 | assert status == 503, (status, payload) |
| 300 | assert payload["code"] == "identity_store_unavailable" |
| 301 | assert headers[b"retry-after"] == str(object_server.IDENTITY_UNAVAILABLE_RETRY_AFTER_SECONDS).encode() |
| 302 | |
| 303 | |
| 304 | @pytest.mark.skipif(os.geteuid() == 0, reason="root reads a chmod 000 file") |
| 305 | def test_drift_identity_store_chmod_000_stays_enforced(box): |
| 306 | path = object_identity.users_path(box.data_dir) |
| 307 | path.chmod(0) |
| 308 | try: |
| 309 | _assert_fenced(box) |
| 310 | finally: |
| 311 | path.chmod(0o600) |
| 312 | |
| 313 | |
| 314 | def test_identity_store_unreadable_admin_token_still_works_and_box_recovers(box): |
| 315 | _break_users_file(box.data_dir) |
| 316 | _assert_admin_gets_in(box) |
| 317 | status, _, payload = request("/permissions/status", headers=ADMIN) |
| 318 | assert payload["identity"]["valid"] is False and payload["identity"]["error"] |
| 319 | _repair_users_file(box.data_dir) |
| 320 | status, _, payload = request("/collections/contacts/records", headers=box.alice) |
| 321 | assert status == 200 and [r["id"] for r in payload["records"]] == ["1"] |
| 322 | |
| 323 | |
| 324 | # ---- 5-7. the policy file becomes invalid or unreadable ---------------------------------- |
| 325 | |
| 326 | |
| 327 | def _corrupt_policy(data_dir, text="{not json"): |
| 328 | object_permission_store.policy_path(data_dir).write_text(text) |
| 329 | |
| 330 | |
| 331 | def test_drift_policy_invalid_json_stays_enforced_on_object_routes(box): |
| 332 | _corrupt_policy(box.data_dir) |
| 333 | status, _, payload = request("/objects/secret_runner") |
| 334 | assert status == 503 and payload != {"ran": True}, (status, payload) |
| 335 | assert payload["code"] == "permission_policy_unavailable" |
| 336 | assert "JSON" not in payload["error"] # no parse error for strangers |
| 337 | |
| 338 | |
| 339 | def test_drift_policy_invalid_json_stays_enforced_on_collection_routes(box): |
| 340 | _corrupt_policy(box.data_dir) |
| 341 | _assert_fenced(box, check_audit=False) |
| 342 | status, _, payload = request("/api/search", query_string="q=note") |
| 343 | assert status == 503 and payload["code"] == "permission_policy_unavailable", payload |
| 344 | status, _, payload = request("/collections/contacts/records", headers=box.alice) |
| 345 | assert status == 503 and payload["code"] == "permission_policy_unavailable", payload |
| 346 | assert "JSON" not in payload["error"] |
| 347 | |
| 348 | |
| 349 | def test_drift_policy_invalid_access_mode_stays_enforced(box): |
| 350 | _corrupt_policy(box.data_dir, json.dumps({"access_mode": "bogus", "rules": []})) |
| 351 | _assert_fenced(box, check_audit=False) |
| 352 | status, _, payload = request("/objects/secret_runner") |
| 353 | assert status == 503 and payload["code"] == "permission_policy_unavailable", payload |
| 354 | |
| 355 | |
| 356 | @pytest.mark.skipif(os.geteuid() == 0, reason="root reads a chmod 000 file") |
| 357 | def test_drift_policy_unreadable_oserror_answers_503_not_500(box): |
| 358 | path = object_permission_store.policy_path(box.data_dir) |
| 359 | path.chmod(0) |
| 360 | try: |
| 361 | status, _, payload = request("/objects/secret_runner") |
| 362 | assert status == 503 and payload["code"] == "permission_policy_unavailable", payload |
| 363 | status, _, payload = request("/collections/contacts/records") |
| 364 | assert status == 503, payload |
| 365 | finally: |
| 366 | path.chmod(0o600) |
| 367 | |
| 368 | |
| 369 | def test_invalid_policy_admin_token_still_works_and_repairs_with_put(box): |
| 370 | _corrupt_policy(box.data_dir) |
| 371 | _assert_admin_gets_in(box) |
| 372 | status, _, payload = request("/permissions/status", headers=ADMIN) |
| 373 | assert payload["policy"]["valid"] is False and "JSON" in payload["policy"]["error"] |
| 374 | status, _, payload = request( |
| 375 | "/permissions/policy", method="PUT", body=json.dumps(POLICY).encode(), headers=ADMIN |
| 376 | ) |
| 377 | assert status == 200, payload |
| 378 | status, _, payload = request("/collections/contacts/records", headers=box.alice) |
| 379 | assert status == 200 and [r["id"] for r in payload["records"]] == ["1"] |
| 380 | status, _, _ = request("/objects/secret_runner") |
| 381 | assert status == 403 |
| 382 | |
| 383 | |
| 384 | # ---- 8. the policy is switched to password mode -------------------------------------------- |
| 385 | |
| 386 | |
| 387 | def test_drift_policy_switched_to_password_mode_stays_enforced(box): |
| 388 | status, _, payload = request( |
| 389 | "/permissions/policy", |
| 390 | method="PUT", |
| 391 | body=json.dumps({**POLICY, "access_mode": "password"}).encode(), |
| 392 | headers=ADMIN, |
| 393 | ) |
| 394 | assert status == 200, payload |
| 395 | _assert_fenced(box) |
| 396 | status, _, payload = request("/objects/secret_runner") |
| 397 | assert status == 401, payload |
| 398 | |
| 399 | |
| 400 | def test_password_mode_admin_token_still_works_and_switches_back(box): |
| 401 | request( |
| 402 | "/permissions/policy", |
| 403 | method="PUT", |
| 404 | body=json.dumps({**POLICY, "access_mode": "password"}).encode(), |
| 405 | headers=ADMIN, |
| 406 | ) |
| 407 | _assert_admin_gets_in(box) |
| 408 | status, _, _ = request( |
| 409 | "/permissions/policy", method="PUT", body=json.dumps(POLICY).encode(), headers=ADMIN |
| 410 | ) |
| 411 | assert status == 200 |
| 412 | status, _, payload = request("/collections/contacts/records", headers=box.alice) |
| 413 | assert status == 200 and [r["id"] for r in payload["records"]] == ["1"] |
| 414 | |
| 415 | |
| 416 | # ---- 9. the admin token is unset ------------------------------------------------------ |
| 417 | |
| 418 | |
| 419 | def test_drift_admin_token_removed_from_env_stays_enforced(box, monkeypatch): |
| 420 | monkeypatch.delenv(object_server.ADMIN_TOKEN_ENV) |
| 421 | _assert_fenced(box) |
| 422 | status, _, payload = request("/permissions/status", headers=ADMIN) |
| 423 | assert status == 403, payload |
| 424 | |
| 425 | |
| 426 | def test_drift_admin_token_unset_at_start_with_the_override_starts_enforced(box, monkeypatch): |
| 427 | monkeypatch.delenv(object_server.ADMIN_TOKEN_ENV) |
| 428 | monkeypatch.setenv(object_server.ALLOW_BLOCKED_ENFORCEMENT_START_ENV, "true") |
| 429 | assert run_lifespan()["type"] == "lifespan.startup.complete" |
| 430 | _assert_fenced(box) |
| 431 | |
| 432 | |
| 433 | # ---- 10. the other surfaces, one representative drift -------------------------------------- |
| 434 | |
| 435 | |
| 436 | def test_drift_search_record_detail_files_and_websocket_stay_enforced(box, monkeypatch): |
| 437 | _expire_every_session(monkeypatch) |
| 438 | status, _, payload = request("/api/search", query_string="q=note") |
| 439 | assert status != 200 or payload["total_count"] == 0, payload |
| 440 | status, _, payload = request("/collections/contacts/records/2") |
| 441 | assert status != 200, payload |
| 442 | status, _, body = raw_request(f"/api/files/{box.file_id}") |
| 443 | assert status != 200 and body != b"bobbin" |
| 444 | alice = object_permissions.PermissionSubject(user_id="alice") |
| 445 | assert object_server._ws_can_subscribe(alice, "secret_notes") is False |
| 446 | assert object_server._ws_can_subscribe(alice, "contacts") is True |
| 447 | |
| 448 | |
| 449 | # ---- the mode word ----------------------------------------------------------------------- |
| 450 | |
| 451 | |
| 452 | @pytest.mark.parametrize( |
| 453 | ("enforce", "audit", "mode"), |
| 454 | [(None, None, "off"), (None, "true", "audit"), ("true", None, "enforced"), ("true", "true", "enforced")], |
| 455 | ) |
| 456 | def test_status_mode_field_off_audit_enforced(box, monkeypatch, enforce, audit, mode): |
| 457 | for name, value in ((object_server.PERMISSION_ENFORCEMENT_ENV, enforce), |
| 458 | (object_server.PERMISSION_AUDIT_ENV, audit)): |
| 459 | if value is None: |
| 460 | monkeypatch.delenv(name, raising=False) |
| 461 | else: |
| 462 | monkeypatch.setenv(name, value) |
| 463 | _, _, status = request("/permissions/status", headers=ADMIN) |
| 464 | assert status["permissions"]["mode"] == mode |
| 465 | _, _, identity = request("/identity") |
| 466 | assert identity["permissions"]["mode"] == mode |
| 467 | _, _, admin = request("/admin/status", headers=ADMIN) |
| 468 | assert admin["permissions"]["mode"] == mode |
| 469 | assert admin["capabilities"]["permission_enforcement"]["mode"] == mode |
| 470 | _, _, health = request("/health", query_string="capacity=true", headers=ADMIN) |
| 471 | assert health["config"]["permission_mode"] == mode |
| 472 | |
| 473 | |
| 474 | # ---- readiness is diagnostics: watched, never a switch ------------------------------------- |
| 475 | |
| 476 | |
| 477 | def test_enforcement_does_not_read_the_identity_store_to_decide(box, monkeypatch): |
| 478 | def boom(**_kwargs): |
| 479 | raise AssertionError("readiness must not run per request") |
| 480 | |
| 481 | monkeypatch.setattr(object_server.object_permission_status, "enforcement_readiness", boom) |
| 482 | monkeypatch.setattr(object_server, "_permission_readiness_watch", lambda: None) |
| 483 | assert object_server._permission_enforcement_enabled() is True |
| 484 | status, _, _ = request("/collections/contacts/records") |
| 485 | assert status in (401, 403) |
| 486 | status, _, payload = request("/collections/contacts/records", headers=box.alice) |
| 487 | assert status == 200 and [r["id"] for r in payload["records"]] == ["1"] |
| 488 | |
| 489 | |
| 490 | def test_requests_run_the_readiness_watch(box, monkeypatch): |
| 491 | calls = [] |
| 492 | monkeypatch.setattr(object_server, "_permission_readiness_watch", lambda: calls.append(1)) |
| 493 | request("/health") |
| 494 | request("/collections/contacts/records") |
| 495 | assert len(calls) == 2 |
| 496 | |
| 497 | |
| 498 | def _readiness_rows(data_dir): |
| 499 | return [ |
| 500 | row for row in object_server.object_ops_log.read_events(base_dir=data_dir) |
| 501 | if row["kind"] == "permission_readiness" |
| 502 | ] |
| 503 | |
| 504 | |
| 505 | def test_readiness_watch_logs_once_per_transition_and_at_most_once_a_minute(box, monkeypatch, caplog, capsys): |
| 506 | import logging |
| 507 | |
| 508 | t0 = object_server.time.monotonic() |
| 509 | watch = object_server._permission_readiness_watch |
| 510 | capsys.readouterr() |
| 511 | with caplog.at_level(logging.INFO, logger="dbbasic.object_server"): |
| 512 | watch(now=t0 + 1) |
| 513 | assert _readiness_rows(box.data_dir) == [] # healthy since startup |
| 514 | |
| 515 | real_now = object_identity._now |
| 516 | _expire_every_session(monkeypatch) |
| 517 | watch(now=t0 + 2) # inside the minute: not even checked |
| 518 | assert _readiness_rows(box.data_dir) == [] |
| 519 | |
| 520 | watch(now=t0 + 70) |
| 521 | rows = _readiness_rows(box.data_dir) |
| 522 | assert len(rows) == 1 |
| 523 | assert rows[0]["mode"] == "enforced" |
| 524 | assert rows[0]["appeared"] == [object_server.object_permission_status.NO_SIGN_IN_PATH_PROBLEM] |
| 525 | errors = [r for r in caplog.records if r.levelname == "ERROR"] |
| 526 | assert len(errors) == 1 and "Permission enforcement is ON" in errors[0].getMessage() |
| 527 | assert "[dbbasic] ERROR: Permission enforcement is ON" in capsys.readouterr().err |
| 528 | |
| 529 | watch(now=t0 + 140) # same problem: no new row, no new error |
| 530 | assert len(_readiness_rows(box.data_dir)) == 1 |
| 531 | |
| 532 | monkeypatch.setattr(object_identity, "_now", real_now) |
| 533 | watch(now=t0 + 210) |
| 534 | rows = _readiness_rows(box.data_dir) |
| 535 | assert len(rows) == 2 |
| 536 | cleared = [row for row in rows if row.get("cleared")] |
| 537 | assert len(cleared) == 1 and cleared[0]["problems"] == [] |
| 538 | status, _, payload = request( |
| 539 | "/admin/ops", query_string="kind=permission_readiness", headers=ADMIN |
| 540 | ) |
| 541 | assert status == 200 and len(payload["events"]) == 2, payload |
| 542 | assert len([r for r in caplog.records if r.levelname == "ERROR"]) == 1 |
| 543 | |
| 544 | |
| 545 | def test_a_failed_first_watch_is_no_baseline_and_logs_nothing_later(box, monkeypatch, caplog): |
| 546 | """A worker that skipped the lifespan and whose first check raised kept an empty |
| 547 | baseline, then reported every existing problem as "appeared" a minute later.""" |
| 548 | import logging |
| 549 | |
| 550 | _expire_every_session(monkeypatch) # a problem that exists from the start |
| 551 | object_server._PERMISSION_READINESS_STATE.pop(str(box.data_dir), None) # no lifespan here |
| 552 | real = object_server._permission_enforcement_problems |
| 553 | calls = [] |
| 554 | |
| 555 | def flaky(): |
| 556 | calls.append(1) |
| 557 | if len(calls) == 1: |
| 558 | raise OSError("transient") |
| 559 | return real() |
| 560 | |
| 561 | monkeypatch.setattr(object_server, "_permission_enforcement_problems", flaky) |
| 562 | t0 = object_server.time.monotonic() |
| 563 | with caplog.at_level(logging.INFO, logger="dbbasic.object_server"): |
| 564 | object_server._permission_readiness_watch(now=t0) # raises inside: no baseline |
| 565 | object_server._permission_readiness_watch(now=t0 + 70) # first good check: the baseline |
| 566 | object_server._permission_readiness_watch(now=t0 + 140) # unchanged |
| 567 | assert len(calls) == 3 |
| 568 | assert _readiness_rows(box.data_dir) == [] |
| 569 | assert not [r for r in caplog.records if r.levelname == "ERROR"] |
| 570 | |
| 571 | |
| 572 | def test_admin_status_alert_names_a_runtime_problem_and_says_enforced(box, monkeypatch): |
| 573 | _expire_every_session(monkeypatch) |
| 574 | status, _, payload = request("/admin/status", headers=ADMIN) |
| 575 | assert status == 200 |
| 576 | alert = payload["alerts"][0] |
| 577 | assert alert.startswith("Permission enforcement is ON") and "No non-admin sign-in path" in alert |
| 578 | assert payload["capabilities"]["permission_enforcement"]["blocked"] is False |
| 579 | assert payload["permissions"]["mode"] == "enforced" |
| 580 | |
| 581 | |
| 582 | # ---- audit mode serves what "off" serves ---------------------------------------------------- |
| 583 | |
| 584 | |
| 585 | @pytest.mark.parametrize("audit", [None, "true"]) |
| 586 | def test_audit_mode_keeps_off_mode_admin_gates(box, monkeypatch, audit): |
| 587 | """Turning the audit log on must not change what is served. It used to skip the |
| 588 | admin gate on collection reads, record detail, search and user files.""" |
| 589 | monkeypatch.delenv(object_server.PERMISSION_ENFORCEMENT_ENV) |
| 590 | if audit: |
| 591 | monkeypatch.setenv(object_server.PERMISSION_AUDIT_ENV, audit) |
| 592 | assert object_server._permission_mode() == ("audit" if audit else "off") |
| 593 | before = len(object_permission_audit.get_permission_audit(box.data_dir)) |
| 594 | for who in ([], box.alice): |
| 595 | status, _, payload = request("/collections/contacts/records", headers=who) |
| 596 | assert status == 401, payload |
| 597 | status, _, payload = request("/collections/contacts/records/2", headers=who) |
| 598 | assert status == 401, payload |
| 599 | status, _, payload = request("/collections/contacts/records/missing", headers=who) |
| 600 | assert status == 401, payload # no 404 before the gate |
| 601 | status, _, payload = request("/api/search", query_string="q=note", headers=who) |
| 602 | assert status == 401, payload |
| 603 | status, _, body = raw_request(f"/api/files/{box.file_id}", headers=who) |
| 604 | assert status == 401 and body != b"bobbin" |
| 605 | status, _, payload = request("/collections/contacts/records", headers=ADMIN) |
| 606 | assert status == 200 and len(payload["records"]) == 2 |
| 607 | status, _, payload = request("/api/search", query_string="q=note", headers=ADMIN) |
| 608 | assert status == 200 and payload["total_count"] == 2 |
| 609 | after = object_permission_audit.get_permission_audit(box.data_dir) |
| 610 | if audit: |
| 611 | # still an observer: the refused requests were decided and logged, never enforced |
| 612 | assert len(after) > before |
| 613 | assert all(entry["enforced"] is False for entry in after[before:]) |
| 614 | assert all("enforcement_blocked" not in entry for entry in after[before:]) |
| 615 | else: |
| 616 | assert len(after) == before |
| 617 | |
| 618 | |
| 619 | # ---- an unreadable policy, enforced: 503 for non-admins, the admin token still decides ---- |
| 620 | |
| 621 | |
| 622 | @pytest.fixture |
| 623 | def forced_box(box, monkeypatch): |
| 624 | """The old override set: a no-op now, kept to show it changes nothing.""" |
| 625 | monkeypatch.setenv(object_server.PERMISSION_UNREADY_ENFORCEMENT_ENV, "true") |
| 626 | return box |
| 627 | |
| 628 | |
| 629 | def test_invalid_policy_when_enforced_answers_503_without_the_parse_error(forced_box): |
| 630 | _corrupt_policy(forced_box.data_dir) |
| 631 | for path in ("/objects/secret_runner", "/collections/contacts/records", |
| 632 | "/collections/contacts/records/2"): |
| 633 | status, _, payload = request(path) |
| 634 | assert status == 503, (path, payload) |
| 635 | assert payload["code"] == "permission_policy_unavailable" |
| 636 | assert "JSON" not in json.dumps(payload) and "error_detail" not in payload |
| 637 | status, _, payload = request("/api/search", query_string="q=note") |
| 638 | assert status == 503 and payload["code"] == "permission_policy_unavailable" |
| 639 | status, _, payload = request( |
| 640 | "/collections/contacts/records", |
| 641 | method="POST", |
| 642 | body=json.dumps({"name": "x", "owner_id": "bob"}).encode(), |
| 643 | headers=forced_box.alice + [("content-type", "application/json")], |
| 644 | ) |
| 645 | assert status == 503, payload |
| 646 | status, _, payload = request( |
| 647 | "/collections/contacts/records/2", |
| 648 | method="PUT", |
| 649 | body=json.dumps({"name": "x"}).encode(), |
| 650 | headers=forced_box.alice + [("content-type", "application/json")], |
| 651 | ) |
| 652 | assert status == 503, payload |
| 653 | |
| 654 | |
| 655 | def test_invalid_policy_when_enforced_lets_the_admin_token_read_run_and_repair(forced_box): |
| 656 | _corrupt_policy(forced_box.data_dir) |
| 657 | status, _, payload = request("/objects/secret_runner", headers=ADMIN) |
| 658 | assert status == 200 and payload == {"ran": True} |
| 659 | status, _, payload = request("/collections/contacts/records", headers=ADMIN) |
| 660 | assert status == 200 and len(payload["records"]) == 2, payload |
| 661 | entry = object_permission_audit.get_permission_audit(forced_box.data_dir)[-1] |
| 662 | assert "JSON" in entry["error"] and entry["decision"]["allowed"] is True |
| 663 | # Search lists every collection name, and a broken policy file keeps a name from |
| 664 | # quietly becoming known or unknown (object_collections), so the admin token gets |
| 665 | # the 503 too -- with the detail, and never a crash. |
| 666 | status, _, payload = request("/api/search", query_string="q=note", headers=ADMIN) |
| 667 | assert status == 503 and "JSON" in payload["error_detail"], payload |
| 668 | status, _, payload = request( |
| 669 | "/permissions/policy", method="PUT", body=json.dumps(POLICY).encode(), headers=ADMIN |
| 670 | ) |
| 671 | assert status == 200, payload |
| 672 | status, _, payload = request("/collections/contacts/records", headers=forced_box.alice) |
| 673 | assert status == 200 and [r["id"] for r in payload["records"]] == ["1"] |
| 674 | |
| 675 | |
| 676 | def test_unreadable_identity_store_when_enforced_answers_503_to_a_signed_in_user(forced_box): |
| 677 | """A customer with a valid session is not silently turned into a stranger.""" |
| 678 | _break_users_file(forced_box.data_dir) |
| 679 | status, headers, payload = request("/collections/contacts/records", headers=forced_box.alice) |
| 680 | assert status == 503, payload |
| 681 | assert payload["code"] == "identity_store_unavailable" |
| 682 | assert headers[b"retry-after"] == b"2" |
| 683 | cookie = [("cookie", f"{object_server.SESSION_COOKIE_NAME}={forced_box.alice_token}")] |
| 684 | status, _, payload = request("/objects/secret_runner", headers=cookie) |
| 685 | assert status == 503 and payload["code"] == "identity_store_unavailable", payload |
| 686 | # no credential: anonymous, and the policy decides |
| 687 | status, _, payload = request("/collections/contacts/records") |
| 688 | assert status in (401, 403), payload |
| 689 | # the admin token never touches the store |
| 690 | status, _, payload = request("/collections/contacts/records", headers=ADMIN) |
| 691 | assert status == 200 and len(payload["records"]) == 2 |
| 692 | |
| 693 | |
| 694 | def _replace_with_directory(path): |
| 695 | path.rename(path.with_name(path.name + ".bak")) |
| 696 | path.mkdir() |
| 697 | |
| 698 | |
| 699 | def _assert_identity_503(headers): |
| 700 | status, response_headers, payload = request("/collections/contacts/records", headers=headers) |
| 701 | assert status == 503, payload |
| 702 | assert payload["code"] == "identity_store_unavailable" |
| 703 | assert response_headers[b"retry-after"] == b"2" |
| 704 | |
| 705 | |
| 706 | def test_unreadable_api_keys_file_answers_503_to_a_key_holder(box): |
| 707 | """resolve_api_key swallowed the OSError, so a key holder became anonymous.""" |
| 708 | import object_api_keys |
| 709 | |
| 710 | _, key = object_api_keys.create_api_key("alice", "laptop", base_dir=box.data_dir) |
| 711 | status, _, payload = request("/collections/contacts/records", headers=[("authorization", f"Bearer {key}")]) |
| 712 | assert status == 200 and [r["id"] for r in payload["records"]] == ["1"] |
| 713 | _replace_with_directory(object_api_keys.api_keys_path(box.data_dir)) |
| 714 | _assert_identity_503([("authorization", f"Bearer {key}")]) |
| 715 | status, _, _ = request("/collections/contacts/records") |
| 716 | assert status in (401, 403) |
| 717 | |
| 718 | |
| 719 | def test_unreadable_sessions_file_answers_503_to_a_session_holder(box): |
| 720 | _replace_with_directory(object_identity.sessions_path(box.data_dir)) |
| 721 | _assert_identity_503(box.alice) |
| 722 | status, _, _ = request("/collections/contacts/records") |
| 723 | assert status in (401, 403) |
| 724 | status, _, payload = request("/collections/contacts/records", headers=ADMIN) |
| 725 | assert status == 200 and len(payload["records"]) == 2 |
| 726 | |
| 727 | |
| 728 | def test_unreadable_users_file_answers_503_to_trusted_identity_headers(box, monkeypatch): |
| 729 | monkeypatch.setenv(object_server.PERMISSION_TRUST_HEADERS_ENV, "true") |
| 730 | status, _, payload = request("/collections/contacts/records", headers=[("x-dbbasic-user-id", "alice")]) |
| 731 | assert status == 200 and [r["id"] for r in payload["records"]] == ["1"] |
| 732 | _break_users_file(box.data_dir) |
| 733 | _assert_identity_503([("x-dbbasic-user-id", "alice")]) |
| 734 | |
| 735 | |
| 736 | @pytest.mark.skipif(os.geteuid() == 0, reason="root reads a chmod 000 file") |
| 737 | def test_unreadable_policy_when_enforced_answers_503_not_500(forced_box): |
| 738 | path = object_permission_store.policy_path(forced_box.data_dir) |
| 739 | path.chmod(0) |
| 740 | try: |
| 741 | status, _, payload = request("/objects/secret_runner") |
| 742 | assert status == 503 and payload["code"] == "permission_policy_unavailable", payload |
| 743 | status, _, payload = request("/collections/contacts/records") |
| 744 | assert status == 503, payload |
| 745 | status, _, payload = request("/objects/secret_runner", headers=ADMIN) |
| 746 | assert status == 200, payload |
| 747 | finally: |
| 748 | path.chmod(0o600) |
| 749 | |
| 750 | |
| 751 | # ---- single-record reads are no oracle for which ids exist -------------------------------- |
| 752 | |
| 753 | |
| 754 | def _drop_contacts_schema(data_dir): |
| 755 | (data_dir / "schemas" / "contacts.json").unlink() |
| 756 | |
| 757 | |
| 758 | @pytest.mark.parametrize("schema", [True, False]) |
| 759 | def test_record_detail_answers_a_hidden_row_like_a_missing_one(box, schema): |
| 760 | if not schema: |
| 761 | _drop_contacts_schema(box.data_dir) |
| 762 | # anonymous: refused at the collection level, whatever the id |
| 763 | existing = raw_request("/collections/contacts/records/2") |
| 764 | missing = raw_request("/collections/contacts/records/999") |
| 765 | assert existing[0] in (401, 403) and (existing[0], existing[2]) == (missing[0], missing[2]) |
| 766 | # a row-filtered user: someone else's row is "not found", like a missing id |
| 767 | status, _, payload = request("/collections/contacts/records/2", headers=box.alice) |
| 768 | assert status == 404 and payload == {"status": "error", "error": "Record not found: contacts/2"} |
| 769 | status, _, payload = request("/collections/contacts/records/999", headers=box.alice) |
| 770 | assert status == 404 and payload == {"status": "error", "error": "Record not found: contacts/999"} |
| 771 | status, _, payload = request("/collections/contacts/records/1", headers=box.alice) |
| 772 | assert status == 200 and payload["record"]["name"] == "Alice note" |
| 773 | |
| 774 | |
| 775 | def test_user_file_by_id_answers_someone_elses_file_like_a_missing_one(box): |
| 776 | status, _, payload = request(f"/api/files/{box.file_id}", headers=box.alice) |
| 777 | assert status == 404 and payload == {"status": "error", "error": "File not found"} |
| 778 | status, _, payload = request("/api/files/nosuchfile", headers=box.alice) |
| 779 | assert status == 404 and payload == {"status": "error", "error": "File not found"} |
| 780 | status, _, payload = request(f"/api/files/{box.file_id}", method="DELETE", headers=box.alice) |
| 781 | assert status in (403, 404) and "bob.txt" not in json.dumps(payload) |
| 782 | |
| 783 | |
| 784 | @pytest.mark.parametrize("schema", [True, False]) |
| 785 | def test_broken_policy_record_detail_is_503_without_detail_whatever_the_id(box, schema): |
| 786 | """With no schema file, the record lookup itself loads the policy (to tell a known |
| 787 | collection from an unknown one) and answered the parse error as a 400.""" |
| 788 | if not schema: |
| 789 | _drop_contacts_schema(box.data_dir) |
| 790 | _corrupt_policy(box.data_dir) |
| 791 | for path in ("/collections/contacts/records/2", "/collections/contacts/records/999", |
| 792 | "/collections/nosuch/records/1"): |
| 793 | for who in ([], box.alice): |
| 794 | status, _, payload = request(path, headers=who) |
| 795 | assert status == 503, (path, payload) |
| 796 | assert payload["code"] == "permission_policy_unavailable" and "error_detail" not in payload |
| 797 | assert "JSON" not in json.dumps(payload) |
| 798 | # the admin token still reads by id (with a schema; without one the lookup needs the policy) |
| 799 | status, _, payload = request("/collections/contacts/records/2", headers=ADMIN) |
| 800 | assert status == (200 if schema else 400), payload |
| 801 | |
| 802 | |
| 803 | # ---- a token that is not ASCII is refused cleanly --------------------------------------------- |
| 804 | |
| 805 | |
| 806 | @pytest.mark.parametrize("value", ["Bearer \xe9\xe9", "Token \xe9" + "e" * 31, "Bearer dbk_\xe9"]) |
| 807 | def test_a_non_ascii_authorization_header_is_refused_not_a_500(box, value): |
| 808 | """hmac.compare_digest raises TypeError for non-ASCII str, which answered 500.""" |
| 809 | for path in ("/objects/secret_runner", "/collections/contacts/records"): |
| 810 | status, _, body = raw_request(path, headers=[("authorization", value)]) |
| 811 | assert status in (401, 403), (path, status, body) |
| 812 | _no_secret(body) |
| 813 | status, _, _ = raw_request("/permissions/status", headers=[("authorization", value)]) |
| 814 | assert status == 401 |
| 815 | cookie = [("cookie", f"{object_server.SESSION_COOKIE_NAME}=\xe9\xe9")] |
| 816 | status, _, _ = raw_request("/objects/secret_runner", headers=cookie) |
| 817 | assert status in (401, 403) |
| 818 | |
| 819 | |
| 820 | # ---- only the admin TOKEN acts while the policy cannot be read ------------------------------ |
| 821 | |
| 822 | |
| 823 | def test_session_admin_gates_refuse_while_the_policy_cannot_be_read(box, monkeypatch): |
| 824 | """The policy names which roles are admin. Falling back to the default |
| 825 | (admin, superuser) when it cannot be read let a session user whose identity |
| 826 | roles say "admin" through the admin gates even if the real policy says otherwise.""" |
| 827 | monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true") |
| 828 | object_permission_store.replace_policy({**POLICY, "admin_roles": ["owner"]}, base_dir=box.data_dir) |
| 829 | object_identity.create_user({"user_id": "mallory", "roles": ["admin"]}, base_dir=box.data_dir) |
| 830 | created = object_identity.create_session({"user_id": "mallory"}, base_dir=box.data_dir) |
| 831 | mallory = [("authorization", f"Bearer {created['token']}")] |
| 832 | status, _, _ = request("/permissions/status", headers=mallory) |
| 833 | assert status == 401 # healthy: "admin" is not an admin role here |
| 834 | _corrupt_policy(box.data_dir) |
| 835 | status, _, _ = request("/permissions/status", headers=mallory) |
| 836 | assert status == 401 |
| 837 | status, _, _ = request("/permissions/status", headers=ADMIN) |
| 838 | assert status == 200 |
| 839 | |
| 840 | |
| 841 | # ---- the composed surfaces under drift: websocket, MCP, AI-chat tools ----------------------- |
| 842 | |
| 843 | |
| 844 | def _ws_session(headers, messages): |
| 845 | """Connect to /ws over the ASGI websocket path, send `messages`, return what came back.""" |
| 846 | from test_object_realtime import _WS, _settle |
| 847 | |
| 848 | async def body(): |
| 849 | ws = _WS(headers) |
| 850 | task = asyncio.ensure_future(object_server.app(ws.scope, ws.receive, ws.send)) |
| 851 | await ws.to_server.put({"type": "websocket.connect"}) |
| 852 | await _settle() |
| 853 | for message in messages: |
| 854 | await ws.to_server.put({"type": "websocket.receive", "text": json.dumps(message)}) |
| 855 | await _settle() |
| 856 | await ws.to_server.put({"type": "websocket.disconnect"}) |
| 857 | await asyncio.wait_for(task, timeout=2) |
| 858 | return ws |
| 859 | |
| 860 | return asyncio.run(body()) |
| 861 | |
| 862 | |
| 863 | def _subscribed(ws): |
| 864 | replies = [t for t in ws.texts() if t.get("type") == "subscribed"] |
| 865 | return replies[-1]["collections"] if replies else None |
| 866 | |
| 867 | |
| 868 | def test_websocket_subscribe_over_the_wire_follows_the_policy_and_its_drift(box, monkeypatch): |
| 869 | subscribe = {"action": "subscribe", "collections": ["contacts", "secret_notes"]} |
| 870 | ws = _ws_session(box.alice, [subscribe]) |
| 871 | assert "websocket.accept" in ws.kinds() and _subscribed(ws) == ["contacts"] |
| 872 | |
| 873 | _corrupt_policy(box.data_dir) # cannot decide: subscribes to nothing |
| 874 | ws = _ws_session(box.alice, [subscribe]) |
| 875 | assert _subscribed(ws) == [] |
| 876 | object_permission_store.replace_policy(POLICY, base_dir=box.data_dir) |
| 877 | |
| 878 | _break_users_file(box.data_dir) # cannot check the session: try again later |
| 879 | ws = _ws_session(box.alice, [subscribe]) |
| 880 | assert "websocket.accept" not in ws.kinds() |
| 881 | assert ws.sent[-1] == {"type": "websocket.close", "code": 1013} |
| 882 | _repair_users_file(box.data_dir) |
| 883 | |
| 884 | _expire_every_session(monkeypatch) # the last session expired: anonymous is refused |
| 885 | ws = _ws_session(box.alice, [subscribe]) |
| 886 | assert "websocket.accept" not in ws.kinds() |
| 887 | |
| 888 | |
| 889 | def _mcp_call(name, arguments, headers): |
| 890 | status, _, payload = request( |
| 891 | "/api/mcp", method="POST", headers=headers, |
| 892 | body=json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", |
| 893 | "params": {"name": name, "arguments": arguments}}).encode(), |
| 894 | ) |
| 895 | return status, payload |
| 896 | |
| 897 | |
| 898 | def test_mcp_under_a_broken_policy_admits_only_the_admin_token(box, monkeypatch): |
| 899 | monkeypatch.setenv(object_server.SESSION_ADMIN_GATES_ENV, "true") |
| 900 | object_identity.create_user({"user_id": "root", "roles": ["admin"]}, base_dir=box.data_dir) |
| 901 | root = [("authorization", |
| 902 | f"Bearer {object_identity.create_session({'user_id': 'root'}, base_dir=box.data_dir)['token']}")] |
| 903 | args = {"collection": "contacts"} |
| 904 | status, payload = _mcp_call("list_records", args, root) |
| 905 | assert status == 200 and "Bob note" in json.dumps(payload) # healthy: an admin-role session |
| 906 | status, payload = _mcp_call("list_records", args, box.alice) |
| 907 | assert status == 401 and "Bob note" not in json.dumps(payload) |
| 908 | |
| 909 | _corrupt_policy(box.data_dir) |
| 910 | for who in (root, box.alice, []): |
| 911 | status, payload = _mcp_call("list_records", args, who) |
| 912 | assert status == 401, payload |
| 913 | _no_secret(json.dumps(payload).encode()) |
| 914 | status, payload = _mcp_call("list_records", args, ADMIN) |
| 915 | assert status == 200 and "Bob note" in json.dumps(payload) # the repair path |
| 916 | |
| 917 | |
| 918 | def test_ai_chat_tools_under_a_broken_policy_get_the_503_and_no_data(box, monkeypatch): |
| 919 | import object_service_keys |
| 920 | from test_object_ai import anthropic_text_response, anthropic_tool_response |
| 921 | |
| 922 | monkeypatch.setenv(object_server.AI_CHAT_ENABLED_ENV, "true") |
| 923 | # as installed by app-settings: the usage row is written after the turn |
| 924 | _write_schema(box.data_dir, "ai_usage", {"fields": [{"name": "id"}, {"name": "owner_id"}]}) |
| 925 | object_service_keys.set_service_key("alice", "anthropic", "sk-test", base_dir=box.data_dir) |
| 926 | responses = [ |
| 927 | anthropic_tool_response("global_search", {"query": "note"}), |
| 928 | anthropic_tool_response("get_feed", {}), |
| 929 | anthropic_text_response("done"), |
| 930 | ] |
| 931 | monkeypatch.setenv(object_server.FEED_ENABLED_ENV, "true") |
| 932 | sent_bodies = [] |
| 933 | |
| 934 | class FakeResponse: |
| 935 | def __init__(self, status, body): |
| 936 | self.status, self._body = status, body |
| 937 | |
| 938 | def read(self): |
| 939 | return self._body |
| 940 | |
| 941 | def __enter__(self): |
| 942 | return self |
| 943 | |
| 944 | def __exit__(self, *args): |
| 945 | return False |
| 946 | |
| 947 | def fake_transport(request_obj, timeout=None): |
| 948 | sent_bodies.append(request_obj.data or b"") |
| 949 | return FakeResponse(*responses.pop(0)) |
| 950 | |
| 951 | monkeypatch.setattr(object_server.urllib.request, "urlopen", fake_transport) |
| 952 | _corrupt_policy(box.data_dir) |
| 953 | status, _, chat = request( |
| 954 | "/api/ai/chat", method="POST", |
| 955 | body=json.dumps({"message": "find notes", "tools": ["global_search", "get_feed"]}).encode(), |
| 956 | headers=box.alice + [("content-type", "application/json")], |
| 957 | ) |
| 958 | assert status == 200, chat |
| 959 | assert [call["http_status"] for call in chat["tool_calls"]] == [503, 503] |
| 960 | for body in sent_bodies: # nothing private, and no parse error, went to the provider |
| 961 | _no_secret(body) |
| 962 | assert b"JSON" not in body.replace(b"application/json", b"") |